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