1 /*****************************************************************************
2 * getaddrinfo.c: getaddrinfo/getnameinfo replacement functions
3 *****************************************************************************
4 * Copyright (C) 2005 the VideoLAN team
5 * Copyright (C) 2002-2007 Rémi Denis-Courmont
8 * Author: Rémi Denis-Courmont <rem # videolan.org>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
29 #include <vlc_common.h>
30 #include <vlc_charset.h>
32 #include <stddef.h> /* size_t */
33 #include <string.h> /* strlen(), memcpy(), memset(), strchr() */
34 #include <stdlib.h> /* malloc(), free(), strtoul() */
38 #ifdef HAVE_SYS_TYPES_H
39 # include <sys/types.h>
41 #ifdef HAVE_ARPA_INET_H
42 # include <arpa/inet.h>
44 #ifdef HAVE_NETINET_IN_H
45 # include <netinet/in.h>
51 #include <vlc_network.h>
54 # define NO_ADDRESS NO_DATA
57 # define INADDR_NONE 0xFFFFFFFF
64 #ifndef HAVE_GAI_STRERROR
72 { EAI_BADFLAGS, "Invalid flag used" },
73 { EAI_NONAME, "Host or service not found" },
74 { EAI_AGAIN, "Temporary name service failure" },
75 { EAI_FAIL, "Non-recoverable name service failure" },
76 { EAI_NODATA, "No data for host name" },
77 { EAI_FAMILY, "Unsupported address family" },
78 { EAI_SOCKTYPE, "Unsupported socket type" },
79 { EAI_SERVICE, "Incompatible service for socket type" },
80 { EAI_ADDRFAMILY, "Unavailable address family for host name" },
81 { EAI_MEMORY, "Memory allocation failure" },
82 { EAI_OVERFLOW, "Buffer overflow" },
83 { EAI_SYSTEM, "System error" },
87 static const char gai_unknownerr[] = "Unrecognized error number";
89 /****************************************************************************
90 * Converts an EAI_* error code into human readable english text.
91 ****************************************************************************/
92 const char *vlc_gai_strerror (int errnum)
94 for (unsigned i = 0; *gai_errlist[i].msg; i++)
95 if (errnum == gai_errlist[i].code)
96 return gai_errlist[i].msg;
98 return gai_unknownerr;
100 #else /* ifndef HAVE_GAI_STRERROR */
101 const char *vlc_gai_strerror (int errnum)
103 return gai_strerror (errnum);
107 #ifndef HAVE_GETNAMEINFO
108 #define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
111 * getnameinfo() non-thread-safe IPv4-only implementation,
112 * Address-family-independent address to hostname translation
113 * (reverse DNS lookup in case of IPv4).
115 * This is meant for use on old IP-enabled systems that are not IPv6-aware,
116 * and probably do not have getnameinfo(), but have the old gethostbyaddr()
119 * GNU C library 2.0.x is known to lack this function, even though it defines
124 stub_getnameinfo (const struct sockaddr *sa, socklen_t salen,
125 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags)
128 stub_getnameinfo (const struct sockaddr *sa, socklen_t salen,
129 char *host, int hostlen, char *serv, int servlen, int flags)
132 if (((size_t)salen < sizeof (struct sockaddr_in))
133 || (sa->sa_family != AF_INET))
135 else if (flags & (~_NI_MASK))
139 const struct sockaddr_in *addr;
141 addr = (const struct sockaddr_in *)sa;
145 /* host name resolution */
146 if (!(flags & NI_NUMERICHOST))
148 if (flags & NI_NAMEREQD)
152 /* inet_ntoa() is not thread-safe, do not use it */
153 uint32_t ipv4 = ntohl (addr->sin_addr.s_addr);
155 if (snprintf (host, hostlen, "%u.%u.%u.%u", ipv4 >> 24,
156 (ipv4 >> 16) & 0xff, (ipv4 >> 8) & 0xff,
157 ipv4 & 0xff) >= (int)hostlen)
163 if (snprintf (serv, servlen, "%u",
164 (unsigned int)ntohs (addr->sin_port)) >= (int)servlen)
171 #define getnameifo stub_getnameinfo
172 #endif /* if !HAVE_GETNAMEINFO */
174 #ifndef HAVE_GETADDRINFO
175 #define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
177 * Converts the current herrno error value into an EAI_* error code.
178 * That error code is normally returned by getnameinfo() or getaddrinfo().
181 gai_error_from_herrno (void)
189 # if (NO_ADDRESS != NO_DATA)
204 * This functions must be used to free the memory allocated by getaddrinfo().
207 static void WSAAPI stub_freeaddrinfo (struct addrinfo *res)
209 static void stub_freeaddrinfo (struct addrinfo *res)
214 free (res->ai_canonname);
222 * Internal function that builds an addrinfo struct.
224 static struct addrinfo *
225 makeaddrinfo (int af, int type, int proto,
226 const struct sockaddr *addr, size_t addrlen,
227 const char *canonname)
229 struct addrinfo *res;
231 res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
236 res->ai_socktype = type;
237 res->ai_protocol = proto;
238 res->ai_addrlen = addrlen;
239 res->ai_addr = malloc (addrlen);
240 res->ai_canonname = NULL;
243 if (res->ai_addr != NULL)
245 memcpy (res->ai_addr, addr, addrlen);
247 if (canonname != NULL)
249 res->ai_canonname = strdup (canonname);
250 if (res->ai_canonname != NULL)
251 return res; /* success ! */
258 vlc_freeaddrinfo (res);
263 static struct addrinfo *
264 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
266 struct sockaddr_in addr;
268 memset (&addr, 0, sizeof (addr));
269 addr.sin_family = AF_INET;
271 addr.sin_len = sizeof (addr);
273 addr.sin_port = port;
274 addr.sin_addr.s_addr = ip;
276 return makeaddrinfo (AF_INET, type, proto,
277 (struct sockaddr*)&addr, sizeof (addr), name);
282 * getaddrinfo() non-thread-safe IPv4-only implementation
283 * Address-family-independent hostname to address resolution.
285 * This is meant for IPv6-unaware systems that do probably not provide
286 * getaddrinfo(), but still have old function gethostbyname().
288 * Only UDP and TCP over IPv4 are supported here.
292 stub_getaddrinfo (const char *node, const char *service,
293 const struct addrinfo *hints, struct addrinfo **res)
296 stub_getaddrinfo (const char *node, const char *service,
297 const struct addrinfo *hints, struct addrinfo **res)
300 struct addrinfo *info;
303 int protocol = 0, flags = 0;
304 const char *name = NULL;
308 * Maybe you knew already that Winsock does not handle TCP/RST packets
309 * properly, so that when a TCP connection fails, it will wait until it
310 * times out even if the remote host did return a TCP/RST. However, it
311 * still sees the TCP/RST as the error code is 10061 instead of 10060.
312 * Basically, we have the stupid brainfucked behavior with DNS queries...
313 * When the recursive DNS server returns an error, Winsock waits about
314 * 2 seconds before it returns to the callers, even though it should know
315 * that is pointless. I'd like to know how come this hasn't been fixed
316 * for the past decade, or maybe not.
318 * Anyway, this is causing a severe delay when the SAP listener tries
319 * to resolve more than ten IPv6 numeric addresses. Modern systems will
320 * eventually realize that it is an IPv6 address, and won't try to resolve
321 * it as a IPv4 address via the Domain Name Service. Old systems
322 * (including Windows XP without the IPv6 stack) will not. It is normally
323 * not an issue as the DNS server usually returns an error very quickly.
324 * But it IS a severe issue on Windows, given the bug explained above.
325 * So here comes one more bug-to-bug Windows compatibility fix.
327 if ((node != NULL) && (strchr (node, ':') != NULL))
333 flags = hints->ai_flags;
335 if (flags & ~_AI_MASK)
337 /* only accept AF_INET and AF_UNSPEC */
338 if (hints->ai_family && (hints->ai_family != AF_INET))
341 /* protocol sanity check */
342 switch (hints->ai_socktype)
345 protocol = IPPROTO_TCP;
349 protocol = IPPROTO_UDP;
361 if (hints->ai_protocol && protocol
362 && (protocol != hints->ai_protocol))
371 if (flags & AI_PASSIVE)
372 ip = htonl (INADDR_ANY);
374 ip = htonl (INADDR_LOOPBACK);
377 if ((ip = inet_addr (node)) == INADDR_NONE)
379 struct hostent *entry = NULL;
381 /* hostname resolution */
382 if (!(flags & AI_NUMERICHOST))
383 entry = gethostbyname (node);
386 return gai_error_from_herrno ();
388 if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
391 ip = *((u_long *) entry->h_addr);
392 if (flags & AI_CANONNAME)
393 name = entry->h_name;
396 if ((flags & AI_CANONNAME) && (name == NULL))
399 /* service resolution */
407 d = strtoul (service, &end, 0);
408 if (end[0] || (d > 65535u))
411 port = htons ((u_short)d);
414 /* building results... */
415 if ((!protocol) || (protocol == IPPROTO_UDP))
417 info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
423 if (flags & AI_PASSIVE)
424 info->ai_flags |= AI_PASSIVE;
427 if ((!protocol) || (protocol == IPPROTO_TCP))
429 info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
435 info->ai_next = *res;
436 if (flags & AI_PASSIVE)
437 info->ai_flags |= AI_PASSIVE;
444 #define getaddrifo stub_getaddrinfo
446 #define freeaddrifo stub_freeaddrinfo
447 #endif /* if !HAVE_GETADDRINFO */
449 #if defined( WIN32 ) && !defined( UNDER_CE )
451 * Here is the kind of kludge you need to keep binary compatibility among
452 * varying OS versions...
454 typedef int (WSAAPI * GETNAMEINFO) ( const struct sockaddr FAR *, socklen_t,
455 char FAR *, DWORD, char FAR *, DWORD, int );
456 typedef int (WSAAPI * GETADDRINFO) (const char FAR *, const char FAR *,
457 const struct addrinfo FAR *,
458 struct addrinfo FAR * FAR *);
460 typedef void (WSAAPI * FREEADDRINFO) ( struct addrinfo FAR * );
462 static int WSAAPI _ws2_getnameinfo_bind ( const struct sockaddr FAR *, socklen_t,
463 char FAR *, DWORD, char FAR *, DWORD, int );
464 static int WSAAPI _ws2_getaddrinfo_bind (const char FAR *, const char FAR *,
465 const struct addrinfo FAR *,
466 struct addrinfo FAR * FAR *);
468 static GETNAMEINFO ws2_getnameinfo = _ws2_getnameinfo_bind;
469 static GETADDRINFO ws2_getaddrinfo = _ws2_getaddrinfo_bind;
470 static FREEADDRINFO ws2_freeaddrinfo;
472 static FARPROC ws2_find_api (LPCTSTR name)
476 HMODULE m = GetModuleHandle (TEXT("WS2_32"));
478 f = GetProcAddress (m, name);
482 /* Windows 2K IPv6 preview */
483 m = LoadLibrary (TEXT("WSHIP6"));
485 f = GetProcAddress (m, name);
491 static WSAAPI int _ws2_getnameinfo_bind( const struct sockaddr FAR * sa, socklen_t salen,
492 char FAR *host, DWORD hostlen, char FAR *serv, DWORD servlen, int flags )
494 GETNAMEINFO entry = (GETNAMEINFO)ws2_find_api (TEXT("getnameinfo"));
499 /* not found, use replacement API instead */
500 entry = stub_getnameinfo;
502 /* call API before replacing function pointer to avoid crash */
503 result = entry (sa, salen, host, hostlen, serv, servlen, flags);
504 ws2_getnameinfo = entry;
508 #define getnameinfo ws2_getnameinfo
510 static WSAAPI int _ws2_getaddrinfo_bind(const char FAR *node, const char FAR *service,
511 const struct addrinfo FAR *hints, struct addrinfo FAR * FAR *res)
514 FREEADDRINFO freentry;
517 entry = (GETADDRINFO)ws2_find_api (TEXT("getaddrinfo"));
518 freentry = (FREEADDRINFO)ws2_find_api (TEXT("freeaddrinfo"));
520 if ((entry == NULL) || (freentry == NULL))
522 /* not found, use replacement API instead */
523 entry = stub_getaddrinfo;
524 freentry = stub_freeaddrinfo;
526 /* call API before replacing function pointer to avoid crash */
527 result = entry (node, service, hints, res);
528 ws2_freeaddrinfo = freentry;
529 ws2_getaddrinfo = entry;
534 #define getaddrinfo ws2_getaddrinfo
535 #define freeaddrinfo ws2_freeaddrinfo
536 #define HAVE_GETADDRINFO
540 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
541 char *host, int hostlen, int *portnum, int flags )
543 char psz_servbuf[6], *psz_serv;
544 int i_servlen, i_val;
546 flags |= NI_NUMERICSERV;
547 if( portnum != NULL )
549 psz_serv = psz_servbuf;
550 i_servlen = sizeof( psz_servbuf );
558 i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
560 if( portnum != NULL )
561 *portnum = atoi( psz_serv );
568 * Resolves a host name to a list of socket addresses (like getaddrinfo()).
570 * @param p_this a VLC object
571 * @param node host name to resolve (encoded as UTF-8), or NULL
572 * @param i_port port number for the socket addresses
573 * @param p_hints parameters (see getaddrinfo() manual page)
574 * @param res pointer set to the resulting chained list.
575 * @return 0 on success, a getaddrinfo() error otherwise.
576 * On failure, *res is undefined. On success, it must be freed with
577 * vlc_freeaddrinfo().
579 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
580 int i_port, const struct addrinfo *p_hints,
581 struct addrinfo **res )
583 struct addrinfo hints;
584 char psz_buf[NI_MAXHOST], psz_service[6];
587 * In VLC, we always use port number as integer rather than strings
588 * for historical reasons (and portability).
590 if( ( i_port > 65535 ) || ( i_port < 0 ) )
592 msg_Err( p_this, "invalid port number %d specified", i_port );
596 /* cannot overflow */
597 snprintf( psz_service, 6, "%d", i_port );
599 /* Check if we have to force ipv4 or ipv6 */
600 memset (&hints, 0, sizeof (hints));
603 const int safe_flags =
619 hints.ai_family = p_hints->ai_family;
620 hints.ai_socktype = p_hints->ai_socktype;
621 hints.ai_protocol = p_hints->ai_protocol;
622 /* Unfortunately, some flags chang the layout of struct addrinfo, so
623 * they cannot be copied blindly from p_hints to &hints. Therefore, we
624 * only copy flags that we know for sure are "safe".
626 hints.ai_flags = p_hints->ai_flags & safe_flags;
629 /* We only ever use port *numbers* */
630 hints.ai_flags |= AI_NUMERICSERV;
632 if( hints.ai_family == AF_UNSPEC )
635 if (var_CreateGetBool (p_this, "ipv6"))
636 hints.ai_family = AF_INET6;
639 if (var_CreateGetBool (p_this, "ipv4"))
640 hints.ai_family = AF_INET;
645 * - accept "" as NULL
646 * - ignore square brackets
652 size_t len = strlen (node + 1);
653 if ((len <= sizeof (psz_buf)) && (node[len] == ']'))
656 memcpy (psz_buf, node + 1, len - 1);
657 psz_buf[len - 1] = '\0';
666 node = ToLocale (node);
669 * Winsock tries to resolve numerical IPv4 addresses as AAAA
670 * and IPv6 addresses as A... There comes the bug-to-bug fix.
672 if ((hints.ai_flags & AI_NUMERICHOST) == 0)
674 hints.ai_flags |= AI_NUMERICHOST;
675 ret = getaddrinfo (node, psz_service, &hints, res);
678 hints.ai_flags &= ~AI_NUMERICHOST;
682 /* Run-time I18n Domain Names support */
683 hints.ai_flags |= AI_IDN;
684 ret = getaddrinfo (node, psz_service, &hints, res);
685 if (ret != EAI_BADFLAGS)
687 /* IDN not available: disable and retry without it */
688 hints.ai_flags &= ~AI_IDN;
690 ret = getaddrinfo (node, psz_service, &hints, res);
698 void vlc_freeaddrinfo( struct addrinfo *infos )
700 freeaddrinfo (infos);
704 * inet_pton() replacement
706 int vlc_inet_pton (int af, const char *src, void *dst)
708 #ifndef HAVE_INET_PTON
709 /* Windows Vista has inet_pton(), but not XP. */
710 /* We have a pretty good example of abstraction inversion here... */
711 struct addrinfo hints = {
713 .ai_socktype = SOCK_DGRAM, /* make sure we have... */
714 .ai_protocol = IPPROTO_UDP, /* ...only one response */
715 .ai_flags = AI_NUMERICHOST,
718 if (getaddrinfo (src, NULL, &hints, &res))
727 data = &((const struct sockaddr_in *)res->ai_addr)->sin_addr;
728 len = sizeof (struct in_addr);
732 data = &((const struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
733 len = sizeof (struct in6_addr);
740 memcpy (dst, data, len);
743 #else /* HAVE_INET_PTON */
744 return inet_pton( af, src, dst );
745 #endif /* HAVE_INET_PTON */
749 * inet_ntop() replacement
751 const char *vlc_inet_ntop (int af, const void *src, char *dst, socklen_t cnt)
753 #ifndef HAVE_INET_NTOP
754 int ret = EAI_FAMILY;
761 struct sockaddr_in6 addr;
762 memset (&addr, 0, sizeof(addr));
763 addr.sin6_family = AF_INET6;
764 addr.sin6_addr = *(struct in6_addr *)src;
765 ret = getnameinfo ((struct sockaddr *)&addr, sizeof (addr),
766 dst, cnt, NULL, 0, NI_NUMERICHOST);
772 struct sockaddr_in addr;
773 memset(&addr, 0, sizeof(addr));
774 addr.sin_family = AF_INET;
775 addr.sin_addr = *(struct in_addr *)src;
776 ret = getnameinfo ((struct sockaddr *)&addr, sizeof (addr),
777 dst, cnt, NULL, 0, NI_NUMERICHOST);
780 return (ret == 0) ? dst : NULL;
781 #else /* HAVE_INET_NTOP */
782 return inet_ntop( af, src, dst, cnt );
783 #endif /* HAVE_INET_NTOP */