source: trunk/libtransmission/torrent.c @ 1829

Last change on this file since 1829 was 1829, checked in by livings124, 15 years ago

only allow one active transfer with the same name in the same location

  • Property svn:keywords set to Date Rev Author Id
File size: 22.9 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 1829 2007-05-05 14:43:52Z livings124 $
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
28/***********************************************************************
29 * Local prototypes
30 **********************************************************************/
31static tr_torrent_t * torrentRealInit( tr_handle_t *, tr_torrent_t * tor,
32                                       uint8_t *, int flags, int * error );
33static void torrentReallyStop( tr_torrent_t * );
34static void downloadLoop( void * );
35
36void tr_setUseCustomUpload( tr_torrent_t * tor, int limit )
37{
38    tor->customUploadLimit = limit;
39}
40
41void tr_setUseCustomDownload( tr_torrent_t * tor, int limit )
42{
43    tor->customDownloadLimit = limit;
44}
45
46void tr_setUploadLimit( tr_torrent_t * tor, int limit )
47{
48    tr_rcSetLimit( tor->upload, limit );
49}
50
51void tr_setDownloadLimit( tr_torrent_t * tor, int limit )
52{
53    tr_rcSetLimit( tor->download, limit );
54}
55
56tr_torrent_t *
57tr_torrentInit( tr_handle_t * h, const char * path,
58                uint8_t * hash, int flags, int * error )
59{
60    tr_torrent_t * tor;
61
62    tor  = calloc( 1, sizeof *tor );
63    if( NULL == tor )
64    {
65        *error = TR_EOTHER;
66        return NULL;
67    }
68
69    /* Parse torrent file */
70    if( tr_metainfoParseFile( &tor->info, h->tag, path,
71                              TR_FLAG_SAVE & flags ) )
72    {
73        *error = TR_EINVALID;
74        free( tor );
75        return NULL;
76    }
77
78    return torrentRealInit( h, tor, hash, flags, error );
79}
80
81tr_torrent_t *
82tr_torrentInitData( tr_handle_t * h, uint8_t * data, size_t size,
83                    uint8_t * hash, int flags, int * error )
84{
85    tr_torrent_t * tor;
86
87    tor  = calloc( 1, sizeof *tor );
88    if( NULL == tor )
89    {
90        *error = TR_EOTHER;
91        return NULL;
92    }
93
94    /* Parse torrent file */
95    if( tr_metainfoParseData( &tor->info, h->tag, data, size,
96                              TR_FLAG_SAVE & flags ) )
97    {
98        *error = TR_EINVALID;
99        free( tor );
100        return NULL;
101    }
102
103    return torrentRealInit( h, tor, hash, flags, error );
104}
105
106tr_torrent_t *
107tr_torrentInitSaved( tr_handle_t * h, const char * hashStr,
108                     int flags, int * error )
109{
110    tr_torrent_t * tor;
111
112    tor  = calloc( 1, sizeof *tor );
113    if( NULL == tor )
114    {
115        *error = TR_EOTHER;
116        return NULL;
117    }
118
119    /* Parse torrent file */
120    if( tr_metainfoParseHash( &tor->info, h->tag, hashStr ) )
121    {
122        *error = TR_EINVALID;
123        free( tor );
124        return NULL;
125    }
126
127    return torrentRealInit( h, tor, NULL, ( TR_FLAG_SAVE | flags ), error );
128}
129
130/***********************************************************************
131 * tr_torrentInit
132 ***********************************************************************
133 * Allocates a tr_torrent_t structure, then relies on tr_metainfoParse
134 * to fill it.
135 **********************************************************************/
136static tr_torrent_t * torrentRealInit( tr_handle_t * h, tr_torrent_t * tor,
137                                       uint8_t * hash, int flags, int * error )
138{
139    tr_torrent_t  * tor_tmp;
140    tr_info_t     * inf;
141    int             i;
142   
143    inf         = &tor->info;
144    inf->flags |= flags;
145
146    tr_sharedLock( h->shared );
147
148    /* Make sure this torrent is not already open */
149    for( tor_tmp = h->torrentList; tor_tmp; tor_tmp = tor_tmp->next )
150    {
151        if( !memcmp( tor->info.hash, tor_tmp->info.hash,
152                     SHA_DIGEST_LENGTH ) )
153        {
154            if( NULL != hash )
155            {
156                memcpy( hash, tor->info.hash, SHA_DIGEST_LENGTH );
157            }
158            *error = TR_EDUPLICATE;
159            tr_metainfoFree( &tor->info );
160            free( tor );
161            tr_sharedUnlock( h->shared );
162            return NULL;
163        }
164    }
165
166    tor->handle   = h;
167    tor->status   = TR_STATUS_PAUSE;
168    tor->id       = h->id;
169    tor->key      = h->key;
170    tor->azId     = h->azId;
171    tor->finished = 0;
172
173    /* Escaped info hash for HTTP queries */
174    for( i = 0; i < SHA_DIGEST_LENGTH; i++ )
175    {
176        snprintf( &tor->escapedHashString[3*i],
177                  sizeof( tor->escapedHashString ) - 3 * i,
178                  "%%%02x", inf->hash[i] );
179    }
180
181    tor->pexDisabled = 0;
182
183    /* Block size: usually 16 ko, or less if we have to */
184    tor->blockSize  = MIN( inf->pieceSize, 1 << 14 );
185    tor->blockCount = ( inf->totalSize + tor->blockSize - 1 ) /
186                        tor->blockSize;
187    tor->completion = tr_cpInit( tor );
188
189    tr_lockInit( &tor->lock );
190    tr_condInit( &tor->cond );
191
192    tor->upload         = tr_rcInit();
193    tor->download       = tr_rcInit();
194    tor->swarmspeed     = tr_rcInit();
195 
196    /* We have a new torrent */
197    tor->publicPort = tr_sharedGetPublicPort( h->shared );
198    tor->prev       = NULL;
199    tor->next       = h->torrentList;
200    if( tor->next )
201    {
202        tor->next->prev = tor;
203    }
204    h->torrentList = tor;
205    (h->torrentCount)++;
206
207    tr_sharedUnlock( h->shared );
208
209    if( !h->isPortSet )
210    {
211        tr_setBindPort( h, TR_DEFAULT_PORT );
212    }
213
214    return tor;
215}
216
217tr_info_t * tr_torrentInfo( tr_torrent_t * tor )
218{
219    return &tor->info;
220}
221
222/***********************************************************************
223 * tr_torrentScrape     
224 **********************************************************************/
225int tr_torrentScrape( tr_torrent_t * tor, int * s, int * l, int * d )
226{
227    return tr_trackerScrape( tor, s, l, d );
228}
229
230void tr_torrentSetFolder( tr_torrent_t * tor, const char * path )
231{
232    tor->destination = strdup( path );
233    tr_ioLoadResume( tor );
234}
235
236char * tr_torrentGetFolder( tr_torrent_t * tor )
237{
238    return tor->destination;
239}
240
241void tr_torrentStart( tr_torrent_t * tor )
242{
243    char name[32];
244    tr_torrent_t * current, * next;
245   
246    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
247    {
248        /* Join the thread first */
249        torrentReallyStop( tor );
250    }
251   
252    /* Don't start if a torrent with the same name and destination is already active */
253    for( current = tor->handle->torrentList; current; current = current->next )
254    {
255        if( current != tor && current->status != TR_STATUS_PAUSE
256            && !strcmp( tor->destination, current->destination )
257            && !strcmp( tor->info.name, current->info.name ) )
258        {
259            tor->error = TR_ERROR_IO_DUP_NAME;
260            snprintf( tor->errorString, sizeof( tor->errorString ),
261                          "%s", tr_errorString( TR_ERROR_IO_DUP_NAME ) );
262            return;
263        }
264    }
265
266    tr_lockLock( &tor->lock );
267
268    tor->downloadedPrev += tor->downloadedCur;
269    tor->downloadedCur   = 0;
270    tor->uploadedPrev   += tor->uploadedCur;
271    tor->uploadedCur     = 0;
272
273    tor->status  = TR_STATUS_CHECK;
274    tor->error   = TR_OK;
275    tor->tracker = tr_trackerInit( tor );
276
277    tor->date = tr_date();
278    tor->die = 0;
279    snprintf( name, sizeof( name ), "torrent %p", tor );
280
281    tr_lockUnlock( &tor->lock );
282
283    tr_threadCreate( &tor->thread, downloadLoop, tor, name );
284}
285
286static void torrentStop( tr_torrent_t * tor )
287{
288    tr_trackerStopped( tor->tracker );
289    tr_rcReset( tor->download );
290    tr_rcReset( tor->upload );
291    tr_rcReset( tor->swarmspeed );
292    tor->status = TR_STATUS_STOPPING;
293    tor->stopDate = tr_date();
294}
295
296void tr_torrentStop( tr_torrent_t * tor )
297{
298    tr_lockLock( &tor->lock );
299    torrentStop( tor );
300
301    /* Don't return until the files are closed, so the UI can trash
302     * them if requested */
303    tr_condWait( &tor->cond, &tor->lock );
304    tr_lockUnlock( &tor->lock );
305}
306
307/***********************************************************************
308 * torrentReallyStop
309 ***********************************************************************
310 * Joins the download thread and frees/closes everything related to it.
311 **********************************************************************/
312static void torrentReallyStop( tr_torrent_t * tor )
313{
314    int i;
315
316    tor->die = 1;
317    tr_threadJoin( &tor->thread );
318
319    tr_trackerClose( tor->tracker );
320    tor->tracker = NULL;
321
322    tr_lockLock( &tor->lock );
323    for( i = 0; i < tor->peerCount; i++ )
324    {
325        tr_peerDestroy( tor->peers[i] );
326    }
327    tor->peerCount = 0;
328    tr_lockUnlock( &tor->lock );
329}
330
331void tr_torrentDisablePex( tr_torrent_t * tor, int disable )
332{
333    int ii;
334
335    if( TR_FLAG_PRIVATE & tor->info.flags )
336    {
337        return;
338    }
339
340    tr_lockLock( &tor->lock );
341
342    if( tor->pexDisabled == disable )
343    {
344        tr_lockUnlock( &tor->lock );
345        return;
346    }
347
348    tor->pexDisabled = disable;
349    for( ii = 0; ii < tor->peerCount; ii++ )
350    {
351        tr_peerSetPrivate( tor->peers[ii], disable );
352    }
353
354    tr_lockUnlock( &tor->lock );
355}
356
357int tr_getFinished( tr_torrent_t * tor )
358{
359    if( tor->finished )
360    {
361        tor->finished = 0;
362        return 1;
363    }
364    return 0;
365}
366
367void tr_manualUpdate( tr_torrent_t * tor )
368{
369    int peerCount, new;
370    uint8_t * peerCompact;
371
372    if( !( tor->status & TR_STATUS_ACTIVE ) )
373        return;
374   
375    tr_lockLock( &tor->lock );
376    tr_trackerAnnouncePulse( tor->tracker, &peerCount, &peerCompact, 1 );
377    new = 0;
378    if( peerCount > 0 )
379    {
380        new = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
381                              peerCompact, peerCount );
382        free( peerCompact );
383    }
384    tr_dbg( "got %i peers from manual announce, used %i", peerCount, new );
385    tr_lockUnlock( &tor->lock );
386}
387
388tr_stat_t * tr_torrentStat( tr_torrent_t * tor )
389{
390    tr_stat_t * s;
391    tr_peer_t * peer;
392    tr_info_t * inf = &tor->info;
393    tr_tracker_t * tc;
394    int i;
395
396    tor->statCur = ( tor->statCur + 1 ) % 2;
397    s = &tor->stats[tor->statCur];
398
399    if( ( tor->status & TR_STATUS_STOPPED ) ||
400        ( ( tor->status & TR_STATUS_STOPPING ) &&
401          tr_date() > tor->stopDate + 60000 ) )
402    {
403        torrentReallyStop( tor );
404        tor->status = TR_STATUS_PAUSE;
405    }
406
407    tr_lockLock( &tor->lock );
408
409    s->status = tor->status;
410    s->error  = tor->error;
411    memcpy( s->errorString, tor->errorString,
412            sizeof( s->errorString ) );
413
414    tc = tor->tracker;
415    s->cannotConnect = tr_trackerCannotConnect( tc );
416    s->tracker = ( tc ? tr_trackerGet( tc ) : &inf->trackerList[0].list[0] );
417
418    s->peersTotal       = 0;
419    memset( s->peersFrom, 0, sizeof( s->peersFrom ) );
420    s->peersUploading   = 0;
421    s->peersDownloading = 0;
422   
423    for( i = 0; i < tor->peerCount; i++ )
424    {
425        peer = tor->peers[i];
426   
427        if( tr_peerIsConnected( peer ) )
428        {
429            (s->peersTotal)++;
430            (s->peersFrom[ tr_peerIsFrom( peer ) ])++;
431            if( tr_peerAmInterested( peer ) && !tr_peerIsChoking( peer ) )
432            {
433                (s->peersUploading)++;
434            }
435            if( !tr_peerAmChoking( peer ) )
436            {
437                (s->peersDownloading)++;
438            }
439        }
440    }
441
442    s->progress = tr_cpCompletionAsFloat( tor->completion );
443    s->left     = tr_cpLeftBytes( tor->completion );
444    if( tor->status & TR_STATUS_DOWNLOAD )
445    {
446        s->rateDownload = tr_rcRate( tor->download );
447    }
448    else
449    {
450        /* tr_rcRate() doesn't make the difference between 'piece'
451           messages and other messages, which causes a non-zero
452           download rate even tough we are not downloading. So we
453           force it to zero not to confuse the user. */
454        s->rateDownload = 0.0;
455    }
456    s->rateUpload = tr_rcRate( tor->upload );
457   
458    s->seeders  = tr_trackerSeeders( tc );
459    s->leechers = tr_trackerLeechers( tc );
460    s->completedFromTracker = tr_trackerDownloaded( tc );
461
462    s->swarmspeed = tr_rcRate( tor->swarmspeed );
463
464    if( s->rateDownload < 0.1 )
465    {
466        s->eta = -1;
467    }
468    else
469    {
470        s->eta = (float) s->left / s->rateDownload / 1024.0;
471    }
472
473    s->downloaded = tor->downloadedCur + tor->downloadedPrev;
474    s->uploaded   = tor->uploadedCur   + tor->uploadedPrev;
475   
476    if( s->downloaded == 0 && s->progress == 0.0 )
477    {
478        s->ratio = TR_RATIO_NA;
479    }
480    else
481    {
482        s->ratio = (float)s->uploaded / (float)MAX(s->downloaded, inf->totalSize - s->left);
483    }
484   
485    tr_lockUnlock( &tor->lock );
486
487    return s;
488}
489
490tr_peer_stat_t * tr_torrentPeers( tr_torrent_t * tor, int * peerCount )
491{
492    tr_peer_stat_t * peers;
493
494    tr_lockLock( &tor->lock );
495
496    *peerCount = tor->peerCount;
497   
498    peers = (tr_peer_stat_t *) calloc( tor->peerCount, sizeof( tr_peer_stat_t ) );
499    if (peers != NULL)
500    {
501        tr_peer_t * peer;
502        struct in_addr * addr;
503        int i;
504        for( i = 0; i < tor->peerCount; i++ )
505        {
506            peer = tor->peers[i];
507           
508            addr = tr_peerAddress( peer );
509            if( NULL != addr )
510            {
511                tr_netNtop( addr, peers[i].addr,
512                           sizeof( peers[i].addr ) );
513            }
514           
515            peers[i].client        = tr_peerClient( peer );
516            peers[i].isConnected   = tr_peerIsConnected( peer );
517            peers[i].from          = tr_peerIsFrom( peer );
518            peers[i].progress      = tr_peerProgress( peer );
519            peers[i].port          = tr_peerPort( peer );
520           
521            if( ( peers[i].isDownloading = !tr_peerAmChoking( peer ) ) )
522            {
523                peers[i].uploadToRate = tr_peerUploadRate( peer );
524            }
525            if( ( peers[i].isUploading = ( tr_peerAmInterested( peer ) &&
526                                           !tr_peerIsChoking( peer ) ) ) )
527            {
528                peers[i].downloadFromRate = tr_peerDownloadRate( peer );
529            }
530        }
531    }
532   
533    tr_lockUnlock( &tor->lock );
534   
535    return peers;
536}
537
538void tr_torrentPeersFree( tr_peer_stat_t * peers, int peerCount UNUSED )
539{
540    if (peers == NULL)
541        return;
542
543    free( peers );
544}
545
546void tr_torrentAvailability( tr_torrent_t * tor, int8_t * tab, int size )
547{
548    int i, j, piece;
549    float interval;
550
551    tr_lockLock( &tor->lock );
552    interval = (float)tor->info.pieceCount / (float)size;
553    for( i = 0; i < size; i++ )
554    {
555        piece = i * interval;
556
557        if( tr_cpPieceIsComplete( tor->completion, piece ) )
558        {
559            tab[i] = -1;
560            continue;
561        }
562
563        tab[i] = 0;
564        for( j = 0; j < tor->peerCount; j++ )
565        {
566            if( tr_peerBitfield( tor->peers[j] ) &&
567                tr_bitfieldHas( tr_peerBitfield( tor->peers[j] ), piece ) )
568            {
569                (tab[i])++;
570            }
571        }
572    }
573    tr_lockUnlock( &tor->lock );
574}
575
576float * tr_torrentCompletion( tr_torrent_t * tor )
577{
578    tr_info_t * inf = &tor->info;
579    int         piece, file;
580    float     * ret, prog, weight;
581    uint64_t    piecemax, piecesize;
582    uint64_t    filestart, fileoff, filelen, blockend, blockused;
583
584    tr_lockLock( &tor->lock );
585
586    ret       = calloc( inf->fileCount, sizeof( float ) );
587    file      = 0;
588    piecemax  = inf->pieceSize;
589    filestart = 0;
590    fileoff   = 0;
591    piece     = 0;
592    while( inf->pieceCount > piece )
593    {
594        assert( file < inf->fileCount );
595        assert( filestart + fileoff < inf->totalSize );
596        filelen    = inf->files[file].length;
597        piecesize  = tr_pieceSize( piece );
598        blockend   = MIN( filestart + filelen, piecemax * piece + piecesize );
599        blockused  = blockend - ( filestart + fileoff );
600        weight     = ( filelen ? ( float )blockused / ( float )filelen : 1.0 );
601        prog       = tr_cpPercentBlocksInPiece( tor->completion, piece );
602        ret[file] += prog * weight;
603        fileoff   += blockused;
604        assert( -0.1 < prog   && 1.1 > prog );
605        assert( -0.1 < weight && 1.1 > weight );
606        if( fileoff == filelen )
607        {
608            ret[file] = MIN( 1.0, ret[file] );
609            ret[file] = MAX( 0.0, ret[file] );
610            filestart += fileoff;
611            fileoff    = 0;
612            file++;
613        }
614        if( filestart + fileoff >= piecemax * piece + piecesize )
615        {
616            piece++;
617        }
618    }
619
620    tr_lockUnlock( &tor->lock );
621
622    return ret;
623}
624
625void tr_torrentAmountFinished( tr_torrent_t * tor, float * tab, int size )
626{
627    int i, piece;
628    float interval;
629
630    tr_lockLock( &tor->lock );
631    interval = (float)tor->info.pieceCount / (float)size;
632    for( i = 0; i < size; i++ )
633    {
634        piece = i * interval;
635        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
636    }
637    tr_lockUnlock( &tor->lock );
638}
639
640void tr_torrentRemoveSaved( tr_torrent_t * tor )
641{
642    tr_metainfoRemoveSaved( tor->info.hashString, tor->handle->tag );
643}
644
645void tr_torrentRemoveFastResume( tr_torrent_t * tor )
646{
647    tr_ioRemoveResume( tor );
648}
649
650/***********************************************************************
651 * tr_torrentClose
652 ***********************************************************************
653 * Frees memory allocated by tr_torrentInit.
654 **********************************************************************/
655void tr_torrentClose( tr_handle_t * h, tr_torrent_t * tor )
656{
657    tr_info_t * inf = &tor->info;
658
659    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
660    {
661        /* Join the thread first */
662        torrentReallyStop( tor );
663    }
664
665    tr_sharedLock( h->shared );
666
667    h->torrentCount--;
668
669    tr_lockClose( &tor->lock );
670    tr_condClose( &tor->cond );
671    tr_cpClose( tor->completion );
672
673    tr_rcClose( tor->upload );
674    tr_rcClose( tor->download );
675    tr_rcClose( tor->swarmspeed );
676
677    if( tor->destination )
678    {
679        free( tor->destination );
680    }
681
682    tr_metainfoFree( inf );
683
684    if( tor->prev )
685    {
686        tor->prev->next = tor->next;
687    }
688    else
689    {
690        h->torrentList = tor->next;
691    }
692    if( tor->next )
693    {
694        tor->next->prev = tor->prev;
695    }
696    free( tor );
697
698    tr_sharedUnlock( h->shared );
699}
700
701int tr_torrentAttachPeer( tr_torrent_t * tor, tr_peer_t * peer )
702{
703    int i;
704    tr_peer_t * otherPeer;
705
706    if( tor->peerCount >= TR_MAX_PEER_COUNT )
707    {
708        tr_peerDestroy(  peer );
709        return 0;
710    }
711
712    /* Don't accept two connections from the same IP */
713    for( i = 0; i < tor->peerCount; i++ )
714    {
715        otherPeer = tor->peers[i];
716        if( !memcmp( tr_peerAddress( peer ), tr_peerAddress( otherPeer ), 4 ) )
717        {
718            tr_peerDestroy(  peer );
719            return 0;
720        }
721    }
722
723    tr_peerSetPrivate( peer, tor->info.flags & TR_FLAG_PRIVATE ||
724                       tor->pexDisabled );
725    tr_peerSetTorrent( peer, tor );
726    tor->peers[tor->peerCount++] = peer;
727
728    return 1;
729}
730
731int tr_torrentAddCompact( tr_torrent_t * tor, int from,
732                           uint8_t * buf, int count )
733{
734    struct in_addr addr;
735    in_port_t port;
736    int i, added;
737    tr_peer_t * peer;
738
739    added = 0;
740    for( i = 0; i < count; i++ )
741    {
742        memcpy( &addr, buf, 4 ); buf += 4;
743        memcpy( &port, buf, 2 ); buf += 2;
744
745        peer = tr_peerInit( addr, port, -1, from );
746        added += tr_torrentAttachPeer( tor, peer );
747    }
748
749    return added;
750}
751
752/***********************************************************************
753 * downloadLoop
754 **********************************************************************/
755static void downloadLoop( void * _tor )
756{
757    tr_torrent_t * tor = _tor;
758    int            i, ret;
759    int            peerCount, used;
760    uint8_t      * peerCompact;
761    tr_peer_t    * peer;
762
763    tr_lockLock( &tor->lock );
764
765    tr_cpReset( tor->completion );
766    tor->io     = tr_ioInit( tor );
767    tor->status = tr_cpIsSeeding( tor->completion ) ?
768                      TR_STATUS_SEED : TR_STATUS_DOWNLOAD;
769
770    while( !tor->die )
771    {
772        tr_lockUnlock( &tor->lock );
773        tr_wait( 20 );
774        tr_lockLock( &tor->lock );
775
776        /* Are we finished ? */
777        if( ( tor->status & TR_STATUS_DOWNLOAD ) &&
778            tr_cpIsSeeding( tor->completion ) )
779        {
780            /* Done */
781            tor->status = TR_STATUS_SEED;
782                        tor->finished = 1;
783            tr_trackerCompleted( tor->tracker );
784            tr_ioSync( tor->io );
785        }
786
787        /* Try to get new peers or to send a message to the tracker */
788        tr_trackerPulse( tor->tracker, &peerCount, &peerCompact );
789        if( peerCount > 0 )
790        {
791            used = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
792                                         peerCompact, peerCount );
793            free( peerCompact );
794            tr_dbg( "got %i peers from announce, used %i", peerCount, used );
795        }
796        if( tor->status & TR_STATUS_STOPPED )
797        {
798            break;
799        }
800
801        /* Stopping: make sure all files are closed and stop talking
802           to peers */
803        if( tor->status & TR_STATUS_STOPPING )
804        {
805            if( tor->io )
806            {
807                tr_ioClose( tor->io ); tor->io = NULL;
808                tr_condSignal( &tor->cond );
809            }
810            continue;
811        }
812
813        /* Shuffle peers */
814        if( tor->peerCount > 1 )
815        {
816            peer = tor->peers[0];
817            memmove( &tor->peers[0], &tor->peers[1],
818                    ( tor->peerCount - 1 ) * sizeof( void * ) );
819            tor->peers[tor->peerCount - 1] = peer;
820        }
821
822        /* Receive/send messages */
823        for( i = 0; i < tor->peerCount; )
824        {
825            peer = tor->peers[i];
826
827            ret = tr_peerPulse( peer );
828            if( ret & TR_ERROR_IO_MASK )
829            {
830                tr_err( "Fatal error, stopping download (%d)", ret );
831                torrentStop( tor );
832                tor->error = ret;
833                snprintf( tor->errorString, sizeof( tor->errorString ),
834                          "%s", tr_errorString( ret ) );
835                break;
836            }
837            if( ret )
838            {
839                tr_peerDestroy( peer );
840                tor->peerCount--;
841                memmove( &tor->peers[i], &tor->peers[i+1],
842                         ( tor->peerCount - i ) * sizeof( void * ) );
843                continue;
844            }
845            i++;
846        }
847    }
848
849    tr_lockUnlock( &tor->lock );
850
851    if( tor->io )
852    {
853        tr_ioClose( tor->io ); tor->io = NULL;
854        tr_condSignal( &tor->cond );
855    }
856
857    tor->status = TR_STATUS_STOPPED;
858}
859
Note: See TracBrowser for help on using the repository browser.