source: trunk/libtransmission/torrent.c @ 8414

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

(trunk) add an option to the JSON generator to disable the human-readable indentations. Keep indenting the data files such as settings.json, but don't indent the messages used for RPC. This cuts the cost of deflate()ing those RPC messages by about 80%...

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