source: trunk/libtransmission/torrent.c @ 8389

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

(trunk) #920: add "move data" to libT so all clients can use it

  • Property svn:keywords set to Date Rev Author Id
File size: 59.2 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 8389 2009-05-13 15:54:04Z 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( session->isPortSet );
600    assert( !tor->downloadedCur );
601    assert( !tor->uploadedCur );
602
603    tr_ctorInitTorrentPriorities( ctor, tor );
604
605    tr_ctorInitTorrentWanted( ctor, tor );
606
607    tor->error   = 0;
608
609    tr_bitfieldConstruct( &tor->checkedPieces, tor->info.pieceCount );
610    tr_torrentUncheck( tor );
611
612    tr_torrentSetAddedDate( tor, time( NULL ) ); /* this is a default value to be
613                                                    overwritten by the resume file */
614
615    loaded = tr_torrentLoadResume( tor, ~0, ctor );
616
617    doStart = tor->isRunning;
618    tor->isRunning = 0;
619
620    if( !( loaded & TR_FR_SPEEDLIMIT ) )
621    {
622        tr_torrentUseSpeedLimit( tor, TR_UP, FALSE );
623        tr_torrentUseSpeedLimit( tor, TR_DOWN, FALSE );
624        tr_torrentUseSessionLimits( tor, TRUE );
625    }
626
627    if( !( loaded & TR_FR_RATIOLIMIT ) )
628    {
629        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_GLOBAL );
630        tr_torrentSetRatioLimit( tor, tr_sessionGetRatioLimit( tor->session ) );
631    }
632
633    tor->completeness = tr_cpGetStatus( &tor->completion );
634
635    tor->tracker = tr_trackerNew( tor );
636    tor->trackerSubscription =
637        tr_trackerSubscribe( tor->tracker, onTrackerResponse,
638                             tor );
639
640    {
641        tr_torrent * it = NULL;
642        tr_torrent * last = NULL;
643        while( ( it = tr_torrentNext( session, it ) ) )
644            last = it;
645
646        if( !last )
647            session->torrentList = tor;
648        else
649            last->next = tor;
650        ++session->torrentCount;
651    }
652
653    tr_globalUnlock( session );
654
655    /* maybe save our own copy of the metainfo */
656    if( tr_ctorGetSave( ctor ) )
657    {
658        const tr_benc * val;
659        if( !tr_ctorGetMetainfo( ctor, &val ) )
660        {
661            const char * filename = tor->info.torrent;
662            tr_bencSaveFile( filename, val );
663            tr_sessionSetTorrentFile( tor->session, tor->info.hashString,
664                                      filename );
665        }
666    }
667
668    tr_metainfoMigrate( session, &tor->info );
669
670    if( doStart )
671        torrentStart( tor, FALSE );
672}
673
674int
675tr_torrentParse( const tr_ctor     * ctor,
676                 tr_info           * setmeInfo )
677{
678    int             err = 0;
679    int             doFree;
680    tr_info         tmp;
681    const tr_benc * metainfo;
682    tr_session    * session = tr_ctorGetSession( ctor );
683
684    if( setmeInfo == NULL )
685        setmeInfo = &tmp;
686    memset( setmeInfo, 0, sizeof( tr_info ) );
687
688    if( !err && tr_ctorGetMetainfo( ctor, &metainfo ) )
689        return TR_EINVALID;
690
691    err = tr_metainfoParse( session, setmeInfo, metainfo );
692    doFree = !err && ( setmeInfo == &tmp );
693
694    if( !err && !getBlockSize( setmeInfo->pieceSize ) )
695        err = TR_EINVALID;
696
697    if( !err && session && tr_torrentExists( session, setmeInfo->hash ) )
698        err = TR_EDUPLICATE;
699
700    if( doFree )
701        tr_metainfoFree( setmeInfo );
702
703    return err;
704}
705
706tr_torrent *
707tr_torrentNew( const tr_ctor  * ctor,
708               int            * setmeError )
709{
710    int          err;
711    tr_info      tmpInfo;
712    tr_torrent * tor = NULL;
713
714    assert( ctor != NULL );
715    assert( tr_isSession( tr_ctorGetSession( ctor ) ) );
716
717    err = tr_torrentParse( ctor, &tmpInfo );
718    if( !err )
719    {
720        tor = tr_new0( tr_torrent, 1 );
721        tor->info = tmpInfo;
722        torrentRealInit( tor, ctor );
723    }
724    else if( setmeError )
725    {
726        *setmeError = err;
727    }
728
729    return tor;
730}
731
732/**
733***
734**/
735
736void
737tr_torrentSetDownloadDir( tr_torrent * tor, const char * path )
738{
739    assert( tr_isTorrent( tor  ) );
740
741    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
742    {
743        tr_free( tor->downloadDir );
744        tor->downloadDir = tr_strdup( path );
745        tr_torrentSaveResume( tor );
746    }
747}
748
749const char*
750tr_torrentGetDownloadDir( const tr_torrent * tor )
751{
752    assert( tr_isTorrent( tor  ) );
753
754    return tor->downloadDir;
755}
756
757void
758tr_torrentChangeMyPort( tr_torrent * tor )
759{
760    assert( tr_isTorrent( tor  ) );
761
762    if( tor->tracker )
763        tr_trackerChangeMyPort( tor->tracker );
764}
765
766static TR_INLINE void
767tr_torrentManualUpdateImpl( void * vtor )
768{
769    tr_torrent * tor = vtor;
770
771    assert( tr_isTorrent( tor  ) );
772
773    if( tor->isRunning )
774        tr_trackerReannounce( tor->tracker );
775}
776
777void
778tr_torrentManualUpdate( tr_torrent * tor )
779{
780    assert( tr_isTorrent( tor  ) );
781
782    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
783}
784
785tr_bool
786tr_torrentCanManualUpdate( const tr_torrent * tor )
787{
788    return ( tr_isTorrent( tor  ) )
789        && ( tor->isRunning )
790        && ( tr_trackerCanManualAnnounce( tor->tracker ) );
791}
792
793const tr_info *
794tr_torrentInfo( const tr_torrent * tor )
795{
796    return tr_isTorrent( tor ) ? &tor->info : NULL;
797}
798
799const tr_stat *
800tr_torrentStatCached( tr_torrent * tor )
801{
802    const time_t now = time( NULL );
803
804    return tr_isTorrent( tor ) && ( now == tor->lastStatTime )
805         ? &tor->stats
806         : tr_torrentStat( tor );
807}
808
809void
810tr_torrentSetVerifyState( tr_torrent * tor, tr_verify_state state )
811{
812    assert( tr_isTorrent( tor ) );
813    assert( state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW );
814
815    tor->verifyState = state;
816    tor->anyDate = time( NULL );
817}
818
819tr_torrent_activity
820tr_torrentGetActivity( tr_torrent * tor )
821{
822    assert( tr_isTorrent( tor ) );
823
824    tr_torrentRecheckCompleteness( tor );
825
826    if( tor->verifyState == TR_VERIFY_NOW )
827        return TR_STATUS_CHECK;
828    if( tor->verifyState == TR_VERIFY_WAIT )
829        return TR_STATUS_CHECK_WAIT;
830    if( !tor->isRunning )
831        return TR_STATUS_STOPPED;
832    if( tor->completeness == TR_LEECH )
833        return TR_STATUS_DOWNLOAD;
834
835    return TR_STATUS_SEED;
836}
837
838const tr_stat *
839tr_torrentStat( tr_torrent * tor )
840{
841    tr_stat *               s;
842    struct tr_tracker *     tc;
843    const tr_tracker_info * ti;
844    int                     usableSeeds = 0;
845    uint64_t                now;
846    double                  downloadedForRatio, seedRatio;
847    tr_bool                 checkSeedRatio;
848
849    if( !tor )
850        return NULL;
851
852    assert( tr_isTorrent( tor ) );
853    tr_torrentLock( tor );
854
855    tor->lastStatTime = time( NULL );
856
857    s = &tor->stats;
858    s->id = tor->uniqueId;
859    s->activity = tr_torrentGetActivity( tor );
860    s->error  = tor->error;
861    memcpy( s->errorString, tor->errorString,
862           sizeof( s->errorString ) );
863
864    tc = tor->tracker;
865    ti = tr_trackerGetAddress( tor->tracker, tor );
866    s->announceURL = ti ? ti->announce : NULL;
867    s->scrapeURL   = ti ? ti->scrape   : NULL;
868    tr_trackerStat( tc, s );
869
870    tr_trackerGetCounts( tc, &s->timesCompleted,
871                             &s->leechers,
872                             &s->seeders,
873                             &s->downloaders );
874
875    tr_peerMgrTorrentStats( tor,
876                            &s->peersKnown,
877                            &s->peersConnected,
878                            &usableSeeds,
879                            &s->webseedsSendingToUs,
880                            &s->peersSendingToUs,
881                            &s->peersGettingFromUs,
882                            s->peersFrom );
883
884    now = tr_date( );
885    s->swarmSpeed         = tr_rcRate( &tor->swarmSpeed, now );
886    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
887    s->rawDownloadSpeed   = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
888    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
889    s->pieceDownloadSpeed = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
890
891    usableSeeds += tor->info.webseedCount;
892
893    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
894
895    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
896    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
897    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
898
899    s->recheckProgress = s->activity == TR_STATUS_CHECK
900                       ? 1.0 -
901                         ( tr_torrentCountUncheckedPieces( tor ) /
902                           (double) tor->info.pieceCount )
903                       : 0.0;
904
905    s->activityDate = tor->activityDate;
906    s->addedDate    = tor->addedDate;
907    s->doneDate     = tor->doneDate;
908    s->startDate    = tor->startDate;
909
910    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
911    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
912    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
913    s->haveValid       = tr_cpHaveValid( &tor->completion );
914    s->haveUnchecked   = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
915
916    if( usableSeeds > 0 )
917    {
918        s->desiredAvailable = s->leftUntilDone;
919    }
920    else if( !s->leftUntilDone || !s->peersConnected )
921    {
922        s->desiredAvailable = 0;
923    }
924    else
925    {
926        tr_piece_index_t i;
927        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable( tor );
928        s->desiredAvailable = 0;
929        for( i = 0; i < tor->info.pieceCount; ++i )
930            if( !tor->info.pieces[i].dnd && tr_bitfieldHasFast( peerPieces, i ) )
931                s->desiredAvailable += tr_cpMissingBlocksInPiece( &tor->completion, i );
932        s->desiredAvailable *= tor->blockSize;
933        tr_bitfieldFree( peerPieces );
934    }
935
936    downloadedForRatio = s->downloadedEver ? s->downloadedEver : s->haveValid;
937    s->ratio = tr_getRatio( s->uploadedEver, downloadedForRatio );
938
939    checkSeedRatio = tr_torrentGetSeedRatio( tor, &seedRatio );
940
941    switch( s->activity )
942    {
943        case TR_STATUS_DOWNLOAD:
944            if( s->leftUntilDone > s->desiredAvailable )
945                s->eta = TR_ETA_NOT_AVAIL;
946            else if( s->pieceDownloadSpeed < 0.1 )
947                s->eta = TR_ETA_UNKNOWN;
948            else
949                s->eta = s->leftUntilDone / s->pieceDownloadSpeed / 1024.0;
950            break;
951
952        case TR_STATUS_SEED:
953            if( checkSeedRatio )
954            {
955                if( s->pieceUploadSpeed < 0.1 )
956                    s->eta = TR_ETA_UNKNOWN;
957                else
958                    s->eta = (downloadedForRatio * (seedRatio - s->ratio)) / s->pieceUploadSpeed / 1024.0;
959            }
960            else
961                s->eta = TR_ETA_NOT_AVAIL;
962            break;
963
964        default:
965            s->eta = TR_ETA_NOT_AVAIL;
966            break;
967    }
968
969    if( !checkSeedRatio || s->ratio >= seedRatio || s->ratio == TR_RATIO_INF )
970        s->percentRatio = 1.0;
971    else if( s->ratio == TR_RATIO_NA )
972        s->percentRatio = 0.0;
973    else 
974        s->percentRatio = s->ratio / seedRatio;
975
976    tr_torrentUnlock( tor );
977
978    return s;
979}
980
981/***
982****
983***/
984
985static uint64_t
986fileBytesCompleted( const tr_torrent * tor,
987                    tr_file_index_t    fileIndex )
988{
989    const tr_file *        file     =  &tor->info.files[fileIndex];
990    const tr_block_index_t firstBlock       =  file->offset /
991                                              tor->blockSize;
992    const uint64_t         firstBlockOffset =  file->offset %
993                                              tor->blockSize;
994    const uint64_t         lastOffset       =
995        file->length ? ( file->length - 1 ) : 0;
996    const tr_block_index_t lastBlock        =
997        ( file->offset + lastOffset ) / tor->blockSize;
998    const uint64_t         lastBlockOffset  =
999        ( file->offset + lastOffset ) % tor->blockSize;
1000    uint64_t               haveBytes = 0;
1001
1002    assert( tr_isTorrent( tor ) );
1003    assert( fileIndex < tor->info.fileCount );
1004    assert( file->offset + file->length <= tor->info.totalSize );
1005    assert( ( firstBlock < tor->blockCount )
1006          || ( !file->length && file->offset == tor->info.totalSize ) );
1007    assert( ( lastBlock < tor->blockCount )
1008          || ( !file->length && file->offset == tor->info.totalSize ) );
1009    assert( firstBlock <= lastBlock );
1010    assert( tr_torBlockPiece( tor, firstBlock ) == file->firstPiece );
1011    assert( tr_torBlockPiece( tor, lastBlock ) == file->lastPiece );
1012
1013    if( firstBlock == lastBlock )
1014    {
1015        if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1016            haveBytes += lastBlockOffset + 1 - firstBlockOffset;
1017    }
1018    else
1019    {
1020        tr_block_index_t i;
1021
1022        if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1023            haveBytes += tor->blockSize - firstBlockOffset;
1024
1025        for( i = firstBlock + 1; i < lastBlock; ++i )
1026            if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1027                haveBytes += tor->blockSize;
1028
1029        if( tr_cpBlockIsCompleteFast( &tor->completion, lastBlock ) )
1030            haveBytes += lastBlockOffset + 1;
1031    }
1032
1033    return haveBytes;
1034}
1035
1036tr_file_stat *
1037tr_torrentFiles( const tr_torrent * tor,
1038                 tr_file_index_t *  fileCount )
1039{
1040    tr_file_index_t       i;
1041    const tr_file_index_t n = tor->info.fileCount;
1042    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1043    tr_file_stat *        walk = files;
1044    const tr_bool         isSeed = tor->completeness == TR_SEED;
1045
1046    assert( tr_isTorrent( tor ) );
1047
1048    for( i = 0; i < n; ++i, ++walk )
1049    {
1050        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1051        walk->bytesCompleted = b;
1052        walk->progress = tr_getRatio( b, tor->info.files[i].length );
1053    }
1054
1055    if( fileCount )
1056        *fileCount = n;
1057
1058    return files;
1059}
1060
1061void
1062tr_torrentFilesFree( tr_file_stat *            files,
1063                     tr_file_index_t fileCount UNUSED )
1064{
1065    tr_free( files );
1066}
1067
1068/***
1069****
1070***/
1071
1072float*
1073tr_torrentWebSpeeds( const tr_torrent * tor )
1074{
1075    return tr_isTorrent( tor )
1076         ? tr_peerMgrWebSpeeds( tor )
1077         : NULL;
1078}
1079
1080tr_peer_stat *
1081tr_torrentPeers( const tr_torrent * tor,
1082                 int *              peerCount )
1083{
1084    tr_peer_stat * ret = NULL;
1085
1086    if( tr_isTorrent( tor ) )
1087        ret = tr_peerMgrPeerStats( tor, peerCount );
1088
1089    return ret;
1090}
1091
1092void
1093tr_torrentPeersFree( tr_peer_stat * peers,
1094                     int peerCount  UNUSED )
1095{
1096    tr_free( peers );
1097}
1098
1099void
1100tr_torrentAvailability( const tr_torrent * tor,
1101                        int8_t *           tab,
1102                        int                size )
1103{
1104    tr_peerMgrTorrentAvailability( tor, tab, size );
1105}
1106
1107void
1108tr_torrentAmountFinished( const tr_torrent * tor,
1109                          float *            tab,
1110                          int                size )
1111{
1112    assert( tr_isTorrent( tor ) );
1113
1114    tr_torrentLock( tor );
1115    tr_cpGetAmountDone( &tor->completion, tab, size );
1116    tr_torrentUnlock( tor );
1117}
1118
1119void
1120tr_torrentResetTransferStats( tr_torrent * tor )
1121{
1122    assert( tr_isTorrent( tor ) );
1123
1124    tr_torrentLock( tor );
1125
1126    tor->downloadedPrev += tor->downloadedCur;
1127    tor->downloadedCur   = 0;
1128    tor->uploadedPrev   += tor->uploadedCur;
1129    tor->uploadedCur     = 0;
1130    tor->corruptPrev    += tor->corruptCur;
1131    tor->corruptCur      = 0;
1132
1133    tr_torrentUnlock( tor );
1134}
1135
1136void
1137tr_torrentSetHasPiece( tr_torrent *     tor,
1138                       tr_piece_index_t pieceIndex,
1139                       tr_bool          has )
1140{
1141    assert( tr_isTorrent( tor ) );
1142    assert( pieceIndex < tor->info.pieceCount );
1143
1144    if( has )
1145        tr_cpPieceAdd( &tor->completion, pieceIndex );
1146    else
1147        tr_cpPieceRem( &tor->completion, pieceIndex );
1148}
1149
1150/***
1151****
1152***/
1153
1154static void
1155freeTorrent( tr_torrent * tor )
1156{
1157    tr_torrent * t;
1158    tr_session *  session = tor->session;
1159    tr_info *    inf = &tor->info;
1160
1161    assert( tr_isTorrent( tor ) );
1162    assert( !tor->isRunning );
1163
1164    tr_globalLock( session );
1165
1166    tr_peerMgrRemoveTorrent( tor );
1167
1168    tr_cpDestruct( &tor->completion );
1169
1170    tr_rcDestruct( &tor->swarmSpeed );
1171
1172    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
1173    tr_trackerFree( tor->tracker );
1174    tor->tracker = NULL;
1175
1176    tr_bitfieldDestruct( &tor->checkedPieces );
1177
1178    tr_free( tor->downloadDir );
1179    tr_free( tor->peer_id );
1180
1181    if( tor == session->torrentList )
1182        session->torrentList = tor->next;
1183    else for( t = session->torrentList; t != NULL; t = t->next ) {
1184        if( t->next == tor ) {
1185            t->next = tor->next;
1186            break;
1187        }
1188    }
1189
1190    assert( session->torrentCount >= 1 );
1191    session->torrentCount--;
1192
1193    tr_bandwidthFree( tor->bandwidth );
1194
1195    tr_metainfoFree( inf );
1196    tr_free( tor );
1197
1198    tr_globalUnlock( session );
1199}
1200
1201/**
1202***  Start/Stop Callback
1203**/
1204
1205static void
1206checkAndStartImpl( void * vtor )
1207{
1208    tr_torrent * tor = vtor;
1209
1210    assert( tr_isTorrent( tor ) );
1211
1212    tr_globalLock( tor->session );
1213
1214    tor->isRunning = TRUE;
1215    tor->needsSeedRatioCheck = TRUE;
1216    *tor->errorString = '\0';
1217    tr_torrentResetTransferStats( tor );
1218    tor->completeness = tr_cpGetStatus( &tor->completion );
1219    tr_torrentSaveResume( tor );
1220    tor->startDate = tor->anyDate = time( NULL );
1221    tr_trackerStart( tor->tracker );
1222    tr_peerMgrStartTorrent( tor );
1223
1224    tr_globalUnlock( tor->session );
1225}
1226
1227static void
1228checkAndStartCB( tr_torrent * tor )
1229{
1230    assert( tr_isTorrent( tor ) );
1231    assert( tr_isSession( tor->session ) );
1232
1233    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1234}
1235
1236static void
1237torrentStart( tr_torrent * tor, int reloadProgress )
1238{
1239    assert( tr_isTorrent( tor ) );
1240
1241    tr_globalLock( tor->session );
1242
1243    if( !tor->isRunning )
1244    {
1245        const tr_bool isVerifying = tr_verifyInProgress( tor );
1246
1247        if( !isVerifying && reloadProgress )
1248            tr_torrentLoadResume( tor, TR_FR_PROGRESS, NULL );
1249
1250        tor->isRunning = 1;
1251
1252        if( !isVerifying )
1253            tr_verifyAdd( tor, checkAndStartCB );
1254    }
1255
1256    tr_globalUnlock( tor->session );
1257}
1258
1259void
1260tr_torrentStart( tr_torrent * tor )
1261{
1262    if( tr_isTorrent( tor ) )
1263        torrentStart( tor, TRUE );
1264}
1265
1266static void
1267torrentRecheckDoneImpl( void * vtor )
1268{
1269    tr_torrent * tor = vtor;
1270
1271    assert( tr_isTorrent( tor ) );
1272    tr_torrentRecheckCompleteness( tor );
1273
1274    if( tor->startAfterVerify )
1275    {
1276        tor->startAfterVerify = FALSE;
1277        tr_torrentStart( tor );
1278    }
1279}
1280
1281static void
1282torrentRecheckDoneCB( tr_torrent * tor )
1283{
1284    assert( tr_isTorrent( tor ) );
1285
1286    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1287}
1288
1289void
1290tr_torrentVerify( tr_torrent * tor )
1291{
1292    assert( tr_isTorrent( tor ) );
1293    tr_globalLock( tor->session );
1294
1295    /* if the torrent's already being verified, stop it */
1296    tr_verifyRemove( tor );
1297
1298    /* if the torrent's running, stop it & set the restart-after-verify flag */
1299    if( tor->isRunning ) {
1300        tr_torrentStop( tor );
1301        tor->startAfterVerify = TRUE;
1302    }
1303
1304    /* add the torrent to the recheck queue */
1305    tr_torrentUncheck( tor );
1306    tr_verifyAdd( tor, torrentRecheckDoneCB );
1307
1308    tr_globalUnlock( tor->session );
1309}
1310
1311static void
1312tr_torrentCloseLocalFiles( const tr_torrent * tor )
1313{
1314    tr_file_index_t i;
1315    struct evbuffer * buf = evbuffer_new( );
1316
1317    assert( tr_isTorrent( tor ) );
1318
1319    for( i=0; i<tor->info.fileCount; ++i )
1320    {
1321        const tr_file * file = &tor->info.files[i];
1322        evbuffer_drain( buf, EVBUFFER_LENGTH( buf ) );
1323        evbuffer_add_printf( buf, "%s%s%s", tor->downloadDir, TR_PATH_DELIMITER_STR, file->name );
1324        tr_fdFileClose( (const char*) EVBUFFER_DATA( buf ) );
1325    }
1326
1327    evbuffer_free( buf );
1328}
1329
1330static void
1331stopTorrent( void * vtor )
1332{
1333    tr_torrent * tor = vtor;
1334
1335    assert( tr_isTorrent( tor ) );
1336
1337    tr_verifyRemove( tor );
1338    tr_peerMgrStopTorrent( tor );
1339    tr_trackerStop( tor->tracker );
1340
1341    tr_torrentCloseLocalFiles( tor );
1342}
1343
1344void
1345tr_torrentStop( tr_torrent * tor )
1346{
1347    assert( tr_isTorrent( tor ) );
1348
1349    if( tr_isTorrent( tor ) )
1350    {
1351        tr_globalLock( tor->session );
1352
1353        tor->isRunning = 0;
1354        if( !tor->isDeleting )
1355            tr_torrentSaveResume( tor );
1356        tr_runInEventThread( tor->session, stopTorrent, tor );
1357
1358        tr_globalUnlock( tor->session );
1359    }
1360}
1361
1362static void
1363closeTorrent( void * vtor )
1364{
1365    tr_benc * d;
1366    tr_torrent * tor = vtor;
1367
1368    assert( tr_isTorrent( tor ) );
1369
1370    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1371    tr_bencDictAddInt( d, "id", tor->uniqueId );
1372    tr_bencDictAddInt( d, "date", time( NULL ) );
1373
1374    tr_torrentSaveResume( tor );
1375    tor->isRunning = 0;
1376    stopTorrent( tor );
1377    if( tor->isDeleting )
1378    {
1379        tr_metainfoRemoveSaved( tor->session, &tor->info );
1380        tr_torrentRemoveResume( tor );
1381    }
1382    freeTorrent( tor );
1383}
1384
1385void
1386tr_torrentFree( tr_torrent * tor )
1387{
1388    if( tr_isTorrent( tor ) )
1389    {
1390        tr_session * session = tor->session;
1391        assert( tr_isSession( session ) );
1392        tr_globalLock( session );
1393
1394        tr_torrentClearCompletenessCallback( tor );
1395        tr_runInEventThread( session, closeTorrent, tor );
1396
1397        tr_globalUnlock( session );
1398    }
1399}
1400
1401void
1402tr_torrentRemove( tr_torrent * tor )
1403{
1404    assert( tr_isTorrent( tor ) );
1405
1406    tor->isDeleting = 1;
1407    tr_torrentFree( tor );
1408}
1409
1410/**
1411***  Completeness
1412**/
1413
1414static const char *
1415getCompletionString( int type )
1416{
1417    switch( type )
1418    {
1419        /* Translators: this is a minor point that's safe to skip over, but FYI:
1420           "Complete" and "Done" are specific, different terms in Transmission:
1421           "Complete" means we've downloaded every file in the torrent.
1422           "Done" means we're done downloading the files we wanted, but NOT all
1423           that exist */
1424        case TR_PARTIAL_SEED:
1425            return _( "Done" );
1426
1427        case TR_SEED:
1428            return _( "Complete" );
1429
1430        default:
1431            return _( "Incomplete" );
1432    }
1433}
1434
1435static void
1436fireCompletenessChange( tr_torrent       * tor,
1437                        tr_completeness    status )
1438{
1439    assert( tr_isTorrent( tor ) );
1440    assert( ( status == TR_LEECH )
1441         || ( status == TR_SEED )
1442         || ( status == TR_PARTIAL_SEED ) );
1443
1444    if( tor->completeness_func )
1445        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1446}
1447
1448void
1449tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1450                                   tr_torrent_completeness_func    func,
1451                                   void                          * user_data )
1452{
1453    assert( tr_isTorrent( tor ) );
1454
1455    tor->completeness_func = func;
1456    tor->completeness_func_user_data = user_data;
1457}
1458
1459void
1460tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1461                                    tr_torrent_ratio_limit_hit_func  func,
1462                                    void                           * user_data )
1463{
1464    assert( tr_isTorrent( tor ) );
1465
1466    tor->ratio_limit_hit_func = func;
1467    tor->ratio_limit_hit_func_user_data = user_data;
1468}
1469
1470void
1471tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1472{
1473    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1474}
1475
1476void
1477tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1478{
1479    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1480}
1481
1482void
1483tr_torrentRecheckCompleteness( tr_torrent * tor )
1484{
1485    tr_completeness completeness;
1486
1487    assert( tr_isTorrent( tor ) );
1488
1489    tr_torrentLock( tor );
1490
1491    completeness = tr_cpGetStatus( &tor->completion );
1492
1493    if( completeness != tor->completeness )
1494    {
1495        const int recentChange = tor->downloadedCur != 0;
1496
1497        if( recentChange )
1498        {
1499            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1500                      getCompletionString( tor->completeness ),
1501                      getCompletionString( completeness ) );
1502        }
1503
1504        tor->completeness = completeness;
1505        tor->needsSeedRatioCheck = TRUE;
1506        tr_torrentCloseLocalFiles( tor );
1507        fireCompletenessChange( tor, completeness );
1508
1509        if( recentChange && ( completeness == TR_SEED ) )
1510        {
1511            tr_trackerCompleted( tor->tracker );
1512
1513            tor->doneDate = tor->anyDate = time( NULL );
1514        }
1515
1516        tr_torrentSaveResume( tor );
1517    }
1518
1519    tr_torrentUnlock( tor );
1520}
1521
1522/**
1523***  File priorities
1524**/
1525
1526void
1527tr_torrentInitFilePriority( tr_torrent *    tor,
1528                            tr_file_index_t fileIndex,
1529                            tr_priority_t   priority )
1530{
1531    tr_piece_index_t i;
1532    tr_file *        file;
1533
1534    assert( tr_isTorrent( tor ) );
1535    assert( fileIndex < tor->info.fileCount );
1536    assert( tr_isPriority( priority ) );
1537
1538    file = &tor->info.files[fileIndex];
1539    file->priority = priority;
1540    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1541        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1542}
1543
1544void
1545tr_torrentSetFilePriorities( tr_torrent *      tor,
1546                             tr_file_index_t * files,
1547                             tr_file_index_t   fileCount,
1548                             tr_priority_t     priority )
1549{
1550    tr_file_index_t i;
1551
1552    assert( tr_isTorrent( tor ) );
1553
1554    tr_torrentLock( tor );
1555
1556    for( i = 0; i < fileCount; ++i )
1557        tr_torrentInitFilePriority( tor, files[i], priority );
1558
1559    tr_torrentSaveResume( tor );
1560    tr_torrentUnlock( tor );
1561}
1562
1563tr_priority_t
1564tr_torrentGetFilePriority( const tr_torrent * tor,
1565                           tr_file_index_t    file )
1566{
1567    tr_priority_t ret;
1568
1569    assert( tr_isTorrent( tor ) );
1570
1571    tr_torrentLock( tor );
1572    assert( tor );
1573    assert( file < tor->info.fileCount );
1574    ret = tor->info.files[file].priority;
1575    tr_torrentUnlock( tor );
1576
1577    return ret;
1578}
1579
1580tr_priority_t*
1581tr_torrentGetFilePriorities( const tr_torrent * tor )
1582{
1583    tr_file_index_t i;
1584    tr_priority_t * p;
1585
1586    assert( tr_isTorrent( tor ) );
1587
1588    tr_torrentLock( tor );
1589    p = tr_new0( tr_priority_t, tor->info.fileCount );
1590    for( i = 0; i < tor->info.fileCount; ++i )
1591        p[i] = tor->info.files[i].priority;
1592    tr_torrentUnlock( tor );
1593
1594    return p;
1595}
1596
1597/**
1598***  File DND
1599**/
1600
1601int
1602tr_torrentGetFileDL( const tr_torrent * tor,
1603                     tr_file_index_t    file )
1604{
1605    int doDownload;
1606
1607    assert( tr_isTorrent( tor ) );
1608
1609    tr_torrentLock( tor );
1610
1611    assert( file < tor->info.fileCount );
1612    doDownload = !tor->info.files[file].dnd;
1613
1614    tr_torrentUnlock( tor );
1615    return doDownload != 0;
1616}
1617
1618static void
1619setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1620{
1621    tr_file *        file;
1622    const int        dnd = !doDownload;
1623    tr_piece_index_t firstPiece, firstPieceDND;
1624    tr_piece_index_t lastPiece, lastPieceDND;
1625    tr_file_index_t  i;
1626
1627    assert( tr_isTorrent( tor ) );
1628
1629    file = &tor->info.files[fileIndex];
1630    file->dnd = dnd;
1631    firstPiece = file->firstPiece;
1632    lastPiece = file->lastPiece;
1633
1634    /* can't set the first piece to DND unless
1635       every file using that piece is DND */
1636    firstPieceDND = dnd;
1637    if( fileIndex > 0 )
1638    {
1639        for( i = fileIndex - 1; firstPieceDND; --i )
1640        {
1641            if( tor->info.files[i].lastPiece != firstPiece )
1642                break;
1643            firstPieceDND = tor->info.files[i].dnd;
1644            if( !i )
1645                break;
1646        }
1647    }
1648
1649    /* can't set the last piece to DND unless
1650       every file using that piece is DND */
1651    lastPieceDND = dnd;
1652    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1653    {
1654        if( tor->info.files[i].firstPiece != lastPiece )
1655            break;
1656        lastPieceDND = tor->info.files[i].dnd;
1657    }
1658
1659    if( firstPiece == lastPiece )
1660    {
1661        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1662    }
1663    else
1664    {
1665        tr_piece_index_t pp;
1666        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1667        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1668        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1669            tor->info.pieces[pp].dnd = dnd;
1670    }
1671}
1672
1673void
1674tr_torrentInitFileDLs( tr_torrent      * tor,
1675                       tr_file_index_t * files,
1676                       tr_file_index_t   fileCount,
1677                       tr_bool           doDownload )
1678{
1679    tr_file_index_t i;
1680
1681    assert( tr_isTorrent( tor ) );
1682
1683    tr_torrentLock( tor );
1684
1685    for( i=0; i<fileCount; ++i )
1686        setFileDND( tor, files[i], doDownload );
1687    tr_cpInvalidateDND( &tor->completion );
1688    tor->needsSeedRatioCheck = TRUE;
1689
1690    tr_torrentUnlock( tor );
1691}
1692
1693void
1694tr_torrentSetFileDLs( tr_torrent *      tor,
1695                      tr_file_index_t * files,
1696                      tr_file_index_t   fileCount,
1697                      tr_bool           doDownload )
1698{
1699    assert( tr_isTorrent( tor ) );
1700
1701    tr_torrentLock( tor );
1702    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1703    tr_torrentSaveResume( tor );
1704    tr_torrentUnlock( tor );
1705}
1706
1707/***
1708****
1709***/
1710
1711tr_priority_t
1712tr_torrentGetPriority( const tr_torrent * tor )
1713{
1714    assert( tr_isTorrent( tor ) );
1715
1716    return tor->bandwidth->priority;
1717}
1718
1719void
1720tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1721{
1722    assert( tr_isTorrent( tor ) );
1723    assert( tr_isPriority( priority ) );
1724
1725    tor->bandwidth->priority = priority;
1726}
1727
1728/***
1729****
1730***/
1731
1732void
1733tr_torrentSetPeerLimit( tr_torrent * tor,
1734                        uint16_t     maxConnectedPeers )
1735{
1736    assert( tr_isTorrent( tor ) );
1737
1738    tor->maxConnectedPeers = maxConnectedPeers;
1739}
1740
1741uint16_t
1742tr_torrentGetPeerLimit( const tr_torrent * tor )
1743{
1744    assert( tr_isTorrent( tor ) );
1745
1746    return tor->maxConnectedPeers;
1747}
1748
1749/***
1750****
1751***/
1752
1753tr_block_index_t
1754_tr_block( const tr_torrent * tor,
1755           tr_piece_index_t   index,
1756           uint32_t           offset )
1757{
1758    tr_block_index_t ret;
1759
1760    assert( tr_isTorrent( tor ) );
1761
1762    ret = index;
1763    ret *= ( tor->info.pieceSize / tor->blockSize );
1764    ret += offset / tor->blockSize;
1765    return ret;
1766}
1767
1768tr_bool
1769tr_torrentReqIsValid( const tr_torrent * tor,
1770                      tr_piece_index_t   index,
1771                      uint32_t           offset,
1772                      uint32_t           length )
1773{
1774    int err = 0;
1775
1776    assert( tr_isTorrent( tor ) );
1777
1778    if( index >= tor->info.pieceCount )
1779        err = 1;
1780    else if( length < 1 )
1781        err = 2;
1782    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1783        err = 3;
1784    else if( length > MAX_BLOCK_SIZE )
1785        err = 4;
1786    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1787        err = 5;
1788
1789    if( err ) fprintf( stderr, "index %lu offset %lu length %lu err %d\n",
1790                       (unsigned long)index, (unsigned long)offset,
1791                       (unsigned long)length,
1792                       err );
1793
1794    return !err;
1795}
1796
1797uint64_t
1798tr_pieceOffset( const tr_torrent * tor,
1799                tr_piece_index_t   index,
1800                uint32_t           offset,
1801                uint32_t           length )
1802{
1803    uint64_t ret;
1804
1805    assert( tr_isTorrent( tor ) );
1806
1807    ret = tor->info.pieceSize;
1808    ret *= index;
1809    ret += offset;
1810    ret += length;
1811    return ret;
1812}
1813
1814/***
1815****
1816***/
1817
1818void
1819tr_torrentSetPieceChecked( tr_torrent        * tor,
1820                           tr_piece_index_t    piece,
1821                           tr_bool             isChecked )
1822{
1823    assert( tr_isTorrent( tor ) );
1824
1825    if( isChecked )
1826        tr_bitfieldAdd( &tor->checkedPieces, piece );
1827    else
1828        tr_bitfieldRem( &tor->checkedPieces, piece );
1829}
1830
1831void
1832tr_torrentSetFileChecked( tr_torrent *    tor,
1833                          tr_file_index_t fileIndex,
1834                          tr_bool         isChecked )
1835{
1836    const tr_file *        file = &tor->info.files[fileIndex];
1837    const tr_piece_index_t begin = file->firstPiece;
1838    const tr_piece_index_t end = file->lastPiece + 1;
1839
1840    assert( tr_isTorrent( tor ) );
1841
1842    if( isChecked )
1843        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
1844    else
1845        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
1846}
1847
1848tr_bool
1849tr_torrentIsFileChecked( const tr_torrent * tor,
1850                         tr_file_index_t    fileIndex )
1851{
1852    const tr_file *        file = &tor->info.files[fileIndex];
1853    const tr_piece_index_t begin = file->firstPiece;
1854    const tr_piece_index_t end = file->lastPiece + 1;
1855    tr_piece_index_t       i;
1856    tr_bool                isChecked = TRUE;
1857
1858    assert( tr_isTorrent( tor ) );
1859
1860    for( i = begin; isChecked && i < end; ++i )
1861        if( !tr_torrentIsPieceChecked( tor, i ) )
1862            isChecked = FALSE;
1863
1864    return isChecked;
1865}
1866
1867void
1868tr_torrentUncheck( tr_torrent * tor )
1869{
1870    assert( tr_isTorrent( tor ) );
1871
1872    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
1873}
1874
1875int
1876tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1877{
1878    assert( tr_isTorrent( tor ) );
1879
1880    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
1881}
1882
1883time_t*
1884tr_torrentGetMTimes( const tr_torrent * tor,
1885                     size_t *           setme_n )
1886{
1887    size_t       i;
1888    const size_t n = tor->info.fileCount;
1889    time_t *     m = tr_new0( time_t, n );
1890
1891    assert( tr_isTorrent( tor ) );
1892
1893    for( i = 0; i < n; ++i )
1894    {
1895        struct stat sb;
1896        char * path = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
1897        if( !stat( path, &sb ) )
1898        {
1899#ifdef SYS_DARWIN
1900            m[i] = sb.st_mtimespec.tv_sec;
1901#else
1902            m[i] = sb.st_mtime;
1903#endif
1904        }
1905        tr_free( path );
1906    }
1907
1908    *setme_n = n;
1909    return m;
1910}
1911
1912/***
1913****
1914***/
1915
1916void
1917tr_torrentSetAnnounceList( tr_torrent *            tor,
1918                           const tr_tracker_info * trackers,
1919                           int                     trackerCount )
1920{
1921    tr_benc metainfo;
1922
1923    assert( tr_isTorrent( tor ) );
1924
1925    /* save to the .torrent file */
1926    if( !tr_bencLoadFile( tor->info.torrent, &metainfo ) )
1927    {
1928        int       i;
1929        int       prevTier = -1;
1930        tr_benc * tier = NULL;
1931        tr_benc * announceList;
1932        tr_info   tmpInfo;
1933
1934        /* remove the old fields */
1935        tr_bencDictRemove( &metainfo, "announce" );
1936        tr_bencDictRemove( &metainfo, "announce-list" );
1937
1938        /* add the new fields */
1939        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
1940        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
1941        for( i = 0; i < trackerCount; ++i ) {
1942            if( prevTier != trackers[i].tier ) {
1943                prevTier = trackers[i].tier;
1944                tier = tr_bencListAddList( announceList, 0 );
1945            }
1946            tr_bencListAddStr( tier, trackers[i].announce );
1947        }
1948
1949        /* try to parse it back again, to make sure it's good */
1950        memset( &tmpInfo, 0, sizeof( tr_info ) );
1951        if( !tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
1952        {
1953            /* it's good, so keep these new trackers and free the old ones */
1954
1955            tr_info swap;
1956            swap.trackers = tor->info.trackers;
1957            swap.trackerCount = tor->info.trackerCount;
1958            tor->info.trackers = tmpInfo.trackers;
1959            tor->info.trackerCount = tmpInfo.trackerCount;
1960            tmpInfo.trackers = swap.trackers;
1961            tmpInfo.trackerCount = swap.trackerCount;
1962
1963            tr_metainfoFree( &tmpInfo );
1964            tr_bencSaveFile( tor->info.torrent, &metainfo );
1965        }
1966
1967        /* cleanup */
1968        tr_bencFree( &metainfo );
1969    }
1970}
1971
1972/**
1973***
1974**/
1975
1976void
1977tr_torrentSetAddedDate( tr_torrent * tor,
1978                        time_t       t )
1979{
1980    assert( tr_isTorrent( tor ) );
1981
1982    tor->addedDate = t;
1983    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
1984}
1985
1986void
1987tr_torrentSetActivityDate( tr_torrent * tor,
1988                           time_t       t )
1989{
1990    assert( tr_isTorrent( tor ) );
1991
1992    tor->activityDate = t;
1993    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
1994}
1995
1996void
1997tr_torrentSetDoneDate( tr_torrent * tor,
1998                       time_t       t )
1999{
2000    assert( tr_isTorrent( tor ) );
2001
2002    tor->doneDate = t;
2003    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2004}
2005
2006/**
2007***
2008**/
2009
2010uint64_t
2011tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2012{
2013    const tr_file * it;
2014    const tr_file * end;
2015    struct stat sb;
2016    uint64_t bytesLeft = 0;
2017
2018    assert( tr_isTorrent( tor ) );
2019
2020    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
2021    {
2022        if( !it->dnd )
2023        {
2024            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
2025
2026            bytesLeft += it->length;
2027
2028            if( !stat( path, &sb )
2029                    && S_ISREG( sb.st_mode )
2030                    && ( (uint64_t)sb.st_size <= it->length ) )
2031                bytesLeft -= sb.st_size;
2032
2033            tr_free( path );
2034        }
2035    }
2036
2037    return bytesLeft;
2038}
2039
2040/****
2041*****  Removing the torrent's local data
2042****/
2043
2044static int
2045vstrcmp( const void * a, const void * b )
2046{
2047    return strcmp( a, b );
2048}
2049
2050static int
2051compareLongestFirst( const void * a, const void * b )
2052{
2053    const size_t alen = strlen( a );
2054    const size_t blen = strlen( b );
2055
2056    if( alen != blen )
2057        return alen > blen ? -1 : 1;
2058
2059    return vstrcmp( a, b );
2060}
2061
2062static void
2063addDirtyFile( const char  * root,
2064              const char  * filename,
2065              tr_ptrArray * dirtyFolders )
2066{
2067    char * dir = tr_dirname( filename );
2068
2069    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2070    while (     ( dir != NULL )
2071             && ( strlen( root ) <= strlen( dir ) )
2072             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2073    {
2074        char * tmp;
2075        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2076
2077        tmp = tr_dirname( dir );
2078        tr_free( dir );
2079        dir = tmp;
2080    }
2081
2082    tr_free( dir );
2083}
2084
2085static void
2086walkLocalData( const tr_torrent * tor,
2087               const char       * root,
2088               const char       * dir,
2089               const char       * base,
2090               tr_ptrArray      * torrentFiles,
2091               tr_ptrArray      * folders,
2092               tr_ptrArray      * dirtyFolders )
2093{
2094    int i;
2095    struct stat sb;
2096    char * buf;
2097
2098    assert( tr_isTorrent( tor ) );
2099
2100    buf = tr_buildPath( dir, base, NULL );
2101    i = stat( buf, &sb );
2102    if( !i )
2103    {
2104        DIR * odir = NULL;
2105
2106        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2107        {
2108            struct dirent *d;
2109            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2110            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2111                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2112                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2113            closedir( odir );
2114        }
2115        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2116        {
2117            const char * sub = buf + strlen( tor->downloadDir ) + strlen( TR_PATH_DELIMITER_STR );
2118            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2119            if( !isTorrentFile )
2120                addDirtyFile( root, buf, dirtyFolders );
2121        }
2122    }
2123
2124    tr_free( buf );
2125}
2126
2127static void
2128deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2129{
2130    int i, n;
2131    char ** s;
2132    tr_file_index_t f;
2133    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2134    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2135    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2136
2137    const char * firstFile = tor->info.files[0].name;
2138    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2139    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2140    char * root = tr_buildPath( tor->downloadDir, tmp, NULL );
2141
2142    assert( tr_isTorrent( tor ) );
2143
2144    for( f=0; f<tor->info.fileCount; ++f )
2145        tr_ptrArrayInsertSorted( &torrentFiles, tor->info.files[f].name, vstrcmp );
2146
2147    /* build the set of folders and dirtyFolders */
2148    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2149
2150    /* try to remove entire folders first, so that the recycle bin will be tidy */
2151    s = (char**) tr_ptrArrayPeek( &folders, &n );
2152    for( i=0; i<n; ++i )
2153        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2154            fileFunc( s[i] );
2155
2156    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2157    for( f=0; f<tor->info.fileCount; ++f ) {
2158        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
2159        fileFunc( path );
2160        tr_free( path );
2161    }
2162
2163    /* Now clean out the directories left empty from the previous step.
2164     * Work from deepest to shallowest s.t. lower folders
2165     * won't prevent the upper folders from being deleted */
2166    {
2167        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2168        s = (char**) tr_ptrArrayPeek( &folders, &n );
2169        for( i=0; i<n; ++i )
2170            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2171                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2172        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2173        for( i=0; i<n; ++i )
2174            fileFunc( s[i] );
2175        tr_ptrArrayDestruct( &cleanFolders, NULL );
2176    }
2177
2178    /* cleanup */
2179    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2180    tr_ptrArrayDestruct( &folders, tr_free );
2181    tr_ptrArrayDestruct( &torrentFiles, NULL );
2182    tr_free( root );
2183    tr_free( tmp );
2184}
2185
2186void
2187tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2188{
2189    assert( tr_isTorrent( tor ) );
2190
2191    if( fileFunc == NULL )
2192        fileFunc = remove;
2193
2194    /* close all the files because we're about to delete them */
2195    tr_torrentCloseLocalFiles( tor );
2196
2197    if( tor->info.fileCount > 1 )
2198        deleteLocalData( tor, fileFunc );
2199    else {
2200        /* torrent only has one file */
2201        char * path = tr_buildPath( tor->downloadDir, tor->info.files[0].name, NULL );
2202        fileFunc( path );
2203        tr_free( path );
2204    }
2205}
2206
2207/***
2208****
2209***/
2210
2211struct LocationData
2212{
2213    tr_bool move_from_old_location;
2214    tr_bool * setme_done;
2215    char * location;
2216    tr_torrent * tor;
2217};
2218
2219static void
2220setLocation( void * vdata )
2221{
2222    struct LocationData * data = vdata;
2223    tr_torrent * tor = data->tor;
2224    const tr_bool do_move = data->move_from_old_location;
2225    const char * location = data->location;
2226
2227    assert( tr_isTorrent( tor ) );
2228
2229    if( strcmp( location, tor->downloadDir ) )
2230    {
2231        tr_file_index_t i;
2232
2233        /* bad idea to move files while they're being verified... */
2234        tr_verifyRemove( tor );
2235
2236        /* if the torrent is running, stop it and set a flag to
2237         * restart after we're done */
2238        if( tor->isRunning )
2239        {
2240            tr_torrentStop( tor );
2241            tor->startAfterVerify = TRUE;
2242        }
2243
2244        /* try to move the files.
2245         * FIXME: there are still all kinds of nasty cases, like what
2246         * if the target directory runs out of space halfway through... */
2247        for( i=0; i<tor->info.fileCount; ++i )
2248        {
2249            struct stat sb;
2250            char * oldpath = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
2251            char * newpath = tr_buildPath( location, tor->info.files[i].name, NULL );
2252
2253           
2254            if( do_move && !stat( oldpath, &sb ) )
2255            {
2256                tr_moveFile( oldpath, newpath );
2257                tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2258            }
2259            else if( !stat( newpath, &sb ) )
2260            {
2261                tr_torinf( tor, "found \"%s\"", newpath );
2262            }
2263
2264            tr_free( newpath );
2265            tr_free( oldpath );
2266        }
2267
2268        /* blow away the leftover subdirectories in the old location */
2269        tr_torrentDeleteLocalData( tor, unlink );
2270
2271        /* set the new location and reverify */
2272        tr_torrentSetDownloadDir( tor, location );
2273        tr_torrentVerify( tor );
2274    }
2275
2276    if( data->setme_done )
2277        *data->setme_done = TRUE;
2278
2279    /* cleanup */
2280    tr_free( data->location );
2281    tr_free( data );
2282}
2283
2284void
2285tr_torrentSetLocation( tr_torrent * tor,
2286                       const char * location,
2287                       tr_bool      move_from_old_location,
2288                       tr_bool    * setme_done )
2289{
2290    struct LocationData * data;
2291
2292    assert( tr_isTorrent( tor ) );
2293
2294    if( setme_done )
2295        *setme_done = FALSE;
2296
2297    /* run this in the libtransmission thread */
2298    data = tr_new( struct LocationData, 1 );
2299    data->tor = tor;
2300    data->location = tr_strdup( location );
2301    data->move_from_old_location = move_from_old_location;
2302    data->setme_done = setme_done;
2303    tr_runInEventThread( tor->session, setLocation, data );
2304}
2305
2306/***
2307****
2308***/
2309
2310void
2311tr_torrentCheckSeedRatio( tr_torrent * tor )
2312{
2313    double seedRatio;
2314
2315    assert( tr_isTorrent( tor ) );
2316
2317    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2318    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2319    {
2320        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2321        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2322        double ratio;
2323
2324        /* maybe we're the initial seeder and never downloaded anything... */
2325        if( down == 0 )
2326            down = tr_cpHaveValid( &tor->completion );
2327
2328        ratio = tr_getRatio( up, down );
2329
2330        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2331        {
2332            tr_torrentStop( tor );
2333
2334            /* set to no ratio limit to allow easy restarting */
2335            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2336
2337            /* maybe notify the client */
2338            if( tor->ratio_limit_hit_func != NULL )
2339                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2340        }
2341    }
2342}
Note: See TracBrowser for help on using the repository browser.