source: trunk/libtransmission/torrent.c @ 12057

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

(trunk libT) #4073 "suggest inclusion of <signal.h> in torrent.c" -- done.

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