source: trunk/libtransmission/torrent.c @ 8683

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

(trunk) #1864: Tracker not found (404) when a check of local file is done.

  • Property svn:keywords set to Date Rev Author Id
File size: 61.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 8683 2009-06-13 17:11:46Z 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        tr_verifyRemove( tor );
1269
1270        if( reloadProgress )
1271            tr_torrentLoadResume( tor, TR_FR_PROGRESS, NULL );
1272
1273        tor->isRunning = 1;
1274        tr_verifyAdd( tor, checkAndStartCB );
1275    }
1276
1277    tr_globalUnlock( tor->session );
1278}
1279
1280void
1281tr_torrentStart( tr_torrent * tor )
1282{
1283    if( tr_isTorrent( tor ) )
1284        torrentStart( tor, TRUE );
1285}
1286
1287static void
1288torrentRecheckDoneImpl( void * vtor )
1289{
1290    tr_torrent * tor = vtor;
1291
1292    assert( tr_isTorrent( tor ) );
1293    tr_torrentRecheckCompleteness( tor );
1294
1295    if( tor->startAfterVerify )
1296    {
1297        tor->startAfterVerify = FALSE;
1298        tr_torrentStart( tor );
1299    }
1300}
1301
1302static void
1303torrentRecheckDoneCB( tr_torrent * tor )
1304{
1305    assert( tr_isTorrent( tor ) );
1306
1307    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1308}
1309
1310void
1311tr_torrentVerify( tr_torrent * tor )
1312{
1313    assert( tr_isTorrent( tor ) );
1314    tr_globalLock( tor->session );
1315
1316    /* if the torrent's already being verified, stop it */
1317    tr_verifyRemove( tor );
1318
1319    /* if the torrent's running, stop it & set the restart-after-verify flag */
1320    if( tor->isRunning ) {
1321        tr_torrentStop( tor );
1322        tor->startAfterVerify = TRUE;
1323    }
1324
1325    /* add the torrent to the recheck queue */
1326    tr_torrentUncheck( tor );
1327    tr_verifyAdd( tor, torrentRecheckDoneCB );
1328
1329    tr_globalUnlock( tor->session );
1330}
1331
1332static void
1333tr_torrentCloseLocalFiles( const tr_torrent * tor )
1334{
1335    tr_file_index_t i;
1336    struct evbuffer * buf = evbuffer_new( );
1337
1338    assert( tr_isTorrent( tor ) );
1339
1340    /* FIXME(libevent2) we're just using the evbuffer to build a key here anyway.
1341       so we do (tor->info.fileCount * fd.openFileLimit) strcmps for these keys. :/
1342       it would be more efficient to remove this code altogether and
1343       add "int torrentId;" to "struct tr_openfile", and a new function
1344       tr_fdCloseTorrentFiles( tr_session*, int torrentId ) */
1345    for( i=0; i<tor->info.fileCount; ++i )
1346    {
1347        const tr_file * file = &tor->info.files[i];
1348        evbuffer_drain( buf, EVBUFFER_LENGTH( buf ) );
1349        evbuffer_add_printf( buf, "%s%s%s", tor->downloadDir, TR_PATH_DELIMITER_STR, file->name );
1350        tr_fdFileClose( (const char*) EVBUFFER_DATA( buf ) );
1351    }
1352
1353    evbuffer_free( buf );
1354}
1355
1356static void
1357stopTorrent( void * vtor )
1358{
1359    tr_torrent * tor = vtor;
1360
1361    assert( tr_isTorrent( tor ) );
1362
1363    tr_verifyRemove( tor );
1364    tr_peerMgrStopTorrent( tor );
1365    tr_trackerStop( tor->tracker );
1366
1367    tr_torrentCloseLocalFiles( tor );
1368}
1369
1370void
1371tr_torrentStop( tr_torrent * tor )
1372{
1373    assert( tr_isTorrent( tor ) );
1374
1375    if( tr_isTorrent( tor ) )
1376    {
1377        tr_globalLock( tor->session );
1378
1379        tor->isRunning = 0;
1380        if( !tor->isDeleting )
1381            tr_torrentSaveResume( tor );
1382        tr_runInEventThread( tor->session, stopTorrent, tor );
1383
1384        tr_globalUnlock( tor->session );
1385    }
1386}
1387
1388static void
1389closeTorrent( void * vtor )
1390{
1391    tr_benc * d;
1392    tr_torrent * tor = vtor;
1393
1394    assert( tr_isTorrent( tor ) );
1395
1396    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1397    tr_bencDictAddInt( d, "id", tor->uniqueId );
1398    tr_bencDictAddInt( d, "date", time( NULL ) );
1399
1400    tr_torrentSaveResume( tor );
1401    tor->isRunning = 0;
1402    stopTorrent( tor );
1403    if( tor->isDeleting )
1404    {
1405        tr_metainfoRemoveSaved( tor->session, &tor->info );
1406        tr_torrentRemoveResume( tor );
1407    }
1408    freeTorrent( tor );
1409}
1410
1411void
1412tr_torrentFree( tr_torrent * tor )
1413{
1414    if( tr_isTorrent( tor ) )
1415    {
1416        tr_session * session = tor->session;
1417        assert( tr_isSession( session ) );
1418        tr_globalLock( session );
1419
1420        tr_torrentClearCompletenessCallback( tor );
1421        tr_runInEventThread( session, closeTorrent, tor );
1422
1423        tr_globalUnlock( session );
1424    }
1425}
1426
1427void
1428tr_torrentRemove( tr_torrent * tor )
1429{
1430    assert( tr_isTorrent( tor ) );
1431
1432    tor->isDeleting = 1;
1433    tr_torrentFree( tor );
1434}
1435
1436/**
1437***  Completeness
1438**/
1439
1440static const char *
1441getCompletionString( int type )
1442{
1443    switch( type )
1444    {
1445        /* Translators: this is a minor point that's safe to skip over, but FYI:
1446           "Complete" and "Done" are specific, different terms in Transmission:
1447           "Complete" means we've downloaded every file in the torrent.
1448           "Done" means we're done downloading the files we wanted, but NOT all
1449           that exist */
1450        case TR_PARTIAL_SEED:
1451            return _( "Done" );
1452
1453        case TR_SEED:
1454            return _( "Complete" );
1455
1456        default:
1457            return _( "Incomplete" );
1458    }
1459}
1460
1461static void
1462fireCompletenessChange( tr_torrent       * tor,
1463                        tr_completeness    status )
1464{
1465    assert( tr_isTorrent( tor ) );
1466    assert( ( status == TR_LEECH )
1467         || ( status == TR_SEED )
1468         || ( status == TR_PARTIAL_SEED ) );
1469
1470    if( tor->completeness_func )
1471        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1472}
1473
1474void
1475tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1476                                   tr_torrent_completeness_func    func,
1477                                   void                          * user_data )
1478{
1479    assert( tr_isTorrent( tor ) );
1480
1481    tor->completeness_func = func;
1482    tor->completeness_func_user_data = user_data;
1483}
1484
1485void
1486tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1487                                    tr_torrent_ratio_limit_hit_func  func,
1488                                    void                           * user_data )
1489{
1490    assert( tr_isTorrent( tor ) );
1491
1492    tor->ratio_limit_hit_func = func;
1493    tor->ratio_limit_hit_func_user_data = user_data;
1494}
1495
1496void
1497tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1498{
1499    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1500}
1501
1502void
1503tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1504{
1505    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1506}
1507
1508void
1509tr_torrentRecheckCompleteness( tr_torrent * tor )
1510{
1511    tr_completeness completeness;
1512
1513    assert( tr_isTorrent( tor ) );
1514
1515    tr_torrentLock( tor );
1516
1517    completeness = tr_cpGetStatus( &tor->completion );
1518
1519    if( completeness != tor->completeness )
1520    {
1521        const int recentChange = tor->downloadedCur != 0;
1522
1523        if( recentChange )
1524        {
1525            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1526                      getCompletionString( tor->completeness ),
1527                      getCompletionString( completeness ) );
1528        }
1529
1530        tor->completeness = completeness;
1531        tor->needsSeedRatioCheck = TRUE;
1532        tr_torrentCloseLocalFiles( tor );
1533        fireCompletenessChange( tor, completeness );
1534
1535        if( recentChange && ( completeness == TR_SEED ) )
1536        {
1537            tr_trackerCompleted( tor->tracker );
1538
1539            tor->doneDate = tor->anyDate = time( NULL );
1540        }
1541
1542        tr_torrentSaveResume( tor );
1543    }
1544
1545    tr_torrentUnlock( tor );
1546}
1547
1548/**
1549***  File priorities
1550**/
1551
1552void
1553tr_torrentInitFilePriority( tr_torrent *    tor,
1554                            tr_file_index_t fileIndex,
1555                            tr_priority_t   priority )
1556{
1557    tr_piece_index_t i;
1558    tr_file *        file;
1559
1560    assert( tr_isTorrent( tor ) );
1561    assert( fileIndex < tor->info.fileCount );
1562    assert( tr_isPriority( priority ) );
1563
1564    file = &tor->info.files[fileIndex];
1565    file->priority = priority;
1566    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1567        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1568}
1569
1570void
1571tr_torrentSetFilePriorities( tr_torrent *      tor,
1572                             tr_file_index_t * files,
1573                             tr_file_index_t   fileCount,
1574                             tr_priority_t     priority )
1575{
1576    tr_file_index_t i;
1577
1578    assert( tr_isTorrent( tor ) );
1579
1580    tr_torrentLock( tor );
1581
1582    for( i = 0; i < fileCount; ++i )
1583        tr_torrentInitFilePriority( tor, files[i], priority );
1584
1585    tr_torrentSaveResume( tor );
1586    tr_torrentUnlock( tor );
1587}
1588
1589tr_priority_t
1590tr_torrentGetFilePriority( const tr_torrent * tor,
1591                           tr_file_index_t    file )
1592{
1593    tr_priority_t ret;
1594
1595    assert( tr_isTorrent( tor ) );
1596
1597    tr_torrentLock( tor );
1598    assert( tor );
1599    assert( file < tor->info.fileCount );
1600    ret = tor->info.files[file].priority;
1601    tr_torrentUnlock( tor );
1602
1603    return ret;
1604}
1605
1606tr_priority_t*
1607tr_torrentGetFilePriorities( const tr_torrent * tor )
1608{
1609    tr_file_index_t i;
1610    tr_priority_t * p;
1611
1612    assert( tr_isTorrent( tor ) );
1613
1614    tr_torrentLock( tor );
1615    p = tr_new0( tr_priority_t, tor->info.fileCount );
1616    for( i = 0; i < tor->info.fileCount; ++i )
1617        p[i] = tor->info.files[i].priority;
1618    tr_torrentUnlock( tor );
1619
1620    return p;
1621}
1622
1623/**
1624***  File DND
1625**/
1626
1627int
1628tr_torrentGetFileDL( const tr_torrent * tor,
1629                     tr_file_index_t    file )
1630{
1631    int doDownload;
1632
1633    assert( tr_isTorrent( tor ) );
1634
1635    tr_torrentLock( tor );
1636
1637    assert( file < tor->info.fileCount );
1638    doDownload = !tor->info.files[file].dnd;
1639
1640    tr_torrentUnlock( tor );
1641    return doDownload != 0;
1642}
1643
1644static void
1645setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1646{
1647    tr_file *        file;
1648    const int        dnd = !doDownload;
1649    tr_piece_index_t firstPiece, firstPieceDND;
1650    tr_piece_index_t lastPiece, lastPieceDND;
1651    tr_file_index_t  i;
1652
1653    assert( tr_isTorrent( tor ) );
1654
1655    file = &tor->info.files[fileIndex];
1656    file->dnd = dnd;
1657    firstPiece = file->firstPiece;
1658    lastPiece = file->lastPiece;
1659
1660    /* can't set the first piece to DND unless
1661       every file using that piece is DND */
1662    firstPieceDND = dnd;
1663    if( fileIndex > 0 )
1664    {
1665        for( i = fileIndex - 1; firstPieceDND; --i )
1666        {
1667            if( tor->info.files[i].lastPiece != firstPiece )
1668                break;
1669            firstPieceDND = tor->info.files[i].dnd;
1670            if( !i )
1671                break;
1672        }
1673    }
1674
1675    /* can't set the last piece to DND unless
1676       every file using that piece is DND */
1677    lastPieceDND = dnd;
1678    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1679    {
1680        if( tor->info.files[i].firstPiece != lastPiece )
1681            break;
1682        lastPieceDND = tor->info.files[i].dnd;
1683    }
1684
1685    if( firstPiece == lastPiece )
1686    {
1687        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1688    }
1689    else
1690    {
1691        tr_piece_index_t pp;
1692        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1693        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1694        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1695            tor->info.pieces[pp].dnd = dnd;
1696    }
1697}
1698
1699void
1700tr_torrentInitFileDLs( tr_torrent      * tor,
1701                       tr_file_index_t * files,
1702                       tr_file_index_t   fileCount,
1703                       tr_bool           doDownload )
1704{
1705    tr_file_index_t i;
1706
1707    assert( tr_isTorrent( tor ) );
1708
1709    tr_torrentLock( tor );
1710
1711    for( i=0; i<fileCount; ++i )
1712        setFileDND( tor, files[i], doDownload );
1713    tr_cpInvalidateDND( &tor->completion );
1714    tor->needsSeedRatioCheck = TRUE;
1715
1716    tr_torrentUnlock( tor );
1717}
1718
1719void
1720tr_torrentSetFileDLs( tr_torrent *      tor,
1721                      tr_file_index_t * files,
1722                      tr_file_index_t   fileCount,
1723                      tr_bool           doDownload )
1724{
1725    assert( tr_isTorrent( tor ) );
1726
1727    tr_torrentLock( tor );
1728    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1729    tr_torrentSaveResume( tor );
1730    tr_torrentUnlock( tor );
1731}
1732
1733/***
1734****
1735***/
1736
1737tr_priority_t
1738tr_torrentGetPriority( const tr_torrent * tor )
1739{
1740    assert( tr_isTorrent( tor ) );
1741
1742    return tor->bandwidth->priority;
1743}
1744
1745void
1746tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1747{
1748    assert( tr_isTorrent( tor ) );
1749    assert( tr_isPriority( priority ) );
1750
1751    tor->bandwidth->priority = priority;
1752}
1753
1754/***
1755****
1756***/
1757
1758void
1759tr_torrentSetPeerLimit( tr_torrent * tor,
1760                        uint16_t     maxConnectedPeers )
1761{
1762    assert( tr_isTorrent( tor ) );
1763
1764    tor->maxConnectedPeers = maxConnectedPeers;
1765}
1766
1767uint16_t
1768tr_torrentGetPeerLimit( const tr_torrent * tor )
1769{
1770    assert( tr_isTorrent( tor ) );
1771
1772    return tor->maxConnectedPeers;
1773}
1774
1775/***
1776****
1777***/
1778
1779tr_block_index_t
1780_tr_block( const tr_torrent * tor,
1781           tr_piece_index_t   index,
1782           uint32_t           offset )
1783{
1784    tr_block_index_t ret;
1785
1786    assert( tr_isTorrent( tor ) );
1787
1788    ret = index;
1789    ret *= ( tor->info.pieceSize / tor->blockSize );
1790    ret += offset / tor->blockSize;
1791    return ret;
1792}
1793
1794tr_bool
1795tr_torrentReqIsValid( const tr_torrent * tor,
1796                      tr_piece_index_t   index,
1797                      uint32_t           offset,
1798                      uint32_t           length )
1799{
1800    int err = 0;
1801
1802    assert( tr_isTorrent( tor ) );
1803
1804    if( index >= tor->info.pieceCount )
1805        err = 1;
1806    else if( length < 1 )
1807        err = 2;
1808    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1809        err = 3;
1810    else if( length > MAX_BLOCK_SIZE )
1811        err = 4;
1812    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1813        err = 5;
1814
1815    if( err ) fprintf( stderr, "index %lu offset %lu length %lu err %d\n",
1816                       (unsigned long)index, (unsigned long)offset,
1817                       (unsigned long)length,
1818                       err );
1819
1820    return !err;
1821}
1822
1823uint64_t
1824tr_pieceOffset( const tr_torrent * tor,
1825                tr_piece_index_t   index,
1826                uint32_t           offset,
1827                uint32_t           length )
1828{
1829    uint64_t ret;
1830
1831    assert( tr_isTorrent( tor ) );
1832
1833    ret = tor->info.pieceSize;
1834    ret *= index;
1835    ret += offset;
1836    ret += length;
1837    return ret;
1838}
1839
1840/***
1841****
1842***/
1843
1844void
1845tr_torrentSetPieceChecked( tr_torrent        * tor,
1846                           tr_piece_index_t    piece,
1847                           tr_bool             isChecked )
1848{
1849    assert( tr_isTorrent( tor ) );
1850
1851    if( isChecked )
1852        tr_bitfieldAdd( &tor->checkedPieces, piece );
1853    else
1854        tr_bitfieldRem( &tor->checkedPieces, piece );
1855}
1856
1857void
1858tr_torrentSetFileChecked( tr_torrent *    tor,
1859                          tr_file_index_t fileIndex,
1860                          tr_bool         isChecked )
1861{
1862    const tr_file *        file = &tor->info.files[fileIndex];
1863    const tr_piece_index_t begin = file->firstPiece;
1864    const tr_piece_index_t end = file->lastPiece + 1;
1865
1866    assert( tr_isTorrent( tor ) );
1867
1868    if( isChecked )
1869        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
1870    else
1871        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
1872}
1873
1874tr_bool
1875tr_torrentIsFileChecked( const tr_torrent * tor,
1876                         tr_file_index_t    fileIndex )
1877{
1878    const tr_file *        file = &tor->info.files[fileIndex];
1879    const tr_piece_index_t begin = file->firstPiece;
1880    const tr_piece_index_t end = file->lastPiece + 1;
1881    tr_piece_index_t       i;
1882    tr_bool                isChecked = TRUE;
1883
1884    assert( tr_isTorrent( tor ) );
1885
1886    for( i = begin; isChecked && i < end; ++i )
1887        if( !tr_torrentIsPieceChecked( tor, i ) )
1888            isChecked = FALSE;
1889
1890    return isChecked;
1891}
1892
1893void
1894tr_torrentUncheck( tr_torrent * tor )
1895{
1896    assert( tr_isTorrent( tor ) );
1897
1898    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
1899}
1900
1901int
1902tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1903{
1904    assert( tr_isTorrent( tor ) );
1905
1906    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
1907}
1908
1909time_t*
1910tr_torrentGetMTimes( const tr_torrent * tor,
1911                     size_t *           setme_n )
1912{
1913    size_t       i;
1914    const size_t n = tor->info.fileCount;
1915    time_t *     m = tr_new0( time_t, n );
1916
1917    assert( tr_isTorrent( tor ) );
1918
1919    for( i = 0; i < n; ++i )
1920    {
1921        struct stat sb;
1922        char * path = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
1923        if( !stat( path, &sb ) )
1924        {
1925#ifdef SYS_DARWIN
1926            m[i] = sb.st_mtimespec.tv_sec;
1927#else
1928            m[i] = sb.st_mtime;
1929#endif
1930        }
1931        tr_free( path );
1932    }
1933
1934    *setme_n = n;
1935    return m;
1936}
1937
1938/***
1939****
1940***/
1941
1942void
1943tr_torrentSetAnnounceList( tr_torrent *            tor,
1944                           const tr_tracker_info * trackers,
1945                           int                     trackerCount )
1946{
1947    tr_benc metainfo;
1948
1949    assert( tr_isTorrent( tor ) );
1950
1951    /* save to the .torrent file */
1952    if( !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
1953    {
1954        int       i;
1955        int       prevTier = -1;
1956        tr_benc * tier = NULL;
1957        tr_benc * announceList;
1958        tr_info   tmpInfo;
1959
1960        /* remove the old fields */
1961        tr_bencDictRemove( &metainfo, "announce" );
1962        tr_bencDictRemove( &metainfo, "announce-list" );
1963
1964        /* add the new fields */
1965        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
1966        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
1967        for( i = 0; i < trackerCount; ++i ) {
1968            if( prevTier != trackers[i].tier ) {
1969                prevTier = trackers[i].tier;
1970                tier = tr_bencListAddList( announceList, 0 );
1971            }
1972            tr_bencListAddStr( tier, trackers[i].announce );
1973        }
1974
1975        /* try to parse it back again, to make sure it's good */
1976        memset( &tmpInfo, 0, sizeof( tr_info ) );
1977        if( !tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
1978        {
1979            /* it's good, so keep these new trackers and free the old ones */
1980
1981            tr_info swap;
1982            swap.trackers = tor->info.trackers;
1983            swap.trackerCount = tor->info.trackerCount;
1984            tor->info.trackers = tmpInfo.trackers;
1985            tor->info.trackerCount = tmpInfo.trackerCount;
1986            tmpInfo.trackers = swap.trackers;
1987            tmpInfo.trackerCount = swap.trackerCount;
1988
1989            tr_metainfoFree( &tmpInfo );
1990            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
1991        }
1992
1993        /* cleanup */
1994        tr_bencFree( &metainfo );
1995    }
1996}
1997
1998/**
1999***
2000**/
2001
2002void
2003tr_torrentSetAddedDate( tr_torrent * tor,
2004                        time_t       t )
2005{
2006    assert( tr_isTorrent( tor ) );
2007
2008    tor->addedDate = t;
2009    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2010}
2011
2012void
2013tr_torrentSetActivityDate( tr_torrent * tor,
2014                           time_t       t )
2015{
2016    assert( tr_isTorrent( tor ) );
2017
2018    tor->activityDate = t;
2019    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2020}
2021
2022void
2023tr_torrentSetDoneDate( tr_torrent * tor,
2024                       time_t       t )
2025{
2026    assert( tr_isTorrent( tor ) );
2027
2028    tor->doneDate = t;
2029    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2030}
2031
2032/**
2033***
2034**/
2035
2036uint64_t
2037tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2038{
2039    const tr_file * it;
2040    const tr_file * end;
2041    struct stat sb;
2042    uint64_t bytesLeft = 0;
2043
2044    assert( tr_isTorrent( tor ) );
2045
2046    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
2047    {
2048        if( !it->dnd )
2049        {
2050            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
2051
2052            bytesLeft += it->length;
2053
2054            if( !stat( path, &sb )
2055                    && S_ISREG( sb.st_mode )
2056                    && ( (uint64_t)sb.st_size <= it->length ) )
2057                bytesLeft -= sb.st_size;
2058
2059            tr_free( path );
2060        }
2061    }
2062
2063    return bytesLeft;
2064}
2065
2066/****
2067*****  Removing the torrent's local data
2068****/
2069
2070static int
2071vstrcmp( const void * a, const void * b )
2072{
2073    return strcmp( a, b );
2074}
2075
2076static int
2077compareLongestFirst( const void * a, const void * b )
2078{
2079    const size_t alen = strlen( a );
2080    const size_t blen = strlen( b );
2081
2082    if( alen != blen )
2083        return alen > blen ? -1 : 1;
2084
2085    return vstrcmp( a, b );
2086}
2087
2088static void
2089addDirtyFile( const char  * root,
2090              const char  * filename,
2091              tr_ptrArray * dirtyFolders )
2092{
2093    char * dir = tr_dirname( filename );
2094
2095    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2096    while (     ( dir != NULL )
2097             && ( strlen( root ) <= strlen( dir ) )
2098             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2099    {
2100        char * tmp;
2101        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2102
2103        tmp = tr_dirname( dir );
2104        tr_free( dir );
2105        dir = tmp;
2106    }
2107
2108    tr_free( dir );
2109}
2110
2111static void
2112walkLocalData( const tr_torrent * tor,
2113               const char       * root,
2114               const char       * dir,
2115               const char       * base,
2116               tr_ptrArray      * torrentFiles,
2117               tr_ptrArray      * folders,
2118               tr_ptrArray      * dirtyFolders )
2119{
2120    int i;
2121    struct stat sb;
2122    char * buf;
2123
2124    assert( tr_isTorrent( tor ) );
2125
2126    buf = tr_buildPath( dir, base, NULL );
2127    i = stat( buf, &sb );
2128    if( !i )
2129    {
2130        DIR * odir = NULL;
2131
2132        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2133        {
2134            struct dirent *d;
2135            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2136            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2137                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2138                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2139            closedir( odir );
2140        }
2141        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2142        {
2143            const char * sub = buf + strlen( tor->downloadDir ) + strlen( TR_PATH_DELIMITER_STR );
2144            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2145            if( !isTorrentFile )
2146                addDirtyFile( root, buf, dirtyFolders );
2147        }
2148    }
2149
2150    tr_free( buf );
2151}
2152
2153static void
2154deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2155{
2156    int i, n;
2157    char ** s;
2158    tr_file_index_t f;
2159    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2160    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2161    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2162
2163    const char * firstFile = tor->info.files[0].name;
2164    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2165    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2166    char * root = tr_buildPath( tor->downloadDir, tmp, NULL );
2167
2168    assert( tr_isTorrent( tor ) );
2169
2170    for( f=0; f<tor->info.fileCount; ++f )
2171        tr_ptrArrayInsertSorted( &torrentFiles, tor->info.files[f].name, vstrcmp );
2172
2173    /* build the set of folders and dirtyFolders */
2174    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2175
2176    /* try to remove entire folders first, so that the recycle bin will be tidy */
2177    s = (char**) tr_ptrArrayPeek( &folders, &n );
2178    for( i=0; i<n; ++i )
2179        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2180            fileFunc( s[i] );
2181
2182    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2183    for( f=0; f<tor->info.fileCount; ++f ) {
2184        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
2185        fileFunc( path );
2186        tr_free( path );
2187    }
2188
2189    /* Now clean out the directories left empty from the previous step.
2190     * Work from deepest to shallowest s.t. lower folders
2191     * won't prevent the upper folders from being deleted */
2192    {
2193        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2194        s = (char**) tr_ptrArrayPeek( &folders, &n );
2195        for( i=0; i<n; ++i )
2196            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2197                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2198        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2199        for( i=0; i<n; ++i )
2200            fileFunc( s[i] );
2201        tr_ptrArrayDestruct( &cleanFolders, NULL );
2202    }
2203
2204    /* cleanup */
2205    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2206    tr_ptrArrayDestruct( &folders, tr_free );
2207    tr_ptrArrayDestruct( &torrentFiles, NULL );
2208    tr_free( root );
2209    tr_free( tmp );
2210}
2211
2212void
2213tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2214{
2215    assert( tr_isTorrent( tor ) );
2216
2217    if( fileFunc == NULL )
2218        fileFunc = remove;
2219
2220    /* close all the files because we're about to delete them */
2221    tr_torrentCloseLocalFiles( tor );
2222
2223    if( tor->info.fileCount > 1 )
2224        deleteLocalData( tor, fileFunc );
2225    else {
2226        /* torrent only has one file */
2227        char * path = tr_buildPath( tor->downloadDir, tor->info.files[0].name, NULL );
2228        fileFunc( path );
2229        tr_free( path );
2230    }
2231}
2232
2233/***
2234****
2235***/
2236
2237struct LocationData
2238{
2239    tr_bool move_from_old_location;
2240    int * setme_state;
2241    double * setme_progress;
2242    char * location;
2243    tr_torrent * tor;
2244};
2245
2246static void
2247setLocation( void * vdata )
2248{
2249    int err = 0;
2250    struct LocationData * data = vdata;
2251    tr_torrent * tor = data->tor;
2252    const tr_bool do_move = data->move_from_old_location;
2253    const char * location = data->location;
2254    double bytesHandled = 0;
2255
2256    assert( tr_isTorrent( tor ) );
2257
2258    if( strcmp( location, tor->downloadDir ) )
2259    {
2260        tr_file_index_t i;
2261
2262        /* bad idea to move files while they're being verified... */
2263        tr_verifyRemove( tor );
2264
2265        /* if the torrent is running, stop it and set a flag to
2266         * restart after we're done */
2267        if( tor->isRunning )
2268        {
2269            tr_torrentStop( tor );
2270            tor->startAfterVerify = TRUE;
2271        }
2272
2273        /* try to move the files.
2274         * FIXME: there are still all kinds of nasty cases, like what
2275         * if the target directory runs out of space halfway through... */
2276        for( i=0; !err && i<tor->info.fileCount; ++i )
2277        {
2278            struct stat sb;
2279            const tr_file * f = &tor->info.files[i];
2280            char * oldpath = tr_buildPath( tor->downloadDir, f->name, NULL );
2281            char * newpath = tr_buildPath( location, f->name, NULL );
2282           
2283            if( do_move )
2284            {
2285                errno = 0;
2286                tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2287                if( tr_moveFile( oldpath, newpath ) ) {
2288                    err = 1;
2289                    tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2290                                    oldpath, newpath, tr_strerror( errno ) );
2291                }
2292            }
2293            else if( !stat( newpath, &sb ) )
2294            {
2295                tr_torinf( tor, "found \"%s\"", newpath );
2296            }
2297
2298            if( data->setme_progress )
2299            {
2300                bytesHandled += f->length;
2301                *data->setme_progress = bytesHandled / tor->info.totalSize;
2302            }
2303
2304            tr_free( newpath );
2305            tr_free( oldpath );
2306        }
2307
2308        if( !err )
2309        {
2310            /* blow away the leftover subdirectories in the old location */
2311            tr_torrentDeleteLocalData( tor, unlink );
2312
2313            /* set the new location and reverify */
2314            tr_torrentSetDownloadDir( tor, location );
2315            tr_torrentVerify( tor );
2316        }
2317    }
2318
2319    if( data->setme_state )
2320        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2321
2322    /* cleanup */
2323    tr_free( data->location );
2324    tr_free( data );
2325}
2326
2327void
2328tr_torrentSetLocation( tr_torrent  * tor,
2329                       const char  * location,
2330                       tr_bool       move_from_old_location,
2331                       double      * setme_progress,
2332                       int         * setme_state )
2333{
2334    struct LocationData * data;
2335
2336    assert( tr_isTorrent( tor ) );
2337
2338    if( setme_state )
2339        *setme_state = TR_LOC_MOVING;
2340    if( setme_progress )
2341        *setme_progress = 0;
2342
2343    /* run this in the libtransmission thread */
2344    data = tr_new( struct LocationData, 1 );
2345    data->tor = tor;
2346    data->location = tr_strdup( location );
2347    data->move_from_old_location = move_from_old_location;
2348    data->setme_state = setme_state;
2349    data->setme_progress = setme_progress;
2350    tr_runInEventThread( tor->session, setLocation, data );
2351}
2352
2353/***
2354****
2355***/
2356
2357void
2358tr_torrentCheckSeedRatio( tr_torrent * tor )
2359{
2360    double seedRatio;
2361
2362    assert( tr_isTorrent( tor ) );
2363
2364    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2365    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2366    {
2367        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2368        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2369        double ratio;
2370
2371        /* maybe we're the initial seeder and never downloaded anything... */
2372        if( down == 0 )
2373            down = tr_cpHaveValid( &tor->completion );
2374
2375        ratio = tr_getRatio( up, down );
2376
2377        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2378        {
2379            tr_torrentStop( tor );
2380
2381            /* set to no ratio limit to allow easy restarting */
2382            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2383
2384            /* maybe notify the client */
2385            if( tor->ratio_limit_hit_func != NULL )
2386                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2387        }
2388    }
2389}
Note: See TracBrowser for help on using the repository browser.