source: trunk/libtransmission/torrent.c @ 11565

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

(trunk libT) remove some of the lazy-verify debug messages.

  • Property svn:keywords set to Date Rev Author Id
File size: 80.9 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 11565 2010-12-21 23:09:26Z 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    /* otherwise, start it now... */
1596    tr_sessionLock( tor->session );
1597
1598    /* allow finished torrents to be resumed */
1599    if( tr_torrentIsSeedRatioDone( tor ) ) {
1600        tr_torinf( tor, _( "Restarted manually -- disabling its seed ratio" ) );
1601        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
1602    }
1603
1604    tr_verifyRemove( tor );
1605
1606    /* corresponds to the peer_id sent as a tracker request parameter.
1607     * one tracker admin says: "When the same torrent is opened and
1608     * closed and opened again without quitting Transmission ...
1609     * change the peerid. It would help sometimes if a stopped event
1610     * was missed to ensure that we didn't think someone was cheating. */
1611    tr_free( tor->peer_id );
1612    tor->peer_id = tr_peerIdNew( );
1613    tor->isRunning = 1;
1614    tr_torrentSetDirty( tor );
1615    tr_runInEventThread( tor->session, torrentStartImpl, tor );
1616
1617    tr_sessionUnlock( tor->session );
1618}
1619
1620void
1621tr_torrentStart( tr_torrent * tor )
1622{
1623    if( tr_isTorrent( tor ) )
1624        torrentStart( tor );
1625}
1626
1627static void
1628torrentRecheckDoneImpl( void * vtor )
1629{
1630    tr_torrent * tor = vtor;
1631    assert( tr_isTorrent( tor ) );
1632
1633    tr_torrentRecheckCompleteness( tor );
1634
1635    if( tor->startAfterVerify ) {
1636        tor->startAfterVerify = FALSE;
1637        torrentStart( tor );
1638    }
1639}
1640
1641static void
1642torrentRecheckDoneCB( tr_torrent * tor )
1643{
1644    assert( tr_isTorrent( tor ) );
1645
1646    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1647}
1648
1649static void
1650verifyTorrent( void * vtor )
1651{
1652    tr_torrent * tor = vtor;
1653
1654    assert( tr_isTorrent( tor ) );
1655    tr_sessionLock( tor->session );
1656
1657    /* if the torrent's already being verified, stop it */
1658    tr_verifyRemove( tor );
1659
1660    /* if the torrent's running, stop it & set the restart-after-verify flag */
1661    if( tor->startAfterVerify || tor->isRunning ) {
1662        /* don't clobber isStopping */
1663        const tr_bool startAfter = tor->isStopping ? FALSE : TRUE;
1664        tr_torrentStop( tor );
1665        tor->startAfterVerify = startAfter;
1666    }
1667
1668    if( setLocalErrorIfFilesDisappeared( tor ) )
1669        tor->startAfterVerify = FALSE;
1670    else
1671        tr_verifyAdd( tor, torrentRecheckDoneCB );
1672
1673    tr_sessionUnlock( tor->session );
1674}
1675
1676void
1677tr_torrentVerify( tr_torrent * tor )
1678{
1679    if( tr_isTorrent( tor ) )
1680        tr_runInEventThread( tor->session, verifyTorrent, tor );
1681}
1682
1683void
1684tr_torrentSave( tr_torrent * tor )
1685{
1686    assert( tr_isTorrent( tor ) );
1687
1688    if( tor->isDirty )
1689    {
1690        tor->isDirty = FALSE;
1691        tr_torrentSaveResume( tor );
1692    }
1693}
1694
1695static void
1696stopTorrent( void * vtor )
1697{
1698    tr_torrent * tor = vtor;
1699    tr_torinf( tor, "Pausing" );
1700
1701    assert( tr_isTorrent( tor ) );
1702
1703    tr_verifyRemove( tor );
1704    tr_peerMgrStopTorrent( tor );
1705    tr_announcerTorrentStopped( tor );
1706    tr_cacheFlushTorrent( tor->session->cache, tor );
1707
1708    tr_fdTorrentClose( tor->session, tor->uniqueId );
1709
1710    if( !tor->isDeleting )
1711        tr_torrentSave( tor );
1712}
1713
1714void
1715tr_torrentStop( tr_torrent * tor )
1716{
1717    assert( tr_isTorrent( tor ) );
1718
1719    if( tr_isTorrent( tor ) )
1720    {
1721        tr_sessionLock( tor->session );
1722
1723        tor->isRunning = 0;
1724        tor->isStopping = 0;
1725        tr_torrentSetDirty( tor );
1726        tr_runInEventThread( tor->session, stopTorrent, tor );
1727
1728        tr_sessionUnlock( tor->session );
1729    }
1730}
1731
1732static void
1733closeTorrent( void * vtor )
1734{
1735    tr_benc * d;
1736    tr_torrent * tor = vtor;
1737
1738    assert( tr_isTorrent( tor ) );
1739
1740    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1741    tr_bencDictAddInt( d, "id", tor->uniqueId );
1742    tr_bencDictAddInt( d, "date", tr_time( ) );
1743
1744    tr_torinf( tor, "%s", _( "Removing torrent" ) );
1745
1746    stopTorrent( tor );
1747
1748    if( tor->isDeleting )
1749    {
1750        tr_metainfoRemoveSaved( tor->session, &tor->info );
1751        tr_torrentRemoveResume( tor );
1752    }
1753
1754    tor->isRunning = 0;
1755    freeTorrent( tor );
1756}
1757
1758void
1759tr_torrentFree( tr_torrent * tor )
1760{
1761    if( tr_isTorrent( tor ) )
1762    {
1763        tr_session * session = tor->session;
1764        assert( tr_isSession( session ) );
1765        tr_sessionLock( session );
1766
1767        tr_torrentClearCompletenessCallback( tor );
1768        tr_runInEventThread( session, closeTorrent, tor );
1769
1770        tr_sessionUnlock( session );
1771    }
1772}
1773
1774struct remove_data
1775{
1776    tr_torrent   * tor;
1777    tr_bool        deleteFlag;
1778    tr_fileFunc  * deleteFunc;
1779};
1780
1781static void tr_torrentDeleteLocalData( tr_torrent *, tr_fileFunc );
1782
1783static void
1784removeTorrent( void * vdata )
1785{
1786    struct remove_data * data = vdata;
1787
1788    if( data->deleteFlag )
1789        tr_torrentDeleteLocalData( data->tor, data->deleteFunc );
1790
1791    tr_torrentClearCompletenessCallback( data->tor );
1792    closeTorrent( data->tor );
1793    tr_free( data );
1794}
1795
1796void
1797tr_torrentRemove( tr_torrent   * tor,
1798                  tr_bool        deleteFlag, 
1799                  tr_fileFunc    deleteFunc )
1800{
1801    struct remove_data * data;
1802
1803    assert( tr_isTorrent( tor ) );
1804    tor->isDeleting = 1;
1805
1806    data = tr_new0( struct remove_data, 1 );
1807    data->tor = tor;
1808    data->deleteFlag = deleteFlag;
1809    data->deleteFunc = deleteFunc;
1810    tr_runInEventThread( tor->session, removeTorrent, data );
1811}
1812
1813/**
1814***  Completeness
1815**/
1816
1817static const char *
1818getCompletionString( int type )
1819{
1820    switch( type )
1821    {
1822        /* Translators: this is a minor point that's safe to skip over, but FYI:
1823           "Complete" and "Done" are specific, different terms in Transmission:
1824           "Complete" means we've downloaded every file in the torrent.
1825           "Done" means we're done downloading the files we wanted, but NOT all
1826           that exist */
1827        case TR_PARTIAL_SEED:
1828            return _( "Done" );
1829
1830        case TR_SEED:
1831            return _( "Complete" );
1832
1833        default:
1834            return _( "Incomplete" );
1835    }
1836}
1837
1838static void
1839fireCompletenessChange( tr_torrent       * tor,
1840                        tr_completeness    status,
1841                        tr_bool            wasRunning )
1842{
1843    assert( tr_isTorrent( tor ) );
1844    assert( ( status == TR_LEECH )
1845         || ( status == TR_SEED )
1846         || ( status == TR_PARTIAL_SEED ) );
1847
1848    if( tor->completeness_func )
1849        tor->completeness_func( tor, status, wasRunning,
1850                                tor->completeness_func_user_data );
1851}
1852
1853void
1854tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1855                                   tr_torrent_completeness_func    func,
1856                                   void                          * user_data )
1857{
1858    assert( tr_isTorrent( tor ) );
1859
1860    tor->completeness_func = func;
1861    tor->completeness_func_user_data = user_data;
1862}
1863
1864void
1865tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1866{
1867    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1868}
1869
1870void
1871tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1872                                    tr_torrent_ratio_limit_hit_func  func,
1873                                    void                           * user_data )
1874{
1875    assert( tr_isTorrent( tor ) );
1876
1877    tor->ratio_limit_hit_func = func;
1878    tor->ratio_limit_hit_func_user_data = user_data;
1879}
1880
1881void
1882tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1883{
1884    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1885}
1886
1887void
1888tr_torrentSetIdleLimitHitCallback( tr_torrent                    * tor,
1889                                   tr_torrent_idle_limit_hit_func  func,
1890                                   void                          * user_data )
1891{
1892    assert( tr_isTorrent( tor ) );
1893
1894    tor->idle_limit_hit_func = func;
1895    tor->idle_limit_hit_func_user_data = user_data;
1896}
1897
1898void
1899tr_torrentClearIdleLimitHitCallback( tr_torrent * torrent )
1900{
1901    tr_torrentSetIdleLimitHitCallback( torrent, NULL, NULL );
1902}
1903
1904static void
1905onSigCHLD( int i UNUSED )
1906{
1907    waitpid( -1, 0, WNOHANG );
1908}
1909
1910static void
1911torrentCallScript( const tr_torrent * tor, const char * script )
1912{
1913    char timeStr[128];
1914    const time_t now = tr_time( );
1915
1916    assert( tr_isTorrent( tor ) );
1917
1918    tr_strlcpy( timeStr, ctime( &now ), sizeof( timeStr ) );
1919    *strchr( timeStr,'\n' ) = '\0';
1920
1921    if( script && *script )
1922    {
1923        char * cmd[] = { tr_strdup( script ), NULL };
1924        char * env[] = {
1925            tr_strdup_printf( "TR_APP_VERSION=%s", SHORT_VERSION_STRING ),
1926            tr_strdup_printf( "TR_TIME_LOCALTIME=%s", timeStr ),
1927            tr_strdup_printf( "TR_TORRENT_DIR=%s", tor->currentDir ),
1928            tr_strdup_printf( "TR_TORRENT_ID=%d", tr_torrentId( tor ) ),
1929            tr_strdup_printf( "TR_TORRENT_HASH=%s", tor->info.hashString ),
1930            tr_strdup_printf( "TR_TORRENT_NAME=%s", tr_torrentName( tor ) ),
1931            NULL };
1932
1933        tr_torinf( tor, "Calling script \"%s\"", script ); 
1934        signal( SIGCHLD, onSigCHLD );
1935
1936        if( !fork( ) )
1937        {
1938            execve( script, cmd, env );
1939            _exit( 0 );
1940        }
1941    }
1942}
1943
1944void
1945tr_torrentRecheckCompleteness( tr_torrent * tor )
1946{
1947    tr_completeness completeness;
1948
1949    assert( tr_isTorrent( tor ) );
1950
1951    tr_torrentLock( tor );
1952
1953    completeness = tr_cpGetStatus( &tor->completion );
1954
1955    if( completeness != tor->completeness )
1956    {
1957        const int recentChange = tor->downloadedCur != 0;
1958        const tr_bool wasLeeching = !tr_torrentIsSeed( tor );
1959        const tr_bool wasRunning = tor->isRunning;
1960
1961        if( recentChange )
1962        {
1963            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1964                      getCompletionString( tor->completeness ),
1965                      getCompletionString( completeness ) );
1966        }
1967
1968        tor->completeness = completeness;
1969        tr_fdTorrentClose( tor->session, tor->uniqueId );
1970
1971        if( tr_torrentIsSeed( tor ) )
1972        {
1973            if( recentChange )
1974            {
1975                tr_announcerTorrentCompleted( tor );
1976                tor->doneDate = tor->anyDate = tr_time( );
1977            }
1978
1979            if( wasLeeching && wasRunning )
1980            {
1981                /* clear interested flag on all peers */
1982                tr_peerMgrClearInterest( tor );
1983
1984                /* if completeness was TR_LEECH then the seed limit check will have been skipped in bandwidthPulse */
1985                tr_torrentCheckSeedLimit( tor );
1986            }
1987
1988            if( tor->currentDir == tor->incompleteDir )
1989                tr_torrentSetLocation( tor, tor->downloadDir, TRUE, NULL, NULL );
1990
1991            if( tr_sessionIsTorrentDoneScriptEnabled( tor->session ) )
1992                torrentCallScript( tor, tr_sessionGetTorrentDoneScript( tor->session ) );
1993        }
1994
1995        fireCompletenessChange( tor, wasRunning, completeness );
1996
1997        tr_torrentSetDirty( tor );
1998    }
1999
2000    tr_torrentUnlock( tor );
2001}
2002
2003/***
2004****
2005***/
2006
2007static void
2008tr_torrentFireMetadataCompleted( tr_torrent * tor )
2009{
2010    assert( tr_isTorrent( tor ) );
2011
2012    if( tor->metadata_func )
2013        tor->metadata_func( tor, tor->metadata_func_user_data );
2014}
2015
2016void
2017tr_torrentSetMetadataCallback( tr_torrent                * tor,
2018                               tr_torrent_metadata_func    func,
2019                               void                      * user_data )
2020{
2021    assert( tr_isTorrent( tor ) );
2022
2023    tor->metadata_func = func;
2024    tor->metadata_func_user_data = user_data;
2025}
2026
2027
2028/**
2029***  File priorities
2030**/
2031
2032void
2033tr_torrentInitFilePriority( tr_torrent *    tor,
2034                            tr_file_index_t fileIndex,
2035                            tr_priority_t   priority )
2036{
2037    tr_piece_index_t i;
2038    tr_file *        file;
2039
2040    assert( tr_isTorrent( tor ) );
2041    assert( fileIndex < tor->info.fileCount );
2042    assert( tr_isPriority( priority ) );
2043
2044    file = &tor->info.files[fileIndex];
2045    file->priority = priority;
2046    for( i = file->firstPiece; i <= file->lastPiece; ++i )
2047        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
2048}
2049
2050void
2051tr_torrentSetFilePriorities( tr_torrent             * tor,
2052                             const tr_file_index_t  * files,
2053                             tr_file_index_t          fileCount,
2054                             tr_priority_t            priority )
2055{
2056    tr_file_index_t i;
2057    assert( tr_isTorrent( tor ) );
2058    tr_torrentLock( tor );
2059
2060    for( i = 0; i < fileCount; ++i )
2061        if( files[i] < tor->info.fileCount )
2062            tr_torrentInitFilePriority( tor, files[i], priority );
2063    tr_torrentSetDirty( tor );
2064    tr_peerMgrRebuildRequests( tor );
2065
2066    tr_torrentUnlock( tor );
2067}
2068
2069tr_priority_t*
2070tr_torrentGetFilePriorities( const tr_torrent * tor )
2071{
2072    tr_file_index_t i;
2073    tr_priority_t * p;
2074
2075    assert( tr_isTorrent( tor ) );
2076
2077    tr_torrentLock( tor );
2078    p = tr_new0( tr_priority_t, tor->info.fileCount );
2079    for( i = 0; i < tor->info.fileCount; ++i )
2080        p[i] = tor->info.files[i].priority;
2081    tr_torrentUnlock( tor );
2082
2083    return p;
2084}
2085
2086/**
2087***  File DND
2088**/
2089
2090static void
2091setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
2092{
2093    tr_file *        file;
2094    const int8_t     dnd = !doDownload;
2095    tr_piece_index_t firstPiece;
2096    int8_t           firstPieceDND;
2097    tr_piece_index_t lastPiece;
2098    int8_t           lastPieceDND;
2099    tr_file_index_t  i;
2100
2101    assert( tr_isTorrent( tor ) );
2102
2103    file = &tor->info.files[fileIndex];
2104    file->dnd = dnd;
2105    firstPiece = file->firstPiece;
2106    lastPiece = file->lastPiece;
2107
2108    /* can't set the first piece to DND unless
2109       every file using that piece is DND */
2110    firstPieceDND = dnd;
2111    if( fileIndex > 0 )
2112    {
2113        for( i = fileIndex - 1; firstPieceDND; --i )
2114        {
2115            if( tor->info.files[i].lastPiece != firstPiece )
2116                break;
2117            firstPieceDND = tor->info.files[i].dnd;
2118            if( !i )
2119                break;
2120        }
2121    }
2122
2123    /* can't set the last piece to DND unless
2124       every file using that piece is DND */
2125    lastPieceDND = dnd;
2126    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
2127    {
2128        if( tor->info.files[i].firstPiece != lastPiece )
2129            break;
2130        lastPieceDND = tor->info.files[i].dnd;
2131    }
2132
2133    if( firstPiece == lastPiece )
2134    {
2135        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
2136    }
2137    else
2138    {
2139        tr_piece_index_t pp;
2140        tor->info.pieces[firstPiece].dnd = firstPieceDND;
2141        tor->info.pieces[lastPiece].dnd = lastPieceDND;
2142        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
2143            tor->info.pieces[pp].dnd = dnd;
2144    }
2145}
2146
2147void
2148tr_torrentInitFileDLs( tr_torrent             * tor,
2149                       const tr_file_index_t  * files,
2150                       tr_file_index_t          fileCount,
2151                       tr_bool                  doDownload )
2152{
2153    tr_file_index_t i;
2154
2155    assert( tr_isTorrent( tor ) );
2156
2157    tr_torrentLock( tor );
2158
2159    for( i=0; i<fileCount; ++i )
2160        if( files[i] < tor->info.fileCount )
2161            setFileDND( tor, files[i], doDownload );
2162
2163    tr_cpInvalidateDND( &tor->completion );
2164
2165    tr_torrentUnlock( tor );
2166}
2167
2168void
2169tr_torrentSetFileDLs( tr_torrent             * tor,
2170                      const tr_file_index_t  * files,
2171                      tr_file_index_t          fileCount,
2172                      tr_bool                  doDownload )
2173{
2174    assert( tr_isTorrent( tor ) );
2175    tr_torrentLock( tor );
2176
2177    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
2178    tr_torrentSetDirty( tor );
2179    tr_peerMgrRebuildRequests( tor );
2180
2181    tr_torrentUnlock( tor );
2182}
2183
2184/***
2185****
2186***/
2187
2188tr_priority_t
2189tr_torrentGetPriority( const tr_torrent * tor )
2190{
2191    assert( tr_isTorrent( tor ) );
2192
2193    return tor->bandwidth->priority;
2194}
2195
2196void
2197tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
2198{
2199    assert( tr_isTorrent( tor ) );
2200    assert( tr_isPriority( priority ) );
2201
2202    if( tor->bandwidth->priority != priority )
2203    {
2204        tor->bandwidth->priority = priority;
2205
2206        tr_torrentSetDirty( tor );
2207    }
2208}
2209
2210/***
2211****
2212***/
2213
2214void
2215tr_torrentSetPeerLimit( tr_torrent * tor,
2216                        uint16_t     maxConnectedPeers )
2217{
2218    assert( tr_isTorrent( tor ) );
2219
2220    if ( tor->maxConnectedPeers != maxConnectedPeers )
2221    {
2222        tor->maxConnectedPeers = maxConnectedPeers;
2223
2224        tr_torrentSetDirty( tor );
2225    }
2226}
2227
2228uint16_t
2229tr_torrentGetPeerLimit( const tr_torrent * tor )
2230{
2231    assert( tr_isTorrent( tor ) );
2232
2233    return tor->maxConnectedPeers;
2234}
2235
2236/***
2237****
2238***/
2239
2240tr_block_index_t
2241_tr_block( const tr_torrent * tor,
2242           tr_piece_index_t   index,
2243           uint32_t           offset )
2244{
2245    tr_block_index_t ret;
2246
2247    assert( tr_isTorrent( tor ) );
2248
2249    ret = index;
2250    ret *= ( tor->info.pieceSize / tor->blockSize );
2251    ret += offset / tor->blockSize;
2252    return ret;
2253}
2254
2255tr_bool
2256tr_torrentReqIsValid( const tr_torrent * tor,
2257                      tr_piece_index_t   index,
2258                      uint32_t           offset,
2259                      uint32_t           length )
2260{
2261    int err = 0;
2262
2263    assert( tr_isTorrent( tor ) );
2264
2265    if( index >= tor->info.pieceCount )
2266        err = 1;
2267    else if( length < 1 )
2268        err = 2;
2269    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
2270        err = 3;
2271    else if( length > MAX_BLOCK_SIZE )
2272        err = 4;
2273    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
2274        err = 5;
2275
2276    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
2277                              (unsigned long)index,
2278                              (unsigned long)offset,
2279                              (unsigned long)length,
2280                              err );
2281
2282    return !err;
2283}
2284
2285uint64_t
2286tr_pieceOffset( const tr_torrent * tor,
2287                tr_piece_index_t   index,
2288                uint32_t           offset,
2289                uint32_t           length )
2290{
2291    uint64_t ret;
2292
2293    assert( tr_isTorrent( tor ) );
2294
2295    ret = tor->info.pieceSize;
2296    ret *= index;
2297    ret += offset;
2298    ret += length;
2299    return ret;
2300}
2301
2302/***
2303****
2304***/
2305
2306void
2307tr_torrentSetPieceChecked( tr_torrent * tor, tr_piece_index_t pieceIndex )
2308{
2309    assert( tr_isTorrent( tor ) );
2310    assert( pieceIndex < tor->info.pieceCount );
2311
2312    tr_tordbg( tor, "[LAZY] setting piece %zu timeChecked to now", (size_t)pieceIndex );
2313    tor->info.pieces[pieceIndex].timeChecked = tr_time( );
2314}
2315
2316void
2317tr_torrentSetChecked( tr_torrent * tor, time_t when )
2318{
2319    tr_piece_index_t i, n;
2320
2321    assert( tr_isTorrent( tor ) );
2322
2323    for( i=0, n=tor->info.pieceCount; i!=n; ++i )
2324        tor->info.pieces[i].timeChecked = when;
2325}
2326
2327tr_bool
2328tr_torrentCheckPiece( tr_torrent * tor, tr_piece_index_t pieceIndex )
2329{
2330    const tr_bool pass = tr_ioTestPiece( tor, pieceIndex );
2331
2332    tr_tordbg( tor, "[LAZY] tr_torrentCheckPiece tested piece %zu, pass==%d", (size_t)pieceIndex, (int)pass );
2333    tr_torrentSetHasPiece( tor, pieceIndex, pass );
2334    tr_torrentSetPieceChecked( tor, pieceIndex );
2335    tor->anyDate = tr_time( );
2336    tr_torrentSetDirty( tor );
2337
2338    return pass;
2339}
2340
2341static time_t
2342getFileMTime( const tr_torrent * tor, tr_file_index_t i )
2343{
2344    struct stat sb;
2345    time_t mtime = 0;
2346    char * path = tr_torrentFindFile( tor, i );
2347
2348    if( ( path != NULL ) && !stat( path, &sb ) && S_ISREG( sb.st_mode ) )
2349    {
2350#ifdef SYS_DARWIN
2351        mtime = sb.st_mtimespec.tv_sec;
2352#else
2353        mtime = sb.st_mtime;
2354#endif
2355    }
2356
2357    tr_free( path );
2358    return mtime;
2359}
2360
2361tr_bool
2362tr_torrentPieceNeedsCheck( const tr_torrent * tor, tr_piece_index_t p )
2363{
2364    uint64_t unused;
2365    tr_file_index_t f;
2366    const tr_info * inf = tr_torrentInfo( tor );
2367
2368    /* if we've never checked this piece, then it needs to be checked */
2369    if( !inf->pieces[p].timeChecked )
2370        return TRUE;
2371
2372    /* If we think we've completed one of the files in this piece,
2373     * but it's been modified since we last checked it,
2374     * then it needs to be rechecked */
2375    tr_ioFindFileLocation( tor, p, 0, &f, &unused );
2376    for( ; f < inf->fileCount && pieceHasFile( p, &inf->files[f] ); ++f )
2377        if( tr_cpFileIsComplete( &tor->completion, f ) )
2378            if( getFileMTime( tor, f ) > inf->pieces[p].timeChecked )
2379                return TRUE;
2380
2381    return FALSE;
2382}
2383
2384/***
2385****
2386***/
2387
2388static int
2389compareTrackerByTier( const void * va, const void * vb )
2390{
2391    const tr_tracker_info * a = va;
2392    const tr_tracker_info * b = vb;
2393
2394    /* sort by tier */
2395    if( a->tier != b->tier )
2396        return a->tier - b->tier;
2397
2398    /* get the effects of a stable sort by comparing the two elements' addresses */
2399    return a - b;
2400}
2401
2402tr_bool
2403tr_torrentSetAnnounceList( tr_torrent             * tor,
2404                           const tr_tracker_info  * trackers_in,
2405                           int                      trackerCount )
2406{
2407    int i;
2408    tr_benc metainfo;
2409    tr_bool ok = TRUE;
2410    tr_tracker_info * trackers;
2411
2412    tr_torrentLock( tor );
2413
2414    assert( tr_isTorrent( tor ) );
2415
2416    /* ensure the trackers' tiers are in ascending order */
2417    trackers = tr_memdup( trackers_in, sizeof( tr_tracker_info ) * trackerCount );
2418    qsort( trackers, trackerCount, sizeof( tr_tracker_info ), compareTrackerByTier );
2419
2420    /* look for bad URLs */
2421    for( i=0; ok && i<trackerCount; ++i )
2422        if( !tr_urlIsValidTracker( trackers[i].announce ) )
2423            ok = FALSE;
2424
2425    /* save to the .torrent file */
2426    if( ok && !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2427    {
2428        tr_bool hasInfo;
2429        tr_info tmpInfo;
2430
2431        /* remove the old fields */
2432        tr_bencDictRemove( &metainfo, "announce" );
2433        tr_bencDictRemove( &metainfo, "announce-list" );
2434
2435        /* add the new fields */
2436        if( trackerCount > 0 )
2437        {
2438            tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2439        }
2440        if( trackerCount > 1 )
2441        {
2442            int i;
2443            int prevTier = -1;
2444            tr_benc * tier = NULL;
2445            tr_benc * announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2446
2447            for( i=0; i<trackerCount; ++i ) {
2448                if( prevTier != trackers[i].tier ) {
2449                    prevTier = trackers[i].tier;
2450                    tier = tr_bencListAddList( announceList, 0 );
2451                }
2452                tr_bencListAddStr( tier, trackers[i].announce );
2453            }
2454        }
2455
2456        /* try to parse it back again, to make sure it's good */
2457        memset( &tmpInfo, 0, sizeof( tr_info ) );
2458        if( tr_metainfoParse( tor->session, &metainfo, &tmpInfo,
2459                              &hasInfo, &tor->infoDictLength ) )
2460        {
2461            /* it's good, so keep these new trackers and free the old ones */
2462
2463            tr_info swap;
2464            swap.trackers = tor->info.trackers;
2465            swap.trackerCount = tor->info.trackerCount;
2466            tor->info.trackers = tmpInfo.trackers;
2467            tor->info.trackerCount = tmpInfo.trackerCount;
2468            tmpInfo.trackers = swap.trackers;
2469            tmpInfo.trackerCount = swap.trackerCount;
2470
2471            tr_metainfoFree( &tmpInfo );
2472            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2473        }
2474
2475        /* cleanup */
2476        tr_bencFree( &metainfo );
2477
2478        /* if we had a tracker-related error on this torrent,
2479         * and that tracker's been removed,
2480         * then clear the error */
2481        if(    ( tor->error == TR_STAT_TRACKER_WARNING )
2482            || ( tor->error == TR_STAT_TRACKER_ERROR ) )
2483        {
2484            tr_bool clear = TRUE;
2485
2486            for( i=0; clear && i<trackerCount; ++i )
2487                if( !strcmp( trackers[i].announce, tor->errorTracker ) )
2488                    clear = FALSE;
2489
2490            if( clear )
2491                tr_torrentClearError( tor );
2492        }
2493
2494        /* tell the announcer to reload this torrent's tracker list */
2495        tr_announcerResetTorrent( tor->session->announcer, tor );
2496    }
2497
2498    tr_torrentUnlock( tor );
2499
2500    tr_free( trackers );
2501    return ok;
2502}
2503
2504/**
2505***
2506**/
2507
2508void
2509tr_torrentSetAddedDate( tr_torrent * tor,
2510                        time_t       t )
2511{
2512    assert( tr_isTorrent( tor ) );
2513
2514    tor->addedDate = t;
2515    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2516}
2517
2518void
2519tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2520{
2521    assert( tr_isTorrent( tor ) );
2522
2523    tor->activityDate = t;
2524    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2525}
2526
2527void
2528tr_torrentSetDoneDate( tr_torrent * tor,
2529                       time_t       t )
2530{
2531    assert( tr_isTorrent( tor ) );
2532
2533    tor->doneDate = t;
2534    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2535}
2536
2537/**
2538***
2539**/
2540
2541uint64_t
2542tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2543{
2544    tr_file_index_t i;
2545    uint64_t bytesLeft = 0;
2546
2547    assert( tr_isTorrent( tor ) );
2548
2549    for( i=0; i<tor->info.fileCount; ++i )
2550    {
2551        if( !tor->info.files[i].dnd )
2552        {
2553            struct stat sb;
2554            const uint64_t length = tor->info.files[i].length;
2555            char * path = tr_torrentFindFile( tor, i );
2556
2557            bytesLeft += length;
2558
2559            if( ( path != NULL ) && !stat( path, &sb )
2560                                 && S_ISREG( sb.st_mode )
2561                                 && ( (uint64_t)sb.st_size <= length ) )
2562                bytesLeft -= sb.st_size;
2563
2564            tr_free( path );
2565        }
2566    }
2567
2568    return bytesLeft;
2569}
2570
2571/****
2572*****  Removing the torrent's local data
2573****/
2574
2575static int
2576vstrcmp( const void * a, const void * b )
2577{
2578    return strcmp( a, b );
2579}
2580
2581static int
2582compareLongestFirst( const void * a, const void * b )
2583{
2584    const size_t alen = strlen( a );
2585    const size_t blen = strlen( b );
2586
2587    if( alen != blen )
2588        return alen > blen ? -1 : 1;
2589
2590    return vstrcmp( a, b );
2591}
2592
2593static void
2594addDirtyFile( const char  * root,
2595              const char  * filename,
2596              tr_ptrArray * dirtyFolders )
2597{
2598    char * dir = tr_dirname( filename );
2599
2600    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2601    while (     ( dir != NULL )
2602             && ( strlen( root ) <= strlen( dir ) )
2603             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2604    {
2605        char * tmp;
2606        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2607
2608        tmp = tr_dirname( dir );
2609        tr_free( dir );
2610        dir = tmp;
2611    }
2612
2613    tr_free( dir );
2614}
2615
2616static void
2617walkLocalData( const tr_torrent * tor,
2618               const char       * root,
2619               const char       * dir,
2620               const char       * base,
2621               tr_ptrArray      * torrentFiles,
2622               tr_ptrArray      * folders,
2623               tr_ptrArray      * dirtyFolders )
2624{
2625    int i;
2626    struct stat sb;
2627    char * buf;
2628
2629    assert( tr_isTorrent( tor ) );
2630
2631    buf = tr_buildPath( dir, base, NULL );
2632    i = stat( buf, &sb );
2633    if( !i )
2634    {
2635        DIR * odir = NULL;
2636
2637        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2638        {
2639            struct dirent *d;
2640            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2641            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2642                if( d->d_name && strcmp( d->d_name, "." ) && strcmp( d->d_name, ".." ) )
2643                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2644            closedir( odir );
2645        }
2646        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2647        {
2648            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2649            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2650            if( !isTorrentFile )
2651                addDirtyFile( root, buf, dirtyFolders );
2652        }
2653    }
2654
2655    tr_free( buf );
2656}
2657
2658static void
2659deleteLocalFile( const char * filename, tr_fileFunc fileFunc )
2660{
2661    struct stat sb;
2662    if( !stat( filename, &sb ) ) /* if file exists... */
2663        fileFunc( filename );
2664}
2665
2666static void
2667deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2668{
2669    int i, n;
2670    char ** s;
2671    tr_file_index_t f;
2672    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2673    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2674    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2675
2676    const char * firstFile = tor->info.files[0].name;
2677    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2678    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2679    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2680
2681    assert( tr_isTorrent( tor ) );
2682
2683    for( f=0; f<tor->info.fileCount; ++f ) {
2684        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2685        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2686    }
2687
2688    /* build the set of folders and dirtyFolders */
2689    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2690
2691    /* try to remove entire folders first, so that the recycle bin will be tidy */
2692    s = (char**) tr_ptrArrayPeek( &folders, &n );
2693    for( i=0; i<n; ++i )
2694        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2695            deleteLocalFile( s[i], fileFunc );
2696
2697    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2698    for( i=0, n=tr_ptrArraySize( &torrentFiles ); i<n; ++i ) {
2699        char * path = tr_buildPath( tor->currentDir, tr_ptrArrayNth( &torrentFiles, i ), NULL );
2700        deleteLocalFile( path, fileFunc );
2701        tr_free( path );
2702    }
2703
2704    /* Now clean out the directories left empty from the previous step.
2705     * Work from deepest to shallowest s.t. lower folders
2706     * won't prevent the upper folders from being deleted */
2707    {
2708        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2709        s = (char**) tr_ptrArrayPeek( &folders, &n );
2710        for( i=0; i<n; ++i )
2711            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2712                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2713        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2714        for( i=0; i<n; ++i ) {
2715#ifdef SYS_DARWIN
2716            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2717            deleteLocalFile( dsStore, fileFunc );
2718            tr_free( dsStore );
2719#endif
2720            deleteLocalFile( s[i], fileFunc );
2721        }
2722        tr_ptrArrayDestruct( &cleanFolders, NULL );
2723    }
2724
2725    /* cleanup */
2726    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2727    tr_ptrArrayDestruct( &folders, tr_free );
2728    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2729    tr_free( root );
2730    tr_free( tmp );
2731}
2732
2733static void
2734tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2735{
2736    assert( tr_isTorrent( tor ) );
2737
2738    if( fileFunc == NULL )
2739        fileFunc = remove;
2740
2741    /* close all the files because we're about to delete them */
2742    tr_cacheFlushTorrent( tor->session->cache, tor );
2743    tr_fdTorrentClose( tor->session, tor->uniqueId );
2744
2745    if( tor->info.fileCount > 1 )
2746    {
2747        deleteLocalData( tor, fileFunc );
2748    }
2749    else if( tor->info.fileCount == 1 )
2750    {
2751        char * tmp;
2752
2753        /* torrent only has one file */
2754        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2755        deleteLocalFile( path, fileFunc );
2756        tr_free( path );
2757
2758        tmp = tr_torrentBuildPartial( tor, 0 );
2759        path = tr_buildPath( tor->currentDir, tmp, NULL );
2760        deleteLocalFile( path, fileFunc );
2761        tr_free( path );
2762        tr_free( tmp );
2763    }
2764}
2765
2766/***
2767****
2768***/
2769
2770struct LocationData
2771{
2772    tr_bool move_from_old_location;
2773    int * setme_state;
2774    double * setme_progress;
2775    char * location;
2776    tr_torrent * tor;
2777};
2778
2779static tr_bool
2780isSameLocation( const char * path1, const char * path2 )
2781{
2782    struct stat s1, s2;
2783    const int err1 = stat( path1, &s1 );
2784    const int err2 = stat( path2, &s2 );
2785
2786    if( !err1 && !err2 ) {
2787        tr_dbg( "path1 dev:inode is %"PRIu64":%"PRIu64"; "
2788                "path2 dev:inode is %"PRIu64":%"PRIu64,
2789                (uint64_t)s1.st_dev, (uint64_t)s1.st_ino,
2790                (uint64_t)s2.st_dev, (uint64_t)s2.st_ino );
2791        return ( s1.st_dev == s2.st_dev )
2792            && ( s1.st_ino == s2.st_ino );
2793    }
2794
2795    /* either one, or the other, or both don't exist... */
2796    tr_dbg( "stat(%s) returned %d\n", path1, err1 );
2797    tr_dbg( "stat(%s) returned %d\n", path2, err2 );
2798    return FALSE;
2799}
2800
2801static void
2802setLocation( void * vdata )
2803{
2804    tr_bool err = FALSE;
2805    struct LocationData * data = vdata;
2806    tr_torrent * tor = data->tor;
2807    const tr_bool do_move = data->move_from_old_location;
2808    const char * location = data->location;
2809    double bytesHandled = 0;
2810
2811    assert( tr_isTorrent( tor ) );
2812
2813    tr_dbg( "Moving \"%s\" location from currentDir \"%s\" to \"%s\"",
2814            tr_torrentName(tor), tor->currentDir, location );
2815
2816    tr_mkdirp( location, 0777 );
2817
2818    if( !isSameLocation( location, tor->currentDir ) )
2819    {
2820        tr_file_index_t i;
2821
2822        /* bad idea to move files while they're being verified... */
2823        tr_verifyRemove( tor );
2824
2825        /* try to move the files.
2826         * FIXME: there are still all kinds of nasty cases, like what
2827         * if the target directory runs out of space halfway through... */
2828        for( i=0; !err && i<tor->info.fileCount; ++i )
2829        {
2830            const tr_file * f = &tor->info.files[i];
2831            const char * oldbase;
2832            char * sub;
2833            if( tr_torrentFindFile2( tor, i, &oldbase, &sub ) )
2834            {
2835                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2836                char * newpath = tr_buildPath( location, sub, NULL );
2837
2838                tr_dbg( "Found file #%d: %s", (int)i, oldpath );
2839
2840                if( do_move )
2841                {
2842                    tr_bool renamed = FALSE;
2843                    errno = 0;
2844                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2845                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2846                    {
2847                        err = TRUE;
2848                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2849                                        oldpath, newpath, tr_strerror( errno ) );
2850                    }
2851                }
2852
2853                tr_free( newpath );
2854                tr_free( oldpath );
2855                tr_free( sub );
2856            }
2857
2858            if( data->setme_progress )
2859            {
2860                bytesHandled += f->length;
2861                *data->setme_progress = bytesHandled / tor->info.totalSize;
2862            }
2863        }
2864
2865        if( !err )
2866        {
2867            /* blow away the leftover subdirectories in the old location */
2868            if( do_move )
2869                tr_torrentDeleteLocalData( tor, remove );
2870
2871            /* set the new location and reverify */
2872            tr_torrentSetDownloadDir( tor, location );
2873        }
2874    }
2875
2876    if( !err && do_move )
2877    {
2878        tr_free( tor->incompleteDir );
2879        tor->incompleteDir = NULL;
2880        tor->currentDir = tor->downloadDir;
2881    }
2882
2883    if( data->setme_state )
2884        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2885
2886    /* cleanup */
2887    tr_free( data->location );
2888    tr_free( data );
2889}
2890
2891void
2892tr_torrentSetLocation( tr_torrent  * tor,
2893                       const char  * location,
2894                       tr_bool       move_from_old_location,
2895                       double      * setme_progress,
2896                       int         * setme_state )
2897{
2898    struct LocationData * data;
2899
2900    assert( tr_isTorrent( tor ) );
2901
2902    if( setme_state )
2903        *setme_state = TR_LOC_MOVING;
2904    if( setme_progress )
2905        *setme_progress = 0;
2906
2907    /* run this in the libtransmission thread */
2908    data = tr_new( struct LocationData, 1 );
2909    data->tor = tor;
2910    data->location = tr_strdup( location );
2911    data->move_from_old_location = move_from_old_location;
2912    data->setme_state = setme_state;
2913    data->setme_progress = setme_progress;
2914    tr_runInEventThread( tor->session, setLocation, data );
2915}
2916
2917/***
2918****
2919***/
2920
2921void
2922tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2923{
2924    char * sub;
2925    const char * base;
2926
2927    /* close the file so that we can reopen in read-only mode as needed */
2928    tr_fdFileClose( tor->session, tor, fileNum );
2929
2930    /* if the torrent's current filename isn't the same as the one in the
2931     * metadata -- for example, if it had the ".part" suffix appended to
2932     * it until now -- then rename it to match the one in the metadata */
2933    if( tr_torrentFindFile2( tor, fileNum, &base, &sub ) )
2934    {
2935        const tr_file * file = &tor->info.files[fileNum];
2936
2937        if( strcmp( sub, file->name ) )
2938        {
2939            char * oldpath = tr_buildPath( base, sub, NULL );
2940            char * newpath = tr_buildPath( base, file->name, NULL );
2941
2942            if( rename( oldpath, newpath ) )
2943                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2944
2945            tr_free( newpath );
2946            tr_free( oldpath );
2947        }
2948
2949        tr_free( sub );
2950    }
2951}
2952
2953/***
2954****
2955***/
2956
2957static tr_bool
2958fileExists( const char * filename )
2959{
2960    struct stat sb;
2961    const tr_bool ok = !stat( filename, &sb );
2962    return ok;
2963}
2964
2965tr_bool
2966tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
2967                     const char ** base, char ** subpath )
2968{
2969    char * part;
2970    const tr_file * file;
2971    const char * b = NULL;
2972    const char * s = NULL;
2973
2974    assert( tr_isTorrent( tor ) );
2975    assert( fileNum < tor->info.fileCount );
2976
2977    file = &tor->info.files[fileNum];
2978    part = tr_torrentBuildPartial( tor, fileNum );
2979
2980    if( b == NULL ) {
2981        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
2982        if( fileExists( filename ) ) {
2983            b = tor->downloadDir;
2984            s = file->name;
2985        }
2986        tr_free( filename );
2987    }
2988
2989    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2990        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
2991        if( fileExists( filename ) ) {
2992            b = tor->incompleteDir;
2993            s = file->name;
2994        }
2995        tr_free( filename );
2996    }
2997
2998    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2999        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
3000        if( fileExists( filename ) ) {
3001            b = tor->incompleteDir;
3002            s = part;
3003        }
3004        tr_free( filename );
3005    }
3006
3007    if( b == NULL) {
3008        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
3009        if( fileExists( filename ) ) {
3010            b = tor->downloadDir;
3011            s = part;
3012        }
3013        tr_free( filename );
3014    }
3015
3016    if( base != NULL )
3017        *base = b;
3018    if( subpath != NULL )
3019        *subpath = tr_strdup( s );
3020
3021    tr_free( part );
3022    return b != NULL;
3023}
3024
3025char*
3026tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
3027{
3028    char * subpath;
3029    char * ret = NULL;
3030    const char * base;
3031
3032    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath ) )
3033    {
3034        ret = tr_buildPath( base, subpath, NULL );
3035        tr_free( subpath );
3036    }
3037
3038    return ret;
3039}
3040
3041/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
3042static void
3043refreshCurrentDir( tr_torrent * tor )
3044{
3045    const char * dir = NULL;
3046
3047    if( tor->incompleteDir == NULL )
3048        dir = tor->downloadDir;
3049    else if( !tr_torrentHasMetadata( tor ) ) /* no files to find */
3050        dir = tor->incompleteDir;
3051    else if( !tr_torrentFindFile2( tor, 0, &dir, NULL ) )
3052        dir = tor->incompleteDir;
3053
3054    assert( dir != NULL );
3055    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
3056    tor->currentDir = dir;
3057}
3058
3059char*
3060tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
3061{
3062    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
3063}
Note: See TracBrowser for help on using the repository browser.