source: trunk/libtransmission/torrent.c @ 10477

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

(trunk libT) #1869 "new status for torrents that reached the seed ratio" -- maybe fix the issue reported by leena

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