source: branches/1.1x/libtransmission/torrent.c @ 5537

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

#843: download eta should consider availability

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