Contribs: gnutls: Fix win32, winrt, android, macOS compilation
[vlc.git] / src / network / udp.c
blob6a590b98c317133806bec513093c860bb5957fdc
1 /*****************************************************************************
2 * udp.c:
3 *****************************************************************************
4 * Copyright (C) 2004-2006 VLC authors and VideoLAN
5 * Copyright © 2006-2007 Rémi Denis-Courmont
7 * $Id$
9 * Authors: Laurent Aimar <fenrir@videolan.org>
10 * Rémi Denis-Courmont <rem # videolan.org>
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU Lesser General Public License as published by
14 * the Free Software Foundation; either version 2.1 of the License, or
15 * (at your option) any later version.
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 Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public License
23 * along with this program; if not, write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
28 * Preamble
29 *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
34 #include <vlc_common.h>
36 #include <errno.h>
37 #include <assert.h>
39 #include <vlc_network.h>
41 #ifdef _WIN32
42 # undef EAFNOSUPPORT
43 # define EAFNOSUPPORT WSAEAFNOSUPPORT
44 # include <wincrypt.h>
45 # include <iphlpapi.h>
46 #else
47 # include <unistd.h>
48 # ifdef HAVE_NET_IF_H
49 # include <net/if.h>
50 # endif
51 #endif
53 #ifdef HAVE_LINUX_DCCP_H
54 # include <linux/dccp.h>
55 # ifndef SOCK_DCCP /* provisional API */
56 # define SOCK_DCCP 6
57 # endif
58 #endif
60 #ifndef SOL_IP
61 # define SOL_IP IPPROTO_IP
62 #endif
63 #ifndef SOL_IPV6
64 # define SOL_IPV6 IPPROTO_IPV6
65 #endif
66 #ifndef IPPROTO_IPV6
67 # define IPPROTO_IPV6 41 /* IANA */
68 #endif
69 #ifndef SOL_DCCP
70 # define SOL_DCCP IPPROTO_DCCP
71 #endif
72 #ifndef IPPROTO_DCCP
73 # define IPPROTO_DCCP 33 /* IANA */
74 #endif
75 #ifndef SOL_UDPLITE
76 # define SOL_UDPLITE IPPROTO_UDPLITE
77 #endif
78 #ifndef IPPROTO_UDPLITE
79 # define IPPROTO_UDPLITE 136 /* IANA */
80 #endif
82 #if defined (HAVE_NETINET_UDPLITE_H)
83 # include <netinet/udplite.h>
84 #elif defined (__linux__)
85 /* still missing from glibc 2.6 */
86 # define UDPLITE_SEND_CSCOV 10
87 # define UDPLITE_RECV_CSCOV 11
88 #endif
90 extern int net_Socket( vlc_object_t *p_this, int i_family, int i_socktype,
91 int i_protocol );
93 /* */
94 static int net_SetupDgramSocket (vlc_object_t *p_obj, int fd,
95 const struct addrinfo *ptr)
97 #ifdef SO_REUSEPORT
98 setsockopt (fd, SOL_SOCKET, SO_REUSEPORT, &(int){ 1 }, sizeof (int));
99 #endif
101 #if defined (_WIN32)
103 /* Check windows version so we know if we need to increase receive buffers
104 * for Windows 7 and earlier
106 * SetSocketMediaStreamingMode is present in win 8 and later, so we set
107 * receive buffer if that isn't present
109 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
110 HINSTANCE h_Network = LoadLibrary(TEXT("Windows.Networking.dll"));
111 if( (h_Network == NULL) ||
112 (GetProcAddress( h_Network, "SetSocketMediaStreamingMode" ) == NULL ) )
114 setsockopt (fd, SOL_SOCKET, SO_RCVBUF,
115 (void *)&(int){ 0x80000 }, sizeof (int));
117 if( h_Network )
118 FreeLibrary( h_Network );
119 #endif
121 if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
122 && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
124 // This works for IPv4 too - don't worry!
125 struct sockaddr_in6 dumb =
127 .sin6_family = ptr->ai_addr->sa_family,
128 .sin6_port = ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
131 bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
133 else
134 #endif
135 if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
137 msg_Err( p_obj, "socket bind error: %s", vlc_strerror_c(net_errno) );
138 net_Close (fd);
139 return -1;
141 return fd;
144 /* */
145 static int net_ListenSingle (vlc_object_t *obj, const char *host, int port,
146 int protocol)
148 struct addrinfo hints = {
149 .ai_socktype = SOCK_DGRAM,
150 .ai_protocol = protocol,
151 .ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_IDN,
152 }, *res;
154 if (host && !*host)
155 host = NULL;
157 msg_Dbg (obj, "net: opening %s datagram port %d",
158 host ? host : "any", port);
160 int val = vlc_getaddrinfo (host, port, &hints, &res);
161 if (val)
163 msg_Err (obj, "Cannot resolve %s port %d : %s", host, port,
164 gai_strerror (val));
165 return -1;
168 val = -1;
170 for (const struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
172 int fd = net_Socket (obj, ptr->ai_family, ptr->ai_socktype,
173 ptr->ai_protocol);
174 if (fd == -1)
176 msg_Dbg (obj, "socket error: %s", vlc_strerror_c(net_errno));
177 continue;
180 #ifdef IPV6_V6ONLY
181 /* Try dual-mode IPv6 if available. */
182 if (ptr->ai_family == AF_INET6)
183 setsockopt (fd, SOL_IPV6, IPV6_V6ONLY, &(int){ 0 }, sizeof (int));
184 #endif
185 fd = net_SetupDgramSocket( obj, fd, ptr );
186 if( fd == -1 )
187 continue;
189 if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
190 && net_Subscribe (obj, fd, ptr->ai_addr, ptr->ai_addrlen))
192 net_Close (fd);
193 continue;
196 val = fd;
197 break;
200 freeaddrinfo (res);
201 return val;
205 static int net_SetMcastHopLimit( vlc_object_t *p_this,
206 int fd, int family, int hlim )
208 int proto, cmd;
210 /* There is some confusion in the world whether IP_MULTICAST_TTL
211 * takes a byte or an int as an argument.
212 * BSD seems to indicate byte so we are going with that and use
213 * int as a fallback to be safe */
214 switch( family )
216 #ifdef IP_MULTICAST_TTL
217 case AF_INET:
218 proto = SOL_IP;
219 cmd = IP_MULTICAST_TTL;
220 break;
221 #endif
223 #ifdef IPV6_MULTICAST_HOPS
224 case AF_INET6:
225 proto = SOL_IPV6;
226 cmd = IPV6_MULTICAST_HOPS;
227 break;
228 #endif
230 default:
231 errno = EAFNOSUPPORT;
232 msg_Warn( p_this, "%s", vlc_strerror_c(EAFNOSUPPORT) );
233 return VLC_EGENERIC;
236 if( setsockopt( fd, proto, cmd, &hlim, sizeof( hlim ) ) < 0 )
238 /* BSD compatibility */
239 unsigned char buf;
241 msg_Dbg( p_this, "cannot set hop limit (%d): %s", hlim,
242 vlc_strerror_c(net_errno) );
243 buf = (unsigned char)(( hlim > 255 ) ? 255 : hlim);
244 if( setsockopt( fd, proto, cmd, &buf, sizeof( buf ) ) )
246 msg_Err( p_this, "cannot set hop limit (%d): %s", hlim,
247 vlc_strerror_c(net_errno) );
248 return VLC_EGENERIC;
252 return VLC_SUCCESS;
256 static int net_SetMcastOut (vlc_object_t *p_this, int fd, int family,
257 const char *iface)
259 int scope = if_nametoindex (iface);
260 if (scope == 0)
262 msg_Err (p_this, "invalid multicast interface: %s", iface);
263 return -1;
266 switch (family)
268 #ifdef IPV6_MULTICAST_IF
269 case AF_INET6:
270 if (setsockopt (fd, SOL_IPV6, IPV6_MULTICAST_IF,
271 &scope, sizeof (scope)) == 0)
272 return 0;
273 break;
274 #endif
276 #ifdef __linux__
277 case AF_INET:
279 struct ip_mreqn req = { .imr_ifindex = scope };
280 if (setsockopt (fd, SOL_IP, IP_MULTICAST_IF,
281 &req, sizeof (req)) == 0)
282 return 0;
283 break;
285 #endif
286 default:
287 errno = EAFNOSUPPORT;
289 msg_Err (p_this, "cannot force multicast interface %s: %s", iface,
290 vlc_strerror_c(errno));
291 return -1;
295 static unsigned var_GetIfIndex (vlc_object_t *obj)
297 char *ifname = var_InheritString (obj, "miface");
298 if (ifname == NULL)
299 return 0;
301 unsigned ifindex = if_nametoindex (ifname);
302 if (ifindex == 0)
303 msg_Err (obj, "invalid multicast interface: %s", ifname);
304 free (ifname);
305 return ifindex;
310 * IP-agnostic multicast join,
311 * with fallback to old APIs, and fallback from SSM to ASM.
313 static int
314 net_SourceSubscribe (vlc_object_t *obj, int fd,
315 const struct sockaddr *src, socklen_t srclen,
316 const struct sockaddr *grp, socklen_t grplen)
318 /* MCAST_JOIN_SOURCE_GROUP was introduced to OS X in v10.7, but it doesn't work,
319 * so ignore it to use the same code path as on 10.5 or 10.6 */
320 #if defined (MCAST_JOIN_SOURCE_GROUP) && !defined (__APPLE__)
321 /* Family-agnostic Source-Specific Multicast join */
322 int level;
323 struct group_source_req gsr;
325 memset (&gsr, 0, sizeof (gsr));
326 gsr.gsr_interface = var_GetIfIndex (obj);
328 switch (grp->sa_family)
330 #ifdef AF_INET6
331 case AF_INET6:
333 const struct sockaddr_in6 *g6 = (const struct sockaddr_in6 *)grp;
335 level = SOL_IPV6;
336 assert (grplen >= sizeof (struct sockaddr_in6));
337 if (g6->sin6_scope_id != 0)
338 gsr.gsr_interface = g6->sin6_scope_id;
339 break;
341 #endif
342 case AF_INET:
343 level = SOL_IP;
344 break;
345 default:
346 errno = EAFNOSUPPORT;
347 return -1;
350 assert (grplen <= sizeof (gsr.gsr_group));
351 memcpy (&gsr.gsr_source, src, srclen);
352 assert (srclen <= sizeof (gsr.gsr_source));
353 memcpy (&gsr.gsr_group, grp, grplen);
354 if (setsockopt (fd, level, MCAST_JOIN_SOURCE_GROUP,
355 &gsr, sizeof (gsr)) == 0)
356 return 0;
358 #else
359 if (src->sa_family != grp->sa_family)
361 errno = EAFNOSUPPORT;
362 return -1;
365 switch (grp->sa_family)
367 # ifdef IP_ADD_SOURCE_MEMBERSHIP
368 /* IPv4-specific API */
369 case AF_INET:
371 struct ip_mreq_source imr;
373 memset (&imr, 0, sizeof (imr));
374 assert (grplen >= sizeof (struct sockaddr_in));
375 imr.imr_multiaddr = ((const struct sockaddr_in *)grp)->sin_addr;
376 assert (srclen >= sizeof (struct sockaddr_in));
377 imr.imr_sourceaddr = ((const struct sockaddr_in *)src)->sin_addr;
378 if (setsockopt (fd, SOL_IP, IP_ADD_SOURCE_MEMBERSHIP,
379 &imr, sizeof (imr)) == 0)
380 return 0;
381 break;
383 # endif
384 default:
385 errno = EAFNOSUPPORT;
388 #endif
389 msg_Err (obj, "cannot join source multicast group: %s",
390 vlc_strerror_c(net_errno));
391 msg_Warn (obj, "trying ASM instead of SSM...");
392 return net_Subscribe (obj, fd, grp, grplen);
396 int net_Subscribe (vlc_object_t *obj, int fd,
397 const struct sockaddr *grp, socklen_t grplen)
399 /* MCAST_JOIN_GROUP was introduced to OS X in v10.7, but it doesn't work,
400 * so ignore it to use the same code as on 10.5 or 10.6 */
401 #if defined (MCAST_JOIN_GROUP) && !defined (__APPLE__)
402 /* Family-agnostic Any-Source Multicast join */
403 int level;
404 struct group_req gr;
406 memset (&gr, 0, sizeof (gr));
407 gr.gr_interface = var_GetIfIndex (obj);
409 switch (grp->sa_family)
411 #ifdef AF_INET6
412 case AF_INET6:
414 const struct sockaddr_in6 *g6 = (const struct sockaddr_in6 *)grp;
416 level = SOL_IPV6;
417 assert (grplen >= sizeof (struct sockaddr_in6));
418 if (g6->sin6_scope_id != 0)
419 gr.gr_interface = g6->sin6_scope_id;
420 break;
422 #endif
423 case AF_INET:
424 level = SOL_IP;
425 break;
426 default:
427 errno = EAFNOSUPPORT;
428 return -1;
431 assert (grplen <= sizeof (gr.gr_group));
432 memcpy (&gr.gr_group, grp, grplen);
433 if (setsockopt (fd, level, MCAST_JOIN_GROUP, &gr, sizeof (gr)) == 0)
434 return 0;
436 #else
437 switch (grp->sa_family)
439 # ifdef IPV6_JOIN_GROUP
440 case AF_INET6:
442 struct ipv6_mreq ipv6mr;
443 const struct sockaddr_in6 *g6 = (const struct sockaddr_in6 *)grp;
445 memset (&ipv6mr, 0, sizeof (ipv6mr));
446 assert (grplen >= sizeof (struct sockaddr_in6));
447 ipv6mr.ipv6mr_multiaddr = g6->sin6_addr;
448 ipv6mr.ipv6mr_interface = g6->sin6_scope_id;
449 if (!setsockopt (fd, SOL_IPV6, IPV6_JOIN_GROUP,
450 &ipv6mr, sizeof (ipv6mr)))
451 return 0;
452 break;
454 # endif
455 # ifdef IP_ADD_MEMBERSHIP
456 case AF_INET:
458 struct ip_mreq imr;
460 memset (&imr, 0, sizeof (imr));
461 assert (grplen >= sizeof (struct sockaddr_in));
462 imr.imr_multiaddr = ((const struct sockaddr_in *)grp)->sin_addr;
463 if (setsockopt (fd, SOL_IP, IP_ADD_MEMBERSHIP,
464 &imr, sizeof (imr)) == 0)
465 return 0;
466 break;
468 # endif
469 default:
470 errno = EAFNOSUPPORT;
473 #endif
474 msg_Err (obj, "cannot join multicast group: %s",
475 vlc_strerror_c(net_errno));
476 return -1;
480 static int net_SetDSCP( int fd, uint8_t dscp )
482 struct sockaddr_storage addr;
483 if( getsockname( fd, (struct sockaddr *)&addr, &(socklen_t){ sizeof (addr) }) )
484 return -1;
486 int level, cmd;
488 switch( addr.ss_family )
490 #ifdef IPV6_TCLASS
491 case AF_INET6:
492 level = SOL_IPV6;
493 cmd = IPV6_TCLASS;
494 break;
495 #endif
497 case AF_INET:
498 level = SOL_IP;
499 cmd = IP_TOS;
500 break;
502 default:
503 #ifdef ENOPROTOOPT
504 errno = ENOPROTOOPT;
505 #endif
506 return -1;
509 return setsockopt( fd, level, cmd, &(int){ dscp }, sizeof (int));
512 #undef net_ConnectDgram
513 /*****************************************************************************
514 * net_ConnectDgram:
515 *****************************************************************************
516 * Open a datagram socket to send data to a defined destination, with an
517 * optional hop limit.
518 *****************************************************************************/
519 int net_ConnectDgram( vlc_object_t *p_this, const char *psz_host, int i_port,
520 int i_hlim, int proto )
522 struct addrinfo hints = {
523 .ai_socktype = SOCK_DGRAM,
524 .ai_protocol = proto,
525 .ai_flags = AI_NUMERICSERV | AI_IDN,
526 }, *res;
527 int i_handle = -1;
528 bool b_unreach = false;
530 if( i_hlim < 0 )
531 i_hlim = var_InheritInteger( p_this, "ttl" );
533 msg_Dbg( p_this, "net: connecting to [%s]:%d", psz_host, i_port );
535 int val = vlc_getaddrinfo (psz_host, i_port, &hints, &res);
536 if (val)
538 msg_Err (p_this, "cannot resolve [%s]:%d : %s", psz_host, i_port,
539 gai_strerror (val));
540 return -1;
543 for (struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
545 char *str;
546 int fd = net_Socket (p_this, ptr->ai_family, ptr->ai_socktype,
547 ptr->ai_protocol);
548 if (fd == -1)
549 continue;
551 /* Allow broadcast sending */
552 setsockopt (fd, SOL_SOCKET, SO_BROADCAST, &(int){ 1 }, sizeof (int));
554 if( i_hlim >= 0 )
555 net_SetMcastHopLimit( p_this, fd, ptr->ai_family, i_hlim );
557 str = var_InheritString (p_this, "miface");
558 if (str != NULL)
560 net_SetMcastOut (p_this, fd, ptr->ai_family, str);
561 free (str);
564 net_SetDSCP (fd, var_InheritInteger (p_this, "dscp"));
566 if( connect( fd, ptr->ai_addr, ptr->ai_addrlen ) == 0 )
568 /* success */
569 i_handle = fd;
570 break;
573 #if defined( _WIN32 )
574 if( WSAGetLastError () == WSAENETUNREACH )
575 #else
576 if( errno == ENETUNREACH )
577 #endif
578 b_unreach = true;
579 else
580 msg_Warn( p_this, "%s port %d : %s", psz_host, i_port,
581 vlc_strerror_c(errno) );
582 net_Close( fd );
585 freeaddrinfo( res );
587 if( i_handle == -1 )
589 if( b_unreach )
590 msg_Err( p_this, "Host %s port %d is unreachable", psz_host,
591 i_port );
592 return -1;
595 return i_handle;
598 #undef net_OpenDgram
599 /*****************************************************************************
600 * net_OpenDgram:
601 *****************************************************************************
602 * OpenDgram a datagram socket and return a handle
603 *****************************************************************************/
604 int net_OpenDgram( vlc_object_t *obj, const char *psz_bind, int i_bind,
605 const char *psz_server, int i_server, int protocol )
607 if ((psz_server == NULL) || (psz_server[0] == '\0'))
608 return net_ListenSingle (obj, psz_bind, i_bind, protocol);
610 msg_Dbg (obj, "net: connecting to [%s]:%d from [%s]:%d",
611 psz_server, i_server, psz_bind, i_bind);
613 struct addrinfo hints = {
614 .ai_socktype = SOCK_DGRAM,
615 .ai_protocol = protocol,
616 .ai_flags = AI_NUMERICSERV | AI_IDN,
617 }, *loc, *rem;
619 int val = vlc_getaddrinfo (psz_server, i_server, &hints, &rem);
620 if (val)
622 msg_Err (obj, "cannot resolve %s port %d : %s", psz_bind, i_bind,
623 gai_strerror (val));
624 return -1;
627 hints.ai_flags |= AI_PASSIVE;
628 val = vlc_getaddrinfo (psz_bind, i_bind, &hints, &loc);
629 if (val)
631 msg_Err (obj, "cannot resolve %s port %d : %s", psz_bind, i_bind,
632 gai_strerror (val));
633 freeaddrinfo (rem);
634 return -1;
637 val = -1;
638 for (struct addrinfo *ptr = loc; ptr != NULL; ptr = ptr->ai_next)
640 int fd = net_Socket (obj, ptr->ai_family, ptr->ai_socktype,
641 ptr->ai_protocol);
642 if (fd == -1)
643 continue; // usually, address family not supported
645 fd = net_SetupDgramSocket( obj, fd, ptr );
646 if( fd == -1 )
647 continue;
649 for (struct addrinfo *ptr2 = rem; ptr2 != NULL; ptr2 = ptr2->ai_next)
651 if ((ptr2->ai_family != ptr->ai_family)
652 || (ptr2->ai_socktype != ptr->ai_socktype)
653 || (ptr2->ai_protocol != ptr->ai_protocol))
654 continue;
656 if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
657 ? net_SourceSubscribe (obj, fd,
658 ptr2->ai_addr, ptr2->ai_addrlen,
659 ptr->ai_addr, ptr->ai_addrlen)
660 : connect (fd, ptr2->ai_addr, ptr2->ai_addrlen))
662 msg_Err (obj, "cannot connect to %s port %d: %s",
663 psz_server, i_server, vlc_strerror_c(net_errno));
664 continue;
666 val = fd;
667 break;
670 if (val != -1)
671 break;
673 net_Close (fd);
676 freeaddrinfo (rem);
677 freeaddrinfo (loc);
678 return val;
683 * net_SetCSCov:
684 * Sets the send and receive checksum coverage of a socket:
685 * @param fd socket
686 * @param sendcov payload coverage of sent packets (bytes), -1 for full
687 * @param recvcov minimum payload coverage of received packets, -1 for full
689 int net_SetCSCov (int fd, int sendcov, int recvcov)
691 int type;
693 if (getsockopt (fd, SOL_SOCKET, SO_TYPE,
694 &type, &(socklen_t){ sizeof (type) }))
695 return VLC_EGENERIC;
697 switch (type)
699 #ifdef UDPLITE_RECV_CSCOV
700 case SOCK_DGRAM: /* UDP-Lite */
701 if (sendcov == -1)
702 sendcov = 0;
703 else
704 sendcov += 8; /* partial */
705 if (setsockopt (fd, SOL_UDPLITE, UDPLITE_SEND_CSCOV, &sendcov,
706 sizeof (sendcov)))
707 return VLC_EGENERIC;
709 if (recvcov == -1)
710 recvcov = 0;
711 else
712 recvcov += 8;
713 if (setsockopt (fd, SOL_UDPLITE, UDPLITE_RECV_CSCOV,
714 &recvcov, sizeof (recvcov)))
715 return VLC_EGENERIC;
717 return VLC_SUCCESS;
718 #endif
719 #ifdef DCCP_SOCKOPT_SEND_CSCOV
720 case SOCK_DCCP: /* DCCP and its ill-named socket type */
721 if ((sendcov == -1) || (sendcov > 56))
722 sendcov = 0;
723 else
724 sendcov = (sendcov + 3) / 4;
725 if (setsockopt (fd, SOL_DCCP, DCCP_SOCKOPT_SEND_CSCOV,
726 &sendcov, sizeof (sendcov)))
727 return VLC_EGENERIC;
729 if ((recvcov == -1) || (recvcov > 56))
730 recvcov = 0;
731 else
732 recvcov = (recvcov + 3) / 4;
733 if (setsockopt (fd, SOL_DCCP, DCCP_SOCKOPT_RECV_CSCOV,
734 &recvcov, sizeof (recvcov)))
735 return VLC_EGENERIC;
737 return VLC_SUCCESS;
738 #endif
740 #if !defined( UDPLITE_RECV_CSCOV ) && !defined( DCCP_SOCKOPT_SEND_CSCOV )
741 VLC_UNUSED(sendcov);
742 VLC_UNUSED(recvcov);
743 #endif
745 return VLC_EGENERIC;