source: trunk/libtransmission/torrent.c @ 11987

Last change on this file since 11987 was 11987, checked in by jordan, 11 years ago

(trunk libT) mark the two "progress" args to tr_torrentSetLocation() as volatile.

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