source: trunk/libtransmission/torrent.c @ 5613

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

get tr_ctorSetMetainfoFromHash() working again.

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