source: trunk/libtransmission/torrent.c @ 11540

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

(trunk libT) make tr_torrentDeleteLocalData() a private function

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