source: trunk/libtransmission/torrent.c @ 10347

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

(trunk libT) code cleanup: after r10346, we don't need to keep the per-torrent cancel/block histories anymore

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