source: trunk/libtransmission/torrent.c @ 8413

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

(trunk libT) experimental faster implementation of tr_torrentFiles(). for the time being, keep the old implementation too and add an assertion that the two come up with the same results.

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