source: trunk/libtransmission/torrent.c @ 7893

Last change on this file since 7893 was 7893, checked in by livings124, 14 years ago

a newly-added torrent should always follow the global ratio setting

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