source: trunk/libtransmission/torrent.c @ 8592

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

(trunk libT) add a bunch of comments denoting where the libevent 2.0 changes will go

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