source: trunk/libtransmission/net.c @ 7652

Last change on this file since 7652 was 7652, checked in by charles, 13 years ago

(trunk libT) win32 portability fixes, reported by Alexey

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