source: trunk/libtransmission/torrent.c @ 7199

Last change on this file since 7199 was 7199, checked in by charles, 12 years ago

#1379 lay some very early groundwork for "partial seeds" -- change tr_completion's enum to use the partial seed terminology

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