source: trunk/libtransmission/torrent.c @ 10851

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

(trunk libT) #3320 "If the seed ratio is already met" -- fix a bug in r10848 reported by BMW

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