source: trunk/libtransmission/torrent.c @ 7065

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

(libT) revise r7065

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