source: trunk/libtransmission/torrent.c @ 11536

Last change on this file since 11536 was 11536, checked in by charles, 11 years ago

(trunk libT) #3764 "script-torrent-done shouldn't block libtransmission" -- handle zombie processes.

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