source: trunk/libtransmission/torrent.c @ 9451

Last change on this file since 9451 was 9451, checked in by charles, 13 years ago

(trunk libT) BANG

  • Property svn:keywords set to Date Rev Author Id
File size: 71.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 9451 2009-10-30 22:03:32Z 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 <math.h> /* fabs */
21#include <stdarg.h>
22#include <string.h> /* memcmp */
23#include <stdlib.h> /* qsort */
24
25#include <event.h> /* evbuffer */
26
27#include "transmission.h"
28#include "announcer.h"
29#include "bandwidth.h"
30#include "bencode.h"
31#include "completion.h"
32#include "crypto.h" /* for tr_sha1 */
33#include "resume.h"
34#include "fdlimit.h" /* tr_fdTorrentClose */
35#include "metainfo.h"
36#include "peer-mgr.h"
37#include "platform.h" /* TR_PATH_DELIMITER_STR */
38#include "ptrarray.h"
39#include "ratecontrol.h"
40#include "session.h"
41#include "torrent.h"
42#include "trevent.h"
43#include "utils.h"
44#include "verify.h"
45
46#define MAX_BLOCK_SIZE ( 1024 * 16 )
47
48/***
49****
50***/
51
52int
53tr_torrentId( const tr_torrent * tor )
54{
55    return tor->uniqueId;
56}
57
58tr_torrent*
59tr_torrentFindFromId( tr_session * session, int id )
60{
61    tr_torrent * tor = NULL;
62
63    while(( tor = tr_torrentNext( session, tor )))
64        if( tor->uniqueId == id )
65            return tor;
66
67    return NULL;
68}
69
70tr_torrent*
71tr_torrentFindFromHashString( tr_session *  session, const char * str )
72{
73    tr_torrent * tor = NULL;
74
75    while(( tor = tr_torrentNext( session, tor )))
76        if( !strcmp( str, tor->info.hashString ) )
77            return tor;
78
79    return NULL;
80}
81
82tr_torrent*
83tr_torrentFindFromHash( tr_session * session, const uint8_t * torrentHash )
84{
85    tr_torrent * tor = NULL;
86
87    while(( tor = tr_torrentNext( session, tor )))
88        if( *tor->info.hash == *torrentHash )
89            if( !memcmp( tor->info.hash, torrentHash, SHA_DIGEST_LENGTH ) )
90                return tor;
91
92    return NULL;
93}
94
95tr_torrent*
96tr_torrentFindFromObfuscatedHash( tr_session * session,
97                                  const uint8_t * obfuscatedTorrentHash )
98{
99    tr_torrent * tor = NULL;
100
101    while(( tor = tr_torrentNext( session, tor )))
102        if( !memcmp( tor->obfuscatedHash, obfuscatedTorrentHash,
103                     SHA_DIGEST_LENGTH ) )
104            return tor;
105
106    return NULL;
107}
108
109/***
110****  PER-TORRENT UL / DL SPEEDS
111***/
112
113void
114tr_torrentSetSpeedLimit( tr_torrent * tor, tr_direction dir, int KiB_sec )
115{
116    assert( tr_isTorrent( tor ) );
117    assert( tr_isDirection( dir ) );
118
119    if( tr_bandwidthSetDesiredSpeed( tor->bandwidth, dir, KiB_sec ) )
120        tr_torrentSetDirty( tor );
121}
122
123int
124tr_torrentGetSpeedLimit( const tr_torrent * tor, tr_direction dir )
125{
126    assert( tr_isTorrent( tor ) );
127    assert( tr_isDirection( dir ) );
128
129    return tr_bandwidthGetDesiredSpeed( tor->bandwidth, dir );
130}
131
132void
133tr_torrentUseSpeedLimit( tr_torrent * tor, tr_direction dir, tr_bool do_use )
134{
135    assert( tr_isTorrent( tor ) );
136    assert( tr_isDirection( dir ) );
137
138    if( tr_bandwidthSetLimited( tor->bandwidth, dir, do_use ) )
139        tr_torrentSetDirty( tor );
140}
141
142tr_bool
143tr_torrentUsesSpeedLimit( const tr_torrent * tor, tr_direction dir )
144{
145    assert( tr_isTorrent( tor ) );
146    assert( tr_isDirection( dir ) );
147
148    return tr_bandwidthIsLimited( tor->bandwidth, dir );
149}
150
151void
152tr_torrentUseSessionLimits( tr_torrent * tor, tr_bool doUse )
153{
154    tr_bool changed;
155
156    assert( tr_isTorrent( tor ) );
157
158    changed = tr_bandwidthHonorParentLimits( tor->bandwidth, TR_UP, doUse );
159    changed |= tr_bandwidthHonorParentLimits( tor->bandwidth, TR_DOWN, doUse );
160
161    if( changed )
162        tr_torrentSetDirty( tor );
163}
164
165tr_bool
166tr_torrentUsesSessionLimits( const tr_torrent * tor )
167{
168    assert( tr_isTorrent( tor ) );
169
170    return tr_bandwidthAreParentLimitsHonored( tor->bandwidth, TR_UP );
171}
172
173/***
174****
175***/
176
177void
178tr_torrentSetRatioMode( tr_torrent *  tor, tr_ratiolimit mode )
179{
180    assert( tr_isTorrent( tor ) );
181    assert( mode==TR_RATIOLIMIT_GLOBAL || mode==TR_RATIOLIMIT_SINGLE || mode==TR_RATIOLIMIT_UNLIMITED  );
182
183    if( mode != tor->ratioLimitMode )
184    {
185        tor->ratioLimitMode = mode;
186        tor->needsSeedRatioCheck = TRUE;
187
188        tr_torrentSetDirty( tor );
189    }
190}
191
192tr_ratiolimit
193tr_torrentGetRatioMode( const tr_torrent * tor )
194{
195    assert( tr_isTorrent( tor ) );
196
197    return tor->ratioLimitMode;
198}
199
200void
201tr_torrentSetRatioLimit( tr_torrent * tor, double desiredRatio )
202{
203    assert( tr_isTorrent( tor ) );
204
205    if( (int)(desiredRatio*100.0) != (int)(tor->desiredRatio*100.0) )
206    {
207        tor->desiredRatio = desiredRatio;
208
209        tor->needsSeedRatioCheck = TRUE;
210
211        tr_torrentSetDirty( tor );
212    }
213}
214
215double
216tr_torrentGetRatioLimit( const tr_torrent * tor )
217{
218    assert( tr_isTorrent( tor ) );
219
220    return tor->desiredRatio;
221}
222
223tr_bool
224tr_torrentIsPieceTransferAllowed( const tr_torrent  * tor,
225                                  tr_direction        direction )
226{
227    int limit;
228    tr_bool allowed = TRUE;
229
230    if( tr_torrentUsesSpeedLimit( tor, direction ) )
231        if( tr_torrentGetSpeedLimit( tor, direction ) <= 0 )
232            allowed = FALSE;
233
234    if( tr_torrentUsesSessionLimits( tor ) )
235        if( tr_sessionGetActiveSpeedLimit( tor->session, direction, &limit ) )
236            if( limit <= 0 )
237                allowed = FALSE;
238
239    return allowed;
240}
241
242tr_bool
243tr_torrentGetSeedRatio( const tr_torrent * tor, double * ratio )
244{
245    tr_bool isLimited;
246
247    switch( tr_torrentGetRatioMode( tor ) )
248    {
249        case TR_RATIOLIMIT_SINGLE:
250            isLimited = TRUE;
251            if( ratio )
252                *ratio = tr_torrentGetRatioLimit( tor );
253            break;
254
255        case TR_RATIOLIMIT_GLOBAL:
256            isLimited = tr_sessionIsRatioLimited( tor->session );
257            if( isLimited && ratio )
258                *ratio = tr_sessionGetRatioLimit( tor->session );
259            break;
260
261        default: /* TR_RATIOLIMIT_UNLIMITED */
262            isLimited = FALSE;
263            break;
264    }
265
266    return isLimited;
267}
268
269/***
270****
271***/
272
273void
274tr_torrentSetLocalError( tr_torrent * tor, const char * fmt, ... )
275{
276    va_list ap;
277
278    assert( tr_isTorrent( tor ) );
279
280    va_start( ap, fmt );
281    tor->error = TR_STAT_LOCAL_ERROR;
282    evutil_vsnprintf( tor->errorString, sizeof( tor->errorString ), fmt, ap );
283    va_end( ap );
284}
285
286static void
287onTrackerResponse( void * tracker UNUSED,
288                   void * vevent,
289                   void * user_data )
290{
291    tr_torrent *       tor = user_data;
292    tr_tracker_event * event = vevent;
293
294    switch( event->messageType )
295    {
296        case TR_TRACKER_PEERS:
297        {
298            size_t   i, n;
299            tr_pex * pex = tr_peerMgrArrayToPex( event->compact,
300                                                 event->compactLen, &n );
301             if( event->allAreSeeds )
302                tr_tordbg( tor, "Got %d seeds from tracker", (int)n );
303            else
304                tr_torinf( tor, _( "Got %d peers from tracker" ), (int)n );
305
306            for( i = 0; i < n; ++i )
307            {
308                if( event->allAreSeeds )
309                    pex[i].flags |= ADDED_F_SEED_FLAG;
310                tr_peerMgrAddPex( tor, TR_PEER_FROM_TRACKER, pex + i );
311            }
312
313            tr_free( pex );
314            break;
315        }
316
317        case TR_TRACKER_WARNING:
318            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
319            tor->error = TR_STAT_TRACKER_WARNING;
320            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
321            break;
322
323        case TR_TRACKER_ERROR:
324            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
325            tor->error = TR_STAT_TRACKER_ERROR;
326            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
327            break;
328
329        case TR_TRACKER_ERROR_CLEAR:
330            tor->error = TR_STAT_OK;
331            tor->errorString[0] = '\0';
332            break;
333    }
334}
335
336/***
337****
338****  TORRENT INSTANTIATION
339****
340***/
341
342static int
343getBytePiece( const tr_info * info,
344              uint64_t        byteOffset )
345{
346    assert( info );
347    assert( info->pieceSize != 0 );
348
349    return byteOffset / info->pieceSize;
350}
351
352static void
353initFilePieces( tr_info *       info,
354                tr_file_index_t fileIndex )
355{
356    tr_file * file;
357    uint64_t  firstByte, lastByte;
358
359    assert( info );
360    assert( fileIndex < info->fileCount );
361
362    file = &info->files[fileIndex];
363    firstByte = file->offset;
364    lastByte = firstByte + ( file->length ? file->length - 1 : 0 );
365    file->firstPiece = getBytePiece( info, firstByte );
366    file->lastPiece = getBytePiece( info, lastByte );
367}
368
369static int
370pieceHasFile( tr_piece_index_t piece,
371              const tr_file *  file )
372{
373    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
374}
375
376static tr_priority_t
377calculatePiecePriority( const tr_torrent * tor,
378                        tr_piece_index_t   piece,
379                        int                fileHint )
380{
381    tr_file_index_t i;
382    int             priority = TR_PRI_LOW;
383
384    /* find the first file that has data in this piece */
385    if( fileHint >= 0 ) {
386        i = fileHint;
387        while( i > 0 && pieceHasFile( piece, &tor->info.files[i - 1] ) )
388            --i;
389    } else {
390        for( i = 0; i < tor->info.fileCount; ++i )
391            if( pieceHasFile( piece, &tor->info.files[i] ) )
392                break;
393    }
394
395    /* the piece's priority is the max of the priorities
396     * of all the files in that piece */
397    for( ; i < tor->info.fileCount; ++i )
398    {
399        const tr_file * file = &tor->info.files[i];
400
401        if( !pieceHasFile( piece, file ) )
402            break;
403
404        priority = MAX( priority, file->priority );
405
406        /* when dealing with multimedia files, getting the first and
407           last pieces can sometimes allow you to preview it a bit
408           before it's fully downloaded... */
409        if( file->priority >= TR_PRI_NORMAL )
410            if( file->firstPiece == piece || file->lastPiece == piece )
411                priority = TR_PRI_HIGH;
412    }
413
414    return priority;
415}
416
417static void
418tr_torrentInitFilePieces( tr_torrent * tor )
419{
420    tr_file_index_t  f;
421    tr_piece_index_t p;
422    uint64_t offset = 0;
423    tr_info * inf = &tor->info;
424    int * firstFiles;
425
426    /* assign the file offsets */
427    for( f=0; f<inf->fileCount; ++f ) {
428        inf->files[f].offset = offset;
429        offset += inf->files[f].length;
430        initFilePieces( inf, f );
431    }
432
433    /* build the array of first-file hints to give calculatePiecePriority */
434    firstFiles = tr_new( int, inf->pieceCount );
435    for( p=f=0; p<inf->pieceCount; ++p ) {
436        while( inf->files[f].lastPiece < p )
437            ++f;
438        firstFiles[p] = f;
439    }
440
441#if 0
442    /* test to confirm the first-file hints are correct */
443    for( p=0; p<inf->pieceCount; ++p ) {
444        f = firstFiles[p];
445        assert( inf->files[f].firstPiece <= p );
446        assert( inf->files[f].lastPiece >= p );
447        if( f > 0 )
448            assert( inf->files[f-1].lastPiece < p );
449        for( f=0; f<inf->fileCount; ++f )
450            if( pieceHasFile( p, &inf->files[f] ) )
451                break;
452        assert( (int)f == firstFiles[p] );
453    }
454#endif
455
456    for( p=0; p<inf->pieceCount; ++p )
457        inf->pieces[p].priority = calculatePiecePriority( tor, p, firstFiles[p] );
458
459    tr_free( firstFiles );
460}
461
462int
463tr_torrentPromoteTracker( tr_torrent * tor,
464                          int          pos )
465{
466    int i;
467    int tier;
468
469    assert( tor );
470    assert( ( 0 <= pos ) && ( pos < tor->info.trackerCount ) );
471
472    /* the tier of the tracker we're promoting */
473    tier = tor->info.trackers[pos].tier;
474
475    /* find the index of that tier's first tracker */
476    for( i = 0; i < tor->info.trackerCount; ++i )
477        if( tor->info.trackers[i].tier == tier )
478            break;
479
480    assert( i < tor->info.trackerCount );
481
482    /* promote the tracker at `pos' to the front of the tier */
483    if( i != pos )
484    {
485        const tr_tracker_info tmp = tor->info.trackers[i];
486        tor->info.trackers[i] = tor->info.trackers[pos];
487        tor->info.trackers[pos] = tmp;
488    }
489
490    /* return the new position of the tracker that started out at [pos] */
491    return i;
492}
493
494struct RandomTracker
495{
496    tr_tracker_info    tracker;
497    int                random_value;
498};
499
500/* the tiers will be sorted from lowest to highest,
501 * and trackers are randomized within the tiers */
502static TR_INLINE int
503compareRandomTracker( const void * va,
504                      const void * vb )
505{
506    const struct RandomTracker * a = va;
507    const struct RandomTracker * b = vb;
508
509    if( a->tracker.tier != b->tracker.tier )
510        return a->tracker.tier - b->tracker.tier;
511
512    return a->random_value - b->random_value;
513}
514
515static void
516randomizeTiers( tr_info * info )
517{
518    int                    i;
519    const int              n = info->trackerCount;
520    struct RandomTracker * r = tr_new0( struct RandomTracker, n );
521
522    for( i = 0; i < n; ++i )
523    {
524        r[i].tracker = info->trackers[i];
525        r[i].random_value = tr_cryptoRandInt( INT_MAX );
526    }
527    qsort( r, n, sizeof( struct RandomTracker ), compareRandomTracker );
528    for( i = 0; i < n; ++i )
529        info->trackers[i] = r[i].tracker;
530    tr_free( r );
531}
532
533static void torrentStart( tr_torrent * tor );
534
535/**
536 * Decide on a block size.  constraints:
537 * (1) most clients decline requests over 16 KiB
538 * (2) pieceSize must be a multiple of block size
539 */
540static uint32_t
541getBlockSize( uint32_t pieceSize )
542{
543    uint32_t b = pieceSize;
544
545    while( b > MAX_BLOCK_SIZE )
546        b /= 2u;
547
548    if( !b || ( pieceSize % b ) ) /* not cleanly divisible */
549        return 0;
550    return b;
551}
552
553static void refreshCurrentDir( tr_torrent * tor );;
554
555static void
556torrentRealInit( tr_torrent * tor, const tr_ctor * ctor )
557{
558    int          doStart;
559    uint64_t     loaded;
560    uint64_t     t;
561    const char * dir;
562    static int   nextUniqueId = 1;
563    tr_info    * info = &tor->info;
564    tr_session * session = tr_ctorGetSession( ctor );
565
566    assert( session != NULL );
567
568    tr_globalLock( session );
569
570    tor->session   = session;
571    tor->uniqueId = nextUniqueId++;
572    tor->magicNumber = TORRENT_MAGIC_NUMBER;
573
574    randomizeTiers( info );
575
576    tor->bandwidth = tr_bandwidthNew( session, session->bandwidth );
577
578    tor->blockSize = getBlockSize( info->pieceSize );
579
580    if( !tr_ctorGetDownloadDir( ctor, TR_FORCE, &dir ) ||
581        !tr_ctorGetDownloadDir( ctor, TR_FALLBACK, &dir ) )
582            tor->downloadDir = tr_strdup( dir );
583
584    if( tr_ctorGetIncompleteDir( ctor, &dir ) )
585        dir = tr_sessionGetIncompleteDir( session );
586    if( tr_sessionIsIncompleteDirEnabled( session ) )
587        tor->incompleteDir = tr_strdup( dir );
588
589    tor->lastPieceSize = info->totalSize % info->pieceSize;
590
591    if( !tor->lastPieceSize )
592        tor->lastPieceSize = info->pieceSize;
593
594    tor->lastBlockSize = info->totalSize % tor->blockSize;
595
596    if( !tor->lastBlockSize )
597        tor->lastBlockSize = tor->blockSize;
598
599    tor->blockCount =
600        ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize;
601
602    tor->blockCountInPiece =
603        info->pieceSize / tor->blockSize;
604
605    tor->blockCountInLastPiece =
606        ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize;
607
608    /* check our work */
609    assert( ( info->pieceSize % tor->blockSize ) == 0 );
610    t = info->pieceCount - 1;
611    t *= info->pieceSize;
612    t += tor->lastPieceSize;
613    assert( t == info->totalSize );
614    t = tor->blockCount - 1;
615    t *= tor->blockSize;
616    t += tor->lastBlockSize;
617    assert( t == info->totalSize );
618    t = info->pieceCount - 1;
619    t *= tor->blockCountInPiece;
620    t += tor->blockCountInLastPiece;
621    assert( t == (uint64_t)tor->blockCount );
622
623    tr_cpConstruct( &tor->completion, tor );
624
625    tr_torrentInitFilePieces( tor );
626
627    tr_rcConstruct( &tor->swarmSpeed );
628
629    tr_sha1( tor->obfuscatedHash, "req2", 4,
630             info->hash, SHA_DIGEST_LENGTH,
631             NULL );
632
633    tr_peerMgrAddTorrent( session->peerMgr, tor );
634
635    assert( !tor->downloadedCur );
636    assert( !tor->uploadedCur );
637
638    tr_ctorInitTorrentPriorities( ctor, tor );
639
640    tr_ctorInitTorrentWanted( ctor, tor );
641
642    tor->error = TR_STAT_OK;
643
644    tr_bitfieldConstruct( &tor->checkedPieces, tor->info.pieceCount );
645    tr_torrentUncheck( tor );
646
647    tr_torrentSetAddedDate( tor, time( NULL ) ); /* this is a default value to be
648                                                    overwritten by the resume file */
649
650    loaded = tr_torrentLoadResume( tor, ~0, ctor );
651
652    refreshCurrentDir( tor );
653
654    doStart = tor->isRunning;
655    tor->isRunning = 0;
656
657    if( !( loaded & TR_FR_SPEEDLIMIT ) )
658    {
659        tr_torrentUseSpeedLimit( tor, TR_UP, FALSE );
660        tr_torrentSetSpeedLimit( tor, TR_UP, tr_sessionGetSpeedLimit( tor->session, TR_UP ) );
661        tr_torrentUseSpeedLimit( tor, TR_DOWN, FALSE );
662        tr_torrentSetSpeedLimit( tor, TR_DOWN, tr_sessionGetSpeedLimit( tor->session, TR_DOWN ) );
663        tr_torrentUseSessionLimits( tor, TRUE );
664    }
665
666    if( !( loaded & TR_FR_RATIOLIMIT ) )
667    {
668        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_GLOBAL );
669        tr_torrentSetRatioLimit( tor, tr_sessionGetRatioLimit( tor->session ) );
670    }
671
672    tor->completeness = tr_cpGetStatus( &tor->completion );
673
674    {
675        tr_torrent * it = NULL;
676        tr_torrent * last = NULL;
677        while( ( it = tr_torrentNext( session, it ) ) )
678            last = it;
679
680        if( !last )
681            session->torrentList = tor;
682        else
683            last->next = tor;
684        ++session->torrentCount;
685    }
686
687    tr_globalUnlock( session );
688
689    /* maybe save our own copy of the metainfo */
690    if( tr_ctorGetSave( ctor ) )
691    {
692        const tr_benc * val;
693        if( !tr_ctorGetMetainfo( ctor, &val ) )
694        {
695            const char * filename = tor->info.torrent;
696            tr_bencToFile( val, TR_FMT_BENC, filename );
697            tr_sessionSetTorrentFile( tor->session, tor->info.hashString, filename );
698        }
699    }
700
701    tor->tiers = tr_announcerAddTorrent( session->announcer, tor );
702    tor->tiersSubscription = tr_announcerSubscribe( tor->tiers, onTrackerResponse, tor );
703
704    tr_metainfoMigrate( session, &tor->info );
705
706    if( doStart )
707        torrentStart( tor );
708}
709
710tr_parse_result
711tr_torrentParse( const tr_ctor * ctor, tr_info * setmeInfo )
712{
713    int             doFree;
714    tr_bool         didParse;
715    tr_info         tmp;
716    const tr_benc * metainfo;
717    tr_session    * session = tr_ctorGetSession( ctor );
718    tr_parse_result result = TR_PARSE_OK;
719
720    if( setmeInfo == NULL )
721        setmeInfo = &tmp;
722    memset( setmeInfo, 0, sizeof( tr_info ) );
723
724    if( tr_ctorGetMetainfo( ctor, &metainfo ) )
725        return TR_PARSE_ERR;
726
727    didParse = tr_metainfoParse( session, setmeInfo, metainfo );
728    doFree = didParse && ( setmeInfo == &tmp );
729
730    if( !didParse )
731        result = TR_PARSE_ERR;
732
733    if( didParse && !getBlockSize( setmeInfo->pieceSize ) )
734        result = TR_PARSE_ERR;
735
736    if( didParse && session && tr_torrentExists( session, setmeInfo->hash ) )
737        result = TR_PARSE_DUPLICATE;
738
739    if( doFree )
740        tr_metainfoFree( setmeInfo );
741
742    return result;
743}
744
745tr_torrent *
746tr_torrentNew( const tr_ctor  * ctor,
747               int            * setmeError )
748{
749    int          err;
750    tr_info      tmpInfo;
751    tr_torrent * tor = NULL;
752
753    assert( ctor != NULL );
754    assert( tr_isSession( tr_ctorGetSession( ctor ) ) );
755
756    err = tr_torrentParse( ctor, &tmpInfo );
757    if( !err )
758    {
759        tor = tr_new0( tr_torrent, 1 );
760        tor->info = tmpInfo;
761        torrentRealInit( tor, ctor );
762    }
763    else if( setmeError )
764    {
765        *setmeError = err;
766    }
767
768    return tor;
769}
770
771/**
772***
773**/
774
775void
776tr_torrentSetDownloadDir( tr_torrent * tor, const char * path )
777{
778    assert( tr_isTorrent( tor  ) );
779
780    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
781    {
782        tr_free( tor->downloadDir );
783        tor->downloadDir = tr_strdup( path );
784        tr_torrentSetDirty( tor );
785    }
786
787    refreshCurrentDir( tor );
788}
789
790const char*
791tr_torrentGetDownloadDir( const tr_torrent * tor )
792{
793    assert( tr_isTorrent( tor  ) );
794
795    return tor->downloadDir;
796}
797
798const char *
799tr_torrentGetCurrentDir( const tr_torrent * tor )
800{
801    assert( tr_isTorrent( tor  ) );
802
803    return tor->currentDir;
804}
805
806
807void
808tr_torrentChangeMyPort( tr_torrent * tor )
809{
810    assert( tr_isTorrent( tor  ) );
811
812    tr_announcerChangeMyPort( tor );
813}
814
815static TR_INLINE void
816tr_torrentManualUpdateImpl( void * vtor )
817{
818    tr_torrent * tor = vtor;
819
820    assert( tr_isTorrent( tor  ) );
821
822    if( tor->isRunning )
823        tr_announcerManualAnnounce( tor );
824}
825
826void
827tr_torrentManualUpdate( tr_torrent * tor )
828{
829    assert( tr_isTorrent( tor  ) );
830
831    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
832}
833
834tr_bool
835tr_torrentCanManualUpdate( const tr_torrent * tor )
836{
837    return ( tr_isTorrent( tor  ) )
838        && ( tor->isRunning )
839        && ( tr_announcerCanManualAnnounce( tor ) );
840}
841
842const tr_info *
843tr_torrentInfo( const tr_torrent * tor )
844{
845    return tr_isTorrent( tor ) ? &tor->info : NULL;
846}
847
848const tr_stat *
849tr_torrentStatCached( tr_torrent * tor )
850{
851    const time_t now = time( NULL );
852
853    return tr_isTorrent( tor ) && ( now == tor->lastStatTime )
854         ? &tor->stats
855         : tr_torrentStat( tor );
856}
857
858void
859tr_torrentSetVerifyState( tr_torrent * tor, tr_verify_state state )
860{
861    assert( tr_isTorrent( tor ) );
862    assert( state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW );
863
864    tor->verifyState = state;
865    tor->anyDate = time( NULL );
866}
867
868tr_torrent_activity
869tr_torrentGetActivity( tr_torrent * tor )
870{
871    assert( tr_isTorrent( tor ) );
872
873    tr_torrentRecheckCompleteness( tor );
874
875    if( tor->verifyState == TR_VERIFY_NOW )
876        return TR_STATUS_CHECK;
877    if( tor->verifyState == TR_VERIFY_WAIT )
878        return TR_STATUS_CHECK_WAIT;
879    if( !tor->isRunning )
880        return TR_STATUS_STOPPED;
881    if( tor->completeness == TR_LEECH )
882        return TR_STATUS_DOWNLOAD;
883
884    return TR_STATUS_SEED;
885}
886
887const tr_stat *
888tr_torrentStat( tr_torrent * tor )
889{
890    tr_stat *               s;
891    int                     usableSeeds;
892    uint64_t                now;
893    double                  downloadedForRatio, seedRatio=0;
894    double                  d;
895    tr_bool                 checkSeedRatio;
896
897    if( !tor )
898        return NULL;
899
900    assert( tr_isTorrent( tor ) );
901    tr_torrentLock( tor );
902
903    tor->lastStatTime = time( NULL );
904
905    s = &tor->stats;
906    s->id = tor->uniqueId;
907    s->activity = tr_torrentGetActivity( tor );
908    s->error = tor->error;
909    memcpy( s->errorString, tor->errorString, sizeof( s->errorString ) );
910
911    s->manualAnnounceTime = tr_announcerNextManualAnnounce( tor );
912
913    tr_peerMgrTorrentStats( tor,
914                            &s->peersKnown,
915                            &s->peersConnected,
916                            &usableSeeds,
917                            &s->webseedsSendingToUs,
918                            &s->peersSendingToUs,
919                            &s->peersGettingFromUs,
920                            s->peersFrom );
921
922    now = tr_date( );
923    d = tr_peerMgrGetWebseedSpeed( tor, now );
924    s->swarmSpeed         = tr_rcRate( &tor->swarmSpeed, now );
925    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
926    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
927    s->rawDownloadSpeed   = d + tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
928    s->pieceDownloadSpeed = d + tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
929
930    usableSeeds += tor->info.webseedCount;
931
932    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
933
934    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
935    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
936    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
937
938    s->recheckProgress = s->activity == TR_STATUS_CHECK
939                       ? 1.0 -
940                         ( tr_torrentCountUncheckedPieces( tor ) /
941                           (double) tor->info.pieceCount )
942                       : 0.0;
943
944    s->activityDate = tor->activityDate;
945    s->addedDate    = tor->addedDate;
946    s->doneDate     = tor->doneDate;
947    s->startDate    = tor->startDate;
948
949    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
950    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
951    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
952    s->haveValid       = tr_cpHaveValid( &tor->completion );
953    s->haveUnchecked   = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
954
955    if( usableSeeds > 0 )
956    {
957        s->desiredAvailable = s->leftUntilDone;
958    }
959    else if( !s->leftUntilDone || !s->peersConnected )
960    {
961        s->desiredAvailable = 0;
962    }
963    else
964    {
965        tr_piece_index_t i;
966        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable( tor );
967        s->desiredAvailable = 0;
968        for( i = 0; i < tor->info.pieceCount; ++i )
969            if( !tor->info.pieces[i].dnd && tr_bitfieldHasFast( peerPieces, i ) )
970                s->desiredAvailable += tr_cpMissingBlocksInPiece( &tor->completion, i );
971        s->desiredAvailable *= tor->blockSize;
972        tr_bitfieldFree( peerPieces );
973    }
974
975    downloadedForRatio = s->downloadedEver ? s->downloadedEver : s->haveValid;
976    s->ratio = tr_getRatio( s->uploadedEver, downloadedForRatio );
977
978    checkSeedRatio = tr_torrentGetSeedRatio( tor, &seedRatio );
979
980    switch( s->activity )
981    {
982        /* etaXLSpeed exists because if we use the piece speed directly,
983         * brief fluctuations cause the ETA to jump all over the place.
984         * so, etaXLSpeed is a smoothed-out version of the piece speed
985         * to dampen the effect of fluctuations */
986
987        case TR_STATUS_DOWNLOAD:
988            if( ( tor->etaDLSpeedCalculatedAt + 800 ) < now ) {
989                tor->etaDLSpeed = ( ( tor->etaDLSpeedCalculatedAt + 4000 ) < now )
990                    ? s->pieceDownloadSpeed /* if no recent previous speed, no need to smooth */
991                    : 0.8*tor->etaDLSpeed + 0.2*s->pieceDownloadSpeed; /* smooth across 5 readings */
992                tor->etaDLSpeedCalculatedAt = now;
993            }
994           
995            if( s->leftUntilDone > s->desiredAvailable )
996                s->eta = TR_ETA_NOT_AVAIL;
997            else if( s->pieceDownloadSpeed < 0.1 )
998                s->eta = TR_ETA_UNKNOWN;
999            else
1000                s->eta = s->leftUntilDone / tor->etaDLSpeed / 1024.0;
1001            break;
1002
1003        case TR_STATUS_SEED:
1004            if( checkSeedRatio )
1005            {
1006                if( ( tor->etaULSpeedCalculatedAt + 800 ) < now ) {
1007                    tor->etaULSpeed = ( ( tor->etaULSpeedCalculatedAt + 4000 ) < now )
1008                        ? s->pieceUploadSpeed /* if no recent previous speed, no need to smooth */
1009                        : 0.8*tor->etaULSpeed + 0.2*s->pieceUploadSpeed; /* smooth across 5 readings */
1010                    tor->etaULSpeedCalculatedAt = now;
1011                }
1012               
1013                if( s->pieceUploadSpeed < 0.1 )
1014                    s->eta = TR_ETA_UNKNOWN;
1015                else
1016                    s->eta = (downloadedForRatio * (seedRatio - s->ratio)) / tor->etaULSpeed / 1024.0;
1017            }
1018            else
1019                s->eta = TR_ETA_NOT_AVAIL;
1020            break;
1021
1022        default:
1023            s->eta = TR_ETA_NOT_AVAIL;
1024            break;
1025    }
1026   
1027    if( !checkSeedRatio || s->ratio >= seedRatio || s->ratio == TR_RATIO_INF ) 
1028        s->percentRatio = 1.0; 
1029    else if( s->ratio == TR_RATIO_NA ) 
1030        s->percentRatio = 0.0; 
1031    else 
1032        s->percentRatio = s->ratio / seedRatio; 
1033
1034    tr_torrentUnlock( tor );
1035
1036    return s;
1037}
1038
1039/***
1040****
1041***/
1042
1043static uint64_t
1044fileBytesCompleted( const tr_torrent * tor, tr_file_index_t index )
1045{
1046    uint64_t total = 0;
1047    const tr_file * f = &tor->info.files[index];
1048fprintf( stderr, "in fileBytesCompleted for file #%d\n", (int)index );
1049
1050    if( f->length )
1051    {
1052        const tr_block_index_t firstBlock = f->offset / tor->blockSize;
1053        const uint64_t lastByte = f->offset + f->length - 1;
1054        const tr_block_index_t lastBlock = lastByte / tor->blockSize;
1055
1056        if( firstBlock == lastBlock )
1057        {
1058fprintf( stderr, "file fits in a single block\n" );
1059            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1060                total = f->length;
1061        }
1062        else
1063        {
1064            //uint32_t i;
1065            tr_block_index_t i;
1066
1067            /* the first block */
1068            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1069                total += tor->blockSize - ( f->offset % tor->blockSize );
1070
1071            /* the middle blocks */
1072            if( f->firstPiece == f->lastPiece )
1073            {
1074fprintf( stderr, "f->firstPiece == f->lastPiece\n" );
1075                for( i=firstBlock+1; i<lastBlock; ++i )
1076                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1077                        total += tor->blockSize;
1078            }
1079            else
1080            {
1081                uint64_t b = 0;
1082                const tr_block_index_t firstBlockOfLastPiece
1083                           = tr_torPieceFirstBlock( tor, f->lastPiece );
1084                const tr_block_index_t lastBlockOfFirstPiece
1085                           = tr_torPieceFirstBlock( tor, f->firstPiece )
1086                             + tr_torPieceCountBlocks( tor, f->firstPiece ) - 1;
1087
1088                /* the rest of the first piece */
1089fprintf( stderr, "looping on the rest of the first piece\n" );
1090fprintf( stderr, "firstBlock is %"PRIu64"\n", (uint64_t)firstBlock );
1091fprintf( stderr, "lastBlock is %"PRIu64"\n", (uint64_t)lastBlock );
1092fprintf( stderr, "lastBlockOfFirstPiece is %"PRIu64"\n", (uint64_t)lastBlockOfFirstPiece );
1093                //for( i=firstBlock+1; i<lastBlock && i<=lastBlockOfFirstPiece; ++i ) {
1094                for( i=firstBlock+1; i<lastBlock && i<=lastBlockOfFirstPiece; ) {
1095fprintf( stderr, "looping on i(1): %"PRIu64"\n", i );
1096                //    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) ) {
1097                //        ++b;
1098                //    }
1099                ++i;
1100fprintf( stderr, "looping on i(2): %"PRIu64"\n", i );
1101                }
1102
1103                /* the middle pieces */
1104fprintf( stderr, "looking at the middle pieces\n" );
1105                if( f->firstPiece + 1 < f->lastPiece )
1106                    for( i=f->firstPiece+1; i<f->lastPiece; ++i )
1107                        b += tor->blockCountInPiece - tr_cpMissingBlocksInPiece( &tor->completion, i );
1108
1109                /* the rest of the last piece */
1110fprintf( stderr, "looping on the rest of the last piece\n" );
1111                for( i=firstBlockOfLastPiece; i<lastBlock; ++i )
1112                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1113                        ++b;
1114
1115                b *= tor->blockSize;
1116                total += b;
1117            }
1118
1119            /* the last block */
1120            if( tr_cpBlockIsCompleteFast( &tor->completion, lastBlock ) )
1121                total += ( f->offset + f->length ) - ( tor->blockSize * lastBlock );
1122        }
1123    }
1124fprintf( stderr, "finished fileBytesCompleted for file #%d\n", (int)index );
1125
1126    return total;
1127}
1128
1129tr_file_stat *
1130tr_torrentFiles( const tr_torrent * tor,
1131                 tr_file_index_t *  fileCount )
1132{
1133    tr_file_index_t       i;
1134    const tr_file_index_t n = tor->info.fileCount;
1135    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1136    tr_file_stat *        walk = files;
1137    const tr_bool         isSeed = tor->completeness == TR_SEED;
1138static int numCalls = 0;
1139
1140fprintf( stderr, "entering tr_torrentFiles for the %d time\n", ++numCalls );
1141
1142    assert( tr_isTorrent( tor ) );
1143
1144    for( i=0; i<n; ++i, ++walk )
1145    {
1146fprintf( stderr, "looking at file #%d of %d\n", (int)i, (int)n );
1147        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1148fprintf( stderr, "file has %"PRIu64" out of %"PRIu64" bytes\n", b, tor->info.files[i].length );
1149        walk->bytesCompleted = b;
1150        walk->progress = tr_getRatio( b, tor->info.files[i].length );
1151fprintf( stderr, "walk->progress is %f\n", walk->progress );
1152    }
1153
1154    if( fileCount )
1155        *fileCount = n;
1156
1157fprintf( stderr, "tr_torrentFiles finished\n" );
1158
1159    return files;
1160}
1161
1162void
1163tr_torrentFilesFree( tr_file_stat *            files,
1164                     tr_file_index_t fileCount UNUSED )
1165{
1166    tr_free( files );
1167}
1168
1169/***
1170****
1171***/
1172
1173float*
1174tr_torrentWebSpeeds( const tr_torrent * tor )
1175{
1176    return tr_isTorrent( tor )
1177         ? tr_peerMgrWebSpeeds( tor )
1178         : NULL;
1179}
1180
1181tr_peer_stat *
1182tr_torrentPeers( const tr_torrent * tor,
1183                 int *              peerCount )
1184{
1185    tr_peer_stat * ret = NULL;
1186
1187    if( tr_isTorrent( tor ) )
1188        ret = tr_peerMgrPeerStats( tor, peerCount );
1189
1190    return ret;
1191}
1192
1193void
1194tr_torrentPeersFree( tr_peer_stat * peers,
1195                     int peerCount  UNUSED )
1196{
1197    tr_free( peers );
1198}
1199
1200tr_tracker_stat *
1201tr_torrentTrackers( const tr_torrent * torrent,
1202                    int              * setmeTrackerCount )
1203{
1204    assert( tr_isTorrent( torrent ) );
1205
1206    return tr_announcerStats( torrent, setmeTrackerCount );
1207}
1208
1209void
1210tr_torrentTrackersFree( tr_tracker_stat * trackers,
1211                        int trackerCount )
1212{
1213    tr_announcerStatsFree( trackers, trackerCount );
1214}
1215
1216void
1217tr_torrentAvailability( const tr_torrent * tor,
1218                        int8_t *           tab,
1219                        int                size )
1220{
1221    tr_peerMgrTorrentAvailability( tor, tab, size );
1222}
1223
1224void
1225tr_torrentAmountFinished( const tr_torrent * tor,
1226                          float *            tab,
1227                          int                size )
1228{
1229    assert( tr_isTorrent( tor ) );
1230
1231    tr_torrentLock( tor );
1232    tr_cpGetAmountDone( &tor->completion, tab, size );
1233    tr_torrentUnlock( tor );
1234}
1235
1236static void
1237tr_torrentResetTransferStats( tr_torrent * tor )
1238{
1239    assert( tr_isTorrent( tor ) );
1240
1241    tr_torrentLock( tor );
1242
1243    tor->downloadedPrev += tor->downloadedCur;
1244    tor->downloadedCur   = 0;
1245    tor->uploadedPrev   += tor->uploadedCur;
1246    tor->uploadedCur     = 0;
1247    tor->corruptPrev    += tor->corruptCur;
1248    tor->corruptCur      = 0;
1249
1250    tr_torrentSetDirty( tor );
1251
1252    tr_torrentUnlock( tor );
1253}
1254
1255void
1256tr_torrentSetHasPiece( tr_torrent *     tor,
1257                       tr_piece_index_t pieceIndex,
1258                       tr_bool          has )
1259{
1260    assert( tr_isTorrent( tor ) );
1261    assert( pieceIndex < tor->info.pieceCount );
1262
1263    if( has )
1264        tr_cpPieceAdd( &tor->completion, pieceIndex );
1265    else
1266        tr_cpPieceRem( &tor->completion, pieceIndex );
1267}
1268
1269/***
1270****
1271***/
1272
1273static void
1274freeTorrent( tr_torrent * tor )
1275{
1276    tr_torrent * t;
1277    tr_session *  session = tor->session;
1278    tr_info *    inf = &tor->info;
1279
1280    assert( tr_isTorrent( tor ) );
1281    assert( !tor->isRunning );
1282
1283    tr_globalLock( session );
1284
1285    tr_peerMgrRemoveTorrent( tor );
1286
1287    tr_cpDestruct( &tor->completion );
1288
1289    tr_rcDestruct( &tor->swarmSpeed );
1290
1291    tr_announcerUnsubscribe( tor->tiers, tor->tiersSubscription );
1292    tr_announcerRemoveTorrent( session->announcer, tor );
1293
1294    tr_bitfieldDestruct( &tor->checkedPieces );
1295
1296    tr_free( tor->downloadDir );
1297    tr_free( tor->incompleteDir );
1298    tr_free( tor->peer_id );
1299
1300    if( tor == session->torrentList )
1301        session->torrentList = tor->next;
1302    else for( t = session->torrentList; t != NULL; t = t->next ) {
1303        if( t->next == tor ) {
1304            t->next = tor->next;
1305            break;
1306        }
1307    }
1308
1309    assert( session->torrentCount >= 1 );
1310    session->torrentCount--;
1311
1312    tr_bandwidthFree( tor->bandwidth );
1313
1314    tr_metainfoFree( inf );
1315    tr_free( tor );
1316
1317    tr_globalUnlock( session );
1318}
1319
1320/**
1321***  Start/Stop Callback
1322**/
1323
1324static void
1325checkAndStartImpl( void * vtor )
1326{
1327    tr_torrent * tor = vtor;
1328
1329    assert( tr_isTorrent( tor ) );
1330
1331    tr_globalLock( tor->session );
1332
1333    /** If we had local data before, but it's disappeared,
1334        stop the torrent and log an error. */
1335    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1336    {
1337        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1338        tr_torrentStop( tor );
1339    }
1340    else
1341    {
1342        const time_t now = time( NULL );
1343        tor->isRunning = TRUE;
1344        tor->needsSeedRatioCheck = TRUE;
1345        tor->error = TR_STAT_OK;
1346        tor->errorString[0] = '\0';
1347        tor->completeness = tr_cpGetStatus( &tor->completion );
1348        tor->startDate = tor->anyDate = now;
1349
1350        tr_torrentResetTransferStats( tor );
1351        tr_announcerTorrentStarted( tor );
1352        tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1353        tr_peerMgrStartTorrent( tor );
1354    }
1355
1356    tr_globalUnlock( tor->session );
1357}
1358
1359static void
1360checkAndStartCB( tr_torrent * tor )
1361{
1362    assert( tr_isTorrent( tor ) );
1363    assert( tr_isSession( tor->session ) );
1364
1365    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1366}
1367
1368static void
1369torrentStart( tr_torrent * tor )
1370{
1371    assert( tr_isTorrent( tor ) );
1372
1373    tr_globalLock( tor->session );
1374
1375    if( !tor->isRunning )
1376    {
1377        tr_verifyRemove( tor );
1378
1379        /* corresponds to the peer_id sent as a tracker request parameter.
1380         * one tracker admin says: "When the same torrent is opened and
1381         * closed and opened again without quitting Transmission ...
1382         * change the peerid. It would help sometimes if a stopped event
1383         * was missed to ensure that we didn't think someone was cheating. */
1384        tr_free( tor->peer_id );
1385        tor->peer_id = tr_peerIdNew( );
1386
1387        tor->isRunning = 1;
1388        tr_torrentSetDirty( tor );
1389        tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1390        tr_verifyAdd( tor, checkAndStartCB );
1391    }
1392
1393    tr_globalUnlock( tor->session );
1394}
1395
1396void
1397tr_torrentStart( tr_torrent * tor )
1398{
1399    if( tr_isTorrent( tor ) )
1400        torrentStart( tor );
1401}
1402
1403static void
1404torrentRecheckDoneImpl( void * vtor )
1405{
1406    tr_torrent * tor = vtor;
1407
1408    assert( tr_isTorrent( tor ) );
1409    tr_torrentRecheckCompleteness( tor );
1410
1411    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1412    {
1413        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1414        tr_torrentStop( tor );
1415    }
1416    else if( tor->startAfterVerify )
1417    {
1418        tor->startAfterVerify = FALSE;
1419
1420        tr_torrentStart( tor );
1421    }
1422}
1423
1424static void
1425torrentRecheckDoneCB( tr_torrent * tor )
1426{
1427    assert( tr_isTorrent( tor ) );
1428
1429    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1430}
1431
1432static void
1433verifyTorrent( void * vtor )
1434{
1435    tr_torrent * tor = vtor;
1436
1437    assert( tr_isTorrent( tor ) );
1438    tr_globalLock( tor->session );
1439
1440    /* if the torrent's already being verified, stop it */
1441    tr_verifyRemove( tor );
1442
1443    /* if the torrent's running, stop it & set the restart-after-verify flag */
1444    if( tor->startAfterVerify || tor->isRunning ) {
1445        tr_torrentStop( tor );
1446        tor->startAfterVerify = TRUE;
1447    }
1448
1449    /* add the torrent to the recheck queue */
1450    tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1451    tr_torrentUncheck( tor );
1452    tr_verifyAdd( tor, torrentRecheckDoneCB );
1453
1454    tr_globalUnlock( tor->session );
1455}
1456
1457void
1458tr_torrentVerify( tr_torrent * tor )
1459{
1460    if( tr_isTorrent( tor ) )
1461        tr_runInEventThread( tor->session, verifyTorrent, tor );
1462}
1463
1464void
1465tr_torrentSave( tr_torrent * tor )
1466{
1467    assert( tr_isTorrent( tor ) );
1468
1469    if( tor->isDirty ) {
1470        tor->isDirty = FALSE;
1471        tr_torrentSaveResume( tor );
1472    }
1473}
1474
1475static void
1476stopTorrent( void * vtor )
1477{
1478    tr_torrent * tor = vtor;
1479
1480    assert( tr_isTorrent( tor ) );
1481
1482    tr_verifyRemove( tor );
1483    tr_peerMgrStopTorrent( tor );
1484    tr_announcerTorrentStopped( tor );
1485
1486    tr_fdTorrentClose( tor->session, tor->uniqueId );
1487
1488    if( !tor->isDeleting )
1489        tr_torrentSave( tor );
1490}
1491
1492void
1493tr_torrentStop( tr_torrent * tor )
1494{
1495    assert( tr_isTorrent( tor ) );
1496
1497    if( tr_isTorrent( tor ) )
1498    {
1499        tr_globalLock( tor->session );
1500
1501        tor->isRunning = 0;
1502        tr_torrentSetDirty( tor );
1503        tr_runInEventThread( tor->session, stopTorrent, tor );
1504
1505        tr_globalUnlock( tor->session );
1506    }
1507}
1508
1509static void
1510closeTorrent( void * vtor )
1511{
1512    tr_benc * d;
1513    tr_torrent * tor = vtor;
1514
1515    assert( tr_isTorrent( tor ) );
1516
1517    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1518    tr_bencDictAddInt( d, "id", tor->uniqueId );
1519    tr_bencDictAddInt( d, "date", time( NULL ) );
1520
1521    stopTorrent( tor );
1522
1523    if( tor->isDeleting )
1524    {
1525        tr_metainfoRemoveSaved( tor->session, &tor->info );
1526        tr_torrentRemoveResume( tor );
1527    }
1528
1529    tor->isRunning = 0;
1530    freeTorrent( tor );
1531}
1532
1533void
1534tr_torrentFree( tr_torrent * tor )
1535{
1536    if( tr_isTorrent( tor ) )
1537    {
1538        tr_session * session = tor->session;
1539        assert( tr_isSession( session ) );
1540        tr_globalLock( session );
1541
1542        tr_torrentClearCompletenessCallback( tor );
1543        tr_runInEventThread( session, closeTorrent, tor );
1544
1545        tr_globalUnlock( session );
1546    }
1547}
1548
1549void
1550tr_torrentRemove( tr_torrent * tor )
1551{
1552    assert( tr_isTorrent( tor ) );
1553
1554    tor->isDeleting = 1;
1555    tr_torrentFree( tor );
1556}
1557
1558/**
1559***  Completeness
1560**/
1561
1562static const char *
1563getCompletionString( int type )
1564{
1565    switch( type )
1566    {
1567        /* Translators: this is a minor point that's safe to skip over, but FYI:
1568           "Complete" and "Done" are specific, different terms in Transmission:
1569           "Complete" means we've downloaded every file in the torrent.
1570           "Done" means we're done downloading the files we wanted, but NOT all
1571           that exist */
1572        case TR_PARTIAL_SEED:
1573            return _( "Done" );
1574
1575        case TR_SEED:
1576            return _( "Complete" );
1577
1578        default:
1579            return _( "Incomplete" );
1580    }
1581}
1582
1583static void
1584fireCompletenessChange( tr_torrent       * tor,
1585                        tr_completeness    status )
1586{
1587    assert( tr_isTorrent( tor ) );
1588    assert( ( status == TR_LEECH )
1589         || ( status == TR_SEED )
1590         || ( status == TR_PARTIAL_SEED ) );
1591
1592    if( tor->completeness_func )
1593        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1594}
1595
1596void
1597tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1598                                   tr_torrent_completeness_func    func,
1599                                   void                          * user_data )
1600{
1601    assert( tr_isTorrent( tor ) );
1602
1603    tor->completeness_func = func;
1604    tor->completeness_func_user_data = user_data;
1605}
1606
1607void
1608tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1609                                    tr_torrent_ratio_limit_hit_func  func,
1610                                    void                           * user_data )
1611{
1612    assert( tr_isTorrent( tor ) );
1613
1614    tor->ratio_limit_hit_func = func;
1615    tor->ratio_limit_hit_func_user_data = user_data;
1616}
1617
1618void
1619tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1620{
1621    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1622}
1623
1624void
1625tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1626{
1627    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1628}
1629
1630void
1631tr_torrentRecheckCompleteness( tr_torrent * tor )
1632{
1633    tr_completeness completeness;
1634
1635    assert( tr_isTorrent( tor ) );
1636
1637    tr_torrentLock( tor );
1638
1639    completeness = tr_cpGetStatus( &tor->completion );
1640
1641    if( completeness != tor->completeness )
1642    {
1643        const int recentChange = tor->downloadedCur != 0;
1644
1645        if( recentChange )
1646        {
1647            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1648                      getCompletionString( tor->completeness ),
1649                      getCompletionString( completeness ) );
1650        }
1651
1652        tor->completeness = completeness;
1653        tor->needsSeedRatioCheck = TRUE;
1654        tr_fdTorrentClose( tor->session, tor->uniqueId );
1655
1656        /* if the torrent is a seed now,
1657         * and the files used to be in the incompleteDir,
1658         * then move them to the destination directory */
1659        if( tr_torrentIsSeed( tor ) && ( tor->currentDir == tor->incompleteDir ) )
1660            tr_torrentSetLocation( tor, tor->downloadDir, TRUE, NULL, NULL );
1661
1662        fireCompletenessChange( tor, completeness );
1663
1664        if( recentChange && ( completeness == TR_SEED ) )
1665        {
1666            tr_announcerTorrentCompleted( tor );
1667
1668            tor->doneDate = tor->anyDate = time( NULL );
1669        }
1670
1671        tr_torrentSetDirty( tor );
1672    }
1673
1674    tr_torrentUnlock( tor );
1675}
1676
1677/**
1678***  File priorities
1679**/
1680
1681void
1682tr_torrentInitFilePriority( tr_torrent *    tor,
1683                            tr_file_index_t fileIndex,
1684                            tr_priority_t   priority )
1685{
1686    tr_piece_index_t i;
1687    tr_file *        file;
1688
1689    assert( tr_isTorrent( tor ) );
1690    assert( fileIndex < tor->info.fileCount );
1691    assert( tr_isPriority( priority ) );
1692
1693    file = &tor->info.files[fileIndex];
1694    file->priority = priority;
1695    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1696        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1697}
1698
1699void
1700tr_torrentSetFilePriorities( tr_torrent *      tor,
1701                             tr_file_index_t * files,
1702                             tr_file_index_t   fileCount,
1703                             tr_priority_t     priority )
1704{
1705    tr_file_index_t i;
1706
1707    assert( tr_isTorrent( tor ) );
1708
1709    tr_torrentLock( tor );
1710
1711    for( i = 0; i < fileCount; ++i )
1712        tr_torrentInitFilePriority( tor, files[i], priority );
1713
1714    tr_torrentSetDirty( tor );
1715    tr_torrentUnlock( tor );
1716}
1717
1718tr_priority_t
1719tr_torrentGetFilePriority( const tr_torrent * tor,
1720                           tr_file_index_t    file )
1721{
1722    tr_priority_t ret;
1723
1724    assert( tr_isTorrent( tor ) );
1725
1726    tr_torrentLock( tor );
1727    assert( tor );
1728    assert( file < tor->info.fileCount );
1729    ret = tor->info.files[file].priority;
1730    tr_torrentUnlock( tor );
1731
1732    return ret;
1733}
1734
1735tr_priority_t*
1736tr_torrentGetFilePriorities( const tr_torrent * tor )
1737{
1738    tr_file_index_t i;
1739    tr_priority_t * p;
1740
1741    assert( tr_isTorrent( tor ) );
1742
1743    tr_torrentLock( tor );
1744    p = tr_new0( tr_priority_t, tor->info.fileCount );
1745    for( i = 0; i < tor->info.fileCount; ++i )
1746        p[i] = tor->info.files[i].priority;
1747    tr_torrentUnlock( tor );
1748
1749    return p;
1750}
1751
1752/**
1753***  File DND
1754**/
1755
1756int
1757tr_torrentGetFileDL( const tr_torrent * tor,
1758                     tr_file_index_t    file )
1759{
1760    int doDownload;
1761
1762    assert( tr_isTorrent( tor ) );
1763
1764    tr_torrentLock( tor );
1765
1766    assert( file < tor->info.fileCount );
1767    doDownload = !tor->info.files[file].dnd;
1768
1769    tr_torrentUnlock( tor );
1770    return doDownload != 0;
1771}
1772
1773static void
1774setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1775{
1776    tr_file *        file;
1777    const int        dnd = !doDownload;
1778    tr_piece_index_t firstPiece, firstPieceDND;
1779    tr_piece_index_t lastPiece, lastPieceDND;
1780    tr_file_index_t  i;
1781
1782    assert( tr_isTorrent( tor ) );
1783
1784    file = &tor->info.files[fileIndex];
1785    file->dnd = dnd;
1786    firstPiece = file->firstPiece;
1787    lastPiece = file->lastPiece;
1788
1789    /* can't set the first piece to DND unless
1790       every file using that piece is DND */
1791    firstPieceDND = dnd;
1792    if( fileIndex > 0 )
1793    {
1794        for( i = fileIndex - 1; firstPieceDND; --i )
1795        {
1796            if( tor->info.files[i].lastPiece != firstPiece )
1797                break;
1798            firstPieceDND = tor->info.files[i].dnd;
1799            if( !i )
1800                break;
1801        }
1802    }
1803
1804    /* can't set the last piece to DND unless
1805       every file using that piece is DND */
1806    lastPieceDND = dnd;
1807    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1808    {
1809        if( tor->info.files[i].firstPiece != lastPiece )
1810            break;
1811        lastPieceDND = tor->info.files[i].dnd;
1812    }
1813
1814    if( firstPiece == lastPiece )
1815    {
1816        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1817    }
1818    else
1819    {
1820        tr_piece_index_t pp;
1821        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1822        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1823        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1824            tor->info.pieces[pp].dnd = dnd;
1825    }
1826}
1827
1828void
1829tr_torrentInitFileDLs( tr_torrent      * tor,
1830                       tr_file_index_t * files,
1831                       tr_file_index_t   fileCount,
1832                       tr_bool           doDownload )
1833{
1834    tr_file_index_t i;
1835
1836    assert( tr_isTorrent( tor ) );
1837
1838    tr_torrentLock( tor );
1839
1840    for( i=0; i<fileCount; ++i )
1841        setFileDND( tor, files[i], doDownload );
1842    tr_cpInvalidateDND( &tor->completion );
1843    tor->needsSeedRatioCheck = TRUE;
1844
1845    tr_torrentUnlock( tor );
1846}
1847
1848void
1849tr_torrentSetFileDLs( tr_torrent *      tor,
1850                      tr_file_index_t * files,
1851                      tr_file_index_t   fileCount,
1852                      tr_bool           doDownload )
1853{
1854    assert( tr_isTorrent( tor ) );
1855
1856    tr_torrentLock( tor );
1857    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1858    tr_torrentSetDirty( tor );
1859    tr_torrentUnlock( tor );
1860}
1861
1862/***
1863****
1864***/
1865
1866tr_priority_t
1867tr_torrentGetPriority( const tr_torrent * tor )
1868{
1869    assert( tr_isTorrent( tor ) );
1870
1871    return tor->bandwidth->priority;
1872}
1873
1874void
1875tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1876{
1877    assert( tr_isTorrent( tor ) );
1878    assert( tr_isPriority( priority ) );
1879
1880    if( tor->bandwidth->priority != priority )
1881    {
1882        tor->bandwidth->priority = priority;
1883
1884        tr_torrentSetDirty( tor );
1885    }
1886}
1887
1888/***
1889****
1890***/
1891
1892void
1893tr_torrentSetPeerLimit( tr_torrent * tor,
1894                        uint16_t     maxConnectedPeers )
1895{
1896    assert( tr_isTorrent( tor ) );
1897
1898    if ( tor->maxConnectedPeers != maxConnectedPeers )
1899    {
1900        tor->maxConnectedPeers = maxConnectedPeers;
1901
1902        tr_torrentSetDirty( tor );
1903    }
1904}
1905
1906uint16_t
1907tr_torrentGetPeerLimit( const tr_torrent * tor )
1908{
1909    assert( tr_isTorrent( tor ) );
1910
1911    return tor->maxConnectedPeers;
1912}
1913
1914/***
1915****
1916***/
1917
1918tr_block_index_t
1919_tr_block( const tr_torrent * tor,
1920           tr_piece_index_t   index,
1921           uint32_t           offset )
1922{
1923    tr_block_index_t ret;
1924
1925    assert( tr_isTorrent( tor ) );
1926
1927    ret = index;
1928    ret *= ( tor->info.pieceSize / tor->blockSize );
1929    ret += offset / tor->blockSize;
1930    return ret;
1931}
1932
1933tr_bool
1934tr_torrentReqIsValid( const tr_torrent * tor,
1935                      tr_piece_index_t   index,
1936                      uint32_t           offset,
1937                      uint32_t           length )
1938{
1939    int err = 0;
1940
1941    assert( tr_isTorrent( tor ) );
1942
1943    if( index >= tor->info.pieceCount )
1944        err = 1;
1945    else if( length < 1 )
1946        err = 2;
1947    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1948        err = 3;
1949    else if( length > MAX_BLOCK_SIZE )
1950        err = 4;
1951    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1952        err = 5;
1953
1954    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
1955                              (unsigned long)index,
1956                              (unsigned long)offset,
1957                              (unsigned long)length,
1958                              err );
1959
1960    return !err;
1961}
1962
1963uint64_t
1964tr_pieceOffset( const tr_torrent * tor,
1965                tr_piece_index_t   index,
1966                uint32_t           offset,
1967                uint32_t           length )
1968{
1969    uint64_t ret;
1970
1971    assert( tr_isTorrent( tor ) );
1972
1973    ret = tor->info.pieceSize;
1974    ret *= index;
1975    ret += offset;
1976    ret += length;
1977    return ret;
1978}
1979
1980/***
1981****
1982***/
1983
1984void
1985tr_torrentSetPieceChecked( tr_torrent        * tor,
1986                           tr_piece_index_t    piece,
1987                           tr_bool             isChecked )
1988{
1989    assert( tr_isTorrent( tor ) );
1990
1991    if( isChecked )
1992        tr_bitfieldAdd( &tor->checkedPieces, piece );
1993    else
1994        tr_bitfieldRem( &tor->checkedPieces, piece );
1995}
1996
1997void
1998tr_torrentSetFileChecked( tr_torrent *    tor,
1999                          tr_file_index_t fileIndex,
2000                          tr_bool         isChecked )
2001{
2002    const tr_file *        file = &tor->info.files[fileIndex];
2003    const tr_piece_index_t begin = file->firstPiece;
2004    const tr_piece_index_t end = file->lastPiece + 1;
2005
2006    assert( tr_isTorrent( tor ) );
2007
2008    if( isChecked )
2009        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
2010    else
2011        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
2012}
2013
2014tr_bool
2015tr_torrentIsFileChecked( const tr_torrent * tor,
2016                         tr_file_index_t    fileIndex )
2017{
2018    const tr_file *        file = &tor->info.files[fileIndex];
2019    const tr_piece_index_t begin = file->firstPiece;
2020    const tr_piece_index_t end = file->lastPiece + 1;
2021    tr_piece_index_t       i;
2022    tr_bool                isChecked = TRUE;
2023
2024    assert( tr_isTorrent( tor ) );
2025
2026    for( i = begin; isChecked && i < end; ++i )
2027        if( !tr_torrentIsPieceChecked( tor, i ) )
2028            isChecked = FALSE;
2029
2030    return isChecked;
2031}
2032
2033void
2034tr_torrentUncheck( tr_torrent * tor )
2035{
2036    assert( tr_isTorrent( tor ) );
2037
2038    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
2039}
2040
2041int
2042tr_torrentCountUncheckedPieces( const tr_torrent * tor )
2043{
2044    assert( tr_isTorrent( tor ) );
2045
2046    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
2047}
2048
2049time_t*
2050tr_torrentGetMTimes( const tr_torrent * tor, size_t * setme_n )
2051{
2052    size_t       i;
2053    const size_t n = tor->info.fileCount;
2054    time_t *     m = tr_new0( time_t, n );
2055
2056    assert( tr_isTorrent( tor ) );
2057
2058    for( i = 0; i < n; ++i )
2059    {
2060        struct stat sb;
2061        char * path = tr_torrentFindFile( tor, i );
2062        if( ( path != NULL ) && !stat( path, &sb ) && S_ISREG( sb.st_mode ) )
2063        {
2064#ifdef SYS_DARWIN
2065            m[i] = sb.st_mtimespec.tv_sec;
2066#else
2067            m[i] = sb.st_mtime;
2068#endif
2069        }
2070        tr_free( path );
2071    }
2072
2073    *setme_n = n;
2074    return m;
2075}
2076
2077/***
2078****
2079***/
2080
2081tr_announce_list_err
2082tr_torrentSetAnnounceList( tr_torrent *            tor,
2083                           const tr_tracker_info * trackers,
2084                           int                     trackerCount )
2085{
2086    int i, j;
2087    tr_benc metainfo;
2088
2089    assert( tr_isTorrent( tor ) );
2090
2091    /* look for bad URLs */
2092    for( i=0; i<trackerCount; ++i )
2093        if( !tr_httpIsValidURL( trackers[i].announce ) )
2094            return TR_ANNOUNCE_LIST_HAS_BAD;
2095
2096    /* look for duplicates */
2097    for( i=0; i<trackerCount; ++i )
2098        for( j=0; j<trackerCount; ++j )
2099            if( ( i != j ) && ( !strcmp( trackers[i].announce, trackers[j].announce ) ) )
2100                return TR_ANNOUNCE_LIST_HAS_DUPLICATES;
2101
2102    /* save to the .torrent file */
2103    if( !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2104    {
2105        int       i;
2106        int       prevTier = -1;
2107        tr_benc * tier = NULL;
2108        tr_benc * announceList;
2109        tr_info   tmpInfo;
2110
2111        /* remove the old fields */
2112        tr_bencDictRemove( &metainfo, "announce" );
2113        tr_bencDictRemove( &metainfo, "announce-list" );
2114
2115        /* add the new fields */
2116        tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2117        announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2118        for( i = 0; i < trackerCount; ++i ) {
2119            if( prevTier != trackers[i].tier ) {
2120                prevTier = trackers[i].tier;
2121                tier = tr_bencListAddList( announceList, 0 );
2122            }
2123            tr_bencListAddStr( tier, trackers[i].announce );
2124        }
2125
2126        /* try to parse it back again, to make sure it's good */
2127        memset( &tmpInfo, 0, sizeof( tr_info ) );
2128        if( tr_metainfoParse( tor->session, &tmpInfo, &metainfo ) )
2129        {
2130            /* it's good, so keep these new trackers and free the old ones */
2131
2132            tr_info swap;
2133            swap.trackers = tor->info.trackers;
2134            swap.trackerCount = tor->info.trackerCount;
2135            tor->info.trackers = tmpInfo.trackers;
2136            tor->info.trackerCount = tmpInfo.trackerCount;
2137            tmpInfo.trackers = swap.trackers;
2138            tmpInfo.trackerCount = swap.trackerCount;
2139
2140            tr_metainfoFree( &tmpInfo );
2141            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2142        }
2143
2144        /* cleanup */
2145        tr_bencFree( &metainfo );
2146
2147        /* tell the announcer to reload this torrent's tracker list */
2148        tr_announcerResetTorrent( tor->session->announcer, tor );
2149    }
2150
2151    return TR_ANNOUNCE_LIST_OK;
2152}
2153
2154/**
2155***
2156**/
2157
2158void
2159tr_torrentSetAddedDate( tr_torrent * tor,
2160                        time_t       t )
2161{
2162    assert( tr_isTorrent( tor ) );
2163
2164    tor->addedDate = t;
2165    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2166}
2167
2168void
2169tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2170{
2171    assert( tr_isTorrent( tor ) );
2172
2173    tor->activityDate = t;
2174    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2175}
2176
2177void
2178tr_torrentSetDoneDate( tr_torrent * tor,
2179                       time_t       t )
2180{
2181    assert( tr_isTorrent( tor ) );
2182
2183    tor->doneDate = t;
2184    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2185}
2186
2187/**
2188***
2189**/
2190
2191uint64_t
2192tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2193{
2194    tr_file_index_t i;
2195    uint64_t bytesLeft = 0;
2196
2197    assert( tr_isTorrent( tor ) );
2198
2199    for( i=0; i<tor->info.fileCount; ++i )
2200    {
2201        if( !tor->info.files[i].dnd )
2202        {
2203            struct stat sb;
2204            const uint64_t length = tor->info.files[i].length;
2205            char * path = tr_torrentFindFile( tor, i );
2206
2207            bytesLeft += length;
2208
2209            if( ( path != NULL ) && !stat( path, &sb )
2210                                 && S_ISREG( sb.st_mode )
2211                                 && ( (uint64_t)sb.st_size <= length ) )
2212                bytesLeft -= sb.st_size;
2213
2214            tr_free( path );
2215        }
2216    }
2217
2218    return bytesLeft;
2219}
2220
2221/****
2222*****  Removing the torrent's local data
2223****/
2224
2225static int
2226vstrcmp( const void * a, const void * b )
2227{
2228    return strcmp( a, b );
2229}
2230
2231static int
2232compareLongestFirst( const void * a, const void * b )
2233{
2234    const size_t alen = strlen( a );
2235    const size_t blen = strlen( b );
2236
2237    if( alen != blen )
2238        return alen > blen ? -1 : 1;
2239
2240    return vstrcmp( a, b );
2241}
2242
2243static void
2244addDirtyFile( const char  * root,
2245              const char  * filename,
2246              tr_ptrArray * dirtyFolders )
2247{
2248    char * dir = tr_dirname( filename );
2249
2250    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2251    while (     ( dir != NULL )
2252             && ( strlen( root ) <= strlen( dir ) )
2253             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2254    {
2255        char * tmp;
2256        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2257
2258        tmp = tr_dirname( dir );
2259        tr_free( dir );
2260        dir = tmp;
2261    }
2262
2263    tr_free( dir );
2264}
2265
2266static void
2267walkLocalData( const tr_torrent * tor,
2268               const char       * root,
2269               const char       * dir,
2270               const char       * base,
2271               tr_ptrArray      * torrentFiles,
2272               tr_ptrArray      * folders,
2273               tr_ptrArray      * dirtyFolders )
2274{
2275    int i;
2276    struct stat sb;
2277    char * buf;
2278
2279    assert( tr_isTorrent( tor ) );
2280
2281    buf = tr_buildPath( dir, base, NULL );
2282    i = stat( buf, &sb );
2283    if( !i )
2284    {
2285        DIR * odir = NULL;
2286
2287        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2288        {
2289            struct dirent *d;
2290            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2291            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2292                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2293                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2294            closedir( odir );
2295        }
2296        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2297        {
2298            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2299            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2300            if( !isTorrentFile )
2301                addDirtyFile( root, buf, dirtyFolders );
2302        }
2303    }
2304
2305    tr_free( buf );
2306}
2307
2308static void
2309deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2310{
2311    int i, n;
2312    char ** s;
2313    tr_file_index_t f;
2314    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2315    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2316    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2317
2318    const char * firstFile = tor->info.files[0].name;
2319    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2320    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2321    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2322
2323    assert( tr_isTorrent( tor ) );
2324
2325    for( f=0; f<tor->info.fileCount; ++f ) {
2326        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2327        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2328    }
2329
2330    /* build the set of folders and dirtyFolders */
2331    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2332
2333    /* try to remove entire folders first, so that the recycle bin will be tidy */
2334    s = (char**) tr_ptrArrayPeek( &folders, &n );
2335    for( i=0; i<n; ++i )
2336        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2337            fileFunc( s[i] );
2338
2339    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2340    for( f=0; f<tor->info.fileCount; ++f ) {
2341        char * path = tr_buildPath( tor->currentDir, tor->info.files[f].name, NULL );
2342        fileFunc( path );
2343        tr_free( path );
2344    }
2345
2346    /* Now clean out the directories left empty from the previous step.
2347     * Work from deepest to shallowest s.t. lower folders
2348     * won't prevent the upper folders from being deleted */
2349    {
2350        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2351        s = (char**) tr_ptrArrayPeek( &folders, &n );
2352        for( i=0; i<n; ++i )
2353            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2354                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2355        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2356        for( i=0; i<n; ++i ) {
2357#ifdef SYS_DARWIN
2358            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2359            fileFunc( dsStore );
2360            tr_free( dsStore );
2361#endif
2362            fileFunc( s[i] );
2363        }
2364        tr_ptrArrayDestruct( &cleanFolders, NULL );
2365    }
2366
2367    /* cleanup */
2368    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2369    tr_ptrArrayDestruct( &folders, tr_free );
2370    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2371    tr_free( root );
2372    tr_free( tmp );
2373}
2374
2375void
2376tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2377{
2378    assert( tr_isTorrent( tor ) );
2379
2380    if( fileFunc == NULL )
2381        fileFunc = remove;
2382
2383    /* close all the files because we're about to delete them */
2384    tr_fdTorrentClose( tor->session, tor->uniqueId );
2385
2386    if( tor->info.fileCount > 1 )
2387    {
2388        deleteLocalData( tor, fileFunc );
2389    }
2390    else
2391    {
2392        char * tmp;
2393
2394        /* torrent only has one file */
2395        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2396        fileFunc( path );
2397        tr_free( path );
2398
2399       
2400        tmp = tr_torrentBuildPartial( tor, 0 );
2401        path = tr_buildPath( tor->currentDir, tmp, NULL );
2402        fileFunc( path );
2403        tr_free( path );
2404        tr_free( tmp );
2405    }
2406}
2407
2408/***
2409****
2410***/
2411
2412struct LocationData
2413{
2414    tr_bool move_from_old_location;
2415    int * setme_state;
2416    double * setme_progress;
2417    char * location;
2418    tr_torrent * tor;
2419};
2420
2421static void
2422setLocation( void * vdata )
2423{
2424    tr_bool err = FALSE;
2425    tr_bool verify_needed = FALSE;
2426    struct LocationData * data = vdata;
2427    tr_torrent * tor = data->tor;
2428    const tr_bool do_move = data->move_from_old_location;
2429    const char * location = data->location;
2430    double bytesHandled = 0;
2431
2432    assert( tr_isTorrent( tor ) );
2433
2434    if( strcmp( location, tor->currentDir ) )
2435    {
2436        tr_file_index_t i;
2437
2438        /* bad idea to move files while they're being verified... */
2439        tr_verifyRemove( tor );
2440
2441        /* if the torrent is running, stop it and set a flag to
2442         * restart after we're done */
2443        if( tor->isRunning )
2444        {
2445            tr_torrentStop( tor );
2446            tor->startAfterVerify = TRUE;
2447        }
2448
2449        /* try to move the files.
2450         * FIXME: there are still all kinds of nasty cases, like what
2451         * if the target directory runs out of space halfway through... */
2452        for( i=0; !err && i<tor->info.fileCount; ++i )
2453        {
2454            const tr_file * f = &tor->info.files[i];
2455            const char * oldbase;
2456            char * sub;
2457            if( tr_torrentFindFile2( tor, i, &oldbase, &sub ) )
2458            {
2459                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2460                char * newpath = tr_buildPath( location, sub, NULL );
2461
2462                if( do_move )
2463                {
2464                    tr_bool renamed = FALSE;
2465                    errno = 0;
2466                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2467                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2468                    {
2469                        err = TRUE;
2470                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2471                                        oldpath, newpath, tr_strerror( errno ) );
2472                    }
2473                    else if( !renamed )
2474                    {
2475                        verify_needed = TRUE;
2476                    }
2477                }
2478
2479                tr_free( newpath );
2480                tr_free( oldpath );
2481                tr_free( sub );
2482            }
2483
2484            if( data->setme_progress )
2485            {
2486                bytesHandled += f->length;
2487                *data->setme_progress = bytesHandled / tor->info.totalSize;
2488            }
2489        }
2490
2491        if( !err )
2492        {
2493            /* blow away the leftover subdirectories in the old location */
2494            if( do_move )
2495                tr_torrentDeleteLocalData( tor, remove );
2496
2497            /* set the new location and reverify */
2498            tr_torrentSetDownloadDir( tor, location );
2499            if( verify_needed )
2500                tr_torrentVerify( tor );
2501            else if( tor->startAfterVerify ) {
2502                tor->startAfterVerify = FALSE;
2503                tr_torrentStart( tor );
2504            }
2505        }
2506    }
2507
2508    if( data->setme_state )
2509        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2510
2511    /* cleanup */
2512    tr_free( data->location );
2513    tr_free( data );
2514}
2515
2516void
2517tr_torrentSetLocation( tr_torrent  * tor,
2518                       const char  * location,
2519                       tr_bool       move_from_old_location,
2520                       double      * setme_progress,
2521                       int         * setme_state )
2522{
2523    struct LocationData * data;
2524
2525    assert( tr_isTorrent( tor ) );
2526
2527    if( setme_state )
2528        *setme_state = TR_LOC_MOVING;
2529    if( setme_progress )
2530        *setme_progress = 0;
2531
2532    /* run this in the libtransmission thread */
2533    data = tr_new( struct LocationData, 1 );
2534    data->tor = tor;
2535    data->location = tr_strdup( location );
2536    data->move_from_old_location = move_from_old_location;
2537    data->setme_state = setme_state;
2538    data->setme_progress = setme_progress;
2539    tr_runInEventThread( tor->session, setLocation, data );
2540}
2541
2542/***
2543****
2544***/
2545
2546void
2547tr_torrentCheckSeedRatio( tr_torrent * tor )
2548{
2549    double seedRatio;
2550
2551    assert( tr_isTorrent( tor ) );
2552
2553    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2554    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2555    {
2556        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2557        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2558        double ratio;
2559
2560        /* maybe we're the initial seeder and never downloaded anything... */
2561        if( down == 0 )
2562            down = tr_cpHaveValid( &tor->completion );
2563
2564        ratio = tr_getRatio( up, down );
2565
2566        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2567        {
2568            tr_torrentStop( tor );
2569
2570            /* set to no ratio limit to allow easy restarting */
2571            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2572
2573            /* maybe notify the client */
2574            if( tor->ratio_limit_hit_func != NULL )
2575                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2576        }
2577    }
2578}
2579
2580/***
2581****
2582***/
2583
2584void
2585tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2586{
2587    char * sub;
2588    const char * base;
2589
2590    /* close the file so that we can reopen in read-only mode as needed */
2591    tr_fdFileClose( tor->session, tor, fileNum );
2592
2593    /* if the torrent's filename on disk isn't the same as the one in the metadata,
2594     * then it's been modified to denote that it was a partial file.
2595     * Now that it's complete, use the proper filename. */
2596    if( tr_torrentFindFile2( tor, fileNum, &base, &sub ) )
2597    {
2598        const tr_file * file = &tor->info.files[fileNum];
2599
2600        if( strcmp( sub, file->name ) )
2601        {
2602            char * oldpath = tr_buildPath( base, sub, NULL );
2603            char * newpath = tr_buildPath( base, file->name, NULL );
2604
2605            if( rename( oldpath, newpath ) )
2606                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2607
2608            tr_free( newpath );
2609            tr_free( oldpath );
2610        }
2611
2612        tr_free( sub );
2613    }
2614}
2615
2616/***
2617****
2618***/
2619
2620static tr_bool
2621fileExists( const char * filename )
2622{
2623    struct stat sb;
2624    const tr_bool ok = !stat( filename, &sb );
2625    return ok;
2626}
2627
2628tr_bool
2629tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
2630                     const char ** base, char ** subpath )
2631{
2632    char * part;
2633    const tr_file * file;
2634    const char * b = NULL;
2635    const char * s = NULL;
2636
2637    assert( tr_isTorrent( tor ) );
2638    assert( fileNum < tor->info.fileCount );
2639
2640    file = &tor->info.files[fileNum];
2641    part = tr_torrentBuildPartial( tor, fileNum );
2642
2643    if( b == NULL ) {
2644        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
2645        if( fileExists( filename ) ) {
2646            b = tor->downloadDir;
2647            s = file->name;
2648        }
2649        tr_free( filename );
2650    }
2651
2652    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2653        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
2654        if( fileExists( filename ) ) {
2655            b = tor->incompleteDir;
2656            s = file->name;
2657        }
2658        tr_free( filename );
2659    }
2660
2661    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2662        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
2663        if( fileExists( filename ) ) {
2664            b = tor->incompleteDir;
2665            s = part;
2666        }
2667        tr_free( filename );
2668    }
2669
2670    if( b == NULL) {
2671        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
2672        if( fileExists( filename ) ) {
2673            b = tor->downloadDir;
2674            s = part;
2675        }
2676        tr_free( filename );
2677    }
2678
2679    if( base != NULL )
2680        *base = b;
2681    if( subpath != NULL )
2682        *subpath = tr_strdup( s );
2683
2684    tr_free( part );
2685    return b != NULL;
2686}
2687
2688
2689char*
2690tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
2691{
2692    char * subpath;
2693    char * ret = NULL;
2694    const char * base;
2695
2696    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath ) )
2697    {
2698        ret = tr_buildPath( base, subpath, NULL );
2699        tr_free( subpath );
2700    }
2701
2702    return ret;
2703}
2704
2705/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
2706static void
2707refreshCurrentDir( tr_torrent * tor )
2708{
2709    const char * dir = NULL;
2710    char * sub;
2711
2712    if( tor->incompleteDir == NULL )
2713        dir = tor->downloadDir;
2714    else if( !tr_torrentFindFile2( tor, 0, &dir, &sub ) )
2715        dir = tor->incompleteDir;
2716
2717    assert( dir != NULL );
2718    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
2719    tor->currentDir = dir;
2720}
2721
2722char*
2723tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
2724{
2725    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
2726}
Note: See TracBrowser for help on using the repository browser.