source: trunk/libtransmission/torrent.c @ 5313

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

more string work before the freeze. (1) use %'d to get thousands' grouping in end-user strings (2) follow HiG capitalization, quotation guidelines (3) fold a few more strings

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