source: trunk/libtransmission/torrent.c @ 1772

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

streamline eta calculation

  • Property svn:keywords set to Date Rev Author Id
File size: 22.1 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 1772 2007-04-21 13:57:30Z 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
245    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
246    {
247        /* Join the thread first */
248        torrentReallyStop( tor );
249    }
250
251    tr_lockLock( &tor->lock );
252
253    tor->downloadedPrev += tor->downloadedCur;
254    tor->downloadedCur   = 0;
255    tor->uploadedPrev   += tor->uploadedCur;
256    tor->uploadedCur     = 0;
257
258    tor->status  = TR_STATUS_CHECK;
259    tor->error   = TR_OK;
260    tor->tracker = tr_trackerInit( tor );
261
262    tor->date = tr_date();
263    tor->die = 0;
264    snprintf( name, sizeof( name ), "torrent %p", tor );
265
266    tr_lockUnlock( &tor->lock );
267
268    tr_threadCreate( &tor->thread, downloadLoop, tor, name );
269}
270
271static void torrentStop( tr_torrent_t * tor )
272{
273    tr_trackerStopped( tor->tracker );
274    tr_rcReset( tor->download );
275    tr_rcReset( tor->upload );
276    tr_rcReset( tor->swarmspeed );
277    tor->status = TR_STATUS_STOPPING;
278    tor->stopDate = tr_date();
279}
280
281void tr_torrentStop( tr_torrent_t * tor )
282{
283    tr_lockLock( &tor->lock );
284    torrentStop( tor );
285
286    /* Don't return until the files are closed, so the UI can trash
287     * them if requested */
288    tr_condWait( &tor->cond, &tor->lock );
289    tr_lockUnlock( &tor->lock );
290}
291
292/***********************************************************************
293 * torrentReallyStop
294 ***********************************************************************
295 * Joins the download thread and frees/closes everything related to it.
296 **********************************************************************/
297static void torrentReallyStop( tr_torrent_t * tor )
298{
299    int i;
300
301    tor->die = 1;
302    tr_threadJoin( &tor->thread );
303
304    tr_trackerClose( tor->tracker );
305    tor->tracker = NULL;
306
307    tr_lockLock( &tor->lock );
308    for( i = 0; i < tor->peerCount; i++ )
309    {
310        tr_peerDestroy( tor->peers[i] );
311    }
312    tor->peerCount = 0;
313    tr_lockUnlock( &tor->lock );
314}
315
316void tr_torrentDisablePex( tr_torrent_t * tor, int disable )
317{
318    int ii;
319
320    if( TR_FLAG_PRIVATE & tor->info.flags )
321    {
322        return;
323    }
324
325    tr_lockLock( &tor->lock );
326
327    if( tor->pexDisabled == disable )
328    {
329        tr_lockUnlock( &tor->lock );
330        return;
331    }
332
333    tor->pexDisabled = disable;
334    for( ii = 0; ii < tor->peerCount; ii++ )
335    {
336        tr_peerSetPrivate( tor->peers[ii], disable );
337    }
338
339    tr_lockUnlock( &tor->lock );
340}
341
342int tr_getFinished( tr_torrent_t * tor )
343{
344    if( tor->finished )
345    {
346        tor->finished = 0;
347        return 1;
348    }
349    return 0;
350}
351
352void tr_manualUpdate( tr_torrent_t * tor )
353{
354    int peerCount, new;
355    uint8_t * peerCompact;
356
357    if( !( tor->status & TR_STATUS_ACTIVE ) )
358        return;
359   
360    tr_lockLock( &tor->lock );
361    tr_trackerAnnouncePulse( tor->tracker, &peerCount, &peerCompact, 1 );
362    new = 0;
363    if( peerCount > 0 )
364    {
365        new = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
366                              peerCompact, peerCount );
367        free( peerCompact );
368    }
369    tr_dbg( "got %i peers from manual announce, used %i", peerCount, new );
370    tr_lockUnlock( &tor->lock );
371}
372
373tr_stat_t * tr_torrentStat( tr_torrent_t * tor )
374{
375    tr_stat_t * s;
376    tr_peer_t * peer;
377    tr_info_t * inf = &tor->info;
378    tr_tracker_t * tc;
379    int i;
380
381    tor->statCur = ( tor->statCur + 1 ) % 2;
382    s = &tor->stats[tor->statCur];
383
384    if( ( tor->status & TR_STATUS_STOPPED ) ||
385        ( ( tor->status & TR_STATUS_STOPPING ) &&
386          tr_date() > tor->stopDate + 60000 ) )
387    {
388        torrentReallyStop( tor );
389        tor->status = TR_STATUS_PAUSE;
390    }
391
392    tr_lockLock( &tor->lock );
393
394    s->status = tor->status;
395    s->error  = tor->error;
396    memcpy( s->errorString, tor->errorString,
397            sizeof( s->errorString ) );
398
399    tc = tor->tracker;
400    s->cannotConnect = tr_trackerCannotConnect( tc );
401    s->tracker = ( tc ? tr_trackerGet( tc ) : &inf->trackerList[0].list[0] );
402
403    s->peersTotal       = 0;
404    memset( s->peersFrom, 0, sizeof( s->peersFrom ) );
405    s->peersUploading   = 0;
406    s->peersDownloading = 0;
407   
408    for( i = 0; i < tor->peerCount; i++ )
409    {
410        peer = tor->peers[i];
411   
412        if( tr_peerIsConnected( peer ) )
413        {
414            (s->peersTotal)++;
415            (s->peersFrom[ tr_peerIsFrom( peer ) ])++;
416            if( tr_peerAmInterested( peer ) && !tr_peerIsChoking( peer ) )
417            {
418                (s->peersUploading)++;
419            }
420            if( !tr_peerAmChoking( peer ) )
421            {
422                (s->peersDownloading)++;
423            }
424        }
425    }
426
427    s->progress = tr_cpCompletionAsFloat( tor->completion );
428    s->left     = tr_cpLeftBytes( tor->completion );
429    if( tor->status & TR_STATUS_DOWNLOAD )
430    {
431        s->rateDownload = tr_rcRate( tor->download );
432    }
433    else
434    {
435        /* tr_rcRate() doesn't make the difference between 'piece'
436           messages and other messages, which causes a non-zero
437           download rate even tough we are not downloading. So we
438           force it to zero not to confuse the user. */
439        s->rateDownload = 0.0;
440    }
441    s->rateUpload = tr_rcRate( tor->upload );
442   
443    s->seeders  = tr_trackerSeeders( tc );
444    s->leechers = tr_trackerLeechers( tc );
445    s->completedFromTracker = tr_trackerDownloaded( tc );
446
447    s->swarmspeed = tr_rcRate( tor->swarmspeed );
448
449    if( s->rateDownload < 0.1 )
450    {
451        s->eta = -1;
452    }
453    else
454    {
455        s->eta = (float) s->left / s->rateDownload / 1024.0;
456    }
457
458    s->downloaded = tor->downloadedCur + tor->downloadedPrev;
459    s->uploaded   = tor->uploadedCur   + tor->uploadedPrev;
460   
461    if( s->downloaded == 0 && s->progress == 0.0 )
462    {
463        s->ratio = TR_RATIO_NA;
464    }
465    else
466    {
467        s->ratio = (float)s->uploaded / (float)MAX(s->downloaded, inf->totalSize - s->left);
468    }
469   
470    tr_lockUnlock( &tor->lock );
471
472    return s;
473}
474
475tr_peer_stat_t * tr_torrentPeers( tr_torrent_t * tor, int * peerCount )
476{
477    tr_peer_stat_t * peers;
478
479    tr_lockLock( &tor->lock );
480
481    *peerCount = tor->peerCount;
482   
483    peers = (tr_peer_stat_t *) calloc( tor->peerCount, sizeof( tr_peer_stat_t ) );
484    if (peers != NULL)
485    {
486        tr_peer_t * peer;
487        struct in_addr * addr;
488        int i;
489        for( i = 0; i < tor->peerCount; i++ )
490        {
491            peer = tor->peers[i];
492           
493            addr = tr_peerAddress( peer );
494            if( NULL != addr )
495            {
496                tr_netNtop( addr, peers[i].addr,
497                           sizeof( peers[i].addr ) );
498            }
499           
500            peers[i].client        = tr_peerClient( peer );
501            peers[i].isConnected   = tr_peerIsConnected( peer );
502            peers[i].from          = tr_peerIsFrom( peer );
503            peers[i].progress      = tr_peerProgress( peer );
504            peers[i].port          = tr_peerPort( peer );
505           
506            if( ( peers[i].isDownloading = !tr_peerAmChoking( peer ) ) )
507            {
508                peers[i].uploadToRate = tr_peerUploadRate( peer );
509            }
510            if( ( peers[i].isUploading = ( tr_peerAmInterested( peer ) &&
511                                           !tr_peerIsChoking( peer ) ) ) )
512            {
513                peers[i].downloadFromRate = tr_peerDownloadRate( peer );
514            }
515        }
516    }
517   
518    tr_lockUnlock( &tor->lock );
519   
520    return peers;
521}
522
523void tr_torrentPeersFree( tr_peer_stat_t * peers, int peerCount UNUSED )
524{
525    if (peers == NULL)
526        return;
527
528    free( peers );
529}
530
531void tr_torrentAvailability( tr_torrent_t * tor, int8_t * tab, int size )
532{
533    int i, j, piece;
534    float interval;
535
536    tr_lockLock( &tor->lock );
537    interval = (float)tor->info.pieceCount / (float)size;
538    for( i = 0; i < size; i++ )
539    {
540        piece = i * interval;
541
542        if( tr_cpPieceIsComplete( tor->completion, piece ) )
543        {
544            tab[i] = -1;
545            continue;
546        }
547
548        tab[i] = 0;
549        for( j = 0; j < tor->peerCount; j++ )
550        {
551            if( tr_peerBitfield( tor->peers[j] ) &&
552                tr_bitfieldHas( tr_peerBitfield( tor->peers[j] ), piece ) )
553            {
554                (tab[i])++;
555            }
556        }
557    }
558    tr_lockUnlock( &tor->lock );
559}
560
561float * tr_torrentCompletion( tr_torrent_t * tor )
562{
563    tr_info_t * inf = &tor->info;
564    int         piece, file;
565    float     * ret, prog, weight;
566    uint64_t    piecemax, piecesize;
567    uint64_t    filestart, fileoff, filelen, blockend, blockused;
568
569    tr_lockLock( &tor->lock );
570
571    ret       = calloc( inf->fileCount, sizeof( float ) );
572    file      = 0;
573    piecemax  = inf->pieceSize;
574    filestart = 0;
575    fileoff   = 0;
576    piece     = 0;
577    while( inf->pieceCount > piece )
578    {
579        assert( file < inf->fileCount );
580        assert( filestart + fileoff < inf->totalSize );
581        filelen    = inf->files[file].length;
582        piecesize  = tr_pieceSize( piece );
583        blockend   = MIN( filestart + filelen, piecemax * piece + piecesize );
584        blockused  = blockend - ( filestart + fileoff );
585        weight     = ( filelen ? ( float )blockused / ( float )filelen : 1.0 );
586        prog       = tr_cpPercentBlocksInPiece( tor->completion, piece );
587        ret[file] += prog * weight;
588        fileoff   += blockused;
589        assert( -0.1 < prog   && 1.1 > prog );
590        assert( -0.1 < weight && 1.1 > weight );
591        if( fileoff == filelen )
592        {
593            ret[file] = MIN( 1.0, ret[file] );
594            ret[file] = MAX( 0.0, ret[file] );
595            filestart += fileoff;
596            fileoff    = 0;
597            file++;
598        }
599        if( filestart + fileoff >= piecemax * piece + piecesize )
600        {
601            piece++;
602        }
603    }
604
605    tr_lockUnlock( &tor->lock );
606
607    return ret;
608}
609
610void tr_torrentAmountFinished( tr_torrent_t * tor, float * tab, int size )
611{
612    int i, piece;
613    float interval;
614
615    tr_lockLock( &tor->lock );
616    interval = (float)tor->info.pieceCount / (float)size;
617    for( i = 0; i < size; i++ )
618    {
619        piece = i * interval;
620        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
621    }
622    tr_lockUnlock( &tor->lock );
623}
624
625void tr_torrentRemoveSaved( tr_torrent_t * tor )
626{
627    tr_metainfoRemoveSaved( tor->info.hashString, tor->handle->tag );
628}
629
630/***********************************************************************
631 * tr_torrentClose
632 ***********************************************************************
633 * Frees memory allocated by tr_torrentInit.
634 **********************************************************************/
635void tr_torrentClose( tr_handle_t * h, tr_torrent_t * tor )
636{
637    tr_info_t * inf = &tor->info;
638
639    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
640    {
641        /* Join the thread first */
642        torrentReallyStop( tor );
643    }
644
645    tr_sharedLock( h->shared );
646
647    h->torrentCount--;
648
649    tr_lockClose( &tor->lock );
650    tr_condClose( &tor->cond );
651    tr_cpClose( tor->completion );
652
653    tr_rcClose( tor->upload );
654    tr_rcClose( tor->download );
655    tr_rcClose( tor->swarmspeed );
656
657    if( tor->destination )
658    {
659        free( tor->destination );
660    }
661
662    tr_metainfoFree( inf );
663
664    if( tor->prev )
665    {
666        tor->prev->next = tor->next;
667    }
668    else
669    {
670        h->torrentList = tor->next;
671    }
672    if( tor->next )
673    {
674        tor->next->prev = tor->prev;
675    }
676    free( tor );
677
678    tr_sharedUnlock( h->shared );
679}
680
681int tr_torrentAttachPeer( tr_torrent_t * tor, tr_peer_t * peer )
682{
683    int i;
684    tr_peer_t * otherPeer;
685
686    if( tor->peerCount >= TR_MAX_PEER_COUNT )
687    {
688        tr_peerDestroy(  peer );
689        return 0;
690    }
691
692    /* Don't accept two connections from the same IP */
693    for( i = 0; i < tor->peerCount; i++ )
694    {
695        otherPeer = tor->peers[i];
696        if( !memcmp( tr_peerAddress( peer ), tr_peerAddress( otherPeer ), 4 ) )
697        {
698            tr_peerDestroy(  peer );
699            return 0;
700        }
701    }
702
703    tr_peerSetPrivate( peer, tor->info.flags & TR_FLAG_PRIVATE ||
704                       tor->pexDisabled );
705    tr_peerSetTorrent( peer, tor );
706    tor->peers[tor->peerCount++] = peer;
707
708    return 1;
709}
710
711int tr_torrentAddCompact( tr_torrent_t * tor, int from,
712                           uint8_t * buf, int count )
713{
714    struct in_addr addr;
715    in_port_t port;
716    int i, added;
717    tr_peer_t * peer;
718
719    added = 0;
720    for( i = 0; i < count; i++ )
721    {
722        memcpy( &addr, buf, 4 ); buf += 4;
723        memcpy( &port, buf, 2 ); buf += 2;
724
725        peer = tr_peerInit( addr, port, -1, from );
726        added += tr_torrentAttachPeer( tor, peer );
727    }
728
729    return added;
730}
731
732/***********************************************************************
733 * downloadLoop
734 **********************************************************************/
735static void downloadLoop( void * _tor )
736{
737    tr_torrent_t * tor = _tor;
738    int            i, ret;
739    int            peerCount, used;
740    uint8_t      * peerCompact;
741    tr_peer_t    * peer;
742
743    tr_lockLock( &tor->lock );
744
745    tr_cpReset( tor->completion );
746    tor->io     = tr_ioInit( tor );
747    tor->status = tr_cpIsSeeding( tor->completion ) ?
748                      TR_STATUS_SEED : TR_STATUS_DOWNLOAD;
749
750    while( !tor->die )
751    {
752        tr_lockUnlock( &tor->lock );
753        tr_wait( 20 );
754        tr_lockLock( &tor->lock );
755
756        /* Are we finished ? */
757        if( ( tor->status & TR_STATUS_DOWNLOAD ) &&
758            tr_cpIsSeeding( tor->completion ) )
759        {
760            /* Done */
761            tor->status = TR_STATUS_SEED;
762                        tor->finished = 1;
763            tr_trackerCompleted( tor->tracker );
764            tr_ioSync( tor->io );
765        }
766
767        /* Try to get new peers or to send a message to the tracker */
768        tr_trackerPulse( tor->tracker, &peerCount, &peerCompact );
769        if( peerCount > 0 )
770        {
771            used = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
772                                         peerCompact, peerCount );
773            free( peerCompact );
774            tr_dbg( "got %i peers from announce, used %i", peerCount, used );
775        }
776        if( tor->status & TR_STATUS_STOPPED )
777        {
778            break;
779        }
780
781        /* Stopping: make sure all files are closed and stop talking
782           to peers */
783        if( tor->status & TR_STATUS_STOPPING )
784        {
785            if( tor->io )
786            {
787                tr_ioClose( tor->io ); tor->io = NULL;
788                tr_condSignal( &tor->cond );
789            }
790            continue;
791        }
792
793        /* Shuffle peers */
794        if( tor->peerCount > 1 )
795        {
796            peer = tor->peers[0];
797            memmove( &tor->peers[0], &tor->peers[1],
798                    ( tor->peerCount - 1 ) * sizeof( void * ) );
799            tor->peers[tor->peerCount - 1] = peer;
800        }
801
802        /* Receive/send messages */
803        for( i = 0; i < tor->peerCount; )
804        {
805            peer = tor->peers[i];
806
807            ret = tr_peerPulse( peer );
808            if( ret & TR_ERROR_IO_MASK )
809            {
810                tr_err( "Fatal error, stopping download (%d)", ret );
811                torrentStop( tor );
812                tor->error = ret;
813                snprintf( tor->errorString, sizeof( tor->errorString ),
814                          "%s", tr_errorString( ret ) );
815                break;
816            }
817            if( ret )
818            {
819                tr_peerDestroy( peer );
820                tor->peerCount--;
821                memmove( &tor->peers[i], &tor->peers[i+1],
822                         ( tor->peerCount - i ) * sizeof( void * ) );
823                continue;
824            }
825            i++;
826        }
827    }
828
829    tr_lockUnlock( &tor->lock );
830
831    if( tor->io )
832    {
833        tr_ioClose( tor->io ); tor->io = NULL;
834        tr_condSignal( &tor->cond );
835    }
836
837    tor->status = TR_STATUS_STOPPED;
838}
839
Note: See TracBrowser for help on using the repository browser.