source: trunk/libtransmission/torrent.c @ 9975

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

(trunk libT) still too wordy

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