source: trunk/libtransmission/torrent.c @ 9274

Last change on this file since 9274 was 9274, checked in by charles, 13 years ago

(trunk libT) #2489: tr_torrentSetAnnounceList() should check for invalid and duplicate announce URLs

  • Property svn:keywords set to Date Rev Author Id
File size: 64.2 KB
Line 
1/*
2 * This file Copyright (C) 2009 Charles Kerr <charles@transmissionbt.com>
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 9274 2009-10-10 19:16:21Z charles $
11 */
12
13#include <sys/types.h> /* stat */
14#include <sys/stat.h> /* stat */
15#include <unistd.h> /* stat */
16#include <dirent.h>
17
18#include <assert.h>
19#include <limits.h> /* INT_MAX */
20#include <math.h> /* fabs */
21#include <stdarg.h>
22#include <string.h> /* memcmp */
23#include <stdlib.h> /* qsort */
24
25#include <event.h> /* evbuffer */
26
27#include "transmission.h"
28#include "announcer.h"
29#include "bandwidth.h"
30#include "bencode.h"
31#include "completion.h"
32#include "crypto.h" /* for tr_sha1 */
33#include "resume.h"
34#include "fdlimit.h" /* tr_fdTorrentClose */
35#include "metainfo.h"
36#include "peer-mgr.h"
37#include "platform.h" /* TR_PATH_DELIMITER_STR */
38#include "ptrarray.h"
39#include "ratecontrol.h"
40#include "session.h"
41#include "torrent.h"
42#include "trevent.h"
43#include "utils.h"
44#include "verify.h"
45
46#define MAX_BLOCK_SIZE ( 1024 * 16 )
47
48/***
49****
50***/
51
52int
53tr_torrentId( const tr_torrent * tor )
54{
55    return tor->uniqueId;
56}
57
58tr_torrent*
59tr_torrentFindFromId( tr_session * session, int id )
60{
61    tr_torrent * tor = NULL;
62
63    while(( tor = tr_torrentNext( session, tor )))
64        if( tor->uniqueId == id )
65            return tor;
66
67    return NULL;
68}
69
70tr_torrent*
71tr_torrentFindFromHashString( tr_session *  session, const char * str )
72{
73    tr_torrent * tor = NULL;
74
75    while(( tor = tr_torrentNext( session, tor )))
76        if( !strcmp( str, tor->info.hashString ) )
77            return tor;
78
79    return NULL;
80}
81
82tr_torrent*
83tr_torrentFindFromHash( tr_session * session, const uint8_t * torrentHash )
84{
85    tr_torrent * tor = NULL;
86
87    while(( tor = tr_torrentNext( session, tor )))
88        if( *tor->info.hash == *torrentHash )
89            if( !memcmp( tor->info.hash, torrentHash, SHA_DIGEST_LENGTH ) )
90                return tor;
91
92    return NULL;
93}
94
95tr_torrent*
96tr_torrentFindFromObfuscatedHash( tr_session * session,
97                                  const uint8_t * obfuscatedTorrentHash )
98{
99    tr_torrent * tor = NULL;
100
101    while(( tor = tr_torrentNext( session, tor )))
102        if( !memcmp( tor->obfuscatedHash, obfuscatedTorrentHash,
103                     SHA_DIGEST_LENGTH ) )
104            return tor;
105
106    return NULL;
107}
108
109/***
110****  PER-TORRENT UL / DL SPEEDS
111***/
112
113void
114tr_torrentSetSpeedLimit( tr_torrent * tor, tr_direction dir, int KiB_sec )
115{
116    assert( tr_isTorrent( tor ) );
117    assert( tr_isDirection( dir ) );
118
119    if( tr_bandwidthSetDesiredSpeed( tor->bandwidth, dir, KiB_sec ) )
120        tr_torrentSetDirty( tor );
121}
122
123int
124tr_torrentGetSpeedLimit( const tr_torrent * tor, tr_direction dir )
125{
126    assert( tr_isTorrent( tor ) );
127    assert( tr_isDirection( dir ) );
128
129    return tr_bandwidthGetDesiredSpeed( tor->bandwidth, dir );
130}
131
132void
133tr_torrentUseSpeedLimit( tr_torrent * tor, tr_direction dir, tr_bool do_use )
134{
135    assert( tr_isTorrent( tor ) );
136    assert( tr_isDirection( dir ) );
137
138    if( tr_bandwidthSetLimited( tor->bandwidth, dir, do_use ) )
139        tr_torrentSetDirty( tor );
140}
141
142tr_bool
143tr_torrentUsesSpeedLimit( const tr_torrent * tor, tr_direction dir )
144{
145    assert( tr_isTorrent( tor ) );
146    assert( tr_isDirection( dir ) );
147
148    return tr_bandwidthIsLimited( tor->bandwidth, dir );
149}
150
151void
152tr_torrentUseSessionLimits( tr_torrent * tor, tr_bool doUse )
153{
154    tr_bool changed;
155
156    assert( tr_isTorrent( tor ) );
157
158    changed = tr_bandwidthHonorParentLimits( tor->bandwidth, TR_UP, doUse );
159    changed |= tr_bandwidthHonorParentLimits( tor->bandwidth, TR_DOWN, doUse );
160
161    if( changed )
162        tr_torrentSetDirty( tor );
163}
164
165tr_bool
166tr_torrentUsesSessionLimits( const tr_torrent * tor )
167{
168    assert( tr_isTorrent( tor ) );
169
170    return tr_bandwidthAreParentLimitsHonored( tor->bandwidth, TR_UP );
171}
172
173/***
174****
175***/
176
177void
178tr_torrentSetRatioMode( tr_torrent *  tor, tr_ratiolimit mode )
179{
180    assert( tr_isTorrent( tor ) );
181    assert( mode==TR_RATIOLIMIT_GLOBAL || mode==TR_RATIOLIMIT_SINGLE || mode==TR_RATIOLIMIT_UNLIMITED  );
182
183    if( mode != tor->ratioLimitMode )
184    {
185        tor->ratioLimitMode = mode;
186        tor->needsSeedRatioCheck = TRUE;
187
188        tr_torrentSetDirty( tor );
189    }
190}
191
192tr_ratiolimit
193tr_torrentGetRatioMode( const tr_torrent * tor )
194{
195    assert( tr_isTorrent( tor ) );
196
197    return tor->ratioLimitMode;
198}
199
200void
201tr_torrentSetRatioLimit( tr_torrent * tor, double desiredRatio )
202{
203    assert( tr_isTorrent( tor ) );
204
205    if( (int)(desiredRatio*100.0) != (int)(tor->desiredRatio*100.0) )
206    {
207        tor->desiredRatio = desiredRatio;
208
209        tor->needsSeedRatioCheck = TRUE;
210
211        tr_torrentSetDirty( tor );
212    }
213}
214
215double
216tr_torrentGetRatioLimit( const tr_torrent * tor )
217{
218    assert( tr_isTorrent( tor ) );
219
220    return tor->desiredRatio;
221}
222
223tr_bool
224tr_torrentIsPieceTransferAllowed( const tr_torrent  * tor,
225                                  tr_direction        direction )
226{
227    int limit;
228    tr_bool allowed = TRUE;
229
230    if( tr_torrentUsesSpeedLimit( tor, direction ) )
231        if( tr_torrentGetSpeedLimit( tor, direction ) <= 0 )
232            allowed = FALSE;
233
234    if( tr_torrentUsesSessionLimits( tor ) )
235        if( tr_sessionGetActiveSpeedLimit( tor->session, direction, &limit ) )
236            if( limit <= 0 )
237                allowed = FALSE;
238
239    return allowed;
240}
241
242tr_bool
243tr_torrentGetSeedRatio( const tr_torrent * tor, double * ratio )
244{
245    tr_bool isLimited;
246
247    switch( tr_torrentGetRatioMode( tor ) )
248    {
249        case TR_RATIOLIMIT_SINGLE:
250            isLimited = TRUE;
251            if( ratio )
252                *ratio = tr_torrentGetRatioLimit( tor );
253            break;
254
255        case TR_RATIOLIMIT_GLOBAL:
256            isLimited = tr_sessionIsRatioLimited( tor->session );
257            if( isLimited && ratio )
258                *ratio = tr_sessionGetRatioLimit( tor->session );
259            break;
260
261        default: /* TR_RATIOLIMIT_UNLIMITED */
262            isLimited = FALSE;
263            break;
264    }
265
266    return isLimited;
267}
268
269/***
270****
271***/
272
273void
274tr_torrentSetLocalError( tr_torrent * tor, const char * fmt, ... )
275{
276    va_list ap;
277
278    assert( tr_isTorrent( tor ) );
279
280    va_start( ap, fmt );
281    tor->error = TR_STAT_LOCAL_ERROR;
282    evutil_vsnprintf( tor->errorString, sizeof( tor->errorString ), fmt, ap );
283    va_end( ap );
284}
285
286static void
287onTrackerResponse( void * tracker UNUSED,
288                   void * vevent,
289                   void * user_data )
290{
291    tr_torrent *       tor = user_data;
292    tr_tracker_event * event = vevent;
293
294    switch( event->messageType )
295    {
296        case TR_TRACKER_PEERS:
297        {
298            size_t   i, n;
299            tr_pex * pex = tr_peerMgrArrayToPex( event->compact,
300                                                 event->compactLen, &n );
301             if( event->allAreSeeds )
302                tr_tordbg( tor, "Got %d seeds from tracker", (int)n );
303            else
304                tr_torinf( tor, _( "Got %d peers from tracker" ), (int)n );
305
306            for( i = 0; i < n; ++i )
307            {
308                if( event->allAreSeeds )
309                    pex[i].flags |= ADDED_F_SEED_FLAG;
310                tr_peerMgrAddPex( tor, TR_PEER_FROM_TRACKER, pex + i );
311            }
312
313            tr_free( pex );
314            break;
315        }
316
317        case TR_TRACKER_WARNING:
318            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
319            tor->error = TR_STAT_TRACKER_WARNING;
320            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
321            break;
322
323        case TR_TRACKER_ERROR:
324            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
325            tor->error = TR_STAT_TRACKER_ERROR;
326            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
327            break;
328
329        case TR_TRACKER_ERROR_CLEAR:
330            tor->error = TR_STAT_OK;
331            tor->errorString[0] = '\0';
332            break;
333    }
334}
335
336/***
337****
338****  TORRENT INSTANTIATION
339****
340***/
341
342static int
343getBytePiece( const tr_info * info,
344              uint64_t        byteOffset )
345{
346    assert( info );
347    assert( info->pieceSize != 0 );
348
349    return byteOffset / info->pieceSize;
350}
351
352static void
353initFilePieces( tr_info *       info,
354                tr_file_index_t fileIndex )
355{
356    tr_file * file;
357    uint64_t  firstByte, lastByte;
358
359    assert( info );
360    assert( fileIndex < info->fileCount );
361
362    file = &info->files[fileIndex];
363    firstByte = file->offset;
364    lastByte = firstByte + ( file->length ? file->length - 1 : 0 );
365    file->firstPiece = getBytePiece( info, firstByte );
366    file->lastPiece = getBytePiece( info, lastByte );
367}
368
369static int
370pieceHasFile( tr_piece_index_t piece,
371              const tr_file *  file )
372{
373    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
374}
375
376static tr_priority_t
377calculatePiecePriority( const tr_torrent * tor,
378                        tr_piece_index_t   piece,
379                        int                fileHint )
380{
381    tr_file_index_t i;
382    int             priority = TR_PRI_LOW;
383
384    /* find the first file that has data in this piece */
385    if( fileHint >= 0 ) {
386        i = fileHint;
387        while( i > 0 && pieceHasFile( piece, &tor->info.files[i - 1] ) )
388            --i;
389    } else {
390        for( i = 0; i < tor->info.fileCount; ++i )
391            if( pieceHasFile( piece, &tor->info.files[i] ) )
392                break;
393    }
394
395    /* the piece's priority is the max of the priorities
396     * of all the files in that piece */
397    for( ; i < tor->info.fileCount; ++i )
398    {
399        const tr_file * file = &tor->info.files[i];
400
401        if( !pieceHasFile( piece, file ) )
402            break;
403
404        priority = MAX( priority, file->priority );
405
406        /* when dealing with multimedia files, getting the first and
407           last pieces can sometimes allow you to preview it a bit
408           before it's fully downloaded... */
409        if( file->priority >= TR_PRI_NORMAL )
410            if( file->firstPiece == piece || file->lastPiece == piece )
411                priority = TR_PRI_HIGH;
412    }
413
414    return priority;
415}
416
417static void
418tr_torrentInitFilePieces( tr_torrent * tor )
419{
420    tr_file_index_t  f;
421    tr_piece_index_t p;
422    uint64_t offset = 0;
423    tr_info * inf = &tor->info;
424    int * firstFiles;
425
426    /* assign the file offsets */
427    for( f=0; f<inf->fileCount; ++f ) {
428        inf->files[f].offset = offset;
429        offset += inf->files[f].length;
430        initFilePieces( inf, f );
431    }
432
433    /* build the array of first-file hints to give calculatePiecePriority */
434    firstFiles = tr_new( int, inf->pieceCount );
435    for( p=f=0; p<inf->pieceCount; ++p ) {
436        while( inf->files[f].lastPiece < p )
437            ++f;
438        firstFiles[p] = f;
439    }
440
441#if 0
442    /* test to confirm the first-file hints are correct */
443    for( p=0; p<inf->pieceCount; ++p ) {
444        f = firstFiles[p];
445        assert( inf->files[f].firstPiece <= p );
446        assert( inf->files[f].lastPiece >= p );
447        if( f > 0 )
448            assert( inf->files[f-1].lastPiece < p );
449        for( f=0; f<inf->fileCount; ++f )
450            if( pieceHasFile( p, &inf->files[f] ) )
451                break;
452        assert( (int)f == firstFiles[p] );
453    }
454#endif
455
456    for( p=0; p<inf->pieceCount; ++p )
457        inf->pieces[p].priority = calculatePiecePriority( tor, p, firstFiles[p] );
458
459    tr_free( firstFiles );
460}
461
462int
463tr_torrentPromoteTracker( tr_torrent * tor,
464                          int          pos )
465{
466    int i;
467    int tier;
468
469    assert( tor );
470    assert( ( 0 <= pos ) && ( pos < tor->info.trackerCount ) );
471
472    /* the tier of the tracker we're promoting */
473    tier = tor->info.trackers[pos].tier;
474
475    /* find the index of that tier's first tracker */
476    for( i = 0; i < tor->info.trackerCount; ++i )
477        if( tor->info.trackers[i].tier == tier )
478            break;
479
480    assert( i < tor->info.trackerCount );
481
482    /* promote the tracker at `pos' to the front of the tier */
483    if( i != pos )
484    {
485        const tr_tracker_info tmp = tor->info.trackers[i];
486        tor->info.trackers[i] = tor->info.trackers[pos];
487        tor->info.trackers[pos] = tmp;
488    }
489
490    /* return the new position of the tracker that started out at [pos] */
491    return i;
492}
493
494struct RandomTracker
495{
496    tr_tracker_info    tracker;
497    int                random_value;
498};
499
500/* the tiers will be sorted from lowest to highest,
501 * and trackers are randomized within the tiers */
502static TR_INLINE int
503compareRandomTracker( const void * va,
504                      const void * vb )
505{
506    const struct RandomTracker * a = va;
507    const struct RandomTracker * b = vb;
508
509    if( a->tracker.tier != b->tracker.tier )
510        return a->tracker.tier - b->tracker.tier;
511
512    return a->random_value - b->random_value;
513}
514
515static void
516randomizeTiers( tr_info * info )
517{
518    int                    i;
519    const int              n = info->trackerCount;
520    struct RandomTracker * r = tr_new0( struct RandomTracker, n );
521
522    for( i = 0; i < n; ++i )
523    {
524        r[i].tracker = info->trackers[i];
525        r[i].random_value = tr_cryptoRandInt( INT_MAX );
526    }
527    qsort( r, n, sizeof( struct RandomTracker ), compareRandomTracker );
528    for( i = 0; i < n; ++i )
529        info->trackers[i] = r[i].tracker;
530    tr_free( r );
531}
532
533static void torrentStart( tr_torrent * tor );
534
535/**
536 * Decide on a block size.  constraints:
537 * (1) most clients decline requests over 16 KiB
538 * (2) pieceSize must be a multiple of block size
539 */
540static uint32_t
541getBlockSize( uint32_t pieceSize )
542{
543    uint32_t b = pieceSize;
544
545    while( b > MAX_BLOCK_SIZE )
546        b /= 2u;
547
548    if( !b || ( pieceSize % b ) ) /* not cleanly divisible */
549        return 0;
550    return b;
551}
552
553static void
554torrentRealInit( tr_torrent * tor, const tr_ctor * ctor )
555{
556    int          doStart;
557    uint64_t     loaded;
558    uint64_t     t;
559    const char * dir;
560    static int   nextUniqueId = 1;
561    tr_info    * info = &tor->info;
562    tr_session * session = tr_ctorGetSession( ctor );
563
564    assert( session != NULL );
565
566    tr_globalLock( session );
567
568    tor->session   = session;
569    tor->uniqueId = nextUniqueId++;
570    tor->magicNumber = TORRENT_MAGIC_NUMBER;
571
572    randomizeTiers( info );
573
574    tor->bandwidth = tr_bandwidthNew( session, session->bandwidth );
575
576    tor->blockSize = getBlockSize( info->pieceSize );
577
578    if( !tr_ctorGetDownloadDir( ctor, TR_FORCE, &dir ) ||
579        !tr_ctorGetDownloadDir( ctor, TR_FALLBACK, &dir ) )
580            tor->downloadDir = tr_strdup( dir );
581
582    tor->lastPieceSize = info->totalSize % info->pieceSize;
583
584    if( !tor->lastPieceSize )
585        tor->lastPieceSize = info->pieceSize;
586
587    tor->lastBlockSize = info->totalSize % tor->blockSize;
588
589    if( !tor->lastBlockSize )
590        tor->lastBlockSize = tor->blockSize;
591
592    tor->blockCount =
593        ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize;
594
595    tor->blockCountInPiece =
596        info->pieceSize / tor->blockSize;
597
598    tor->blockCountInLastPiece =
599        ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize;
600
601    /* check our work */
602    assert( ( info->pieceSize % tor->blockSize ) == 0 );
603    t = info->pieceCount - 1;
604    t *= info->pieceSize;
605    t += tor->lastPieceSize;
606    assert( t == info->totalSize );
607    t = tor->blockCount - 1;
608    t *= tor->blockSize;
609    t += tor->lastBlockSize;
610    assert( t == info->totalSize );
611    t = info->pieceCount - 1;
612    t *= tor->blockCountInPiece;
613    t += tor->blockCountInLastPiece;
614    assert( t == (uint64_t)tor->blockCount );
615
616    tr_cpConstruct( &tor->completion, tor );
617
618    tr_torrentInitFilePieces( tor );
619
620    tr_rcConstruct( &tor->swarmSpeed );
621
622    tr_sha1( tor->obfuscatedHash, "req2", 4,
623             info->hash, SHA_DIGEST_LENGTH,
624             NULL );
625
626    tr_peerMgrAddTorrent( session->peerMgr, tor );
627
628    assert( !tor->downloadedCur );
629    assert( !tor->uploadedCur );
630
631    tr_ctorInitTorrentPriorities( ctor, tor );
632
633    tr_ctorInitTorrentWanted( ctor, tor );
634
635    tor->error = TR_STAT_OK;
636
637    tr_bitfieldConstruct( &tor->checkedPieces, tor->info.pieceCount );
638    tr_torrentUncheck( tor );
639
640    tr_torrentSetAddedDate( tor, time( NULL ) ); /* this is a default value to be
641                                                    overwritten by the resume file */
642
643    loaded = tr_torrentLoadResume( tor, ~0, ctor );
644
645    doStart = tor->isRunning;
646    tor->isRunning = 0;
647
648    if( !( loaded & TR_FR_SPEEDLIMIT ) )
649    {
650        tr_torrentUseSpeedLimit( tor, TR_UP, FALSE );
651        tr_torrentSetSpeedLimit( tor, TR_UP, tr_sessionGetSpeedLimit( tor->session, TR_UP ) );
652        tr_torrentUseSpeedLimit( tor, TR_DOWN, FALSE );
653        tr_torrentSetSpeedLimit( tor, TR_DOWN, tr_sessionGetSpeedLimit( tor->session, TR_DOWN ) );
654        tr_torrentUseSessionLimits( tor, TRUE );
655    }
656
657    if( !( loaded & TR_FR_RATIOLIMIT ) )
658    {
659        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_GLOBAL );
660        tr_torrentSetRatioLimit( tor, tr_sessionGetRatioLimit( tor->session ) );
661    }
662
663    tor->completeness = tr_cpGetStatus( &tor->completion );
664
665    {
666        tr_torrent * it = NULL;
667        tr_torrent * last = NULL;
668        while( ( it = tr_torrentNext( session, it ) ) )
669            last = it;
670
671        if( !last )
672            session->torrentList = tor;
673        else
674            last->next = tor;
675        ++session->torrentCount;
676    }
677
678    tr_globalUnlock( session );
679
680    /* maybe save our own copy of the metainfo */
681    if( tr_ctorGetSave( ctor ) )
682    {
683        const tr_benc * val;
684        if( !tr_ctorGetMetainfo( ctor, &val ) )
685        {
686            const char * filename = tor->info.torrent;
687            tr_bencToFile( val, TR_FMT_BENC, filename );
688            tr_sessionSetTorrentFile( tor->session, tor->info.hashString, filename );
689        }
690    }
691
692    tor->tiers = tr_announcerAddTorrent( session->announcer, tor );
693    tor->tiersSubscription = tr_announcerSubscribe( tor->tiers, onTrackerResponse, tor );
694
695    tr_metainfoMigrate( session, &tor->info );
696
697    if( doStart )
698        torrentStart( tor );
699}
700
701tr_parse_result
702tr_torrentParse( const tr_ctor * ctor, tr_info * setmeInfo )
703{
704    int             doFree;
705    tr_bool         didParse;
706    tr_info         tmp;
707    const tr_benc * metainfo;
708    tr_session    * session = tr_ctorGetSession( ctor );
709    tr_parse_result result = TR_PARSE_OK;
710
711    if( setmeInfo == NULL )
712        setmeInfo = &tmp;
713    memset( setmeInfo, 0, sizeof( tr_info ) );
714
715    if( tr_ctorGetMetainfo( ctor, &metainfo ) )
716        return TR_PARSE_ERR;
717
718    didParse = tr_metainfoParse( session, setmeInfo, metainfo );
719    doFree = didParse && ( setmeInfo == &tmp );
720
721    if( !didParse )
722        result = TR_PARSE_ERR;
723
724    if( didParse && !getBlockSize( setmeInfo->pieceSize ) )
725        result = TR_PARSE_ERR;
726
727    if( didParse && session && tr_torrentExists( session, setmeInfo->hash ) )
728        result = TR_PARSE_DUPLICATE;
729
730    if( doFree )
731        tr_metainfoFree( setmeInfo );
732
733    return result;
734}
735
736tr_torrent *
737tr_torrentNew( const tr_ctor  * ctor,
738               int            * setmeError )
739{
740    int          err;
741    tr_info      tmpInfo;
742    tr_torrent * tor = NULL;
743
744    assert( ctor != NULL );
745    assert( tr_isSession( tr_ctorGetSession( ctor ) ) );
746
747    err = tr_torrentParse( ctor, &tmpInfo );
748    if( !err )
749    {
750        tor = tr_new0( tr_torrent, 1 );
751        tor->info = tmpInfo;
752        torrentRealInit( tor, ctor );
753    }
754    else if( setmeError )
755    {
756        *setmeError = err;
757    }
758
759    return tor;
760}
761
762/**
763***
764**/
765
766void
767tr_torrentSetDownloadDir( tr_torrent * tor, const char * path )
768{
769    assert( tr_isTorrent( tor  ) );
770
771    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
772    {
773        tr_free( tor->downloadDir );
774        tor->downloadDir = tr_strdup( path );
775        tr_torrentSetDirty( tor );
776    }
777}
778
779const char*
780tr_torrentGetDownloadDir( const tr_torrent * tor )
781{
782    assert( tr_isTorrent( tor  ) );
783
784    return tor->downloadDir;
785}
786
787void
788tr_torrentChangeMyPort( tr_torrent * tor )
789{
790    assert( tr_isTorrent( tor  ) );
791
792    tr_announcerChangeMyPort( tor );
793}
794
795static TR_INLINE void
796tr_torrentManualUpdateImpl( void * vtor )
797{
798    tr_torrent * tor = vtor;
799
800    assert( tr_isTorrent( tor  ) );
801
802    if( tor->isRunning )
803        tr_announcerManualAnnounce( tor );
804}
805
806void
807tr_torrentManualUpdate( tr_torrent * tor )
808{
809    assert( tr_isTorrent( tor  ) );
810
811    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
812}
813
814tr_bool
815tr_torrentCanManualUpdate( const tr_torrent * tor )
816{
817    return ( tr_isTorrent( tor  ) )
818        && ( tor->isRunning )
819        && ( tr_announcerCanManualAnnounce( tor ) );
820}
821
822const tr_info *
823tr_torrentInfo( const tr_torrent * tor )
824{
825    return tr_isTorrent( tor ) ? &tor->info : NULL;
826}
827
828const tr_stat *
829tr_torrentStatCached( tr_torrent * tor )
830{
831    const time_t now = time( NULL );
832
833    return tr_isTorrent( tor ) && ( now == tor->lastStatTime )
834         ? &tor->stats
835         : tr_torrentStat( tor );
836}
837
838void
839tr_torrentSetVerifyState( tr_torrent * tor, tr_verify_state state )
840{
841    assert( tr_isTorrent( tor ) );
842    assert( state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW );
843
844    tor->verifyState = state;
845    tor->anyDate = time( NULL );
846}
847
848tr_torrent_activity
849tr_torrentGetActivity( tr_torrent * tor )
850{
851    assert( tr_isTorrent( tor ) );
852
853    tr_torrentRecheckCompleteness( tor );
854
855    if( tor->verifyState == TR_VERIFY_NOW )
856        return TR_STATUS_CHECK;
857    if( tor->verifyState == TR_VERIFY_WAIT )
858        return TR_STATUS_CHECK_WAIT;
859    if( !tor->isRunning )
860        return TR_STATUS_STOPPED;
861    if( tor->completeness == TR_LEECH )
862        return TR_STATUS_DOWNLOAD;
863
864    return TR_STATUS_SEED;
865}
866
867const tr_stat *
868tr_torrentStat( tr_torrent * tor )
869{
870    tr_stat *               s;
871    int                     usableSeeds = 0;
872    uint64_t                now;
873    double                  downloadedForRatio, seedRatio=0;
874    double                  d;
875    tr_bool                 checkSeedRatio;
876
877    if( !tor )
878        return NULL;
879
880    assert( tr_isTorrent( tor ) );
881    tr_torrentLock( tor );
882
883    tor->lastStatTime = time( NULL );
884
885    s = &tor->stats;
886    s->id = tor->uniqueId;
887    s->activity = tr_torrentGetActivity( tor );
888    s->error = tor->error;
889    memcpy( s->errorString, tor->errorString, sizeof( s->errorString ) );
890
891    s->manualAnnounceTime = tr_announcerNextManualAnnounce( tor );
892
893    tr_peerMgrTorrentStats( tor,
894                            &s->peersKnown,
895                            &s->peersConnected,
896                            &usableSeeds,
897                            &s->webseedsSendingToUs,
898                            &s->peersSendingToUs,
899                            &s->peersGettingFromUs,
900                            s->peersFrom );
901
902    now = tr_date( );
903    d = tr_peerMgrGetWebseedSpeed( tor, now );
904    s->swarmSpeed         = tr_rcRate( &tor->swarmSpeed, now );
905    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
906    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
907    s->rawDownloadSpeed   = d + tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
908    s->pieceDownloadSpeed = d + tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
909
910    usableSeeds += tor->info.webseedCount;
911
912    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
913
914    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
915    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
916    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
917
918    s->recheckProgress = s->activity == TR_STATUS_CHECK
919                       ? 1.0 -
920                         ( tr_torrentCountUncheckedPieces( tor ) /
921                           (double) tor->info.pieceCount )
922                       : 0.0;
923
924    s->activityDate = tor->activityDate;
925    s->addedDate    = tor->addedDate;
926    s->doneDate     = tor->doneDate;
927    s->startDate    = tor->startDate;
928
929    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
930    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
931    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
932    s->haveValid       = tr_cpHaveValid( &tor->completion );
933    s->haveUnchecked   = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
934
935    if( usableSeeds > 0 )
936    {
937        s->desiredAvailable = s->leftUntilDone;
938    }
939    else if( !s->leftUntilDone || !s->peersConnected )
940    {
941        s->desiredAvailable = 0;
942    }
943    else
944    {
945        tr_piece_index_t i;
946        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable( tor );
947        s->desiredAvailable = 0;
948        for( i = 0; i < tor->info.pieceCount; ++i )
949            if( !tor->info.pieces[i].dnd && tr_bitfieldHasFast( peerPieces, i ) )
950                s->desiredAvailable += tr_cpMissingBlocksInPiece( &tor->completion, i );
951        s->desiredAvailable *= tor->blockSize;
952        tr_bitfieldFree( peerPieces );
953    }
954
955    downloadedForRatio = s->downloadedEver ? s->downloadedEver : s->haveValid;
956    s->ratio = tr_getRatio( s->uploadedEver, downloadedForRatio );
957
958    checkSeedRatio = tr_torrentGetSeedRatio( tor, &seedRatio );
959
960    switch( s->activity )
961    {
962        case TR_STATUS_DOWNLOAD:
963            if( s->leftUntilDone > s->desiredAvailable )
964                s->eta = TR_ETA_NOT_AVAIL;
965            else if( s->pieceDownloadSpeed < 0.1 )
966                s->eta = TR_ETA_UNKNOWN;
967            else {
968                /* etaSpeed exists because if we pieceDownloadSpeed directly,
969                 * brief fluctuations cause the ETA to jump all over the place.
970                 * so, etaSpeed is a smoothed-out version of pieceDownloadSpeed
971                 * to dampen the effect of fluctuations */
972                if( ( tor->etaSpeedCalculatedAt + 800 ) < now ) {
973                    tor->etaSpeedCalculatedAt = now;
974                    tor->etaSpeed = (fabs(tor->etaSpeed)<0.0001)
975                        ? s->pieceDownloadSpeed /* if no previous speed, no need to smooth */
976                        : 0.8*tor->etaSpeed + 0.2*s->pieceDownloadSpeed; /* smooth across 5 readings */
977                }
978                s->eta = s->leftUntilDone / tor->etaSpeed / 1024.0;
979            }
980            break;
981
982        case TR_STATUS_SEED:
983            if( checkSeedRatio )
984            {
985                if( s->pieceUploadSpeed < 0.1 )
986                    s->eta = TR_ETA_UNKNOWN;
987                else
988                    s->eta = (downloadedForRatio * (seedRatio - s->ratio)) / s->pieceUploadSpeed / 1024.0;
989            }
990            else
991                s->eta = TR_ETA_NOT_AVAIL;
992            break;
993
994        default:
995            s->eta = TR_ETA_NOT_AVAIL;
996            break;
997    }
998
999    if( !checkSeedRatio || s->ratio >= seedRatio || s->ratio == TR_RATIO_INF )
1000        s->percentRatio = 1.0;
1001    else if( s->ratio == TR_RATIO_NA )
1002        s->percentRatio = 0.0;
1003    else
1004        s->percentRatio = s->ratio / seedRatio;
1005
1006    tr_torrentUnlock( tor );
1007
1008    return s;
1009}
1010
1011/***
1012****
1013***/
1014
1015static uint64_t
1016fileBytesCompleted( const tr_torrent * tor, tr_file_index_t index )
1017{
1018    uint64_t total = 0;
1019    const tr_file * f = &tor->info.files[index];
1020
1021    if( f->length )
1022    {
1023        const tr_block_index_t firstBlock = f->offset / tor->blockSize;
1024        const uint64_t lastByte = f->offset + f->length - 1;
1025        const tr_block_index_t lastBlock = lastByte / tor->blockSize;
1026
1027        if( firstBlock == lastBlock )
1028        {
1029            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1030                total = f->length;
1031        }
1032        else
1033        {
1034            uint32_t i;
1035
1036            /* the first block */
1037            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1038                total += tor->blockSize - ( f->offset % tor->blockSize );
1039
1040            /* the middle blocks */
1041            if( f->firstPiece == f->lastPiece )
1042            {
1043                for( i=firstBlock+1; i<lastBlock; ++i )
1044                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1045                        total += tor->blockSize;
1046            }
1047            else
1048            {
1049                int64_t b = 0;
1050                const tr_block_index_t firstBlockOfLastPiece
1051                           = tr_torPieceFirstBlock( tor, f->lastPiece );
1052                const tr_block_index_t lastBlockOfFirstPiece
1053                           = tr_torPieceFirstBlock( tor, f->firstPiece )
1054                             + tr_torPieceCountBlocks( tor, f->firstPiece ) - 1;
1055
1056                /* the rest of the first piece */
1057                for( i=firstBlock+1; i<lastBlock && i<=lastBlockOfFirstPiece; ++i )
1058                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1059                        ++b;
1060
1061                /* the middle pieces */
1062                if( f->firstPiece + 1 < f->lastPiece )
1063                    for( i=f->firstPiece+1; i<f->lastPiece; ++i )
1064                        b += tor->blockCountInPiece - tr_cpMissingBlocksInPiece( &tor->completion, i );
1065
1066                /* the rest of the last piece */
1067                for( i=firstBlockOfLastPiece; i<lastBlock; ++i )
1068                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1069                        ++b;
1070
1071                b *= tor->blockSize;
1072                total += b;
1073            }
1074
1075            /* the last block */
1076            if( tr_cpBlockIsCompleteFast( &tor->completion, lastBlock ) )
1077                total += ( f->offset + f->length ) - ( tor->blockSize * lastBlock );
1078        }
1079    }
1080
1081    return total;
1082}
1083
1084tr_file_stat *
1085tr_torrentFiles( const tr_torrent * tor,
1086                 tr_file_index_t *  fileCount )
1087{
1088    tr_file_index_t       i;
1089    const tr_file_index_t n = tor->info.fileCount;
1090    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1091    tr_file_stat *        walk = files;
1092    const tr_bool         isSeed = tor->completeness == TR_SEED;
1093
1094    assert( tr_isTorrent( tor ) );
1095
1096    for( i = 0; i < n; ++i, ++walk )
1097    {
1098        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1099        walk->bytesCompleted = b;
1100        walk->progress = tr_getRatio( b, tor->info.files[i].length );
1101    }
1102
1103    if( fileCount )
1104        *fileCount = n;
1105
1106    return files;
1107}
1108
1109void
1110tr_torrentFilesFree( tr_file_stat *            files,
1111                     tr_file_index_t fileCount UNUSED )
1112{
1113    tr_free( files );
1114}
1115
1116/***
1117****
1118***/
1119
1120float*
1121tr_torrentWebSpeeds( const tr_torrent * tor )
1122{
1123    return tr_isTorrent( tor )
1124         ? tr_peerMgrWebSpeeds( tor )
1125         : NULL;
1126}
1127
1128tr_peer_stat *
1129tr_torrentPeers( const tr_torrent * tor,
1130                 int *              peerCount )
1131{
1132    tr_peer_stat * ret = NULL;
1133
1134    if( tr_isTorrent( tor ) )
1135        ret = tr_peerMgrPeerStats( tor, peerCount );
1136
1137    return ret;
1138}
1139
1140void
1141tr_torrentPeersFree( tr_peer_stat * peers,
1142                     int peerCount  UNUSED )
1143{
1144    tr_free( peers );
1145}
1146
1147tr_tracker_stat *
1148tr_torrentTrackers( const tr_torrent * torrent,
1149                    int              * setmeTrackerCount )
1150{
1151    assert( tr_isTorrent( torrent ) );
1152
1153    return tr_announcerStats( torrent, setmeTrackerCount );
1154}
1155
1156void
1157tr_torrentTrackersFree( tr_tracker_stat * trackers,
1158                        int trackerCount )
1159{
1160    tr_announcerStatsFree( trackers, trackerCount );
1161}
1162
1163void
1164tr_torrentAvailability( const tr_torrent * tor,
1165                        int8_t *           tab,
1166                        int                size )
1167{
1168    tr_peerMgrTorrentAvailability( tor, tab, size );
1169}
1170
1171void
1172tr_torrentAmountFinished( const tr_torrent * tor,
1173                          float *            tab,
1174                          int                size )
1175{
1176    assert( tr_isTorrent( tor ) );
1177
1178    tr_torrentLock( tor );
1179    tr_cpGetAmountDone( &tor->completion, tab, size );
1180    tr_torrentUnlock( tor );
1181}
1182
1183static void
1184tr_torrentResetTransferStats( tr_torrent * tor )
1185{
1186    assert( tr_isTorrent( tor ) );
1187
1188    tr_torrentLock( tor );
1189
1190    tor->downloadedPrev += tor->downloadedCur;
1191    tor->downloadedCur   = 0;
1192    tor->uploadedPrev   += tor->uploadedCur;
1193    tor->uploadedCur     = 0;
1194    tor->corruptPrev    += tor->corruptCur;
1195    tor->corruptCur      = 0;
1196
1197    tr_torrentSetDirty( tor );
1198
1199    tr_torrentUnlock( tor );
1200}
1201
1202void
1203tr_torrentSetHasPiece( tr_torrent *     tor,
1204                       tr_piece_index_t pieceIndex,
1205                       tr_bool          has )
1206{
1207    assert( tr_isTorrent( tor ) );
1208    assert( pieceIndex < tor->info.pieceCount );
1209
1210    if( has )
1211        tr_cpPieceAdd( &tor->completion, pieceIndex );
1212    else
1213        tr_cpPieceRem( &tor->completion, pieceIndex );
1214}
1215
1216/***
1217****
1218***/
1219
1220static void
1221freeTorrent( tr_torrent * tor )
1222{
1223    tr_torrent * t;
1224    tr_session *  session = tor->session;
1225    tr_info *    inf = &tor->info;
1226
1227    assert( tr_isTorrent( tor ) );
1228    assert( !tor->isRunning );
1229
1230    tr_globalLock( session );
1231
1232    tr_peerMgrRemoveTorrent( tor );
1233
1234    tr_cpDestruct( &tor->completion );
1235
1236    tr_rcDestruct( &tor->swarmSpeed );
1237
1238    tr_announcerUnsubscribe( tor->tiers, tor->tiersSubscription );
1239    tr_announcerRemoveTorrent( session->announcer, tor );
1240
1241    tr_bitfieldDestruct( &tor->checkedPieces );
1242
1243    tr_free( tor->downloadDir );
1244    tr_free( tor->peer_id );
1245
1246    if( tor == session->torrentList )
1247        session->torrentList = tor->next;
1248    else for( t = session->torrentList; t != NULL; t = t->next ) {
1249        if( t->next == tor ) {
1250            t->next = tor->next;
1251            break;
1252        }
1253    }
1254
1255    assert( session->torrentCount >= 1 );
1256    session->torrentCount--;
1257
1258    tr_bandwidthFree( tor->bandwidth );
1259
1260    tr_metainfoFree( inf );
1261    tr_free( tor );
1262
1263    tr_globalUnlock( session );
1264}
1265
1266/**
1267***  Start/Stop Callback
1268**/
1269
1270static void
1271checkAndStartImpl( void * vtor )
1272{
1273    tr_torrent * tor = vtor;
1274
1275    assert( tr_isTorrent( tor ) );
1276
1277    tr_globalLock( tor->session );
1278
1279    /** If we had local data before, but it's disappeared,
1280        stop the torrent and log an error. */
1281    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1282    {
1283        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1284        tr_torrentStop( tor );
1285    }
1286    else
1287    {
1288        const time_t now = time( NULL );
1289        tor->isRunning = TRUE;
1290        tor->needsSeedRatioCheck = TRUE;
1291        tor->error = TR_STAT_OK;
1292        tor->errorString[0] = '\0';
1293        tor->completeness = tr_cpGetStatus( &tor->completion );
1294        tor->startDate = tor->anyDate = now;
1295
1296        tr_torrentResetTransferStats( tor );
1297        tr_announcerTorrentStarted( tor );
1298        tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1299        tr_peerMgrStartTorrent( tor );
1300    }
1301
1302    tr_globalUnlock( tor->session );
1303}
1304
1305static void
1306checkAndStartCB( tr_torrent * tor )
1307{
1308    assert( tr_isTorrent( tor ) );
1309    assert( tr_isSession( tor->session ) );
1310
1311    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1312}
1313
1314static void
1315torrentStart( tr_torrent * tor )
1316{
1317    assert( tr_isTorrent( tor ) );
1318
1319    tr_globalLock( tor->session );
1320
1321    if( !tor->isRunning )
1322    {
1323        tr_verifyRemove( tor );
1324
1325        /* corresponds to the peer_id sent as a tracker request parameter.
1326         * one tracker admin says: "When the same torrent is opened and
1327         * closed and opened again without quitting Transmission ...
1328         * change the peerid. It would help sometimes if a stopped event
1329         * was missed to ensure that we didn't think someone was cheating. */
1330        tr_free( tor->peer_id );
1331        tor->peer_id = tr_peerIdNew( );
1332
1333        tor->isRunning = 1;
1334        tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1335        tr_verifyAdd( tor, checkAndStartCB );
1336    }
1337
1338    tr_globalUnlock( tor->session );
1339}
1340
1341void
1342tr_torrentStart( tr_torrent * tor )
1343{
1344    if( tr_isTorrent( tor ) )
1345        torrentStart( tor );
1346}
1347
1348static void
1349torrentRecheckDoneImpl( void * vtor )
1350{
1351    tr_torrent * tor = vtor;
1352
1353    assert( tr_isTorrent( tor ) );
1354    tr_torrentRecheckCompleteness( tor );
1355
1356    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1357    {
1358        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1359        tr_torrentStop( tor );
1360    }
1361    else if( tor->startAfterVerify )
1362    {
1363        tor->startAfterVerify = FALSE;
1364
1365        tr_torrentStart( tor );
1366    }
1367}
1368
1369static void
1370torrentRecheckDoneCB( tr_torrent * tor )
1371{
1372    assert( tr_isTorrent( tor ) );
1373
1374    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1375}
1376
1377static void
1378verifyTorrent( void * vtor )
1379{
1380    tr_torrent * tor = vtor;
1381
1382    assert( tr_isTorrent( tor ) );
1383    tr_globalLock( tor->session );
1384
1385    /* if the torrent's already being verified, stop it */
1386    tr_verifyRemove( tor );
1387
1388    /* if the torrent's running, stop it & set the restart-after-verify flag */
1389    if( tor->startAfterVerify || tor->isRunning ) {
1390        tr_torrentStop( tor );
1391        tor->startAfterVerify = TRUE;
1392    }
1393
1394    /* add the torrent to the recheck queue */
1395    tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1396    tr_torrentUncheck( tor );
1397    tr_verifyAdd( tor, torrentRecheckDoneCB );
1398
1399    tr_globalUnlock( tor->session );
1400}
1401
1402void
1403tr_torrentVerify( tr_torrent * tor )
1404{
1405    if( tr_isTorrent( tor ) )
1406        tr_runInEventThread( tor->session, verifyTorrent, tor );
1407}
1408
1409void
1410tr_torrentSave( tr_torrent * tor )
1411{
1412    assert( tr_isTorrent( tor ) );
1413
1414    if( tor->isDirty ) {
1415        tor->isDirty = FALSE;
1416        tr_torrentSaveResume( tor );
1417    }
1418}
1419
1420static void
1421stopTorrent( void * vtor )
1422{
1423    tr_torrent * tor = vtor;
1424
1425    assert( tr_isTorrent( tor ) );
1426
1427    tr_verifyRemove( tor );
1428    tr_peerMgrStopTorrent( tor );
1429    tr_announcerTorrentStopped( tor );
1430
1431    tr_fdTorrentClose( tor->uniqueId );
1432
1433    if( !tor->isDeleting )
1434        tr_torrentSave( tor );
1435}
1436
1437void
1438tr_torrentStop( tr_torrent * tor )
1439{
1440    assert( tr_isTorrent( tor ) );
1441
1442    if( tr_isTorrent( tor ) )
1443    {
1444        tr_globalLock( tor->session );
1445
1446        tor->isRunning = 0;
1447        tr_runInEventThread( tor->session, stopTorrent, tor );
1448
1449        tr_globalUnlock( tor->session );
1450    }
1451}
1452
1453static void
1454closeTorrent( void * vtor )
1455{
1456    tr_benc * d;
1457    tr_torrent * tor = vtor;
1458
1459    assert( tr_isTorrent( tor ) );
1460
1461    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1462    tr_bencDictAddInt( d, "id", tor->uniqueId );
1463    tr_bencDictAddInt( d, "date", time( NULL ) );
1464
1465    stopTorrent( tor );
1466
1467    if( tor->isDeleting )
1468    {
1469        tr_metainfoRemoveSaved( tor->session, &tor->info );
1470        tr_torrentRemoveResume( tor );
1471    }
1472
1473    tor->isRunning = 0;
1474    freeTorrent( tor );
1475}
1476
1477void
1478tr_torrentFree( tr_torrent * tor )
1479{
1480    if( tr_isTorrent( tor ) )
1481    {
1482        tr_session * session = tor->session;
1483        assert( tr_isSession( session ) );
1484        tr_globalLock( session );
1485
1486        tr_torrentClearCompletenessCallback( tor );
1487        tr_runInEventThread( session, closeTorrent, tor );
1488
1489        tr_globalUnlock( session );
1490    }
1491}
1492
1493void
1494tr_torrentRemove( tr_torrent * tor )
1495{
1496    assert( tr_isTorrent( tor ) );
1497
1498    tor->isDeleting = 1;
1499    tr_torrentFree( tor );
1500}
1501
1502/**
1503***  Completeness
1504**/
1505
1506static const char *
1507getCompletionString( int type )
1508{
1509    switch( type )
1510    {
1511        /* Translators: this is a minor point that's safe to skip over, but FYI:
1512           "Complete" and "Done" are specific, different terms in Transmission:
1513           "Complete" means we've downloaded every file in the torrent.
1514           "Done" means we're done downloading the files we wanted, but NOT all
1515           that exist */
1516        case TR_PARTIAL_SEED:
1517            return _( "Done" );
1518
1519        case TR_SEED:
1520            return _( "Complete" );
1521
1522        default:
1523            return _( "Incomplete" );
1524    }
1525}
1526
1527static void
1528fireCompletenessChange( tr_torrent       * tor,
1529                        tr_completeness    status )
1530{
1531    assert( tr_isTorrent( tor ) );
1532    assert( ( status == TR_LEECH )
1533         || ( status == TR_SEED )
1534         || ( status == TR_PARTIAL_SEED ) );
1535
1536    if( tor->completeness_func )
1537        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1538}
1539
1540void
1541tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1542                                   tr_torrent_completeness_func    func,
1543                                   void                          * user_data )
1544{
1545    assert( tr_isTorrent( tor ) );
1546
1547    tor->completeness_func = func;
1548    tor->completeness_func_user_data = user_data;
1549}
1550
1551void
1552tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1553                                    tr_torrent_ratio_limit_hit_func  func,
1554                                    void                           * user_data )
1555{
1556    assert( tr_isTorrent( tor ) );
1557
1558    tor->ratio_limit_hit_func = func;
1559    tor->ratio_limit_hit_func_user_data = user_data;
1560}
1561
1562void
1563tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1564{
1565    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1566}
1567
1568void
1569tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1570{
1571    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1572}
1573
1574void
1575tr_torrentRecheckCompleteness( tr_torrent * tor )
1576{
1577    tr_completeness completeness;
1578
1579    assert( tr_isTorrent( tor ) );
1580
1581    tr_torrentLock( tor );
1582
1583    completeness = tr_cpGetStatus( &tor->completion );
1584
1585    if( completeness != tor->completeness )
1586    {
1587        const int recentChange = tor->downloadedCur != 0;
1588
1589        if( recentChange )
1590        {
1591            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1592                      getCompletionString( tor->completeness ),
1593                      getCompletionString( completeness ) );
1594        }
1595
1596        tor->completeness = completeness;
1597        tor->needsSeedRatioCheck = TRUE;
1598        tr_fdTorrentClose( tor->uniqueId );
1599        fireCompletenessChange( tor, completeness );
1600
1601        if( recentChange && ( completeness == TR_SEED ) )
1602        {
1603            tr_announcerTorrentCompleted( tor );
1604
1605            tor->doneDate = tor->anyDate = time( NULL );
1606        }
1607
1608        tr_torrentSetDirty( tor );
1609    }
1610
1611    tr_torrentUnlock( tor );
1612}
1613
1614/**
1615***  File priorities
1616**/
1617
1618void
1619tr_torrentInitFilePriority( tr_torrent *    tor,
1620                            tr_file_index_t fileIndex,
1621                            tr_priority_t   priority )
1622{
1623    tr_piece_index_t i;
1624    tr_file *        file;
1625
1626    assert( tr_isTorrent( tor ) );
1627    assert( fileIndex < tor->info.fileCount );
1628    assert( tr_isPriority( priority ) );
1629
1630    file = &tor->info.files[fileIndex];
1631    file->priority = priority;
1632    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1633        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1634}
1635
1636void
1637tr_torrentSetFilePriorities( tr_torrent *      tor,
1638                             tr_file_index_t * files,
1639                             tr_file_index_t   fileCount,
1640                             tr_priority_t     priority )
1641{
1642    tr_file_index_t i;
1643
1644    assert( tr_isTorrent( tor ) );
1645
1646    tr_torrentLock( tor );
1647
1648    for( i = 0; i < fileCount; ++i )
1649        tr_torrentInitFilePriority( tor, files[i], priority );
1650
1651    tr_torrentSetDirty( tor );
1652    tr_torrentUnlock( tor );
1653}
1654
1655tr_priority_t
1656tr_torrentGetFilePriority( const tr_torrent * tor,
1657                           tr_file_index_t    file )
1658{
1659    tr_priority_t ret;
1660
1661    assert( tr_isTorrent( tor ) );
1662
1663    tr_torrentLock( tor );
1664    assert( tor );
1665    assert( file < tor->info.fileCount );
1666    ret = tor->info.files[file].priority;
1667    tr_torrentUnlock( tor );
1668
1669    return ret;
1670}
1671
1672tr_priority_t*
1673tr_torrentGetFilePriorities( const tr_torrent * tor )
1674{
1675    tr_file_index_t i;
1676    tr_priority_t * p;
1677
1678    assert( tr_isTorrent( tor ) );
1679
1680    tr_torrentLock( tor );
1681    p = tr_new0( tr_priority_t, tor->info.fileCount );
1682    for( i = 0; i < tor->info.fileCount; ++i )
1683        p[i] = tor->info.files[i].priority;
1684    tr_torrentUnlock( tor );
1685
1686    return p;
1687}
1688
1689/**
1690***  File DND
1691**/
1692
1693int
1694tr_torrentGetFileDL( const tr_torrent * tor,
1695                     tr_file_index_t    file )
1696{
1697    int doDownload;
1698
1699    assert( tr_isTorrent( tor ) );
1700
1701    tr_torrentLock( tor );
1702
1703    assert( file < tor->info.fileCount );
1704    doDownload = !tor->info.files[file].dnd;
1705
1706    tr_torrentUnlock( tor );
1707    return doDownload != 0;
1708}
1709
1710static void
1711setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1712{
1713    tr_file *        file;
1714    const int        dnd = !doDownload;
1715    tr_piece_index_t firstPiece, firstPieceDND;
1716    tr_piece_index_t lastPiece, lastPieceDND;
1717    tr_file_index_t  i;
1718
1719    assert( tr_isTorrent( tor ) );
1720
1721    file = &tor->info.files[fileIndex];
1722    file->dnd = dnd;
1723    firstPiece = file->firstPiece;
1724    lastPiece = file->lastPiece;
1725
1726    /* can't set the first piece to DND unless
1727       every file using that piece is DND */
1728    firstPieceDND = dnd;
1729    if( fileIndex > 0 )
1730    {
1731        for( i = fileIndex - 1; firstPieceDND; --i )
1732        {
1733            if( tor->info.files[i].lastPiece != firstPiece )
1734                break;
1735            firstPieceDND = tor->info.files[i].dnd;
1736            if( !i )
1737                break;
1738        }
1739    }
1740
1741    /* can't set the last piece to DND unless
1742       every file using that piece is DND */
1743    lastPieceDND = dnd;
1744    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1745    {
1746        if( tor->info.files[i].firstPiece != lastPiece )
1747            break;
1748        lastPieceDND = tor->info.files[i].dnd;
1749    }
1750
1751    if( firstPiece == lastPiece )
1752    {
1753        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1754    }
1755    else
1756    {
1757        tr_piece_index_t pp;
1758        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1759        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1760        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1761            tor->info.pieces[pp].dnd = dnd;
1762    }
1763}
1764
1765void
1766tr_torrentInitFileDLs( tr_torrent      * tor,
1767                       tr_file_index_t * files,
1768                       tr_file_index_t   fileCount,
1769                       tr_bool           doDownload )
1770{
1771    tr_file_index_t i;
1772
1773    assert( tr_isTorrent( tor ) );
1774
1775    tr_torrentLock( tor );
1776
1777    for( i=0; i<fileCount; ++i )
1778        setFileDND( tor, files[i], doDownload );
1779    tr_cpInvalidateDND( &tor->completion );
1780    tor->needsSeedRatioCheck = TRUE;
1781
1782    tr_torrentUnlock( tor );
1783}
1784
1785void
1786tr_torrentSetFileDLs( tr_torrent *      tor,
1787                      tr_file_index_t * files,
1788                      tr_file_index_t   fileCount,
1789                      tr_bool           doDownload )
1790{
1791    assert( tr_isTorrent( tor ) );
1792
1793    tr_torrentLock( tor );
1794    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1795    tr_torrentSetDirty( tor );
1796    tr_torrentUnlock( tor );
1797}
1798
1799/***
1800****
1801***/
1802
1803tr_priority_t
1804tr_torrentGetPriority( const tr_torrent * tor )
1805{
1806    assert( tr_isTorrent( tor ) );
1807
1808    return tor->bandwidth->priority;
1809}
1810
1811void
1812tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1813{
1814    assert( tr_isTorrent( tor ) );
1815    assert( tr_isPriority( priority ) );
1816
1817    if( tor->bandwidth->priority != priority )
1818    {
1819        tor->bandwidth->priority = priority;
1820
1821        tr_torrentSetDirty( tor );
1822    }
1823}
1824
1825/***
1826****
1827***/
1828
1829void
1830tr_torrentSetPeerLimit( tr_torrent * tor,
1831                        uint16_t     maxConnectedPeers )
1832{
1833    assert( tr_isTorrent( tor ) );
1834
1835    tor->maxConnectedPeers = maxConnectedPeers;
1836}
1837
1838uint16_t
1839tr_torrentGetPeerLimit( const tr_torrent * tor )
1840{
1841    assert( tr_isTorrent( tor ) );
1842
1843    return tor->maxConnectedPeers;
1844}
1845
1846/***
1847****
1848***/
1849
1850tr_block_index_t
1851_tr_block( const tr_torrent * tor,
1852           tr_piece_index_t   index,
1853           uint32_t           offset )
1854{
1855    tr_block_index_t ret;
1856
1857    assert( tr_isTorrent( tor ) );
1858
1859    ret = index;
1860    ret *= ( tor->info.pieceSize / tor->blockSize );
1861    ret += offset / tor->blockSize;
1862    return ret;
1863}
1864
1865tr_bool
1866tr_torrentReqIsValid( const tr_torrent * tor,
1867                      tr_piece_index_t   index,
1868                      uint32_t           offset,
1869                      uint32_t           length )
1870{
1871    int err = 0;
1872
1873    assert( tr_isTorrent( tor ) );
1874
1875    if( index >= tor->info.pieceCount )
1876        err = 1;
1877    else if( length < 1 )
1878        err = 2;
1879    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1880        err = 3;
1881    else if( length > MAX_BLOCK_SIZE )
1882        err = 4;
1883    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1884        err = 5;
1885
1886    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
1887                              (unsigned long)index,
1888                              (unsigned long)offset,
1889                              (unsigned long)length,
1890                              err );
1891
1892    return !err;
1893}
1894
1895uint64_t
1896tr_pieceOffset( const tr_torrent * tor,
1897                tr_piece_index_t   index,
1898                uint32_t           offset,
1899                uint32_t           length )
1900{
1901    uint64_t ret;
1902
1903    assert( tr_isTorrent( tor ) );
1904
1905    ret = tor->info.pieceSize;
1906    ret *= index;
1907    ret += offset;
1908    ret += length;
1909    return ret;
1910}
1911
1912/***
1913****
1914***/
1915
1916void
1917tr_torrentSetPieceChecked( tr_torrent        * tor,
1918                           tr_piece_index_t    piece,
1919                           tr_bool             isChecked )
1920{
1921    assert( tr_isTorrent( tor ) );
1922
1923    if( isChecked )
1924        tr_bitfieldAdd( &tor->checkedPieces, piece );
1925    else
1926        tr_bitfieldRem( &tor->checkedPieces, piece );
1927}
1928
1929void
1930tr_torrentSetFileChecked( tr_torrent *    tor,
1931                          tr_file_index_t fileIndex,
1932                          tr_bool         isChecked )
1933{
1934    const tr_file *        file = &tor->info.files[fileIndex];
1935    const tr_piece_index_t begin = file->firstPiece;
1936    const tr_piece_index_t end = file->lastPiece + 1;
1937
1938    assert( tr_isTorrent( tor ) );
1939
1940    if( isChecked )
1941        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
1942    else
1943        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
1944}
1945
1946tr_bool
1947tr_torrentIsFileChecked( const tr_torrent * tor,
1948                         tr_file_index_t    fileIndex )
1949{
1950    const tr_file *        file = &tor->info.files[fileIndex];
1951    const tr_piece_index_t begin = file->firstPiece;
1952    const tr_piece_index_t end = file->lastPiece + 1;
1953    tr_piece_index_t       i;
1954    tr_bool                isChecked = TRUE;
1955
1956    assert( tr_isTorrent( tor ) );
1957
1958    for( i = begin; isChecked && i < end; ++i )
1959        if( !tr_torrentIsPieceChecked( tor, i ) )
1960            isChecked = FALSE;
1961
1962    return isChecked;
1963}
1964
1965void
1966tr_torrentUncheck( tr_torrent * tor )
1967{
1968    assert( tr_isTorrent( tor ) );
1969
1970    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
1971}
1972
1973int
1974tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1975{
1976    assert( tr_isTorrent( tor ) );
1977
1978    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
1979}
1980
1981time_t*
1982tr_torrentGetMTimes( const tr_torrent * tor,
1983                     size_t *           setme_n )
1984{
1985    size_t       i;
1986    const size_t n = tor->info.fileCount;
1987    time_t *     m = tr_new0( time_t, n );
1988
1989    assert( tr_isTorrent( tor ) );
1990
1991    for( i = 0; i < n; ++i )
1992    {
1993        struct stat sb;
1994        char * path = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
1995        if( !stat( path, &sb ) )
1996        {
1997#ifdef SYS_DARWIN
1998            m[i] = sb.st_mtimespec.tv_sec;
1999#else
2000            m[i] = sb.st_mtime;
2001#endif
2002        }
2003        tr_free( path );
2004    }
2005
2006    *setme_n = n;
2007    return m;
2008}
2009
2010/***
2011****
2012***/
2013
2014tr_announce_list_err
2015tr_torrentSetAnnounceList( tr_torrent *            tor,
2016                           const tr_tracker_info * trackers,
2017                           int                     trackerCount )
2018{
2019    int i, j;
2020    tr_benc metainfo;
2021
2022    assert( tr_isTorrent( tor ) );
2023
2024    /* look for bad URLs */
2025    for( i=0; i<trackerCount; ++i )
2026        if( !tr_httpIsValidURL( trackers[i].announce ) )
2027            return TR_ANNOUNCE_LIST_HAS_BAD;
2028
2029    /* look for duplicates */
2030    for( i=0; i<trackerCount; ++i )
2031        for( j=0; j<trackerCount; ++j )
2032            if(    ( i != j )
2033                && ( trackers[i].tier == trackers[j].tier)
2034                && ( !strcmp( trackers[i].announce, trackers[j].announce ) ) )
2035                    return TR_ANNOUNCE_LIST_HAS_DUPLICATES;
2036
2037    /* save to the .torrent file */
2038    if( !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2039    {
2040        int       i;
2041        int       prevTier = -1;
2042        tr_benc * tier = NULL;
2043        tr_benc * announceList;
2044        tr_info   tmpInfo;
2045
2046        /* remove the old fields */
2047        tr_bencDictRemove( &metainfo, "announce" );
2048        tr_bencDictRemove( &metainfo, "announce-list" );
2049
2050        /* add the new fields */
2051        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2052        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2053        for( i = 0; i < trackerCount; ++i ) {
2054            if( prevTier != trackers[i].tier ) {
2055                prevTier = trackers[i].tier;
2056                tier = tr_bencListAddList( announceList, 0 );
2057            }
2058            tr_bencListAddStr( tier, trackers[i].announce );
2059        }
2060
2061        /* try to parse it back again, to make sure it's good */
2062        memset( &tmpInfo, 0, sizeof( tr_info ) );
2063        if( tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
2064        {
2065            /* it's good, so keep these new trackers and free the old ones */
2066
2067            tr_info swap;
2068            swap.trackers = tor->info.trackers;
2069            swap.trackerCount = tor->info.trackerCount;
2070            tor->info.trackers = tmpInfo.trackers;
2071            tor->info.trackerCount = tmpInfo.trackerCount;
2072            tmpInfo.trackers = swap.trackers;
2073            tmpInfo.trackerCount = swap.trackerCount;
2074
2075            tr_metainfoFree( &tmpInfo );
2076            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2077        }
2078
2079        /* cleanup */
2080        tr_bencFree( &metainfo );
2081
2082        /* tell the announcer to reload this torrent's tracker list */
2083        tr_announcerResetTorrent( tor->session->announcer, tor );
2084    }
2085
2086    return TR_ANNOUNCE_LIST_OK;
2087}
2088
2089/**
2090***
2091**/
2092
2093void
2094tr_torrentSetAddedDate( tr_torrent * tor,
2095                        time_t       t )
2096{
2097    assert( tr_isTorrent( tor ) );
2098
2099    tor->addedDate = t;
2100    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2101}
2102
2103void
2104tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2105{
2106    assert( tr_isTorrent( tor ) );
2107
2108    tor->activityDate = t;
2109    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2110}
2111
2112void
2113tr_torrentSetDoneDate( tr_torrent * tor,
2114                       time_t       t )
2115{
2116    assert( tr_isTorrent( tor ) );
2117
2118    tor->doneDate = t;
2119    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2120}
2121
2122/**
2123***
2124**/
2125
2126uint64_t
2127tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2128{
2129    const tr_file * it;
2130    const tr_file * end;
2131    struct stat sb;
2132    uint64_t bytesLeft = 0;
2133
2134    assert( tr_isTorrent( tor ) );
2135
2136    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
2137    {
2138        if( !it->dnd )
2139        {
2140            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
2141
2142            bytesLeft += it->length;
2143
2144            if( !stat( path, &sb )
2145                    && S_ISREG( sb.st_mode )
2146                    && ( (uint64_t)sb.st_size <= it->length ) )
2147                bytesLeft -= sb.st_size;
2148
2149            tr_free( path );
2150        }
2151    }
2152
2153    return bytesLeft;
2154}
2155
2156/****
2157*****  Removing the torrent's local data
2158****/
2159
2160static int
2161vstrcmp( const void * a, const void * b )
2162{
2163    return strcmp( a, b );
2164}
2165
2166static int
2167compareLongestFirst( const void * a, const void * b )
2168{
2169    const size_t alen = strlen( a );
2170    const size_t blen = strlen( b );
2171
2172    if( alen != blen )
2173        return alen > blen ? -1 : 1;
2174
2175    return vstrcmp( a, b );
2176}
2177
2178static void
2179addDirtyFile( const char  * root,
2180              const char  * filename,
2181              tr_ptrArray * dirtyFolders )
2182{
2183    char * dir = tr_dirname( filename );
2184
2185    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2186    while (     ( dir != NULL )
2187             && ( strlen( root ) <= strlen( dir ) )
2188             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2189    {
2190        char * tmp;
2191        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2192
2193        tmp = tr_dirname( dir );
2194        tr_free( dir );
2195        dir = tmp;
2196    }
2197
2198    tr_free( dir );
2199}
2200
2201static void
2202walkLocalData( const tr_torrent * tor,
2203               const char       * root,
2204               const char       * dir,
2205               const char       * base,
2206               tr_ptrArray      * torrentFiles,
2207               tr_ptrArray      * folders,
2208               tr_ptrArray      * dirtyFolders )
2209{
2210    int i;
2211    struct stat sb;
2212    char * buf;
2213
2214    assert( tr_isTorrent( tor ) );
2215
2216    buf = tr_buildPath( dir, base, NULL );
2217    i = stat( buf, &sb );
2218    if( !i )
2219    {
2220        DIR * odir = NULL;
2221
2222        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2223        {
2224            struct dirent *d;
2225            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2226            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2227                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2228                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2229            closedir( odir );
2230        }
2231        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2232        {
2233            const char * sub = buf + strlen( tor->downloadDir ) + strlen( TR_PATH_DELIMITER_STR );
2234            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2235            if( !isTorrentFile )
2236                addDirtyFile( root, buf, dirtyFolders );
2237        }
2238    }
2239
2240    tr_free( buf );
2241}
2242
2243static void
2244deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2245{
2246    int i, n;
2247    char ** s;
2248    tr_file_index_t f;
2249    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2250    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2251    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2252
2253    const char * firstFile = tor->info.files[0].name;
2254    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2255    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2256    char * root = tr_buildPath( tor->downloadDir, tmp, NULL );
2257
2258    assert( tr_isTorrent( tor ) );
2259
2260    for( f=0; f<tor->info.fileCount; ++f )
2261        tr_ptrArrayInsertSorted( &torrentFiles, tor->info.files[f].name, vstrcmp );
2262
2263    /* build the set of folders and dirtyFolders */
2264    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2265
2266    /* try to remove entire folders first, so that the recycle bin will be tidy */
2267    s = (char**) tr_ptrArrayPeek( &folders, &n );
2268    for( i=0; i<n; ++i )
2269        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2270            fileFunc( s[i] );
2271
2272    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2273    for( f=0; f<tor->info.fileCount; ++f ) {
2274        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
2275        fileFunc( path );
2276        tr_free( path );
2277    }
2278
2279    /* Now clean out the directories left empty from the previous step.
2280     * Work from deepest to shallowest s.t. lower folders
2281     * won't prevent the upper folders from being deleted */
2282    {
2283        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2284        s = (char**) tr_ptrArrayPeek( &folders, &n );
2285        for( i=0; i<n; ++i )
2286            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2287                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2288        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2289        for( i=0; i<n; ++i )
2290            fileFunc( s[i] );
2291        tr_ptrArrayDestruct( &cleanFolders, NULL );
2292    }
2293
2294    /* cleanup */
2295    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2296    tr_ptrArrayDestruct( &folders, tr_free );
2297    tr_ptrArrayDestruct( &torrentFiles, NULL );
2298    tr_free( root );
2299    tr_free( tmp );
2300}
2301
2302void
2303tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2304{
2305    assert( tr_isTorrent( tor ) );
2306
2307    if( fileFunc == NULL )
2308        fileFunc = remove;
2309
2310    /* close all the files because we're about to delete them */
2311    tr_fdTorrentClose( tor->uniqueId );
2312
2313    if( tor->info.fileCount > 1 )
2314        deleteLocalData( tor, fileFunc );
2315    else {
2316        /* torrent only has one file */
2317        char * path = tr_buildPath( tor->downloadDir, tor->info.files[0].name, NULL );
2318        fileFunc( path );
2319        tr_free( path );
2320    }
2321}
2322
2323/***
2324****
2325***/
2326
2327struct LocationData
2328{
2329    tr_bool move_from_old_location;
2330    int * setme_state;
2331    double * setme_progress;
2332    char * location;
2333    tr_torrent * tor;
2334};
2335
2336static void
2337setLocation( void * vdata )
2338{
2339    tr_bool err = FALSE;
2340    tr_bool verify_needed = FALSE;
2341    struct LocationData * data = vdata;
2342    tr_torrent * tor = data->tor;
2343    const tr_bool do_move = data->move_from_old_location;
2344    const char * location = data->location;
2345    double bytesHandled = 0;
2346
2347    assert( tr_isTorrent( tor ) );
2348
2349    if( strcmp( location, tor->downloadDir ) )
2350    {
2351        tr_file_index_t i;
2352
2353        /* bad idea to move files while they're being verified... */
2354        tr_verifyRemove( tor );
2355
2356        /* if the torrent is running, stop it and set a flag to
2357         * restart after we're done */
2358        if( tor->isRunning )
2359        {
2360            tr_torrentStop( tor );
2361            tor->startAfterVerify = TRUE;
2362        }
2363
2364        /* try to move the files.
2365         * FIXME: there are still all kinds of nasty cases, like what
2366         * if the target directory runs out of space halfway through... */
2367        for( i=0; !err && i<tor->info.fileCount; ++i )
2368        {
2369            struct stat sb;
2370            const tr_file * f = &tor->info.files[i];
2371            char * oldpath = tr_buildPath( tor->downloadDir, f->name, NULL );
2372            char * newpath = tr_buildPath( location, f->name, NULL );
2373
2374            if( do_move )
2375            {
2376                errno = 0;
2377                tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2378                if( rename( oldpath, newpath ) )
2379                {
2380                    verify_needed = TRUE;
2381                    if( tr_moveFile( oldpath, newpath ) )
2382                    {
2383                        err = TRUE;
2384                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2385                                        oldpath, newpath, tr_strerror( errno ) );
2386                    }
2387                }
2388            }
2389            else if( !stat( newpath, &sb ) )
2390            {
2391                tr_torinf( tor, "found \"%s\"", newpath );
2392            }
2393
2394            if( data->setme_progress )
2395            {
2396                bytesHandled += f->length;
2397                *data->setme_progress = bytesHandled / tor->info.totalSize;
2398            }
2399
2400            tr_free( newpath );
2401            tr_free( oldpath );
2402        }
2403
2404        if( !err )
2405        {
2406            /* blow away the leftover subdirectories in the old location */
2407            if( do_move && verify_needed )
2408                tr_torrentDeleteLocalData( tor, remove );
2409
2410            /* set the new location and reverify */
2411            tr_torrentSetDownloadDir( tor, location );
2412            if( verify_needed )
2413                tr_torrentVerify( tor );
2414        }
2415    }
2416
2417    if( data->setme_state )
2418        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2419
2420    /* cleanup */
2421    tr_free( data->location );
2422    tr_free( data );
2423}
2424
2425void
2426tr_torrentSetLocation( tr_torrent  * tor,
2427                       const char  * location,
2428                       tr_bool       move_from_old_location,
2429                       double      * setme_progress,
2430                       int         * setme_state )
2431{
2432    struct LocationData * data;
2433
2434    assert( tr_isTorrent( tor ) );
2435
2436    if( setme_state )
2437        *setme_state = TR_LOC_MOVING;
2438    if( setme_progress )
2439        *setme_progress = 0;
2440
2441    /* run this in the libtransmission thread */
2442    data = tr_new( struct LocationData, 1 );
2443    data->tor = tor;
2444    data->location = tr_strdup( location );
2445    data->move_from_old_location = move_from_old_location;
2446    data->setme_state = setme_state;
2447    data->setme_progress = setme_progress;
2448    tr_runInEventThread( tor->session, setLocation, data );
2449}
2450
2451/***
2452****
2453***/
2454
2455void
2456tr_torrentCheckSeedRatio( tr_torrent * tor )
2457{
2458    double seedRatio;
2459
2460    assert( tr_isTorrent( tor ) );
2461
2462    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2463    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2464    {
2465        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2466        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2467        double ratio;
2468
2469        /* maybe we're the initial seeder and never downloaded anything... */
2470        if( down == 0 )
2471            down = tr_cpHaveValid( &tor->completion );
2472
2473        ratio = tr_getRatio( up, down );
2474
2475        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2476        {
2477            tr_torrentStop( tor );
2478
2479            /* set to no ratio limit to allow easy restarting */
2480            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2481
2482            /* maybe notify the client */
2483            if( tor->ratio_limit_hit_func != NULL )
2484                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2485        }
2486    }
2487}
Note: See TracBrowser for help on using the repository browser.