source: trunk/libtransmission/torrent.c @ 8132

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

(trunk)

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