source: trunk/libtransmission/torrent.c @ 8398

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

(trunk libT) #2035: Transmission causes wakeups by unnecessary polling.

  • 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 8398 2009-05-14 13:42:29Z 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;
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
985fileBytesCompleted( 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
1035tr_file_stat *
1036tr_torrentFiles( const tr_torrent * tor,
1037                 tr_file_index_t *  fileCount )
1038{
1039    tr_file_index_t       i;
1040    const tr_file_index_t n = tor->info.fileCount;
1041    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1042    tr_file_stat *        walk = files;
1043    const tr_bool         isSeed = tor->completeness == TR_SEED;
1044
1045    assert( tr_isTorrent( tor ) );
1046
1047    for( i = 0; i < n; ++i, ++walk )
1048    {
1049        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1050        walk->bytesCompleted = b;
1051        walk->progress = tr_getRatio( b, tor->info.files[i].length );
1052    }
1053
1054    if( fileCount )
1055        *fileCount = n;
1056
1057    return files;
1058}
1059
1060void
1061tr_torrentFilesFree( tr_file_stat *            files,
1062                     tr_file_index_t fileCount UNUSED )
1063{
1064    tr_free( files );
1065}
1066
1067/***
1068****
1069***/
1070
1071float*
1072tr_torrentWebSpeeds( const tr_torrent * tor )
1073{
1074    return tr_isTorrent( tor )
1075         ? tr_peerMgrWebSpeeds( tor )
1076         : NULL;
1077}
1078
1079tr_peer_stat *
1080tr_torrentPeers( const tr_torrent * tor,
1081                 int *              peerCount )
1082{
1083    tr_peer_stat * ret = NULL;
1084
1085    if( tr_isTorrent( tor ) )
1086        ret = tr_peerMgrPeerStats( tor, peerCount );
1087
1088    return ret;
1089}
1090
1091void
1092tr_torrentPeersFree( tr_peer_stat * peers,
1093                     int peerCount  UNUSED )
1094{
1095    tr_free( peers );
1096}
1097
1098void
1099tr_torrentAvailability( const tr_torrent * tor,
1100                        int8_t *           tab,
1101                        int                size )
1102{
1103    tr_peerMgrTorrentAvailability( tor, tab, size );
1104}
1105
1106void
1107tr_torrentAmountFinished( const tr_torrent * tor,
1108                          float *            tab,
1109                          int                size )
1110{
1111    assert( tr_isTorrent( tor ) );
1112
1113    tr_torrentLock( tor );
1114    tr_cpGetAmountDone( &tor->completion, tab, size );
1115    tr_torrentUnlock( tor );
1116}
1117
1118void
1119tr_torrentResetTransferStats( tr_torrent * tor )
1120{
1121    assert( tr_isTorrent( tor ) );
1122
1123    tr_torrentLock( tor );
1124
1125    tor->downloadedPrev += tor->downloadedCur;
1126    tor->downloadedCur   = 0;
1127    tor->uploadedPrev   += tor->uploadedCur;
1128    tor->uploadedCur     = 0;
1129    tor->corruptPrev    += tor->corruptCur;
1130    tor->corruptCur      = 0;
1131
1132    tr_torrentUnlock( tor );
1133}
1134
1135void
1136tr_torrentSetHasPiece( tr_torrent *     tor,
1137                       tr_piece_index_t pieceIndex,
1138                       tr_bool          has )
1139{
1140    assert( tr_isTorrent( tor ) );
1141    assert( pieceIndex < tor->info.pieceCount );
1142
1143    if( has )
1144        tr_cpPieceAdd( &tor->completion, pieceIndex );
1145    else
1146        tr_cpPieceRem( &tor->completion, pieceIndex );
1147}
1148
1149/***
1150****
1151***/
1152
1153static void
1154freeTorrent( tr_torrent * tor )
1155{
1156    tr_torrent * t;
1157    tr_session *  session = tor->session;
1158    tr_info *    inf = &tor->info;
1159
1160    assert( tr_isTorrent( tor ) );
1161    assert( !tor->isRunning );
1162
1163    tr_globalLock( session );
1164
1165    tr_peerMgrRemoveTorrent( tor );
1166
1167    tr_cpDestruct( &tor->completion );
1168
1169    tr_rcDestruct( &tor->swarmSpeed );
1170
1171    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
1172    tr_trackerFree( tor->tracker );
1173    tor->tracker = NULL;
1174
1175    tr_bitfieldDestruct( &tor->checkedPieces );
1176
1177    tr_free( tor->downloadDir );
1178    tr_free( tor->peer_id );
1179
1180    if( tor == session->torrentList )
1181        session->torrentList = tor->next;
1182    else for( t = session->torrentList; t != NULL; t = t->next ) {
1183        if( t->next == tor ) {
1184            t->next = tor->next;
1185            break;
1186        }
1187    }
1188
1189    assert( session->torrentCount >= 1 );
1190    session->torrentCount--;
1191
1192    tr_bandwidthFree( tor->bandwidth );
1193
1194    tr_metainfoFree( inf );
1195    tr_free( tor );
1196
1197    tr_globalUnlock( session );
1198}
1199
1200/**
1201***  Start/Stop Callback
1202**/
1203
1204static void
1205checkAndStartImpl( void * vtor )
1206{
1207    tr_torrent * tor = vtor;
1208
1209    assert( tr_isTorrent( tor ) );
1210
1211    tr_globalLock( tor->session );
1212
1213    tor->isRunning = TRUE;
1214    tor->needsSeedRatioCheck = TRUE;
1215    *tor->errorString = '\0';
1216    tr_torrentResetTransferStats( tor );
1217    tor->completeness = tr_cpGetStatus( &tor->completion );
1218    tr_torrentSaveResume( tor );
1219    tor->startDate = tor->anyDate = time( NULL );
1220    tr_trackerStart( tor->tracker );
1221    tr_peerMgrStartTorrent( tor );
1222
1223    tr_globalUnlock( tor->session );
1224}
1225
1226static void
1227checkAndStartCB( tr_torrent * tor )
1228{
1229    assert( tr_isTorrent( tor ) );
1230    assert( tr_isSession( tor->session ) );
1231
1232    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1233}
1234
1235static void
1236torrentStart( tr_torrent * tor, int reloadProgress )
1237{
1238    assert( tr_isTorrent( tor ) );
1239
1240    tr_globalLock( tor->session );
1241
1242    if( !tor->isRunning )
1243    {
1244        const tr_bool isVerifying = tr_verifyInProgress( tor );
1245
1246        if( !isVerifying && reloadProgress )
1247            tr_torrentLoadResume( tor, TR_FR_PROGRESS, NULL );
1248
1249        tor->isRunning = 1;
1250
1251        if( !isVerifying )
1252            tr_verifyAdd( tor, checkAndStartCB );
1253    }
1254
1255    tr_globalUnlock( tor->session );
1256}
1257
1258void
1259tr_torrentStart( tr_torrent * tor )
1260{
1261    if( tr_isTorrent( tor ) )
1262        torrentStart( tor, TRUE );
1263}
1264
1265static void
1266torrentRecheckDoneImpl( void * vtor )
1267{
1268    tr_torrent * tor = vtor;
1269
1270    assert( tr_isTorrent( tor ) );
1271    tr_torrentRecheckCompleteness( tor );
1272
1273    if( tor->startAfterVerify )
1274    {
1275        tor->startAfterVerify = FALSE;
1276        tr_torrentStart( tor );
1277    }
1278}
1279
1280static void
1281torrentRecheckDoneCB( tr_torrent * tor )
1282{
1283    assert( tr_isTorrent( tor ) );
1284
1285    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1286}
1287
1288void
1289tr_torrentVerify( tr_torrent * tor )
1290{
1291    assert( tr_isTorrent( tor ) );
1292    tr_globalLock( tor->session );
1293
1294    /* if the torrent's already being verified, stop it */
1295    tr_verifyRemove( tor );
1296
1297    /* if the torrent's running, stop it & set the restart-after-verify flag */
1298    if( tor->isRunning ) {
1299        tr_torrentStop( tor );
1300        tor->startAfterVerify = TRUE;
1301    }
1302
1303    /* add the torrent to the recheck queue */
1304    tr_torrentUncheck( tor );
1305    tr_verifyAdd( tor, torrentRecheckDoneCB );
1306
1307    tr_globalUnlock( tor->session );
1308}
1309
1310static void
1311tr_torrentCloseLocalFiles( const tr_torrent * tor )
1312{
1313    tr_file_index_t i;
1314    struct evbuffer * buf = evbuffer_new( );
1315
1316    assert( tr_isTorrent( tor ) );
1317
1318    for( i=0; i<tor->info.fileCount; ++i )
1319    {
1320        const tr_file * file = &tor->info.files[i];
1321        evbuffer_drain( buf, EVBUFFER_LENGTH( buf ) );
1322        evbuffer_add_printf( buf, "%s%s%s", tor->downloadDir, TR_PATH_DELIMITER_STR, file->name );
1323        tr_fdFileClose( (const char*) EVBUFFER_DATA( buf ) );
1324    }
1325
1326    evbuffer_free( buf );
1327}
1328
1329static void
1330stopTorrent( void * vtor )
1331{
1332    tr_torrent * tor = vtor;
1333
1334    assert( tr_isTorrent( tor ) );
1335
1336    tr_verifyRemove( tor );
1337    tr_peerMgrStopTorrent( tor );
1338    tr_trackerStop( tor->tracker );
1339
1340    tr_torrentCloseLocalFiles( tor );
1341}
1342
1343void
1344tr_torrentStop( tr_torrent * tor )
1345{
1346    assert( tr_isTorrent( tor ) );
1347
1348    if( tr_isTorrent( tor ) )
1349    {
1350        tr_globalLock( tor->session );
1351
1352        tor->isRunning = 0;
1353        if( !tor->isDeleting )
1354            tr_torrentSaveResume( tor );
1355        tr_runInEventThread( tor->session, stopTorrent, tor );
1356
1357        tr_globalUnlock( tor->session );
1358    }
1359}
1360
1361static void
1362closeTorrent( void * vtor )
1363{
1364    tr_benc * d;
1365    tr_torrent * tor = vtor;
1366
1367    assert( tr_isTorrent( tor ) );
1368
1369    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1370    tr_bencDictAddInt( d, "id", tor->uniqueId );
1371    tr_bencDictAddInt( d, "date", time( NULL ) );
1372
1373    tr_torrentSaveResume( tor );
1374    tor->isRunning = 0;
1375    stopTorrent( tor );
1376    if( tor->isDeleting )
1377    {
1378        tr_metainfoRemoveSaved( tor->session, &tor->info );
1379        tr_torrentRemoveResume( tor );
1380    }
1381    freeTorrent( tor );
1382}
1383
1384void
1385tr_torrentFree( tr_torrent * tor )
1386{
1387    if( tr_isTorrent( tor ) )
1388    {
1389        tr_session * session = tor->session;
1390        assert( tr_isSession( session ) );
1391        tr_globalLock( session );
1392
1393        tr_torrentClearCompletenessCallback( tor );
1394        tr_runInEventThread( session, closeTorrent, tor );
1395
1396        tr_globalUnlock( session );
1397    }
1398}
1399
1400void
1401tr_torrentRemove( tr_torrent * tor )
1402{
1403    assert( tr_isTorrent( tor ) );
1404
1405    tor->isDeleting = 1;
1406    tr_torrentFree( tor );
1407}
1408
1409/**
1410***  Completeness
1411**/
1412
1413static const char *
1414getCompletionString( int type )
1415{
1416    switch( type )
1417    {
1418        /* Translators: this is a minor point that's safe to skip over, but FYI:
1419           "Complete" and "Done" are specific, different terms in Transmission:
1420           "Complete" means we've downloaded every file in the torrent.
1421           "Done" means we're done downloading the files we wanted, but NOT all
1422           that exist */
1423        case TR_PARTIAL_SEED:
1424            return _( "Done" );
1425
1426        case TR_SEED:
1427            return _( "Complete" );
1428
1429        default:
1430            return _( "Incomplete" );
1431    }
1432}
1433
1434static void
1435fireCompletenessChange( tr_torrent       * tor,
1436                        tr_completeness    status )
1437{
1438    assert( tr_isTorrent( tor ) );
1439    assert( ( status == TR_LEECH )
1440         || ( status == TR_SEED )
1441         || ( status == TR_PARTIAL_SEED ) );
1442
1443    if( tor->completeness_func )
1444        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1445}
1446
1447void
1448tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1449                                   tr_torrent_completeness_func    func,
1450                                   void                          * user_data )
1451{
1452    assert( tr_isTorrent( tor ) );
1453
1454    tor->completeness_func = func;
1455    tor->completeness_func_user_data = user_data;
1456}
1457
1458void
1459tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1460                                    tr_torrent_ratio_limit_hit_func  func,
1461                                    void                           * user_data )
1462{
1463    assert( tr_isTorrent( tor ) );
1464
1465    tor->ratio_limit_hit_func = func;
1466    tor->ratio_limit_hit_func_user_data = user_data;
1467}
1468
1469void
1470tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1471{
1472    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1473}
1474
1475void
1476tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1477{
1478    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1479}
1480
1481void
1482tr_torrentRecheckCompleteness( tr_torrent * tor )
1483{
1484    tr_completeness completeness;
1485
1486    assert( tr_isTorrent( tor ) );
1487
1488    tr_torrentLock( tor );
1489
1490    completeness = tr_cpGetStatus( &tor->completion );
1491
1492    if( completeness != tor->completeness )
1493    {
1494        const int recentChange = tor->downloadedCur != 0;
1495
1496        if( recentChange )
1497        {
1498            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1499                      getCompletionString( tor->completeness ),
1500                      getCompletionString( completeness ) );
1501        }
1502
1503        tor->completeness = completeness;
1504        tor->needsSeedRatioCheck = TRUE;
1505        tr_torrentCloseLocalFiles( tor );
1506        fireCompletenessChange( tor, completeness );
1507
1508        if( recentChange && ( completeness == TR_SEED ) )
1509        {
1510            tr_trackerCompleted( tor->tracker );
1511
1512            tor->doneDate = tor->anyDate = time( NULL );
1513        }
1514
1515        tr_torrentSaveResume( tor );
1516    }
1517
1518    tr_torrentUnlock( tor );
1519}
1520
1521/**
1522***  File priorities
1523**/
1524
1525void
1526tr_torrentInitFilePriority( tr_torrent *    tor,
1527                            tr_file_index_t fileIndex,
1528                            tr_priority_t   priority )
1529{
1530    tr_piece_index_t i;
1531    tr_file *        file;
1532
1533    assert( tr_isTorrent( tor ) );
1534    assert( fileIndex < tor->info.fileCount );
1535    assert( tr_isPriority( priority ) );
1536
1537    file = &tor->info.files[fileIndex];
1538    file->priority = priority;
1539    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1540        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1541}
1542
1543void
1544tr_torrentSetFilePriorities( tr_torrent *      tor,
1545                             tr_file_index_t * files,
1546                             tr_file_index_t   fileCount,
1547                             tr_priority_t     priority )
1548{
1549    tr_file_index_t i;
1550
1551    assert( tr_isTorrent( tor ) );
1552
1553    tr_torrentLock( tor );
1554
1555    for( i = 0; i < fileCount; ++i )
1556        tr_torrentInitFilePriority( tor, files[i], priority );
1557
1558    tr_torrentSaveResume( tor );
1559    tr_torrentUnlock( tor );
1560}
1561
1562tr_priority_t
1563tr_torrentGetFilePriority( const tr_torrent * tor,
1564                           tr_file_index_t    file )
1565{
1566    tr_priority_t ret;
1567
1568    assert( tr_isTorrent( tor ) );
1569
1570    tr_torrentLock( tor );
1571    assert( tor );
1572    assert( file < tor->info.fileCount );
1573    ret = tor->info.files[file].priority;
1574    tr_torrentUnlock( tor );
1575
1576    return ret;
1577}
1578
1579tr_priority_t*
1580tr_torrentGetFilePriorities( const tr_torrent * tor )
1581{
1582    tr_file_index_t i;
1583    tr_priority_t * p;
1584
1585    assert( tr_isTorrent( tor ) );
1586
1587    tr_torrentLock( tor );
1588    p = tr_new0( tr_priority_t, tor->info.fileCount );
1589    for( i = 0; i < tor->info.fileCount; ++i )
1590        p[i] = tor->info.files[i].priority;
1591    tr_torrentUnlock( tor );
1592
1593    return p;
1594}
1595
1596/**
1597***  File DND
1598**/
1599
1600int
1601tr_torrentGetFileDL( const tr_torrent * tor,
1602                     tr_file_index_t    file )
1603{
1604    int doDownload;
1605
1606    assert( tr_isTorrent( tor ) );
1607
1608    tr_torrentLock( tor );
1609
1610    assert( file < tor->info.fileCount );
1611    doDownload = !tor->info.files[file].dnd;
1612
1613    tr_torrentUnlock( tor );
1614    return doDownload != 0;
1615}
1616
1617static void
1618setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1619{
1620    tr_file *        file;
1621    const int        dnd = !doDownload;
1622    tr_piece_index_t firstPiece, firstPieceDND;
1623    tr_piece_index_t lastPiece, lastPieceDND;
1624    tr_file_index_t  i;
1625
1626    assert( tr_isTorrent( tor ) );
1627
1628    file = &tor->info.files[fileIndex];
1629    file->dnd = dnd;
1630    firstPiece = file->firstPiece;
1631    lastPiece = file->lastPiece;
1632
1633    /* can't set the first piece to DND unless
1634       every file using that piece is DND */
1635    firstPieceDND = dnd;
1636    if( fileIndex > 0 )
1637    {
1638        for( i = fileIndex - 1; firstPieceDND; --i )
1639        {
1640            if( tor->info.files[i].lastPiece != firstPiece )
1641                break;
1642            firstPieceDND = tor->info.files[i].dnd;
1643            if( !i )
1644                break;
1645        }
1646    }
1647
1648    /* can't set the last piece to DND unless
1649       every file using that piece is DND */
1650    lastPieceDND = dnd;
1651    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1652    {
1653        if( tor->info.files[i].firstPiece != lastPiece )
1654            break;
1655        lastPieceDND = tor->info.files[i].dnd;
1656    }
1657
1658    if( firstPiece == lastPiece )
1659    {
1660        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1661    }
1662    else
1663    {
1664        tr_piece_index_t pp;
1665        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1666        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1667        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1668            tor->info.pieces[pp].dnd = dnd;
1669    }
1670}
1671
1672void
1673tr_torrentInitFileDLs( tr_torrent      * tor,
1674                       tr_file_index_t * files,
1675                       tr_file_index_t   fileCount,
1676                       tr_bool           doDownload )
1677{
1678    tr_file_index_t i;
1679
1680    assert( tr_isTorrent( tor ) );
1681
1682    tr_torrentLock( tor );
1683
1684    for( i=0; i<fileCount; ++i )
1685        setFileDND( tor, files[i], doDownload );
1686    tr_cpInvalidateDND( &tor->completion );
1687    tor->needsSeedRatioCheck = TRUE;
1688
1689    tr_torrentUnlock( tor );
1690}
1691
1692void
1693tr_torrentSetFileDLs( tr_torrent *      tor,
1694                      tr_file_index_t * files,
1695                      tr_file_index_t   fileCount,
1696                      tr_bool           doDownload )
1697{
1698    assert( tr_isTorrent( tor ) );
1699
1700    tr_torrentLock( tor );
1701    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1702    tr_torrentSaveResume( tor );
1703    tr_torrentUnlock( tor );
1704}
1705
1706/***
1707****
1708***/
1709
1710tr_priority_t
1711tr_torrentGetPriority( const tr_torrent * tor )
1712{
1713    assert( tr_isTorrent( tor ) );
1714
1715    return tor->bandwidth->priority;
1716}
1717
1718void
1719tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1720{
1721    assert( tr_isTorrent( tor ) );
1722    assert( tr_isPriority( priority ) );
1723
1724    tor->bandwidth->priority = priority;
1725}
1726
1727/***
1728****
1729***/
1730
1731void
1732tr_torrentSetPeerLimit( tr_torrent * tor,
1733                        uint16_t     maxConnectedPeers )
1734{
1735    assert( tr_isTorrent( tor ) );
1736
1737    tor->maxConnectedPeers = maxConnectedPeers;
1738}
1739
1740uint16_t
1741tr_torrentGetPeerLimit( const tr_torrent * tor )
1742{
1743    assert( tr_isTorrent( tor ) );
1744
1745    return tor->maxConnectedPeers;
1746}
1747
1748/***
1749****
1750***/
1751
1752tr_block_index_t
1753_tr_block( const tr_torrent * tor,
1754           tr_piece_index_t   index,
1755           uint32_t           offset )
1756{
1757    tr_block_index_t ret;
1758
1759    assert( tr_isTorrent( tor ) );
1760
1761    ret = index;
1762    ret *= ( tor->info.pieceSize / tor->blockSize );
1763    ret += offset / tor->blockSize;
1764    return ret;
1765}
1766
1767tr_bool
1768tr_torrentReqIsValid( const tr_torrent * tor,
1769                      tr_piece_index_t   index,
1770                      uint32_t           offset,
1771                      uint32_t           length )
1772{
1773    int err = 0;
1774
1775    assert( tr_isTorrent( tor ) );
1776
1777    if( index >= tor->info.pieceCount )
1778        err = 1;
1779    else if( length < 1 )
1780        err = 2;
1781    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1782        err = 3;
1783    else if( length > MAX_BLOCK_SIZE )
1784        err = 4;
1785    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1786        err = 5;
1787
1788    if( err ) fprintf( stderr, "index %lu offset %lu length %lu err %d\n",
1789                       (unsigned long)index, (unsigned long)offset,
1790                       (unsigned long)length,
1791                       err );
1792
1793    return !err;
1794}
1795
1796uint64_t
1797tr_pieceOffset( const tr_torrent * tor,
1798                tr_piece_index_t   index,
1799                uint32_t           offset,
1800                uint32_t           length )
1801{
1802    uint64_t ret;
1803
1804    assert( tr_isTorrent( tor ) );
1805
1806    ret = tor->info.pieceSize;
1807    ret *= index;
1808    ret += offset;
1809    ret += length;
1810    return ret;
1811}
1812
1813/***
1814****
1815***/
1816
1817void
1818tr_torrentSetPieceChecked( tr_torrent        * tor,
1819                           tr_piece_index_t    piece,
1820                           tr_bool             isChecked )
1821{
1822    assert( tr_isTorrent( tor ) );
1823
1824    if( isChecked )
1825        tr_bitfieldAdd( &tor->checkedPieces, piece );
1826    else
1827        tr_bitfieldRem( &tor->checkedPieces, piece );
1828}
1829
1830void
1831tr_torrentSetFileChecked( tr_torrent *    tor,
1832                          tr_file_index_t fileIndex,
1833                          tr_bool         isChecked )
1834{
1835    const tr_file *        file = &tor->info.files[fileIndex];
1836    const tr_piece_index_t begin = file->firstPiece;
1837    const tr_piece_index_t end = file->lastPiece + 1;
1838
1839    assert( tr_isTorrent( tor ) );
1840
1841    if( isChecked )
1842        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
1843    else
1844        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
1845}
1846
1847tr_bool
1848tr_torrentIsFileChecked( const tr_torrent * tor,
1849                         tr_file_index_t    fileIndex )
1850{
1851    const tr_file *        file = &tor->info.files[fileIndex];
1852    const tr_piece_index_t begin = file->firstPiece;
1853    const tr_piece_index_t end = file->lastPiece + 1;
1854    tr_piece_index_t       i;
1855    tr_bool                isChecked = TRUE;
1856
1857    assert( tr_isTorrent( tor ) );
1858
1859    for( i = begin; isChecked && i < end; ++i )
1860        if( !tr_torrentIsPieceChecked( tor, i ) )
1861            isChecked = FALSE;
1862
1863    return isChecked;
1864}
1865
1866void
1867tr_torrentUncheck( tr_torrent * tor )
1868{
1869    assert( tr_isTorrent( tor ) );
1870
1871    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
1872}
1873
1874int
1875tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1876{
1877    assert( tr_isTorrent( tor ) );
1878
1879    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
1880}
1881
1882time_t*
1883tr_torrentGetMTimes( const tr_torrent * tor,
1884                     size_t *           setme_n )
1885{
1886    size_t       i;
1887    const size_t n = tor->info.fileCount;
1888    time_t *     m = tr_new0( time_t, n );
1889
1890    assert( tr_isTorrent( tor ) );
1891
1892    for( i = 0; i < n; ++i )
1893    {
1894        struct stat sb;
1895        char * path = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
1896        if( !stat( path, &sb ) )
1897        {
1898#ifdef SYS_DARWIN
1899            m[i] = sb.st_mtimespec.tv_sec;
1900#else
1901            m[i] = sb.st_mtime;
1902#endif
1903        }
1904        tr_free( path );
1905    }
1906
1907    *setme_n = n;
1908    return m;
1909}
1910
1911/***
1912****
1913***/
1914
1915void
1916tr_torrentSetAnnounceList( tr_torrent *            tor,
1917                           const tr_tracker_info * trackers,
1918                           int                     trackerCount )
1919{
1920    tr_benc metainfo;
1921
1922    assert( tr_isTorrent( tor ) );
1923
1924    /* save to the .torrent file */
1925    if( !tr_bencLoadFile( tor->info.torrent, &metainfo ) )
1926    {
1927        int       i;
1928        int       prevTier = -1;
1929        tr_benc * tier = NULL;
1930        tr_benc * announceList;
1931        tr_info   tmpInfo;
1932
1933        /* remove the old fields */
1934        tr_bencDictRemove( &metainfo, "announce" );
1935        tr_bencDictRemove( &metainfo, "announce-list" );
1936
1937        /* add the new fields */
1938        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
1939        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
1940        for( i = 0; i < trackerCount; ++i ) {
1941            if( prevTier != trackers[i].tier ) {
1942                prevTier = trackers[i].tier;
1943                tier = tr_bencListAddList( announceList, 0 );
1944            }
1945            tr_bencListAddStr( tier, trackers[i].announce );
1946        }
1947
1948        /* try to parse it back again, to make sure it's good */
1949        memset( &tmpInfo, 0, sizeof( tr_info ) );
1950        if( !tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
1951        {
1952            /* it's good, so keep these new trackers and free the old ones */
1953
1954            tr_info swap;
1955            swap.trackers = tor->info.trackers;
1956            swap.trackerCount = tor->info.trackerCount;
1957            tor->info.trackers = tmpInfo.trackers;
1958            tor->info.trackerCount = tmpInfo.trackerCount;
1959            tmpInfo.trackers = swap.trackers;
1960            tmpInfo.trackerCount = swap.trackerCount;
1961
1962            tr_metainfoFree( &tmpInfo );
1963            tr_bencSaveFile( tor->info.torrent, &metainfo );
1964        }
1965
1966        /* cleanup */
1967        tr_bencFree( &metainfo );
1968    }
1969}
1970
1971/**
1972***
1973**/
1974
1975void
1976tr_torrentSetAddedDate( tr_torrent * tor,
1977                        time_t       t )
1978{
1979    assert( tr_isTorrent( tor ) );
1980
1981    tor->addedDate = t;
1982    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
1983}
1984
1985void
1986tr_torrentSetActivityDate( tr_torrent * tor,
1987                           time_t       t )
1988{
1989    assert( tr_isTorrent( tor ) );
1990
1991    tor->activityDate = t;
1992    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
1993}
1994
1995void
1996tr_torrentSetDoneDate( tr_torrent * tor,
1997                       time_t       t )
1998{
1999    assert( tr_isTorrent( tor ) );
2000
2001    tor->doneDate = t;
2002    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2003}
2004
2005/**
2006***
2007**/
2008
2009uint64_t
2010tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2011{
2012    const tr_file * it;
2013    const tr_file * end;
2014    struct stat sb;
2015    uint64_t bytesLeft = 0;
2016
2017    assert( tr_isTorrent( tor ) );
2018
2019    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
2020    {
2021        if( !it->dnd )
2022        {
2023            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
2024
2025            bytesLeft += it->length;
2026
2027            if( !stat( path, &sb )
2028                    && S_ISREG( sb.st_mode )
2029                    && ( (uint64_t)sb.st_size <= it->length ) )
2030                bytesLeft -= sb.st_size;
2031
2032            tr_free( path );
2033        }
2034    }
2035
2036    return bytesLeft;
2037}
2038
2039/****
2040*****  Removing the torrent's local data
2041****/
2042
2043static int
2044vstrcmp( const void * a, const void * b )
2045{
2046    return strcmp( a, b );
2047}
2048
2049static int
2050compareLongestFirst( const void * a, const void * b )
2051{
2052    const size_t alen = strlen( a );
2053    const size_t blen = strlen( b );
2054
2055    if( alen != blen )
2056        return alen > blen ? -1 : 1;
2057
2058    return vstrcmp( a, b );
2059}
2060
2061static void
2062addDirtyFile( const char  * root,
2063              const char  * filename,
2064              tr_ptrArray * dirtyFolders )
2065{
2066    char * dir = tr_dirname( filename );
2067
2068    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2069    while (     ( dir != NULL )
2070             && ( strlen( root ) <= strlen( dir ) )
2071             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2072    {
2073        char * tmp;
2074        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2075
2076        tmp = tr_dirname( dir );
2077        tr_free( dir );
2078        dir = tmp;
2079    }
2080
2081    tr_free( dir );
2082}
2083
2084static void
2085walkLocalData( const tr_torrent * tor,
2086               const char       * root,
2087               const char       * dir,
2088               const char       * base,
2089               tr_ptrArray      * torrentFiles,
2090               tr_ptrArray      * folders,
2091               tr_ptrArray      * dirtyFolders )
2092{
2093    int i;
2094    struct stat sb;
2095    char * buf;
2096
2097    assert( tr_isTorrent( tor ) );
2098
2099    buf = tr_buildPath( dir, base, NULL );
2100    i = stat( buf, &sb );
2101    if( !i )
2102    {
2103        DIR * odir = NULL;
2104
2105        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2106        {
2107            struct dirent *d;
2108            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2109            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2110                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2111                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2112            closedir( odir );
2113        }
2114        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2115        {
2116            const char * sub = buf + strlen( tor->downloadDir ) + strlen( TR_PATH_DELIMITER_STR );
2117            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2118            if( !isTorrentFile )
2119                addDirtyFile( root, buf, dirtyFolders );
2120        }
2121    }
2122
2123    tr_free( buf );
2124}
2125
2126static void
2127deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2128{
2129    int i, n;
2130    char ** s;
2131    tr_file_index_t f;
2132    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2133    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2134    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2135
2136    const char * firstFile = tor->info.files[0].name;
2137    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2138    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2139    char * root = tr_buildPath( tor->downloadDir, tmp, NULL );
2140
2141    assert( tr_isTorrent( tor ) );
2142
2143    for( f=0; f<tor->info.fileCount; ++f )
2144        tr_ptrArrayInsertSorted( &torrentFiles, tor->info.files[f].name, vstrcmp );
2145
2146    /* build the set of folders and dirtyFolders */
2147    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2148
2149    /* try to remove entire folders first, so that the recycle bin will be tidy */
2150    s = (char**) tr_ptrArrayPeek( &folders, &n );
2151    for( i=0; i<n; ++i )
2152        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2153            fileFunc( s[i] );
2154
2155    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2156    for( f=0; f<tor->info.fileCount; ++f ) {
2157        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
2158        fileFunc( path );
2159        tr_free( path );
2160    }
2161
2162    /* Now clean out the directories left empty from the previous step.
2163     * Work from deepest to shallowest s.t. lower folders
2164     * won't prevent the upper folders from being deleted */
2165    {
2166        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2167        s = (char**) tr_ptrArrayPeek( &folders, &n );
2168        for( i=0; i<n; ++i )
2169            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2170                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2171        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2172        for( i=0; i<n; ++i )
2173            fileFunc( s[i] );
2174        tr_ptrArrayDestruct( &cleanFolders, NULL );
2175    }
2176
2177    /* cleanup */
2178    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2179    tr_ptrArrayDestruct( &folders, tr_free );
2180    tr_ptrArrayDestruct( &torrentFiles, NULL );
2181    tr_free( root );
2182    tr_free( tmp );
2183}
2184
2185void
2186tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2187{
2188    assert( tr_isTorrent( tor ) );
2189
2190    if( fileFunc == NULL )
2191        fileFunc = remove;
2192
2193    /* close all the files because we're about to delete them */
2194    tr_torrentCloseLocalFiles( tor );
2195
2196    if( tor->info.fileCount > 1 )
2197        deleteLocalData( tor, fileFunc );
2198    else {
2199        /* torrent only has one file */
2200        char * path = tr_buildPath( tor->downloadDir, tor->info.files[0].name, NULL );
2201        fileFunc( path );
2202        tr_free( path );
2203    }
2204}
2205
2206/***
2207****
2208***/
2209
2210struct LocationData
2211{
2212    tr_bool move_from_old_location;
2213    tr_bool * setme_done;
2214    char * location;
2215    tr_torrent * tor;
2216};
2217
2218static void
2219setLocation( void * vdata )
2220{
2221    struct LocationData * data = vdata;
2222    tr_torrent * tor = data->tor;
2223    const tr_bool do_move = data->move_from_old_location;
2224    const char * location = data->location;
2225
2226    assert( tr_isTorrent( tor ) );
2227
2228    if( strcmp( location, tor->downloadDir ) )
2229    {
2230        tr_file_index_t i;
2231
2232        /* bad idea to move files while they're being verified... */
2233        tr_verifyRemove( tor );
2234
2235        /* if the torrent is running, stop it and set a flag to
2236         * restart after we're done */
2237        if( tor->isRunning )
2238        {
2239            tr_torrentStop( tor );
2240            tor->startAfterVerify = TRUE;
2241        }
2242
2243        /* try to move the files.
2244         * FIXME: there are still all kinds of nasty cases, like what
2245         * if the target directory runs out of space halfway through... */
2246        for( i=0; i<tor->info.fileCount; ++i )
2247        {
2248            struct stat sb;
2249            char * oldpath = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
2250            char * newpath = tr_buildPath( location, tor->info.files[i].name, NULL );
2251
2252           
2253            if( do_move && !stat( oldpath, &sb ) )
2254            {
2255                tr_moveFile( oldpath, newpath );
2256                tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2257            }
2258            else if( !stat( newpath, &sb ) )
2259            {
2260                tr_torinf( tor, "found \"%s\"", newpath );
2261            }
2262
2263            tr_free( newpath );
2264            tr_free( oldpath );
2265        }
2266
2267        /* blow away the leftover subdirectories in the old location */
2268        tr_torrentDeleteLocalData( tor, unlink );
2269
2270        /* set the new location and reverify */
2271        tr_torrentSetDownloadDir( tor, location );
2272        tr_torrentVerify( tor );
2273    }
2274
2275    if( data->setme_done )
2276        *data->setme_done = TRUE;
2277
2278    /* cleanup */
2279    tr_free( data->location );
2280    tr_free( data );
2281}
2282
2283void
2284tr_torrentSetLocation( tr_torrent * tor,
2285                       const char * location,
2286                       tr_bool      move_from_old_location,
2287                       tr_bool    * setme_done )
2288{
2289    struct LocationData * data;
2290
2291    assert( tr_isTorrent( tor ) );
2292
2293    if( setme_done )
2294        *setme_done = FALSE;
2295
2296    /* run this in the libtransmission thread */
2297    data = tr_new( struct LocationData, 1 );
2298    data->tor = tor;
2299    data->location = tr_strdup( location );
2300    data->move_from_old_location = move_from_old_location;
2301    data->setme_done = setme_done;
2302    tr_runInEventThread( tor->session, setLocation, data );
2303}
2304
2305/***
2306****
2307***/
2308
2309void
2310tr_torrentCheckSeedRatio( tr_torrent * tor )
2311{
2312    double seedRatio;
2313
2314    assert( tr_isTorrent( tor ) );
2315
2316    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2317    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2318    {
2319        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2320        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2321        double ratio;
2322
2323        /* maybe we're the initial seeder and never downloaded anything... */
2324        if( down == 0 )
2325            down = tr_cpHaveValid( &tor->completion );
2326
2327        ratio = tr_getRatio( up, down );
2328
2329        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2330        {
2331            tr_torrentStop( tor );
2332
2333            /* set to no ratio limit to allow easy restarting */
2334            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2335
2336            /* maybe notify the client */
2337            if( tor->ratio_limit_hit_func != NULL )
2338                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2339        }
2340    }
2341}
Note: See TracBrowser for help on using the repository browser.