source: trunk/libtransmission/torrent.c @ 11606

Last change on this file since 11606 was 11606, checked in by charles, 11 years ago

(trunk, libT) #2955 "jit verify" -- shorten the error message for torrents whose files disappeared.

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