source: trunk/libtransmission/torrent.c @ 7576

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

(trunk libT) add "inline" hint to several one-liner functions

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