]> git.sesse.net Git - vlc/blob - modules/misc/network/ipv4.c
* ipv4.c: make MSVC happy
[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                                 typedef DWORD (CALLBACK * GETBESTINTERFACE) ( IPAddr, PDWORD );
348                                 typedef DWORD (CALLBACK * GETIPADDRTABLE) ( PMIB_IPADDRTABLE, PULONG, BOOL );
349
350                 GETBESTINTERFACE OurGetBestInterface;
351                                 GETIPADDRTABLE OurGetIpAddrTable;
352                 HINSTANCE hiphlpapi = LoadLibrary(_T("Iphlpapi.dll"));
353                 DWORD i_index;
354
355                 if( hiphlpapi )
356                 {
357                     OurGetBestInterface =
358                         (void *)GetProcAddress( hiphlpapi,
359                                                 _T("GetBestInterface") );
360                     OurGetIpAddrTable =
361                         (void *)GetProcAddress( hiphlpapi,
362                                                 _T("GetIpAddrTable") );
363                 }
364
365                 if( hiphlpapi && OurGetBestInterface && OurGetIpAddrTable &&
366                     OurGetBestInterface( sock.sin_addr.s_addr,
367                                          &i_index ) == NO_ERROR )
368                 {
369                     PMIB_IPADDRTABLE p_table;
370                     DWORD i = 0;
371
372                     msg_Dbg( p_this, "Winsock best interface is %lu",
373                              (unsigned long)i_index );
374                     OurGetIpAddrTable( NULL, &i, 0 );
375
376                     p_table = (PMIB_IPADDRTABLE)malloc( i );
377                     if( p_table != NULL )
378                     {
379                         if( OurGetIpAddrTable( p_table, &i, 0 ) == NO_ERROR )
380                         {
381                             for( i = 0; i < p_table->dwNumEntries; i-- )
382                             {
383                                 if( p_table->table[i].dwIndex == i_index )
384                                 {
385                                     imr.imr_interface.s_addr =
386                                                      p_table->table[i].dwAddr;
387                                     msg_Dbg( p_this, "using interface 0x%08x",
388                                              p_table->table[i].dwAddr );
389                                 }
390                             }
391                         }
392                         else msg_Warn( p_this, "GetIpAddrTable failed" );
393                         free( p_table );
394                     }
395                 }
396                 else msg_Dbg( p_this, "GetBestInterface failed" );
397
398                 if( hiphlpapi ) FreeLibrary( hiphlpapi );
399             }
400 #endif
401             if( psz_if_addr != NULL ) free( psz_if_addr );
402
403             msg_Dbg( p_this, "IP_ADD_MEMBERSHIP multicast request" );
404             /* Join Multicast group without source filter */
405             if( setsockopt( i_handle, IPPROTO_IP, IP_ADD_MEMBERSHIP,
406                             (char*)&imr, sizeof(struct ip_mreq) ) == -1 )
407             {
408                 msg_Err( p_this, "failed to join IP multicast group (%s)",
409                                   strerror(errno) );
410                 close( i_handle );
411                 return 0;
412             }
413          }
414     }
415 #endif
416
417     if( *psz_server_addr )
418     {
419         /* Build socket for remote connection */
420         if ( BuildAddr( &sock, psz_server_addr, i_server_port ) == -1 )
421         {
422             msg_Warn( p_this, "cannot build remote address" );
423             close( i_handle );
424             return 0;
425         }
426
427         /* Connect the socket */
428         if( connect( i_handle, (struct sockaddr *) &sock,
429                      sizeof( sock ) ) == (-1) )
430         {
431             msg_Warn( p_this, "cannot connect socket (%s)", strerror(errno) );
432             close( i_handle );
433             return 0;
434         }
435
436 #if !defined( SYS_BEOS )
437         if( IN_MULTICAST( ntohl(inet_addr(psz_server_addr) ) ) )
438         {
439             /* set the time-to-live */
440             int i_ttl = p_socket->i_ttl;
441             unsigned char ttl;
442             
443             /* set the multicast interface */
444             char * psz_mif_addr = config_GetPsz( p_this, "miface-addr" );
445             if( psz_mif_addr )
446             {
447                 struct in_addr intf;
448                 intf.s_addr = inet_addr(psz_mif_addr);
449                 free( psz_mif_addr  );
450
451                 if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_IF,
452                                 &intf, sizeof( intf ) ) < 0 )
453                 {
454                     msg_Dbg( p_this, "failed to set multicast interface (%s).", strerror(errno) );
455                     close( i_handle );
456                     return 0;
457                 }
458             }
459
460             if( i_ttl < 1 )
461             {
462                 if( var_Get( p_this, "ttl", &val ) != VLC_SUCCESS )
463                 {
464                     var_Create( p_this, "ttl",
465                                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
466                     var_Get( p_this, "ttl", &val );
467                 }
468                 i_ttl = val.i_int;
469             }
470             if( i_ttl < 1 ) i_ttl = 1;
471             ttl = (unsigned char) i_ttl;
472
473             /* There is some confusion in the world whether IP_MULTICAST_TTL 
474              * takes a byte or an int as an argument.
475              * BSD seems to indicate byte so we are going with that and use
476              * int as a fallback to be safe */
477             if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_TTL,
478                             &ttl, sizeof( ttl ) ) < 0 )
479             {
480                 msg_Dbg( p_this, "failed to set ttl (%s). Let's try it "
481                          "the integer way.", strerror(errno) );
482                 if( setsockopt( i_handle, IPPROTO_IP, IP_MULTICAST_TTL,
483                                 &i_ttl, sizeof( i_ttl ) ) <0 )
484                 {
485                     msg_Err( p_this, "failed to set ttl (%s)",
486                              strerror(errno) );
487                     close( i_handle );
488                     return 0;
489                 }
490             }
491         }
492 #endif
493     }
494
495     p_socket->i_handle = i_handle;
496
497     if( var_Get( p_this, "mtu", &val ) != VLC_SUCCESS )
498     {
499         var_Create( p_this, "mtu", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
500         var_Get( p_this, "mtu", &val );
501     }
502     p_socket->i_mtu = val.i_int;
503
504     return 0;
505 }