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 #include <sys/types.h>
39 #ifdef HAVE_ARPA_INET_H
40 # include <arpa/inet.h>
42 #ifdef HAVE_NETINET_IN_H
43 # include <netinet/in.h>
49 #include <vlc_network.h>
52 # define NO_ADDRESS NO_DATA
55 # define INADDR_NONE 0xFFFFFFFF
62 #ifndef HAVE_GAI_STRERROR
70 { EAI_BADFLAGS, "Invalid flag used" },
71 { EAI_NONAME, "Host or service not found" },
72 { EAI_AGAIN, "Temporary name service failure" },
73 { EAI_FAIL, "Non-recoverable name service failure" },
74 { EAI_NODATA, "No data for host name" },
75 { EAI_FAMILY, "Unsupported address family" },
76 { EAI_SOCKTYPE, "Unsupported socket type" },
77 { EAI_SERVICE, "Incompatible service for socket type" },
78 { EAI_ADDRFAMILY, "Unavailable address family for host name" },
79 { EAI_MEMORY, "Memory allocation failure" },
80 { EAI_OVERFLOW, "Buffer overflow" },
81 { EAI_SYSTEM, "System error" },
85 static const char gai_unknownerr[] = "Unrecognized error number";
87 /****************************************************************************
88 * Converts an EAI_* error code into human readable english text.
89 ****************************************************************************/
90 const char *vlc_gai_strerror (int errnum)
92 for (unsigned i = 0; *gai_errlist[i].msg; i++)
93 if (errnum == gai_errlist[i].code)
94 return gai_errlist[i].msg;
96 return gai_unknownerr;
98 #else /* ifndef HAVE_GAI_STRERROR */
99 const char *vlc_gai_strerror (int errnum)
101 return gai_strerror (errnum);
105 #ifndef HAVE_GETNAMEINFO
106 #define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
109 * getnameinfo() non-thread-safe IPv4-only implementation,
110 * Address-family-independent address to hostname translation
111 * (reverse DNS lookup in case of IPv4).
113 * This is meant for use on old IP-enabled systems that are not IPv6-aware,
114 * and probably do not have getnameinfo(), but have the old gethostbyaddr()
117 * GNU C library 2.0.x is known to lack this function, even though it defines
122 stub_getnameinfo (const struct sockaddr *sa, socklen_t salen,
123 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags)
126 stub_getnameinfo (const struct sockaddr *sa, socklen_t salen,
127 char *host, int hostlen, char *serv, int servlen, int flags)
130 if (((size_t)salen < sizeof (struct sockaddr_in))
131 || (sa->sa_family != AF_INET))
133 else if (flags & (~_NI_MASK))
137 const struct sockaddr_in *addr;
139 addr = (const struct sockaddr_in *)sa;
143 /* host name resolution */
144 if (!(flags & NI_NUMERICHOST))
146 if (flags & NI_NAMEREQD)
150 /* inet_ntoa() is not thread-safe, do not use it */
151 uint32_t ipv4 = ntohl (addr->sin_addr.s_addr);
153 if (snprintf (host, hostlen, "%u.%u.%u.%u", ipv4 >> 24,
154 (ipv4 >> 16) & 0xff, (ipv4 >> 8) & 0xff,
155 ipv4 & 0xff) >= (int)hostlen)
161 if (snprintf (serv, servlen, "%u",
162 (unsigned int)ntohs (addr->sin_port)) >= (int)servlen)
169 #define getnameifo stub_getnameinfo
170 #endif /* if !HAVE_GETNAMEINFO */
172 #ifndef HAVE_GETADDRINFO
173 #define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
175 * Converts the current herrno error value into an EAI_* error code.
176 * That error code is normally returned by getnameinfo() or getaddrinfo().
179 gai_error_from_herrno (void)
187 # if (NO_ADDRESS != NO_DATA)
202 * This functions must be used to free the memory allocated by getaddrinfo().
205 static void WSAAPI stub_freeaddrinfo (struct addrinfo *res)
207 static void stub_freeaddrinfo (struct addrinfo *res)
212 free (res->ai_canonname);
220 * Internal function that builds an addrinfo struct.
222 static struct addrinfo *
223 makeaddrinfo (int af, int type, int proto,
224 const struct sockaddr *addr, size_t addrlen,
225 const char *canonname)
227 struct addrinfo *res;
229 res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
234 res->ai_socktype = type;
235 res->ai_protocol = proto;
236 res->ai_addrlen = addrlen;
237 res->ai_addr = malloc (addrlen);
238 res->ai_canonname = NULL;
241 if (res->ai_addr != NULL)
243 memcpy (res->ai_addr, addr, addrlen);
245 if (canonname != NULL)
247 res->ai_canonname = strdup (canonname);
248 if (res->ai_canonname != NULL)
249 return res; /* success ! */
256 vlc_freeaddrinfo (res);
261 static struct addrinfo *
262 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
264 struct sockaddr_in addr;
266 memset (&addr, 0, sizeof (addr));
267 addr.sin_family = AF_INET;
269 addr.sin_len = sizeof (addr);
271 addr.sin_port = port;
272 addr.sin_addr.s_addr = ip;
274 return makeaddrinfo (AF_INET, type, proto,
275 (struct sockaddr*)&addr, sizeof (addr), name);
280 * getaddrinfo() non-thread-safe IPv4-only implementation
281 * Address-family-independent hostname to address resolution.
283 * This is meant for IPv6-unaware systems that do probably not provide
284 * getaddrinfo(), but still have old function gethostbyname().
286 * Only UDP and TCP over IPv4 are supported here.
290 stub_getaddrinfo (const char *node, const char *service,
291 const struct addrinfo *hints, struct addrinfo **res)
294 stub_getaddrinfo (const char *node, const char *service,
295 const struct addrinfo *hints, struct addrinfo **res)
298 struct addrinfo *info;
301 int protocol = 0, flags = 0;
302 const char *name = NULL;
306 * Maybe you knew already that Winsock does not handle TCP/RST packets
307 * properly, so that when a TCP connection fails, it will wait until it
308 * times out even if the remote host did return a TCP/RST. However, it
309 * still sees the TCP/RST as the error code is 10061 instead of 10060.
310 * Basically, we have the stupid brainfucked behavior with DNS queries...
311 * When the recursive DNS server returns an error, Winsock waits about
312 * 2 seconds before it returns to the callers, even though it should know
313 * that is pointless. I'd like to know how come this hasn't been fixed
314 * for the past decade, or maybe not.
316 * Anyway, this is causing a severe delay when the SAP listener tries
317 * to resolve more than ten IPv6 numeric addresses. Modern systems will
318 * eventually realize that it is an IPv6 address, and won't try to resolve
319 * it as a IPv4 address via the Domain Name Service. Old systems
320 * (including Windows XP without the IPv6 stack) will not. It is normally
321 * not an issue as the DNS server usually returns an error very quickly.
322 * But it IS a severe issue on Windows, given the bug explained above.
323 * So here comes one more bug-to-bug Windows compatibility fix.
325 if ((node != NULL) && (strchr (node, ':') != NULL))
331 flags = hints->ai_flags;
333 if (flags & ~_AI_MASK)
335 /* only accept AF_INET and AF_UNSPEC */
336 if (hints->ai_family && (hints->ai_family != AF_INET))
339 /* protocol sanity check */
340 switch (hints->ai_socktype)
343 protocol = IPPROTO_TCP;
347 protocol = IPPROTO_UDP;
359 if (hints->ai_protocol && protocol
360 && (protocol != hints->ai_protocol))
369 if (flags & AI_PASSIVE)
370 ip = htonl (INADDR_ANY);
372 ip = htonl (INADDR_LOOPBACK);
375 if ((ip = inet_addr (node)) == INADDR_NONE)
377 struct hostent *entry = NULL;
379 /* hostname resolution */
380 if (!(flags & AI_NUMERICHOST))
381 entry = gethostbyname (node);
384 return gai_error_from_herrno ();
386 if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
389 ip = *((u_long *) entry->h_addr);
390 if (flags & AI_CANONNAME)
391 name = entry->h_name;
394 if ((flags & AI_CANONNAME) && (name == NULL))
397 /* service resolution */
405 d = strtoul (service, &end, 0);
406 if (end[0] || (d > 65535u))
409 port = htons ((u_short)d);
412 /* building results... */
413 if ((!protocol) || (protocol == IPPROTO_UDP))
415 info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
421 if (flags & AI_PASSIVE)
422 info->ai_flags |= AI_PASSIVE;
425 if ((!protocol) || (protocol == IPPROTO_TCP))
427 info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
433 info->ai_next = *res;
434 if (flags & AI_PASSIVE)
435 info->ai_flags |= AI_PASSIVE;
442 #define getaddrifo stub_getaddrinfo
444 #define freeaddrifo stub_freeaddrinfo
445 #endif /* if !HAVE_GETADDRINFO */
447 #if defined( WIN32 ) && !defined( UNDER_CE )
449 * Here is the kind of kludge you need to keep binary compatibility among
450 * varying OS versions...
452 typedef int (WSAAPI * GETNAMEINFO) ( const struct sockaddr FAR *, socklen_t,
453 char FAR *, DWORD, char FAR *, DWORD, int );
454 typedef int (WSAAPI * GETADDRINFO) (const char FAR *, const char FAR *,
455 const struct addrinfo FAR *,
456 struct addrinfo FAR * FAR *);
458 typedef void (WSAAPI * FREEADDRINFO) ( struct addrinfo FAR * );
460 static int WSAAPI _ws2_getnameinfo_bind ( const struct sockaddr FAR *, socklen_t,
461 char FAR *, DWORD, char FAR *, DWORD, int );
462 static int WSAAPI _ws2_getaddrinfo_bind (const char FAR *, const char FAR *,
463 const struct addrinfo FAR *,
464 struct addrinfo FAR * FAR *);
466 static GETNAMEINFO ws2_getnameinfo = _ws2_getnameinfo_bind;
467 static GETADDRINFO ws2_getaddrinfo = _ws2_getaddrinfo_bind;
468 static FREEADDRINFO ws2_freeaddrinfo;
470 static FARPROC ws2_find_api (LPCTSTR name)
474 HMODULE m = GetModuleHandle (TEXT("WS2_32"));
476 f = GetProcAddress (m, name);
480 /* Windows 2K IPv6 preview */
481 m = LoadLibrary (TEXT("WSHIP6"));
483 f = GetProcAddress (m, name);
489 static WSAAPI int _ws2_getnameinfo_bind( const struct sockaddr FAR * sa, socklen_t salen,
490 char FAR *host, DWORD hostlen, char FAR *serv, DWORD servlen, int flags )
492 GETNAMEINFO entry = (GETNAMEINFO)ws2_find_api (TEXT("getnameinfo"));
497 /* not found, use replacement API instead */
498 entry = stub_getnameinfo;
500 /* call API before replacing function pointer to avoid crash */
501 result = entry (sa, salen, host, hostlen, serv, servlen, flags);
502 ws2_getnameinfo = entry;
506 #define getnameinfo ws2_getnameinfo
508 static WSAAPI int _ws2_getaddrinfo_bind(const char FAR *node, const char FAR *service,
509 const struct addrinfo FAR *hints, struct addrinfo FAR * FAR *res)
512 FREEADDRINFO freentry;
515 entry = (GETADDRINFO)ws2_find_api (TEXT("getaddrinfo"));
516 freentry = (FREEADDRINFO)ws2_find_api (TEXT("freeaddrinfo"));
518 if ((entry == NULL) || (freentry == NULL))
520 /* not found, use replacement API instead */
521 entry = stub_getaddrinfo;
522 freentry = stub_freeaddrinfo;
524 /* call API before replacing function pointer to avoid crash */
525 result = entry (node, service, hints, res);
526 ws2_freeaddrinfo = freentry;
527 ws2_getaddrinfo = entry;
532 #define getaddrinfo ws2_getaddrinfo
533 #define freeaddrinfo ws2_freeaddrinfo
534 #define HAVE_GETADDRINFO
538 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
539 char *host, int hostlen, int *portnum, int flags )
541 char psz_servbuf[6], *psz_serv;
542 int i_servlen, i_val;
544 flags |= NI_NUMERICSERV;
545 if( portnum != NULL )
547 psz_serv = psz_servbuf;
548 i_servlen = sizeof( psz_servbuf );
556 i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
558 if( portnum != NULL )
559 *portnum = atoi( psz_serv );
566 * Resolves a host name to a list of socket addresses (like getaddrinfo()).
568 * @param p_this a VLC object
569 * @param node host name to resolve (encoded as UTF-8), or NULL
570 * @param i_port port number for the socket addresses
571 * @param p_hints parameters (see getaddrinfo() manual page)
572 * @param res pointer set to the resulting chained list.
573 * @return 0 on success, a getaddrinfo() error otherwise.
574 * On failure, *res is undefined. On success, it must be freed with
575 * vlc_freeaddrinfo().
577 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
578 int i_port, const struct addrinfo *p_hints,
579 struct addrinfo **res )
581 struct addrinfo hints;
582 char psz_buf[NI_MAXHOST], psz_service[6];
585 * In VLC, we always use port number as integer rather than strings
586 * for historical reasons (and portability).
588 if( ( i_port > 65535 ) || ( i_port < 0 ) )
590 msg_Err( p_this, "invalid port number %d specified", i_port );
594 /* cannot overflow */
595 snprintf( psz_service, 6, "%d", i_port );
597 /* Check if we have to force ipv4 or ipv6 */
598 memset (&hints, 0, sizeof (hints));
601 const int safe_flags =
617 hints.ai_family = p_hints->ai_family;
618 hints.ai_socktype = p_hints->ai_socktype;
619 hints.ai_protocol = p_hints->ai_protocol;
620 /* Unfortunately, some flags chang the layout of struct addrinfo, so
621 * they cannot be copied blindly from p_hints to &hints. Therefore, we
622 * only copy flags that we know for sure are "safe".
624 hints.ai_flags = p_hints->ai_flags & safe_flags;
627 /* We only ever use port *numbers* */
628 hints.ai_flags |= AI_NUMERICSERV;
630 if( hints.ai_family == AF_UNSPEC )
633 if (var_CreateGetBool (p_this, "ipv6"))
634 hints.ai_family = AF_INET6;
637 if (var_CreateGetBool (p_this, "ipv4"))
638 hints.ai_family = AF_INET;
643 * - accept "" as NULL
644 * - ignore square brackets
650 size_t len = strlen (node + 1);
651 if ((len <= sizeof (psz_buf)) && (node[len] == ']'))
654 memcpy (psz_buf, node + 1, len - 1);
655 psz_buf[len - 1] = '\0';
664 node = ToLocale (node);
667 * Winsock tries to resolve numerical IPv4 addresses as AAAA
668 * and IPv6 addresses as A... There comes the bug-to-bug fix.
670 if ((hints.ai_flags & AI_NUMERICHOST) == 0)
672 hints.ai_flags |= AI_NUMERICHOST;
673 ret = getaddrinfo (node, psz_service, &hints, res);
676 hints.ai_flags &= ~AI_NUMERICHOST;
680 /* Run-time I18n Domain Names support */
681 hints.ai_flags |= AI_IDN;
682 ret = getaddrinfo (node, psz_service, &hints, res);
683 if (ret != EAI_BADFLAGS)
685 /* IDN not available: disable and retry without it */
686 hints.ai_flags &= ~AI_IDN;
688 ret = getaddrinfo (node, psz_service, &hints, res);
690 #if defined(AI_IDN) || defined(WIN32)
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 */