source: trunk/libtransmission/torrent.c @ 12434

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

(trunk libT) #4237 "tarnsmission-remote -l shows torrent list in reverse order" -- revert r12424 to fix this

  • Property svn:keywords set to Date Rev Author Id
File size: 80.5 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 12434 2011-05-16 02:09:31Z 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 <math.h>
27#include <stdarg.h>
28#include <string.h> /* memcmp */
29#include <stdlib.h> /* qsort */
30#include <stdio.h> /* remove() */
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( !evutil_ascii_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
152bool
153tr_torrentIsPieceTransferAllowed( const tr_torrent  * tor,
154                                  tr_direction        direction )
155{
156    int limit;
157    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, 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
215bool
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, bool doUse )
226{
227    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
238bool
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
293bool
294tr_torrentGetSeedRatio( const tr_torrent * tor, double * ratio )
295{
296    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 bool
323tr_torrentGetSeedRatioBytes( tr_torrent  * tor,
324                             uint64_t    * setmeLeft,
325                             uint64_t    * setmeGoal )
326{
327    double seedRatio;
328    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 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
398bool
399tr_torrentGetSeedIdle( const tr_torrent * tor, uint16_t * idleMinutes )
400{
401    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 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 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 bool
762hasAnyLocalData( const tr_torrent * tor )
763{
764    tr_file_index_t i;
765
766    for( i=0; i<tor->info.fileCount; ++i )
767        if( tr_torrentFindFile2( tor, i, NULL, NULL, NULL ) )
768            return true;
769
770    return false;
771}
772
773static bool
774setLocalErrorIfFilesDisappeared( tr_torrent * tor )
775{
776    const bool disappeared = ( tr_cpHaveTotal( &tor->completion ) > 0 ) && !hasAnyLocalData( tor );
777
778    if( disappeared )
779    {
780        tr_deeplog_tor( tor, "%s", "[LAZY] uh oh, the files disappeared" );
781        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." ) );
782    }
783
784    return disappeared;
785}
786
787static void
788torrentInit( tr_torrent * tor, const tr_ctor * ctor )
789{
790    int doStart;
791    uint64_t loaded;
792    const char * dir;
793    bool isNewTorrent;
794    struct stat st;
795    static int nextUniqueId = 1;
796    tr_session * session = tr_ctorGetSession( ctor );
797
798    assert( session != NULL );
799
800    tr_sessionLock( session );
801
802    tor->session   = session;
803    tor->uniqueId = nextUniqueId++;
804    tor->magicNumber = TORRENT_MAGIC_NUMBER;
805
806    tr_peerIdInit( tor->peer_id );
807
808    tr_sha1( tor->obfuscatedHash, "req2", 4,
809             tor->info.hash, SHA_DIGEST_LENGTH,
810             NULL );
811
812    if( !tr_ctorGetDownloadDir( ctor, TR_FORCE, &dir ) ||
813        !tr_ctorGetDownloadDir( ctor, TR_FALLBACK, &dir ) )
814            tor->downloadDir = tr_strdup( dir );
815
816    if( tr_ctorGetIncompleteDir( ctor, &dir ) )
817        dir = tr_sessionGetIncompleteDir( session );
818    if( tr_sessionIsIncompleteDirEnabled( session ) )
819        tor->incompleteDir = tr_strdup( dir );
820
821    tr_bandwidthConstruct( &tor->bandwidth, session, &session->bandwidth );
822
823    tor->bandwidth.priority = tr_ctorGetBandwidthPriority( ctor );
824
825    tor->error = TR_STAT_OK;
826
827    tor->finishedSeedingByIdle = false;
828
829    tr_peerMgrAddTorrent( session->peerMgr, tor );
830
831    assert( !tor->downloadedCur );
832    assert( !tor->uploadedCur );
833
834    tr_torrentSetAddedDate( tor, tr_time( ) ); /* this is a default value to be
835                                                  overwritten by the resume file */
836
837    torrentInitFromInfo( tor );
838    loaded = tr_torrentLoadResume( tor, ~0, ctor );
839    tor->completeness = tr_cpGetStatus( &tor->completion );
840    setLocalErrorIfFilesDisappeared( tor );
841
842    tr_ctorInitTorrentPriorities( ctor, tor );
843    tr_ctorInitTorrentWanted( ctor, tor );
844
845    refreshCurrentDir( tor );
846
847    doStart = tor->isRunning;
848    tor->isRunning = 0;
849
850    if( !( loaded & TR_FR_SPEEDLIMIT ) )
851    {
852        tr_torrentUseSpeedLimit( tor, TR_UP, false );
853        tr_torrentSetSpeedLimit_Bps( tor, TR_UP, tr_sessionGetSpeedLimit_Bps( tor->session, TR_UP ) );
854        tr_torrentUseSpeedLimit( tor, TR_DOWN, false );
855        tr_torrentSetSpeedLimit_Bps( tor, TR_DOWN, tr_sessionGetSpeedLimit_Bps( tor->session, TR_DOWN ) );
856        tr_torrentUseSessionLimits( tor, true );
857    }
858
859    if( !( loaded & TR_FR_RATIOLIMIT ) )
860    {
861        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_GLOBAL );
862        tr_torrentSetRatioLimit( tor, tr_sessionGetRatioLimit( tor->session ) );
863    }
864
865    if( !( loaded & TR_FR_IDLELIMIT ) )
866    {
867        tr_torrentSetIdleMode( tor, TR_IDLELIMIT_GLOBAL );
868        tr_torrentSetIdleLimit( tor, tr_sessionGetIdleLimit( tor->session ) );
869    }
870
871    /* add the torrent to tr_session.torrentList */
872    {
873        tr_torrent * it = NULL;
874        tr_torrent * last = NULL;
875        while(( it = tr_torrentNext( session, it )))
876            last = it;
877
878        if( !last )
879            session->torrentList = tor;
880        else
881            last->next = tor;
882        ++session->torrentCount;
883    }
884
885    /* if we don't have a local .torrent file already, assume the torrent is new */
886    isNewTorrent = stat( tor->info.torrent, &st );
887
888    /* maybe save our own copy of the metainfo */
889    if( tr_ctorGetSave( ctor ) )
890    {
891        const tr_benc * val;
892        if( !tr_ctorGetMetainfo( ctor, &val ) )
893        {
894            const char * path = tor->info.torrent;
895            const int err = tr_bencToFile( val, TR_FMT_BENC, path );
896            if( err )
897                tr_torrentSetLocalError( tor, "Unable to save torrent file: %s", tr_strerror( err ) );
898            tr_sessionSetTorrentFile( tor->session, tor->info.hashString, path );
899        }
900    }
901
902    tor->tiers = tr_announcerAddTorrent( tor, onTrackerResponse, NULL );
903
904    if( isNewTorrent )
905    {
906        tor->startAfterVerify = doStart;
907        tr_torrentVerify( tor );
908    }
909    else if( doStart )
910    {
911        torrentStart( tor );
912    }
913
914    tr_sessionUnlock( session );
915}
916
917static tr_parse_result
918torrentParseImpl( const tr_ctor * ctor, tr_info * setmeInfo,
919                  bool * setmeHasInfo, int * dictLength )
920{
921    int             doFree;
922    bool            didParse;
923    bool            hasInfo = false;
924    tr_info         tmp;
925    const tr_benc * metainfo;
926    tr_session    * session = tr_ctorGetSession( ctor );
927    tr_parse_result result = TR_PARSE_OK;
928
929    if( setmeInfo == NULL )
930        setmeInfo = &tmp;
931    memset( setmeInfo, 0, sizeof( tr_info ) );
932
933    if( tr_ctorGetMetainfo( ctor, &metainfo ) )
934        return TR_PARSE_ERR;
935
936    didParse = tr_metainfoParse( session, metainfo, setmeInfo,
937                                 &hasInfo, dictLength );
938    doFree = didParse && ( setmeInfo == &tmp );
939
940    if( !didParse )
941        result = TR_PARSE_ERR;
942
943    if( didParse && hasInfo && !tr_getBlockSize( setmeInfo->pieceSize ) )
944        result = TR_PARSE_ERR;
945
946    if( didParse && session && tr_torrentExists( session, setmeInfo->hash ) )
947        result = TR_PARSE_DUPLICATE;
948
949    if( doFree )
950        tr_metainfoFree( setmeInfo );
951
952    if( setmeHasInfo != NULL )
953        *setmeHasInfo = hasInfo;
954
955    return result;
956}
957
958tr_parse_result
959tr_torrentParse( const tr_ctor * ctor, tr_info * setmeInfo )
960{
961    return torrentParseImpl( ctor, setmeInfo, NULL, NULL );
962}
963
964tr_torrent *
965tr_torrentNew( const tr_ctor * ctor, int * setmeError )
966{
967    int len;
968    bool hasInfo;
969    tr_info tmpInfo;
970    tr_parse_result r;
971    tr_torrent * tor = NULL;
972
973    assert( ctor != NULL );
974    assert( tr_isSession( tr_ctorGetSession( ctor ) ) );
975
976    r = torrentParseImpl( ctor, &tmpInfo, &hasInfo, &len );
977    if( r == TR_PARSE_OK )
978    {
979        tor = tr_new0( tr_torrent, 1 );
980        tor->info = tmpInfo;
981        if( hasInfo )
982            tor->infoDictLength = len;
983        torrentInit( tor, ctor );
984    }
985    else
986    {
987        if( r == TR_PARSE_DUPLICATE )
988            tr_metainfoFree( &tmpInfo );
989
990        if( setmeError )
991            *setmeError = r;
992    }
993
994    return tor;
995}
996
997/**
998***
999**/
1000
1001void
1002tr_torrentSetDownloadDir( tr_torrent * tor, const char * path )
1003{
1004    assert( tr_isTorrent( tor  ) );
1005
1006    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
1007    {
1008        tr_free( tor->downloadDir );
1009        tor->downloadDir = tr_strdup( path );
1010        tr_torrentSetDirty( tor );
1011    }
1012
1013    refreshCurrentDir( tor );
1014}
1015
1016const char*
1017tr_torrentGetDownloadDir( const tr_torrent * tor )
1018{
1019    assert( tr_isTorrent( tor  ) );
1020
1021    return tor->downloadDir;
1022}
1023
1024const char *
1025tr_torrentGetCurrentDir( const tr_torrent * tor )
1026{
1027    assert( tr_isTorrent( tor  ) );
1028
1029    return tor->currentDir;
1030}
1031
1032
1033void
1034tr_torrentChangeMyPort( tr_torrent * tor )
1035{
1036    assert( tr_isTorrent( tor  ) );
1037
1038    if( tor->isRunning )
1039        tr_announcerChangeMyPort( tor );
1040}
1041
1042static inline void
1043tr_torrentManualUpdateImpl( void * vtor )
1044{
1045    tr_torrent * tor = vtor;
1046
1047    assert( tr_isTorrent( tor  ) );
1048
1049    if( tor->isRunning )
1050        tr_announcerManualAnnounce( tor );
1051}
1052
1053void
1054tr_torrentManualUpdate( tr_torrent * tor )
1055{
1056    assert( tr_isTorrent( tor  ) );
1057
1058    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
1059}
1060
1061bool
1062tr_torrentCanManualUpdate( const tr_torrent * tor )
1063{
1064    return ( tr_isTorrent( tor  ) )
1065        && ( tor->isRunning )
1066        && ( tr_announcerCanManualAnnounce( tor ) );
1067}
1068
1069const tr_info *
1070tr_torrentInfo( const tr_torrent * tor )
1071{
1072    return tr_isTorrent( tor ) ? &tor->info : NULL;
1073}
1074
1075const tr_stat *
1076tr_torrentStatCached( tr_torrent * tor )
1077{
1078    const time_t now = tr_time( );
1079
1080    return tr_isTorrent( tor ) && ( now == tor->lastStatTime )
1081         ? &tor->stats
1082         : tr_torrentStat( tor );
1083}
1084
1085void
1086tr_torrentSetVerifyState( tr_torrent * tor, tr_verify_state state )
1087{
1088    assert( tr_isTorrent( tor ) );
1089    assert( state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW );
1090
1091    tor->verifyState = state;
1092    tor->anyDate = tr_time( );
1093}
1094
1095tr_torrent_activity
1096tr_torrentGetActivity( tr_torrent * tor )
1097{
1098    assert( tr_isTorrent( tor ) );
1099
1100    tr_torrentRecheckCompleteness( tor );
1101
1102    if( tor->verifyState == TR_VERIFY_NOW )
1103        return TR_STATUS_CHECK;
1104    if( tor->verifyState == TR_VERIFY_WAIT )
1105        return TR_STATUS_CHECK_WAIT;
1106    if( !tor->isRunning )
1107        return TR_STATUS_STOPPED;
1108    if( tor->completeness == TR_LEECH )
1109        return TR_STATUS_DOWNLOAD;
1110
1111    return TR_STATUS_SEED;
1112}
1113
1114static double
1115getVerifyProgress( const tr_torrent * tor )
1116{
1117    tr_piece_index_t i, n;
1118    tr_piece_index_t checked = 0;
1119
1120    assert( tr_isTorrent( tor ) );
1121
1122    for( i=0, n=tor->info.pieceCount; i!=n; ++i )
1123        if( tor->info.pieces[i].timeChecked )
1124            ++checked;
1125
1126    return checked / (double)tor->info.pieceCount;
1127}
1128
1129const tr_stat *
1130tr_torrentStat( tr_torrent * tor )
1131{
1132    tr_stat *               s;
1133    uint64_t                now;
1134    uint64_t                seedRatioBytesLeft;
1135    uint64_t                seedRatioBytesGoal;
1136    bool                    seedRatioApplies;
1137    uint16_t                seedIdleMinutes;
1138
1139    if( !tor )
1140        return NULL;
1141
1142    assert( tr_isTorrent( tor ) );
1143    tr_torrentLock( tor );
1144
1145    tor->lastStatTime = tr_time( );
1146
1147    s = &tor->stats;
1148    s->id = tor->uniqueId;
1149    s->activity = tr_torrentGetActivity( tor );
1150    s->error = tor->error;
1151    tr_strlcpy( s->errorString, tor->errorString, sizeof( s->errorString ) );
1152
1153    s->manualAnnounceTime = tr_announcerNextManualAnnounce( tor );
1154
1155    tr_peerMgrTorrentStats( tor,
1156                            &s->peersConnected,
1157                            &s->webseedsSendingToUs,
1158                            &s->peersSendingToUs,
1159                            &s->peersGettingFromUs,
1160                            s->peersFrom );
1161
1162    now = tr_time_msec( );
1163    s->rawUploadSpeed_KBps     = toSpeedKBps( tr_bandwidthGetRawSpeed_Bps  ( &tor->bandwidth, now, TR_UP ) );
1164    s->pieceUploadSpeed_KBps   = toSpeedKBps( tr_bandwidthGetPieceSpeed_Bps( &tor->bandwidth, now, TR_UP ) );
1165    s->rawDownloadSpeed_KBps   = toSpeedKBps( tr_bandwidthGetRawSpeed_Bps  ( &tor->bandwidth, now, TR_DOWN ) );
1166    s->pieceDownloadSpeed_KBps = toSpeedKBps( tr_bandwidthGetPieceSpeed_Bps( &tor->bandwidth, now, TR_DOWN ) );
1167
1168    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
1169    s->metadataPercentComplete = tr_torrentGetMetadataPercent( tor );
1170
1171    s->percentDone         = tr_cpPercentDone  ( &tor->completion );
1172    s->leftUntilDone       = tr_cpLeftUntilDone( &tor->completion );
1173    s->sizeWhenDone        = tr_cpSizeWhenDone ( &tor->completion );
1174    s->recheckProgress     = s->activity == TR_STATUS_CHECK ? getVerifyProgress( tor ) : 0;
1175    s->activityDate        = tor->activityDate;
1176    s->addedDate           = tor->addedDate;
1177    s->doneDate            = tor->doneDate;
1178    s->startDate           = tor->startDate;
1179    s->secondsSeeding      = tor->secondsSeeding;
1180    s->secondsDownloading  = tor->secondsDownloading;
1181
1182    if ((s->activity == TR_STATUS_DOWNLOAD || s->activity == TR_STATUS_SEED) && s->startDate != 0)
1183        s->idleSecs = difftime(tr_time(), MAX(s->startDate, s->activityDate));
1184    else
1185        s->idleSecs = -1;
1186
1187    s->corruptEver      = tor->corruptCur    + tor->corruptPrev;
1188    s->downloadedEver   = tor->downloadedCur + tor->downloadedPrev;
1189    s->uploadedEver     = tor->uploadedCur   + tor->uploadedPrev;
1190    s->haveValid        = tr_cpHaveValid( &tor->completion );
1191    s->haveUnchecked    = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
1192    s->desiredAvailable = tr_peerMgrGetDesiredAvailable( tor );
1193
1194    s->ratio = tr_getRatio( s->uploadedEver,
1195                            s->downloadedEver ? s->downloadedEver : s->haveValid );
1196
1197    seedRatioApplies = tr_torrentGetSeedRatioBytes( tor, &seedRatioBytesLeft,
1198                                                         &seedRatioBytesGoal );
1199
1200    switch( s->activity )
1201    {
1202        /* etaXLSpeed exists because if we use the piece speed directly,
1203         * brief fluctuations cause the ETA to jump all over the place.
1204         * so, etaXLSpeed is a smoothed-out version of the piece speed
1205         * to dampen the effect of fluctuations */
1206
1207        case TR_STATUS_DOWNLOAD:
1208            if( ( tor->etaDLSpeedCalculatedAt + 800 ) < now ) {
1209                tor->etaDLSpeed_KBps = ( ( tor->etaDLSpeedCalculatedAt + 4000 ) < now )
1210                    ? s->pieceDownloadSpeed_KBps /* if no recent previous speed, no need to smooth */
1211                    : ((tor->etaDLSpeed_KBps*4.0) + s->pieceDownloadSpeed_KBps)/5.0; /* smooth across 5 readings */
1212                tor->etaDLSpeedCalculatedAt = now;
1213            }
1214
1215            if( s->leftUntilDone > s->desiredAvailable )
1216                s->eta = TR_ETA_NOT_AVAIL;
1217            else if( tor->etaDLSpeed_KBps < 1 )
1218                s->eta = TR_ETA_UNKNOWN;
1219            else
1220                s->eta = s->leftUntilDone / toSpeedBytes(tor->etaDLSpeed_KBps);
1221
1222            s->etaIdle = TR_ETA_NOT_AVAIL;
1223            break;
1224
1225        case TR_STATUS_SEED: {
1226            if( !seedRatioApplies )
1227                s->eta = TR_ETA_NOT_AVAIL;
1228            else {
1229                if( ( tor->etaULSpeedCalculatedAt + 800 ) < now ) {
1230                    tor->etaULSpeed_KBps = ( ( tor->etaULSpeedCalculatedAt + 4000 ) < now )
1231                        ? s->pieceUploadSpeed_KBps /* if no recent previous speed, no need to smooth */
1232                        : ((tor->etaULSpeed_KBps*4.0) + s->pieceUploadSpeed_KBps)/5.0; /* smooth across 5 readings */
1233                    tor->etaULSpeedCalculatedAt = now;
1234                }
1235                if( tor->etaULSpeed_KBps < 1 )
1236                    s->eta = TR_ETA_UNKNOWN;
1237                else
1238                    s->eta = seedRatioBytesLeft / toSpeedBytes(tor->etaULSpeed_KBps);
1239            }
1240
1241            if( tor->etaULSpeed_KBps < 1 && tr_torrentGetSeedIdle( tor, &seedIdleMinutes ) )
1242                s->etaIdle = seedIdleMinutes * 60 - s->idleSecs;
1243            else
1244                s->etaIdle = TR_ETA_NOT_AVAIL;
1245            break;
1246        }
1247
1248        default:
1249            s->eta = TR_ETA_NOT_AVAIL;
1250            s->etaIdle = TR_ETA_NOT_AVAIL;
1251            break;
1252    }
1253
1254    /* s->haveValid is here to make sure a torrent isn't marked 'finished'
1255     * when the user hits "uncheck all" prior to starting the torrent... */
1256    s->finished = tor->finishedSeedingByIdle || (seedRatioApplies && !seedRatioBytesLeft && s->haveValid);
1257
1258    if( !seedRatioApplies || s->finished )
1259        s->seedRatioPercentDone = 1;
1260    else if( !seedRatioBytesGoal ) /* impossible? safeguard for div by zero */
1261        s->seedRatioPercentDone = 0;
1262    else
1263        s->seedRatioPercentDone = (double)(seedRatioBytesGoal - seedRatioBytesLeft) / seedRatioBytesGoal;
1264
1265    tr_torrentUnlock( tor );
1266
1267    return s;
1268}
1269
1270/***
1271****
1272***/
1273
1274static uint64_t
1275fileBytesCompleted( const tr_torrent * tor, tr_file_index_t index )
1276{
1277    uint64_t total = 0;
1278    const tr_file * f = &tor->info.files[index];
1279
1280    if( f->length )
1281    {
1282        tr_block_index_t first;
1283        tr_block_index_t last;
1284        tr_torGetFileBlockRange( tor, index, &first, &last );
1285
1286        if( first == last )
1287        {
1288            if( tr_cpBlockIsComplete( &tor->completion, first ) )
1289                total = f->length;
1290        }
1291        else
1292        {
1293            /* the first block */
1294            if( tr_cpBlockIsComplete( &tor->completion, first ) )
1295                total += tor->blockSize - ( f->offset % tor->blockSize );
1296
1297            /* the middle blocks */
1298            if( first + 1 < last ) {
1299                uint64_t u = tr_bitfieldCountRange( &tor->completion.blockBitfield, first+1, last );
1300                u *= tor->blockSize;
1301                total += u;
1302            }
1303
1304            /* the last block */
1305            if( tr_cpBlockIsComplete( &tor->completion, last ) )
1306                total += ( f->offset + f->length ) - ( (uint64_t)tor->blockSize * last );
1307        }
1308    }
1309
1310    return total;
1311}
1312
1313tr_file_stat *
1314tr_torrentFiles( const tr_torrent * tor,
1315                 tr_file_index_t *  fileCount )
1316{
1317    tr_file_index_t       i;
1318    const tr_file_index_t n = tor->info.fileCount;
1319    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1320    tr_file_stat *        walk = files;
1321    const bool            isSeed = tor->completeness == TR_SEED;
1322
1323    assert( tr_isTorrent( tor ) );
1324
1325    for( i=0; i<n; ++i, ++walk ) {
1326        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1327        walk->bytesCompleted = b;
1328        walk->progress = tor->info.files[i].length > 0 ? ( (float)b / tor->info.files[i].length ) : 1.0f;
1329    }
1330
1331    if( fileCount )
1332        *fileCount = n;
1333
1334    return files;
1335}
1336
1337void
1338tr_torrentFilesFree( tr_file_stat *            files,
1339                     tr_file_index_t fileCount UNUSED )
1340{
1341    tr_free( files );
1342}
1343
1344/***
1345****
1346***/
1347
1348double*
1349tr_torrentWebSpeeds_KBps( const tr_torrent * tor )
1350{
1351    double * ret = NULL;
1352
1353    if( tr_isTorrent( tor ) )
1354    {
1355        tr_torrentLock( tor );
1356        ret = tr_peerMgrWebSpeeds_KBps( tor );
1357        tr_torrentUnlock( tor );
1358    }
1359
1360    return ret;
1361}
1362
1363tr_peer_stat *
1364tr_torrentPeers( const tr_torrent * tor, int * peerCount )
1365{
1366    tr_peer_stat * ret = NULL;
1367
1368    if( tr_isTorrent( tor ) )
1369    {
1370        tr_torrentLock( tor );
1371        ret = tr_peerMgrPeerStats( tor, peerCount );
1372        tr_torrentUnlock( tor );
1373    }
1374
1375    return ret;
1376}
1377
1378void
1379tr_torrentPeersFree( tr_peer_stat * peers, int peerCount UNUSED )
1380{
1381    tr_free( peers );
1382}
1383
1384tr_tracker_stat *
1385tr_torrentTrackers( const tr_torrent * torrent, int * setmeTrackerCount )
1386{
1387    tr_tracker_stat * ret = NULL;
1388
1389    if( tr_isTorrent( torrent ) )
1390    {
1391        tr_torrentLock( torrent );
1392        ret = tr_announcerStats( torrent, setmeTrackerCount );
1393        tr_torrentUnlock( torrent );
1394    }
1395
1396    return ret;
1397}
1398
1399void
1400tr_torrentTrackersFree( tr_tracker_stat * trackers, int trackerCount )
1401{
1402    tr_announcerStatsFree( trackers, trackerCount );
1403}
1404
1405void
1406tr_torrentAvailability( const tr_torrent * tor, int8_t * tab, int size )
1407{
1408    if( tr_isTorrent( tor ) && ( tab != NULL ) && ( size > 0 ) )
1409    {
1410        tr_torrentLock( tor );
1411        tr_peerMgrTorrentAvailability( tor, tab, size );
1412        tr_torrentUnlock( tor );
1413    }
1414}
1415
1416void
1417tr_torrentAmountFinished( const tr_torrent * tor,
1418                          float *            tab,
1419                          int                size )
1420{
1421    assert( tr_isTorrent( tor ) );
1422
1423    tr_torrentLock( tor );
1424    tr_cpGetAmountDone( &tor->completion, tab, size );
1425    tr_torrentUnlock( tor );
1426}
1427
1428static void
1429tr_torrentResetTransferStats( tr_torrent * tor )
1430{
1431    tr_torrentLock( tor );
1432
1433    tor->downloadedPrev += tor->downloadedCur;
1434    tor->downloadedCur   = 0;
1435    tor->uploadedPrev   += tor->uploadedCur;
1436    tor->uploadedCur     = 0;
1437    tor->corruptPrev    += tor->corruptCur;
1438    tor->corruptCur      = 0;
1439
1440    tr_torrentSetDirty( tor );
1441
1442    tr_torrentUnlock( tor );
1443}
1444
1445void
1446tr_torrentSetHasPiece( tr_torrent *     tor,
1447                       tr_piece_index_t pieceIndex,
1448                       bool             has )
1449{
1450    assert( tr_isTorrent( tor ) );
1451    assert( pieceIndex < tor->info.pieceCount );
1452
1453    if( has )
1454        tr_cpPieceAdd( &tor->completion, pieceIndex );
1455    else
1456        tr_cpPieceRem( &tor->completion, pieceIndex );
1457}
1458
1459/***
1460****
1461***/
1462
1463static void
1464freeTorrent( tr_torrent * tor )
1465{
1466    tr_torrent * t;
1467    tr_session *  session = tor->session;
1468    tr_info *    inf = &tor->info;
1469
1470    assert( !tor->isRunning );
1471
1472    tr_sessionLock( session );
1473
1474    tr_peerMgrRemoveTorrent( tor );
1475
1476    tr_cpDestruct( &tor->completion );
1477
1478    tr_announcerRemoveTorrent( session->announcer, tor );
1479
1480    tr_free( tor->downloadDir );
1481    tr_free( tor->incompleteDir );
1482
1483    if( tor == session->torrentList )
1484        session->torrentList = tor->next;
1485    else for( t = session->torrentList; t != NULL; t = t->next ) {
1486        if( t->next == tor ) {
1487            t->next = tor->next;
1488            break;
1489        }
1490    }
1491
1492    assert( session->torrentCount >= 1 );
1493    session->torrentCount--;
1494
1495    tr_bandwidthDestruct( &tor->bandwidth );
1496
1497    tr_metainfoFree( inf );
1498    tr_free( tor );
1499
1500    tr_sessionUnlock( session );
1501}
1502
1503/**
1504***  Start/Stop Callback
1505**/
1506
1507static void
1508torrentStartImpl( void * vtor )
1509{
1510    time_t now;
1511    tr_torrent * tor = vtor;
1512
1513    assert( tr_isTorrent( tor ) );
1514
1515    tr_sessionLock( tor->session );
1516
1517    tr_torrentRecheckCompleteness( tor );
1518
1519    now = tr_time( );
1520    tor->isRunning = true;
1521    tor->completeness = tr_cpGetStatus( &tor->completion );
1522    tor->startDate = tor->anyDate = now;
1523    tr_torrentClearError( tor );
1524    tor->finishedSeedingByIdle = false;
1525
1526    tr_torrentResetTransferStats( tor );
1527    tr_announcerTorrentStarted( tor );
1528    tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1529    tor->dhtAnnounce6At = now + tr_cryptoWeakRandInt( 20 );
1530    tor->lpdAnnounceAt = now;
1531    tr_peerMgrStartTorrent( tor );
1532
1533    tr_sessionUnlock( tor->session );
1534}
1535
1536uint64_t
1537tr_torrentGetCurrentSizeOnDisk( const tr_torrent * tor )
1538{
1539    tr_file_index_t i;
1540    uint64_t byte_count = 0;
1541    const tr_file_index_t n = tor->info.fileCount;
1542
1543    for( i=0; i<n; ++i )
1544    {
1545        struct stat sb;
1546        char * filename = tr_torrentFindFile( tor, i );
1547
1548        sb.st_size = 0;
1549        if( filename && !stat( filename, &sb ) )
1550            byte_count += sb.st_size;
1551
1552        tr_free( filename );
1553    }
1554
1555    return byte_count;
1556}
1557
1558static void
1559torrentStart( tr_torrent * tor )
1560{
1561    /* already running... */
1562    if( tor->isRunning )
1563        return;
1564
1565    /* don't allow the torrent to be started if the files disappeared */
1566    if( setLocalErrorIfFilesDisappeared( tor ) )
1567        return;
1568
1569    /* verifying right now... wait until that's done so
1570     * we'll know what completeness to use/announce */
1571    if( tor->verifyState != TR_VERIFY_NONE ) {
1572        tor->startAfterVerify = true;
1573        return;
1574    }
1575
1576    /* otherwise, start it now... */
1577    tr_sessionLock( tor->session );
1578
1579    /* allow finished torrents to be resumed */
1580    if( tr_torrentIsSeedRatioDone( tor ) ) {
1581        tr_torinf( tor, _( "Restarted manually -- disabling its seed ratio" ) );
1582        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
1583    }
1584
1585    /* corresponds to the peer_id sent as a tracker request parameter.
1586     * one tracker admin says: "When the same torrent is opened and
1587     * closed and opened again without quitting Transmission ...
1588     * change the peerid. It would help sometimes if a stopped event
1589     * was missed to ensure that we didn't think someone was cheating. */
1590    tr_peerIdInit( tor->peer_id );
1591    tor->isRunning = 1;
1592    tr_torrentSetDirty( tor );
1593    tr_runInEventThread( tor->session, torrentStartImpl, tor );
1594
1595    tr_sessionUnlock( tor->session );
1596}
1597
1598void
1599tr_torrentStart( tr_torrent * tor )
1600{
1601    if( tr_isTorrent( tor ) )
1602        torrentStart( tor );
1603}
1604
1605static void
1606torrentRecheckDoneImpl( void * vtor )
1607{
1608    tr_torrent * tor = vtor;
1609    assert( tr_isTorrent( tor ) );
1610
1611    tr_torrentRecheckCompleteness( tor );
1612
1613    if( tor->startAfterVerify ) {
1614        tor->startAfterVerify = false;
1615        torrentStart( tor );
1616    }
1617}
1618
1619static void
1620torrentRecheckDoneCB( tr_torrent * tor )
1621{
1622    assert( tr_isTorrent( tor ) );
1623
1624    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1625}
1626
1627static void
1628verifyTorrent( void * vtor )
1629{
1630    tr_torrent * tor = vtor;
1631
1632    tr_sessionLock( tor->session );
1633
1634    /* if the torrent's already being verified, stop it */
1635    tr_verifyRemove( tor );
1636
1637    /* if the torrent's running, stop it & set the restart-after-verify flag */
1638    if( tor->startAfterVerify || tor->isRunning ) {
1639        /* don't clobber isStopping */
1640        const bool startAfter = tor->isStopping ? false : true;
1641        tr_torrentStop( tor );
1642        tor->startAfterVerify = startAfter;
1643    }
1644
1645    if( setLocalErrorIfFilesDisappeared( tor ) )
1646        tor->startAfterVerify = false;
1647    else
1648        tr_verifyAdd( tor, torrentRecheckDoneCB );
1649
1650    tr_sessionUnlock( tor->session );
1651}
1652
1653void
1654tr_torrentVerify( tr_torrent * tor )
1655{
1656    if( tr_isTorrent( tor ) )
1657        tr_runInEventThread( tor->session, verifyTorrent, tor );
1658}
1659
1660void
1661tr_torrentSave( tr_torrent * tor )
1662{
1663    assert( tr_isTorrent( tor ) );
1664
1665    if( tor->isDirty )
1666    {
1667        tor->isDirty = false;
1668        tr_torrentSaveResume( tor );
1669    }
1670}
1671
1672static void
1673stopTorrent( void * vtor )
1674{
1675    tr_torrent * tor = vtor;
1676    tr_torinf( tor, "Pausing" );
1677
1678    assert( tr_isTorrent( tor ) );
1679
1680    tr_torrentLock( tor );
1681
1682    tr_verifyRemove( tor );
1683    tr_peerMgrStopTorrent( tor );
1684    tr_announcerTorrentStopped( tor );
1685    tr_cacheFlushTorrent( tor->session->cache, tor );
1686
1687    tr_fdTorrentClose( tor->session, tor->uniqueId );
1688
1689    if( !tor->isDeleting )
1690        tr_torrentSave( tor );
1691
1692    tr_torrentUnlock( tor );
1693}
1694
1695void
1696tr_torrentStop( tr_torrent * tor )
1697{
1698    assert( tr_isTorrent( tor ) );
1699
1700    if( tr_isTorrent( tor ) )
1701    {
1702        tr_sessionLock( tor->session );
1703
1704        tor->isRunning = 0;
1705        tor->isStopping = 0;
1706        tr_torrentSetDirty( tor );
1707        tr_runInEventThread( tor->session, stopTorrent, tor );
1708
1709        tr_sessionUnlock( tor->session );
1710    }
1711}
1712
1713static void
1714closeTorrent( void * vtor )
1715{
1716    tr_benc * d;
1717    tr_torrent * tor = vtor;
1718
1719    assert( tr_isTorrent( tor ) );
1720
1721    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1722    tr_bencDictAddInt( d, "id", tor->uniqueId );
1723    tr_bencDictAddInt( d, "date", tr_time( ) );
1724
1725    tr_torinf( tor, "%s", _( "Removing torrent" ) );
1726
1727    stopTorrent( tor );
1728
1729    if( tor->isDeleting )
1730    {
1731        tr_metainfoRemoveSaved( tor->session, &tor->info );
1732        tr_torrentRemoveResume( tor );
1733    }
1734
1735    tor->isRunning = 0;
1736    freeTorrent( tor );
1737}
1738
1739void
1740tr_torrentFree( tr_torrent * tor )
1741{
1742    if( tr_isTorrent( tor ) )
1743    {
1744        tr_session * session = tor->session;
1745        assert( tr_isSession( session ) );
1746        tr_sessionLock( session );
1747
1748        tr_torrentClearCompletenessCallback( tor );
1749        tr_runInEventThread( session, closeTorrent, tor );
1750
1751        tr_sessionUnlock( session );
1752    }
1753}
1754
1755struct remove_data
1756{
1757    tr_torrent   * tor;
1758    bool           deleteFlag;
1759    tr_fileFunc  * deleteFunc;
1760};
1761
1762static void tr_torrentDeleteLocalData( tr_torrent *, tr_fileFunc );
1763
1764static void
1765removeTorrent( void * vdata )
1766{
1767    struct remove_data * data = vdata;
1768
1769    if( data->deleteFlag )
1770        tr_torrentDeleteLocalData( data->tor, data->deleteFunc );
1771
1772    tr_torrentClearCompletenessCallback( data->tor );
1773    closeTorrent( data->tor );
1774    tr_free( data );
1775}
1776
1777void
1778tr_torrentRemove( tr_torrent   * tor,
1779                  bool           deleteFlag,
1780                  tr_fileFunc    deleteFunc )
1781{
1782    struct remove_data * data;
1783
1784    assert( tr_isTorrent( tor ) );
1785    tor->isDeleting = 1;
1786
1787    data = tr_new0( struct remove_data, 1 );
1788    data->tor = tor;
1789    data->deleteFlag = deleteFlag;
1790    data->deleteFunc = deleteFunc;
1791    tr_runInEventThread( tor->session, removeTorrent, data );
1792}
1793
1794/**
1795***  Completeness
1796**/
1797
1798static const char *
1799getCompletionString( int type )
1800{
1801    switch( type )
1802    {
1803        /* Translators: this is a minor point that's safe to skip over, but FYI:
1804           "Complete" and "Done" are specific, different terms in Transmission:
1805           "Complete" means we've downloaded every file in the torrent.
1806           "Done" means we're done downloading the files we wanted, but NOT all
1807           that exist */
1808        case TR_PARTIAL_SEED:
1809            return _( "Done" );
1810
1811        case TR_SEED:
1812            return _( "Complete" );
1813
1814        default:
1815            return _( "Incomplete" );
1816    }
1817}
1818
1819static void
1820fireCompletenessChange( tr_torrent       * tor,
1821                        tr_completeness    status,
1822                        bool               wasRunning )
1823{
1824    assert( ( status == TR_LEECH )
1825         || ( status == TR_SEED )
1826         || ( status == TR_PARTIAL_SEED ) );
1827
1828    if( tor->completeness_func )
1829        tor->completeness_func( tor, status, wasRunning,
1830                                tor->completeness_func_user_data );
1831}
1832
1833void
1834tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1835                                   tr_torrent_completeness_func    func,
1836                                   void                          * user_data )
1837{
1838    assert( tr_isTorrent( tor ) );
1839
1840    tor->completeness_func = func;
1841    tor->completeness_func_user_data = user_data;
1842}
1843
1844void
1845tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1846{
1847    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1848}
1849
1850void
1851tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1852                                    tr_torrent_ratio_limit_hit_func  func,
1853                                    void                           * user_data )
1854{
1855    assert( tr_isTorrent( tor ) );
1856
1857    tor->ratio_limit_hit_func = func;
1858    tor->ratio_limit_hit_func_user_data = user_data;
1859}
1860
1861void
1862tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1863{
1864    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1865}
1866
1867void
1868tr_torrentSetIdleLimitHitCallback( tr_torrent                    * tor,
1869                                   tr_torrent_idle_limit_hit_func  func,
1870                                   void                          * user_data )
1871{
1872    assert( tr_isTorrent( tor ) );
1873
1874    tor->idle_limit_hit_func = func;
1875    tor->idle_limit_hit_func_user_data = user_data;
1876}
1877
1878void
1879tr_torrentClearIdleLimitHitCallback( tr_torrent * torrent )
1880{
1881    tr_torrentSetIdleLimitHitCallback( torrent, NULL, NULL );
1882}
1883
1884static void
1885onSigCHLD( int i UNUSED )
1886{
1887    waitpid( -1, NULL, WNOHANG );
1888}
1889
1890static void
1891torrentCallScript( const tr_torrent * tor, const char * script )
1892{
1893    char timeStr[128];
1894    const time_t now = tr_time( );
1895
1896    tr_strlcpy( timeStr, ctime( &now ), sizeof( timeStr ) );
1897    *strchr( timeStr,'\n' ) = '\0';
1898
1899    if( script && *script )
1900    {
1901        int i;
1902        char * cmd[] = { tr_strdup( script ), NULL };
1903        char * env[] = {
1904            tr_strdup_printf( "TR_APP_VERSION=%s", SHORT_VERSION_STRING ),
1905            tr_strdup_printf( "TR_TIME_LOCALTIME=%s", timeStr ),
1906            tr_strdup_printf( "TR_TORRENT_DIR=%s", tor->currentDir ),
1907            tr_strdup_printf( "TR_TORRENT_ID=%d", tr_torrentId( tor ) ),
1908            tr_strdup_printf( "TR_TORRENT_HASH=%s", tor->info.hashString ),
1909            tr_strdup_printf( "TR_TORRENT_NAME=%s", tr_torrentName( tor ) ),
1910            NULL };
1911
1912        tr_torinf( tor, "Calling script \"%s\"", script );
1913
1914#ifdef WIN32
1915        _spawnvpe( _P_NOWAIT, script, (const char*)cmd, env );
1916#else
1917        signal( SIGCHLD, onSigCHLD );
1918
1919        if( !fork( ) )
1920        {
1921            for (i=0; env[i]; ++i)
1922                putenv(env[i]);
1923            execvp( script, cmd );
1924            _exit( 0 );
1925        }
1926#endif
1927
1928        for( i=0; cmd[i]; ++i ) tr_free( cmd[i] );
1929        for( i=0; env[i]; ++i ) tr_free( env[i] );
1930    }
1931}
1932
1933void
1934tr_torrentRecheckCompleteness( tr_torrent * tor )
1935{
1936    tr_completeness completeness;
1937
1938    assert( tr_isTorrent( tor ) );
1939
1940    tr_torrentLock( tor );
1941
1942    completeness = tr_cpGetStatus( &tor->completion );
1943
1944    if( completeness != tor->completeness )
1945    {
1946        const int recentChange = tor->downloadedCur != 0;
1947        const bool wasLeeching = !tr_torrentIsSeed( tor );
1948        const bool wasRunning = tor->isRunning;
1949
1950        if( recentChange )
1951        {
1952            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1953                      getCompletionString( tor->completeness ),
1954                      getCompletionString( completeness ) );
1955        }
1956
1957        tor->completeness = completeness;
1958        tr_fdTorrentClose( tor->session, tor->uniqueId );
1959
1960        if( tr_torrentIsSeed( tor ) )
1961        {
1962            if( recentChange )
1963            {
1964                tr_announcerTorrentCompleted( tor );
1965                tor->doneDate = tor->anyDate = tr_time( );
1966            }
1967
1968            if( wasLeeching && wasRunning )
1969            {
1970                /* clear interested flag on all peers */
1971                tr_peerMgrClearInterest( tor );
1972
1973                /* if completeness was TR_LEECH then the seed limit check will have been skipped in bandwidthPulse */
1974                tr_torrentCheckSeedLimit( tor );
1975            }
1976
1977            if( tor->currentDir == tor->incompleteDir )
1978                tr_torrentSetLocation( tor, tor->downloadDir, true, NULL, NULL );
1979
1980            if( tr_sessionIsTorrentDoneScriptEnabled( tor->session ) )
1981                torrentCallScript( tor, tr_sessionGetTorrentDoneScript( tor->session ) );
1982        }
1983
1984        fireCompletenessChange( tor, wasRunning, completeness );
1985
1986        tr_torrentSetDirty( tor );
1987    }
1988
1989    tr_torrentUnlock( tor );
1990}
1991
1992/***
1993****
1994***/
1995
1996static void
1997tr_torrentFireMetadataCompleted( tr_torrent * tor )
1998{
1999    assert( tr_isTorrent( tor ) );
2000
2001    if( tor->metadata_func )
2002        tor->metadata_func( tor, tor->metadata_func_user_data );
2003}
2004
2005void
2006tr_torrentSetMetadataCallback( tr_torrent                * tor,
2007                               tr_torrent_metadata_func    func,
2008                               void                      * user_data )
2009{
2010    assert( tr_isTorrent( tor ) );
2011
2012    tor->metadata_func = func;
2013    tor->metadata_func_user_data = user_data;
2014}
2015
2016
2017/**
2018***  File priorities
2019**/
2020
2021void
2022tr_torrentInitFilePriority( tr_torrent *    tor,
2023                            tr_file_index_t fileIndex,
2024                            tr_priority_t   priority )
2025{
2026    tr_piece_index_t i;
2027    tr_file *        file;
2028
2029    assert( tr_isTorrent( tor ) );
2030    assert( fileIndex < tor->info.fileCount );
2031    assert( tr_isPriority( priority ) );
2032
2033    file = &tor->info.files[fileIndex];
2034    file->priority = priority;
2035    for( i = file->firstPiece; i <= file->lastPiece; ++i )
2036        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
2037}
2038
2039void
2040tr_torrentSetFilePriorities( tr_torrent             * tor,
2041                             const tr_file_index_t  * files,
2042                             tr_file_index_t          fileCount,
2043                             tr_priority_t            priority )
2044{
2045    tr_file_index_t i;
2046    assert( tr_isTorrent( tor ) );
2047    tr_torrentLock( tor );
2048
2049    for( i = 0; i < fileCount; ++i )
2050        if( files[i] < tor->info.fileCount )
2051            tr_torrentInitFilePriority( tor, files[i], priority );
2052    tr_torrentSetDirty( tor );
2053    tr_peerMgrRebuildRequests( tor );
2054
2055    tr_torrentUnlock( tor );
2056}
2057
2058tr_priority_t*
2059tr_torrentGetFilePriorities( const tr_torrent * tor )
2060{
2061    tr_file_index_t i;
2062    tr_priority_t * p;
2063
2064    assert( tr_isTorrent( tor ) );
2065
2066    tr_torrentLock( tor );
2067    p = tr_new0( tr_priority_t, tor->info.fileCount );
2068    for( i = 0; i < tor->info.fileCount; ++i )
2069        p[i] = tor->info.files[i].priority;
2070    tr_torrentUnlock( tor );
2071
2072    return p;
2073}
2074
2075/**
2076***  File DND
2077**/
2078
2079static void
2080setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
2081{
2082    const int8_t     dnd = !doDownload;
2083    tr_piece_index_t firstPiece;
2084    int8_t           firstPieceDND;
2085    tr_piece_index_t lastPiece;
2086    int8_t           lastPieceDND;
2087    tr_file_index_t  i;
2088    tr_file *        file = &tor->info.files[fileIndex];
2089
2090    file->dnd = dnd;
2091    firstPiece = file->firstPiece;
2092    lastPiece = file->lastPiece;
2093
2094    /* can't set the first piece to DND unless
2095       every file using that piece is DND */
2096    firstPieceDND = dnd;
2097    if( fileIndex > 0 )
2098    {
2099        for( i = fileIndex - 1; firstPieceDND; --i )
2100        {
2101            if( tor->info.files[i].lastPiece != firstPiece )
2102                break;
2103            firstPieceDND = tor->info.files[i].dnd;
2104            if( !i )
2105                break;
2106        }
2107    }
2108
2109    /* can't set the last piece to DND unless
2110       every file using that piece is DND */
2111    lastPieceDND = dnd;
2112    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
2113    {
2114        if( tor->info.files[i].firstPiece != lastPiece )
2115            break;
2116        lastPieceDND = tor->info.files[i].dnd;
2117    }
2118
2119    if( firstPiece == lastPiece )
2120    {
2121        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
2122    }
2123    else
2124    {
2125        tr_piece_index_t pp;
2126        tor->info.pieces[firstPiece].dnd = firstPieceDND;
2127        tor->info.pieces[lastPiece].dnd = lastPieceDND;
2128        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
2129            tor->info.pieces[pp].dnd = dnd;
2130    }
2131}
2132
2133void
2134tr_torrentInitFileDLs( tr_torrent             * tor,
2135                       const tr_file_index_t  * files,
2136                       tr_file_index_t          fileCount,
2137                       bool                     doDownload )
2138{
2139    tr_file_index_t i;
2140
2141    assert( tr_isTorrent( tor ) );
2142
2143    tr_torrentLock( tor );
2144
2145    for( i=0; i<fileCount; ++i )
2146        if( files[i] < tor->info.fileCount )
2147            setFileDND( tor, files[i], doDownload );
2148
2149    tr_cpInvalidateDND( &tor->completion );
2150
2151    tr_torrentUnlock( tor );
2152}
2153
2154void
2155tr_torrentSetFileDLs( tr_torrent             * tor,
2156                      const tr_file_index_t  * files,
2157                      tr_file_index_t          fileCount,
2158                      bool                     doDownload )
2159{
2160    assert( tr_isTorrent( tor ) );
2161    tr_torrentLock( tor );
2162
2163    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
2164    tr_torrentSetDirty( tor );
2165    tr_peerMgrRebuildRequests( tor );
2166
2167    tr_torrentUnlock( tor );
2168}
2169
2170/***
2171****
2172***/
2173
2174tr_priority_t
2175tr_torrentGetPriority( const tr_torrent * tor )
2176{
2177    assert( tr_isTorrent( tor ) );
2178
2179    return tor->bandwidth.priority;
2180}
2181
2182void
2183tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
2184{
2185    assert( tr_isTorrent( tor ) );
2186    assert( tr_isPriority( priority ) );
2187
2188    if( tor->bandwidth.priority != priority )
2189    {
2190        tor->bandwidth.priority = priority;
2191
2192        tr_torrentSetDirty( tor );
2193    }
2194}
2195
2196/***
2197****
2198***/
2199
2200void
2201tr_torrentSetPeerLimit( tr_torrent * tor,
2202                        uint16_t     maxConnectedPeers )
2203{
2204    assert( tr_isTorrent( tor ) );
2205
2206    if ( tor->maxConnectedPeers != maxConnectedPeers )
2207    {
2208        tor->maxConnectedPeers = maxConnectedPeers;
2209
2210        tr_torrentSetDirty( tor );
2211    }
2212}
2213
2214uint16_t
2215tr_torrentGetPeerLimit( const tr_torrent * tor )
2216{
2217    assert( tr_isTorrent( tor ) );
2218
2219    return tor->maxConnectedPeers;
2220}
2221
2222/***
2223****
2224***/
2225
2226void
2227tr_torrentGetBlockLocation( const tr_torrent * tor,
2228                            tr_block_index_t   block,
2229                            tr_piece_index_t * piece,
2230                            uint32_t         * offset,
2231                            uint32_t         * length )
2232{
2233    uint64_t pos = block;
2234    pos *= tor->blockSize;
2235    *piece = pos / tor->info.pieceSize;
2236    *offset = pos - ( *piece * tor->info.pieceSize );
2237    *length = tr_torBlockCountBytes( tor, block );
2238}
2239
2240
2241tr_block_index_t
2242_tr_block( const tr_torrent * tor,
2243           tr_piece_index_t   index,
2244           uint32_t           offset )
2245{
2246    tr_block_index_t ret;
2247
2248    assert( tr_isTorrent( tor ) );
2249
2250    ret = index;
2251    ret *= ( tor->info.pieceSize / tor->blockSize );
2252    ret += offset / tor->blockSize;
2253    return ret;
2254}
2255
2256bool
2257tr_torrentReqIsValid( const tr_torrent * tor,
2258                      tr_piece_index_t   index,
2259                      uint32_t           offset,
2260                      uint32_t           length )
2261{
2262    int err = 0;
2263
2264    assert( tr_isTorrent( tor ) );
2265
2266    if( index >= tor->info.pieceCount )
2267        err = 1;
2268    else if( length < 1 )
2269        err = 2;
2270    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
2271        err = 3;
2272    else if( length > MAX_BLOCK_SIZE )
2273        err = 4;
2274    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
2275        err = 5;
2276
2277    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
2278                              (unsigned long)index,
2279                              (unsigned long)offset,
2280                              (unsigned long)length,
2281                              err );
2282
2283    return !err;
2284}
2285
2286uint64_t
2287tr_pieceOffset( const tr_torrent * tor,
2288                tr_piece_index_t   index,
2289                uint32_t           offset,
2290                uint32_t           length )
2291{
2292    uint64_t ret;
2293
2294    assert( tr_isTorrent( tor ) );
2295
2296    ret = tor->info.pieceSize;
2297    ret *= index;
2298    ret += offset;
2299    ret += length;
2300    return ret;
2301}
2302
2303void
2304tr_torGetFileBlockRange( const tr_torrent        * tor,
2305                         const tr_file_index_t     file,
2306                         tr_block_index_t        * first,
2307                         tr_block_index_t        * last )
2308{
2309    const tr_file * f = &tor->info.files[file];
2310    uint64_t offset = f->offset;
2311    *first = offset / tor->blockSize;
2312    if( !f->length )
2313        *last = *first;
2314    else {
2315        offset += f->length - 1;
2316        *last = offset / tor->blockSize;
2317    }
2318}
2319
2320void
2321tr_torGetPieceBlockRange( const tr_torrent        * tor,
2322                          const tr_piece_index_t    piece,
2323                          tr_block_index_t        * first,
2324                          tr_block_index_t        * last )
2325{
2326    uint64_t offset = tor->info.pieceSize;
2327    offset *= piece;
2328    *first = offset / tor->blockSize;
2329    offset += ( tr_torPieceCountBytes( tor, piece ) - 1 );
2330    *last = offset / tor->blockSize;
2331}
2332
2333
2334/***
2335****
2336***/
2337
2338void
2339tr_torrentSetPieceChecked( tr_torrent * tor, tr_piece_index_t pieceIndex )
2340{
2341    assert( tr_isTorrent( tor ) );
2342    assert( pieceIndex < tor->info.pieceCount );
2343
2344    tor->info.pieces[pieceIndex].timeChecked = tr_time( );
2345}
2346
2347void
2348tr_torrentSetChecked( tr_torrent * tor, time_t when )
2349{
2350    tr_piece_index_t i, n;
2351
2352    assert( tr_isTorrent( tor ) );
2353
2354    for( i=0, n=tor->info.pieceCount; i!=n; ++i )
2355        tor->info.pieces[i].timeChecked = when;
2356}
2357
2358bool
2359tr_torrentCheckPiece( tr_torrent * tor, tr_piece_index_t pieceIndex )
2360{
2361    const bool pass = tr_ioTestPiece( tor, pieceIndex );
2362
2363    tr_deeplog_tor( tor, "[LAZY] tr_torrentCheckPiece tested piece %zu, pass==%d", (size_t)pieceIndex, (int)pass );
2364    tr_torrentSetHasPiece( tor, pieceIndex, pass );
2365    tr_torrentSetPieceChecked( tor, pieceIndex );
2366    tor->anyDate = tr_time( );
2367    tr_torrentSetDirty( tor );
2368
2369    return pass;
2370}
2371
2372time_t
2373tr_torrentGetFileMTime( const tr_torrent * tor, tr_file_index_t i )
2374{
2375    time_t mtime = 0;
2376    if( !tr_fdFileGetCachedMTime( tor->session, tor->uniqueId, i, &mtime ) )
2377        tr_torrentFindFile2( tor, i, NULL, NULL, &mtime );
2378    return mtime;
2379}
2380
2381bool
2382tr_torrentPieceNeedsCheck( const tr_torrent * tor, tr_piece_index_t p )
2383{
2384    uint64_t unused;
2385    tr_file_index_t f;
2386    const tr_info * inf = tr_torrentInfo( tor );
2387
2388    /* if we've never checked this piece, then it needs to be checked */
2389    if( !inf->pieces[p].timeChecked )
2390        return true;
2391
2392    /* If we think we've completed one of the files in this piece,
2393     * but it's been modified since we last checked it,
2394     * then it needs to be rechecked */
2395    tr_ioFindFileLocation( tor, p, 0, &f, &unused );
2396    for( ; f < inf->fileCount && pieceHasFile( p, &inf->files[f] ); ++f )
2397        if( tr_cpFileIsComplete( &tor->completion, f ) )
2398            if( tr_torrentGetFileMTime( tor, f ) > inf->pieces[p].timeChecked )
2399                return true;
2400
2401    return false;
2402}
2403
2404/***
2405****
2406***/
2407
2408static int
2409compareTrackerByTier( const void * va, const void * vb )
2410{
2411    const tr_tracker_info * a = va;
2412    const tr_tracker_info * b = vb;
2413
2414    /* sort by tier */
2415    if( a->tier != b->tier )
2416        return a->tier - b->tier;
2417
2418    /* get the effects of a stable sort by comparing the two elements' addresses */
2419    return a - b;
2420}
2421
2422bool
2423tr_torrentSetAnnounceList( tr_torrent             * tor,
2424                           const tr_tracker_info  * trackers_in,
2425                           int                      trackerCount )
2426{
2427    int i;
2428    tr_benc metainfo;
2429    bool ok = true;
2430    tr_tracker_info * trackers;
2431
2432    tr_torrentLock( tor );
2433
2434    assert( tr_isTorrent( tor ) );
2435
2436    /* ensure the trackers' tiers are in ascending order */
2437    trackers = tr_memdup( trackers_in, sizeof( tr_tracker_info ) * trackerCount );
2438    qsort( trackers, trackerCount, sizeof( tr_tracker_info ), compareTrackerByTier );
2439
2440    /* look for bad URLs */
2441    for( i=0; ok && i<trackerCount; ++i )
2442        if( !tr_urlIsValidTracker( trackers[i].announce ) )
2443            ok = false;
2444
2445    /* save to the .torrent file */
2446    if( ok && !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2447    {
2448        bool hasInfo;
2449        tr_info tmpInfo;
2450
2451        /* remove the old fields */
2452        tr_bencDictRemove( &metainfo, "announce" );
2453        tr_bencDictRemove( &metainfo, "announce-list" );
2454
2455        /* add the new fields */
2456        if( trackerCount > 0 )
2457        {
2458            tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2459        }
2460        if( trackerCount > 1 )
2461        {
2462            int i;
2463            int prevTier = -1;
2464            tr_benc * tier = NULL;
2465            tr_benc * announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2466
2467            for( i=0; i<trackerCount; ++i ) {
2468                if( prevTier != trackers[i].tier ) {
2469                    prevTier = trackers[i].tier;
2470                    tier = tr_bencListAddList( announceList, 0 );
2471                }
2472                tr_bencListAddStr( tier, trackers[i].announce );
2473            }
2474        }
2475
2476        /* try to parse it back again, to make sure it's good */
2477        memset( &tmpInfo, 0, sizeof( tr_info ) );
2478        if( tr_metainfoParse( tor->session, &metainfo, &tmpInfo,
2479                              &hasInfo, &tor->infoDictLength ) )
2480        {
2481            /* it's good, so keep these new trackers and free the old ones */
2482
2483            tr_info swap;
2484            swap.trackers = tor->info.trackers;
2485            swap.trackerCount = tor->info.trackerCount;
2486            tor->info.trackers = tmpInfo.trackers;
2487            tor->info.trackerCount = tmpInfo.trackerCount;
2488            tmpInfo.trackers = swap.trackers;
2489            tmpInfo.trackerCount = swap.trackerCount;
2490
2491            tr_metainfoFree( &tmpInfo );
2492            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2493        }
2494
2495        /* cleanup */
2496        tr_bencFree( &metainfo );
2497
2498        /* if we had a tracker-related error on this torrent,
2499         * and that tracker's been removed,
2500         * then clear the error */
2501        if(    ( tor->error == TR_STAT_TRACKER_WARNING )
2502            || ( tor->error == TR_STAT_TRACKER_ERROR ) )
2503        {
2504            bool clear = true;
2505
2506            for( i=0; clear && i<trackerCount; ++i )
2507                if( !strcmp( trackers[i].announce, tor->errorTracker ) )
2508                    clear = false;
2509
2510            if( clear )
2511                tr_torrentClearError( tor );
2512        }
2513
2514        /* tell the announcer to reload this torrent's tracker list */
2515        tr_announcerResetTorrent( tor->session->announcer, tor );
2516    }
2517
2518    tr_torrentUnlock( tor );
2519
2520    tr_free( trackers );
2521    return ok;
2522}
2523
2524/**
2525***
2526**/
2527
2528void
2529tr_torrentSetAddedDate( tr_torrent * tor,
2530                        time_t       t )
2531{
2532    assert( tr_isTorrent( tor ) );
2533
2534    tor->addedDate = t;
2535    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2536}
2537
2538void
2539tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2540{
2541    assert( tr_isTorrent( tor ) );
2542
2543    tor->activityDate = t;
2544    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2545}
2546
2547void
2548tr_torrentSetDoneDate( tr_torrent * tor,
2549                       time_t       t )
2550{
2551    assert( tr_isTorrent( tor ) );
2552
2553    tor->doneDate = t;
2554    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2555}
2556
2557/**
2558***
2559**/
2560
2561uint64_t
2562tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2563{
2564    tr_file_index_t i;
2565    uint64_t bytesLeft = 0;
2566
2567    assert( tr_isTorrent( tor ) );
2568
2569    for( i=0; i<tor->info.fileCount; ++i )
2570    {
2571        if( !tor->info.files[i].dnd )
2572        {
2573            struct stat sb;
2574            const uint64_t length = tor->info.files[i].length;
2575            char * path = tr_torrentFindFile( tor, i );
2576
2577            bytesLeft += length;
2578
2579            if( ( path != NULL ) && !stat( path, &sb )
2580                                 && S_ISREG( sb.st_mode )
2581                                 && ( (uint64_t)sb.st_size <= length ) )
2582                bytesLeft -= sb.st_size;
2583
2584            tr_free( path );
2585        }
2586    }
2587
2588    return bytesLeft;
2589}
2590
2591/****
2592*****  Removing the torrent's local data
2593****/
2594
2595static int
2596vstrcmp( const void * a, const void * b )
2597{
2598    return strcmp( a, b );
2599}
2600
2601static int
2602compareLongestFirst( const void * a, const void * b )
2603{
2604    const size_t alen = strlen( a );
2605    const size_t blen = strlen( b );
2606
2607    if( alen != blen )
2608        return alen > blen ? -1 : 1;
2609
2610    return vstrcmp( a, b );
2611}
2612
2613static void
2614addDirtyFile( const char  * root,
2615              const char  * filename,
2616              tr_ptrArray * dirtyFolders )
2617{
2618    char * dir = tr_dirname( filename );
2619
2620    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2621    while (     ( dir != NULL )
2622             && ( strlen( root ) <= strlen( dir ) )
2623             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2624    {
2625        char * tmp;
2626        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2627
2628        tmp = tr_dirname( dir );
2629        tr_free( dir );
2630        dir = tmp;
2631    }
2632
2633    tr_free( dir );
2634}
2635
2636static void
2637walkLocalData( const tr_torrent * tor,
2638               const char       * root,
2639               const char       * dir,
2640               const char       * base,
2641               tr_ptrArray      * torrentFiles,
2642               tr_ptrArray      * folders,
2643               tr_ptrArray      * dirtyFolders )
2644{
2645    struct stat sb;
2646    char * buf = tr_buildPath( dir, base, NULL );
2647    int i = stat( buf, &sb );
2648
2649    if( !i )
2650    {
2651        DIR * odir = NULL;
2652
2653        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2654        {
2655            struct dirent *d;
2656            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2657            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2658                if( d->d_name && strcmp( d->d_name, "." ) && strcmp( d->d_name, ".." ) )
2659                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2660            closedir( odir );
2661        }
2662        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2663        {
2664            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2665            const bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2666            if( !isTorrentFile )
2667                addDirtyFile( root, buf, dirtyFolders );
2668        }
2669    }
2670
2671    tr_free( buf );
2672}
2673
2674static void
2675deleteLocalFile( const char * filename, tr_fileFunc fileFunc )
2676{
2677    struct stat sb;
2678    if( !stat( filename, &sb ) ) /* if file exists... */
2679        fileFunc( filename );
2680}
2681
2682static void
2683deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2684{
2685    int i, n;
2686    char ** s;
2687    tr_file_index_t f;
2688    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2689    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2690    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2691
2692    const char * firstFile = tor->info.files[0].name;
2693    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2694    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2695    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2696
2697    for( f=0; f<tor->info.fileCount; ++f ) {
2698        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2699        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2700    }
2701
2702    /* build the set of folders and dirtyFolders */
2703    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2704
2705    /* try to remove entire folders first, so that the recycle bin will be tidy */
2706    s = (char**) tr_ptrArrayPeek( &folders, &n );
2707    for( i=0; i<n; ++i )
2708        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2709            deleteLocalFile( s[i], fileFunc );
2710
2711    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2712    for( i=0, n=tr_ptrArraySize( &torrentFiles ); i<n; ++i ) {
2713        char * path = tr_buildPath( tor->currentDir, tr_ptrArrayNth( &torrentFiles, i ), NULL );
2714        deleteLocalFile( path, fileFunc );
2715        tr_free( path );
2716    }
2717
2718    /* Now clean out the directories left empty from the previous step.
2719     * Work from deepest to shallowest s.t. lower folders
2720     * won't prevent the upper folders from being deleted */
2721    {
2722        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2723        s = (char**) tr_ptrArrayPeek( &folders, &n );
2724        for( i=0; i<n; ++i )
2725            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2726                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2727        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2728        for( i=0; i<n; ++i ) {
2729#ifdef SYS_DARWIN
2730            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2731            deleteLocalFile( dsStore, fileFunc );
2732            tr_free( dsStore );
2733#endif
2734            deleteLocalFile( s[i], fileFunc );
2735        }
2736        tr_ptrArrayDestruct( &cleanFolders, NULL );
2737    }
2738
2739    /* cleanup */
2740    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2741    tr_ptrArrayDestruct( &folders, tr_free );
2742    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2743    tr_free( root );
2744    tr_free( tmp );
2745}
2746
2747static void
2748tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2749{
2750    assert( tr_isTorrent( tor ) );
2751
2752    if( fileFunc == NULL )
2753        fileFunc = remove;
2754
2755    /* close all the files because we're about to delete them */
2756    tr_cacheFlushTorrent( tor->session->cache, tor );
2757    tr_fdTorrentClose( tor->session, tor->uniqueId );
2758
2759    if( tor->info.fileCount > 1 )
2760    {
2761        deleteLocalData( tor, fileFunc );
2762    }
2763    else if( tor->info.fileCount == 1 )
2764    {
2765        char * tmp;
2766
2767        /* torrent only has one file */
2768        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2769        deleteLocalFile( path, fileFunc );
2770        tr_free( path );
2771
2772        tmp = tr_torrentBuildPartial( tor, 0 );
2773        path = tr_buildPath( tor->currentDir, tmp, NULL );
2774        deleteLocalFile( path, fileFunc );
2775        tr_free( path );
2776        tr_free( tmp );
2777    }
2778}
2779
2780/***
2781****
2782***/
2783
2784struct LocationData
2785{
2786    bool move_from_old_location;
2787    volatile int * setme_state;
2788    volatile double * setme_progress;
2789    char * location;
2790    tr_torrent * tor;
2791};
2792
2793static void
2794setLocation( void * vdata )
2795{
2796    bool err = false;
2797    struct LocationData * data = vdata;
2798    tr_torrent * tor = data->tor;
2799    const bool do_move = data->move_from_old_location;
2800    const char * location = data->location;
2801    double bytesHandled = 0;
2802
2803    assert( tr_isTorrent( tor ) );
2804
2805    tr_dbg( "Moving \"%s\" location from currentDir \"%s\" to \"%s\"",
2806            tr_torrentName(tor), tor->currentDir, location );
2807
2808    tr_mkdirp( location, 0777 );
2809
2810    if( !tr_is_same_file( location, tor->currentDir ) )
2811    {
2812        tr_file_index_t i;
2813
2814        /* bad idea to move files while they're being verified... */
2815        tr_verifyRemove( tor );
2816
2817        /* try to move the files.
2818         * FIXME: there are still all kinds of nasty cases, like what
2819         * if the target directory runs out of space halfway through... */
2820        for( i=0; !err && i<tor->info.fileCount; ++i )
2821        {
2822            const tr_file * f = &tor->info.files[i];
2823            const char * oldbase;
2824            char * sub;
2825            if( tr_torrentFindFile2( tor, i, &oldbase, &sub, NULL ) )
2826            {
2827                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2828                char * newpath = tr_buildPath( location, sub, NULL );
2829
2830                tr_dbg( "Found file #%d: %s", (int)i, oldpath );
2831
2832                if( do_move && !tr_is_same_file( oldpath, newpath ) )
2833                {
2834                    bool renamed = false;
2835                    errno = 0;
2836                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2837                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2838                    {
2839                        err = true;
2840                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2841                                        oldpath, newpath, tr_strerror( errno ) );
2842                    }
2843                }
2844
2845                tr_free( newpath );
2846                tr_free( oldpath );
2847                tr_free( sub );
2848            }
2849
2850            if( data->setme_progress )
2851            {
2852                bytesHandled += f->length;
2853                *data->setme_progress = bytesHandled / tor->info.totalSize;
2854            }
2855        }
2856
2857        if( !err )
2858        {
2859            /* blow away the leftover subdirectories in the old location */
2860            if( do_move )
2861                tr_torrentDeleteLocalData( tor, remove );
2862
2863            /* set the new location and reverify */
2864            tr_torrentSetDownloadDir( tor, location );
2865        }
2866    }
2867
2868    if( !err && do_move )
2869    {
2870        tr_free( tor->incompleteDir );
2871        tor->incompleteDir = NULL;
2872        tor->currentDir = tor->downloadDir;
2873    }
2874
2875    if( data->setme_state )
2876        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2877
2878    /* cleanup */
2879    tr_free( data->location );
2880    tr_free( data );
2881}
2882
2883void
2884tr_torrentSetLocation( tr_torrent       * tor,
2885                       const char       * location,
2886                       bool               move_from_old_location,
2887                       volatile double  * setme_progress,
2888                       volatile int     * setme_state )
2889{
2890    struct LocationData * data;
2891
2892    assert( tr_isTorrent( tor ) );
2893
2894    if( setme_state )
2895        *setme_state = TR_LOC_MOVING;
2896    if( setme_progress )
2897        *setme_progress = 0;
2898
2899    /* run this in the libtransmission thread */
2900    data = tr_new( struct LocationData, 1 );
2901    data->tor = tor;
2902    data->location = tr_strdup( location );
2903    data->move_from_old_location = move_from_old_location;
2904    data->setme_state = setme_state;
2905    data->setme_progress = setme_progress;
2906    tr_runInEventThread( tor->session, setLocation, data );
2907}
2908
2909/***
2910****
2911***/
2912
2913void
2914tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2915{
2916    char * sub;
2917    const char * base;
2918    const tr_info * inf = &tor->info;
2919    const tr_file * f = &inf->files[fileNum];
2920    tr_piece * p;
2921    const tr_piece * pend;
2922    const time_t now = tr_time( );
2923
2924    /* close the file so that we can reopen in read-only mode as needed */
2925    tr_fdFileClose( tor->session, tor, fileNum );
2926
2927    /* now that the file is complete and closed, we can start watching its
2928     * mtime timestamp for changes to know if we need to reverify pieces */
2929    for( p=&inf->pieces[f->firstPiece], pend=&inf->pieces[f->lastPiece]; p!=pend; ++p )
2930        p->timeChecked = now;
2931
2932    /* if the torrent's current filename isn't the same as the one in the
2933     * metadata -- for example, if it had the ".part" suffix appended to
2934     * it until now -- then rename it to match the one in the metadata */
2935    if( tr_torrentFindFile2( tor, fileNum, &base, &sub, NULL ) )
2936    {
2937        if( strcmp( sub, f->name ) )
2938        {
2939            char * oldpath = tr_buildPath( base, sub, NULL );
2940            char * newpath = tr_buildPath( base, f->name, NULL );
2941
2942            if( rename( oldpath, newpath ) )
2943                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2944
2945            tr_free( newpath );
2946            tr_free( oldpath );
2947        }
2948
2949        tr_free( sub );
2950    }
2951}
2952
2953/***
2954****
2955***/
2956
2957#ifdef SYS_DARWIN
2958 #define TR_STAT_MTIME(sb) ((sb).st_mtimespec.tv_sec)
2959#else
2960 #define TR_STAT_MTIME(sb) ((sb).st_mtime)
2961#endif
2962
2963
2964static bool
2965fileExists( const char * filename, time_t * mtime )
2966{
2967    struct stat sb;
2968    const bool ok = !stat( filename, &sb );
2969
2970    if( ok && ( mtime != NULL ) )
2971        *mtime = TR_STAT_MTIME( sb );
2972
2973    return ok;
2974}
2975
2976bool
2977tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
2978                     const char ** base, char ** subpath, time_t * mtime )
2979{
2980    char * part = NULL;
2981    const tr_file * file;
2982    const char * b = NULL;
2983    const char * s = NULL;
2984
2985    assert( tr_isTorrent( tor ) );
2986    assert( fileNum < tor->info.fileCount );
2987
2988    file = &tor->info.files[fileNum];
2989
2990    if( b == NULL ) {
2991        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
2992        if( fileExists( filename, mtime ) ) {
2993            b = tor->downloadDir;
2994            s = file->name;
2995        }
2996        tr_free( filename );
2997    }
2998
2999    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
3000        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
3001        if( fileExists( filename, mtime ) ) {
3002            b = tor->incompleteDir;
3003            s = file->name;
3004        }
3005        tr_free( filename );
3006    }
3007
3008    if( b == NULL )
3009        part = tr_torrentBuildPartial( tor, fileNum );
3010
3011    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
3012        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
3013        if( fileExists( filename, mtime ) ) {
3014            b = tor->incompleteDir;
3015            s = part;
3016        }
3017        tr_free( filename );
3018    }
3019
3020    if( b == NULL) {
3021        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
3022        if( fileExists( filename, mtime ) ) {
3023            b = tor->downloadDir;
3024            s = part;
3025        }
3026        tr_free( filename );
3027    }
3028
3029    if( base != NULL )
3030        *base = b;
3031    if( subpath != NULL )
3032        *subpath = tr_strdup( s );
3033
3034    tr_free( part );
3035    return b != NULL;
3036}
3037
3038char*
3039tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
3040{
3041    char * subpath;
3042    char * ret = NULL;
3043    const char * base;
3044
3045    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath, NULL ) )
3046    {
3047        ret = tr_buildPath( base, subpath, NULL );
3048        tr_free( subpath );
3049    }
3050
3051    return ret;
3052}
3053
3054/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
3055static void
3056refreshCurrentDir( tr_torrent * tor )
3057{
3058    const char * dir = NULL;
3059
3060    if( tor->incompleteDir == NULL )
3061        dir = tor->downloadDir;
3062    else if( !tr_torrentHasMetadata( tor ) ) /* no files to find */
3063        dir = tor->incompleteDir;
3064    else if( !tr_torrentFindFile2( tor, 0, &dir, NULL, NULL ) )
3065        dir = tor->incompleteDir;
3066
3067    assert( dir != NULL );
3068    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
3069    tor->currentDir = dir;
3070}
3071
3072char*
3073tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
3074{
3075    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
3076}
Note: See TracBrowser for help on using the repository browser.