source: trunk/libtransmission/torrent.c @ 12132

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

(trunk libT) ensure that a tr_torrent's peer id is initialized when the tr_torrent is constructed

  • 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 12132 2011-03-11 15:00:10Z jordan $
11 */
12
13#include <signal.h> /* signal() */
14#include <sys/types.h> /* stat */
15#include <sys/stat.h> /* stat */
16#ifndef WIN32
17 #include <sys/wait.h> /* wait() */
18#else
19 #include <process.h>
20 #define waitpid(pid, status, options)  _cwait(status, pid, WAIT_CHILD)
21#endif
22#include <unistd.h> /* stat */
23#include <dirent.h>
24
25#include <assert.h>
26#include <limits.h> /* INT_MAX */
27#include <math.h>
28#include <stdarg.h>
29#include <string.h> /* memcmp */
30#include <stdlib.h> /* qsort */
31
32#include <event2/util.h> /* evutil_vsnprintf() */
33
34#include "transmission.h"
35#include "announcer.h"
36#include "bandwidth.h"
37#include "bencode.h"
38#include "cache.h"
39#include "completion.h"
40#include "crypto.h" /* for tr_sha1 */
41#include "resume.h"
42#include "fdlimit.h" /* tr_fdTorrentClose */
43#include "inout.h" /* tr_ioTestPiece() */
44#include "magnet.h"
45#include "metainfo.h"
46#include "peer-common.h" /* MAX_BLOCK_SIZE */
47#include "peer-mgr.h"
48#include "platform.h" /* TR_PATH_DELIMITER_STR */
49#include "ptrarray.h"
50#include "session.h"
51#include "torrent.h"
52#include "torrent-magnet.h"
53#include "trevent.h" /* tr_runInEventThread() */
54#include "utils.h"
55#include "verify.h"
56#include "version.h"
57
58/***
59****
60***/
61
62#define tr_deeplog_tor( tor, ... ) \
63    do { \
64        if( tr_deepLoggingIsActive( ) ) \
65            tr_deepLog( __FILE__, __LINE__, tr_torrentName( tor ), __VA_ARGS__ ); \
66    } while( 0 )
67
68/***
69****
70***/
71
72const char *
73tr_torrentName( const tr_torrent * tor )
74{
75    assert( tr_isTorrent( tor ) );
76
77    return tor->info.name;
78}
79
80int
81tr_torrentId( const tr_torrent * tor )
82{
83    return tor->uniqueId;
84}
85
86tr_torrent*
87tr_torrentFindFromId( tr_session * session, int id )
88{
89    tr_torrent * tor = NULL;
90
91    while(( tor = tr_torrentNext( session, tor )))
92        if( tor->uniqueId == id )
93            return tor;
94
95    return NULL;
96}
97
98tr_torrent*
99tr_torrentFindFromHashString( tr_session *  session, const char * str )
100{
101    tr_torrent * tor = NULL;
102
103    while(( tor = tr_torrentNext( session, tor )))
104        if( !strcasecmp( str, tor->info.hashString ) )
105            return tor;
106
107    return NULL;
108}
109
110tr_torrent*
111tr_torrentFindFromHash( tr_session * session, const uint8_t * torrentHash )
112{
113    tr_torrent * tor = NULL;
114
115    while(( tor = tr_torrentNext( session, tor )))
116        if( *tor->info.hash == *torrentHash )
117            if( !memcmp( tor->info.hash, torrentHash, SHA_DIGEST_LENGTH ) )
118                return tor;
119
120    return NULL;
121}
122
123tr_torrent*
124tr_torrentFindFromMagnetLink( tr_session * session, const char * magnet )
125{
126    tr_magnet_info * info;
127    tr_torrent * tor = NULL;
128
129    if(( info = tr_magnetParse( magnet )))
130    {
131        tor = tr_torrentFindFromHash( session, info->hash );
132        tr_magnetFree( info );
133    }
134
135    return tor;
136}
137
138tr_torrent*
139tr_torrentFindFromObfuscatedHash( tr_session * session,
140                                  const uint8_t * obfuscatedTorrentHash )
141{
142    tr_torrent * tor = NULL;
143
144    while(( tor = tr_torrentNext( session, tor )))
145        if( !memcmp( tor->obfuscatedHash, obfuscatedTorrentHash,
146                     SHA_DIGEST_LENGTH ) )
147            return tor;
148
149    return NULL;
150}
151
152tr_bool
153tr_torrentIsPieceTransferAllowed( const tr_torrent  * tor,
154                                  tr_direction        direction )
155{
156    int limit;
157    tr_bool allowed = TRUE;
158
159    if( tr_torrentUsesSpeedLimit( tor, direction ) )
160        if( tr_torrentGetSpeedLimit_Bps( tor, direction ) <= 0 )
161            allowed = FALSE;
162
163    if( tr_torrentUsesSessionLimits( tor ) )
164        if( tr_sessionGetActiveSpeedLimit_Bps( tor->session, direction, &limit ) )
165            if( limit <= 0 )
166                allowed = FALSE;
167
168    return allowed;
169}
170
171/***
172****  PER-TORRENT UL / DL SPEEDS
173***/
174
175void
176tr_torrentSetSpeedLimit_Bps( tr_torrent * tor, tr_direction dir, int Bps )
177{
178    assert( tr_isTorrent( tor ) );
179    assert( tr_isDirection( dir ) );
180    assert( Bps >= 0 );
181
182    if( tr_bandwidthSetDesiredSpeed_Bps( tor->bandwidth, dir, Bps ) )
183        tr_torrentSetDirty( tor );
184}
185void
186tr_torrentSetSpeedLimit_KBps( tr_torrent * tor, tr_direction dir, int KBps )
187{
188    tr_torrentSetSpeedLimit_Bps( tor, dir, toSpeedBytes( KBps ) );
189}
190
191int
192tr_torrentGetSpeedLimit_Bps( const tr_torrent * tor, tr_direction dir )
193{
194    assert( tr_isTorrent( tor ) );
195    assert( tr_isDirection( dir ) );
196
197    return tr_bandwidthGetDesiredSpeed_Bps( tor->bandwidth, dir );
198}
199int
200tr_torrentGetSpeedLimit_KBps( const tr_torrent * tor, tr_direction dir )
201{
202    return toSpeedKBps( tr_torrentGetSpeedLimit_Bps( tor, dir ) );
203}
204
205void
206tr_torrentUseSpeedLimit( tr_torrent * tor, tr_direction dir, tr_bool do_use )
207{
208    assert( tr_isTorrent( tor ) );
209    assert( tr_isDirection( dir ) );
210
211    if( tr_bandwidthSetLimited( tor->bandwidth, dir, do_use ) )
212        tr_torrentSetDirty( tor );
213}
214
215tr_bool
216tr_torrentUsesSpeedLimit( const tr_torrent * tor, tr_direction dir )
217{
218    assert( tr_isTorrent( tor ) );
219    assert( tr_isDirection( dir ) );
220
221    return tr_bandwidthIsLimited( tor->bandwidth, dir );
222}
223
224void
225tr_torrentUseSessionLimits( tr_torrent * tor, tr_bool doUse )
226{
227    tr_bool changed;
228
229    assert( tr_isTorrent( tor ) );
230
231    changed = tr_bandwidthHonorParentLimits( tor->bandwidth, TR_UP, doUse );
232    changed |= tr_bandwidthHonorParentLimits( tor->bandwidth, TR_DOWN, doUse );
233
234    if( changed )
235        tr_torrentSetDirty( tor );
236}
237
238tr_bool
239tr_torrentUsesSessionLimits( const tr_torrent * tor )
240{
241    assert( tr_isTorrent( tor ) );
242
243    return tr_bandwidthAreParentLimitsHonored( tor->bandwidth, TR_UP );
244}
245
246/***
247****
248***/
249
250void
251tr_torrentSetRatioMode( tr_torrent *  tor, tr_ratiolimit mode )
252{
253    assert( tr_isTorrent( tor ) );
254    assert( mode==TR_RATIOLIMIT_GLOBAL || mode==TR_RATIOLIMIT_SINGLE || mode==TR_RATIOLIMIT_UNLIMITED  );
255
256    if( mode != tor->ratioLimitMode )
257    {
258        tor->ratioLimitMode = mode;
259
260        tr_torrentSetDirty( tor );
261    }
262}
263
264tr_ratiolimit
265tr_torrentGetRatioMode( const tr_torrent * tor )
266{
267    assert( tr_isTorrent( tor ) );
268
269    return tor->ratioLimitMode;
270}
271
272void
273tr_torrentSetRatioLimit( tr_torrent * tor, double desiredRatio )
274{
275    assert( tr_isTorrent( tor ) );
276
277    if( (int)(desiredRatio*100.0) != (int)(tor->desiredRatio*100.0) )
278    {
279        tor->desiredRatio = desiredRatio;
280
281        tr_torrentSetDirty( tor );
282    }
283}
284
285double
286tr_torrentGetRatioLimit( const tr_torrent * tor )
287{
288    assert( tr_isTorrent( tor ) );
289
290    return tor->desiredRatio;
291}
292
293tr_bool
294tr_torrentGetSeedRatio( const tr_torrent * tor, double * ratio )
295{
296    tr_bool isLimited;
297
298    switch( tr_torrentGetRatioMode( tor ) )
299    {
300        case TR_RATIOLIMIT_SINGLE:
301            isLimited = TRUE;
302            if( ratio )
303                *ratio = tr_torrentGetRatioLimit( tor );
304            break;
305
306        case TR_RATIOLIMIT_GLOBAL:
307            isLimited = tr_sessionIsRatioLimited( tor->session );
308            if( isLimited && ratio )
309                *ratio = tr_sessionGetRatioLimit( tor->session );
310            break;
311
312        default: /* TR_RATIOLIMIT_UNLIMITED */
313            isLimited = FALSE;
314            break;
315    }
316
317    return isLimited;
318}
319
320/* returns true if the seed ratio applies --
321 * it applies if the torrent's a seed AND it has a seed ratio set */
322static tr_bool
323tr_torrentGetSeedRatioBytes( tr_torrent  * tor,
324                             uint64_t    * setmeLeft,
325                             uint64_t    * setmeGoal )
326{
327    double seedRatio;
328    tr_bool seedRatioApplies = FALSE;
329
330    if( tr_torrentGetSeedRatio( tor, &seedRatio ) )
331    {
332        const uint64_t u = tor->uploadedCur + tor->uploadedPrev;
333        const uint64_t d = tor->downloadedCur + tor->downloadedPrev;
334        const uint64_t baseline = d ? d : tr_cpSizeWhenDone( &tor->completion );
335        const uint64_t goal = baseline * seedRatio;
336        if( setmeLeft ) *setmeLeft = goal > u ? goal - u : 0;
337        if( setmeGoal ) *setmeGoal = goal;
338        seedRatioApplies = tr_torrentIsSeed( tor );
339    }
340
341    return seedRatioApplies;
342}
343
344static tr_bool
345tr_torrentIsSeedRatioDone( tr_torrent * tor )
346{
347    uint64_t bytesLeft;
348    return tr_torrentGetSeedRatioBytes( tor, &bytesLeft, NULL ) && !bytesLeft;
349}
350
351/***
352****
353***/
354
355void
356tr_torrentSetIdleMode( tr_torrent *  tor, tr_idlelimit mode )
357{
358    assert( tr_isTorrent( tor ) );
359    assert( mode==TR_IDLELIMIT_GLOBAL || mode==TR_IDLELIMIT_SINGLE || mode==TR_IDLELIMIT_UNLIMITED  );
360
361    if( mode != tor->idleLimitMode )
362    {
363        tor->idleLimitMode = mode;
364
365        tr_torrentSetDirty( tor );
366    }
367}
368
369tr_idlelimit
370tr_torrentGetIdleMode( const tr_torrent * tor )
371{
372    assert( tr_isTorrent( tor ) );
373
374    return tor->idleLimitMode;
375}
376
377void
378tr_torrentSetIdleLimit( tr_torrent * tor, uint16_t idleMinutes )
379{
380    assert( tr_isTorrent( tor ) );
381
382    if( idleMinutes > 0 )
383    {
384        tor->idleLimitMinutes = idleMinutes;
385
386        tr_torrentSetDirty( tor );
387    }
388}
389
390uint16_t
391tr_torrentGetIdleLimit( const tr_torrent * tor )
392{
393    assert( tr_isTorrent( tor ) );
394
395    return tor->idleLimitMinutes;
396}
397
398tr_bool
399tr_torrentGetSeedIdle( const tr_torrent * tor, uint16_t * idleMinutes )
400{
401    tr_bool isLimited;
402
403    switch( tr_torrentGetIdleMode( tor ) )
404    {
405        case TR_IDLELIMIT_SINGLE:
406            isLimited = TRUE;
407            if( idleMinutes )
408                *idleMinutes = tr_torrentGetIdleLimit( tor );
409            break;
410
411        case TR_IDLELIMIT_GLOBAL:
412            isLimited = tr_sessionIsIdleLimited( tor->session );
413            if( isLimited && idleMinutes )
414                *idleMinutes = tr_sessionGetIdleLimit( tor->session );
415            break;
416
417        default: /* TR_IDLELIMIT_UNLIMITED */
418            isLimited = FALSE;
419            break;
420    }
421
422    return isLimited;
423}
424
425static tr_bool
426tr_torrentIsSeedIdleLimitDone( tr_torrent * tor )
427{
428    uint16_t idleMinutes;
429    return tr_torrentGetSeedIdle( tor, &idleMinutes )
430        && difftime(tr_time(), MAX(tor->startDate, tor->activityDate)) >= idleMinutes * 60u;
431}
432
433/***
434****
435***/
436
437void
438tr_torrentCheckSeedLimit( tr_torrent * tor )
439{
440    assert( tr_isTorrent( tor ) );
441
442    if( !tor->isRunning || !tr_torrentIsSeed( tor ) )
443        return;
444
445    /* if we're seeding and reach our seed ratio limit, stop the torrent */
446    if( tr_torrentIsSeedRatioDone( tor ) )
447    {
448        tr_torinf( tor, "Seed ratio reached; pausing torrent" );
449
450        tor->isStopping = TRUE;
451
452        /* maybe notify the client */
453        if( tor->ratio_limit_hit_func != NULL )
454            tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
455    }
456    /* if we're seeding and reach our inactiviy limit, stop the torrent */
457    else if( tr_torrentIsSeedIdleLimitDone( tor ) )
458    {
459        tr_torinf( tor, "Seeding idle limit reached; pausing torrent" );
460
461        tor->isStopping = TRUE;
462        tor->finishedSeedingByIdle = TRUE;
463
464        /* maybe notify the client */
465        if( tor->idle_limit_hit_func != NULL )
466            tor->idle_limit_hit_func( tor, tor->idle_limit_hit_func_user_data );
467    }
468}
469
470/***
471****
472***/
473
474void
475tr_torrentSetLocalError( tr_torrent * tor, const char * fmt, ... )
476{
477    va_list ap;
478
479    assert( tr_isTorrent( tor ) );
480
481    va_start( ap, fmt );
482    tor->error = TR_STAT_LOCAL_ERROR;
483    tor->errorTracker[0] = '\0';
484    evutil_vsnprintf( tor->errorString, sizeof( tor->errorString ), fmt, ap );
485    va_end( ap );
486
487    tr_torerr( tor, "%s", tor->errorString );
488
489    if( tor->isRunning )
490        tor->isStopping = TRUE;
491}
492
493static void
494tr_torrentClearError( tr_torrent * tor )
495{
496    tor->error = TR_STAT_OK;
497    tor->errorString[0] = '\0';
498    tor->errorTracker[0] = '\0';
499}
500
501static void
502onTrackerResponse( tr_torrent * tor, const tr_tracker_event * event, void * unused UNUSED )
503{
504    switch( event->messageType )
505    {
506        case TR_TRACKER_PEERS:
507        {
508            size_t i;
509            const int8_t seedProbability = event->seedProbability;
510            const tr_bool allAreSeeds = seedProbability == 100;
511
512             if( allAreSeeds )
513                tr_tordbg( tor, "Got %zu seeds from tracker", event->pexCount );
514            else
515                tr_tordbg( tor, "Got %zu peers from tracker", event->pexCount );
516
517            for( i = 0; i < event->pexCount; ++i )
518                tr_peerMgrAddPex( tor, TR_PEER_FROM_TRACKER, &event->pex[i], seedProbability );
519
520            if( allAreSeeds && tr_torrentIsPrivate( tor ) )
521                tr_peerMgrMarkAllAsSeeds( tor );
522
523            break;
524        }
525
526        case TR_TRACKER_WARNING:
527            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
528            tor->error = TR_STAT_TRACKER_WARNING;
529            tr_strlcpy( tor->errorTracker, event->tracker, sizeof( tor->errorTracker ) );
530            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
531            break;
532
533        case TR_TRACKER_ERROR:
534            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
535            tor->error = TR_STAT_TRACKER_ERROR;
536            tr_strlcpy( tor->errorTracker, event->tracker, sizeof( tor->errorTracker ) );
537            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
538            break;
539
540        case TR_TRACKER_ERROR_CLEAR:
541            if( tor->error != TR_STAT_LOCAL_ERROR )
542                tr_torrentClearError( tor );
543            break;
544    }
545}
546
547/***
548****
549****  TORRENT INSTANTIATION
550****
551***/
552
553static tr_piece_index_t
554getBytePiece( const tr_info * info, uint64_t byteOffset )
555{
556    assert( info );
557    assert( info->pieceSize != 0 );
558
559    return byteOffset / info->pieceSize;
560}
561
562static void
563initFilePieces( tr_info *       info,
564                tr_file_index_t fileIndex )
565{
566    tr_file * file;
567    uint64_t  firstByte, lastByte;
568
569    assert( info );
570    assert( fileIndex < info->fileCount );
571
572    file = &info->files[fileIndex];
573    firstByte = file->offset;
574    lastByte = firstByte + ( file->length ? file->length - 1 : 0 );
575    file->firstPiece = getBytePiece( info, firstByte );
576    file->lastPiece = getBytePiece( info, lastByte );
577}
578
579static int
580pieceHasFile( tr_piece_index_t piece,
581              const tr_file *  file )
582{
583    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
584}
585
586static tr_priority_t
587calculatePiecePriority( const tr_torrent * tor,
588                        tr_piece_index_t   piece,
589                        int                fileHint )
590{
591    tr_file_index_t i;
592    tr_priority_t priority = TR_PRI_LOW;
593
594    /* find the first file that has data in this piece */
595    if( fileHint >= 0 ) {
596        i = fileHint;
597        while( i > 0 && pieceHasFile( piece, &tor->info.files[i - 1] ) )
598            --i;
599    } else {
600        for( i = 0; i < tor->info.fileCount; ++i )
601            if( pieceHasFile( piece, &tor->info.files[i] ) )
602                break;
603    }
604
605    /* the piece's priority is the max of the priorities
606     * of all the files in that piece */
607    for( ; i < tor->info.fileCount; ++i )
608    {
609        const tr_file * file = &tor->info.files[i];
610
611        if( !pieceHasFile( piece, file ) )
612            break;
613
614        priority = MAX( priority, file->priority );
615
616        /* when dealing with multimedia files, getting the first and
617           last pieces can sometimes allow you to preview it a bit
618           before it's fully downloaded... */
619        if( file->priority >= TR_PRI_NORMAL )
620            if( file->firstPiece == piece || file->lastPiece == piece )
621                priority = TR_PRI_HIGH;
622    }
623
624    return priority;
625}
626
627static void
628tr_torrentInitFilePieces( tr_torrent * tor )
629{
630    int * firstFiles;
631    tr_file_index_t f;
632    tr_piece_index_t p;
633    uint64_t offset = 0;
634    tr_info * inf = &tor->info;
635
636    /* assign the file offsets */
637    for( f=0; f<inf->fileCount; ++f ) {
638        inf->files[f].offset = offset;
639        offset += inf->files[f].length;
640        initFilePieces( inf, f );
641    }
642
643    /* build the array of first-file hints to give calculatePiecePriority */
644    firstFiles = tr_new( int, inf->pieceCount );
645    for( p=f=0; p<inf->pieceCount; ++p ) {
646        while( inf->files[f].lastPiece < p )
647            ++f;
648        firstFiles[p] = f;
649    }
650
651#if 0
652    /* test to confirm the first-file hints are correct */
653    for( p=0; p<inf->pieceCount; ++p ) {
654        f = firstFiles[p];
655        assert( inf->files[f].firstPiece <= p );
656        assert( inf->files[f].lastPiece >= p );
657        if( f > 0 )
658            assert( inf->files[f-1].lastPiece < p );
659        for( f=0; f<inf->fileCount; ++f )
660            if( pieceHasFile( p, &inf->files[f] ) )
661                break;
662        assert( (int)f == firstFiles[p] );
663    }
664#endif
665
666    for( p=0; p<inf->pieceCount; ++p )
667        inf->pieces[p].priority = calculatePiecePriority( tor, p, firstFiles[p] );
668
669    tr_free( firstFiles );
670}
671
672static void torrentStart( tr_torrent * tor );
673
674/**
675 * Decide on a block size. Constraints:
676 * (1) most clients decline requests over 16 KiB
677 * (2) pieceSize must be a multiple of block size
678 */
679uint32_t
680tr_getBlockSize( uint32_t pieceSize )
681{
682    uint32_t b = pieceSize;
683
684    while( b > MAX_BLOCK_SIZE )
685        b /= 2u;
686
687    if( !b || ( pieceSize % b ) ) /* not cleanly divisible */
688        return 0;
689    return b;
690}
691
692static void refreshCurrentDir( tr_torrent * tor );
693
694static void
695torrentInitFromInfo( tr_torrent * tor )
696{
697    uint64_t t;
698    tr_info * info = &tor->info;
699
700    tor->blockSize = tr_getBlockSize( info->pieceSize );
701
702    if( info->pieceSize )
703        tor->lastPieceSize = (uint32_t)(info->totalSize % info->pieceSize);
704
705    if( !tor->lastPieceSize )
706        tor->lastPieceSize = info->pieceSize;
707
708    if( tor->blockSize )
709        tor->lastBlockSize = info->totalSize % tor->blockSize;
710
711    if( !tor->lastBlockSize )
712        tor->lastBlockSize = tor->blockSize;
713
714    tor->blockCount = tor->blockSize
715        ? ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize
716        : 0;
717
718    tor->blockCountInPiece = tor->blockSize
719        ? info->pieceSize / tor->blockSize
720        : 0;
721
722    tor->blockCountInLastPiece = tor->blockSize
723        ? ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize
724        : 0;
725
726    /* check our work */
727    if( tor->blockSize != 0 )
728        assert( ( info->pieceSize % tor->blockSize ) == 0 );
729    t = info->pieceCount - 1;
730    t *= info->pieceSize;
731    t += tor->lastPieceSize;
732    assert( t == info->totalSize );
733    t = tor->blockCount - 1;
734    t *= tor->blockSize;
735    t += tor->lastBlockSize;
736    assert( t == info->totalSize );
737    t = info->pieceCount - 1;
738    t *= tor->blockCountInPiece;
739    t += tor->blockCountInLastPiece;
740    assert( t == (uint64_t)tor->blockCount );
741
742    tr_cpConstruct( &tor->completion, tor );
743
744    tr_torrentInitFilePieces( tor );
745
746    tor->completeness = tr_cpGetStatus( &tor->completion );
747}
748
749static void tr_torrentFireMetadataCompleted( tr_torrent * tor );
750
751void
752tr_torrentGotNewInfoDict( tr_torrent * tor )
753{
754    torrentInitFromInfo( tor );
755
756    tr_peerMgrOnTorrentGotMetainfo( tor );
757
758    tr_torrentFireMetadataCompleted( tor );
759}
760
761static tr_bool
762hasAnyLocalData( const tr_torrent * tor )
763{
764    tr_file_index_t i;
765    tr_bool has_local_data = FALSE;
766    const tr_file_index_t n = tor->info.fileCount;
767
768    for( i=0; i<n && !has_local_data; ++i )
769    {
770        struct stat sb;
771        char * filename = tr_torrentFindFile( tor, i );
772
773        if( filename && !stat( filename, &sb ) )
774            has_local_data = TRUE;
775
776        tr_free( filename );
777    }
778
779    return has_local_data;
780}
781
782static tr_bool
783setLocalErrorIfFilesDisappeared( tr_torrent * tor )
784{
785    const tr_bool disappeared = ( tr_cpHaveTotal( &tor->completion ) > 0 ) && !hasAnyLocalData( tor );
786
787    if( disappeared )
788    {
789        tr_deeplog_tor( tor, "%s", "[LAZY] uh oh, the files disappeared" );
790        tr_torrentSetLocalError( tor, "%s", _( "No data found! Ensure your drives are connected or use \"Set Location\". To re-download, remove the torrent and re-add it." ) );
791    }
792
793    return disappeared;
794}
795
796static void
797torrentInit( tr_torrent * tor, const tr_ctor * ctor )
798{
799    int doStart;
800    uint64_t loaded;
801    const char * dir;
802    tr_bool isNewTorrent;
803    struct stat st;
804    static int nextUniqueId = 1;
805    tr_session * session = tr_ctorGetSession( ctor );
806
807    assert( session != NULL );
808
809    tr_sessionLock( session );
810
811    tor->session   = session;
812    tor->uniqueId = nextUniqueId++;
813    tor->magicNumber = TORRENT_MAGIC_NUMBER;
814
815    tr_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                  tr_bool * setmeHasInfo, int * dictLength )
928{
929    int             doFree;
930    tr_bool         didParse;
931    tr_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    tr_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
1069tr_bool
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    tr_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 tr_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                       tr_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 tr_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    tr_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                  tr_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                        tr_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            execve( script, cmd, env );
1953            _exit( 0 );
1954        }
1955#endif
1956
1957        for( i=0; cmd[i]; ++i ) tr_free( cmd[i] );
1958        for( i=0; env[i]; ++i ) tr_free( env[i] );
1959    }
1960}
1961
1962void
1963tr_torrentRecheckCompleteness( tr_torrent * tor )
1964{
1965    tr_completeness completeness;
1966
1967    assert( tr_isTorrent( tor ) );
1968
1969    tr_torrentLock( tor );
1970
1971    completeness = tr_cpGetStatus( &tor->completion );
1972
1973    if( completeness != tor->completeness )
1974    {
1975        const int recentChange = tor->downloadedCur != 0;
1976        const tr_bool wasLeeching = !tr_torrentIsSeed( tor );
1977        const tr_bool wasRunning = tor->isRunning;
1978
1979        if( recentChange )
1980        {
1981            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1982                      getCompletionString( tor->completeness ),
1983                      getCompletionString( completeness ) );
1984        }
1985
1986        tor->completeness = completeness;
1987        tr_fdTorrentClose( tor->session, tor->uniqueId );
1988
1989        if( tr_torrentIsSeed( tor ) )
1990        {
1991            if( recentChange )
1992            {
1993                tr_announcerTorrentCompleted( tor );
1994                tor->doneDate = tor->anyDate = tr_time( );
1995            }
1996
1997            if( wasLeeching && wasRunning )
1998            {
1999                /* clear interested flag on all peers */
2000                tr_peerMgrClearInterest( tor );
2001
2002                /* if completeness was TR_LEECH then the seed limit check will have been skipped in bandwidthPulse */
2003                tr_torrentCheckSeedLimit( tor );
2004            }
2005
2006            if( tor->currentDir == tor->incompleteDir )
2007                tr_torrentSetLocation( tor, tor->downloadDir, TRUE, NULL, NULL );
2008
2009            if( tr_sessionIsTorrentDoneScriptEnabled( tor->session ) )
2010                torrentCallScript( tor, tr_sessionGetTorrentDoneScript( tor->session ) );
2011        }
2012
2013        fireCompletenessChange( tor, wasRunning, completeness );
2014
2015        tr_torrentSetDirty( tor );
2016    }
2017
2018    tr_torrentUnlock( tor );
2019}
2020
2021/***
2022****
2023***/
2024
2025static void
2026tr_torrentFireMetadataCompleted( tr_torrent * tor )
2027{
2028    assert( tr_isTorrent( tor ) );
2029
2030    if( tor->metadata_func )
2031        tor->metadata_func( tor, tor->metadata_func_user_data );
2032}
2033
2034void
2035tr_torrentSetMetadataCallback( tr_torrent                * tor,
2036                               tr_torrent_metadata_func    func,
2037                               void                      * user_data )
2038{
2039    assert( tr_isTorrent( tor ) );
2040
2041    tor->metadata_func = func;
2042    tor->metadata_func_user_data = user_data;
2043}
2044
2045
2046/**
2047***  File priorities
2048**/
2049
2050void
2051tr_torrentInitFilePriority( tr_torrent *    tor,
2052                            tr_file_index_t fileIndex,
2053                            tr_priority_t   priority )
2054{
2055    tr_piece_index_t i;
2056    tr_file *        file;
2057
2058    assert( tr_isTorrent( tor ) );
2059    assert( fileIndex < tor->info.fileCount );
2060    assert( tr_isPriority( priority ) );
2061
2062    file = &tor->info.files[fileIndex];
2063    file->priority = priority;
2064    for( i = file->firstPiece; i <= file->lastPiece; ++i )
2065        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
2066}
2067
2068void
2069tr_torrentSetFilePriorities( tr_torrent             * tor,
2070                             const tr_file_index_t  * files,
2071                             tr_file_index_t          fileCount,
2072                             tr_priority_t            priority )
2073{
2074    tr_file_index_t i;
2075    assert( tr_isTorrent( tor ) );
2076    tr_torrentLock( tor );
2077
2078    for( i = 0; i < fileCount; ++i )
2079        if( files[i] < tor->info.fileCount )
2080            tr_torrentInitFilePriority( tor, files[i], priority );
2081    tr_torrentSetDirty( tor );
2082    tr_peerMgrRebuildRequests( tor );
2083
2084    tr_torrentUnlock( tor );
2085}
2086
2087tr_priority_t*
2088tr_torrentGetFilePriorities( const tr_torrent * tor )
2089{
2090    tr_file_index_t i;
2091    tr_priority_t * p;
2092
2093    assert( tr_isTorrent( tor ) );
2094
2095    tr_torrentLock( tor );
2096    p = tr_new0( tr_priority_t, tor->info.fileCount );
2097    for( i = 0; i < tor->info.fileCount; ++i )
2098        p[i] = tor->info.files[i].priority;
2099    tr_torrentUnlock( tor );
2100
2101    return p;
2102}
2103
2104/**
2105***  File DND
2106**/
2107
2108static void
2109setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
2110{
2111    const int8_t     dnd = !doDownload;
2112    tr_piece_index_t firstPiece;
2113    int8_t           firstPieceDND;
2114    tr_piece_index_t lastPiece;
2115    int8_t           lastPieceDND;
2116    tr_file_index_t  i;
2117    tr_file *        file = &tor->info.files[fileIndex];
2118
2119    file->dnd = dnd;
2120    firstPiece = file->firstPiece;
2121    lastPiece = file->lastPiece;
2122
2123    /* can't set the first piece to DND unless
2124       every file using that piece is DND */
2125    firstPieceDND = dnd;
2126    if( fileIndex > 0 )
2127    {
2128        for( i = fileIndex - 1; firstPieceDND; --i )
2129        {
2130            if( tor->info.files[i].lastPiece != firstPiece )
2131                break;
2132            firstPieceDND = tor->info.files[i].dnd;
2133            if( !i )
2134                break;
2135        }
2136    }
2137
2138    /* can't set the last piece to DND unless
2139       every file using that piece is DND */
2140    lastPieceDND = dnd;
2141    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
2142    {
2143        if( tor->info.files[i].firstPiece != lastPiece )
2144            break;
2145        lastPieceDND = tor->info.files[i].dnd;
2146    }
2147
2148    if( firstPiece == lastPiece )
2149    {
2150        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
2151    }
2152    else
2153    {
2154        tr_piece_index_t pp;
2155        tor->info.pieces[firstPiece].dnd = firstPieceDND;
2156        tor->info.pieces[lastPiece].dnd = lastPieceDND;
2157        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
2158            tor->info.pieces[pp].dnd = dnd;
2159    }
2160}
2161
2162void
2163tr_torrentInitFileDLs( tr_torrent             * tor,
2164                       const tr_file_index_t  * files,
2165                       tr_file_index_t          fileCount,
2166                       tr_bool                  doDownload )
2167{
2168    tr_file_index_t i;
2169
2170    assert( tr_isTorrent( tor ) );
2171
2172    tr_torrentLock( tor );
2173
2174    for( i=0; i<fileCount; ++i )
2175        if( files[i] < tor->info.fileCount )
2176            setFileDND( tor, files[i], doDownload );
2177
2178    tr_cpInvalidateDND( &tor->completion );
2179
2180    tr_torrentUnlock( tor );
2181}
2182
2183void
2184tr_torrentSetFileDLs( tr_torrent             * tor,
2185                      const tr_file_index_t  * files,
2186                      tr_file_index_t          fileCount,
2187                      tr_bool                  doDownload )
2188{
2189    assert( tr_isTorrent( tor ) );
2190    tr_torrentLock( tor );
2191
2192    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
2193    tr_torrentSetDirty( tor );
2194    tr_peerMgrRebuildRequests( tor );
2195
2196    tr_torrentUnlock( tor );
2197}
2198
2199/***
2200****
2201***/
2202
2203tr_priority_t
2204tr_torrentGetPriority( const tr_torrent * tor )
2205{
2206    assert( tr_isTorrent( tor ) );
2207
2208    return tor->bandwidth->priority;
2209}
2210
2211void
2212tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
2213{
2214    assert( tr_isTorrent( tor ) );
2215    assert( tr_isPriority( priority ) );
2216
2217    if( tor->bandwidth->priority != priority )
2218    {
2219        tor->bandwidth->priority = priority;
2220
2221        tr_torrentSetDirty( tor );
2222    }
2223}
2224
2225/***
2226****
2227***/
2228
2229void
2230tr_torrentSetPeerLimit( tr_torrent * tor,
2231                        uint16_t     maxConnectedPeers )
2232{
2233    assert( tr_isTorrent( tor ) );
2234
2235    if ( tor->maxConnectedPeers != maxConnectedPeers )
2236    {
2237        tor->maxConnectedPeers = maxConnectedPeers;
2238
2239        tr_torrentSetDirty( tor );
2240    }
2241}
2242
2243uint16_t
2244tr_torrentGetPeerLimit( const tr_torrent * tor )
2245{
2246    assert( tr_isTorrent( tor ) );
2247
2248    return tor->maxConnectedPeers;
2249}
2250
2251/***
2252****
2253***/
2254
2255void
2256tr_torrentGetBlockLocation( const tr_torrent * tor,
2257                            tr_block_index_t   block,
2258                            tr_piece_index_t * piece,
2259                            uint32_t         * offset,
2260                            uint32_t         * length )
2261{
2262    uint64_t pos = block;
2263    pos *= tor->blockSize;
2264    *piece = pos / tor->info.pieceSize;
2265    *offset = pos - ( *piece * tor->info.pieceSize );
2266    *length = tr_torBlockCountBytes( tor, block );
2267}
2268
2269
2270tr_block_index_t
2271_tr_block( const tr_torrent * tor,
2272           tr_piece_index_t   index,
2273           uint32_t           offset )
2274{
2275    tr_block_index_t ret;
2276
2277    assert( tr_isTorrent( tor ) );
2278
2279    ret = index;
2280    ret *= ( tor->info.pieceSize / tor->blockSize );
2281    ret += offset / tor->blockSize;
2282    return ret;
2283}
2284
2285tr_bool
2286tr_torrentReqIsValid( const tr_torrent * tor,
2287                      tr_piece_index_t   index,
2288                      uint32_t           offset,
2289                      uint32_t           length )
2290{
2291    int err = 0;
2292
2293    assert( tr_isTorrent( tor ) );
2294
2295    if( index >= tor->info.pieceCount )
2296        err = 1;
2297    else if( length < 1 )
2298        err = 2;
2299    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
2300        err = 3;
2301    else if( length > MAX_BLOCK_SIZE )
2302        err = 4;
2303    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
2304        err = 5;
2305
2306    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
2307                              (unsigned long)index,
2308                              (unsigned long)offset,
2309                              (unsigned long)length,
2310                              err );
2311
2312    return !err;
2313}
2314
2315uint64_t
2316tr_pieceOffset( const tr_torrent * tor,
2317                tr_piece_index_t   index,
2318                uint32_t           offset,
2319                uint32_t           length )
2320{
2321    uint64_t ret;
2322
2323    assert( tr_isTorrent( tor ) );
2324
2325    ret = tor->info.pieceSize;
2326    ret *= index;
2327    ret += offset;
2328    ret += length;
2329    return ret;
2330}
2331
2332void
2333tr_torGetFileBlockRange( const tr_torrent        * tor,
2334                         const tr_file_index_t     file,
2335                         tr_block_index_t        * first,
2336                         tr_block_index_t        * last )
2337{
2338    const tr_file * f = &tor->info.files[file];
2339    uint64_t offset = f->offset;
2340    *first = offset / tor->blockSize;
2341    if( !f->length )
2342        *last = *first;
2343    else {
2344        offset += f->length - 1;
2345        *last = offset / tor->blockSize;
2346    }
2347}
2348
2349void
2350tr_torGetPieceBlockRange( const tr_torrent        * tor,
2351                          const tr_piece_index_t    piece,
2352                          tr_block_index_t        * first,
2353                          tr_block_index_t        * last )
2354{
2355    uint64_t offset = tor->info.pieceSize;
2356    offset *= piece;
2357    *first = offset / tor->blockSize;
2358    offset += ( tr_torPieceCountBytes( tor, piece ) - 1 );
2359    *last = offset / tor->blockSize;
2360}
2361
2362
2363/***
2364****
2365***/
2366
2367void
2368tr_torrentSetPieceChecked( tr_torrent * tor, tr_piece_index_t pieceIndex )
2369{
2370    assert( tr_isTorrent( tor ) );
2371    assert( pieceIndex < tor->info.pieceCount );
2372
2373    tor->info.pieces[pieceIndex].timeChecked = tr_time( );
2374}
2375
2376void
2377tr_torrentSetChecked( tr_torrent * tor, time_t when )
2378{
2379    tr_piece_index_t i, n;
2380
2381    assert( tr_isTorrent( tor ) );
2382
2383    for( i=0, n=tor->info.pieceCount; i!=n; ++i )
2384        tor->info.pieces[i].timeChecked = when;
2385}
2386
2387tr_bool
2388tr_torrentCheckPiece( tr_torrent * tor, tr_piece_index_t pieceIndex )
2389{
2390    const tr_bool pass = tr_ioTestPiece( tor, pieceIndex );
2391
2392    tr_deeplog_tor( tor, "[LAZY] tr_torrentCheckPiece tested piece %zu, pass==%d", (size_t)pieceIndex, (int)pass );
2393    tr_torrentSetHasPiece( tor, pieceIndex, pass );
2394    tr_torrentSetPieceChecked( tor, pieceIndex );
2395    tor->anyDate = tr_time( );
2396    tr_torrentSetDirty( tor );
2397
2398    return pass;
2399}
2400
2401time_t
2402tr_torrentGetFileMTime( const tr_torrent * tor, tr_file_index_t i )
2403{
2404    struct stat sb;
2405    time_t mtime = 0;
2406    char * path = tr_torrentFindFile( tor, i );
2407
2408    if( ( path != NULL ) && !stat( path, &sb ) && S_ISREG( sb.st_mode ) )
2409    {
2410#ifdef SYS_DARWIN
2411        mtime = sb.st_mtimespec.tv_sec;
2412#else
2413        mtime = sb.st_mtime;
2414#endif
2415    }
2416
2417    tr_free( path );
2418    return mtime;
2419}
2420
2421tr_bool
2422tr_torrentPieceNeedsCheck( const tr_torrent * tor, tr_piece_index_t p )
2423{
2424    uint64_t unused;
2425    tr_file_index_t f;
2426    const tr_info * inf = tr_torrentInfo( tor );
2427
2428    /* if we've never checked this piece, then it needs to be checked */
2429    if( !inf->pieces[p].timeChecked )
2430        return TRUE;
2431
2432    /* If we think we've completed one of the files in this piece,
2433     * but it's been modified since we last checked it,
2434     * then it needs to be rechecked */
2435    tr_ioFindFileLocation( tor, p, 0, &f, &unused );
2436    for( ; f < inf->fileCount && pieceHasFile( p, &inf->files[f] ); ++f )
2437        if( tr_cpFileIsComplete( &tor->completion, f ) )
2438            if( tr_torrentGetFileMTime( tor, f ) > inf->pieces[p].timeChecked )
2439                return TRUE;
2440
2441    return FALSE;
2442}
2443
2444/***
2445****
2446***/
2447
2448static int
2449compareTrackerByTier( const void * va, const void * vb )
2450{
2451    const tr_tracker_info * a = va;
2452    const tr_tracker_info * b = vb;
2453
2454    /* sort by tier */
2455    if( a->tier != b->tier )
2456        return a->tier - b->tier;
2457
2458    /* get the effects of a stable sort by comparing the two elements' addresses */
2459    return a - b;
2460}
2461
2462tr_bool
2463tr_torrentSetAnnounceList( tr_torrent             * tor,
2464                           const tr_tracker_info  * trackers_in,
2465                           int                      trackerCount )
2466{
2467    int i;
2468    tr_benc metainfo;
2469    tr_bool ok = TRUE;
2470    tr_tracker_info * trackers;
2471
2472    tr_torrentLock( tor );
2473
2474    assert( tr_isTorrent( tor ) );
2475
2476    /* ensure the trackers' tiers are in ascending order */
2477    trackers = tr_memdup( trackers_in, sizeof( tr_tracker_info ) * trackerCount );
2478    qsort( trackers, trackerCount, sizeof( tr_tracker_info ), compareTrackerByTier );
2479
2480    /* look for bad URLs */
2481    for( i=0; ok && i<trackerCount; ++i )
2482        if( !tr_urlIsValidTracker( trackers[i].announce ) )
2483            ok = FALSE;
2484
2485    /* save to the .torrent file */
2486    if( ok && !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2487    {
2488        tr_bool hasInfo;
2489        tr_info tmpInfo;
2490
2491        /* remove the old fields */
2492        tr_bencDictRemove( &metainfo, "announce" );
2493        tr_bencDictRemove( &metainfo, "announce-list" );
2494
2495        /* add the new fields */
2496        if( trackerCount > 0 )
2497        {
2498            tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2499        }
2500        if( trackerCount > 1 )
2501        {
2502            int i;
2503            int prevTier = -1;
2504            tr_benc * tier = NULL;
2505            tr_benc * announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2506
2507            for( i=0; i<trackerCount; ++i ) {
2508                if( prevTier != trackers[i].tier ) {
2509                    prevTier = trackers[i].tier;
2510                    tier = tr_bencListAddList( announceList, 0 );
2511                }
2512                tr_bencListAddStr( tier, trackers[i].announce );
2513            }
2514        }
2515
2516        /* try to parse it back again, to make sure it's good */
2517        memset( &tmpInfo, 0, sizeof( tr_info ) );
2518        if( tr_metainfoParse( tor->session, &metainfo, &tmpInfo,
2519                              &hasInfo, &tor->infoDictLength ) )
2520        {
2521            /* it's good, so keep these new trackers and free the old ones */
2522
2523            tr_info swap;
2524            swap.trackers = tor->info.trackers;
2525            swap.trackerCount = tor->info.trackerCount;
2526            tor->info.trackers = tmpInfo.trackers;
2527            tor->info.trackerCount = tmpInfo.trackerCount;
2528            tmpInfo.trackers = swap.trackers;
2529            tmpInfo.trackerCount = swap.trackerCount;
2530
2531            tr_metainfoFree( &tmpInfo );
2532            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2533        }
2534
2535        /* cleanup */
2536        tr_bencFree( &metainfo );
2537
2538        /* if we had a tracker-related error on this torrent,
2539         * and that tracker's been removed,
2540         * then clear the error */
2541        if(    ( tor->error == TR_STAT_TRACKER_WARNING )
2542            || ( tor->error == TR_STAT_TRACKER_ERROR ) )
2543        {
2544            tr_bool clear = TRUE;
2545
2546            for( i=0; clear && i<trackerCount; ++i )
2547                if( !strcmp( trackers[i].announce, tor->errorTracker ) )
2548                    clear = FALSE;
2549
2550            if( clear )
2551                tr_torrentClearError( tor );
2552        }
2553
2554        /* tell the announcer to reload this torrent's tracker list */
2555        tr_announcerResetTorrent( tor->session->announcer, tor );
2556    }
2557
2558    tr_torrentUnlock( tor );
2559
2560    tr_free( trackers );
2561    return ok;
2562}
2563
2564/**
2565***
2566**/
2567
2568void
2569tr_torrentSetAddedDate( tr_torrent * tor,
2570                        time_t       t )
2571{
2572    assert( tr_isTorrent( tor ) );
2573
2574    tor->addedDate = t;
2575    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2576}
2577
2578void
2579tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2580{
2581    assert( tr_isTorrent( tor ) );
2582
2583    tor->activityDate = t;
2584    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2585}
2586
2587void
2588tr_torrentSetDoneDate( tr_torrent * tor,
2589                       time_t       t )
2590{
2591    assert( tr_isTorrent( tor ) );
2592
2593    tor->doneDate = t;
2594    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2595}
2596
2597/**
2598***
2599**/
2600
2601uint64_t
2602tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2603{
2604    tr_file_index_t i;
2605    uint64_t bytesLeft = 0;
2606
2607    assert( tr_isTorrent( tor ) );
2608
2609    for( i=0; i<tor->info.fileCount; ++i )
2610    {
2611        if( !tor->info.files[i].dnd )
2612        {
2613            struct stat sb;
2614            const uint64_t length = tor->info.files[i].length;
2615            char * path = tr_torrentFindFile( tor, i );
2616
2617            bytesLeft += length;
2618
2619            if( ( path != NULL ) && !stat( path, &sb )
2620                                 && S_ISREG( sb.st_mode )
2621                                 && ( (uint64_t)sb.st_size <= length ) )
2622                bytesLeft -= sb.st_size;
2623
2624            tr_free( path );
2625        }
2626    }
2627
2628    return bytesLeft;
2629}
2630
2631/****
2632*****  Removing the torrent's local data
2633****/
2634
2635static int
2636vstrcmp( const void * a, const void * b )
2637{
2638    return strcmp( a, b );
2639}
2640
2641static int
2642compareLongestFirst( const void * a, const void * b )
2643{
2644    const size_t alen = strlen( a );
2645    const size_t blen = strlen( b );
2646
2647    if( alen != blen )
2648        return alen > blen ? -1 : 1;
2649
2650    return vstrcmp( a, b );
2651}
2652
2653static void
2654addDirtyFile( const char  * root,
2655              const char  * filename,
2656              tr_ptrArray * dirtyFolders )
2657{
2658    char * dir = tr_dirname( filename );
2659
2660    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2661    while (     ( dir != NULL )
2662             && ( strlen( root ) <= strlen( dir ) )
2663             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2664    {
2665        char * tmp;
2666        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2667
2668        tmp = tr_dirname( dir );
2669        tr_free( dir );
2670        dir = tmp;
2671    }
2672
2673    tr_free( dir );
2674}
2675
2676static void
2677walkLocalData( const tr_torrent * tor,
2678               const char       * root,
2679               const char       * dir,
2680               const char       * base,
2681               tr_ptrArray      * torrentFiles,
2682               tr_ptrArray      * folders,
2683               tr_ptrArray      * dirtyFolders )
2684{
2685    struct stat sb;
2686    char * buf = tr_buildPath( dir, base, NULL );
2687    int i = stat( buf, &sb );
2688
2689    if( !i )
2690    {
2691        DIR * odir = NULL;
2692
2693        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2694        {
2695            struct dirent *d;
2696            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2697            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2698                if( d->d_name && strcmp( d->d_name, "." ) && strcmp( d->d_name, ".." ) )
2699                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2700            closedir( odir );
2701        }
2702        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2703        {
2704            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2705            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2706            if( !isTorrentFile )
2707                addDirtyFile( root, buf, dirtyFolders );
2708        }
2709    }
2710
2711    tr_free( buf );
2712}
2713
2714static void
2715deleteLocalFile( const char * filename, tr_fileFunc fileFunc )
2716{
2717    struct stat sb;
2718    if( !stat( filename, &sb ) ) /* if file exists... */
2719        fileFunc( filename );
2720}
2721
2722static void
2723deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2724{
2725    int i, n;
2726    char ** s;
2727    tr_file_index_t f;
2728    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2729    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2730    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2731
2732    const char * firstFile = tor->info.files[0].name;
2733    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2734    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2735    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2736
2737    for( f=0; f<tor->info.fileCount; ++f ) {
2738        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2739        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2740    }
2741
2742    /* build the set of folders and dirtyFolders */
2743    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2744
2745    /* try to remove entire folders first, so that the recycle bin will be tidy */
2746    s = (char**) tr_ptrArrayPeek( &folders, &n );
2747    for( i=0; i<n; ++i )
2748        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2749            deleteLocalFile( s[i], fileFunc );
2750
2751    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2752    for( i=0, n=tr_ptrArraySize( &torrentFiles ); i<n; ++i ) {
2753        char * path = tr_buildPath( tor->currentDir, tr_ptrArrayNth( &torrentFiles, i ), NULL );
2754        deleteLocalFile( path, fileFunc );
2755        tr_free( path );
2756    }
2757
2758    /* Now clean out the directories left empty from the previous step.
2759     * Work from deepest to shallowest s.t. lower folders
2760     * won't prevent the upper folders from being deleted */
2761    {
2762        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2763        s = (char**) tr_ptrArrayPeek( &folders, &n );
2764        for( i=0; i<n; ++i )
2765            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2766                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2767        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2768        for( i=0; i<n; ++i ) {
2769#ifdef SYS_DARWIN
2770            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2771            deleteLocalFile( dsStore, fileFunc );
2772            tr_free( dsStore );
2773#endif
2774            deleteLocalFile( s[i], fileFunc );
2775        }
2776        tr_ptrArrayDestruct( &cleanFolders, NULL );
2777    }
2778
2779    /* cleanup */
2780    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2781    tr_ptrArrayDestruct( &folders, tr_free );
2782    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2783    tr_free( root );
2784    tr_free( tmp );
2785}
2786
2787static void
2788tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2789{
2790    assert( tr_isTorrent( tor ) );
2791
2792    if( fileFunc == NULL )
2793        fileFunc = remove;
2794
2795    /* close all the files because we're about to delete them */
2796    tr_cacheFlushTorrent( tor->session->cache, tor );
2797    tr_fdTorrentClose( tor->session, tor->uniqueId );
2798
2799    if( tor->info.fileCount > 1 )
2800    {
2801        deleteLocalData( tor, fileFunc );
2802    }
2803    else if( tor->info.fileCount == 1 )
2804    {
2805        char * tmp;
2806
2807        /* torrent only has one file */
2808        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2809        deleteLocalFile( path, fileFunc );
2810        tr_free( path );
2811
2812        tmp = tr_torrentBuildPartial( tor, 0 );
2813        path = tr_buildPath( tor->currentDir, tmp, NULL );
2814        deleteLocalFile( path, fileFunc );
2815        tr_free( path );
2816        tr_free( tmp );
2817    }
2818}
2819
2820/***
2821****
2822***/
2823
2824struct LocationData
2825{
2826    tr_bool move_from_old_location;
2827    volatile int * setme_state;
2828    volatile double * setme_progress;
2829    char * location;
2830    tr_torrent * tor;
2831};
2832
2833static void
2834setLocation( void * vdata )
2835{
2836    tr_bool err = FALSE;
2837    struct LocationData * data = vdata;
2838    tr_torrent * tor = data->tor;
2839    const tr_bool do_move = data->move_from_old_location;
2840    const char * location = data->location;
2841    double bytesHandled = 0;
2842
2843    assert( tr_isTorrent( tor ) );
2844
2845    tr_dbg( "Moving \"%s\" location from currentDir \"%s\" to \"%s\"",
2846            tr_torrentName(tor), tor->currentDir, location );
2847
2848    tr_mkdirp( location, 0777 );
2849
2850    if( !tr_is_same_file( location, tor->currentDir ) )
2851    {
2852        tr_file_index_t i;
2853
2854        /* bad idea to move files while they're being verified... */
2855        tr_verifyRemove( tor );
2856
2857        /* try to move the files.
2858         * FIXME: there are still all kinds of nasty cases, like what
2859         * if the target directory runs out of space halfway through... */
2860        for( i=0; !err && i<tor->info.fileCount; ++i )
2861        {
2862            const tr_file * f = &tor->info.files[i];
2863            const char * oldbase;
2864            char * sub;
2865            if( tr_torrentFindFile2( tor, i, &oldbase, &sub ) )
2866            {
2867                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2868                char * newpath = tr_buildPath( location, sub, NULL );
2869
2870                tr_dbg( "Found file #%d: %s", (int)i, oldpath );
2871
2872                if( do_move && !tr_is_same_file( oldpath, newpath ) )
2873                {
2874                    tr_bool renamed = FALSE;
2875                    errno = 0;
2876                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2877                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2878                    {
2879                        err = TRUE;
2880                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2881                                        oldpath, newpath, tr_strerror( errno ) );
2882                    }
2883                }
2884
2885                tr_free( newpath );
2886                tr_free( oldpath );
2887                tr_free( sub );
2888            }
2889
2890            if( data->setme_progress )
2891            {
2892                bytesHandled += f->length;
2893                *data->setme_progress = bytesHandled / tor->info.totalSize;
2894            }
2895        }
2896
2897        if( !err )
2898        {
2899            /* blow away the leftover subdirectories in the old location */
2900            if( do_move )
2901                tr_torrentDeleteLocalData( tor, remove );
2902
2903            /* set the new location and reverify */
2904            tr_torrentSetDownloadDir( tor, location );
2905        }
2906    }
2907
2908    if( !err && do_move )
2909    {
2910        tr_free( tor->incompleteDir );
2911        tor->incompleteDir = NULL;
2912        tor->currentDir = tor->downloadDir;
2913    }
2914
2915    if( data->setme_state )
2916        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2917
2918    /* cleanup */
2919    tr_free( data->location );
2920    tr_free( data );
2921}
2922
2923void
2924tr_torrentSetLocation( tr_torrent       * tor,
2925                       const char       * location,
2926                       tr_bool             move_from_old_location,
2927                       volatile double  * setme_progress,
2928                       volatile int     * setme_state )
2929{
2930    struct LocationData * data;
2931
2932    assert( tr_isTorrent( tor ) );
2933
2934    if( setme_state )
2935        *setme_state = TR_LOC_MOVING;
2936    if( setme_progress )
2937        *setme_progress = 0;
2938
2939    /* run this in the libtransmission thread */
2940    data = tr_new( struct LocationData, 1 );
2941    data->tor = tor;
2942    data->location = tr_strdup( location );
2943    data->move_from_old_location = move_from_old_location;
2944    data->setme_state = setme_state;
2945    data->setme_progress = setme_progress;
2946    tr_runInEventThread( tor->session, setLocation, data );
2947}
2948
2949/***
2950****
2951***/
2952
2953void
2954tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2955{
2956    char * sub;
2957    const char * base;
2958    const tr_info * inf = &tor->info;
2959    const tr_file * f = &inf->files[fileNum];
2960    tr_piece * p;
2961    const tr_piece * pend;
2962    const time_t now = tr_time( );
2963
2964    /* close the file so that we can reopen in read-only mode as needed */
2965    tr_fdFileClose( tor->session, tor, fileNum );
2966
2967    /* now that the file is complete and closed, we can start watching its
2968     * mtime timestamp for changes to know if we need to reverify pieces */
2969    for( p=&inf->pieces[f->firstPiece], pend=&inf->pieces[f->lastPiece]; p!=pend; ++p )
2970        p->timeChecked = now;
2971
2972    /* if the torrent's current filename isn't the same as the one in the
2973     * metadata -- for example, if it had the ".part" suffix appended to
2974     * it until now -- then rename it to match the one in the metadata */
2975    if( tr_torrentFindFile2( tor, fileNum, &base, &sub ) )
2976    {
2977        if( strcmp( sub, f->name ) )
2978        {
2979            char * oldpath = tr_buildPath( base, sub, NULL );
2980            char * newpath = tr_buildPath( base, f->name, NULL );
2981
2982            if( rename( oldpath, newpath ) )
2983                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2984
2985            tr_free( newpath );
2986            tr_free( oldpath );
2987        }
2988
2989        tr_free( sub );
2990    }
2991}
2992
2993/***
2994****
2995***/
2996
2997static tr_bool
2998fileExists( const char * filename )
2999{
3000    struct stat sb;
3001    const tr_bool ok = !stat( filename, &sb );
3002    return ok;
3003}
3004
3005tr_bool
3006tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
3007                     const char ** base, char ** subpath )
3008{
3009    char * part;
3010    const tr_file * file;
3011    const char * b = NULL;
3012    const char * s = NULL;
3013
3014    assert( tr_isTorrent( tor ) );
3015    assert( fileNum < tor->info.fileCount );
3016
3017    file = &tor->info.files[fileNum];
3018    part = tr_torrentBuildPartial( tor, fileNum );
3019
3020    if( b == NULL ) {
3021        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
3022        if( fileExists( filename ) ) {
3023            b = tor->downloadDir;
3024            s = file->name;
3025        }
3026        tr_free( filename );
3027    }
3028
3029    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
3030        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
3031        if( fileExists( filename ) ) {
3032            b = tor->incompleteDir;
3033            s = file->name;
3034        }
3035        tr_free( filename );
3036    }
3037
3038    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
3039        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
3040        if( fileExists( filename ) ) {
3041            b = tor->incompleteDir;
3042            s = part;
3043        }
3044        tr_free( filename );
3045    }
3046
3047    if( b == NULL) {
3048        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
3049        if( fileExists( filename ) ) {
3050            b = tor->downloadDir;
3051            s = part;
3052        }
3053        tr_free( filename );
3054    }
3055
3056    if( base != NULL )
3057        *base = b;
3058    if( subpath != NULL )
3059        *subpath = tr_strdup( s );
3060
3061    tr_free( part );
3062    return b != NULL;
3063}
3064
3065char*
3066tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
3067{
3068    char * subpath;
3069    char * ret = NULL;
3070    const char * base;
3071
3072    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath ) )
3073    {
3074        ret = tr_buildPath( base, subpath, NULL );
3075        tr_free( subpath );
3076    }
3077
3078    return ret;
3079}
3080
3081/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
3082static void
3083refreshCurrentDir( tr_torrent * tor )
3084{
3085    const char * dir = NULL;
3086
3087    if( tor->incompleteDir == NULL )
3088        dir = tor->downloadDir;
3089    else if( !tr_torrentHasMetadata( tor ) ) /* no files to find */
3090        dir = tor->incompleteDir;
3091    else if( !tr_torrentFindFile2( tor, 0, &dir, NULL ) )
3092        dir = tor->incompleteDir;
3093
3094    assert( dir != NULL );
3095    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
3096    tor->currentDir = dir;
3097}
3098
3099char*
3100tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
3101{
3102    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
3103}
Note: See TracBrowser for help on using the repository browser.