source: trunk/libtransmission/torrent.c @ 12295

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

(trunk libT) tr_torrentFindFile2(): avoid an unnecessary malloc() + free() if the file we're looking for is complete and doesn't have a ".part" suffix

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