source: trunk/libtransmission/torrent.c @ 8021

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

(trunk) libT and gtk+ parts for #1889: per-torrent vs. global speed limit confusion

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