source: trunk/libtransmission/torrent.c @ 5647

Last change on this file since 5647 was 5647, checked in by charles, 14 years ago

#890: be smarter about noticing seeds from tracker & pex

  • Property svn:keywords set to Date Rev Author Id
File size: 37.3 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 5647 2008-04-19 15:07:59Z charles $
3 *
4 * Copyright (c) 2005-2008 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#include <sys/types.h> /* stat */
26#include <sys/stat.h> /* stat */
27#include <unistd.h> /* stat */
28
29#include <assert.h>
30#include <string.h> /* memcmp */
31
32#include "transmission.h"
33#include "bencode.h"
34#include "completion.h"
35#include "crypto.h" /* for tr_sha1 */
36#include "resume.h"
37#include "fdlimit.h" /* tr_fdFileClose */
38#include "metainfo.h"
39#include "peer-mgr.h"
40#include "ratecontrol.h"
41#include "torrent.h"
42#include "tracker.h"
43#include "trcompat.h" /* for strlcpy */
44#include "trevent.h"
45#include "utils.h"
46#include "verify.h"
47
48#define MAX_BLOCK_SIZE (1024*16)
49
50/***
51****
52***/
53
54int
55tr_torrentExists( tr_handle       * handle,
56                  const uint8_t   * torrentHash )
57{
58    return tr_torrentFindFromHash( handle, torrentHash ) != NULL;
59}
60
61tr_torrent*
62tr_torrentFindFromHash( tr_handle      * handle,
63                        const uint8_t  * torrentHash )
64{
65    tr_torrent * tor;
66
67    for( tor = handle->torrentList; tor; tor = tor->next )
68        if( !memcmp( tor->info.hash, torrentHash, SHA_DIGEST_LENGTH ) )
69            return tor;
70
71    return NULL;
72}
73
74tr_torrent*
75tr_torrentFindFromObfuscatedHash( tr_handle      * handle,
76                                  const uint8_t  * obfuscatedTorrentHash )
77{
78    tr_torrent * tor;
79
80    for( tor = handle->torrentList; tor; tor = tor->next )
81        if( !memcmp( tor->obfuscatedHash, obfuscatedTorrentHash, SHA_DIGEST_LENGTH ) )
82            return tor;
83
84    return NULL;
85}
86
87/***
88****  LOCKS
89***/
90
91void
92tr_torrentLock( const tr_torrent * tor )
93{
94    tr_globalLock( tor->handle );
95}
96
97void
98tr_torrentUnlock( const tr_torrent * tor )
99{
100    tr_globalUnlock( tor->handle );
101}
102
103/***
104****  PER-TORRENT UL / DL SPEEDS
105***/
106
107void
108tr_torrentSetSpeedMode( tr_torrent   * tor,
109                        int            up_or_down,
110                        tr_speedlimit  mode )
111{
112    tr_speedlimit * limit = up_or_down==TR_UP
113        ? &tor->uploadLimitMode
114        : &tor->downloadLimitMode;
115    *limit = mode;
116}
117
118tr_speedlimit
119tr_torrentGetSpeedMode( const tr_torrent * tor,
120                        int                up_or_down)
121{
122    return up_or_down==TR_UP ? tor->uploadLimitMode
123                             : tor->downloadLimitMode;
124}
125
126void
127tr_torrentSetSpeedLimit( tr_torrent   * tor,
128                         int            up_or_down,
129                         int            single_KiB_sec )
130{
131    tr_ratecontrol * rc = up_or_down==TR_UP ? tor->upload : tor->download;
132    tr_rcSetLimit( rc, single_KiB_sec );
133}
134
135int
136tr_torrentGetSpeedLimit( const tr_torrent  * tor,
137                         int                 up_or_down )
138{
139    tr_ratecontrol * rc = up_or_down==TR_UP ? tor->upload : tor->download;
140    return tr_rcGetLimit( rc );
141}
142
143/***
144****
145***/
146
147static void
148onTrackerResponse( void * tracker UNUSED, void * vevent, void * user_data )
149{
150    tr_torrent * tor = user_data;
151    tr_tracker_event * event = vevent;
152
153    switch( event->messageType )
154    {
155        case TR_TRACKER_PEERS: {
156            size_t i, n;
157            tr_pex * pex = tr_peerMgrCompactToPex( event->compact,
158                                                   event->compactLen,
159                                                   NULL, &n );
160            if( event->allAreSeeds )
161                tr_tordbg( tor, "Got %d seeds from tracker", (int)n );
162            else
163                tr_torinf( tor, _( "Got %d peers from tracker" ), (int)n );
164
165            for( i=0; i<n; ++i ) {
166                if( event->allAreSeeds )
167                    pex[i].flags |= ADDED_F_SEED_FLAG;
168                tr_peerMgrAddPex( tor->handle->peerMgr, tor->info.hash,
169                                  TR_PEER_FROM_TRACKER, pex+i );
170            }
171
172            tr_free( pex );
173            break;
174        }
175
176        case TR_TRACKER_WARNING:
177            tr_torerr( tor, _( "Tracker warning: \"%s\"" ), event->text );
178            tor->error = TR_ERROR_TC_WARNING;
179            strlcpy( tor->errorString, event->text, sizeof(tor->errorString) );
180            break;
181
182        case TR_TRACKER_ERROR:
183            tr_torerr( tor, _( "Tracker error: \"%s\"" ), event->text );
184            tor->error = TR_ERROR_TC_ERROR;
185            strlcpy( tor->errorString, event->text, sizeof(tor->errorString) );
186            break;
187
188        case TR_TRACKER_ERROR_CLEAR:
189            tor->error = 0;
190            tor->errorString[0] = '\0';
191            break;
192    }
193}
194
195/***
196****
197****  TORRENT INSTANTIATION
198****
199***/
200
201static int
202getBytePiece( const tr_info * info, uint64_t byteOffset )
203{
204    assert( info != NULL );
205    assert( info->pieceSize != 0 );
206
207    return byteOffset / info->pieceSize;
208}
209
210static void
211initFilePieces ( tr_info * info, tr_file_index_t fileIndex )
212{
213    tr_file * file = &info->files[fileIndex];
214    uint64_t firstByte, lastByte;
215
216    assert( info != NULL );
217    assert( fileIndex < info->fileCount );
218
219    file = &info->files[fileIndex];
220    firstByte = file->offset;
221    lastByte = firstByte + (file->length ? file->length-1 : 0);
222    file->firstPiece = getBytePiece( info, firstByte );
223    file->lastPiece = getBytePiece( info, lastByte );
224}
225
226static int
227pieceHasFile( tr_piece_index_t piece, const tr_file * file )
228{
229    return ( file->firstPiece <= piece ) && ( piece <= file->lastPiece );
230}
231
232static tr_priority_t
233calculatePiecePriority ( const tr_torrent * tor,
234                         tr_piece_index_t   piece,
235                         int                fileHint )
236{
237    tr_file_index_t i;
238    int priority = TR_PRI_LOW;
239
240    /* find the first file that has data in this piece */
241    if( fileHint >= 0 ) {
242        i = fileHint;
243        while( i>0 && pieceHasFile( piece, &tor->info.files[i-1] ) )
244            --i;
245    } else {
246        for( i=0; i<tor->info.fileCount; ++i )
247            if( pieceHasFile( piece, &tor->info.files[i] ) )
248                break;
249    }
250
251    /* the piece's priority is the max of the priorities
252     * of all the files in that piece */
253    for( ; i<tor->info.fileCount; ++i )
254    {
255        const tr_file * file = &tor->info.files[i];
256
257        if( !pieceHasFile( piece, file ) )
258            break;
259
260        priority = MAX( priority, file->priority );
261
262        /* when dealing with multimedia files, getting the first and
263           last pieces can sometimes allow you to preview it a bit
264           before it's fully downloaded... */
265        if ( file->priority >= TR_PRI_NORMAL )
266            if ( file->firstPiece == piece || file->lastPiece == piece )
267                priority = TR_PRI_HIGH;
268    }
269
270    return priority;
271}
272
273static void
274tr_torrentInitFilePieces( tr_torrent * tor )
275{
276    tr_file_index_t ff;
277    tr_piece_index_t pp;
278    uint64_t offset = 0;
279
280    assert( tor != NULL );
281
282    for( ff=0; ff<tor->info.fileCount; ++ff ) {
283      tor->info.files[ff].offset = offset;
284      offset += tor->info.files[ff].length;
285      initFilePieces( &tor->info, ff );
286    }
287
288    for( pp=0; pp<tor->info.pieceCount; ++pp )
289        tor->info.pieces[pp].priority = calculatePiecePriority( tor, pp, -1 );
290}
291
292static void
293torrentRealInit( tr_handle     * h,
294                 tr_torrent    * tor,
295                 const tr_ctor * ctor )
296{
297    int doStart;
298    uint64_t loaded;
299    uint64_t t;
300    tr_info * info = &tor->info;
301   
302    tr_globalLock( h );
303
304    tor->handle   = h;
305
306    /**
307     * Decide on a block size.  constraints:
308     * (1) most clients decline requests over 16 KiB
309     * (2) pieceSize must be a multiple of block size
310     */
311    tor->blockSize = info->pieceSize;
312    while( tor->blockSize > MAX_BLOCK_SIZE )
313        tor->blockSize /= 2;
314
315    tor->lastPieceSize = info->totalSize % info->pieceSize;
316
317    if( !tor->lastPieceSize )
318         tor->lastPieceSize = info->pieceSize;
319
320    tor->lastBlockSize = info->totalSize % tor->blockSize;
321
322    if( !tor->lastBlockSize )
323         tor->lastBlockSize = tor->blockSize;
324
325    tor->blockCount =
326        ( info->totalSize + tor->blockSize - 1 ) / tor->blockSize;
327
328    tor->blockCountInPiece =
329        info->pieceSize / tor->blockSize;
330
331    tor->blockCountInLastPiece =
332        ( tor->lastPieceSize + tor->blockSize - 1 ) / tor->blockSize;
333
334    /* check our work */
335    assert( ( info->pieceSize % tor->blockSize ) == 0 );
336    t = info->pieceCount - 1;
337    t *= info->pieceSize;
338    t += tor->lastPieceSize;
339    assert( t == info->totalSize );
340    t = tor->blockCount - 1;
341    t *= tor->blockSize;
342    t += tor->lastBlockSize;
343    assert( t == info->totalSize );
344    t = info->pieceCount - 1;
345    t *= tor->blockCountInPiece;
346    t += tor->blockCountInLastPiece;
347    assert( t == (uint64_t)tor->blockCount );
348
349    tor->completion = tr_cpInit( tor );
350
351    tr_torrentInitFilePieces( tor );
352
353    tor->upload         = tr_rcInit();
354    tor->download       = tr_rcInit();
355    tor->swarmspeed     = tr_rcInit();
356
357    tr_sha1( tor->obfuscatedHash, "req2", 4,
358                                  info->hash, SHA_DIGEST_LENGTH,
359                                  NULL );
360
361    tr_peerMgrAddTorrent( h->peerMgr, tor );
362
363    if( !h->isPortSet )
364        tr_setBindPort( h, TR_DEFAULT_PORT );
365
366    assert( !tor->downloadedCur );
367    assert( !tor->uploadedCur );
368
369    tor->error   = TR_OK;
370
371    tor->checkedPieces = tr_bitfieldNew( tor->info.pieceCount );
372    tr_torrentUncheck( tor );
373    loaded = tr_torrentLoadResume( tor, ~0, ctor );
374   
375    doStart = tor->isRunning;
376    tor->isRunning = 0;
377
378    if( !(loaded & TR_FR_SPEEDLIMIT ) ) {
379        int limit, enabled;
380        tr_getGlobalSpeedLimit( tor->handle, TR_UP, &enabled, &limit );
381        tr_torrentSetSpeedLimit( tor, TR_UP, limit );
382        tr_getGlobalSpeedLimit( tor->handle, TR_DOWN, &enabled, &limit );
383        tr_torrentSetSpeedLimit( tor, TR_DOWN, limit );
384    }
385
386    tor->cpStatus = tr_cpGetStatus( tor->completion );
387
388    tor->tracker = tr_trackerNew( tor );
389    tor->trackerSubscription = tr_trackerSubscribe( tor->tracker, onTrackerResponse, tor );
390
391    tor->next = h->torrentList;
392    h->torrentList = tor;
393    h->torrentCount++;
394
395    tr_globalUnlock( h );
396
397    /* maybe save our own copy of the metainfo */
398    if( tr_ctorGetSave( ctor ) ) {
399        const tr_benc * val;
400        if( !tr_ctorGetMetainfo( ctor, &val ) ) {
401            const char * filename = tor->info.torrent;
402            tr_bencSaveFile( filename, val );
403            tr_sessionSetTorrentFile( tor->handle, tor->info.hashString, filename );
404        }
405    }
406
407    tr_metainfoMigrate( h, &tor->info );
408
409    if( doStart )
410        tr_torrentStart( tor );
411}
412
413static int
414hashExists( const tr_handle   * h,
415            const uint8_t     * hash )
416{
417    const tr_torrent * tor;
418
419    for( tor=h->torrentList; tor; tor=tor->next )
420        if( !memcmp( hash, tor->info.hash, SHA_DIGEST_LENGTH ) )
421            return TRUE;
422
423    return FALSE;
424}
425
426int
427tr_torrentParse( const tr_handle  * handle,
428                 const tr_ctor    * ctor,
429                 tr_info          * setmeInfo )
430{
431    int err = 0;
432    int doFree;
433    tr_info tmp;
434    const tr_benc * metainfo;
435
436    if( setmeInfo == NULL )
437        setmeInfo = &tmp;
438    memset( setmeInfo, 0, sizeof( tr_info ) );
439
440    if( !err && tr_ctorGetMetainfo( ctor, &metainfo ) )
441        return TR_EINVALID;
442
443    err = tr_metainfoParse( handle, setmeInfo, metainfo );
444    doFree = !err && ( setmeInfo == &tmp );
445
446    if( !err && hashExists( handle, setmeInfo->hash ) )
447        err = TR_EDUPLICATE;
448
449    if( doFree )
450        tr_metainfoFree( setmeInfo );
451
452    return err;
453}
454
455tr_torrent *
456tr_torrentNew( tr_handle      * handle,
457               const tr_ctor  * ctor,
458               int            * setmeError )
459{
460    int err;
461    tr_info tmpInfo;
462    tr_torrent * tor = NULL;
463
464    err = tr_torrentParse( handle, ctor, &tmpInfo );
465    if( !err ) {
466        tor = tr_new0( tr_torrent, 1 );
467        tor->info = tmpInfo;
468        torrentRealInit( handle, tor, ctor );
469    } else if( setmeError ) {
470        *setmeError = err;
471    }
472
473    return tor;
474}
475
476/**
477***
478**/
479
480void
481tr_torrentSetFolder( tr_torrent * tor, const char * path )
482{
483    tr_free( tor->destination );
484    tor->destination = tr_strdup( path );
485    tr_torrentSaveResume( tor );
486}
487
488const char*
489tr_torrentGetFolder( const tr_torrent * tor )
490{
491    return tor->destination;
492}
493
494void
495tr_torrentChangeMyPort( tr_torrent * tor )
496{
497    if( tor->tracker )
498        tr_trackerChangeMyPort( tor->tracker );
499}
500
501int
502tr_torrentIsPrivate( const tr_torrent * tor )
503{
504    return tor
505        && tor->info.isPrivate;
506}
507
508int
509tr_torrentAllowsPex( const tr_torrent * tor )
510{
511    return tor
512        && tor->handle->isPexEnabled
513        && !tr_torrentIsPrivate( tor );
514}
515
516static void
517tr_manualUpdateImpl( void * vtor )
518{
519    tr_torrent * tor = vtor;
520    if( tor->isRunning )
521        tr_trackerReannounce( tor->tracker );
522}
523void
524tr_manualUpdate( tr_torrent * tor )
525{
526    tr_runInEventThread( tor->handle, tr_manualUpdateImpl, tor );
527}
528int
529tr_torrentCanManualUpdate( const tr_torrent * tor )
530{
531    return ( tor != NULL )
532        && ( tor->isRunning )
533        && ( tr_trackerCanManualAnnounce( tor->tracker ) );
534}
535
536/* rcRate's averaging code can make it appear that we're
537 * still sending bytes after a torrent stops or all the
538 * peers disconnect, so short-circuit that appearance here */
539void
540tr_torrentGetRates( const tr_torrent * tor,
541                    float            * toClient,
542                    float            * toPeer)
543{
544    const int showSpeed = tor->isRunning
545        && tr_peerMgrHasConnections( tor->handle->peerMgr, tor->info.hash );
546
547    if( toClient )
548        *toClient = showSpeed ? tr_rcRate( tor->download ) : 0.0;
549    if( toPeer )
550        *toPeer = showSpeed ? tr_rcRate( tor->upload ) : 0.0;
551}
552const tr_info *
553tr_torrentInfo( const tr_torrent * tor )
554{
555    return tor ? &tor->info : NULL;
556}
557
558const tr_stat *
559tr_torrentStatCached( tr_torrent * tor )
560{
561    const time_t now = time( NULL );
562
563    return tor && ( now == tor->lastStatTime ) ? &tor->stats
564                                               : tr_torrentStat( tor );
565}
566
567tr_torrent_status
568tr_torrentGetStatus( tr_torrent * tor )
569{
570    tr_torrentRecheckCompleteness( tor );
571
572    if( tor->verifyState == TR_VERIFY_NOW )
573        return TR_STATUS_CHECK;
574    if( tor->verifyState == TR_VERIFY_WAIT )
575        return TR_STATUS_CHECK_WAIT;
576    if( !tor->isRunning )
577        return TR_STATUS_STOPPED;
578    if( tor->cpStatus == TR_CP_INCOMPLETE )
579        return TR_STATUS_DOWNLOAD;
580
581    return TR_STATUS_SEED;
582}
583
584const tr_stat *
585tr_torrentStat( tr_torrent * tor )
586{
587    tr_stat * s;
588    struct tr_tracker * tc;
589
590    if( !tor )
591        return NULL;
592
593    tr_torrentLock( tor );
594
595    tor->lastStatTime = time( NULL );
596
597    s = &tor->stats;
598    s->status = tr_torrentGetStatus( tor );
599    s->error  = tor->error;
600    memcpy( s->errorString, tor->errorString,
601            sizeof( s->errorString ) );
602
603    tc = tor->tracker;
604    s->tracker = tr_trackerGetAddress( tor->tracker );
605
606    tr_trackerStat( tor->tracker, &s->tracker_stat );
607
608    tr_peerMgrTorrentStats( tor->handle->peerMgr,
609                            tor->info.hash,
610                            &s->peersKnown,
611                            &s->peersConnected,
612                            &s->peersSendingToUs,
613                            &s->peersGettingFromUs,
614                             s->peersFrom );
615
616    s->manualAnnounceTime = tr_trackerGetManualAnnounceTime( tor->tracker );
617
618    s->percentComplete = tr_cpPercentComplete ( tor->completion );
619
620    s->percentDone = tr_cpPercentDone( tor->completion );
621    s->leftUntilDone = tr_cpLeftUntilDone( tor->completion );
622    s->sizeWhenDone = tr_cpSizeWhenDone( tor->completion );
623
624    s->recheckProgress =
625        1.0 - (tr_torrentCountUncheckedPieces( tor ) / (double) tor->info.pieceCount);
626
627    tr_torrentGetRates( tor, &s->rateDownload, &s->rateUpload );
628   
629    tr_trackerGetCounts( tc,
630                         &s->completedFromTracker,
631                         &s->leechers, 
632                         &s->seeders );
633
634    s->swarmspeed = tr_rcRate( tor->swarmspeed );
635   
636    s->startDate = tor->startDate;
637    s->activityDate = tor->activityDate;
638
639    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
640    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
641    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
642    s->haveValid       = tr_cpHaveValid( tor->completion );
643    s->haveUnchecked   = tr_cpHaveTotal( tor->completion ) - s->haveValid;
644
645
646    {
647        tr_piece_index_t i;
648        tr_bitfield * peerPieces = tr_peerMgrGetAvailable( tor->handle->peerMgr,
649                                                           tor->info.hash );
650        s->desiredAvailable = 0;
651        for( i=0; i<tor->info.pieceCount; ++i )
652            if( !tor->info.pieces[i].dnd && tr_bitfieldHas( peerPieces, i ) )
653                s->desiredAvailable += tr_cpMissingBlocksInPiece( tor->completion, i );
654        s->desiredAvailable *= tor->blockSize;
655        tr_bitfieldFree( peerPieces );
656    }
657
658    if( s->leftUntilDone > s->desiredAvailable )
659        s->eta = TR_ETA_NOT_AVAIL;
660    else if( s->rateDownload < 0.1 )
661        s->eta = TR_ETA_UNKNOWN;
662    else
663        s->eta = s->leftUntilDone / s->rateDownload / 1024.0;
664
665    s->ratio = tr_getRatio( s->uploadedEver,
666                            s->downloadedEver ? s->downloadedEver : s->haveValid );
667   
668    tr_torrentUnlock( tor );
669
670    return s;
671}
672
673/***
674****
675***/
676
677static uint64_t
678fileBytesCompleted ( const tr_torrent * tor, tr_file_index_t fileIndex )
679{
680    const tr_file * file     =  &tor->info.files[fileIndex];
681    const tr_block_index_t firstBlock       =  file->offset / tor->blockSize;
682    const uint64_t firstBlockOffset =  file->offset % tor->blockSize;
683    const uint64_t lastOffset       =  file->length ? (file->length-1) : 0;
684    const tr_block_index_t lastBlock        = (file->offset + lastOffset) / tor->blockSize;
685    const uint64_t lastBlockOffset  = (file->offset + lastOffset) % tor->blockSize;
686    uint64_t haveBytes = 0;
687
688    assert( tor != NULL );
689    assert( fileIndex < tor->info.fileCount );
690    assert( file->offset + file->length <= tor->info.totalSize );
691    assert( ( firstBlock < tor->blockCount ) || (!file->length && file->offset==tor->info.totalSize) );
692    assert( ( lastBlock < tor->blockCount ) || (!file->length && file->offset==tor->info.totalSize) );
693    assert( firstBlock <= lastBlock );
694    assert( tr_torBlockPiece( tor, firstBlock ) == file->firstPiece );
695    assert( tr_torBlockPiece( tor, lastBlock ) == file->lastPiece );
696
697    if( firstBlock == lastBlock )
698    {
699        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
700            haveBytes += lastBlockOffset + 1 - firstBlockOffset;
701    }
702    else
703    {
704        tr_block_index_t i;
705
706        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
707            haveBytes += tor->blockSize - firstBlockOffset;
708
709        for( i=firstBlock+1; i<lastBlock; ++i )
710            if( tr_cpBlockIsComplete( tor->completion, i ) )
711               haveBytes += tor->blockSize;
712
713        if( tr_cpBlockIsComplete( tor->completion, lastBlock ) )
714            haveBytes += lastBlockOffset + 1;
715    }
716
717    return haveBytes;
718}
719
720tr_file_stat *
721tr_torrentFiles( const tr_torrent * tor, tr_file_index_t * fileCount )
722{
723    tr_file_index_t i;
724    const tr_file_index_t n = tor->info.fileCount;
725    tr_file_stat * files = tr_new0( tr_file_stat, n );
726    tr_file_stat * walk = files;
727
728    for( i=0; i<n; ++i, ++walk )
729    {
730        const tr_file * file = tor->info.files + i;
731
732        walk->bytesCompleted = fileBytesCompleted( tor, i );
733
734        walk->progress = file->length
735            ? walk->bytesCompleted / (float)file->length
736            : 1.0;
737    }
738
739    if( fileCount )
740        *fileCount = n;
741
742    return files;
743}
744
745void
746tr_torrentFilesFree( tr_file_stat * files, tr_file_index_t fileCount UNUSED )
747{
748    tr_free( files );
749}
750
751/***
752****
753***/
754
755tr_peer_stat *
756tr_torrentPeers( const tr_torrent * tor, int * peerCount )
757{
758    tr_peer_stat * ret = NULL;
759
760    if( tor != NULL )
761        ret = tr_peerMgrPeerStats( tor->handle->peerMgr,
762                                   tor->info.hash, peerCount );
763
764    return ret;
765}
766
767void
768tr_torrentPeersFree( tr_peer_stat * peers, int peerCount UNUSED )
769{
770    tr_free( peers );
771}
772
773void tr_torrentAvailability( const tr_torrent * tor, int8_t * tab, int size )
774{
775    return tr_peerMgrTorrentAvailability( tor->handle->peerMgr,
776                                          tor->info.hash,
777                                          tab, size );
778}
779
780void tr_torrentAmountFinished( const tr_torrent * tor, float * tab, int size )
781{
782    int i;
783    float interval;
784    tr_torrentLock( tor );
785
786    interval = (float)tor->info.pieceCount / (float)size;
787    for( i = 0; i < size; i++ )
788    {
789        int piece = i * interval;
790        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
791    }
792
793    tr_torrentUnlock( tor );
794}
795
796void
797tr_torrentResetTransferStats( tr_torrent * tor )
798{
799    tr_torrentLock( tor );
800
801    tor->downloadedPrev += tor->downloadedCur;
802    tor->downloadedCur   = 0;
803    tor->uploadedPrev   += tor->uploadedCur;
804    tor->uploadedCur     = 0;
805    tor->corruptPrev    += tor->corruptCur;
806    tor->corruptCur      = 0;
807
808    tr_torrentUnlock( tor );
809}
810
811
812void
813tr_torrentSetHasPiece( tr_torrent * tor, tr_piece_index_t pieceIndex, int has )
814{
815    tr_torrentLock( tor );
816
817    assert( tor != NULL );
818    assert( pieceIndex < tor->info.pieceCount );
819
820    if( has )
821        tr_cpPieceAdd( tor->completion, pieceIndex );
822    else
823        tr_cpPieceRem( tor->completion, pieceIndex );
824
825    tr_torrentUnlock( tor );
826}
827
828void
829tr_torrentRemoveSaved( tr_torrent * tor )
830{
831    tr_metainfoRemoveSaved( tor->handle, &tor->info );
832
833    tr_torrentRemoveResume( tor );
834}
835
836/***
837****
838***/
839
840static void
841freeTorrent( tr_torrent * tor )
842{
843    tr_torrent * t;
844    tr_handle * h = tor->handle;
845    tr_info * inf = &tor->info;
846
847    assert( tor != NULL );
848    assert( !tor->isRunning );
849
850    tr_globalLock( h );
851
852    tr_peerMgrRemoveTorrent( h->peerMgr, tor->info.hash );
853
854    tr_cpClose( tor->completion );
855
856    tr_rcClose( tor->upload );
857    tr_rcClose( tor->download );
858    tr_rcClose( tor->swarmspeed );
859
860    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
861    tr_trackerFree( tor->tracker );
862    tor->tracker = NULL;
863
864    tr_bitfieldFree( tor->checkedPieces );
865
866    tr_free( tor->destination );
867
868    if( tor == h->torrentList )
869        h->torrentList = tor->next;
870    else for( t=h->torrentList; t!=NULL; t=t->next ) {
871        if( t->next == tor ) {
872            t->next = tor->next;
873            break;
874        }
875    }
876
877    assert( h->torrentCount >= 1 );
878    h->torrentCount--;
879
880    tr_torinf( tor, _( "Closing torrent; %d left" ), h->torrentCount );
881
882    tr_metainfoFree( inf );
883    tr_free( tor );
884
885    tr_globalUnlock( h );
886}
887
888/**
889***  Start/Stop Callback
890**/
891
892static void
893fireActiveChange( tr_torrent * tor, int isRunning )
894{
895    assert( tor != NULL );
896
897    if( tor->active_func != NULL )
898        (tor->active_func)( tor, isRunning, tor->active_func_user_data );
899}
900
901void
902tr_torrentSetActiveCallback( tr_torrent             * tor,
903                             tr_torrent_active_func   func,
904                             void                   * user_data )
905{
906    assert( tor != NULL );
907    tor->active_func = func;
908    tor->active_func_user_data = user_data;
909}
910
911void
912tr_torrentClearActiveCallback( tr_torrent * torrent )
913{
914    tr_torrentSetActiveCallback( torrent, NULL, NULL );
915}
916
917
918static void
919checkAndStartImpl( void * vtor )
920{
921    tr_torrent * tor = vtor;
922
923    tr_globalLock( tor->handle );
924
925    tor->isRunning  = 1;
926    fireActiveChange( tor, tor->isRunning );
927    *tor->errorString = '\0';
928    tr_torrentResetTransferStats( tor );
929    tor->cpStatus = tr_cpGetStatus( tor->completion );
930    tr_torrentSaveResume( tor );
931    tor->startDate = tr_date( );
932    tr_trackerStart( tor->tracker );
933    tr_peerMgrStartTorrent( tor->handle->peerMgr, tor->info.hash );
934
935    tr_globalUnlock( tor->handle );
936}
937
938static void
939checkAndStartCB( tr_torrent * tor )
940{
941    tr_runInEventThread( tor->handle, checkAndStartImpl, tor );
942}
943
944void
945tr_torrentStart( tr_torrent * tor )
946{
947    tr_globalLock( tor->handle );
948
949    if( !tor->isRunning )
950    {
951        tr_torrentLoadResume( tor, TR_FR_PROGRESS, NULL );
952        tor->isRunning = 1;
953        tr_verifyAdd( tor, checkAndStartCB );
954    }
955
956    tr_globalUnlock( tor->handle );
957}
958
959static void
960torrentRecheckDoneImpl( void * vtor )
961{
962    tr_torrentRecheckCompleteness( vtor );
963}
964static void
965torrentRecheckDoneCB( tr_torrent * tor )
966{
967    tr_runInEventThread( tor->handle, torrentRecheckDoneImpl, tor );
968}
969void
970tr_torrentVerify( tr_torrent * tor )
971{
972    tr_globalLock( tor->handle );
973
974    tr_verifyRemove( tor );
975    tr_torrentUncheck( tor );
976    tr_verifyAdd( tor, torrentRecheckDoneCB );
977
978    tr_globalUnlock( tor->handle );
979}
980
981
982static void
983stopTorrent( void * vtor )
984{
985    tr_file_index_t i;
986
987    tr_torrent * tor = vtor;
988    tr_verifyRemove( tor );
989    tr_peerMgrStopTorrent( tor->handle->peerMgr, tor->info.hash );
990    tr_trackerStop( tor->tracker );
991    fireActiveChange( tor, 0 );
992
993    for( i=0; i<tor->info.fileCount; ++i )
994    {
995        char path[MAX_PATH_LENGTH];
996        const tr_file * file = &tor->info.files[i];
997        tr_buildPath( path, sizeof(path), tor->destination, file->name, NULL );
998        tr_fdFileClose( path );
999    }
1000}
1001
1002void
1003tr_torrentStop( tr_torrent * tor )
1004{
1005    tr_globalLock( tor->handle );
1006
1007    tor->isRunning = 0;
1008    if( !tor->isDeleting )
1009        tr_torrentSaveResume( tor );
1010    tr_runInEventThread( tor->handle, stopTorrent, tor );
1011
1012    tr_globalUnlock( tor->handle );
1013}
1014
1015static void
1016closeTorrent( void * vtor )
1017{
1018    tr_torrent * tor = vtor;
1019    tr_torrentSaveResume( tor );
1020    tor->isRunning = 0;
1021    stopTorrent( tor );
1022    if( tor->isDeleting )
1023        tr_torrentRemoveSaved( tor );
1024    freeTorrent( tor );
1025}
1026
1027void
1028tr_torrentClose( tr_torrent * tor )
1029{
1030    if( tor != NULL )
1031    {
1032        tr_handle * handle = tor->handle;
1033        tr_globalLock( handle );
1034
1035        tr_torrentClearStatusCallback( tor );
1036        tr_runInEventThread( handle, closeTorrent, tor );
1037
1038        tr_globalUnlock( handle );
1039    }
1040}
1041
1042void
1043tr_torrentDelete( tr_torrent * tor )
1044{
1045    tor->isDeleting = 1;
1046    tr_torrentClose( tor );
1047}
1048
1049
1050/**
1051***  Completeness
1052**/
1053
1054static const char *
1055getCompletionString( int type )
1056{
1057    switch( type )
1058    {
1059        /* Translators: this is a minor point that's safe to skip over, but FYI:
1060           "Complete" and "Done" are specific, different terms in Transmission:
1061           "Complete" means we've downloaded every file in the torrent.
1062           "Done" means we're done downloading the files we wanted, but NOT all that exist */
1063        case TR_CP_DONE:     return _( "Done" );
1064        case TR_CP_COMPLETE: return _( "Complete" );
1065        default:             return _( "Incomplete" );
1066    }
1067}
1068
1069static void
1070fireStatusChange( tr_torrent * tor, cp_status_t status )
1071{
1072    assert( tor != NULL );
1073    assert( status==TR_CP_INCOMPLETE || status==TR_CP_DONE || status==TR_CP_COMPLETE );
1074
1075    if( tor->status_func != NULL )
1076        (tor->status_func)( tor, status, tor->status_func_user_data );
1077}
1078
1079void
1080tr_torrentSetStatusCallback( tr_torrent             * tor,
1081                             tr_torrent_status_func   func,
1082                             void                   * user_data )
1083{
1084    assert( tor != NULL );
1085    tor->status_func = func;
1086    tor->status_func_user_data = user_data;
1087}
1088
1089void
1090tr_torrentClearStatusCallback( tr_torrent * torrent )
1091{
1092    tr_torrentSetStatusCallback( torrent, NULL, NULL );
1093}
1094
1095void
1096tr_torrentRecheckCompleteness( tr_torrent * tor )
1097{
1098    cp_status_t cpStatus;
1099
1100    tr_torrentLock( tor );
1101
1102    cpStatus = tr_cpGetStatus( tor->completion );
1103
1104    if( cpStatus != tor->cpStatus )
1105    {
1106        const int recentChange = tor->downloadedCur != 0;
1107
1108        if( recentChange )
1109        {
1110            tr_torinf( tor, _( "State changed from \"%s\" to \"%s\"" ),
1111                            getCompletionString( tor->cpStatus ),
1112                            getCompletionString( cpStatus ) );
1113        }
1114
1115        tor->cpStatus = cpStatus;
1116        fireStatusChange( tor, cpStatus );
1117
1118        if( recentChange && ( cpStatus == TR_CP_COMPLETE ) )
1119            tr_trackerCompleted( tor->tracker );
1120
1121        tr_torrentSaveResume( tor );
1122    }
1123
1124    tr_torrentUnlock( tor );
1125}
1126
1127int
1128tr_torrentIsSeed( const tr_torrent * tor )
1129{
1130    return tor->cpStatus==TR_CP_COMPLETE || tor->cpStatus==TR_CP_DONE;
1131}
1132
1133/**
1134***  File priorities
1135**/
1136
1137void
1138tr_torrentInitFilePriority( tr_torrent      * tor,
1139                            tr_file_index_t   fileIndex,
1140                            tr_priority_t     priority )
1141{
1142    tr_piece_index_t i;
1143    tr_file * file;
1144
1145    assert( tor != NULL );
1146    assert( fileIndex < tor->info.fileCount );
1147    assert( priority==TR_PRI_LOW || priority==TR_PRI_NORMAL || priority==TR_PRI_HIGH );
1148
1149    file = &tor->info.files[fileIndex];
1150    file->priority = priority;
1151    for( i=file->firstPiece; i<=file->lastPiece; ++i )
1152      tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1153}
1154
1155void
1156tr_torrentSetFilePriorities( tr_torrent       * tor,
1157                             tr_file_index_t  * files,
1158                             tr_file_index_t    fileCount,
1159                             tr_priority_t      priority )
1160{
1161    tr_file_index_t i;
1162    tr_torrentLock( tor );
1163
1164    for( i=0; i<fileCount; ++i )
1165        tr_torrentInitFilePriority( tor, files[i], priority );
1166
1167    tr_torrentSaveResume( tor );
1168    tr_torrentUnlock( tor );
1169}
1170
1171tr_priority_t
1172tr_torrentGetFilePriority( const tr_torrent *  tor, tr_file_index_t file )
1173{
1174    tr_priority_t ret;
1175
1176    tr_torrentLock( tor );
1177    assert( tor != NULL );
1178    assert( file < tor->info.fileCount );
1179    ret = tor->info.files[file].priority;
1180    tr_torrentUnlock( tor );
1181
1182    return ret;
1183}
1184
1185tr_priority_t*
1186tr_torrentGetFilePriorities( const tr_torrent * tor )
1187{
1188    tr_file_index_t i;
1189    tr_priority_t * p;
1190
1191    tr_torrentLock( tor );
1192    p = tr_new0( tr_priority_t, tor->info.fileCount );
1193    for( i=0; i<tor->info.fileCount; ++i )
1194        p[i] = tor->info.files[i].priority;
1195    tr_torrentUnlock( tor );
1196
1197    return p;
1198}
1199
1200/**
1201***  File DND
1202**/
1203
1204int
1205tr_torrentGetFileDL( const tr_torrent * tor,
1206                     tr_file_index_t    file )
1207{
1208    int doDownload;
1209    tr_torrentLock( tor );
1210
1211    assert( file < tor->info.fileCount );
1212    doDownload = !tor->info.files[file].dnd;
1213
1214    tr_torrentUnlock( tor );
1215    return doDownload != 0;
1216}
1217
1218static void
1219setFileDND( tr_torrent      * tor,
1220            tr_file_index_t   fileIndex,
1221            int               doDownload )
1222{
1223    tr_file * file;
1224    const int dnd = !doDownload;
1225    tr_piece_index_t firstPiece, firstPieceDND;
1226    tr_piece_index_t lastPiece, lastPieceDND;
1227    tr_file_index_t i;
1228
1229    file = &tor->info.files[fileIndex];
1230    file->dnd = dnd;
1231    firstPiece = file->firstPiece;
1232    lastPiece = file->lastPiece;
1233
1234    /* can't set the first piece to DND unless
1235       every file using that piece is DND */
1236    firstPieceDND = dnd;
1237    if( fileIndex > 0 ) {
1238        for( i=fileIndex-1; firstPieceDND; --i ) {
1239            if( tor->info.files[i].lastPiece != firstPiece )
1240                break;
1241            firstPieceDND = tor->info.files[i].dnd;
1242            if( !i )
1243                break;
1244        }
1245    }
1246
1247    /* can't set the last piece to DND unless
1248       every file using that piece is DND */
1249    lastPieceDND = dnd;
1250    for( i=fileIndex+1; lastPieceDND && i<tor->info.fileCount; ++i ) {
1251        if( tor->info.files[i].firstPiece != lastPiece )
1252            break;
1253        lastPieceDND = tor->info.files[i].dnd;
1254    }
1255
1256    if( firstPiece == lastPiece )
1257    {
1258        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1259    }
1260    else
1261    {
1262        tr_piece_index_t pp;
1263        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1264        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1265        for( pp=firstPiece+1; pp<lastPiece; ++pp )
1266            tor->info.pieces[pp].dnd = dnd;
1267    }
1268}
1269
1270void
1271tr_torrentInitFileDLs ( tr_torrent       * tor,
1272                        tr_file_index_t  * files,
1273                        tr_file_index_t    fileCount,
1274                        int                doDownload )
1275{
1276    tr_file_index_t i;
1277    tr_torrentLock( tor );
1278
1279    for( i=0; i<fileCount; ++i )
1280        setFileDND( tor, files[i], doDownload );
1281    tr_cpInvalidateDND ( tor->completion );
1282
1283    tr_torrentUnlock( tor );
1284}
1285
1286void
1287tr_torrentSetFileDLs ( tr_torrent      * tor,
1288                       tr_file_index_t * files,
1289                       tr_file_index_t   fileCount,
1290                       int               doDownload )
1291{
1292    tr_torrentLock( tor );
1293    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1294    tr_torrentSaveResume( tor );
1295    tr_torrentUnlock( tor );
1296}
1297
1298/***
1299****
1300***/
1301
1302void
1303tr_torrentSetMaxConnectedPeers( tr_torrent  * tor,
1304                                uint16_t      maxConnectedPeers )
1305{
1306    tor->maxConnectedPeers = maxConnectedPeers;
1307}
1308
1309uint16_t
1310tr_torrentGetMaxConnectedPeers( const tr_torrent  * tor )
1311{
1312    return tor->maxConnectedPeers;
1313}
1314
1315/***
1316****
1317***/
1318
1319tr_block_index_t
1320_tr_block( const tr_torrent  * tor,
1321           tr_piece_index_t    index,
1322           uint32_t            offset )
1323{
1324    const tr_info * inf = &tor->info;
1325    tr_block_index_t ret;
1326    ret = index;
1327    ret *= ( inf->pieceSize / tor->blockSize );
1328    ret += offset / tor->blockSize;
1329    return ret;
1330}
1331
1332int
1333tr_torrentReqIsValid( const tr_torrent * tor,
1334                      tr_piece_index_t   index,
1335                      uint32_t           offset,
1336                      uint32_t           length )
1337{
1338    int err = 0;
1339
1340    if( index >= tor->info.pieceCount )
1341        err = 1;
1342    else if ( offset >= tr_torPieceCountBytes( tor, index ) )
1343        err = 2;
1344    else if( length > MAX_BLOCK_SIZE )
1345        err = 3;
1346    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1347        err = 4;
1348
1349    if( err )
1350    {
1351        fprintf( stderr, "(ticket #751) err is %d\n", err );
1352        fprintf( stderr, "(ticket #751) req.index is %"PRIu32"\n", index );
1353        fprintf( stderr, "(ticket #751) req.offset is %"PRIu32"\n", offset );
1354        fprintf( stderr, "(ticket #751) req.length is %"PRIu32"\n", length );
1355        fprintf( stderr, "(ticket #751) tor->info.totalSize is %"PRIu64"\n", tor->info.totalSize );
1356        fprintf( stderr, "(ticket #751) tor->info.pieceCount is %d\n", tor->info.pieceCount );
1357        fprintf( stderr, "(ticket #751) tr_torPieceCountBytes is %d\n", tr_torPieceCountBytes( tor, index ) );
1358        fprintf( stderr, "(ticket #751) tr_pieceOffset is %"PRIu64"\n", tr_pieceOffset( tor, index, offset, length ) );
1359    }
1360
1361    return !err;
1362}
1363
1364
1365uint64_t
1366tr_pieceOffset( const tr_torrent * tor,
1367                tr_piece_index_t   index,
1368                uint32_t           offset,
1369                uint32_t           length )
1370{
1371    uint64_t ret;
1372    ret = tor->info.pieceSize;
1373    ret *= index;
1374    ret += offset;
1375    ret += length;
1376    return ret;
1377}
1378
1379/***
1380****
1381***/
1382
1383int
1384tr_torrentIsPieceChecked( const tr_torrent * tor, tr_piece_index_t piece )
1385{
1386    return tr_bitfieldHas( tor->checkedPieces, piece );
1387}
1388
1389void
1390tr_torrentSetPieceChecked( tr_torrent * tor, tr_piece_index_t piece, int isChecked )
1391{
1392    if( isChecked )
1393        tr_bitfieldAdd( tor->checkedPieces, piece );
1394    else
1395        tr_bitfieldRem( tor->checkedPieces, piece );
1396}
1397
1398void
1399tr_torrentSetFileChecked( tr_torrent * tor, tr_file_index_t fileIndex, int isChecked )
1400{
1401    const tr_file * file = &tor->info.files[fileIndex];
1402    const tr_piece_index_t begin = file->firstPiece;
1403    const tr_piece_index_t end = file->lastPiece + 1;
1404
1405    if( isChecked )
1406        tr_bitfieldAddRange ( tor->checkedPieces, begin, end );
1407    else
1408        tr_bitfieldRemRange ( tor->checkedPieces, begin, end );
1409}
1410
1411int
1412tr_torrentIsFileChecked( const tr_torrent * tor, tr_file_index_t fileIndex )
1413{
1414    const tr_file * file = &tor->info.files[fileIndex];
1415    const tr_piece_index_t begin = file->firstPiece;
1416    const tr_piece_index_t end = file->lastPiece + 1;
1417    tr_piece_index_t i;
1418    int isChecked = TRUE;
1419
1420    for( i=begin; isChecked && i<end; ++i )
1421        if( !tr_torrentIsPieceChecked( tor, i ) )
1422            isChecked = FALSE;
1423
1424    return isChecked;
1425}
1426
1427void
1428tr_torrentUncheck( tr_torrent * tor )
1429{
1430    tr_bitfieldRemRange ( tor->checkedPieces, 0, tor->info.pieceCount );
1431}
1432
1433int
1434tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1435{
1436    return tor->info.pieceCount - tr_bitfieldCountTrueBits( tor->checkedPieces );
1437}
1438
1439time_t*
1440tr_torrentGetMTimes( const tr_torrent * tor, int * setme_n )
1441{
1442    int i;
1443    const int n = tor->info.fileCount;
1444    time_t * m = tr_new0( time_t, n );
1445
1446    for( i=0; i<n; ++i ) {
1447        char fname[MAX_PATH_LENGTH];
1448        struct stat sb;
1449        tr_buildPath( fname, sizeof(fname),
1450                      tor->destination, tor->info.files[i].name, NULL );
1451        if ( !stat( fname, &sb ) ) {
1452#ifdef SYS_DARWIN
1453            m[i] = sb.st_mtimespec.tv_sec;
1454#else
1455            m[i] = sb.st_mtime;
1456#endif
1457        }
1458    }
1459
1460    *setme_n = n;
1461    return m;
1462}
Note: See TracBrowser for help on using the repository browser.