source: trunk/libtransmission/torrent.c @ 12177

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

(trunk) it's bad form to #include so many system headers in libtransmission/utils.h...

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