source: trunk/libtransmission/torrent.c @ 8940

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

(trunk libT) fix pause-on-shutdown bug reported by KyleK and introduced in r8878 for #2317.

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