source: trunk/libtransmission/torrent.c @ 9974

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

(trunk libT) #2676 "Transmission writes to non-existent drive in '/Volumes'" -- we're already stopping the torrent when the local data disappears, but let's add a more explicit and helpful error message to help users diagnoses the problem.

  • Property svn:keywords set to Date Rev Author Id
File size: 71.5 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 9974 2010-01-20 20:08:12Z 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_torrentStop( tor );
1324    }
1325    else
1326    {
1327        const time_t now = tr_time( );
1328        tor->isRunning = TRUE;
1329        tor->needsSeedRatioCheck = TRUE;
1330        tor->error = TR_STAT_OK;
1331        tor->errorString[0] = '\0';
1332        tor->completeness = tr_cpGetStatus( &tor->completion );
1333        tor->startDate = tor->anyDate = now;
1334
1335        tr_torrentResetTransferStats( tor );
1336        tr_announcerTorrentStarted( tor );
1337        tor->dhtAnnounceAt = now + tr_cryptoWeakRandInt( 20 );
1338        tor->dhtAnnounce6At = now + tr_cryptoWeakRandInt( 20 );
1339        tr_peerMgrStartTorrent( tor );
1340    }
1341
1342    tr_sessionUnlock( tor->session );
1343}
1344
1345static void
1346checkAndStartCB( tr_torrent * tor )
1347{
1348    assert( tr_isTorrent( tor ) );
1349    assert( tr_isSession( tor->session ) );
1350
1351    tr_runInEventThread( tor->session, checkAndStartImpl, tor );
1352}
1353
1354static void
1355torrentStart( tr_torrent * tor )
1356{
1357    assert( tr_isTorrent( tor ) );
1358
1359    tr_sessionLock( tor->session );
1360
1361    if( !tor->isRunning )
1362    {
1363        tr_verifyRemove( tor );
1364
1365        /* corresponds to the peer_id sent as a tracker request parameter.
1366         * one tracker admin says: "When the same torrent is opened and
1367         * closed and opened again without quitting Transmission ...
1368         * change the peerid. It would help sometimes if a stopped event
1369         * was missed to ensure that we didn't think someone was cheating. */
1370        tr_free( tor->peer_id );
1371        tor->peer_id = tr_peerIdNew( );
1372
1373        tor->isRunning = 1;
1374        tr_torrentSetDirty( tor );
1375        tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1376        tr_verifyAdd( tor, checkAndStartCB );
1377    }
1378
1379    tr_sessionUnlock( tor->session );
1380}
1381
1382void
1383tr_torrentStart( tr_torrent * tor )
1384{
1385    if( tr_isTorrent( tor ) )
1386        torrentStart( tor );
1387}
1388
1389static void
1390torrentRecheckDoneImpl( void * vtor )
1391{
1392    tr_torrent * tor = vtor;
1393
1394    assert( tr_isTorrent( tor ) );
1395    tr_torrentRecheckCompleteness( tor );
1396
1397    if( tor->preVerifyTotal && !tr_cpHaveTotal( &tor->completion ) )
1398    {
1399        tr_torrentSetLocalError( tor, _( "Can't find local data.  Try \"Set Location\" to find it, or restart the torrent to re-download." ) );
1400        tr_torrentStop( tor );
1401    }
1402    else if( tor->startAfterVerify )
1403    {
1404        tor->startAfterVerify = FALSE;
1405
1406        tr_torrentStart( tor );
1407    }
1408}
1409
1410static void
1411torrentRecheckDoneCB( tr_torrent * tor )
1412{
1413    assert( tr_isTorrent( tor ) );
1414
1415    tr_runInEventThread( tor->session, torrentRecheckDoneImpl, tor );
1416}
1417
1418static void
1419verifyTorrent( void * vtor )
1420{
1421    tr_torrent * tor = vtor;
1422
1423    assert( tr_isTorrent( tor ) );
1424    tr_sessionLock( tor->session );
1425
1426    /* if the torrent's already being verified, stop it */
1427    tr_verifyRemove( tor );
1428
1429    /* if the torrent's running, stop it & set the restart-after-verify flag */
1430    if( tor->startAfterVerify || tor->isRunning ) {
1431        tr_torrentStop( tor );
1432        tor->startAfterVerify = TRUE;
1433    }
1434
1435    /* add the torrent to the recheck queue */
1436    tor->preVerifyTotal = tr_cpHaveTotal( &tor->completion );
1437    tr_torrentUncheck( tor );
1438    tr_verifyAdd( tor, torrentRecheckDoneCB );
1439
1440    tr_sessionUnlock( tor->session );
1441}
1442
1443void
1444tr_torrentVerify( tr_torrent * tor )
1445{
1446    if( tr_isTorrent( tor ) )
1447        tr_runInEventThread( tor->session, verifyTorrent, tor );
1448}
1449
1450void
1451tr_torrentSave( tr_torrent * tor )
1452{
1453    assert( tr_isTorrent( tor ) );
1454
1455    if( tor->isDirty && tr_torrentHasMetadata( tor ) )
1456    {
1457        tor->isDirty = FALSE;
1458        tr_torrentSaveResume( tor );
1459    }
1460}
1461
1462static void
1463stopTorrent( void * vtor )
1464{
1465    tr_torrent * tor = vtor;
1466
1467    assert( tr_isTorrent( tor ) );
1468
1469    tr_verifyRemove( tor );
1470    tr_peerMgrStopTorrent( tor );
1471    tr_announcerTorrentStopped( tor );
1472
1473    tr_fdTorrentClose( tor->session, tor->uniqueId );
1474
1475    if( !tor->isDeleting )
1476        tr_torrentSave( tor );
1477}
1478
1479void
1480tr_torrentStop( tr_torrent * tor )
1481{
1482    assert( tr_isTorrent( tor ) );
1483
1484    if( tr_isTorrent( tor ) )
1485    {
1486        tr_sessionLock( tor->session );
1487
1488        tor->isRunning = 0;
1489        tr_torrentSetDirty( tor );
1490        tr_runInEventThread( tor->session, stopTorrent, tor );
1491
1492        tr_sessionUnlock( tor->session );
1493    }
1494}
1495
1496static void
1497closeTorrent( void * vtor )
1498{
1499    tr_benc * d;
1500    tr_torrent * tor = vtor;
1501
1502    assert( tr_isTorrent( tor ) );
1503
1504    d = tr_bencListAddDict( &tor->session->removedTorrents, 2 );
1505    tr_bencDictAddInt( d, "id", tor->uniqueId );
1506    tr_bencDictAddInt( d, "date", tr_time( ) );
1507
1508    stopTorrent( tor );
1509
1510    if( tor->isDeleting )
1511    {
1512        tr_metainfoRemoveSaved( tor->session, &tor->info );
1513        tr_torrentRemoveResume( tor );
1514    }
1515
1516    tor->isRunning = 0;
1517    freeTorrent( tor );
1518}
1519
1520void
1521tr_torrentFree( tr_torrent * tor )
1522{
1523    if( tr_isTorrent( tor ) )
1524    {
1525        tr_session * session = tor->session;
1526        assert( tr_isSession( session ) );
1527        tr_sessionLock( session );
1528
1529        tr_torrentClearCompletenessCallback( tor );
1530        tr_runInEventThread( session, closeTorrent, tor );
1531
1532        tr_sessionUnlock( session );
1533    }
1534}
1535
1536void
1537tr_torrentRemove( tr_torrent * tor )
1538{
1539    assert( tr_isTorrent( tor ) );
1540
1541    tor->isDeleting = 1;
1542    tr_torrentFree( tor );
1543}
1544
1545/**
1546***  Completeness
1547**/
1548
1549static const char *
1550getCompletionString( int type )
1551{
1552    switch( type )
1553    {
1554        /* Translators: this is a minor point that's safe to skip over, but FYI:
1555           "Complete" and "Done" are specific, different terms in Transmission:
1556           "Complete" means we've downloaded every file in the torrent.
1557           "Done" means we're done downloading the files we wanted, but NOT all
1558           that exist */
1559        case TR_PARTIAL_SEED:
1560            return _( "Done" );
1561
1562        case TR_SEED:
1563            return _( "Complete" );
1564
1565        default:
1566            return _( "Incomplete" );
1567    }
1568}
1569
1570static void
1571fireCompletenessChange( tr_torrent       * tor,
1572                        tr_completeness    status )
1573{
1574    assert( tr_isTorrent( tor ) );
1575    assert( ( status == TR_LEECH )
1576         || ( status == TR_SEED )
1577         || ( status == TR_PARTIAL_SEED ) );
1578
1579    if( tor->completeness_func )
1580        tor->completeness_func( tor, status, tor->completeness_func_user_data );
1581}
1582
1583void
1584tr_torrentSetCompletenessCallback( tr_torrent                    * tor,
1585                                   tr_torrent_completeness_func    func,
1586                                   void                          * user_data )
1587{
1588    assert( tr_isTorrent( tor ) );
1589
1590    tor->completeness_func = func;
1591    tor->completeness_func_user_data = user_data;
1592}
1593
1594void
1595tr_torrentClearCompletenessCallback( tr_torrent * torrent )
1596{
1597    tr_torrentSetCompletenessCallback( torrent, NULL, NULL );
1598}
1599
1600void
1601tr_torrentSetRatioLimitHitCallback( tr_torrent                     * tor,
1602                                    tr_torrent_ratio_limit_hit_func  func,
1603                                    void                           * user_data )
1604{
1605    assert( tr_isTorrent( tor ) );
1606
1607    tor->ratio_limit_hit_func = func;
1608    tor->ratio_limit_hit_func_user_data = user_data;
1609}
1610
1611void
1612tr_torrentClearRatioLimitHitCallback( tr_torrent * torrent )
1613{
1614    tr_torrentSetRatioLimitHitCallback( torrent, NULL, NULL );
1615}
1616
1617void
1618tr_torrentRecheckCompleteness( tr_torrent * tor )
1619{
1620    tr_completeness completeness;
1621
1622    assert( tr_isTorrent( tor ) );
1623
1624    tr_torrentLock( tor );
1625
1626    completeness = tr_cpGetStatus( &tor->completion );
1627
1628    if( completeness != tor->completeness )
1629    {
1630        const int recentChange = tor->downloadedCur != 0;
1631
1632        if( recentChange )
1633        {
1634            tr_torinf( tor, _( "State changed from \"%1$s\" to \"%2$s\"" ),
1635                      getCompletionString( tor->completeness ),
1636                      getCompletionString( completeness ) );
1637        }
1638
1639        tor->completeness = completeness;
1640        tor->needsSeedRatioCheck = TRUE;
1641        tr_fdTorrentClose( tor->session, tor->uniqueId );
1642
1643        /* if the torrent is a seed now,
1644         * and the files used to be in the incompleteDir,
1645         * then move them to the destination directory */
1646        if( tr_torrentIsSeed( tor ) && ( tor->currentDir == tor->incompleteDir ) )
1647            tr_torrentSetLocation( tor, tor->downloadDir, TRUE, NULL, NULL );
1648
1649        fireCompletenessChange( tor, completeness );
1650
1651        if( recentChange && ( completeness == TR_SEED ) )
1652        {
1653            tr_announcerTorrentCompleted( tor );
1654
1655            tor->doneDate = tor->anyDate = tr_time( );
1656        }
1657
1658        tr_torrentSetDirty( tor );
1659    }
1660
1661    tr_torrentUnlock( tor );
1662}
1663
1664/***
1665****
1666***/
1667
1668static void
1669tr_torrentFireMetadataCompleted( tr_torrent * tor )
1670{
1671    assert( tr_isTorrent( tor ) );
1672
1673    if( tor->metadata_func )
1674        tor->metadata_func( tor, tor->metadata_func_user_data );
1675}
1676
1677void
1678tr_torrentSetMetadataCallback( tr_torrent                * tor,
1679                               tr_torrent_metadata_func    func,
1680                               void                      * user_data )
1681{
1682    assert( tr_isTorrent( tor ) );
1683
1684    tor->metadata_func = func;
1685    tor->metadata_func_user_data = user_data;
1686}
1687
1688
1689/**
1690***  File priorities
1691**/
1692
1693void
1694tr_torrentInitFilePriority( tr_torrent *    tor,
1695                            tr_file_index_t fileIndex,
1696                            tr_priority_t   priority )
1697{
1698    tr_piece_index_t i;
1699    tr_file *        file;
1700
1701    assert( tr_isTorrent( tor ) );
1702    assert( fileIndex < tor->info.fileCount );
1703    assert( tr_isPriority( priority ) );
1704
1705    file = &tor->info.files[fileIndex];
1706    file->priority = priority;
1707    for( i = file->firstPiece; i <= file->lastPiece; ++i )
1708        tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1709}
1710
1711void
1712tr_torrentSetFilePriorities( tr_torrent *      tor,
1713                             tr_file_index_t * files,
1714                             tr_file_index_t   fileCount,
1715                             tr_priority_t     priority )
1716{
1717    tr_file_index_t i;
1718    assert( tr_isTorrent( tor ) );
1719    tr_torrentLock( tor );
1720
1721    for( i = 0; i < fileCount; ++i )
1722        if( files[i] < tor->info.fileCount )
1723            tr_torrentInitFilePriority( tor, files[i], priority );
1724    tr_torrentSetDirty( tor );
1725    tr_peerMgrRebuildRequests( tor );
1726
1727    tr_torrentUnlock( tor );
1728}
1729
1730tr_priority_t
1731tr_torrentGetFilePriority( const tr_torrent * tor,
1732                           tr_file_index_t    file )
1733{
1734    tr_priority_t ret;
1735
1736    assert( tr_isTorrent( tor ) );
1737
1738    tr_torrentLock( tor );
1739    assert( tor );
1740    assert( file < tor->info.fileCount );
1741    ret = tor->info.files[file].priority;
1742    tr_torrentUnlock( tor );
1743
1744    return ret;
1745}
1746
1747tr_priority_t*
1748tr_torrentGetFilePriorities( const tr_torrent * tor )
1749{
1750    tr_file_index_t i;
1751    tr_priority_t * p;
1752
1753    assert( tr_isTorrent( tor ) );
1754
1755    tr_torrentLock( tor );
1756    p = tr_new0( tr_priority_t, tor->info.fileCount );
1757    for( i = 0; i < tor->info.fileCount; ++i )
1758        p[i] = tor->info.files[i].priority;
1759    tr_torrentUnlock( tor );
1760
1761    return p;
1762}
1763
1764/**
1765***  File DND
1766**/
1767
1768int
1769tr_torrentGetFileDL( const tr_torrent * tor,
1770                     tr_file_index_t    file )
1771{
1772    int doDownload;
1773
1774    assert( tr_isTorrent( tor ) );
1775
1776    tr_torrentLock( tor );
1777
1778    assert( file < tor->info.fileCount );
1779    doDownload = !tor->info.files[file].dnd;
1780
1781    tr_torrentUnlock( tor );
1782    return doDownload != 0;
1783}
1784
1785static void
1786setFileDND( tr_torrent * tor, tr_file_index_t fileIndex, int doDownload )
1787{
1788    tr_file *        file;
1789    const int        dnd = !doDownload;
1790    tr_piece_index_t firstPiece, firstPieceDND;
1791    tr_piece_index_t lastPiece, lastPieceDND;
1792    tr_file_index_t  i;
1793
1794    assert( tr_isTorrent( tor ) );
1795
1796    file = &tor->info.files[fileIndex];
1797    file->dnd = dnd;
1798    firstPiece = file->firstPiece;
1799    lastPiece = file->lastPiece;
1800
1801    /* can't set the first piece to DND unless
1802       every file using that piece is DND */
1803    firstPieceDND = dnd;
1804    if( fileIndex > 0 )
1805    {
1806        for( i = fileIndex - 1; firstPieceDND; --i )
1807        {
1808            if( tor->info.files[i].lastPiece != firstPiece )
1809                break;
1810            firstPieceDND = tor->info.files[i].dnd;
1811            if( !i )
1812                break;
1813        }
1814    }
1815
1816    /* can't set the last piece to DND unless
1817       every file using that piece is DND */
1818    lastPieceDND = dnd;
1819    for( i = fileIndex + 1; lastPieceDND && i < tor->info.fileCount; ++i )
1820    {
1821        if( tor->info.files[i].firstPiece != lastPiece )
1822            break;
1823        lastPieceDND = tor->info.files[i].dnd;
1824    }
1825
1826    if( firstPiece == lastPiece )
1827    {
1828        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1829    }
1830    else
1831    {
1832        tr_piece_index_t pp;
1833        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1834        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1835        for( pp = firstPiece + 1; pp < lastPiece; ++pp )
1836            tor->info.pieces[pp].dnd = dnd;
1837    }
1838}
1839
1840void
1841tr_torrentInitFileDLs( tr_torrent      * tor,
1842                       tr_file_index_t * files,
1843                       tr_file_index_t   fileCount,
1844                       tr_bool           doDownload )
1845{
1846    tr_file_index_t i;
1847
1848    assert( tr_isTorrent( tor ) );
1849
1850    tr_torrentLock( tor );
1851
1852    for( i=0; i<fileCount; ++i )
1853        if( files[i] < tor->info.fileCount )
1854            setFileDND( tor, files[i], doDownload );
1855
1856    tr_cpInvalidateDND( &tor->completion );
1857    tor->needsSeedRatioCheck = TRUE;
1858
1859    tr_torrentUnlock( tor );
1860}
1861
1862void
1863tr_torrentSetFileDLs( tr_torrent *      tor,
1864                      tr_file_index_t * files,
1865                      tr_file_index_t   fileCount,
1866                      tr_bool           doDownload )
1867{
1868    assert( tr_isTorrent( tor ) );
1869    tr_torrentLock( tor );
1870
1871    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1872    tr_torrentSetDirty( tor );
1873    tr_peerMgrRebuildRequests( tor );
1874
1875    tr_torrentUnlock( tor );
1876}
1877
1878/***
1879****
1880***/
1881
1882tr_priority_t
1883tr_torrentGetPriority( const tr_torrent * tor )
1884{
1885    assert( tr_isTorrent( tor ) );
1886
1887    return tor->bandwidth->priority;
1888}
1889
1890void
1891tr_torrentSetPriority( tr_torrent * tor, tr_priority_t priority )
1892{
1893    assert( tr_isTorrent( tor ) );
1894    assert( tr_isPriority( priority ) );
1895
1896    if( tor->bandwidth->priority != priority )
1897    {
1898        tor->bandwidth->priority = priority;
1899
1900        tr_torrentSetDirty( tor );
1901    }
1902}
1903
1904/***
1905****
1906***/
1907
1908void
1909tr_torrentSetPeerLimit( tr_torrent * tor,
1910                        uint16_t     maxConnectedPeers )
1911{
1912    assert( tr_isTorrent( tor ) );
1913
1914    if ( tor->maxConnectedPeers != maxConnectedPeers )
1915    {
1916        tor->maxConnectedPeers = maxConnectedPeers;
1917
1918        tr_torrentSetDirty( tor );
1919    }
1920}
1921
1922uint16_t
1923tr_torrentGetPeerLimit( const tr_torrent * tor )
1924{
1925    assert( tr_isTorrent( tor ) );
1926
1927    return tor->maxConnectedPeers;
1928}
1929
1930/***
1931****
1932***/
1933
1934tr_block_index_t
1935_tr_block( const tr_torrent * tor,
1936           tr_piece_index_t   index,
1937           uint32_t           offset )
1938{
1939    tr_block_index_t ret;
1940
1941    assert( tr_isTorrent( tor ) );
1942
1943    ret = index;
1944    ret *= ( tor->info.pieceSize / tor->blockSize );
1945    ret += offset / tor->blockSize;
1946    return ret;
1947}
1948
1949tr_bool
1950tr_torrentReqIsValid( const tr_torrent * tor,
1951                      tr_piece_index_t   index,
1952                      uint32_t           offset,
1953                      uint32_t           length )
1954{
1955    int err = 0;
1956
1957    assert( tr_isTorrent( tor ) );
1958
1959    if( index >= tor->info.pieceCount )
1960        err = 1;
1961    else if( length < 1 )
1962        err = 2;
1963    else if( ( offset + length ) > tr_torPieceCountBytes( tor, index ) )
1964        err = 3;
1965    else if( length > MAX_BLOCK_SIZE )
1966        err = 4;
1967    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1968        err = 5;
1969
1970    if( err ) tr_tordbg( tor, "index %lu offset %lu length %lu err %d\n",
1971                              (unsigned long)index,
1972                              (unsigned long)offset,
1973                              (unsigned long)length,
1974                              err );
1975
1976    return !err;
1977}
1978
1979uint64_t
1980tr_pieceOffset( const tr_torrent * tor,
1981                tr_piece_index_t   index,
1982                uint32_t           offset,
1983                uint32_t           length )
1984{
1985    uint64_t ret;
1986
1987    assert( tr_isTorrent( tor ) );
1988
1989    ret = tor->info.pieceSize;
1990    ret *= index;
1991    ret += offset;
1992    ret += length;
1993    return ret;
1994}
1995
1996/***
1997****
1998***/
1999
2000void
2001tr_torrentSetPieceChecked( tr_torrent        * tor,
2002                           tr_piece_index_t    piece,
2003                           tr_bool             isChecked )
2004{
2005    assert( tr_isTorrent( tor ) );
2006
2007    if( isChecked )
2008        tr_bitfieldAdd( &tor->checkedPieces, piece );
2009    else
2010        tr_bitfieldRem( &tor->checkedPieces, piece );
2011}
2012
2013void
2014tr_torrentSetFileChecked( tr_torrent *    tor,
2015                          tr_file_index_t fileIndex,
2016                          tr_bool         isChecked )
2017{
2018    const tr_file *        file = &tor->info.files[fileIndex];
2019    const tr_piece_index_t begin = file->firstPiece;
2020    const tr_piece_index_t end = file->lastPiece + 1;
2021
2022    assert( tr_isTorrent( tor ) );
2023
2024    if( isChecked )
2025        tr_bitfieldAddRange( &tor->checkedPieces, begin, end );
2026    else
2027        tr_bitfieldRemRange( &tor->checkedPieces, begin, end );
2028}
2029
2030tr_bool
2031tr_torrentIsFileChecked( const tr_torrent * tor,
2032                         tr_file_index_t    fileIndex )
2033{
2034    const tr_file *        file = &tor->info.files[fileIndex];
2035    const tr_piece_index_t begin = file->firstPiece;
2036    const tr_piece_index_t end = file->lastPiece + 1;
2037    tr_piece_index_t       i;
2038    tr_bool                isChecked = TRUE;
2039
2040    assert( tr_isTorrent( tor ) );
2041
2042    for( i = begin; isChecked && i < end; ++i )
2043        if( !tr_torrentIsPieceChecked( tor, i ) )
2044            isChecked = FALSE;
2045
2046    return isChecked;
2047}
2048
2049void
2050tr_torrentUncheck( tr_torrent * tor )
2051{
2052    assert( tr_isTorrent( tor ) );
2053
2054    tr_bitfieldRemRange( &tor->checkedPieces, 0, tor->info.pieceCount );
2055}
2056
2057int
2058tr_torrentCountUncheckedPieces( const tr_torrent * tor )
2059{
2060    assert( tr_isTorrent( tor ) );
2061
2062    return tor->info.pieceCount - tr_bitfieldCountTrueBits( &tor->checkedPieces );
2063}
2064
2065time_t*
2066tr_torrentGetMTimes( const tr_torrent * tor, size_t * setme_n )
2067{
2068    size_t       i;
2069    const size_t n = tor->info.fileCount;
2070    time_t *     m = tr_new0( time_t, n );
2071
2072    assert( tr_isTorrent( tor ) );
2073
2074    for( i = 0; i < n; ++i )
2075    {
2076        struct stat sb;
2077        char * path = tr_torrentFindFile( tor, i );
2078        if( ( path != NULL ) && !stat( path, &sb ) && S_ISREG( sb.st_mode ) )
2079        {
2080#ifdef SYS_DARWIN
2081            m[i] = sb.st_mtimespec.tv_sec;
2082#else
2083            m[i] = sb.st_mtime;
2084#endif
2085        }
2086        tr_free( path );
2087    }
2088
2089    *setme_n = n;
2090    return m;
2091}
2092
2093/***
2094****
2095***/
2096
2097tr_bool
2098tr_torrentSetAnnounceList( tr_torrent             * tor,
2099                           const tr_tracker_info  * trackers,
2100                           int                      trackerCount )
2101{
2102    int i;
2103    tr_benc metainfo;
2104    tr_bool ok = TRUE;
2105    tr_torrentLock( tor );
2106
2107    assert( tr_isTorrent( tor ) );
2108
2109    /* look for bad URLs */
2110    for( i=0; ok && i<trackerCount; ++i )
2111        if( !tr_httpIsValidURL( trackers[i].announce ) )
2112            ok = FALSE;
2113
2114    /* save to the .torrent file */
2115    if( ok && !tr_bencLoadFile( &metainfo, TR_FMT_BENC, tor->info.torrent ) )
2116    {
2117        tr_info   tmpInfo;
2118
2119        /* remove the old fields */
2120        tr_bencDictRemove( &metainfo, "announce" );
2121        tr_bencDictRemove( &metainfo, "announce-list" );
2122
2123        /* add the new fields */
2124        if( trackerCount > 0 )
2125        {
2126            tr_bencDictAddStr( &metainfo, "announce", trackers[0].announce );
2127        }
2128        if( trackerCount > 1 )
2129        {
2130            int i;
2131            int prevTier = -1;
2132            tr_benc * tier = NULL;
2133            tr_benc * announceList = tr_bencDictAddList( &metainfo, "announce-list", 0 );
2134
2135            for( i=0; i<trackerCount; ++i ) {
2136                if( prevTier != trackers[i].tier ) {
2137                    prevTier = trackers[i].tier;
2138                    tier = tr_bencListAddList( announceList, 0 );
2139                }
2140                tr_bencListAddStr( tier, trackers[i].announce );
2141            }
2142        }
2143
2144        /* try to parse it back again, to make sure it's good */
2145        memset( &tmpInfo, 0, sizeof( tr_info ) );
2146        if( tr_metainfoParse( tor->session, &tmpInfo,
2147                              &tor->infoDictOffset,
2148                              &tor->infoDictLength,
2149                              &metainfo ) )
2150        {
2151            /* it's good, so keep these new trackers and free the old ones */
2152
2153            tr_info swap;
2154            swap.trackers = tor->info.trackers;
2155            swap.trackerCount = tor->info.trackerCount;
2156            tor->info.trackers = tmpInfo.trackers;
2157            tor->info.trackerCount = tmpInfo.trackerCount;
2158            tmpInfo.trackers = swap.trackers;
2159            tmpInfo.trackerCount = swap.trackerCount;
2160
2161            tr_metainfoFree( &tmpInfo );
2162            tr_bencToFile( &metainfo, TR_FMT_BENC, tor->info.torrent );
2163        }
2164
2165        /* cleanup */
2166        tr_bencFree( &metainfo );
2167
2168        /* tell the announcer to reload this torrent's tracker list */
2169        tr_announcerResetTorrent( tor->session->announcer, tor );
2170    }
2171
2172    tr_torrentUnlock( tor );
2173    return ok;
2174}
2175
2176/**
2177***
2178**/
2179
2180void
2181tr_torrentSetAddedDate( tr_torrent * tor,
2182                        time_t       t )
2183{
2184    assert( tr_isTorrent( tor ) );
2185
2186    tor->addedDate = t;
2187    tor->anyDate = MAX( tor->anyDate, tor->addedDate );
2188}
2189
2190void
2191tr_torrentSetActivityDate( tr_torrent * tor, time_t t )
2192{
2193    assert( tr_isTorrent( tor ) );
2194
2195    tor->activityDate = t;
2196    tor->anyDate = MAX( tor->anyDate, tor->activityDate );
2197}
2198
2199void
2200tr_torrentSetDoneDate( tr_torrent * tor,
2201                       time_t       t )
2202{
2203    assert( tr_isTorrent( tor ) );
2204
2205    tor->doneDate = t;
2206    tor->anyDate = MAX( tor->anyDate, tor->doneDate );
2207}
2208
2209/**
2210***
2211**/
2212
2213uint64_t
2214tr_torrentGetBytesLeftToAllocate( const tr_torrent * tor )
2215{
2216    tr_file_index_t i;
2217    uint64_t bytesLeft = 0;
2218
2219    assert( tr_isTorrent( tor ) );
2220
2221    for( i=0; i<tor->info.fileCount; ++i )
2222    {
2223        if( !tor->info.files[i].dnd )
2224        {
2225            struct stat sb;
2226            const uint64_t length = tor->info.files[i].length;
2227            char * path = tr_torrentFindFile( tor, i );
2228
2229            bytesLeft += length;
2230
2231            if( ( path != NULL ) && !stat( path, &sb )
2232                                 && S_ISREG( sb.st_mode )
2233                                 && ( (uint64_t)sb.st_size <= length ) )
2234                bytesLeft -= sb.st_size;
2235
2236            tr_free( path );
2237        }
2238    }
2239
2240    return bytesLeft;
2241}
2242
2243/****
2244*****  Removing the torrent's local data
2245****/
2246
2247static int
2248vstrcmp( const void * a, const void * b )
2249{
2250    return strcmp( a, b );
2251}
2252
2253static int
2254compareLongestFirst( const void * a, const void * b )
2255{
2256    const size_t alen = strlen( a );
2257    const size_t blen = strlen( b );
2258
2259    if( alen != blen )
2260        return alen > blen ? -1 : 1;
2261
2262    return vstrcmp( a, b );
2263}
2264
2265static void
2266addDirtyFile( const char  * root,
2267              const char  * filename,
2268              tr_ptrArray * dirtyFolders )
2269{
2270    char * dir = tr_dirname( filename );
2271
2272    /* add the parent folders to dirtyFolders until we reach the root or a known-dirty */
2273    while (     ( dir != NULL )
2274             && ( strlen( root ) <= strlen( dir ) )
2275             && ( tr_ptrArrayFindSorted( dirtyFolders, dir, vstrcmp ) == NULL ) )
2276    {
2277        char * tmp;
2278        tr_ptrArrayInsertSorted( dirtyFolders, tr_strdup( dir ), vstrcmp );
2279
2280        tmp = tr_dirname( dir );
2281        tr_free( dir );
2282        dir = tmp;
2283    }
2284
2285    tr_free( dir );
2286}
2287
2288static void
2289walkLocalData( const tr_torrent * tor,
2290               const char       * root,
2291               const char       * dir,
2292               const char       * base,
2293               tr_ptrArray      * torrentFiles,
2294               tr_ptrArray      * folders,
2295               tr_ptrArray      * dirtyFolders )
2296{
2297    int i;
2298    struct stat sb;
2299    char * buf;
2300
2301    assert( tr_isTorrent( tor ) );
2302
2303    buf = tr_buildPath( dir, base, NULL );
2304    i = stat( buf, &sb );
2305    if( !i )
2306    {
2307        DIR * odir = NULL;
2308
2309        if( S_ISDIR( sb.st_mode ) && ( ( odir = opendir ( buf ) ) ) )
2310        {
2311            struct dirent *d;
2312            tr_ptrArrayInsertSorted( folders, tr_strdup( buf ), vstrcmp );
2313            for( d = readdir( odir ); d != NULL; d = readdir( odir ) )
2314                if( d->d_name && d->d_name[0] != '.' ) /* skip dotfiles */
2315                    walkLocalData( tor, root, buf, d->d_name, torrentFiles, folders, dirtyFolders );
2316            closedir( odir );
2317        }
2318        else if( S_ISREG( sb.st_mode ) && ( sb.st_size > 0 ) )
2319        {
2320            const char * sub = buf + strlen( tor->currentDir ) + strlen( TR_PATH_DELIMITER_STR );
2321            const tr_bool isTorrentFile = tr_ptrArrayFindSorted( torrentFiles, sub, vstrcmp ) != NULL;
2322            if( !isTorrentFile )
2323                addDirtyFile( root, buf, dirtyFolders );
2324        }
2325    }
2326
2327    tr_free( buf );
2328}
2329
2330static void
2331deleteLocalFile( const char * filename, tr_fileFunc fileFunc )
2332{
2333    struct stat sb;
2334    if( !stat( filename, &sb ) ) /* if file exists... */
2335        fileFunc( filename );
2336}
2337
2338static void
2339deleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2340{
2341    int i, n;
2342    char ** s;
2343    tr_file_index_t f;
2344    tr_ptrArray torrentFiles = TR_PTR_ARRAY_INIT;
2345    tr_ptrArray folders      = TR_PTR_ARRAY_INIT;
2346    tr_ptrArray dirtyFolders = TR_PTR_ARRAY_INIT; /* dirty == contains non-torrent files */
2347
2348    const char * firstFile = tor->info.files[0].name;
2349    const char * cpch = strchr( firstFile, TR_PATH_DELIMITER );
2350    char * tmp = cpch ? tr_strndup( firstFile, cpch - firstFile ) : NULL;
2351    char * root = tr_buildPath( tor->currentDir, tmp, NULL );
2352
2353    assert( tr_isTorrent( tor ) );
2354
2355    for( f=0; f<tor->info.fileCount; ++f ) {
2356        tr_ptrArrayInsertSorted( &torrentFiles, tr_strdup( tor->info.files[f].name ), vstrcmp );
2357        tr_ptrArrayInsertSorted( &torrentFiles, tr_torrentBuildPartial( tor, f ), vstrcmp );
2358    }
2359
2360    /* build the set of folders and dirtyFolders */
2361    walkLocalData( tor, root, root, NULL, &torrentFiles, &folders, &dirtyFolders );
2362
2363    /* try to remove entire folders first, so that the recycle bin will be tidy */
2364    s = (char**) tr_ptrArrayPeek( &folders, &n );
2365    for( i=0; i<n; ++i )
2366        if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2367            deleteLocalFile( s[i], fileFunc );
2368
2369    /* now blow away any remaining torrent files, such as torrent files in dirty folders */
2370    for( f=0; f<tor->info.fileCount; ++f ) {
2371        char * path = tr_buildPath( tor->currentDir, tor->info.files[f].name, NULL );
2372        deleteLocalFile( path, fileFunc );
2373        tr_free( path );
2374    }
2375
2376    /* Now clean out the directories left empty from the previous step.
2377     * Work from deepest to shallowest s.t. lower folders
2378     * won't prevent the upper folders from being deleted */
2379    {
2380        tr_ptrArray cleanFolders = TR_PTR_ARRAY_INIT;
2381        s = (char**) tr_ptrArrayPeek( &folders, &n );
2382        for( i=0; i<n; ++i )
2383            if( tr_ptrArrayFindSorted( &dirtyFolders, s[i], vstrcmp ) == NULL )
2384                tr_ptrArrayInsertSorted( &cleanFolders, s[i], compareLongestFirst );
2385        s = (char**) tr_ptrArrayPeek( &cleanFolders, &n );
2386        for( i=0; i<n; ++i ) {
2387#ifdef SYS_DARWIN
2388            char * dsStore = tr_buildPath( s[i], ".DS_Store", NULL );
2389            deleteLocalFile( dsStore, fileFunc );
2390            tr_free( dsStore );
2391#endif
2392            deleteLocalFile( s[i], fileFunc );
2393        }
2394        tr_ptrArrayDestruct( &cleanFolders, NULL );
2395    }
2396
2397    /* cleanup */
2398    tr_ptrArrayDestruct( &dirtyFolders, tr_free );
2399    tr_ptrArrayDestruct( &folders, tr_free );
2400    tr_ptrArrayDestruct( &torrentFiles, tr_free );
2401    tr_free( root );
2402    tr_free( tmp );
2403}
2404
2405void
2406tr_torrentDeleteLocalData( tr_torrent * tor, tr_fileFunc fileFunc )
2407{
2408    assert( tr_isTorrent( tor ) );
2409
2410    if( fileFunc == NULL )
2411        fileFunc = remove;
2412
2413    /* close all the files because we're about to delete them */
2414    tr_fdTorrentClose( tor->session, tor->uniqueId );
2415
2416    if( tor->info.fileCount > 1 )
2417    {
2418        deleteLocalData( tor, fileFunc );
2419    }
2420    else if( tor->info.fileCount == 1 )
2421    {
2422        char * tmp;
2423
2424        /* torrent only has one file */
2425        char * path = tr_buildPath( tor->currentDir, tor->info.files[0].name, NULL );
2426        deleteLocalFile( path, fileFunc );
2427        tr_free( path );
2428
2429        tmp = tr_torrentBuildPartial( tor, 0 );
2430        path = tr_buildPath( tor->currentDir, tmp, NULL );
2431        deleteLocalFile( path, fileFunc );
2432        tr_free( path );
2433        tr_free( tmp );
2434    }
2435}
2436
2437/***
2438****
2439***/
2440
2441struct LocationData
2442{
2443    tr_bool move_from_old_location;
2444    int * setme_state;
2445    double * setme_progress;
2446    char * location;
2447    tr_torrent * tor;
2448};
2449
2450static void
2451setLocation( void * vdata )
2452{
2453    tr_bool err = FALSE;
2454    tr_bool verify_needed = FALSE;
2455    struct LocationData * data = vdata;
2456    tr_torrent * tor = data->tor;
2457    const tr_bool do_move = data->move_from_old_location;
2458    const char * location = data->location;
2459    double bytesHandled = 0;
2460
2461    assert( tr_isTorrent( tor ) );
2462
2463    if( strcmp( location, tor->currentDir ) )
2464    {
2465        tr_file_index_t i;
2466
2467        /* bad idea to move files while they're being verified... */
2468        tr_verifyRemove( tor );
2469
2470        /* if the torrent is running, stop it and set a flag to
2471         * restart after we're done */
2472        if( tor->isRunning )
2473        {
2474            tr_torrentStop( tor );
2475            tor->startAfterVerify = TRUE;
2476        }
2477
2478        /* try to move the files.
2479         * FIXME: there are still all kinds of nasty cases, like what
2480         * if the target directory runs out of space halfway through... */
2481        for( i=0; !err && i<tor->info.fileCount; ++i )
2482        {
2483            const tr_file * f = &tor->info.files[i];
2484            const char * oldbase;
2485            char * sub;
2486            if( tr_torrentFindFile2( tor, i, &oldbase, &sub ) )
2487            {
2488                char * oldpath = tr_buildPath( oldbase, sub, NULL );
2489                char * newpath = tr_buildPath( location, sub, NULL );
2490
2491                if( do_move )
2492                {
2493                    tr_bool renamed = FALSE;
2494                    errno = 0;
2495                    tr_torinf( tor, "moving \"%s\" to \"%s\"", oldpath, newpath );
2496                    if( tr_moveFile( oldpath, newpath, &renamed ) )
2497                    {
2498                        err = TRUE;
2499                        tr_torerr( tor, "error moving \"%s\" to \"%s\": %s",
2500                                        oldpath, newpath, tr_strerror( errno ) );
2501                    }
2502                    else if( !renamed )
2503                    {
2504                        verify_needed = TRUE;
2505                    }
2506                }
2507
2508                tr_free( newpath );
2509                tr_free( oldpath );
2510                tr_free( sub );
2511            }
2512
2513            if( data->setme_progress )
2514            {
2515                bytesHandled += f->length;
2516                *data->setme_progress = bytesHandled / tor->info.totalSize;
2517            }
2518        }
2519
2520        if( !err )
2521        {
2522            /* blow away the leftover subdirectories in the old location */
2523            if( do_move )
2524                tr_torrentDeleteLocalData( tor, remove );
2525
2526            /* set the new location and reverify */
2527            tr_torrentSetDownloadDir( tor, location );
2528            if( verify_needed )
2529                tr_torrentVerify( tor );
2530            else if( tor->startAfterVerify ) {
2531                tor->startAfterVerify = FALSE;
2532                tr_torrentStart( tor );
2533            }
2534        }
2535    }
2536
2537    if( data->setme_state )
2538        *data->setme_state = err ? TR_LOC_ERROR : TR_LOC_DONE;
2539
2540    /* cleanup */
2541    tr_free( data->location );
2542    tr_free( data );
2543}
2544
2545void
2546tr_torrentSetLocation( tr_torrent  * tor,
2547                       const char  * location,
2548                       tr_bool       move_from_old_location,
2549                       double      * setme_progress,
2550                       int         * setme_state )
2551{
2552    struct LocationData * data;
2553
2554    assert( tr_isTorrent( tor ) );
2555
2556    if( setme_state )
2557        *setme_state = TR_LOC_MOVING;
2558    if( setme_progress )
2559        *setme_progress = 0;
2560
2561    /* run this in the libtransmission thread */
2562    data = tr_new( struct LocationData, 1 );
2563    data->tor = tor;
2564    data->location = tr_strdup( location );
2565    data->move_from_old_location = move_from_old_location;
2566    data->setme_state = setme_state;
2567    data->setme_progress = setme_progress;
2568    tr_runInEventThread( tor->session, setLocation, data );
2569}
2570
2571/***
2572****
2573***/
2574
2575void
2576tr_torrentCheckSeedRatio( tr_torrent * tor )
2577{
2578    double seedRatio;
2579
2580    assert( tr_isTorrent( tor ) );
2581
2582    /* if we're seeding and we've reached our seed ratio limit, stop the torrent */
2583    if( tor->isRunning && tr_torrentIsSeed( tor ) && tr_torrentGetSeedRatio( tor, &seedRatio ) )
2584    {
2585        const uint64_t up = tor->uploadedCur + tor->uploadedPrev;
2586        uint64_t down = tor->downloadedCur + tor->downloadedPrev;
2587        double ratio;
2588
2589        /* maybe we're the initial seeder and never downloaded anything... */
2590        if( down == 0 )
2591            down = tr_cpHaveValid( &tor->completion );
2592
2593        ratio = tr_getRatio( up, down );
2594
2595        if( ratio >= seedRatio || ratio == TR_RATIO_INF )
2596        {
2597            tr_torrentStop( tor );
2598
2599            /* set to no ratio limit to allow easy restarting */
2600            tr_torrentSetRatioMode( tor, TR_RATIOLIMIT_UNLIMITED );
2601
2602            /* maybe notify the client */
2603            if( tor->ratio_limit_hit_func != NULL )
2604                tor->ratio_limit_hit_func( tor, tor->ratio_limit_hit_func_user_data );
2605        }
2606    }
2607}
2608
2609/***
2610****
2611***/
2612
2613void
2614tr_torrentFileCompleted( tr_torrent * tor, tr_file_index_t fileNum )
2615{
2616    char * sub;
2617    const char * base;
2618
2619    /* close the file so that we can reopen in read-only mode as needed */
2620    tr_fdFileClose( tor->session, tor, fileNum );
2621
2622    /* if the torrent's filename on disk isn't the same as the one in the metadata,
2623     * then it's been modified to denote that it was a partial file.
2624     * Now that it's complete, use the proper filename. */
2625    if( tr_torrentFindFile2( tor, fileNum, &base, &sub ) )
2626    {
2627        const tr_file * file = &tor->info.files[fileNum];
2628
2629        if( strcmp( sub, file->name ) )
2630        {
2631            char * oldpath = tr_buildPath( base, sub, NULL );
2632            char * newpath = tr_buildPath( base, file->name, NULL );
2633
2634            if( rename( oldpath, newpath ) )
2635                tr_torerr( tor, "Error moving \"%s\" to \"%s\": %s", oldpath, newpath, tr_strerror( errno ) );
2636
2637            tr_free( newpath );
2638            tr_free( oldpath );
2639        }
2640
2641        tr_free( sub );
2642    }
2643}
2644
2645/***
2646****
2647***/
2648
2649static tr_bool
2650fileExists( const char * filename )
2651{
2652    struct stat sb;
2653    const tr_bool ok = !stat( filename, &sb );
2654    return ok;
2655}
2656
2657tr_bool
2658tr_torrentFindFile2( const tr_torrent * tor, tr_file_index_t fileNum,
2659                     const char ** base, char ** subpath )
2660{
2661    char * part;
2662    const tr_file * file;
2663    const char * b = NULL;
2664    const char * s = NULL;
2665
2666    assert( tr_isTorrent( tor ) );
2667    assert( fileNum < tor->info.fileCount );
2668
2669    file = &tor->info.files[fileNum];
2670    part = tr_torrentBuildPartial( tor, fileNum );
2671
2672    if( b == NULL ) {
2673        char * filename = tr_buildPath( tor->downloadDir, file->name, NULL );
2674        if( fileExists( filename ) ) {
2675            b = tor->downloadDir;
2676            s = file->name;
2677        }
2678        tr_free( filename );
2679    }
2680
2681    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2682        char * filename = tr_buildPath( tor->incompleteDir, file->name, NULL );
2683        if( fileExists( filename ) ) {
2684            b = tor->incompleteDir;
2685            s = file->name;
2686        }
2687        tr_free( filename );
2688    }
2689
2690    if( ( b == NULL ) && ( tor->incompleteDir != NULL ) ) {
2691        char * filename = tr_buildPath( tor->incompleteDir, part, NULL );
2692        if( fileExists( filename ) ) {
2693            b = tor->incompleteDir;
2694            s = part;
2695        }
2696        tr_free( filename );
2697    }
2698
2699    if( b == NULL) {
2700        char * filename = tr_buildPath( tor->downloadDir, part, NULL );
2701        if( fileExists( filename ) ) {
2702            b = tor->downloadDir;
2703            s = part;
2704        }
2705        tr_free( filename );
2706    }
2707
2708    if( base != NULL )
2709        *base = b;
2710    if( subpath != NULL )
2711        *subpath = tr_strdup( s );
2712
2713    tr_free( part );
2714    return b != NULL;
2715}
2716
2717char*
2718tr_torrentFindFile( const tr_torrent * tor, tr_file_index_t fileNum )
2719{
2720    char * subpath;
2721    char * ret = NULL;
2722    const char * base;
2723
2724    if( tr_torrentFindFile2( tor, fileNum, &base, &subpath ) )
2725    {
2726        ret = tr_buildPath( base, subpath, NULL );
2727        tr_free( subpath );
2728    }
2729
2730    return ret;
2731}
2732
2733/* Decide whether we should be looking for files in downloadDir or incompleteDir. */
2734static void
2735refreshCurrentDir( tr_torrent * tor )
2736{
2737    const char * dir = NULL;
2738    char * sub;
2739
2740    if( tor->incompleteDir == NULL )
2741        dir = tor->downloadDir;
2742    else if( !tr_torrentHasMetadata( tor ) ) /* no files to find */
2743        dir = tor->incompleteDir;
2744    else if( !tr_torrentFindFile2( tor, 0, &dir, &sub ) )
2745        dir = tor->incompleteDir;
2746
2747    assert( dir != NULL );
2748    assert( ( dir == tor->downloadDir ) || ( dir == tor->incompleteDir ) );
2749    tor->currentDir = dir;
2750}
2751
2752char*
2753tr_torrentBuildPartial( const tr_torrent * tor, tr_file_index_t fileNum )
2754{
2755    return tr_strdup_printf( "%s.part", tor->info.files[fileNum].name );
2756}
Note: See TracBrowser for help on using the repository browser.