source: trunk/libtransmission/torrent.c @ 9556

Last change on this file since 9556 was 9556, checked in by charles, 12 years ago

(trunk) more magnet fixes

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