source: branches/1.5x/libtransmission/net.c @ 7741

Last change on this file since 7741 was 7741, checked in by charles, 12 years ago

(1.5x) copy r7739 and r7740 to 1.5x

  • Property svn:keywords set to Date Rev Author Id
File size: 15.0 KB
Line 
1/******************************************************************************
2 * $Id: net.c 7741 2009-01-17 23:34:00Z charles $
3 *
4 * Copyright (c) 2005-2008 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 <errno.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <assert.h>
30
31#include <sys/types.h>
32
33#ifdef WIN32
34 #include <winsock2.h> /* inet_addr */
35 #include <WS2tcpip.h>
36#else
37 #include <arpa/inet.h> /* inet_addr */
38 #include <netdb.h>
39 #include <fcntl.h>
40#endif
41
42#include <evutil.h>
43
44#include "transmission.h"
45#include "fdlimit.h"
46#include "natpmp.h"
47#include "net.h"
48#include "peer-io.h"
49#include "platform.h"
50#include "utils.h"
51
52#ifndef IN_MULTICAST
53#define IN_MULTICAST( a ) ( ( ( a ) & 0xf0000000 ) == 0xe0000000 )
54#endif
55
56const tr_address tr_in6addr_any = { TR_AF_INET6, { IN6ADDR_ANY_INIT } }; 
57const tr_address tr_inaddr_any = { TR_AF_INET, 
58    { { { { INADDR_ANY, 0x00, 0x00, 0x00 } } } } }; 
59
60#ifdef WIN32
61static const char *
62inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
63{
64    if (af == AF_INET)
65    {
66        struct sockaddr_in in;
67        memset(&in, 0, sizeof(in));
68        in.sin_family = AF_INET;
69        memcpy(&in.sin_addr, src, sizeof(struct in_addr));
70        getnameinfo((struct sockaddr *)&in, sizeof(struct
71            sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
72        return dst;
73    }
74    else if (af == AF_INET6)
75    {
76        struct sockaddr_in6 in;
77        memset(&in, 0, sizeof(in));
78        in.sin6_family = AF_INET6;
79        memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
80        getnameinfo((struct sockaddr *)&in, sizeof(struct
81            sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
82        return dst;
83    }
84    return NULL;
85}
86
87static int
88inet_pton(int af, const char *src, void *dst)
89{
90    struct addrinfo hints;
91    struct addrinfo *res;
92    struct addrinfo *ressave;
93
94    memset(&hints, 0, sizeof(struct addrinfo));
95    hints.ai_family = af;
96
97    if (getaddrinfo(src, NULL, &hints, &res) != 0)
98        return -1;
99
100    ressave = res;
101
102    while (res)
103    {
104        memcpy(dst, res->ai_addr, res->ai_addrlen);
105        res = res->ai_next;
106    }
107
108    freeaddrinfo(ressave);
109    return 0;
110}
111
112#endif
113
114
115void
116tr_netInit( void )
117{
118    static int initialized = FALSE;
119
120    if( !initialized )
121    {
122#ifdef WIN32
123        WSADATA wsaData;
124        WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
125#endif
126        initialized = TRUE;
127    }
128}
129
130void
131tr_suspectAddress( const tr_address * a UNUSED, const char * source UNUSED )
132{
133/* this is overkill for a production environment,
134 * but useful in the nightly builds, so only compile it into the nightlies */
135#ifdef TR_UNSTABLE
136    /* be really aggressive in what we report */
137    if( a->type == TR_AF_INET && !( ntohl( a->addr.addr4.s_addr ) & 0xff000000 ) )
138        tr_err(  "Funny looking address %s from %s", tr_ntop_non_ts( a ), source );
139    /* /16s taken from ipv6 rib on 21 dec, 2008 */
140    /* this is really, really ugly. expedience over quality */
141    if( a->type == TR_AF_INET6 )
142    {
143        uint16_t slash16;
144        uint16_t valid[] = { 0x339, 0x2002, 0x2003, 0x2400, 0x2401, 0x2402,
145            0x2403, 0x2404, 0x2405, 0x2406, 0x2407, 0x2600, 0x2607, 0x2610,
146            0x2620, 0x2800, 0x2801, 0x2a00, 0x2a01, 0x0a02, 0x2001, 0x0000 };
147        uint16_t *p;
148        tr_bool good = FALSE;
149        p = valid;
150        memcpy( &slash16, &a->addr, 2 );
151        slash16 = ntohs( slash16 );
152        while( *p )
153        {
154            if( slash16 == *p )
155                good = TRUE;
156            p++;
157        }
158        if( !good && !IN6_IS_ADDR_V4MAPPED( &a->addr.addr6 ) )
159            tr_err(  "Funny looking address %s from %s", tr_ntop_non_ts( a ), source );
160    }
161#endif
162}
163
164const char * 
165tr_ntop( const tr_address * src, char * dst, int size ) 
166{
167    assert( tr_isAddress( src ) );
168
169    if( src->type == TR_AF_INET ) 
170        return inet_ntop( AF_INET, &src->addr, dst, size ); 
171    else 
172        return inet_ntop( AF_INET6, &src->addr, dst, size ); 
173} 
174
175/*
176 * Non-threadsafe version of tr_ntop, which uses a static memory area for a buffer.
177 * This function is suitable to be called from libTransmission's networking code,
178 * which is single-threaded.
179 */ 
180const char * 
181tr_ntop_non_ts( const tr_address * src ) 
182{ 
183    static char buf[INET6_ADDRSTRLEN]; 
184    return tr_ntop( src, buf, sizeof( buf ) ); 
185} 
186
187tr_address * 
188tr_pton( const char * src, tr_address * dst ) 
189{ 
190    int retval = inet_pton( AF_INET, src, &dst->addr ); 
191    if( retval < 0 ) 
192        return NULL; 
193    else if( retval == 0 ) 
194        retval = inet_pton( AF_INET6, src, &dst->addr ); 
195    else
196    { 
197        dst->type = TR_AF_INET; 
198        return dst; 
199    } 
200
201    if( retval < 1 ) 
202        return NULL; 
203    dst->type = TR_AF_INET6; 
204    return dst; 
205}
206
207void
208tr_normalizeV4Mapped( tr_address * const addr )
209{
210    assert( tr_isAddress( addr ) );
211
212    if( addr->type == TR_AF_INET6 && IN6_IS_ADDR_V4MAPPED( &addr->addr.addr6 ) )
213    {
214        addr->type = TR_AF_INET;
215        memcpy( &addr->addr.addr4.s_addr, addr->addr.addr6.s6_addr + 12, 4 );
216    }
217}
218
219/*
220 * Compare two tr_address structures.
221 * Returns:
222 * <0 if a < b
223 * >0 if a > b
224 * 0  if a == b
225 */ 
226int
227tr_compareAddresses( const tr_address * a, const tr_address * b)
228{
229    int addrlen;
230
231    assert( tr_isAddress( a ) );
232    assert( tr_isAddress( b ) );
233
234    /* IPv6 addresses are always "greater than" IPv4 */ 
235    if( a->type != b->type )
236        return a->type == TR_AF_INET ? 1 : -1;
237
238    if( a->type == TR_AF_INET ) 
239        addrlen = sizeof( struct in_addr ); 
240    else 
241        addrlen = sizeof( struct in6_addr ); 
242    return memcmp( &a->addr, &b->addr, addrlen );
243} 
244
245tr_net_af_support
246tr_net_getAFSupport( tr_port port )
247{
248    /* Do we care if an address is in use? Probably not, since it will be
249     * caught later. This will only set up the list of sockets to bind. */
250    static tr_bool alreadyDone       = FALSE;
251    static tr_net_af_support support = { FALSE, FALSE };
252    int s4, s6;
253    if( alreadyDone )
254        return support;
255    s6 = tr_netBindTCP( &tr_in6addr_any, port, TRUE );
256    if( s6 >= 0 || -s6 != EAFNOSUPPORT ) /* we support ipv6 */
257    {
258        listen( s6, 1 );
259        support.has_inet6 = TRUE;
260    }
261    s4 = tr_netBindTCP( &tr_inaddr_any, port, TRUE );
262    if( s4 >= 0 ) /* we bound *with* the ipv6 socket bound (need both)
263                   * or only have ipv4 */
264    {
265        tr_netClose( s4 );
266        support.needs_inet4 = TRUE;
267    }
268    if( s6 >= 0 )
269        tr_netClose( s6 );
270    alreadyDone = TRUE;
271    return support;
272}
273
274/***********************************************************************
275 * Socket list housekeeping
276 **********************************************************************/
277struct tr_socketList
278{
279    int             socket;
280    tr_address      addr;
281    tr_socketList * next;
282};
283
284tr_socketList *
285tr_socketListAppend( tr_socketList * const head,
286                     const tr_address * const addr )
287{
288    tr_socketList * tmp;
289
290    assert( head );
291    assert( tr_isAddress( addr ) );
292
293    for( tmp = head; tmp->next; tmp = tmp->next );
294    tmp->next = tr_socketListNew( addr );
295    return tmp->next;
296}
297
298tr_socketList *
299tr_socketListNew( const tr_address * const addr )
300{
301    tr_socketList * tmp;
302
303    assert( tr_isAddress( addr ) );
304
305    tmp = tr_new( tr_socketList, 1 );
306    tmp->socket = -1;
307    tmp->addr = *addr;
308    tmp->next = NULL;
309    return tmp;
310}
311
312void
313tr_socketListFree( tr_socketList * const head )
314{
315    assert( head );
316
317    if( head->next )
318        tr_socketListFree( head->next );
319    tr_free( head );
320}
321
322void
323tr_socketListRemove( tr_socketList * const head,
324                     tr_socketList * const el)
325{
326    tr_socketList * tmp;
327
328    assert( head );
329    assert( el );
330
331    for( tmp = head; tmp->next && tmp->next != el; tmp = tmp->next );
332    tmp->next = el->next;
333    el->next = NULL;
334    tr_socketListFree(el);
335}
336
337void
338tr_socketListTruncate( tr_socketList * const head,
339                       tr_socketList * const start )
340{
341    tr_socketList * tmp;
342
343    assert( head );
344    assert( start );
345
346    for( tmp = head; tmp->next && tmp->next != start; tmp = tmp->next );
347    tr_socketListFree( start );
348    tmp->next = NULL;
349}
350
351#if 0
352int
353tr_socketListGetSocket( const tr_socketList * const el )
354{
355    assert( el );
356
357    return el->socket;
358}
359
360const tr_address *
361tr_socketListGetAddress( const tr_socketList * const el )
362{
363    assert( el );
364    return &el->addr;
365}
366#endif
367
368void
369tr_socketListForEach( tr_socketList * const head,
370                      void ( * cb ) ( int * const,
371                                      tr_address * const,
372                                      void * const),
373                      void * const userData )
374{
375    tr_socketList * tmp;
376    for( tmp = head; tmp; tmp = tmp->next )
377        cb( &tmp->socket, &tmp->addr, userData );
378}
379
380/***********************************************************************
381 * TCP sockets
382 **********************************************************************/
383
384int
385tr_netSetTOS( int s, int tos )
386{
387#ifdef IP_TOS
388    return setsockopt( s, IPPROTO_IP, IP_TOS, (char*)&tos, sizeof( tos ) );
389#else
390    return 0;
391#endif
392}
393
394static int
395makeSocketNonBlocking( int fd )
396{
397    if( fd >= 0 )
398    {
399        if( evutil_make_socket_nonblocking( fd ) )
400        {
401            int tmperrno;
402            tr_err( _( "Couldn't create socket: %s" ),
403                   tr_strerror( sockerrno ) );
404            tmperrno = sockerrno;
405            tr_netClose( fd );
406            fd = -tmperrno;
407        }
408    }
409
410    return fd;
411}
412
413static int
414createSocket( int domain, int type )
415{
416    return makeSocketNonBlocking( tr_fdSocketCreate( domain, type ) );
417}
418
419static void
420setSndBuf( tr_session * session UNUSED, int fd UNUSED )
421{
422#if 0
423    if( fd >= 0 )
424    {
425        const int sndbuf = session->so_sndbuf;
426        const int rcvbuf = session->so_rcvbuf;
427        setsockopt( fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof( sndbuf ) );
428        setsockopt( fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof( rcvbuf ) );
429    }
430#endif
431}
432
433static socklen_t
434setup_sockaddr( const tr_address        * addr,
435                tr_port                   port,
436                struct sockaddr_storage * sockaddr)
437{
438    struct sockaddr_in  sock4;
439    struct sockaddr_in6 sock6;
440
441    assert( tr_isAddress( addr ) );
442
443    if( addr->type == TR_AF_INET )
444    {
445        memset( &sock4, 0, sizeof( sock4 ) );
446        sock4.sin_family      = AF_INET;
447        sock4.sin_addr.s_addr = addr->addr.addr4.s_addr;
448        sock4.sin_port        = port;
449        memcpy( sockaddr, &sock4, sizeof( sock4 ) );
450        return sizeof( struct sockaddr_in );
451    }
452    else
453    {
454        memset( &sock6, 0, sizeof( sock6 ) );
455        sock6.sin6_family = AF_INET6;
456        sock6.sin6_port = port;
457        sock6.sin6_flowinfo = 0;
458        sock6.sin6_addr = addr->addr.addr6;
459        memcpy( sockaddr, &sock6, sizeof( sock6 ) );
460        return sizeof( struct sockaddr_in6 );
461    }
462}
463
464static tr_bool
465isMulticastAddress( const tr_address * addr )
466{
467    if( addr->type == TR_AF_INET && IN_MULTICAST( htonl( addr->addr.addr4.s_addr ) ) )
468        return TRUE;
469
470    if( addr->type == TR_AF_INET6 && ( addr->addr.addr6.s6_addr[0] == 0xff ) )
471        return TRUE;
472
473    return FALSE;
474}
475
476tr_bool
477tr_isValidPeerAddress( const tr_address * addr, tr_port port )
478{
479    if( isMulticastAddress( addr ) )
480        return FALSE;
481
482    if( port == 0 )
483        return FALSE;
484
485    return TRUE;
486}
487
488int
489tr_netOpenTCP( tr_session        * session,
490               const tr_address  * addr,
491               tr_port             port )
492{
493    int                     s;
494    struct sockaddr_storage sock;
495    const int               type = SOCK_STREAM;
496    socklen_t               addrlen;
497
498    assert( tr_isAddress( addr ) );
499
500    if( isMulticastAddress( addr ) )
501        return -EINVAL;
502
503    if( ( s = createSocket( ( addr->type == TR_AF_INET ? AF_INET : AF_INET6 ), type ) ) < 0 )
504        return s;
505
506    setSndBuf( session, s );
507
508    addrlen = setup_sockaddr( addr, port, &sock );
509
510    if( ( connect( s, (struct sockaddr *) &sock,
511                  addrlen ) < 0 )
512#ifdef WIN32
513      && ( sockerrno != WSAEWOULDBLOCK )
514#endif
515      && ( sockerrno != EINPROGRESS ) )
516    {
517        int tmperrno;
518        tmperrno = sockerrno;
519        if( tmperrno != ENETUNREACH || addr->type == TR_AF_INET )
520            tr_err( _( "Couldn't connect socket %d to %s, port %d (errno %d - %s)" ),
521                    s, tr_ntop_non_ts( addr ), (int)port, tmperrno,
522                    tr_strerror( tmperrno ) );
523        tr_netClose( s );
524        s = -tmperrno;
525    }
526
527    tr_deepLog( __FILE__, __LINE__, NULL, "New OUTGOING connection %d (%s)",
528               s, tr_peerIoAddrStr( addr, port ) );
529
530    return s;
531}
532
533int
534tr_netBindTCP( const tr_address * addr, tr_port port, tr_bool suppressMsgs )
535{
536    int                     s;
537    struct sockaddr_storage sock;
538    const int               type = SOCK_STREAM;
539    int                     addrlen;
540
541#if defined( SO_REUSEADDR ) || defined( SO_REUSEPORT )
542    int                optval;
543#endif
544
545    assert( tr_isAddress( addr ) );
546
547    if( ( s = createSocket( ( addr->type == TR_AF_INET ? AF_INET : AF_INET6 ),
548                            type ) ) < 0 )
549        return s;
550
551#ifdef SO_REUSEADDR
552    optval = 1;
553    setsockopt( s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof( optval ) );
554#endif
555
556    addrlen = setup_sockaddr( addr, htons( port ), &sock );
557
558    if( bind( s, (struct sockaddr *) &sock,
559             addrlen ) )
560    {
561        int tmperrno;
562        if( !suppressMsgs )
563            tr_err( _( "Couldn't bind port %d on %s: %s" ), port,
564                    tr_ntop_non_ts( addr ), tr_strerror( sockerrno ) );
565        tmperrno = sockerrno;
566        tr_netClose( s );
567        return -tmperrno;
568    }
569    if( !suppressMsgs )
570        tr_dbg(  "Bound socket %d to port %d on %s",
571                 s, port, tr_ntop_non_ts( addr ) );
572    return s;
573}
574
575int
576tr_netAccept( tr_session  * session,
577              int           b,
578              tr_address  * addr,
579              tr_port     * port )
580{
581    int fd;
582
583    fd = makeSocketNonBlocking( tr_fdSocketAccept( b, addr, port ) );
584    setSndBuf( session, fd );
585    return fd;
586}
587
588void
589tr_netClose( int s )
590{
591    tr_fdSocketClose( s );
592}
Note: See TracBrowser for help on using the repository browser.