]> git.sesse.net Git - vlc/blob - modules/misc/network/ipv4.c
3a0f46746d55d7dbdba74cc18c868edd93799414
[vlc] / modules / misc / network / ipv4.c
1 /*****************************************************************************
2  * ipv4.c: IPv4 network abstraction layer
3  *****************************************************************************
4  * Copyright (C) 2001-2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *          Mathias Kretschmer <mathias@research.att.com>
9  *          Alexis de Lattre <alexis@via.ecp.fr>
10  *          RĂ©mi Denis-Courmont <rem # videolan.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include <vlc/vlc.h>
34 #include <errno.h>
35
36 #ifdef HAVE_SYS_TYPES_H
37 #   include <sys/types.h>
38 #endif
39 #ifdef HAVE_SYS_STAT_H
40 #   include <sys/stat.h>
41 #endif
42 #ifdef HAVE_FCNTL_H
43 #   include <fcntl.h>
44 #endif
45
46 #ifdef HAVE_UNISTD_H
47 #   include <unistd.h>
48 #endif
49
50 #if defined(WIN32) || defined(UNDER_CE)
51 #   if defined(UNDER_CE) && defined(sockaddr_storage)
52 #       undef sockaddr_storage
53 #   endif
54 #   include <winsock2.h>
55 #   include <ws2tcpip.h>
56 #   include <iphlpapi.h>
57 #   define close closesocket
58 #   if defined(UNDER_CE)
59 #       undef IP_MULTICAST_TTL
60 #       define IP_MULTICAST_TTL 3
61 #       undef IP_ADD_MEMBERSHIP
62 #       define IP_ADD_MEMBERSHIP 5
63 #   endif
64 #else
65 #   include <netdb.h>                                         /* hostent ... */
66 #   include <sys/socket.h>
67 #   include <netinet/in.h>
68 #   ifdef HAVE_ARPA_INET_H
69 #       include <arpa/inet.h>                    /* inet_ntoa(), inet_aton() */
70 #   endif
71 #endif
72
73 #include "network.h"
74
75 #ifndef INADDR_ANY
76 #   define INADDR_ANY  0x00000000
77 #endif
78 #ifndef INADDR_NONE
79 #   define INADDR_NONE 0xFFFFFFFF
80 #endif
81 #ifndef IN_MULTICAST
82 #   define IN_MULTICAST(a) IN_CLASSD(a)
83 #endif
84
85
86 /*****************************************************************************
87  * Local prototypes
88  *****************************************************************************/
89 static int OpenUDP( vlc_object_t * );
90
91 /*****************************************************************************
92  * Module descriptor
93  *****************************************************************************/
94 #define MIFACE_TEXT N_("Multicast output interface")
95 #define MIFACE_LONGTEXT N_( \
96     "Indicate here the multicast output interface. " \
97     "This overrides the routing table.")
98
99 vlc_module_begin();
100     set_shortname( "IPv4" );
101     set_description( _("UDP/IPv4 network abstraction layer") );
102     set_capability( "network", 50 );
103     set_category( CAT_INPUT );
104     set_subcategory( SUBCAT_INPUT_GENERAL );
105     set_callbacks( OpenUDP, NULL );
106     add_string( "miface-addr", NULL, NULL, MIFACE_TEXT, MIFACE_LONGTEXT, VLC_TRUE );
107 vlc_module_end();
108
109 /*****************************************************************************
110  * BuildAddr: utility function to build a struct sockaddr_in
111  *****************************************************************************/
112 static int BuildAddr( struct sockaddr_in * p_socket,
113                       const char * psz_address, int i_port )
114 {
115     /* Reset struct */
116     memset( p_socket, 0, sizeof( struct sockaddr_in ) );
117     p_socket->sin_family = AF_INET;                                /* family */
118     p_socket->sin_port = htons( (uint16_t)i_port );
119     if( !*psz_address )
120     {
121         p_socket->sin_addr.s_addr = INADDR_ANY;
122     }
123     else
124     {
125         struct hostent    * p_hostent;
126
127         /* Try to convert address directly from in_addr - this will work if
128          * psz_address is dotted decimal. */
129 #ifdef HAVE_ARPA_INET_H
130         if( !inet_aton( psz_address, &p_socket->sin_addr ) )
131 #else
132         p_socket->sin_addr.s_addr = inet_addr( psz_address );
133         if( p_socket->sin_addr.s_addr == INADDR_NONE )
134 #endif
135         {
136             /* We have a fqdn, try to find its address */
137             if ( (p_hostent = gethostbyname( psz_address )) == NULL )
138             {
139                 return( -1 );
140             }
141
142             /* Copy the first address of the host in the socket address */
143             memcpy( &p_socket->sin_addr, p_hostent->h_addr_list[0],
144                      p_hostent->h_length );
145         }
146     }
147     return( 0 );
148 }
149
150 #if defined(WIN32) || defined(UNDER_CE)
151 # define WINSOCK_STRERROR_SIZE 20
152 static const char *winsock_strerror( char *buf )
153 {
154     snprintf( buf, WINSOCK_STRERROR_SIZE, "Winsock error %d",
155               WSAGetLastError( ) );
156     buf[WINSOCK_STRERROR_SIZE - 1] = '\0';
157     return buf;
158 }
159 #endif
160
161
162 /*****************************************************************************
163  * OpenUDP: open a UDP socket
164  *****************************************************************************
165  * psz_bind_addr, i_bind_port : address and port used for the bind()
166  *   system call. If psz_bind_addr == "", the socket is bound to
167  *   INADDR_ANY and broadcast reception is enabled. If psz_bind_addr is a
168  *   multicast (class D) address, join the multicast group.
169  * psz_server_addr, i_server_port : address and port used for the connect()
170  *   system call. It can avoid receiving packets from unauthorized IPs.
171  *   Its use leads to great confusion and is currently discouraged.
172  * This function returns -1 in case of error.
173  *****************************************************************************/
174 static int OpenUDP( vlc_object_t * p_this )
175 {
176     network_socket_t * p_socket = p_this->p_private;
177     const char * psz_bind_addr = p_socket->psz_bind_addr;
178     int i_bind_port = p_socket->i_bind_port;
179     const char * psz_server_addr = p_socket->psz_server_addr;
180     int i_server_port = p_socket->i_server_port;
181
182     int i_handle, i_opt;
183     struct sockaddr_in sock;
184     vlc_value_t val;
185 #if defined(WIN32) || defined(UNDER_CE)
186     char strerror_buf[WINSOCK_STRERROR_SIZE];
187 # define strerror( x ) winsock_strerror( strerror_buf )
188 #endif
189
190     /* If IP_ADD_SOURCE_MEMBERSHIP is not defined in the headers
191        (because it's not in glibc for example), we have to define the
192        headers required for IGMPv3 here */
193 #ifndef IP_ADD_SOURCE_MEMBERSHIP
194     #define IP_ADD_SOURCE_MEMBERSHIP  39
195     struct ip_mreq_source {
196         struct in_addr  imr_multiaddr;
197         struct in_addr  imr_interface;
198         struct in_addr  imr_sourceaddr;
199      };
200 #endif
201
202     p_socket->i_handle = -1;
203
204     /* Open a SOCK_DGRAM (UDP) socket, in the AF_INET domain, automatic (0)
205      * protocol */
206     if( (i_handle = socket( AF_INET, SOCK_DGRAM, 0 )) == -1 )
207     {
208         msg_Warn( p_this, "cannot create socket (%s)", strerror(errno) );
209         return 0;
210     }
211
212     /* We may want to reuse an already used socket */
213     i_opt = 1;
214     if( setsockopt( i_handle, SOL_SOCKET, SO_REUSEADDR,
215                     (void *) &i_opt, sizeof( i_opt ) ) == -1 )
216     {
217         msg_Warn( p_this, "cannot configure socket (SO_REUSEADDR: %s)",
218                           strerror(errno));
219         close( i_handle );
220         return 0;
221     }
222
223 #ifdef SO_REUSEPORT
224     i_opt = 1;
225     if( setsockopt( i_handle, SOL_SOCKET, SO_REUSEPORT,
226                     (void *) &i_opt, sizeof( i_opt ) ) == -1 )
227     {
228         msg_Warn( p_this, "cannot configure socket (SO_REUSEPORT)" );
229     }
230 #endif
231
232     /* Increase the receive buffer size to 1/2MB (8Mb/s during 1/2s) to avoid
233      * packet loss caused by scheduling problems */
234 #if !defined( SYS_BEOS )
235     i_opt = 0x80000;
236     if( setsockopt( i_handle, SOL_SOCKET, SO_RCVBUF, (void *) &i_opt,
237                     sizeof( i_opt ) ) == -1 )
238         msg_Dbg( p_this, "cannot configure socket (SO_RCVBUF: %s)",
239                           strerror(errno));
240     i_opt = 0x80000;
241     if( setsockopt( i_handle, SOL_SOCKET, SO_SNDBUF, (void *) &i_opt,
242                     sizeof( i_opt ) ) == -1 )
243         msg_Dbg( p_this, "cannot configure socket (SO_SNDBUF: %s)",
244                           strerror(errno));
245 #endif
246
247     /* Build the local socket */
248
249 #if defined( WIN32 ) || defined( UNDER_CE )
250     /* Under Win32 and for multicasting, we bind to INADDR_ANY,
251      * so let's call BuildAddr with "" instead of psz_bind_addr */
252     if( BuildAddr( &sock, IN_MULTICAST( ntohl( inet_addr(psz_bind_addr) ) ) ?
253                    "" : psz_bind_addr, i_bind_port ) == -1 )
254 #else
255     if( BuildAddr( &sock, psz_bind_addr, i_bind_port ) == -1 )
256 #endif
257     {
258         msg_Dbg( p_this, "could not build local address" );
259         close( i_handle );
260         return 0;
261     }
262
263     /* Bind it */
264     if( bind( i_handle, (struct sockaddr *)&sock, sizeof( sock ) ) < 0 )
265     {
266         msg_Warn( p_this, "cannot bind socket (%s)", strerror(errno) );
267         close( i_handle );
268         return 0;
269     }
270
271 #if defined( WIN32 ) || defined( UNDER_CE )
272     /* Restore the sock struct so we can spare a few #ifdef WIN32 later on */
273     if( IN_MULTICAST( ntohl( inet_addr(psz_bind_addr) ) ) )
274     {
275         if ( BuildAddr( &sock, psz_bind_addr, i_bind_port ) == -1 )
276         {
277             msg_Dbg( p_this, "could not build local address" );
278             close( i_handle );
279             return 0;
280         }
281     }
282 #endif
283
284 #if !defined( SYS_BEOS )
285     /* Allow broadcast reception if we bound on INADDR_ANY */
286     if( !*psz_bind_addr )
287     {
288         i_opt = 1;
289         if( setsockopt( i_handle, SOL_SOCKET, SO_BROADCAST, (void*) &i_opt,
290                         sizeof( i_opt ) ) == -1 )
291             msg_Warn( p_this, "cannot configure socket (SO_BROADCAST: %s)",
292                        strerror(errno) );
293     }
294 #endif
295
296 #if !defined( SYS_BEOS )
297     /* Join the multicast group if the socket is a multicast address */
298     if( IN_MULTICAST( ntohl(sock.sin_addr.s_addr) ) )
299     {
300         /* Determine interface to be used for multicast */
301         char * psz_if_addr = config_GetPsz( p_this, "miface-addr" );
302
303         /* If we have a source address, we use IP_ADD_SOURCE_MEMBERSHIP
304            so that IGMPv3 aware OSes running on IGMPv3 aware networks
305            will do an IGMPv3 query on the network */
306         if( *psz_server_addr )
307         {
308             struct ip_mreq_source imr;
309
310             imr.imr_multiaddr.s_addr = sock.sin_addr.s_addr;
311             imr.imr_sourceaddr.s_addr = inet_addr(psz_server_addr);
312
313             if( psz_if_addr != NULL && *psz_if_addr
314                 && inet_addr(psz_if_addr) != INADDR_NONE )
315             {
316                 imr.imr_interface.s_addr = inet_addr(psz_if_addr);
317             }
318             else
319             {
320                 imr.imr_interface.s_addr = INADDR_ANY;
321             }
322             if( psz_if_addr != NULL ) free( psz_if_addr );
323
324             msg_Dbg( p_this, "IP_ADD_SOURCE_MEMBERSHIP multicast request" );
325             /* Join Multicast group with source filter */
326             if( setsockopt( i_handle, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP,
327                          (char*)&imr,
328                          sizeof(struct ip_mreq_source) ) == -1 )
329             {
330                 msg_Err( p_this, "failed to join IP multicast group (%s)",
331                                   strerror(errno) );
332                 msg_Err( p_this, "are you sure your OS supports IGMPv3?" );
333                 close( i_handle );
334                 return 0;
335             }
336          }
337          /* If there is no source address, we use IP_ADD_MEMBERSHIP */
338          else
339          {
340              struct ip_mreq imr;
341
342              imr.imr_interface.s_addr = INADDR_ANY;
343              imr.imr_multiaddr.s_addr = sock.sin_addr.s_addr;
344              if( psz_if_addr != NULL && *psz_if_addr
345                 && inet_addr(psz_if_addr) != INADDR_NONE )
346             {
347                 imr.imr_interface.s_addr = inet_addr(psz_if_addr);
348             }
349 #if defined (WIN32) || defined (UNDER_CE)
350             else
351             {
352                                 typedef DWORD (CALLBACK * GETBESTINTERFACE) ( IPAddr, PDWORD );
353                                 typedef DWORD (CALLBACK * GETIPADDRTABLE) ( PMIB_IPADDRTABLE, PULONG, BOOL );
354
355                 GETBESTINTERFACE OurGetBestInterface;
356                                 GETIPADDRTABLE OurGetIpAddrTable;
357                 HINSTANCE hiphlpapi = LoadLibrary(_T("Iphlpapi.dll"));
358                 DWORD i_index;
359
360                 if( hiphlpapi )
361                 {
362                     OurGetBestInterface =
363                         (void *)GetProcAddress( hiphlpapi,
364                                                 _T("GetBestInterface") );
365                     OurGetIpAddrTable =
366                         (void *)GetProcAddress( hiphlpapi,
367                                                 _T("GetIpAddrTable") );
368                 }
369
370                 if( hiphlpapi && OurGetBestInterface && OurGetIpAddrTable &&
371                     OurGetBestInterface( sock.sin_addr.s_addr,
372                                          &i_index ) == NO_ERROR )
373                 {
374                     PMIB_IPADDRTABLE p_table;
375                     DWORD i = 0;
376
377                     msg_Dbg( p_this, "Winsock best interface is %lu",
378                              (unsigned long)i_index );
379                     OurGetIpAddrTable( NULL, &i, 0 );
380
381                     p_table = (PMIB_IPADDRTABLE)malloc( i );
382                     if( p_table != NULL )
383                     {
384                         if( OurGetIpAddrTable( p_table, &i, 0 ) == NO_ERROR )
385                         {
386                             for( i = 0; i < p_table->dwNumEntries; i-- )
387                             {
388                                 if( p_table->table[i].dwIndex == i_index )
389                                 {
390                                     imr.imr_interface.s_addr =
391                                                      p_table->table[i].dwAddr;
392                                     msg_Dbg( p_this, "using interface 0x%08x",
393                                              p_table->table[i].dwAddr );
394                                 }
395                             }
396                         }
397                         else msg_Warn( p_this, "GetIpAddrTable failed" );
398                         free( p_table );
399                     }
400                 }
401                 else msg_Dbg( p_this, "GetBestInterface failed" );
402
403                 if( hiphlpapi ) FreeLibrary( hiphlpapi );
404             }
405 #endif
406             if( psz_if_addr != NULL ) free( psz_if_addr );
407
408             msg_Dbg( p_this, "IP_ADD_MEMBERSHIP multicast request" );
409             /* Join Multicast group without source filter */
410             if( setsockopt( i_handle, IPPROTO_IP, IP_ADD_MEMBERSHIP,
411                             (char*)&imr, sizeof(struct ip_mreq) ) == -1 )
412             {
413                 msg_Err( p_this, "failed to join IP multicast group (%s)",
414                                   strerror(errno) );
415                 close( i_handle );
416                 return 0;
417             }
418          }
419     }
420 #endif
421
422     if( *psz_server_addr )
423     {
424         /* Build socket for remote connection */
425         if ( BuildAddr( &sock, psz_server_addr, i_server_port ) == -1 )
426         {
427             msg_Warn( p_this, "cannot build remote address" );
428             close( i_handle );
429             return 0;
430         }
431
432         /* Connect the socket */
433         if( connect( i_handle, (struct sockaddr *) &sock,
434                      sizeof( sock ) ) == (-1) )
435         {
436             msg_Warn( p_this, "cannot connect socket (%s)", strerror(errno) );
437             close( i_handle );
438             return 0;
439         }
440
441 #if !defined( SYS_BEOS )
442         if( IN_MULTICAST( ntohl(inet_addr(psz_server_addr) ) ) )
443         {
444             /* set the time-to-live */
445             int i_ttl = p_socket->i_ttl;
446             unsigned char ttl;
447
448             /* set the multicast interface */
449             char * psz_mif_addr = config_GetPsz( p_this, "miface-addr" );
450             if( psz_mif_addr )
451             {
452                 struct in_addr intf;
453                 intf.s_addr = inet_addr(psz_mif_addr);
454                 free( psz_mif_addr  );
455
456                 if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_IF,
457                                 &intf, sizeof( intf ) ) < 0 )
458                 {
459                     msg_Dbg( p_this, "failed to set multicast interface (%s).", strerror(errno) );
460                     close( i_handle );
461                     return 0;
462                 }
463             }
464
465             if( i_ttl < 1 )
466             {
467                 if( var_Get( p_this, "ttl", &val ) != VLC_SUCCESS )
468                 {
469                     var_Create( p_this, "ttl",
470                                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
471                     var_Get( p_this, "ttl", &val );
472                 }
473                 i_ttl = val.i_int;
474             }
475             if( i_ttl < 1 ) i_ttl = 1;
476             ttl = (unsigned char) i_ttl;
477
478             /* There is some confusion in the world whether IP_MULTICAST_TTL 
479              * takes a byte or an int as an argument.
480              * BSD seems to indicate byte so we are going with that and use
481              * int as a fallback to be safe */
482             if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_TTL,
483                             &ttl, sizeof( ttl ) ) < 0 )
484             {
485                 msg_Dbg( p_this, "failed to set ttl (%s). Let's try it "
486                          "the integer way.", strerror(errno) );
487                 if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_TTL,
488                                 &i_ttl, sizeof( i_ttl ) ) <0 )
489                 {
490                     msg_Err( p_this, "failed to set ttl (%s)",
491                              strerror(errno) );
492                     close( i_handle );
493                     return 0;
494                 }
495             }
496         }
497 #endif
498     }
499
500     p_socket->i_handle = i_handle;
501
502     if( var_Get( p_this, "mtu", &val ) != VLC_SUCCESS )
503     {
504         var_Create( p_this, "mtu", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
505         var_Get( p_this, "mtu", &val );
506     }
507     p_socket->i_mtu = val.i_int;
508
509     return 0;
510 }