source: trunk/libtransmission/torrent.c @ 10078

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

(trunk libT) #2846 "Priority Selection in `Add' Window" -- added RPC hooks for doing this via remote client

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