source: trunk/libtransmission/torrent.c @ 10157

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

(trunk libT) Yippie, plug a small memory leak reported by valgrind!

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