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