source: branches/1.5x/libtransmission/torrent.c @ 7813

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

(trunk libT) backport latest changes to 1.5x -- (1) all of libT (2) more stats in daemon (3) compiler warning in gtk

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