]> git.sesse.net Git - vlc/blob - src/network/udp.c
08bcffd33d1d4f17f9d0ff0778ec0041e4ed19db
[vlc] / src / network / udp.c
1 /*****************************************************************************
2  * udp.c:
3  *****************************************************************************
4  * Copyright (C) 2004-2006 the VideoLAN team
5  * Copyright © 2006 Rémi Denis-Courmont
6  *
7  * $Id$
8  *
9  * Authors: Laurent Aimar <fenrir@videolan.org>
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 <vlc/vlc.h>
32
33 #include <errno.h>
34 #include <assert.h>
35
36 #ifdef HAVE_SYS_TIME_H
37 #    include <sys/time.h>
38 #endif
39
40 #include "network.h"
41
42 #ifdef WIN32
43 #   if defined(UNDER_CE)
44 #       undef IP_MULTICAST_TTL
45 #       define IP_MULTICAST_TTL 3
46 #       undef IP_ADD_MEMBERSHIP
47 #       define IP_ADD_MEMBERSHIP 5
48 #   endif
49 #   define EAFNOSUPPORT WSAEAFNOSUPPORT
50 #   define if_nametoindex( str ) atoi( str )
51 #else
52 #   include <unistd.h>
53 #   ifdef HAVE_NET_IF_H
54 #       include <net/if.h>
55 #   endif
56 #endif
57
58 #ifndef SOL_IP
59 # define SOL_IP IPPROTO_IP
60 #endif
61 #ifndef SOL_IPV6
62 # define SOL_IPV6 IPPROTO_IPV6
63 #endif
64 #ifndef IPPROTO_IPV6
65 # define IPPROTO_IPV6 41
66 #endif
67
68 extern int net_Socket( vlc_object_t *p_this, int i_family, int i_socktype,
69                        int i_protocol );
70
71
72 static int net_SetMcastHopLimit( vlc_object_t *p_this,
73                                  int fd, int family, int hlim )
74 {
75 #ifndef SYS_BEOS
76     int proto, cmd;
77
78     /* There is some confusion in the world whether IP_MULTICAST_TTL 
79      * takes a byte or an int as an argument.
80      * BSD seems to indicate byte so we are going with that and use
81      * int as a fallback to be safe */
82     switch( family )
83     {
84         case AF_INET:
85             proto = SOL_IP;
86             cmd = IP_MULTICAST_TTL;
87             break;
88
89 #ifdef IPV6_MULTICAST_HOPS
90         case AF_INET6:
91             proto = SOL_IPV6;
92             cmd = IPV6_MULTICAST_HOPS;
93             break;
94 #endif
95
96         default:
97             msg_Warn( p_this, "%s", strerror( EAFNOSUPPORT ) );
98             return VLC_EGENERIC;
99     }
100
101     if( setsockopt( fd, proto, cmd, &hlim, sizeof( hlim ) ) < 0 )
102     {
103         /* BSD compatibility */
104         unsigned char buf;
105
106         buf = (unsigned char)(( hlim > 255 ) ? 255 : hlim);
107         if( setsockopt( fd, proto, cmd, &buf, sizeof( buf ) ) )
108             return VLC_EGENERIC;
109     }
110 #endif
111     return VLC_SUCCESS;
112 }
113
114
115 static int net_SetMcastOutIface (int fd, int family, int scope)
116 {
117     switch (family)
118     {
119 #ifdef IPV6_MULTICAST_IF
120         case AF_INET6:
121             return setsockopt (fd, SOL_IPV6, IPV6_MULTICAST_IF,
122                                &scope, sizeof (scope));
123 #endif
124
125 #ifdef __linux__
126         case AF_INET:
127         {
128             struct ip_mreqn req = { .imr_ifindex = scope };
129
130             return setsockopt (fd, SOL_IP, IP_MULTICAST_IF, &req,
131                                sizeof (req));
132         }
133 #endif
134     }
135
136     errno = EAFNOSUPPORT;
137     return -1;
138 }
139
140
141 static inline int net_SetMcastOutIPv4 (int fd, struct in_addr ipv4)
142 {
143 #ifdef IP_MULTICAST_IF
144     return setsockopt( fd, SOL_IP, IP_MULTICAST_IF, &ipv4, sizeof (ipv4));
145 #else
146     errno = EAFNOSUPPORT;
147     return -1;
148 #endif
149 }
150
151
152 static int net_SetMcastOut (vlc_object_t *p_this, int fd, int family,
153                             const char *iface, const char *addr)
154 {
155     if (iface != NULL)
156     {
157         int scope = if_nametoindex (iface);
158         if (scope == 0)
159         {
160             msg_Err (p_this, "%s: invalid interface for multicast", iface);
161             return -1;
162         }
163
164         if (net_SetMcastOutIface (fd, family, scope) == 0)
165             return 0;
166
167         msg_Err (p_this, "%s: %s", iface, net_strerror (net_errno));
168     }
169
170     if (addr != NULL)
171     {
172         if (family == AF_INET)
173         {
174             struct in_addr ipv4;
175             if (inet_pton (AF_INET, addr, &ipv4) <= 0)
176             {
177                 msg_Err (p_this, "%s: invalid IPv4 address for multicast",
178                          addr);
179                 return -1;
180             }
181
182             if (net_SetMcastOutIPv4 (fd, ipv4) == 0)
183                 return 0;
184
185             msg_Err (p_this, "%s: %s", addr, net_strerror (net_errno));
186         }
187     }
188
189     return -1;
190 }
191
192
193 int net_Subscribe (vlc_object_t *obj, int fd, const struct sockaddr *addr,
194                    socklen_t addrlen)
195 {
196     switch (addr->sa_family)
197     {
198 #ifdef IP_ADD_MEMBERSHIP
199         case AF_INET:
200         {
201             const struct sockaddr_in *v4 = (const struct sockaddr_in *)addr;
202             if (addrlen < sizeof (*v4))
203                 return -1;
204
205             struct ip_mreq imr;
206             memset (&imr, 0, sizeof (imr));
207             memcpy (&imr.imr_multiaddr, &v4->sin_addr, 4);
208
209             /* FIXME: should use a different option for in and out */
210             char *iif = config_GetPsz (obj, "miface-addr");
211             if (iif != NULL)
212             {
213                 if ((iif[0] != '\0') &&
214                     (inet_pton (AF_INET, iif, &imr.imr_interface) <= 0))
215                 {
216                     msg_Err (obj, "invalid multicast interface address %s",
217                              iif);
218                     free (iif);
219                     return -1;
220                 }
221                 free (iif);
222             }
223
224             msg_Dbg (obj, "IP_ADD_MEMBERSHIP multicast request");
225
226             if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr,
227                             sizeof (imr)))
228             {
229                 msg_Err (obj, "cannot join IPv4 multicast group (%s)",
230                          net_strerror (net_errno));
231                 return -1;
232             }
233             return 0;
234         }
235 #endif
236
237 #ifdef IPV6_JOIN_GROUP
238         case AF_INET6:
239         {
240             const struct sockaddr_in6 *v6 = (const struct sockaddr_in6 *)addr;
241             if (addrlen < sizeof (*v6))
242                 return -1;
243
244             struct ipv6_mreq imr;
245             memset (&imr, 0, sizeof (imr));
246             imr.ipv6mr_interface = v6->sin6_scope_id;
247             memcpy (&imr.ipv6mr_multiaddr, &v6->sin6_addr, 16);
248
249             if (setsockopt (fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr,
250                             sizeof (imr)))
251             {
252                 msg_Err (obj, "cannot join IPv6 multicast group (%s)",
253                          net_strerror (net_errno));
254                 return -1;
255             }
256
257             return 0;
258         }
259 #endif
260     }
261
262     msg_Err (obj, "Multicast not supported");
263     return -1;
264 }
265
266
267 int net_SetDSCP( int fd, uint8_t dscp )
268 {
269     struct sockaddr_storage addr;
270     if( getsockname( fd, (struct sockaddr *)&addr, &(socklen_t){ sizeof (addr) }) )
271         return -1;
272
273     int level, cmd;
274
275     switch( addr.ss_family )
276     {
277 #ifdef IPV6_TCLASS
278         case AF_INET6:
279             level = SOL_IPV6;
280             cmd = IPV6_TCLASS;
281             break;
282 #endif
283
284         case AF_INET:
285             level = SOL_IP;
286             cmd = IP_TOS;
287             break;
288
289         default:
290 #ifdef ENOPROTOOPT
291             errno = ENOPROTOOPT;
292 #endif
293             return -1;
294     }
295
296     return setsockopt( fd, level, cmd, &(int){ dscp }, sizeof (int));
297 }
298
299
300 /*****************************************************************************
301  * __net_ConnectUDP:
302  *****************************************************************************
303  * Open a UDP socket to send data to a defined destination, with an optional
304  * hop limit.
305  *****************************************************************************/
306 int __net_ConnectUDP( vlc_object_t *p_this, const char *psz_host, int i_port,
307                       int i_hlim )
308 {
309     struct addrinfo hints, *res, *ptr;
310     int             i_val, i_handle = -1;
311     vlc_bool_t      b_unreach = VLC_FALSE;
312
313     if( i_port == 0 )
314         i_port = 1234; /* historical VLC thing */
315
316     if( i_hlim < 1 )
317         i_hlim = var_CreateGetInteger( p_this, "ttl" );
318
319     memset( &hints, 0, sizeof( hints ) );
320     hints.ai_socktype = SOCK_DGRAM;
321
322     msg_Dbg( p_this, "net: connecting to %s port %d", psz_host, i_port );
323
324     i_val = vlc_getaddrinfo( p_this, psz_host, i_port, &hints, &res );
325     if( i_val )
326     {
327         msg_Err( p_this, "cannot resolve %s port %d : %s", psz_host, i_port,
328                  vlc_gai_strerror( i_val ) );
329         return -1;
330     }
331
332     for( ptr = res; ptr != NULL; ptr = ptr->ai_next )
333     {
334         char *str;
335         int fd = net_Socket (p_this, ptr->ai_family, ptr->ai_socktype,
336                              ptr->ai_protocol);
337         if (fd == -1)
338             continue;
339
340 #if !defined( SYS_BEOS )
341         /* Increase the receive buffer size to 1/2MB (8Mb/s during 1/2s)
342         * to avoid packet loss caused by scheduling problems */
343         setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &(int){ 0x80000 }, sizeof (int));
344         setsockopt (fd, SOL_SOCKET, SO_SNDBUF, &(int){ 0x80000 }, sizeof (int));
345
346         /* Allow broadcast sending */
347         setsockopt (fd, SOL_SOCKET, SO_BROADCAST, &(int){ 1 }, sizeof (int));
348 #endif
349
350         if( i_hlim > 0 )
351             net_SetMcastHopLimit( p_this, fd, ptr->ai_family, i_hlim );
352
353         str = var_CreateGetString (p_this, "miface");
354         if (str != NULL)
355         {
356             net_SetMcastOut (p_this, fd, ptr->ai_family, str, NULL);
357             free (str);
358         }
359
360         str = var_CreateGetString (p_this, "miface-addr");
361         if (str != NULL)
362         {
363             net_SetMcastOut (p_this, fd, ptr->ai_family, NULL, str);
364             free (str);
365         }
366
367         net_SetDSCP (fd, var_CreateGetInteger (p_this, "dscp"));
368
369         if( connect( fd, ptr->ai_addr, ptr->ai_addrlen ) == 0 )
370         {
371             /* success */
372             i_handle = fd;
373             break;
374         }
375
376 #if defined( WIN32 ) || defined( UNDER_CE )
377         if( WSAGetLastError () == WSAENETUNREACH )
378 #else
379         if( errno == ENETUNREACH )
380 #endif
381             b_unreach = VLC_TRUE;
382         else
383         {
384             msg_Warn( p_this, "%s port %d : %s", psz_host, i_port,
385                       strerror( errno ) );
386             net_Close( fd );
387             continue;
388         }
389     }
390
391     vlc_freeaddrinfo( res );
392
393     if( i_handle == -1 )
394     {
395         if( b_unreach )
396             msg_Err( p_this, "Host %s port %d is unreachable", psz_host,
397                      i_port );
398         return -1;
399     }
400
401     return i_handle;
402 }
403
404
405 static inline
406 int *__net_ListenUDP (vlc_object_t *obj, const char *host, int port)
407 {
408     int *fdv = net_Listen (obj, host, port, 0, SOCK_DGRAM, IPPROTO_UDP);
409     if (fdv == NULL)
410         return NULL;
411
412     /* FIXME: handle multicast subscription */
413     return fdv;
414 }
415
416
417 int net_ListenUDP1 (vlc_object_t *obj, const char *host, int port)
418 {
419     int *fdv = __net_ListenUDP (obj, host, port);
420     if (fdv == NULL)
421         return -1;
422
423     for (unsigned i = 1; fdv[i] != -1; i++)
424     {
425         msg_Warn (obj, "A socket has been dropped!");
426         net_Close (fdv[i]);
427     }
428
429     int fd = fdv[0];
430     assert (fd != -1);
431
432     free (fdv);
433     return fd;
434 }
435
436
437 /*****************************************************************************
438  * __net_OpenUDP:
439  *****************************************************************************
440  * Open a UDP connection and return a handle
441  *****************************************************************************/
442 int __net_OpenUDP( vlc_object_t *p_this, const char *psz_bind, int i_bind,
443                    const char *psz_server, int i_server )
444 {
445     vlc_value_t      v4, v6;
446     void            *private;
447     network_socket_t sock;
448     module_t         *p_network = NULL;
449
450     if (((psz_bind == NULL) || (psz_bind[0] == '\0')) && (i_bind == 0))
451         msg_Warn (p_this,
452                   "Obsolete net_OpenUDP with no local endpoint; "
453                   "Use net_ConnectUDP instead");
454
455 #if 0
456     if (((psz_server == NULL) || (psz_server[0] == '\0')) && (i_server == 0))
457         msg_Warn (p_this,
458                   "Obsolete net_OpenUDP with no remote endpoint; "
459                   "Use net_ListenUDP instead");
460 #endif
461
462     if( psz_server == NULL ) psz_server = "";
463     if( psz_bind == NULL ) psz_bind = "";
464
465     /* Prepare the network_socket_t structure */
466     sock.psz_bind_addr   = psz_bind;
467     sock.i_bind_port     = i_bind;
468     sock.psz_server_addr = psz_server;
469     sock.i_server_port   = i_server;
470     sock.i_ttl           = 0;
471     sock.v6only          = 0;
472     sock.i_handle        = -1;
473
474     msg_Dbg( p_this, "net: connecting to '[%s]:%d@[%s]:%d'",
475              psz_server, i_server, psz_bind, i_bind );
476
477     /* Check if we have force ipv4 or ipv6 */
478     var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
479     var_Get( p_this, "ipv4", &v4 );
480     var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
481     var_Get( p_this, "ipv6", &v6 );
482
483     if( !v4.b_bool )
484     {
485         if( v6.b_bool )
486             sock.v6only = 1;
487
488         /* try IPv6 first (unless IPv4 forced) */
489         private = p_this->p_private;
490         p_this->p_private = (void*)&sock;
491         p_network = module_Need( p_this, "network", "ipv6", VLC_TRUE );
492
493         if( p_network != NULL )
494             module_Unneed( p_this, p_network );
495
496         p_this->p_private = private;
497
498         /*
499          * Check if the IP stack can receive IPv4 packets on IPv6 sockets.
500          * If yes, then it is better to use the IPv6 socket.
501          * Otherwise, if we also get an IPv4, we have to choose, so we use
502          * IPv4 only.
503          */
504         if( ( sock.i_handle != -1 ) && ( ( sock.v6only == 0 ) || v6.b_bool ) )
505             return sock.i_handle;
506     }
507
508     if( !v6.b_bool )
509     {
510         int fd6 = sock.i_handle;
511
512         /* also try IPv4 (unless IPv6 forced) */
513         private = p_this->p_private;
514         p_this->p_private = (void*)&sock;
515         p_network = module_Need( p_this, "network", "ipv4", VLC_TRUE );
516
517         if( p_network != NULL )
518             module_Unneed( p_this, p_network );
519
520         p_this->p_private = private;
521
522         if( fd6 != -1 )
523         {
524             if( sock.i_handle != -1 )
525             {
526                 msg_Warn( p_this, "net: lame IPv6/IPv4 dual-stack present, "
527                                   "using only IPv4." );
528                 net_Close( fd6 );
529             }
530             else
531                 sock.i_handle = fd6;
532         }
533     }
534
535     if( sock.i_handle == -1 )
536         msg_Dbg( p_this, "net: connection to '[%s]:%d@[%s]:%d' failed",
537                 psz_server, i_server, psz_bind, i_bind );
538
539     return sock.i_handle;
540 }