source: branches/multitracker/libtransmission/transmission.c @ 1234

Last change on this file since 1234 was 1234, checked in by livings124, 16 years ago

libT can now better report if it can connect to a tracker, and as a result the mac's queue system will now start the next for any error (not just those sent by the tracker)

  • Property svn:keywords set to Date Rev Author Id
File size: 25.2 KB
Line 
1/******************************************************************************
2 * $Id: transmission.c 1234 2006-12-16 01:58:07Z livings124 $
3 *
4 * Copyright (c) 2005-2006 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
27/***********************************************************************
28 * Local prototypes
29 **********************************************************************/
30static tr_torrent_t * torrentRealInit( tr_handle_t *, tr_torrent_t * tor,
31                                       int flags, int * error );
32static void torrentReallyStop( tr_torrent_t * );
33static void downloadLoop( void * );
34static void acceptLoop( void * );
35static void acceptStop( tr_handle_t * h );
36
37/***********************************************************************
38 * tr_init
39 ***********************************************************************
40 * Allocates a tr_handle_t structure and initializes a few things
41 **********************************************************************/
42tr_handle_t * tr_init()
43{
44    tr_handle_t * h;
45    int           i, r;
46
47    tr_msgInit();
48    tr_netResolveThreadInit();
49
50    h = calloc( sizeof( tr_handle_t ), 1 );
51
52    /* Generate a peer id : "-TRxxyy-" + 12 random alphanumeric
53       characters, where xx is the major version number and yy the
54       minor version number (Azureus-style) */
55    sprintf( h->id, "-TR%02d%02d-", VERSION_MAJOR, VERSION_MINOR );
56    for( i = 8; i < 20; i++ )
57    {
58        r        = tr_rand( 36 );
59        h->id[i] = ( r < 26 ) ? ( 'a' + r ) : ( '0' + r - 26 ) ;
60    }
61
62    /* Random key */
63    for( i = 0; i < 20; i++ )
64    {
65        r         = tr_rand( 36 );
66        h->key[i] = ( r < 26 ) ? ( 'a' + r ) : ( '0' + r - 26 ) ;
67    }
68
69    /* Don't exit when writing on a broken socket */
70    signal( SIGPIPE, SIG_IGN );
71
72    /* Initialize rate and file descripts controls */
73    h->upload   = tr_rcInit();
74    h->download = tr_rcInit();
75    h->fdlimit  = tr_fdInit();
76    h->choking  = tr_chokingInit( h );
77    h->natpmp   = tr_natpmpInit( h->fdlimit );
78    h->upnp     = tr_upnpInit( h->fdlimit );
79
80    h->bindPort = -1;
81    h->bindSocket = -1;
82
83    h->acceptDie = 0;
84    tr_lockInit( &h->acceptLock );
85    tr_threadCreate( &h->acceptThread, acceptLoop, h );
86
87    return h;
88}
89
90/***********************************************************************
91 * tr_setBindPort
92 ***********************************************************************
93 *
94 **********************************************************************/
95void tr_setBindPort( tr_handle_t * h, int port )
96{
97    int sock = -1;
98    tr_torrent_t * tor;
99
100    if( h->bindPort == port )
101      return;
102
103#ifndef BEOS_NETSERVER
104    /* BeOS net_server seems to be unable to set incoming connections to
105       non-blocking. Too bad. */
106    if( !tr_fdSocketWillCreate( h->fdlimit, 0 ) )
107    {
108        /* XXX should handle failure here in a better way */
109        sock = tr_netBindTCP( port );
110        if( 0 > sock)
111        {
112            tr_fdSocketClosed( h->fdlimit, 0 );
113        }
114        else
115        {   
116            tr_inf( "Bound listening port %d", port );
117            listen( sock, 5 );
118        }
119    }
120#else
121    return;
122#endif
123
124    tr_lockLock( &h->acceptLock );
125
126    h->bindPort = port;
127
128    for( tor = h->torrentList; tor; tor = tor->next )
129    {
130        tr_lockLock( &tor->lock );
131        if( NULL != tor->tracker )
132        {
133            tr_trackerChangePort( tor->tracker, port );
134        }
135        tr_lockUnlock( &tor->lock );
136    }
137
138    if( h->bindSocket > -1 )
139    {
140        tr_netClose( h->bindSocket );
141        tr_fdSocketClosed( h->fdlimit, 0 );
142    }
143
144    h->bindSocket = sock;
145
146    tr_natpmpForwardPort( h->natpmp, port );
147    tr_upnpForwardPort( h->upnp, port );
148
149    tr_lockUnlock( &h->acceptLock );
150}
151
152void tr_natTraversalEnable( tr_handle_t * h )
153{
154    tr_natpmpStart( h->natpmp );
155    tr_upnpStart( h->upnp );
156}
157
158void tr_natTraversalDisable( tr_handle_t * h )
159{
160    tr_natpmpStop( h->natpmp );
161    tr_upnpStop( h->upnp );
162}
163
164int tr_natTraversalStatus( tr_handle_t * h )
165{
166    int statuses[] = {
167        TR_NAT_TRAVERSAL_MAPPED,
168        TR_NAT_TRAVERSAL_MAPPING,
169        TR_NAT_TRAVERSAL_UNMAPPING,
170        TR_NAT_TRAVERSAL_ERROR,
171        TR_NAT_TRAVERSAL_NOTFOUND,
172        TR_NAT_TRAVERSAL_DISABLED,
173        -1,
174    };
175    int natpmp, upnp, ii;
176
177    natpmp = tr_natpmpStatus( h->natpmp );
178    upnp = tr_upnpStatus( h->upnp );
179
180    for( ii = 0; 0 <= statuses[ii]; ii++ )
181    {
182        if( statuses[ii] == natpmp || statuses[ii] == upnp )
183        {
184            return statuses[ii];
185        }
186    }
187
188    assert( 0 );
189
190    return TR_NAT_TRAVERSAL_ERROR;
191}
192
193/***********************************************************************
194 * tr_setUploadLimit
195 ***********************************************************************
196 *
197 **********************************************************************/
198void tr_setUploadLimit( tr_handle_t * h, int limit )
199{
200    tr_rcSetLimit( h->upload, limit );
201    tr_chokingSetLimit( h->choking, limit );
202}
203
204/***********************************************************************
205 * tr_setDownloadLimit
206 ***********************************************************************
207 *
208 **********************************************************************/
209void tr_setDownloadLimit( tr_handle_t * h, int limit )
210{
211    tr_rcSetLimit( h->download, limit );
212}
213
214/***********************************************************************
215 * tr_torrentRates
216 ***********************************************************************
217 *
218 **********************************************************************/
219void tr_torrentRates( tr_handle_t * h, float * dl, float * ul )
220{
221    tr_torrent_t * tor;
222
223    *dl = 0.0;
224    *ul = 0.0;
225    for( tor = h->torrentList; tor; tor = tor->next )
226    {
227        tr_lockLock( &tor->lock );
228        if( tor->status & TR_STATUS_DOWNLOAD )
229            *dl += tr_rcRate( tor->download );
230        *ul += tr_rcRate( tor->upload );
231        tr_lockUnlock( &tor->lock );
232    }
233}
234
235tr_torrent_t * tr_torrentInit( tr_handle_t * h, const char * path,
236                               int flags, int * error )
237{
238    tr_torrent_t  * tor = calloc( sizeof( tr_torrent_t ), 1 );
239    int             saveCopy = ( TR_FSAVEPRIVATE & flags );
240
241    /* Parse torrent file */
242    if( tr_metainfoParse( &tor->info, path, NULL, saveCopy ) )
243    {
244        *error = TR_EINVALID;
245        free( tor );
246        return NULL;
247    }
248
249    return torrentRealInit( h, tor, flags, error );
250}
251
252tr_torrent_t * tr_torrentInitSaved( tr_handle_t * h, const char * hashStr,
253                                    int flags, int * error )
254{
255    tr_torrent_t  * tor = calloc( sizeof( tr_torrent_t ), 1 );
256
257    /* Parse torrent file */
258    if( tr_metainfoParse( &tor->info, NULL, hashStr, 0 ) )
259    {
260        *error = TR_EINVALID;
261        free( tor );
262        return NULL;
263    }
264
265    return torrentRealInit( h, tor, ( TR_FSAVEPRIVATE | flags ), error );
266}
267
268/***********************************************************************
269 * tr_torrentInit
270 ***********************************************************************
271 * Allocates a tr_torrent_t structure, then relies on tr_metainfoParse
272 * to fill it.
273 **********************************************************************/
274static tr_torrent_t * torrentRealInit( tr_handle_t * h, tr_torrent_t * tor,
275                                       int flags, int * error )
276{
277    tr_torrent_t  * tor_tmp;
278    tr_info_t     * inf;
279    int             i;
280
281    inf        = &tor->info;
282    inf->flags = flags;
283
284    /* Make sure this torrent is not already open */
285    for( tor_tmp = h->torrentList; tor_tmp; tor_tmp = tor_tmp->next )
286    {
287        if( !memcmp( tor->info.hash, tor_tmp->info.hash,
288                     SHA_DIGEST_LENGTH ) )
289        {
290            *error = TR_EDUPLICATE;
291            tr_metainfoFree( &tor->info );
292            free( tor );
293            return NULL;
294        }
295    }
296
297    tor->status = TR_STATUS_PAUSE;
298    tor->id     = h->id;
299    tor->key    = h->key;
300    tor->bindPort = &h->bindPort;
301        tor->finished = 0;
302
303    /* Escaped info hash for HTTP queries */
304    for( i = 0; i < SHA_DIGEST_LENGTH; i++ )
305    {
306        sprintf( &tor->escapedHashString[3*i], "%%%02x", inf->hash[i] );
307    }
308
309    /* Block size: usually 16 ko, or less if we have to */
310    tor->blockSize  = MIN( inf->pieceSize, 1 << 14 );
311    tor->blockCount = ( inf->totalSize + tor->blockSize - 1 ) /
312                        tor->blockSize;
313    tor->completion = tr_cpInit( tor );
314
315    tr_lockInit( &tor->lock );
316
317    tor->globalUpload   = h->upload;
318    tor->globalDownload = h->download;
319    tor->fdlimit        = h->fdlimit;
320    tor->upload         = tr_rcInit();
321    tor->download       = tr_rcInit();
322    tor->swarmspeed     = tr_rcInit();
323 
324    /* We have a new torrent */
325    tr_lockLock( &h->acceptLock );
326    tor->prev = NULL;
327    tor->next = h->torrentList;
328    if( tor->next )
329    {
330        tor->next->prev = tor;
331    }
332    h->torrentList = tor;
333    (h->torrentCount)++;
334    tr_lockUnlock( &h->acceptLock );
335
336    if( 0 > h->bindPort )
337    {
338        tr_setBindPort( h, TR_DEFAULT_PORT );
339    }
340
341    return tor;
342}
343
344tr_info_t * tr_torrentInfo( tr_torrent_t * tor )
345{
346    return &tor->info;
347}
348
349/***********************************************************************
350 * tr_torrentScrape     
351 **********************************************************************/
352int tr_torrentScrape( tr_torrent_t * tor, int * s, int * l, int * d )
353{
354    return tr_trackerScrape( tor, s, l, d );
355}
356
357void tr_torrentSetFolder( tr_torrent_t * tor, const char * path )
358{
359    tor->destination = strdup( path );
360    tr_ioLoadResume( tor );
361}
362
363char * tr_torrentGetFolder( tr_torrent_t * tor )
364{
365    return tor->destination;
366}
367
368void tr_torrentStart( tr_torrent_t * tor )
369{
370    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
371    {
372        /* Join the thread first */
373        torrentReallyStop( tor );
374    }
375
376    tor->downloadedPrev += tor->downloadedCur;
377    tor->downloadedCur   = 0;
378    tor->uploadedPrev   += tor->uploadedCur;
379    tor->uploadedCur     = 0;
380
381    tor->status  = TR_STATUS_CHECK;
382    tor->tracker = tr_trackerInit( tor );
383
384    tor->date = tr_date();
385    tor->die = 0;
386    tr_threadCreate( &tor->thread, downloadLoop, tor );
387}
388
389void tr_torrentStop( tr_torrent_t * tor )
390{
391    tr_lockLock( &tor->lock );
392    tr_trackerStopped( tor->tracker );
393    tr_rcReset( tor->download );
394    tr_rcReset( tor->upload );
395    tr_rcReset( tor->swarmspeed );
396    tor->status = TR_STATUS_STOPPING;
397    tor->stopDate = tr_date();
398    tr_lockUnlock( &tor->lock );
399}
400
401/***********************************************************************
402 * torrentReallyStop
403 ***********************************************************************
404 * Joins the download thread and frees/closes everything related to it.
405 **********************************************************************/
406static void torrentReallyStop( tr_torrent_t * tor )
407{
408    tor->die = 1;
409    tr_threadJoin( &tor->thread );
410    tr_dbg( "Thread joined" );
411
412    tr_trackerClose( tor->tracker );
413    tor->tracker = NULL;
414
415    while( tor->peerCount > 0 )
416    {
417        tr_peerRem( tor, 0 );
418    }
419}
420
421/***********************************************************************
422 * tr_torrentCount
423 ***********************************************************************
424 *
425 **********************************************************************/
426int tr_torrentCount( tr_handle_t * h )
427{
428    return h->torrentCount;
429}
430
431void tr_torrentIterate( tr_handle_t * h, tr_callback_t func, void * d )
432{
433    tr_torrent_t * tor, * next;
434
435    for( tor = h->torrentList; tor; tor = next )
436    {
437        next = tor->next;
438        func( tor, d );
439    }
440}
441
442int tr_getFinished( tr_torrent_t * tor )
443{
444    if( tor->finished )
445    {
446        tor->finished = 0;
447        return 1;
448    }
449    return 0;
450}
451
452tr_stat_t * tr_torrentStat( tr_torrent_t * tor )
453{
454    tr_stat_t * s;
455    tr_peer_t * peer;
456    tr_info_t * inf = &tor->info;
457    tr_tracker_t * tc = tor->tracker;
458    int i;
459
460    tor->statCur = ( tor->statCur + 1 ) % 2;
461    s = &tor->stats[tor->statCur];
462
463    if( ( tor->status & TR_STATUS_STOPPED ) ||
464        ( ( tor->status & TR_STATUS_STOPPING ) &&
465          tr_date() > tor->stopDate + 60000 ) )
466    {
467        torrentReallyStop( tor );
468        tor->status = TR_STATUS_PAUSE;
469    }
470
471    tr_lockLock( &tor->lock );
472
473    s->status = tor->status;
474    s->error  = tor->error;
475    memcpy( s->trackerError, tor->trackerError,
476            sizeof( s->trackerError ) );
477    s->cannotConnect = tr_trackerCannotConnecting( tc );
478   
479    if( tor->tracker )
480    {
481        s->trackerAddress  = tr_trackerAddress(  tor->tracker );
482        s->trackerPort     = tr_trackerPort(     tor->tracker );
483        s->trackerAnnounce = tr_trackerAnnounce( tor->tracker );
484    }
485    else
486    {
487        s->trackerAddress  = inf->trackerList[0].list[0].address;
488        s->trackerPort     = inf->trackerList[0].list[0].port;
489        s->trackerAnnounce = inf->trackerList[0].list[0].announce;
490    }
491
492    s->peersTotal       = 0;
493    s->peersIncoming    = 0;
494    s->peersUploading   = 0;
495    s->peersDownloading = 0;
496   
497    for( i = 0; i < tor->peerCount; i++ )
498    {
499        peer = tor->peers[i];
500   
501        if( tr_peerIsConnected( peer ) )
502        {
503            (s->peersTotal)++;
504           
505            if( tr_peerIsIncoming( peer ) )
506            {
507                (s->peersIncoming)++;
508            }
509           
510            if( tr_peerIsUploading( peer ) )
511            {
512                (s->peersUploading)++;
513            }
514            if( tr_peerIsDownloading( peer ) )
515            {
516                (s->peersDownloading)++;
517            }
518        }
519    }
520
521    s->progress = tr_cpCompletionAsFloat( tor->completion );
522    if( tor->status & TR_STATUS_DOWNLOAD )
523    {
524        s->rateDownload = tr_rcRate( tor->download );
525    }
526    else
527    {
528        /* tr_rcRate() doesn't make the difference between 'piece'
529           messages and other messages, which causes a non-zero
530           download rate even tough we are not downloading. So we
531           force it to zero not to confuse the user. */
532        s->rateDownload = 0.0;
533    }
534    s->rateUpload = tr_rcRate( tor->upload );
535   
536    s->seeders  = tr_trackerSeeders( tc );
537    s->leechers = tr_trackerLeechers( tc );
538    s->completedFromTracker = tr_trackerDownloaded( tor->tracker );
539
540    s->swarmspeed = tr_rcRate( tor->swarmspeed );
541
542    if( s->rateDownload < 0.1 )
543    {
544        s->eta = -1;
545    }
546    else
547    {
548        s->eta = (float) ( 1.0 - s->progress ) *
549            (float) inf->totalSize / s->rateDownload / 1024.0;
550    }
551
552    s->downloaded = tor->downloadedCur + tor->downloadedPrev;
553    s->uploaded   = tor->uploadedCur   + tor->uploadedPrev;
554
555    tr_lockUnlock( &tor->lock );
556
557    return s;
558}
559
560tr_peer_stat_t * tr_torrentPeers( tr_torrent_t * tor, int * peerCount )
561{
562    tr_peer_stat_t * peers;
563
564    tr_lockLock( &tor->lock );
565
566    *peerCount = tor->peerCount;
567   
568    peers = (tr_peer_stat_t *) calloc( tor->peerCount, sizeof( tr_peer_stat_t ) );
569    if (peers != NULL)
570    {
571        tr_peer_t * peer;
572        struct in_addr * addr;
573        int i = 0;
574        for( i = 0; i < tor->peerCount; i++ )
575        {
576            peer = tor->peers[i];
577           
578            addr = tr_peerAddress( peer );
579            if( NULL != addr )
580            {
581                tr_netNtop( addr, peers[i].addr,
582                           sizeof( peers[i].addr ) );
583            }
584           
585            peers[i].client = tr_clientForId(tr_peerId(peer));
586           
587            peers[i].isConnected = tr_peerIsConnected(peer);
588            peers[i].isIncoming = tr_peerIsIncoming(peer);
589            peers[i].isDownloading = tr_peerIsDownloading(peer);
590            peers[i].isUploading = tr_peerIsUploading(peer);
591            peers[i].progress = tr_peerProgress(peer);
592        }
593    }
594   
595    tr_lockUnlock( &tor->lock );
596   
597    return peers;
598}
599
600void tr_torrentPeersFree( tr_peer_stat_t * peers, int peerCount )
601{
602    int i;
603
604    if (peers == NULL)
605        return;
606
607    for (i = 0; i < peerCount; i++)
608        free( peers[i].client );
609
610    free( peers );
611}
612
613void tr_torrentAvailability( tr_torrent_t * tor, int8_t * tab, int size )
614{
615    int i, j, piece;
616
617    tr_lockLock( &tor->lock );
618    for( i = 0; i < size; i++ )
619    {
620        piece = i * tor->info.pieceCount / size;
621
622        if( tr_cpPieceIsComplete( tor->completion, piece ) )
623        {
624            tab[i] = -1;
625            continue;
626        }
627
628        tab[i] = 0;
629        for( j = 0; j < tor->peerCount; j++ )
630        {
631            if( tr_peerBitfield( tor->peers[j] ) &&
632                tr_bitfieldHas( tr_peerBitfield( tor->peers[j] ), piece ) )
633            {
634                (tab[i])++;
635            }
636        }
637    }
638    tr_lockUnlock( &tor->lock );
639}
640
641void tr_torrentAmountFinished( tr_torrent_t * tor, float * tab, int size )
642{
643    int i, piece;
644
645    tr_lockLock( &tor->lock );
646    for( i = 0; i < size; i++ )
647    {
648        piece = i * tor->info.pieceCount / size;
649        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
650    }
651    tr_lockUnlock( &tor->lock );
652}
653
654void tr_torrentRemoveSaved( tr_torrent_t * tor ) {
655    tr_metainfoRemoveSaved( tor->info.hashString );
656}
657
658/***********************************************************************
659 * tr_torrentClose
660 ***********************************************************************
661 * Frees memory allocated by tr_torrentInit.
662 **********************************************************************/
663void tr_torrentClose( tr_handle_t * h, tr_torrent_t * tor )
664{
665    tr_info_t * inf = &tor->info;
666
667    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
668    {
669        /* Join the thread first */
670        torrentReallyStop( tor );
671    }
672
673    tr_lockLock( &h->acceptLock );
674
675    h->torrentCount--;
676
677    tr_lockClose( &tor->lock );
678    tr_cpClose( tor->completion );
679
680    tr_rcClose( tor->upload );
681    tr_rcClose( tor->download );
682    tr_rcClose( tor->swarmspeed );
683
684    if( tor->destination )
685    {
686        free( tor->destination );
687    }
688
689    tr_metainfoFree( inf );
690
691    if( tor->prev )
692    {
693        tor->prev->next = tor->next;
694    }
695    else
696    {
697        h->torrentList = tor->next;
698    }
699    if( tor->next )
700    {
701        tor->next->prev = tor->prev;
702    }
703    free( tor );
704
705    tr_lockUnlock( &h->acceptLock );
706}
707
708void tr_close( tr_handle_t * h )
709{
710    acceptStop( h );
711    tr_natpmpClose( h->natpmp );
712    tr_upnpClose( h->upnp );
713    tr_chokingClose( h->choking );
714    tr_fdClose( h->fdlimit );
715    tr_rcClose( h->upload );
716    tr_rcClose( h->download );
717    free( h );
718
719    tr_netResolveThreadClose();
720}
721
722/***********************************************************************
723 * downloadLoop
724 **********************************************************************/
725static void downloadLoop( void * _tor )
726{
727    tr_torrent_t * tor = _tor;
728    uint64_t       date1, date2;
729
730    tr_dbg( "Thread started" );
731
732#ifdef SYS_BEOS
733    /* This is required because on BeOS, SIGINT is sent to each thread,
734       which kills them not nicely */
735    signal( SIGINT, SIG_IGN );
736#endif
737
738    tr_lockLock( &tor->lock );
739
740    tr_cpReset( tor->completion );
741    tor->io     = tr_ioInit( tor );
742    tor->status = tr_cpIsSeeding( tor->completion ) ?
743                      TR_STATUS_SEED : TR_STATUS_DOWNLOAD;
744
745    while( !tor->die )
746    {
747        date1 = tr_date();
748
749        /* Are we finished ? */
750        if( ( tor->status & TR_STATUS_DOWNLOAD ) &&
751            tr_cpIsSeeding( tor->completion ) )
752        {
753            /* Done */
754            tor->status = TR_STATUS_SEED;
755                        tor->finished = 1;
756            tr_trackerCompleted( tor->tracker );
757            tr_ioSaveResume( tor->io );
758#ifndef __AMIGAOS4__
759            sync(); /* KLUDGE: all files should be closed and
760                       re-opened in read-only mode instead */
761#endif
762        }
763
764        /* Receive/send messages */
765        tr_peerPulse( tor );
766
767        /* Try to get new peers or to send a message to the tracker */
768        tr_trackerPulse( tor->tracker );
769
770        if( tor->status & TR_STATUS_STOPPED )
771        {
772            break;
773        }
774
775        /* Wait up to 20 ms */
776        date2 = tr_date();
777        if( date2 < date1 + 20 )
778        {
779            tr_lockUnlock( &tor->lock );
780            tr_wait( date1 + 20 - date2 );
781            tr_lockLock( &tor->lock );
782        }
783    }
784
785    tr_lockUnlock( &tor->lock );
786
787    tr_ioClose( tor->io );
788
789    tor->status = TR_STATUS_STOPPED;
790
791    tr_dbg( "Thread exited" );
792}
793
794/***********************************************************************
795 * acceptLoop
796 **********************************************************************/
797static void acceptLoop( void * _h )
798{
799    tr_handle_t * h = _h;
800    uint64_t      date1, date2, lastchoke = 0;
801    int           ii;
802    uint8_t     * hash;
803    tr_torrent_t * tor;
804
805    tr_dbg( "Accept thread started" );
806
807#ifdef SYS_BEOS
808    /* This is required because on BeOS, SIGINT is sent to each thread,
809       which kills them not nicely */
810    signal( SIGINT, SIG_IGN );
811#endif
812
813    tr_lockLock( &h->acceptLock );
814
815    while( !h->acceptDie )
816    {
817        date1 = tr_date();
818
819        /* do NAT-PMP and UPnP pulses here since there's nowhere better */
820        tr_natpmpPulse( h->natpmp );
821        tr_upnpPulse( h->upnp );
822
823        /* Check for incoming connections */
824        if( h->bindSocket > -1 &&
825            h->acceptPeerCount < TR_MAX_PEER_COUNT &&
826            !tr_fdSocketWillCreate( h->fdlimit, 0 ) )
827        {
828            int            s;
829            struct in_addr addr;
830            in_port_t      port;
831            s = tr_netAccept( h->bindSocket, &addr, &port );
832            if( s > -1 )
833            {
834                h->acceptPeers[h->acceptPeerCount++] = tr_peerInit( addr, port, s );
835            }
836            else
837            {
838                tr_fdSocketClosed( h->fdlimit, 0 );
839            }
840        }
841
842        for( ii = 0; ii < h->acceptPeerCount; )
843        {
844            if( tr_peerRead( NULL, h->acceptPeers[ii] ) )
845            {
846                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
847                goto removePeer;
848            }
849            if( NULL != ( hash = tr_peerHash( h->acceptPeers[ii] ) ) )
850            {
851                for( tor = h->torrentList; tor; tor = tor->next )
852                {
853                    tr_lockLock( &tor->lock );
854                    if( tor->status & TR_STATUS_INACTIVE )
855                    {
856                        tr_lockUnlock( &tor->lock );
857                        continue;
858                    }
859
860                    if( 0 == memcmp( tor->info.hash, hash,
861                                     SHA_DIGEST_LENGTH ) )
862                    {
863                      tr_peerAttach( tor, h->acceptPeers[ii] );
864                      tr_lockUnlock( &tor->lock );
865                      goto removePeer;
866                    }
867                    tr_lockUnlock( &tor->lock );
868                }
869                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
870                goto removePeer;
871            }
872            if( date1 > tr_peerDate( h->acceptPeers[ii] ) + 10000 )
873            {
874                /* Give them 10 seconds to send the handshake */
875                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
876                goto removePeer;
877            }
878            ii++;
879            continue;
880           removePeer:
881            h->acceptPeerCount--;
882            memmove( &h->acceptPeers[ii], &h->acceptPeers[ii+1],
883                     ( h->acceptPeerCount - ii ) * sizeof( tr_peer_t * ) );
884        }
885
886        if( date1 > lastchoke + 2000 )
887        {
888            tr_chokingPulse( h->choking );
889            lastchoke = date1;
890        }
891
892        /* Wait up to 20 ms */
893        date2 = tr_date();
894        if( date2 < date1 + 20 )
895        {
896            tr_lockUnlock( &h->acceptLock );
897            tr_wait( date1 + 20 - date2 );
898            tr_lockLock( &h->acceptLock );
899        }
900    }
901
902    tr_lockUnlock( &h->acceptLock );
903
904    tr_dbg( "Accept thread exited" );
905}
906
907/***********************************************************************
908 * acceptStop
909 ***********************************************************************
910 * Joins the accept thread and frees/closes everything related to it.
911 **********************************************************************/
912static void acceptStop( tr_handle_t * h )
913{
914    int ii;
915
916    h->acceptDie = 1;
917    tr_threadJoin( &h->acceptThread );
918    tr_lockClose( &h->acceptLock );
919    tr_dbg( "Accept thread joined" );
920
921    for( ii = 0; ii < h->acceptPeerCount; ii++ )
922    {
923        tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
924    }
925
926    if( h->bindSocket > -1 )
927    {
928        tr_netClose( h->bindSocket );
929        tr_fdSocketClosed( h->fdlimit, 0 );
930    }
931}
Note: See TracBrowser for help on using the repository browser.