source: trunk/libtransmission/torrent.c @ 7977

Last change on this file since 7977 was 7977, checked in by charles, 14 years ago

(trunk libT) #1823: Ratio limit is only checked when peers are active

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