source: trunk/libtransmission/transmission.c @ 1007

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

don't know how this happened...

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