source: trunk/libtransmission/torrent.c @ 7397

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

(trunk libT) add ipv6 support by jhujhiti. I think this is the largest user-contributed patch we've ever used... thanks jhujhiti :)

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