source: trunk/libtransmission/torrent.c @ 13469

Last change on this file since 13469 was 13469, checked in by livings124, 10 years ago

Revert r13468 for now.

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