source: trunk/libtransmission/torrent.c @ 9863

Last change on this file since 9863 was 9863, checked in by charles, 6 years ago

(trunk libT) remove dead code: tr_announce_list_err

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