source: trunk/libtransmission/torrent.c @ 9591

Last change on this file since 9591 was 9591, checked in by charles, 13 years ago

(trunk libT) #2096 "magnet links" -- add a callback for clients to know when a magnet torrent's metainfo is finished downloading.

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