source: trunk/libtransmission/torrent.c @ 10694

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

(trunk libT) define MAX_BLOCK_SIZE once instead of in a handful of places

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