source: trunk/libtransmission/torrent.c @ 12503

Last change on this file since 12503 was 12503, checked in by livings124, 10 years ago

#4326 flags for completeness and wasRunning flipped in completeness callback

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