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