source: trunk/libtransmission/torrent.c @ 10483

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

(trunk libT) #1869 "new status for torrents that reach seed ratio" -- possible fix for the bug reported by leena

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