source: trunk/libtransmission/torrent.c @ 12627

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

silence a minor compiler warning when building with -DNDEBUG

  • Property svn:keywords set to Date Rev Author Id
File size: 87.3 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 12627 2011-08-05 17:03:34Z 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 = session->torrentCount;
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( tr_torrentIsQueued( tor ) ) {
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    s->isStalled = tr_torrentIsStalled( tor );
1187    tr_strlcpy( s->errorString, tor->errorString, sizeof( s->errorString ) );
1188
1189    s->manualAnnounceTime = tr_announcerNextManualAnnounce( tor );
1190
1191    tr_peerMgrTorrentStats( tor,
1192                            &s->peersConnected,
1193                            &s->webseedsSendingToUs,
1194                            &s->peersSendingToUs,
1195                            &s->peersGettingFromUs,
1196                            s->peersFrom );
1197
1198    now = tr_time_msec( );
1199    s->rawUploadSpeed_KBps     = toSpeedKBps( tr_bandwidthGetRawSpeed_Bps  ( &tor->bandwidth, now, TR_UP ) );
1200    s->pieceUploadSpeed_KBps   = toSpeedKBps( tr_bandwidthGetPieceSpeed_Bps( &tor->bandwidth, now, TR_UP ) );
1201    s->rawDownloadSpeed_KBps   = toSpeedKBps( tr_bandwidthGetRawSpeed_Bps  ( &tor->bandwidth, now, TR_DOWN ) );
1202    s->pieceDownloadSpeed_KBps = toSpeedKBps( tr_bandwidthGetPieceSpeed_Bps( &tor->bandwidth, now, TR_DOWN ) );
1203
1204    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
1205    s->metadataPercentComplete = tr_torrentGetMetadataPercent( tor );
1206
1207    s->percentDone         = tr_cpPercentDone  ( &tor->completion );
1208    s->leftUntilDone       = tr_cpLeftUntilDone( &tor->completion );
1209    s->sizeWhenDone        = tr_cpSizeWhenDone ( &tor->completion );
1210    s->recheckProgress     = s->activity == TR_STATUS_CHECK ? getVerifyProgress( tor ) : 0;
1211    s->activityDate        = tor->activityDate;
1212    s->addedDate           = tor->addedDate;
1213    s->doneDate            = tor->doneDate;
1214    s->startDate           = tor->startDate;
1215    s->secondsSeeding      = tor->secondsSeeding;
1216    s->secondsDownloading  = tor->secondsDownloading;
1217    s->idleSecs            = torrentGetIdleSecs( tor );
1218
1219    s->corruptEver      = tor->corruptCur    + tor->corruptPrev;
1220    s->downloadedEver   = tor->downloadedCur + tor->downloadedPrev;
1221    s->uploadedEver     = tor->uploadedCur   + tor->uploadedPrev;
1222    s->haveValid        = tr_cpHaveValid( &tor->completion );
1223    s->haveUnchecked    = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
1224    s->desiredAvailable = tr_peerMgrGetDesiredAvailable( tor );
1225
1226    s->ratio = tr_getRatio( s->uploadedEver,
1227                            s->downloadedEver ? s->downloadedEver : s->haveValid );
1228
1229    seedRatioApplies = tr_torrentGetSeedRatioBytes( tor, &seedRatioBytesLeft,
1230                                                         &seedRatioBytesGoal );
1231
1232    switch( s->activity )
1233    {
1234        /* etaXLSpeed exists because if we use the piece speed directly,
1235         * brief fluctuations cause the ETA to jump all over the place.
1236         * so, etaXLSpeed is a smoothed-out version of the piece speed
1237         * to dampen the effect of fluctuations */
1238
1239        case TR_STATUS_DOWNLOAD:
1240            if( ( tor->etaDLSpeedCalculatedAt + 800 ) < now ) {
1241                tor->etaDLSpeed_KBps = ( ( tor->etaDLSpeedCalculatedAt + 4000 ) < now )
1242                    ? s->pieceDownloadSpeed_KBps /* if no recent previous speed, no need to smooth */
1243                    : ((tor->etaDLSpeed_KBps*4.0) + s->pieceDownloadSpeed_KBps)/5.0; /* smooth across 5 readings */
1244                tor->etaDLSpeedCalculatedAt = now;
1245            }
1246
1247            if( s->leftUntilDone > s->desiredAvailable )
1248                s->eta = TR_ETA_NOT_AVAIL;
1249            else if( tor->etaDLSpeed_KBps < 1 )
1250                s->eta = TR_ETA_UNKNOWN;
1251            else
1252                s->eta = s->leftUntilDone / toSpeedBytes(tor->etaDLSpeed_KBps);
1253
1254            s->etaIdle = TR_ETA_NOT_AVAIL;
1255            break;
1256
1257        case TR_STATUS_SEED: {
1258            if( !seedRatioApplies )
1259                s->eta = TR_ETA_NOT_AVAIL;
1260            else {
1261                if( ( tor->etaULSpeedCalculatedAt + 800 ) < now ) {
1262                    tor->etaULSpeed_KBps = ( ( tor->etaULSpeedCalculatedAt + 4000 ) < now )
1263                        ? s->pieceUploadSpeed_KBps /* if no recent previous speed, no need to smooth */
1264                        : ((tor->etaULSpeed_KBps*4.0) + s->pieceUploadSpeed_KBps)/5.0; /* smooth across 5 readings */
1265                    tor->etaULSpeedCalculatedAt = now;
1266                }
1267                if( tor->etaULSpeed_KBps < 1 )
1268                    s->eta = TR_ETA_UNKNOWN;
1269                else
1270                    s->eta = seedRatioBytesLeft / toSpeedBytes(tor->etaULSpeed_KBps);
1271            }
1272
1273            if( tor->etaULSpeed_KBps < 1 && tr_torrentGetSeedIdle( tor, &seedIdleMinutes ) )
1274                s->etaIdle = seedIdleMinutes * 60 - s->idleSecs;
1275            else
1276                s->etaIdle = TR_ETA_NOT_AVAIL;
1277            break;
1278        }
1279
1280        default:
1281            s->eta = TR_ETA_NOT_AVAIL;
1282            s->etaIdle = TR_ETA_NOT_AVAIL;
1283            break;
1284    }
1285
1286    /* s->haveValid is here to make sure a torrent isn't marked 'finished'
1287     * when the user hits "uncheck all" prior to starting the torrent... */
1288    s->finished = tor->finishedSeedingByIdle || (seedRatioApplies && !seedRatioBytesLeft && s->haveValid);
1289
1290    if( !seedRatioApplies || s->finished )
1291        s->seedRatioPercentDone = 1;
1292    else if( !seedRatioBytesGoal ) /* impossible? safeguard for div by zero */
1293        s->seedRatioPercentDone = 0;
1294    else
1295        s->seedRatioPercentDone = (double)(seedRatioBytesGoal - seedRatioBytesLeft) / seedRatioBytesGoal;
1296
1297    tr_torrentUnlock( tor );
1298
1299    /* test some of the constraints */
1300    assert( s->sizeWhenDone <= tor->info.totalSize );
1301    assert( s->leftUntilDone <= s->sizeWhenDone );
1302    assert( s->desiredAvailable <= s->leftUntilDone );
1303    return s;
1304}
1305
1306/***
1307****
1308***/
1309
1310static uint64_t
1311fileBytesCompleted( const tr_torrent * tor, tr_file_index_t index )
1312{
1313    uint64_t total = 0;
1314    const tr_file * f = &tor->info.files[index];
1315
1316    if( f->length )
1317    {
1318        tr_block_index_t first;
1319        tr_block_index_t last;
1320        tr_torGetFileBlockRange( tor, index, &first, &last );
1321
1322        if( first == last )
1323        {
1324            if( tr_cpBlockIsComplete( &tor->completion, first ) )
1325                total = f->length;
1326        }
1327        else
1328        {
1329            /* the first block */
1330            if( tr_cpBlockIsComplete( &tor->completion, first ) )
1331                total += tor->blockSize - ( f->offset % tor->blockSize );
1332
1333            /* the middle blocks */
1334            if( first + 1 < last ) {
1335                uint64_t u = tr_bitfieldCountRange( &tor->completion.blockBitfield, first+1, last );
1336                u *= tor->blockSize;
1337                total += u;
1338            }
1339
1340            /* the last block */
1341            if( tr_cpBlockIsComplete( &tor->completion, last ) )
1342                total += ( f->offset + f->length ) - ( (uint64_t)tor->blockSize * last );
1343        }
1344    }
1345
1346    return total;
1347}
1348
1349tr_file_stat *
1350tr_torrentFiles( const tr_torrent * tor,
1351                 tr_file_index_t *  fileCount )
1352{
1353    tr_file_index_t       i;
1354    const tr_file_index_t n = tor->info.fileCount;
1355    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1356    tr_file_stat *        walk = files;
1357    const bool            isSeed = tor->completeness == TR_SEED;
1358
1359    assert( tr_isTorrent( tor ) );
1360
1361    for( i=0; i<n; ++i, ++walk ) {
1362        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1363        walk->bytesCompleted = b;
1364        walk->progress = tor->info.files[i].length > 0 ? ( (float)b / tor->info.files[i].length ) : 1.0f;
1365    }
1366
1367    if( fileCount )
1368        *fileCount = n;
1369
1370    return files;
1371}
1372
1373void
1374tr_torrentFilesFree( tr_file_stat *            files,
1375                     tr_file_index_t fileCount UNUSED )
1376{
1377    tr_free( files );
1378}
1379
1380/***
1381****
1382***/
1383
1384double*
1385tr_torrentWebSpeeds_KBps( const tr_torrent * tor )
1386{
1387    double * ret = NULL;
1388
1389    if( tr_isTorrent( tor ) )
1390    {
1391        tr_torrentLock( tor );
1392        ret = tr_peerMgrWebSpeeds_KBps( tor );
1393        tr_torrentUnlock( tor );
1394    }
1395
1396    return ret;
1397}
1398
1399tr_peer_stat *
1400tr_torrentPeers( const tr_torrent * tor, int * peerCount )
1401{
1402    tr_peer_stat * ret = NULL;
1403
1404    if( tr_isTorrent( tor ) )
1405    {
1406        tr_torrentLock( tor );
1407        ret = tr_peerMgrPeerStats( tor, peerCount );
1408        tr_torrentUnlock( tor );
1409    }
1410
1411    return ret;
1412}
1413
1414void
1415tr_torrentPeersFree( tr_peer_stat * peers, int peerCount UNUSED )
1416{
1417    tr_free( peers );
1418}
1419
1420tr_tracker_stat *
1421tr_torrentTrackers( const tr_torrent * torrent, int * setmeTrackerCount )
1422{
1423    tr_tracker_stat * ret = NULL;
1424
1425    if( tr_isTorrent( torrent ) )
1426    {
1427        tr_torrentLock( torrent );
1428        ret = tr_announcerStats( torrent, setmeTrackerCount );
1429        tr_torrentUnlock( torrent );
1430    }
1431
1432    return ret;
1433}
1434
1435void
1436tr_torrentTrackersFree( tr_tracker_stat * trackers, int trackerCount )
1437{
1438    tr_announcerStatsFree( trackers, trackerCount );
1439}
1440
1441void
1442tr_torrentAvailability( const tr_torrent * tor, int8_t * tab, int size )
1443{
1444    if( tr_isTorrent( tor ) && ( tab != NULL ) && ( size > 0 ) )
1445    {
1446        tr_torrentLock( tor );
1447        tr_peerMgrTorrentAvailability( tor, tab, size );
1448        tr_torrentUnlock( tor );
1449    }
1450}
1451
1452void
1453tr_torrentAmountFinished( const tr_torrent * tor,
1454                          float *            tab,
1455                          int                size )
1456{
1457    assert( tr_isTorrent( tor ) );
1458
1459    tr_torrentLock( tor );
1460    tr_cpGetAmountDone( &tor->completion, tab, size );
1461    tr_torrentUnlock( tor );
1462}
1463
1464static void
1465tr_torrentResetTransferStats( tr_torrent * tor )
1466{
1467    tr_torrentLock( tor );
1468
1469    tor->downloadedPrev += tor->downloadedCur;
1470    tor->downloadedCur   = 0;
1471    tor->uploadedPrev   += tor->uploadedCur;
1472    tor->uploadedCur     = 0;
1473    tor->corruptPrev    += tor->corruptCur;
1474    tor->corruptCur      = 0;
1475
1476    tr_torrentSetDirty( tor );
1477
1478    tr_torrentUnlock( tor );
1479}
1480
1481void
1482tr_torrentSetHasPiece( tr_torrent *     tor,
1483                       tr_piece_index_t pieceIndex,
1484                       bool             has )
1485{
1486    assert( tr_isTorrent( tor ) );
1487    assert( pieceIndex < tor->info.pieceCount );
1488
1489    if( has )
1490        tr_cpPieceAdd( &tor->completion, pieceIndex );
1491    else
1492        tr_cpPieceRem( &tor->completion, pieceIndex );
1493}
1494
1495/***
1496****
1497***/
1498
1499#ifndef NDEBUG
1500static bool queueIsSequenced( tr_session * );
1501#endif
1502
1503static void
1504freeTorrent( tr_torrent * tor )
1505{
1506    tr_torrent * t;
1507    tr_session *  session = tor->session;
1508    tr_info *    inf = &tor->info;
1509    const time_t now = tr_time( );
1510
1511    assert( !tor->isRunning );
1512
1513    tr_sessionLock( session );
1514
1515    tr_peerMgrRemoveTorrent( tor );
1516
1517    tr_cpDestruct( &tor->completion );
1518
1519    tr_announcerRemoveTorrent( session->announcer, tor );
1520
1521    tr_free( tor->downloadDir );
1522    tr_free( tor->incompleteDir );
1523
1524    if( tor == session->torrentList )
1525        session->torrentList = tor->next;
1526    else for( t = session->torrentList; t != NULL; t = t->next ) {
1527        if( t->next == tor ) {
1528            t->next = tor->next;
1529            break;
1530        }
1531    }
1532
1533    /* decrement the torrent count */
1534    assert( session->torrentCount >= 1 );
1535    session->torrentCount--;
1536
1537    /* resequence the queue positions */
1538    t = NULL;
1539    while(( t = tr_torrentNext( session, t ))) {
1540        if( t->queuePosition > tor->queuePosition ) {
1541            t->queuePosition--;
1542            t->anyDate = now;
1543        }
1544    }
1545    assert( queueIsSequenced( session ) );
1546
1547    tr_bandwidthDestruct( &tor->bandwidth );
1548
1549    tr_metainfoFree( inf );
1550    tr_free( tor );
1551
1552    tr_sessionUnlock( session );
1553}
1554
1555/**
1556***  Start/Stop Callback
1557**/
1558
1559static void torrentSetQueued( tr_torrent * tor, bool queued );
1560
1561static void
1562torrentStartImpl( void * vtor )
1563{
1564    time_t now;
1565    tr_torrent * tor = vtor;
1566
1567    assert( tr_isTorrent( tor ) );
1568
1569    tr_sessionLock( tor->session );
1570
1571    tr_torrentRecheckCompleteness( tor );
1572    torrentSetQueued( tor, false );
1573
1574    now = tr_time( );
1575    tor->isRunning = true;
1576    tor->completeness = tr_cpGetStatus( &tor->completion );
1577    tor->startDate = tor->anyDate = now;
1578    tr_torrentClearError( tor );
1579    tor->finishedSeedingByIdle = false;
1580
1581    tr_torrentResetTransferStats( tor );
1582    tr_announcerTorrentStarted( tor );
1583    tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1584    tor->dhtAnnounce6At = now + tr_cryptoWeakRandInt( 20 );
1585    tor->lpdAnnounceAt = now;
1586    tr_peerMgrStartTorrent( tor );
1587
1588    tr_sessionUnlock( tor->session );
1589}
1590
1591uint64_t
1592tr_torrentGetCurrentSizeOnDisk( const tr_torrent * tor )
1593{
1594    tr_file_index_t i;
1595    uint64_t byte_count = 0;
1596    const tr_file_index_t n = tor->info.fileCount;
1597
1598    for( i=0; i<n; ++i )
1599    {
1600        struct stat sb;
1601        char * filename = tr_torrentFindFile( tor, i );
1602
1603        sb.st_size = 0;
1604        if( filename && !stat( filename, &sb ) )
1605            byte_count += sb.st_size;
1606
1607        tr_free( filename );
1608    }
1609
1610    return byte_count;
1611}
1612
1613static bool
1614torrentShouldQueue( const tr_torrent * tor )
1615{
1616    const tr_direction dir = tr_torrentGetQueueDirection( tor );
1617
1618    return tr_sessionCountQueueFreeSlots( tor->session, dir ) == 0;
1619}
1620
1621static void
1622torrentStart( tr_torrent * tor, bool bypass_queue )
1623{
1624    switch( torrentGetActivity( tor ) )
1625    {
1626        case TR_STATUS_SEED:
1627        case TR_STATUS_DOWNLOAD:
1628            return; /* already started */
1629            break;
1630
1631        case TR_STATUS_SEED_WAIT:
1632        case TR_STATUS_DOWNLOAD_WAIT:
1633            if( !bypass_queue )
1634                return; /* already queued */
1635            break;
1636
1637        case TR_STATUS_CHECK:
1638        case TR_STATUS_CHECK_WAIT:
1639            /* verifying right now... wait until that's done so
1640             * we'll know what completeness to use/announce */
1641            tor->startAfterVerify = true;
1642            return;
1643            break;
1644
1645        case TR_STATUS_STOPPED:
1646            if( !bypass_queue && torrentShouldQueue( tor ) ) {
1647                torrentSetQueued( tor, true );
1648                return;
1649            }
1650            break;
1651    }
1652
1653    /* don't allow the torrent to be started if the files disappeared */
1654    if( setLocalErrorIfFilesDisappeared( tor ) )
1655        return;
1656
1657    /* otherwise, start it now... */
1658    tr_sessionLock( tor->session );
1659
1660    /* allow finished torrents to be resumed */
1661    if( tr_torrentIsSeedRatioDone( tor ) ) {
1662        tr_torinf( tor, _( "Restarted manually -- disabling its seed ratio" ) );
1663        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
1664    }
1665
1666    /* corresponds to the peer_id sent as a tracker request parameter.
1667     * one tracker admin says: "When the same torrent is opened and
1668     * closed and opened again without quitting Transmission ...
1669     * change the peerid. It would help sometimes if a stopped event
1670     * was missed to ensure that we didn't think someone was cheating. */
1671    tr_peerIdInit( tor->peer_id );
1672    tor->isRunning = 1;
1673    tr_torrentSetDirty( tor );
1674    tr_runInEventThread( tor->session, torrentStartImpl, tor );
1675
1676    tr_sessionUnlock( tor->session );
1677}
1678
1679void
1680tr_torrentStart( tr_torrent * tor )
1681{
1682    if( tr_isTorrent( tor ) )
1683        torrentStart( tor, false );
1684}
1685
1686void
1687tr_torrentStartNow( tr_torrent * tor )
1688{
1689    if( tr_isTorrent( tor ) )
1690        torrentStart( tor, true );
1691}
1692
1693static void
1694torrentRecheckDoneImpl( void * vtor )
1695{
1696    tr_torrent * tor = vtor;
1697    assert( tr_isTorrent( tor ) );
1698
1699    tr_torrentRecheckCompleteness( tor );
1700
1701    if( tor->startAfterVerify ) {
1702        tor->startAfterVerify = false;
1703        torrentStart( tor, false );
1704    }
1705}
1706
1707static void
1708torrentRecheckDoneCB( tr_torrent * tor )
1709{
1710    assert( tr_isTorrent( tor ) );
1711
1712    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1713}
1714
1715static void
1716verifyTorrent( void * vtor )
1717{
1718    tr_torrent * tor = vtor;
1719
1720    tr_sessionLock( tor->session );
1721
1722    /* if the torrent's already being verified, stop it */
1723    tr_verifyRemove( tor );
1724
1725    /* if the torrent's running, stop it & set the restart-after-verify flag */
1726    if( tor->startAfterVerify || tor->isRunning ) {
1727        /* don't clobber isStopping */
1728        const bool startAfter = tor->isStopping ? false : true;
1729        tr_torrentStop( tor );
1730        tor->startAfterVerify = startAfter;
1731    }
1732
1733    if( setLocalErrorIfFilesDisappeared( tor ) )
1734        tor->startAfterVerify = false;
1735    else
1736        tr_verifyAdd( tor, torrentRecheckDoneCB );
1737
1738    tr_sessionUnlock( tor->session );
1739}
1740
1741void
1742tr_torrentVerify( tr_torrent * tor )
1743{
1744    if( tr_isTorrent( tor ) )
1745        tr_runInEventThread( tor->session, verifyTorrent, tor );
1746}
1747
1748void
1749tr_torrentSave( tr_torrent * tor )
1750{
1751    assert( tr_isTorrent( tor ) );
1752
1753    if( tor->isDirty )
1754    {
1755        tor->isDirty = false;
1756        tr_torrentSaveResume( tor );
1757    }
1758}
1759
1760static void
1761stopTorrent( void * vtor )
1762{
1763    tr_torrent * tor = vtor;
1764    tr_torinf( tor, "Pausing" );
1765
1766    assert( tr_isTorrent( tor ) );
1767
1768    tr_torrentLock( tor );
1769
1770    tr_verifyRemove( tor );
1771    torrentSetQueued( tor, false );
1772    tr_peerMgrStopTorrent( tor );
1773    tr_announcerTorrentStopped( tor );
1774    tr_cacheFlushTorrent( tor->session->cache, tor );
1775
1776    tr_fdTorrentClose( tor->session, tor->uniqueId );
1777
1778    if( !tor->isDeleting )
1779        tr_torrentSave( tor );
1780
1781    tr_torrentUnlock( tor );
1782}
1783
1784void
1785tr_torrentStop( tr_torrent * tor )
1786{
1787    assert( tr_isTorrent( tor ) );
1788
1789    if( tr_isTorrent( tor ) )
1790    {
1791        tr_sessionLock( tor->session );
1792
1793        tor->isRunning = 0;
1794        tor->isStopping = 0;
1795        tr_torrentSetDirty( tor );
1796        tr_runInEventThread( tor->session, stopTorrent, tor );
1797
1798        tr_sessionUnlock( tor->session );
1799    }
1800}
1801
1802static void
1803closeTorrent( void * vtor )
1804{
1805    tr_benc * d;
1806    tr_torrent * tor = vtor;
1807
1808    assert( tr_isTorrent( tor ) );
1809
1810    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1811    tr_bencDictAddInt( d, "id", tor->uniqueId );
1812    tr_bencDictAddInt( d, "date", tr_time( ) );
1813
1814    tr_torinf( tor, "%s", _( "Removing torrent" ) );
1815
1816    stopTorrent( tor );
1817
1818    if( tor->isDeleting )
1819    {
1820        tr_metainfoRemoveSaved( tor->session, &tor->info );
1821        tr_torrentRemoveResume( tor );
1822    }
1823
1824    tor->isRunning = 0;
1825    freeTorrent( tor );
1826}
1827
1828void
1829tr_torrentFree( tr_torrent * tor )
1830{
1831    if( tr_isTorrent( tor ) )
1832    {
1833        tr_session * session = tor->session;
1834        assert( tr_isSession( session ) );
1835        tr_sessionLock( session );
1836
1837        tr_torrentClearCompletenessCallback( tor );
1838        tr_runInEventThread( session, closeTorrent, tor );
1839
1840        tr_sessionUnlock( session );
1841    }
1842}
1843
1844struct remove_data
1845{
1846    tr_torrent   * tor;
1847    bool           deleteFlag;
1848    tr_fileFunc  * deleteFunc;
1849};
1850
1851static void tr_torrentDeleteLocalData( tr_torrent *, tr_fileFunc );
1852
1853static void
1854removeTorrent( void * vdata )
1855{
1856    struct remove_data * data = vdata;
1857
1858    if( data->deleteFlag )
1859        tr_torrentDeleteLocalData( data->tor, data->deleteFunc );
1860
1861    tr_torrentClearCompletenessCallback( data->tor );
1862    closeTorrent( data->tor );
1863    tr_free( data );
1864}
1865
1866void
1867tr_torrentRemove( tr_torrent   * tor,
1868                  bool           deleteFlag,
1869                  tr_fileFunc    deleteFunc )
1870{
1871    struct remove_data * data;
1872
1873    assert( tr_isTorrent( tor ) );
1874    tor->isDeleting = 1;
1875
1876    data = tr_new0( struct remove_data, 1 );
1877    data->tor = tor;
1878    data->deleteFlag = deleteFlag;
1879    data->deleteFunc = deleteFunc;
1880    tr_runInEventThread( tor->session, removeTorrent, data );
1881}
1882
1883/**
1884***  Completeness
1885**/
1886
1887static const char *
1888getCompletionString( int type )
1889{
1890    switch( type )
1891    {
1892        /* Translators: this is a minor point that's safe to skip over, but FYI:
1893           "Complete" and "Done" are specific, different terms in Transmission:
1894           "Complete" means we've downloaded every file in the torrent.
1895           "Done" means we're done downloading the files we wanted, but NOT all
1896           that exist */
1897        case TR_PARTIAL_SEED:
1898            return _( "Done" );
1899
1900        case TR_SEED:
1901            return _( "Complete" );
1902
1903        default:
1904            return _( "Incomplete" );
1905    }
1906}
1907
1908static void
1909fireCompletenessChange( tr_torrent       * tor,
1910                        tr_completeness    status,
1911                        bool               wasRunning )
1912{
1913    assert( ( status == TR_LEECH )
1914         || ( status == TR_SEED )
1915         || ( status == TR_PARTIAL_SEED ) );
1916
1917    if( tor->completeness_func )
1918        tor->completeness_func( tor, status, wasRunning,
1919                                tor->completeness_func_user_data );
1920}
1921
1922void
1923tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1924                                   tr_torrent_completeness_func    func,
1925                                   void                          * user_data )
1926{
1927    assert( tr_isTorrent( tor ) );
1928
1929    tor->completeness_func = func;
1930    tor->completeness_func_user_data = user_data;
1931}
1932
1933void
1934tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1935{
1936    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1937}
1938
1939void
1940tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1941                                    tr_torrent_ratio_limit_hit_func  func,
1942                                    void                           * user_data )
1943{
1944    assert( tr_isTorrent( tor ) );
1945
1946    tor->ratio_limit_hit_func = func;
1947    tor->ratio_limit_hit_func_user_data = user_data;
1948}
1949
1950void
1951tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1952{
1953    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1954}
1955
1956void
1957tr_torrentSetIdleLimitHitCallback( tr_torrent                    * tor,
1958                                   tr_torrent_idle_limit_hit_func  func,
1959                                   void                          * user_data )
1960{
1961    assert( tr_isTorrent( tor ) );
1962
1963    tor->idle_limit_hit_func = func;
1964    tor->idle_limit_hit_func_user_data = user_data;
1965}
1966
1967void
1968tr_torrentClearIdleLimitHitCallback( tr_torrent * torrent )
1969{
1970    tr_torrentSetIdleLimitHitCallback( torrent, NULL, NULL );
1971}
1972
1973static void
1974onSigCHLD( int i UNUSED )
1975{
1976    waitpid( -1, NULL, WNOHANG );
1977}
1978
1979static void
1980torrentCallScript( const tr_torrent * tor, const char * script )
1981{
1982    char timeStr[128];
1983    const time_t now = tr_time( );
1984
1985    tr_strlcpy( timeStr, ctime( &now ), sizeof( timeStr ) );
1986    *strchr( timeStr,'\n' ) = '\0';
1987
1988    if( script && *script )
1989    {
1990        int i;
1991        char * cmd[] = { tr_strdup( script ), NULL };
1992        char * env[] = {
1993            tr_strdup_printf( "TR_APP_VERSION=%s", SHORT_VERSION_STRING ),
1994            tr_strdup_printf( "TR_TIME_LOCALTIME=%s", timeStr ),
1995            tr_strdup_printf( "TR_TORRENT_DIR=%s", tor->currentDir ),
1996            tr_strdup_printf( "TR_TORRENT_ID=%d", tr_torrentId( tor ) ),
1997            tr_strdup_printf( "TR_TORRENT_HASH=%s", tor->info.hashString ),
1998            tr_strdup_printf( "TR_TORRENT_NAME=%s", tr_torrentName( tor ) ),
1999            NULL };
2000
2001        tr_torinf( tor, "Calling script \"%s\"", script );
2002
2003#ifdef WIN32
2004        _spawnvpe( _P_NOWAIT, script, (const char*)cmd, env );
2005#else
2006        signal( SIGCHLD, onSigCHLD );
2007
2008        if( !fork( ) )
2009        {
2010            for (i=0; env[i]; ++i)
2011                putenv(env[i]);
2012            execvp( script, cmd );
2013            _exit( 0 );
2014        }
2015#endif
2016
2017        for( i=0; cmd[i]; ++i ) tr_free( cmd[i] );
2018        for( i=0; env[i]; ++i ) tr_free( env[i] );
2019    }
2020}
2021
2022void
2023tr_torrentRecheckCompleteness( tr_torrent * tor )
2024{
2025    tr_completeness completeness;
2026
2027    assert( tr_isTorrent( tor ) );
2028
2029    tr_torrentLock( tor );
2030
2031    completeness = tr_cpGetStatus( &tor->completion );
2032
2033    if( completeness != tor->completeness )
2034    {
2035        const int recentChange = tor->downloadedCur != 0;
2036        const bool wasLeeching = !tr_torrentIsSeed( tor );
2037        const bool wasRunning = tor->isRunning;
2038
2039        if( recentChange )
2040        {
2041            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
2042                      getCompletionString( tor->completeness ),
2043                      getCompletionString( completeness ) );
2044        }
2045
2046        tor->completeness = completeness;
2047        tr_fdTorrentClose( tor->session, tor->uniqueId );
2048
2049        if( tr_torrentIsSeed( tor ) )
2050        {
2051            if( recentChange )
2052            {
2053                tr_announcerTorrentCompleted( tor );
2054                tor->doneDate = tor->anyDate = tr_time( );
2055            }
2056
2057            if( wasLeeching && wasRunning )
2058            {
2059                /* clear interested flag on all peers */
2060                tr_peerMgrClearInterest( tor );
2061
2062                /* if completeness was TR_LEECH then the seed limit check will have been skipped in bandwidthPulse */
2063                tr_torrentCheckSeedLimit( tor );
2064            }
2065
2066            if( tor->currentDir == tor->incompleteDir )
2067                tr_torrentSetLocation( tor, tor->downloadDir, true, NULL, NULL );
2068
2069            if( tr_sessionIsTorrentDoneScriptEnabled( tor->session ) )
2070                torrentCallScript( tor, tr_sessionGetTorrentDoneScript( tor->session ) );
2071        }
2072
2073        fireCompletenessChange( tor, completeness, wasRunning );
2074
2075        tr_torrentSetDirty( tor );
2076    }
2077
2078    tr_torrentUnlock( tor );
2079}
2080
2081/***
2082****
2083***/
2084
2085static void
2086tr_torrentFireMetadataCompleted( tr_torrent * tor )
2087{
2088    assert( tr_isTorrent( tor ) );
2089
2090    if( tor->metadata_func )
2091        tor->metadata_func( tor, tor->metadata_func_user_data );
2092}
2093
2094void
2095tr_torrentSetMetadataCallback( tr_torrent                * tor,
2096                               tr_torrent_metadata_func    func,
2097                               void                      * user_data )
2098{
2099    assert( tr_isTorrent( tor ) );
2100
2101    tor->metadata_func = func;
2102    tor->metadata_func_user_data = user_data;
2103}
2104
2105
2106/**
2107***  File priorities
2108**/
2109
2110void
2111tr_torrentInitFilePriority( tr_torrent *    tor,
2112                            tr_file_index_t fileIndex,
2113                            tr_priority_t   priority )
2114{
2115    tr_piece_index_t i;
2116    tr_file *        file;
2117
2118    assert( tr_isTorrent( tor ) );
2119    assert( fileIndex < tor->info.fileCount );
2120    assert( tr_isPriority( priority ) );
2121
2122    file = &tor->info.files[fileIndex];
2123    file->priority = priority;
2124    for( i = file->firstPiece; i <= file->lastPiece; ++i )
2125        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
2126}
2127
2128void
2129tr_torrentSetFilePriorities( tr_torrent             * tor,
2130                             const tr_file_index_t  * files,
2131                             tr_file_index_t          fileCount,
2132                             tr_priority_t            priority )
2133{
2134    tr_file_index_t i;
2135    assert( tr_isTorrent( tor ) );
2136    tr_torrentLock( tor );
2137
2138    for( i = 0; i < fileCount; ++i )
2139        if( files[i] < tor->info.fileCount )
2140            tr_torrentInitFilePriority( tor, files[i], priority );
2141    tr_torrentSetDirty( tor );
2142    tr_peerMgrRebuildRequests( tor );
2143
2144    tr_torrentUnlock( tor );
2145}
2146
2147tr_priority_t*
2148tr_torrentGetFilePriorities( const tr_torrent * tor )
2149{
2150    tr_file_index_t i;
2151    tr_priority_t * p;
2152
2153    assert( tr_isTorrent( tor ) );
2154
2155    tr_torrentLock( tor );
2156    p = tr_new0( tr_priority_t, tor->info.fileCount );
2157    for( i = 0; i < tor->info.fileCount; ++i )
2158        p[i] = tor->info.files[i].priority;
2159    tr_torrentUnlock( tor );
2160
2161    return p;
2162}
2163
2164/**
2165***  File DND
2166**/
2167
2168static void
2169setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
2170{
2171    const int8_t     dnd = !doDownload;
2172    tr_piece_index_t firstPiece;
2173    int8_t           firstPieceDND;
2174    tr_piece_index_t lastPiece;
2175    int8_t           lastPieceDND;
2176    tr_file_index_t  i;
2177    tr_file *        file = &tor->info.files[fileIndex];
2178
2179    file->dnd = dnd;
2180    firstPiece = file->firstPiece;
2181    lastPiece = file->lastPiece;
2182
2183    /* can't set the first piece to DND unless
2184       every file using that piece is DND */
2185    firstPieceDND = dnd;
2186    if( fileIndex > 0 )
2187    {
2188        for( i = fileIndex - 1; firstPieceDND; --i )
2189        {
2190            if( tor->info.files[i].lastPiece != firstPiece )
2191                break;
2192            firstPieceDND = tor->info.files[i].dnd;
2193            if( !i )
2194                break;
2195        }
2196    }
2197
2198    /* can't set the last piece to DND unless
2199       every file using that piece is DND */
2200    lastPieceDND = dnd;
2201    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
2202    {
2203        if( tor->info.files[i].firstPiece != lastPiece )
2204            break;
2205        lastPieceDND = tor->info.files[i].dnd;
2206    }
2207
2208    if( firstPiece == lastPiece )
2209    {
2210        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
2211    }
2212    else
2213    {
2214        tr_piece_index_t pp;
2215        tor->info.pieces[firstPiece].dnd = firstPieceDND;
2216        tor->info.pieces[lastPiece].dnd = lastPieceDND;
2217        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
2218            tor->info.pieces[pp].dnd = dnd;
2219    }
2220}
2221
2222void
2223tr_torrentInitFileDLs( tr_torrent             * tor,
2224                       const tr_file_index_t  * files,
2225                       tr_file_index_t          fileCount,
2226                       bool                     doDownload )
2227{
2228    tr_file_index_t i;
2229
2230    assert( tr_isTorrent( tor ) );
2231
2232    tr_torrentLock( tor );
2233
2234    for( i=0; i<fileCount; ++i )
2235        if( files[i] < tor->info.fileCount )
2236            setFileDND( tor, files[i], doDownload );
2237
2238    tr_cpInvalidateDND( &tor->completion );
2239
2240    tr_torrentUnlock( tor );
2241}
2242
2243void
2244tr_torrentSetFileDLs( tr_torrent             * tor,
2245                      const tr_file_index_t  * files,
2246                      tr_file_index_t          fileCount,
2247                      bool                     doDownload )
2248{
2249    assert( tr_isTorrent( tor ) );
2250    tr_torrentLock( tor );
2251
2252    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
2253    tr_torrentSetDirty( tor );
2254    tr_peerMgrRebuildRequests( tor );
2255
2256    tr_torrentUnlock( tor );
2257}
2258
2259/***
2260****
2261***/
2262
2263tr_priority_t
2264tr_torrentGetPriority( const tr_torrent * tor )
2265{
2266    assert( tr_isTorrent( tor ) );
2267
2268    return tor->bandwidth.priority;
2269}
2270
2271void
2272tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
2273{
2274    assert( tr_isTorrent( tor ) );
2275    assert( tr_isPriority( priority ) );
2276
2277    if( tor->bandwidth.priority != priority )
2278    {
2279        tor->bandwidth.priority = priority;
2280
2281        tr_torrentSetDirty( tor );
2282    }
2283}
2284
2285/***
2286****
2287***/
2288
2289void
2290tr_torrentSetPeerLimit( tr_torrent * tor,
2291                        uint16_t     maxConnectedPeers )
2292{
2293    assert( tr_isTorrent( tor ) );
2294
2295    if ( tor->maxConnectedPeers != maxConnectedPeers )
2296    {
2297        tor->maxConnectedPeers = maxConnectedPeers;
2298
2299        tr_torrentSetDirty( tor );
2300    }
2301}
2302
2303uint16_t
2304tr_torrentGetPeerLimit( const tr_torrent * tor )
2305{
2306    assert( tr_isTorrent( tor ) );
2307
2308    return tor->maxConnectedPeers;
2309}
2310
2311/***
2312****
2313***/
2314
2315void
2316tr_torrentGetBlockLocation( const tr_torrent * tor,
2317                            tr_block_index_t   block,
2318                            tr_piece_index_t * piece,
2319                            uint32_t         * offset,
2320                            uint32_t         * length )
2321{
2322    uint64_t pos = block;
2323    pos *= tor->blockSize;
2324    *piece = pos / tor->info.pieceSize;
2325    *offset = pos - ( *piece * tor->info.pieceSize );
2326    *length = tr_torBlockCountBytes( tor, block );
2327}
2328
2329
2330tr_block_index_t
2331_tr_block( const tr_torrent * tor,
2332           tr_piece_index_t   index,
2333           uint32_t           offset )
2334{
2335    tr_block_index_t ret;
2336
2337    assert( tr_isTorrent( tor ) );
2338
2339    ret = index;
2340    ret *= ( tor->info.pieceSize / tor->blockSize );
2341    ret += offset / tor->blockSize;
2342    return ret;
2343}
2344
2345bool
2346tr_torrentReqIsValid( const tr_torrent * tor,
2347                      tr_piece_index_t   index,
2348                      uint32_t           offset,
2349                      uint32_t           length )
2350{
2351    int err = 0;
2352
2353    assert( tr_isTorrent( tor ) );
2354
2355    if( index >= tor->info.pieceCount )
2356        err = 1;
2357    else if( length < 1 )
2358        err = 2;
2359    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
2360        err = 3;
2361    else if( length > MAX_BLOCK_SIZE )
2362        err = 4;
2363    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
2364        err = 5;
2365
2366    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
2367                              (unsigned long)index,
2368                              (unsigned long)offset,
2369                              (unsigned long)length,
2370                              err );
2371
2372    return !err;
2373}
2374
2375uint64_t
2376tr_pieceOffset( const tr_torrent * tor,
2377                tr_piece_index_t   index,
2378                uint32_t           offset,
2379                uint32_t           length )
2380{
2381    uint64_t ret;
2382
2383    assert( tr_isTorrent( tor ) );
2384
2385    ret = tor->info.pieceSize;
2386    ret *= index;
2387    ret += offset;
2388    ret += length;
2389    return ret;
2390}
2391
2392void
2393tr_torGetFileBlockRange( const tr_torrent        * tor,
2394                         const tr_file_index_t     file,
2395                         tr_block_index_t        * first,
2396                         tr_block_index_t        * last )
2397{
2398    const tr_file * f = &tor->info.files[file];
2399    uint64_t offset = f->offset;
2400    *first = offset / tor->blockSize;
2401    if( !f->length )
2402        *last = *first;
2403    else {
2404        offset += f->length - 1;
2405        *last = offset / tor->blockSize;
2406    }
2407}
2408
2409void
2410tr_torGetPieceBlockRange( const tr_torrent        * tor,
2411                          const tr_piece_index_t    piece,
2412                          tr_block_index_t        * first,
2413                          tr_block_index_t        * last )
2414{
2415    uint64_t offset = tor->info.pieceSize;
2416    offset *= piece;
2417    *first = offset / tor->blockSize;
2418    offset += ( tr_torPieceCountBytes( tor, piece ) - 1 );
2419    *last = offset / tor->blockSize;
2420}
2421
2422
2423/***
2424****
2425***/
2426
2427void
2428tr_torrentSetPieceChecked( tr_torrent * tor, tr_piece_index_t pieceIndex )
2429{
2430    assert( tr_isTorrent( tor ) );
2431    assert( pieceIndex < tor->info.pieceCount );
2432
2433    tor->info.pieces[pieceIndex].timeChecked = tr_time( );
2434}
2435
2436void
2437tr_torrentSetChecked( tr_torrent * tor, time_t when )
2438{
2439    tr_piece_index_t i, n;
2440
2441    assert( tr_isTorrent( tor ) );
2442
2443    for( i=0, n=tor->info.pieceCount; i!=n; ++i )
2444        tor->info.pieces[i].timeChecked = when;
2445}
2446
2447bool
2448tr_torrentCheckPiece( tr_torrent * tor, tr_piece_index_t pieceIndex )
2449{
2450    const bool pass = tr_ioTestPiece( tor, pieceIndex );
2451
2452    tr_deeplog_tor( tor, "[LAZY] tr_torrentCheckPiece tested piece %zu, pass==%d", (size_t)pieceIndex, (int)pass );
2453    tr_torrentSetHasPiece( tor, pieceIndex, pass );
2454    tr_torrentSetPieceChecked( tor, pieceIndex );
2455    tor->anyDate = tr_time( );
2456    tr_torrentSetDirty( tor );
2457
2458    return pass;
2459}
2460
2461time_t
2462tr_torrentGetFileMTime( const tr_torrent * tor, tr_file_index_t i )
2463{
2464    time_t mtime = 0;
2465    if( !tr_fdFileGetCachedMTime( tor->session, tor->uniqueId, i, &mtime ) )
2466        tr_torrentFindFile2( tor, i, NULL, NULL, &mtime );
2467    return mtime;
2468}
2469
2470bool
2471tr_torrentPieceNeedsCheck( const tr_torrent * tor, tr_piece_index_t p )
2472{
2473    uint64_t unused;
2474    tr_file_index_t f;
2475    const tr_info * inf = tr_torrentInfo( tor );
2476
2477    /* if we've never checked this piece, then it needs to be checked */
2478    if( !inf->pieces[p].timeChecked )
2479        return true;
2480
2481    /* If we think we've completed one of the files in this piece,
2482     * but it's been modified since we last checked it,
2483     * then it needs to be rechecked */
2484    tr_ioFindFileLocation( tor, p, 0, &f, &unused );
2485    for( ; f < inf->fileCount && pieceHasFile( p, &inf->files[f] ); ++f )
2486        if( tr_cpFileIsComplete( &tor->completion, f ) )
2487            if( tr_torrentGetFileMTime( tor, f ) > inf->pieces[p].timeChecked )
2488                return true;
2489
2490    return false;
2491}
2492
2493/***
2494****
2495***/
2496
2497static int
2498compareTrackerByTier( const void * va, const void * vb )
2499{
2500    const tr_tracker_info * a = va;
2501    const tr_tracker_info * b = vb;
2502
2503    /* sort by tier */
2504    if( a->tier != b->tier )
2505        return a->tier - b->tier;
2506
2507    /* get the effects of a stable sort by comparing the two elements' addresses */
2508    return a - b;
2509}
2510
2511bool
2512tr_torrentSetAnnounceList( tr_torrent             * tor,
2513                           const tr_tracker_info  * trackers_in,
2514                           int                      trackerCount )
2515{
2516    int i;
2517    tr_benc metainfo;
2518    bool ok = true;
2519    tr_tracker_info * trackers;
2520
2521    tr_torrentLock( tor );
2522
2523    assert( tr_isTorrent( tor ) );
2524
2525    /* ensure the trackers' tiers are in ascending order */
2526    trackers = tr_memdup( trackers_in, sizeof( tr_tracker_info ) * trackerCount );
2527    qsort( trackers, trackerCount, sizeof( tr_tracker_info ), compareTrackerByTier );
2528
2529    /* look for bad URLs */
2530    for( i=0; ok && i<trackerCount; ++i )
2531        if( !tr_urlIsValidTracker( trackers[i].announce ) )
2532            ok = false;
2533
2534    /* save to the .torrent file */
2535    if( ok && !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2536    {
2537        bool hasInfo;
2538        tr_info tmpInfo;
2539
2540        /* remove the old fields */
2541        tr_bencDictRemove( &metainfo, "announce" );
2542        tr_bencDictRemove( &metainfo, "announce-list" );
2543
2544        /* add the new fields */
2545        if( trackerCount > 0 )
2546        {
2547            tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2548        }
2549        if( trackerCount > 1 )
2550        {
2551            int i;
2552            int prevTier = -1;
2553            tr_benc * tier = NULL;
2554            tr_benc * announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2555
2556            for( i=0; i<trackerCount; ++i ) {
2557                if( prevTier != trackers[i].tier ) {
2558                    prevTier = trackers[i].tier;
2559                    tier = tr_bencListAddList( announceList, 0 );
2560                }
2561                tr_bencListAddStr( tier, trackers[i].announce );
2562            }
2563        }
2564
2565        /* try to parse it back again, to make sure it's good */
2566        memset( &tmpInfo, 0, sizeof( tr_info ) );
2567        if( tr_metainfoParse( tor->session, &metainfo, &tmpInfo,
2568                              &hasInfo, &tor->infoDictLength ) )
2569        {
2570            /* it's good, so keep these new trackers and free the old ones */
2571
2572            tr_info swap;
2573            swap.trackers = tor->info.trackers;
2574            swap.trackerCount = tor->info.trackerCount;
2575            tor->info.trackers = tmpInfo.trackers;
2576            tor->info.trackerCount = tmpInfo.trackerCount;
2577            tmpInfo.trackers = swap.trackers;
2578            tmpInfo.trackerCount = swap.trackerCount;
2579
2580            tr_metainfoFree( &tmpInfo );
2581            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2582        }
2583
2584        /* cleanup */
2585        tr_bencFree( &metainfo );
2586
2587        /* if we had a tracker-related error on this torrent,
2588         * and that tracker's been removed,
2589         * then clear the error */
2590        if(    ( tor->error == TR_STAT_TRACKER_WARNING )
2591            || ( tor->error == TR_STAT_TRACKER_ERROR ) )
2592        {
2593            bool clear = true;
2594
2595            for( i=0; clear && i<trackerCount; ++i )
2596                if( !strcmp( trackers[i].announce, tor->errorTracker ) )
2597                    clear = false;
2598
2599            if( clear )
2600                tr_torrentClearError( tor );
2601        }
2602
2603        /* tell the announcer to reload this torrent's tracker list */
2604        tr_announcerResetTorrent( tor->session->announcer, tor );
2605    }
2606
2607    tr_torrentUnlock( tor );
2608
2609    tr_free( trackers );
2610    return ok;
2611}
2612
2613/**
2614***
2615**/
2616
2617void
2618tr_torrentSetAddedDate( tr_torrent * tor,
2619                        time_t       t )
2620{
2621    assert( tr_isTorrent( tor ) );
2622
2623    tor->addedDate = t;
2624    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2625}
2626
2627void
2628tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2629{
2630    assert( tr_isTorrent( tor ) );
2631
2632    tor->activityDate = t;
2633    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2634}
2635
2636void
2637tr_torrentSetDoneDate( tr_torrent * tor,
2638                       time_t       t )
2639{
2640    assert( tr_isTorrent( tor ) );
2641
2642    tor->doneDate = t;
2643    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2644}
2645
2646/**
2647***
2648**/
2649
2650uint64_t
2651tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2652{
2653    tr_file_index_t i;
2654    uint64_t bytesLeft = 0;
2655
2656    assert( tr_isTorrent( tor ) );
2657
2658    for( i=0; i<tor->info.fileCount; ++i )
2659    {
2660        if( !tor->info.files[i].dnd )
2661        {
2662            struct stat sb;
2663            const uint64_t length = tor->info.files[i].length;
2664            char * path = tr_torrentFindFile( tor, i );
2665
2666            bytesLeft += length;
2667
2668            if( ( path != NULL ) && !stat( path, &sb )
2669                                 && S_ISREG( sb.st_mode )
2670                                 && ( (uint64_t)sb.st_size <= length ) )
2671                bytesLeft -= sb.st_size;
2672
2673            tr_free( path );
2674        }
2675    }
2676
2677    return bytesLeft;
2678}
2679
2680/****
2681*****  Removing the torrent's local data
2682****/
2683
2684static int
2685vstrcmp( const void * a, const void * b )
2686{
2687    return strcmp( a, b );
2688}
2689
2690static int
2691compareLongestFirst( const void * a, const void * b )
2692{
2693    const size_t alen = strlen( a );
2694    const size_t blen = strlen( b );
2695
2696    if( alen != blen )
2697        return alen > blen ? -1 : 1;
2698
2699    return vstrcmp( a, b );
2700}
2701
2702static void
2703addDirtyFile( const char  * root,
2704              const char  * filename,
2705              tr_ptrArray * dirtyFolders )
2706{
2707    char * dir = tr_dirname( filename );
2708
2709    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2710    while (     ( dir != NULL )
2711             && ( strlen( root ) <= strlen( dir ) )
2712             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2713    {
2714        char * tmp;
2715        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2716
2717        tmp = tr_dirname( dir );
2718        tr_free( dir );
2719        dir = tmp;
2720    }
2721
2722    tr_free( dir );
2723}
2724
2725static bool
2726isSystemFile( const char * base )
2727{
2728    int i;
2729    static const char * stockFiles[] = { ".DS_Store", "desktop.ini", "Thumbs.db" };
2730    static const int stockFileCount = sizeof(stockFiles) / sizeof(stockFiles[0]);
2731
2732    for( i=0; i<stockFileCount; ++i )
2733        if( !strcmp( base, stockFiles[i] ) )
2734            return true;
2735
2736    /* check for resource forks. <http://support.apple.com/kb/TA20578> */
2737    if( !memcmp( base, "._", 2 ) )
2738        return true;
2739
2740    return false;
2741}
2742
2743static void
2744deleteLocalFile( const tr_torrent * tor, const char * filename, tr_fileFunc fileFunc )
2745{
2746    struct stat sb;
2747
2748    /* add safeguards for (1) making sure the file exists and
2749       (2) that we haven't somehow walked up past the torrent's top directory... */
2750    if( !stat( filename, &sb ) )
2751        if( !tr_is_same_file( tor->currentDir, filename ) )
2752            fileFunc( filename );
2753}
2754
2755static void
2756walkLocalData( const tr_torrent * tor,
2757               const char       * root,
2758               const char       * dir,
2759               const char       * base,
2760               tr_ptrArray      * torrentFiles,
2761               tr_ptrArray      * folders,
2762               tr_ptrArray      * dirtyFolders,
2763               tr_fileFunc        fileFunc )
2764{
2765    struct stat sb;
2766    char * buf = tr_buildPath( dir, base, NULL );
2767    int i = stat( buf, &sb );
2768
2769    if( !i )
2770    {
2771        DIR * odir = NULL;
2772
2773        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2774        {
2775            struct dirent *d;
2776            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2777            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2778                if( d->d_name && strcmp( d->d_name, "." ) && strcmp( d->d_name, ".." ) )
2779                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders, fileFunc );
2780            closedir( odir );
2781        }
2782        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2783        {
2784            if( isSystemFile( base ) )
2785                deleteLocalFile( tor, buf, fileFunc );
2786            else {
2787                 const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2788                const bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2789                if( !isTorrentFile )
2790                    addDirtyFile( root, buf, dirtyFolders );
2791            }
2792        }
2793    }
2794
2795    tr_free( buf );
2796}
2797
2798static void
2799deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2800{
2801    int i, n;
2802    char * tmp;
2803    char * root;
2804    char ** s;
2805    tr_file_index_t f;
2806    const char * cpch;
2807    const char * firstFile;
2808    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2809    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2810    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2811
2812    if( !tr_torrentHasMetadata( tor ) )
2813        return;
2814
2815    firstFile = tor->info.files[0].name;
2816    cpch = strchr( firstFile, TR_PATH_DELIMITER );
2817    tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2818    root = tr_buildPath( tor->currentDir, tmp, NULL );
2819
2820    for( f=0; f<tor->info.fileCount; ++f ) {
2821        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2822        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2823    }
2824
2825    /* build the set of folders and dirtyFolders */
2826    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders, fileFunc );
2827
2828    /* try to remove entire folders first, so that the recycle bin will be tidy */
2829    s = (char**) tr_ptrArrayPeek( &folders, &n );
2830    for( i=0; i<n; ++i )
2831        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2832            deleteLocalFile( tor, s[i], fileFunc );
2833
2834    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2835    for( i=0, n=tr_ptrArraySize( &torrentFiles ); i<n; ++i ) {
2836        char * path = tr_buildPath( tor->currentDir, tr_ptrArrayNth( &torrentFiles, i ), NULL );
2837        deleteLocalFile( tor, path, fileFunc );
2838        tr_free( path );
2839    }
2840
2841    /* Now clean out the directories left empty from the previous step.
2842     * Work from deepest to shallowest s.t. lower folders
2843     * won't prevent the upper folders from being deleted */
2844    {
2845        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2846        s = (char**) tr_ptrArrayPeek( &folders, &n );
2847        for( i=0; i<n; ++i )
2848            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2849                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2850        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2851        for( i=0; i<n; ++i )
2852            deleteLocalFile( tor, s[i], fileFunc );
2853        tr_ptrArrayDestruct( &cleanFolders, NULL );
2854    }
2855
2856    /* cleanup */
2857    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2858    tr_ptrArrayDestruct( &folders, tr_free );
2859    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2860    tr_free( root );
2861    tr_free( tmp );
2862}
2863
2864static void
2865tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2866{
2867    assert( tr_isTorrent( tor ) );
2868
2869    if( fileFunc == NULL )
2870        fileFunc = remove;
2871
2872    /* close all the files because we're about to delete them */
2873    tr_cacheFlushTorrent( tor->session->cache, tor );
2874    tr_fdTorrentClose( tor->session, tor->uniqueId );
2875
2876    deleteLocalData( tor, fileFunc );
2877}
2878
2879/***
2880****
2881***/
2882
2883struct LocationData
2884{
2885    bool move_from_old_location;
2886    volatile int * setme_state;
2887    volatile double * setme_progress;
2888    char * location;
2889    tr_torrent * tor;
2890};
2891
2892static void
2893setLocation( void * vdata )
2894{
2895    bool err = false;
2896    struct LocationData * data = vdata;
2897    tr_torrent * tor = data->tor;
2898    const bool do_move = data->move_from_old_location;
2899    const char * location = data->location;
2900    double bytesHandled = 0;
2901
2902    assert( tr_isTorrent( tor ) );
2903
2904    tr_dbg( "Moving \"%s\" location from currentDir \"%s\" to \"%s\"",
2905            tr_torrentName(tor), tor->currentDir, location );
2906
2907    tr_mkdirp( location, 0777 );
2908
2909    if( !tr_is_same_file( location, tor->currentDir ) )
2910    {
2911        tr_file_index_t i;
2912
2913        /* bad idea to move files while they're being verified... */
2914        tr_verifyRemove( tor );
2915
2916        /* try to move the files.
2917         * FIXME: there are still all kinds of nasty cases, like what
2918         * if the target directory runs out of space halfway through... */
2919        for( i=0; !err && i<tor->info.fileCount; ++i )
2920        {
2921            const tr_file * f = &tor->info.files[i];
2922            const char * oldbase;
2923            char * sub;
2924            if( tr_torrentFindFile2( tor, i, &oldbase, &sub, NULL ) )
2925            {
2926                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2927                char * newpath = tr_buildPath( location, sub, NULL );
2928
2929                tr_dbg( "Found file #%d: %s", (int)i, oldpath );
2930
2931                if( do_move && !tr_is_same_file( oldpath, newpath ) )
2932                {
2933                    bool renamed = false;
2934                    errno = 0;
2935                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2936                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2937                    {
2938                        err = true;
2939                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2940                                        oldpath, newpath, tr_strerror( errno ) );
2941                    }
2942                }
2943
2944                tr_free( newpath );
2945                tr_free( oldpath );
2946                tr_free( sub );
2947            }
2948
2949            if( data->setme_progress )
2950            {
2951                bytesHandled += f->length;
2952                *data->setme_progress = bytesHandled / tor->info.totalSize;
2953            }
2954        }
2955
2956        if( !err )
2957        {
2958            /* blow away the leftover subdirectories in the old location */
2959            if( do_move )
2960                tr_torrentDeleteLocalData( tor, remove );
2961
2962            /* set the new location and reverify */
2963            tr_torrentSetDownloadDir( tor, location );
2964        }
2965    }
2966
2967    if( !err && do_move )
2968    {
2969        tr_free( tor->incompleteDir );
2970        tor->incompleteDir = NULL;
2971        tor->currentDir = tor->downloadDir;
2972    }
2973
2974    if( data->setme_state )
2975        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2976
2977    /* cleanup */
2978    tr_free( data->location );
2979    tr_free( data );
2980}
2981
2982void
2983tr_torrentSetLocation( tr_torrent       * tor,
2984                       const char       * location,
2985                       bool               move_from_old_location,
2986                       volatile double  * setme_progress,
2987                       volatile int     * setme_state )
2988{
2989    struct LocationData * data;
2990
2991    assert( tr_isTorrent( tor ) );
2992
2993    if( setme_state )
2994        *setme_state = TR_LOC_MOVING;
2995    if( setme_progress )
2996        *setme_progress = 0;
2997
2998    /* run this in the libtransmission thread */
2999    data = tr_new( struct LocationData, 1 );
3000    data->tor = tor;
3001    data->location = tr_strdup( location );
3002    data->move_from_old_location = move_from_old_location;
3003    data->setme_state = setme_state;
3004    data->setme_progress = setme_progress;
3005    tr_runInEventThread( tor->session, setLocation, data );
3006}
3007
3008/***
3009****
3010***/
3011
3012void
3013tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
3014{
3015    char * sub;
3016    const char * base;
3017    const tr_info * inf = &tor->info;
3018    const tr_file * f = &inf->files[fileNum];
3019    tr_piece * p;
3020    const tr_piece * pend;
3021    const time_t now = tr_time( );
3022
3023    /* close the file so that we can reopen in read-only mode as needed */
3024    tr_fdFileClose( tor->session, tor, fileNum );
3025
3026    /* now that the file is complete and closed, we can start watching its
3027     * mtime timestamp for changes to know if we need to reverify pieces */
3028    for( p=&inf->pieces[f->firstPiece], pend=&inf->pieces[f->lastPiece]; p!=pend; ++p )
3029        p->timeChecked = now;
3030
3031    /* if the torrent's current filename isn't the same as the one in the
3032     * metadata -- for example, if it had the ".part" suffix appended to
3033     * it until now -- then rename it to match the one in the metadata */
3034    if( tr_torrentFindFile2( tor, fileNum, &base, &sub, NULL ) )
3035    {
3036        if( strcmp( sub, f->name ) )
3037        {
3038            char * oldpath = tr_buildPath( base, sub, NULL );
3039            char * newpath = tr_buildPath( base, f->name, NULL );
3040
3041            if( rename( oldpath, newpath ) )
3042                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
3043
3044            tr_free( newpath );
3045            tr_free( oldpath );
3046        }
3047
3048        tr_free( sub );
3049    }
3050}
3051
3052/***
3053****
3054***/
3055
3056#ifdef SYS_DARWIN
3057 #define TR_STAT_MTIME(sb) ((sb).st_mtimespec.tv_sec)
3058#else
3059 #define TR_STAT_MTIME(sb) ((sb).st_mtime)
3060#endif
3061
3062
3063static bool
3064fileExists( const char * filename, time_t * mtime )
3065{
3066    struct stat sb;
3067    const bool ok = !stat( filename, &sb );
3068
3069    if( ok && ( mtime != NULL ) )
3070        *mtime = TR_STAT_MTIME( sb );
3071
3072    return ok;
3073}
3074
3075bool
3076tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
3077                     const char ** base, char ** subpath, time_t * mtime )
3078{
3079    char * part = NULL;
3080    const tr_file * file;
3081    const char * b = NULL;
3082    const char * s = NULL;
3083
3084    assert( tr_isTorrent( tor ) );
3085    assert( fileNum < tor->info.fileCount );
3086
3087    file = &tor->info.files[fileNum];
3088
3089    if( b == NULL ) {
3090        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
3091        if( fileExists( filename, mtime ) ) {
3092            b = tor->downloadDir;
3093            s = file->name;
3094        }
3095        tr_free( filename );
3096    }
3097
3098    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
3099        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
3100        if( fileExists( filename, mtime ) ) {
3101            b = tor->incompleteDir;
3102            s = file->name;
3103        }
3104        tr_free( filename );
3105    }
3106
3107    if( b == NULL )
3108        part = tr_torrentBuildPartial( tor, fileNum );
3109
3110    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
3111        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
3112        if( fileExists( filename, mtime ) ) {
3113            b = tor->incompleteDir;
3114            s = part;
3115        }
3116        tr_free( filename );
3117    }
3118
3119    if( b == NULL) {
3120        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
3121        if( fileExists( filename, mtime ) ) {
3122            b = tor->downloadDir;
3123            s = part;
3124        }
3125        tr_free( filename );
3126    }
3127
3128    if( base != NULL )
3129        *base = b;
3130    if( subpath != NULL )
3131        *subpath = tr_strdup( s );
3132
3133    tr_free( part );
3134    return b != NULL;
3135}
3136
3137char*
3138tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
3139{
3140    char * subpath;
3141    char * ret = NULL;
3142    const char * base;
3143
3144    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath, NULL ) )
3145    {
3146        ret = tr_buildPath( base, subpath, NULL );
3147        tr_free( subpath );
3148    }
3149
3150    return ret;
3151}
3152
3153/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
3154static void
3155refreshCurrentDir( tr_torrent * tor )
3156{
3157    const char * dir = NULL;
3158
3159    if( tor->incompleteDir == NULL )
3160        dir = tor->downloadDir;
3161    else if( !tr_torrentHasMetadata( tor ) ) /* no files to find */
3162        dir = tor->incompleteDir;
3163    else if( !tr_torrentFindFile2( tor, 0, &dir, NULL, NULL ) )
3164        dir = tor->incompleteDir;
3165
3166    assert( dir != NULL );
3167    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
3168    tor->currentDir = dir;
3169}
3170
3171char*
3172tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
3173{
3174    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
3175}
3176
3177/***
3178****
3179***/
3180
3181static int
3182compareTorrentByQueuePosition( const void * va, const void * vb )
3183{
3184    const tr_torrent * a = * (const tr_torrent **) va;
3185    const tr_torrent * b = * (const tr_torrent **) vb;
3186
3187    return a->queuePosition - b->queuePosition;
3188}
3189
3190#ifndef NDEBUG
3191static bool
3192queueIsSequenced( tr_session * session )
3193{
3194    int i ;
3195    int n ;
3196    bool is_sequenced = true;
3197    tr_torrent * tor;
3198    tr_torrent ** tmp = tr_new( tr_torrent *, session->torrentCount );
3199
3200    /* get all the torrents */
3201    n = 0;
3202    tor = NULL;
3203    while(( tor = tr_torrentNext( session, tor )))
3204        tmp[n++] = tor;
3205
3206    /* sort them by position */
3207    qsort( tmp, n, sizeof( tr_torrent * ), compareTorrentByQueuePosition );
3208
3209#if 0
3210    fprintf( stderr, "%s", "queue: " );
3211    for( i=0; i<n; ++i )
3212        fprintf( stderr, "%d ", tmp[i]->queuePosition );
3213    fputc( '\n', stderr );
3214#endif
3215
3216    /* test them */
3217    for( i=0; is_sequenced && i<n; ++i )
3218        if( tmp[i]->queuePosition != i )
3219            is_sequenced = false;
3220
3221    tr_free( tmp );
3222    return is_sequenced;
3223}
3224#endif
3225
3226int
3227tr_torrentGetQueuePosition( const tr_torrent * tor )
3228{
3229    return tor->queuePosition;
3230}
3231
3232void
3233tr_torrentSetQueuePosition( tr_torrent * tor, int pos )
3234{
3235    int back = -1;
3236    tr_torrent * walk;
3237    const int old_pos = tor->queuePosition;
3238    const time_t now = tr_time( );
3239
3240    if( pos < 0 )
3241        pos = 0;
3242
3243    tor->queuePosition = -1;
3244
3245    walk = NULL;
3246    while(( walk = tr_torrentNext( tor->session, walk )))
3247    {
3248        if( old_pos < pos ) {
3249            if( ( old_pos <= walk->queuePosition ) && ( walk->queuePosition <= pos ) ) {
3250                walk->queuePosition--;
3251                walk->anyDate = now;
3252            }
3253        }
3254
3255        if( old_pos > pos ) {
3256            if( ( pos <= walk->queuePosition ) && ( walk->queuePosition < old_pos ) ) {
3257                walk->queuePosition++;
3258                walk->anyDate = now;
3259            }
3260        }
3261
3262        if( back < walk->queuePosition )
3263            back = walk->queuePosition;
3264    }
3265
3266    tor->queuePosition = MIN( pos, (back+1) );
3267    tor->anyDate = now;
3268
3269    assert( queueIsSequenced( tor->session ) );
3270}
3271
3272void
3273tr_torrentsQueueMoveTop( tr_torrent ** torrents_in, int n )
3274{
3275    int i;
3276    tr_torrent ** torrents = tr_memdup( torrents_in, sizeof( tr_torrent * ) * n );
3277    qsort( torrents, n, sizeof( tr_torrent * ), compareTorrentByQueuePosition );
3278    for( i=n-1; i>=0; --i )
3279        tr_torrentSetQueuePosition( torrents[i], 0 );
3280    tr_free( torrents );
3281}
3282
3283void
3284tr_torrentsQueueMoveUp( tr_torrent ** torrents_in, int n )
3285{
3286    int i;
3287    tr_torrent ** torrents = tr_memdup( torrents_in, sizeof( tr_torrent * ) * n );
3288    qsort( torrents, n, sizeof( tr_torrent * ), compareTorrentByQueuePosition );
3289    for( i=0; i<n; ++i )
3290        tr_torrentSetQueuePosition( torrents[i], torrents[i]->queuePosition - 1 );
3291    tr_free( torrents );
3292}
3293
3294void
3295tr_torrentsQueueMoveDown( tr_torrent ** torrents_in, int n )
3296{
3297    int i;
3298    tr_torrent ** torrents = tr_memdup( torrents_in, sizeof( tr_torrent * ) * n );
3299    qsort( torrents, n, sizeof( tr_torrent * ), compareTorrentByQueuePosition );
3300    for( i=n-1; i>=0; --i )
3301        tr_torrentSetQueuePosition( torrents[i], torrents[i]->queuePosition + 1 );
3302    tr_free( torrents );
3303}
3304
3305void
3306tr_torrentsQueueMoveBottom( tr_torrent ** torrents_in, int n )
3307{
3308    int i;
3309    tr_torrent ** torrents = tr_memdup( torrents_in, sizeof( tr_torrent * ) * n );
3310    qsort( torrents, n, sizeof( tr_torrent * ), compareTorrentByQueuePosition );
3311    for( i=0; i<n; ++i )
3312        tr_torrentSetQueuePosition( torrents[i], INT_MAX );
3313    tr_free( torrents );
3314}
3315
3316static void
3317torrentSetQueued( tr_torrent * tor, bool queued )
3318{
3319    assert( tr_isTorrent( tor ) );
3320    assert( tr_isBool( queued ) );
3321
3322    if( tr_torrentIsQueued( tor ) != queued )
3323    {
3324        tor->isQueued = queued;
3325        tor->anyDate = tr_time( );
3326    }
3327}
3328
3329void
3330tr_torrentSetQueueStartCallback( tr_torrent * torrent, void (*callback)( tr_torrent *, void * ), void * user_data )
3331{
3332    torrent->queue_started_callback = callback;
3333    torrent->queue_started_user_data = user_data;
3334}
3335
3336
Note: See TracBrowser for help on using the repository browser.