source: trunk/libtransmission/torrent.c @ 7147

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

(libT) #1468: another stab at getting the peer transfer speeds both fast and a little more consistent.

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