]> git.sesse.net Git - vlc/blob - src/network/udp.c
Fix unitialized interface for old-style IPv4 joins
[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 <vlc_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 /*
73  * XXX: I am too lazy to put all these dual functions in “next generation”
74  * network plugins.
75  */
76
77 static int net_SetMcastHopLimit( vlc_object_t *p_this,
78                                  int fd, int family, int hlim )
79 {
80     int proto, cmd;
81
82     /* There is some confusion in the world whether IP_MULTICAST_TTL 
83      * takes a byte or an int as an argument.
84      * BSD seems to indicate byte so we are going with that and use
85      * int as a fallback to be safe */
86     switch( family )
87     {
88 #ifdef IP_MULTICAST_TTL
89         case AF_INET:
90             proto = SOL_IP;
91             cmd = IP_MULTICAST_TTL;
92             break;
93 #endif
94
95 #ifdef IPV6_MULTICAST_HOPS
96         case AF_INET6:
97             proto = SOL_IPV6;
98             cmd = IPV6_MULTICAST_HOPS;
99             break;
100 #endif
101
102         default:
103             msg_Warn( p_this, "%s", strerror( EAFNOSUPPORT ) );
104             return VLC_EGENERIC;
105     }
106
107     if( setsockopt( fd, proto, cmd, &hlim, sizeof( hlim ) ) < 0 )
108     {
109         /* BSD compatibility */
110         unsigned char buf;
111
112         buf = (unsigned char)(( hlim > 255 ) ? 255 : hlim);
113         if( setsockopt( fd, proto, cmd, &buf, sizeof( buf ) ) )
114             return VLC_EGENERIC;
115     }
116
117     return VLC_SUCCESS;
118 }
119
120
121 static int net_SetMcastOutIface (int fd, int family, int scope)
122 {
123     switch (family)
124     {
125 #ifdef IPV6_MULTICAST_IF
126         case AF_INET6:
127             return setsockopt (fd, SOL_IPV6, IPV6_MULTICAST_IF,
128                                &scope, sizeof (scope));
129 #endif
130
131 #ifdef __linux__
132         case AF_INET:
133         {
134             struct ip_mreqn req = { .imr_ifindex = scope };
135
136             return setsockopt (fd, SOL_IP, IP_MULTICAST_IF, &req,
137                                sizeof (req));
138         }
139 #endif
140     }
141
142     errno = EAFNOSUPPORT;
143     return -1;
144 }
145
146
147 static inline int net_SetMcastOutIPv4 (int fd, struct in_addr ipv4)
148 {
149 #ifdef IP_MULTICAST_IF
150     return setsockopt( fd, SOL_IP, IP_MULTICAST_IF, &ipv4, sizeof (ipv4));
151 #else
152     errno = EAFNOSUPPORT;
153     return -1;
154 #endif
155 }
156
157
158 static int net_SetMcastOut (vlc_object_t *p_this, int fd, int family,
159                             const char *iface, const char *addr)
160 {
161     if (iface != NULL)
162     {
163         int scope = if_nametoindex (iface);
164         if (scope == 0)
165         {
166             msg_Err (p_this, "invalid multicast interface: %s", iface);
167             return -1;
168         }
169
170         if (net_SetMcastOutIface (fd, family, scope) == 0)
171             return 0;
172
173         msg_Err (p_this, "%s: %s", iface, net_strerror (net_errno));
174     }
175
176     if (addr != NULL)
177     {
178         if (family == AF_INET)
179         {
180             struct in_addr ipv4;
181             if (inet_pton (AF_INET, addr, &ipv4) <= 0)
182             {
183                 msg_Err (p_this, "invalid IPv4 address for multicast: %s",
184                          addr);
185                 return -1;
186             }
187
188             if (net_SetMcastOutIPv4 (fd, ipv4) == 0)
189                 return 0;
190
191             msg_Err (p_this, "%s: %s", addr, net_strerror (net_errno));
192         }
193     }
194
195     return -1;
196 }
197
198
199 /**
200  * Old-style any-source multicast join.
201  * In use on Windows XP/2003 and older.
202  */
203 static int
204 net_IPv4Join (vlc_object_t *obj, int fd,
205               const struct sockaddr_in *src, const struct sockaddr_in *grp)
206 {
207 #ifdef IP_ADD_MEMBERSHIP
208     union
209     {
210         struct ip_mreq gr4;
211 # ifdef IP_ADD_SOURCE_MEMBERSHIP
212         struct ip_mreq_source gsr4;
213 # endif
214     } opt;
215     int cmd;
216     struct in_addr id = { .s_addr = INADDR_ANY };
217     socklen_t optlen;
218
219     /* Multicast interface IPv4 address */
220     char *iface = var_CreateGetString (obj, "miface-addr");
221     if (iface != NULL)
222     {
223         if ((*iface)
224          && (inet_pton (AF_INET, iface, &id) <= 0))
225         {
226             msg_Err (obj, "invalid multicast interface address %s", iface);
227             free (iface);
228             goto error;
229         }
230     }
231
232     memset (&opt, 0, sizeof (opt));
233     if (src != NULL)
234     {
235 # ifdef IP_ADD_SOURCE_MEMBERSHIP
236         cmd = IP_ADD_SOURCE_MEMBERSHIP;
237         opt.gsr4.imr_multiaddr = grp->sin_addr;
238         opt.gsr4.imr_sourceaddr = src->sin_addr;
239         opt.gsr4.imr_interface = id;
240         optlen = sizeof (opt.gsr4);
241 # else
242         errno = ENOSYS;
243         goto error;
244 # endif
245     }
246     else
247     {
248         cmd = IP_ADD_MEMBERSHIP;
249         opt.gr4.imr_multiaddr = grp->sin_addr;
250         opt.gr4.imr_interface = id;
251         optlen = sizeof (opt.gr4);
252     }
253
254     msg_Dbg (obj, "IP_ADD_%sMEMBERSHIP multicast request",
255              (src != NULL) ? "SOURCE_" : "");
256
257     if (setsockopt (fd, SOL_IP, cmd, &opt, optlen) == 0)
258         return 0;
259
260 error:
261 #endif
262
263     msg_Err (obj, "cannot join IPv4 multicast group (%s)",
264              net_strerror (net_errno));
265     return -1;
266 }
267
268
269 static int
270 net_IPv6Join (vlc_object_t *obj, int fd, const struct sockaddr_in6 *src)
271 {
272 #ifdef IPV6_JOIN_GROUP
273     struct ipv6_mreq gr6;
274     memset (&gr6, 0, sizeof (gr6));
275     gr6.ipv6mr_interface = src->sin6_scope_id;
276     memcpy (&gr6.ipv6mr_multiaddr, &src->sin6_addr, 16);
277
278     msg_Dbg (obj, "IPV6_JOIN_GROUP multicast request");
279
280     if (!setsockopt (fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &gr6, sizeof (gr6)))
281         return 0;
282 #else
283     errno = ENOSYS;
284 #endif
285
286     msg_Err (obj, "cannot join IPv6 any-source multicast group (%s)",
287              net_strerror (net_errno));
288     return -1;
289 }
290
291
292 #if 0
293 #if defined (WIN32) && !defined (MCAST_JOIN_SOURCE_GROUP)
294 /*
295  * I hate manual definitions: Error-prone. Portability hell.
296  * Developers shall use UP-TO-DATE compilers. Full point.
297  * If you remove the warning, you remove the whole ifndef.
298  */
299 #  warning Your C headers are out-of-date. Please update.
300
301 /* No, I won't guess the layout of these two.
302  * No, I don't want another socket protection level type-of obnoxious bug. */
303 #  error Hmmm? This needs fixing.
304 #  define MCAST_JOIN_GROUP XXX
305 struct group_req
306 {
307     uint32_t gr_interface; FIXME
308     struct sockaddr_storage gr_group; FIXME
309 };
310
311
312 #  define MCAST_JOIN_SOURCE_GROUP 45 /* from <ws2ipdef.h> */
313 struct group_source_req
314 {
315     uint32_t gsr_interface;
316     struct sockaddr_storage gsr_group;
317     struct sockaddr_storage gsr_source;
318 };
319 #endif
320 #endif
321
322 /**
323  * IP-agnostic multicast join,
324  * with fallback to old APIs, and fallback from SSM to ASM.
325  */
326 static int
327 net_SourceSubscribe (vlc_object_t *obj, int fd,
328                      const struct sockaddr *src, socklen_t srclen,
329                      const struct sockaddr *grp, socklen_t grplen)
330 {
331     int level, iid = 0;
332
333     char *iface = var_CreateGetString (obj, "miface");
334     if (iface != NULL)
335     {
336         if (*iface)
337         {
338             iid = if_nametoindex (iface);
339             if (iid == 0)
340             {
341                 msg_Err (obj, "invalid multicast interface: %s", iface);
342                 free (iface);
343                 return -1;
344             }
345         }
346         free (iface);
347     }
348
349     switch (grp->sa_family)
350     {
351 #ifdef AF_INET6
352         case AF_INET6:
353             level = SOL_IPV6;
354             if ((src != NULL)
355              && memcmp (&((const struct sockaddr_in6 *)src)->sin6_addr,
356                         &in6addr_any, sizeof (in6addr_any)) == 0)
357                 src = NULL;
358
359             if (((const struct sockaddr_in6 *)src)->sin6_scope_id)
360                 iid = ((const struct sockaddr_in6 *)src)->sin6_scope_id;
361             break;
362 #endif
363
364         case AF_INET:
365             level = SOL_IP;
366             if ((src != NULL)
367              && ((const struct sockaddr_in *)src)->sin_addr.s_addr
368                   == INADDR_ANY)
369                 src = NULL;
370             break;
371
372         default:
373             errno = EAFNOSUPPORT;
374             return -1;
375     }
376
377     /* Agnostic ASM/SSM multicast join */
378 #ifdef MCAST_JOIN_SOURCE_GROUP
379     union
380     {
381         struct group_req gr;
382         struct group_source_req gsr;
383     } opt;
384     socklen_t optlen;
385
386     memset (&opt, 0, sizeof (opt));
387
388     if (src != NULL)
389     {
390         if ((grplen > sizeof (opt.gsr.gsr_group))
391          || (srclen > sizeof (opt.gsr.gsr_source)))
392             return -1;
393
394         opt.gsr.gsr_interface = iid;
395         memcpy (&opt.gsr.gsr_source, src, srclen);
396         memcpy (&opt.gsr.gsr_group,  grp, grplen);
397         optlen = sizeof (opt.gsr);
398     }
399     else
400     {
401         if (grplen > sizeof (opt.gr.gr_group))
402             return -1;
403
404         opt.gr.gr_interface = iid;
405         memcpy (&opt.gr.gr_group, grp, grplen);
406         optlen = sizeof (opt.gr);
407     }
408
409     msg_Dbg (obj, "Multicast %sgroup join request", src ? "source " : "");
410
411     if (setsockopt (fd, level, 
412                     src ? MCAST_JOIN_SOURCE_GROUP : MCAST_JOIN_GROUP,
413                     (void *)&opt, optlen) == 0)
414         return 0;
415 #endif
416
417     /* Fallback to IPv-specific APIs */
418     if ((src != NULL) && (src->sa_family != grp->sa_family))
419         return -1;
420
421     switch (grp->sa_family)
422     {
423         case AF_INET:
424             if ((grplen < sizeof (struct sockaddr_in))
425              || ((src != NULL) && (srclen < sizeof (struct sockaddr_in))))
426                 return -1;
427
428             if (net_IPv4Join (obj, fd, (const struct sockaddr_in *)src,
429                               (const struct sockaddr_in *)grp) == 0)
430                 return 0;
431             break;
432
433 #ifdef AF_INET6
434         case AF_INET6:
435             if ((grplen < sizeof (struct sockaddr_in6))
436              || ((src != NULL) && (srclen < sizeof (struct sockaddr_in6))))
437                 return -1;
438
439             /* We don't provide IPv6-specific SSM at the moment.
440              * It seems all the OSes with IPv6 SSM have the new API anyway. */
441
442             if (net_IPv6Join (obj, fd, (const struct sockaddr_in6 *)grp) == 0)
443                 return 0;
444             break;
445 #endif
446     }
447
448     msg_Err (obj, "Multicast group join error (%s)",
449              net_strerror (net_errno));
450
451     if (src != NULL)
452     {
453         msg_Warn (obj, "Trying ASM instead of SSM...");
454         return net_Subscribe (obj, fd, grp, grplen);
455     }
456
457     msg_Err (obj, "Multicast not supported");
458     return -1;
459 }
460
461
462 int net_Subscribe (vlc_object_t *obj, int fd,
463                    const struct sockaddr *addr, socklen_t addrlen)
464 {
465     return net_SourceSubscribe (obj, fd, NULL, 0, addr, addrlen);
466 }
467
468
469 int net_SetDSCP( int fd, uint8_t dscp )
470 {
471     struct sockaddr_storage addr;
472     if( getsockname( fd, (struct sockaddr *)&addr, &(socklen_t){ sizeof (addr) }) )
473         return -1;
474
475     int level, cmd;
476
477     switch( addr.ss_family )
478     {
479 #ifdef IPV6_TCLASS
480         case AF_INET6:
481             level = SOL_IPV6;
482             cmd = IPV6_TCLASS;
483             break;
484 #endif
485
486         case AF_INET:
487             level = SOL_IP;
488             cmd = IP_TOS;
489             break;
490
491         default:
492 #ifdef ENOPROTOOPT
493             errno = ENOPROTOOPT;
494 #endif
495             return -1;
496     }
497
498     return setsockopt( fd, level, cmd, &(int){ dscp }, sizeof (int));
499 }
500
501
502 /*****************************************************************************
503  * __net_ConnectUDP:
504  *****************************************************************************
505  * Open a UDP socket to send data to a defined destination, with an optional
506  * hop limit.
507  *****************************************************************************/
508 int __net_ConnectUDP( vlc_object_t *p_this, const char *psz_host, int i_port,
509                       int i_hlim )
510 {
511     struct addrinfo hints, *res, *ptr;
512     int             i_val, i_handle = -1;
513     vlc_bool_t      b_unreach = VLC_FALSE;
514
515     if( i_port == 0 )
516         i_port = 1234; /* historical VLC thing */
517
518     if( i_hlim < 1 )
519         i_hlim = var_CreateGetInteger( p_this, "ttl" );
520
521     memset( &hints, 0, sizeof( hints ) );
522     hints.ai_socktype = SOCK_DGRAM;
523
524     msg_Dbg( p_this, "net: connecting to %s port %d", psz_host, i_port );
525
526     i_val = vlc_getaddrinfo( p_this, psz_host, i_port, &hints, &res );
527     if( i_val )
528     {
529         msg_Err( p_this, "cannot resolve %s port %d : %s", psz_host, i_port,
530                  vlc_gai_strerror( i_val ) );
531         return -1;
532     }
533
534     for( ptr = res; ptr != NULL; ptr = ptr->ai_next )
535     {
536         char *str;
537         int fd = net_Socket (p_this, ptr->ai_family, ptr->ai_socktype,
538                              ptr->ai_protocol);
539         if (fd == -1)
540             continue;
541
542 #if !defined( SYS_BEOS )
543         /* Increase the receive buffer size to 1/2MB (8Mb/s during 1/2s)
544         * to avoid packet loss caused by scheduling problems */
545         setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &(int){ 0x80000 }, sizeof (int));
546         setsockopt (fd, SOL_SOCKET, SO_SNDBUF, &(int){ 0x80000 }, sizeof (int));
547
548         /* Allow broadcast sending */
549         setsockopt (fd, SOL_SOCKET, SO_BROADCAST, &(int){ 1 }, sizeof (int));
550 #endif
551
552         if( i_hlim > 0 )
553             net_SetMcastHopLimit( p_this, fd, ptr->ai_family, i_hlim );
554
555         str = var_CreateGetString (p_this, "miface");
556         if (str != NULL)
557         {
558             if (*str)
559                 net_SetMcastOut (p_this, fd, ptr->ai_family, str, NULL);
560             free (str);
561         }
562
563         str = var_CreateGetString (p_this, "miface-addr");
564         if (str != NULL)
565         {
566             if (*str)
567                 net_SetMcastOut (p_this, fd, ptr->ai_family, NULL, str);
568             free (str);
569         }
570
571         net_SetDSCP (fd, var_CreateGetInteger (p_this, "dscp"));
572
573         if( connect( fd, ptr->ai_addr, ptr->ai_addrlen ) == 0 )
574         {
575             /* success */
576             i_handle = fd;
577             break;
578         }
579
580 #if defined( WIN32 ) || defined( UNDER_CE )
581         if( WSAGetLastError () == WSAENETUNREACH )
582 #else
583         if( errno == ENETUNREACH )
584 #endif
585             b_unreach = VLC_TRUE;
586         else
587         {
588             msg_Warn( p_this, "%s port %d : %s", psz_host, i_port,
589                       strerror( errno ) );
590             net_Close( fd );
591             continue;
592         }
593     }
594
595     vlc_freeaddrinfo( res );
596
597     if( i_handle == -1 )
598     {
599         if( b_unreach )
600             msg_Err( p_this, "Host %s port %d is unreachable", psz_host,
601                      i_port );
602         return -1;
603     }
604
605     return i_handle;
606 }
607
608
609 /*****************************************************************************
610  * __net_OpenUDP:
611  *****************************************************************************
612  * Open a UDP connection and return a handle
613  *****************************************************************************/
614 int __net_OpenUDP( vlc_object_t *obj, const char *psz_bind, int i_bind,
615                    const char *psz_server, int i_server )
616 {
617     struct addrinfo hints, *loc, *rem;
618     int val;
619
620     msg_Dbg( obj, "net: connecting to '[%s]:%d@[%s]:%d'",
621              psz_server, i_server, psz_bind, i_bind );
622
623     memset (&hints, 0, sizeof (hints));
624     hints.ai_socktype = SOCK_DGRAM;
625     hints.ai_protocol = IPPROTO_UDP;
626     hints.ai_flags = AI_PASSIVE;
627
628     val = vlc_getaddrinfo (obj, psz_server, i_server, &hints, &rem);
629     if (val)
630     {
631         msg_Err (obj, "cannot resolve %s port %d : %s", psz_bind, i_bind,
632                  vlc_gai_strerror (val));
633         return -1;
634     }
635
636     val = vlc_getaddrinfo (obj, psz_bind, i_bind, &hints, &loc);
637     if (val)
638     {
639         msg_Err (obj, "cannot resolve %s port %d : %s", psz_bind, i_bind,
640                  vlc_gai_strerror (val));
641         vlc_freeaddrinfo (rem);
642         return -1;
643     }
644
645     for (struct addrinfo *ptr = loc; ptr != NULL; ptr = ptr->ai_next)
646     {
647         int fd = net_Socket (obj, ptr->ai_family, ptr->ai_socktype,
648                              ptr->ai_protocol);
649         if (fd == -1)
650             continue; // usually, address family not supported
651
652 #ifdef SO_REUSEPORT
653         setsockopt (fd, SOL_SOCKET, SO_REUSEPORT, &(int){ 1 }, sizeof (int));
654 #endif
655
656 #ifdef SO_RCVBUF
657         /* Increase the receive buffer size to 1/2MB (8Mb/s during 1/2s)
658          * to avoid packet loss caused in case of scheduling hiccups */
659         setsockopt (fd, SOL_SOCKET, SO_RCVBUF,
660                     (void *)&(int){ 0x80000 }, sizeof (int));
661         setsockopt (fd, SOL_SOCKET, SO_SNDBUF,
662                     (void *)&(int){ 0x80000 }, sizeof (int));
663 #endif
664
665 #if defined (WIN32) || defined (UNDER_CE)
666         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
667          && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
668         {
669             // This works for IPv4 too - don't worry!
670             struct sockaddr_in6 dumb =
671             {
672                 .sin6_family = ptr->ai_addr->sa_family,
673                 .sin6_port =  ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
674             };
675
676             bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
677         }
678         else
679 #endif
680         if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
681         {
682             net_Close (fd);
683             continue;
684         }
685
686         struct addrinfo *ptr2;
687         for (ptr2 = rem; ptr2 != NULL; ptr2 = ptr2->ai_next)
688         {
689             if ((ptr2->ai_family != ptr->ai_family)
690              || (ptr2->ai_socktype != ptr->ai_socktype)
691              || (ptr2->ai_protocol != ptr->ai_protocol))
692                 continue;
693
694             if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen))
695             {
696                 if (net_SourceSubscribe (obj, fd,
697                                          ptr2->ai_addr, ptr2->ai_addrlen,
698                                          ptr->ai_addr, ptr->ai_addrlen) == 0)
699                     break;
700             }
701             else
702             {
703                 if (connect (fd, ptr2->ai_addr, ptr2->ai_addrlen) == 0)
704                     break;
705             }
706         }
707
708         if (ptr2 == NULL)
709         {
710             msg_Err (obj, "cannot connect to %s port %d: %s",
711                      psz_server, i_server, net_strerror (net_errno));
712             close (fd);
713             continue;
714         }
715
716         return fd;
717     }
718
719     return -1;
720 }