source: trunk/libtransmission/torrent.c @ 10496

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

(trunk libT) #3105 "Torrentadd over rpc not files wanted/unwanted bug" -- fixed in trunk for 2.00

  • 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 10496 2010-04-19 23:10:30Z 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_torrentUncheck( tor );
694
695    tr_torrentSetAddedDate( tor, tr_time( ) ); /* this is a default value to be
696                                                  overwritten by the resume file */
697
698    torrentInitFromInfo( tor );
699    loaded = tr_torrentLoadResume( tor, ~0, ctor );
700    tor->completeness = tr_cpGetStatus( &tor->completion );
701
702    tr_ctorInitTorrentPriorities( ctor, tor );
703    tr_ctorInitTorrentWanted( ctor, tor );
704
705    refreshCurrentDir( tor );
706
707    doStart = tor->isRunning;
708    tor->isRunning = 0;
709
710    if( !( loaded & TR_FR_SPEEDLIMIT ) )
711    {
712        tr_torrentUseSpeedLimit( tor, TR_UP, FALSE );
713        tr_torrentSetSpeedLimit( tor, TR_UP, tr_sessionGetSpeedLimit( tor->session, TR_UP ) );
714        tr_torrentUseSpeedLimit( tor, TR_DOWN, FALSE );
715        tr_torrentSetSpeedLimit( tor, TR_DOWN, tr_sessionGetSpeedLimit( tor->session, TR_DOWN ) );
716        tr_torrentUseSessionLimits( tor, TRUE );
717    }
718
719    if( !( loaded & TR_FR_RATIOLIMIT ) )
720    {
721        tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_GLOBAL );
722        tr_torrentSetRatioLimit( tor, tr_sessionGetRatioLimit( tor->session ) );
723    }
724
725    {
726        tr_torrent * it = NULL;
727        tr_torrent * last = NULL;
728        while( ( it = tr_torrentNext( session, it ) ) )
729            last = it;
730
731        if( !last )
732            session->torrentList = tor;
733        else
734            last->next = tor;
735        ++session->torrentCount;
736    }
737
738    /* maybe save our own copy of the metainfo */
739    if( tr_ctorGetSave( ctor ) )
740    {
741        const tr_benc * val;
742        if( !tr_ctorGetMetainfo( ctor, &val ) )
743        {
744            const char * path = tor->info.torrent;
745            const int err = tr_bencToFile( val, TR_FMT_BENC, path );
746            if( err )
747                tr_torrentSetLocalError( tor, "Unable to save torrent file: %s", tr_strerror( err ) );
748            tr_sessionSetTorrentFile( tor->session, tor->info.hashString, path );
749        }
750    }
751
752    tor->tiers = tr_announcerAddTorrent( tor->session->announcer, tor );
753    tor->tiersSubscription = tr_announcerSubscribe( tor->tiers, onTrackerResponse, tor );
754
755    if( doStart )
756        torrentStart( tor );
757
758    tr_sessionUnlock( session );
759}
760
761static tr_parse_result
762torrentParseImpl( const tr_ctor * ctor, tr_info * setmeInfo,
763                  tr_bool * setmeHasInfo, int * dictOffset, int * dictLength )
764{
765    int             doFree;
766    tr_bool         didParse;
767    tr_bool         hasInfo = FALSE;
768    tr_info         tmp;
769    const tr_benc * metainfo;
770    tr_session    * session = tr_ctorGetSession( ctor );
771    tr_parse_result result = TR_PARSE_OK;
772
773    if( setmeInfo == NULL )
774        setmeInfo = &tmp;
775    memset( setmeInfo, 0, sizeof( tr_info ) );
776
777    if( tr_ctorGetMetainfo( ctor, &metainfo ) )
778        return TR_PARSE_ERR;
779
780    didParse = tr_metainfoParse( session, metainfo, setmeInfo,
781                                 &hasInfo, dictOffset, dictLength );
782    doFree = didParse && ( setmeInfo == &tmp );
783
784    if( !didParse )
785        result = TR_PARSE_ERR;
786
787    if( didParse && hasInfo && !getBlockSize( setmeInfo->pieceSize ) )
788        result = TR_PARSE_ERR;
789
790    if( didParse && session && tr_torrentExists( session, setmeInfo->hash ) )
791        result = TR_PARSE_DUPLICATE;
792
793    if( doFree )
794        tr_metainfoFree( setmeInfo );
795
796    if( setmeHasInfo != NULL )
797        *setmeHasInfo = hasInfo;
798
799    return result;
800}
801
802tr_parse_result
803tr_torrentParse( const tr_ctor * ctor, tr_info * setmeInfo )
804{
805    return torrentParseImpl( ctor, setmeInfo, NULL, NULL, NULL );
806}
807
808tr_torrent *
809tr_torrentNew( const tr_ctor * ctor, int * setmeError )
810{
811    int off, len;
812    tr_bool hasInfo;
813    tr_info tmpInfo;
814    tr_parse_result r;
815    tr_torrent * tor = NULL;
816
817    assert( ctor != NULL );
818    assert( tr_isSession( tr_ctorGetSession( ctor ) ) );
819
820    r = torrentParseImpl( ctor, &tmpInfo, &hasInfo, &off, &len );
821    if( r == TR_PARSE_OK )
822    {
823        tor = tr_new0( tr_torrent, 1 );
824        tor->info = tmpInfo;
825        if( hasInfo )
826        {
827            tor->infoDictOffset = off;
828            tor->infoDictLength = len;
829        }
830        torrentInit( tor, ctor );
831    }
832    else
833    {
834        if( r == TR_PARSE_DUPLICATE )
835            tr_metainfoFree( &tmpInfo );
836
837        if( setmeError )
838            *setmeError = r;
839    }
840
841    return tor;
842}
843
844/**
845***
846**/
847
848void
849tr_torrentSetDownloadDir( tr_torrent * tor, const char * path )
850{
851    assert( tr_isTorrent( tor  ) );
852
853    if( !path || !tor->downloadDir || strcmp( path, tor->downloadDir ) )
854    {
855        tr_free( tor->downloadDir );
856        tor->downloadDir = tr_strdup( path );
857        tr_torrentSetDirty( tor );
858    }
859
860    refreshCurrentDir( tor );
861}
862
863const char*
864tr_torrentGetDownloadDir( const tr_torrent * tor )
865{
866    assert( tr_isTorrent( tor  ) );
867
868    return tor->downloadDir;
869}
870
871const char *
872tr_torrentGetCurrentDir( const tr_torrent * tor )
873{
874    assert( tr_isTorrent( tor  ) );
875
876    return tor->currentDir;
877}
878
879
880void
881tr_torrentChangeMyPort( tr_torrent * tor )
882{
883    assert( tr_isTorrent( tor  ) );
884
885    if( tor->isRunning )
886        tr_announcerChangeMyPort( tor );
887}
888
889static inline void
890tr_torrentManualUpdateImpl( void * vtor )
891{
892    tr_torrent * tor = vtor;
893
894    assert( tr_isTorrent( tor  ) );
895
896    if( tor->isRunning )
897        tr_announcerManualAnnounce( tor );
898}
899
900void
901tr_torrentManualUpdate( tr_torrent * tor )
902{
903    assert( tr_isTorrent( tor  ) );
904
905    tr_runInEventThread( tor->session, tr_torrentManualUpdateImpl, tor );
906}
907
908tr_bool
909tr_torrentCanManualUpdate( const tr_torrent * tor )
910{
911    return ( tr_isTorrent( tor  ) )
912        && ( tor->isRunning )
913        && ( tr_announcerCanManualAnnounce( tor ) );
914}
915
916const tr_info *
917tr_torrentInfo( const tr_torrent * tor )
918{
919    return tr_isTorrent( tor ) ? &tor->info : NULL;
920}
921
922const tr_stat *
923tr_torrentStatCached( tr_torrent * tor )
924{
925    const time_t now = tr_time( );
926
927    return tr_isTorrent( tor ) && ( now == tor->lastStatTime )
928         ? &tor->stats
929         : tr_torrentStat( tor );
930}
931
932void
933tr_torrentSetVerifyState( tr_torrent * tor, tr_verify_state state )
934{
935    assert( tr_isTorrent( tor ) );
936    assert( state==TR_VERIFY_NONE || state==TR_VERIFY_WAIT || state==TR_VERIFY_NOW );
937
938    tor->verifyState = state;
939    tor->anyDate = tr_time( );
940}
941
942tr_torrent_activity
943tr_torrentGetActivity( tr_torrent * tor )
944{
945    assert( tr_isTorrent( tor ) );
946
947    tr_torrentRecheckCompleteness( tor );
948
949    if( tor->verifyState == TR_VERIFY_NOW )
950        return TR_STATUS_CHECK;
951    if( tor->verifyState == TR_VERIFY_WAIT )
952        return TR_STATUS_CHECK_WAIT;
953    if( !tor->isRunning )
954        return TR_STATUS_STOPPED;
955    if( tor->completeness == TR_LEECH )
956        return TR_STATUS_DOWNLOAD;
957
958    return TR_STATUS_SEED;
959}
960
961const tr_stat *
962tr_torrentStat( tr_torrent * tor )
963{
964    tr_stat *               s;
965    int                     usableSeeds;
966    uint64_t                now;
967    double                  d;
968    uint64_t                seedRatioBytesLeft;
969    uint64_t                seedRatioBytesGoal;
970    tr_bool                 seedRatioApplies;
971
972    if( !tor )
973        return NULL;
974
975    assert( tr_isTorrent( tor ) );
976    tr_torrentLock( tor );
977
978    tor->lastStatTime = tr_time( );
979
980    s = &tor->stats;
981    s->id = tor->uniqueId;
982    s->activity = tr_torrentGetActivity( tor );
983    s->error = tor->error;
984    memcpy( s->errorString, tor->errorString, sizeof( s->errorString ) );
985
986    s->manualAnnounceTime = tr_announcerNextManualAnnounce( tor );
987
988    tr_peerMgrTorrentStats( tor,
989                            &s->peersKnown,
990                            &s->peersConnected,
991                            &usableSeeds,
992                            &s->webseedsSendingToUs,
993                            &s->peersSendingToUs,
994                            &s->peersGettingFromUs,
995                            s->peersFrom );
996
997    now = tr_date( );
998    d = tr_peerMgrGetWebseedSpeed( tor, now );
999    s->rawUploadSpeed     = tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_UP );
1000    s->pieceUploadSpeed   = tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_UP );
1001    s->rawDownloadSpeed   = d + tr_bandwidthGetRawSpeed  ( tor->bandwidth, now, TR_DOWN );
1002    s->pieceDownloadSpeed = d + tr_bandwidthGetPieceSpeed( tor->bandwidth, now, TR_DOWN );
1003
1004    usableSeeds += tor->info.webseedCount;
1005
1006    s->percentComplete = tr_cpPercentComplete ( &tor->completion );
1007    s->metadataPercentComplete = tr_torrentGetMetadataPercent( tor );
1008
1009    s->percentDone   = tr_cpPercentDone  ( &tor->completion );
1010    s->leftUntilDone = tr_cpLeftUntilDone( &tor->completion );
1011    s->sizeWhenDone  = tr_cpSizeWhenDone ( &tor->completion );
1012
1013    s->recheckProgress = s->activity == TR_STATUS_CHECK
1014                       ? 1.0 -
1015                         ( tr_torrentCountUncheckedPieces( tor ) /
1016                           (double) tor->info.pieceCount )
1017                       : 0.0;
1018
1019    s->activityDate = tor->activityDate;
1020    s->addedDate    = tor->addedDate;
1021    s->doneDate     = tor->doneDate;
1022    s->startDate    = tor->startDate;
1023
1024    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
1025    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
1026    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
1027    s->haveValid       = tr_cpHaveValid( &tor->completion );
1028    s->haveUnchecked   = tr_cpHaveTotal( &tor->completion ) - s->haveValid;
1029
1030    if( usableSeeds > 0 )
1031    {
1032        s->desiredAvailable = s->leftUntilDone;
1033    }
1034    else if( !s->leftUntilDone || !s->peersConnected )
1035    {
1036        s->desiredAvailable = 0;
1037    }
1038    else
1039    {
1040        tr_piece_index_t i;
1041        tr_bitfield *    peerPieces = tr_peerMgrGetAvailable( tor );
1042        s->desiredAvailable = 0;
1043        for( i = 0; i < tor->info.pieceCount; ++i )
1044            if( !tor->info.pieces[i].dnd && tr_bitfieldHasFast( peerPieces, i ) )
1045                s->desiredAvailable += tr_cpMissingBlocksInPiece( &tor->completion, i );
1046        s->desiredAvailable *= tor->blockSize;
1047        tr_bitfieldFree( peerPieces );
1048    }
1049
1050    s->ratio = tr_getRatio( s->uploadedEver,
1051                            s->downloadedEver ? s->downloadedEver : s->haveValid );
1052
1053    seedRatioApplies = tr_torrentGetSeedRatioBytes( tor, &seedRatioBytesLeft,
1054                                                         &seedRatioBytesGoal );
1055
1056    switch( s->activity )
1057    {
1058        /* etaXLSpeed exists because if we use the piece speed directly,
1059         * brief fluctuations cause the ETA to jump all over the place.
1060         * so, etaXLSpeed is a smoothed-out version of the piece speed
1061         * to dampen the effect of fluctuations */
1062
1063        case TR_STATUS_DOWNLOAD:
1064            if( ( tor->etaDLSpeedCalculatedAt + 800 ) < now ) {
1065                tor->etaDLSpeed = ( ( tor->etaDLSpeedCalculatedAt + 4000 ) < now )
1066                    ? s->pieceDownloadSpeed /* if no recent previous speed, no need to smooth */
1067                    : 0.8*tor->etaDLSpeed + 0.2*s->pieceDownloadSpeed; /* smooth across 5 readings */
1068                tor->etaDLSpeedCalculatedAt = now;
1069            }
1070
1071            if( s->leftUntilDone > s->desiredAvailable )
1072                s->eta = TR_ETA_NOT_AVAIL;
1073            else if( s->pieceDownloadSpeed < 0.1 )
1074                s->eta = TR_ETA_UNKNOWN;
1075            else
1076                s->eta = s->leftUntilDone / tor->etaDLSpeed / 1024.0;
1077            break;
1078
1079        case TR_STATUS_SEED: {
1080            if( !seedRatioApplies )
1081                s->eta = TR_ETA_NOT_AVAIL;
1082            else {
1083                if( ( tor->etaULSpeedCalculatedAt + 800 ) < now ) {
1084                    tor->etaULSpeed = ( ( tor->etaULSpeedCalculatedAt + 4000 ) < now )
1085                        ? s->pieceUploadSpeed /* if no recent previous speed, no need to smooth */
1086                        : 0.8*tor->etaULSpeed + 0.2*s->pieceUploadSpeed; /* smooth across 5 readings */
1087                    tor->etaULSpeedCalculatedAt = now;
1088                }
1089                if( s->pieceUploadSpeed < 0.1 )
1090                    s->eta = TR_ETA_UNKNOWN;
1091                else
1092                    s->eta = seedRatioBytesLeft / tor->etaULSpeed / 1024.0;
1093            }
1094            break;
1095        }
1096
1097        default:
1098            s->eta = TR_ETA_NOT_AVAIL;
1099            break;
1100    }
1101
1102    s->finished = seedRatioApplies && !seedRatioBytesLeft;
1103
1104    if( !seedRatioApplies || s->finished )
1105        s->seedRatioPercentDone = 1;
1106    else if( !seedRatioBytesGoal ) /* impossible? safeguard for div by zero */
1107        s->seedRatioPercentDone = 0;
1108    else
1109        s->seedRatioPercentDone = (double)(seedRatioBytesGoal - seedRatioBytesLeft) / seedRatioBytesGoal;
1110
1111    tr_torrentUnlock( tor );
1112
1113    return s;
1114}
1115
1116/***
1117****
1118***/
1119
1120static uint64_t
1121fileBytesCompleted( const tr_torrent * tor, tr_file_index_t index )
1122{
1123    uint64_t total = 0;
1124    const tr_file * f = &tor->info.files[index];
1125
1126    if( f->length )
1127    {
1128        const tr_block_index_t firstBlock = f->offset / tor->blockSize;
1129        const uint64_t lastByte = f->offset + f->length - 1;
1130        const tr_block_index_t lastBlock = lastByte / tor->blockSize;
1131
1132        if( firstBlock == lastBlock )
1133        {
1134            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1135                total = f->length;
1136        }
1137        else
1138        {
1139            tr_block_index_t i;
1140
1141            /* the first block */
1142            if( tr_cpBlockIsCompleteFast( &tor->completion, firstBlock ) )
1143                total += tor->blockSize - ( f->offset % tor->blockSize );
1144
1145            /* the middle blocks */
1146            if( f->firstPiece == f->lastPiece )
1147            {
1148                for( i=firstBlock+1; i<lastBlock; ++i )
1149                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1150                        total += tor->blockSize;
1151            }
1152            else
1153            {
1154                uint64_t b = 0;
1155                const tr_block_index_t firstBlockOfLastPiece
1156                           = tr_torPieceFirstBlock( tor, f->lastPiece );
1157                const tr_block_index_t lastBlockOfFirstPiece
1158                           = tr_torPieceFirstBlock( tor, f->firstPiece )
1159                             + tr_torPieceCountBlocks( tor, f->firstPiece ) - 1;
1160
1161                /* the rest of the first piece */
1162                for( i=firstBlock+1; i<lastBlock && i<=lastBlockOfFirstPiece; ++i )
1163                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1164                        ++b;
1165
1166                /* the middle pieces */
1167                if( f->firstPiece + 1 < f->lastPiece )
1168                    for( i=f->firstPiece+1; i<f->lastPiece; ++i )
1169                        b += tor->blockCountInPiece - tr_cpMissingBlocksInPiece( &tor->completion, i );
1170
1171                /* the rest of the last piece */
1172                for( i=firstBlockOfLastPiece; i<lastBlock; ++i )
1173                    if( tr_cpBlockIsCompleteFast( &tor->completion, i ) )
1174                        ++b;
1175
1176                b *= tor->blockSize;
1177                total += b;
1178            }
1179
1180            /* the last block */
1181            if( tr_cpBlockIsCompleteFast( &tor->completion, lastBlock ) )
1182                total += ( f->offset + f->length ) - ( tor->blockSize * lastBlock );
1183        }
1184    }
1185
1186    return total;
1187}
1188
1189tr_file_stat *
1190tr_torrentFiles( const tr_torrent * tor,
1191                 tr_file_index_t *  fileCount )
1192{
1193    tr_file_index_t       i;
1194    const tr_file_index_t n = tor->info.fileCount;
1195    tr_file_stat *        files = tr_new0( tr_file_stat, n );
1196    tr_file_stat *        walk = files;
1197    const tr_bool         isSeed = tor->completeness == TR_SEED;
1198
1199    assert( tr_isTorrent( tor ) );
1200
1201    for( i=0; i<n; ++i, ++walk ) {
1202        const uint64_t b = isSeed ? tor->info.files[i].length : fileBytesCompleted( tor, i );
1203        walk->bytesCompleted = b;
1204        walk->progress = tor->info.files[i].length > 0 ? ( (float)b / tor->info.files[i].length ) : 1.0;
1205    }
1206
1207    if( fileCount )
1208        *fileCount = n;
1209
1210    return files;
1211}
1212
1213void
1214tr_torrentFilesFree( tr_file_stat *            files,
1215                     tr_file_index_t fileCount UNUSED )
1216{
1217    tr_free( files );
1218}
1219
1220/***
1221****
1222***/
1223
1224float*
1225tr_torrentWebSpeeds( const tr_torrent * tor )
1226{
1227    return tr_isTorrent( tor )
1228         ? tr_peerMgrWebSpeeds( tor )
1229         : NULL;
1230}
1231
1232tr_peer_stat *
1233tr_torrentPeers( const tr_torrent * tor,
1234                 int *              peerCount )
1235{
1236    tr_peer_stat * ret = NULL;
1237
1238    if( tr_isTorrent( tor ) )
1239        ret = tr_peerMgrPeerStats( tor, peerCount );
1240
1241    return ret;
1242}
1243
1244void
1245tr_torrentPeersFree( tr_peer_stat * peers,
1246                     int peerCount  UNUSED )
1247{
1248    tr_free( peers );
1249}
1250
1251tr_tracker_stat *
1252tr_torrentTrackers( const tr_torrent * torrent,
1253                    int              * setmeTrackerCount )
1254{
1255    assert( tr_isTorrent( torrent ) );
1256
1257    return tr_announcerStats( torrent, setmeTrackerCount );
1258}
1259
1260void
1261tr_torrentTrackersFree( tr_tracker_stat * trackers,
1262                        int trackerCount )
1263{
1264    tr_announcerStatsFree( trackers, trackerCount );
1265}
1266
1267void
1268tr_torrentAvailability( const tr_torrent * tor,
1269                        int8_t *           tab,
1270                        int                size )
1271{
1272    tr_peerMgrTorrentAvailability( tor, tab, size );
1273}
1274
1275void
1276tr_torrentAmountFinished( const tr_torrent * tor,
1277                          float *            tab,
1278                          int                size )
1279{
1280    assert( tr_isTorrent( tor ) );
1281
1282    tr_torrentLock( tor );
1283    tr_cpGetAmountDone( &tor->completion, tab, size );
1284    tr_torrentUnlock( tor );
1285}
1286
1287static void
1288tr_torrentResetTransferStats( tr_torrent * tor )
1289{
1290    assert( tr_isTorrent( tor ) );
1291
1292    tr_torrentLock( tor );
1293
1294    tor->downloadedPrev += tor->downloadedCur;
1295    tor->downloadedCur   = 0;
1296    tor->uploadedPrev   += tor->uploadedCur;
1297    tor->uploadedCur     = 0;
1298    tor->corruptPrev    += tor->corruptCur;
1299    tor->corruptCur      = 0;
1300
1301    tr_torrentSetDirty( tor );
1302
1303    tr_torrentUnlock( tor );
1304}
1305
1306void
1307tr_torrentSetHasPiece( tr_torrent *     tor,
1308                       tr_piece_index_t pieceIndex,
1309                       tr_bool          has )
1310{
1311    assert( tr_isTorrent( tor ) );
1312    assert( pieceIndex < tor->info.pieceCount );
1313
1314    if( has )
1315        tr_cpPieceAdd( &tor->completion, pieceIndex );
1316    else
1317        tr_cpPieceRem( &tor->completion, pieceIndex );
1318}
1319
1320/***
1321****
1322***/
1323
1324static void
1325freeTorrent( tr_torrent * tor )
1326{
1327    tr_torrent * t;
1328    tr_session *  session = tor->session;
1329    tr_info *    inf = &tor->info;
1330
1331    assert( tr_isTorrent( tor ) );
1332    assert( !tor->isRunning );
1333
1334    tr_sessionLock( session );
1335
1336    tr_peerMgrRemoveTorrent( tor );
1337
1338    tr_cpDestruct( &tor->completion );
1339
1340    tr_announcerUnsubscribe( tor->tiers, tor->tiersSubscription );
1341    tr_announcerRemoveTorrent( session->announcer, tor );
1342
1343    tr_bitfieldDestruct( &tor->checkedPieces );
1344
1345    tr_free( tor->downloadDir );
1346    tr_free( tor->incompleteDir );
1347    tr_free( tor->peer_id );
1348
1349    if( tor == session->torrentList )
1350        session->torrentList = tor->next;
1351    else for( t = session->torrentList; t != NULL; t = t->next ) {
1352        if( t->next == tor ) {
1353            t->next = tor->next;
1354            break;
1355        }
1356    }
1357
1358    assert( session->torrentCount >= 1 );
1359    session->torrentCount--;
1360
1361    tr_bandwidthFree( tor->bandwidth );
1362
1363    tr_metainfoFree( inf );
1364    tr_free( tor );
1365
1366    tr_sessionUnlock( session );
1367}
1368
1369/**
1370***  Start/Stop Callback
1371**/
1372
1373static void
1374checkAndStartImpl( void * vtor )
1375{
1376    tr_torrent * tor = vtor;
1377
1378    assert( tr_isTorrent( tor ) );
1379
1380    tr_sessionLock( tor->session );
1381
1382    /** If we had local data before, but it's disappeared,
1383        stop the torrent and log an error. */
1384    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1385    {
1386        tr_torrentSetLocalError( tor, _( "No data found!  Reconnect any disconnected drives, use \"Set Location\", or restart the torrent to re-download." ) );
1387        tr_torrentStop( tor );
1388    }
1389    else
1390    {
1391        const time_t now = tr_time( );
1392        tor->isRunning = TRUE;
1393        tor->error = TR_STAT_OK;
1394        tor->errorString[0] = '\0';
1395        tor->completeness = tr_cpGetStatus( &tor->completion );
1396        tor->startDate = tor->anyDate = now;
1397
1398        tr_torrentResetTransferStats( tor );
1399        tr_announcerTorrentStarted( tor );
1400        tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1401        tor->dhtAnnounce6At = now + tr_cryptoWeakRandInt( 20 );
1402        tr_peerMgrStartTorrent( tor );
1403    }
1404
1405    tr_sessionUnlock( tor->session );
1406}
1407
1408static void
1409checkAndStartCB( tr_torrent * tor )
1410{
1411    assert( tr_isTorrent( tor ) );
1412    assert( tr_isSession( tor->session ) );
1413
1414    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1415}
1416
1417static void
1418torrentStart( tr_torrent * tor )
1419{
1420    assert( tr_isTorrent( tor ) );
1421
1422    tr_sessionLock( tor->session );
1423
1424    if( !tor->isRunning )
1425    {
1426        /* allow finished torrents to be resumed */
1427        if( tr_torrentIsSeedRatioDone( tor ) )
1428        {
1429            tr_torinf( tor, "Restarted manually -- disabling its seed ratio" );
1430            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
1431        }
1432
1433        tr_verifyRemove( tor );
1434
1435        /* corresponds to the peer_id sent as a tracker request parameter.
1436         * one tracker admin says: "When the same torrent is opened and
1437         * closed and opened again without quitting Transmission ...
1438         * change the peerid. It would help sometimes if a stopped event
1439         * was missed to ensure that we didn't think someone was cheating. */
1440        tr_free( tor->peer_id );
1441        tor->peer_id = tr_peerIdNew( );
1442
1443        tor->isRunning = 1;
1444        tr_torrentSetDirty( tor );
1445        tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1446        tr_verifyAdd( tor, checkAndStartCB );
1447    }
1448
1449    tr_sessionUnlock( tor->session );
1450}
1451
1452void
1453tr_torrentStart( tr_torrent * tor )
1454{
1455    if( tr_isTorrent( tor ) )
1456        torrentStart( tor );
1457}
1458
1459static void
1460torrentRecheckDoneImpl( void * vtor )
1461{
1462    tr_torrent * tor = vtor;
1463
1464    assert( tr_isTorrent( tor ) );
1465    tr_torrentRecheckCompleteness( tor );
1466
1467    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1468    {
1469        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1470        tr_torrentStop( tor );
1471    }
1472    else if( tor->startAfterVerify )
1473    {
1474        tor->startAfterVerify = FALSE;
1475
1476        tr_torrentStart( tor );
1477    }
1478}
1479
1480static void
1481torrentRecheckDoneCB( tr_torrent * tor )
1482{
1483    assert( tr_isTorrent( tor ) );
1484
1485    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1486}
1487
1488static void
1489verifyTorrent( void * vtor )
1490{
1491    tr_torrent * tor = vtor;
1492
1493    assert( tr_isTorrent( tor ) );
1494    tr_sessionLock( tor->session );
1495
1496    /* if the torrent's already being verified, stop it */
1497    tr_verifyRemove( tor );
1498
1499    /* if the torrent's running, stop it & set the restart-after-verify flag */
1500    if( tor->startAfterVerify || tor->isRunning ) {
1501        tr_torrentStop( tor );
1502        tor->startAfterVerify = TRUE;
1503    }
1504
1505    /* add the torrent to the recheck queue */
1506    tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1507    tr_torrentUncheck( tor );
1508    tr_verifyAdd( tor, torrentRecheckDoneCB );
1509
1510    tr_sessionUnlock( tor->session );
1511}
1512
1513void
1514tr_torrentVerify( tr_torrent * tor )
1515{
1516    if( tr_isTorrent( tor ) )
1517        tr_runInEventThread( tor->session, verifyTorrent, tor );
1518}
1519
1520void
1521tr_torrentSave( tr_torrent * tor )
1522{
1523    assert( tr_isTorrent( tor ) );
1524
1525    if( tor->isDirty )
1526    {
1527        tor->isDirty = FALSE;
1528        tr_torrentSaveResume( tor );
1529    }
1530}
1531
1532static void
1533stopTorrent( void * vtor )
1534{
1535    tr_torrent * tor = vtor;
1536    tr_torinf( tor, "Pausing" );
1537
1538    assert( tr_isTorrent( tor ) );
1539
1540    tr_verifyRemove( tor );
1541    tr_peerMgrStopTorrent( tor );
1542    tr_announcerTorrentStopped( tor );
1543
1544    tr_fdTorrentClose( tor->session, tor->uniqueId );
1545
1546    if( !tor->isDeleting )
1547        tr_torrentSave( tor );
1548}
1549
1550void
1551tr_torrentStop( tr_torrent * tor )
1552{
1553    assert( tr_isTorrent( tor ) );
1554
1555    if( tr_isTorrent( tor ) )
1556    {
1557        tr_sessionLock( tor->session );
1558
1559        tor->isRunning = 0;
1560        tr_torrentSetDirty( tor );
1561        tr_runInEventThread( tor->session, stopTorrent, tor );
1562
1563        tr_sessionUnlock( tor->session );
1564    }
1565}
1566
1567static void
1568closeTorrent( void * vtor )
1569{
1570    tr_benc * d;
1571    tr_torrent * tor = vtor;
1572
1573    assert( tr_isTorrent( tor ) );
1574
1575    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1576    tr_bencDictAddInt( d, "id", tor->uniqueId );
1577    tr_bencDictAddInt( d, "date", tr_time( ) );
1578
1579    tr_torinf( tor, _( "Removing torrent" ) );
1580
1581    stopTorrent( tor );
1582
1583    if( tor->isDeleting )
1584    {
1585        tr_metainfoRemoveSaved( tor->session, &tor->info );
1586        tr_torrentRemoveResume( tor );
1587    }
1588
1589    tor->isRunning = 0;
1590    freeTorrent( tor );
1591}
1592
1593void
1594tr_torrentFree( tr_torrent * tor )
1595{
1596    if( tr_isTorrent( tor ) )
1597    {
1598        tr_session * session = tor->session;
1599        assert( tr_isSession( session ) );
1600        tr_sessionLock( session );
1601
1602        tr_torrentClearCompletenessCallback( tor );
1603        tr_runInEventThread( session, closeTorrent, tor );
1604
1605        tr_sessionUnlock( session );
1606    }
1607}
1608
1609void
1610tr_torrentRemove( tr_torrent * tor )
1611{
1612    assert( tr_isTorrent( tor ) );
1613
1614    tor->isDeleting = 1;
1615    tr_torrentFree( tor );
1616}
1617
1618/**
1619***  Completeness
1620**/
1621
1622static const char *
1623getCompletionString( int type )
1624{
1625    switch( type )
1626    {
1627        /* Translators: this is a minor point that's safe to skip over, but FYI:
1628           "Complete" and "Done" are specific, different terms in Transmission:
1629           "Complete" means we've downloaded every file in the torrent.
1630           "Done" means we're done downloading the files we wanted, but NOT all
1631           that exist */
1632        case TR_PARTIAL_SEED:
1633            return _( "Done" );
1634
1635        case TR_SEED:
1636            return _( "Complete" );
1637
1638        default:
1639            return _( "Incomplete" );
1640    }
1641}
1642
1643static void
1644fireCompletenessChange( tr_torrent       * tor,
1645                        tr_completeness    status )
1646{
1647    assert( tr_isTorrent( tor ) );
1648    assert( ( status == TR_LEECH )
1649         || ( status == TR_SEED )
1650         || ( status == TR_PARTIAL_SEED ) );
1651
1652    if( tor->completeness_func )
1653        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1654}
1655
1656void
1657tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1658                                   tr_torrent_completeness_func    func,
1659                                   void                          * user_data )
1660{
1661    assert( tr_isTorrent( tor ) );
1662
1663    tor->completeness_func = func;
1664    tor->completeness_func_user_data = user_data;
1665}
1666
1667void
1668tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1669{
1670    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1671}
1672
1673void
1674tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1675                                    tr_torrent_ratio_limit_hit_func  func,
1676                                    void                           * user_data )
1677{
1678    assert( tr_isTorrent( tor ) );
1679
1680    tor->ratio_limit_hit_func = func;
1681    tor->ratio_limit_hit_func_user_data = user_data;
1682}
1683
1684void
1685tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1686{
1687    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1688}
1689
1690void
1691tr_torrentRecheckCompleteness( tr_torrent * tor )
1692{
1693    tr_completeness completeness;
1694
1695    assert( tr_isTorrent( tor ) );
1696
1697    tr_torrentLock( tor );
1698
1699    completeness = tr_cpGetStatus( &tor->completion );
1700
1701    if( completeness != tor->completeness )
1702    {
1703        const int recentChange = tor->downloadedCur != 0;
1704
1705        if( recentChange )
1706        {
1707            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1708                      getCompletionString( tor->completeness ),
1709                      getCompletionString( completeness ) );
1710        }
1711
1712        tor->completeness = completeness;
1713        tr_fdTorrentClose( tor->session, tor->uniqueId );
1714
1715        /* if the torrent is a seed now,
1716         * and the files used to be in the incompleteDir,
1717         * then move them to the destination directory */
1718        if( tr_torrentIsSeed( tor ) && ( tor->currentDir == tor->incompleteDir ) )
1719            tr_torrentSetLocation( tor, tor->downloadDir, TRUE, NULL, NULL );
1720
1721        fireCompletenessChange( tor, completeness );
1722
1723        if( recentChange && tr_torrentIsSeed( tor ) )
1724        {
1725            tr_announcerTorrentCompleted( tor );
1726
1727            tor->doneDate = tor->anyDate = tr_time( );
1728        }
1729
1730        tr_torrentSetDirty( tor );
1731    }
1732
1733    tr_torrentUnlock( tor );
1734}
1735
1736/***
1737****
1738***/
1739
1740static void
1741tr_torrentFireMetadataCompleted( tr_torrent * tor )
1742{
1743    assert( tr_isTorrent( tor ) );
1744
1745    if( tor->metadata_func )
1746        tor->metadata_func( tor, tor->metadata_func_user_data );
1747}
1748
1749void
1750tr_torrentSetMetadataCallback( tr_torrent                * tor,
1751                               tr_torrent_metadata_func    func,
1752                               void                      * user_data )
1753{
1754    assert( tr_isTorrent( tor ) );
1755
1756    tor->metadata_func = func;
1757    tor->metadata_func_user_data = user_data;
1758}
1759
1760
1761/**
1762***  File priorities
1763**/
1764
1765void
1766tr_torrentInitFilePriority( tr_torrent *    tor,
1767                            tr_file_index_t fileIndex,
1768                            tr_priority_t   priority )
1769{
1770    tr_piece_index_t i;
1771    tr_file *        file;
1772
1773    assert( tr_isTorrent( tor ) );
1774    assert( fileIndex < tor->info.fileCount );
1775    assert( tr_isPriority( priority ) );
1776
1777    file = &tor->info.files[fileIndex];
1778    file->priority = priority;
1779    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1780        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1781}
1782
1783void
1784tr_torrentSetFilePriorities( tr_torrent *      tor,
1785                             tr_file_index_t * files,
1786                             tr_file_index_t   fileCount,
1787                             tr_priority_t     priority )
1788{
1789    tr_file_index_t i;
1790    assert( tr_isTorrent( tor ) );
1791    tr_torrentLock( tor );
1792
1793    for( i = 0; i < fileCount; ++i )
1794        if( files[i] < tor->info.fileCount )
1795            tr_torrentInitFilePriority( tor, files[i], priority );
1796    tr_torrentSetDirty( tor );
1797    tr_peerMgrRebuildRequests( tor );
1798
1799    tr_torrentUnlock( tor );
1800}
1801
1802tr_priority_t*
1803tr_torrentGetFilePriorities( const tr_torrent * tor )
1804{
1805    tr_file_index_t i;
1806    tr_priority_t * p;
1807
1808    assert( tr_isTorrent( tor ) );
1809
1810    tr_torrentLock( tor );
1811    p = tr_new0( tr_priority_t, tor->info.fileCount );
1812    for( i = 0; i < tor->info.fileCount; ++i )
1813        p[i] = tor->info.files[i].priority;
1814    tr_torrentUnlock( tor );
1815
1816    return p;
1817}
1818
1819/**
1820***  File DND
1821**/
1822
1823static void
1824setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1825{
1826    tr_file *        file;
1827    const int        dnd = !doDownload;
1828    tr_piece_index_t firstPiece, firstPieceDND;
1829    tr_piece_index_t lastPiece, lastPieceDND;
1830    tr_file_index_t  i;
1831
1832    assert( tr_isTorrent( tor ) );
1833
1834    file = &tor->info.files[fileIndex];
1835    file->dnd = dnd;
1836    firstPiece = file->firstPiece;
1837    lastPiece = file->lastPiece;
1838
1839    /* can't set the first piece to DND unless
1840       every file using that piece is DND */
1841    firstPieceDND = dnd;
1842    if( fileIndex > 0 )
1843    {
1844        for( i = fileIndex - 1; firstPieceDND; --i )
1845        {
1846            if( tor->info.files[i].lastPiece != firstPiece )
1847                break;
1848            firstPieceDND = tor->info.files[i].dnd;
1849            if( !i )
1850                break;
1851        }
1852    }
1853
1854    /* can't set the last piece to DND unless
1855       every file using that piece is DND */
1856    lastPieceDND = dnd;
1857    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1858    {
1859        if( tor->info.files[i].firstPiece != lastPiece )
1860            break;
1861        lastPieceDND = tor->info.files[i].dnd;
1862    }
1863
1864    if( firstPiece == lastPiece )
1865    {
1866        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1867    }
1868    else
1869    {
1870        tr_piece_index_t pp;
1871        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1872        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1873        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1874            tor->info.pieces[pp].dnd = dnd;
1875    }
1876}
1877
1878void
1879tr_torrentInitFileDLs( tr_torrent      * tor,
1880                       tr_file_index_t * files,
1881                       tr_file_index_t   fileCount,
1882                       tr_bool           doDownload )
1883{
1884    tr_file_index_t i;
1885
1886    assert( tr_isTorrent( tor ) );
1887
1888    tr_torrentLock( tor );
1889
1890    for( i=0; i<fileCount; ++i )
1891        if( files[i] < tor->info.fileCount )
1892            setFileDND( tor, files[i], doDownload );
1893
1894    tr_cpInvalidateDND( &tor->completion );
1895
1896    tr_torrentUnlock( tor );
1897}
1898
1899void
1900tr_torrentSetFileDLs( tr_torrent *      tor,
1901                      tr_file_index_t * files,
1902                      tr_file_index_t   fileCount,
1903                      tr_bool           doDownload )
1904{
1905    assert( tr_isTorrent( tor ) );
1906    tr_torrentLock( tor );
1907
1908    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1909    tr_torrentSetDirty( tor );
1910    tr_peerMgrRebuildRequests( tor );
1911
1912    tr_torrentUnlock( tor );
1913}
1914
1915/***
1916****
1917***/
1918
1919tr_priority_t
1920tr_torrentGetPriority( const tr_torrent * tor )
1921{
1922    assert( tr_isTorrent( tor ) );
1923
1924    return tor->bandwidth->priority;
1925}
1926
1927void
1928tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1929{
1930    assert( tr_isTorrent( tor ) );
1931    assert( tr_isPriority( priority ) );
1932
1933    if( tor->bandwidth->priority != priority )
1934    {
1935        tor->bandwidth->priority = priority;
1936
1937        tr_torrentSetDirty( tor );
1938    }
1939}
1940
1941/***
1942****
1943***/
1944
1945void
1946tr_torrentSetPeerLimit( tr_torrent * tor,
1947                        uint16_t     maxConnectedPeers )
1948{
1949    assert( tr_isTorrent( tor ) );
1950
1951    if ( tor->maxConnectedPeers != maxConnectedPeers )
1952    {
1953        tor->maxConnectedPeers = maxConnectedPeers;
1954
1955        tr_torrentSetDirty( tor );
1956    }
1957}
1958
1959uint16_t
1960tr_torrentGetPeerLimit( const tr_torrent * tor )
1961{
1962    assert( tr_isTorrent( tor ) );
1963
1964    return tor->maxConnectedPeers;
1965}
1966
1967/***
1968****
1969***/
1970
1971tr_block_index_t
1972_tr_block( const tr_torrent * tor,
1973           tr_piece_index_t   index,
1974           uint32_t           offset )
1975{
1976    tr_block_index_t ret;
1977
1978    assert( tr_isTorrent( tor ) );
1979
1980    ret = index;
1981    ret *= ( tor->info.pieceSize / tor->blockSize );
1982    ret += offset / tor->blockSize;
1983    return ret;
1984}
1985
1986tr_bool
1987tr_torrentReqIsValid( const tr_torrent * tor,
1988                      tr_piece_index_t   index,
1989                      uint32_t           offset,
1990                      uint32_t           length )
1991{
1992    int err = 0;
1993
1994    assert( tr_isTorrent( tor ) );
1995
1996    if( index >= tor->info.pieceCount )
1997        err = 1;
1998    else if( length < 1 )
1999        err = 2;
2000    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
2001        err = 3;
2002    else if( length > MAX_BLOCK_SIZE )
2003        err = 4;
2004    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
2005        err = 5;
2006
2007    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
2008                              (unsigned long)index,
2009                              (unsigned long)offset,
2010                              (unsigned long)length,
2011                              err );
2012
2013    return !err;
2014}
2015
2016uint64_t
2017tr_pieceOffset( const tr_torrent * tor,
2018                tr_piece_index_t   index,
2019                uint32_t           offset,
2020                uint32_t           length )
2021{
2022    uint64_t ret;
2023
2024    assert( tr_isTorrent( tor ) );
2025
2026    ret = tor->info.pieceSize;
2027    ret *= index;
2028    ret += offset;
2029    ret += length;
2030    return ret;
2031}
2032
2033/***
2034****
2035***/
2036
2037void
2038tr_torrentSetPieceChecked( tr_torrent        * tor,
2039                           tr_piece_index_t    piece,
2040                           tr_bool             isChecked )
2041{
2042    assert( tr_isTorrent( tor ) );
2043
2044    if( isChecked )
2045        tr_bitfieldAdd( &tor->checkedPieces, piece );
2046    else
2047        tr_bitfieldRem( &tor->checkedPieces, piece );
2048}
2049
2050void
2051tr_torrentSetFileChecked( tr_torrent *    tor,
2052                          tr_file_index_t fileIndex,
2053                          tr_bool         isChecked )
2054{
2055    const tr_file *        file = &tor->info.files[fileIndex];
2056    const tr_piece_index_t begin = file->firstPiece;
2057    const tr_piece_index_t end = file->lastPiece + 1;
2058
2059    assert( tr_isTorrent( tor ) );
2060
2061    if( isChecked )
2062        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
2063    else
2064        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
2065}
2066
2067tr_bool
2068tr_torrentIsFileChecked( const tr_torrent * tor,
2069                         tr_file_index_t    fileIndex )
2070{
2071    const tr_file *        file = &tor->info.files[fileIndex];
2072    const tr_piece_index_t begin = file->firstPiece;
2073    const tr_piece_index_t end = file->lastPiece + 1;
2074    tr_piece_index_t       i;
2075    tr_bool                isChecked = TRUE;
2076
2077    assert( tr_isTorrent( tor ) );
2078
2079    for( i = begin; isChecked && i < end; ++i )
2080        if( !tr_torrentIsPieceChecked( tor, i ) )
2081            isChecked = FALSE;
2082
2083    return isChecked;
2084}
2085
2086void
2087tr_torrentUncheck( tr_torrent * tor )
2088{
2089    assert( tr_isTorrent( tor ) );
2090
2091    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
2092}
2093
2094int
2095tr_torrentCountUncheckedPieces( const tr_torrent * tor )
2096{
2097    assert( tr_isTorrent( tor ) );
2098
2099    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
2100}
2101
2102time_t*
2103tr_torrentGetMTimes( const tr_torrent * tor, size_t * setme_n )
2104{
2105    size_t       i;
2106    const size_t n = tor->info.fileCount;
2107    time_t *     m = tr_new0( time_t, n );
2108
2109    assert( tr_isTorrent( tor ) );
2110
2111    for( i = 0; i < n; ++i )
2112    {
2113        struct stat sb;
2114        char * path = tr_torrentFindFile( tor, i );
2115        if( ( path != NULL ) && !stat( path, &sb ) && S_ISREG( sb.st_mode ) )
2116        {
2117#ifdef SYS_DARWIN
2118            m[i] = sb.st_mtimespec.tv_sec;
2119#else
2120            m[i] = sb.st_mtime;
2121#endif
2122        }
2123        tr_free( path );
2124    }
2125
2126    *setme_n = n;
2127    return m;
2128}
2129
2130/***
2131****
2132***/
2133
2134tr_bool
2135tr_torrentSetAnnounceList( tr_torrent             * tor,
2136                           const tr_tracker_info  * trackers,
2137                           int                      trackerCount )
2138{
2139    int i;
2140    tr_benc metainfo;
2141    tr_bool ok = TRUE;
2142    tr_torrentLock( tor );
2143
2144    assert( tr_isTorrent( tor ) );
2145
2146    /* look for bad URLs */
2147    for( i=0; ok && i<trackerCount; ++i )
2148        if( !tr_urlIsValidTracker( trackers[i].announce ) )
2149            ok = FALSE;
2150
2151    /* save to the .torrent file */
2152    if( ok && !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2153    {
2154        tr_bool hasInfo;
2155        tr_info tmpInfo;
2156
2157        /* remove the old fields */
2158        tr_bencDictRemove( &metainfo, "announce" );
2159        tr_bencDictRemove( &metainfo, "announce-list" );
2160
2161        /* add the new fields */
2162        if( trackerCount > 0 )
2163        {
2164            tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2165        }
2166        if( trackerCount > 1 )
2167        {
2168            int i;
2169            int prevTier = -1;
2170            tr_benc * tier = NULL;
2171            tr_benc * announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2172
2173            for( i=0; i<trackerCount; ++i ) {
2174                if( prevTier != trackers[i].tier ) {
2175                    prevTier = trackers[i].tier;
2176                    tier = tr_bencListAddList( announceList, 0 );
2177                }
2178                tr_bencListAddStr( tier, trackers[i].announce );
2179            }
2180        }
2181
2182        /* try to parse it back again, to make sure it's good */
2183        memset( &tmpInfo, 0, sizeof( tr_info ) );
2184        if( tr_metainfoParse( tor->session, &metainfo, &tmpInfo,
2185                              &hasInfo, &tor->infoDictOffset, &tor->infoDictLength ) )
2186        {
2187            /* it's good, so keep these new trackers and free the old ones */
2188
2189            tr_info swap;
2190            swap.trackers = tor->info.trackers;
2191            swap.trackerCount = tor->info.trackerCount;
2192            tor->info.trackers = tmpInfo.trackers;
2193            tor->info.trackerCount = tmpInfo.trackerCount;
2194            tmpInfo.trackers = swap.trackers;
2195            tmpInfo.trackerCount = swap.trackerCount;
2196
2197            tr_metainfoFree( &tmpInfo );
2198            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2199        }
2200
2201        /* cleanup */
2202        tr_bencFree( &metainfo );
2203
2204        /* tell the announcer to reload this torrent's tracker list */
2205        tr_announcerResetTorrent( tor->session->announcer, tor );
2206    }
2207
2208    tr_torrentUnlock( tor );
2209    return ok;
2210}
2211
2212/**
2213***
2214**/
2215
2216void
2217tr_torrentSetAddedDate( tr_torrent * tor,
2218                        time_t       t )
2219{
2220    assert( tr_isTorrent( tor ) );
2221
2222    tor->addedDate = t;
2223    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2224}
2225
2226void
2227tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2228{
2229    assert( tr_isTorrent( tor ) );
2230
2231    tor->activityDate = t;
2232    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2233}
2234
2235void
2236tr_torrentSetDoneDate( tr_torrent * tor,
2237                       time_t       t )
2238{
2239    assert( tr_isTorrent( tor ) );
2240
2241    tor->doneDate = t;
2242    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2243}
2244
2245/**
2246***
2247**/
2248
2249uint64_t
2250tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2251{
2252    tr_file_index_t i;
2253    uint64_t bytesLeft = 0;
2254
2255    assert( tr_isTorrent( tor ) );
2256
2257    for( i=0; i<tor->info.fileCount; ++i )
2258    {
2259        if( !tor->info.files[i].dnd )
2260        {
2261            struct stat sb;
2262            const uint64_t length = tor->info.files[i].length;
2263            char * path = tr_torrentFindFile( tor, i );
2264
2265            bytesLeft += length;
2266
2267            if( ( path != NULL ) && !stat( path, &sb )
2268                                 && S_ISREG( sb.st_mode )
2269                                 && ( (uint64_t)sb.st_size <= length ) )
2270                bytesLeft -= sb.st_size;
2271
2272            tr_free( path );
2273        }
2274    }
2275
2276    return bytesLeft;
2277}
2278
2279/****
2280*****  Removing the torrent's local data
2281****/
2282
2283static int
2284vstrcmp( const void * a, const void * b )
2285{
2286    return strcmp( a, b );
2287}
2288
2289static int
2290compareLongestFirst( const void * a, const void * b )
2291{
2292    const size_t alen = strlen( a );
2293    const size_t blen = strlen( b );
2294
2295    if( alen != blen )
2296        return alen > blen ? -1 : 1;
2297
2298    return vstrcmp( a, b );
2299}
2300
2301static void
2302addDirtyFile( const char  * root,
2303              const char  * filename,
2304              tr_ptrArray * dirtyFolders )
2305{
2306    char * dir = tr_dirname( filename );
2307
2308    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2309    while (     ( dir != NULL )
2310             && ( strlen( root ) <= strlen( dir ) )
2311             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2312    {
2313        char * tmp;
2314        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2315
2316        tmp = tr_dirname( dir );
2317        tr_free( dir );
2318        dir = tmp;
2319    }
2320
2321    tr_free( dir );
2322}
2323
2324static void
2325walkLocalData( const tr_torrent * tor,
2326               const char       * root,
2327               const char       * dir,
2328               const char       * base,
2329               tr_ptrArray      * torrentFiles,
2330               tr_ptrArray      * folders,
2331               tr_ptrArray      * dirtyFolders )
2332{
2333    int i;
2334    struct stat sb;
2335    char * buf;
2336
2337    assert( tr_isTorrent( tor ) );
2338
2339    buf = tr_buildPath( dir, base, NULL );
2340    i = stat( buf, &sb );
2341    if( !i )
2342    {
2343        DIR * odir = NULL;
2344
2345        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2346        {
2347            struct dirent *d;
2348            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2349            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2350                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2351                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2352            closedir( odir );
2353        }
2354        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2355        {
2356            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2357            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2358            if( !isTorrentFile )
2359                addDirtyFile( root, buf, dirtyFolders );
2360        }
2361    }
2362
2363    tr_free( buf );
2364}
2365
2366static void
2367deleteLocalFile( const char * filename, tr_fileFunc fileFunc )
2368{
2369    struct stat sb;
2370    if( !stat( filename, &sb ) ) /* if file exists... */
2371        fileFunc( filename );
2372}
2373
2374static void
2375deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2376{
2377    int i, n;
2378    char ** s;
2379    tr_file_index_t f;
2380    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2381    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2382    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2383
2384    const char * firstFile = tor->info.files[0].name;
2385    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2386    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2387    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2388
2389    assert( tr_isTorrent( tor ) );
2390
2391    for( f=0; f<tor->info.fileCount; ++f ) {
2392        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2393        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2394    }
2395
2396    /* build the set of folders and dirtyFolders */
2397    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2398
2399    /* try to remove entire folders first, so that the recycle bin will be tidy */
2400    s = (char**) tr_ptrArrayPeek( &folders, &n );
2401    for( i=0; i<n; ++i )
2402        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2403            deleteLocalFile( s[i], fileFunc );
2404
2405    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2406    for( i=0, n=tr_ptrArraySize( &torrentFiles ); i<n; ++i ) {
2407        char * path = tr_buildPath( tor->currentDir, tr_ptrArrayNth( &torrentFiles, i ), NULL );
2408        deleteLocalFile( path, fileFunc );
2409        tr_free( path );
2410    }
2411
2412    /* Now clean out the directories left empty from the previous step.
2413     * Work from deepest to shallowest s.t. lower folders
2414     * won't prevent the upper folders from being deleted */
2415    {
2416        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2417        s = (char**) tr_ptrArrayPeek( &folders, &n );
2418        for( i=0; i<n; ++i )
2419            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2420                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2421        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2422        for( i=0; i<n; ++i ) {
2423#ifdef SYS_DARWIN
2424            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2425            deleteLocalFile( dsStore, fileFunc );
2426            tr_free( dsStore );
2427#endif
2428            deleteLocalFile( s[i], fileFunc );
2429        }
2430        tr_ptrArrayDestruct( &cleanFolders, NULL );
2431    }
2432
2433    /* cleanup */
2434    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2435    tr_ptrArrayDestruct( &folders, tr_free );
2436    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2437    tr_free( root );
2438    tr_free( tmp );
2439}
2440
2441void
2442tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2443{
2444    assert( tr_isTorrent( tor ) );
2445
2446    if( fileFunc == NULL )
2447        fileFunc = remove;
2448
2449    /* close all the files because we're about to delete them */
2450    tr_fdTorrentClose( tor->session, tor->uniqueId );
2451
2452    if( tor->info.fileCount > 1 )
2453    {
2454        deleteLocalData( tor, fileFunc );
2455    }
2456    else if( tor->info.fileCount == 1 )
2457    {
2458        char * tmp;
2459
2460        /* torrent only has one file */
2461        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2462        deleteLocalFile( path, fileFunc );
2463        tr_free( path );
2464
2465        tmp = tr_torrentBuildPartial( tor, 0 );
2466        path = tr_buildPath( tor->currentDir, tmp, NULL );
2467        deleteLocalFile( path, fileFunc );
2468        tr_free( path );
2469        tr_free( tmp );
2470    }
2471}
2472
2473/***
2474****
2475***/
2476
2477struct LocationData
2478{
2479    tr_bool move_from_old_location;
2480    int * setme_state;
2481    double * setme_progress;
2482    char * location;
2483    tr_torrent * tor;
2484};
2485
2486static tr_bool
2487sameInode( const char * path1, const char * path2 )
2488{
2489    int i1, i2;
2490    struct stat s1, s2;
2491
2492    s1.st_ino = 1;
2493    i1 = stat( path1, &s1 );
2494
2495    s2.st_ino = 2;
2496    i2 = stat( path2, &s2 );
2497
2498    if( !i1 && !i2 ) {
2499        tr_dbg( "path1 inode is %"PRIu64"; path2 inode is %"PRIu64,
2500                (uint64_t)s1.st_ino,
2501                (uint64_t)s2.st_ino );
2502        return s1.st_ino == s2.st_ino;
2503    }
2504
2505    /* either one, or the other, or both don't exist... */
2506    tr_dbg( "stat(%s) returned %d\n", path1, i1 );
2507    tr_dbg( "stat(%s) returned %d\n", path2, i2 );
2508    return FALSE;
2509}
2510
2511static void
2512setLocation( void * vdata )
2513{
2514    tr_bool err = FALSE;
2515    tr_bool verify_needed = FALSE;
2516    struct LocationData * data = vdata;
2517    tr_torrent * tor = data->tor;
2518    const tr_bool do_move = data->move_from_old_location;
2519    const char * location = data->location;
2520    double bytesHandled = 0;
2521
2522    assert( tr_isTorrent( tor ) );
2523
2524    tr_dbg( "Moving \"%s\" location from currentDir \"%s\" to \"%s\"",
2525            tr_torrentName(tor), tor->currentDir, location );
2526
2527    tr_mkdirp( location, 0777 );
2528
2529    if( !sameInode( location, tor->currentDir ) )
2530    {
2531        tr_file_index_t i;
2532
2533        /* bad idea to move files while they're being verified... */
2534        tr_verifyRemove( tor );
2535
2536        /* if the torrent is running, stop it and set a flag to
2537         * restart after we're done */
2538        if( tor->isRunning )
2539        {
2540            tr_torrentStop( tor );
2541            tor->startAfterVerify = TRUE;
2542        }
2543
2544        /* try to move the files.
2545         * FIXME: there are still all kinds of nasty cases, like what
2546         * if the target directory runs out of space halfway through... */
2547        for( i=0; !err && i<tor->info.fileCount; ++i )
2548        {
2549            const tr_file * f = &tor->info.files[i];
2550            const char * oldbase;
2551            char * sub;
2552            if( tr_torrentFindFile2( tor, i, &oldbase, &sub ) )
2553            {
2554                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2555                char * newpath = tr_buildPath( location, sub, NULL );
2556
2557                tr_dbg( "Found file #%d: %s", (int)i, oldpath );
2558
2559                if( do_move )
2560                {
2561                    tr_bool renamed = FALSE;
2562                    errno = 0;
2563                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2564                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2565                    {
2566                        err = TRUE;
2567                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2568                                        oldpath, newpath, tr_strerror( errno ) );
2569                    }
2570                    else if( !renamed )
2571                    {
2572                        verify_needed = TRUE;
2573                    }
2574                }
2575
2576                tr_free( newpath );
2577                tr_free( oldpath );
2578                tr_free( sub );
2579            }
2580
2581            if( data->setme_progress )
2582            {
2583                bytesHandled += f->length;
2584                *data->setme_progress = bytesHandled / tor->info.totalSize;
2585            }
2586        }
2587
2588        if( !err )
2589        {
2590            /* blow away the leftover subdirectories in the old location */
2591            if( do_move )
2592                tr_torrentDeleteLocalData( tor, remove );
2593
2594            /* set the new location and reverify */
2595            tr_torrentSetDownloadDir( tor, location );
2596            if( verify_needed )
2597                tr_torrentVerify( tor );
2598            else if( tor->startAfterVerify ) {
2599                tor->startAfterVerify = FALSE;
2600                tr_torrentStart( tor );
2601            }
2602        }
2603    }
2604
2605    if( !err && do_move )
2606    {
2607        tr_free( tor->incompleteDir );
2608        tor->incompleteDir = NULL;
2609        tor->currentDir = tor->downloadDir;
2610    }
2611
2612    if( data->setme_state )
2613        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2614
2615    /* cleanup */
2616    tr_free( data->location );
2617    tr_free( data );
2618}
2619
2620void
2621tr_torrentSetLocation( tr_torrent  * tor,
2622                       const char  * location,
2623                       tr_bool       move_from_old_location,
2624                       double      * setme_progress,
2625                       int         * setme_state )
2626{
2627    struct LocationData * data;
2628
2629    assert( tr_isTorrent( tor ) );
2630
2631    if( setme_state )
2632        *setme_state = TR_LOC_MOVING;
2633    if( setme_progress )
2634        *setme_progress = 0;
2635
2636    /* run this in the libtransmission thread */
2637    data = tr_new( struct LocationData, 1 );
2638    data->tor = tor;
2639    data->location = tr_strdup( location );
2640    data->move_from_old_location = move_from_old_location;
2641    data->setme_state = setme_state;
2642    data->setme_progress = setme_progress;
2643    tr_runInEventThread( tor->session, setLocation, data );
2644}
2645
2646/***
2647****
2648***/
2649
2650void
2651tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2652{
2653    char * sub;
2654    const char * base;
2655
2656    /* close the file so that we can reopen in read-only mode as needed */
2657    tr_fdFileClose( tor->session, tor, fileNum );
2658
2659    /* if the torrent's filename on disk isn't the same as the one in the metadata,
2660     * then it's been modified to denote that it was a partial file.
2661     * Now that it's complete, use the proper filename. */
2662    if( tr_torrentFindFile2( tor, fileNum, &base, &sub ) )
2663    {
2664        const tr_file * file = &tor->info.files[fileNum];
2665
2666        if( strcmp( sub, file->name ) )
2667        {
2668            char * oldpath = tr_buildPath( base, sub, NULL );
2669            char * newpath = tr_buildPath( base, file->name, NULL );
2670
2671            if( rename( oldpath, newpath ) )
2672                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2673
2674            tr_free( newpath );
2675            tr_free( oldpath );
2676        }
2677
2678        tr_free( sub );
2679    }
2680}
2681
2682/***
2683****
2684***/
2685
2686static tr_bool
2687fileExists( const char * filename )
2688{
2689    struct stat sb;
2690    const tr_bool ok = !stat( filename, &sb );
2691    return ok;
2692}
2693
2694tr_bool
2695tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
2696                     const char ** base, char ** subpath )
2697{
2698    char * part;
2699    const tr_file * file;
2700    const char * b = NULL;
2701    const char * s = NULL;
2702
2703    assert( tr_isTorrent( tor ) );
2704    assert( fileNum < tor->info.fileCount );
2705
2706    file = &tor->info.files[fileNum];
2707    part = tr_torrentBuildPartial( tor, fileNum );
2708
2709    if( b == NULL ) {
2710        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
2711        if( fileExists( filename ) ) {
2712            b = tor->downloadDir;
2713            s = file->name;
2714        }
2715        tr_free( filename );
2716    }
2717
2718    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2719        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
2720        if( fileExists( filename ) ) {
2721            b = tor->incompleteDir;
2722            s = file->name;
2723        }
2724        tr_free( filename );
2725    }
2726
2727    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2728        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
2729        if( fileExists( filename ) ) {
2730            b = tor->incompleteDir;
2731            s = part;
2732        }
2733        tr_free( filename );
2734    }
2735
2736    if( b == NULL) {
2737        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
2738        if( fileExists( filename ) ) {
2739            b = tor->downloadDir;
2740            s = part;
2741        }
2742        tr_free( filename );
2743    }
2744
2745    if( base != NULL )
2746        *base = b;
2747    if( subpath != NULL )
2748        *subpath = tr_strdup( s );
2749
2750    tr_free( part );
2751    return b != NULL;
2752}
2753
2754char*
2755tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
2756{
2757    char * subpath;
2758    char * ret = NULL;
2759    const char * base;
2760
2761    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath ) )
2762    {
2763        ret = tr_buildPath( base, subpath, NULL );
2764        tr_free( subpath );
2765    }
2766
2767    return ret;
2768}
2769
2770/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
2771static void
2772refreshCurrentDir( tr_torrent * tor )
2773{
2774    const char * dir = NULL;
2775    char * sub;
2776
2777    if( tor->incompleteDir == NULL )
2778        dir = tor->downloadDir;
2779    else if( !tr_torrentHasMetadata( tor ) ) /* no files to find */
2780        dir = tor->incompleteDir;
2781    else if( !tr_torrentFindFile2( tor, 0, &dir, &sub ) )
2782        dir = tor->incompleteDir;
2783
2784    assert( dir != NULL );
2785    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
2786    tor->currentDir = dir;
2787}
2788
2789char*
2790tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
2791{
2792    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
2793}
Note: See TracBrowser for help on using the repository browser.