source: trunk/libtransmission/torrent.c @ 1767

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

expand the last commit a bit so that ratio is calculated with the actual downloaded amount if amount downloaded in T is 0. This should eliminate ever showing infinity for ratio.

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