source: trunk/libtransmission/torrent.c @ 12607

Last change on this file since 12607 was 12607, checked in by jordan, 10 years ago

(trunk) #671 "torrent queuing" -- Preliminary implementation. Covers libtransmission; GTK+ and Qt clients, and rudimentary web client support.

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