source: trunk/libtransmission/torrent.c @ 8912

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

(trunk libT) fix #2332: filesystem-based error messages lack context

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