source: trunk/libtransmission/torrent.c @ 11750

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

(trunk libT) #3933 "announcer.c peer parsing could be simpler" -- fixed.

Remove redundant code by using tr_peerMgrCompactToPex() and tr_peerMgrCompact6ToPex() to parse compact ipv4 and ipv6 peer lists. Simplify the old-style benc peer list parsing and fix a bug that returned too few bytes in the old-style peer array.

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