source: trunk/libtransmission/torrent.c @ 10183

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

(trunk libT) fix memory leak when trying to add duplicate torrents. thanks valgrind!

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