source: branches/1.7x/libtransmission/torrent.c @ 9362

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

(1.7x) backports for 1.76: r9251 #2393 possible dataloss when trying to move torrents to the directory they're already in :/

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