source: trunk/libtransmission/torrent.c @ 9549

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

(trunk libT) jch's patches 0001 through 0004 for ticket #2576, IPv6 support for DHT (BEP #32)

  • Property svn:keywords set to Date Rev Author Id
File size: 69.9 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 9549 2009-11-24 01:59:51Z 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 "announcer.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 "session.h"
41#include "torrent.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 refreshCurrentDir( tr_torrent * tor );;
554
555static void
556torrentRealInit( tr_torrent * tor, const tr_ctor * ctor )
557{
558    int          doStart;
559    uint64_t     loaded;
560    uint64_t     t;
561    const char * dir;
562    static int   nextUniqueId = 1;
563    tr_info    * info = &tor->info;
564    tr_session * session = tr_ctorGetSession( ctor );
565
566    assert( session != NULL );
567
568    tr_globalLock( session );
569
570    tor->session   = session;
571    tor->uniqueId = nextUniqueId++;
572    tor->magicNumber = TORRENT_MAGIC_NUMBER;
573
574    randomizeTiers( info );
575
576    tor->bandwidth = tr_bandwidthNew( session, session->bandwidth );
577
578    tor->blockSize = getBlockSize( info->pieceSize );
579
580    if( !tr_ctorGetDownloadDir( ctor, TR_FORCE, &dir ) ||
581        !tr_ctorGetDownloadDir( ctor, TR_FALLBACK, &dir ) )
582            tor->downloadDir = tr_strdup( dir );
583
584    if( tr_ctorGetIncompleteDir( ctor, &dir ) )
585        dir = tr_sessionGetIncompleteDir( session );
586    if( tr_sessionIsIncompleteDirEnabled( session ) )
587        tor->incompleteDir = tr_strdup( dir );
588
589    tor->lastPieceSize = info->totalSize % info->pieceSize;
590
591    if( !tor->lastPieceSize )
592        tor->lastPieceSize = info->pieceSize;
593
594    tor->lastBlockSize = info->totalSize % tor->blockSize;
595
596    if( !tor->lastBlockSize )
597        tor->lastBlockSize = tor->blockSize;
598
599    tor->blockCount =
600        ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize;
601
602    tor->blockCountInPiece =
603        info->pieceSize / tor->blockSize;
604
605    tor->blockCountInLastPiece =
606        ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize;
607
608    /* check our work */
609    assert( ( info->pieceSize % tor->blockSize ) == 0 );
610    t = info->pieceCount - 1;
611    t *= info->pieceSize;
612    t += tor->lastPieceSize;
613    assert( t == info->totalSize );
614    t = tor->blockCount - 1;
615    t *= tor->blockSize;
616    t += tor->lastBlockSize;
617    assert( t == info->totalSize );
618    t = info->pieceCount - 1;
619    t *= tor->blockCountInPiece;
620    t += tor->blockCountInLastPiece;
621    assert( t == (uint64_t)tor->blockCount );
622
623    tr_cpConstruct( &tor->completion, tor );
624
625    tr_torrentInitFilePieces( tor );
626
627    tr_sha1( tor->obfuscatedHash, "req2", 4,
628             info->hash, SHA_DIGEST_LENGTH,
629             NULL );
630
631    tr_peerMgrAddTorrent( session->peerMgr, tor );
632
633    assert( !tor->downloadedCur );
634    assert( !tor->uploadedCur );
635
636    tr_ctorInitTorrentPriorities( ctor, tor );
637
638    tr_ctorInitTorrentWanted( ctor, tor );
639
640    tor->error = TR_STAT_OK;
641
642    tr_bitfieldConstruct( &tor->checkedPieces, tor->info.pieceCount );
643    tr_torrentUncheck( tor );
644
645    tr_torrentSetAddedDate( tor, time( NULL ) ); /* this is a default value to be
646                                                    overwritten by the resume file */
647
648    loaded = tr_torrentLoadResume( tor, ~0, ctor );
649
650    refreshCurrentDir( tor );
651
652    doStart = tor->isRunning;
653    tor->isRunning = 0;
654
655    if( !( loaded & TR_FR_SPEEDLIMIT ) )
656    {
657        tr_torrentUseSpeedLimit( tor, TR_UP, FALSE );
658        tr_torrentSetSpeedLimit( tor, TR_UP, tr_sessionGetSpeedLimit( tor->session, TR_UP ) );
659        tr_torrentUseSpeedLimit( tor, TR_DOWN, FALSE );
660        tr_torrentSetSpeedLimit( tor, TR_DOWN, tr_sessionGetSpeedLimit( tor->session, TR_DOWN ) );
661        tr_torrentUseSessionLimits( tor, TRUE );
662    }
663
664    if( !( loaded & TR_FR_RATIOLIMIT ) )
665    {
666        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_GLOBAL );
667        tr_torrentSetRatioLimit( tor, tr_sessionGetRatioLimit( tor->session ) );
668    }
669
670    tor->completeness = tr_cpGetStatus( &tor->completion );
671
672    {
673        tr_torrent * it = NULL;
674        tr_torrent * last = NULL;
675        while( ( it = tr_torrentNext( session, it ) ) )
676            last = it;
677
678        if( !last )
679            session->torrentList = tor;
680        else
681            last->next = tor;
682        ++session->torrentCount;
683    }
684
685    tr_globalUnlock( session );
686
687    /* maybe save our own copy of the metainfo */
688    if( tr_ctorGetSave( ctor ) )
689    {
690        const tr_benc * val;
691        if( !tr_ctorGetMetainfo( ctor, &val ) )
692        {
693            const char * filename = tor->info.torrent;
694            tr_bencToFile( val, TR_FMT_BENC, filename );
695            tr_sessionSetTorrentFile( tor->session, tor->info.hashString, filename );
696        }
697    }
698
699    tor->tiers = tr_announcerAddTorrent( session->announcer, tor );
700    tor->tiersSubscription = tr_announcerSubscribe( tor->tiers, onTrackerResponse, tor );
701
702    tr_metainfoMigrate( session, &tor->info );
703
704    if( doStart )
705        torrentStart( tor );
706}
707
708tr_parse_result
709tr_torrentParse( const tr_ctor * ctor, tr_info * setmeInfo )
710{
711    int             doFree;
712    tr_bool         didParse;
713    tr_info         tmp;
714    const tr_benc * metainfo;
715    tr_session    * session = tr_ctorGetSession( ctor );
716    tr_parse_result result = TR_PARSE_OK;
717
718    if( setmeInfo == NULL )
719        setmeInfo = &tmp;
720    memset( setmeInfo, 0, sizeof( tr_info ) );
721
722    if( tr_ctorGetMetainfo( ctor, &metainfo ) )
723        return TR_PARSE_ERR;
724
725    didParse = tr_metainfoParse( session, setmeInfo, metainfo );
726    doFree = didParse && ( setmeInfo == &tmp );
727
728    if( !didParse )
729        result = TR_PARSE_ERR;
730
731    if( didParse && !getBlockSize( setmeInfo->pieceSize ) )
732        result = TR_PARSE_ERR;
733
734    if( didParse && session && tr_torrentExists( session, setmeInfo->hash ) )
735        result = TR_PARSE_DUPLICATE;
736
737    if( doFree )
738        tr_metainfoFree( setmeInfo );
739
740    return result;
741}
742
743tr_torrent *
744tr_torrentNew( const tr_ctor  * ctor,
745               int            * setmeError )
746{
747    int          err;
748    tr_info      tmpInfo;
749    tr_torrent * tor = NULL;
750
751    assert( ctor != NULL );
752    assert( tr_isSession( tr_ctorGetSession( ctor ) ) );
753
754    err = tr_torrentParse( ctor, &tmpInfo );
755    if( !err )
756    {
757        tor = tr_new0( tr_torrent, 1 );
758        tor->info = tmpInfo;
759        torrentRealInit( tor, ctor );
760    }
761    else if( setmeError )
762    {
763        *setmeError = err;
764    }
765
766    return tor;
767}
768
769/**
770***
771**/
772
773void
774tr_torrentSetDownloadDir( tr_torrent * tor, const char * path )
775{
776    assert( tr_isTorrent( tor  ) );
777
778    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
779    {
780        tr_free( tor->downloadDir );
781        tor->downloadDir = tr_strdup( path );
782        tr_torrentSetDirty( tor );
783    }
784
785    refreshCurrentDir( tor );
786}
787
788const char*
789tr_torrentGetDownloadDir( const tr_torrent * tor )
790{
791    assert( tr_isTorrent( tor  ) );
792
793    return tor->downloadDir;
794}
795
796const char *
797tr_torrentGetCurrentDir( const tr_torrent * tor )
798{
799    assert( tr_isTorrent( tor  ) );
800
801    return tor->currentDir;
802}
803
804
805void
806tr_torrentChangeMyPort( tr_torrent * tor )
807{
808    assert( tr_isTorrent( tor  ) );
809
810    tr_announcerChangeMyPort( tor );
811}
812
813static TR_INLINE void
814tr_torrentManualUpdateImpl( void * vtor )
815{
816    tr_torrent * tor = vtor;
817
818    assert( tr_isTorrent( tor  ) );
819
820    if( tor->isRunning )
821        tr_announcerManualAnnounce( tor );
822}
823
824void
825tr_torrentManualUpdate( tr_torrent * tor )
826{
827    assert( tr_isTorrent( tor  ) );
828
829    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
830}
831
832tr_bool
833tr_torrentCanManualUpdate( const tr_torrent * tor )
834{
835    return ( tr_isTorrent( tor  ) )
836        && ( tor->isRunning )
837        && ( tr_announcerCanManualAnnounce( tor ) );
838}
839
840const tr_info *
841tr_torrentInfo( const tr_torrent * tor )
842{
843    return tr_isTorrent( tor ) ? &tor->info : NULL;
844}
845
846const tr_stat *
847tr_torrentStatCached( tr_torrent * tor )
848{
849    const time_t now = time( NULL );
850
851    return tr_isTorrent( tor ) && ( now == tor->lastStatTime )
852         ? &tor->stats
853         : tr_torrentStat( tor );
854}
855
856void
857tr_torrentSetVerifyState( tr_torrent * tor, tr_verify_state state )
858{
859    assert( tr_isTorrent( tor ) );
860    assert( state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW );
861
862    tor->verifyState = state;
863    tor->anyDate = time( NULL );
864}
865
866tr_torrent_activity
867tr_torrentGetActivity( tr_torrent * tor )
868{
869    assert( tr_isTorrent( tor ) );
870
871    tr_torrentRecheckCompleteness( tor );
872
873    if( tor->verifyState == TR_VERIFY_NOW )
874        return TR_STATUS_CHECK;
875    if( tor->verifyState == TR_VERIFY_WAIT )
876        return TR_STATUS_CHECK_WAIT;
877    if( !tor->isRunning )
878        return TR_STATUS_STOPPED;
879    if( tor->completeness == TR_LEECH )
880        return TR_STATUS_DOWNLOAD;
881
882    return TR_STATUS_SEED;
883}
884
885const tr_stat *
886tr_torrentStat( tr_torrent * tor )
887{
888    tr_stat *               s;
889    int                     usableSeeds;
890    uint64_t                now;
891    double                  downloadedForRatio, seedRatio=0;
892    double                  d;
893    tr_bool                 checkSeedRatio;
894
895    if( !tor )
896        return NULL;
897
898    assert( tr_isTorrent( tor ) );
899    tr_torrentLock( tor );
900
901    tor->lastStatTime = time( NULL );
902
903    s = &tor->stats;
904    s->id = tor->uniqueId;
905    s->activity = tr_torrentGetActivity( tor );
906    s->error = tor->error;
907    memcpy( s->errorString, tor->errorString, sizeof( s->errorString ) );
908
909    s->manualAnnounceTime = tr_announcerNextManualAnnounce( tor );
910
911    tr_peerMgrTorrentStats( tor,
912                            &s->peersKnown,
913                            &s->peersConnected,
914                            &usableSeeds,
915                            &s->webseedsSendingToUs,
916                            &s->peersSendingToUs,
917                            &s->peersGettingFromUs,
918                            s->peersFrom );
919
920    now = tr_date( );
921    d = tr_peerMgrGetWebseedSpeed( tor, now );
922    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
923    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
924    s->rawDownloadSpeed   = d + tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
925    s->pieceDownloadSpeed = d + tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
926
927    usableSeeds += tor->info.webseedCount;
928
929    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
930
931    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
932    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
933    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
934
935    s->recheckProgress = s->activity == TR_STATUS_CHECK
936                       ? 1.0 -
937                         ( tr_torrentCountUncheckedPieces( tor ) /
938                           (double) tor->info.pieceCount )
939                       : 0.0;
940
941    s->activityDate = tor->activityDate;
942    s->addedDate    = tor->addedDate;
943    s->doneDate     = tor->doneDate;
944    s->startDate    = tor->startDate;
945
946    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
947    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
948    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
949    s->haveValid       = tr_cpHaveValid( &tor->completion );
950    s->haveUnchecked   = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
951
952    if( usableSeeds > 0 )
953    {
954        s->desiredAvailable = s->leftUntilDone;
955    }
956    else if( !s->leftUntilDone || !s->peersConnected )
957    {
958        s->desiredAvailable = 0;
959    }
960    else
961    {
962        tr_piece_index_t i;
963        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable( tor );
964        s->desiredAvailable = 0;
965        for( i = 0; i < tor->info.pieceCount; ++i )
966            if( !tor->info.pieces[i].dnd && tr_bitfieldHasFast( peerPieces, i ) )
967                s->desiredAvailable += tr_cpMissingBlocksInPiece( &tor->completion, i );
968        s->desiredAvailable *= tor->blockSize;
969        tr_bitfieldFree( peerPieces );
970    }
971
972    downloadedForRatio = s->downloadedEver ? s->downloadedEver : s->haveValid;
973    s->ratio = tr_getRatio( s->uploadedEver, downloadedForRatio );
974
975    checkSeedRatio = tr_torrentGetSeedRatio( tor, &seedRatio );
976
977    switch( s->activity )
978    {
979        /* etaXLSpeed exists because if we use the piece speed directly,
980         * brief fluctuations cause the ETA to jump all over the place.
981         * so, etaXLSpeed is a smoothed-out version of the piece speed
982         * to dampen the effect of fluctuations */
983
984        case TR_STATUS_DOWNLOAD:
985            if( ( tor->etaDLSpeedCalculatedAt + 800 ) < now ) {
986                tor->etaDLSpeed = ( ( tor->etaDLSpeedCalculatedAt + 4000 ) < now )
987                    ? s->pieceDownloadSpeed /* if no recent previous speed, no need to smooth */
988                    : 0.8*tor->etaDLSpeed + 0.2*s->pieceDownloadSpeed; /* smooth across 5 readings */
989                tor->etaDLSpeedCalculatedAt = now;
990            }
991           
992            if( s->leftUntilDone > s->desiredAvailable )
993                s->eta = TR_ETA_NOT_AVAIL;
994            else if( s->pieceDownloadSpeed < 0.1 )
995                s->eta = TR_ETA_UNKNOWN;
996            else
997                s->eta = s->leftUntilDone / tor->etaDLSpeed / 1024.0;
998            break;
999
1000        case TR_STATUS_SEED:
1001            if( checkSeedRatio )
1002            {
1003                if( ( tor->etaULSpeedCalculatedAt + 800 ) < now ) {
1004                    tor->etaULSpeed = ( ( tor->etaULSpeedCalculatedAt + 4000 ) < now )
1005                        ? s->pieceUploadSpeed /* if no recent previous speed, no need to smooth */
1006                        : 0.8*tor->etaULSpeed + 0.2*s->pieceUploadSpeed; /* smooth across 5 readings */
1007                    tor->etaULSpeedCalculatedAt = now;
1008                }
1009               
1010                if( s->pieceUploadSpeed < 0.1 )
1011                    s->eta = TR_ETA_UNKNOWN;
1012                else
1013                    s->eta = (downloadedForRatio * (seedRatio - s->ratio)) / tor->etaULSpeed / 1024.0;
1014            }
1015            else
1016                s->eta = TR_ETA_NOT_AVAIL;
1017            break;
1018
1019        default:
1020            s->eta = TR_ETA_NOT_AVAIL;
1021            break;
1022    }
1023   
1024    if( !checkSeedRatio || s->ratio >= seedRatio || s->ratio == TR_RATIO_INF ) 
1025        s->percentRatio = 1.0; 
1026    else if( s->ratio == TR_RATIO_NA ) 
1027        s->percentRatio = 0.0; 
1028    else 
1029        s->percentRatio = s->ratio / seedRatio; 
1030
1031    tr_torrentUnlock( tor );
1032
1033    return s;
1034}
1035
1036/***
1037****
1038***/
1039
1040static uint64_t
1041fileBytesCompleted( const tr_torrent * tor, tr_file_index_t index )
1042{
1043    uint64_t total = 0;
1044    const tr_file * f = &tor->info.files[index];
1045
1046    if( f->length )
1047    {
1048        const tr_block_index_t firstBlock = f->offset / tor->blockSize;
1049        const uint64_t lastByte = f->offset + f->length - 1;
1050        const tr_block_index_t lastBlock = lastByte / tor->blockSize;
1051
1052        if( firstBlock == lastBlock )
1053        {
1054            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1055                total = f->length;
1056        }
1057        else
1058        {
1059            tr_block_index_t i;
1060
1061            /* the first block */
1062            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1063                total += tor->blockSize - ( f->offset % tor->blockSize );
1064
1065            /* the middle blocks */
1066            if( f->firstPiece == f->lastPiece )
1067            {
1068                for( i=firstBlock+1; i<lastBlock; ++i )
1069                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1070                        total += tor->blockSize;
1071            }
1072            else
1073            {
1074                uint64_t b = 0;
1075                const tr_block_index_t firstBlockOfLastPiece
1076                           = tr_torPieceFirstBlock( tor, f->lastPiece );
1077                const tr_block_index_t lastBlockOfFirstPiece
1078                           = tr_torPieceFirstBlock( tor, f->firstPiece )
1079                             + tr_torPieceCountBlocks( tor, f->firstPiece ) - 1;
1080
1081                /* the rest of the first piece */
1082                for( i=firstBlock+1; i<lastBlock && i<=lastBlockOfFirstPiece; ++i )
1083                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1084                        ++b;
1085
1086                /* the middle pieces */
1087                if( f->firstPiece + 1 < f->lastPiece )
1088                    for( i=f->firstPiece+1; i<f->lastPiece; ++i )
1089                        b += tor->blockCountInPiece - tr_cpMissingBlocksInPiece( &tor->completion, i );
1090
1091                /* the rest of the last piece */
1092                for( i=firstBlockOfLastPiece; i<lastBlock; ++i )
1093                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1094                        ++b;
1095
1096                b *= tor->blockSize;
1097                total += b;
1098            }
1099
1100            /* the last block */
1101            if( tr_cpBlockIsCompleteFast( &tor->completion, lastBlock ) )
1102                total += ( f->offset + f->length ) - ( tor->blockSize * lastBlock );
1103        }
1104    }
1105
1106    return total;
1107}
1108
1109tr_file_stat *
1110tr_torrentFiles( const tr_torrent * tor,
1111                 tr_file_index_t *  fileCount )
1112{
1113    tr_file_index_t       i;
1114    const tr_file_index_t n = tor->info.fileCount;
1115    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1116    tr_file_stat *        walk = files;
1117    const tr_bool         isSeed = tor->completeness == TR_SEED;
1118
1119    assert( tr_isTorrent( tor ) );
1120
1121    for( i=0; i<n; ++i, ++walk ) {
1122        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1123        walk->bytesCompleted = b;
1124        walk->progress = tr_getRatio( b, tor->info.files[i].length );
1125    }
1126
1127    if( fileCount )
1128        *fileCount = n;
1129
1130    return files;
1131}
1132
1133void
1134tr_torrentFilesFree( tr_file_stat *            files,
1135                     tr_file_index_t fileCount UNUSED )
1136{
1137    tr_free( files );
1138}
1139
1140/***
1141****
1142***/
1143
1144float*
1145tr_torrentWebSpeeds( const tr_torrent * tor )
1146{
1147    return tr_isTorrent( tor )
1148         ? tr_peerMgrWebSpeeds( tor )
1149         : NULL;
1150}
1151
1152tr_peer_stat *
1153tr_torrentPeers( const tr_torrent * tor,
1154                 int *              peerCount )
1155{
1156    tr_peer_stat * ret = NULL;
1157
1158    if( tr_isTorrent( tor ) )
1159        ret = tr_peerMgrPeerStats( tor, peerCount );
1160
1161    return ret;
1162}
1163
1164void
1165tr_torrentPeersFree( tr_peer_stat * peers,
1166                     int peerCount  UNUSED )
1167{
1168    tr_free( peers );
1169}
1170
1171tr_tracker_stat *
1172tr_torrentTrackers( const tr_torrent * torrent,
1173                    int              * setmeTrackerCount )
1174{
1175    assert( tr_isTorrent( torrent ) );
1176
1177    return tr_announcerStats( torrent, setmeTrackerCount );
1178}
1179
1180void
1181tr_torrentTrackersFree( tr_tracker_stat * trackers,
1182                        int trackerCount )
1183{
1184    tr_announcerStatsFree( trackers, trackerCount );
1185}
1186
1187void
1188tr_torrentAvailability( const tr_torrent * tor,
1189                        int8_t *           tab,
1190                        int                size )
1191{
1192    tr_peerMgrTorrentAvailability( tor, tab, size );
1193}
1194
1195void
1196tr_torrentAmountFinished( const tr_torrent * tor,
1197                          float *            tab,
1198                          int                size )
1199{
1200    assert( tr_isTorrent( tor ) );
1201
1202    tr_torrentLock( tor );
1203    tr_cpGetAmountDone( &tor->completion, tab, size );
1204    tr_torrentUnlock( tor );
1205}
1206
1207static void
1208tr_torrentResetTransferStats( tr_torrent * tor )
1209{
1210    assert( tr_isTorrent( tor ) );
1211
1212    tr_torrentLock( tor );
1213
1214    tor->downloadedPrev += tor->downloadedCur;
1215    tor->downloadedCur   = 0;
1216    tor->uploadedPrev   += tor->uploadedCur;
1217    tor->uploadedCur     = 0;
1218    tor->corruptPrev    += tor->corruptCur;
1219    tor->corruptCur      = 0;
1220
1221    tr_torrentSetDirty( tor );
1222
1223    tr_torrentUnlock( tor );
1224}
1225
1226void
1227tr_torrentSetHasPiece( tr_torrent *     tor,
1228                       tr_piece_index_t pieceIndex,
1229                       tr_bool          has )
1230{
1231    assert( tr_isTorrent( tor ) );
1232    assert( pieceIndex < tor->info.pieceCount );
1233
1234    if( has )
1235        tr_cpPieceAdd( &tor->completion, pieceIndex );
1236    else
1237        tr_cpPieceRem( &tor->completion, pieceIndex );
1238}
1239
1240/***
1241****
1242***/
1243
1244static void
1245freeTorrent( tr_torrent * tor )
1246{
1247    tr_torrent * t;
1248    tr_session *  session = tor->session;
1249    tr_info *    inf = &tor->info;
1250
1251    assert( tr_isTorrent( tor ) );
1252    assert( !tor->isRunning );
1253
1254    tr_globalLock( session );
1255
1256    tr_peerMgrRemoveTorrent( tor );
1257
1258    tr_cpDestruct( &tor->completion );
1259
1260    tr_announcerUnsubscribe( tor->tiers, tor->tiersSubscription );
1261    tr_announcerRemoveTorrent( session->announcer, tor );
1262
1263    tr_bitfieldDestruct( &tor->checkedPieces );
1264
1265    tr_free( tor->downloadDir );
1266    tr_free( tor->incompleteDir );
1267    tr_free( tor->peer_id );
1268
1269    if( tor == session->torrentList )
1270        session->torrentList = tor->next;
1271    else for( t = session->torrentList; t != NULL; t = t->next ) {
1272        if( t->next == tor ) {
1273            t->next = tor->next;
1274            break;
1275        }
1276    }
1277
1278    assert( session->torrentCount >= 1 );
1279    session->torrentCount--;
1280
1281    tr_bandwidthFree( tor->bandwidth );
1282
1283    tr_metainfoFree( inf );
1284    tr_free( tor );
1285
1286    tr_globalUnlock( session );
1287}
1288
1289/**
1290***  Start/Stop Callback
1291**/
1292
1293static void
1294checkAndStartImpl( void * vtor )
1295{
1296    tr_torrent * tor = vtor;
1297
1298    assert( tr_isTorrent( tor ) );
1299
1300    tr_globalLock( tor->session );
1301
1302    /** If we had local data before, but it's disappeared,
1303        stop the torrent and log an error. */
1304    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1305    {
1306        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1307        tr_torrentStop( tor );
1308    }
1309    else
1310    {
1311        const time_t now = time( NULL );
1312        tor->isRunning = TRUE;
1313        tor->needsSeedRatioCheck = TRUE;
1314        tor->error = TR_STAT_OK;
1315        tor->errorString[0] = '\0';
1316        tor->completeness = tr_cpGetStatus( &tor->completion );
1317        tor->startDate = tor->anyDate = now;
1318
1319        tr_torrentResetTransferStats( tor );
1320        tr_announcerTorrentStarted( tor );
1321        tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1322        tor->dhtAnnounce6At = now + tr_cryptoWeakRandInt( 20 );
1323        tr_peerMgrStartTorrent( tor );
1324    }
1325
1326    tr_globalUnlock( tor->session );
1327}
1328
1329static void
1330checkAndStartCB( tr_torrent * tor )
1331{
1332    assert( tr_isTorrent( tor ) );
1333    assert( tr_isSession( tor->session ) );
1334
1335    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1336}
1337
1338static void
1339torrentStart( tr_torrent * tor )
1340{
1341    assert( tr_isTorrent( tor ) );
1342
1343    tr_globalLock( tor->session );
1344
1345    if( !tor->isRunning )
1346    {
1347        tr_verifyRemove( tor );
1348
1349        /* corresponds to the peer_id sent as a tracker request parameter.
1350         * one tracker admin says: "When the same torrent is opened and
1351         * closed and opened again without quitting Transmission ...
1352         * change the peerid. It would help sometimes if a stopped event
1353         * was missed to ensure that we didn't think someone was cheating. */
1354        tr_free( tor->peer_id );
1355        tor->peer_id = tr_peerIdNew( );
1356
1357        tor->isRunning = 1;
1358        tr_torrentSetDirty( tor );
1359        tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1360        tr_verifyAdd( tor, checkAndStartCB );
1361    }
1362
1363    tr_globalUnlock( tor->session );
1364}
1365
1366void
1367tr_torrentStart( tr_torrent * tor )
1368{
1369    if( tr_isTorrent( tor ) )
1370        torrentStart( tor );
1371}
1372
1373static void
1374torrentRecheckDoneImpl( void * vtor )
1375{
1376    tr_torrent * tor = vtor;
1377
1378    assert( tr_isTorrent( tor ) );
1379    tr_torrentRecheckCompleteness( tor );
1380
1381    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1382    {
1383        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1384        tr_torrentStop( tor );
1385    }
1386    else if( tor->startAfterVerify )
1387    {
1388        tor->startAfterVerify = FALSE;
1389
1390        tr_torrentStart( tor );
1391    }
1392}
1393
1394static void
1395torrentRecheckDoneCB( tr_torrent * tor )
1396{
1397    assert( tr_isTorrent( tor ) );
1398
1399    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1400}
1401
1402static void
1403verifyTorrent( void * vtor )
1404{
1405    tr_torrent * tor = vtor;
1406
1407    assert( tr_isTorrent( tor ) );
1408    tr_globalLock( tor->session );
1409
1410    /* if the torrent's already being verified, stop it */
1411    tr_verifyRemove( tor );
1412
1413    /* if the torrent's running, stop it & set the restart-after-verify flag */
1414    if( tor->startAfterVerify || tor->isRunning ) {
1415        tr_torrentStop( tor );
1416        tor->startAfterVerify = TRUE;
1417    }
1418
1419    /* add the torrent to the recheck queue */
1420    tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1421    tr_torrentUncheck( tor );
1422    tr_verifyAdd( tor, torrentRecheckDoneCB );
1423
1424    tr_globalUnlock( tor->session );
1425}
1426
1427void
1428tr_torrentVerify( tr_torrent * tor )
1429{
1430    if( tr_isTorrent( tor ) )
1431        tr_runInEventThread( tor->session, verifyTorrent, tor );
1432}
1433
1434void
1435tr_torrentSave( tr_torrent * tor )
1436{
1437    assert( tr_isTorrent( tor ) );
1438
1439    if( tor->isDirty ) {
1440        tor->isDirty = FALSE;
1441        tr_torrentSaveResume( tor );
1442    }
1443}
1444
1445static void
1446stopTorrent( void * vtor )
1447{
1448    tr_torrent * tor = vtor;
1449
1450    assert( tr_isTorrent( tor ) );
1451
1452    tr_verifyRemove( tor );
1453    tr_peerMgrStopTorrent( tor );
1454    tr_announcerTorrentStopped( tor );
1455
1456    tr_fdTorrentClose( tor->session, tor->uniqueId );
1457
1458    if( !tor->isDeleting )
1459        tr_torrentSave( tor );
1460}
1461
1462void
1463tr_torrentStop( tr_torrent * tor )
1464{
1465    assert( tr_isTorrent( tor ) );
1466
1467    if( tr_isTorrent( tor ) )
1468    {
1469        tr_globalLock( tor->session );
1470
1471        tor->isRunning = 0;
1472        tr_torrentSetDirty( tor );
1473        tr_runInEventThread( tor->session, stopTorrent, tor );
1474
1475        tr_globalUnlock( tor->session );
1476    }
1477}
1478
1479static void
1480closeTorrent( void * vtor )
1481{
1482    tr_benc * d;
1483    tr_torrent * tor = vtor;
1484
1485    assert( tr_isTorrent( tor ) );
1486
1487    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1488    tr_bencDictAddInt( d, "id", tor->uniqueId );
1489    tr_bencDictAddInt( d, "date", time( NULL ) );
1490
1491    stopTorrent( tor );
1492
1493    if( tor->isDeleting )
1494    {
1495        tr_metainfoRemoveSaved( tor->session, &tor->info );
1496        tr_torrentRemoveResume( tor );
1497    }
1498
1499    tor->isRunning = 0;
1500    freeTorrent( tor );
1501}
1502
1503void
1504tr_torrentFree( tr_torrent * tor )
1505{
1506    if( tr_isTorrent( tor ) )
1507    {
1508        tr_session * session = tor->session;
1509        assert( tr_isSession( session ) );
1510        tr_globalLock( session );
1511
1512        tr_torrentClearCompletenessCallback( tor );
1513        tr_runInEventThread( session, closeTorrent, tor );
1514
1515        tr_globalUnlock( session );
1516    }
1517}
1518
1519void
1520tr_torrentRemove( tr_torrent * tor )
1521{
1522    assert( tr_isTorrent( tor ) );
1523
1524    tor->isDeleting = 1;
1525    tr_torrentFree( tor );
1526}
1527
1528/**
1529***  Completeness
1530**/
1531
1532static const char *
1533getCompletionString( int type )
1534{
1535    switch( type )
1536    {
1537        /* Translators: this is a minor point that's safe to skip over, but FYI:
1538           "Complete" and "Done" are specific, different terms in Transmission:
1539           "Complete" means we've downloaded every file in the torrent.
1540           "Done" means we're done downloading the files we wanted, but NOT all
1541           that exist */
1542        case TR_PARTIAL_SEED:
1543            return _( "Done" );
1544
1545        case TR_SEED:
1546            return _( "Complete" );
1547
1548        default:
1549            return _( "Incomplete" );
1550    }
1551}
1552
1553static void
1554fireCompletenessChange( tr_torrent       * tor,
1555                        tr_completeness    status )
1556{
1557    assert( tr_isTorrent( tor ) );
1558    assert( ( status == TR_LEECH )
1559         || ( status == TR_SEED )
1560         || ( status == TR_PARTIAL_SEED ) );
1561
1562    if( tor->completeness_func )
1563        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1564}
1565
1566void
1567tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1568                                   tr_torrent_completeness_func    func,
1569                                   void                          * user_data )
1570{
1571    assert( tr_isTorrent( tor ) );
1572
1573    tor->completeness_func = func;
1574    tor->completeness_func_user_data = user_data;
1575}
1576
1577void
1578tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1579                                    tr_torrent_ratio_limit_hit_func  func,
1580                                    void                           * user_data )
1581{
1582    assert( tr_isTorrent( tor ) );
1583
1584    tor->ratio_limit_hit_func = func;
1585    tor->ratio_limit_hit_func_user_data = user_data;
1586}
1587
1588void
1589tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1590{
1591    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1592}
1593
1594void
1595tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1596{
1597    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1598}
1599
1600void
1601tr_torrentRecheckCompleteness( tr_torrent * tor )
1602{
1603    tr_completeness completeness;
1604
1605    assert( tr_isTorrent( tor ) );
1606
1607    tr_torrentLock( tor );
1608
1609    completeness = tr_cpGetStatus( &tor->completion );
1610
1611    if( completeness != tor->completeness )
1612    {
1613        const int recentChange = tor->downloadedCur != 0;
1614
1615        if( recentChange )
1616        {
1617            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1618                      getCompletionString( tor->completeness ),
1619                      getCompletionString( completeness ) );
1620        }
1621
1622        tor->completeness = completeness;
1623        tor->needsSeedRatioCheck = TRUE;
1624        tr_fdTorrentClose( tor->session, tor->uniqueId );
1625
1626        /* if the torrent is a seed now,
1627         * and the files used to be in the incompleteDir,
1628         * then move them to the destination directory */
1629        if( tr_torrentIsSeed( tor ) && ( tor->currentDir == tor->incompleteDir ) )
1630            tr_torrentSetLocation( tor, tor->downloadDir, TRUE, NULL, NULL );
1631
1632        fireCompletenessChange( tor, completeness );
1633
1634        if( recentChange && ( completeness == TR_SEED ) )
1635        {
1636            tr_announcerTorrentCompleted( tor );
1637
1638            tor->doneDate = tor->anyDate = time( NULL );
1639        }
1640
1641        tr_torrentSetDirty( tor );
1642    }
1643
1644    tr_torrentUnlock( tor );
1645}
1646
1647/**
1648***  File priorities
1649**/
1650
1651void
1652tr_torrentInitFilePriority( tr_torrent *    tor,
1653                            tr_file_index_t fileIndex,
1654                            tr_priority_t   priority )
1655{
1656    tr_piece_index_t i;
1657    tr_file *        file;
1658
1659    assert( tr_isTorrent( tor ) );
1660    assert( fileIndex < tor->info.fileCount );
1661    assert( tr_isPriority( priority ) );
1662
1663    file = &tor->info.files[fileIndex];
1664    file->priority = priority;
1665    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1666        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1667}
1668
1669void
1670tr_torrentSetFilePriorities( tr_torrent *      tor,
1671                             tr_file_index_t * files,
1672                             tr_file_index_t   fileCount,
1673                             tr_priority_t     priority )
1674{
1675    tr_file_index_t i;
1676    assert( tr_isTorrent( tor ) );
1677    tr_torrentLock( tor );
1678
1679    for( i = 0; i < fileCount; ++i )
1680        tr_torrentInitFilePriority( tor, files[i], priority );
1681    tr_torrentSetDirty( tor );
1682    tr_peerMgrRebuildRequests( tor );
1683
1684    tr_torrentUnlock( tor );
1685}
1686
1687tr_priority_t
1688tr_torrentGetFilePriority( const tr_torrent * tor,
1689                           tr_file_index_t    file )
1690{
1691    tr_priority_t ret;
1692
1693    assert( tr_isTorrent( tor ) );
1694
1695    tr_torrentLock( tor );
1696    assert( tor );
1697    assert( file < tor->info.fileCount );
1698    ret = tor->info.files[file].priority;
1699    tr_torrentUnlock( tor );
1700
1701    return ret;
1702}
1703
1704tr_priority_t*
1705tr_torrentGetFilePriorities( const tr_torrent * tor )
1706{
1707    tr_file_index_t i;
1708    tr_priority_t * p;
1709
1710    assert( tr_isTorrent( tor ) );
1711
1712    tr_torrentLock( tor );
1713    p = tr_new0( tr_priority_t, tor->info.fileCount );
1714    for( i = 0; i < tor->info.fileCount; ++i )
1715        p[i] = tor->info.files[i].priority;
1716    tr_torrentUnlock( tor );
1717
1718    return p;
1719}
1720
1721/**
1722***  File DND
1723**/
1724
1725int
1726tr_torrentGetFileDL( const tr_torrent * tor,
1727                     tr_file_index_t    file )
1728{
1729    int doDownload;
1730
1731    assert( tr_isTorrent( tor ) );
1732
1733    tr_torrentLock( tor );
1734
1735    assert( file < tor->info.fileCount );
1736    doDownload = !tor->info.files[file].dnd;
1737
1738    tr_torrentUnlock( tor );
1739    return doDownload != 0;
1740}
1741
1742static void
1743setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1744{
1745    tr_file *        file;
1746    const int        dnd = !doDownload;
1747    tr_piece_index_t firstPiece, firstPieceDND;
1748    tr_piece_index_t lastPiece, lastPieceDND;
1749    tr_file_index_t  i;
1750
1751    assert( tr_isTorrent( tor ) );
1752
1753    file = &tor->info.files[fileIndex];
1754    file->dnd = dnd;
1755    firstPiece = file->firstPiece;
1756    lastPiece = file->lastPiece;
1757
1758    /* can't set the first piece to DND unless
1759       every file using that piece is DND */
1760    firstPieceDND = dnd;
1761    if( fileIndex > 0 )
1762    {
1763        for( i = fileIndex - 1; firstPieceDND; --i )
1764        {
1765            if( tor->info.files[i].lastPiece != firstPiece )
1766                break;
1767            firstPieceDND = tor->info.files[i].dnd;
1768            if( !i )
1769                break;
1770        }
1771    }
1772
1773    /* can't set the last piece to DND unless
1774       every file using that piece is DND */
1775    lastPieceDND = dnd;
1776    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1777    {
1778        if( tor->info.files[i].firstPiece != lastPiece )
1779            break;
1780        lastPieceDND = tor->info.files[i].dnd;
1781    }
1782
1783    if( firstPiece == lastPiece )
1784    {
1785        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1786    }
1787    else
1788    {
1789        tr_piece_index_t pp;
1790        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1791        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1792        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1793            tor->info.pieces[pp].dnd = dnd;
1794    }
1795}
1796
1797void
1798tr_torrentInitFileDLs( tr_torrent      * tor,
1799                       tr_file_index_t * files,
1800                       tr_file_index_t   fileCount,
1801                       tr_bool           doDownload )
1802{
1803    tr_file_index_t i;
1804
1805    assert( tr_isTorrent( tor ) );
1806
1807    tr_torrentLock( tor );
1808
1809    for( i=0; i<fileCount; ++i )
1810        setFileDND( tor, files[i], doDownload );
1811    tr_cpInvalidateDND( &tor->completion );
1812    tor->needsSeedRatioCheck = TRUE;
1813
1814    tr_torrentUnlock( tor );
1815}
1816
1817void
1818tr_torrentSetFileDLs( tr_torrent *      tor,
1819                      tr_file_index_t * files,
1820                      tr_file_index_t   fileCount,
1821                      tr_bool           doDownload )
1822{
1823    assert( tr_isTorrent( tor ) );
1824    tr_torrentLock( tor );
1825
1826    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1827    tr_torrentSetDirty( tor );
1828    tr_peerMgrRebuildRequests( tor );
1829
1830    tr_torrentUnlock( tor );
1831}
1832
1833/***
1834****
1835***/
1836
1837tr_priority_t
1838tr_torrentGetPriority( const tr_torrent * tor )
1839{
1840    assert( tr_isTorrent( tor ) );
1841
1842    return tor->bandwidth->priority;
1843}
1844
1845void
1846tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1847{
1848    assert( tr_isTorrent( tor ) );
1849    assert( tr_isPriority( priority ) );
1850
1851    if( tor->bandwidth->priority != priority )
1852    {
1853        tor->bandwidth->priority = priority;
1854
1855        tr_torrentSetDirty( tor );
1856    }
1857}
1858
1859/***
1860****
1861***/
1862
1863void
1864tr_torrentSetPeerLimit( tr_torrent * tor,
1865                        uint16_t     maxConnectedPeers )
1866{
1867    assert( tr_isTorrent( tor ) );
1868
1869    if ( tor->maxConnectedPeers != maxConnectedPeers )
1870    {
1871        tor->maxConnectedPeers = maxConnectedPeers;
1872
1873        tr_torrentSetDirty( tor );
1874    }
1875}
1876
1877uint16_t
1878tr_torrentGetPeerLimit( const tr_torrent * tor )
1879{
1880    assert( tr_isTorrent( tor ) );
1881
1882    return tor->maxConnectedPeers;
1883}
1884
1885/***
1886****
1887***/
1888
1889tr_block_index_t
1890_tr_block( const tr_torrent * tor,
1891           tr_piece_index_t   index,
1892           uint32_t           offset )
1893{
1894    tr_block_index_t ret;
1895
1896    assert( tr_isTorrent( tor ) );
1897
1898    ret = index;
1899    ret *= ( tor->info.pieceSize / tor->blockSize );
1900    ret += offset / tor->blockSize;
1901    return ret;
1902}
1903
1904tr_bool
1905tr_torrentReqIsValid( const tr_torrent * tor,
1906                      tr_piece_index_t   index,
1907                      uint32_t           offset,
1908                      uint32_t           length )
1909{
1910    int err = 0;
1911
1912    assert( tr_isTorrent( tor ) );
1913
1914    if( index >= tor->info.pieceCount )
1915        err = 1;
1916    else if( length < 1 )
1917        err = 2;
1918    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1919        err = 3;
1920    else if( length > MAX_BLOCK_SIZE )
1921        err = 4;
1922    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1923        err = 5;
1924
1925    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
1926                              (unsigned long)index,
1927                              (unsigned long)offset,
1928                              (unsigned long)length,
1929                              err );
1930
1931    return !err;
1932}
1933
1934uint64_t
1935tr_pieceOffset( const tr_torrent * tor,
1936                tr_piece_index_t   index,
1937                uint32_t           offset,
1938                uint32_t           length )
1939{
1940    uint64_t ret;
1941
1942    assert( tr_isTorrent( tor ) );
1943
1944    ret = tor->info.pieceSize;
1945    ret *= index;
1946    ret += offset;
1947    ret += length;
1948    return ret;
1949}
1950
1951/***
1952****
1953***/
1954
1955void
1956tr_torrentSetPieceChecked( tr_torrent        * tor,
1957                           tr_piece_index_t    piece,
1958                           tr_bool             isChecked )
1959{
1960    assert( tr_isTorrent( tor ) );
1961
1962    if( isChecked )
1963        tr_bitfieldAdd( &tor->checkedPieces, piece );
1964    else
1965        tr_bitfieldRem( &tor->checkedPieces, piece );
1966}
1967
1968void
1969tr_torrentSetFileChecked( tr_torrent *    tor,
1970                          tr_file_index_t fileIndex,
1971                          tr_bool         isChecked )
1972{
1973    const tr_file *        file = &tor->info.files[fileIndex];
1974    const tr_piece_index_t begin = file->firstPiece;
1975    const tr_piece_index_t end = file->lastPiece + 1;
1976
1977    assert( tr_isTorrent( tor ) );
1978
1979    if( isChecked )
1980        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
1981    else
1982        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
1983}
1984
1985tr_bool
1986tr_torrentIsFileChecked( const tr_torrent * tor,
1987                         tr_file_index_t    fileIndex )
1988{
1989    const tr_file *        file = &tor->info.files[fileIndex];
1990    const tr_piece_index_t begin = file->firstPiece;
1991    const tr_piece_index_t end = file->lastPiece + 1;
1992    tr_piece_index_t       i;
1993    tr_bool                isChecked = TRUE;
1994
1995    assert( tr_isTorrent( tor ) );
1996
1997    for( i = begin; isChecked && i < end; ++i )
1998        if( !tr_torrentIsPieceChecked( tor, i ) )
1999            isChecked = FALSE;
2000
2001    return isChecked;
2002}
2003
2004void
2005tr_torrentUncheck( tr_torrent * tor )
2006{
2007    assert( tr_isTorrent( tor ) );
2008
2009    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
2010}
2011
2012int
2013tr_torrentCountUncheckedPieces( const tr_torrent * tor )
2014{
2015    assert( tr_isTorrent( tor ) );
2016
2017    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
2018}
2019
2020time_t*
2021tr_torrentGetMTimes( const tr_torrent * tor, size_t * setme_n )
2022{
2023    size_t       i;
2024    const size_t n = tor->info.fileCount;
2025    time_t *     m = tr_new0( time_t, n );
2026
2027    assert( tr_isTorrent( tor ) );
2028
2029    for( i = 0; i < n; ++i )
2030    {
2031        struct stat sb;
2032        char * path = tr_torrentFindFile( tor, i );
2033        if( ( path != NULL ) && !stat( path, &sb ) && S_ISREG( sb.st_mode ) )
2034        {
2035#ifdef SYS_DARWIN
2036            m[i] = sb.st_mtimespec.tv_sec;
2037#else
2038            m[i] = sb.st_mtime;
2039#endif
2040        }
2041        tr_free( path );
2042    }
2043
2044    *setme_n = n;
2045    return m;
2046}
2047
2048/***
2049****
2050***/
2051
2052tr_announce_list_err
2053tr_torrentSetAnnounceList( tr_torrent *            tor,
2054                           const tr_tracker_info * trackers,
2055                           int                     trackerCount )
2056{
2057    int i, j;
2058    tr_benc metainfo;
2059
2060    assert( tr_isTorrent( tor ) );
2061
2062    /* look for bad URLs */
2063    for( i=0; i<trackerCount; ++i )
2064        if( !tr_httpIsValidURL( trackers[i].announce ) )
2065            return TR_ANNOUNCE_LIST_HAS_BAD;
2066
2067    /* look for duplicates */
2068    for( i=0; i<trackerCount; ++i )
2069        for( j=0; j<trackerCount; ++j )
2070            if( ( i != j ) && ( !strcmp( trackers[i].announce, trackers[j].announce ) ) )
2071                return TR_ANNOUNCE_LIST_HAS_DUPLICATES;
2072
2073    /* save to the .torrent file */
2074    if( !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2075    {
2076        int       i;
2077        int       prevTier = -1;
2078        tr_benc * tier = NULL;
2079        tr_benc * announceList;
2080        tr_info   tmpInfo;
2081
2082        /* remove the old fields */
2083        tr_bencDictRemove( &metainfo, "announce" );
2084        tr_bencDictRemove( &metainfo, "announce-list" );
2085
2086        /* add the new fields */
2087        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2088        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2089        for( i = 0; i < trackerCount; ++i ) {
2090            if( prevTier != trackers[i].tier ) {
2091                prevTier = trackers[i].tier;
2092                tier = tr_bencListAddList( announceList, 0 );
2093            }
2094            tr_bencListAddStr( tier, trackers[i].announce );
2095        }
2096
2097        /* try to parse it back again, to make sure it's good */
2098        memset( &tmpInfo, 0, sizeof( tr_info ) );
2099        if( tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
2100        {
2101            /* it's good, so keep these new trackers and free the old ones */
2102
2103            tr_info swap;
2104            swap.trackers = tor->info.trackers;
2105            swap.trackerCount = tor->info.trackerCount;
2106            tor->info.trackers = tmpInfo.trackers;
2107            tor->info.trackerCount = tmpInfo.trackerCount;
2108            tmpInfo.trackers = swap.trackers;
2109            tmpInfo.trackerCount = swap.trackerCount;
2110
2111            tr_metainfoFree( &tmpInfo );
2112            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2113        }
2114
2115        /* cleanup */
2116        tr_bencFree( &metainfo );
2117
2118        /* tell the announcer to reload this torrent's tracker list */
2119        tr_announcerResetTorrent( tor->session->announcer, tor );
2120    }
2121
2122    return TR_ANNOUNCE_LIST_OK;
2123}
2124
2125/**
2126***
2127**/
2128
2129void
2130tr_torrentSetAddedDate( tr_torrent * tor,
2131                        time_t       t )
2132{
2133    assert( tr_isTorrent( tor ) );
2134
2135    tor->addedDate = t;
2136    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2137}
2138
2139void
2140tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2141{
2142    assert( tr_isTorrent( tor ) );
2143
2144    tor->activityDate = t;
2145    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2146}
2147
2148void
2149tr_torrentSetDoneDate( tr_torrent * tor,
2150                       time_t       t )
2151{
2152    assert( tr_isTorrent( tor ) );
2153
2154    tor->doneDate = t;
2155    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2156}
2157
2158/**
2159***
2160**/
2161
2162uint64_t
2163tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2164{
2165    tr_file_index_t i;
2166    uint64_t bytesLeft = 0;
2167
2168    assert( tr_isTorrent( tor ) );
2169
2170    for( i=0; i<tor->info.fileCount; ++i )
2171    {
2172        if( !tor->info.files[i].dnd )
2173        {
2174            struct stat sb;
2175            const uint64_t length = tor->info.files[i].length;
2176            char * path = tr_torrentFindFile( tor, i );
2177
2178            bytesLeft += length;
2179
2180            if( ( path != NULL ) && !stat( path, &sb )
2181                                 && S_ISREG( sb.st_mode )
2182                                 && ( (uint64_t)sb.st_size <= length ) )
2183                bytesLeft -= sb.st_size;
2184
2185            tr_free( path );
2186        }
2187    }
2188
2189    return bytesLeft;
2190}
2191
2192/****
2193*****  Removing the torrent's local data
2194****/
2195
2196static int
2197vstrcmp( const void * a, const void * b )
2198{
2199    return strcmp( a, b );
2200}
2201
2202static int
2203compareLongestFirst( const void * a, const void * b )
2204{
2205    const size_t alen = strlen( a );
2206    const size_t blen = strlen( b );
2207
2208    if( alen != blen )
2209        return alen > blen ? -1 : 1;
2210
2211    return vstrcmp( a, b );
2212}
2213
2214static void
2215addDirtyFile( const char  * root,
2216              const char  * filename,
2217              tr_ptrArray * dirtyFolders )
2218{
2219    char * dir = tr_dirname( filename );
2220
2221    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2222    while (     ( dir != NULL )
2223             && ( strlen( root ) <= strlen( dir ) )
2224             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2225    {
2226        char * tmp;
2227        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2228
2229        tmp = tr_dirname( dir );
2230        tr_free( dir );
2231        dir = tmp;
2232    }
2233
2234    tr_free( dir );
2235}
2236
2237static void
2238walkLocalData( const tr_torrent * tor,
2239               const char       * root,
2240               const char       * dir,
2241               const char       * base,
2242               tr_ptrArray      * torrentFiles,
2243               tr_ptrArray      * folders,
2244               tr_ptrArray      * dirtyFolders )
2245{
2246    int i;
2247    struct stat sb;
2248    char * buf;
2249
2250    assert( tr_isTorrent( tor ) );
2251
2252    buf = tr_buildPath( dir, base, NULL );
2253    i = stat( buf, &sb );
2254    if( !i )
2255    {
2256        DIR * odir = NULL;
2257
2258        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2259        {
2260            struct dirent *d;
2261            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2262            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2263                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2264                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2265            closedir( odir );
2266        }
2267        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2268        {
2269            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2270            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2271            if( !isTorrentFile )
2272                addDirtyFile( root, buf, dirtyFolders );
2273        }
2274    }
2275
2276    tr_free( buf );
2277}
2278
2279static void
2280deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2281{
2282    int i, n;
2283    char ** s;
2284    tr_file_index_t f;
2285    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2286    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2287    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2288
2289    const char * firstFile = tor->info.files[0].name;
2290    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2291    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2292    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2293
2294    assert( tr_isTorrent( tor ) );
2295
2296    for( f=0; f<tor->info.fileCount; ++f ) {
2297        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2298        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2299    }
2300
2301    /* build the set of folders and dirtyFolders */
2302    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2303
2304    /* try to remove entire folders first, so that the recycle bin will be tidy */
2305    s = (char**) tr_ptrArrayPeek( &folders, &n );
2306    for( i=0; i<n; ++i )
2307        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2308            fileFunc( s[i] );
2309
2310    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2311    for( f=0; f<tor->info.fileCount; ++f ) {
2312        char * path = tr_buildPath( tor->currentDir, tor->info.files[f].name, NULL );
2313        fileFunc( path );
2314        tr_free( path );
2315    }
2316
2317    /* Now clean out the directories left empty from the previous step.
2318     * Work from deepest to shallowest s.t. lower folders
2319     * won't prevent the upper folders from being deleted */
2320    {
2321        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2322        s = (char**) tr_ptrArrayPeek( &folders, &n );
2323        for( i=0; i<n; ++i )
2324            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2325                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2326        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2327        for( i=0; i<n; ++i ) {
2328#ifdef SYS_DARWIN
2329            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2330            fileFunc( dsStore );
2331            tr_free( dsStore );
2332#endif
2333            fileFunc( s[i] );
2334        }
2335        tr_ptrArrayDestruct( &cleanFolders, NULL );
2336    }
2337
2338    /* cleanup */
2339    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2340    tr_ptrArrayDestruct( &folders, tr_free );
2341    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2342    tr_free( root );
2343    tr_free( tmp );
2344}
2345
2346void
2347tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2348{
2349    assert( tr_isTorrent( tor ) );
2350
2351    if( fileFunc == NULL )
2352        fileFunc = remove;
2353
2354    /* close all the files because we're about to delete them */
2355    tr_fdTorrentClose( tor->session, tor->uniqueId );
2356
2357    if( tor->info.fileCount > 1 )
2358    {
2359        deleteLocalData( tor, fileFunc );
2360    }
2361    else
2362    {
2363        char * tmp;
2364
2365        /* torrent only has one file */
2366        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2367        fileFunc( path );
2368        tr_free( path );
2369
2370       
2371        tmp = tr_torrentBuildPartial( tor, 0 );
2372        path = tr_buildPath( tor->currentDir, tmp, NULL );
2373        fileFunc( path );
2374        tr_free( path );
2375        tr_free( tmp );
2376    }
2377}
2378
2379/***
2380****
2381***/
2382
2383struct LocationData
2384{
2385    tr_bool move_from_old_location;
2386    int * setme_state;
2387    double * setme_progress;
2388    char * location;
2389    tr_torrent * tor;
2390};
2391
2392static void
2393setLocation( void * vdata )
2394{
2395    tr_bool err = FALSE;
2396    tr_bool verify_needed = FALSE;
2397    struct LocationData * data = vdata;
2398    tr_torrent * tor = data->tor;
2399    const tr_bool do_move = data->move_from_old_location;
2400    const char * location = data->location;
2401    double bytesHandled = 0;
2402
2403    assert( tr_isTorrent( tor ) );
2404
2405    if( strcmp( location, tor->currentDir ) )
2406    {
2407        tr_file_index_t i;
2408
2409        /* bad idea to move files while they're being verified... */
2410        tr_verifyRemove( tor );
2411
2412        /* if the torrent is running, stop it and set a flag to
2413         * restart after we're done */
2414        if( tor->isRunning )
2415        {
2416            tr_torrentStop( tor );
2417            tor->startAfterVerify = TRUE;
2418        }
2419
2420        /* try to move the files.
2421         * FIXME: there are still all kinds of nasty cases, like what
2422         * if the target directory runs out of space halfway through... */
2423        for( i=0; !err && i<tor->info.fileCount; ++i )
2424        {
2425            const tr_file * f = &tor->info.files[i];
2426            const char * oldbase;
2427            char * sub;
2428            if( tr_torrentFindFile2( tor, i, &oldbase, &sub ) )
2429            {
2430                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2431                char * newpath = tr_buildPath( location, sub, NULL );
2432
2433                if( do_move )
2434                {
2435                    tr_bool renamed = FALSE;
2436                    errno = 0;
2437                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2438                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2439                    {
2440                        err = TRUE;
2441                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2442                                        oldpath, newpath, tr_strerror( errno ) );
2443                    }
2444                    else if( !renamed )
2445                    {
2446                        verify_needed = TRUE;
2447                    }
2448                }
2449
2450                tr_free( newpath );
2451                tr_free( oldpath );
2452                tr_free( sub );
2453            }
2454
2455            if( data->setme_progress )
2456            {
2457                bytesHandled += f->length;
2458                *data->setme_progress = bytesHandled / tor->info.totalSize;
2459            }
2460        }
2461
2462        if( !err )
2463        {
2464            /* blow away the leftover subdirectories in the old location */
2465            if( do_move )
2466                tr_torrentDeleteLocalData( tor, remove );
2467
2468            /* set the new location and reverify */
2469            tr_torrentSetDownloadDir( tor, location );
2470            if( verify_needed )
2471                tr_torrentVerify( tor );
2472            else if( tor->startAfterVerify ) {
2473                tor->startAfterVerify = FALSE;
2474                tr_torrentStart( tor );
2475            }
2476        }
2477    }
2478
2479    if( data->setme_state )
2480        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2481
2482    /* cleanup */
2483    tr_free( data->location );
2484    tr_free( data );
2485}
2486
2487void
2488tr_torrentSetLocation( tr_torrent  * tor,
2489                       const char  * location,
2490                       tr_bool       move_from_old_location,
2491                       double      * setme_progress,
2492                       int         * setme_state )
2493{
2494    struct LocationData * data;
2495
2496    assert( tr_isTorrent( tor ) );
2497
2498    if( setme_state )
2499        *setme_state = TR_LOC_MOVING;
2500    if( setme_progress )
2501        *setme_progress = 0;
2502
2503    /* run this in the libtransmission thread */
2504    data = tr_new( struct LocationData, 1 );
2505    data->tor = tor;
2506    data->location = tr_strdup( location );
2507    data->move_from_old_location = move_from_old_location;
2508    data->setme_state = setme_state;
2509    data->setme_progress = setme_progress;
2510    tr_runInEventThread( tor->session, setLocation, data );
2511}
2512
2513/***
2514****
2515***/
2516
2517void
2518tr_torrentCheckSeedRatio( tr_torrent * tor )
2519{
2520    double seedRatio;
2521
2522    assert( tr_isTorrent( tor ) );
2523
2524    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2525    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2526    {
2527        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2528        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2529        double ratio;
2530
2531        /* maybe we're the initial seeder and never downloaded anything... */
2532        if( down == 0 )
2533            down = tr_cpHaveValid( &tor->completion );
2534
2535        ratio = tr_getRatio( up, down );
2536
2537        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2538        {
2539            tr_torrentStop( tor );
2540
2541            /* set to no ratio limit to allow easy restarting */
2542            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2543
2544            /* maybe notify the client */
2545            if( tor->ratio_limit_hit_func != NULL )
2546                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2547        }
2548    }
2549}
2550
2551/***
2552****
2553***/
2554
2555void
2556tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2557{
2558    char * sub;
2559    const char * base;
2560
2561    /* close the file so that we can reopen in read-only mode as needed */
2562    tr_fdFileClose( tor->session, tor, fileNum );
2563
2564    /* if the torrent's filename on disk isn't the same as the one in the metadata,
2565     * then it's been modified to denote that it was a partial file.
2566     * Now that it's complete, use the proper filename. */
2567    if( tr_torrentFindFile2( tor, fileNum, &base, &sub ) )
2568    {
2569        const tr_file * file = &tor->info.files[fileNum];
2570
2571        if( strcmp( sub, file->name ) )
2572        {
2573            char * oldpath = tr_buildPath( base, sub, NULL );
2574            char * newpath = tr_buildPath( base, file->name, NULL );
2575
2576            if( rename( oldpath, newpath ) )
2577                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2578
2579            tr_free( newpath );
2580            tr_free( oldpath );
2581        }
2582
2583        tr_free( sub );
2584    }
2585}
2586
2587/***
2588****
2589***/
2590
2591static tr_bool
2592fileExists( const char * filename )
2593{
2594    struct stat sb;
2595    const tr_bool ok = !stat( filename, &sb );
2596    return ok;
2597}
2598
2599tr_bool
2600tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
2601                     const char ** base, char ** subpath )
2602{
2603    char * part;
2604    const tr_file * file;
2605    const char * b = NULL;
2606    const char * s = NULL;
2607
2608    assert( tr_isTorrent( tor ) );
2609    assert( fileNum < tor->info.fileCount );
2610
2611    file = &tor->info.files[fileNum];
2612    part = tr_torrentBuildPartial( tor, fileNum );
2613
2614    if( b == NULL ) {
2615        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
2616        if( fileExists( filename ) ) {
2617            b = tor->downloadDir;
2618            s = file->name;
2619        }
2620        tr_free( filename );
2621    }
2622
2623    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2624        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
2625        if( fileExists( filename ) ) {
2626            b = tor->incompleteDir;
2627            s = file->name;
2628        }
2629        tr_free( filename );
2630    }
2631
2632    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2633        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
2634        if( fileExists( filename ) ) {
2635            b = tor->incompleteDir;
2636            s = part;
2637        }
2638        tr_free( filename );
2639    }
2640
2641    if( b == NULL) {
2642        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
2643        if( fileExists( filename ) ) {
2644            b = tor->downloadDir;
2645            s = part;
2646        }
2647        tr_free( filename );
2648    }
2649
2650    if( base != NULL )
2651        *base = b;
2652    if( subpath != NULL )
2653        *subpath = tr_strdup( s );
2654
2655    tr_free( part );
2656    return b != NULL;
2657}
2658
2659
2660char*
2661tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
2662{
2663    char * subpath;
2664    char * ret = NULL;
2665    const char * base;
2666
2667    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath ) )
2668    {
2669        ret = tr_buildPath( base, subpath, NULL );
2670        tr_free( subpath );
2671    }
2672
2673    return ret;
2674}
2675
2676/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
2677static void
2678refreshCurrentDir( tr_torrent * tor )
2679{
2680    const char * dir = NULL;
2681    char * sub;
2682
2683    if( tor->incompleteDir == NULL )
2684        dir = tor->downloadDir;
2685    else if( !tr_torrentFindFile2( tor, 0, &dir, &sub ) )
2686        dir = tor->incompleteDir;
2687
2688    assert( dir != NULL );
2689    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
2690    tor->currentDir = dir;
2691}
2692
2693char*
2694tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
2695{
2696    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
2697}
Note: See TracBrowser for help on using the repository browser.