source: trunk/libtransmission/torrent.c @ 12022

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

(trunk libT) #4035 "In seed state, transmission disconnect from leechers" -- fixed.

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