source: trunk/libtransmission/torrent.c @ 8433

Last change on this file since 8433 was 8433, checked in by charles, 13 years ago

(trunk) #7: DHT support. This is a work in progress... no gui/rpc support yet

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