source: trunk/libtransmission/torrent.c @ 12074

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

(trunk libT) remove the unused tr_ratecontrol code. switch webseed over to using tr_bandwidth.

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