source: trunk/libtransmission/torrent.c @ 10174

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

(trunk) #2894 "tr_torrentGetFileDL() and tr_torrentGetFilePriority() should go away" -- get rid of it in the mac client and libtransmission too

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