]> git.sesse.net Git - vlc/blob - modules/misc/network/ipv4.c
90d8370fbde7be58f098b0ad5c7341d6c1397ce1
[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_ADVANCED );
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     i_opt = 0x80000;
235 #if !defined( SYS_BEOS )
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 #endif
241
242     /* Build the local socket */
243
244 #if defined( WIN32 ) || defined( UNDER_CE )
245     /* Under Win32 and for multicasting, we bind to INADDR_ANY,
246      * so let's call BuildAddr with "" instead of psz_bind_addr */
247     if( BuildAddr( &sock, IN_MULTICAST( ntohl( inet_addr(psz_bind_addr) ) ) ?
248                    "" : psz_bind_addr, i_bind_port ) == -1 )
249 #else
250     if( BuildAddr( &sock, psz_bind_addr, i_bind_port ) == -1 )
251 #endif
252     {
253         msg_Dbg( p_this, "could not build local address" );
254         close( i_handle );
255         return 0;
256     }
257
258     /* Bind it */
259     if( bind( i_handle, (struct sockaddr *)&sock, sizeof( sock ) ) < 0 )
260     {
261         msg_Warn( p_this, "cannot bind socket (%s)", strerror(errno) );
262         close( i_handle );
263         return 0;
264     }
265
266 #if defined( WIN32 ) || defined( UNDER_CE )
267     /* Restore the sock struct so we can spare a few #ifdef WIN32 later on */
268     if( IN_MULTICAST( ntohl( inet_addr(psz_bind_addr) ) ) )
269     {
270         if ( BuildAddr( &sock, psz_bind_addr, i_bind_port ) == -1 )
271         {
272             msg_Dbg( p_this, "could not build local address" );
273             close( i_handle );
274             return 0;
275         }
276     }
277 #endif
278
279 #if !defined( SYS_BEOS )
280     /* Allow broadcast reception if we bound on INADDR_ANY */
281     if( !*psz_bind_addr )
282     {
283         i_opt = 1;
284         if( setsockopt( i_handle, SOL_SOCKET, SO_BROADCAST, (void*) &i_opt,
285                         sizeof( i_opt ) ) == -1 )
286             msg_Warn( p_this, "cannot configure socket (SO_BROADCAST: %s)",
287                        strerror(errno) );
288     }
289 #endif
290
291 #if !defined( SYS_BEOS )
292     /* Join the multicast group if the socket is a multicast address */
293     if( IN_MULTICAST( ntohl(sock.sin_addr.s_addr) ) )
294     {
295         /* Determine interface to be used for multicast */
296         char * psz_if_addr = config_GetPsz( p_this, "iface-addr" );
297
298         /* If we have a source address, we use IP_ADD_SOURCE_MEMBERSHIP
299            so that IGMPv3 aware OSes running on IGMPv3 aware networks
300            will do an IGMPv3 query on the network */
301         if( *psz_server_addr )
302         {
303             struct ip_mreq_source imr;
304
305             imr.imr_multiaddr.s_addr = sock.sin_addr.s_addr;
306             imr.imr_sourceaddr.s_addr = inet_addr(psz_server_addr);
307
308             if( psz_if_addr != NULL && *psz_if_addr
309                 && inet_addr(psz_if_addr) != INADDR_NONE )
310             {
311                 imr.imr_interface.s_addr = inet_addr(psz_if_addr);
312             }
313             else
314             {
315                 imr.imr_interface.s_addr = INADDR_ANY;
316             }
317             if( psz_if_addr != NULL ) free( psz_if_addr );
318
319             msg_Dbg( p_this, "IP_ADD_SOURCE_MEMBERSHIP multicast request" );
320             /* Join Multicast group with source filter */
321             if( setsockopt( i_handle, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP,
322                          (char*)&imr,
323                          sizeof(struct ip_mreq_source) ) == -1 )
324             {
325                 msg_Err( p_this, "failed to join IP multicast group (%s)",
326                                   strerror(errno) );
327                 msg_Err( p_this, "are you sure your OS supports IGMPv3?" );
328                 close( i_handle );
329                 return 0;
330             }
331          }
332          /* If there is no source address, we use IP_ADD_MEMBERSHIP */
333          else
334          {
335              struct ip_mreq imr;
336
337              imr.imr_interface.s_addr = INADDR_ANY;
338              imr.imr_multiaddr.s_addr = sock.sin_addr.s_addr;
339              if( psz_if_addr != NULL && *psz_if_addr
340                 && inet_addr(psz_if_addr) != INADDR_NONE )
341             {
342                 imr.imr_interface.s_addr = inet_addr(psz_if_addr);
343             }
344 #if defined (WIN32) || defined (UNDER_CE)
345             else
346             {
347                 DWORD WINAPI (*OurGetBestInterface)(IPAddr,PDWORD);
348                 DWORD WINAPI (*OurGetIpAddrTable)(PMIB_IPADDRTABLE,PULONG,BOOL);
349                 HINSTANCE hiphlpapi = LoadLibrary(_T("Iphlpapi.dll"));
350                 DWORD i_index;
351
352                 if( hiphlpapi )
353                 {
354                     OurGetBestInterface =
355                         (void *)GetProcAddress( hiphlpapi,
356                                                 _T("GetBestInterface") );
357                     OurGetIpAddrTable =
358                         (void *)GetProcAddress( hiphlpapi,
359                                                 _T("GetIpAddrTable") );
360                 }
361
362                 if( hiphlpapi && OurGetBestInterface && OurGetIpAddrTable &&
363                     OurGetBestInterface( sock.sin_addr.s_addr,
364                                          &i_index ) == NO_ERROR )
365                 {
366                     PMIB_IPADDRTABLE p_table;
367                     DWORD i = 0;
368
369                     msg_Dbg( p_this, "Winsock best interface is %lu",
370                              (unsigned long)i_index );
371                     OurGetIpAddrTable( NULL, &i, 0 );
372
373                     p_table = (PMIB_IPADDRTABLE)malloc( i );
374                     if( p_table != NULL )
375                     {
376                         if( OurGetIpAddrTable( p_table, &i, 0 ) == NO_ERROR )
377                         {
378                             for( i = 0; i < p_table->dwNumEntries; i-- )
379                             {
380                                 if( p_table->table[i].dwIndex == i_index )
381                                 {
382                                     imr.imr_interface.s_addr =
383                                                      p_table->table[i].dwAddr;
384                                     msg_Dbg( p_this, "using interface 0x%08x",
385                                              p_table->table[i].dwAddr );
386                                 }
387                             }
388                         }
389                         else msg_Warn( p_this, "GetIpAddrTable failed" );
390                         free( p_table );
391                     }
392                 }
393                 else msg_Dbg( p_this, "GetBestInterface failed" );
394
395                 if( hiphlpapi ) FreeLibrary( hiphlpapi );
396             }
397 #endif
398             if( psz_if_addr != NULL ) free( psz_if_addr );
399
400             msg_Dbg( p_this, "IP_ADD_MEMBERSHIP multicast request" );
401             /* Join Multicast group without source filter */
402             if( setsockopt( i_handle, IPPROTO_IP, IP_ADD_MEMBERSHIP,
403                             (char*)&imr, sizeof(struct ip_mreq) ) == -1 )
404             {
405                 msg_Err( p_this, "failed to join IP multicast group (%s)",
406                                   strerror(errno) );
407                 close( i_handle );
408                 return 0;
409             }
410          }
411     }
412 #endif
413
414     if( *psz_server_addr )
415     {
416         /* Build socket for remote connection */
417         if ( BuildAddr( &sock, psz_server_addr, i_server_port ) == -1 )
418         {
419             msg_Warn( p_this, "cannot build remote address" );
420             close( i_handle );
421             return 0;
422         }
423
424         /* Connect the socket */
425         if( connect( i_handle, (struct sockaddr *) &sock,
426                      sizeof( sock ) ) == (-1) )
427         {
428             msg_Warn( p_this, "cannot connect socket (%s)", strerror(errno) );
429             close( i_handle );
430             return 0;
431         }
432
433 #if !defined( SYS_BEOS )
434         if( IN_MULTICAST( ntohl(inet_addr(psz_server_addr) ) ) )
435         {
436             /* set the time-to-live */
437             int i_ttl = p_socket->i_ttl;
438             unsigned char ttl;
439             
440             /* set the multicast interface */
441             char * psz_mif_addr = config_GetPsz( p_this, "miface-addr" );
442             if( psz_mif_addr )
443             {
444                 struct in_addr intf;
445                 intf.s_addr = inet_addr(psz_mif_addr);
446                 free( psz_mif_addr  );
447
448                 if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_IF,
449                                 &intf, sizeof( intf ) ) < 0 )
450                 {
451                     msg_Dbg( p_this, "failed to set multicast interface (%s).", strerror(errno) );
452                     close( i_handle );
453                     return 0;
454                 }
455             }
456
457             if( i_ttl < 1 )
458             {
459                 if( var_Get( p_this, "ttl", &val ) != VLC_SUCCESS )
460                 {
461                     var_Create( p_this, "ttl",
462                                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
463                     var_Get( p_this, "ttl", &val );
464                 }
465                 i_ttl = val.i_int;
466             }
467             if( i_ttl < 1 ) i_ttl = 1;
468             ttl = (unsigned char) i_ttl;
469
470             /* There is some confusion in the world whether IP_MULTICAST_TTL 
471              * takes a byte or an int as an argument.
472              * BSD seems to indicate byte so we are going with that and use
473              * int as a fallback to be safe */
474             if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_TTL,
475                             &ttl, sizeof( ttl ) ) < 0 )
476             {
477                 msg_Dbg( p_this, "failed to set ttl (%s). Let's try it "
478                          "the integer way.", strerror(errno) );
479                 if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_TTL,
480                                 &i_ttl, sizeof( i_ttl ) ) <0 )
481                 {
482                     msg_Err( p_this, "failed to set ttl (%s)",
483                              strerror(errno) );
484                     close( i_handle );
485                     return 0;
486                 }
487             }
488         }
489 #endif
490     }
491
492     p_socket->i_handle = i_handle;
493
494     if( var_Get( p_this, "mtu", &val ) != VLC_SUCCESS )
495     {
496         var_Create( p_this, "mtu", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
497         var_Get( p_this, "mtu", &val );
498     }
499     p_socket->i_mtu = val.i_int;
500
501     return 0;
502 }