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