source: trunk/libtransmission/torrent.c @ 8910

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

(trunk libT) fix #2162: .resume file doesn't get saved often enough when its contents change

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