source: trunk/libtransmission/torrent.c @ 10072

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

(trunk libT) #2720 "Misleading error message when adding a duplicate magnet transfer" -- add a public API call in libtransmission for testing to see if we already have a magnet link as a torrent

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