source: trunk/libtransmission/torrent.c @ 10084

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

(trunk) #2802, #2716, #2717 -- remember magnet links and their settings between sessions, and allow their trackers to be modified

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