source: trunk/libtransmission/torrent.c @ 8897

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

(trunk libT) possible fix for #2297 by removing potential thread issue in tr_torrentVerify()

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