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

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

initial support for announce-list (currently crashes when a tracker fails)

  • Property svn:keywords set to Date Rev Author Id
File size: 24.8 KB
Line 
1/******************************************************************************
2 * $Id: transmission.c 1154 2006-12-05 00:14:52Z 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    char          * s1, * s2;
281
282    inf        = &tor->info;
283    inf->flags = flags;
284
285    /* Make sure this torrent is not already open */
286    for( tor_tmp = h->torrentList; tor_tmp; tor_tmp = tor_tmp->next )
287    {
288        if( !memcmp( tor->info.hash, tor_tmp->info.hash,
289                     SHA_DIGEST_LENGTH ) )
290        {
291            *error = TR_EDUPLICATE;
292            free( inf->pieces );
293            free( inf->files );
294            free( tor );
295            return NULL;
296        }
297    }
298
299    tor->status = TR_STATUS_PAUSE;
300    tor->id     = h->id;
301    tor->key    = h->key;
302    tor->bindPort = &h->bindPort;
303        tor->finished = 0;
304
305    /* Escaped info hash for HTTP queries */
306    for( i = 0; i < SHA_DIGEST_LENGTH; i++ )
307    {
308        sprintf( &tor->escapedHashString[3*i], "%%%02x", inf->hash[i] );
309    }
310
311    /* Block size: usually 16 ko, or less if we have to */
312    tor->blockSize  = MIN( inf->pieceSize, 1 << 14 );
313    tor->blockCount = ( inf->totalSize + tor->blockSize - 1 ) /
314                        tor->blockSize;
315    tor->completion = tr_cpInit( tor );
316
317    tr_lockInit( &tor->lock );
318
319    tor->globalUpload   = h->upload;
320    tor->globalDownload = h->download;
321    tor->fdlimit        = h->fdlimit;
322    tor->upload         = tr_rcInit();
323    tor->download       = tr_rcInit();
324    tor->swarmspeed     = tr_rcInit();
325 
326    /* We have a new torrent */
327    tr_lockLock( &h->acceptLock );
328    tor->prev = NULL;
329    tor->next = h->torrentList;
330    if( tor->next )
331    {
332        tor->next->prev = tor;
333    }
334    h->torrentList = tor;
335    (h->torrentCount)++;
336    tr_lockUnlock( &h->acceptLock );
337
338    if( 0 > h->bindPort )
339    {
340        tr_setBindPort( h, TR_DEFAULT_PORT );
341    }
342
343    return tor;
344}
345
346tr_info_t * tr_torrentInfo( tr_torrent_t * tor )
347{
348    return &tor->info;
349}
350
351/***********************************************************************
352 * tr_torrentScrape     
353 **********************************************************************/
354int tr_torrentScrape( tr_torrent_t * tor, int * s, int * l, int * d )
355{
356    return tr_trackerScrape( tor, s, l, d );
357}
358
359void tr_torrentSetFolder( tr_torrent_t * tor, const char * path )
360{
361    tor->destination = strdup( path );
362    tr_ioLoadResume( tor );
363}
364
365char * tr_torrentGetFolder( tr_torrent_t * tor )
366{
367    return tor->destination;
368}
369
370void tr_torrentStart( tr_torrent_t * tor )
371{
372    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
373    {
374        /* Join the thread first */
375        torrentReallyStop( tor );
376    }
377
378    tor->downloadedPrev += tor->downloadedCur;
379    tor->downloadedCur   = 0;
380    tor->uploadedPrev   += tor->uploadedCur;
381    tor->uploadedCur     = 0;
382
383    tor->status  = TR_STATUS_CHECK;
384    tor->tracker = tr_trackerInit( tor );
385
386    tor->date = tr_date();
387    tor->die = 0;
388    tr_threadCreate( &tor->thread, downloadLoop, tor );
389}
390
391void tr_torrentStop( tr_torrent_t * tor )
392{
393    tr_lockLock( &tor->lock );
394    tr_trackerStopped( tor->tracker );
395    tr_rcReset( tor->download );
396    tr_rcReset( tor->upload );
397    tr_rcReset( tor->swarmspeed );
398    tor->status = TR_STATUS_STOPPING;
399    tor->stopDate = tr_date();
400    tr_lockUnlock( &tor->lock );
401}
402
403/***********************************************************************
404 * torrentReallyStop
405 ***********************************************************************
406 * Joins the download thread and frees/closes everything related to it.
407 **********************************************************************/
408static void torrentReallyStop( tr_torrent_t * tor )
409{
410    tor->die = 1;
411    tr_threadJoin( &tor->thread );
412    tr_dbg( "Thread joined" );
413
414    tr_trackerClose( tor->tracker );
415    tor->tracker = NULL;
416
417    while( tor->peerCount > 0 )
418    {
419        tr_peerRem( tor, 0 );
420    }
421}
422
423/***********************************************************************
424 * tr_torrentCount
425 ***********************************************************************
426 *
427 **********************************************************************/
428int tr_torrentCount( tr_handle_t * h )
429{
430    return h->torrentCount;
431}
432
433void tr_torrentIterate( tr_handle_t * h, tr_callback_t func, void * d )
434{
435    tr_torrent_t * tor, * next;
436
437    for( tor = h->torrentList; tor; tor = next )
438    {
439        next = tor->next;
440        func( tor, d );
441    }
442}
443
444int tr_getFinished( tr_torrent_t * tor )
445{
446    if( tor->finished )
447    {
448        tor->finished = 0;
449        return 1;
450    }
451    return 0;
452}
453
454tr_stat_t * tr_torrentStat( tr_torrent_t * tor )
455{
456    tr_stat_t * s;
457    tr_peer_t * peer;
458    tr_info_t * inf = &tor->info;
459    int i;
460
461    tor->statCur = ( tor->statCur + 1 ) % 2;
462    s = &tor->stats[tor->statCur];
463
464    if( ( tor->status & TR_STATUS_STOPPED ) ||
465        ( ( tor->status & TR_STATUS_STOPPING ) &&
466          tr_date() > tor->stopDate + 60000 ) )
467    {
468        torrentReallyStop( tor );
469        tor->status = TR_STATUS_PAUSE;
470    }
471
472    tr_lockLock( &tor->lock );
473
474    s->status = tor->status;
475    s->error  = tor->error;
476    memcpy( s->trackerError, tor->trackerError,
477            sizeof( s->trackerError ) );
478
479    s->peersTotal       = 0;
480    s->peersIncoming    = 0;
481    s->peersUploading   = 0;
482    s->peersDownloading = 0;
483   
484    for( i = 0; i < tor->peerCount; i++ )
485    {
486        peer = tor->peers[i];
487   
488        if( tr_peerIsConnected( peer ) )
489        {
490            (s->peersTotal)++;
491           
492            if( tr_peerIsIncoming( peer ) )
493            {
494                (s->peersIncoming)++;
495            }
496           
497            if( tr_peerIsUploading( peer ) )
498            {
499                (s->peersUploading)++;
500            }
501            if( tr_peerIsDownloading( peer ) )
502            {
503                (s->peersDownloading)++;
504            }
505        }
506    }
507
508    s->progress = tr_cpCompletionAsFloat( tor->completion );
509    if( tor->status & TR_STATUS_DOWNLOAD )
510    {
511        s->rateDownload = tr_rcRate( tor->download );
512    }
513    else
514    {
515        /* tr_rcRate() doesn't make the difference between 'piece'
516           messages and other messages, which causes a non-zero
517           download rate even tough we are not downloading. So we
518           force it to zero not to confuse the user. */
519        s->rateDownload = 0.0;
520    }
521    s->rateUpload = tr_rcRate( tor->upload );
522   
523    s->seeders  = tr_trackerSeeders(tor->tracker);
524    s->leechers = tr_trackerLeechers(tor->tracker);
525    s->completedFromTracker = tr_trackerDownloaded(tor->tracker);
526
527    s->swarmspeed = tr_rcRate( tor->swarmspeed );
528
529    if( s->rateDownload < 0.1 )
530    {
531        s->eta = -1;
532    }
533    else
534    {
535        s->eta = (float) ( 1.0 - s->progress ) *
536            (float) inf->totalSize / s->rateDownload / 1024.0;
537    }
538
539    s->downloaded = tor->downloadedCur + tor->downloadedPrev;
540    s->uploaded   = tor->uploadedCur   + tor->uploadedPrev;
541
542    tr_lockUnlock( &tor->lock );
543
544    return s;
545}
546
547tr_peer_stat_t * tr_torrentPeers( tr_torrent_t * tor, int * peerCount )
548{
549    tr_peer_stat_t * peers;
550
551    tr_lockLock( &tor->lock );
552
553    *peerCount = tor->peerCount;
554   
555    peers = (tr_peer_stat_t *) calloc( tor->peerCount, sizeof( tr_peer_stat_t ) );
556    if (peers != NULL)
557    {
558        tr_peer_t * peer;
559        struct in_addr * addr;
560        int i = 0;
561        for( i = 0; i < tor->peerCount; i++ )
562        {
563            peer = tor->peers[i];
564           
565            addr = tr_peerAddress( peer );
566            if( NULL != addr )
567            {
568                tr_netNtop( addr, peers[i].addr,
569                           sizeof( peers[i].addr ) );
570            }
571           
572            peers[i].client = tr_clientForId(tr_peerId(peer));
573           
574            peers[i].isConnected = tr_peerIsConnected(peer);
575            peers[i].isIncoming = tr_peerIsIncoming(peer);
576            peers[i].isDownloading = tr_peerIsDownloading(peer);
577            peers[i].isUploading = tr_peerIsUploading(peer);
578            peers[i].progress = tr_peerProgress(peer);
579        }
580    }
581   
582    tr_lockUnlock( &tor->lock );
583   
584    return peers;
585}
586
587void tr_torrentPeersFree( tr_peer_stat_t * peers, int peerCount )
588{
589    int i;
590
591    if (peers == NULL)
592        return;
593
594    for (i = 0; i < peerCount; i++)
595        free( peers[i].client );
596
597    free( peers );
598}
599
600void tr_torrentAvailability( tr_torrent_t * tor, int8_t * tab, int size )
601{
602    int i, j, piece;
603
604    tr_lockLock( &tor->lock );
605    for( i = 0; i < size; i++ )
606    {
607        piece = i * tor->info.pieceCount / size;
608
609        if( tr_cpPieceIsComplete( tor->completion, piece ) )
610        {
611            tab[i] = -1;
612            continue;
613        }
614
615        tab[i] = 0;
616        for( j = 0; j < tor->peerCount; j++ )
617        {
618            if( tr_peerBitfield( tor->peers[j] ) &&
619                tr_bitfieldHas( tr_peerBitfield( tor->peers[j] ), piece ) )
620            {
621                (tab[i])++;
622            }
623        }
624    }
625    tr_lockUnlock( &tor->lock );
626}
627
628void tr_torrentAmountFinished( tr_torrent_t * tor, float * tab, int size )
629{
630    int i, piece;
631
632    tr_lockLock( &tor->lock );
633    for( i = 0; i < size; i++ )
634    {
635        piece = i * tor->info.pieceCount / size;
636        tab[i] = tr_cpPercentBlocksInPiece( tor->completion, piece );
637    }
638    tr_lockUnlock( &tor->lock );
639}
640
641void tr_torrentRemoveSaved( tr_torrent_t * tor ) {
642    tr_metainfoRemoveSaved( tor->info.hashString );
643}
644
645/***********************************************************************
646 * tr_torrentClose
647 ***********************************************************************
648 * Frees memory allocated by tr_torrentInit.
649 **********************************************************************/
650void tr_torrentClose( tr_handle_t * h, tr_torrent_t * tor )
651{
652    tr_info_t * inf = &tor->info;
653
654    if( tor->status & ( TR_STATUS_STOPPING | TR_STATUS_STOPPED ) )
655    {
656        /* Join the thread first */
657        torrentReallyStop( tor );
658    }
659
660    tr_lockLock( &h->acceptLock );
661
662    h->torrentCount--;
663
664    tr_lockClose( &tor->lock );
665    tr_cpClose( tor->completion );
666
667    tr_rcClose( tor->upload );
668    tr_rcClose( tor->download );
669    tr_rcClose( tor->swarmspeed );
670
671    if( tor->destination )
672    {
673        free( tor->destination );
674    }
675    free( inf->pieces );
676    free( inf->files );
677
678    if( tor->prev )
679    {
680        tor->prev->next = tor->next;
681    }
682    else
683    {
684        h->torrentList = tor->next;
685    }
686    if( tor->next )
687    {
688        tor->next->prev = tor->prev;
689    }
690    free( tor );
691
692    tr_lockUnlock( &h->acceptLock );
693}
694
695void tr_close( tr_handle_t * h )
696{
697    acceptStop( h );
698    tr_natpmpClose( h->natpmp );
699    tr_upnpClose( h->upnp );
700    tr_chokingClose( h->choking );
701    tr_fdClose( h->fdlimit );
702    tr_rcClose( h->upload );
703    tr_rcClose( h->download );
704    free( h );
705
706    tr_netResolveThreadClose();
707}
708
709/***********************************************************************
710 * downloadLoop
711 **********************************************************************/
712static void downloadLoop( void * _tor )
713{
714    tr_torrent_t * tor = _tor;
715    uint64_t       date1, date2;
716
717    tr_dbg( "Thread started" );
718
719#ifdef SYS_BEOS
720    /* This is required because on BeOS, SIGINT is sent to each thread,
721       which kills them not nicely */
722    signal( SIGINT, SIG_IGN );
723#endif
724
725    tr_lockLock( &tor->lock );
726
727    tr_cpReset( tor->completion );
728    tor->io     = tr_ioInit( tor );
729    tor->status = tr_cpIsSeeding( tor->completion ) ?
730                      TR_STATUS_SEED : TR_STATUS_DOWNLOAD;
731
732    while( !tor->die )
733    {
734        date1 = tr_date();
735
736        /* Are we finished ? */
737        if( ( tor->status & TR_STATUS_DOWNLOAD ) &&
738            tr_cpIsSeeding( tor->completion ) )
739        {
740            /* Done */
741            tor->status = TR_STATUS_SEED;
742                        tor->finished = 1;
743            tr_trackerCompleted( tor->tracker );
744            tr_ioSaveResume( tor->io );
745#ifndef __AMIGAOS4__
746            sync(); /* KLUDGE: all files should be closed and
747                       re-opened in read-only mode instead */
748#endif
749        }
750
751        /* Receive/send messages */
752        tr_peerPulse( tor );
753
754        /* Try to get new peers or to send a message to the tracker */
755        tr_trackerPulse( tor->tracker );
756
757        if( tor->status & TR_STATUS_STOPPED )
758        {
759            break;
760        }
761
762        /* Wait up to 20 ms */
763        date2 = tr_date();
764        if( date2 < date1 + 20 )
765        {
766            tr_lockUnlock( &tor->lock );
767            tr_wait( date1 + 20 - date2 );
768            tr_lockLock( &tor->lock );
769        }
770    }
771
772    tr_lockUnlock( &tor->lock );
773
774    tr_ioClose( tor->io );
775
776    tor->status = TR_STATUS_STOPPED;
777
778    tr_dbg( "Thread exited" );
779}
780
781/***********************************************************************
782 * acceptLoop
783 **********************************************************************/
784static void acceptLoop( void * _h )
785{
786    tr_handle_t * h = _h;
787    uint64_t      date1, date2, lastchoke = 0;
788    int           ii;
789    uint8_t     * hash;
790    tr_torrent_t * tor;
791
792    tr_dbg( "Accept thread started" );
793
794#ifdef SYS_BEOS
795    /* This is required because on BeOS, SIGINT is sent to each thread,
796       which kills them not nicely */
797    signal( SIGINT, SIG_IGN );
798#endif
799
800    tr_lockLock( &h->acceptLock );
801
802    while( !h->acceptDie )
803    {
804        date1 = tr_date();
805
806        /* do NAT-PMP and UPnP pulses here since there's nowhere better */
807        tr_natpmpPulse( h->natpmp );
808        tr_upnpPulse( h->upnp );
809
810        /* Check for incoming connections */
811        if( h->bindSocket > -1 &&
812            h->acceptPeerCount < TR_MAX_PEER_COUNT &&
813            !tr_fdSocketWillCreate( h->fdlimit, 0 ) )
814        {
815            int            s;
816            struct in_addr addr;
817            in_port_t      port;
818            s = tr_netAccept( h->bindSocket, &addr, &port );
819            if( s > -1 )
820            {
821                h->acceptPeers[h->acceptPeerCount++] = tr_peerInit( addr, port, s );
822            }
823            else
824            {
825                tr_fdSocketClosed( h->fdlimit, 0 );
826            }
827        }
828
829        for( ii = 0; ii < h->acceptPeerCount; )
830        {
831            if( tr_peerRead( NULL, h->acceptPeers[ii] ) )
832            {
833                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
834                goto removePeer;
835            }
836            if( NULL != ( hash = tr_peerHash( h->acceptPeers[ii] ) ) )
837            {
838                for( tor = h->torrentList; tor; tor = tor->next )
839                {
840                    tr_lockLock( &tor->lock );
841                    if( tor->status & TR_STATUS_INACTIVE )
842                    {
843                        tr_lockUnlock( &tor->lock );
844                        continue;
845                    }
846
847                    if( 0 == memcmp( tor->info.hash, hash,
848                                     SHA_DIGEST_LENGTH ) )
849                    {
850                      tr_peerAttach( tor, h->acceptPeers[ii] );
851                      tr_lockUnlock( &tor->lock );
852                      goto removePeer;
853                    }
854                    tr_lockUnlock( &tor->lock );
855                }
856                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
857                goto removePeer;
858            }
859            if( date1 > tr_peerDate( h->acceptPeers[ii] ) + 10000 )
860            {
861                /* Give them 10 seconds to send the handshake */
862                tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
863                goto removePeer;
864            }
865            ii++;
866            continue;
867           removePeer:
868            h->acceptPeerCount--;
869            memmove( &h->acceptPeers[ii], &h->acceptPeers[ii+1],
870                     ( h->acceptPeerCount - ii ) * sizeof( tr_peer_t * ) );
871        }
872
873        if( date1 > lastchoke + 2000 )
874        {
875            tr_chokingPulse( h->choking );
876            lastchoke = date1;
877        }
878
879        /* Wait up to 20 ms */
880        date2 = tr_date();
881        if( date2 < date1 + 20 )
882        {
883            tr_lockUnlock( &h->acceptLock );
884            tr_wait( date1 + 20 - date2 );
885            tr_lockLock( &h->acceptLock );
886        }
887    }
888
889    tr_lockUnlock( &h->acceptLock );
890
891    tr_dbg( "Accept thread exited" );
892}
893
894/***********************************************************************
895 * acceptStop
896 ***********************************************************************
897 * Joins the accept thread and frees/closes everything related to it.
898 **********************************************************************/
899static void acceptStop( tr_handle_t * h )
900{
901    int ii;
902
903    h->acceptDie = 1;
904    tr_threadJoin( &h->acceptThread );
905    tr_lockClose( &h->acceptLock );
906    tr_dbg( "Accept thread joined" );
907
908    for( ii = 0; ii < h->acceptPeerCount; ii++ )
909    {
910        tr_peerDestroy( h->fdlimit, h->acceptPeers[ii] );
911    }
912
913    if( h->bindSocket > -1 )
914    {
915        tr_netClose( h->bindSocket );
916        tr_fdSocketClosed( h->fdlimit, 0 );
917    }
918}
Note: See TracBrowser for help on using the repository browser.