source: trunk/libtransmission/torrent.c @ 11570

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

(trunk libt) experimental fix for the updated torrent issue reported by Lacrocivious

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