source: branches/daemon/libtransmission/torrent.c @ 1634

Last change on this file since 1634 was 1634, checked in by joshe, 15 years ago

Add API function for adding a torrent from data, instead of a filename.

  • Property svn:keywords set to Date Rev Author Id
File size: 22.2 KB
Line 
1/******************************************************************************
2 * $Id: torrent.c 1634 2007-04-02 20:32:20Z joshe $
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    if( tor->status & TR_STATUS_DOWNLOAD )
429    {
430        s->rateDownload = tr_rcRate( tor->download );
431    }
432    else
433    {
434        /* tr_rcRate() doesn't make the difference between 'piece'
435           messages and other messages, which causes a non-zero
436           download rate even tough we are not downloading. So we
437           force it to zero not to confuse the user. */
438        s->rateDownload = 0.0;
439    }
440    s->rateUpload = tr_rcRate( tor->upload );
441   
442    s->seeders  = tr_trackerSeeders( tc );
443    s->leechers = tr_trackerLeechers( tc );
444    s->completedFromTracker = tr_trackerDownloaded( tc );
445
446    s->swarmspeed = tr_rcRate( tor->swarmspeed );
447
448    if( s->rateDownload < 0.1 )
449    {
450        s->eta = -1;
451    }
452    else
453    {
454        s->eta = ( 1.0 - s->progress ) *
455            (float) inf->totalSize / 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 )
462    {
463        s->ratio = s->uploaded == 0 ? TR_RATIO_NA : TR_RATIO_INF;
464    }
465    else
466    {
467        s->ratio = (float)s->uploaded / (float)s->downloaded;
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_clientForId(tr_peerId(peer));
501           
502            peers[i].isConnected   = tr_peerIsConnected( peer );
503            peers[i].from          = tr_peerIsFrom( peer );
504            peers[i].progress      = tr_peerProgress( peer );
505            peers[i].port          = tr_peerPort( peer );
506           
507            if( ( peers[i].isDownloading = !tr_peerAmChoking( peer ) ) )
508            {
509                peers[i].uploadToRate = tr_peerUploadRate( peer );
510            }
511            if( ( peers[i].isUploading = ( tr_peerAmInterested( peer ) &&
512                                           !tr_peerIsChoking( peer ) ) ) )
513            {
514                peers[i].downloadFromRate = tr_peerDownloadRate( peer );
515            }
516        }
517    }
518   
519    tr_lockUnlock( &tor->lock );
520   
521    return peers;
522}
523
524void tr_torrentPeersFree( tr_peer_stat_t * peers, int peerCount )
525{
526    int i;
527
528    if (peers == NULL)
529        return;
530
531    for (i = 0; i < peerCount; i++)
532        free( peers[i].client );
533
534    free( peers );
535}
536
537void tr_torrentAvailability( tr_torrent_t * tor, int8_t * tab, int size )
538{
539    int i, j, piece;
540    float interval;
541
542    tr_lockLock( &tor->lock );
543    interval = (float)tor->info.pieceCount / (float)size;
544    for( i = 0; i < size; i++ )
545    {
546        piece = i * interval;
547
548        if( tr_cpPieceIsComplete( tor->completion, piece ) )
549        {
550            tab[i] = -1;
551            continue;
552        }
553
554        tab[i] = 0;
555        for( j = 0; j < tor->peerCount; j++ )
556        {
557            if( tr_peerBitfield( tor->peers[j] ) &&
558                tr_bitfieldHas( tr_peerBitfield( tor->peers[j] ), piece ) )
559            {
560                (tab[i])++;
561            }
562        }
563    }
564    tr_lockUnlock( &tor->lock );
565}
566
567float * tr_torrentCompletion( tr_torrent_t * tor )
568{
569    tr_info_t * inf = &tor->info;
570    int         piece, file;
571    float     * ret, prog, weight;
572    uint64_t    piecemax, piecesize;
573    uint64_t    filestart, fileoff, filelen, blockend, blockused;
574
575    tr_lockLock( &tor->lock );
576
577    ret       = calloc( inf->fileCount, sizeof( float ) );
578    file      = 0;
579    piecemax  = inf->pieceSize;
580    filestart = 0;
581    fileoff   = 0;
582    piece     = 0;
583    while( inf->pieceCount > piece )
584    {
585        assert( file < inf->fileCount );
586        assert( filestart + fileoff < inf->totalSize );
587        filelen    = inf->files[file].length;
588        piecesize  = tr_pieceSize( piece );
589        blockend   = MIN( filestart + filelen, piecemax * piece + piecesize );
590        blockused  = blockend - ( filestart + fileoff );
591        weight     = ( filelen ? ( float )blockused / ( float )filelen : 1.0 );
592        prog       = tr_cpPercentBlocksInPiece( tor->completion, piece );
593        ret[file] += prog * weight;
594        fileoff   += blockused;
595        assert( -0.1 < prog   && 1.1 > prog );
596        assert( -0.1 < weight && 1.1 > weight );
597        if( fileoff == filelen )
598        {
599            ret[file] = MIN( 1.0, ret[file] );
600            ret[file] = MAX( 0.0, ret[file] );
601            filestart += fileoff;
602            fileoff    = 0;
603            file++;
604        }
605        if( filestart + fileoff >= piecemax * piece + piecesize )
606        {
607            piece++;
608        }
609    }
610
611    tr_lockUnlock( &tor->lock );
612
613    return ret;
614}
615
616void tr_torrentAmountFinished( tr_torrent_t * tor, float * tab, int size )
617{
618    int i, piece;
619    float interval;
620
621    tr_lockLock( &tor->lock );
622    interval = (float)tor->info.pieceCount / (float)size;
623    for( i = 0; i < size; i++ )
624    {
625        piece = i * interval;
626        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
627    }
628    tr_lockUnlock( &tor->lock );
629}
630
631void tr_torrentRemoveSaved( tr_torrent_t * tor )
632{
633    tr_metainfoRemoveSaved( tor->info.hashString, tor->handle->tag );
634}
635
636/***********************************************************************
637 * tr_torrentClose
638 ***********************************************************************
639 * Frees memory allocated by tr_torrentInit.
640 **********************************************************************/
641void tr_torrentClose( tr_handle_t * h, tr_torrent_t * tor )
642{
643    tr_info_t * inf = &tor->info;
644
645    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
646    {
647        /* Join the thread first */
648        torrentReallyStop( tor );
649    }
650
651    tr_sharedLock( h->shared );
652
653    h->torrentCount--;
654
655    tr_lockClose( &tor->lock );
656    tr_condClose( &tor->cond );
657    tr_cpClose( tor->completion );
658
659    tr_rcClose( tor->upload );
660    tr_rcClose( tor->download );
661    tr_rcClose( tor->swarmspeed );
662
663    if( tor->destination )
664    {
665        free( tor->destination );
666    }
667
668    tr_metainfoFree( inf );
669
670    if( tor->prev )
671    {
672        tor->prev->next = tor->next;
673    }
674    else
675    {
676        h->torrentList = tor->next;
677    }
678    if( tor->next )
679    {
680        tor->next->prev = tor->prev;
681    }
682    free( tor );
683
684    tr_sharedUnlock( h->shared );
685}
686
687int tr_torrentAttachPeer( tr_torrent_t * tor, tr_peer_t * peer )
688{
689    int i;
690    tr_peer_t * otherPeer;
691
692    if( tor->peerCount >= TR_MAX_PEER_COUNT )
693    {
694        tr_peerDestroy(  peer );
695        return 0;
696    }
697
698    /* Don't accept two connections from the same IP */
699    for( i = 0; i < tor->peerCount; i++ )
700    {
701        otherPeer = tor->peers[i];
702        if( !memcmp( tr_peerAddress( peer ), tr_peerAddress( otherPeer ), 4 ) )
703        {
704            tr_peerDestroy(  peer );
705            return 0;
706        }
707    }
708
709    tr_peerSetPrivate( peer, tor->info.flags & TR_FLAG_PRIVATE ||
710                       tor->pexDisabled );
711    tr_peerSetTorrent( peer, tor );
712    tor->peers[tor->peerCount++] = peer;
713
714    return 1;
715}
716
717int tr_torrentAddCompact( tr_torrent_t * tor, int from,
718                           uint8_t * buf, int count )
719{
720    struct in_addr addr;
721    in_port_t port;
722    int i, added;
723    tr_peer_t * peer;
724
725    added = 0;
726    for( i = 0; i < count; i++ )
727    {
728        memcpy( &addr, buf, 4 ); buf += 4;
729        memcpy( &port, buf, 2 ); buf += 2;
730
731        peer = tr_peerInit( addr, port, -1, from );
732        added += tr_torrentAttachPeer( tor, peer );
733    }
734
735    return added;
736}
737
738/***********************************************************************
739 * downloadLoop
740 **********************************************************************/
741static void downloadLoop( void * _tor )
742{
743    tr_torrent_t * tor = _tor;
744    int            i, ret;
745    int            peerCount, used;
746    uint8_t      * peerCompact;
747    tr_peer_t    * peer;
748
749    tr_lockLock( &tor->lock );
750
751    tr_cpReset( tor->completion );
752    tor->io     = tr_ioInit( tor );
753    tor->status = tr_cpIsSeeding( tor->completion ) ?
754                      TR_STATUS_SEED : TR_STATUS_DOWNLOAD;
755
756    while( !tor->die )
757    {
758        tr_lockUnlock( &tor->lock );
759        tr_wait( 20 );
760        tr_lockLock( &tor->lock );
761
762        /* Are we finished ? */
763        if( ( tor->status & TR_STATUS_DOWNLOAD ) &&
764            tr_cpIsSeeding( tor->completion ) )
765        {
766            /* Done */
767            tor->status = TR_STATUS_SEED;
768                        tor->finished = 1;
769            tr_trackerCompleted( tor->tracker );
770            tr_ioSync( tor->io );
771        }
772
773        /* Try to get new peers or to send a message to the tracker */
774        tr_trackerPulse( tor->tracker, &peerCount, &peerCompact );
775        if( peerCount > 0 )
776        {
777            used = tr_torrentAddCompact( tor, TR_PEER_FROM_TRACKER,
778                                         peerCompact, peerCount );
779            free( peerCompact );
780            tr_dbg( "got %i peers from announce, used %i", peerCount, used );
781        }
782        if( tor->status & TR_STATUS_STOPPED )
783        {
784            break;
785        }
786
787        /* Stopping: make sure all files are closed and stop talking
788           to peers */
789        if( tor->status & TR_STATUS_STOPPING )
790        {
791            if( tor->io )
792            {
793                tr_ioClose( tor->io ); tor->io = NULL;
794                tr_condSignal( &tor->cond );
795            }
796            continue;
797        }
798
799        /* Shuffle peers */
800        if( tor->peerCount > 1 )
801        {
802            peer = tor->peers[0];
803            memmove( &tor->peers[0], &tor->peers[1],
804                    ( tor->peerCount - 1 ) * sizeof( void * ) );
805            tor->peers[tor->peerCount - 1] = peer;
806        }
807
808        /* Receive/send messages */
809        for( i = 0; i < tor->peerCount; )
810        {
811            peer = tor->peers[i];
812
813            ret = tr_peerPulse( peer );
814            if( ret & TR_ERROR_IO_MASK )
815            {
816                tr_err( "Fatal error, stopping download (%d)", ret );
817                torrentStop( tor );
818                tor->error = ret;
819                snprintf( tor->errorString, sizeof( tor->errorString ),
820                          "%s", tr_errorString( ret ) );
821                break;
822            }
823            if( ret )
824            {
825                tr_peerDestroy( peer );
826                tor->peerCount--;
827                memmove( &tor->peers[i], &tor->peers[i+1],
828                         ( tor->peerCount - i ) * sizeof( void * ) );
829                continue;
830            }
831            i++;
832        }
833    }
834
835    tr_lockUnlock( &tor->lock );
836
837    if( tor->io )
838    {
839        tr_ioClose( tor->io ); tor->io = NULL;
840        tr_condSignal( &tor->cond );
841    }
842
843    tor->status = TR_STATUS_STOPPED;
844}
845
Note: See TracBrowser for help on using the repository browser.