source: trunk/libtransmission/torrent.c @ 9550

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

(trunk) #2096: Magnet, BEP #9 support

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