source: trunk/libtransmission/torrent.c @ 11696

Last change on this file since 11696 was 11696, checked in by jordan, 11 years ago

(trunk libT) demote the remaining lazy-verify debug messages from the debug window to deep logging

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