source: trunk/libtransmission/torrent.c @ 7368

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

(trunk libT) semantic cleanup: int -> tr_bool

  • Property svn:keywords set to Date Rev Author Id
File size: 45.4 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 7368 2008-12-13 23:39:12Z 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
88tr_bool
89tr_torrentExists( const tr_handle * handle,
90                  const uint8_t *   torrentHash )
91{
92    return tr_torrentFindFromHash( (tr_handle*)handle,
93                                  torrentHash ) != NULL;
94}
95
96tr_torrent*
97tr_torrentFindFromHash( tr_handle *     handle,
98                        const uint8_t * torrentHash )
99{
100    tr_torrent * tor = NULL;
101
102    while( ( tor = tr_torrentNext( handle, tor ) ) )
103        if( *tor->info.hash == *torrentHash )
104            if( !memcmp( tor->info.hash, torrentHash, SHA_DIGEST_LENGTH ) )
105                return tor;
106
107    return NULL;
108}
109
110tr_torrent*
111tr_torrentFindFromObfuscatedHash( tr_handle *     handle,
112                                  const uint8_t * obfuscatedTorrentHash )
113{
114    tr_torrent * tor = NULL;
115
116    while( ( tor = tr_torrentNext( handle, tor ) ) )
117        if( !memcmp( tor->obfuscatedHash, obfuscatedTorrentHash,
118                     SHA_DIGEST_LENGTH ) )
119            return tor;
120
121    return NULL;
122}
123
124/***
125****  LOCKS
126***/
127
128void
129tr_torrentLock( const tr_torrent * tor )
130{
131    tr_globalLock( tor->session );
132}
133
134void
135tr_torrentUnlock( const tr_torrent * tor )
136{
137    tr_globalUnlock( tor->session );
138}
139
140/***
141****  PER-TORRENT UL / DL SPEEDS
142***/
143
144void
145tr_torrentSetSpeedMode( tr_torrent *  tor,
146                        tr_direction  dir,
147                        tr_speedlimit mode )
148{
149    assert( tor != NULL );
150    assert( dir==TR_UP || dir==TR_DOWN );
151    assert( mode==TR_SPEEDLIMIT_GLOBAL || mode==TR_SPEEDLIMIT_SINGLE || mode==TR_SPEEDLIMIT_UNLIMITED  );
152
153    tor->speedLimitMode[dir] = mode;
154
155    tr_bandwidthSetLimited( tor->bandwidth, dir, mode==TR_SPEEDLIMIT_SINGLE );
156    tr_bandwidthHonorParentLimits( tor->bandwidth, dir, mode==TR_SPEEDLIMIT_GLOBAL );
157}
158
159tr_speedlimit
160tr_torrentGetSpeedMode( const tr_torrent * tor,
161                        tr_direction       dir )
162{
163    assert( tor != NULL );
164    assert( dir==TR_UP || dir==TR_DOWN );
165
166    return tor->speedLimitMode[dir];
167}
168
169void
170tr_torrentSetSpeedLimit( tr_torrent * tor,
171                         tr_direction dir,
172                         int          desiredSpeed )
173{
174    tr_bandwidthSetDesiredSpeed( tor->bandwidth, dir, desiredSpeed );
175}
176
177int
178tr_torrentGetSpeedLimit( const tr_torrent * tor,
179                         tr_direction       dir )
180{
181    return tr_bandwidthGetDesiredSpeed( tor->bandwidth, dir );
182}
183
184tr_bool
185tr_torrentIsPieceTransferAllowed( const tr_torrent  * tor,
186                                  tr_direction        direction )
187{
188    tr_bool isEnabled = FALSE;
189
190    switch( tr_torrentGetSpeedMode( tor, direction ) )
191    {
192        case TR_SPEEDLIMIT_GLOBAL:
193            isEnabled = !tr_sessionIsSpeedLimitEnabled( tor->session, direction )
194                      || tr_sessionGetSpeedLimit( tor->session, direction ) > 0;
195            break;
196
197        case TR_SPEEDLIMIT_SINGLE:
198            isEnabled = tr_torrentGetSpeedLimit( tor, direction ) > 0;
199            break;
200
201        case TR_SPEEDLIMIT_UNLIMITED:
202            isEnabled = TRUE;
203            break;
204
205        default:
206            assert( 0 && "unhandled speed mode" );
207            break;
208    }
209
210    return isEnabled;
211}
212
213/***
214****
215***/
216
217static void
218onTrackerResponse( void * tracker UNUSED,
219                   void *         vevent,
220                   void *         user_data )
221{
222    tr_torrent *       tor = user_data;
223    tr_tracker_event * event = vevent;
224
225    switch( event->messageType )
226    {
227        case TR_TRACKER_PEERS:
228        {
229            size_t   i, n;
230            tr_pex * pex = tr_peerMgrCompactToPex( event->compact,
231                                                   event->compactLen,
232                                                   NULL, 0, &n );
233            if( event->allAreSeeds )
234                tr_tordbg( tor, "Got %d seeds from tracker", (int)n );
235            else
236                tr_torinf( tor, _( "Got %d peers from tracker" ), (int)n );
237
238            for( i = 0; i < n; ++i )
239            {
240                if( event->allAreSeeds )
241                    pex[i].flags |= ADDED_F_SEED_FLAG;
242                tr_peerMgrAddPex( tor->session->peerMgr, tor->info.hash,
243                                  TR_PEER_FROM_TRACKER, pex + i );
244            }
245
246            tr_free( pex );
247            break;
248        }
249
250        case TR_TRACKER_WARNING:
251            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
252            tor->error = -1;
253            tr_strlcpy( tor->errorString, event->text,
254                       sizeof( tor->errorString ) );
255            break;
256
257        case TR_TRACKER_ERROR:
258            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
259            tor->error = -2;
260            tr_strlcpy( tor->errorString, event->text,
261                       sizeof( tor->errorString ) );
262            break;
263
264        case TR_TRACKER_ERROR_CLEAR:
265            tor->error = 0;
266            tor->errorString[0] = '\0';
267            break;
268    }
269}
270
271/***
272****
273****  TORRENT INSTANTIATION
274****
275***/
276
277static int
278getBytePiece( const tr_info * info,
279              uint64_t        byteOffset )
280{
281    assert( info );
282    assert( info->pieceSize != 0 );
283
284    return byteOffset / info->pieceSize;
285}
286
287static void
288initFilePieces( tr_info *       info,
289                tr_file_index_t fileIndex )
290{
291    tr_file * file;
292    uint64_t  firstByte, lastByte;
293
294    assert( info );
295    assert( fileIndex < info->fileCount );
296
297    file = &info->files[fileIndex];
298    firstByte = file->offset;
299    lastByte = firstByte + ( file->length ? file->length - 1 : 0 );
300    file->firstPiece = getBytePiece( info, firstByte );
301    file->lastPiece = getBytePiece( info, lastByte );
302}
303
304static int
305pieceHasFile( tr_piece_index_t piece,
306              const tr_file *  file )
307{
308    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
309}
310
311static tr_priority_t
312calculatePiecePriority( const tr_torrent * tor,
313                        tr_piece_index_t   piece,
314                        int                fileHint )
315{
316    tr_file_index_t i;
317    int             priority = TR_PRI_LOW;
318
319    /* find the first file that has data in this piece */
320    if( fileHint >= 0 )
321    {
322        i = fileHint;
323        while( i > 0 && pieceHasFile( piece, &tor->info.files[i - 1] ) )
324            --i;
325    }
326    else
327    {
328        for( i = 0; i < tor->info.fileCount; ++i )
329            if( pieceHasFile( piece, &tor->info.files[i] ) )
330                break;
331    }
332
333    /* the piece's priority is the max of the priorities
334     * of all the files in that piece */
335    for( ; i < tor->info.fileCount; ++i )
336    {
337        const tr_file * file = &tor->info.files[i];
338
339        if( !pieceHasFile( piece, file ) )
340            break;
341
342        priority = MAX( priority, file->priority );
343
344        /* when dealing with multimedia files, getting the first and
345           last pieces can sometimes allow you to preview it a bit
346           before it's fully downloaded... */
347        if( file->priority >= TR_PRI_NORMAL )
348            if( file->firstPiece == piece || file->lastPiece == piece )
349                priority = TR_PRI_HIGH;
350    }
351
352    return priority;
353}
354
355static void
356tr_torrentInitFilePieces( tr_torrent * tor )
357{
358    tr_file_index_t  ff;
359    tr_piece_index_t pp;
360    uint64_t         offset = 0;
361    tr_info *        inf = &tor->info;
362
363    assert( inf );
364
365    for( ff = 0; ff < inf->fileCount; ++ff )
366    {
367        inf->files[ff].offset = offset;
368        offset += inf->files[ff].length;
369        initFilePieces( inf, ff );
370    }
371
372    for( pp = 0; pp < inf->pieceCount; ++pp )
373        inf->pieces[pp].priority = calculatePiecePriority( tor, pp, -1 );
374}
375
376int
377tr_torrentPromoteTracker( tr_torrent * tor,
378                          int          pos )
379{
380    int i;
381    int tier;
382
383    assert( tor );
384    assert( ( 0 <= pos ) && ( pos < tor->info.trackerCount ) );
385
386    /* the tier of the tracker we're promoting */
387    tier = tor->info.trackers[pos].tier;
388
389    /* find the index of that tier's first tracker */
390    for( i = 0; i < tor->info.trackerCount; ++i )
391        if( tor->info.trackers[i].tier == tier )
392            break;
393
394    assert( i < tor->info.trackerCount );
395
396    /* promote the tracker at `pos' to the front of the tier */
397    if( i != pos )
398    {
399        const tr_tracker_info tmp = tor->info.trackers[i];
400        tor->info.trackers[i] = tor->info.trackers[pos];
401        tor->info.trackers[pos] = tmp;
402    }
403
404    /* return the new position of the tracker that started out at [pos] */
405    return i;
406}
407
408struct RandomTracker
409{
410    tr_tracker_info    tracker;
411    int                random_value;
412};
413
414/* the tiers will be sorted from lowest to highest,
415 * and trackers are randomized within the tiers */
416static int
417compareRandomTracker( const void * va,
418                      const void * vb )
419{
420    const struct RandomTracker * a = va;
421    const struct RandomTracker * b = vb;
422
423    if( a->tracker.tier != b->tracker.tier )
424        return a->tracker.tier - b->tracker.tier;
425
426    return a->random_value - b->random_value;
427}
428
429static void
430randomizeTiers( tr_info * info )
431{
432    int                    i;
433    const int              n = info->trackerCount;
434    struct RandomTracker * r = tr_new0( struct RandomTracker, n );
435
436    for( i = 0; i < n; ++i )
437    {
438        r[i].tracker = info->trackers[i];
439        r[i].random_value = tr_cryptoRandInt( INT_MAX );
440    }
441    qsort( r, n, sizeof( struct RandomTracker ), compareRandomTracker );
442    for( i = 0; i < n; ++i )
443        info->trackers[i] = r[i].tracker;
444    tr_free( r );
445}
446
447static void torrentStart( tr_torrent * tor,
448                          int          reloadProgress );
449
450/**
451 * Decide on a block size.  constraints:
452 * (1) most clients decline requests over 16 KiB
453 * (2) pieceSize must be a multiple of block size
454 */
455static uint32_t
456getBlockSize( uint32_t pieceSize )
457{
458    uint32_t b = pieceSize;
459
460    while( b > MAX_BLOCK_SIZE )
461        b /= 2u;
462
463    if( !b || ( pieceSize % b ) ) /* not cleanly divisible */
464        return 0;
465    return b;
466}
467
468static void
469torrentRealInit( tr_handle *     h,
470                 tr_torrent *    tor,
471                 const tr_ctor * ctor )
472{
473    int        doStart;
474    uint64_t   loaded;
475    uint64_t   t;
476    tr_info *  info = &tor->info;
477    static int nextUniqueId = 1;
478
479    tr_globalLock( h );
480
481    tor->session   = h;
482    tor->uniqueId = nextUniqueId++;
483
484    randomizeTiers( info );
485
486    tor->bandwidth = tr_bandwidthNew( h, h->bandwidth );
487
488    tor->blockSize = getBlockSize( info->pieceSize );
489
490    tor->lastPieceSize = info->totalSize % info->pieceSize;
491
492    if( !tor->lastPieceSize )
493        tor->lastPieceSize = info->pieceSize;
494
495    tor->lastBlockSize = info->totalSize % tor->blockSize;
496
497    if( !tor->lastBlockSize )
498        tor->lastBlockSize = tor->blockSize;
499
500    tor->blockCount =
501        ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize;
502
503    tor->blockCountInPiece =
504        info->pieceSize / tor->blockSize;
505
506    tor->blockCountInLastPiece =
507        ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize;
508
509    /* check our work */
510    assert( ( info->pieceSize % tor->blockSize ) == 0 );
511    t = info->pieceCount - 1;
512    t *= info->pieceSize;
513    t += tor->lastPieceSize;
514    assert( t == info->totalSize );
515    t = tor->blockCount - 1;
516    t *= tor->blockSize;
517    t += tor->lastBlockSize;
518    assert( t == info->totalSize );
519    t = info->pieceCount - 1;
520    t *= tor->blockCountInPiece;
521    t += tor->blockCountInLastPiece;
522    assert( t == (uint64_t)tor->blockCount );
523
524    tor->completion = tr_cpInit( tor );
525
526    tr_torrentInitFilePieces( tor );
527
528    tor->swarmSpeed = tr_rcInit( );
529
530    tr_sha1( tor->obfuscatedHash, "req2", 4,
531             info->hash, SHA_DIGEST_LENGTH,
532             NULL );
533
534    tr_peerMgrAddTorrent( h->peerMgr, tor );
535
536    assert( h->isPortSet );
537
538    assert( !tor->downloadedCur );
539    assert( !tor->uploadedCur );
540
541    tor->error   = 0;
542
543    tor->checkedPieces = tr_bitfieldNew( tor->info.pieceCount );
544    tr_torrentUncheck( tor );
545
546    tor->addedDate = time( NULL ); /* this is a default value to be
547                                      overwritten by the resume file */
548    loaded = tr_torrentLoadResume( tor, ~0, ctor );
549
550    doStart = tor->isRunning;
551    tor->isRunning = 0;
552
553    if( !( loaded & TR_FR_SPEEDLIMIT ) )
554    {
555        tr_torrentSetSpeedLimit( tor, TR_UP,
556                                tr_sessionGetSpeedLimit( tor->session, TR_UP ) );
557        tr_torrentSetSpeedLimit( tor, TR_DOWN,
558                                tr_sessionGetSpeedLimit( tor->session,
559                                                         TR_DOWN ) );
560    }
561
562    tor->completeness = tr_cpGetStatus( tor->completion );
563
564    tor->tracker = tr_trackerNew( tor );
565    tor->trackerSubscription =
566        tr_trackerSubscribe( tor->tracker, onTrackerResponse,
567                             tor );
568
569    {
570        tr_torrent * it = NULL;
571        tr_torrent * last = NULL;
572        while( ( it = tr_torrentNext( h, it ) ) )
573            last = it;
574
575        if( !last )
576            h->torrentList = tor;
577        else
578            last->next = tor;
579        ++h->torrentCount;
580    }
581
582    tr_globalUnlock( h );
583
584    /* maybe save our own copy of the metainfo */
585    if( tr_ctorGetSave( ctor ) )
586    {
587        const tr_benc * val;
588        if( !tr_ctorGetMetainfo( ctor, &val ) )
589        {
590            const char * filename = tor->info.torrent;
591            tr_bencSaveFile( filename, val );
592            tr_sessionSetTorrentFile( tor->session, tor->info.hashString,
593                                      filename );
594        }
595    }
596
597    tr_metainfoMigrate( h, &tor->info );
598
599    if( doStart )
600        torrentStart( tor, FALSE );
601}
602
603int
604tr_torrentParse( const tr_handle * handle,
605                 const tr_ctor *   ctor,
606                 tr_info *         setmeInfo )
607{
608    int             err = 0;
609    int             doFree;
610    tr_info         tmp;
611    const tr_benc * metainfo;
612
613    if( setmeInfo == NULL )
614        setmeInfo = &tmp;
615    memset( setmeInfo, 0, sizeof( tr_info ) );
616
617    if( !err && tr_ctorGetMetainfo( ctor, &metainfo ) )
618        return TR_EINVALID;
619
620    err = tr_metainfoParse( handle, setmeInfo, metainfo );
621    doFree = !err && ( setmeInfo == &tmp );
622
623    if( !err && !getBlockSize( setmeInfo->pieceSize ) )
624        err = TR_EINVALID;
625
626    if( !err && tr_torrentExists( handle, setmeInfo->hash ) )
627        err = TR_EDUPLICATE;
628
629    if( doFree )
630        tr_metainfoFree( setmeInfo );
631
632    return err;
633}
634
635tr_torrent *
636tr_torrentNew( tr_handle *     handle,
637               const tr_ctor * ctor,
638               int *           setmeError )
639{
640    int          err;
641    tr_info      tmpInfo;
642    tr_torrent * tor = NULL;
643
644    err = tr_torrentParse( handle, ctor, &tmpInfo );
645    if( !err )
646    {
647        tor = tr_new0( tr_torrent, 1 );
648        tor->info = tmpInfo;
649        torrentRealInit( handle, tor, ctor );
650    }
651    else if( setmeError )
652    {
653        *setmeError = err;
654    }
655
656    return tor;
657}
658
659/**
660***
661**/
662
663void
664tr_torrentSetDownloadDir( tr_torrent * tor,
665                          const char * path )
666{
667    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
668    {
669        tr_free( tor->downloadDir );
670        tor->downloadDir = tr_strdup( path );
671        tr_torrentSaveResume( tor );
672    }
673}
674
675const char*
676tr_torrentGetDownloadDir( const tr_torrent * tor )
677{
678    return tor->downloadDir;
679}
680
681void
682tr_torrentChangeMyPort( tr_torrent * tor )
683{
684    if( tor->tracker )
685        tr_trackerChangeMyPort( tor->tracker );
686}
687
688tr_bool
689tr_torrentIsPrivate( const tr_torrent * tor )
690{
691    return tor
692        && tor->info.isPrivate;
693}
694
695tr_bool
696tr_torrentAllowsPex( const tr_torrent * tor )
697{
698    return tor
699        && tor->session->isPexEnabled
700        && !tr_torrentIsPrivate( tor );
701}
702
703static void
704tr_torrentManualUpdateImpl( void * vtor )
705{
706    tr_torrent * tor = vtor;
707
708    if( tor->isRunning )
709        tr_trackerReannounce( tor->tracker );
710}
711
712void
713tr_torrentManualUpdate( tr_torrent * tor )
714{
715    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
716}
717
718int
719tr_torrentCanManualUpdate( const tr_torrent * tor )
720{
721    return ( tor )
722           && ( tor->isRunning )
723           && ( tr_trackerCanManualAnnounce( tor->tracker ) );
724}
725
726const tr_info *
727tr_torrentInfo( const tr_torrent * tor )
728{
729    return tor ? &tor->info : NULL;
730}
731
732const tr_stat *
733tr_torrentStatCached( tr_torrent * tor )
734{
735    const time_t now = time( NULL );
736
737    return tor && ( now == tor->lastStatTime ) ? &tor->stats
738           : tr_torrentStat( tor );
739}
740
741tr_torrent_activity
742tr_torrentGetActivity( tr_torrent * tor )
743{
744    tr_torrentRecheckCompleteness( tor );
745
746    if( tor->verifyState == TR_VERIFY_NOW )
747        return TR_STATUS_CHECK;
748    if( tor->verifyState == TR_VERIFY_WAIT )
749        return TR_STATUS_CHECK_WAIT;
750    if( !tor->isRunning )
751        return TR_STATUS_STOPPED;
752    if( tor->completeness == TR_LEECH )
753        return TR_STATUS_DOWNLOAD;
754
755    return TR_STATUS_SEED;
756}
757
758const tr_stat *
759tr_torrentStat( tr_torrent * tor )
760{
761    tr_stat *               s;
762    struct tr_tracker *     tc;
763    const tr_tracker_info * ti;
764    int                     usableSeeds = 0;
765
766    if( !tor )
767        return NULL;
768
769    tr_torrentLock( tor );
770
771    tor->lastStatTime = time( NULL );
772
773    s = &tor->stats;
774    s->id = tor->uniqueId;
775    s->activity = tr_torrentGetActivity( tor );
776    s->error  = tor->error;
777    memcpy( s->errorString, tor->errorString,
778           sizeof( s->errorString ) );
779
780    tc = tor->tracker;
781    ti = tr_trackerGetAddress( tor->tracker );
782    s->announceURL = ti ? ti->announce : NULL;
783    s->scrapeURL   = ti ? ti->scrape   : NULL;
784    tr_trackerStat( tc, s );
785
786    tr_trackerGetCounts( tc, &s->timesCompleted,
787                             &s->leechers,
788                             &s->seeders,
789                             &s->downloaders );
790
791    tr_peerMgrTorrentStats( tor->session->peerMgr,
792                            tor->info.hash,
793                            &s->peersKnown,
794                            &s->peersConnected,
795                            &usableSeeds,
796                            &s->webseedsSendingToUs,
797                            &s->peersSendingToUs,
798                            &s->peersGettingFromUs,
799                            s->peersFrom );
800
801    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, TR_UP );
802    s->rawDownloadSpeed   = tr_bandwidthGetRawSpeed  ( tor->bandwidth, TR_DOWN );
803    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, TR_UP );
804    s->pieceDownloadSpeed = tr_bandwidthGetPieceSpeed( tor->bandwidth, TR_DOWN );
805
806    usableSeeds += tor->info.webseedCount;
807
808    s->percentComplete = tr_cpPercentComplete ( tor->completion );
809
810    s->percentDone = tr_cpPercentDone( tor->completion );
811    s->leftUntilDone = tr_cpLeftUntilDone( tor->completion );
812    s->sizeWhenDone = tr_cpSizeWhenDone( tor->completion );
813
814    s->recheckProgress = s->activity == TR_STATUS_CHECK
815                       ? 1.0 -
816                         ( tr_torrentCountUncheckedPieces( tor ) /
817                           (double) tor->info.pieceCount )
818                       : 0.0;
819
820    s->swarmSpeed = tr_rcRate( tor->swarmSpeed );
821
822    s->activityDate = tor->activityDate;
823    s->addedDate    = tor->addedDate;
824    s->doneDate     = tor->doneDate;
825    s->startDate    = tor->startDate;
826
827    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
828    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
829    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
830    s->haveValid       = tr_cpHaveValid( tor->completion );
831    s->haveUnchecked   = tr_cpHaveTotal( tor->completion ) - s->haveValid;
832
833
834    if( usableSeeds > 0 )
835    {
836        s->desiredAvailable = s->leftUntilDone;
837    }
838    else if( !s->leftUntilDone || !s->peersConnected )
839    {
840        s->desiredAvailable = 0;
841    }
842    else
843    {
844        tr_piece_index_t i;
845        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable(
846            tor->session->peerMgr,
847            tor->info.
848            hash );
849        s->desiredAvailable = 0;
850        for( i = 0; i < tor->info.pieceCount; ++i )
851            if( !tor->info.pieces[i].dnd && tr_bitfieldHas( peerPieces, i ) )
852                s->desiredAvailable += tr_cpMissingBlocksInPiece(
853                    tor->completion, i );
854        s->desiredAvailable *= tor->blockSize;
855        tr_bitfieldFree( peerPieces );
856    }
857
858    if( s->leftUntilDone > s->desiredAvailable )
859        s->eta = TR_ETA_NOT_AVAIL;
860    else if( s->pieceDownloadSpeed < 0.1 )
861        s->eta = TR_ETA_UNKNOWN;
862    else
863        s->eta = s->leftUntilDone / s->pieceDownloadSpeed / 1024.0;
864
865    s->ratio = tr_getRatio(
866        s->uploadedEver,
867        s->downloadedEver ? s->downloadedEver : s->
868        haveValid );
869
870    tr_torrentUnlock( tor );
871
872    return s;
873}
874
875/***
876****
877***/
878
879static uint64_t
880fileBytesCompleted( const tr_torrent * tor,
881                    tr_file_index_t    fileIndex )
882{
883    const tr_file *        file     =  &tor->info.files[fileIndex];
884    const tr_block_index_t firstBlock       =  file->offset /
885                                              tor->blockSize;
886    const uint64_t         firstBlockOffset =  file->offset %
887                                              tor->blockSize;
888    const uint64_t         lastOffset       =
889        file->length ? ( file->length - 1 ) : 0;
890    const tr_block_index_t lastBlock        =
891        ( file->offset + lastOffset ) / tor->blockSize;
892    const uint64_t         lastBlockOffset  =
893        ( file->offset + lastOffset ) % tor->blockSize;
894    uint64_t               haveBytes = 0;
895
896    assert( tor );
897    assert( fileIndex < tor->info.fileCount );
898    assert( file->offset + file->length <= tor->info.totalSize );
899    assert( ( firstBlock < tor->blockCount )
900          || ( !file->length && file->offset == tor->info.totalSize ) );
901    assert( ( lastBlock < tor->blockCount )
902          || ( !file->length && file->offset == tor->info.totalSize ) );
903    assert( firstBlock <= lastBlock );
904    assert( tr_torBlockPiece( tor, firstBlock ) == file->firstPiece );
905    assert( tr_torBlockPiece( tor, lastBlock ) == file->lastPiece );
906
907    if( firstBlock == lastBlock )
908    {
909        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
910            haveBytes += lastBlockOffset + 1 - firstBlockOffset;
911    }
912    else
913    {
914        tr_block_index_t i;
915
916        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
917            haveBytes += tor->blockSize - firstBlockOffset;
918
919        for( i = firstBlock + 1; i < lastBlock; ++i )
920            if( tr_cpBlockIsComplete( tor->completion, i ) )
921                haveBytes += tor->blockSize;
922
923        if( tr_cpBlockIsComplete( tor->completion, lastBlock ) )
924            haveBytes += lastBlockOffset + 1;
925    }
926
927    return haveBytes;
928}
929
930tr_file_stat *
931tr_torrentFiles( const tr_torrent * tor,
932                 tr_file_index_t *  fileCount )
933{
934    tr_file_index_t       i;
935    const tr_file_index_t n = tor->info.fileCount;
936    tr_file_stat *        files = tr_new0( tr_file_stat, n );
937    tr_file_stat *        walk = files;
938
939    for( i = 0; i < n; ++i, ++walk )
940    {
941        const uint64_t b = fileBytesCompleted( tor, i );
942        walk->bytesCompleted = b;
943        walk->progress = tr_getRatio( b, tor->info.files[i].length );
944    }
945
946    if( fileCount )
947        *fileCount = n;
948
949    return files;
950}
951
952void
953tr_torrentFilesFree( tr_file_stat *            files,
954                     tr_file_index_t fileCount UNUSED )
955{
956    tr_free( files );
957}
958
959/***
960****
961***/
962
963float*
964tr_torrentWebSpeeds( const tr_torrent * tor )
965{
966    return tor ? tr_peerMgrWebSpeeds( tor->session->peerMgr, tor->info.hash )
967           : NULL;
968}
969
970tr_peer_stat *
971tr_torrentPeers( const tr_torrent * tor,
972                 int *              peerCount )
973{
974    tr_peer_stat * ret = NULL;
975
976    if( tor )
977        ret = tr_peerMgrPeerStats( tor->session->peerMgr,
978                                   tor->info.hash, peerCount );
979
980    return ret;
981}
982
983void
984tr_torrentPeersFree( tr_peer_stat * peers,
985                     int peerCount  UNUSED )
986{
987    tr_free( peers );
988}
989
990void
991tr_torrentAvailability( const tr_torrent * tor,
992                        int8_t *           tab,
993                        int                size )
994{
995    tr_peerMgrTorrentAvailability( tor->session->peerMgr,
996                                   tor->info.hash,
997                                   tab, size );
998}
999
1000void
1001tr_torrentAmountFinished( const tr_torrent * tor,
1002                          float *            tab,
1003                          int                size )
1004{
1005    tr_torrentLock( tor );
1006    tr_cpGetAmountDone( tor->completion, tab, size );
1007    tr_torrentUnlock( tor );
1008}
1009
1010void
1011tr_torrentResetTransferStats( tr_torrent * tor )
1012{
1013    tr_torrentLock( tor );
1014
1015    tor->downloadedPrev += tor->downloadedCur;
1016    tor->downloadedCur   = 0;
1017    tor->uploadedPrev   += tor->uploadedCur;
1018    tor->uploadedCur     = 0;
1019    tor->corruptPrev    += tor->corruptCur;
1020    tor->corruptCur      = 0;
1021
1022    tr_torrentUnlock( tor );
1023}
1024
1025void
1026tr_torrentSetHasPiece( tr_torrent *     tor,
1027                       tr_piece_index_t pieceIndex,
1028                       tr_bool          has )
1029{
1030    tr_torrentLock( tor );
1031
1032    assert( tor );
1033    assert( pieceIndex < tor->info.pieceCount );
1034
1035    if( has )
1036        tr_cpPieceAdd( tor->completion, pieceIndex );
1037    else
1038        tr_cpPieceRem( tor->completion, pieceIndex );
1039
1040    tr_torrentUnlock( tor );
1041}
1042
1043/***
1044****
1045***/
1046
1047static void
1048freeTorrent( tr_torrent * tor )
1049{
1050    tr_torrent * t;
1051    tr_handle *  h = tor->session;
1052    tr_info *    inf = &tor->info;
1053
1054    assert( tor );
1055    assert( !tor->isRunning );
1056
1057    tr_globalLock( h );
1058
1059    tr_peerMgrRemoveTorrent( h->peerMgr, tor->info.hash );
1060
1061    tr_cpClose( tor->completion );
1062
1063    tr_rcClose( tor->swarmSpeed );
1064
1065    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
1066    tr_trackerFree( tor->tracker );
1067    tor->tracker = NULL;
1068
1069    tr_bitfieldFree( tor->checkedPieces );
1070
1071    tr_free( tor->downloadDir );
1072    tr_free( tor->peer_id );
1073
1074    if( tor == h->torrentList )
1075        h->torrentList = tor->next;
1076    else for( t = h->torrentList; t != NULL; t = t->next )
1077        {
1078            if( t->next == tor )
1079            {
1080                t->next = tor->next;
1081                break;
1082            }
1083        }
1084
1085    assert( h->torrentCount >= 1 );
1086    h->torrentCount--;
1087
1088    tr_bandwidthFree( tor->bandwidth );
1089
1090    tr_metainfoFree( inf );
1091    tr_free( tor );
1092
1093    tr_globalUnlock( h );
1094}
1095
1096/**
1097***  Start/Stop Callback
1098**/
1099
1100static void
1101checkAndStartImpl( void * vtor )
1102{
1103    tr_torrent * tor = vtor;
1104
1105    tr_globalLock( tor->session );
1106
1107    tor->isRunning = 1;
1108    *tor->errorString = '\0';
1109    tr_torrentResetTransferStats( tor );
1110    tor->completeness = tr_cpGetStatus( tor->completion );
1111    tr_torrentSaveResume( tor );
1112    tor->startDate = time( NULL );
1113    tr_trackerStart( tor->tracker );
1114    tr_peerMgrStartTorrent( tor->session->peerMgr, tor->info.hash );
1115
1116    tr_globalUnlock( tor->session );
1117}
1118
1119static void
1120checkAndStartCB( tr_torrent * tor )
1121{
1122    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1123}
1124
1125static void
1126torrentStart( tr_torrent * tor,
1127              int          reloadProgress )
1128{
1129    tr_globalLock( tor->session );
1130
1131    if( !tor->isRunning )
1132    {
1133        const int isVerifying = tr_verifyInProgress( tor );
1134
1135        if( !isVerifying && reloadProgress )
1136            tr_torrentLoadResume( tor, TR_FR_PROGRESS, NULL );
1137
1138        tor->isRunning = 1;
1139
1140        if( !isVerifying )
1141            tr_verifyAdd( tor, checkAndStartCB );
1142    }
1143
1144    tr_globalUnlock( tor->session );
1145}
1146
1147void
1148tr_torrentStart( tr_torrent * tor )
1149{
1150    if( tor )
1151        torrentStart( tor, TRUE );
1152}
1153
1154static void
1155torrentRecheckDoneImpl( void * vtor )
1156{
1157    tr_torrentRecheckCompleteness( vtor );
1158}
1159
1160static void
1161torrentRecheckDoneCB( tr_torrent * tor )
1162{
1163    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1164}
1165
1166void
1167tr_torrentVerify( tr_torrent * tor )
1168{
1169    tr_verifyRemove( tor );
1170
1171    tr_globalLock( tor->session );
1172
1173    tr_torrentUncheck( tor );
1174    tr_verifyAdd( tor, torrentRecheckDoneCB );
1175
1176    tr_globalUnlock( tor->session );
1177}
1178
1179static void
1180stopTorrent( void * vtor )
1181{
1182    tr_file_index_t i;
1183
1184    tr_torrent *    tor = vtor;
1185
1186    tr_verifyRemove( tor );
1187    tr_peerMgrStopTorrent( tor->session->peerMgr, tor->info.hash );
1188    tr_trackerStop( tor->tracker );
1189
1190    for( i = 0; i < tor->info.fileCount; ++i )
1191    {
1192        const tr_file * file = &tor->info.files[i];
1193        char * path = tr_buildPath( tor->downloadDir, file->name, NULL );
1194        tr_fdFileClose( path );
1195        tr_free( path );
1196    }
1197}
1198
1199void
1200tr_torrentDeleteLocalData( tr_torrent * tor )
1201{
1202    tr_file_index_t i;
1203
1204    for( i=0; i<tor->info.fileCount; ++i )
1205    {
1206        const tr_file * file = &tor->info.files[i];
1207        char * path = tr_buildPath( tor->downloadDir, file->name, NULL );
1208        tr_fdFileClose( path );
1209        unlink( 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_PARTIAL_SEED:
1283            return _( "Done" );
1284
1285        case TR_SEED:
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_LEECH )
1299         || ( status == TR_SEED )
1300         || ( status == TR_PARTIAL_SEED ) );
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_SEED ) )
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
1358tr_bool
1359tr_torrentIsSeed( const tr_torrent * tor )
1360{
1361    return tor->completeness != TR_LEECH;
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                       tr_bool           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                      tr_bool           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
1574tr_bool
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
1620tr_bool
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                           tr_bool             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                          tr_bool         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
1653tr_bool
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    tr_bool                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            if( prevTier != trackers[i].tier ) {
1739                prevTier = trackers[i].tier;
1740                tier = tr_bencListAddList( announceList, 0 );
1741            }
1742            tr_bencListAddStr( tier, trackers[i].announce );
1743        }
1744
1745        /* try to parse it back again, to make sure it's good */
1746        memset( &tmpInfo, 0, sizeof( tr_info ) );
1747        if( !tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
1748        {
1749            /* it's good, so keep these new trackers and free the old ones */
1750
1751            tr_info swap;
1752            swap.trackers = tor->info.trackers;
1753            swap.trackerCount = tor->info.trackerCount;
1754            tor->info.trackers = tmpInfo.trackers;
1755            tor->info.trackerCount = tmpInfo.trackerCount;
1756            tmpInfo.trackers = swap.trackers;
1757            tmpInfo.trackerCount = swap.trackerCount;
1758
1759            tr_metainfoFree( &tmpInfo );
1760            tr_bencSaveFile( tor->info.torrent, &metainfo );
1761        }
1762
1763        /* cleanup */
1764        tr_bencFree( &metainfo );
1765    }
1766}
1767
1768/**
1769***
1770**/
1771
1772/** @deprecated this method will be removed in 1.40 */
1773void
1774tr_torrentSetAddedDate( tr_torrent * tor,
1775                        time_t       t )
1776{
1777    tor->addedDate = t;
1778}
1779
1780/** @deprecated this method will be removed in 1.40 */
1781void
1782tr_torrentSetActivityDate( tr_torrent * tor,
1783                           time_t       t )
1784{
1785    tor->activityDate = t;
1786}
1787
1788/** @deprecated this method will be removed in 1.40 */
1789void
1790tr_torrentSetDoneDate( tr_torrent * tor,
1791                       time_t       t )
1792{
1793    tor->doneDate = t;
1794}
1795
1796/**
1797***
1798**/
1799
1800uint64_t
1801tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
1802{
1803    const tr_file * it;
1804    const tr_file * end;
1805    struct stat sb;
1806    uint64_t bytesLeft = 0;
1807
1808    for( it=tor->info.files, end=it+tor->info.fileCount; it!=end; ++it )
1809    {
1810        if( !it->dnd )
1811        {
1812            char * path = tr_buildPath( tor->downloadDir, it->name, NULL );
1813
1814            bytesLeft += it->length;
1815
1816            if( !stat( path, &sb )
1817                    && S_ISREG( sb.st_mode )
1818                    && ( (uint64_t)sb.st_size <= it->length ) )
1819                bytesLeft -= sb.st_size;
1820
1821            tr_free( path );
1822        }
1823    }
1824
1825    return bytesLeft;
1826}
Note: See TracBrowser for help on using the repository browser.