source: trunk/libtransmission/torrent.c @ 10414

Last change on this file since 10414 was 10414, checked in by charles, 12 years ago

(trunk libt) #3004 "Transmission doesn't report to the user errors when saving settings files" -- committed Longinus00's patch to trunk for 2.00

  • Property svn:keywords set to Date Rev Author Id
File size: 72.0 KB
Line 
1/*
2 * This file Copyright (C) 2009-2010 Mnemosyne LLC
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id: torrent.c 10414 2010-03-22 00:55:43Z charles $
11 */
12
13#include <sys/types.h> /* stat */
14#include <sys/stat.h> /* stat */
15#include <unistd.h> /* stat */
16#include <dirent.h>
17
18#include <assert.h>
19#include <limits.h> /* INT_MAX */
20#include <math.h>
21#include <stdarg.h>
22#include <string.h> /* memcmp */
23#include <stdlib.h> /* qsort */
24
25#include <event.h> /* evbuffer */
26
27#include "transmission.h"
28#include "announcer.h"
29#include "bandwidth.h"
30#include "bencode.h"
31#include "completion.h"
32#include "crypto.h" /* for tr_sha1 */
33#include "resume.h"
34#include "fdlimit.h" /* tr_fdTorrentClose */
35#include "magnet.h"
36#include "metainfo.h"
37#include "peer-mgr.h"
38#include "platform.h" /* TR_PATH_DELIMITER_STR */
39#include "ptrarray.h"
40#include "session.h"
41#include "torrent.h"
42#include "torrent-magnet.h"
43#include "trevent.h" /* tr_runInEventThread() */
44#include "utils.h"
45#include "verify.h"
46
47enum
48{
49    MAX_BLOCK_SIZE = 1024 * 16
50};
51
52/***
53****
54***/
55
56int
57tr_torrentId( const tr_torrent * tor )
58{
59    return tor->uniqueId;
60}
61
62tr_torrent*
63tr_torrentFindFromId( tr_session * session, int id )
64{
65    tr_torrent * tor = NULL;
66
67    while(( tor = tr_torrentNext( session, tor )))
68        if( tor->uniqueId == id )
69            return tor;
70
71    return NULL;
72}
73
74tr_torrent*
75tr_torrentFindFromHashString( tr_session *  session, const char * str )
76{
77    tr_torrent * tor = NULL;
78
79    while(( tor = tr_torrentNext( session, tor )))
80        if( !strcasecmp( str, tor->info.hashString ) )
81            return tor;
82
83    return NULL;
84}
85
86tr_torrent*
87tr_torrentFindFromHash( tr_session * session, const uint8_t * torrentHash )
88{
89    tr_torrent * tor = NULL;
90
91    while(( tor = tr_torrentNext( session, tor )))
92        if( *tor->info.hash == *torrentHash )
93            if( !memcmp( tor->info.hash, torrentHash, SHA_DIGEST_LENGTH ) )
94                return tor;
95
96    return NULL;
97}
98
99tr_torrent*
100tr_torrentFindFromMagnetLink( tr_session * session, const char * magnet )
101{
102    tr_magnet_info * info;
103    tr_torrent * tor = NULL;
104
105    if(( info = tr_magnetParse( magnet )))
106    {
107        tor = tr_torrentFindFromHash( session, info->hash );
108        tr_magnetFree( info );
109    }
110
111    return tor;
112}
113
114tr_torrent*
115tr_torrentFindFromObfuscatedHash( tr_session * session,
116                                  const uint8_t * obfuscatedTorrentHash )
117{
118    tr_torrent * tor = NULL;
119
120    while(( tor = tr_torrentNext( session, tor )))
121        if( !memcmp( tor->obfuscatedHash, obfuscatedTorrentHash,
122                     SHA_DIGEST_LENGTH ) )
123            return tor;
124
125    return NULL;
126}
127
128/***
129****  PER-TORRENT UL / DL SPEEDS
130***/
131
132void
133tr_torrentSetSpeedLimit( tr_torrent * tor, tr_direction dir, int KiB_sec )
134{
135    assert( tr_isTorrent( tor ) );
136    assert( tr_isDirection( dir ) );
137
138    if( tr_bandwidthSetDesiredSpeed( tor->bandwidth, dir, KiB_sec ) )
139        tr_torrentSetDirty( tor );
140}
141
142int
143tr_torrentGetSpeedLimit( const tr_torrent * tor, tr_direction dir )
144{
145    assert( tr_isTorrent( tor ) );
146    assert( tr_isDirection( dir ) );
147
148    return tr_bandwidthGetDesiredSpeed( tor->bandwidth, dir );
149}
150
151void
152tr_torrentUseSpeedLimit( tr_torrent * tor, tr_direction dir, tr_bool do_use )
153{
154    assert( tr_isTorrent( tor ) );
155    assert( tr_isDirection( dir ) );
156
157    if( tr_bandwidthSetLimited( tor->bandwidth, dir, do_use ) )
158        tr_torrentSetDirty( tor );
159}
160
161tr_bool
162tr_torrentUsesSpeedLimit( const tr_torrent * tor, tr_direction dir )
163{
164    assert( tr_isTorrent( tor ) );
165    assert( tr_isDirection( dir ) );
166
167    return tr_bandwidthIsLimited( tor->bandwidth, dir );
168}
169
170void
171tr_torrentUseSessionLimits( tr_torrent * tor, tr_bool doUse )
172{
173    tr_bool changed;
174
175    assert( tr_isTorrent( tor ) );
176
177    changed = tr_bandwidthHonorParentLimits( tor->bandwidth, TR_UP, doUse );
178    changed |= tr_bandwidthHonorParentLimits( tor->bandwidth, TR_DOWN, doUse );
179
180    if( changed )
181        tr_torrentSetDirty( tor );
182}
183
184tr_bool
185tr_torrentUsesSessionLimits( const tr_torrent * tor )
186{
187    assert( tr_isTorrent( tor ) );
188
189    return tr_bandwidthAreParentLimitsHonored( tor->bandwidth, TR_UP );
190}
191
192/***
193****
194***/
195
196void
197tr_torrentSetRatioMode( tr_torrent *  tor, tr_ratiolimit mode )
198{
199    assert( tr_isTorrent( tor ) );
200    assert( mode==TR_RATIOLIMIT_GLOBAL || mode==TR_RATIOLIMIT_SINGLE || mode==TR_RATIOLIMIT_UNLIMITED  );
201
202    if( mode != tor->ratioLimitMode )
203    {
204        tor->ratioLimitMode = mode;
205        tor->needsSeedRatioCheck = TRUE;
206
207        tr_torrentSetDirty( tor );
208    }
209}
210
211tr_ratiolimit
212tr_torrentGetRatioMode( const tr_torrent * tor )
213{
214    assert( tr_isTorrent( tor ) );
215
216    return tor->ratioLimitMode;
217}
218
219void
220tr_torrentSetRatioLimit( tr_torrent * tor, double desiredRatio )
221{
222    assert( tr_isTorrent( tor ) );
223
224    if( (int)(desiredRatio*100.0) != (int)(tor->desiredRatio*100.0) )
225    {
226        tor->desiredRatio = desiredRatio;
227
228        tor->needsSeedRatioCheck = TRUE;
229
230        tr_torrentSetDirty( tor );
231    }
232}
233
234double
235tr_torrentGetRatioLimit( const tr_torrent * tor )
236{
237    assert( tr_isTorrent( tor ) );
238
239    return tor->desiredRatio;
240}
241
242tr_bool
243tr_torrentIsPieceTransferAllowed( const tr_torrent  * tor,
244                                  tr_direction        direction )
245{
246    int limit;
247    tr_bool allowed = TRUE;
248
249    if( tr_torrentUsesSpeedLimit( tor, direction ) )
250        if( tr_torrentGetSpeedLimit( tor, direction ) <= 0 )
251            allowed = FALSE;
252
253    if( tr_torrentUsesSessionLimits( tor ) )
254        if( tr_sessionGetActiveSpeedLimit( tor->session, direction, &limit ) )
255            if( limit <= 0 )
256                allowed = FALSE;
257
258    return allowed;
259}
260
261tr_bool
262tr_torrentGetSeedRatio( const tr_torrent * tor, double * ratio )
263{
264    tr_bool isLimited;
265
266    switch( tr_torrentGetRatioMode( tor ) )
267    {
268        case TR_RATIOLIMIT_SINGLE:
269            isLimited = TRUE;
270            if( ratio )
271                *ratio = tr_torrentGetRatioLimit( tor );
272            break;
273
274        case TR_RATIOLIMIT_GLOBAL:
275            isLimited = tr_sessionIsRatioLimited( tor->session );
276            if( isLimited && ratio )
277                *ratio = tr_sessionGetRatioLimit( tor->session );
278            break;
279
280        default: /* TR_RATIOLIMIT_UNLIMITED */
281            isLimited = FALSE;
282            break;
283    }
284
285    return isLimited;
286}
287
288/***
289****
290***/
291
292void
293tr_torrentSetLocalError( tr_torrent * tor, const char * fmt, ... )
294{
295    va_list ap;
296
297    assert( tr_isTorrent( tor ) );
298
299    va_start( ap, fmt );
300    tor->error = TR_STAT_LOCAL_ERROR;
301    evutil_vsnprintf( tor->errorString, sizeof( tor->errorString ), fmt, ap );
302    va_end( ap );
303}
304
305static void
306onTrackerResponse( void * tracker UNUSED,
307                   void * vevent,
308                   void * user_data )
309{
310    tr_torrent *       tor = user_data;
311    tr_tracker_event * event = vevent;
312
313    switch( event->messageType )
314    {
315        case TR_TRACKER_PEERS:
316        {
317            size_t   i, n;
318            tr_pex * pex = tr_peerMgrArrayToPex( event->compact,
319                                                 event->compactLen, &n );
320             if( event->allAreSeeds )
321                tr_tordbg( tor, "Got %d seeds from tracker", (int)n );
322            else
323                tr_tordbg( tor, "Got %d peers from tracker", (int)n );
324
325            for( i = 0; i < n; ++i )
326            {
327                if( event->allAreSeeds )
328                    pex[i].flags |= ADDED_F_SEED_FLAG;
329                tr_peerMgrAddPex( tor, TR_PEER_FROM_TRACKER, pex + i );
330            }
331
332            tr_free( pex );
333            break;
334        }
335
336        case TR_TRACKER_WARNING:
337            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
338            tor->error = TR_STAT_TRACKER_WARNING;
339            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
340            break;
341
342        case TR_TRACKER_ERROR:
343            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
344            tor->error = TR_STAT_TRACKER_ERROR;
345            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
346            break;
347
348        case TR_TRACKER_ERROR_CLEAR:
349            if( tor->error != TR_STAT_LOCAL_ERROR )
350            {
351                tor->error = TR_STAT_OK;
352                tor->errorString[0] = '\0';
353            }
354            break;
355    }
356}
357
358/***
359****
360****  TORRENT INSTANTIATION
361****
362***/
363
364static int
365getBytePiece( const tr_info * info,
366              uint64_t        byteOffset )
367{
368    assert( info );
369    assert( info->pieceSize != 0 );
370
371    return byteOffset / info->pieceSize;
372}
373
374static void
375initFilePieces( tr_info *       info,
376                tr_file_index_t fileIndex )
377{
378    tr_file * file;
379    uint64_t  firstByte, lastByte;
380
381    assert( info );
382    assert( fileIndex < info->fileCount );
383
384    file = &info->files[fileIndex];
385    firstByte = file->offset;
386    lastByte = firstByte + ( file->length ? file->length - 1 : 0 );
387    file->firstPiece = getBytePiece( info, firstByte );
388    file->lastPiece = getBytePiece( info, lastByte );
389}
390
391static int
392pieceHasFile( tr_piece_index_t piece,
393              const tr_file *  file )
394{
395    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
396}
397
398static tr_priority_t
399calculatePiecePriority( const tr_torrent * tor,
400                        tr_piece_index_t   piece,
401                        int                fileHint )
402{
403    tr_file_index_t i;
404    int             priority = TR_PRI_LOW;
405
406    /* find the first file that has data in this piece */
407    if( fileHint >= 0 ) {
408        i = fileHint;
409        while( i > 0 && pieceHasFile( piece, &tor->info.files[i - 1] ) )
410            --i;
411    } else {
412        for( i = 0; i < tor->info.fileCount; ++i )
413            if( pieceHasFile( piece, &tor->info.files[i] ) )
414                break;
415    }
416
417    /* the piece's priority is the max of the priorities
418     * of all the files in that piece */
419    for( ; i < tor->info.fileCount; ++i )
420    {
421        const tr_file * file = &tor->info.files[i];
422
423        if( !pieceHasFile( piece, file ) )
424            break;
425
426        priority = MAX( priority, file->priority );
427
428        /* when dealing with multimedia files, getting the first and
429           last pieces can sometimes allow you to preview it a bit
430           before it's fully downloaded... */
431        if( file->priority >= TR_PRI_NORMAL )
432            if( file->firstPiece == piece || file->lastPiece == piece )
433                priority = TR_PRI_HIGH;
434    }
435
436    return priority;
437}
438
439static void
440tr_torrentInitFilePieces( tr_torrent * tor )
441{
442    tr_file_index_t  f;
443    tr_piece_index_t p;
444    uint64_t offset = 0;
445    tr_info * inf = &tor->info;
446    int * firstFiles;
447
448    /* assign the file offsets */
449    for( f=0; f<inf->fileCount; ++f ) {
450        inf->files[f].offset = offset;
451        offset += inf->files[f].length;
452        initFilePieces( inf, f );
453    }
454
455    /* build the array of first-file hints to give calculatePiecePriority */
456    firstFiles = tr_new( int, inf->pieceCount );
457    for( p=f=0; p<inf->pieceCount; ++p ) {
458        while( inf->files[f].lastPiece < p )
459            ++f;
460        firstFiles[p] = f;
461    }
462
463#if 0
464    /* test to confirm the first-file hints are correct */
465    for( p=0; p<inf->pieceCount; ++p ) {
466        f = firstFiles[p];
467        assert( inf->files[f].firstPiece <= p );
468        assert( inf->files[f].lastPiece >= p );
469        if( f > 0 )
470            assert( inf->files[f-1].lastPiece < p );
471        for( f=0; f<inf->fileCount; ++f )
472            if( pieceHasFile( p, &inf->files[f] ) )
473                break;
474        assert( (int)f == firstFiles[p] );
475    }
476#endif
477
478    for( p=0; p<inf->pieceCount; ++p )
479        inf->pieces[p].priority = calculatePiecePriority( tor, p, firstFiles[p] );
480
481    tr_free( firstFiles );
482}
483
484int
485tr_torrentPromoteTracker( tr_torrent * tor,
486                          int          pos )
487{
488    int i;
489    int tier;
490
491    assert( tor );
492    assert( ( 0 <= pos ) && ( pos < tor->info.trackerCount ) );
493
494    /* the tier of the tracker we're promoting */
495    tier = tor->info.trackers[pos].tier;
496
497    /* find the index of that tier's first tracker */
498    for( i = 0; i < tor->info.trackerCount; ++i )
499        if( tor->info.trackers[i].tier == tier )
500            break;
501
502    assert( i < tor->info.trackerCount );
503
504    /* promote the tracker at `pos' to the front of the tier */
505    if( i != pos )
506    {
507        const tr_tracker_info tmp = tor->info.trackers[i];
508        tor->info.trackers[i] = tor->info.trackers[pos];
509        tor->info.trackers[pos] = tmp;
510    }
511
512    /* return the new position of the tracker that started out at [pos] */
513    return i;
514}
515
516static void torrentStart( tr_torrent * tor );
517
518/**
519 * Decide on a block size.  constraints:
520 * (1) most clients decline requests over 16 KiB
521 * (2) pieceSize must be a multiple of block size
522 */
523static uint32_t
524getBlockSize( uint32_t pieceSize )
525{
526    uint32_t b = pieceSize;
527
528    while( b > MAX_BLOCK_SIZE )
529        b /= 2u;
530
531    if( !b || ( pieceSize % b ) ) /* not cleanly divisible */
532        return 0;
533    return b;
534}
535
536static void refreshCurrentDir( tr_torrent * tor );
537
538static void
539torrentInitFromInfo( tr_torrent * tor )
540{
541    uint64_t t;
542    tr_info * info = &tor->info;
543
544    tor->blockSize = getBlockSize( info->pieceSize );
545
546    if( info->pieceSize )
547        tor->lastPieceSize = info->totalSize % info->pieceSize;
548
549    if( !tor->lastPieceSize )
550        tor->lastPieceSize = info->pieceSize;
551
552    if( tor->blockSize )
553        tor->lastBlockSize = info->totalSize % tor->blockSize;
554
555    if( !tor->lastBlockSize )
556        tor->lastBlockSize = tor->blockSize;
557
558    tor->blockCount = tor->blockSize
559        ? ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize
560        : 0;
561
562    tor->blockCountInPiece = tor->blockSize
563        ? info->pieceSize / tor->blockSize
564        : 0;
565
566    tor->blockCountInLastPiece = tor->blockSize
567        ? ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize
568        : 0;
569
570    /* check our work */
571    if( tor->blockSize != 0 )
572        assert( ( info->pieceSize % tor->blockSize ) == 0 );
573    t = info->pieceCount - 1;
574    t *= info->pieceSize;
575    t += tor->lastPieceSize;
576    assert( t == info->totalSize );
577    t = tor->blockCount - 1;
578    t *= tor->blockSize;
579    t += tor->lastBlockSize;
580    assert( t == info->totalSize );
581    t = info->pieceCount - 1;
582    t *= tor->blockCountInPiece;
583    t += tor->blockCountInLastPiece;
584    assert( t == (uint64_t)tor->blockCount );
585
586    tr_cpConstruct( &tor->completion, tor );
587
588    tr_torrentInitFilePieces( tor );
589
590    tr_bitfieldConstruct( &tor->checkedPieces, tor->info.pieceCount );
591
592    tor->completeness = tr_cpGetStatus( &tor->completion );
593}
594
595static void tr_torrentFireMetadataCompleted( tr_torrent * tor );
596
597void
598tr_torrentGotNewInfoDict( tr_torrent * tor )
599{
600    torrentInitFromInfo( tor );
601
602    tr_torrentFireMetadataCompleted( tor );
603}
604
605static void
606torrentInit( tr_torrent * tor, const tr_ctor * ctor )
607{
608    int doStart;
609    uint64_t loaded;
610    const char * dir;
611    static int nextUniqueId = 1;
612    tr_session * session = tr_ctorGetSession( ctor );
613
614    assert( session != NULL );
615
616    tr_sessionLock( session );
617
618    tor->session   = session;
619    tor->uniqueId = nextUniqueId++;
620    tor->magicNumber = TORRENT_MAGIC_NUMBER;
621
622    tr_sha1( tor->obfuscatedHash, "req2", 4,
623             tor->info.hash, SHA_DIGEST_LENGTH,
624             NULL );
625
626    if( !tr_ctorGetDownloadDir( ctor, TR_FORCE, &dir ) ||
627        !tr_ctorGetDownloadDir( ctor, TR_FALLBACK, &dir ) )
628            tor->downloadDir = tr_strdup( dir );
629
630    if( tr_ctorGetIncompleteDir( ctor, &dir ) )
631        dir = tr_sessionGetIncompleteDir( session );
632    if( tr_sessionIsIncompleteDirEnabled( session ) )
633        tor->incompleteDir = tr_strdup( dir );
634
635    tor->bandwidth = tr_bandwidthNew( session, session->bandwidth );
636
637    tor->bandwidth->priority = tr_ctorGetBandwidthPriority( ctor );
638
639    tor->error = TR_STAT_OK;
640
641    tr_peerMgrAddTorrent( session->peerMgr, tor );
642
643    assert( !tor->downloadedCur );
644    assert( !tor->uploadedCur );
645
646    tr_ctorInitTorrentPriorities( ctor, tor );
647
648    tr_ctorInitTorrentWanted( ctor, tor );
649
650    tr_torrentUncheck( tor );
651
652    tr_torrentSetAddedDate( tor, tr_time( ) ); /* this is a default value to be
653                                                  overwritten by the resume file */
654
655    torrentInitFromInfo( tor );
656    loaded = tr_torrentLoadResume( tor, ~0, ctor );
657    tor->completeness = tr_cpGetStatus( &tor->completion );
658
659    refreshCurrentDir( tor );
660
661    doStart = tor->isRunning;
662    tor->isRunning = 0;
663
664    if( !( loaded & TR_FR_SPEEDLIMIT ) )
665    {
666        tr_torrentUseSpeedLimit( tor, TR_UP, FALSE );
667        tr_torrentSetSpeedLimit( tor, TR_UP, tr_sessionGetSpeedLimit( tor->session, TR_UP ) );
668        tr_torrentUseSpeedLimit( tor, TR_DOWN, FALSE );
669        tr_torrentSetSpeedLimit( tor, TR_DOWN, tr_sessionGetSpeedLimit( tor->session, TR_DOWN ) );
670        tr_torrentUseSessionLimits( tor, TRUE );
671    }
672
673    if( !( loaded & TR_FR_RATIOLIMIT ) )
674    {
675        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_GLOBAL );
676        tr_torrentSetRatioLimit( tor, tr_sessionGetRatioLimit( tor->session ) );
677    }
678
679    {
680        tr_torrent * it = NULL;
681        tr_torrent * last = NULL;
682        while( ( it = tr_torrentNext( session, it ) ) )
683            last = it;
684
685        if( !last )
686            session->torrentList = tor;
687        else
688            last->next = tor;
689        ++session->torrentCount;
690    }
691
692    /* maybe save our own copy of the metainfo */
693    if( tr_ctorGetSave( ctor ) )
694    {
695        const tr_benc * val;
696        if( !tr_ctorGetMetainfo( ctor, &val ) )
697        {
698            const char * path = tor->info.torrent;
699            const int err = tr_bencToFile( val, TR_FMT_BENC, path );
700            if( err )
701                tr_torrentSetLocalError( tor, "Unable to save torrent file: %s", tr_strerror( err ) );
702            tr_sessionSetTorrentFile( tor->session, tor->info.hashString, path );
703        }
704    }
705
706    tor->tiers = tr_announcerAddTorrent( tor->session->announcer, tor );
707    tor->tiersSubscription = tr_announcerSubscribe( tor->tiers, onTrackerResponse, tor );
708
709    if( doStart )
710        torrentStart( tor );
711
712    tr_sessionUnlock( session );
713}
714
715static tr_parse_result
716torrentParseImpl( const tr_ctor * ctor, tr_info * setmeInfo,
717                  tr_bool * setmeHasInfo, int * dictOffset, int * dictLength )
718{
719    int             doFree;
720    tr_bool         didParse;
721    tr_bool         hasInfo = FALSE;
722    tr_info         tmp;
723    const tr_benc * metainfo;
724    tr_session    * session = tr_ctorGetSession( ctor );
725    tr_parse_result result = TR_PARSE_OK;
726
727    if( setmeInfo == NULL )
728        setmeInfo = &tmp;
729    memset( setmeInfo, 0, sizeof( tr_info ) );
730
731    if( tr_ctorGetMetainfo( ctor, &metainfo ) )
732        return TR_PARSE_ERR;
733
734    didParse = tr_metainfoParse( session, metainfo, setmeInfo,
735                                 &hasInfo, dictOffset, dictLength );
736    doFree = didParse && ( setmeInfo == &tmp );
737
738    if( !didParse )
739        result = TR_PARSE_ERR;
740
741    if( didParse && hasInfo && !getBlockSize( setmeInfo->pieceSize ) )
742        result = TR_PARSE_ERR;
743
744    if( didParse && session && tr_torrentExists( session, setmeInfo->hash ) )
745        result = TR_PARSE_DUPLICATE;
746
747    if( doFree )
748        tr_metainfoFree( setmeInfo );
749
750    if( setmeHasInfo != NULL )
751        *setmeHasInfo = hasInfo;
752
753    return result;
754}
755
756tr_parse_result
757tr_torrentParse( const tr_ctor * ctor, tr_info * setmeInfo )
758{
759    return torrentParseImpl( ctor, setmeInfo, NULL, NULL, NULL );
760}
761
762tr_torrent *
763tr_torrentNew( const tr_ctor * ctor, int * setmeError )
764{
765    int off, len;
766    tr_bool hasInfo;
767    tr_info tmpInfo;
768    tr_parse_result r;
769    tr_torrent * tor = NULL;
770
771    assert( ctor != NULL );
772    assert( tr_isSession( tr_ctorGetSession( ctor ) ) );
773
774    r = torrentParseImpl( ctor, &tmpInfo, &hasInfo, &off, &len );
775    if( r == TR_PARSE_OK )
776    {
777        tor = tr_new0( tr_torrent, 1 );
778        tor->info = tmpInfo;
779        if( hasInfo )
780        {
781            tor->infoDictOffset = off;
782            tor->infoDictLength = len;
783        }
784        torrentInit( tor, ctor );
785    }
786    else
787    {
788        if( r == TR_PARSE_DUPLICATE )
789            tr_metainfoFree( &tmpInfo );
790
791        if( setmeError )
792            *setmeError = r;
793    }
794
795    return tor;
796}
797
798/**
799***
800**/
801
802void
803tr_torrentSetDownloadDir( tr_torrent * tor, const char * path )
804{
805    assert( tr_isTorrent( tor  ) );
806
807    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
808    {
809        tr_free( tor->downloadDir );
810        tor->downloadDir = tr_strdup( path );
811        tr_torrentSetDirty( tor );
812    }
813
814    refreshCurrentDir( tor );
815}
816
817const char*
818tr_torrentGetDownloadDir( const tr_torrent * tor )
819{
820    assert( tr_isTorrent( tor  ) );
821
822    return tor->downloadDir;
823}
824
825const char *
826tr_torrentGetCurrentDir( const tr_torrent * tor )
827{
828    assert( tr_isTorrent( tor  ) );
829
830    return tor->currentDir;
831}
832
833
834void
835tr_torrentChangeMyPort( tr_torrent * tor )
836{
837    assert( tr_isTorrent( tor  ) );
838
839    if( tor->isRunning )
840        tr_announcerChangeMyPort( tor );
841}
842
843static inline void
844tr_torrentManualUpdateImpl( void * vtor )
845{
846    tr_torrent * tor = vtor;
847
848    assert( tr_isTorrent( tor  ) );
849
850    if( tor->isRunning )
851        tr_announcerManualAnnounce( tor );
852}
853
854void
855tr_torrentManualUpdate( tr_torrent * tor )
856{
857    assert( tr_isTorrent( tor  ) );
858
859    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
860}
861
862tr_bool
863tr_torrentCanManualUpdate( const tr_torrent * tor )
864{
865    return ( tr_isTorrent( tor  ) )
866        && ( tor->isRunning )
867        && ( tr_announcerCanManualAnnounce( tor ) );
868}
869
870const tr_info *
871tr_torrentInfo( const tr_torrent * tor )
872{
873    return tr_isTorrent( tor ) ? &tor->info : NULL;
874}
875
876const tr_stat *
877tr_torrentStatCached( tr_torrent * tor )
878{
879    const time_t now = tr_time( );
880
881    return tr_isTorrent( tor ) && ( now == tor->lastStatTime )
882         ? &tor->stats
883         : tr_torrentStat( tor );
884}
885
886void
887tr_torrentSetVerifyState( tr_torrent * tor, tr_verify_state state )
888{
889    assert( tr_isTorrent( tor ) );
890    assert( state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW );
891
892    tor->verifyState = state;
893    tor->anyDate = tr_time( );
894}
895
896tr_torrent_activity
897tr_torrentGetActivity( tr_torrent * tor )
898{
899    assert( tr_isTorrent( tor ) );
900
901    tr_torrentRecheckCompleteness( tor );
902
903    if( tor->verifyState == TR_VERIFY_NOW )
904        return TR_STATUS_CHECK;
905    if( tor->verifyState == TR_VERIFY_WAIT )
906        return TR_STATUS_CHECK_WAIT;
907    if( !tor->isRunning )
908        return TR_STATUS_STOPPED;
909    if( tor->completeness == TR_LEECH )
910        return TR_STATUS_DOWNLOAD;
911
912    return TR_STATUS_SEED;
913}
914
915const tr_stat *
916tr_torrentStat( tr_torrent * tor )
917{
918    tr_stat *               s;
919    int                     usableSeeds;
920    uint64_t                now;
921    double                  downloadedForRatio, seedRatio=0;
922    double                  d;
923    tr_bool                 checkSeedRatio;
924
925    if( !tor )
926        return NULL;
927
928    assert( tr_isTorrent( tor ) );
929    tr_torrentLock( tor );
930
931    tor->lastStatTime = tr_time( );
932
933    s = &tor->stats;
934    s->id = tor->uniqueId;
935    s->activity = tr_torrentGetActivity( tor );
936    s->error = tor->error;
937    memcpy( s->errorString, tor->errorString, sizeof( s->errorString ) );
938
939    s->manualAnnounceTime = tr_announcerNextManualAnnounce( tor );
940
941    tr_peerMgrTorrentStats( tor,
942                            &s->peersKnown,
943                            &s->peersConnected,
944                            &usableSeeds,
945                            &s->webseedsSendingToUs,
946                            &s->peersSendingToUs,
947                            &s->peersGettingFromUs,
948                            s->peersFrom );
949
950    now = tr_date( );
951    d = tr_peerMgrGetWebseedSpeed( tor, now );
952    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
953    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
954    s->rawDownloadSpeed   = d + tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
955    s->pieceDownloadSpeed = d + tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
956
957    usableSeeds += tor->info.webseedCount;
958
959    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
960    s->metadataPercentComplete = tr_torrentGetMetadataPercent( tor );
961
962    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
963    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
964    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
965
966    s->recheckProgress = s->activity == TR_STATUS_CHECK
967                       ? 1.0 -
968                         ( tr_torrentCountUncheckedPieces( tor ) /
969                           (double) tor->info.pieceCount )
970                       : 0.0;
971
972    s->activityDate = tor->activityDate;
973    s->addedDate    = tor->addedDate;
974    s->doneDate     = tor->doneDate;
975    s->startDate    = tor->startDate;
976
977    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
978    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
979    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
980    s->haveValid       = tr_cpHaveValid( &tor->completion );
981    s->haveUnchecked   = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
982
983    if( usableSeeds > 0 )
984    {
985        s->desiredAvailable = s->leftUntilDone;
986    }
987    else if( !s->leftUntilDone || !s->peersConnected )
988    {
989        s->desiredAvailable = 0;
990    }
991    else
992    {
993        tr_piece_index_t i;
994        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable( tor );
995        s->desiredAvailable = 0;
996        for( i = 0; i < tor->info.pieceCount; ++i )
997            if( !tor->info.pieces[i].dnd && tr_bitfieldHasFast( peerPieces, i ) )
998                s->desiredAvailable += tr_cpMissingBlocksInPiece( &tor->completion, i );
999        s->desiredAvailable *= tor->blockSize;
1000        tr_bitfieldFree( peerPieces );
1001    }
1002
1003    downloadedForRatio = s->downloadedEver ? s->downloadedEver : s->haveValid;
1004    s->ratio = tr_getRatio( s->uploadedEver, downloadedForRatio );
1005
1006    checkSeedRatio = tr_torrentGetSeedRatio( tor, &seedRatio );
1007
1008    switch( s->activity )
1009    {
1010        /* etaXLSpeed exists because if we use the piece speed directly,
1011         * brief fluctuations cause the ETA to jump all over the place.
1012         * so, etaXLSpeed is a smoothed-out version of the piece speed
1013         * to dampen the effect of fluctuations */
1014
1015        case TR_STATUS_DOWNLOAD:
1016            if( ( tor->etaDLSpeedCalculatedAt + 800 ) < now ) {
1017                tor->etaDLSpeed = ( ( tor->etaDLSpeedCalculatedAt + 4000 ) < now )
1018                    ? s->pieceDownloadSpeed /* if no recent previous speed, no need to smooth */
1019                    : 0.8*tor->etaDLSpeed + 0.2*s->pieceDownloadSpeed; /* smooth across 5 readings */
1020                tor->etaDLSpeedCalculatedAt = now;
1021            }
1022
1023            if( s->leftUntilDone > s->desiredAvailable )
1024                s->eta = TR_ETA_NOT_AVAIL;
1025            else if( s->pieceDownloadSpeed < 0.1 )
1026                s->eta = TR_ETA_UNKNOWN;
1027            else
1028                s->eta = s->leftUntilDone / tor->etaDLSpeed / 1024.0;
1029            break;
1030
1031        case TR_STATUS_SEED:
1032            if( checkSeedRatio )
1033            {
1034                if( ( tor->etaULSpeedCalculatedAt + 800 ) < now ) {
1035                    tor->etaULSpeed = ( ( tor->etaULSpeedCalculatedAt + 4000 ) < now )
1036                        ? s->pieceUploadSpeed /* if no recent previous speed, no need to smooth */
1037                        : 0.8*tor->etaULSpeed + 0.2*s->pieceUploadSpeed; /* smooth across 5 readings */
1038                    tor->etaULSpeedCalculatedAt = now;
1039                }
1040
1041                if( s->pieceUploadSpeed < 0.1 )
1042                    s->eta = TR_ETA_UNKNOWN;
1043                else
1044                    s->eta = (downloadedForRatio * (seedRatio - s->ratio)) / tor->etaULSpeed / 1024.0;
1045            }
1046            else
1047                s->eta = TR_ETA_NOT_AVAIL;
1048            break;
1049
1050        default:
1051            s->eta = TR_ETA_NOT_AVAIL;
1052            break;
1053    }
1054
1055    if( !checkSeedRatio || s->ratio >= seedRatio || s->ratio == TR_RATIO_INF )
1056        s->percentRatio = 1.0;
1057    else if( s->ratio == TR_RATIO_NA )
1058        s->percentRatio = 0.0;
1059    else
1060        s->percentRatio = s->ratio / seedRatio;
1061
1062    tr_torrentUnlock( tor );
1063
1064    return s;
1065}
1066
1067/***
1068****
1069***/
1070
1071static uint64_t
1072fileBytesCompleted( const tr_torrent * tor, tr_file_index_t index )
1073{
1074    uint64_t total = 0;
1075    const tr_file * f = &tor->info.files[index];
1076
1077    if( f->length )
1078    {
1079        const tr_block_index_t firstBlock = f->offset / tor->blockSize;
1080        const uint64_t lastByte = f->offset + f->length - 1;
1081        const tr_block_index_t lastBlock = lastByte / tor->blockSize;
1082
1083        if( firstBlock == lastBlock )
1084        {
1085            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1086                total = f->length;
1087        }
1088        else
1089        {
1090            tr_block_index_t i;
1091
1092            /* the first block */
1093            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1094                total += tor->blockSize - ( f->offset % tor->blockSize );
1095
1096            /* the middle blocks */
1097            if( f->firstPiece == f->lastPiece )
1098            {
1099                for( i=firstBlock+1; i<lastBlock; ++i )
1100                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1101                        total += tor->blockSize;
1102            }
1103            else
1104            {
1105                uint64_t b = 0;
1106                const tr_block_index_t firstBlockOfLastPiece
1107                           = tr_torPieceFirstBlock( tor, f->lastPiece );
1108                const tr_block_index_t lastBlockOfFirstPiece
1109                           = tr_torPieceFirstBlock( tor, f->firstPiece )
1110                             + tr_torPieceCountBlocks( tor, f->firstPiece ) - 1;
1111
1112                /* the rest of the first piece */
1113                for( i=firstBlock+1; i<lastBlock && i<=lastBlockOfFirstPiece; ++i )
1114                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1115                        ++b;
1116
1117                /* the middle pieces */
1118                if( f->firstPiece + 1 < f->lastPiece )
1119                    for( i=f->firstPiece+1; i<f->lastPiece; ++i )
1120                        b += tor->blockCountInPiece - tr_cpMissingBlocksInPiece( &tor->completion, i );
1121
1122                /* the rest of the last piece */
1123                for( i=firstBlockOfLastPiece; i<lastBlock; ++i )
1124                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1125                        ++b;
1126
1127                b *= tor->blockSize;
1128                total += b;
1129            }
1130
1131            /* the last block */
1132            if( tr_cpBlockIsCompleteFast( &tor->completion, lastBlock ) )
1133                total += ( f->offset + f->length ) - ( tor->blockSize * lastBlock );
1134        }
1135    }
1136
1137    return total;
1138}
1139
1140tr_file_stat *
1141tr_torrentFiles( const tr_torrent * tor,
1142                 tr_file_index_t *  fileCount )
1143{
1144    tr_file_index_t       i;
1145    const tr_file_index_t n = tor->info.fileCount;
1146    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1147    tr_file_stat *        walk = files;
1148    const tr_bool         isSeed = tor->completeness == TR_SEED;
1149
1150    assert( tr_isTorrent( tor ) );
1151
1152    for( i=0; i<n; ++i, ++walk ) {
1153        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1154        walk->bytesCompleted = b;
1155        walk->progress = tor->info.files[i].length > 0 ? ( (float)b / tor->info.files[i].length ) : 1.0;
1156    }
1157
1158    if( fileCount )
1159        *fileCount = n;
1160
1161    return files;
1162}
1163
1164void
1165tr_torrentFilesFree( tr_file_stat *            files,
1166                     tr_file_index_t fileCount UNUSED )
1167{
1168    tr_free( files );
1169}
1170
1171/***
1172****
1173***/
1174
1175float*
1176tr_torrentWebSpeeds( const tr_torrent * tor )
1177{
1178    return tr_isTorrent( tor )
1179         ? tr_peerMgrWebSpeeds( tor )
1180         : NULL;
1181}
1182
1183tr_peer_stat *
1184tr_torrentPeers( const tr_torrent * tor,
1185                 int *              peerCount )
1186{
1187    tr_peer_stat * ret = NULL;
1188
1189    if( tr_isTorrent( tor ) )
1190        ret = tr_peerMgrPeerStats( tor, peerCount );
1191
1192    return ret;
1193}
1194
1195void
1196tr_torrentPeersFree( tr_peer_stat * peers,
1197                     int peerCount  UNUSED )
1198{
1199    tr_free( peers );
1200}
1201
1202tr_tracker_stat *
1203tr_torrentTrackers( const tr_torrent * torrent,
1204                    int              * setmeTrackerCount )
1205{
1206    assert( tr_isTorrent( torrent ) );
1207
1208    return tr_announcerStats( torrent, setmeTrackerCount );
1209}
1210
1211void
1212tr_torrentTrackersFree( tr_tracker_stat * trackers,
1213                        int trackerCount )
1214{
1215    tr_announcerStatsFree( trackers, trackerCount );
1216}
1217
1218void
1219tr_torrentAvailability( const tr_torrent * tor,
1220                        int8_t *           tab,
1221                        int                size )
1222{
1223    tr_peerMgrTorrentAvailability( tor, tab, size );
1224}
1225
1226void
1227tr_torrentAmountFinished( const tr_torrent * tor,
1228                          float *            tab,
1229                          int                size )
1230{
1231    assert( tr_isTorrent( tor ) );
1232
1233    tr_torrentLock( tor );
1234    tr_cpGetAmountDone( &tor->completion, tab, size );
1235    tr_torrentUnlock( tor );
1236}
1237
1238static void
1239tr_torrentResetTransferStats( tr_torrent * tor )
1240{
1241    assert( tr_isTorrent( tor ) );
1242
1243    tr_torrentLock( tor );
1244
1245    tor->downloadedPrev += tor->downloadedCur;
1246    tor->downloadedCur   = 0;
1247    tor->uploadedPrev   += tor->uploadedCur;
1248    tor->uploadedCur     = 0;
1249    tor->corruptPrev    += tor->corruptCur;
1250    tor->corruptCur      = 0;
1251
1252    tr_torrentSetDirty( tor );
1253
1254    tr_torrentUnlock( tor );
1255}
1256
1257void
1258tr_torrentSetHasPiece( tr_torrent *     tor,
1259                       tr_piece_index_t pieceIndex,
1260                       tr_bool          has )
1261{
1262    assert( tr_isTorrent( tor ) );
1263    assert( pieceIndex < tor->info.pieceCount );
1264
1265    if( has )
1266        tr_cpPieceAdd( &tor->completion, pieceIndex );
1267    else
1268        tr_cpPieceRem( &tor->completion, pieceIndex );
1269}
1270
1271/***
1272****
1273***/
1274
1275static void
1276freeTorrent( tr_torrent * tor )
1277{
1278    tr_torrent * t;
1279    tr_session *  session = tor->session;
1280    tr_info *    inf = &tor->info;
1281
1282    assert( tr_isTorrent( tor ) );
1283    assert( !tor->isRunning );
1284
1285    tr_sessionLock( session );
1286
1287    tr_peerMgrRemoveTorrent( tor );
1288
1289    tr_cpDestruct( &tor->completion );
1290
1291    tr_announcerUnsubscribe( tor->tiers, tor->tiersSubscription );
1292    tr_announcerRemoveTorrent( session->announcer, tor );
1293
1294    tr_bitfieldDestruct( &tor->checkedPieces );
1295
1296    tr_free( tor->downloadDir );
1297    tr_free( tor->incompleteDir );
1298    tr_free( tor->peer_id );
1299
1300    if( tor == session->torrentList )
1301        session->torrentList = tor->next;
1302    else for( t = session->torrentList; t != NULL; t = t->next ) {
1303        if( t->next == tor ) {
1304            t->next = tor->next;
1305            break;
1306        }
1307    }
1308
1309    assert( session->torrentCount >= 1 );
1310    session->torrentCount--;
1311
1312    tr_bandwidthFree( tor->bandwidth );
1313
1314    tr_metainfoFree( inf );
1315    tr_free( tor );
1316
1317    tr_sessionUnlock( session );
1318}
1319
1320/**
1321***  Start/Stop Callback
1322**/
1323
1324static void
1325checkAndStartImpl( void * vtor )
1326{
1327    tr_torrent * tor = vtor;
1328
1329    assert( tr_isTorrent( tor ) );
1330
1331    tr_sessionLock( tor->session );
1332
1333    /** If we had local data before, but it's disappeared,
1334        stop the torrent and log an error. */
1335    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1336    {
1337        tr_torrentSetLocalError( tor, _( "No data found!  Reconnect any disconnected drives, use \"Set Location\", or restart the torrent to re-download." ) );
1338        tr_torrentStop( tor );
1339    }
1340    else
1341    {
1342        const time_t now = tr_time( );
1343        tor->isRunning = TRUE;
1344        tor->needsSeedRatioCheck = TRUE;
1345        tor->error = TR_STAT_OK;
1346        tor->errorString[0] = '\0';
1347        tor->completeness = tr_cpGetStatus( &tor->completion );
1348        tor->startDate = tor->anyDate = now;
1349
1350        tr_torrentResetTransferStats( tor );
1351        tr_announcerTorrentStarted( tor );
1352        tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1353        tor->dhtAnnounce6At = now + tr_cryptoWeakRandInt( 20 );
1354        tr_peerMgrStartTorrent( tor );
1355    }
1356
1357    tr_sessionUnlock( tor->session );
1358}
1359
1360static void
1361checkAndStartCB( tr_torrent * tor )
1362{
1363    assert( tr_isTorrent( tor ) );
1364    assert( tr_isSession( tor->session ) );
1365
1366    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1367}
1368
1369static void
1370torrentStart( tr_torrent * tor )
1371{
1372    assert( tr_isTorrent( tor ) );
1373
1374    tr_sessionLock( tor->session );
1375
1376    if( !tor->isRunning )
1377    {
1378        tr_verifyRemove( tor );
1379
1380        /* corresponds to the peer_id sent as a tracker request parameter.
1381         * one tracker admin says: "When the same torrent is opened and
1382         * closed and opened again without quitting Transmission ...
1383         * change the peerid. It would help sometimes if a stopped event
1384         * was missed to ensure that we didn't think someone was cheating. */
1385        tr_free( tor->peer_id );
1386        tor->peer_id = tr_peerIdNew( );
1387
1388        tor->isRunning = 1;
1389        tr_torrentSetDirty( tor );
1390        tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1391        tr_verifyAdd( tor, checkAndStartCB );
1392    }
1393
1394    tr_sessionUnlock( tor->session );
1395}
1396
1397void
1398tr_torrentStart( tr_torrent * tor )
1399{
1400    if( tr_isTorrent( tor ) )
1401        torrentStart( tor );
1402}
1403
1404static void
1405torrentRecheckDoneImpl( void * vtor )
1406{
1407    tr_torrent * tor = vtor;
1408
1409    assert( tr_isTorrent( tor ) );
1410    tr_torrentRecheckCompleteness( tor );
1411
1412    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1413    {
1414        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1415        tr_torrentStop( tor );
1416    }
1417    else if( tor->startAfterVerify )
1418    {
1419        tor->startAfterVerify = FALSE;
1420
1421        tr_torrentStart( tor );
1422    }
1423}
1424
1425static void
1426torrentRecheckDoneCB( tr_torrent * tor )
1427{
1428    assert( tr_isTorrent( tor ) );
1429
1430    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1431}
1432
1433static void
1434verifyTorrent( void * vtor )
1435{
1436    tr_torrent * tor = vtor;
1437
1438    assert( tr_isTorrent( tor ) );
1439    tr_sessionLock( tor->session );
1440
1441    /* if the torrent's already being verified, stop it */
1442    tr_verifyRemove( tor );
1443
1444    /* if the torrent's running, stop it & set the restart-after-verify flag */
1445    if( tor->startAfterVerify || tor->isRunning ) {
1446        tr_torrentStop( tor );
1447        tor->startAfterVerify = TRUE;
1448    }
1449
1450    /* add the torrent to the recheck queue */
1451    tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1452    tr_torrentUncheck( tor );
1453    tr_verifyAdd( tor, torrentRecheckDoneCB );
1454
1455    tr_sessionUnlock( tor->session );
1456}
1457
1458void
1459tr_torrentVerify( tr_torrent * tor )
1460{
1461    if( tr_isTorrent( tor ) )
1462        tr_runInEventThread( tor->session, verifyTorrent, tor );
1463}
1464
1465void
1466tr_torrentSave( tr_torrent * tor )
1467{
1468    assert( tr_isTorrent( tor ) );
1469
1470    if( tor->isDirty )
1471    {
1472        tor->isDirty = FALSE;
1473        tr_torrentSaveResume( tor );
1474    }
1475}
1476
1477static void
1478stopTorrent( void * vtor )
1479{
1480    tr_torrent * tor = vtor;
1481
1482    assert( tr_isTorrent( tor ) );
1483
1484    tr_verifyRemove( tor );
1485    tr_peerMgrStopTorrent( tor );
1486    tr_announcerTorrentStopped( tor );
1487
1488    tr_fdTorrentClose( tor->session, tor->uniqueId );
1489
1490    if( !tor->isDeleting )
1491        tr_torrentSave( tor );
1492}
1493
1494void
1495tr_torrentStop( tr_torrent * tor )
1496{
1497    assert( tr_isTorrent( tor ) );
1498
1499    if( tr_isTorrent( tor ) )
1500    {
1501        tr_sessionLock( tor->session );
1502
1503        tor->isRunning = 0;
1504        tr_torrentSetDirty( tor );
1505        tr_runInEventThread( tor->session, stopTorrent, tor );
1506
1507        tr_sessionUnlock( tor->session );
1508    }
1509}
1510
1511static void
1512closeTorrent( void * vtor )
1513{
1514    tr_benc * d;
1515    tr_torrent * tor = vtor;
1516
1517    assert( tr_isTorrent( tor ) );
1518
1519    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1520    tr_bencDictAddInt( d, "id", tor->uniqueId );
1521    tr_bencDictAddInt( d, "date", tr_time( ) );
1522
1523    stopTorrent( tor );
1524
1525    if( tor->isDeleting )
1526    {
1527        tr_metainfoRemoveSaved( tor->session, &tor->info );
1528        tr_torrentRemoveResume( tor );
1529    }
1530
1531    tor->isRunning = 0;
1532    freeTorrent( tor );
1533}
1534
1535void
1536tr_torrentFree( tr_torrent * tor )
1537{
1538    if( tr_isTorrent( tor ) )
1539    {
1540        tr_session * session = tor->session;
1541        assert( tr_isSession( session ) );
1542        tr_sessionLock( session );
1543
1544        tr_torrentClearCompletenessCallback( tor );
1545        tr_runInEventThread( session, closeTorrent, tor );
1546
1547        tr_sessionUnlock( session );
1548    }
1549}
1550
1551void
1552tr_torrentRemove( tr_torrent * tor )
1553{
1554    assert( tr_isTorrent( tor ) );
1555
1556    tor->isDeleting = 1;
1557    tr_torrentFree( tor );
1558}
1559
1560/**
1561***  Completeness
1562**/
1563
1564static const char *
1565getCompletionString( int type )
1566{
1567    switch( type )
1568    {
1569        /* Translators: this is a minor point that's safe to skip over, but FYI:
1570           "Complete" and "Done" are specific, different terms in Transmission:
1571           "Complete" means we've downloaded every file in the torrent.
1572           "Done" means we're done downloading the files we wanted, but NOT all
1573           that exist */
1574        case TR_PARTIAL_SEED:
1575            return _( "Done" );
1576
1577        case TR_SEED:
1578            return _( "Complete" );
1579
1580        default:
1581            return _( "Incomplete" );
1582    }
1583}
1584
1585static void
1586fireCompletenessChange( tr_torrent       * tor,
1587                        tr_completeness    status )
1588{
1589    assert( tr_isTorrent( tor ) );
1590    assert( ( status == TR_LEECH )
1591         || ( status == TR_SEED )
1592         || ( status == TR_PARTIAL_SEED ) );
1593
1594    if( tor->completeness_func )
1595        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1596}
1597
1598void
1599tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1600                                   tr_torrent_completeness_func    func,
1601                                   void                          * user_data )
1602{
1603    assert( tr_isTorrent( tor ) );
1604
1605    tor->completeness_func = func;
1606    tor->completeness_func_user_data = user_data;
1607}
1608
1609void
1610tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1611{
1612    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1613}
1614
1615void
1616tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1617                                    tr_torrent_ratio_limit_hit_func  func,
1618                                    void                           * user_data )
1619{
1620    assert( tr_isTorrent( tor ) );
1621
1622    tor->ratio_limit_hit_func = func;
1623    tor->ratio_limit_hit_func_user_data = user_data;
1624}
1625
1626void
1627tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1628{
1629    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1630}
1631
1632void
1633tr_torrentRecheckCompleteness( tr_torrent * tor )
1634{
1635    tr_completeness completeness;
1636
1637    assert( tr_isTorrent( tor ) );
1638
1639    tr_torrentLock( tor );
1640
1641    completeness = tr_cpGetStatus( &tor->completion );
1642
1643    if( completeness != tor->completeness )
1644    {
1645        const int recentChange = tor->downloadedCur != 0;
1646
1647        if( recentChange )
1648        {
1649            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1650                      getCompletionString( tor->completeness ),
1651                      getCompletionString( completeness ) );
1652        }
1653
1654        tor->completeness = completeness;
1655        tor->needsSeedRatioCheck = TRUE;
1656        tr_fdTorrentClose( tor->session, tor->uniqueId );
1657
1658        /* if the torrent is a seed now,
1659         * and the files used to be in the incompleteDir,
1660         * then move them to the destination directory */
1661        if( tr_torrentIsSeed( tor ) && ( tor->currentDir == tor->incompleteDir ) )
1662            tr_torrentSetLocation( tor, tor->downloadDir, TRUE, NULL, NULL );
1663
1664        fireCompletenessChange( tor, completeness );
1665
1666        if( recentChange && tr_torrentIsSeed( tor ) )
1667        {
1668            tr_announcerTorrentCompleted( tor );
1669
1670            tor->doneDate = tor->anyDate = tr_time( );
1671        }
1672
1673        tr_torrentSetDirty( tor );
1674    }
1675
1676    tr_torrentUnlock( tor );
1677}
1678
1679/***
1680****
1681***/
1682
1683static void
1684tr_torrentFireMetadataCompleted( tr_torrent * tor )
1685{
1686    assert( tr_isTorrent( tor ) );
1687
1688    if( tor->metadata_func )
1689        tor->metadata_func( tor, tor->metadata_func_user_data );
1690}
1691
1692void
1693tr_torrentSetMetadataCallback( tr_torrent                * tor,
1694                               tr_torrent_metadata_func    func,
1695                               void                      * user_data )
1696{
1697    assert( tr_isTorrent( tor ) );
1698
1699    tor->metadata_func = func;
1700    tor->metadata_func_user_data = user_data;
1701}
1702
1703
1704/**
1705***  File priorities
1706**/
1707
1708void
1709tr_torrentInitFilePriority( tr_torrent *    tor,
1710                            tr_file_index_t fileIndex,
1711                            tr_priority_t   priority )
1712{
1713    tr_piece_index_t i;
1714    tr_file *        file;
1715
1716    assert( tr_isTorrent( tor ) );
1717    assert( fileIndex < tor->info.fileCount );
1718    assert( tr_isPriority( priority ) );
1719
1720    file = &tor->info.files[fileIndex];
1721    file->priority = priority;
1722    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1723        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1724}
1725
1726void
1727tr_torrentSetFilePriorities( tr_torrent *      tor,
1728                             tr_file_index_t * files,
1729                             tr_file_index_t   fileCount,
1730                             tr_priority_t     priority )
1731{
1732    tr_file_index_t i;
1733    assert( tr_isTorrent( tor ) );
1734    tr_torrentLock( tor );
1735
1736    for( i = 0; i < fileCount; ++i )
1737        if( files[i] < tor->info.fileCount )
1738            tr_torrentInitFilePriority( tor, files[i], priority );
1739    tr_torrentSetDirty( tor );
1740    tr_peerMgrRebuildRequests( tor );
1741
1742    tr_torrentUnlock( tor );
1743}
1744
1745tr_priority_t*
1746tr_torrentGetFilePriorities( const tr_torrent * tor )
1747{
1748    tr_file_index_t i;
1749    tr_priority_t * p;
1750
1751    assert( tr_isTorrent( tor ) );
1752
1753    tr_torrentLock( tor );
1754    p = tr_new0( tr_priority_t, tor->info.fileCount );
1755    for( i = 0; i < tor->info.fileCount; ++i )
1756        p[i] = tor->info.files[i].priority;
1757    tr_torrentUnlock( tor );
1758
1759    return p;
1760}
1761
1762/**
1763***  File DND
1764**/
1765
1766static void
1767setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1768{
1769    tr_file *        file;
1770    const int        dnd = !doDownload;
1771    tr_piece_index_t firstPiece, firstPieceDND;
1772    tr_piece_index_t lastPiece, lastPieceDND;
1773    tr_file_index_t  i;
1774
1775    assert( tr_isTorrent( tor ) );
1776
1777    file = &tor->info.files[fileIndex];
1778    file->dnd = dnd;
1779    firstPiece = file->firstPiece;
1780    lastPiece = file->lastPiece;
1781
1782    /* can't set the first piece to DND unless
1783       every file using that piece is DND */
1784    firstPieceDND = dnd;
1785    if( fileIndex > 0 )
1786    {
1787        for( i = fileIndex - 1; firstPieceDND; --i )
1788        {
1789            if( tor->info.files[i].lastPiece != firstPiece )
1790                break;
1791            firstPieceDND = tor->info.files[i].dnd;
1792            if( !i )
1793                break;
1794        }
1795    }
1796
1797    /* can't set the last piece to DND unless
1798       every file using that piece is DND */
1799    lastPieceDND = dnd;
1800    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1801    {
1802        if( tor->info.files[i].firstPiece != lastPiece )
1803            break;
1804        lastPieceDND = tor->info.files[i].dnd;
1805    }
1806
1807    if( firstPiece == lastPiece )
1808    {
1809        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1810    }
1811    else
1812    {
1813        tr_piece_index_t pp;
1814        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1815        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1816        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1817            tor->info.pieces[pp].dnd = dnd;
1818    }
1819}
1820
1821void
1822tr_torrentInitFileDLs( tr_torrent      * tor,
1823                       tr_file_index_t * files,
1824                       tr_file_index_t   fileCount,
1825                       tr_bool           doDownload )
1826{
1827    tr_file_index_t i;
1828
1829    assert( tr_isTorrent( tor ) );
1830
1831    tr_torrentLock( tor );
1832
1833    for( i=0; i<fileCount; ++i )
1834        if( files[i] < tor->info.fileCount )
1835            setFileDND( tor, files[i], doDownload );
1836
1837    tr_cpInvalidateDND( &tor->completion );
1838    tor->needsSeedRatioCheck = TRUE;
1839
1840    tr_torrentUnlock( tor );
1841}
1842
1843void
1844tr_torrentSetFileDLs( tr_torrent *      tor,
1845                      tr_file_index_t * files,
1846                      tr_file_index_t   fileCount,
1847                      tr_bool           doDownload )
1848{
1849    assert( tr_isTorrent( tor ) );
1850    tr_torrentLock( tor );
1851
1852    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1853    tr_torrentSetDirty( tor );
1854    tr_peerMgrRebuildRequests( tor );
1855
1856    tr_torrentUnlock( tor );
1857}
1858
1859/***
1860****
1861***/
1862
1863tr_priority_t
1864tr_torrentGetPriority( const tr_torrent * tor )
1865{
1866    assert( tr_isTorrent( tor ) );
1867
1868    return tor->bandwidth->priority;
1869}
1870
1871void
1872tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1873{
1874    assert( tr_isTorrent( tor ) );
1875    assert( tr_isPriority( priority ) );
1876
1877    if( tor->bandwidth->priority != priority )
1878    {
1879        tor->bandwidth->priority = priority;
1880
1881        tr_torrentSetDirty( tor );
1882    }
1883}
1884
1885/***
1886****
1887***/
1888
1889void
1890tr_torrentSetPeerLimit( tr_torrent * tor,
1891                        uint16_t     maxConnectedPeers )
1892{
1893    assert( tr_isTorrent( tor ) );
1894
1895    if ( tor->maxConnectedPeers != maxConnectedPeers )
1896    {
1897        tor->maxConnectedPeers = maxConnectedPeers;
1898
1899        tr_torrentSetDirty( tor );
1900    }
1901}
1902
1903uint16_t
1904tr_torrentGetPeerLimit( const tr_torrent * tor )
1905{
1906    assert( tr_isTorrent( tor ) );
1907
1908    return tor->maxConnectedPeers;
1909}
1910
1911/***
1912****
1913***/
1914
1915tr_block_index_t
1916_tr_block( const tr_torrent * tor,
1917           tr_piece_index_t   index,
1918           uint32_t           offset )
1919{
1920    tr_block_index_t ret;
1921
1922    assert( tr_isTorrent( tor ) );
1923
1924    ret = index;
1925    ret *= ( tor->info.pieceSize / tor->blockSize );
1926    ret += offset / tor->blockSize;
1927    return ret;
1928}
1929
1930tr_bool
1931tr_torrentReqIsValid( const tr_torrent * tor,
1932                      tr_piece_index_t   index,
1933                      uint32_t           offset,
1934                      uint32_t           length )
1935{
1936    int err = 0;
1937
1938    assert( tr_isTorrent( tor ) );
1939
1940    if( index >= tor->info.pieceCount )
1941        err = 1;
1942    else if( length < 1 )
1943        err = 2;
1944    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1945        err = 3;
1946    else if( length > MAX_BLOCK_SIZE )
1947        err = 4;
1948    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1949        err = 5;
1950
1951    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
1952                              (unsigned long)index,
1953                              (unsigned long)offset,
1954                              (unsigned long)length,
1955                              err );
1956
1957    return !err;
1958}
1959
1960uint64_t
1961tr_pieceOffset( const tr_torrent * tor,
1962                tr_piece_index_t   index,
1963                uint32_t           offset,
1964                uint32_t           length )
1965{
1966    uint64_t ret;
1967
1968    assert( tr_isTorrent( tor ) );
1969
1970    ret = tor->info.pieceSize;
1971    ret *= index;
1972    ret += offset;
1973    ret += length;
1974    return ret;
1975}
1976
1977/***
1978****
1979***/
1980
1981void
1982tr_torrentSetPieceChecked( tr_torrent        * tor,
1983                           tr_piece_index_t    piece,
1984                           tr_bool             isChecked )
1985{
1986    assert( tr_isTorrent( tor ) );
1987
1988    if( isChecked )
1989        tr_bitfieldAdd( &tor->checkedPieces, piece );
1990    else
1991        tr_bitfieldRem( &tor->checkedPieces, piece );
1992}
1993
1994void
1995tr_torrentSetFileChecked( tr_torrent *    tor,
1996                          tr_file_index_t fileIndex,
1997                          tr_bool         isChecked )
1998{
1999    const tr_file *        file = &tor->info.files[fileIndex];
2000    const tr_piece_index_t begin = file->firstPiece;
2001    const tr_piece_index_t end = file->lastPiece + 1;
2002
2003    assert( tr_isTorrent( tor ) );
2004
2005    if( isChecked )
2006        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
2007    else
2008        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
2009}
2010
2011tr_bool
2012tr_torrentIsFileChecked( const tr_torrent * tor,
2013                         tr_file_index_t    fileIndex )
2014{
2015    const tr_file *        file = &tor->info.files[fileIndex];
2016    const tr_piece_index_t begin = file->firstPiece;
2017    const tr_piece_index_t end = file->lastPiece + 1;
2018    tr_piece_index_t       i;
2019    tr_bool                isChecked = TRUE;
2020
2021    assert( tr_isTorrent( tor ) );
2022
2023    for( i = begin; isChecked && i < end; ++i )
2024        if( !tr_torrentIsPieceChecked( tor, i ) )
2025            isChecked = FALSE;
2026
2027    return isChecked;
2028}
2029
2030void
2031tr_torrentUncheck( tr_torrent * tor )
2032{
2033    assert( tr_isTorrent( tor ) );
2034
2035    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
2036}
2037
2038int
2039tr_torrentCountUncheckedPieces( const tr_torrent * tor )
2040{
2041    assert( tr_isTorrent( tor ) );
2042
2043    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
2044}
2045
2046time_t*
2047tr_torrentGetMTimes( const tr_torrent * tor, size_t * setme_n )
2048{
2049    size_t       i;
2050    const size_t n = tor->info.fileCount;
2051    time_t *     m = tr_new0( time_t, n );
2052
2053    assert( tr_isTorrent( tor ) );
2054
2055    for( i = 0; i < n; ++i )
2056    {
2057        struct stat sb;
2058        char * path = tr_torrentFindFile( tor, i );
2059        if( ( path != NULL ) && !stat( path, &sb ) && S_ISREG( sb.st_mode ) )
2060        {
2061#ifdef SYS_DARWIN
2062            m[i] = sb.st_mtimespec.tv_sec;
2063#else
2064            m[i] = sb.st_mtime;
2065#endif
2066        }
2067        tr_free( path );
2068    }
2069
2070    *setme_n = n;
2071    return m;
2072}
2073
2074/***
2075****
2076***/
2077
2078tr_bool
2079tr_torrentSetAnnounceList( tr_torrent             * tor,
2080                           const tr_tracker_info  * trackers,
2081                           int                      trackerCount )
2082{
2083    int i;
2084    tr_benc metainfo;
2085    tr_bool ok = TRUE;
2086    tr_torrentLock( tor );
2087
2088    assert( tr_isTorrent( tor ) );
2089
2090    /* look for bad URLs */
2091    for( i=0; ok && i<trackerCount; ++i )
2092        if( !tr_urlIsValidTracker( trackers[i].announce ) )
2093            ok = FALSE;
2094
2095    /* save to the .torrent file */
2096    if( ok && !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2097    {
2098        tr_bool hasInfo;
2099        tr_info tmpInfo;
2100
2101        /* remove the old fields */
2102        tr_bencDictRemove( &metainfo, "announce" );
2103        tr_bencDictRemove( &metainfo, "announce-list" );
2104
2105        /* add the new fields */
2106        if( trackerCount > 0 )
2107        {
2108            tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2109        }
2110        if( trackerCount > 1 )
2111        {
2112            int i;
2113            int prevTier = -1;
2114            tr_benc * tier = NULL;
2115            tr_benc * announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2116
2117            for( i=0; i<trackerCount; ++i ) {
2118                if( prevTier != trackers[i].tier ) {
2119                    prevTier = trackers[i].tier;
2120                    tier = tr_bencListAddList( announceList, 0 );
2121                }
2122                tr_bencListAddStr( tier, trackers[i].announce );
2123            }
2124        }
2125
2126        /* try to parse it back again, to make sure it's good */
2127        memset( &tmpInfo, 0, sizeof( tr_info ) );
2128        if( tr_metainfoParse( tor->session, &metainfo, &tmpInfo,
2129                              &hasInfo, &tor->infoDictOffset, &tor->infoDictLength ) )
2130        {
2131            /* it's good, so keep these new trackers and free the old ones */
2132
2133            tr_info swap;
2134            swap.trackers = tor->info.trackers;
2135            swap.trackerCount = tor->info.trackerCount;
2136            tor->info.trackers = tmpInfo.trackers;
2137            tor->info.trackerCount = tmpInfo.trackerCount;
2138            tmpInfo.trackers = swap.trackers;
2139            tmpInfo.trackerCount = swap.trackerCount;
2140
2141            tr_metainfoFree( &tmpInfo );
2142            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2143        }
2144
2145        /* cleanup */
2146        tr_bencFree( &metainfo );
2147
2148        /* tell the announcer to reload this torrent's tracker list */
2149        tr_announcerResetTorrent( tor->session->announcer, tor );
2150    }
2151
2152    tr_torrentUnlock( tor );
2153    return ok;
2154}
2155
2156/**
2157***
2158**/
2159
2160void
2161tr_torrentSetAddedDate( tr_torrent * tor,
2162                        time_t       t )
2163{
2164    assert( tr_isTorrent( tor ) );
2165
2166    tor->addedDate = t;
2167    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2168}
2169
2170void
2171tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2172{
2173    assert( tr_isTorrent( tor ) );
2174
2175    tor->activityDate = t;
2176    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2177}
2178
2179void
2180tr_torrentSetDoneDate( tr_torrent * tor,
2181                       time_t       t )
2182{
2183    assert( tr_isTorrent( tor ) );
2184
2185    tor->doneDate = t;
2186    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2187}
2188
2189/**
2190***
2191**/
2192
2193uint64_t
2194tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2195{
2196    tr_file_index_t i;
2197    uint64_t bytesLeft = 0;
2198
2199    assert( tr_isTorrent( tor ) );
2200
2201    for( i=0; i<tor->info.fileCount; ++i )
2202    {
2203        if( !tor->info.files[i].dnd )
2204        {
2205            struct stat sb;
2206            const uint64_t length = tor->info.files[i].length;
2207            char * path = tr_torrentFindFile( tor, i );
2208
2209            bytesLeft += length;
2210
2211            if( ( path != NULL ) && !stat( path, &sb )
2212                                 && S_ISREG( sb.st_mode )
2213                                 && ( (uint64_t)sb.st_size <= length ) )
2214                bytesLeft -= sb.st_size;
2215
2216            tr_free( path );
2217        }
2218    }
2219
2220    return bytesLeft;
2221}
2222
2223/****
2224*****  Removing the torrent's local data
2225****/
2226
2227static int
2228vstrcmp( const void * a, const void * b )
2229{
2230    return strcmp( a, b );
2231}
2232
2233static int
2234compareLongestFirst( const void * a, const void * b )
2235{
2236    const size_t alen = strlen( a );
2237    const size_t blen = strlen( b );
2238
2239    if( alen != blen )
2240        return alen > blen ? -1 : 1;
2241
2242    return vstrcmp( a, b );
2243}
2244
2245static void
2246addDirtyFile( const char  * root,
2247              const char  * filename,
2248              tr_ptrArray * dirtyFolders )
2249{
2250    char * dir = tr_dirname( filename );
2251
2252    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2253    while (     ( dir != NULL )
2254             && ( strlen( root ) <= strlen( dir ) )
2255             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2256    {
2257        char * tmp;
2258        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2259
2260        tmp = tr_dirname( dir );
2261        tr_free( dir );
2262        dir = tmp;
2263    }
2264
2265    tr_free( dir );
2266}
2267
2268static void
2269walkLocalData( const tr_torrent * tor,
2270               const char       * root,
2271               const char       * dir,
2272               const char       * base,
2273               tr_ptrArray      * torrentFiles,
2274               tr_ptrArray      * folders,
2275               tr_ptrArray      * dirtyFolders )
2276{
2277    int i;
2278    struct stat sb;
2279    char * buf;
2280
2281    assert( tr_isTorrent( tor ) );
2282
2283    buf = tr_buildPath( dir, base, NULL );
2284    i = stat( buf, &sb );
2285    if( !i )
2286    {
2287        DIR * odir = NULL;
2288
2289        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2290        {
2291            struct dirent *d;
2292            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2293            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2294                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2295                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2296            closedir( odir );
2297        }
2298        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2299        {
2300            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2301            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2302            if( !isTorrentFile )
2303                addDirtyFile( root, buf, dirtyFolders );
2304        }
2305    }
2306
2307    tr_free( buf );
2308}
2309
2310static void
2311deleteLocalFile( const char * filename, tr_fileFunc fileFunc )
2312{
2313    struct stat sb;
2314    if( !stat( filename, &sb ) ) /* if file exists... */
2315        fileFunc( filename );
2316}
2317
2318static void
2319deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2320{
2321    int i, n;
2322    char ** s;
2323    tr_file_index_t f;
2324    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2325    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2326    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2327
2328    const char * firstFile = tor->info.files[0].name;
2329    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2330    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2331    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2332
2333    assert( tr_isTorrent( tor ) );
2334
2335    for( f=0; f<tor->info.fileCount; ++f ) {
2336        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2337        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2338    }
2339
2340    /* build the set of folders and dirtyFolders */
2341    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2342
2343    /* try to remove entire folders first, so that the recycle bin will be tidy */
2344    s = (char**) tr_ptrArrayPeek( &folders, &n );
2345    for( i=0; i<n; ++i )
2346        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2347            deleteLocalFile( s[i], fileFunc );
2348
2349    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2350    for( i=0, n=tr_ptrArraySize( &torrentFiles ); i<n; ++i ) {
2351        char * path = tr_buildPath( tor->currentDir, tr_ptrArrayNth( &torrentFiles, i ), NULL );
2352        deleteLocalFile( path, fileFunc );
2353        tr_free( path );
2354    }
2355
2356    /* Now clean out the directories left empty from the previous step.
2357     * Work from deepest to shallowest s.t. lower folders
2358     * won't prevent the upper folders from being deleted */
2359    {
2360        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2361        s = (char**) tr_ptrArrayPeek( &folders, &n );
2362        for( i=0; i<n; ++i )
2363            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2364                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2365        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2366        for( i=0; i<n; ++i ) {
2367#ifdef SYS_DARWIN
2368            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2369            deleteLocalFile( dsStore, fileFunc );
2370            tr_free( dsStore );
2371#endif
2372            deleteLocalFile( s[i], fileFunc );
2373        }
2374        tr_ptrArrayDestruct( &cleanFolders, NULL );
2375    }
2376
2377    /* cleanup */
2378    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2379    tr_ptrArrayDestruct( &folders, tr_free );
2380    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2381    tr_free( root );
2382    tr_free( tmp );
2383}
2384
2385void
2386tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2387{
2388    assert( tr_isTorrent( tor ) );
2389
2390    if( fileFunc == NULL )
2391        fileFunc = remove;
2392
2393    /* close all the files because we're about to delete them */
2394    tr_fdTorrentClose( tor->session, tor->uniqueId );
2395
2396    if( tor->info.fileCount > 1 )
2397    {
2398        deleteLocalData( tor, fileFunc );
2399    }
2400    else if( tor->info.fileCount == 1 )
2401    {
2402        char * tmp;
2403
2404        /* torrent only has one file */
2405        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2406        deleteLocalFile( path, fileFunc );
2407        tr_free( path );
2408
2409        tmp = tr_torrentBuildPartial( tor, 0 );
2410        path = tr_buildPath( tor->currentDir, tmp, NULL );
2411        deleteLocalFile( path, fileFunc );
2412        tr_free( path );
2413        tr_free( tmp );
2414    }
2415}
2416
2417/***
2418****
2419***/
2420
2421struct LocationData
2422{
2423    tr_bool move_from_old_location;
2424    int * setme_state;
2425    double * setme_progress;
2426    char * location;
2427    tr_torrent * tor;
2428};
2429
2430static tr_bool
2431sameInode( const char * path1, const char * path2 )
2432{
2433    int i1, i2;
2434    struct stat s1, s2;
2435
2436    s1.st_ino = 1;
2437    i1 = stat( path1, &s1 );
2438
2439    s2.st_ino = 2;
2440    i2 = stat( path2, &s2 );
2441
2442    if( !i1 && !i2 ) {
2443        tr_dbg( "path1 inode is %"PRIu64"; path2 inode is %"PRIu64,
2444                (uint64_t)s1.st_ino,
2445                (uint64_t)s2.st_ino );
2446        return s1.st_ino == s2.st_ino;
2447    }
2448
2449    /* either one, or the other, or both don't exist... */
2450    tr_dbg( "stat(%s) returned %d\n", path1, i1 );
2451    tr_dbg( "stat(%s) returned %d\n", path2, i2 );
2452    return FALSE;
2453}
2454
2455static void
2456setLocation( void * vdata )
2457{
2458    tr_bool err = FALSE;
2459    tr_bool verify_needed = FALSE;
2460    struct LocationData * data = vdata;
2461    tr_torrent * tor = data->tor;
2462    const tr_bool do_move = data->move_from_old_location;
2463    const char * location = data->location;
2464    double bytesHandled = 0;
2465
2466    assert( tr_isTorrent( tor ) );
2467
2468    tr_dbg( "Moving \"%s\" location from currentDir \"%s\" to \"%s\"",
2469            tr_torrentName(tor), tor->currentDir, location );
2470
2471    tr_mkdirp( location, 0777 );
2472
2473    if( !sameInode( location, tor->currentDir ) )
2474    {
2475        tr_file_index_t i;
2476
2477        /* bad idea to move files while they're being verified... */
2478        tr_verifyRemove( tor );
2479
2480        /* if the torrent is running, stop it and set a flag to
2481         * restart after we're done */
2482        if( tor->isRunning )
2483        {
2484            tr_torrentStop( tor );
2485            tor->startAfterVerify = TRUE;
2486        }
2487
2488        /* try to move the files.
2489         * FIXME: there are still all kinds of nasty cases, like what
2490         * if the target directory runs out of space halfway through... */
2491        for( i=0; !err && i<tor->info.fileCount; ++i )
2492        {
2493            const tr_file * f = &tor->info.files[i];
2494            const char * oldbase;
2495            char * sub;
2496            if( tr_torrentFindFile2( tor, i, &oldbase, &sub ) )
2497            {
2498                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2499                char * newpath = tr_buildPath( location, sub, NULL );
2500
2501                tr_dbg( "Found file #%d: %s", (int)i, oldpath );
2502
2503                if( do_move )
2504                {
2505                    tr_bool renamed = FALSE;
2506                    errno = 0;
2507                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2508                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2509                    {
2510                        err = TRUE;
2511                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2512                                        oldpath, newpath, tr_strerror( errno ) );
2513                    }
2514                    else if( !renamed )
2515                    {
2516                        verify_needed = TRUE;
2517                    }
2518                }
2519
2520                tr_free( newpath );
2521                tr_free( oldpath );
2522                tr_free( sub );
2523            }
2524
2525            if( data->setme_progress )
2526            {
2527                bytesHandled += f->length;
2528                *data->setme_progress = bytesHandled / tor->info.totalSize;
2529            }
2530        }
2531
2532        if( !err )
2533        {
2534            /* blow away the leftover subdirectories in the old location */
2535            if( do_move )
2536                tr_torrentDeleteLocalData( tor, remove );
2537
2538            /* set the new location and reverify */
2539            tr_torrentSetDownloadDir( tor, location );
2540            if( verify_needed )
2541                tr_torrentVerify( tor );
2542            else if( tor->startAfterVerify ) {
2543                tor->startAfterVerify = FALSE;
2544                tr_torrentStart( tor );
2545            }
2546        }
2547    }
2548
2549    if( !err && do_move )
2550    {
2551        tr_free( tor->incompleteDir );
2552        tor->incompleteDir = NULL;
2553        tor->currentDir = tor->downloadDir;
2554    }
2555
2556    if( data->setme_state )
2557        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2558
2559    /* cleanup */
2560    tr_free( data->location );
2561    tr_free( data );
2562}
2563
2564void
2565tr_torrentSetLocation( tr_torrent  * tor,
2566                       const char  * location,
2567                       tr_bool       move_from_old_location,
2568                       double      * setme_progress,
2569                       int         * setme_state )
2570{
2571    struct LocationData * data;
2572
2573    assert( tr_isTorrent( tor ) );
2574
2575    if( setme_state )
2576        *setme_state = TR_LOC_MOVING;
2577    if( setme_progress )
2578        *setme_progress = 0;
2579
2580    /* run this in the libtransmission thread */
2581    data = tr_new( struct LocationData, 1 );
2582    data->tor = tor;
2583    data->location = tr_strdup( location );
2584    data->move_from_old_location = move_from_old_location;
2585    data->setme_state = setme_state;
2586    data->setme_progress = setme_progress;
2587    tr_runInEventThread( tor->session, setLocation, data );
2588}
2589
2590/***
2591****
2592***/
2593
2594void
2595tr_torrentCheckSeedRatio( tr_torrent * tor )
2596{
2597    double seedRatio;
2598
2599    assert( tr_isTorrent( tor ) );
2600
2601    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2602    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2603    {
2604        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2605        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2606        double ratio;
2607
2608        /* maybe we're the initial seeder and never downloaded anything... */
2609        if( down == 0 )
2610            down = tr_cpHaveValid( &tor->completion );
2611
2612        ratio = tr_getRatio( up, down );
2613
2614        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2615        {
2616            tr_torrentStop( tor );
2617
2618            /* set to no ratio limit to allow easy restarting */
2619            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2620
2621            /* maybe notify the client */
2622            if( tor->ratio_limit_hit_func != NULL )
2623                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2624        }
2625    }
2626}
2627
2628/***
2629****
2630***/
2631
2632void
2633tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2634{
2635    char * sub;
2636    const char * base;
2637
2638    /* close the file so that we can reopen in read-only mode as needed */
2639    tr_fdFileClose( tor->session, tor, fileNum );
2640
2641    /* if the torrent's filename on disk isn't the same as the one in the metadata,
2642     * then it's been modified to denote that it was a partial file.
2643     * Now that it's complete, use the proper filename. */
2644    if( tr_torrentFindFile2( tor, fileNum, &base, &sub ) )
2645    {
2646        const tr_file * file = &tor->info.files[fileNum];
2647
2648        if( strcmp( sub, file->name ) )
2649        {
2650            char * oldpath = tr_buildPath( base, sub, NULL );
2651            char * newpath = tr_buildPath( base, file->name, NULL );
2652
2653            if( rename( oldpath, newpath ) )
2654                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2655
2656            tr_free( newpath );
2657            tr_free( oldpath );
2658        }
2659
2660        tr_free( sub );
2661    }
2662}
2663
2664/***
2665****
2666***/
2667
2668static tr_bool
2669fileExists( const char * filename )
2670{
2671    struct stat sb;
2672    const tr_bool ok = !stat( filename, &sb );
2673    return ok;
2674}
2675
2676tr_bool
2677tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
2678                     const char ** base, char ** subpath )
2679{
2680    char * part;
2681    const tr_file * file;
2682    const char * b = NULL;
2683    const char * s = NULL;
2684
2685    assert( tr_isTorrent( tor ) );
2686    assert( fileNum < tor->info.fileCount );
2687
2688    file = &tor->info.files[fileNum];
2689    part = tr_torrentBuildPartial( tor, fileNum );
2690
2691    if( b == NULL ) {
2692        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
2693        if( fileExists( filename ) ) {
2694            b = tor->downloadDir;
2695            s = file->name;
2696        }
2697        tr_free( filename );
2698    }
2699
2700    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2701        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
2702        if( fileExists( filename ) ) {
2703            b = tor->incompleteDir;
2704            s = file->name;
2705        }
2706        tr_free( filename );
2707    }
2708
2709    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2710        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
2711        if( fileExists( filename ) ) {
2712            b = tor->incompleteDir;
2713            s = part;
2714        }
2715        tr_free( filename );
2716    }
2717
2718    if( b == NULL) {
2719        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
2720        if( fileExists( filename ) ) {
2721            b = tor->downloadDir;
2722            s = part;
2723        }
2724        tr_free( filename );
2725    }
2726
2727    if( base != NULL )
2728        *base = b;
2729    if( subpath != NULL )
2730        *subpath = tr_strdup( s );
2731
2732    tr_free( part );
2733    return b != NULL;
2734}
2735
2736char*
2737tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
2738{
2739    char * subpath;
2740    char * ret = NULL;
2741    const char * base;
2742
2743    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath ) )
2744    {
2745        ret = tr_buildPath( base, subpath, NULL );
2746        tr_free( subpath );
2747    }
2748
2749    return ret;
2750}
2751
2752/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
2753static void
2754refreshCurrentDir( tr_torrent * tor )
2755{
2756    const char * dir = NULL;
2757    char * sub;
2758
2759    if( tor->incompleteDir == NULL )
2760        dir = tor->downloadDir;
2761    else if( !tr_torrentHasMetadata( tor ) ) /* no files to find */
2762        dir = tor->incompleteDir;
2763    else if( !tr_torrentFindFile2( tor, 0, &dir, &sub ) )
2764        dir = tor->incompleteDir;
2765
2766    assert( dir != NULL );
2767    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
2768    tor->currentDir = dir;
2769}
2770
2771char*
2772tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
2773{
2774    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
2775}
Note: See TracBrowser for help on using the repository browser.