source: trunk/libtransmission/torrent.c @ 7988

Last change on this file since 7988 was 7988, checked in by livings124, 14 years ago

move the percent to the stop ratio into libtransmission

  • Property svn:keywords set to Date Rev Author Id
File size: 54.6 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 7988 2009-03-01 23:48:04Z livings124 $
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    tr_bool                 checkSeedRatio;
808
809    if( !tor )
810        return NULL;
811
812    assert( tr_isTorrent( tor ) );
813    tr_torrentLock( tor );
814
815    tor->lastStatTime = time( NULL );
816
817    s = &tor->stats;
818    s->id = tor->uniqueId;
819    s->activity = tr_torrentGetActivity( tor );
820    s->error  = tor->error;
821    memcpy( s->errorString, tor->errorString,
822           sizeof( s->errorString ) );
823
824    tc = tor->tracker;
825    ti = tr_trackerGetAddress( tor->tracker, tor );
826    s->announceURL = ti ? ti->announce : NULL;
827    s->scrapeURL   = ti ? ti->scrape   : NULL;
828    tr_trackerStat( tc, s );
829
830    tr_trackerGetCounts( tc, &s->timesCompleted,
831                             &s->leechers,
832                             &s->seeders,
833                             &s->downloaders );
834
835    tr_peerMgrTorrentStats( tor,
836                            &s->peersKnown,
837                            &s->peersConnected,
838                            &usableSeeds,
839                            &s->webseedsSendingToUs,
840                            &s->peersSendingToUs,
841                            &s->peersGettingFromUs,
842                            s->peersFrom );
843
844    now = tr_date( );
845    s->swarmSpeed         = tr_rcRate( &tor->swarmSpeed, now );
846    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
847    s->rawDownloadSpeed   = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
848    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
849    s->pieceDownloadSpeed = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
850
851    usableSeeds += tor->info.webseedCount;
852
853    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
854
855    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
856    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
857    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
858
859    s->recheckProgress = s->activity == TR_STATUS_CHECK
860                       ? 1.0 -
861                         ( tr_torrentCountUncheckedPieces( tor ) /
862                           (double) tor->info.pieceCount )
863                       : 0.0;
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    checkSeedRatio = tr_torrentGetSeedRatio( tor, &seedRatio );
900
901    switch( s->activity )
902    {
903        case TR_STATUS_DOWNLOAD:
904            if( s->leftUntilDone > s->desiredAvailable )
905                s->eta = TR_ETA_NOT_AVAIL;
906            else if( s->pieceDownloadSpeed < 0.1 )
907                s->eta = TR_ETA_UNKNOWN;
908            else
909                s->eta = s->leftUntilDone / s->pieceDownloadSpeed / 1024.0;
910            break;
911
912        case TR_STATUS_SEED:
913            if( checkSeedRatio )
914            {
915                if( s->pieceUploadSpeed < 0.1 )
916                    s->eta = TR_ETA_UNKNOWN;
917                else
918                    s->eta = (downloadedForRatio * (seedRatio - s->ratio)) / s->pieceUploadSpeed / 1024.0;
919            }
920            else
921                s->eta = TR_ETA_NOT_AVAIL;
922            break;
923
924        default:
925            s->eta = TR_ETA_NOT_AVAIL;
926            break;
927    }
928
929    if ( !checkSeedRatio || s->ratio >= seedRatio || s->ratio == TR_RATIO_INF )
930        s->percentRatio = 1.0;
931    else if ( s->ratio == TR_RATIO_NA )
932        s->percentRatio = 0.0;
933    else 
934        s->percentRatio = s->ratio / seedRatio;
935
936    tr_torrentUnlock( tor );
937
938    return s;
939}
940
941/***
942****
943***/
944
945static uint64_t
946fileBytesCompleted( const tr_torrent * tor,
947                    tr_file_index_t    fileIndex )
948{
949    const tr_file *        file     =  &tor->info.files[fileIndex];
950    const tr_block_index_t firstBlock       =  file->offset /
951                                              tor->blockSize;
952    const uint64_t         firstBlockOffset =  file->offset %
953                                              tor->blockSize;
954    const uint64_t         lastOffset       =
955        file->length ? ( file->length - 1 ) : 0;
956    const tr_block_index_t lastBlock        =
957        ( file->offset + lastOffset ) / tor->blockSize;
958    const uint64_t         lastBlockOffset  =
959        ( file->offset + lastOffset ) % tor->blockSize;
960    uint64_t               haveBytes = 0;
961
962    assert( tr_isTorrent( tor ) );
963    assert( fileIndex < tor->info.fileCount );
964    assert( file->offset + file->length <= tor->info.totalSize );
965    assert( ( firstBlock < tor->blockCount )
966          || ( !file->length && file->offset == tor->info.totalSize ) );
967    assert( ( lastBlock < tor->blockCount )
968          || ( !file->length && file->offset == tor->info.totalSize ) );
969    assert( firstBlock <= lastBlock );
970    assert( tr_torBlockPiece( tor, firstBlock ) == file->firstPiece );
971    assert( tr_torBlockPiece( tor, lastBlock ) == file->lastPiece );
972
973    if( firstBlock == lastBlock )
974    {
975        if( tr_cpBlockIsComplete( &tor->completion, firstBlock ) )
976            haveBytes += lastBlockOffset + 1 - firstBlockOffset;
977    }
978    else
979    {
980        tr_block_index_t i;
981
982        if( tr_cpBlockIsComplete( &tor->completion, firstBlock ) )
983            haveBytes += tor->blockSize - firstBlockOffset;
984
985        for( i = firstBlock + 1; i < lastBlock; ++i )
986            if( tr_cpBlockIsComplete( &tor->completion, i ) )
987                haveBytes += tor->blockSize;
988
989        if( tr_cpBlockIsComplete( &tor->completion, lastBlock ) )
990            haveBytes += lastBlockOffset + 1;
991    }
992
993    return haveBytes;
994}
995
996tr_file_stat *
997tr_torrentFiles( const tr_torrent * tor,
998                 tr_file_index_t *  fileCount )
999{
1000    tr_file_index_t       i;
1001    const tr_file_index_t n = tor->info.fileCount;
1002    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1003    tr_file_stat *        walk = files;
1004
1005    assert( tr_isTorrent( tor ) );
1006
1007    for( i = 0; i < n; ++i, ++walk )
1008    {
1009        const uint64_t b = fileBytesCompleted( tor, i );
1010        walk->bytesCompleted = b;
1011        walk->progress = tr_getRatio( b, tor->info.files[i].length );
1012    }
1013
1014    if( fileCount )
1015        *fileCount = n;
1016
1017    return files;
1018}
1019
1020void
1021tr_torrentFilesFree( tr_file_stat *            files,
1022                     tr_file_index_t fileCount UNUSED )
1023{
1024    tr_free( files );
1025}
1026
1027/***
1028****
1029***/
1030
1031float*
1032tr_torrentWebSpeeds( const tr_torrent * tor )
1033{
1034    return tr_isTorrent( tor )
1035         ? tr_peerMgrWebSpeeds( tor )
1036         : NULL;
1037}
1038
1039tr_peer_stat *
1040tr_torrentPeers( const tr_torrent * tor,
1041                 int *              peerCount )
1042{
1043    tr_peer_stat * ret = NULL;
1044
1045    if( tr_isTorrent( tor ) )
1046        ret = tr_peerMgrPeerStats( tor, peerCount );
1047
1048    return ret;
1049}
1050
1051void
1052tr_torrentPeersFree( tr_peer_stat * peers,
1053                     int peerCount  UNUSED )
1054{
1055    tr_free( peers );
1056}
1057
1058void
1059tr_torrentAvailability( const tr_torrent * tor,
1060                        int8_t *           tab,
1061                        int                size )
1062{
1063    tr_peerMgrTorrentAvailability( tor, tab, size );
1064}
1065
1066void
1067tr_torrentAmountFinished( const tr_torrent * tor,
1068                          float *            tab,
1069                          int                size )
1070{
1071    assert( tr_isTorrent( tor ) );
1072
1073    tr_torrentLock( tor );
1074    tr_cpGetAmountDone( &tor->completion, tab, size );
1075    tr_torrentUnlock( tor );
1076}
1077
1078void
1079tr_torrentResetTransferStats( tr_torrent * tor )
1080{
1081    assert( tr_isTorrent( tor ) );
1082
1083    tr_torrentLock( tor );
1084
1085    tor->downloadedPrev += tor->downloadedCur;
1086    tor->downloadedCur   = 0;
1087    tor->uploadedPrev   += tor->uploadedCur;
1088    tor->uploadedCur     = 0;
1089    tor->corruptPrev    += tor->corruptCur;
1090    tor->corruptCur      = 0;
1091
1092    tr_torrentUnlock( tor );
1093}
1094
1095void
1096tr_torrentSetHasPiece( tr_torrent *     tor,
1097                       tr_piece_index_t pieceIndex,
1098                       tr_bool          has )
1099{
1100    assert( tr_isTorrent( tor ) );
1101    assert( pieceIndex < tor->info.pieceCount );
1102
1103    if( has )
1104        tr_cpPieceAdd( &tor->completion, pieceIndex );
1105    else
1106        tr_cpPieceRem( &tor->completion, pieceIndex );
1107}
1108
1109/***
1110****
1111***/
1112
1113static void
1114freeTorrent( tr_torrent * tor )
1115{
1116    tr_torrent * t;
1117    tr_session *  session = tor->session;
1118    tr_info *    inf = &tor->info;
1119
1120    assert( tr_isTorrent( tor ) );
1121    assert( !tor->isRunning );
1122
1123    tr_globalLock( session );
1124
1125    tr_peerMgrRemoveTorrent( tor );
1126
1127    tr_cpDestruct( &tor->completion );
1128
1129    tr_rcDestruct( &tor->swarmSpeed );
1130
1131    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
1132    tr_trackerFree( tor->tracker );
1133    tor->tracker = NULL;
1134
1135    tr_bitfieldDestruct( &tor->checkedPieces );
1136
1137    tr_free( tor->downloadDir );
1138    tr_free( tor->peer_id );
1139
1140    if( tor == session->torrentList )
1141        session->torrentList = tor->next;
1142    else for( t = session->torrentList; t != NULL; t = t->next ) {
1143        if( t->next == tor ) {
1144            t->next = tor->next;
1145            break;
1146        }
1147    }
1148
1149    assert( session->torrentCount >= 1 );
1150    session->torrentCount--;
1151
1152    tr_bandwidthFree( tor->bandwidth );
1153
1154    tr_metainfoFree( inf );
1155    tr_free( tor );
1156
1157    tr_globalUnlock( session );
1158}
1159
1160/**
1161***  Start/Stop Callback
1162**/
1163
1164static void
1165checkAndStartImpl( void * vtor )
1166{
1167    tr_torrent * tor = vtor;
1168
1169    assert( tr_isTorrent( tor ) );
1170
1171    tr_globalLock( tor->session );
1172
1173    tor->isRunning = 1;
1174    *tor->errorString = '\0';
1175    tr_torrentResetTransferStats( tor );
1176    tor->completeness = tr_cpGetStatus( &tor->completion );
1177    tr_torrentSaveResume( tor );
1178    tor->startDate = time( NULL );
1179    tr_trackerStart( tor->tracker );
1180    tr_peerMgrStartTorrent( tor );
1181
1182    tr_globalUnlock( tor->session );
1183}
1184
1185static void
1186checkAndStartCB( tr_torrent * tor )
1187{
1188    assert( tr_isTorrent( tor ) );
1189    assert( tr_isSession( tor->session ) );
1190
1191    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1192}
1193
1194static void
1195torrentStart( tr_torrent * tor,
1196              int          reloadProgress )
1197{
1198    assert( tr_isTorrent( tor ) );
1199
1200    tr_globalLock( tor->session );
1201
1202    if( !tor->isRunning )
1203    {
1204        const int isVerifying = tr_verifyInProgress( tor );
1205
1206        if( !isVerifying && reloadProgress )
1207            tr_torrentLoadResume( tor, TR_FR_PROGRESS, NULL );
1208
1209        tor->isRunning = 1;
1210
1211        if( !isVerifying )
1212            tr_verifyAdd( tor, checkAndStartCB );
1213    }
1214
1215    tr_globalUnlock( tor->session );
1216}
1217
1218void
1219tr_torrentStart( tr_torrent * tor )
1220{
1221    if( tr_isTorrent( tor ) )
1222        torrentStart( tor, TRUE );
1223}
1224
1225static void
1226torrentRecheckDoneImpl( void * vtor )
1227{
1228    tr_torrent * tor = vtor;
1229
1230    assert( tr_isTorrent( tor ) );
1231    tr_torrentRecheckCompleteness( tor );
1232}
1233
1234static void
1235torrentRecheckDoneCB( tr_torrent * tor )
1236{
1237    assert( tr_isTorrent( tor ) );
1238
1239    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1240}
1241
1242void
1243tr_torrentVerify( tr_torrent * tor )
1244{
1245    assert( tr_isTorrent( tor ) );
1246
1247    tr_verifyRemove( tor );
1248
1249    tr_globalLock( tor->session );
1250
1251    tr_torrentUncheck( tor );
1252    tr_verifyAdd( tor, torrentRecheckDoneCB );
1253
1254    tr_globalUnlock( tor->session );
1255}
1256
1257static void
1258tr_torrentCloseLocalFiles( const tr_torrent * tor )
1259{
1260    tr_file_index_t i;
1261    struct evbuffer * buf = evbuffer_new( );
1262
1263    assert( tr_isTorrent( tor ) );
1264
1265    for( i=0; i<tor->info.fileCount; ++i )
1266    {
1267        const tr_file * file = &tor->info.files[i];
1268        evbuffer_drain( buf, EVBUFFER_LENGTH( buf ) );
1269        evbuffer_add_printf( buf, "%s%s%s", tor->downloadDir, TR_PATH_DELIMITER_STR, file->name );
1270        tr_fdFileClose( (const char*) EVBUFFER_DATA( buf ) );
1271    }
1272
1273    evbuffer_free( buf );
1274}
1275
1276
1277static void
1278stopTorrent( void * vtor )
1279{
1280    tr_torrent * tor = vtor;
1281
1282    assert( tr_isTorrent( tor ) );
1283
1284    tr_verifyRemove( tor );
1285    tr_peerMgrStopTorrent( tor );
1286    tr_trackerStop( tor->tracker );
1287
1288    tr_torrentCloseLocalFiles( tor );
1289}
1290
1291void
1292tr_torrentStop( tr_torrent * tor )
1293{
1294    if( tr_isTorrent( tor ) )
1295    {
1296        tr_globalLock( tor->session );
1297
1298        tor->isRunning = 0;
1299        if( !tor->isDeleting )
1300            tr_torrentSaveResume( tor );
1301        tr_runInEventThread( tor->session, stopTorrent, tor );
1302
1303        tr_globalUnlock( tor->session );
1304    }
1305}
1306
1307static void
1308closeTorrent( void * vtor )
1309{
1310    tr_torrent * tor = vtor;
1311
1312    assert( tr_isTorrent( tor ) );
1313
1314    tr_torrentSaveResume( tor );
1315    tor->isRunning = 0;
1316    stopTorrent( tor );
1317    if( tor->isDeleting )
1318    {
1319        tr_metainfoRemoveSaved( tor->session, &tor->info );
1320        tr_torrentRemoveResume( tor );
1321    }
1322    freeTorrent( tor );
1323}
1324
1325void
1326tr_torrentFree( tr_torrent * tor )
1327{
1328    if( tr_isTorrent( tor ) )
1329    {
1330        tr_session * session = tor->session;
1331        assert( tr_isSession( session ) );
1332        tr_globalLock( session );
1333
1334        tr_torrentClearCompletenessCallback( tor );
1335        tr_runInEventThread( session, closeTorrent, tor );
1336
1337        tr_globalUnlock( session );
1338    }
1339}
1340
1341void
1342tr_torrentRemove( tr_torrent * tor )
1343{
1344    assert( tr_isTorrent( tor ) );
1345
1346    tor->isDeleting = 1;
1347    tr_torrentFree( tor );
1348}
1349
1350/**
1351***  Completeness
1352**/
1353
1354static const char *
1355getCompletionString( int type )
1356{
1357    switch( type )
1358    {
1359        /* Translators: this is a minor point that's safe to skip over, but FYI:
1360           "Complete" and "Done" are specific, different terms in Transmission:
1361           "Complete" means we've downloaded every file in the torrent.
1362           "Done" means we're done downloading the files we wanted, but NOT all
1363           that exist */
1364        case TR_PARTIAL_SEED:
1365            return _( "Done" );
1366
1367        case TR_SEED:
1368            return _( "Complete" );
1369
1370        default:
1371            return _( "Incomplete" );
1372    }
1373}
1374
1375static void
1376fireCompletenessChange( tr_torrent       * tor,
1377                        tr_completeness    status )
1378{
1379    assert( tr_isTorrent( tor ) );
1380    assert( ( status == TR_LEECH )
1381         || ( status == TR_SEED )
1382         || ( status == TR_PARTIAL_SEED ) );
1383
1384    if( tor->completeness_func )
1385        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1386}
1387
1388void
1389tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1390                                   tr_torrent_completeness_func    func,
1391                                   void                          * user_data )
1392{
1393    assert( tr_isTorrent( tor ) );
1394
1395    tor->completeness_func = func;
1396    tor->completeness_func_user_data = user_data;
1397}
1398
1399void
1400tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1401                                    tr_torrent_ratio_limit_hit_func  func,
1402                                    void                           * user_data )
1403{
1404    assert( tr_isTorrent( tor ) );
1405
1406    tor->ratio_limit_hit_func = func;
1407    tor->ratio_limit_hit_func_user_data = user_data;
1408}
1409
1410void
1411tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1412{
1413    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1414}
1415
1416void
1417tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1418{
1419    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1420}
1421
1422void
1423tr_torrentRecheckCompleteness( tr_torrent * tor )
1424{
1425    tr_completeness completeness;
1426
1427    assert( tr_isTorrent( tor ) );
1428
1429    tr_torrentLock( tor );
1430
1431    completeness = tr_cpGetStatus( &tor->completion );
1432
1433    if( completeness != tor->completeness )
1434    {
1435        const int recentChange = tor->downloadedCur != 0;
1436
1437        if( recentChange )
1438        {
1439            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1440                      getCompletionString( tor->completeness ),
1441                      getCompletionString( completeness ) );
1442        }
1443
1444        tor->completeness = completeness;
1445        tr_torrentCloseLocalFiles( tor );
1446        fireCompletenessChange( tor, completeness );
1447
1448        if( recentChange && ( completeness == TR_SEED ) )
1449        {
1450            tr_trackerCompleted( tor->tracker );
1451
1452            tor->doneDate = time( NULL );
1453        }
1454
1455        tr_torrentSaveResume( tor );
1456    }
1457
1458    tr_torrentUnlock( tor );
1459}
1460
1461/**
1462***  File priorities
1463**/
1464
1465void
1466tr_torrentInitFilePriority( tr_torrent *    tor,
1467                            tr_file_index_t fileIndex,
1468                            tr_priority_t   priority )
1469{
1470    tr_piece_index_t i;
1471    tr_file *        file;
1472
1473    assert( tr_isTorrent( tor ) );
1474    assert( fileIndex < tor->info.fileCount );
1475    assert( priority == TR_PRI_LOW || priority == TR_PRI_NORMAL || priority == TR_PRI_HIGH );
1476
1477    file = &tor->info.files[fileIndex];
1478    file->priority = priority;
1479    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1480        tor->info.pieces[i].priority = calculatePiecePriority( tor, i,
1481                                                               fileIndex );
1482}
1483
1484void
1485tr_torrentSetFilePriorities( tr_torrent *      tor,
1486                             tr_file_index_t * files,
1487                             tr_file_index_t   fileCount,
1488                             tr_priority_t     priority )
1489{
1490    tr_file_index_t i;
1491
1492    assert( tr_isTorrent( tor ) );
1493
1494    tr_torrentLock( tor );
1495
1496    for( i = 0; i < fileCount; ++i )
1497        tr_torrentInitFilePriority( tor, files[i], priority );
1498
1499    tr_torrentSaveResume( tor );
1500    tr_torrentUnlock( tor );
1501}
1502
1503tr_priority_t
1504tr_torrentGetFilePriority( const tr_torrent * tor,
1505                           tr_file_index_t    file )
1506{
1507    tr_priority_t ret;
1508
1509    assert( tr_isTorrent( tor ) );
1510
1511    tr_torrentLock( tor );
1512    assert( tor );
1513    assert( file < tor->info.fileCount );
1514    ret = tor->info.files[file].priority;
1515    tr_torrentUnlock( tor );
1516
1517    return ret;
1518}
1519
1520tr_priority_t*
1521tr_torrentGetFilePriorities( const tr_torrent * tor )
1522{
1523    tr_file_index_t i;
1524    tr_priority_t * p;
1525
1526    assert( tr_isTorrent( tor ) );
1527
1528    tr_torrentLock( tor );
1529    p = tr_new0( tr_priority_t, tor->info.fileCount );
1530    for( i = 0; i < tor->info.fileCount; ++i )
1531        p[i] = tor->info.files[i].priority;
1532    tr_torrentUnlock( tor );
1533
1534    return p;
1535}
1536
1537/**
1538***  File DND
1539**/
1540
1541int
1542tr_torrentGetFileDL( const tr_torrent * tor,
1543                     tr_file_index_t    file )
1544{
1545    int doDownload;
1546
1547    assert( tr_isTorrent( tor ) );
1548
1549    tr_torrentLock( tor );
1550
1551    assert( file < tor->info.fileCount );
1552    doDownload = !tor->info.files[file].dnd;
1553
1554    tr_torrentUnlock( tor );
1555    return doDownload != 0;
1556}
1557
1558static void
1559setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1560{
1561    tr_file *        file;
1562    const int        dnd = !doDownload;
1563    tr_piece_index_t firstPiece, firstPieceDND;
1564    tr_piece_index_t lastPiece, lastPieceDND;
1565    tr_file_index_t  i;
1566
1567    assert( tr_isTorrent( tor ) );
1568
1569    file = &tor->info.files[fileIndex];
1570    file->dnd = dnd;
1571    firstPiece = file->firstPiece;
1572    lastPiece = file->lastPiece;
1573
1574    /* can't set the first piece to DND unless
1575       every file using that piece is DND */
1576    firstPieceDND = dnd;
1577    if( fileIndex > 0 )
1578    {
1579        for( i = fileIndex - 1; firstPieceDND; --i )
1580        {
1581            if( tor->info.files[i].lastPiece != firstPiece )
1582                break;
1583            firstPieceDND = tor->info.files[i].dnd;
1584            if( !i )
1585                break;
1586        }
1587    }
1588
1589    /* can't set the last piece to DND unless
1590       every file using that piece is DND */
1591    lastPieceDND = dnd;
1592    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1593    {
1594        if( tor->info.files[i].firstPiece != lastPiece )
1595            break;
1596        lastPieceDND = tor->info.files[i].dnd;
1597    }
1598
1599    if( firstPiece == lastPiece )
1600    {
1601        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1602    }
1603    else
1604    {
1605        tr_piece_index_t pp;
1606        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1607        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1608        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1609            tor->info.pieces[pp].dnd = dnd;
1610    }
1611}
1612
1613void
1614tr_torrentInitFileDLs( tr_torrent      * tor,
1615                       tr_file_index_t * files,
1616                       tr_file_index_t   fileCount,
1617                       tr_bool           doDownload )
1618{
1619    tr_file_index_t i;
1620
1621    assert( tr_isTorrent( tor ) );
1622
1623    tr_torrentLock( tor );
1624
1625    for( i=0; i<fileCount; ++i )
1626        setFileDND( tor, files[i], doDownload );
1627    tr_cpInvalidateDND( &tor->completion );
1628    tr_torrentCheckSeedRatio( tor );
1629
1630    tr_torrentUnlock( tor );
1631}
1632
1633void
1634tr_torrentSetFileDLs( tr_torrent *      tor,
1635                      tr_file_index_t * files,
1636                      tr_file_index_t   fileCount,
1637                      tr_bool           doDownload )
1638{
1639    assert( tr_isTorrent( tor ) );
1640
1641    tr_torrentLock( tor );
1642    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1643    tr_torrentSaveResume( tor );
1644    tr_torrentUnlock( tor );
1645}
1646
1647/***
1648****
1649***/
1650
1651void
1652tr_torrentSetPeerLimit( tr_torrent * tor,
1653                        uint16_t     maxConnectedPeers )
1654{
1655    assert( tr_isTorrent( tor ) );
1656
1657    tor->maxConnectedPeers = maxConnectedPeers;
1658}
1659
1660uint16_t
1661tr_torrentGetPeerLimit( const tr_torrent * tor )
1662{
1663    assert( tr_isTorrent( tor ) );
1664
1665    return tor->maxConnectedPeers;
1666}
1667
1668/***
1669****
1670***/
1671
1672tr_block_index_t
1673_tr_block( const tr_torrent * tor,
1674           tr_piece_index_t   index,
1675           uint32_t           offset )
1676{
1677    tr_block_index_t ret;
1678
1679    assert( tr_isTorrent( tor ) );
1680
1681    ret = index;
1682    ret *= ( tor->info.pieceSize / tor->blockSize );
1683    ret += offset / tor->blockSize;
1684    return ret;
1685}
1686
1687tr_bool
1688tr_torrentReqIsValid( const tr_torrent * tor,
1689                      tr_piece_index_t   index,
1690                      uint32_t           offset,
1691                      uint32_t           length )
1692{
1693    int err = 0;
1694
1695    assert( tr_isTorrent( tor ) );
1696
1697    if( index >= tor->info.pieceCount )
1698        err = 1;
1699    else if( length < 1 )
1700        err = 2;
1701    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1702        err = 3;
1703    else if( length > MAX_BLOCK_SIZE )
1704        err = 4;
1705    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1706        err = 5;
1707
1708    if( err ) fprintf( stderr, "index %lu offset %lu length %lu err %d\n",
1709                       (unsigned long)index, (unsigned long)offset,
1710                       (unsigned long)length,
1711                       err );
1712
1713    return !err;
1714}
1715
1716uint64_t
1717tr_pieceOffset( const tr_torrent * tor,
1718                tr_piece_index_t   index,
1719                uint32_t           offset,
1720                uint32_t           length )
1721{
1722    uint64_t ret;
1723
1724    assert( tr_isTorrent( tor ) );
1725
1726    ret = tor->info.pieceSize;
1727    ret *= index;
1728    ret += offset;
1729    ret += length;
1730    return ret;
1731}
1732
1733/***
1734****
1735***/
1736
1737void
1738tr_torrentSetPieceChecked( tr_torrent        * tor,
1739                           tr_piece_index_t    piece,
1740                           tr_bool             isChecked )
1741{
1742    assert( tr_isTorrent( tor ) );
1743
1744    if( isChecked )
1745        tr_bitfieldAdd( &tor->checkedPieces, piece );
1746    else
1747        tr_bitfieldRem( &tor->checkedPieces, piece );
1748}
1749
1750void
1751tr_torrentSetFileChecked( tr_torrent *    tor,
1752                          tr_file_index_t fileIndex,
1753                          tr_bool         isChecked )
1754{
1755    const tr_file *        file = &tor->info.files[fileIndex];
1756    const tr_piece_index_t begin = file->firstPiece;
1757    const tr_piece_index_t end = file->lastPiece + 1;
1758
1759    assert( tr_isTorrent( tor ) );
1760
1761    if( isChecked )
1762        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
1763    else
1764        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
1765}
1766
1767tr_bool
1768tr_torrentIsFileChecked( const tr_torrent * tor,
1769                         tr_file_index_t    fileIndex )
1770{
1771    const tr_file *        file = &tor->info.files[fileIndex];
1772    const tr_piece_index_t begin = file->firstPiece;
1773    const tr_piece_index_t end = file->lastPiece + 1;
1774    tr_piece_index_t       i;
1775    tr_bool                isChecked = TRUE;
1776
1777    assert( tr_isTorrent( tor ) );
1778
1779    for( i = begin; isChecked && i < end; ++i )
1780        if( !tr_torrentIsPieceChecked( tor, i ) )
1781            isChecked = FALSE;
1782
1783    return isChecked;
1784}
1785
1786void
1787tr_torrentUncheck( tr_torrent * tor )
1788{
1789    assert( tr_isTorrent( tor ) );
1790
1791    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
1792}
1793
1794int
1795tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1796{
1797    assert( tr_isTorrent( tor ) );
1798
1799    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
1800}
1801
1802time_t*
1803tr_torrentGetMTimes( const tr_torrent * tor,
1804                     size_t *           setme_n )
1805{
1806    size_t       i;
1807    const size_t n = tor->info.fileCount;
1808    time_t *     m = tr_new0( time_t, n );
1809
1810    assert( tr_isTorrent( tor ) );
1811
1812    for( i = 0; i < n; ++i )
1813    {
1814        struct stat sb;
1815        char * path = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
1816        if( !stat( path, &sb ) )
1817        {
1818#ifdef SYS_DARWIN
1819            m[i] = sb.st_mtimespec.tv_sec;
1820#else
1821            m[i] = sb.st_mtime;
1822#endif
1823        }
1824        tr_free( path );
1825    }
1826
1827    *setme_n = n;
1828    return m;
1829}
1830
1831/***
1832****
1833***/
1834
1835void
1836tr_torrentSetAnnounceList( tr_torrent *            tor,
1837                           const tr_tracker_info * trackers,
1838                           int                     trackerCount )
1839{
1840    tr_benc metainfo;
1841
1842    assert( tr_isTorrent( tor ) );
1843
1844    /* save to the .torrent file */
1845    if( !tr_bencLoadFile( tor->info.torrent, &metainfo ) )
1846    {
1847        int       i;
1848        int       prevTier = -1;
1849        tr_benc * tier = NULL;
1850        tr_benc * announceList;
1851        tr_info   tmpInfo;
1852
1853        /* remove the old fields */
1854        tr_bencDictRemove( &metainfo, "announce" );
1855        tr_bencDictRemove( &metainfo, "announce-list" );
1856
1857        /* add the new fields */
1858        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
1859        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
1860        for( i = 0; i < trackerCount; ++i ) {
1861            if( prevTier != trackers[i].tier ) {
1862                prevTier = trackers[i].tier;
1863                tier = tr_bencListAddList( announceList, 0 );
1864            }
1865            tr_bencListAddStr( tier, trackers[i].announce );
1866        }
1867
1868        /* try to parse it back again, to make sure it's good */
1869        memset( &tmpInfo, 0, sizeof( tr_info ) );
1870        if( !tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
1871        {
1872            /* it's good, so keep these new trackers and free the old ones */
1873
1874            tr_info swap;
1875            swap.trackers = tor->info.trackers;
1876            swap.trackerCount = tor->info.trackerCount;
1877            tor->info.trackers = tmpInfo.trackers;
1878            tor->info.trackerCount = tmpInfo.trackerCount;
1879            tmpInfo.trackers = swap.trackers;
1880            tmpInfo.trackerCount = swap.trackerCount;
1881
1882            tr_metainfoFree( &tmpInfo );
1883            tr_bencSaveFile( tor->info.torrent, &metainfo );
1884        }
1885
1886        /* cleanup */
1887        tr_bencFree( &metainfo );
1888    }
1889}
1890
1891/**
1892***
1893**/
1894
1895/** @deprecated this method will be removed in 1.40 */
1896void
1897tr_torrentSetAddedDate( tr_torrent * tor,
1898                        time_t       t )
1899{
1900    assert( tr_isTorrent( tor ) );
1901
1902    tor->addedDate = t;
1903}
1904
1905/** @deprecated this method will be removed in 1.40 */
1906void
1907tr_torrentSetActivityDate( tr_torrent * tor,
1908                           time_t       t )
1909{
1910    assert( tr_isTorrent( tor ) );
1911
1912    tor->activityDate = t;
1913}
1914
1915/** @deprecated this method will be removed in 1.40 */
1916void
1917tr_torrentSetDoneDate( tr_torrent * tor,
1918                       time_t       t )
1919{
1920    assert( tr_isTorrent( tor ) );
1921
1922    tor->doneDate = t;
1923}
1924
1925/**
1926***
1927**/
1928
1929uint64_t
1930tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
1931{
1932    const tr_file * it;
1933    const tr_file * end;
1934    struct stat sb;
1935    uint64_t bytesLeft = 0;
1936
1937    assert( tr_isTorrent( tor ) );
1938
1939    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
1940    {
1941        if( !it->dnd )
1942        {
1943            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
1944
1945            bytesLeft += it->length;
1946
1947            if( !stat( path, &sb )
1948                    && S_ISREG( sb.st_mode )
1949                    && ( (uint64_t)sb.st_size <= it->length ) )
1950                bytesLeft -= sb.st_size;
1951
1952            tr_free( path );
1953        }
1954    }
1955
1956    return bytesLeft;
1957}
1958
1959/****
1960*****  Removing the torrent's local data
1961****/
1962
1963static int
1964vstrcmp( const void * a, const void * b )
1965{
1966    return strcmp( a, b );
1967}
1968
1969static int
1970compareLongestFirst( const void * a, const void * b )
1971{
1972    const size_t alen = strlen( a );
1973    const size_t blen = strlen( b );
1974
1975    if( alen != blen )
1976        return alen > blen ? -1 : 1;
1977
1978    return vstrcmp( a, b );
1979}
1980
1981static void
1982addDirtyFile( const char  * root,
1983              const char  * filename,
1984              tr_ptrArray * dirtyFolders )
1985{
1986    char * dir = tr_dirname( filename );
1987
1988    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
1989    while (     ( dir != NULL )
1990             && ( strlen( root ) <= strlen( dir ) )
1991             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
1992    {
1993        char * tmp;
1994        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
1995
1996        tmp = tr_dirname( dir );
1997        tr_free( dir );
1998        dir = tmp;
1999    }
2000
2001    tr_free( dir );
2002}
2003
2004static void
2005walkLocalData( const tr_torrent * tor,
2006               const char       * root,
2007               const char       * dir,
2008               const char       * base,
2009               tr_ptrArray      * torrentFiles,
2010               tr_ptrArray      * folders,
2011               tr_ptrArray      * dirtyFolders )
2012{
2013    int i;
2014    struct stat sb;
2015    char * buf;
2016
2017    assert( tr_isTorrent( tor ) );
2018
2019    buf = tr_buildPath( dir, base, NULL );
2020    i = stat( buf, &sb );
2021    if( !i )
2022    {
2023        DIR * odir = NULL;
2024
2025        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2026        {
2027            struct dirent *d;
2028            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2029            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2030                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2031                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2032            closedir( odir );
2033        }
2034        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2035        {
2036            const char * sub = buf + strlen( tor->downloadDir ) + strlen( TR_PATH_DELIMITER_STR );
2037            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2038            if( !isTorrentFile )
2039                addDirtyFile( root, buf, dirtyFolders );
2040        }
2041    }
2042
2043    tr_free( buf );
2044}
2045
2046static void
2047deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2048{
2049    int i, n;
2050    char ** s;
2051    tr_file_index_t f;
2052    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2053    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2054    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2055
2056    const char * firstFile = tor->info.files[0].name;
2057    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2058    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2059    char * root = tr_buildPath( tor->downloadDir, tmp, NULL );
2060
2061    assert( tr_isTorrent( tor ) );
2062
2063    for( f=0; f<tor->info.fileCount; ++f )
2064        tr_ptrArrayInsertSorted( &torrentFiles, tor->info.files[f].name, vstrcmp );
2065
2066    /* build the set of folders and dirtyFolders */
2067    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2068
2069    /* try to remove entire folders first, so that the recycle bin will be tidy */
2070    s = (char**) tr_ptrArrayPeek( &folders, &n );
2071    for( i=0; i<n; ++i )
2072        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2073            fileFunc( s[i] );
2074
2075    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2076    for( f=0; f<tor->info.fileCount; ++f ) {
2077        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
2078        fileFunc( path );
2079        tr_free( path );
2080    }
2081
2082    /* Now clean out the directories left empty from the previous step.
2083     * Work from deepest to shallowest s.t. lower folders
2084     * won't prevent the upper folders from being deleted */
2085    {
2086        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2087        s = (char**) tr_ptrArrayPeek( &folders, &n );
2088        for( i=0; i<n; ++i )
2089            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2090                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2091        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2092        for( i=0; i<n; ++i )
2093            fileFunc( s[i] );
2094        tr_ptrArrayDestruct( &cleanFolders, NULL );
2095    }
2096
2097    /* cleanup */
2098    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2099    tr_ptrArrayDestruct( &folders, tr_free );
2100    tr_ptrArrayDestruct( &torrentFiles, NULL );
2101    tr_free( root );
2102    tr_free( tmp );
2103}
2104
2105void
2106tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2107{
2108    assert( tr_isTorrent( tor ) );
2109
2110    if( fileFunc == NULL )
2111        fileFunc = remove;
2112
2113    /* close all the files because we're about to delete them */
2114    tr_torrentCloseLocalFiles( tor );
2115
2116    if( tor->info.fileCount > 1 )
2117        deleteLocalData( tor, fileFunc );
2118    else {
2119        /* torrent only has one file */
2120        char * path = tr_buildPath( tor->downloadDir, tor->info.files[0].name, NULL );
2121        fileFunc( path );
2122        tr_free( path );
2123    }
2124}
2125
2126/***
2127****
2128***/
2129
2130void
2131tr_torrentCheckSeedRatio( tr_torrent * tor )
2132{
2133    double seedRatio;
2134
2135    assert( tr_isTorrent( tor ) );
2136
2137    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2138    if( tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2139    {
2140        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2141        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2142        double ratio;
2143
2144        /* maybe we're the initial seeder and never downloaded anything... */
2145        if( down == 0 )
2146            down = tr_cpHaveValid( &tor->completion );
2147
2148        ratio = tr_getRatio( up, down );
2149
2150        if( ratio >= seedRatio )
2151        {
2152            tr_torrentStop( tor );
2153
2154            /* set to no ratio limit to allow easy restarting */
2155            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2156
2157            /* maybe notify the client */
2158            if( tor->ratio_limit_hit_func != NULL )
2159                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2160        }
2161    }
2162}
Note: See TracBrowser for help on using the repository browser.