source: trunk/libtransmission/torrent.c @ 8254

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

(trunk) experimental support for tr_torrentSetPriority()

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