source: trunk/libtransmission/torrent.c @ 11704

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

code cleanup for tr_peerMgrTorrentAvailability().

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