source: trunk/libtransmission/torrent.c @ 8122

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

(trunk) modify tr_torrentParse() and tr_torrentNew() arguments s.t. they use the ctor's session instead of passing it in again. Allow a NULL session pointer for some cases of tr_torrentParse().

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