source: trunk/libtransmission/torrent.c @ 10919

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

(trunk libT) a couple more minor -Wconversion warnings

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