source: trunk/libtransmission/torrent.c @ 8948

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

(trunk libT) a debugging message was accidenally being dumped to the terminal. Reported by ubuntuforums user "Nevermor7" in <http://ubuntuforums.org/showpost.php?p=7743702&postcount=1>

  • 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 8948 2009-08-16 21:09:08Z 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 ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
1873                              (unsigned long)index,
1874                              (unsigned long)offset,
1875                              (unsigned long)length,
1876                              err );
1877
1878    return !err;
1879}
1880
1881uint64_t
1882tr_pieceOffset( const tr_torrent * tor,
1883                tr_piece_index_t   index,
1884                uint32_t           offset,
1885                uint32_t           length )
1886{
1887    uint64_t ret;
1888
1889    assert( tr_isTorrent( tor ) );
1890
1891    ret = tor->info.pieceSize;
1892    ret *= index;
1893    ret += offset;
1894    ret += length;
1895    return ret;
1896}
1897
1898/***
1899****
1900***/
1901
1902void
1903tr_torrentSetPieceChecked( tr_torrent        * tor,
1904                           tr_piece_index_t    piece,
1905                           tr_bool             isChecked )
1906{
1907    assert( tr_isTorrent( tor ) );
1908
1909    if( isChecked )
1910        tr_bitfieldAdd( &tor->checkedPieces, piece );
1911    else
1912        tr_bitfieldRem( &tor->checkedPieces, piece );
1913}
1914
1915void
1916tr_torrentSetFileChecked( tr_torrent *    tor,
1917                          tr_file_index_t fileIndex,
1918                          tr_bool         isChecked )
1919{
1920    const tr_file *        file = &tor->info.files[fileIndex];
1921    const tr_piece_index_t begin = file->firstPiece;
1922    const tr_piece_index_t end = file->lastPiece + 1;
1923
1924    assert( tr_isTorrent( tor ) );
1925
1926    if( isChecked )
1927        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
1928    else
1929        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
1930}
1931
1932tr_bool
1933tr_torrentIsFileChecked( const tr_torrent * tor,
1934                         tr_file_index_t    fileIndex )
1935{
1936    const tr_file *        file = &tor->info.files[fileIndex];
1937    const tr_piece_index_t begin = file->firstPiece;
1938    const tr_piece_index_t end = file->lastPiece + 1;
1939    tr_piece_index_t       i;
1940    tr_bool                isChecked = TRUE;
1941
1942    assert( tr_isTorrent( tor ) );
1943
1944    for( i = begin; isChecked && i < end; ++i )
1945        if( !tr_torrentIsPieceChecked( tor, i ) )
1946            isChecked = FALSE;
1947
1948    return isChecked;
1949}
1950
1951void
1952tr_torrentUncheck( tr_torrent * tor )
1953{
1954    assert( tr_isTorrent( tor ) );
1955
1956    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
1957}
1958
1959int
1960tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1961{
1962    assert( tr_isTorrent( tor ) );
1963
1964    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
1965}
1966
1967time_t*
1968tr_torrentGetMTimes( const tr_torrent * tor,
1969                     size_t *           setme_n )
1970{
1971    size_t       i;
1972    const size_t n = tor->info.fileCount;
1973    time_t *     m = tr_new0( time_t, n );
1974
1975    assert( tr_isTorrent( tor ) );
1976
1977    for( i = 0; i < n; ++i )
1978    {
1979        struct stat sb;
1980        char * path = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
1981        if( !stat( path, &sb ) )
1982        {
1983#ifdef SYS_DARWIN
1984            m[i] = sb.st_mtimespec.tv_sec;
1985#else
1986            m[i] = sb.st_mtime;
1987#endif
1988        }
1989        tr_free( path );
1990    }
1991
1992    *setme_n = n;
1993    return m;
1994}
1995
1996/***
1997****
1998***/
1999
2000void
2001tr_torrentSetAnnounceList( tr_torrent *            tor,
2002                           const tr_tracker_info * trackers,
2003                           int                     trackerCount )
2004{
2005    tr_benc metainfo;
2006
2007    assert( tr_isTorrent( tor ) );
2008
2009    /* save to the .torrent file */
2010    if( !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2011    {
2012        int       i;
2013        int       prevTier = -1;
2014        tr_benc * tier = NULL;
2015        tr_benc * announceList;
2016        tr_info   tmpInfo;
2017
2018        /* remove the old fields */
2019        tr_bencDictRemove( &metainfo, "announce" );
2020        tr_bencDictRemove( &metainfo, "announce-list" );
2021
2022        /* add the new fields */
2023        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2024        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2025        for( i = 0; i < trackerCount; ++i ) {
2026            if( prevTier != trackers[i].tier ) {
2027                prevTier = trackers[i].tier;
2028                tier = tr_bencListAddList( announceList, 0 );
2029            }
2030            tr_bencListAddStr( tier, trackers[i].announce );
2031        }
2032
2033        /* try to parse it back again, to make sure it's good */
2034        memset( &tmpInfo, 0, sizeof( tr_info ) );
2035        if( tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
2036        {
2037            /* it's good, so keep these new trackers and free the old ones */
2038
2039            tr_info swap;
2040            swap.trackers = tor->info.trackers;
2041            swap.trackerCount = tor->info.trackerCount;
2042            tor->info.trackers = tmpInfo.trackers;
2043            tor->info.trackerCount = tmpInfo.trackerCount;
2044            tmpInfo.trackers = swap.trackers;
2045            tmpInfo.trackerCount = swap.trackerCount;
2046
2047            tr_metainfoFree( &tmpInfo );
2048            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2049        }
2050
2051        /* cleanup */
2052        tr_bencFree( &metainfo );
2053    }
2054}
2055
2056/**
2057***
2058**/
2059
2060void
2061tr_torrentSetAddedDate( tr_torrent * tor,
2062                        time_t       t )
2063{
2064    assert( tr_isTorrent( tor ) );
2065
2066    tor->addedDate = t;
2067    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2068}
2069
2070void
2071tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2072{
2073    assert( tr_isTorrent( tor ) );
2074
2075    tor->activityDate = t;
2076    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2077}
2078
2079void
2080tr_torrentSetDoneDate( tr_torrent * tor,
2081                       time_t       t )
2082{
2083    assert( tr_isTorrent( tor ) );
2084
2085    tor->doneDate = t;
2086    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2087}
2088
2089/**
2090***
2091**/
2092
2093uint64_t
2094tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2095{
2096    const tr_file * it;
2097    const tr_file * end;
2098    struct stat sb;
2099    uint64_t bytesLeft = 0;
2100
2101    assert( tr_isTorrent( tor ) );
2102
2103    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
2104    {
2105        if( !it->dnd )
2106        {
2107            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
2108
2109            bytesLeft += it->length;
2110
2111            if( !stat( path, &sb )
2112                    && S_ISREG( sb.st_mode )
2113                    && ( (uint64_t)sb.st_size <= it->length ) )
2114                bytesLeft -= sb.st_size;
2115
2116            tr_free( path );
2117        }
2118    }
2119
2120    return bytesLeft;
2121}
2122
2123/****
2124*****  Removing the torrent's local data
2125****/
2126
2127static int
2128vstrcmp( const void * a, const void * b )
2129{
2130    return strcmp( a, b );
2131}
2132
2133static int
2134compareLongestFirst( const void * a, const void * b )
2135{
2136    const size_t alen = strlen( a );
2137    const size_t blen = strlen( b );
2138
2139    if( alen != blen )
2140        return alen > blen ? -1 : 1;
2141
2142    return vstrcmp( a, b );
2143}
2144
2145static void
2146addDirtyFile( const char  * root,
2147              const char  * filename,
2148              tr_ptrArray * dirtyFolders )
2149{
2150    char * dir = tr_dirname( filename );
2151
2152    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2153    while (     ( dir != NULL )
2154             && ( strlen( root ) <= strlen( dir ) )
2155             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2156    {
2157        char * tmp;
2158        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2159
2160        tmp = tr_dirname( dir );
2161        tr_free( dir );
2162        dir = tmp;
2163    }
2164
2165    tr_free( dir );
2166}
2167
2168static void
2169walkLocalData( const tr_torrent * tor,
2170               const char       * root,
2171               const char       * dir,
2172               const char       * base,
2173               tr_ptrArray      * torrentFiles,
2174               tr_ptrArray      * folders,
2175               tr_ptrArray      * dirtyFolders )
2176{
2177    int i;
2178    struct stat sb;
2179    char * buf;
2180
2181    assert( tr_isTorrent( tor ) );
2182
2183    buf = tr_buildPath( dir, base, NULL );
2184    i = stat( buf, &sb );
2185    if( !i )
2186    {
2187        DIR * odir = NULL;
2188
2189        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2190        {
2191            struct dirent *d;
2192            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2193            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2194                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2195                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2196            closedir( odir );
2197        }
2198        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2199        {
2200            const char * sub = buf + strlen( tor->downloadDir ) + strlen( TR_PATH_DELIMITER_STR );
2201            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2202            if( !isTorrentFile )
2203                addDirtyFile( root, buf, dirtyFolders );
2204        }
2205    }
2206
2207    tr_free( buf );
2208}
2209
2210static void
2211deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2212{
2213    int i, n;
2214    char ** s;
2215    tr_file_index_t f;
2216    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2217    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2218    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2219
2220    const char * firstFile = tor->info.files[0].name;
2221    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2222    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2223    char * root = tr_buildPath( tor->downloadDir, tmp, NULL );
2224
2225    assert( tr_isTorrent( tor ) );
2226
2227    for( f=0; f<tor->info.fileCount; ++f )
2228        tr_ptrArrayInsertSorted( &torrentFiles, tor->info.files[f].name, vstrcmp );
2229
2230    /* build the set of folders and dirtyFolders */
2231    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2232
2233    /* try to remove entire folders first, so that the recycle bin will be tidy */
2234    s = (char**) tr_ptrArrayPeek( &folders, &n );
2235    for( i=0; i<n; ++i )
2236        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2237            fileFunc( s[i] );
2238
2239    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2240    for( f=0; f<tor->info.fileCount; ++f ) {
2241        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
2242        fileFunc( path );
2243        tr_free( path );
2244    }
2245
2246    /* Now clean out the directories left empty from the previous step.
2247     * Work from deepest to shallowest s.t. lower folders
2248     * won't prevent the upper folders from being deleted */
2249    {
2250        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2251        s = (char**) tr_ptrArrayPeek( &folders, &n );
2252        for( i=0; i<n; ++i )
2253            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2254                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2255        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2256        for( i=0; i<n; ++i )
2257            fileFunc( s[i] );
2258        tr_ptrArrayDestruct( &cleanFolders, NULL );
2259    }
2260
2261    /* cleanup */
2262    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2263    tr_ptrArrayDestruct( &folders, tr_free );
2264    tr_ptrArrayDestruct( &torrentFiles, NULL );
2265    tr_free( root );
2266    tr_free( tmp );
2267}
2268
2269void
2270tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2271{
2272    assert( tr_isTorrent( tor ) );
2273
2274    if( fileFunc == NULL )
2275        fileFunc = remove;
2276
2277    /* close all the files because we're about to delete them */
2278    tr_fdTorrentClose( tor->uniqueId );
2279
2280    if( tor->info.fileCount > 1 )
2281        deleteLocalData( tor, fileFunc );
2282    else {
2283        /* torrent only has one file */
2284        char * path = tr_buildPath( tor->downloadDir, tor->info.files[0].name, NULL );
2285        fileFunc( path );
2286        tr_free( path );
2287    }
2288}
2289
2290/***
2291****
2292***/
2293
2294struct LocationData
2295{
2296    tr_bool move_from_old_location;
2297    int * setme_state;
2298    double * setme_progress;
2299    char * location;
2300    tr_torrent * tor;
2301};
2302
2303static void
2304setLocation( void * vdata )
2305{
2306    int err = 0;
2307    struct LocationData * data = vdata;
2308    tr_torrent * tor = data->tor;
2309    const tr_bool do_move = data->move_from_old_location;
2310    const char * location = data->location;
2311    double bytesHandled = 0;
2312
2313    assert( tr_isTorrent( tor ) );
2314
2315    if( strcmp( location, tor->downloadDir ) )
2316    {
2317        tr_file_index_t i;
2318
2319        /* bad idea to move files while they're being verified... */
2320        tr_verifyRemove( tor );
2321
2322        /* if the torrent is running, stop it and set a flag to
2323         * restart after we're done */
2324        if( tor->isRunning )
2325        {
2326            tr_torrentStop( tor );
2327            tor->startAfterVerify = TRUE;
2328        }
2329
2330        /* try to move the files.
2331         * FIXME: there are still all kinds of nasty cases, like what
2332         * if the target directory runs out of space halfway through... */
2333        for( i=0; !err && i<tor->info.fileCount; ++i )
2334        {
2335            struct stat sb;
2336            const tr_file * f = &tor->info.files[i];
2337            char * oldpath = tr_buildPath( tor->downloadDir, f->name, NULL );
2338            char * newpath = tr_buildPath( location, f->name, NULL );
2339
2340            if( do_move )
2341            {
2342                errno = 0;
2343                tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2344                if( tr_moveFile( oldpath, newpath ) ) {
2345                    err = 1;
2346                    tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2347                                    oldpath, newpath, tr_strerror( errno ) );
2348                }
2349            }
2350            else if( !stat( newpath, &sb ) )
2351            {
2352                tr_torinf( tor, "found \"%s\"", newpath );
2353            }
2354
2355            if( data->setme_progress )
2356            {
2357                bytesHandled += f->length;
2358                *data->setme_progress = bytesHandled / tor->info.totalSize;
2359            }
2360
2361            tr_free( newpath );
2362            tr_free( oldpath );
2363        }
2364
2365        if( !err )
2366        {
2367            /* blow away the leftover subdirectories in the old location */
2368            tr_torrentDeleteLocalData( tor, remove );
2369
2370            /* set the new location and reverify */
2371            tr_torrentSetDownloadDir( tor, location );
2372            tr_torrentVerify( tor );
2373        }
2374    }
2375
2376    if( data->setme_state )
2377        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2378
2379    /* cleanup */
2380    tr_free( data->location );
2381    tr_free( data );
2382}
2383
2384void
2385tr_torrentSetLocation( tr_torrent  * tor,
2386                       const char  * location,
2387                       tr_bool       move_from_old_location,
2388                       double      * setme_progress,
2389                       int         * setme_state )
2390{
2391    struct LocationData * data;
2392
2393    assert( tr_isTorrent( tor ) );
2394
2395    if( setme_state )
2396        *setme_state = TR_LOC_MOVING;
2397    if( setme_progress )
2398        *setme_progress = 0;
2399
2400    /* run this in the libtransmission thread */
2401    data = tr_new( struct LocationData, 1 );
2402    data->tor = tor;
2403    data->location = tr_strdup( location );
2404    data->move_from_old_location = move_from_old_location;
2405    data->setme_state = setme_state;
2406    data->setme_progress = setme_progress;
2407    tr_runInEventThread( tor->session, setLocation, data );
2408}
2409
2410/***
2411****
2412***/
2413
2414void
2415tr_torrentCheckSeedRatio( tr_torrent * tor )
2416{
2417    double seedRatio;
2418
2419    assert( tr_isTorrent( tor ) );
2420
2421    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2422    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2423    {
2424        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2425        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2426        double ratio;
2427
2428        /* maybe we're the initial seeder and never downloaded anything... */
2429        if( down == 0 )
2430            down = tr_cpHaveValid( &tor->completion );
2431
2432        ratio = tr_getRatio( up, down );
2433
2434        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2435        {
2436            tr_torrentStop( tor );
2437
2438            /* set to no ratio limit to allow easy restarting */
2439            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2440
2441            /* maybe notify the client */
2442            if( tor->ratio_limit_hit_func != NULL )
2443                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2444        }
2445    }
2446}
Note: See TracBrowser for help on using the repository browser.