source: trunk/libtransmission/torrent.c @ 11046

Last change on this file since 11046 was 11046, checked in by livings124, 11 years ago

update Mac build for the change from inactive to idle

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