source: trunk/libtransmission/torrent.c @ 5611

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

'resume' cleanup

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