source: trunk/libtransmission/net.c @ 7574

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

(trunk libT) make tr_isAddress() and tr_isDirection() inline

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