source: trunk/libtransmission/torrent.c @ 12204

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

(trunk) #4138 "use stdbool.h instead of tr_bool" -- done.

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