source: trunk/libtransmission/torrent.c @ 7578

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

(trunk libT) avoid some unnecessary memory fragmentation... for composited objects that have a tr_completion, contain the it directly rather than a pointer to one allocated elsewhere on the heap.

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