source: trunk/libtransmission/torrent.c @ 7618

Last change on this file since 7618 was 7618, checked in by charles, 14 years ago

(trunk libT) fix the much-hated "Assertion failed: (tr_isPeerIo( io ))". Also, repeated calls to tr_date() were taking up about 78% of the time in tr_stat(), so instead of calling multiple times, call it once in tr_stat() and pass that value around to the functions that need it.

  • Property svn:keywords set to Date Rev Author Id
File size: 49.6 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 7618 2009-01-05 04:27:54Z charles $
3 *
4 * Copyright (c) 2005-2008 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#include <sys/types.h> /* stat */
26#include <sys/stat.h> /* stat */
27#include <unistd.h> /* stat */
28#include <dirent.h>
29
30#include <assert.h>
31#include <limits.h> /* INT_MAX */
32#include <string.h> /* memcmp */
33#include <stdlib.h> /* qsort */
34
35#include "transmission.h"
36#include "session.h"
37#include "bandwidth.h"
38#include "bencode.h"
39#include "completion.h"
40#include "crypto.h" /* for tr_sha1 */
41#include "resume.h"
42#include "fdlimit.h" /* tr_fdFileClose */
43#include "metainfo.h"
44#include "peer-mgr.h"
45#include "platform.h" /* TR_PATH_DELIMITER_STR */
46#include "ptrarray.h"
47#include "ratecontrol.h"
48#include "torrent.h"
49#include "tracker.h"
50#include "trevent.h"
51#include "utils.h"
52#include "verify.h"
53
54#define MAX_BLOCK_SIZE ( 1024 * 16 )
55
56/***
57****
58***/
59
60int
61tr_torrentId( const tr_torrent * tor )
62{
63    return tor->uniqueId;
64}
65
66tr_torrent*
67tr_torrentFindFromId( tr_session * session, int id )
68{
69    tr_torrent * tor = NULL;
70
71    while( ( tor = tr_torrentNext( session, tor ) ) )
72        if( tor->uniqueId == id )
73            return tor;
74
75    return NULL;
76}
77
78tr_torrent*
79tr_torrentFindFromHashString( tr_session *  session, const char * str )
80{
81    tr_torrent * tor = NULL;
82
83    while( ( tor = tr_torrentNext( session, tor ) ) )
84        if( !strcmp( str, tor->info.hashString ) )
85            return tor;
86
87    return NULL;
88}
89
90tr_torrent*
91tr_torrentFindFromHash( tr_session * session, const uint8_t * torrentHash )
92{
93    tr_torrent * tor = NULL;
94
95    while( ( tor = tr_torrentNext( session, tor ) ) )
96        if( *tor->info.hash == *torrentHash )
97            if( !memcmp( tor->info.hash, torrentHash, SHA_DIGEST_LENGTH ) )
98                return tor;
99
100    return NULL;
101}
102
103tr_torrent*
104tr_torrentFindFromObfuscatedHash( tr_session * session,
105                                  const uint8_t * obfuscatedTorrentHash )
106{
107    tr_torrent * tor = NULL;
108
109    while( ( tor = tr_torrentNext( session, tor ) ) )
110        if( !memcmp( tor->obfuscatedHash, obfuscatedTorrentHash,
111                     SHA_DIGEST_LENGTH ) )
112            return tor;
113
114    return NULL;
115}
116
117/***
118****  PER-TORRENT UL / DL SPEEDS
119***/
120
121void
122tr_torrentSetSpeedMode( tr_torrent *  tor,
123                        tr_direction  dir,
124                        tr_speedlimit mode )
125{
126    assert( tor != NULL );
127    assert( tr_isDirection( dir ) );
128    assert( mode==TR_SPEEDLIMIT_GLOBAL || mode==TR_SPEEDLIMIT_SINGLE || mode==TR_SPEEDLIMIT_UNLIMITED  );
129
130    tor->speedLimitMode[dir] = mode;
131
132    tr_bandwidthSetLimited( tor->bandwidth, dir, mode==TR_SPEEDLIMIT_SINGLE );
133    tr_bandwidthHonorParentLimits( tor->bandwidth, dir, mode==TR_SPEEDLIMIT_GLOBAL );
134}
135
136tr_speedlimit
137tr_torrentGetSpeedMode( const tr_torrent * tor,
138                        tr_direction       dir )
139{
140    assert( tor != NULL );
141    assert( tr_isDirection( dir ) );
142
143    return tor->speedLimitMode[dir];
144}
145
146void
147tr_torrentSetSpeedLimit( tr_torrent * tor,
148                         tr_direction dir,
149                         int          desiredSpeed )
150{
151    tr_bandwidthSetDesiredSpeed( tor->bandwidth, dir, desiredSpeed );
152}
153
154int
155tr_torrentGetSpeedLimit( const tr_torrent * tor,
156                         tr_direction       dir )
157{
158    return tr_bandwidthGetDesiredSpeed( tor->bandwidth, dir );
159}
160
161tr_bool
162tr_torrentIsPieceTransferAllowed( const tr_torrent  * tor,
163                                  tr_direction        direction )
164{
165    tr_bool isEnabled = FALSE;
166
167    switch( tr_torrentGetSpeedMode( tor, direction ) )
168    {
169        case TR_SPEEDLIMIT_GLOBAL:
170            isEnabled = !tr_sessionIsSpeedLimitEnabled( tor->session, direction )
171                      || tr_sessionGetSpeedLimit( tor->session, direction ) > 0;
172            break;
173
174        case TR_SPEEDLIMIT_SINGLE:
175            isEnabled = tr_torrentGetSpeedLimit( tor, direction ) > 0;
176            break;
177
178        case TR_SPEEDLIMIT_UNLIMITED:
179            isEnabled = TRUE;
180            break;
181
182        default:
183            assert( 0 && "unhandled speed mode" );
184            break;
185    }
186
187    return isEnabled;
188}
189
190/***
191****
192***/
193
194static void
195onTrackerResponse( void * tracker UNUSED,
196                   void *         vevent,
197                   void *         user_data )
198{
199    tr_torrent *       tor = user_data;
200    tr_tracker_event * event = vevent;
201
202    switch( event->messageType )
203    {
204        case TR_TRACKER_PEERS:
205        {
206            size_t   i, n;
207            tr_pex * pex = tr_peerMgrArrayToPex( event->compact,
208                                                 event->compactLen, &n );
209             if( event->allAreSeeds )
210                tr_tordbg( tor, "Got %d seeds from tracker", (int)n );
211            else
212                tr_torinf( tor, _( "Got %d peers from tracker" ), (int)n );
213
214            for( i = 0; i < n; ++i )
215            {
216                if( event->allAreSeeds )
217                    pex[i].flags |= ADDED_F_SEED_FLAG;
218                tr_peerMgrAddPex( tor->session->peerMgr, tor->info.hash,
219                                  TR_PEER_FROM_TRACKER, pex + i );
220            }
221
222            tr_free( pex );
223            break;
224        }
225
226        case TR_TRACKER_WARNING:
227            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
228            tor->error = -1;
229            tr_strlcpy( tor->errorString, event->text,
230                       sizeof( tor->errorString ) );
231            break;
232
233        case TR_TRACKER_ERROR:
234            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
235            tor->error = -2;
236            tr_strlcpy( tor->errorString, event->text,
237                       sizeof( tor->errorString ) );
238            break;
239
240        case TR_TRACKER_ERROR_CLEAR:
241            tor->error = 0;
242            tor->errorString[0] = '\0';
243            break;
244    }
245}
246
247/***
248****
249****  TORRENT INSTANTIATION
250****
251***/
252
253static int
254getBytePiece( const tr_info * info,
255              uint64_t        byteOffset )
256{
257    assert( info );
258    assert( info->pieceSize != 0 );
259
260    return byteOffset / info->pieceSize;
261}
262
263static void
264initFilePieces( tr_info *       info,
265                tr_file_index_t fileIndex )
266{
267    tr_file * file;
268    uint64_t  firstByte, lastByte;
269
270    assert( info );
271    assert( fileIndex < info->fileCount );
272
273    file = &info->files[fileIndex];
274    firstByte = file->offset;
275    lastByte = firstByte + ( file->length ? file->length - 1 : 0 );
276    file->firstPiece = getBytePiece( info, firstByte );
277    file->lastPiece = getBytePiece( info, lastByte );
278}
279
280static int
281pieceHasFile( tr_piece_index_t piece,
282              const tr_file *  file )
283{
284    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
285}
286
287static tr_priority_t
288calculatePiecePriority( const tr_torrent * tor,
289                        tr_piece_index_t   piece,
290                        int                fileHint )
291{
292    tr_file_index_t i;
293    int             priority = TR_PRI_LOW;
294
295    /* find the first file that has data in this piece */
296    if( fileHint >= 0 )
297    {
298        i = fileHint;
299        while( i > 0 && pieceHasFile( piece, &tor->info.files[i - 1] ) )
300            --i;
301    }
302    else
303    {
304        for( i = 0; i < tor->info.fileCount; ++i )
305            if( pieceHasFile( piece, &tor->info.files[i] ) )
306                break;
307    }
308
309    /* the piece's priority is the max of the priorities
310     * of all the files in that piece */
311    for( ; i < tor->info.fileCount; ++i )
312    {
313        const tr_file * file = &tor->info.files[i];
314
315        if( !pieceHasFile( piece, file ) )
316            break;
317
318        priority = MAX( priority, file->priority );
319
320        /* when dealing with multimedia files, getting the first and
321           last pieces can sometimes allow you to preview it a bit
322           before it's fully downloaded... */
323        if( file->priority >= TR_PRI_NORMAL )
324            if( file->firstPiece == piece || file->lastPiece == piece )
325                priority = TR_PRI_HIGH;
326    }
327
328    return priority;
329}
330
331static void
332tr_torrentInitFilePieces( tr_torrent * tor )
333{
334    tr_file_index_t  ff;
335    tr_piece_index_t pp;
336    uint64_t         offset = 0;
337    tr_info *        inf = &tor->info;
338
339    assert( inf );
340
341    for( ff = 0; ff < inf->fileCount; ++ff )
342    {
343        inf->files[ff].offset = offset;
344        offset += inf->files[ff].length;
345        initFilePieces( inf, ff );
346    }
347
348    for( pp = 0; pp < inf->pieceCount; ++pp )
349        inf->pieces[pp].priority = calculatePiecePriority( tor, pp, -1 );
350}
351
352int
353tr_torrentPromoteTracker( tr_torrent * tor,
354                          int          pos )
355{
356    int i;
357    int tier;
358
359    assert( tor );
360    assert( ( 0 <= pos ) && ( pos < tor->info.trackerCount ) );
361
362    /* the tier of the tracker we're promoting */
363    tier = tor->info.trackers[pos].tier;
364
365    /* find the index of that tier's first tracker */
366    for( i = 0; i < tor->info.trackerCount; ++i )
367        if( tor->info.trackers[i].tier == tier )
368            break;
369
370    assert( i < tor->info.trackerCount );
371
372    /* promote the tracker at `pos' to the front of the tier */
373    if( i != pos )
374    {
375        const tr_tracker_info tmp = tor->info.trackers[i];
376        tor->info.trackers[i] = tor->info.trackers[pos];
377        tor->info.trackers[pos] = tmp;
378    }
379
380    /* return the new position of the tracker that started out at [pos] */
381    return i;
382}
383
384struct RandomTracker
385{
386    tr_tracker_info    tracker;
387    int                random_value;
388};
389
390/* the tiers will be sorted from lowest to highest,
391 * and trackers are randomized within the tiers */
392static inline int
393compareRandomTracker( const void * va,
394                      const void * vb )
395{
396    const struct RandomTracker * a = va;
397    const struct RandomTracker * b = vb;
398
399    if( a->tracker.tier != b->tracker.tier )
400        return a->tracker.tier - b->tracker.tier;
401
402    return a->random_value - b->random_value;
403}
404
405static void
406randomizeTiers( tr_info * info )
407{
408    int                    i;
409    const int              n = info->trackerCount;
410    struct RandomTracker * r = tr_new0( struct RandomTracker, n );
411
412    for( i = 0; i < n; ++i )
413    {
414        r[i].tracker = info->trackers[i];
415        r[i].random_value = tr_cryptoRandInt( INT_MAX );
416    }
417    qsort( r, n, sizeof( struct RandomTracker ), compareRandomTracker );
418    for( i = 0; i < n; ++i )
419        info->trackers[i] = r[i].tracker;
420    tr_free( r );
421}
422
423static void torrentStart( tr_torrent * tor,
424                          int          reloadProgress );
425
426/**
427 * Decide on a block size.  constraints:
428 * (1) most clients decline requests over 16 KiB
429 * (2) pieceSize must be a multiple of block size
430 */
431static uint32_t
432getBlockSize( uint32_t pieceSize )
433{
434    uint32_t b = pieceSize;
435
436    while( b > MAX_BLOCK_SIZE )
437        b /= 2u;
438
439    if( !b || ( pieceSize % b ) ) /* not cleanly divisible */
440        return 0;
441    return b;
442}
443
444static void
445torrentRealInit( tr_session      * session,
446                 tr_torrent      * tor,
447                 const tr_ctor   * ctor )
448{
449    int        doStart;
450    uint64_t   loaded;
451    uint64_t   t;
452    tr_info *  info = &tor->info;
453    static int nextUniqueId = 1;
454
455    tr_globalLock( session );
456
457    tor->session   = session;
458    tor->uniqueId = nextUniqueId++;
459
460    randomizeTiers( info );
461
462    tor->bandwidth = tr_bandwidthNew( session, session->bandwidth );
463
464    tor->blockSize = getBlockSize( info->pieceSize );
465
466    tor->lastPieceSize = info->totalSize % info->pieceSize;
467
468    if( !tor->lastPieceSize )
469        tor->lastPieceSize = info->pieceSize;
470
471    tor->lastBlockSize = info->totalSize % tor->blockSize;
472
473    if( !tor->lastBlockSize )
474        tor->lastBlockSize = tor->blockSize;
475
476    tor->blockCount =
477        ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize;
478
479    tor->blockCountInPiece =
480        info->pieceSize / tor->blockSize;
481
482    tor->blockCountInLastPiece =
483        ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize;
484
485    /* check our work */
486    assert( ( info->pieceSize % tor->blockSize ) == 0 );
487    t = info->pieceCount - 1;
488    t *= info->pieceSize;
489    t += tor->lastPieceSize;
490    assert( t == info->totalSize );
491    t = tor->blockCount - 1;
492    t *= tor->blockSize;
493    t += tor->lastBlockSize;
494    assert( t == info->totalSize );
495    t = info->pieceCount - 1;
496    t *= tor->blockCountInPiece;
497    t += tor->blockCountInLastPiece;
498    assert( t == (uint64_t)tor->blockCount );
499
500    tr_cpConstruct( &tor->completion, tor );
501
502    tr_torrentInitFilePieces( tor );
503
504    tr_rcConstruct( &tor->swarmSpeed );
505
506    tr_sha1( tor->obfuscatedHash, "req2", 4,
507             info->hash, SHA_DIGEST_LENGTH,
508             NULL );
509
510    tr_peerMgrAddTorrent( session->peerMgr, tor );
511
512    assert( session->isPortSet );
513    assert( !tor->downloadedCur );
514    assert( !tor->uploadedCur );
515
516    tor->error   = 0;
517
518    tr_bitfieldConstruct( &tor->checkedPieces, tor->info.pieceCount );
519    tr_torrentUncheck( tor );
520
521    tor->addedDate = time( NULL ); /* this is a default value to be
522                                      overwritten by the resume file */
523    loaded = tr_torrentLoadResume( tor, ~0, ctor );
524
525    doStart = tor->isRunning;
526    tor->isRunning = 0;
527
528    if( !( loaded & TR_FR_SPEEDLIMIT ) )
529    {
530        tr_torrentSetSpeedLimit( tor, TR_UP,
531                                tr_sessionGetSpeedLimit( tor->session, TR_UP ) );
532        tr_torrentSetSpeedLimit( tor, TR_DOWN,
533                                tr_sessionGetSpeedLimit( tor->session,
534                                                         TR_DOWN ) );
535    }
536
537    tor->completeness = tr_cpGetStatus( &tor->completion );
538
539    tor->tracker = tr_trackerNew( tor );
540    tor->trackerSubscription =
541        tr_trackerSubscribe( tor->tracker, onTrackerResponse,
542                             tor );
543
544    {
545        tr_torrent * it = NULL;
546        tr_torrent * last = NULL;
547        while( ( it = tr_torrentNext( session, it ) ) )
548            last = it;
549
550        if( !last )
551            session->torrentList = tor;
552        else
553            last->next = tor;
554        ++session->torrentCount;
555    }
556
557    tr_globalUnlock( session );
558
559    /* maybe save our own copy of the metainfo */
560    if( tr_ctorGetSave( ctor ) )
561    {
562        const tr_benc * val;
563        if( !tr_ctorGetMetainfo( ctor, &val ) )
564        {
565            const char * filename = tor->info.torrent;
566            tr_bencSaveFile( filename, val );
567            tr_sessionSetTorrentFile( tor->session, tor->info.hashString,
568                                      filename );
569        }
570    }
571
572    tr_metainfoMigrate( session, &tor->info );
573
574    if( doStart )
575        torrentStart( tor, FALSE );
576}
577
578int
579tr_torrentParse( const tr_session  * session,
580                 const tr_ctor     * ctor,
581                 tr_info           * setmeInfo )
582{
583    int             err = 0;
584    int             doFree;
585    tr_info         tmp;
586    const tr_benc * metainfo;
587
588    if( setmeInfo == NULL )
589        setmeInfo = &tmp;
590    memset( setmeInfo, 0, sizeof( tr_info ) );
591
592    if( !err && tr_ctorGetMetainfo( ctor, &metainfo ) )
593        return TR_EINVALID;
594
595    err = tr_metainfoParse( session, setmeInfo, metainfo );
596    doFree = !err && ( setmeInfo == &tmp );
597
598    if( !err && !getBlockSize( setmeInfo->pieceSize ) )
599        err = TR_EINVALID;
600
601    if( !err && tr_torrentExists( session, setmeInfo->hash ) )
602        err = TR_EDUPLICATE;
603
604    if( doFree )
605        tr_metainfoFree( setmeInfo );
606
607    return err;
608}
609
610tr_torrent *
611tr_torrentNew( tr_session     * session,
612               const tr_ctor  * ctor,
613               int            * setmeError )
614{
615    int          err;
616    tr_info      tmpInfo;
617    tr_torrent * tor = NULL;
618
619    err = tr_torrentParse( session, ctor, &tmpInfo );
620    if( !err )
621    {
622        tor = tr_new0( tr_torrent, 1 );
623        tor->info = tmpInfo;
624        torrentRealInit( session, tor, ctor );
625    }
626    else if( setmeError )
627    {
628        *setmeError = err;
629    }
630
631    return tor;
632}
633
634/**
635***
636**/
637
638void
639tr_torrentSetDownloadDir( tr_torrent * tor,
640                          const char * path )
641{
642    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
643    {
644        tr_free( tor->downloadDir );
645        tor->downloadDir = tr_strdup( path );
646        tr_torrentSaveResume( tor );
647    }
648}
649
650const char*
651tr_torrentGetDownloadDir( const tr_torrent * tor )
652{
653    return tor->downloadDir;
654}
655
656void
657tr_torrentChangeMyPort( tr_torrent * tor )
658{
659    if( tor->tracker )
660        tr_trackerChangeMyPort( tor->tracker );
661}
662
663static inline void
664tr_torrentManualUpdateImpl( void * vtor )
665{
666    tr_torrent * tor = vtor;
667
668    if( tor->isRunning )
669        tr_trackerReannounce( tor->tracker );
670}
671
672void
673tr_torrentManualUpdate( tr_torrent * tor )
674{
675    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
676}
677
678int
679tr_torrentCanManualUpdate( const tr_torrent * tor )
680{
681    return ( tor )
682           && ( tor->isRunning )
683           && ( tr_trackerCanManualAnnounce( tor->tracker ) );
684}
685
686const tr_info *
687tr_torrentInfo( const tr_torrent * tor )
688{
689    return tor ? &tor->info : NULL;
690}
691
692const tr_stat *
693tr_torrentStatCached( tr_torrent * tor )
694{
695    const time_t now = time( NULL );
696
697    return tor && ( now == tor->lastStatTime ) ? &tor->stats
698           : tr_torrentStat( tor );
699}
700
701tr_torrent_activity
702tr_torrentGetActivity( tr_torrent * tor )
703{
704    tr_torrentRecheckCompleteness( tor );
705
706    if( tor->verifyState == TR_VERIFY_NOW )
707        return TR_STATUS_CHECK;
708    if( tor->verifyState == TR_VERIFY_WAIT )
709        return TR_STATUS_CHECK_WAIT;
710    if( !tor->isRunning )
711        return TR_STATUS_STOPPED;
712    if( tor->completeness == TR_LEECH )
713        return TR_STATUS_DOWNLOAD;
714
715    return TR_STATUS_SEED;
716}
717
718const tr_stat *
719tr_torrentStat( tr_torrent * tor )
720{
721    tr_stat *               s;
722    struct tr_tracker *     tc;
723    const tr_tracker_info * ti;
724    int                     usableSeeds = 0;
725    uint64_t                now;
726
727    if( !tor )
728        return NULL;
729
730    tr_torrentLock( tor );
731
732    tor->lastStatTime = time( NULL );
733
734    s = &tor->stats;
735    s->id = tor->uniqueId;
736    s->activity = tr_torrentGetActivity( tor );
737    s->error  = tor->error;
738    memcpy( s->errorString, tor->errorString,
739           sizeof( s->errorString ) );
740
741    tc = tor->tracker;
742    ti = tr_trackerGetAddress( tor->tracker, tor );
743    s->announceURL = ti ? ti->announce : NULL;
744    s->scrapeURL   = ti ? ti->scrape   : NULL;
745    tr_trackerStat( tc, s );
746
747    tr_trackerGetCounts( tc, &s->timesCompleted,
748                             &s->leechers,
749                             &s->seeders,
750                             &s->downloaders );
751
752    tr_peerMgrTorrentStats( tor->session->peerMgr,
753                            tor->info.hash,
754                            &s->peersKnown,
755                            &s->peersConnected,
756                            &usableSeeds,
757                            &s->webseedsSendingToUs,
758                            &s->peersSendingToUs,
759                            &s->peersGettingFromUs,
760                            s->peersFrom );
761
762    now = tr_date( );
763    s->swarmSpeed         = tr_rcRate( &tor->swarmSpeed, now );
764    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
765    s->rawDownloadSpeed   = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
766    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
767    s->pieceDownloadSpeed = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
768
769    usableSeeds += tor->info.webseedCount;
770
771    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
772
773    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
774    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
775    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
776
777    s->recheckProgress = s->activity == TR_STATUS_CHECK
778                       ? 1.0 -
779                         ( tr_torrentCountUncheckedPieces( tor ) /
780                           (double) tor->info.pieceCount )
781                       : 0.0;
782
783
784    s->activityDate = tor->activityDate;
785    s->addedDate    = tor->addedDate;
786    s->doneDate     = tor->doneDate;
787    s->startDate    = tor->startDate;
788
789    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
790    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
791    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
792    s->haveValid       = tr_cpHaveValid( &tor->completion );
793    s->haveUnchecked   = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
794
795
796    if( usableSeeds > 0 )
797    {
798        s->desiredAvailable = s->leftUntilDone;
799    }
800    else if( !s->leftUntilDone || !s->peersConnected )
801    {
802        s->desiredAvailable = 0;
803    }
804    else
805    {
806        tr_piece_index_t i;
807        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable(
808            tor->session->peerMgr,
809            tor->info.
810            hash );
811        s->desiredAvailable = 0;
812        for( i = 0; i < tor->info.pieceCount; ++i )
813            if( !tor->info.pieces[i].dnd && tr_bitfieldHas( peerPieces, i ) )
814                s->desiredAvailable += tr_cpMissingBlocksInPiece( &tor->completion, i );
815        s->desiredAvailable *= tor->blockSize;
816        tr_bitfieldFree( peerPieces );
817    }
818
819    if( s->leftUntilDone > s->desiredAvailable )
820        s->eta = TR_ETA_NOT_AVAIL;
821    else if( s->pieceDownloadSpeed < 0.1 )
822        s->eta = TR_ETA_UNKNOWN;
823    else
824        s->eta = s->leftUntilDone / s->pieceDownloadSpeed / 1024.0;
825
826    s->ratio = tr_getRatio(
827        s->uploadedEver,
828        s->downloadedEver ? s->downloadedEver : s->
829        haveValid );
830
831    tr_torrentUnlock( tor );
832
833    return s;
834}
835
836/***
837****
838***/
839
840static uint64_t
841fileBytesCompleted( const tr_torrent * tor,
842                    tr_file_index_t    fileIndex )
843{
844    const tr_file *        file     =  &tor->info.files[fileIndex];
845    const tr_block_index_t firstBlock       =  file->offset /
846                                              tor->blockSize;
847    const uint64_t         firstBlockOffset =  file->offset %
848                                              tor->blockSize;
849    const uint64_t         lastOffset       =
850        file->length ? ( file->length - 1 ) : 0;
851    const tr_block_index_t lastBlock        =
852        ( file->offset + lastOffset ) / tor->blockSize;
853    const uint64_t         lastBlockOffset  =
854        ( file->offset + lastOffset ) % tor->blockSize;
855    uint64_t               haveBytes = 0;
856
857    assert( tor );
858    assert( fileIndex < tor->info.fileCount );
859    assert( file->offset + file->length <= tor->info.totalSize );
860    assert( ( firstBlock < tor->blockCount )
861          || ( !file->length && file->offset == tor->info.totalSize ) );
862    assert( ( lastBlock < tor->blockCount )
863          || ( !file->length && file->offset == tor->info.totalSize ) );
864    assert( firstBlock <= lastBlock );
865    assert( tr_torBlockPiece( tor, firstBlock ) == file->firstPiece );
866    assert( tr_torBlockPiece( tor, lastBlock ) == file->lastPiece );
867
868    if( firstBlock == lastBlock )
869    {
870        if( tr_cpBlockIsComplete( &tor->completion, firstBlock ) )
871            haveBytes += lastBlockOffset + 1 - firstBlockOffset;
872    }
873    else
874    {
875        tr_block_index_t i;
876
877        if( tr_cpBlockIsComplete( &tor->completion, firstBlock ) )
878            haveBytes += tor->blockSize - firstBlockOffset;
879
880        for( i = firstBlock + 1; i < lastBlock; ++i )
881            if( tr_cpBlockIsComplete( &tor->completion, i ) )
882                haveBytes += tor->blockSize;
883
884        if( tr_cpBlockIsComplete( &tor->completion, lastBlock ) )
885            haveBytes += lastBlockOffset + 1;
886    }
887
888    return haveBytes;
889}
890
891tr_file_stat *
892tr_torrentFiles( const tr_torrent * tor,
893                 tr_file_index_t *  fileCount )
894{
895    tr_file_index_t       i;
896    const tr_file_index_t n = tor->info.fileCount;
897    tr_file_stat *        files = tr_new0( tr_file_stat, n );
898    tr_file_stat *        walk = files;
899
900    for( i = 0; i < n; ++i, ++walk )
901    {
902        const uint64_t b = fileBytesCompleted( tor, i );
903        walk->bytesCompleted = b;
904        walk->progress = tr_getRatio( b, tor->info.files[i].length );
905    }
906
907    if( fileCount )
908        *fileCount = n;
909
910    return files;
911}
912
913void
914tr_torrentFilesFree( tr_file_stat *            files,
915                     tr_file_index_t fileCount UNUSED )
916{
917    tr_free( files );
918}
919
920/***
921****
922***/
923
924float*
925tr_torrentWebSpeeds( const tr_torrent * tor )
926{
927    return tor ? tr_peerMgrWebSpeeds( tor->session->peerMgr, tor->info.hash )
928           : NULL;
929}
930
931tr_peer_stat *
932tr_torrentPeers( const tr_torrent * tor,
933                 int *              peerCount )
934{
935    tr_peer_stat * ret = NULL;
936
937    if( tor )
938        ret = tr_peerMgrPeerStats( tor->session->peerMgr,
939                                   tor->info.hash, peerCount );
940
941    return ret;
942}
943
944void
945tr_torrentPeersFree( tr_peer_stat * peers,
946                     int peerCount  UNUSED )
947{
948    tr_free( peers );
949}
950
951void
952tr_torrentAvailability( const tr_torrent * tor,
953                        int8_t *           tab,
954                        int                size )
955{
956    tr_peerMgrTorrentAvailability( tor->session->peerMgr,
957                                   tor->info.hash,
958                                   tab, size );
959}
960
961void
962tr_torrentAmountFinished( const tr_torrent * tor,
963                          float *            tab,
964                          int                size )
965{
966    tr_torrentLock( tor );
967    tr_cpGetAmountDone( &tor->completion, tab, size );
968    tr_torrentUnlock( tor );
969}
970
971void
972tr_torrentResetTransferStats( tr_torrent * tor )
973{
974    tr_torrentLock( tor );
975
976    tor->downloadedPrev += tor->downloadedCur;
977    tor->downloadedCur   = 0;
978    tor->uploadedPrev   += tor->uploadedCur;
979    tor->uploadedCur     = 0;
980    tor->corruptPrev    += tor->corruptCur;
981    tor->corruptCur      = 0;
982
983    tr_torrentUnlock( tor );
984}
985
986void
987tr_torrentSetHasPiece( tr_torrent *     tor,
988                       tr_piece_index_t pieceIndex,
989                       tr_bool          has )
990{
991    tr_torrentLock( tor );
992
993    assert( tor );
994    assert( pieceIndex < tor->info.pieceCount );
995
996    if( has )
997        tr_cpPieceAdd( &tor->completion, pieceIndex );
998    else
999        tr_cpPieceRem( &tor->completion, pieceIndex );
1000
1001    tr_torrentUnlock( tor );
1002}
1003
1004/***
1005****
1006***/
1007
1008static void
1009freeTorrent( tr_torrent * tor )
1010{
1011    tr_torrent * t;
1012    tr_session *  session = tor->session;
1013    tr_info *    inf = &tor->info;
1014
1015    assert( tor );
1016    assert( !tor->isRunning );
1017
1018    tr_globalLock( session );
1019
1020    tr_peerMgrRemoveTorrent( session->peerMgr, tor->info.hash );
1021
1022    tr_cpDestruct( &tor->completion );
1023
1024    tr_rcDestruct( &tor->swarmSpeed );
1025
1026    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
1027    tr_trackerFree( tor->tracker );
1028    tor->tracker = NULL;
1029
1030    tr_bitfieldDestruct( &tor->checkedPieces );
1031
1032    tr_free( tor->downloadDir );
1033    tr_free( tor->peer_id );
1034
1035    if( tor == session->torrentList )
1036        session->torrentList = tor->next;
1037    else for( t = session->torrentList; t != NULL; t = t->next ) {
1038        if( t->next == tor ) {
1039            t->next = tor->next;
1040            break;
1041        }
1042    }
1043
1044    assert( session->torrentCount >= 1 );
1045    session->torrentCount--;
1046
1047    tr_bandwidthFree( tor->bandwidth );
1048
1049    tr_metainfoFree( inf );
1050    tr_free( tor );
1051
1052    tr_globalUnlock( session );
1053}
1054
1055/**
1056***  Start/Stop Callback
1057**/
1058
1059static void
1060checkAndStartImpl( void * vtor )
1061{
1062    tr_torrent * tor = vtor;
1063
1064    tr_globalLock( tor->session );
1065
1066    tor->isRunning = 1;
1067    *tor->errorString = '\0';
1068    tr_torrentResetTransferStats( tor );
1069    tor->completeness = tr_cpGetStatus( &tor->completion );
1070    tr_torrentSaveResume( tor );
1071    tor->startDate = time( NULL );
1072    tr_trackerStart( tor->tracker );
1073    tr_peerMgrStartTorrent( tor->session->peerMgr, tor->info.hash );
1074
1075    tr_globalUnlock( tor->session );
1076}
1077
1078static void
1079checkAndStartCB( tr_torrent * tor )
1080{
1081    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1082}
1083
1084static void
1085torrentStart( tr_torrent * tor,
1086              int          reloadProgress )
1087{
1088    tr_globalLock( tor->session );
1089
1090    if( !tor->isRunning )
1091    {
1092        const int isVerifying = tr_verifyInProgress( tor );
1093
1094        if( !isVerifying && reloadProgress )
1095            tr_torrentLoadResume( tor, TR_FR_PROGRESS, NULL );
1096
1097        tor->isRunning = 1;
1098
1099        if( !isVerifying )
1100            tr_verifyAdd( tor, checkAndStartCB );
1101    }
1102
1103    tr_globalUnlock( tor->session );
1104}
1105
1106void
1107tr_torrentStart( tr_torrent * tor )
1108{
1109    if( tor )
1110        torrentStart( tor, TRUE );
1111}
1112
1113static void
1114torrentRecheckDoneImpl( void * vtor )
1115{
1116    tr_torrentRecheckCompleteness( vtor );
1117}
1118
1119static void
1120torrentRecheckDoneCB( tr_torrent * tor )
1121{
1122    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1123}
1124
1125void
1126tr_torrentVerify( tr_torrent * tor )
1127{
1128    tr_verifyRemove( tor );
1129
1130    tr_globalLock( tor->session );
1131
1132    tr_torrentUncheck( tor );
1133    tr_verifyAdd( tor, torrentRecheckDoneCB );
1134
1135    tr_globalUnlock( tor->session );
1136}
1137
1138static void
1139stopTorrent( void * vtor )
1140{
1141    tr_file_index_t i;
1142
1143    tr_torrent *    tor = vtor;
1144
1145    tr_verifyRemove( tor );
1146    tr_peerMgrStopTorrent( tor->session->peerMgr, tor->info.hash );
1147    tr_trackerStop( tor->tracker );
1148
1149    for( i = 0; i < tor->info.fileCount; ++i )
1150    {
1151        const tr_file * file = &tor->info.files[i];
1152        char * path = tr_buildPath( tor->downloadDir, file->name, NULL );
1153        tr_fdFileClose( path );
1154        tr_free( path );
1155    }
1156}
1157
1158void
1159tr_torrentStop( tr_torrent * tor )
1160{
1161    if( tor )
1162    {
1163        tr_globalLock( tor->session );
1164
1165        tor->isRunning = 0;
1166        if( !tor->isDeleting )
1167            tr_torrentSaveResume( tor );
1168        tr_runInEventThread( tor->session, stopTorrent, tor );
1169
1170        tr_globalUnlock( tor->session );
1171    }
1172}
1173
1174static void
1175closeTorrent( void * vtor )
1176{
1177    tr_torrent * tor = vtor;
1178
1179    tr_torrentSaveResume( tor );
1180    tor->isRunning = 0;
1181    stopTorrent( tor );
1182    if( tor->isDeleting )
1183    {
1184        tr_metainfoRemoveSaved( tor->session, &tor->info );
1185        tr_torrentRemoveResume( tor );
1186    }
1187    freeTorrent( tor );
1188}
1189
1190void
1191tr_torrentFree( tr_torrent * tor )
1192{
1193    if( tor )
1194    {
1195        tr_session * session = tor->session;
1196        tr_globalLock( session );
1197
1198        tr_torrentClearCompletenessCallback( tor );
1199        tr_runInEventThread( session, closeTorrent, tor );
1200
1201        tr_globalUnlock( session );
1202    }
1203}
1204
1205void
1206tr_torrentRemove( tr_torrent * tor )
1207{
1208    tor->isDeleting = 1;
1209    tr_torrentFree( tor );
1210}
1211
1212/**
1213***  Completeness
1214**/
1215
1216static const char *
1217getCompletionString( int type )
1218{
1219    switch( type )
1220    {
1221        /* Translators: this is a minor point that's safe to skip over, but FYI:
1222           "Complete" and "Done" are specific, different terms in Transmission:
1223           "Complete" means we've downloaded every file in the torrent.
1224           "Done" means we're done downloading the files we wanted, but NOT all
1225           that exist */
1226        case TR_PARTIAL_SEED:
1227            return _( "Done" );
1228
1229        case TR_SEED:
1230            return _( "Complete" );
1231
1232        default:
1233            return _( "Incomplete" );
1234    }
1235}
1236
1237static void
1238fireCompletenessChange( tr_torrent       * tor,
1239                        tr_completeness    status )
1240{
1241    assert( tor );
1242    assert( ( status == TR_LEECH )
1243         || ( status == TR_SEED )
1244         || ( status == TR_PARTIAL_SEED ) );
1245
1246    if( tor->completeness_func )
1247        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1248}
1249
1250void
1251tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1252                                   tr_torrent_completeness_func    func,
1253                                   void                          * user_data )
1254{
1255    assert( tor );
1256    tor->completeness_func = func;
1257    tor->completeness_func_user_data = user_data;
1258}
1259
1260void
1261tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1262{
1263    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1264}
1265
1266void
1267tr_torrentRecheckCompleteness( tr_torrent * tor )
1268{
1269    tr_completeness completeness;
1270
1271    tr_torrentLock( tor );
1272
1273    completeness = tr_cpGetStatus( &tor->completion );
1274
1275    if( completeness != tor->completeness )
1276    {
1277        const int recentChange = tor->downloadedCur != 0;
1278
1279        if( recentChange )
1280        {
1281            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1282                      getCompletionString( tor->completeness ),
1283                      getCompletionString( completeness ) );
1284        }
1285
1286        tor->completeness = completeness;
1287        fireCompletenessChange( tor, completeness );
1288
1289        if( recentChange && ( completeness == TR_SEED ) )
1290        {
1291            tr_trackerCompleted( tor->tracker );
1292
1293            tor->doneDate = time( NULL );
1294        }
1295
1296        tr_torrentSaveResume( tor );
1297    }
1298
1299    tr_torrentUnlock( tor );
1300}
1301
1302/**
1303***  File priorities
1304**/
1305
1306void
1307tr_torrentInitFilePriority( tr_torrent *    tor,
1308                            tr_file_index_t fileIndex,
1309                            tr_priority_t   priority )
1310{
1311    tr_piece_index_t i;
1312    tr_file *        file;
1313
1314    assert( tor );
1315    assert( fileIndex < tor->info.fileCount );
1316    assert(
1317        priority == TR_PRI_LOW || priority == TR_PRI_NORMAL || priority ==
1318        TR_PRI_HIGH );
1319
1320    file = &tor->info.files[fileIndex];
1321    file->priority = priority;
1322    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1323        tor->info.pieces[i].priority = calculatePiecePriority( tor, i,
1324                                                               fileIndex );
1325}
1326
1327void
1328tr_torrentSetFilePriorities( tr_torrent *      tor,
1329                             tr_file_index_t * files,
1330                             tr_file_index_t   fileCount,
1331                             tr_priority_t     priority )
1332{
1333    tr_file_index_t i;
1334
1335    tr_torrentLock( tor );
1336
1337    for( i = 0; i < fileCount; ++i )
1338        tr_torrentInitFilePriority( tor, files[i], priority );
1339
1340    tr_torrentSaveResume( tor );
1341    tr_torrentUnlock( tor );
1342}
1343
1344tr_priority_t
1345tr_torrentGetFilePriority( const tr_torrent * tor,
1346                           tr_file_index_t    file )
1347{
1348    tr_priority_t ret;
1349
1350    tr_torrentLock( tor );
1351    assert( tor );
1352    assert( file < tor->info.fileCount );
1353    ret = tor->info.files[file].priority;
1354    tr_torrentUnlock( tor );
1355
1356    return ret;
1357}
1358
1359tr_priority_t*
1360tr_torrentGetFilePriorities( const tr_torrent * tor )
1361{
1362    tr_file_index_t i;
1363    tr_priority_t * p;
1364
1365    tr_torrentLock( tor );
1366    p = tr_new0( tr_priority_t, tor->info.fileCount );
1367    for( i = 0; i < tor->info.fileCount; ++i )
1368        p[i] = tor->info.files[i].priority;
1369    tr_torrentUnlock( tor );
1370
1371    return p;
1372}
1373
1374/**
1375***  File DND
1376**/
1377
1378int
1379tr_torrentGetFileDL( const tr_torrent * tor,
1380                     tr_file_index_t    file )
1381{
1382    int doDownload;
1383
1384    tr_torrentLock( tor );
1385
1386    assert( file < tor->info.fileCount );
1387    doDownload = !tor->info.files[file].dnd;
1388
1389    tr_torrentUnlock( tor );
1390    return doDownload != 0;
1391}
1392
1393static void
1394setFileDND( tr_torrent *    tor,
1395            tr_file_index_t fileIndex,
1396            int             doDownload )
1397{
1398    tr_file *        file;
1399    const int        dnd = !doDownload;
1400    tr_piece_index_t firstPiece, firstPieceDND;
1401    tr_piece_index_t lastPiece, lastPieceDND;
1402    tr_file_index_t  i;
1403
1404    file = &tor->info.files[fileIndex];
1405    file->dnd = dnd;
1406    firstPiece = file->firstPiece;
1407    lastPiece = file->lastPiece;
1408
1409    /* can't set the first piece to DND unless
1410       every file using that piece is DND */
1411    firstPieceDND = dnd;
1412    if( fileIndex > 0 )
1413    {
1414        for( i = fileIndex - 1; firstPieceDND; --i )
1415        {
1416            if( tor->info.files[i].lastPiece != firstPiece )
1417                break;
1418            firstPieceDND = tor->info.files[i].dnd;
1419            if( !i )
1420                break;
1421        }
1422    }
1423
1424    /* can't set the last piece to DND unless
1425       every file using that piece is DND */
1426    lastPieceDND = dnd;
1427    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1428    {
1429        if( tor->info.files[i].firstPiece != lastPiece )
1430            break;
1431        lastPieceDND = tor->info.files[i].dnd;
1432    }
1433
1434    if( firstPiece == lastPiece )
1435    {
1436        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1437    }
1438    else
1439    {
1440        tr_piece_index_t pp;
1441        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1442        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1443        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1444            tor->info.pieces[pp].dnd = dnd;
1445    }
1446}
1447
1448void
1449tr_torrentInitFileDLs( tr_torrent *      tor,
1450                       tr_file_index_t * files,
1451                       tr_file_index_t   fileCount,
1452                       tr_bool           doDownload )
1453{
1454    tr_file_index_t i;
1455
1456    tr_torrentLock( tor );
1457
1458    for( i = 0; i < fileCount; ++i )
1459        setFileDND( tor, files[i], doDownload );
1460    tr_cpInvalidateDND ( &tor->completion );
1461
1462    tr_torrentUnlock( tor );
1463}
1464
1465void
1466tr_torrentSetFileDLs( tr_torrent *      tor,
1467                      tr_file_index_t * files,
1468                      tr_file_index_t   fileCount,
1469                      tr_bool           doDownload )
1470{
1471    tr_torrentLock( tor );
1472    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1473    tr_torrentSaveResume( tor );
1474    tr_torrentUnlock( tor );
1475}
1476
1477/***
1478****
1479***/
1480
1481void
1482tr_torrentSetPeerLimit( tr_torrent * tor,
1483                        uint16_t     maxConnectedPeers )
1484{
1485    tor->maxConnectedPeers = maxConnectedPeers;
1486}
1487
1488uint16_t
1489tr_torrentGetPeerLimit( const tr_torrent * tor )
1490{
1491    return tor->maxConnectedPeers;
1492}
1493
1494/***
1495****
1496***/
1497
1498tr_block_index_t
1499_tr_block( const tr_torrent * tor,
1500           tr_piece_index_t   index,
1501           uint32_t           offset )
1502{
1503    const tr_info *  inf = &tor->info;
1504    tr_block_index_t ret;
1505
1506    ret = index;
1507    ret *= ( inf->pieceSize / tor->blockSize );
1508    ret += offset / tor->blockSize;
1509    return ret;
1510}
1511
1512tr_bool
1513tr_torrentReqIsValid( const tr_torrent * tor,
1514                      tr_piece_index_t   index,
1515                      uint32_t           offset,
1516                      uint32_t           length )
1517{
1518    int err = 0;
1519
1520    if( index >= tor->info.pieceCount )
1521        err = 1;
1522    else if( length < 1 )
1523        err = 2;
1524    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1525        err = 3;
1526    else if( length > MAX_BLOCK_SIZE )
1527        err = 4;
1528    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1529        err = 5;
1530
1531    if( err ) fprintf( stderr, "index %lu offset %lu length %lu err %d\n",
1532                       (unsigned long)index, (unsigned long)offset,
1533                       (unsigned long)length,
1534                       err );
1535
1536    return !err;
1537}
1538
1539uint64_t
1540tr_pieceOffset( const tr_torrent * tor,
1541                tr_piece_index_t   index,
1542                uint32_t           offset,
1543                uint32_t           length )
1544{
1545    uint64_t ret;
1546
1547    ret = tor->info.pieceSize;
1548    ret *= index;
1549    ret += offset;
1550    ret += length;
1551    return ret;
1552}
1553
1554/***
1555****
1556***/
1557
1558void
1559tr_torrentSetPieceChecked( tr_torrent        * tor,
1560                           tr_piece_index_t    piece,
1561                           tr_bool             isChecked )
1562{
1563    if( isChecked )
1564        tr_bitfieldAdd( &tor->checkedPieces, piece );
1565    else
1566        tr_bitfieldRem( &tor->checkedPieces, piece );
1567}
1568
1569void
1570tr_torrentSetFileChecked( tr_torrent *    tor,
1571                          tr_file_index_t fileIndex,
1572                          tr_bool         isChecked )
1573{
1574    const tr_file *        file = &tor->info.files[fileIndex];
1575    const tr_piece_index_t begin = file->firstPiece;
1576    const tr_piece_index_t end = file->lastPiece + 1;
1577
1578    if( isChecked )
1579        tr_bitfieldAddRange ( &tor->checkedPieces, begin, end );
1580    else
1581        tr_bitfieldRemRange ( &tor->checkedPieces, begin, end );
1582}
1583
1584tr_bool
1585tr_torrentIsFileChecked( const tr_torrent * tor,
1586                         tr_file_index_t    fileIndex )
1587{
1588    const tr_file *        file = &tor->info.files[fileIndex];
1589    const tr_piece_index_t begin = file->firstPiece;
1590    const tr_piece_index_t end = file->lastPiece + 1;
1591    tr_piece_index_t       i;
1592    tr_bool                isChecked = TRUE;
1593
1594    for( i = begin; isChecked && i < end; ++i )
1595        if( !tr_torrentIsPieceChecked( tor, i ) )
1596            isChecked = FALSE;
1597
1598    return isChecked;
1599}
1600
1601void
1602tr_torrentUncheck( tr_torrent * tor )
1603{
1604    tr_bitfieldRemRange ( &tor->checkedPieces, 0, tor->info.pieceCount );
1605}
1606
1607int
1608tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1609{
1610    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
1611}
1612
1613time_t*
1614tr_torrentGetMTimes( const tr_torrent * tor,
1615                     size_t *           setme_n )
1616{
1617    size_t       i;
1618    const size_t n = tor->info.fileCount;
1619    time_t *     m = tr_new0( time_t, n );
1620
1621    for( i = 0; i < n; ++i )
1622    {
1623        struct stat sb;
1624        char * path = tr_buildPath( tor->downloadDir, tor->info.files[i].name, NULL );
1625        if( !stat( path, &sb ) )
1626        {
1627#ifdef SYS_DARWIN
1628            m[i] = sb.st_mtimespec.tv_sec;
1629#else
1630            m[i] = sb.st_mtime;
1631#endif
1632        }
1633        tr_free( path );
1634    }
1635
1636    *setme_n = n;
1637    return m;
1638}
1639
1640/***
1641****
1642***/
1643
1644void
1645tr_torrentSetAnnounceList( tr_torrent *            tor,
1646                           const tr_tracker_info * trackers,
1647                           int                     trackerCount )
1648{
1649    tr_benc metainfo;
1650
1651    /* save to the .torrent file */
1652    if( !tr_bencLoadFile( tor->info.torrent, &metainfo ) )
1653    {
1654        int       i;
1655        int       prevTier = -1;
1656        tr_benc * tier = NULL;
1657        tr_benc * announceList;
1658        tr_info   tmpInfo;
1659
1660        /* remove the old fields */
1661        tr_bencDictRemove( &metainfo, "announce" );
1662        tr_bencDictRemove( &metainfo, "announce-list" );
1663
1664        /* add the new fields */
1665        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
1666        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
1667        for( i = 0; i < trackerCount; ++i ) {
1668            if( prevTier != trackers[i].tier ) {
1669                prevTier = trackers[i].tier;
1670                tier = tr_bencListAddList( announceList, 0 );
1671            }
1672            tr_bencListAddStr( tier, trackers[i].announce );
1673        }
1674
1675        /* try to parse it back again, to make sure it's good */
1676        memset( &tmpInfo, 0, sizeof( tr_info ) );
1677        if( !tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
1678        {
1679            /* it's good, so keep these new trackers and free the old ones */
1680
1681            tr_info swap;
1682            swap.trackers = tor->info.trackers;
1683            swap.trackerCount = tor->info.trackerCount;
1684            tor->info.trackers = tmpInfo.trackers;
1685            tor->info.trackerCount = tmpInfo.trackerCount;
1686            tmpInfo.trackers = swap.trackers;
1687            tmpInfo.trackerCount = swap.trackerCount;
1688
1689            tr_metainfoFree( &tmpInfo );
1690            tr_bencSaveFile( tor->info.torrent, &metainfo );
1691        }
1692
1693        /* cleanup */
1694        tr_bencFree( &metainfo );
1695    }
1696}
1697
1698/**
1699***
1700**/
1701
1702/** @deprecated this method will be removed in 1.40 */
1703void
1704tr_torrentSetAddedDate( tr_torrent * tor,
1705                        time_t       t )
1706{
1707    tor->addedDate = t;
1708}
1709
1710/** @deprecated this method will be removed in 1.40 */
1711void
1712tr_torrentSetActivityDate( tr_torrent * tor,
1713                           time_t       t )
1714{
1715    tor->activityDate = t;
1716}
1717
1718/** @deprecated this method will be removed in 1.40 */
1719void
1720tr_torrentSetDoneDate( tr_torrent * tor,
1721                       time_t       t )
1722{
1723    tor->doneDate = t;
1724}
1725
1726/**
1727***
1728**/
1729
1730uint64_t
1731tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
1732{
1733    const tr_file * it;
1734    const tr_file * end;
1735    struct stat sb;
1736    uint64_t bytesLeft = 0;
1737
1738    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
1739    {
1740        if( !it->dnd )
1741        {
1742            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
1743
1744            bytesLeft += it->length;
1745
1746            if( !stat( path, &sb )
1747                    && S_ISREG( sb.st_mode )
1748                    && ( (uint64_t)sb.st_size <= it->length ) )
1749                bytesLeft -= sb.st_size;
1750
1751            tr_free( path );
1752        }
1753    }
1754
1755    return bytesLeft;
1756}
1757
1758/****
1759*****  Removing the torrent's local data
1760****/
1761
1762static int
1763vstrcmp( const void * a, const void * b )
1764{
1765    return strcmp( a, b );
1766}
1767
1768static int
1769compareLongestFirst( const void * a, const void * b )
1770{
1771    const size_t alen = strlen( a );
1772    const size_t blen = strlen( b );
1773
1774    if( alen != blen )
1775        return alen > blen ? -1 : 1;
1776
1777    return vstrcmp( a, b );
1778}
1779
1780static void
1781addDirtyFile( const char  * root,
1782              const char  * filename,
1783              tr_ptrArray * dirtyFolders )
1784{
1785    char * dir = tr_dirname( filename );
1786
1787    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
1788    while (     ( dir != NULL )
1789             && ( strlen( root ) <= strlen( dir ) )
1790             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
1791    {
1792        char * tmp;
1793        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
1794
1795        tmp = tr_dirname( dir );
1796        tr_free( dir );
1797        dir = tmp;
1798    }
1799
1800    tr_free( dir );
1801}
1802
1803static void
1804walkLocalData( const tr_torrent * tor,
1805               const char       * root,
1806               const char       * dir,
1807               const char       * base,
1808               tr_ptrArray      * torrentFiles,
1809               tr_ptrArray      * folders,
1810               tr_ptrArray      * dirtyFolders )
1811{
1812    int i;
1813    struct stat sb;
1814    char * buf;
1815
1816    buf = tr_buildPath( dir, base, NULL );
1817    i = stat( buf, &sb );
1818    if( !i )
1819    {
1820        DIR * odir = NULL;
1821
1822        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
1823        {
1824            struct dirent *d;
1825            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
1826            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
1827                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
1828                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
1829            closedir( odir );
1830        }
1831        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
1832        {
1833            const char * sub = buf + strlen( tor->downloadDir ) + strlen( TR_PATH_DELIMITER_STR );
1834            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
1835            if( !isTorrentFile )
1836                addDirtyFile( root, buf, dirtyFolders );
1837        }
1838    }
1839
1840    tr_free( buf );
1841}
1842
1843static void
1844deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
1845{
1846    int i, n;
1847    char ** s;
1848    tr_file_index_t f;
1849    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
1850    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
1851    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
1852
1853    const char * firstFile = tor->info.files[0].name;
1854    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
1855    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
1856    char * root = tr_buildPath( tor->downloadDir, tmp, NULL );
1857
1858    for( f=0; f<tor->info.fileCount; ++f )
1859        tr_ptrArrayInsertSorted( &torrentFiles, tor->info.files[f].name, vstrcmp );
1860
1861    /* build the set of folders and dirtyFolders */
1862    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
1863
1864    /* close all the files because we're about to delete them */
1865    for( f=0; f<tor->info.fileCount; ++f ) {
1866        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
1867        tr_fdFileClose( path );
1868        tr_free( path );
1869    }
1870
1871    /* try to remove entire folders first, so that the recycle bin will be tidy */
1872    s = (char**) tr_ptrArrayPeek( &folders, &n );
1873    for( i=0; i<n; ++i )
1874        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
1875            fileFunc( s[i] );
1876
1877    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
1878    for( f=0; f<tor->info.fileCount; ++f ) {
1879        char * path = tr_buildPath( tor->downloadDir, tor->info.files[f].name, NULL );
1880        fileFunc( path );
1881        tr_free( path );
1882    }
1883
1884    /* Now clean out the directories left empty from the previous step.
1885     * Work from deepest to shallowest s.t. lower folders
1886     * won't prevent the upper folders from being deleted */
1887    {
1888        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
1889        s = (char**) tr_ptrArrayPeek( &folders, &n );
1890        for( i=0; i<n; ++i )
1891            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
1892                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
1893        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
1894        for( i=0; i<n; ++i )
1895            fileFunc( s[i] );
1896        tr_ptrArrayDestruct( &cleanFolders, NULL );
1897    }
1898
1899    /* cleanup */
1900    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
1901    tr_ptrArrayDestruct( &folders, tr_free );
1902    tr_ptrArrayDestruct( &torrentFiles, NULL );
1903    tr_free( root );
1904    tr_free( tmp );
1905}
1906
1907void
1908tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
1909{
1910    if( fileFunc == NULL )
1911        fileFunc = unlink;
1912
1913    if( tor->info.fileCount > 1 )
1914        deleteLocalData( tor, fileFunc );
1915    else {
1916        /* torrent only has one file */
1917        char * path = tr_buildPath( tor->downloadDir, tor->info.files[0].name, NULL );
1918        tr_fdFileClose( path );
1919        fileFunc( path );
1920        tr_free( path );
1921    }
1922}
Note: See TracBrowser for help on using the repository browser.