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>
31 #include <stddef.h> /* size_t */
32 #include <string.h> /* strlen(), memcpy(), memset(), strchr() */
33 #include <stdlib.h> /* malloc(), free(), strtoul() */
36 #ifdef HAVE_SYS_TYPES_H
37 # 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 getnameinfo (const struct sockaddr *sa, socklen_t salen,
123 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags)
126 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 #endif /* if !HAVE_GETNAMEINFO */
171 #ifndef HAVE_GETADDRINFO
172 #define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
174 * Converts the current herrno error value into an EAI_* error code.
175 * That error code is normally returned by getnameinfo() or getaddrinfo().
178 gai_error_from_herrno (void)
186 # if (NO_ADDRESS != NO_DATA)
201 * This functions must be used to free the memory allocated by getaddrinfo().
204 static void WSAAPI freeaddrinfo (struct addrinfo *res)
206 static void freeaddrinfo (struct addrinfo *res)
211 if (res->ai_canonname != NULL)
212 free (res->ai_canonname);
213 if (res->ai_addr != NULL)
215 if (res->ai_next != NULL)
223 * Internal function that builds an addrinfo struct.
225 static struct addrinfo *
226 makeaddrinfo (int af, int type, int proto,
227 const struct sockaddr *addr, size_t addrlen,
228 const char *canonname)
230 struct addrinfo *res;
232 res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
237 res->ai_socktype = type;
238 res->ai_protocol = proto;
239 res->ai_addrlen = addrlen;
240 res->ai_addr = malloc (addrlen);
241 res->ai_canonname = NULL;
244 if (res->ai_addr != NULL)
246 memcpy (res->ai_addr, addr, addrlen);
248 if (canonname != NULL)
250 res->ai_canonname = strdup (canonname);
251 if (res->ai_canonname != NULL)
252 return res; /* success ! */
259 vlc_freeaddrinfo (res);
264 static struct addrinfo *
265 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
267 struct sockaddr_in addr;
269 memset (&addr, 0, sizeof (addr));
270 addr.sin_family = AF_INET;
272 addr.sin_len = sizeof (addr);
274 addr.sin_port = port;
275 addr.sin_addr.s_addr = ip;
277 return makeaddrinfo (AF_INET, type, proto,
278 (struct sockaddr*)&addr, sizeof (addr), name);
283 * getaddrinfo() non-thread-safe IPv4-only implementation
284 * Address-family-independent hostname to address resolution.
286 * This is meant for IPv6-unaware systems that do probably not provide
287 * getaddrinfo(), but still have old function gethostbyname().
289 * Only UDP and TCP over IPv4 are supported here.
293 getaddrinfo (const char *node, const char *service,
294 const struct addrinfo *hints, struct addrinfo **res)
297 getaddrinfo (const char *node, const char *service,
298 const struct addrinfo *hints, struct addrinfo **res)
301 struct addrinfo *info;
304 int protocol = 0, flags = 0;
305 const char *name = NULL;
309 * Maybe you knew already that Winsock does not handle TCP/RST packets
310 * properly, so that when a TCP connection fails, it will wait until it
311 * times out even if the remote host did return a TCP/RST. However, it
312 * still sees the TCP/RST as the error code is 10061 instead of 10060.
313 * Basically, we have the stupid brainfucked behavior with DNS queries...
314 * When the recursive DNS server returns an error, Winsock waits about
315 * 2 seconds before it returns to the callers, even though it should know
316 * that is pointless. I'd like to know how come this hasn't been fixed
317 * for the past decade, or maybe not.
319 * Anyway, this is causing a severe delay when the SAP listener tries
320 * to resolve more than ten IPv6 numeric addresses. Modern systems will
321 * eventually realize that it is an IPv6 address, and won't try to resolve
322 * it as a IPv4 address via the Domain Name Service. Old systems
323 * (including Windows XP without the IPv6 stack) will not. It is normally
324 * not an issue as the DNS server usually returns an error very quickly.
325 * But it IS a severe issue on Windows, given the bug explained above.
326 * So here comes one more bug-to-bug Windows compatibility fix.
328 if ((node != NULL) && (strchr (node, ':') != NULL))
334 flags = hints->ai_flags;
336 if (flags & ~_AI_MASK)
338 /* only accept AF_INET and AF_UNSPEC */
339 if (hints->ai_family && (hints->ai_family != AF_INET))
342 /* protocol sanity check */
343 switch (hints->ai_socktype)
346 protocol = IPPROTO_TCP;
350 protocol = IPPROTO_UDP;
362 if (hints->ai_protocol && protocol
363 && (protocol != hints->ai_protocol))
372 if (flags & AI_PASSIVE)
373 ip = htonl (INADDR_ANY);
375 ip = htonl (INADDR_LOOPBACK);
378 if ((ip = inet_addr (node)) == INADDR_NONE)
380 struct hostent *entry = NULL;
382 /* hostname resolution */
383 if (!(flags & AI_NUMERICHOST))
384 entry = gethostbyname (node);
387 return gai_error_from_herrno ();
389 if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
392 ip = *((u_long *) entry->h_addr);
393 if (flags & AI_CANONNAME)
394 name = entry->h_name;
397 if ((flags & AI_CANONNAME) && (name == NULL))
400 /* service resolution */
408 d = strtoul (service, &end, 0);
409 if (end[0] || (d > 65535u))
412 port = htons ((u_short)d);
415 /* building results... */
416 if ((!protocol) || (protocol == IPPROTO_UDP))
418 info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
424 if (flags & AI_PASSIVE)
425 info->ai_flags |= AI_PASSIVE;
428 if ((!protocol) || (protocol == IPPROTO_TCP))
430 info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
436 info->ai_next = *res;
437 if (flags & AI_PASSIVE)
438 info->ai_flags |= AI_PASSIVE;
444 #endif /* if !HAVE_GETADDRINFO */
446 #if defined( WIN32 ) && !defined( UNDER_CE )
448 * Here is the kind of kludge you need to keep binary compatibility among
449 * varying OS versions...
451 typedef int (WSAAPI * GETNAMEINFO) ( const struct sockaddr FAR *, socklen_t,
452 char FAR *, DWORD, char FAR *, DWORD, int );
453 typedef int (WSAAPI * GETADDRINFO) (const char FAR *, const char FAR *,
454 const struct addrinfo FAR *,
455 struct addrinfo FAR * FAR *);
457 typedef void (WSAAPI * FREEADDRINFO) ( struct addrinfo FAR * );
459 static int WSAAPI _ws2_getnameinfo_bind ( const struct sockaddr FAR *, socklen_t,
460 char FAR *, DWORD, char FAR *, DWORD, int );
461 static int WSAAPI _ws2_getaddrinfo_bind (const char FAR *, const char FAR *,
462 const struct addrinfo FAR *,
463 struct addrinfo FAR * FAR *);
465 static GETNAMEINFO ws2_getnameinfo = _ws2_getnameinfo_bind;
466 static GETADDRINFO ws2_getaddrinfo = _ws2_getaddrinfo_bind;
467 static FREEADDRINFO ws2_freeaddrinfo;
469 static FARPROC ws2_find_api (LPCTSTR name)
473 HMODULE m = GetModuleHandle (TEXT("WS2_32"));
475 f = GetProcAddress (m, name);
479 /* Windows 2K IPv6 preview */
480 m = LoadLibrary (TEXT("WSHIP6"));
482 f = GetProcAddress (m, name);
488 static WSAAPI int _ws2_getnameinfo_bind( const struct sockaddr FAR * sa, socklen_t salen,
489 char FAR *host, DWORD hostlen, char FAR *serv, DWORD servlen, int flags )
491 GETNAMEINFO entry = (GETNAMEINFO)ws2_find_api (TEXT("getnameinfo"));
496 /* not found, use replacement API instead */
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 */
522 freentry = 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
539 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
540 char *host, int hostlen, int *portnum, int flags )
542 char psz_servbuf[6], *psz_serv;
543 int i_servlen, i_val;
545 flags |= NI_NUMERICSERV;
546 if( portnum != NULL )
548 psz_serv = psz_servbuf;
549 i_servlen = sizeof( psz_servbuf );
557 i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
559 if( portnum != NULL )
560 *portnum = atoi( psz_serv );
566 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
567 int i_port, const struct addrinfo *p_hints,
568 struct addrinfo **res )
570 struct addrinfo hints;
571 char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
574 * In VLC, we always use port number as integer rather than strings
575 * for historical reasons (and portability).
577 if( ( i_port > 65535 ) || ( i_port < 0 ) )
579 msg_Err( p_this, "invalid port number %d specified", i_port );
583 /* cannot overflow */
584 snprintf( psz_service, 6, "%d", i_port );
586 /* Check if we have to force ipv4 or ipv6 */
587 memset (&hints, 0, sizeof (hints));
590 const int safe_flags =
606 hints.ai_family = p_hints->ai_family;
607 hints.ai_socktype = p_hints->ai_socktype;
608 hints.ai_protocol = p_hints->ai_protocol;
609 /* Unfortunately, some flags chang the layout of struct addrinfo, so
610 * they cannot be copied blindly from p_hints to &hints. Therefore, we
611 * only copy flags that we know for sure are "safe".
613 hints.ai_flags = p_hints->ai_flags & safe_flags;
616 /* We only ever use port *numbers* */
617 hints.ai_flags |= AI_NUMERICSERV;
619 if( hints.ai_family == AF_UNSPEC )
622 if (var_CreateGetBool (p_this, "ipv6"))
623 hints.ai_family = AF_INET6;
626 if (var_CreateGetBool (p_this, "ipv4"))
627 hints.ai_family = AF_INET;
632 * - accept "" as NULL
633 * - ignore square brackets
635 if( ( node == NULL ) || (node[0] == '\0' ) )
641 strlcpy( psz_buf, node, NI_MAXHOST );
645 if( psz_buf[0] == '[' )
649 ptr = strrchr( psz_buf, ']' );
650 if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
660 * Winsock tries to resolve numerical IPv4 addresses as AAAA
661 * and IPv6 addresses as A... There comes the bug-to-bug fix.
663 if ((hints.ai_flags & AI_NUMERICHOST) == 0)
665 hints.ai_flags |= AI_NUMERICHOST;
667 if (getaddrinfo (psz_node, psz_service, &hints, res) == 0)
670 hints.ai_flags &= ~AI_NUMERICHOST;
674 /* Run-time I18n Domain Names support */
675 hints.ai_flags |= AI_IDN;
676 int ret = getaddrinfo (psz_node, psz_service, &hints, res);
677 if (ret != EAI_BADFLAGS)
680 /* IDN not available: disable and retry without it */
681 hints.ai_flags &= ~AI_IDN;
683 return getaddrinfo (psz_node, psz_service, &hints, res);
687 void vlc_freeaddrinfo( struct addrinfo *infos )
689 freeaddrinfo (infos);