source: trunk/libtransmission/torrent.c @ 5357

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

#811: fix r5329 error in trunk.

  • Property svn:keywords set to Date Rev Author Id
File size: 36.4 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 5357 2008-03-24 16:10:04Z 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 if( tor->cpStatus == TR_CP_DONE )
609        s->status = TR_STATUS_DONE;
610    else
611        s->status = TR_STATUS_SEED;
612
613    s->recheckProgress =
614        1.0 - (tr_torrentCountUncheckedPieces( tor ) / (double) tor->info.pieceCount);
615
616    tr_torrentGetRates( tor, &s->rateDownload, &s->rateUpload );
617   
618    tr_trackerGetCounts( tc,
619                         &s->completedFromTracker,
620                         &s->leechers, 
621                         &s->seeders );
622
623    s->swarmspeed = tr_rcRate( tor->swarmspeed );
624   
625    s->startDate = tor->startDate;
626    s->activityDate = tor->activityDate;
627
628    s->eta = s->rateDownload < 0.1
629        ? -1.0f
630        : (s->leftUntilDone / s->rateDownload / 1024.0);
631
632    s->corruptEver     = tor->corruptCur    + tor->corruptPrev;
633    s->downloadedEver  = tor->downloadedCur + tor->downloadedPrev;
634    s->uploadedEver    = tor->uploadedCur   + tor->uploadedPrev;
635    s->haveValid       = tr_cpHaveValid( tor->completion );
636    s->haveUnchecked   = tr_cpHaveTotal( tor->completion ) - s->haveValid;
637
638
639    {
640        tr_piece_index_t i;
641        tr_bitfield * availablePieces = tr_peerMgrGetAvailable( tor->handle->peerMgr,
642                                                                tor->info.hash );
643        s->desiredSize = 0;
644        s->desiredAvailable = 0;
645
646        for( i=0; i<tor->info.pieceCount; ++i ) {
647            if( !tor->info.pieces[i].dnd ) {
648                const uint64_t byteCount = tr_torPieceCountBytes( tor, i );
649                s->desiredSize += byteCount;
650                if( tr_bitfieldHas( availablePieces, i ) )
651                    s->desiredAvailable += byteCount;
652            }
653        }
654
655        /* "availablePieces" can miss our unverified blocks... */
656        if( s->desiredAvailable < s->haveValid + s->haveUnchecked )
657            s->desiredAvailable = s->haveValid + s->haveUnchecked;
658
659        tr_bitfieldFree( availablePieces );
660    }
661
662    s->ratio = tr_getRatio( s->uploadedEver,
663                            s->downloadedEver ? s->downloadedEver : s->haveValid );
664   
665    tr_torrentUnlock( tor );
666
667    return s;
668}
669
670/***
671****
672***/
673
674static uint64_t
675fileBytesCompleted ( const tr_torrent * tor, tr_file_index_t fileIndex )
676{
677    const tr_file * file     =  &tor->info.files[fileIndex];
678    const tr_block_index_t firstBlock       =  file->offset / tor->blockSize;
679    const uint64_t firstBlockOffset =  file->offset % tor->blockSize;
680    const uint64_t lastOffset       =  file->length ? (file->length-1) : 0;
681    const tr_block_index_t lastBlock        = (file->offset + lastOffset) / tor->blockSize;
682    const uint64_t lastBlockOffset  = (file->offset + lastOffset) % tor->blockSize;
683    uint64_t haveBytes = 0;
684
685    assert( tor != NULL );
686    assert( fileIndex < tor->info.fileCount );
687    assert( file->offset + file->length <= tor->info.totalSize );
688    assert( ( firstBlock < tor->blockCount ) || (!file->length && file->offset==tor->info.totalSize) );
689    assert( ( lastBlock < tor->blockCount ) || (!file->length && file->offset==tor->info.totalSize) );
690    assert( firstBlock <= lastBlock );
691    assert( tr_torBlockPiece( tor, firstBlock ) == file->firstPiece );
692    assert( tr_torBlockPiece( tor, lastBlock ) == file->lastPiece );
693
694    if( firstBlock == lastBlock )
695    {
696        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
697            haveBytes += lastBlockOffset + 1 - firstBlockOffset;
698    }
699    else
700    {
701        tr_block_index_t i;
702
703        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
704            haveBytes += tor->blockSize - firstBlockOffset;
705
706        for( i=firstBlock+1; i<lastBlock; ++i )
707            if( tr_cpBlockIsComplete( tor->completion, i ) )
708               haveBytes += tor->blockSize;
709
710        if( tr_cpBlockIsComplete( tor->completion, lastBlock ) )
711            haveBytes += lastBlockOffset + 1;
712    }
713
714    return haveBytes;
715}
716
717tr_file_stat *
718tr_torrentFiles( const tr_torrent * tor, tr_file_index_t * fileCount )
719{
720    tr_file_index_t i;
721    const tr_file_index_t n = tor->info.fileCount;
722    tr_file_stat * files = tr_new0( tr_file_stat, n );
723    tr_file_stat * walk = files;
724
725    for( i=0; i<n; ++i, ++walk )
726    {
727        const tr_file * file = tor->info.files + i;
728
729        walk->bytesCompleted = fileBytesCompleted( tor, i );
730
731        walk->progress = file->length
732            ? walk->bytesCompleted / (float)file->length
733            : 1.0;
734    }
735
736    if( fileCount )
737        *fileCount = n;
738
739    return files;
740}
741
742void
743tr_torrentFilesFree( tr_file_stat * files, tr_file_index_t fileCount UNUSED )
744{
745    tr_free( files );
746}
747
748/***
749****
750***/
751
752tr_peer_stat *
753tr_torrentPeers( const tr_torrent * tor, int * peerCount )
754{
755    tr_peer_stat * ret = NULL;
756
757    if( tor != NULL )
758        ret = tr_peerMgrPeerStats( tor->handle->peerMgr,
759                                   tor->info.hash, peerCount );
760
761    return ret;
762}
763
764void
765tr_torrentPeersFree( tr_peer_stat * peers, int peerCount UNUSED )
766{
767    tr_free( peers );
768}
769
770void tr_torrentAvailability( const tr_torrent * tor, int8_t * tab, int size )
771{
772    return tr_peerMgrTorrentAvailability( tor->handle->peerMgr,
773                                          tor->info.hash,
774                                          tab, size );
775}
776
777void tr_torrentAmountFinished( const tr_torrent * tor, float * tab, int size )
778{
779    int i;
780    float interval;
781    tr_torrentLock( tor );
782
783    interval = (float)tor->info.pieceCount / (float)size;
784    for( i = 0; i < size; i++ )
785    {
786        int piece = i * interval;
787        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
788    }
789
790    tr_torrentUnlock( tor );
791}
792
793void
794tr_torrentResetTransferStats( tr_torrent * tor )
795{
796    tr_torrentLock( tor );
797
798    tor->downloadedPrev += tor->downloadedCur;
799    tor->downloadedCur   = 0;
800    tor->uploadedPrev   += tor->uploadedCur;
801    tor->uploadedCur     = 0;
802    tor->corruptPrev    += tor->corruptCur;
803    tor->corruptCur      = 0;
804
805    tr_torrentUnlock( tor );
806}
807
808
809void
810tr_torrentSetHasPiece( tr_torrent * tor, tr_piece_index_t pieceIndex, int has )
811{
812    tr_torrentLock( tor );
813
814    assert( tor != NULL );
815    assert( pieceIndex < tor->info.pieceCount );
816
817    if( has )
818        tr_cpPieceAdd( tor->completion, pieceIndex );
819    else
820        tr_cpPieceRem( tor->completion, pieceIndex );
821
822    tr_torrentUnlock( tor );
823}
824
825void
826tr_torrentRemoveSaved( tr_torrent * tor )
827{
828    tr_metainfoRemoveSaved( tor->info.hashString, tor->handle->tag );
829
830    tr_fastResumeRemove( tor );
831}
832
833/***
834****
835***/
836
837static void
838freeTorrent( tr_torrent * tor )
839{
840    tr_torrent * t;
841    tr_handle * h = tor->handle;
842    tr_info * inf = &tor->info;
843
844    assert( tor != NULL );
845    assert( !tor->isRunning );
846
847    tr_globalLock( h );
848
849    tr_peerMgrRemoveTorrent( h->peerMgr, tor->info.hash );
850
851    tr_cpClose( tor->completion );
852
853    tr_rcClose( tor->upload );
854    tr_rcClose( tor->download );
855    tr_rcClose( tor->swarmspeed );
856
857    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
858    tr_trackerFree( tor->tracker );
859    tor->tracker = NULL;
860
861    tr_bitfieldFree( tor->checkedPieces );
862
863    tr_free( tor->destination );
864
865    if( tor == h->torrentList )
866        h->torrentList = tor->next;
867    else for( t=h->torrentList; t!=NULL; t=t->next ) {
868        if( t->next == tor ) {
869            t->next = tor->next;
870            break;
871        }
872    }
873
874    assert( h->torrentCount >= 1 );
875    h->torrentCount--;
876
877    tr_torinf( tor, _( "Closing torrent; %d left" ), h->torrentCount );
878
879    tr_metainfoFree( inf );
880    tr_free( tor );
881
882    tr_globalUnlock( h );
883}
884
885/**
886***  Start/Stop Callback
887**/
888
889static void
890fireActiveChange( tr_torrent * tor, int isRunning )
891{
892    assert( tor != NULL );
893
894    if( tor->active_func != NULL )
895        (tor->active_func)( tor, isRunning, tor->active_func_user_data );
896}
897
898void
899tr_torrentSetActiveCallback( tr_torrent             * tor,
900                             tr_torrent_active_func   func,
901                             void                   * user_data )
902{
903    assert( tor != NULL );
904    tor->active_func = func;
905    tor->active_func_user_data = user_data;
906}
907
908void
909tr_torrentClearActiveCallback( tr_torrent * torrent )
910{
911    tr_torrentSetActiveCallback( torrent, NULL, NULL );
912}
913
914
915static void
916checkAndStartImpl( void * vtor )
917{
918    tr_torrent * tor = vtor;
919
920    tr_globalLock( tor->handle );
921
922    tor->isRunning  = 1;
923    fireActiveChange( tor, tor->isRunning );
924    *tor->errorString = '\0';
925    tr_torrentResetTransferStats( tor );
926    tor->cpStatus = tr_cpGetStatus( tor->completion );
927    saveFastResumeNow( tor );
928    tor->startDate = tr_date( );
929    tr_trackerStart( tor->tracker );
930    tr_peerMgrStartTorrent( tor->handle->peerMgr, tor->info.hash );
931
932    tr_globalUnlock( tor->handle );
933}
934
935static void
936checkAndStartCB( tr_torrent * tor )
937{
938    tr_runInEventThread( tor->handle, checkAndStartImpl, tor );
939}
940
941void
942tr_torrentStart( tr_torrent * tor )
943{
944    tr_globalLock( tor->handle );
945
946    if( !tor->isRunning )
947    {
948        tr_fastResumeLoad( tor, TR_FR_PROGRESS, NULL );
949        tor->isRunning = 1;
950        tr_verifyAdd( tor, checkAndStartCB );
951    }
952
953    tr_globalUnlock( tor->handle );
954}
955
956static void
957torrentRecheckDoneImpl( void * vtor )
958{
959    tr_torrentRecheckCompleteness( vtor );
960}
961static void
962torrentRecheckDoneCB( tr_torrent * tor )
963{
964    tr_runInEventThread( tor->handle, torrentRecheckDoneImpl, tor );
965}
966void
967tr_torrentVerify( tr_torrent * tor )
968{
969    tr_globalLock( tor->handle );
970
971    tr_verifyRemove( tor );
972    tr_torrentUncheck( tor );
973    tr_verifyAdd( tor, torrentRecheckDoneCB );
974
975    tr_globalUnlock( tor->handle );
976}
977
978
979static void
980stopTorrent( void * vtor )
981{
982    tr_file_index_t i;
983
984    tr_torrent * tor = vtor;
985    tr_verifyRemove( tor );
986    tr_peerMgrStopTorrent( tor->handle->peerMgr, tor->info.hash );
987    tr_trackerStop( tor->tracker );
988    fireActiveChange( tor, 0 );
989
990    for( i=0; i<tor->info.fileCount; ++i )
991    {
992        char path[MAX_PATH_LENGTH];
993        const tr_file * file = &tor->info.files[i];
994        tr_buildPath( path, sizeof(path), tor->destination, file->name, NULL );
995        tr_fdFileClose( path );
996    }
997}
998
999void
1000tr_torrentStop( tr_torrent * tor )
1001{
1002    tr_globalLock( tor->handle );
1003
1004    if( !tor->isDeleting )
1005        saveFastResumeNow( tor );
1006    tor->isRunning = 0;
1007    tr_runInEventThread( tor->handle, stopTorrent, tor );
1008
1009    tr_globalUnlock( tor->handle );
1010}
1011
1012static void
1013closeTorrent( void * vtor )
1014{
1015    tr_torrent * tor = vtor;
1016    saveFastResumeNow( tor );
1017    tor->isRunning = 0;
1018    stopTorrent( tor );
1019    if( tor->isDeleting )
1020        tr_torrentRemoveSaved( tor );
1021    freeTorrent( tor );
1022}
1023
1024void
1025tr_torrentClose( tr_torrent * tor )
1026{
1027    if( tor != NULL )
1028    {
1029        tr_handle * handle = tor->handle;
1030        tr_globalLock( handle );
1031
1032        tr_torrentClearStatusCallback( tor );
1033        tr_runInEventThread( handle, closeTorrent, tor );
1034
1035        tr_globalUnlock( handle );
1036    }
1037}
1038
1039void
1040tr_torrentDelete( tr_torrent * tor )
1041{
1042    tor->isDeleting = 1;
1043    tr_torrentClose( tor );
1044}
1045
1046
1047/**
1048***  Completeness
1049**/
1050
1051static const char *
1052getCompletionString( int type )
1053{
1054    switch( type )
1055    {
1056        /* Translators: this is a minor point that's safe to skip over, but FYI:
1057           "Complete" and "Done" are specific, different terms in Transmission:
1058           "Complete" means we've downloaded every file in the torrent.
1059           "Done" means we're done downloading the files we wanted, but NOT all that exist */
1060        case TR_CP_DONE:     return _( "Done" );
1061        case TR_CP_COMPLETE: return _( "Complete" );
1062        default:             return _( "Incomplete" );
1063    }
1064}
1065
1066static void
1067fireStatusChange( tr_torrent * tor, cp_status_t status )
1068{
1069    assert( tor != NULL );
1070    assert( status==TR_CP_INCOMPLETE || status==TR_CP_DONE || status==TR_CP_COMPLETE );
1071
1072    if( tor->status_func != NULL )
1073        (tor->status_func)( tor, status, tor->status_func_user_data );
1074}
1075
1076void
1077tr_torrentSetStatusCallback( tr_torrent             * tor,
1078                             tr_torrent_status_func   func,
1079                             void                   * user_data )
1080{
1081    assert( tor != NULL );
1082    tor->status_func = func;
1083    tor->status_func_user_data = user_data;
1084}
1085
1086void
1087tr_torrentClearStatusCallback( tr_torrent * torrent )
1088{
1089    tr_torrentSetStatusCallback( torrent, NULL, NULL );
1090}
1091
1092void
1093tr_torrentRecheckCompleteness( tr_torrent * tor )
1094{
1095    cp_status_t cpStatus;
1096
1097    tr_torrentLock( tor );
1098
1099    cpStatus = tr_cpGetStatus( tor->completion );
1100
1101    if( cpStatus != tor->cpStatus )
1102    {
1103        const int recentChange = tor->downloadedCur != 0;
1104
1105        if( recentChange )
1106        {
1107            tr_torinf( tor, _( "State changed from \"%s\" to \"%s\"" ),
1108                            getCompletionString( tor->cpStatus ),
1109                            getCompletionString( cpStatus ) );
1110        }
1111
1112        tor->cpStatus = cpStatus;
1113        fireStatusChange( tor, cpStatus );
1114
1115        if( recentChange && ( cpStatus == TR_CP_COMPLETE ) )
1116            tr_trackerCompleted( tor->tracker );
1117
1118        saveFastResumeNow( tor );
1119    }
1120
1121    tr_torrentUnlock( tor );
1122}
1123
1124int
1125tr_torrentIsSeed( const tr_torrent * tor )
1126{
1127    return tor->cpStatus==TR_CP_COMPLETE || tor->cpStatus==TR_CP_DONE;
1128}
1129
1130/**
1131***  File priorities
1132**/
1133
1134void
1135tr_torrentInitFilePriority( tr_torrent      * tor,
1136                            tr_file_index_t   fileIndex,
1137                            tr_priority_t     priority )
1138{
1139    tr_piece_index_t i;
1140    tr_file * file;
1141
1142    assert( tor != NULL );
1143    assert( fileIndex < tor->info.fileCount );
1144    assert( priority==TR_PRI_LOW || priority==TR_PRI_NORMAL || priority==TR_PRI_HIGH );
1145
1146    file = &tor->info.files[fileIndex];
1147    file->priority = priority;
1148    for( i=file->firstPiece; i<=file->lastPiece; ++i )
1149      tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1150}
1151
1152void
1153tr_torrentSetFilePriorities( tr_torrent       * tor,
1154                             tr_file_index_t  * files,
1155                             tr_file_index_t    fileCount,
1156                             tr_priority_t      priority )
1157{
1158    tr_file_index_t i;
1159    tr_torrentLock( tor );
1160
1161    for( i=0; i<fileCount; ++i )
1162        tr_torrentInitFilePriority( tor, files[i], priority );
1163
1164    saveFastResumeNow( tor );
1165    tr_torrentUnlock( tor );
1166}
1167
1168tr_priority_t
1169tr_torrentGetFilePriority( const tr_torrent *  tor, tr_file_index_t file )
1170{
1171    tr_priority_t ret;
1172
1173    tr_torrentLock( tor );
1174    assert( tor != NULL );
1175    assert( file < tor->info.fileCount );
1176    ret = tor->info.files[file].priority;
1177    tr_torrentUnlock( tor );
1178
1179    return ret;
1180}
1181
1182tr_priority_t*
1183tr_torrentGetFilePriorities( const tr_torrent * tor )
1184{
1185    tr_file_index_t i;
1186    tr_priority_t * p;
1187
1188    tr_torrentLock( tor );
1189    p = tr_new0( tr_priority_t, tor->info.fileCount );
1190    for( i=0; i<tor->info.fileCount; ++i )
1191        p[i] = tor->info.files[i].priority;
1192    tr_torrentUnlock( tor );
1193
1194    return p;
1195}
1196
1197/**
1198***  File DND
1199**/
1200
1201int
1202tr_torrentGetFileDL( const tr_torrent * tor,
1203                     tr_file_index_t    file )
1204{
1205    int doDownload;
1206    tr_torrentLock( tor );
1207
1208    assert( file < tor->info.fileCount );
1209    doDownload = !tor->info.files[file].dnd;
1210
1211    tr_torrentUnlock( tor );
1212    return doDownload != 0;
1213}
1214
1215static void
1216setFileDND( tr_torrent      * tor,
1217            tr_file_index_t   fileIndex,
1218            int               doDownload )
1219{
1220    tr_file * file;
1221    const int dnd = !doDownload;
1222    tr_piece_index_t firstPiece, firstPieceDND;
1223    tr_piece_index_t lastPiece, lastPieceDND;
1224    tr_file_index_t i;
1225
1226    file = &tor->info.files[fileIndex];
1227    file->dnd = dnd;
1228    firstPiece = file->firstPiece;
1229    lastPiece = file->lastPiece;
1230
1231    /* can't set the first piece to DND unless
1232       every file using that piece is DND */
1233    firstPieceDND = dnd;
1234    if( fileIndex > 0 ) {
1235        for( i=fileIndex-1; firstPieceDND; --i ) {
1236            if( tor->info.files[i].lastPiece != firstPiece )
1237                break;
1238            firstPieceDND = tor->info.files[i].dnd;
1239            if( !i )
1240                break;
1241        }
1242    }
1243
1244    /* can't set the last piece to DND unless
1245       every file using that piece is DND */
1246    lastPieceDND = dnd;
1247    for( i=fileIndex+1; lastPieceDND && i<tor->info.fileCount; ++i ) {
1248        if( tor->info.files[i].firstPiece != lastPiece )
1249            break;
1250        lastPieceDND = tor->info.files[i].dnd;
1251    }
1252
1253    if( firstPiece == lastPiece )
1254    {
1255        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1256    }
1257    else
1258    {
1259        tr_piece_index_t pp;
1260        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1261        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1262        for( pp=firstPiece+1; pp<lastPiece; ++pp )
1263            tor->info.pieces[pp].dnd = dnd;
1264    }
1265}
1266
1267void
1268tr_torrentInitFileDLs ( tr_torrent       * tor,
1269                        tr_file_index_t  * files,
1270                        tr_file_index_t    fileCount,
1271                        int                doDownload )
1272{
1273    tr_file_index_t i;
1274    tr_torrentLock( tor );
1275
1276    for( i=0; i<fileCount; ++i )
1277        setFileDND( tor, files[i], doDownload );
1278    tr_cpInvalidateDND ( tor->completion );
1279
1280    tr_torrentUnlock( tor );
1281}
1282
1283void
1284tr_torrentSetFileDLs ( tr_torrent      * tor,
1285                       tr_file_index_t * files,
1286                       tr_file_index_t   fileCount,
1287                       int               doDownload )
1288{
1289    tr_torrentLock( tor );
1290    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1291    saveFastResumeNow( tor );
1292    tr_torrentUnlock( tor );
1293}
1294
1295/***
1296****
1297***/
1298
1299void
1300tr_torrentSetMaxConnectedPeers( tr_torrent  * tor,
1301                                uint16_t      maxConnectedPeers )
1302{
1303    tor->maxConnectedPeers = maxConnectedPeers;
1304}
1305
1306uint16_t
1307tr_torrentGetMaxConnectedPeers( const tr_torrent  * tor )
1308{
1309    return tor->maxConnectedPeers;
1310}
1311
1312/***
1313****
1314***/
1315
1316tr_block_index_t
1317_tr_block( const tr_torrent  * tor,
1318           tr_piece_index_t    index,
1319           uint32_t            offset )
1320{
1321    const tr_info * inf = &tor->info;
1322    tr_block_index_t ret;
1323    ret = index;
1324    ret *= ( inf->pieceSize / tor->blockSize );
1325    ret += offset / tor->blockSize;
1326    return ret;
1327}
1328
1329int
1330tr_torrentReqIsValid( const tr_torrent * tor,
1331                      tr_piece_index_t   index,
1332                      uint32_t           offset,
1333                      uint32_t           length )
1334{
1335    int err = 0;
1336
1337    if( index >= tor->info.pieceCount )
1338        err = 1;
1339    else if ( offset >= tr_torPieceCountBytes( tor, index ) )
1340        err = 2;
1341    else if( length > MAX_BLOCK_SIZE )
1342        err = 3;
1343    else if( tr_pieceOffset( tor, index, offset, length ) > tor->info.totalSize )
1344        err = 4;
1345
1346    if( err )
1347    {
1348        fprintf( stderr, "(ticket #751) err is %d\n", err );
1349        fprintf( stderr, "(ticket #751) req.index is %"PRIu32"\n", index );
1350        fprintf( stderr, "(ticket #751) req.offset is %"PRIu32"\n", offset );
1351        fprintf( stderr, "(ticket #751) req.length is %"PRIu32"\n", length );
1352        fprintf( stderr, "(ticket #751) tor->info.totalSize is %"PRIu64"\n", tor->info.totalSize );
1353        fprintf( stderr, "(ticket #751) tor->info.pieceCount is %d\n", tor->info.pieceCount );
1354        fprintf( stderr, "(ticket #751) tr_torPieceCountBytes is %d\n", tr_torPieceCountBytes( tor, index ) );
1355        fprintf( stderr, "(ticket #751) tr_pieceOffset is %"PRIu64"\n", tr_pieceOffset( tor, index, offset, length ) );
1356    }
1357
1358    return !err;
1359}
1360
1361
1362uint64_t
1363tr_pieceOffset( const tr_torrent * tor,
1364                tr_piece_index_t   index,
1365                uint32_t           offset,
1366                uint32_t           length )
1367{
1368    uint64_t ret;
1369    ret = tor->info.pieceSize;
1370    ret *= index;
1371    ret += offset;
1372    ret += length;
1373    return ret;
1374}
1375
1376/***
1377****
1378***/
1379
1380int
1381tr_torrentIsPieceChecked( const tr_torrent * tor, tr_piece_index_t piece )
1382{
1383    return tr_bitfieldHas( tor->checkedPieces, piece );
1384}
1385
1386void
1387tr_torrentSetPieceChecked( tr_torrent * tor, tr_piece_index_t piece, int isChecked )
1388{
1389    if( isChecked )
1390        tr_bitfieldAdd( tor->checkedPieces, piece );
1391    else
1392        tr_bitfieldRem( tor->checkedPieces, piece );
1393}
1394
1395void
1396tr_torrentSetFileChecked( tr_torrent * tor, tr_file_index_t fileIndex, int isChecked )
1397{
1398    const tr_file * file = &tor->info.files[fileIndex];
1399    const tr_piece_index_t begin = file->firstPiece;
1400    const tr_piece_index_t end = file->lastPiece + 1;
1401
1402    if( isChecked )
1403        tr_bitfieldAddRange ( tor->checkedPieces, begin, end );
1404    else
1405        tr_bitfieldRemRange ( tor->checkedPieces, begin, end );
1406}
1407
1408int
1409tr_torrentIsFileChecked( const tr_torrent * tor, tr_file_index_t fileIndex )
1410{
1411    const tr_file * file = &tor->info.files[fileIndex];
1412    const tr_piece_index_t begin = file->firstPiece;
1413    const tr_piece_index_t end = file->lastPiece + 1;
1414    tr_piece_index_t i;
1415    int isChecked = TRUE;
1416
1417    for( i=begin; isChecked && i<end; ++i )
1418        if( !tr_torrentIsPieceChecked( tor, i ) )
1419            isChecked = FALSE;
1420
1421    return isChecked;
1422}
1423
1424void
1425tr_torrentUncheck( tr_torrent * tor )
1426{
1427    tr_bitfieldRemRange ( tor->checkedPieces, 0, tor->info.pieceCount );
1428}
1429
1430int
1431tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1432{
1433    return tor->info.pieceCount - tr_bitfieldCountTrueBits( tor->checkedPieces );
1434}
Note: See TracBrowser for help on using the repository browser.