codec: jpeg: fix sanity checks
[vlc.git] / src / network / udp.c
blobd098fb142590d2431d4ea7c536419976a9b9e4ba
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 #else
45 # include <unistd.h>
46 # ifdef HAVE_NET_IF_H
47 # include <net/if.h>
48 # endif
49 #endif
51 #ifdef HAVE_LINUX_DCCP_H
52 # include <linux/dccp.h>
53 # ifndef SOCK_DCCP /* provisional API */
54 # define SOCK_DCCP 6
55 # endif
56 #endif
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 /* IANA */
66 #endif
67 #ifndef SOL_DCCP
68 # define SOL_DCCP IPPROTO_DCCP
69 #endif
70 #ifndef IPPROTO_DCCP
71 # define IPPROTO_DCCP 33 /* IANA */
72 #endif
73 #ifndef SOL_UDPLITE
74 # define SOL_UDPLITE IPPROTO_UDPLITE
75 #endif
76 #ifndef IPPROTO_UDPLITE
77 # define IPPROTO_UDPLITE 136 /* IANA */
78 #endif
80 #if defined (HAVE_NETINET_UDPLITE_H)
81 # include <netinet/udplite.h>
82 #elif defined (__linux__)
83 /* still missing from glibc 2.6 */
84 # define UDPLITE_SEND_CSCOV 10
85 # define UDPLITE_RECV_CSCOV 11
86 #endif
88 extern int net_Socket( vlc_object_t *p_this, int i_family, int i_socktype,
89 int i_protocol );
91 /* */
92 static int net_SetupDgramSocket (vlc_object_t *p_obj, int fd,
93 const struct addrinfo *ptr)
95 #ifdef SO_REUSEPORT
96 setsockopt (fd, SOL_SOCKET, SO_REUSEPORT, &(int){ 1 }, sizeof (int));
97 #endif
99 #if defined (_WIN32)
101 /* Check windows version so we know if we need to increase receive buffers
102 * for Windows 7 and earlier
104 * SetSocketMediaStreamingMode is present in win 8 and later, so we set
105 * receive buffer if that isn't present
107 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
108 HINSTANCE h_Network = LoadLibrary(TEXT("Windows.Networking.dll"));
109 if( (h_Network == NULL) ||
110 (GetProcAddress( h_Network, "SetSocketMediaStreamingMode" ) == NULL ) )
112 setsockopt (fd, SOL_SOCKET, SO_RCVBUF,
113 (void *)&(int){ 0x80000 }, sizeof (int));
115 if( h_Network )
116 FreeLibrary( h_Network );
117 #endif
119 if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
120 && (sizeof (struct sockaddr_storage) >= ptr->ai_addrlen))
122 // This works for IPv4 too - don't worry!
123 struct sockaddr_in6 dumb =
125 .sin6_family = ptr->ai_addr->sa_family,
126 .sin6_port = ((struct sockaddr_in *)(ptr->ai_addr))->sin_port
129 bind (fd, (struct sockaddr *)&dumb, ptr->ai_addrlen);
131 else
132 #endif
133 if (bind (fd, ptr->ai_addr, ptr->ai_addrlen))
135 msg_Err( p_obj, "socket bind error: %s", vlc_strerror_c(net_errno) );
136 net_Close (fd);
137 return -1;
139 return fd;
142 /* */
143 static int net_ListenSingle (vlc_object_t *obj, const char *host, int port,
144 int protocol)
146 struct addrinfo hints = {
147 .ai_socktype = SOCK_DGRAM,
148 .ai_protocol = protocol,
149 .ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_IDN,
150 }, *res;
152 if (host && !*host)
153 host = NULL;
155 msg_Dbg (obj, "net: opening %s datagram port %d",
156 host ? host : "any", port);
158 int val = vlc_getaddrinfo (host, port, &hints, &res);
159 if (val)
161 msg_Err (obj, "Cannot resolve %s port %d : %s", host, port,
162 gai_strerror (val));
163 return -1;
166 val = -1;
168 for (const struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
170 int fd = net_Socket (obj, ptr->ai_family, ptr->ai_socktype,
171 ptr->ai_protocol);
172 if (fd == -1)
174 msg_Dbg (obj, "socket error: %s", vlc_strerror_c(net_errno));
175 continue;
178 #ifdef IPV6_V6ONLY
179 /* Try dual-mode IPv6 if available. */
180 if (ptr->ai_family == AF_INET6)
181 setsockopt (fd, SOL_IPV6, IPV6_V6ONLY, &(int){ 0 }, sizeof (int));
182 #endif
183 fd = net_SetupDgramSocket( obj, fd, ptr );
184 if( fd == -1 )
185 continue;
187 if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
188 && net_Subscribe (obj, fd, ptr->ai_addr, ptr->ai_addrlen))
190 net_Close (fd);
191 continue;
194 val = fd;
195 break;
198 freeaddrinfo (res);
199 return val;
203 static int net_SetMcastHopLimit( vlc_object_t *p_this,
204 int fd, int family, int hlim )
206 int proto, cmd;
208 /* There is some confusion in the world whether IP_MULTICAST_TTL
209 * takes a byte or an int as an argument.
210 * BSD seems to indicate byte so we are going with that and use
211 * int as a fallback to be safe */
212 switch( family )
214 #ifdef IP_MULTICAST_TTL
215 case AF_INET:
216 proto = SOL_IP;
217 cmd = IP_MULTICAST_TTL;
218 break;
219 #endif
221 #ifdef IPV6_MULTICAST_HOPS
222 case AF_INET6:
223 proto = SOL_IPV6;
224 cmd = IPV6_MULTICAST_HOPS;
225 break;
226 #endif
228 default:
229 errno = EAFNOSUPPORT;
230 msg_Warn( p_this, "%s", vlc_strerror_c(EAFNOSUPPORT) );
231 return VLC_EGENERIC;
234 if( setsockopt( fd, proto, cmd, &hlim, sizeof( hlim ) ) < 0 )
236 /* BSD compatibility */
237 unsigned char buf;
239 msg_Dbg( p_this, "cannot set hop limit (%d): %s", hlim,
240 vlc_strerror_c(net_errno) );
241 buf = (unsigned char)(( hlim > 255 ) ? 255 : hlim);
242 if( setsockopt( fd, proto, cmd, &buf, sizeof( buf ) ) )
244 msg_Err( p_this, "cannot set hop limit (%d): %s", hlim,
245 vlc_strerror_c(net_errno) );
246 return VLC_EGENERIC;
250 return VLC_SUCCESS;
254 static int net_SetMcastOut (vlc_object_t *p_this, int fd, int family,
255 const char *iface)
257 int scope = if_nametoindex (iface);
258 if (scope == 0)
260 msg_Err (p_this, "invalid multicast interface: %s", iface);
261 return -1;
264 switch (family)
266 #ifdef IPV6_MULTICAST_IF
267 case AF_INET6:
268 if (setsockopt (fd, SOL_IPV6, IPV6_MULTICAST_IF,
269 &scope, sizeof (scope)) == 0)
270 return 0;
271 break;
272 #endif
274 #ifdef __linux__
275 case AF_INET:
277 struct ip_mreqn req = { .imr_ifindex = scope };
278 if (setsockopt (fd, SOL_IP, IP_MULTICAST_IF,
279 &req, sizeof (req)) == 0)
280 return 0;
281 break;
283 #endif
284 default:
285 errno = EAFNOSUPPORT;
287 msg_Err (p_this, "cannot force multicast interface %s: %s", iface,
288 vlc_strerror_c(errno));
289 return -1;
293 static unsigned var_GetIfIndex (vlc_object_t *obj)
295 char *ifname = var_InheritString (obj, "miface");
296 if (ifname == NULL)
297 return 0;
299 unsigned ifindex = if_nametoindex (ifname);
300 if (ifindex == 0)
301 msg_Err (obj, "invalid multicast interface: %s", ifname);
302 free (ifname);
303 return ifindex;
308 * IP-agnostic multicast join,
309 * with fallback to old APIs, and fallback from SSM to ASM.
311 static int
312 net_SourceSubscribe (vlc_object_t *obj, int fd,
313 const struct sockaddr *src, socklen_t srclen,
314 const struct sockaddr *grp, socklen_t grplen)
316 /* MCAST_JOIN_SOURCE_GROUP was introduced to OS X in v10.7, but it doesn't work,
317 * so ignore it to use the same code path as on 10.5 or 10.6 */
318 #if defined (MCAST_JOIN_SOURCE_GROUP) && !defined (__APPLE__)
319 /* Family-agnostic Source-Specific Multicast join */
320 int level;
321 struct group_source_req gsr;
323 memset (&gsr, 0, sizeof (gsr));
324 gsr.gsr_interface = var_GetIfIndex (obj);
326 switch (grp->sa_family)
328 #ifdef AF_INET6
329 case AF_INET6:
331 const struct sockaddr_in6 *g6 = (const struct sockaddr_in6 *)grp;
333 level = SOL_IPV6;
334 assert (grplen >= sizeof (struct sockaddr_in6));
335 if (g6->sin6_scope_id != 0)
336 gsr.gsr_interface = g6->sin6_scope_id;
337 break;
339 #endif
340 case AF_INET:
341 level = SOL_IP;
342 break;
343 default:
344 errno = EAFNOSUPPORT;
345 return -1;
348 assert (grplen <= sizeof (gsr.gsr_group));
349 memcpy (&gsr.gsr_source, src, srclen);
350 assert (srclen <= sizeof (gsr.gsr_source));
351 memcpy (&gsr.gsr_group, grp, grplen);
352 if (setsockopt (fd, level, MCAST_JOIN_SOURCE_GROUP,
353 &gsr, sizeof (gsr)) == 0)
354 return 0;
356 #else
357 if (src->sa_family != grp->sa_family)
359 errno = EAFNOSUPPORT;
360 return -1;
363 switch (grp->sa_family)
365 # ifdef IP_ADD_SOURCE_MEMBERSHIP
366 /* IPv4-specific API */
367 case AF_INET:
369 struct ip_mreq_source imr;
371 memset (&imr, 0, sizeof (imr));
372 assert (grplen >= sizeof (struct sockaddr_in));
373 imr.imr_multiaddr = ((const struct sockaddr_in *)grp)->sin_addr;
374 assert (srclen >= sizeof (struct sockaddr_in));
375 imr.imr_sourceaddr = ((const struct sockaddr_in *)src)->sin_addr;
376 if (setsockopt (fd, SOL_IP, IP_ADD_SOURCE_MEMBERSHIP,
377 &imr, sizeof (imr)) == 0)
378 return 0;
379 break;
381 # endif
382 default:
383 errno = EAFNOSUPPORT;
386 #endif
387 msg_Err (obj, "cannot join source multicast group: %s",
388 vlc_strerror_c(net_errno));
389 msg_Warn (obj, "trying ASM instead of SSM...");
390 return net_Subscribe (obj, fd, grp, grplen);
394 int net_Subscribe (vlc_object_t *obj, int fd,
395 const struct sockaddr *grp, socklen_t grplen)
397 /* MCAST_JOIN_GROUP was introduced to OS X in v10.7, but it doesn't work,
398 * so ignore it to use the same code as on 10.5 or 10.6 */
399 #if defined (MCAST_JOIN_GROUP) && !defined (__APPLE__)
400 /* Family-agnostic Any-Source Multicast join */
401 int level;
402 struct group_req gr;
404 memset (&gr, 0, sizeof (gr));
405 gr.gr_interface = var_GetIfIndex (obj);
407 switch (grp->sa_family)
409 #ifdef AF_INET6
410 case AF_INET6:
412 const struct sockaddr_in6 *g6 = (const struct sockaddr_in6 *)grp;
414 level = SOL_IPV6;
415 assert (grplen >= sizeof (struct sockaddr_in6));
416 if (g6->sin6_scope_id != 0)
417 gr.gr_interface = g6->sin6_scope_id;
418 break;
420 #endif
421 case AF_INET:
422 level = SOL_IP;
423 break;
424 default:
425 errno = EAFNOSUPPORT;
426 return -1;
429 assert (grplen <= sizeof (gr.gr_group));
430 memcpy (&gr.gr_group, grp, grplen);
431 if (setsockopt (fd, level, MCAST_JOIN_GROUP, &gr, sizeof (gr)) == 0)
432 return 0;
434 #else
435 switch (grp->sa_family)
437 # ifdef IPV6_JOIN_GROUP
438 case AF_INET6:
440 struct ipv6_mreq ipv6mr;
441 const struct sockaddr_in6 *g6 = (const struct sockaddr_in6 *)grp;
443 memset (&ipv6mr, 0, sizeof (ipv6mr));
444 assert (grplen >= sizeof (struct sockaddr_in6));
445 ipv6mr.ipv6mr_multiaddr = g6->sin6_addr;
446 ipv6mr.ipv6mr_interface = g6->sin6_scope_id;
447 if (!setsockopt (fd, SOL_IPV6, IPV6_JOIN_GROUP,
448 &ipv6mr, sizeof (ipv6mr)))
449 return 0;
450 break;
452 # endif
453 # ifdef IP_ADD_MEMBERSHIP
454 case AF_INET:
456 struct ip_mreq imr;
458 memset (&imr, 0, sizeof (imr));
459 assert (grplen >= sizeof (struct sockaddr_in));
460 imr.imr_multiaddr = ((const struct sockaddr_in *)grp)->sin_addr;
461 if (setsockopt (fd, SOL_IP, IP_ADD_MEMBERSHIP,
462 &imr, sizeof (imr)) == 0)
463 return 0;
464 break;
466 # endif
467 default:
468 errno = EAFNOSUPPORT;
471 #endif
472 msg_Err (obj, "cannot join multicast group: %s",
473 vlc_strerror_c(net_errno));
474 return -1;
478 static int net_SetDSCP( int fd, uint8_t dscp )
480 struct sockaddr_storage addr;
481 if( getsockname( fd, (struct sockaddr *)&addr, &(socklen_t){ sizeof (addr) }) )
482 return -1;
484 int level, cmd;
486 switch( addr.ss_family )
488 #ifdef IPV6_TCLASS
489 case AF_INET6:
490 level = SOL_IPV6;
491 cmd = IPV6_TCLASS;
492 break;
493 #endif
495 case AF_INET:
496 level = SOL_IP;
497 cmd = IP_TOS;
498 break;
500 default:
501 #ifdef ENOPROTOOPT
502 errno = ENOPROTOOPT;
503 #endif
504 return -1;
507 return setsockopt( fd, level, cmd, &(int){ dscp }, sizeof (int));
510 #undef net_ConnectDgram
511 /*****************************************************************************
512 * net_ConnectDgram:
513 *****************************************************************************
514 * Open a datagram socket to send data to a defined destination, with an
515 * optional hop limit.
516 *****************************************************************************/
517 int net_ConnectDgram( vlc_object_t *p_this, const char *psz_host, int i_port,
518 int i_hlim, int proto )
520 struct addrinfo hints = {
521 .ai_socktype = SOCK_DGRAM,
522 .ai_protocol = proto,
523 .ai_flags = AI_NUMERICSERV | AI_IDN,
524 }, *res;
525 int i_handle = -1;
526 bool b_unreach = false;
528 if( i_hlim < 0 )
529 i_hlim = var_InheritInteger( p_this, "ttl" );
531 msg_Dbg( p_this, "net: connecting to [%s]:%d", psz_host, i_port );
533 int val = vlc_getaddrinfo (psz_host, i_port, &hints, &res);
534 if (val)
536 msg_Err (p_this, "cannot resolve [%s]:%d : %s", psz_host, i_port,
537 gai_strerror (val));
538 return -1;
541 for (struct addrinfo *ptr = res; ptr != NULL; ptr = ptr->ai_next)
543 char *str;
544 int fd = net_Socket (p_this, ptr->ai_family, ptr->ai_socktype,
545 ptr->ai_protocol);
546 if (fd == -1)
547 continue;
549 /* Allow broadcast sending */
550 setsockopt (fd, SOL_SOCKET, SO_BROADCAST, &(int){ 1 }, sizeof (int));
552 if( i_hlim >= 0 )
553 net_SetMcastHopLimit( p_this, fd, ptr->ai_family, i_hlim );
555 str = var_InheritString (p_this, "miface");
556 if (str != NULL)
558 net_SetMcastOut (p_this, fd, ptr->ai_family, str);
559 free (str);
562 net_SetDSCP (fd, var_InheritInteger (p_this, "dscp"));
564 if( connect( fd, ptr->ai_addr, ptr->ai_addrlen ) == 0 )
566 /* success */
567 i_handle = fd;
568 break;
571 #if defined( _WIN32 )
572 if( WSAGetLastError () == WSAENETUNREACH )
573 #else
574 if( errno == ENETUNREACH )
575 #endif
576 b_unreach = true;
577 else
578 msg_Warn( p_this, "%s port %d : %s", psz_host, i_port,
579 vlc_strerror_c(errno) );
580 net_Close( fd );
583 freeaddrinfo( res );
585 if( i_handle == -1 )
587 if( b_unreach )
588 msg_Err( p_this, "Host %s port %d is unreachable", psz_host,
589 i_port );
590 return -1;
593 return i_handle;
596 #undef net_OpenDgram
597 /*****************************************************************************
598 * net_OpenDgram:
599 *****************************************************************************
600 * OpenDgram a datagram socket and return a handle
601 *****************************************************************************/
602 int net_OpenDgram( vlc_object_t *obj, const char *psz_bind, int i_bind,
603 const char *psz_server, int i_server, int protocol )
605 if ((psz_server == NULL) || (psz_server[0] == '\0'))
606 return net_ListenSingle (obj, psz_bind, i_bind, protocol);
608 msg_Dbg (obj, "net: connecting to [%s]:%d from [%s]:%d",
609 psz_server, i_server, psz_bind, i_bind);
611 struct addrinfo hints = {
612 .ai_socktype = SOCK_DGRAM,
613 .ai_protocol = protocol,
614 .ai_flags = AI_NUMERICSERV | AI_IDN,
615 }, *loc, *rem;
617 int val = vlc_getaddrinfo (psz_server, i_server, &hints, &rem);
618 if (val)
620 msg_Err (obj, "cannot resolve %s port %d : %s", psz_bind, i_bind,
621 gai_strerror (val));
622 return -1;
625 hints.ai_flags |= AI_PASSIVE;
626 val = vlc_getaddrinfo (psz_bind, i_bind, &hints, &loc);
627 if (val)
629 msg_Err (obj, "cannot resolve %s port %d : %s", psz_bind, i_bind,
630 gai_strerror (val));
631 freeaddrinfo (rem);
632 return -1;
635 val = -1;
636 for (struct addrinfo *ptr = loc; ptr != NULL; ptr = ptr->ai_next)
638 int fd = net_Socket (obj, ptr->ai_family, ptr->ai_socktype,
639 ptr->ai_protocol);
640 if (fd == -1)
641 continue; // usually, address family not supported
643 fd = net_SetupDgramSocket( obj, fd, ptr );
644 if( fd == -1 )
645 continue;
647 for (struct addrinfo *ptr2 = rem; ptr2 != NULL; ptr2 = ptr2->ai_next)
649 if ((ptr2->ai_family != ptr->ai_family)
650 || (ptr2->ai_socktype != ptr->ai_socktype)
651 || (ptr2->ai_protocol != ptr->ai_protocol))
652 continue;
654 if (net_SockAddrIsMulticast (ptr->ai_addr, ptr->ai_addrlen)
655 ? net_SourceSubscribe (obj, fd,
656 ptr2->ai_addr, ptr2->ai_addrlen,
657 ptr->ai_addr, ptr->ai_addrlen)
658 : connect (fd, ptr2->ai_addr, ptr2->ai_addrlen))
660 msg_Err (obj, "cannot connect to %s port %d: %s",
661 psz_server, i_server, vlc_strerror_c(net_errno));
662 continue;
664 val = fd;
665 break;
668 if (val != -1)
669 break;
671 net_Close (fd);
674 freeaddrinfo (rem);
675 freeaddrinfo (loc);
676 return val;
681 * net_SetCSCov:
682 * Sets the send and receive checksum coverage of a socket:
683 * @param fd socket
684 * @param sendcov payload coverage of sent packets (bytes), -1 for full
685 * @param recvcov minimum payload coverage of received packets, -1 for full
687 int net_SetCSCov (int fd, int sendcov, int recvcov)
689 int type;
691 if (getsockopt (fd, SOL_SOCKET, SO_TYPE,
692 &type, &(socklen_t){ sizeof (type) }))
693 return VLC_EGENERIC;
695 switch (type)
697 #ifdef UDPLITE_RECV_CSCOV
698 case SOCK_DGRAM: /* UDP-Lite */
699 if (sendcov == -1)
700 sendcov = 0;
701 else
702 sendcov += 8; /* partial */
703 if (setsockopt (fd, SOL_UDPLITE, UDPLITE_SEND_CSCOV, &sendcov,
704 sizeof (sendcov)))
705 return VLC_EGENERIC;
707 if (recvcov == -1)
708 recvcov = 0;
709 else
710 recvcov += 8;
711 if (setsockopt (fd, SOL_UDPLITE, UDPLITE_RECV_CSCOV,
712 &recvcov, sizeof (recvcov)))
713 return VLC_EGENERIC;
715 return VLC_SUCCESS;
716 #endif
717 #ifdef DCCP_SOCKOPT_SEND_CSCOV
718 case SOCK_DCCP: /* DCCP and its ill-named socket type */
719 if ((sendcov == -1) || (sendcov > 56))
720 sendcov = 0;
721 else
722 sendcov = (sendcov + 3) / 4;
723 if (setsockopt (fd, SOL_DCCP, DCCP_SOCKOPT_SEND_CSCOV,
724 &sendcov, sizeof (sendcov)))
725 return VLC_EGENERIC;
727 if ((recvcov == -1) || (recvcov > 56))
728 recvcov = 0;
729 else
730 recvcov = (recvcov + 3) / 4;
731 if (setsockopt (fd, SOL_DCCP, DCCP_SOCKOPT_RECV_CSCOV,
732 &recvcov, sizeof (recvcov)))
733 return VLC_EGENERIC;
735 return VLC_SUCCESS;
736 #endif
738 #if !defined( UDPLITE_RECV_CSCOV ) && !defined( DCCP_SOCKOPT_SEND_CSCOV )
739 VLC_UNUSED(sendcov);
740 VLC_UNUSED(recvcov);
741 #endif
743 return VLC_EGENERIC;