source: trunk/libtransmission/torrent.c @ 10479

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

(trunk libT) in seedRatio, handle the case where a file is downloaded more than once

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