]> git.sesse.net Git - vlc/blob - src/network/udp.c
UDP-Lite access
[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 (((const struct sockaddr_in6 *)grp)->sin6_scope_id)
355                 iid = ((const struct sockaddr_in6 *)grp)->sin6_scope_id;
356             break;
357 #endif
358
359         case AF_INET:
360             level = SOL_IP;
361             break;
362
363         default:
364             errno = EAFNOSUPPORT;
365             return -1;
366     }
367
368     if (src != NULL)
369         switch (src->sa_family)
370         {
371 #ifdef AF_INET6
372             case AF_INET6:
373                 if (memcmp (&((const struct sockaddr_in6 *)src)->sin6_addr,
374                             &in6addr_any, sizeof (in6addr_any)) == 0)
375                     src = NULL;
376             break;
377 #endif
378
379             case AF_INET:
380                 if (((const struct sockaddr_in *)src)->sin_addr.s_addr
381                      == INADDR_ANY)
382                     src = NULL;
383                 break;
384         }
385
386
387     /* Agnostic ASM/SSM multicast join */
388 #ifdef MCAST_JOIN_SOURCE_GROUP
389     union
390     {
391         struct group_req gr;
392         struct group_source_req gsr;
393     } opt;
394     socklen_t optlen;
395
396     memset (&opt, 0, sizeof (opt));
397
398     if (src != NULL)
399     {
400         if ((grplen > sizeof (opt.gsr.gsr_group))
401          || (srclen > sizeof (opt.gsr.gsr_source)))
402             return -1;
403
404         opt.gsr.gsr_interface = iid;
405         memcpy (&opt.gsr.gsr_source, src, srclen);
406         memcpy (&opt.gsr.gsr_group,  grp, grplen);
407         optlen = sizeof (opt.gsr);
408     }
409     else
410     {
411         if (grplen > sizeof (opt.gr.gr_group))
412             return -1;
413
414         opt.gr.gr_interface = iid;
415         memcpy (&opt.gr.gr_group, grp, grplen);
416         optlen = sizeof (opt.gr);
417     }
418
419     msg_Dbg (obj, "Multicast %sgroup join request", src ? "source " : "");
420
421     if (setsockopt (fd, level, 
422                     src ? MCAST_JOIN_SOURCE_GROUP : MCAST_JOIN_GROUP,
423                     (void *)&opt, optlen) == 0)
424         return 0;
425 #endif
426
427     /* Fallback to IPv-specific APIs */
428     if ((src != NULL) && (src->sa_family != grp->sa_family))
429         return -1;
430
431     switch (grp->sa_family)
432     {
433         case AF_INET:
434             if ((grplen < sizeof (struct sockaddr_in))
435              || ((src != NULL) && (srclen < sizeof (struct sockaddr_in))))
436                 return -1;
437
438             if (net_IPv4Join (obj, fd, (const struct sockaddr_in *)src,
439                               (const struct sockaddr_in *)grp) == 0)
440                 return 0;
441             break;
442
443 #ifdef AF_INET6
444         case AF_INET6:
445             if ((grplen < sizeof (struct sockaddr_in6))
446              || ((src != NULL) && (srclen < sizeof (struct sockaddr_in6))))
447                 return -1;
448
449             /* IPv6-specific SSM API does not exist. So if we're here
450              * it means IPv6 SSM is not supported on this OS and we
451              * directly fallback to ASM */
452
453             if (net_IPv6Join (obj, fd, (const struct sockaddr_in6 *)grp) == 0)
454                 return 0;
455             break;
456 #endif
457     }
458
459     msg_Err (obj, "Multicast group join error (%s)",
460              net_strerror (net_errno));
461
462     if (src != NULL)
463     {
464         msg_Warn (obj, "Trying ASM instead of SSM...");
465         return net_Subscribe (obj, fd, grp, grplen);
466     }
467
468     msg_Err (obj, "Multicast not supported");
469     return -1;
470 }
471
472
473 int net_Subscribe (vlc_object_t *obj, int fd,
474                    const struct sockaddr *addr, socklen_t addrlen)
475 {
476     return net_SourceSubscribe (obj, fd, NULL, 0, addr, addrlen);
477 }
478
479
480 int net_SetDSCP( int fd, uint8_t dscp )
481 {
482     struct sockaddr_storage addr;
483     if( getsockname( fd, (struct sockaddr *)&addr, &(socklen_t){ sizeof (addr) }) )
484         return -1;
485
486     int level, cmd;
487
488     switch( addr.ss_family )
489     {
490 #ifdef IPV6_TCLASS
491         case AF_INET6:
492             level = SOL_IPV6;
493             cmd = IPV6_TCLASS;
494             break;
495 #endif
496
497         case AF_INET:
498             level = SOL_IP;
499             cmd = IP_TOS;
500             break;
501
502         default:
503 #ifdef ENOPROTOOPT
504             errno = ENOPROTOOPT;
505 #endif
506             return -1;
507     }
508
509     return setsockopt( fd, level, cmd, &(int){ dscp }, sizeof (int));
510 }
511
512
513 /*****************************************************************************
514  * __net_ConnectUDP:
515  *****************************************************************************
516  * Open a UDP socket to send data to a defined destination, with an optional
517  * hop limit.
518  *****************************************************************************/
519 int __net_ConnectUDP( vlc_object_t *p_this, const char *psz_host, int i_port,
520                       int i_hlim )
521 {
522     struct addrinfo hints, *res, *ptr;
523     int             i_val, i_handle = -1;
524     vlc_bool_t      b_unreach = VLC_FALSE;
525
526     if( i_port == 0 )
527         i_port = 1234; /* historical VLC thing */
528
529     if( i_hlim < 1 )
530         i_hlim = var_CreateGetInteger( p_this, "ttl" );
531
532     memset( &hints, 0, sizeof( hints ) );
533     hints.ai_socktype = SOCK_DGRAM;
534
535     msg_Dbg( p_this, "net: connecting to %s port %d", psz_host, i_port );
536
537     i_val = vlc_getaddrinfo( p_this, psz_host, i_port, &hints, &res );
538     if( i_val )
539     {
540         msg_Err( p_this, "cannot resolve %s port %d : %s", psz_host, i_port,
541                  vlc_gai_strerror( i_val ) );
542         return -1;
543     }
544
545     for( ptr = res; ptr != NULL; ptr = ptr->ai_next )
546     {
547         char *str;
548         int fd = net_Socket (p_this, ptr->ai_family, ptr->ai_socktype,
549                              ptr->ai_protocol);
550         if (fd == -1)
551             continue;
552
553 #if !defined( SYS_BEOS )
554         /* Increase the receive buffer size to 1/2MB (8Mb/s during 1/2s)
555         * to avoid packet loss caused by scheduling problems */
556         setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &(int){ 0x80000 }, sizeof (int));
557         setsockopt (fd, SOL_SOCKET, SO_SNDBUF, &(int){ 0x80000 }, sizeof (int));
558
559         /* Allow broadcast sending */
560         setsockopt (fd, SOL_SOCKET, SO_BROADCAST, &(int){ 1 }, sizeof (int));
561 #endif
562
563         if( i_hlim > 0 )
564             net_SetMcastHopLimit( p_this, fd, ptr->ai_family, i_hlim );
565
566         str = var_CreateGetString (p_this, "miface");
567         if (str != NULL)
568         {
569             if (*str)
570                 net_SetMcastOut (p_this, fd, ptr->ai_family, str, NULL);
571             free (str);
572         }
573
574         str = var_CreateGetString (p_this, "miface-addr");
575         if (str != NULL)
576         {
577             if (*str)
578                 net_SetMcastOut (p_this, fd, ptr->ai_family, NULL, str);
579             free (str);
580         }
581
582         net_SetDSCP (fd, var_CreateGetInteger (p_this, "dscp"));
583
584         if( connect( fd, ptr->ai_addr, ptr->ai_addrlen ) == 0 )
585         {
586             /* success */
587             i_handle = fd;
588             break;
589         }
590
591 #if defined( WIN32 ) || defined( UNDER_CE )
592         if( WSAGetLastError () == WSAENETUNREACH )
593 #else
594         if( errno == ENETUNREACH )
595 #endif
596             b_unreach = VLC_TRUE;
597         else
598         {
599             msg_Warn( p_this, "%s port %d : %s", psz_host, i_port,
600                       strerror( errno ) );
601             net_Close( fd );
602             continue;
603         }
604     }
605
606     vlc_freeaddrinfo( res );
607
608     if( i_handle == -1 )
609     {
610         if( b_unreach )
611             msg_Err( p_this, "Host %s port %d is unreachable", psz_host,
612                      i_port );
613         return -1;
614     }
615
616     return i_handle;
617 }
618
619
620 /*****************************************************************************
621  * __net_OpenDgram:
622  *****************************************************************************
623  * OpenDgram a datagram socket and return a handle
624  *****************************************************************************/
625 int __net_OpenDgram( vlc_object_t *obj, const char *psz_bind, int i_bind,
626                      const char *psz_server, int i_server,
627                      int family, int protocol )
628 {
629     struct addrinfo hints, *loc, *rem;
630     int val;
631
632     if( !*psz_server )
633         return net_ListenSingle (obj, psz_bind, i_bind,
634                                  family, SOCK_DGRAM, protocol);
635
636     msg_Dbg( obj, "net: connecting to [%s]:%d from [%s]:%d",
637              psz_server, i_server, psz_bind, i_bind );
638
639     memset (&hints, 0, sizeof (hints));
640     hints.ai_family = family;
641     hints.ai_socktype = SOCK_DGRAM;
642     hints.ai_flags = AI_PASSIVE;
643
644     val = vlc_getaddrinfo (obj, psz_server, i_server, &hints, &rem);
645     if (val)
646     {
647         msg_Err (obj, "cannot resolve %s port %d : %s", psz_bind, i_bind,
648                  vlc_gai_strerror (val));
649         return -1;
650     }
651
652     val = vlc_getaddrinfo (obj, psz_bind, i_bind, &hints, &loc);
653     if (val)
654     {
655         msg_Err (obj, "cannot resolve %s port %d : %s", psz_bind, i_bind,
656                  vlc_gai_strerror (val));
657         vlc_freeaddrinfo (rem);
658         return -1;
659     }
660
661     for (struct addrinfo *ptr = loc; ptr != NULL; ptr = ptr->ai_next)
662     {
663         int fd = net_Socket (obj, ptr->ai_family, ptr->ai_socktype,
664                              protocol ?: ptr->ai_protocol);
665         if (fd == -1)
666             continue; // usually, address family not supported
667
668 #ifdef SO_REUSEPORT
669         setsockopt (fd, SOL_SOCKET, SO_REUSEPORT, &(int){ 1 }, sizeof (int));
670 #endif
671
672 #ifdef SO_RCVBUF
673         /* Increase the receive buffer size to 1/2MB (8Mb/s during 1/2s)
674          * to avoid packet loss caused in case of scheduling hiccups */
675         setsockopt (fd, SOL_SOCKET, SO_RCVBUF,
676                     (void *)&(int){ 0x80000 }, sizeof (int));
677         setsockopt (fd, SOL_SOCKET, SO_SNDBUF,
678                     (void *)&(int){ 0x80000 }, sizeof (int));
679 #endif
680
681 #if defined (WIN32) || defined (UNDER_CE)
682         if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
683          && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
684         {
685             // This works for IPv4 too - don't worry!
686             struct sockaddr_in6 dumb =
687             {
688                 .sin6_family = ptr->ai_addr->sa_family,
689                 .sin6_port =  ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
690             };
691
692             bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
693         }
694         else
695 #endif
696         if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
697         {
698             net_Close (fd);
699             continue;
700         }
701
702         struct addrinfo *ptr2;
703         for (ptr2 = rem; ptr2 != NULL; ptr2 = ptr2->ai_next)
704         {
705             if ((ptr2->ai_family != ptr->ai_family)
706              || (ptr2->ai_socktype != ptr->ai_socktype)
707              || (ptr2->ai_protocol != ptr->ai_protocol))
708                 continue;
709
710             if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen))
711             {
712                 if (net_SourceSubscribe (obj, fd,
713                                          ptr2->ai_addr, ptr2->ai_addrlen,
714                                          ptr->ai_addr, ptr->ai_addrlen) == 0)
715                     break;
716             }
717             else
718             {
719                 if (connect (fd, ptr2->ai_addr, ptr2->ai_addrlen) == 0)
720                     break;
721             }
722         }
723
724         if (ptr2 == NULL)
725         {
726             msg_Err (obj, "cannot connect to %s port %d: %s",
727                      psz_server, i_server, net_strerror (net_errno));
728             close (fd);
729             continue;
730         }
731
732         return fd;
733     }
734
735     return -1;
736 }