source: trunk/libtransmission/torrent.c @ 10551

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

(trunk libT) #1869 "New status for torrents that reached the seed ratio" -- maybe fix the bug where the incomplete-dir and seed-ratio features conflicted with each other as reported by leena in http://trac.transmissionbt.com/ticket/1869#comment:45

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