source: trunk/libtransmission/torrent.c @ 5066

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

(gtk) #544: remove fast-resume cache when appropriate

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