source: trunk/libtransmission/torrent.c @ 11538

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

(trunk) #3675 "Not all .part files are removed" -- added patch for libtransmission and GTK+ client

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