source: branches/file_selection/libtransmission/torrent.c @ 2121

Last change on this file since 2121 was 2121, checked in by charles, 15 years ago
  • gtk: fix another special case bug.
  • cli: sync to libT changes wrt tr_getFinished()
  • Property svn:keywords set to Date Rev Author Id
File size: 31.4 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 2121 2007-06-17 05:29:47Z charles $
3 *
4 * Copyright (c) 2005-2007 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 "transmission.h"
26#include "shared.h"
27#define INTERVAL_MSEC 100
28
29/***********************************************************************
30 * Local prototypes
31 **********************************************************************/
32static tr_torrent_t * torrentRealInit( tr_handle_t *, tr_torrent_t * tor,
33                                       uint8_t *, int flags, int * error );
34static void torrentReallyStop( tr_torrent_t * );
35
36static void ioInitAdd ( tr_torrent_t * );
37static int ioInitRemove ( tr_torrent_t * );
38static void downloadLoop( void * );
39
40void tr_setUseCustomUpload( tr_torrent_t * tor, int limit )
41{
42    tor->customUploadLimit = limit;
43}
44
45void tr_setUseCustomDownload( tr_torrent_t * tor, int limit )
46{
47    tor->customDownloadLimit = limit;
48}
49
50void tr_setUploadLimit( tr_torrent_t * tor, int limit )
51{
52    tr_rcSetLimit( tor->upload, limit );
53}
54
55void tr_setDownloadLimit( tr_torrent_t * tor, int limit )
56{
57    tr_rcSetLimit( tor->download, limit );
58}
59
60tr_torrent_t *
61tr_torrentInit( tr_handle_t * h, const char * path,
62                uint8_t * hash, int flags, int * error )
63{
64    tr_torrent_t * tor;
65
66    tor  = calloc( 1, sizeof *tor );
67    if( NULL == tor )
68    {
69        *error = TR_EOTHER;
70        return NULL;
71    }
72
73    /* Parse torrent file */
74    if( tr_metainfoParseFile( &tor->info, h->tag, path,
75                              TR_FLAG_SAVE & flags ) )
76    {
77        *error = TR_EINVALID;
78        free( tor );
79        return NULL;
80    }
81
82    return torrentRealInit( h, tor, hash, flags, error );
83}
84
85tr_torrent_t *
86tr_torrentInitData( tr_handle_t * h, uint8_t * data, size_t size,
87                    uint8_t * hash, int flags, int * error )
88{
89    tr_torrent_t * tor;
90
91    tor  = calloc( 1, sizeof *tor );
92    if( NULL == tor )
93    {
94        *error = TR_EOTHER;
95        return NULL;
96    }
97
98    /* Parse torrent file */
99    if( tr_metainfoParseData( &tor->info, h->tag, data, size,
100                              TR_FLAG_SAVE & flags ) )
101    {
102        *error = TR_EINVALID;
103        free( tor );
104        return NULL;
105    }
106
107    return torrentRealInit( h, tor, hash, flags, error );
108}
109
110tr_torrent_t *
111tr_torrentInitSaved( tr_handle_t * h, const char * hashStr,
112                     int flags, int * error )
113{
114    tr_torrent_t * tor;
115
116    tor  = calloc( 1, sizeof *tor );
117    if( NULL == tor )
118    {
119        *error = TR_EOTHER;
120        return NULL;
121    }
122
123    /* Parse torrent file */
124    if( tr_metainfoParseHash( &tor->info, h->tag, hashStr ) )
125    {
126        *error = TR_EINVALID;
127        free( tor );
128        return NULL;
129    }
130
131    return torrentRealInit( h, tor, NULL, ( TR_FLAG_SAVE | flags ), error );
132}
133
134/***********************************************************************
135 * tr_torrentInit
136 ***********************************************************************
137 * Allocates a tr_torrent_t structure, then relies on tr_metainfoParse
138 * to fill it.
139 **********************************************************************/
140static tr_torrent_t * torrentRealInit( tr_handle_t * h, tr_torrent_t * tor,
141                                       uint8_t * hash, int flags, int * error )
142{
143    tr_torrent_t  * tor_tmp;
144    tr_info_t     * inf;
145    int             i;
146   
147    inf         = &tor->info;
148    inf->flags |= flags;
149
150    tr_sharedLock( h->shared );
151
152    /* Make sure this torrent is not already open */
153    for( tor_tmp = h->torrentList; tor_tmp; tor_tmp = tor_tmp->next )
154    {
155        if( !memcmp( tor->info.hash, tor_tmp->info.hash,
156                     SHA_DIGEST_LENGTH ) )
157        {
158            if( NULL != hash )
159            {
160                memcpy( hash, tor->info.hash, SHA_DIGEST_LENGTH );
161            }
162            *error = TR_EDUPLICATE;
163            tr_metainfoFree( &tor->info );
164            free( tor );
165            tr_sharedUnlock( h->shared );
166            return NULL;
167        }
168    }
169
170    tor->handle   = h;
171    tor->status   = TR_STATUS_PAUSE;
172    tor->id       = h->id;
173    tor->key      = h->key;
174    tor->azId     = h->azId;
175    tor->hasChangedState = -1;
176
177    /* Escaped info hash for HTTP queries */
178    for( i = 0; i < SHA_DIGEST_LENGTH; i++ )
179    {
180        snprintf( &tor->escapedHashString[3*i],
181                  sizeof( tor->escapedHashString ) - 3 * i,
182                  "%%%02x", inf->hash[i] );
183    }
184
185    tor->pexDisabled = 0;
186
187    /* Block size: usually 16 ko, or less if we have to */
188    tor->blockSize  = MIN( inf->pieceSize, 1 << 14 );
189    tor->blockCount = ( inf->totalSize + tor->blockSize - 1 ) /
190                        tor->blockSize;
191    tor->completion = tr_cpInit( tor );
192
193    tor->thread = THREAD_EMPTY;
194    tr_lockInit( &tor->lock );
195    tr_condInit( &tor->cond );
196
197    tor->upload         = tr_rcInit();
198    tor->download       = tr_rcInit();
199    tor->swarmspeed     = tr_rcInit();
200 
201    /* We have a new torrent */
202    tor->publicPort = tr_sharedGetPublicPort( h->shared );
203    tor->prev       = NULL;
204    tor->next       = h->torrentList;
205    if( tor->next )
206    {
207        tor->next->prev = tor;
208    }
209    h->torrentList = tor;
210    (h->torrentCount)++;
211
212    tr_sharedUnlock( h->shared );
213
214    if( !h->isPortSet )
215    {
216        tr_setBindPort( h, TR_DEFAULT_PORT );
217    }
218
219    tr_torrentInitFilePieces( tor );
220
221    return tor;
222}
223
224tr_info_t * tr_torrentInfo( tr_torrent_t * tor )
225{
226    return &tor->info;
227}
228
229/***********************************************************************
230 * tr_torrentScrape     
231 **********************************************************************/
232int tr_torrentScrape( tr_torrent_t * tor, int * s, int * l, int * d )
233{
234    return tr_trackerScrape( tor, s, l, d );
235}
236
237void tr_torrentSetFolder( tr_torrent_t * tor, const char * path )
238{
239    tor->destination = strdup( path );
240    if ( !tor->ioLoaded )
241    {
242        tr_ioLoadResume( tor );
243    }
244}
245
246char * tr_torrentGetFolder( tr_torrent_t * tor )
247{
248    return tor->destination;
249}
250
251int tr_torrentDuplicateDownload( tr_torrent_t * tor )
252{
253    tr_torrent_t * current;
254   
255    /* Check if a torrent with the same name and destination is already active */
256    for( current = tor->handle->torrentList; current; current = current->next )
257    {
258        if( current != tor && current->status != TR_STATUS_PAUSE
259            && !strcmp( tor->destination, current->destination )
260            && !strcmp( tor->info.name, current->info.name ) )
261        {
262            return 1;
263        }
264    }
265    return 0;
266}
267
268void tr_torrentStart( tr_torrent_t * tor )
269{
270    /* Join the thread first */
271    torrentReallyStop( tor );
272   
273    /* Don't start if a torrent with the same name and destination is already active */
274    if( tr_torrentDuplicateDownload( tor ) )
275    {
276        tor->error = TR_ERROR_IO_DUP_DOWNLOAD;
277        snprintf( tor->errorString, sizeof( tor->errorString ),
278                    "%s", tr_errorString( TR_ERROR_IO_DUP_DOWNLOAD ) );
279        return;
280    }
281
282    tr_lockLock( &tor->lock );
283
284    tor->downloadedPrev += tor->downloadedCur;
285    tor->downloadedCur   = 0;
286    tor->uploadedPrev   += tor->uploadedCur;
287    tor->uploadedCur     = 0;
288
289    tor->status  = TR_STATUS_CHECK_WAIT;
290    tor->error   = TR_OK;
291    tor->tracker = tr_trackerInit( tor );
292
293    tor->startDate = tr_date();
294    tor->die = 0;
295    tor->thread = THREAD_EMPTY;
296
297    tr_lockUnlock( &tor->lock );
298
299    ioInitAdd ( tor );
300}
301
302static void torrentStop( tr_torrent_t * tor )
303{
304    tr_trackerStopped( tor->tracker );
305    tr_rcReset( tor->download );
306    tr_rcReset( tor->upload );
307    tr_rcReset( tor->swarmspeed );
308    tor->status = TR_STATUS_STOPPING;
309    tor->stopDate = tr_date();
310}
311
312void tr_torrentStop( tr_torrent_t * tor )
313{
314    tr_lockLock( &tor->lock );
315    torrentStop( tor );
316
317    /* Don't return until the files are closed, so the UI can trash
318     * them if requested */
319    if ( ioInitRemove( tor ) ) /* torrent never got started */
320        tor->status = TR_STATUS_STOPPED;
321    else
322        tr_condWait( &tor->cond, &tor->lock );
323
324    tr_lockUnlock( &tor->lock );
325}
326
327/***********************************************************************
328 * torrentReallyStop
329 ***********************************************************************
330 * Joins the download thread and frees/closes everything related to it.
331 **********************************************************************/
332static void torrentReallyStop( tr_torrent_t * tor )
333{
334    int i;
335
336    tor->die = 1;
337    tr_threadJoin( &tor->thread );
338
339    if( tor->tracker )
340    {
341       tr_trackerClose( tor->tracker );
342       tor->tracker = NULL;
343    }
344
345    tr_lockLock( &tor->lock );
346    for( i = 0; i < tor->peerCount; i++ )
347    {
348        tr_peerDestroy( tor->peers[i] );
349    }
350    tor->peerCount = 0;
351    tr_lockUnlock( &tor->lock );
352}
353
354void tr_torrentDisablePex( tr_torrent_t * tor, int disable )
355{
356    int ii;
357
358    if( TR_FLAG_PRIVATE & tor->info.flags )
359    {
360        return;
361    }
362
363    tr_lockLock( &tor->lock );
364
365    if( tor->pexDisabled == disable )
366    {
367        tr_lockUnlock( &tor->lock );
368        return;
369    }
370
371    tor->pexDisabled = disable;
372    for( ii = 0; ii < tor->peerCount; ii++ )
373    {
374        tr_peerSetPrivate( tor->peers[ii], disable );
375    }
376
377    tr_lockUnlock( &tor->lock );
378}
379
380static int tr_didStateChangeTo ( tr_torrent_t * tor, int status )
381{
382    if( tor->hasChangedState == status )
383    {
384        tor->hasChangedState = -1;
385        return 1;
386    }
387    return 0;
388}
389
390int tr_getIncomplete( tr_torrent_t * tor )
391{
392    return tr_didStateChangeTo( tor, TR_CP_INCOMPLETE );
393}
394int tr_getDone( tr_torrent_t * tor )
395{
396    return tr_didStateChangeTo( tor, TR_CP_DONE );
397}
398int tr_getComplete( tr_torrent_t * tor )
399{
400    return tr_didStateChangeTo( tor, TR_CP_COMPLETE );
401}
402
403void tr_manualUpdate( tr_torrent_t * tor )
404{
405    int peerCount, new;
406    uint8_t * peerCompact;
407
408    if( !( tor->status & TR_STATUS_ACTIVE ) )
409        return;
410   
411    tr_lockLock( &tor->lock );
412    tr_trackerAnnouncePulse( tor->tracker, &peerCount, &peerCompact, 1 );
413    new = 0;
414    if( peerCount > 0 )
415    {
416        new = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
417                              peerCompact, peerCount );
418        free( peerCompact );
419    }
420    tr_dbg( "got %i peers from manual announce, used %i", peerCount, new );
421    tr_lockUnlock( &tor->lock );
422}
423
424tr_stat_t * tr_torrentStat( tr_torrent_t * tor )
425{
426    tr_stat_t * s;
427    tr_peer_t * peer;
428    tr_info_t * inf = &tor->info;
429    tr_tracker_t * tc;
430    int i;
431
432    tor->statCur = ( tor->statCur + 1 ) % 2;
433    s = &tor->stats[tor->statCur];
434
435    if( ( tor->status & TR_STATUS_STOPPED ) ||
436        ( ( tor->status & TR_STATUS_STOPPING ) &&
437          tr_date() > tor->stopDate + 60000 ) )
438    {
439        torrentReallyStop( tor );
440        tor->status = TR_STATUS_PAUSE;
441    }
442
443    tr_lockLock( &tor->lock );
444
445    s->status = tor->status;
446    s->error  = tor->error;
447    memcpy( s->errorString, tor->errorString,
448            sizeof( s->errorString ) );
449
450    tc = tor->tracker;
451    s->cannotConnect = tr_trackerCannotConnect( tc );
452    s->tracker = ( tc ? tr_trackerGet( tc ) : &inf->trackerList[0].list[0] );
453
454    s->peersTotal       = 0;
455    memset( s->peersFrom, 0, sizeof( s->peersFrom ) );
456    s->peersUploading   = 0;
457    s->peersDownloading = 0;
458   
459    for( i = 0; i < tor->peerCount; i++ )
460    {
461        peer = tor->peers[i];
462   
463        if( tr_peerIsConnected( peer ) )
464        {
465            (s->peersTotal)++;
466            (s->peersFrom[ tr_peerIsFrom( peer ) ])++;
467            if( tr_peerAmInterested( peer ) && !tr_peerIsChoking( peer ) )
468            {
469                (s->peersUploading)++;
470            }
471            if( !tr_peerAmChoking( peer ) )
472            {
473                (s->peersDownloading)++;
474            }
475        }
476    }
477
478    s->percentDone = tr_cpPercentDone( tor->completion );
479    s->percentComplete = tr_cpPercentComplete( tor->completion );
480    s->cpStatus = tr_cpGetStatus( tor->completion );
481    s->left     = tr_cpLeftUntilDone( tor->completion );
482    if( tor->status & TR_STATUS_DOWNLOAD )
483    {
484        s->rateDownload = tr_rcRate( tor->download );
485    }
486    else
487    {
488        /* tr_rcRate() doesn't make the difference between 'piece'
489           messages and other messages, which causes a non-zero
490           download rate even tough we are not downloading. So we
491           force it to zero not to confuse the user. */
492        s->rateDownload = 0.0;
493    }
494    s->rateUpload = tr_rcRate( tor->upload );
495   
496    s->seeders  = tr_trackerSeeders( tc );
497    s->leechers = tr_trackerLeechers( tc );
498    s->completedFromTracker = tr_trackerDownloaded( tc );
499
500    s->swarmspeed = tr_rcRate( tor->swarmspeed );
501   
502    s->startDate = tor->startDate;
503    s->activityDate = tor->activityDate;
504
505    if( s->rateDownload < 0.1 )
506    {
507        s->eta = -1;
508    }
509    else
510    {
511        s->eta = (float) s->left / s->rateDownload / 1024.0;
512    }
513
514    s->uploaded        = tor->uploadedCur   + tor->uploadedPrev;
515    s->downloaded      = tor->downloadedCur + tor->downloadedPrev;
516    s->downloadedValid = tr_cpDownloadedValid( tor->completion );
517   
518    if( s->downloaded == 0 && s->percentDone == 0.0 )
519    {
520        s->ratio = TR_RATIO_NA;
521    }
522    else
523    {
524        s->ratio = (float)s->uploaded
525                 / (float)MAX(s->downloaded, s->downloadedValid);
526    }
527   
528    tr_lockUnlock( &tor->lock );
529
530    return s;
531}
532
533tr_peer_stat_t * tr_torrentPeers( tr_torrent_t * tor, int * peerCount )
534{
535    tr_peer_stat_t * peers;
536
537    tr_lockLock( &tor->lock );
538
539    *peerCount = tor->peerCount;
540   
541    peers = (tr_peer_stat_t *) calloc( tor->peerCount, sizeof( tr_peer_stat_t ) );
542    if (peers != NULL)
543    {
544        tr_peer_t * peer;
545        struct in_addr * addr;
546        int i;
547        for( i = 0; i < tor->peerCount; i++ )
548        {
549            peer = tor->peers[i];
550           
551            addr = tr_peerAddress( peer );
552            if( NULL != addr )
553            {
554                tr_netNtop( addr, peers[i].addr,
555                           sizeof( peers[i].addr ) );
556            }
557           
558            peers[i].client        = tr_peerClient( peer );
559            peers[i].isConnected   = tr_peerIsConnected( peer );
560            peers[i].from          = tr_peerIsFrom( peer );
561            peers[i].progress      = tr_peerProgress( peer );
562            peers[i].port          = tr_peerPort( peer );
563           
564            if( ( peers[i].isDownloading = !tr_peerAmChoking( peer ) ) )
565            {
566                peers[i].uploadToRate = tr_peerUploadRate( peer );
567            }
568            if( ( peers[i].isUploading = ( tr_peerAmInterested( peer ) &&
569                                           !tr_peerIsChoking( peer ) ) ) )
570            {
571                peers[i].downloadFromRate = tr_peerDownloadRate( peer );
572            }
573        }
574    }
575   
576    tr_lockUnlock( &tor->lock );
577   
578    return peers;
579}
580
581void tr_torrentPeersFree( tr_peer_stat_t * peers, int peerCount UNUSED )
582{
583    if (peers == NULL)
584        return;
585
586    free( peers );
587}
588
589void tr_torrentAvailability( tr_torrent_t * tor, int8_t * tab, int size )
590{
591    int i, j, piece;
592    float interval;
593
594    tr_lockLock( &tor->lock );
595    interval = (float)tor->info.pieceCount / (float)size;
596    for( i = 0; i < size; i++ )
597    {
598        piece = i * interval;
599
600        if( tr_cpPieceIsComplete( tor->completion, piece ) )
601        {
602            tab[i] = -1;
603            continue;
604        }
605
606        tab[i] = 0;
607        for( j = 0; j < tor->peerCount; j++ )
608        {
609            if( tr_peerBitfield( tor->peers[j] ) &&
610                tr_bitfieldHas( tr_peerBitfield( tor->peers[j] ), piece ) )
611            {
612                (tab[i])++;
613            }
614        }
615    }
616    tr_lockUnlock( &tor->lock );
617}
618
619size_t
620tr_torrentFileBytesCompleted ( const tr_torrent_t * tor, int fileIndex )
621{
622    const tr_file_t * file = &tor->info.files[fileIndex];
623    int firstBlock         =  file->offset                     / tor->blockSize;
624    int firstBlockOffset   =  file->offset                     % tor->blockSize;
625    int lastBlock          = (file->offset + file->length - 1) / tor->blockSize;
626    int lastBlockOffset    = (file->offset + file->length - 1) % tor->blockSize;
627    size_t haveBytes = 0;
628
629    assert( tor != NULL );
630    assert( 0<=fileIndex && fileIndex<tor->info.fileCount );
631    assert( file->offset + file->length <= tor->info.totalSize );
632    assert( 0<=firstBlock && firstBlock<tor->blockCount );
633    assert( 0<=lastBlock && lastBlock<tor->blockCount );
634    assert( firstBlock <= lastBlock );
635    assert( tr_blockPiece( firstBlock ) == file->firstPiece );
636    assert( tr_blockPiece( lastBlock ) == file->lastPiece );
637
638    if( firstBlock == lastBlock )
639    {
640        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
641            haveBytes += lastBlockOffset + 1 - firstBlockOffset;
642    }
643    else
644    {
645        int i;
646
647        if( tr_cpBlockIsComplete( tor->completion, firstBlock ) )
648            haveBytes += tor->blockSize - firstBlockOffset;
649
650        for( i=firstBlock+1; i<lastBlock; ++i )
651            if( tr_cpBlockIsComplete( tor->completion, i ) )
652               haveBytes += tor->blockSize;
653
654        if( tr_cpBlockIsComplete( tor->completion, lastBlock ) )
655            haveBytes += lastBlockOffset + 1;
656    }
657
658    return haveBytes;
659}
660
661float
662tr_torrentFileCompletion ( const tr_torrent_t * tor, int fileIndex )
663{
664    const size_t c = tr_torrentFileBytesCompleted ( tor, fileIndex );
665    return (float)c / tor->info.files[fileIndex].length;
666}
667
668float*
669tr_torrentCompletion( tr_torrent_t * tor )
670{
671    int i;
672    float * f;
673
674    tr_lockLock( &tor->lock );
675    f = calloc ( tor->info.fileCount, sizeof( float ) );
676    for( i=0; i<tor->info.fileCount; ++i )
677       f[i] = tr_torrentFileCompletion ( tor, i );
678    tr_lockUnlock( &tor->lock );
679
680    return f;
681}
682
683void tr_torrentAmountFinished( tr_torrent_t * tor, float * tab, int size )
684{
685    int i, piece;
686    float interval;
687
688    tr_lockLock( &tor->lock );
689    interval = (float)tor->info.pieceCount / (float)size;
690    for( i = 0; i < size; i++ )
691    {
692        piece = i * interval;
693        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
694    }
695    tr_lockUnlock( &tor->lock );
696}
697
698void tr_torrentRemoveSaved( tr_torrent_t * tor )
699{
700    tr_metainfoRemoveSaved( tor->info.hashString, tor->handle->tag );
701}
702
703void tr_torrentRemoveFastResume( tr_torrent_t * tor )
704{
705    tr_ioRemoveResume( tor );
706}
707
708/***********************************************************************
709 * tr_torrentClose
710 ***********************************************************************
711 * Frees memory allocated by tr_torrentInit.
712 **********************************************************************/
713void tr_torrentClose( tr_torrent_t * tor )
714{
715    tr_handle_t * h = tor->handle;
716    tr_info_t * inf = &tor->info;
717
718    /* Join the thread first */
719    torrentReallyStop( tor );
720
721    tr_sharedLock( h->shared );
722
723    h->torrentCount--;
724
725    tr_lockClose( &tor->lock );
726    tr_condClose( &tor->cond );
727    tr_cpClose( tor->completion );
728
729    tr_rcClose( tor->upload );
730    tr_rcClose( tor->download );
731    tr_rcClose( tor->swarmspeed );
732
733    if( tor->destination )
734    {
735        free( tor->destination );
736    }
737
738    tr_metainfoFree( inf );
739
740    if( tor->prev )
741    {
742        tor->prev->next = tor->next;
743    }
744    else
745    {
746        h->torrentList = tor->next;
747    }
748    if( tor->next )
749    {
750        tor->next->prev = tor->prev;
751    }
752    free( tor );
753
754    tr_sharedUnlock( h->shared );
755}
756
757int tr_torrentAttachPeer( tr_torrent_t * tor, tr_peer_t * peer )
758{
759    int i;
760    tr_peer_t * otherPeer;
761
762    if( tor->peerCount >= TR_MAX_PEER_COUNT )
763    {
764        tr_peerDestroy(  peer );
765        return 0;
766    }
767
768    /* Don't accept two connections from the same IP */
769    for( i = 0; i < tor->peerCount; i++ )
770    {
771        otherPeer = tor->peers[i];
772        if( !memcmp( tr_peerAddress( peer ), tr_peerAddress( otherPeer ), 4 ) )
773        {
774            tr_peerDestroy(  peer );
775            return 0;
776        }
777    }
778
779    tr_peerSetPrivate( peer, tor->info.flags & TR_FLAG_PRIVATE ||
780                       tor->pexDisabled );
781    tr_peerSetTorrent( peer, tor );
782    tor->peers[tor->peerCount++] = peer;
783
784    return 1;
785}
786
787int tr_torrentAddCompact( tr_torrent_t * tor, int from,
788                           uint8_t * buf, int count )
789{
790    struct in_addr addr;
791    in_port_t port;
792    int i, added;
793    tr_peer_t * peer;
794
795    added = 0;
796    for( i = 0; i < count; i++ )
797    {
798        memcpy( &addr, buf, 4 ); buf += 4;
799        memcpy( &port, buf, 2 ); buf += 2;
800
801        peer = tr_peerInit( addr, port, -1, from );
802        added += tr_torrentAttachPeer( tor, peer );
803    }
804
805    return added;
806}
807
808/***********************************************************************
809 * Push a torrent's call to tr_ioInit through a queue in a worker
810 * thread so that only one torrent can be in checkFiles() at a time.
811 **********************************************************************/
812
813struct tr_io_init_list_t
814{
815    tr_torrent_t              * tor;
816    struct tr_io_init_list_t  * next;
817};
818
819static struct tr_io_init_list_t * ioInitQueue = NULL;
820
821static int ioInitWorkerRunning = 0;
822
823static tr_thread_t ioInitThread;
824
825static tr_lock_t* getIOLock( tr_handle_t * h )
826{
827    static tr_lock_t * lock = NULL;
828
829    tr_sharedLock( h->shared );
830    if( lock == NULL )
831    {
832        lock = calloc( 1, sizeof( tr_lock_t ) );
833        tr_lockInit( lock );
834    }
835    tr_sharedUnlock( h->shared );
836
837    return lock;
838}
839
840static void ioInitWorker( void * user_data )
841{
842    tr_handle_t * h = (tr_handle_t*) user_data;
843
844    for (;;)
845    {
846        char name[32];
847
848        /* find the next torrent to process */
849        tr_torrent_t * tor = NULL;
850        tr_lock_t * lock = getIOLock( h );
851        tr_lockLock( lock );
852        if( ioInitQueue != NULL )
853        {
854            struct tr_io_init_list_t * node = ioInitQueue;
855            ioInitQueue = node->next;
856            tor = node->tor;
857            free( node );
858        }
859        tr_lockUnlock( lock );
860
861        /* if no torrents, this worker thread is done */
862        if( tor == NULL )
863        {
864          break;
865        }
866
867        /* check this torrent's files */
868        tor->status = TR_STATUS_CHECK;
869       
870        tr_dbg( "torrent %s checking files", tor->info.name );
871        tr_lockLock( &tor->lock );
872        tr_cpReset( tor->completion );
873        tor->io = tr_ioInit( tor );
874        tr_lockUnlock( &tor->lock );
875
876        snprintf( name, sizeof( name ), "torrent %p", tor );
877        tr_threadCreate( &tor->thread, downloadLoop, tor, name );
878    }
879
880    ioInitWorkerRunning = 0;
881}
882
883/* add tor to the queue of torrents waiting for an tr_ioInit */
884static void ioInitAdd( tr_torrent_t * tor )
885{
886    tr_lock_t * lock = getIOLock( tor->handle );
887    struct tr_io_init_list_t * node;
888    tr_lockLock( lock );
889
890    /* enqueue this torrent to have its io initialized */
891    node = malloc( sizeof( struct tr_io_init_list_t ) );
892    node->tor = tor;
893    node->next = NULL;
894    if( ioInitQueue == NULL )
895    {
896        ioInitQueue = node;
897    }
898    else
899    {
900        struct tr_io_init_list_t * l = ioInitQueue;
901        while( l->next != NULL )
902        {
903            l = l->next;
904        }
905        l->next = node;
906    }
907
908    /* ensure there's a worker thread to process the queue */
909    if( !ioInitWorkerRunning )
910    {
911        ioInitWorkerRunning = 1;
912        tr_threadCreate( &ioInitThread, ioInitWorker, tor->handle, "ioInit" );
913    }
914   
915    tr_lockUnlock( lock );
916}
917
918/* remove tor from the queue of torrents waiting for an tr_ioInit.
919   return nonzero if tor was found and removed */
920static int ioInitRemove( tr_torrent_t * tor )
921{
922    tr_lock_t * lock = getIOLock( tor->handle );
923    struct tr_io_init_list_t *node, *prev;
924    tr_lockLock( lock );
925
926    /* find tor's node */
927    for( prev = NULL, node = ioInitQueue;
928         node != NULL && node->tor != tor;
929         prev=node, node=node->next );
930
931    if( node != NULL )
932    {
933        if( prev == NULL )
934        {
935            ioInitQueue = node->next;
936        }
937        else
938        {
939            prev->next = node->next;
940        }
941    }
942
943    tr_lockUnlock( lock );
944    return node != NULL;
945}
946
947/***********************************************************************
948 * downloadLoop
949 **********************************************************************/
950static void downloadLoop( void * _tor )
951{
952    tr_torrent_t * tor = _tor;
953    int            i, ret;
954    int            peerCount, used;
955    cp_status_t    cpState, cpPrevState;
956    uint8_t      * peerCompact;
957    tr_peer_t    * peer;
958
959    tr_lockLock( &tor->lock );
960
961    cpState = cpPrevState = tr_cpGetStatus( tor->completion );
962    switch( cpState ) {
963        case TR_CP_COMPLETE:   tor->status = TR_STATUS_SEED; break;
964        case TR_CP_DONE:       tor->status = TR_STATUS_DONE; break;
965        case TR_CP_INCOMPLETE: tor->status = TR_STATUS_DOWNLOAD; break;
966    }
967
968    while( !tor->die )
969    {
970        tr_lockUnlock( &tor->lock );
971        tr_wait( INTERVAL_MSEC );
972        tr_lockLock( &tor->lock );
973
974        cpState = tr_cpGetStatus( tor->completion );
975
976        if( cpState != cpPrevState )
977        {
978            switch( cpState ) {
979                case TR_CP_COMPLETE:   tor->status = TR_STATUS_SEED; break;
980                case TR_CP_DONE:       tor->status = TR_STATUS_DONE; break;
981                case TR_CP_INCOMPLETE: tor->status = TR_STATUS_DOWNLOAD; break;
982            }
983
984            tor->hasChangedState = cpState;
985
986            if( cpState == TR_CP_COMPLETE )
987                tr_trackerCompleted( tor->tracker );
988
989            tr_ioSync( tor->io );
990
991            cpPrevState = cpState;
992        }
993
994        /* Try to get new peers or to send a message to the tracker */
995        tr_trackerPulse( tor->tracker, &peerCount, &peerCompact );
996        if( peerCount > 0 )
997        {
998            used = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
999                                         peerCompact, peerCount );
1000            free( peerCompact );
1001            tr_dbg( "got %i peers from announce, used %i", peerCount, used );
1002        }
1003        if( tor->status & TR_STATUS_STOPPED )
1004        {
1005            break;
1006        }
1007
1008        /* Stopping: make sure all files are closed and stop talking
1009           to peers */
1010        if( tor->status & TR_STATUS_STOPPING )
1011        {
1012            if( tor->io )
1013            {
1014                tr_ioClose( tor->io ); tor->io = NULL;
1015                tr_condSignal( &tor->cond );
1016            }
1017            continue;
1018        }
1019
1020        /* Shuffle peers */
1021        if( tor->peerCount > 1 )
1022        {
1023            peer = tor->peers[0];
1024            memmove( &tor->peers[0], &tor->peers[1],
1025                    ( tor->peerCount - 1 ) * sizeof( void * ) );
1026            tor->peers[tor->peerCount - 1] = peer;
1027        }
1028
1029        /* Receive/send messages */
1030        for( i = 0; i < tor->peerCount; )
1031        {
1032            peer = tor->peers[i];
1033
1034            ret = tr_peerPulse( peer );
1035            if( ret & TR_ERROR_IO_MASK )
1036            {
1037                tr_err( "Fatal error, stopping download (%d)", ret );
1038                torrentStop( tor );
1039                tor->error = ret;
1040                snprintf( tor->errorString, sizeof( tor->errorString ),
1041                          "%s", tr_errorString( ret ) );
1042                break;
1043            }
1044            if( ret )
1045            {
1046                tr_peerDestroy( peer );
1047                tor->peerCount--;
1048                memmove( &tor->peers[i], &tor->peers[i+1],
1049                         ( tor->peerCount - i ) * sizeof( void * ) );
1050                continue;
1051            }
1052            i++;
1053        }
1054    }
1055
1056    tr_lockUnlock( &tor->lock );
1057
1058    if( tor->io )
1059    {
1060        tr_ioClose( tor->io ); tor->io = NULL;
1061        tr_condSignal( &tor->cond );
1062    }
1063
1064    tor->status = TR_STATUS_STOPPED;
1065}
1066
1067/***
1068****
1069****  File prioritization
1070****
1071***/
1072
1073static int
1074getBytePiece( const tr_info_t * info, uint64_t byteOffset )
1075{
1076    assert( info != NULL );
1077    assert( info->pieceSize != 0 );
1078
1079    return byteOffset / info->pieceSize;
1080}
1081
1082static void
1083initFilePieces ( tr_info_t * info, int fileIndex )
1084{
1085    tr_file_t * file = &info->files[fileIndex];
1086    uint64_t firstByte, lastByte;
1087
1088    assert( info != NULL );
1089    assert( 0<=fileIndex && fileIndex<info->fileCount );
1090
1091    file = &info->files[fileIndex];
1092    firstByte = file->offset;
1093    lastByte = firstByte + file->length - 1;
1094    file->firstPiece = getBytePiece( info, firstByte );
1095    file->lastPiece = getBytePiece( info, lastByte );
1096    tr_dbg( "file #%d is in pieces [%d...%d] (%s)", fileIndex, file->firstPiece, file->lastPiece, file->name );
1097}
1098
1099static tr_priority_t
1100calculatePiecePriority ( const tr_torrent_t * tor,
1101                         int                  piece )
1102{
1103    int i;
1104    tr_priority_t priority = TR_PRI_DND;
1105
1106    for( i=0; i<tor->info.fileCount; ++i )
1107    {
1108        const tr_file_t * file = &tor->info.files[i];
1109        if ( file->firstPiece <= piece
1110          && file->lastPiece  >= piece
1111          && file->priority   >  priority)
1112              priority = file->priority;
1113    }
1114
1115    return priority;
1116}
1117
1118void
1119tr_torrentInitFilePieces( tr_torrent_t * tor )
1120{
1121    int i;
1122    uint64_t offset = 0;
1123
1124    assert( tor != NULL );
1125
1126    for( i=0; i<tor->info.fileCount; ++i ) {
1127      tor->info.files[i].offset = offset;
1128      offset += tor->info.files[i].length;
1129      initFilePieces( &tor->info, i );
1130    }
1131
1132    for( i=0; i<tor->info.pieceCount; ++i )
1133      tor->info.pieces[i].priority = calculatePiecePriority( tor, i );
1134}
1135
1136void
1137tr_torrentSetFilePriority( tr_torrent_t   * tor,
1138                           int              fileIndex,
1139                           tr_priority_t    priority )
1140{
1141    int i;
1142    tr_file_t * file;
1143
1144    assert( tor != NULL );
1145    assert( 0<=fileIndex && fileIndex<tor->info.fileCount );
1146    assert( priority==TR_PRI_LOW || priority==TR_PRI_NORMAL
1147         || priority==TR_PRI_HIGH || priority==TR_PRI_DND );
1148
1149    file = &tor->info.files[fileIndex];
1150    file->priority = priority;
1151    for( i=file->firstPiece; i<=file->lastPiece; ++i )
1152      tor->info.pieces[i].priority = calculatePiecePriority( tor, i );
1153
1154    tr_dbg ( "Setting file #%d (pieces %d-%d) priority to %d (%s)",
1155             fileIndex, file->firstPiece, file->lastPiece,
1156             priority, tor->info.files[fileIndex].name );
1157}
1158
1159tr_priority_t
1160tr_torrentGetFilePriority( const tr_torrent_t *  tor, int file )
1161{
1162    assert( tor != NULL );
1163    assert( 0<=file && file<tor->info.fileCount );
1164
1165    return tor->info.files[file].priority;
1166}
1167
1168
1169void
1170tr_torrentSetFilePriorities( tr_torrent_t         * tor,
1171                             const tr_priority_t  * filePriorities )
1172{
1173    int i;
1174    for( i=0; i<tor->info.pieceCount; ++i )
1175      tr_torrentSetFilePriority( tor, i, filePriorities[i] );
1176}
1177
1178tr_priority_t*
1179tr_torrentGetFilePriorities( const tr_torrent_t * tor )
1180{
1181    int i;
1182    tr_priority_t * p = malloc( tor->info.fileCount * sizeof(tr_priority_t) );
1183    for( i=0; i<tor->info.fileCount; ++i )
1184        p[i] = tor->info.files[i].priority;
1185    return p;
1186}
Note: See TracBrowser for help on using the repository browser.