source: trunk/libtransmission/torrent.c @ 8869

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

(trunk) #1400, #2308: differentiate warnings and errors; differentiate between local messages and messages from the tracker

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