source: trunk/libtransmission/torrent.c @ 5457

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

remove `TR_STATUS_DONE' from libtransmission's public API. It's useful as an internal state but not for code calling libtransmission.

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