source: trunk/libtransmission/torrent.c @ 8878

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

(trunk libT) #2137: .resume file gets saved too frequently

  • Property svn:keywords set to Date Rev Author Id
File size: 61.3 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 8878 2009-08-07 05:29:37Z 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 <math.h> /* fabs */
21#include <string.h> /* memcmp */
22#include <stdlib.h> /* qsort */
23
24#include <event.h> /* evbuffer */
25
26#include "transmission.h"
27#include "session.h"
28#include "bandwidth.h"
29#include "bencode.h"
30#include "completion.h"
31#include "crypto.h" /* for tr_sha1 */
32#include "resume.h"
33#include "fdlimit.h" /* tr_fdTorrentClose */
34#include "metainfo.h"
35#include "peer-mgr.h"
36#include "platform.h" /* TR_PATH_DELIMITER_STR */
37#include "ptrarray.h"
38#include "ratecontrol.h"
39#include "torrent.h"
40#include "tracker.h"
41#include "trevent.h"
42#include "utils.h"
43#include "verify.h"
44
45#define MAX_BLOCK_SIZE ( 1024 * 16 )
46
47/***
48****
49***/
50
51int
52tr_torrentId( const tr_torrent * tor )
53{
54    return tor->uniqueId;
55}
56
57tr_torrent*
58tr_torrentFindFromId( tr_session * session, int id )
59{
60    tr_torrent * tor = NULL;
61
62    while(( tor = tr_torrentNext( session, tor )))
63        if( tor->uniqueId == id )
64            return tor;
65
66    return NULL;
67}
68
69tr_torrent*
70tr_torrentFindFromHashString( tr_session *  session, const char * str )
71{
72    tr_torrent * tor = NULL;
73
74    while(( tor = tr_torrentNext( session, tor )))
75        if( !strcmp( str, tor->info.hashString ) )
76            return tor;
77
78    return NULL;
79}
80
81tr_torrent*
82tr_torrentFindFromHash( tr_session * session, const uint8_t * torrentHash )
83{
84    tr_torrent * tor = NULL;
85
86    while(( tor = tr_torrentNext( session, tor )))
87        if( *tor->info.hash == *torrentHash )
88            if( !memcmp( tor->info.hash, torrentHash, SHA_DIGEST_LENGTH ) )
89                return tor;
90
91    return NULL;
92}
93
94tr_torrent*
95tr_torrentFindFromObfuscatedHash( tr_session * session,
96                                  const uint8_t * obfuscatedTorrentHash )
97{
98    tr_torrent * tor = NULL;
99
100    while(( tor = tr_torrentNext( session, tor )))
101        if( !memcmp( tor->obfuscatedHash, obfuscatedTorrentHash,
102                     SHA_DIGEST_LENGTH ) )
103            return tor;
104
105    return NULL;
106}
107
108/***
109****  PER-TORRENT UL / DL SPEEDS
110***/
111
112void
113tr_torrentSetSpeedLimit( tr_torrent * tor, tr_direction dir, int KiB_sec )
114{
115    assert( tr_isTorrent( tor ) );
116    assert( tr_isDirection( dir ) );
117
118    tr_bandwidthSetDesiredSpeed( tor->bandwidth, dir, KiB_sec );
119
120    tr_torrentSetDirty( tor );
121}
122
123int
124tr_torrentGetSpeedLimit( const tr_torrent * tor, tr_direction dir )
125{
126    assert( tr_isTorrent( tor ) );
127    assert( tr_isDirection( dir ) );
128
129    return tr_bandwidthGetDesiredSpeed( tor->bandwidth, dir );
130}
131
132void
133tr_torrentUseSpeedLimit( tr_torrent * tor, tr_direction dir, tr_bool do_use )
134{
135    assert( tr_isTorrent( tor ) );
136    assert( tr_isDirection( dir ) );
137
138    tr_bandwidthSetLimited( tor->bandwidth, dir, do_use );
139
140    tr_torrentSetDirty( tor );
141}
142
143tr_bool
144tr_torrentUsesSpeedLimit( const tr_torrent * tor, tr_direction dir )
145{
146    assert( tr_isTorrent( tor ) );
147    assert( tr_isDirection( dir ) );
148
149    return tr_bandwidthIsLimited( tor->bandwidth, dir );
150}
151
152void
153tr_torrentUseSessionLimits( tr_torrent * tor, tr_bool doUse )
154{
155    assert( tr_isTorrent( tor ) );
156
157    tr_bandwidthHonorParentLimits( tor->bandwidth, TR_UP, doUse );
158    tr_bandwidthHonorParentLimits( tor->bandwidth, TR_DOWN, doUse );
159
160    tr_torrentSetDirty( tor );
161}
162
163tr_bool
164tr_torrentUsesSessionLimits( const tr_torrent * tor )
165{
166    assert( tr_isTorrent( tor ) );
167
168    return tr_bandwidthAreParentLimitsHonored( tor->bandwidth, TR_UP );
169}
170
171/***
172****
173***/
174
175void
176tr_torrentSetRatioMode( tr_torrent *  tor, tr_ratiolimit mode )
177{
178    assert( tr_isTorrent( tor ) );
179    assert( mode==TR_RATIOLIMIT_GLOBAL || mode==TR_RATIOLIMIT_SINGLE || mode==TR_RATIOLIMIT_UNLIMITED  );
180
181    tor->ratioLimitMode = mode;
182    tor->needsSeedRatioCheck = TRUE;
183
184    tr_torrentSetDirty( tor );
185}
186
187tr_ratiolimit
188tr_torrentGetRatioMode( const tr_torrent * tor )
189{
190    assert( tr_isTorrent( tor ) );
191
192    return tor->ratioLimitMode;
193}
194
195void
196tr_torrentSetRatioLimit( tr_torrent * tor, double desiredRatio )
197{
198    assert( tr_isTorrent( tor ) );
199
200    tor->desiredRatio = desiredRatio;
201
202    tor->needsSeedRatioCheck = TRUE;
203
204    tr_torrentSetDirty( tor );
205}
206
207double
208tr_torrentGetRatioLimit( const tr_torrent * tor )
209{
210    assert( tr_isTorrent( tor ) );
211
212    return tor->desiredRatio;
213}
214
215tr_bool
216tr_torrentIsPieceTransferAllowed( const tr_torrent  * tor,
217                                  tr_direction        direction )
218{
219    int limit;
220    tr_bool allowed = TRUE;
221
222    if( tr_torrentUsesSpeedLimit( tor, direction ) )
223        if( tr_torrentGetSpeedLimit( tor, direction ) <= 0 )
224            allowed = FALSE;
225
226    if( tr_torrentUsesSessionLimits( tor ) )
227        if( tr_sessionGetActiveSpeedLimit( tor->session, direction, &limit ) )
228            if( limit <= 0 )
229                allowed = FALSE;
230
231    return allowed;
232}
233
234tr_bool
235tr_torrentGetSeedRatio( const tr_torrent * tor, double * ratio )
236{
237    tr_bool isLimited;
238
239    switch( tr_torrentGetRatioMode( tor ) )
240    {
241        case TR_RATIOLIMIT_SINGLE:
242            isLimited = TRUE;
243            if( ratio )
244                *ratio = tr_torrentGetRatioLimit( tor );
245            break;
246
247        case TR_RATIOLIMIT_GLOBAL:
248            isLimited = tr_sessionIsRatioLimited( tor->session );
249            if( isLimited && ratio )
250                *ratio = tr_sessionGetRatioLimit( tor->session );
251            break;
252
253        default: /* TR_RATIOLIMIT_UNLIMITED */
254            isLimited = FALSE;
255            break;
256    }
257
258    return isLimited;
259}
260
261/***
262****
263***/
264
265static void
266onTrackerResponse( void * tracker UNUSED,
267                   void *         vevent,
268                   void *         user_data )
269{
270    tr_torrent *       tor = user_data;
271    tr_tracker_event * event = vevent;
272
273    switch( event->messageType )
274    {
275        case TR_TRACKER_PEERS:
276        {
277            size_t   i, n;
278            tr_pex * pex = tr_peerMgrArrayToPex( event->compact,
279                                                 event->compactLen, &n );
280             if( event->allAreSeeds )
281                tr_tordbg( tor, "Got %d seeds from tracker", (int)n );
282            else
283                tr_torinf( tor, _( "Got %d peers from tracker" ), (int)n );
284
285            for( i = 0; i < n; ++i )
286            {
287                if( event->allAreSeeds )
288                    pex[i].flags |= ADDED_F_SEED_FLAG;
289                tr_peerMgrAddPex( tor, TR_PEER_FROM_TRACKER, pex + i );
290            }
291
292            tr_free( pex );
293            break;
294        }
295
296        case TR_TRACKER_WARNING:
297            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
298            tor->error = TR_STAT_TRACKER_WARNING;
299            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
300            break;
301
302        case TR_TRACKER_ERROR:
303            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
304            tor->error = TR_STAT_TRACKER_ERROR;
305            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
306            break;
307
308        case TR_TRACKER_ERROR_CLEAR:
309            tor->error = TR_STAT_OK;
310            tor->errorString[0] = '\0';
311            break;
312    }
313}
314
315/***
316****
317****  TORRENT INSTANTIATION
318****
319***/
320
321static int
322getBytePiece( const tr_info * info,
323              uint64_t        byteOffset )
324{
325    assert( info );
326    assert( info->pieceSize != 0 );
327
328    return byteOffset / info->pieceSize;
329}
330
331static void
332initFilePieces( tr_info *       info,
333                tr_file_index_t fileIndex )
334{
335    tr_file * file;
336    uint64_t  firstByte, lastByte;
337
338    assert( info );
339    assert( fileIndex < info->fileCount );
340
341    file = &info->files[fileIndex];
342    firstByte = file->offset;
343    lastByte = firstByte + ( file->length ? file->length - 1 : 0 );
344    file->firstPiece = getBytePiece( info, firstByte );
345    file->lastPiece = getBytePiece( info, lastByte );
346}
347
348static int
349pieceHasFile( tr_piece_index_t piece,
350              const tr_file *  file )
351{
352    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
353}
354
355static tr_priority_t
356calculatePiecePriority( const tr_torrent * tor,
357                        tr_piece_index_t   piece,
358                        int                fileHint )
359{
360    tr_file_index_t i;
361    int             priority = TR_PRI_LOW;
362
363    /* find the first file that has data in this piece */
364    if( fileHint >= 0 ) {
365        i = fileHint;
366        while( i > 0 && pieceHasFile( piece, &tor->info.files[i - 1] ) )
367            --i;
368    } else {
369        for( i = 0; i < tor->info.fileCount; ++i )
370            if( pieceHasFile( piece, &tor->info.files[i] ) )
371                break;
372    }
373
374    /* the piece's priority is the max of the priorities
375     * of all the files in that piece */
376    for( ; i < tor->info.fileCount; ++i )
377    {
378        const tr_file * file = &tor->info.files[i];
379
380        if( !pieceHasFile( piece, file ) )
381            break;
382
383        priority = MAX( priority, file->priority );
384
385        /* when dealing with multimedia files, getting the first and
386           last pieces can sometimes allow you to preview it a bit
387           before it's fully downloaded... */
388        if( file->priority >= TR_PRI_NORMAL )
389            if( file->firstPiece == piece || file->lastPiece == piece )
390                priority = TR_PRI_HIGH;
391    }
392
393    return priority;
394}
395
396static void
397tr_torrentInitFilePieces( tr_torrent * tor )
398{
399    tr_file_index_t  f;
400    tr_piece_index_t p;
401    uint64_t offset = 0;
402    tr_info * inf = &tor->info;
403    int * firstFiles;
404
405    /* assign the file offsets */
406    for( f=0; f<inf->fileCount; ++f ) {
407        inf->files[f].offset = offset;
408        offset += inf->files[f].length;
409        initFilePieces( inf, f );
410    }
411
412    /* build the array of first-file hints to give calculatePiecePriority */
413    firstFiles = tr_new( int, inf->pieceCount );
414    for( p=f=0; p<inf->pieceCount; ++p ) {
415        while( inf->files[f].lastPiece < p )
416            ++f;
417        firstFiles[p] = f;
418    }
419
420#if 0
421    /* test to confirm the first-file hints are correct */
422    for( p=0; p<inf->pieceCount; ++p ) {
423        f = firstFiles[p];
424        assert( inf->files[f].firstPiece <= p );
425        assert( inf->files[f].lastPiece >= p );
426        if( f > 0 )
427            assert( inf->files[f-1].lastPiece < p );
428        for( f=0; f<inf->fileCount; ++f )
429            if( pieceHasFile( p, &inf->files[f] ) )
430                break;
431        assert( (int)f == firstFiles[p] );
432    }
433#endif
434
435    for( p=0; p<inf->pieceCount; ++p )
436        inf->pieces[p].priority = calculatePiecePriority( tor, p, firstFiles[p] );
437
438    tr_free( firstFiles );
439}
440
441int
442tr_torrentPromoteTracker( tr_torrent * tor,
443                          int          pos )
444{
445    int i;
446    int tier;
447
448    assert( tor );
449    assert( ( 0 <= pos ) && ( pos < tor->info.trackerCount ) );
450
451    /* the tier of the tracker we're promoting */
452    tier = tor->info.trackers[pos].tier;
453
454    /* find the index of that tier's first tracker */
455    for( i = 0; i < tor->info.trackerCount; ++i )
456        if( tor->info.trackers[i].tier == tier )
457            break;
458
459    assert( i < tor->info.trackerCount );
460
461    /* promote the tracker at `pos' to the front of the tier */
462    if( i != pos )
463    {
464        const tr_tracker_info tmp = tor->info.trackers[i];
465        tor->info.trackers[i] = tor->info.trackers[pos];
466        tor->info.trackers[pos] = tmp;
467    }
468
469    /* return the new position of the tracker that started out at [pos] */
470    return i;
471}
472
473struct RandomTracker
474{
475    tr_tracker_info    tracker;
476    int                random_value;
477};
478
479/* the tiers will be sorted from lowest to highest,
480 * and trackers are randomized within the tiers */
481static TR_INLINE int
482compareRandomTracker( const void * va,
483                      const void * vb )
484{
485    const struct RandomTracker * a = va;
486    const struct RandomTracker * b = vb;
487
488    if( a->tracker.tier != b->tracker.tier )
489        return a->tracker.tier - b->tracker.tier;
490
491    return a->random_value - b->random_value;
492}
493
494static void
495randomizeTiers( tr_info * info )
496{
497    int                    i;
498    const int              n = info->trackerCount;
499    struct RandomTracker * r = tr_new0( struct RandomTracker, n );
500
501    for( i = 0; i < n; ++i )
502    {
503        r[i].tracker = info->trackers[i];
504        r[i].random_value = tr_cryptoRandInt( INT_MAX );
505    }
506    qsort( r, n, sizeof( struct RandomTracker ), compareRandomTracker );
507    for( i = 0; i < n; ++i )
508        info->trackers[i] = r[i].tracker;
509    tr_free( r );
510}
511
512static void torrentStart( tr_torrent * tor,
513                          int          reloadProgress );
514
515/**
516 * Decide on a block size.  constraints:
517 * (1) most clients decline requests over 16 KiB
518 * (2) pieceSize must be a multiple of block size
519 */
520static uint32_t
521getBlockSize( uint32_t pieceSize )
522{
523    uint32_t b = pieceSize;
524
525    while( b > MAX_BLOCK_SIZE )
526        b /= 2u;
527
528    if( !b || ( pieceSize % b ) ) /* not cleanly divisible */
529        return 0;
530    return b;
531}
532
533static void
534torrentRealInit( tr_torrent * tor, const tr_ctor * ctor )
535{
536    int          doStart;
537    uint64_t     loaded;
538    uint64_t     t;
539    const char * dir;
540    static int   nextUniqueId = 1;
541    tr_info    * info = &tor->info;
542    tr_session * session = tr_ctorGetSession( ctor );
543
544    assert( session != NULL );
545
546    tr_globalLock( session );
547
548    tor->session   = session;
549    tor->uniqueId = nextUniqueId++;
550    tor->magicNumber = TORRENT_MAGIC_NUMBER;
551
552    randomizeTiers( info );
553
554    tor->bandwidth = tr_bandwidthNew( session, session->bandwidth );
555
556    tor->blockSize = getBlockSize( info->pieceSize );
557
558    if( !tr_ctorGetDownloadDir( ctor, TR_FORCE, &dir ) ||
559        !tr_ctorGetDownloadDir( ctor, TR_FALLBACK, &dir ) )
560            tor->downloadDir = tr_strdup( dir );
561
562    tor->lastPieceSize = info->totalSize % info->pieceSize;
563
564    if( !tor->lastPieceSize )
565        tor->lastPieceSize = info->pieceSize;
566
567    tor->lastBlockSize = info->totalSize % tor->blockSize;
568
569    if( !tor->lastBlockSize )
570        tor->lastBlockSize = tor->blockSize;
571
572    tor->blockCount =
573        ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize;
574
575    tor->blockCountInPiece =
576        info->pieceSize / tor->blockSize;
577
578    tor->blockCountInLastPiece =
579        ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize;
580
581    /* check our work */
582    assert( ( info->pieceSize % tor->blockSize ) == 0 );
583    t = info->pieceCount - 1;
584    t *= info->pieceSize;
585    t += tor->lastPieceSize;
586    assert( t == info->totalSize );
587    t = tor->blockCount - 1;
588    t *= tor->blockSize;
589    t += tor->lastBlockSize;
590    assert( t == info->totalSize );
591    t = info->pieceCount - 1;
592    t *= tor->blockCountInPiece;
593    t += tor->blockCountInLastPiece;
594    assert( t == (uint64_t)tor->blockCount );
595
596    tr_cpConstruct( &tor->completion, tor );
597
598    tr_torrentInitFilePieces( tor );
599
600    tr_rcConstruct( &tor->swarmSpeed );
601
602    tr_sha1( tor->obfuscatedHash, "req2", 4,
603             info->hash, SHA_DIGEST_LENGTH,
604             NULL );
605
606    tr_peerMgrAddTorrent( session->peerMgr, tor );
607
608    assert( !tor->downloadedCur );
609    assert( !tor->uploadedCur );
610
611    tr_ctorInitTorrentPriorities( ctor, tor );
612
613    tr_ctorInitTorrentWanted( ctor, tor );
614
615    tor->error = TR_STAT_OK;
616
617    tr_bitfieldConstruct( &tor->checkedPieces, tor->info.pieceCount );
618    tr_torrentUncheck( tor );
619
620    tr_torrentSetAddedDate( tor, time( NULL ) ); /* this is a default value to be
621                                                    overwritten by the resume file */
622
623    loaded = tr_torrentLoadResume( tor, ~0, ctor );
624
625    doStart = tor->isRunning;
626    tor->isRunning = 0;
627
628    if( !( loaded & TR_FR_SPEEDLIMIT ) )
629    {
630        tr_torrentUseSpeedLimit( tor, TR_UP, FALSE );
631        tr_torrentSetSpeedLimit( tor, TR_UP, tr_sessionGetSpeedLimit( tor->session, TR_UP ) );
632        tr_torrentUseSpeedLimit( tor, TR_DOWN, FALSE );
633        tr_torrentSetSpeedLimit( tor, TR_DOWN, tr_sessionGetSpeedLimit( tor->session, TR_DOWN ) );
634        tr_torrentUseSessionLimits( tor, TRUE );
635    }
636
637    if( !( loaded & TR_FR_RATIOLIMIT ) )
638    {
639        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_GLOBAL );
640        tr_torrentSetRatioLimit( tor, tr_sessionGetRatioLimit( tor->session ) );
641    }
642
643    tor->completeness = tr_cpGetStatus( &tor->completion );
644
645    tor->tracker = tr_trackerNew( tor );
646    tor->trackerSubscription =
647        tr_trackerSubscribe( tor->tracker, onTrackerResponse,
648                             tor );
649
650    {
651        tr_torrent * it = NULL;
652        tr_torrent * last = NULL;
653        while( ( it = tr_torrentNext( session, it ) ) )
654            last = it;
655
656        if( !last )
657            session->torrentList = tor;
658        else
659            last->next = tor;
660        ++session->torrentCount;
661    }
662
663    tr_globalUnlock( session );
664
665    /* maybe save our own copy of the metainfo */
666    if( tr_ctorGetSave( ctor ) )
667    {
668        const tr_benc * val;
669        if( !tr_ctorGetMetainfo( ctor, &val ) )
670        {
671            const char * filename = tor->info.torrent;
672            tr_bencToFile( val, TR_FMT_BENC, filename );
673            tr_sessionSetTorrentFile( tor->session, tor->info.hashString, filename );
674        }
675    }
676
677    tr_metainfoMigrate( session, &tor->info );
678
679    if( doStart )
680        torrentStart( tor, FALSE );
681}
682
683tr_parse_result
684tr_torrentParse( const tr_ctor * ctor, tr_info * setmeInfo )
685{
686    int             doFree;
687    tr_bool         didParse;
688    tr_info         tmp;
689    const tr_benc * metainfo;
690    tr_session    * session = tr_ctorGetSession( ctor );
691    tr_parse_result result = TR_PARSE_OK;
692
693    if( setmeInfo == NULL )
694        setmeInfo = &tmp;
695    memset( setmeInfo, 0, sizeof( tr_info ) );
696
697    if( tr_ctorGetMetainfo( ctor, &metainfo ) )
698        return TR_PARSE_ERR;
699
700    didParse = tr_metainfoParse( session, setmeInfo, metainfo );
701    doFree = didParse && ( setmeInfo == &tmp );
702
703    if( didParse && !getBlockSize( setmeInfo->pieceSize ) )
704        result = TR_PARSE_ERR;
705
706    if( didParse && session && tr_torrentExists( session, setmeInfo->hash ) )
707        result = TR_PARSE_DUPLICATE;
708
709    if( doFree )
710        tr_metainfoFree( setmeInfo );
711
712    return result;
713}
714
715tr_torrent *
716tr_torrentNew( const tr_ctor  * ctor,
717               int            * setmeError )
718{
719    int          err;
720    tr_info      tmpInfo;
721    tr_torrent * tor = NULL;
722
723    assert( ctor != NULL );
724    assert( tr_isSession( tr_ctorGetSession( ctor ) ) );
725
726    err = tr_torrentParse( ctor, &tmpInfo );
727    if( !err )
728    {
729        tor = tr_new0( tr_torrent, 1 );
730        tor->info = tmpInfo;
731        torrentRealInit( tor, ctor );
732    }
733    else if( setmeError )
734    {
735        *setmeError = err;
736    }
737
738    return tor;
739}
740
741/**
742***
743**/
744
745void
746tr_torrentSetDownloadDir( tr_torrent * tor, const char * path )
747{
748    assert( tr_isTorrent( tor  ) );
749
750    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
751    {
752        tr_free( tor->downloadDir );
753        tor->downloadDir = tr_strdup( path );
754        tr_torrentSetDirty( tor );
755    }
756}
757
758const char*
759tr_torrentGetDownloadDir( const tr_torrent * tor )
760{
761    assert( tr_isTorrent( tor  ) );
762
763    return tor->downloadDir;
764}
765
766void
767tr_torrentChangeMyPort( tr_torrent * tor )
768{
769    assert( tr_isTorrent( tor  ) );
770
771    if( tor->tracker )
772        tr_trackerChangeMyPort( tor->tracker );
773}
774
775static TR_INLINE void
776tr_torrentManualUpdateImpl( void * vtor )
777{
778    tr_torrent * tor = vtor;
779
780    assert( tr_isTorrent( tor  ) );
781
782    if( tor->isRunning )
783        tr_trackerReannounce( tor->tracker );
784}
785
786void
787tr_torrentManualUpdate( tr_torrent * tor )
788{
789    assert( tr_isTorrent( tor  ) );
790
791    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
792}
793
794tr_bool
795tr_torrentCanManualUpdate( const tr_torrent * tor )
796{
797    return ( tr_isTorrent( tor  ) )
798        && ( tor->isRunning )
799        && ( tr_trackerCanManualAnnounce( tor->tracker ) );
800}
801
802const tr_info *
803tr_torrentInfo( const tr_torrent * tor )
804{
805    return tr_isTorrent( tor ) ? &tor->info : NULL;
806}
807
808const tr_stat *
809tr_torrentStatCached( tr_torrent * tor )
810{
811    const time_t now = time( NULL );
812
813    return tr_isTorrent( tor ) && ( now == tor->lastStatTime )
814         ? &tor->stats
815         : tr_torrentStat( tor );
816}
817
818void
819tr_torrentSetVerifyState( tr_torrent * tor, tr_verify_state state )
820{
821    assert( tr_isTorrent( tor ) );
822    assert( state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW );
823
824    tor->verifyState = state;
825    tor->anyDate = time( NULL );
826}
827
828tr_torrent_activity
829tr_torrentGetActivity( tr_torrent * tor )
830{
831    assert( tr_isTorrent( tor ) );
832
833    tr_torrentRecheckCompleteness( tor );
834
835    if( tor->verifyState == TR_VERIFY_NOW )
836        return TR_STATUS_CHECK;
837    if( tor->verifyState == TR_VERIFY_WAIT )
838        return TR_STATUS_CHECK_WAIT;
839    if( !tor->isRunning )
840        return TR_STATUS_STOPPED;
841    if( tor->completeness == TR_LEECH )
842        return TR_STATUS_DOWNLOAD;
843
844    return TR_STATUS_SEED;
845}
846
847const tr_stat *
848tr_torrentStat( tr_torrent * tor )
849{
850    tr_stat *               s;
851    struct tr_tracker *     tc;
852    const tr_tracker_info * ti;
853    int                     usableSeeds = 0;
854    uint64_t                now;
855    double                  downloadedForRatio, seedRatio=0;
856    double                  d;
857    tr_bool                 checkSeedRatio;
858
859    if( !tor )
860        return NULL;
861
862    assert( tr_isTorrent( tor ) );
863    tr_torrentLock( tor );
864
865    tor->lastStatTime = time( NULL );
866
867    s = &tor->stats;
868    s->id = tor->uniqueId;
869    s->activity = tr_torrentGetActivity( tor );
870    s->error = tor->error;
871    memcpy( s->errorString, tor->errorString, sizeof( s->errorString ) );
872
873    tc = tor->tracker;
874    ti = tr_trackerGetAddress( tor->tracker, tor );
875    s->announceURL = ti ? ti->announce : NULL;
876    s->scrapeURL   = ti ? ti->scrape   : NULL;
877    tr_trackerStat( tc, s );
878
879    tr_trackerGetCounts( tc, &s->timesCompleted,
880                             &s->leechers,
881                             &s->seeders,
882                             &s->downloaders );
883
884    tr_peerMgrTorrentStats( tor,
885                            &s->peersKnown,
886                            &s->peersConnected,
887                            &usableSeeds,
888                            &s->webseedsSendingToUs,
889                            &s->peersSendingToUs,
890                            &s->peersGettingFromUs,
891                            s->peersFrom );
892
893    now = tr_date( );
894    d = tr_peerMgrGetWebseedSpeed( tor, now );
895    s->swarmSpeed         = tr_rcRate( &tor->swarmSpeed, now );
896    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
897    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
898    s->rawDownloadSpeed   = d + tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
899    s->pieceDownloadSpeed = d + tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
900
901    usableSeeds += tor->info.webseedCount;
902
903    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
904
905    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
906    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
907    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
908
909    s->recheckProgress = s->activity == TR_STATUS_CHECK
910                       ? 1.0 -
911                         ( tr_torrentCountUncheckedPieces( tor ) /
912                           (double) tor->info.pieceCount )
913                       : 0.0;
914
915    s->activityDate = tor->activityDate;
916    s->addedDate    = tor->addedDate;
917    s->doneDate     = tor->doneDate;
918    s->startDate    = tor->startDate;
919
920    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
921    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
922    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
923    s->haveValid       = tr_cpHaveValid( &tor->completion );
924    s->haveUnchecked   = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
925
926    if( usableSeeds > 0 )
927    {
928        s->desiredAvailable = s->leftUntilDone;
929    }
930    else if( !s->leftUntilDone || !s->peersConnected )
931    {
932        s->desiredAvailable = 0;
933    }
934    else
935    {
936        tr_piece_index_t i;
937        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable( tor );
938        s->desiredAvailable = 0;
939        for( i = 0; i < tor->info.pieceCount; ++i )
940            if( !tor->info.pieces[i].dnd && tr_bitfieldHasFast( peerPieces, i ) )
941                s->desiredAvailable += tr_cpMissingBlocksInPiece( &tor->completion, i );
942        s->desiredAvailable *= tor->blockSize;
943        tr_bitfieldFree( peerPieces );
944    }
945
946    downloadedForRatio = s->downloadedEver ? s->downloadedEver : s->haveValid;
947    s->ratio = tr_getRatio( s->uploadedEver, downloadedForRatio );
948
949    checkSeedRatio = tr_torrentGetSeedRatio( tor, &seedRatio );
950
951    switch( s->activity )
952    {
953        case TR_STATUS_DOWNLOAD:
954            if( s->leftUntilDone > s->desiredAvailable )
955                s->eta = TR_ETA_NOT_AVAIL;
956            else if( s->pieceDownloadSpeed < 0.1 )
957                s->eta = TR_ETA_UNKNOWN;
958            else {
959                /* etaSpeed exists because if we pieceDownloadSpeed directly,
960                 * brief fluctuations cause the ETA to jump all over the place.
961                 * so, etaSpeed is a smoothed-out version of pieceDownloadSpeed
962                 * to dampen the effect of fluctuations */
963                if( ( tor->etaSpeedCalculatedAt + 800 ) < now ) {
964                    tor->etaSpeedCalculatedAt = now;
965                    tor->etaSpeed = (fabs(tor->etaSpeed)<0.0001)
966                        ? s->pieceDownloadSpeed /* if no previous speed, no need to smooth */
967                        : 0.8*tor->etaSpeed + 0.2*s->pieceDownloadSpeed; /* smooth across 5 readings */
968                }
969                s->eta = s->leftUntilDone / tor->etaSpeed / 1024.0;
970            }
971            break;
972
973        case TR_STATUS_SEED:
974            if( checkSeedRatio )
975            {
976                if( s->pieceUploadSpeed < 0.1 )
977                    s->eta = TR_ETA_UNKNOWN;
978                else
979                    s->eta = (downloadedForRatio * (seedRatio - s->ratio)) / s->pieceUploadSpeed / 1024.0;
980            }
981            else
982                s->eta = TR_ETA_NOT_AVAIL;
983            break;
984
985        default:
986            s->eta = TR_ETA_NOT_AVAIL;
987            break;
988    }
989
990    if( !checkSeedRatio || s->ratio >= seedRatio || s->ratio == TR_RATIO_INF )
991        s->percentRatio = 1.0;
992    else if( s->ratio == TR_RATIO_NA )
993        s->percentRatio = 0.0;
994    else 
995        s->percentRatio = s->ratio / seedRatio;
996
997    tr_torrentUnlock( tor );
998
999    return s;
1000}
1001
1002/***
1003****
1004***/
1005
1006static uint64_t
1007fileBytesCompleted( const tr_torrent * tor, tr_file_index_t index )
1008{
1009    uint64_t total = 0;
1010    const tr_file * f = &tor->info.files[index];
1011
1012    if( f->length )
1013    {
1014        const tr_block_index_t firstBlock = f->offset / tor->blockSize;
1015        const uint64_t lastByte = f->offset + f->length - 1;
1016        const tr_block_index_t lastBlock = lastByte / tor->blockSize;
1017
1018        if( firstBlock == lastBlock )
1019        {
1020            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1021                total = f->length;
1022        }
1023        else
1024        {
1025            uint32_t i;
1026
1027            /* the first block */
1028            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1029                total += tor->blockSize - ( f->offset % tor->blockSize );
1030
1031            /* the middle blocks */
1032            if( f->firstPiece == f->lastPiece )
1033            {
1034                for( i=firstBlock+1; i<lastBlock; ++i )
1035                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1036                        total += tor->blockSize;
1037            }
1038            else
1039            {
1040                int64_t b = 0;
1041                const tr_block_index_t firstBlockOfLastPiece
1042                           = tr_torPieceFirstBlock( tor, f->lastPiece );
1043                const tr_block_index_t lastBlockOfFirstPiece
1044                           = tr_torPieceFirstBlock( tor, f->firstPiece )
1045                             + tr_torPieceCountBlocks( tor, f->firstPiece ) - 1;
1046
1047                /* the rest of the first piece */
1048                for( i=firstBlock+1; i<lastBlock && i<=lastBlockOfFirstPiece; ++i )
1049                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1050                        ++b;
1051
1052                /* the middle pieces */
1053                if( f->firstPiece + 1 < f->lastPiece )
1054                    for( i=f->firstPiece+1; i<f->lastPiece; ++i )
1055                        b += tor->blockCountInPiece - tr_cpMissingBlocksInPiece( &tor->completion, i );
1056
1057                /* the rest of the last piece */
1058                for( i=firstBlockOfLastPiece; i<lastBlock; ++i )
1059                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1060                        ++b;
1061
1062                b *= tor->blockSize;
1063                total += b;
1064            }
1065
1066            /* the last block */
1067            if( tr_cpBlockIsCompleteFast( &tor->completion, lastBlock ) )
1068                total += ( f->offset + f->length ) - ( tor->blockSize * lastBlock );
1069        }
1070    }
1071
1072    return total;
1073}
1074
1075tr_file_stat *
1076tr_torrentFiles( const tr_torrent * tor,
1077                 tr_file_index_t *  fileCount )
1078{
1079    tr_file_index_t       i;
1080    const tr_file_index_t n = tor->info.fileCount;
1081    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1082    tr_file_stat *        walk = files;
1083    const tr_bool         isSeed = tor->completeness == TR_SEED;
1084
1085    assert( tr_isTorrent( tor ) );
1086
1087    for( i = 0; i < n; ++i, ++walk )
1088    {
1089        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1090        walk->bytesCompleted = b;
1091        walk->progress = tr_getRatio( b, tor->info.files[i].length );
1092    }
1093
1094    if( fileCount )
1095        *fileCount = n;
1096
1097    return files;
1098}
1099
1100void
1101tr_torrentFilesFree( tr_file_stat *            files,
1102                     tr_file_index_t fileCount UNUSED )
1103{
1104    tr_free( files );
1105}
1106
1107/***
1108****
1109***/
1110
1111float*
1112tr_torrentWebSpeeds( const tr_torrent * tor )
1113{
1114    return tr_isTorrent( tor )
1115         ? tr_peerMgrWebSpeeds( tor )
1116         : NULL;
1117}
1118
1119tr_peer_stat *
1120tr_torrentPeers( const tr_torrent * tor,
1121                 int *              peerCount )
1122{
1123    tr_peer_stat * ret = NULL;
1124
1125    if( tr_isTorrent( tor ) )
1126        ret = tr_peerMgrPeerStats( tor, peerCount );
1127
1128    return ret;
1129}
1130
1131void
1132tr_torrentPeersFree( tr_peer_stat * peers,
1133                     int peerCount  UNUSED )
1134{
1135    tr_free( peers );
1136}
1137
1138void
1139tr_torrentAvailability( const tr_torrent * tor,
1140                        int8_t *           tab,
1141                        int                size )
1142{
1143    tr_peerMgrTorrentAvailability( tor, tab, size );
1144}
1145
1146void
1147tr_torrentAmountFinished( const tr_torrent * tor,
1148                          float *            tab,
1149                          int                size )
1150{
1151    assert( tr_isTorrent( tor ) );
1152
1153    tr_torrentLock( tor );
1154    tr_cpGetAmountDone( &tor->completion, tab, size );
1155    tr_torrentUnlock( tor );
1156}
1157
1158void
1159tr_torrentResetTransferStats( tr_torrent * tor )
1160{
1161    assert( tr_isTorrent( tor ) );
1162
1163    tr_torrentLock( tor );
1164
1165    tor->downloadedPrev += tor->downloadedCur;
1166    tor->downloadedCur   = 0;
1167    tor->uploadedPrev   += tor->uploadedCur;
1168    tor->uploadedCur     = 0;
1169    tor->corruptPrev    += tor->corruptCur;
1170    tor->corruptCur      = 0;
1171
1172    tr_torrentSetDirty( tor );
1173
1174    tr_torrentUnlock( tor );
1175}
1176
1177void
1178tr_torrentSetHasPiece( tr_torrent *     tor,
1179                       tr_piece_index_t pieceIndex,
1180                       tr_bool          has )
1181{
1182    assert( tr_isTorrent( tor ) );
1183    assert( pieceIndex < tor->info.pieceCount );
1184
1185    if( has )
1186        tr_cpPieceAdd( &tor->completion, pieceIndex );
1187    else
1188        tr_cpPieceRem( &tor->completion, pieceIndex );
1189}
1190
1191/***
1192****
1193***/
1194
1195static void
1196freeTorrent( tr_torrent * tor )
1197{
1198    tr_torrent * t;
1199    tr_session *  session = tor->session;
1200    tr_info *    inf = &tor->info;
1201
1202    assert( tr_isTorrent( tor ) );
1203    assert( !tor->isRunning );
1204
1205    tr_globalLock( session );
1206
1207    tr_peerMgrRemoveTorrent( tor );
1208
1209    tr_cpDestruct( &tor->completion );
1210
1211    tr_rcDestruct( &tor->swarmSpeed );
1212
1213    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
1214    tr_trackerFree( tor->tracker );
1215    tor->tracker = NULL;
1216
1217    tr_bitfieldDestruct( &tor->checkedPieces );
1218
1219    tr_free( tor->downloadDir );
1220    tr_free( tor->peer_id );
1221
1222    if( tor == session->torrentList )
1223        session->torrentList = tor->next;
1224    else for( t = session->torrentList; t != NULL; t = t->next ) {
1225        if( t->next == tor ) {
1226            t->next = tor->next;
1227            break;
1228        }
1229    }
1230
1231    assert( session->torrentCount >= 1 );
1232    session->torrentCount--;
1233
1234    tr_bandwidthFree( tor->bandwidth );
1235
1236    tr_metainfoFree( inf );
1237    tr_free( tor );
1238
1239    tr_globalUnlock( session );
1240}
1241
1242/**
1243***  Start/Stop Callback
1244**/
1245
1246static void
1247checkAndStartImpl( void * vtor )
1248{
1249    time_t now;
1250    tr_torrent * tor = vtor;
1251
1252    assert( tr_isTorrent( tor ) );
1253
1254    tr_globalLock( tor->session );
1255
1256    now = time( NULL );
1257    tor->isRunning = TRUE;
1258    tor->needsSeedRatioCheck = TRUE;
1259    tor->error = TR_STAT_OK;
1260    tor->errorString[0] = '\0';
1261    tor->completeness = tr_cpGetStatus( &tor->completion );
1262    tor->startDate = tor->anyDate = now;
1263    tr_torrentResetTransferStats( tor );
1264    tr_trackerStart( tor->tracker );
1265    tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1266    tr_peerMgrStartTorrent( tor );
1267
1268    tr_globalUnlock( tor->session );
1269}
1270
1271static void
1272checkAndStartCB( tr_torrent * tor )
1273{
1274    assert( tr_isTorrent( tor ) );
1275    assert( tr_isSession( tor->session ) );
1276
1277    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1278}
1279
1280static void
1281torrentStart( tr_torrent * tor, int reloadProgress )
1282{
1283    assert( tr_isTorrent( tor ) );
1284
1285    tr_globalLock( tor->session );
1286
1287    if( !tor->isRunning )
1288    {
1289        tr_verifyRemove( tor );
1290
1291        if( reloadProgress )
1292            tr_torrentLoadResume( tor, TR_FR_PROGRESS, NULL );
1293
1294        tor->isRunning = 1;
1295        tr_verifyAdd( tor, checkAndStartCB );
1296    }
1297
1298    tr_globalUnlock( tor->session );
1299}
1300
1301void
1302tr_torrentStart( tr_torrent * tor )
1303{
1304    if( tr_isTorrent( tor ) )
1305        torrentStart( tor, TRUE );
1306}
1307
1308static void
1309torrentRecheckDoneImpl( void * vtor )
1310{
1311    tr_torrent * tor = vtor;
1312
1313    assert( tr_isTorrent( tor ) );
1314    tr_torrentRecheckCompleteness( tor );
1315
1316    if( tor->startAfterVerify )
1317    {
1318        tor->startAfterVerify = FALSE;
1319        tr_torrentStart( tor );
1320    }
1321}
1322
1323static void
1324torrentRecheckDoneCB( tr_torrent * tor )
1325{
1326    assert( tr_isTorrent( tor ) );
1327
1328    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1329}
1330
1331void
1332tr_torrentVerify( tr_torrent * tor )
1333{
1334    assert( tr_isTorrent( tor ) );
1335    tr_globalLock( tor->session );
1336
1337    /* if the torrent's already being verified, stop it */
1338    tr_verifyRemove( tor );
1339
1340    /* if the torrent's running, stop it & set the restart-after-verify flag */
1341    if( tor->isRunning ) {
1342        tr_torrentStop( tor );
1343        tor->startAfterVerify = TRUE;
1344    }
1345
1346    /* add the torrent to the recheck queue */
1347    tr_torrentUncheck( tor );
1348    tr_verifyAdd( tor, torrentRecheckDoneCB );
1349
1350    tr_globalUnlock( tor->session );
1351}
1352
1353static void
1354stopTorrent( void * vtor )
1355{
1356    tr_torrent * tor = vtor;
1357
1358    assert( tr_isTorrent( tor ) );
1359
1360    tr_verifyRemove( tor );
1361    tr_peerMgrStopTorrent( tor );
1362    tr_trackerStop( tor->tracker );
1363
1364    tr_fdTorrentClose( tor->uniqueId );
1365
1366    if( tor->isDirty ) {
1367        tor->isDirty = 0;
1368        if( !tor->isDeleting )
1369            tr_torrentSaveResume( tor );
1370    }
1371}
1372
1373void
1374tr_torrentStop( tr_torrent * tor )
1375{
1376    assert( tr_isTorrent( tor ) );
1377
1378    if( tr_isTorrent( tor ) )
1379    {
1380        tr_globalLock( tor->session );
1381
1382        tor->isRunning = 0;
1383        tr_runInEventThread( tor->session, stopTorrent, tor );
1384
1385        tr_globalUnlock( tor->session );
1386    }
1387}
1388
1389static void
1390closeTorrent( void * vtor )
1391{
1392    tr_benc * d;
1393    tr_torrent * tor = vtor;
1394
1395    assert( tr_isTorrent( tor ) );
1396
1397    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1398    tr_bencDictAddInt( d, "id", tor->uniqueId );
1399    tr_bencDictAddInt( d, "date", time( NULL ) );
1400
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_fdTorrentClose( tor->uniqueId );
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_torrentSetDirty( 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_torrentSetDirty( 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_torrentSetDirty( 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    tr_torrentSetDirty( tor );
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    tr_torrentSetDirty( tor );
2023}
2024
2025void
2026tr_torrentSetDoneDate( tr_torrent * tor,
2027                       time_t       t )
2028{
2029    assert( tr_isTorrent( tor ) );
2030
2031    tor->doneDate = t;
2032    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2033}
2034
2035/**
2036***
2037**/
2038
2039uint64_t
2040tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2041{
2042    const tr_file * it;
2043    const tr_file * end;
2044    struct stat sb;
2045    uint64_t bytesLeft = 0;
2046
2047    assert( tr_isTorrent( tor ) );
2048
2049    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
2050    {
2051        if( !it->dnd )
2052        {
2053            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
2054
2055            bytesLeft += it->length;
2056
2057            if( !stat( path, &sb )
2058                    && S_ISREG( sb.st_mode )
2059                    && ( (uint64_t)sb.st_size <= it->length ) )
2060                bytesLeft -= sb.st_size;
2061
2062            tr_free( path );
2063        }
2064    }
2065
2066    return bytesLeft;
2067}
2068
2069/****
2070*****  Removing the torrent's local data
2071****/
2072
2073static int
2074vstrcmp( const void * a, const void * b )
2075{
2076    return strcmp( a, b );
2077}
2078
2079static int
2080compareLongestFirst( const void * a, const void * b )
2081{
2082    const size_t alen = strlen( a );
2083    const size_t blen = strlen( b );
2084
2085    if( alen != blen )
2086        return alen > blen ? -1 : 1;
2087
2088    return vstrcmp( a, b );
2089}
2090
2091static void
2092addDirtyFile( const char  * root,
2093              const char  * filename,
2094              tr_ptrArray * dirtyFolders )
2095{
2096    char * dir = tr_dirname( filename );
2097
2098    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2099    while (     ( dir != NULL )
2100             && ( strlen( root ) <= strlen( dir ) )
2101             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2102    {
2103        char * tmp;
2104        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2105
2106        tmp = tr_dirname( dir );
2107        tr_free( dir );
2108        dir = tmp;
2109    }
2110
2111    tr_free( dir );
2112}
2113
2114static void
2115walkLocalData( const tr_torrent * tor,
2116               const char       * root,
2117               const char       * dir,
2118               const char       * base,
2119               tr_ptrArray      * torrentFiles,
2120               tr_ptrArray      * folders,
2121               tr_ptrArray      * dirtyFolders )
2122{
2123    int i;
2124    struct stat sb;
2125    char * buf;
2126
2127    assert( tr_isTorrent( tor ) );
2128
2129    buf = tr_buildPath( dir, base, NULL );
2130    i = stat( buf, &sb );
2131    if( !i )
2132    {
2133        DIR * odir = NULL;
2134
2135        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2136        {
2137            struct dirent *d;
2138            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2139            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2140                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2141                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2142            closedir( odir );
2143        }
2144        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2145        {
2146            const char * sub = buf + strlen( tor->downloadDir ) + strlen( TR_PATH_DELIMITER_STR );
2147            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2148            if( !isTorrentFile )
2149                addDirtyFile( root, buf, dirtyFolders );
2150        }
2151    }
2152
2153    tr_free( buf );
2154}
2155
2156static void
2157deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2158{
2159    int i, n;
2160    char ** s;
2161    tr_file_index_t f;
2162    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2163    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2164    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2165
2166    const char * firstFile = tor->info.files[0].name;
2167    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2168    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2169    char * root = tr_buildPath( tor->downloadDir, tmp, NULL );
2170
2171    assert( tr_isTorrent( tor ) );
2172
2173    for( f=0; f<tor->info.fileCount; ++f )
2174        tr_ptrArrayInsertSorted( &torrentFiles, tor->info.files[f].name, vstrcmp );
2175
2176    /* build the set of folders and dirtyFolders */
2177    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2178
2179    /* try to remove entire folders first, so that the recycle bin will be tidy */
2180    s = (char**) tr_ptrArrayPeek( &folders, &n );
2181    for( i=0; i<n; ++i )
2182        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2183            fileFunc( s[i] );
2184
2185    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2186    for( f=0; f<tor->info.fileCount; ++f ) {
2187        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
2188        fileFunc( path );
2189        tr_free( path );
2190    }
2191
2192    /* Now clean out the directories left empty from the previous step.
2193     * Work from deepest to shallowest s.t. lower folders
2194     * won't prevent the upper folders from being deleted */
2195    {
2196        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2197        s = (char**) tr_ptrArrayPeek( &folders, &n );
2198        for( i=0; i<n; ++i )
2199            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2200                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2201        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2202        for( i=0; i<n; ++i )
2203            fileFunc( s[i] );
2204        tr_ptrArrayDestruct( &cleanFolders, NULL );
2205    }
2206
2207    /* cleanup */
2208    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2209    tr_ptrArrayDestruct( &folders, tr_free );
2210    tr_ptrArrayDestruct( &torrentFiles, NULL );
2211    tr_free( root );
2212    tr_free( tmp );
2213}
2214
2215void
2216tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2217{
2218    assert( tr_isTorrent( tor ) );
2219
2220    if( fileFunc == NULL )
2221        fileFunc = remove;
2222
2223    /* close all the files because we're about to delete them */
2224    tr_fdTorrentClose( tor->uniqueId );
2225
2226    if( tor->info.fileCount > 1 )
2227        deleteLocalData( tor, fileFunc );
2228    else {
2229        /* torrent only has one file */
2230        char * path = tr_buildPath( tor->downloadDir, tor->info.files[0].name, NULL );
2231        fileFunc( path );
2232        tr_free( path );
2233    }
2234}
2235
2236/***
2237****
2238***/
2239
2240struct LocationData
2241{
2242    tr_bool move_from_old_location;
2243    int * setme_state;
2244    double * setme_progress;
2245    char * location;
2246    tr_torrent * tor;
2247};
2248
2249static void
2250setLocation( void * vdata )
2251{
2252    int err = 0;
2253    struct LocationData * data = vdata;
2254    tr_torrent * tor = data->tor;
2255    const tr_bool do_move = data->move_from_old_location;
2256    const char * location = data->location;
2257    double bytesHandled = 0;
2258
2259    assert( tr_isTorrent( tor ) );
2260
2261    if( strcmp( location, tor->downloadDir ) )
2262    {
2263        tr_file_index_t i;
2264
2265        /* bad idea to move files while they're being verified... */
2266        tr_verifyRemove( tor );
2267
2268        /* if the torrent is running, stop it and set a flag to
2269         * restart after we're done */
2270        if( tor->isRunning )
2271        {
2272            tr_torrentStop( tor );
2273            tor->startAfterVerify = TRUE;
2274        }
2275
2276        /* try to move the files.
2277         * FIXME: there are still all kinds of nasty cases, like what
2278         * if the target directory runs out of space halfway through... */
2279        for( i=0; !err && i<tor->info.fileCount; ++i )
2280        {
2281            struct stat sb;
2282            const tr_file * f = &tor->info.files[i];
2283            char * oldpath = tr_buildPath( tor->downloadDir, f->name, NULL );
2284            char * newpath = tr_buildPath( location, f->name, NULL );
2285           
2286            if( do_move )
2287            {
2288                errno = 0;
2289                tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2290                if( tr_moveFile( oldpath, newpath ) ) {
2291                    err = 1;
2292                    tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2293                                    oldpath, newpath, tr_strerror( errno ) );
2294                }
2295            }
2296            else if( !stat( newpath, &sb ) )
2297            {
2298                tr_torinf( tor, "found \"%s\"", newpath );
2299            }
2300
2301            if( data->setme_progress )
2302            {
2303                bytesHandled += f->length;
2304                *data->setme_progress = bytesHandled / tor->info.totalSize;
2305            }
2306
2307            tr_free( newpath );
2308            tr_free( oldpath );
2309        }
2310
2311        if( !err )
2312        {
2313            /* blow away the leftover subdirectories in the old location */
2314            tr_torrentDeleteLocalData( tor, remove );
2315
2316            /* set the new location and reverify */
2317            tr_torrentSetDownloadDir( tor, location );
2318            tr_torrentVerify( tor );
2319        }
2320    }
2321
2322    if( data->setme_state )
2323        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2324
2325    /* cleanup */
2326    tr_free( data->location );
2327    tr_free( data );
2328}
2329
2330void
2331tr_torrentSetLocation( tr_torrent  * tor,
2332                       const char  * location,
2333                       tr_bool       move_from_old_location,
2334                       double      * setme_progress,
2335                       int         * setme_state )
2336{
2337    struct LocationData * data;
2338
2339    assert( tr_isTorrent( tor ) );
2340
2341    if( setme_state )
2342        *setme_state = TR_LOC_MOVING;
2343    if( setme_progress )
2344        *setme_progress = 0;
2345
2346    /* run this in the libtransmission thread */
2347    data = tr_new( struct LocationData, 1 );
2348    data->tor = tor;
2349    data->location = tr_strdup( location );
2350    data->move_from_old_location = move_from_old_location;
2351    data->setme_state = setme_state;
2352    data->setme_progress = setme_progress;
2353    tr_runInEventThread( tor->session, setLocation, data );
2354}
2355
2356/***
2357****
2358***/
2359
2360void
2361tr_torrentCheckSeedRatio( tr_torrent * tor )
2362{
2363    double seedRatio;
2364
2365    assert( tr_isTorrent( tor ) );
2366
2367    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2368    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2369    {
2370        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2371        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2372        double ratio;
2373
2374        /* maybe we're the initial seeder and never downloaded anything... */
2375        if( down == 0 )
2376            down = tr_cpHaveValid( &tor->completion );
2377
2378        ratio = tr_getRatio( up, down );
2379
2380        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2381        {
2382            tr_torrentStop( tor );
2383
2384            /* set to no ratio limit to allow easy restarting */
2385            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2386
2387            /* maybe notify the client */
2388            if( tor->ratio_limit_hit_func != NULL )
2389                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2390        }
2391    }
2392}
Note: See TracBrowser for help on using the repository browser.