source: trunk/libtransmission/torrent.c @ 8930

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

(trunk libT) revision to r8910 for #2162: check to see if a field's value has actually changed before setting the "dirty" flag.

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