source: trunk/libtransmission/torrent.c @ 5042

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

modify "verify local data" to not lose the blocks in incomplete pieces

  • Property svn:keywords set to Date Rev Author Id
File size: 33.6 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 5042 2008-02-15 16:00:46Z 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 tr_torrentRemoveSaved( tr_torrent * tor )
830{
831    tr_metainfoRemoveSaved( tor->info.hashString, tor->handle->tag );
832}
833
834/***
835****
836***/
837
838static void
839freeTorrent( tr_torrent * tor )
840{
841    tr_torrent * t;
842    tr_handle * h = tor->handle;
843    tr_info * inf = &tor->info;
844
845    assert( tor != NULL );
846    assert( !tor->isRunning );
847
848    tr_globalLock( h );
849
850    tr_peerMgrRemoveTorrent( h->peerMgr, tor->info.hash );
851
852    tr_cpClose( tor->completion );
853
854    tr_rcClose( tor->upload );
855    tr_rcClose( tor->download );
856    tr_rcClose( tor->swarmspeed );
857
858    tr_trackerUnsubscribe( tor->tracker, tor->trackerSubscription );
859    tr_trackerFree( tor->tracker );
860    tor->tracker = NULL;
861
862    tr_bitfieldFree( tor->checkedPieces );
863
864    tr_free( tor->destination );
865
866    if( tor == h->torrentList )
867        h->torrentList = tor->next;
868    else for( t=h->torrentList; t!=NULL; t=t->next ) {
869        if( t->next == tor ) {
870            t->next = tor->next;
871            break;
872        }
873    }
874
875    assert( h->torrentCount >= 1 );
876    h->torrentCount--;
877
878    tr_inf( "closing torrent %s... %d torrents left",
879            tor->info.name, 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_torrentRecheck( 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    saveFastResumeNow( tor );
1007    tor->isRunning = 0;
1008    tr_runInEventThread( tor->handle, stopTorrent, tor );
1009
1010    tr_globalUnlock( tor->handle );
1011}
1012
1013static void
1014closeTorrent( void * vtor )
1015{
1016    tr_torrent * tor = vtor;
1017    saveFastResumeNow( tor );
1018    tor->isRunning = 0;
1019    stopTorrent( 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
1038/**
1039***  Completeness
1040**/
1041
1042static void
1043fireStatusChange( tr_torrent * tor, cp_status_t status )
1044{
1045    assert( tor != NULL );
1046    assert( status==TR_CP_INCOMPLETE || status==TR_CP_DONE || status==TR_CP_COMPLETE );
1047
1048    if( tor->status_func != NULL )
1049        (tor->status_func)( tor, status, tor->status_func_user_data );
1050}
1051
1052void
1053tr_torrentSetStatusCallback( tr_torrent             * tor,
1054                             tr_torrent_status_func   func,
1055                             void                   * user_data )
1056{
1057    assert( tor != NULL );
1058    tor->status_func = func;
1059    tor->status_func_user_data = user_data;
1060}
1061
1062void
1063tr_torrentClearStatusCallback( tr_torrent * torrent )
1064{
1065    tr_torrentSetStatusCallback( torrent, NULL, NULL );
1066}
1067
1068void
1069tr_torrentRecheckCompleteness( tr_torrent * tor )
1070{
1071    cp_status_t cpStatus;
1072
1073    tr_torrentLock( tor );
1074
1075    cpStatus = tr_cpGetStatus( tor->completion );
1076    if( cpStatus != tor->cpStatus ) {
1077        tor->cpStatus = cpStatus;
1078        fireStatusChange( tor, cpStatus );
1079        if( (cpStatus == TR_CP_COMPLETE) /* ...and if we're complete */
1080            && tor->downloadedCur ) {        /* and it just happened */
1081            tr_trackerCompleted( tor->tracker ); /* tell the tracker */
1082        }
1083        saveFastResumeNow( tor );
1084    }
1085    tr_torrentUnlock( tor );
1086}
1087
1088int
1089tr_torrentIsSeed( const tr_torrent * tor )
1090{
1091    return tor->cpStatus==TR_CP_COMPLETE || tor->cpStatus==TR_CP_DONE;
1092}
1093
1094/**
1095***  File priorities
1096**/
1097
1098void
1099tr_torrentInitFilePriority( tr_torrent   * tor,
1100                            int            fileIndex,
1101                            tr_priority_t  priority )
1102{
1103    int i;
1104    tr_file * file;
1105
1106    assert( tor != NULL );
1107    assert( 0<=fileIndex && fileIndex<tor->info.fileCount );
1108    assert( priority==TR_PRI_LOW || priority==TR_PRI_NORMAL || priority==TR_PRI_HIGH );
1109
1110    file = &tor->info.files[fileIndex];
1111    file->priority = priority;
1112    for( i=file->firstPiece; i<=file->lastPiece; ++i )
1113      tor->info.pieces[i].priority = calculatePiecePriority( tor, i, fileIndex );
1114}
1115
1116void
1117tr_torrentSetFilePriorities( tr_torrent     * tor,
1118                             int            * files,
1119                             int              fileCount,
1120                             tr_priority_t    priority )
1121{
1122    int i;
1123    tr_torrentLock( tor );
1124
1125    for( i=0; i<fileCount; ++i )
1126        tr_torrentInitFilePriority( tor, files[i], priority );
1127
1128    saveFastResumeNow( tor );
1129    tr_torrentUnlock( tor );
1130}
1131
1132tr_priority_t
1133tr_torrentGetFilePriority( const tr_torrent *  tor, int file )
1134{
1135    tr_priority_t ret;
1136
1137    tr_torrentLock( tor );
1138    assert( tor != NULL );
1139    assert( 0<=file && file<tor->info.fileCount );
1140    ret = tor->info.files[file].priority;
1141    tr_torrentUnlock( tor );
1142
1143    return ret;
1144}
1145
1146tr_priority_t*
1147tr_torrentGetFilePriorities( const tr_torrent * tor )
1148{
1149    int i;
1150    tr_priority_t * p;
1151
1152    tr_torrentLock( tor );
1153    p = tr_new0( tr_priority_t, tor->info.fileCount );
1154    for( i=0; i<tor->info.fileCount; ++i )
1155        p[i] = tor->info.files[i].priority;
1156    tr_torrentUnlock( tor );
1157
1158    return p;
1159}
1160
1161/**
1162***  File DND
1163**/
1164
1165int
1166tr_torrentGetFileDL( const tr_torrent * tor,
1167                     int                file )
1168{
1169    int doDownload;
1170    tr_torrentLock( tor );
1171
1172    assert( 0<=file && file<tor->info.fileCount );
1173    doDownload = !tor->info.files[file].dnd;
1174
1175    tr_torrentUnlock( tor );
1176    return doDownload != 0;
1177}
1178
1179static void
1180setFileDND( tr_torrent  * tor,
1181            int           fileIndex,
1182            int           doDownload )
1183{
1184    tr_file * file;
1185    const int dnd = !doDownload;
1186    int firstPiece, firstPieceDND;
1187    int lastPiece, lastPieceDND;
1188    int i;
1189
1190    file = &tor->info.files[fileIndex];
1191    file->dnd = dnd;
1192    firstPiece = file->firstPiece;
1193    lastPiece = file->lastPiece;
1194
1195    /* can't set the first piece to DND unless
1196       every file using that piece is DND */
1197    firstPieceDND = dnd;
1198    for( i=fileIndex-1; firstPieceDND && i>=0; --i ) {
1199        if( tor->info.files[i].lastPiece != firstPiece )
1200            break;
1201        firstPieceDND = tor->info.files[i].dnd;
1202    }
1203
1204    /* can't set the last piece to DND unless
1205       every file using that piece is DND */
1206    lastPieceDND = dnd;
1207    for( i=fileIndex+1; lastPieceDND && i<tor->info.fileCount; ++i ) {
1208        if( tor->info.files[i].firstPiece != lastPiece )
1209            break;
1210        lastPieceDND = tor->info.files[i].dnd;
1211    }
1212
1213    if( firstPiece == lastPiece )
1214    {
1215        tor->info.pieces[firstPiece].dnd = firstPieceDND && lastPieceDND;
1216    }
1217    else
1218    {
1219        tor->info.pieces[firstPiece].dnd = firstPieceDND;
1220        tor->info.pieces[lastPiece].dnd = lastPieceDND;
1221        for( i=firstPiece+1; i<lastPiece; ++i )
1222            tor->info.pieces[i].dnd = dnd;
1223    }
1224}
1225
1226void
1227tr_torrentInitFileDLs ( tr_torrent   * tor,
1228                        int          * files,
1229                        int            fileCount,
1230                        int            doDownload )
1231{
1232    int i;
1233    tr_torrentLock( tor );
1234
1235    for( i=0; i<fileCount; ++i )
1236        setFileDND( tor, files[i], doDownload );
1237    tr_cpInvalidateDND ( tor->completion );
1238
1239    tr_torrentUnlock( tor );
1240}
1241
1242void
1243tr_torrentSetFileDLs ( tr_torrent  * tor,
1244                       int         * files,
1245                       int           fileCount,
1246                       int           doDownload )
1247{
1248    tr_torrentLock( tor );
1249    tr_torrentInitFileDLs( tor, files, fileCount, doDownload );
1250    saveFastResumeNow( tor );
1251    tr_torrentUnlock( tor );
1252}
1253
1254/***
1255****
1256***/
1257
1258void
1259tr_torrentSetMaxConnectedPeers( tr_torrent  * tor,
1260                                uint16_t      maxConnectedPeers )
1261{
1262    tor->maxConnectedPeers = maxConnectedPeers;
1263}
1264
1265uint16_t
1266tr_torrentGetMaxConnectedPeers( const tr_torrent  * tor )
1267{
1268    return tor->maxConnectedPeers;
1269}
1270
1271/***
1272****
1273***/
1274
1275int _tr_block( const tr_torrent * tor, int index, int begin )
1276{
1277    const tr_info * inf = &tor->info;
1278    return index * ( inf->pieceSize / tor->blockSize ) +
1279        begin / tor->blockSize;
1280}
1281
1282uint64_t
1283tr_pieceOffset( const tr_torrent * tor, int index, int begin, int length )
1284{
1285    uint64_t ret;
1286    ret = tor->info.pieceSize;
1287    ret *= index;
1288    ret += begin;
1289    ret += length;
1290    return ret;
1291}
1292
1293/***
1294****
1295***/
1296
1297int
1298tr_torrentIsPieceChecked( const tr_torrent * tor, int piece )
1299{
1300    return tr_bitfieldHas( tor->checkedPieces, piece );
1301}
1302
1303void
1304tr_torrentSetPieceChecked( tr_torrent * tor, int piece, int isChecked )
1305{
1306    if( isChecked )
1307        tr_bitfieldAdd( tor->checkedPieces, piece );
1308    else
1309        tr_bitfieldRem( tor->checkedPieces, piece );
1310}
1311
1312void
1313tr_torrentSetFileChecked( tr_torrent * tor, int fileIndex, int isChecked )
1314{
1315    const tr_file * file = &tor->info.files[fileIndex];
1316    const size_t begin = file->firstPiece;
1317    const size_t end = file->lastPiece + 1;
1318
1319    if( isChecked )
1320        tr_bitfieldAddRange ( tor->checkedPieces, begin, end );
1321    else
1322        tr_bitfieldRemRange ( tor->checkedPieces, begin, end );
1323}
1324
1325int
1326tr_torrentIsFileChecked( const tr_torrent * tor, int fileIndex )
1327{
1328    const tr_file * file = &tor->info.files[fileIndex];
1329    const size_t begin = file->firstPiece;
1330    const size_t end = file->lastPiece + 1;
1331    size_t i;
1332    int isChecked = TRUE;
1333
1334    for( i=begin; isChecked && i<end; ++i )
1335        if( !tr_torrentIsPieceChecked( tor, i ) )
1336            isChecked = FALSE;
1337
1338    return isChecked;
1339}
1340
1341void
1342tr_torrentUncheck( tr_torrent * tor )
1343{
1344    tr_bitfieldRemRange ( tor->checkedPieces, 0, tor->info.pieceCount );
1345}
1346
1347int
1348tr_torrentCountUncheckedPieces( const tr_torrent * tor )
1349{
1350    return tor->info.pieceCount - tr_bitfieldCountTrueBits( tor->checkedPieces );
1351}
Note: See TracBrowser for help on using the repository browser.