source: trunk/libtransmission/torrent.c @ 12233

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

(trunk) yet more "#include" tweaks

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