source: trunk/libtransmission/torrent.c @ 10606

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

(trunk) #3060 -- Local Peer Discovery patch from Eszet

  • Property svn:keywords set to Date Rev Author Id
File size: 72.9 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 10606 2010-05-01 16:04:00Z 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            const int seedProbability = event->seedProbability;
366            const tr_bool allAreSeeds = seedProbability == 100;
367            tr_pex * pex = tr_peerMgrArrayToPex( event->compact,
368                                                 event->compactLen, &n );
369             if( allAreSeeds )
370                tr_tordbg( tor, "Got %d seeds from tracker", (int)n );
371            else
372                tr_tordbg( tor, "Got %d peers from tracker", (int)n );
373
374            for( i = 0; i < n; ++i )
375                tr_peerMgrAddPex( tor, TR_PEER_FROM_TRACKER, pex+i, seedProbability );
376
377            if( allAreSeeds && tr_torrentIsPrivate( tor ) )
378                tr_peerMgrMarkAllAsSeeds( tor );
379
380            tr_free( pex );
381            break;
382        }
383
384        case TR_TRACKER_WARNING:
385            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
386            tor->error = TR_STAT_TRACKER_WARNING;
387            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
388            break;
389
390        case TR_TRACKER_ERROR:
391            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
392            tor->error = TR_STAT_TRACKER_ERROR;
393            tr_strlcpy( tor->errorString, event->text, sizeof( tor->errorString ) );
394            break;
395
396        case TR_TRACKER_ERROR_CLEAR:
397            if( tor->error != TR_STAT_LOCAL_ERROR )
398            {
399                tor->error = TR_STAT_OK;
400                tor->errorString[0] = '\0';
401            }
402            break;
403    }
404}
405
406/***
407****
408****  TORRENT INSTANTIATION
409****
410***/
411
412static int
413getBytePiece( const tr_info * info,
414              uint64_t        byteOffset )
415{
416    assert( info );
417    assert( info->pieceSize != 0 );
418
419    return byteOffset / info->pieceSize;
420}
421
422static void
423initFilePieces( tr_info *       info,
424                tr_file_index_t fileIndex )
425{
426    tr_file * file;
427    uint64_t  firstByte, lastByte;
428
429    assert( info );
430    assert( fileIndex < info->fileCount );
431
432    file = &info->files[fileIndex];
433    firstByte = file->offset;
434    lastByte = firstByte + ( file->length ? file->length - 1 : 0 );
435    file->firstPiece = getBytePiece( info, firstByte );
436    file->lastPiece = getBytePiece( info, lastByte );
437}
438
439static int
440pieceHasFile( tr_piece_index_t piece,
441              const tr_file *  file )
442{
443    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
444}
445
446static tr_priority_t
447calculatePiecePriority( const tr_torrent * tor,
448                        tr_piece_index_t   piece,
449                        int                fileHint )
450{
451    tr_file_index_t i;
452    int             priority = TR_PRI_LOW;
453
454    /* find the first file that has data in this piece */
455    if( fileHint >= 0 ) {
456        i = fileHint;
457        while( i > 0 && pieceHasFile( piece, &tor->info.files[i - 1] ) )
458            --i;
459    } else {
460        for( i = 0; i < tor->info.fileCount; ++i )
461            if( pieceHasFile( piece, &tor->info.files[i] ) )
462                break;
463    }
464
465    /* the piece's priority is the max of the priorities
466     * of all the files in that piece */
467    for( ; i < tor->info.fileCount; ++i )
468    {
469        const tr_file * file = &tor->info.files[i];
470
471        if( !pieceHasFile( piece, file ) )
472            break;
473
474        priority = MAX( priority, file->priority );
475
476        /* when dealing with multimedia files, getting the first and
477           last pieces can sometimes allow you to preview it a bit
478           before it's fully downloaded... */
479        if( file->priority >= TR_PRI_NORMAL )
480            if( file->firstPiece == piece || file->lastPiece == piece )
481                priority = TR_PRI_HIGH;
482    }
483
484    return priority;
485}
486
487static void
488tr_torrentInitFilePieces( tr_torrent * tor )
489{
490    tr_file_index_t  f;
491    tr_piece_index_t p;
492    uint64_t offset = 0;
493    tr_info * inf = &tor->info;
494    int * firstFiles;
495
496    /* assign the file offsets */
497    for( f=0; f<inf->fileCount; ++f ) {
498        inf->files[f].offset = offset;
499        offset += inf->files[f].length;
500        initFilePieces( inf, f );
501    }
502
503    /* build the array of first-file hints to give calculatePiecePriority */
504    firstFiles = tr_new( int, inf->pieceCount );
505    for( p=f=0; p<inf->pieceCount; ++p ) {
506        while( inf->files[f].lastPiece < p )
507            ++f;
508        firstFiles[p] = f;
509    }
510
511#if 0
512    /* test to confirm the first-file hints are correct */
513    for( p=0; p<inf->pieceCount; ++p ) {
514        f = firstFiles[p];
515        assert( inf->files[f].firstPiece <= p );
516        assert( inf->files[f].lastPiece >= p );
517        if( f > 0 )
518            assert( inf->files[f-1].lastPiece < p );
519        for( f=0; f<inf->fileCount; ++f )
520            if( pieceHasFile( p, &inf->files[f] ) )
521                break;
522        assert( (int)f == firstFiles[p] );
523    }
524#endif
525
526    for( p=0; p<inf->pieceCount; ++p )
527        inf->pieces[p].priority = calculatePiecePriority( tor, p, firstFiles[p] );
528
529    tr_free( firstFiles );
530}
531
532int
533tr_torrentPromoteTracker( tr_torrent * tor,
534                          int          pos )
535{
536    int i;
537    int tier;
538
539    assert( tor );
540    assert( ( 0 <= pos ) && ( pos < tor->info.trackerCount ) );
541
542    /* the tier of the tracker we're promoting */
543    tier = tor->info.trackers[pos].tier;
544
545    /* find the index of that tier's first tracker */
546    for( i = 0; i < tor->info.trackerCount; ++i )
547        if( tor->info.trackers[i].tier == tier )
548            break;
549
550    assert( i < tor->info.trackerCount );
551
552    /* promote the tracker at `pos' to the front of the tier */
553    if( i != pos )
554    {
555        const tr_tracker_info tmp = tor->info.trackers[i];
556        tor->info.trackers[i] = tor->info.trackers[pos];
557        tor->info.trackers[pos] = tmp;
558    }
559
560    /* return the new position of the tracker that started out at [pos] */
561    return i;
562}
563
564static void torrentStart( tr_torrent * tor );
565
566/**
567 * Decide on a block size.  constraints:
568 * (1) most clients decline requests over 16 KiB
569 * (2) pieceSize must be a multiple of block size
570 */
571static uint32_t
572getBlockSize( uint32_t pieceSize )
573{
574    uint32_t b = pieceSize;
575
576    while( b > MAX_BLOCK_SIZE )
577        b /= 2u;
578
579    if( !b || ( pieceSize % b ) ) /* not cleanly divisible */
580        return 0;
581    return b;
582}
583
584static void refreshCurrentDir( tr_torrent * tor );
585
586static void
587torrentInitFromInfo( tr_torrent * tor )
588{
589    uint64_t t;
590    tr_info * info = &tor->info;
591
592    tor->blockSize = getBlockSize( info->pieceSize );
593
594    if( info->pieceSize )
595        tor->lastPieceSize = info->totalSize % info->pieceSize;
596
597    if( !tor->lastPieceSize )
598        tor->lastPieceSize = info->pieceSize;
599
600    if( tor->blockSize )
601        tor->lastBlockSize = info->totalSize % tor->blockSize;
602
603    if( !tor->lastBlockSize )
604        tor->lastBlockSize = tor->blockSize;
605
606    tor->blockCount = tor->blockSize
607        ? ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize
608        : 0;
609
610    tor->blockCountInPiece = tor->blockSize
611        ? info->pieceSize / tor->blockSize
612        : 0;
613
614    tor->blockCountInLastPiece = tor->blockSize
615        ? ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize
616        : 0;
617
618    /* check our work */
619    if( tor->blockSize != 0 )
620        assert( ( info->pieceSize % tor->blockSize ) == 0 );
621    t = info->pieceCount - 1;
622    t *= info->pieceSize;
623    t += tor->lastPieceSize;
624    assert( t == info->totalSize );
625    t = tor->blockCount - 1;
626    t *= tor->blockSize;
627    t += tor->lastBlockSize;
628    assert( t == info->totalSize );
629    t = info->pieceCount - 1;
630    t *= tor->blockCountInPiece;
631    t += tor->blockCountInLastPiece;
632    assert( t == (uint64_t)tor->blockCount );
633
634    tr_cpConstruct( &tor->completion, tor );
635
636    tr_torrentInitFilePieces( tor );
637
638    tr_bitfieldConstruct( &tor->checkedPieces, tor->info.pieceCount );
639
640    tor->completeness = tr_cpGetStatus( &tor->completion );
641}
642
643static void tr_torrentFireMetadataCompleted( tr_torrent * tor );
644
645void
646tr_torrentGotNewInfoDict( tr_torrent * tor )
647{
648    torrentInitFromInfo( tor );
649
650    tr_torrentFireMetadataCompleted( tor );
651}
652
653static void
654torrentInit( tr_torrent * tor, const tr_ctor * ctor )
655{
656    int doStart;
657    uint64_t loaded;
658    const char * dir;
659    static int nextUniqueId = 1;
660    tr_session * session = tr_ctorGetSession( ctor );
661
662    assert( session != NULL );
663
664    tr_sessionLock( session );
665
666    tor->session   = session;
667    tor->uniqueId = nextUniqueId++;
668    tor->magicNumber = TORRENT_MAGIC_NUMBER;
669
670    tr_sha1( tor->obfuscatedHash, "req2", 4,
671             tor->info.hash, SHA_DIGEST_LENGTH,
672             NULL );
673
674    if( !tr_ctorGetDownloadDir( ctor, TR_FORCE, &dir ) ||
675        !tr_ctorGetDownloadDir( ctor, TR_FALLBACK, &dir ) )
676            tor->downloadDir = tr_strdup( dir );
677
678    if( tr_ctorGetIncompleteDir( ctor, &dir ) )
679        dir = tr_sessionGetIncompleteDir( session );
680    if( tr_sessionIsIncompleteDirEnabled( session ) )
681        tor->incompleteDir = tr_strdup( dir );
682
683    tor->bandwidth = tr_bandwidthNew( session, session->bandwidth );
684
685    tor->bandwidth->priority = tr_ctorGetBandwidthPriority( ctor );
686
687    tor->error = TR_STAT_OK;
688
689    tr_peerMgrAddTorrent( session->peerMgr, tor );
690
691    assert( !tor->downloadedCur );
692    assert( !tor->uploadedCur );
693
694    tr_torrentUncheck( tor );
695
696    tr_torrentSetAddedDate( tor, tr_time( ) ); /* this is a default value to be
697                                                  overwritten by the resume file */
698
699    torrentInitFromInfo( tor );
700    loaded = tr_torrentLoadResume( tor, ~0, ctor );
701    tor->completeness = tr_cpGetStatus( &tor->completion );
702
703    tr_ctorInitTorrentPriorities( ctor, tor );
704    tr_ctorInitTorrentWanted( ctor, tor );
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        tor->ldsAnnounceAt = now;
1404        tr_peerMgrStartTorrent( tor );
1405    }
1406
1407    tr_sessionUnlock( tor->session );
1408}
1409
1410static void
1411checkAndStartCB( tr_torrent * tor )
1412{
1413    assert( tr_isTorrent( tor ) );
1414    assert( tr_isSession( tor->session ) );
1415
1416    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1417}
1418
1419static void
1420torrentStart( tr_torrent * tor )
1421{
1422    assert( tr_isTorrent( tor ) );
1423
1424    tr_sessionLock( tor->session );
1425
1426    if( !tor->isRunning )
1427    {
1428        /* allow finished torrents to be resumed */
1429        if( tr_torrentIsSeedRatioDone( tor ) )
1430        {
1431            tr_torinf( tor, "Restarted manually -- disabling its seed ratio" );
1432            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
1433        }
1434
1435        tr_verifyRemove( tor );
1436
1437        /* corresponds to the peer_id sent as a tracker request parameter.
1438         * one tracker admin says: "When the same torrent is opened and
1439         * closed and opened again without quitting Transmission ...
1440         * change the peerid. It would help sometimes if a stopped event
1441         * was missed to ensure that we didn't think someone was cheating. */
1442        tr_free( tor->peer_id );
1443        tor->peer_id = tr_peerIdNew( );
1444
1445        tor->isRunning = 1;
1446        tr_torrentSetDirty( tor );
1447        tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1448        tr_verifyAdd( tor, checkAndStartCB );
1449    }
1450
1451    tr_sessionUnlock( tor->session );
1452}
1453
1454void
1455tr_torrentStart( tr_torrent * tor )
1456{
1457    if( tr_isTorrent( tor ) )
1458        torrentStart( tor );
1459}
1460
1461static void
1462torrentRecheckDoneImpl( void * vtor )
1463{
1464    tr_torrent * tor = vtor;
1465
1466    assert( tr_isTorrent( tor ) );
1467    tr_torrentRecheckCompleteness( tor );
1468
1469    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1470    {
1471        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1472        tr_torrentStop( tor );
1473    }
1474    else if( tor->startAfterVerify )
1475    {
1476        tor->startAfterVerify = FALSE;
1477
1478        tr_torrentStart( tor );
1479    }
1480}
1481
1482static void
1483torrentRecheckDoneCB( tr_torrent * tor )
1484{
1485    assert( tr_isTorrent( tor ) );
1486
1487    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1488}
1489
1490static void
1491verifyTorrent( void * vtor )
1492{
1493    tr_torrent * tor = vtor;
1494
1495    assert( tr_isTorrent( tor ) );
1496    tr_sessionLock( tor->session );
1497
1498    /* if the torrent's already being verified, stop it */
1499    tr_verifyRemove( tor );
1500
1501    /* if the torrent's running, stop it & set the restart-after-verify flag */
1502    if( tor->startAfterVerify || tor->isRunning ) {
1503        tr_torrentStop( tor );
1504        tor->startAfterVerify = TRUE;
1505    }
1506
1507    /* add the torrent to the recheck queue */
1508    tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1509    tr_torrentUncheck( tor );
1510    tr_verifyAdd( tor, torrentRecheckDoneCB );
1511
1512    tr_sessionUnlock( tor->session );
1513}
1514
1515void
1516tr_torrentVerify( tr_torrent * tor )
1517{
1518    if( tr_isTorrent( tor ) )
1519        tr_runInEventThread( tor->session, verifyTorrent, tor );
1520}
1521
1522void
1523tr_torrentSave( tr_torrent * tor )
1524{
1525    assert( tr_isTorrent( tor ) );
1526
1527    if( tor->isDirty )
1528    {
1529        tor->isDirty = FALSE;
1530        tr_torrentSaveResume( tor );
1531    }
1532}
1533
1534static void
1535stopTorrent( void * vtor )
1536{
1537    tr_torrent * tor = vtor;
1538    tr_torinf( tor, "Pausing" );
1539
1540    assert( tr_isTorrent( tor ) );
1541
1542    tr_verifyRemove( tor );
1543    tr_peerMgrStopTorrent( tor );
1544    tr_announcerTorrentStopped( tor );
1545
1546    tr_fdTorrentClose( tor->session, tor->uniqueId );
1547
1548    if( !tor->isDeleting )
1549        tr_torrentSave( tor );
1550}
1551
1552void
1553tr_torrentStop( tr_torrent * tor )
1554{
1555    assert( tr_isTorrent( tor ) );
1556
1557    if( tr_isTorrent( tor ) )
1558    {
1559        tr_sessionLock( tor->session );
1560
1561        tor->isRunning = 0;
1562        tr_torrentSetDirty( tor );
1563        tr_runInEventThread( tor->session, stopTorrent, tor );
1564
1565        tr_sessionUnlock( tor->session );
1566    }
1567}
1568
1569static void
1570closeTorrent( void * vtor )
1571{
1572    tr_benc * d;
1573    tr_torrent * tor = vtor;
1574
1575    assert( tr_isTorrent( tor ) );
1576
1577    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1578    tr_bencDictAddInt( d, "id", tor->uniqueId );
1579    tr_bencDictAddInt( d, "date", tr_time( ) );
1580
1581    tr_torinf( tor, _( "Removing torrent" ) );
1582
1583    stopTorrent( tor );
1584
1585    if( tor->isDeleting )
1586    {
1587        tr_metainfoRemoveSaved( tor->session, &tor->info );
1588        tr_torrentRemoveResume( tor );
1589    }
1590
1591    tor->isRunning = 0;
1592    freeTorrent( tor );
1593}
1594
1595void
1596tr_torrentFree( tr_torrent * tor )
1597{
1598    if( tr_isTorrent( tor ) )
1599    {
1600        tr_session * session = tor->session;
1601        assert( tr_isSession( session ) );
1602        tr_sessionLock( session );
1603
1604        tr_torrentClearCompletenessCallback( tor );
1605        tr_runInEventThread( session, closeTorrent, tor );
1606
1607        tr_sessionUnlock( session );
1608    }
1609}
1610
1611void
1612tr_torrentRemove( tr_torrent * tor )
1613{
1614    assert( tr_isTorrent( tor ) );
1615
1616    tor->isDeleting = 1;
1617    tr_torrentFree( tor );
1618}
1619
1620/**
1621***  Completeness
1622**/
1623
1624static const char *
1625getCompletionString( int type )
1626{
1627    switch( type )
1628    {
1629        /* Translators: this is a minor point that's safe to skip over, but FYI:
1630           "Complete" and "Done" are specific, different terms in Transmission:
1631           "Complete" means we've downloaded every file in the torrent.
1632           "Done" means we're done downloading the files we wanted, but NOT all
1633           that exist */
1634        case TR_PARTIAL_SEED:
1635            return _( "Done" );
1636
1637        case TR_SEED:
1638            return _( "Complete" );
1639
1640        default:
1641            return _( "Incomplete" );
1642    }
1643}
1644
1645static void
1646fireCompletenessChange( tr_torrent       * tor,
1647                        tr_completeness    status )
1648{
1649    assert( tr_isTorrent( tor ) );
1650    assert( ( status == TR_LEECH )
1651         || ( status == TR_SEED )
1652         || ( status == TR_PARTIAL_SEED ) );
1653
1654    if( tor->completeness_func )
1655        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1656}
1657
1658void
1659tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1660                                   tr_torrent_completeness_func    func,
1661                                   void                          * user_data )
1662{
1663    assert( tr_isTorrent( tor ) );
1664
1665    tor->completeness_func = func;
1666    tor->completeness_func_user_data = user_data;
1667}
1668
1669void
1670tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1671{
1672    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1673}
1674
1675void
1676tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1677                                    tr_torrent_ratio_limit_hit_func  func,
1678                                    void                           * user_data )
1679{
1680    assert( tr_isTorrent( tor ) );
1681
1682    tor->ratio_limit_hit_func = func;
1683    tor->ratio_limit_hit_func_user_data = user_data;
1684}
1685
1686void
1687tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1688{
1689    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1690}
1691
1692void
1693tr_torrentRecheckCompleteness( tr_torrent * tor )
1694{
1695    tr_completeness completeness;
1696
1697    assert( tr_isTorrent( tor ) );
1698
1699    tr_torrentLock( tor );
1700
1701    completeness = tr_cpGetStatus( &tor->completion );
1702
1703    if( completeness != tor->completeness )
1704    {
1705        const int recentChange = tor->downloadedCur != 0;
1706
1707        if( recentChange )
1708        {
1709            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1710                      getCompletionString( tor->completeness ),
1711                      getCompletionString( completeness ) );
1712        }
1713
1714        tor->completeness = completeness;
1715        tr_fdTorrentClose( tor->session, tor->uniqueId );
1716
1717        if( tr_torrentIsSeed( tor ) )
1718        {
1719            tr_torrentCheckSeedRatio( tor );
1720
1721            if( tor->currentDir == tor->incompleteDir )
1722                tr_torrentSetLocation( tor, tor->downloadDir, TRUE, NULL, NULL );
1723        }
1724
1725        fireCompletenessChange( tor, completeness );
1726
1727        if( recentChange && tr_torrentIsSeed( tor ) )
1728        {
1729            tr_announcerTorrentCompleted( tor );
1730
1731            tor->doneDate = tor->anyDate = tr_time( );
1732        }
1733
1734        tr_torrentSetDirty( tor );
1735    }
1736
1737    tr_torrentUnlock( tor );
1738}
1739
1740/***
1741****
1742***/
1743
1744static void
1745tr_torrentFireMetadataCompleted( tr_torrent * tor )
1746{
1747    assert( tr_isTorrent( tor ) );
1748
1749    if( tor->metadata_func )
1750        tor->metadata_func( tor, tor->metadata_func_user_data );
1751}
1752
1753void
1754tr_torrentSetMetadataCallback( tr_torrent                * tor,
1755                               tr_torrent_metadata_func    func,
1756                               void                      * user_data )
1757{
1758    assert( tr_isTorrent( tor ) );
1759
1760    tor->metadata_func = func;
1761    tor->metadata_func_user_data = user_data;
1762}
1763
1764
1765/**
1766***  File priorities
1767**/
1768
1769void
1770tr_torrentInitFilePriority( tr_torrent *    tor,
1771                            tr_file_index_t fileIndex,
1772                            tr_priority_t   priority )
1773{
1774    tr_piece_index_t i;
1775    tr_file *        file;
1776
1777    assert( tr_isTorrent( tor ) );
1778    assert( fileIndex < tor->info.fileCount );
1779    assert( tr_isPriority( priority ) );
1780
1781    file = &tor->info.files[fileIndex];
1782    file->priority = priority;
1783    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1784        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1785}
1786
1787void
1788tr_torrentSetFilePriorities( tr_torrent *      tor,
1789                             tr_file_index_t * files,
1790                             tr_file_index_t   fileCount,
1791                             tr_priority_t     priority )
1792{
1793    tr_file_index_t i;
1794    assert( tr_isTorrent( tor ) );
1795    tr_torrentLock( tor );
1796
1797    for( i = 0; i < fileCount; ++i )
1798        if( files[i] < tor->info.fileCount )
1799            tr_torrentInitFilePriority( tor, files[i], priority );
1800    tr_torrentSetDirty( tor );
1801    tr_peerMgrRebuildRequests( tor );
1802
1803    tr_torrentUnlock( tor );
1804}
1805
1806tr_priority_t*
1807tr_torrentGetFilePriorities( const tr_torrent * tor )
1808{
1809    tr_file_index_t i;
1810    tr_priority_t * p;
1811
1812    assert( tr_isTorrent( tor ) );
1813
1814    tr_torrentLock( tor );
1815    p = tr_new0( tr_priority_t, tor->info.fileCount );
1816    for( i = 0; i < tor->info.fileCount; ++i )
1817        p[i] = tor->info.files[i].priority;
1818    tr_torrentUnlock( tor );
1819
1820    return p;
1821}
1822
1823/**
1824***  File DND
1825**/
1826
1827static void
1828setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1829{
1830    tr_file *        file;
1831    const int        dnd = !doDownload;
1832    tr_piece_index_t firstPiece, firstPieceDND;
1833    tr_piece_index_t lastPiece, lastPieceDND;
1834    tr_file_index_t  i;
1835
1836    assert( tr_isTorrent( tor ) );
1837
1838    file = &tor->info.files[fileIndex];
1839    file->dnd = dnd;
1840    firstPiece = file->firstPiece;
1841    lastPiece = file->lastPiece;
1842
1843    /* can't set the first piece to DND unless
1844       every file using that piece is DND */
1845    firstPieceDND = dnd;
1846    if( fileIndex > 0 )
1847    {
1848        for( i = fileIndex - 1; firstPieceDND; --i )
1849        {
1850            if( tor->info.files[i].lastPiece != firstPiece )
1851                break;
1852            firstPieceDND = tor->info.files[i].dnd;
1853            if( !i )
1854                break;
1855        }
1856    }
1857
1858    /* can't set the last piece to DND unless
1859       every file using that piece is DND */
1860    lastPieceDND = dnd;
1861    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1862    {
1863        if( tor->info.files[i].firstPiece != lastPiece )
1864            break;
1865        lastPieceDND = tor->info.files[i].dnd;
1866    }
1867
1868    if( firstPiece == lastPiece )
1869    {
1870        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1871    }
1872    else
1873    {
1874        tr_piece_index_t pp;
1875        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1876        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1877        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1878            tor->info.pieces[pp].dnd = dnd;
1879    }
1880}
1881
1882void
1883tr_torrentInitFileDLs( tr_torrent      * tor,
1884                       tr_file_index_t * files,
1885                       tr_file_index_t   fileCount,
1886                       tr_bool           doDownload )
1887{
1888    tr_file_index_t i;
1889
1890    assert( tr_isTorrent( tor ) );
1891
1892    tr_torrentLock( tor );
1893
1894    for( i=0; i<fileCount; ++i )
1895        if( files[i] < tor->info.fileCount )
1896            setFileDND( tor, files[i], doDownload );
1897
1898    tr_cpInvalidateDND( &tor->completion );
1899
1900    tr_torrentUnlock( tor );
1901}
1902
1903void
1904tr_torrentSetFileDLs( tr_torrent *      tor,
1905                      tr_file_index_t * files,
1906                      tr_file_index_t   fileCount,
1907                      tr_bool           doDownload )
1908{
1909    assert( tr_isTorrent( tor ) );
1910    tr_torrentLock( tor );
1911
1912    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1913    tr_torrentSetDirty( tor );
1914    tr_peerMgrRebuildRequests( tor );
1915
1916    tr_torrentUnlock( tor );
1917}
1918
1919/***
1920****
1921***/
1922
1923tr_priority_t
1924tr_torrentGetPriority( const tr_torrent * tor )
1925{
1926    assert( tr_isTorrent( tor ) );
1927
1928    return tor->bandwidth->priority;
1929}
1930
1931void
1932tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1933{
1934    assert( tr_isTorrent( tor ) );
1935    assert( tr_isPriority( priority ) );
1936
1937    if( tor->bandwidth->priority != priority )
1938    {
1939        tor->bandwidth->priority = priority;
1940
1941        tr_torrentSetDirty( tor );
1942    }
1943}
1944
1945/***
1946****
1947***/
1948
1949void
1950tr_torrentSetPeerLimit( tr_torrent * tor,
1951                        uint16_t     maxConnectedPeers )
1952{
1953    assert( tr_isTorrent( tor ) );
1954
1955    if ( tor->maxConnectedPeers != maxConnectedPeers )
1956    {
1957        tor->maxConnectedPeers = maxConnectedPeers;
1958
1959        tr_torrentSetDirty( tor );
1960    }
1961}
1962
1963uint16_t
1964tr_torrentGetPeerLimit( const tr_torrent * tor )
1965{
1966    assert( tr_isTorrent( tor ) );
1967
1968    return tor->maxConnectedPeers;
1969}
1970
1971/***
1972****
1973***/
1974
1975tr_block_index_t
1976_tr_block( const tr_torrent * tor,
1977           tr_piece_index_t   index,
1978           uint32_t           offset )
1979{
1980    tr_block_index_t ret;
1981
1982    assert( tr_isTorrent( tor ) );
1983
1984    ret = index;
1985    ret *= ( tor->info.pieceSize / tor->blockSize );
1986    ret += offset / tor->blockSize;
1987    return ret;
1988}
1989
1990tr_bool
1991tr_torrentReqIsValid( const tr_torrent * tor,
1992                      tr_piece_index_t   index,
1993                      uint32_t           offset,
1994                      uint32_t           length )
1995{
1996    int err = 0;
1997
1998    assert( tr_isTorrent( tor ) );
1999
2000    if( index >= tor->info.pieceCount )
2001        err = 1;
2002    else if( length < 1 )
2003        err = 2;
2004    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
2005        err = 3;
2006    else if( length > MAX_BLOCK_SIZE )
2007        err = 4;
2008    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
2009        err = 5;
2010
2011    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
2012                              (unsigned long)index,
2013                              (unsigned long)offset,
2014                              (unsigned long)length,
2015                              err );
2016
2017    return !err;
2018}
2019
2020uint64_t
2021tr_pieceOffset( const tr_torrent * tor,
2022                tr_piece_index_t   index,
2023                uint32_t           offset,
2024                uint32_t           length )
2025{
2026    uint64_t ret;
2027
2028    assert( tr_isTorrent( tor ) );
2029
2030    ret = tor->info.pieceSize;
2031    ret *= index;
2032    ret += offset;
2033    ret += length;
2034    return ret;
2035}
2036
2037/***
2038****
2039***/
2040
2041void
2042tr_torrentSetPieceChecked( tr_torrent        * tor,
2043                           tr_piece_index_t    piece,
2044                           tr_bool             isChecked )
2045{
2046    assert( tr_isTorrent( tor ) );
2047
2048    if( isChecked )
2049        tr_bitfieldAdd( &tor->checkedPieces, piece );
2050    else
2051        tr_bitfieldRem( &tor->checkedPieces, piece );
2052}
2053
2054void
2055tr_torrentSetFileChecked( tr_torrent *    tor,
2056                          tr_file_index_t fileIndex,
2057                          tr_bool         isChecked )
2058{
2059    const tr_file *        file = &tor->info.files[fileIndex];
2060    const tr_piece_index_t begin = file->firstPiece;
2061    const tr_piece_index_t end = file->lastPiece + 1;
2062
2063    assert( tr_isTorrent( tor ) );
2064
2065    if( isChecked )
2066        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
2067    else
2068        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
2069}
2070
2071tr_bool
2072tr_torrentIsFileChecked( const tr_torrent * tor,
2073                         tr_file_index_t    fileIndex )
2074{
2075    const tr_file *        file = &tor->info.files[fileIndex];
2076    const tr_piece_index_t begin = file->firstPiece;
2077    const tr_piece_index_t end = file->lastPiece + 1;
2078    tr_piece_index_t       i;
2079    tr_bool                isChecked = TRUE;
2080
2081    assert( tr_isTorrent( tor ) );
2082
2083    for( i = begin; isChecked && i < end; ++i )
2084        if( !tr_torrentIsPieceChecked( tor, i ) )
2085            isChecked = FALSE;
2086
2087    return isChecked;
2088}
2089
2090void
2091tr_torrentUncheck( tr_torrent * tor )
2092{
2093    assert( tr_isTorrent( tor ) );
2094
2095    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
2096}
2097
2098int
2099tr_torrentCountUncheckedPieces( const tr_torrent * tor )
2100{
2101    assert( tr_isTorrent( tor ) );
2102
2103    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
2104}
2105
2106time_t*
2107tr_torrentGetMTimes( const tr_torrent * tor, size_t * setme_n )
2108{
2109    size_t       i;
2110    const size_t n = tor->info.fileCount;
2111    time_t *     m = tr_new0( time_t, n );
2112
2113    assert( tr_isTorrent( tor ) );
2114
2115    for( i = 0; i < n; ++i )
2116    {
2117        struct stat sb;
2118        char * path = tr_torrentFindFile( tor, i );
2119        if( ( path != NULL ) && !stat( path, &sb ) && S_ISREG( sb.st_mode ) )
2120        {
2121#ifdef SYS_DARWIN
2122            m[i] = sb.st_mtimespec.tv_sec;
2123#else
2124            m[i] = sb.st_mtime;
2125#endif
2126        }
2127        tr_free( path );
2128    }
2129
2130    *setme_n = n;
2131    return m;
2132}
2133
2134/***
2135****
2136***/
2137
2138tr_bool
2139tr_torrentSetAnnounceList( tr_torrent             * tor,
2140                           const tr_tracker_info  * trackers,
2141                           int                      trackerCount )
2142{
2143    int i;
2144    tr_benc metainfo;
2145    tr_bool ok = TRUE;
2146    tr_torrentLock( tor );
2147
2148    assert( tr_isTorrent( tor ) );
2149
2150    /* look for bad URLs */
2151    for( i=0; ok && i<trackerCount; ++i )
2152        if( !tr_urlIsValidTracker( trackers[i].announce ) )
2153            ok = FALSE;
2154
2155    /* save to the .torrent file */
2156    if( ok && !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2157    {
2158        tr_bool hasInfo;
2159        tr_info tmpInfo;
2160
2161        /* remove the old fields */
2162        tr_bencDictRemove( &metainfo, "announce" );
2163        tr_bencDictRemove( &metainfo, "announce-list" );
2164
2165        /* add the new fields */
2166        if( trackerCount > 0 )
2167        {
2168            tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2169        }
2170        if( trackerCount > 1 )
2171        {
2172            int i;
2173            int prevTier = -1;
2174            tr_benc * tier = NULL;
2175            tr_benc * announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2176
2177            for( i=0; i<trackerCount; ++i ) {
2178                if( prevTier != trackers[i].tier ) {
2179                    prevTier = trackers[i].tier;
2180                    tier = tr_bencListAddList( announceList, 0 );
2181                }
2182                tr_bencListAddStr( tier, trackers[i].announce );
2183            }
2184        }
2185
2186        /* try to parse it back again, to make sure it's good */
2187        memset( &tmpInfo, 0, sizeof( tr_info ) );
2188        if( tr_metainfoParse( tor->session, &metainfo, &tmpInfo,
2189                              &hasInfo, &tor->infoDictOffset, &tor->infoDictLength ) )
2190        {
2191            /* it's good, so keep these new trackers and free the old ones */
2192
2193            tr_info swap;
2194            swap.trackers = tor->info.trackers;
2195            swap.trackerCount = tor->info.trackerCount;
2196            tor->info.trackers = tmpInfo.trackers;
2197            tor->info.trackerCount = tmpInfo.trackerCount;
2198            tmpInfo.trackers = swap.trackers;
2199            tmpInfo.trackerCount = swap.trackerCount;
2200
2201            tr_metainfoFree( &tmpInfo );
2202            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2203        }
2204
2205        /* cleanup */
2206        tr_bencFree( &metainfo );
2207
2208        /* tell the announcer to reload this torrent's tracker list */
2209        tr_announcerResetTorrent( tor->session->announcer, tor );
2210    }
2211
2212    tr_torrentUnlock( tor );
2213    return ok;
2214}
2215
2216/**
2217***
2218**/
2219
2220void
2221tr_torrentSetAddedDate( tr_torrent * tor,
2222                        time_t       t )
2223{
2224    assert( tr_isTorrent( tor ) );
2225
2226    tor->addedDate = t;
2227    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2228}
2229
2230void
2231tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2232{
2233    assert( tr_isTorrent( tor ) );
2234
2235    tor->activityDate = t;
2236    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2237}
2238
2239void
2240tr_torrentSetDoneDate( tr_torrent * tor,
2241                       time_t       t )
2242{
2243    assert( tr_isTorrent( tor ) );
2244
2245    tor->doneDate = t;
2246    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2247}
2248
2249/**
2250***
2251**/
2252
2253uint64_t
2254tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2255{
2256    tr_file_index_t i;
2257    uint64_t bytesLeft = 0;
2258
2259    assert( tr_isTorrent( tor ) );
2260
2261    for( i=0; i<tor->info.fileCount; ++i )
2262    {
2263        if( !tor->info.files[i].dnd )
2264        {
2265            struct stat sb;
2266            const uint64_t length = tor->info.files[i].length;
2267            char * path = tr_torrentFindFile( tor, i );
2268
2269            bytesLeft += length;
2270
2271            if( ( path != NULL ) && !stat( path, &sb )
2272                                 && S_ISREG( sb.st_mode )
2273                                 && ( (uint64_t)sb.st_size <= length ) )
2274                bytesLeft -= sb.st_size;
2275
2276            tr_free( path );
2277        }
2278    }
2279
2280    return bytesLeft;
2281}
2282
2283/****
2284*****  Removing the torrent's local data
2285****/
2286
2287static int
2288vstrcmp( const void * a, const void * b )
2289{
2290    return strcmp( a, b );
2291}
2292
2293static int
2294compareLongestFirst( const void * a, const void * b )
2295{
2296    const size_t alen = strlen( a );
2297    const size_t blen = strlen( b );
2298
2299    if( alen != blen )
2300        return alen > blen ? -1 : 1;
2301
2302    return vstrcmp( a, b );
2303}
2304
2305static void
2306addDirtyFile( const char  * root,
2307              const char  * filename,
2308              tr_ptrArray * dirtyFolders )
2309{
2310    char * dir = tr_dirname( filename );
2311
2312    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2313    while (     ( dir != NULL )
2314             && ( strlen( root ) <= strlen( dir ) )
2315             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2316    {
2317        char * tmp;
2318        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2319
2320        tmp = tr_dirname( dir );
2321        tr_free( dir );
2322        dir = tmp;
2323    }
2324
2325    tr_free( dir );
2326}
2327
2328static void
2329walkLocalData( const tr_torrent * tor,
2330               const char       * root,
2331               const char       * dir,
2332               const char       * base,
2333               tr_ptrArray      * torrentFiles,
2334               tr_ptrArray      * folders,
2335               tr_ptrArray      * dirtyFolders )
2336{
2337    int i;
2338    struct stat sb;
2339    char * buf;
2340
2341    assert( tr_isTorrent( tor ) );
2342
2343    buf = tr_buildPath( dir, base, NULL );
2344    i = stat( buf, &sb );
2345    if( !i )
2346    {
2347        DIR * odir = NULL;
2348
2349        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2350        {
2351            struct dirent *d;
2352            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2353            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2354                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2355                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2356            closedir( odir );
2357        }
2358        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2359        {
2360            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2361            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2362            if( !isTorrentFile )
2363                addDirtyFile( root, buf, dirtyFolders );
2364        }
2365    }
2366
2367    tr_free( buf );
2368}
2369
2370static void
2371deleteLocalFile( const char * filename, tr_fileFunc fileFunc )
2372{
2373    struct stat sb;
2374    if( !stat( filename, &sb ) ) /* if file exists... */
2375        fileFunc( filename );
2376}
2377
2378static void
2379deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2380{
2381    int i, n;
2382    char ** s;
2383    tr_file_index_t f;
2384    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2385    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2386    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2387
2388    const char * firstFile = tor->info.files[0].name;
2389    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2390    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2391    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2392
2393    assert( tr_isTorrent( tor ) );
2394
2395    for( f=0; f<tor->info.fileCount; ++f ) {
2396        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2397        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2398    }
2399
2400    /* build the set of folders and dirtyFolders */
2401    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2402
2403    /* try to remove entire folders first, so that the recycle bin will be tidy */
2404    s = (char**) tr_ptrArrayPeek( &folders, &n );
2405    for( i=0; i<n; ++i )
2406        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2407            deleteLocalFile( s[i], fileFunc );
2408
2409    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2410    for( i=0, n=tr_ptrArraySize( &torrentFiles ); i<n; ++i ) {
2411        char * path = tr_buildPath( tor->currentDir, tr_ptrArrayNth( &torrentFiles, i ), NULL );
2412        deleteLocalFile( path, fileFunc );
2413        tr_free( path );
2414    }
2415
2416    /* Now clean out the directories left empty from the previous step.
2417     * Work from deepest to shallowest s.t. lower folders
2418     * won't prevent the upper folders from being deleted */
2419    {
2420        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2421        s = (char**) tr_ptrArrayPeek( &folders, &n );
2422        for( i=0; i<n; ++i )
2423            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2424                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2425        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2426        for( i=0; i<n; ++i ) {
2427#ifdef SYS_DARWIN
2428            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2429            deleteLocalFile( dsStore, fileFunc );
2430            tr_free( dsStore );
2431#endif
2432            deleteLocalFile( s[i], fileFunc );
2433        }
2434        tr_ptrArrayDestruct( &cleanFolders, NULL );
2435    }
2436
2437    /* cleanup */
2438    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2439    tr_ptrArrayDestruct( &folders, tr_free );
2440    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2441    tr_free( root );
2442    tr_free( tmp );
2443}
2444
2445void
2446tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2447{
2448    assert( tr_isTorrent( tor ) );
2449
2450    if( fileFunc == NULL )
2451        fileFunc = remove;
2452
2453    /* close all the files because we're about to delete them */
2454    tr_fdTorrentClose( tor->session, tor->uniqueId );
2455
2456    if( tor->info.fileCount > 1 )
2457    {
2458        deleteLocalData( tor, fileFunc );
2459    }
2460    else if( tor->info.fileCount == 1 )
2461    {
2462        char * tmp;
2463
2464        /* torrent only has one file */
2465        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2466        deleteLocalFile( path, fileFunc );
2467        tr_free( path );
2468
2469        tmp = tr_torrentBuildPartial( tor, 0 );
2470        path = tr_buildPath( tor->currentDir, tmp, NULL );
2471        deleteLocalFile( path, fileFunc );
2472        tr_free( path );
2473        tr_free( tmp );
2474    }
2475}
2476
2477/***
2478****
2479***/
2480
2481struct LocationData
2482{
2483    tr_bool move_from_old_location;
2484    int * setme_state;
2485    double * setme_progress;
2486    char * location;
2487    tr_torrent * tor;
2488};
2489
2490static tr_bool
2491sameInode( const char * path1, const char * path2 )
2492{
2493    int i1, i2;
2494    struct stat s1, s2;
2495
2496    s1.st_ino = 1;
2497    i1 = stat( path1, &s1 );
2498
2499    s2.st_ino = 2;
2500    i2 = stat( path2, &s2 );
2501
2502    if( !i1 && !i2 ) {
2503        tr_dbg( "path1 inode is %"PRIu64"; path2 inode is %"PRIu64,
2504                (uint64_t)s1.st_ino,
2505                (uint64_t)s2.st_ino );
2506        return s1.st_ino == s2.st_ino;
2507    }
2508
2509    /* either one, or the other, or both don't exist... */
2510    tr_dbg( "stat(%s) returned %d\n", path1, i1 );
2511    tr_dbg( "stat(%s) returned %d\n", path2, i2 );
2512    return FALSE;
2513}
2514
2515static void
2516setLocation( void * vdata )
2517{
2518    tr_bool err = FALSE;
2519    tr_bool verify_needed = FALSE;
2520    struct LocationData * data = vdata;
2521    tr_torrent * tor = data->tor;
2522    const tr_bool do_move = data->move_from_old_location;
2523    const char * location = data->location;
2524    double bytesHandled = 0;
2525
2526    assert( tr_isTorrent( tor ) );
2527
2528    tr_dbg( "Moving \"%s\" location from currentDir \"%s\" to \"%s\"",
2529            tr_torrentName(tor), tor->currentDir, location );
2530
2531    tr_mkdirp( location, 0777 );
2532
2533    if( !sameInode( location, tor->currentDir ) )
2534    {
2535        tr_file_index_t i;
2536
2537        /* bad idea to move files while they're being verified... */
2538        tr_verifyRemove( tor );
2539
2540        /* if the torrent is running, stop it and set a flag to
2541         * restart after we're done */
2542        if( tor->isRunning )
2543        {
2544            tr_torrentStop( tor );
2545            tor->startAfterVerify = TRUE;
2546        }
2547
2548        /* try to move the files.
2549         * FIXME: there are still all kinds of nasty cases, like what
2550         * if the target directory runs out of space halfway through... */
2551        for( i=0; !err && i<tor->info.fileCount; ++i )
2552        {
2553            const tr_file * f = &tor->info.files[i];
2554            const char * oldbase;
2555            char * sub;
2556            if( tr_torrentFindFile2( tor, i, &oldbase, &sub ) )
2557            {
2558                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2559                char * newpath = tr_buildPath( location, sub, NULL );
2560
2561                tr_dbg( "Found file #%d: %s", (int)i, oldpath );
2562
2563                if( do_move )
2564                {
2565                    tr_bool renamed = FALSE;
2566                    errno = 0;
2567                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2568                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2569                    {
2570                        err = TRUE;
2571                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2572                                        oldpath, newpath, tr_strerror( errno ) );
2573                    }
2574                    else if( !renamed )
2575                    {
2576                        verify_needed = TRUE;
2577                    }
2578                }
2579
2580                tr_free( newpath );
2581                tr_free( oldpath );
2582                tr_free( sub );
2583            }
2584
2585            if( data->setme_progress )
2586            {
2587                bytesHandled += f->length;
2588                *data->setme_progress = bytesHandled / tor->info.totalSize;
2589            }
2590        }
2591
2592        if( !err )
2593        {
2594            /* blow away the leftover subdirectories in the old location */
2595            if( do_move )
2596                tr_torrentDeleteLocalData( tor, remove );
2597
2598            /* set the new location and reverify */
2599            tr_torrentSetDownloadDir( tor, location );
2600            if( verify_needed )
2601                tr_torrentVerify( tor );
2602            else if( tor->startAfterVerify ) {
2603                tor->startAfterVerify = FALSE;
2604                tr_torrentStart( tor );
2605            }
2606        }
2607    }
2608
2609    if( !err && do_move )
2610    {
2611        tr_free( tor->incompleteDir );
2612        tor->incompleteDir = NULL;
2613        tor->currentDir = tor->downloadDir;
2614    }
2615
2616    if( data->setme_state )
2617        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2618
2619    /* cleanup */
2620    tr_free( data->location );
2621    tr_free( data );
2622}
2623
2624void
2625tr_torrentSetLocation( tr_torrent  * tor,
2626                       const char  * location,
2627                       tr_bool       move_from_old_location,
2628                       double      * setme_progress,
2629                       int         * setme_state )
2630{
2631    struct LocationData * data;
2632
2633    assert( tr_isTorrent( tor ) );
2634
2635    if( setme_state )
2636        *setme_state = TR_LOC_MOVING;
2637    if( setme_progress )
2638        *setme_progress = 0;
2639
2640    /* run this in the libtransmission thread */
2641    data = tr_new( struct LocationData, 1 );
2642    data->tor = tor;
2643    data->location = tr_strdup( location );
2644    data->move_from_old_location = move_from_old_location;
2645    data->setme_state = setme_state;
2646    data->setme_progress = setme_progress;
2647    tr_runInEventThread( tor->session, setLocation, data );
2648}
2649
2650/***
2651****
2652***/
2653
2654void
2655tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2656{
2657    char * sub;
2658    const char * base;
2659
2660    /* close the file so that we can reopen in read-only mode as needed */
2661    tr_fdFileClose( tor->session, tor, fileNum );
2662
2663    /* if the torrent's current filename isn't the same as the one in the
2664     * metadata -- for example, if it had the ".part" suffix appended to
2665     * it until now -- then rename it to match the one in the metadata */
2666    if( tr_torrentFindFile2( tor, fileNum, &base, &sub ) )
2667    {
2668        const tr_file * file = &tor->info.files[fileNum];
2669
2670        if( strcmp( sub, file->name ) )
2671        {
2672            char * oldpath = tr_buildPath( base, sub, NULL );
2673            char * newpath = tr_buildPath( base, file->name, NULL );
2674
2675            if( rename( oldpath, newpath ) )
2676                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2677
2678            tr_free( newpath );
2679            tr_free( oldpath );
2680        }
2681
2682        tr_free( sub );
2683    }
2684}
2685
2686/***
2687****
2688***/
2689
2690static tr_bool
2691fileExists( const char * filename )
2692{
2693    struct stat sb;
2694    const tr_bool ok = !stat( filename, &sb );
2695    return ok;
2696}
2697
2698tr_bool
2699tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
2700                     const char ** base, char ** subpath )
2701{
2702    char * part;
2703    const tr_file * file;
2704    const char * b = NULL;
2705    const char * s = NULL;
2706
2707    assert( tr_isTorrent( tor ) );
2708    assert( fileNum < tor->info.fileCount );
2709
2710    file = &tor->info.files[fileNum];
2711    part = tr_torrentBuildPartial( tor, fileNum );
2712
2713    if( b == NULL ) {
2714        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
2715        if( fileExists( filename ) ) {
2716            b = tor->downloadDir;
2717            s = file->name;
2718        }
2719        tr_free( filename );
2720    }
2721
2722    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2723        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
2724        if( fileExists( filename ) ) {
2725            b = tor->incompleteDir;
2726            s = file->name;
2727        }
2728        tr_free( filename );
2729    }
2730
2731    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2732        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
2733        if( fileExists( filename ) ) {
2734            b = tor->incompleteDir;
2735            s = part;
2736        }
2737        tr_free( filename );
2738    }
2739
2740    if( b == NULL) {
2741        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
2742        if( fileExists( filename ) ) {
2743            b = tor->downloadDir;
2744            s = part;
2745        }
2746        tr_free( filename );
2747    }
2748
2749    if( base != NULL )
2750        *base = b;
2751    if( subpath != NULL )
2752        *subpath = tr_strdup( s );
2753
2754    tr_free( part );
2755    return b != NULL;
2756}
2757
2758char*
2759tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
2760{
2761    char * subpath;
2762    char * ret = NULL;
2763    const char * base;
2764
2765    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath ) )
2766    {
2767        ret = tr_buildPath( base, subpath, NULL );
2768        tr_free( subpath );
2769    }
2770
2771    return ret;
2772}
2773
2774/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
2775static void
2776refreshCurrentDir( tr_torrent * tor )
2777{
2778    const char * dir = NULL;
2779    char * sub;
2780
2781    if( tor->incompleteDir == NULL )
2782        dir = tor->downloadDir;
2783    else if( !tr_torrentHasMetadata( tor ) ) /* no files to find */
2784        dir = tor->incompleteDir;
2785    else if( !tr_torrentFindFile2( tor, 0, &dir, &sub ) )
2786        dir = tor->incompleteDir;
2787
2788    assert( dir != NULL );
2789    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
2790    tor->currentDir = dir;
2791}
2792
2793char*
2794tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
2795{
2796    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
2797}
Note: See TracBrowser for help on using the repository browser.