source: trunk/libtransmission/torrent.c @ 11543

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

(trunk libT) #2955 "lazy torrent verification" -- speed up setLocalErrorIfFilesDisappeared(). this makes a big difference when loading a lot of torrents on startup.

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