1 /*****************************************************************************
2 * getaddrinfo.c: getaddrinfo/getnameinfo replacement functions
3 *****************************************************************************
4 * Copyright (C) 2005 the VideoLAN team
5 * Copyright (C) 2002-2004 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 *****************************************************************************/
27 #include <stddef.h> /* size_t */
28 #include <string.h> /* strlen(), memcpy(), memset(), strchr() */
29 #include <stdlib.h> /* malloc(), free(), strtoul() */
32 #ifdef HAVE_SYS_TYPES_H
33 # include <sys/types.h>
35 #ifdef HAVE_ARPA_INET_H
36 # include <arpa/inet.h>
38 #ifdef HAVE_NETINET_IN_H
39 # include <netinet/in.h>
45 #include <vlc_network.h>
48 # define NO_ADDRESS NO_DATA
51 # define INADDR_NONE 0xFFFFFFFF
57 # define EAI_OVERFLOW -12 /* Argument buffer overflow. */
60 #define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
62 #define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
65 #ifndef HAVE_GAI_STRERROR
70 } const __gai_errlist[] =
73 { EAI_BADFLAGS, "Invalid flag used" },
74 { EAI_NONAME, "Host or service not found" },
75 { EAI_AGAIN, "Temporary name service failure" },
76 { EAI_FAIL, "Non-recoverable name service failure" },
77 { EAI_NODATA, "No data for host name" },
78 { EAI_FAMILY, "Unsupported address family" },
79 { EAI_SOCKTYPE, "Unsupported socket type" },
80 { EAI_SERVICE, "Incompatible service for socket type" },
81 { EAI_ADDRFAMILY, "Unavailable address family for host name" },
82 { EAI_MEMORY, "Memory allocation failure" },
83 { EAI_OVERFLOW, "Buffer overflow" },
84 { EAI_SYSTEM, "System error" },
88 static const char *__gai_unknownerr = "Unrecognized error number";
90 /****************************************************************************
91 * Converts an EAI_* error code into human readable english text.
92 ****************************************************************************/
93 const char *vlc_gai_strerror( int errnum )
97 for (i = 0; __gai_errlist[i].msg != NULL; i++)
98 if (errnum == __gai_errlist[i].code)
99 return __gai_errlist[i].msg;
101 return __gai_unknownerr;
103 # undef _EAI_POSITIVE_MAX
104 #else /* ifndef HAVE_GAI_STRERROR */
105 const char *vlc_gai_strerror( int errnum )
107 return gai_strerror( errnum );
111 #if !(defined (HAVE_GETNAMEINFO) && defined (HAVE_GETADDRINFO))
113 * Converts the current herrno error value into an EAI_* error code.
114 * That error code is normally returned by getnameinfo() or getaddrinfo().
117 gai_error_from_herrno( void )
125 # if (NO_ADDRESS != NO_DATA)
138 #endif /* if !(HAVE_GETNAMEINFO && HAVE_GETADDRINFO) */
140 #ifndef HAVE_GETNAMEINFO
142 * getnameinfo() non-thread-safe IPv4-only implementation,
143 * Address-family-independant address to hostname translation
144 * (reverse DNS lookup in case of IPv4).
146 * This is meant for use on old IP-enabled systems that are not IPv6-aware,
147 * and probably do not have getnameinfo(), but have the old gethostbyaddr()
150 * GNU C library 2.0.x is known to lack this function, even though it defines
154 __getnameinfo( const struct sockaddr *sa, socklen_t salen,
155 char *host, int hostlen, char *serv, int servlen, int flags )
157 if (((unsigned)salen < sizeof (struct sockaddr_in))
158 || (sa->sa_family != AF_INET))
160 else if (flags & (~_NI_MASK))
164 const struct sockaddr_in *addr;
166 addr = (const struct sockaddr_in *)sa;
170 /* host name resolution */
171 if (!(flags & NI_NUMERICHOST))
173 if (flags & NI_NAMEREQD)
177 /* inet_ntoa() is not thread-safe, do not use it */
178 uint32_t ipv4 = ntohl (addr->sin_addr.s_addr);
180 if (snprintf (host, hostlen, "%u.%u.%u.%u", ipv4 >> 24,
181 (ipv4 >> 16) & 0xff, (ipv4 >> 8) & 0xff,
182 ipv4 & 0xff) >= hostlen)
188 if (snprintf (serv, servlen, "%u",
189 (unsigned int)ntohs (addr->sin_port)) >= servlen)
196 #endif /* if !HAVE_GETNAMEINFO */
198 #if defined( WIN32 ) && !defined( UNDER_CE )
200 * Here is the kind of kludge you need to keep binary compatibility among
201 * varying OS versions...
203 typedef int (CALLBACK * GETNAMEINFO) ( const struct sockaddr*, socklen_t,
204 char*, DWORD, char*, DWORD, int );
205 typedef int (CALLBACK * GETADDRINFO) (const char *, const char *,
206 const struct addrinfo *,
209 typedef void (CALLBACK * FREEADDRINFO) ( struct addrinfo * );
212 static WINAPI int _ws2_getnameinfo_bind( const struct sockaddr *sa, socklen_t salen,
213 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags );
215 static WINAPI int _ws2_getaddrinfo_bind(const char *node, const char *service,
216 const struct addrinfo *hints, struct addrinfo **res);
218 static WINAPI void _ws2_freeaddrinfo_bind( struct addrinfo *infos );
220 static GETNAMEINFO ws2_getnameinfo = _ws2_getnameinfo_bind;
221 static GETADDRINFO ws2_getaddrinfo = _ws2_getaddrinfo_bind;
222 static FREEADDRINFO ws2_freeaddrinfo = _ws2_freeaddrinfo_bind;
224 static int _ws2_find_ipv6_api(void)
226 /* For Windows XP and above, IPv6 stack is in WS2_32.DLL */
227 HINSTANCE module = LoadLibrary( "ws2_32.dll" );
230 ws2_getnameinfo = (GETNAMEINFO)GetProcAddress( module, "getnameinfo" );
231 ws2_getaddrinfo = (GETADDRINFO)GetProcAddress( module, "getaddrinfo" );
232 ws2_freeaddrinfo = (FREEADDRINFO)GetProcAddress( module, "freeaddrinfo" );
233 if( ws2_getnameinfo && ws2_getaddrinfo && ws2_freeaddrinfo )
238 FreeLibrary( module );
240 /* For Windows 2000 and below, try IPv6 stack in in WSHIP6.DLL */
241 module = LoadLibrary( "wship6.dll" );
244 ws2_getnameinfo = (GETNAMEINFO)GetProcAddress( module, "getnameinfo" );
245 ws2_getaddrinfo = (GETADDRINFO)GetProcAddress( module, "getaddrinfo" );
246 ws2_freeaddrinfo = (FREEADDRINFO)GetProcAddress( module, "freeaddrinfo" );
247 if( ws2_getnameinfo && ws2_getaddrinfo && ws2_freeaddrinfo )
252 FreeLibrary( module );
259 static WINAPI int _ws2_getnameinfo_bind( const struct sockaddr *sa, socklen_t salen,
260 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags )
262 if( _ws2_find_ipv6_api() )
264 return ws2_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
266 /* return a possible error if API is not found */
267 WSASetLastError(WSAHOST_NOT_FOUND);
268 return WSAHOST_NOT_FOUND;
271 static WINAPI int _ws2_getaddrinfo_bind(const char *node, const char *service,
272 const struct addrinfo *hints, struct addrinfo **res)
274 if( _ws2_find_ipv6_api() )
276 return ws2_getaddrinfo(node, service, hints, res);
278 /* return a possible error if API is not found */
279 WSASetLastError(WSAHOST_NOT_FOUND);
280 return WSAHOST_NOT_FOUND;
283 static WINAPI void _ws2_freeaddrinfo_bind( struct addrinfo *infos )
285 if( _ws2_find_ipv6_api() )
287 ws2_freeaddrinfo(infos);
293 #ifndef HAVE_GETADDRINFO
295 * This functions must be used to free the memory allocated by getaddrinfo().
298 __freeaddrinfo (struct addrinfo *res)
302 if (res->ai_canonname != NULL)
303 free (res->ai_canonname);
304 if (res->ai_addr != NULL)
306 if (res->ai_next != NULL)
314 * Internal function that builds an addrinfo struct.
316 static struct addrinfo *
317 makeaddrinfo (int af, int type, int proto,
318 const struct sockaddr *addr, size_t addrlen,
319 const char *canonname)
321 struct addrinfo *res;
323 res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
328 res->ai_socktype = type;
329 res->ai_protocol = proto;
330 res->ai_addrlen = addrlen;
331 res->ai_addr = malloc (addrlen);
332 res->ai_canonname = NULL;
335 if (res->ai_addr != NULL)
337 memcpy (res->ai_addr, addr, addrlen);
339 if (canonname != NULL)
341 res->ai_canonname = strdup (canonname);
342 if (res->ai_canonname != NULL)
343 return res; /* success ! */
350 vlc_freeaddrinfo (res);
355 static struct addrinfo *
356 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
358 struct sockaddr_in addr;
360 memset (&addr, 0, sizeof (addr));
361 addr.sin_family = AF_INET;
363 addr.sin_len = sizeof (addr);
365 addr.sin_port = port;
366 addr.sin_addr.s_addr = ip;
368 return makeaddrinfo (AF_INET, type, proto,
369 (struct sockaddr*)&addr, sizeof (addr), name);
374 * getaddrinfo() non-thread-safe IPv4-only implementation
375 * Address-family-independant hostname to address resolution.
377 * This is meant for IPv6-unaware systems that do probably not provide
378 * getaddrinfo(), but still have old function gethostbyname().
380 * Only UDP and TCP over IPv4 are supported here.
383 __getaddrinfo (const char *node, const char *service,
384 const struct addrinfo *hints, struct addrinfo **res)
386 struct addrinfo *info;
389 int protocol = 0, flags = 0;
390 const char *name = NULL;
394 * Maybe you knew already that Winsock does not handle TCP/RST packets
395 * properly, so that when a TCP connection fails, it will wait until it
396 * times out even if the remote host did return a TCP/RST. However, it
397 * still sees the TCP/RST as the error code is 10061 instead of 10060.
398 * Basically, we have the stupid brainfucked behavior with DNS queries...
399 * When the recursive DNS server returns an error, Winsock waits about
400 * 2 seconds before it returns to the callers, even though it should know
401 * that is pointless. I'd like to know how come this hasn't been fixed
402 * for the past decade, or maybe not.
404 * Anyway, this is causing a severe delay when the SAP listener tries
405 * to resolve more than ten IPv6 numeric addresses. Modern systems will
406 * eventually realize that it is an IPv6 address, and won't try to resolve
407 * it as a IPv4 address via the Domain Name Service. Old systems
408 * (including Windows XP without the IPv6 stack) will not. It is normally
409 * not an issue as the DNS server usually returns an error very quickly.
410 * But it IS a severe issue on Windows, given the bug explained above.
411 * So here comes one more bug-to-bug Windows compatibility fix.
413 if ((node != NULL) && (strchr (node, ':') != NULL))
419 flags = hints->ai_flags;
421 if (flags & ~_AI_MASK)
423 /* only accept AF_INET and AF_UNSPEC */
424 if (hints->ai_family && (hints->ai_family != AF_INET))
427 /* protocol sanity check */
428 switch (hints->ai_socktype)
431 protocol = IPPROTO_TCP;
435 protocol = IPPROTO_UDP;
447 if (hints->ai_protocol && protocol
448 && (protocol != hints->ai_protocol))
457 if (flags & AI_PASSIVE)
458 ip = htonl (INADDR_ANY);
460 ip = htonl (INADDR_LOOPBACK);
463 if ((ip = inet_addr (node)) == INADDR_NONE)
465 struct hostent *entry = NULL;
467 /* hostname resolution */
468 if (!(flags & AI_NUMERICHOST))
469 entry = gethostbyname (node);
474 if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
477 ip = *((u_long *) entry->h_addr);
478 if (flags & AI_CANONNAME)
479 name = entry->h_name;
482 if ((flags & AI_CANONNAME) && (name == NULL))
485 /* service resolution */
493 d = strtoul (service, &end, 0);
494 if (end[0] /* service is not a number */
497 struct servent *entry;
498 const char *protoname;
514 entry = getservbyname (service, protoname);
518 port = entry->s_port;
521 port = htons ((u_short)d);
524 /* building results... */
525 if ((!protocol) || (protocol == IPPROTO_UDP))
527 info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
533 if (flags & AI_PASSIVE)
534 info->ai_flags |= AI_PASSIVE;
537 if ((!protocol) || (protocol == IPPROTO_TCP))
539 info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
545 info->ai_next = *res;
546 if (flags & AI_PASSIVE)
547 info->ai_flags |= AI_PASSIVE;
553 #endif /* if !HAVE_GETADDRINFO */
556 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
557 char *host, int hostlen, int *portnum, int flags )
559 char psz_servbuf[6], *psz_serv;
560 int i_servlen, i_val;
562 flags |= NI_NUMERICSERV;
563 if( portnum != NULL )
565 psz_serv = psz_servbuf;
566 i_servlen = sizeof( psz_servbuf );
573 #if defined( WIN32 ) && !defined( UNDER_CE )
574 i_val = ws2_getnameinfo( sa, salen, host, hostlen, psz_serv,
577 #if defined( HAVE_GETNAMEINFO ) || defined( UNDER_CE )
578 i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
581 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
582 static vlc_value_t lock;
584 /* my getnameinfo implementation is not thread-safe as it uses
585 * gethostbyaddr and the likes */
586 vlc_mutex_lock( lock.p_address );
588 # warning FIXME : This is not thread-safe!
590 i_val = __getnameinfo( sa, salen, host, hostlen, psz_serv, i_servlen,
592 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
593 vlc_mutex_unlock( lock.p_address );
598 if( portnum != NULL )
599 *portnum = atoi( psz_serv );
605 /* TODO: support for setting sin6_scope_id */
606 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
607 int i_port, const struct addrinfo *p_hints,
608 struct addrinfo **res )
610 struct addrinfo hints;
611 char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
614 * In VLC, we always use port number as integer rather than strings
615 * for historical reasons (and portability).
617 if( ( i_port > 65535 ) || ( i_port < 0 ) )
619 msg_Err( p_this, "invalid port number %d specified", i_port );
623 /* cannot overflow */
624 snprintf( psz_service, 6, "%d", i_port );
626 /* Check if we have to force ipv4 or ipv6 */
627 if( p_hints == NULL )
628 memset( &hints, 0, sizeof( hints ) );
630 memcpy( &hints, p_hints, sizeof( hints ) );
632 if( hints.ai_family == AF_UNSPEC )
636 var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
637 var_Get( p_this, "ipv4", &val );
639 hints.ai_family = AF_INET;
642 var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
643 var_Get( p_this, "ipv6", &val );
645 hints.ai_family = AF_INET6;
651 * - accept "" as NULL
652 * - ignore square brackets
654 if( ( node == NULL ) || (node[0] == '\0' ) )
660 strlcpy( psz_buf, node, NI_MAXHOST );
664 if( psz_buf[0] == '[' )
668 ptr = strrchr( psz_buf, ']' );
669 if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
677 #if defined( WIN32 ) && !defined( UNDER_CE )
679 * Winsock tries to resolve numerical IPv4 addresses as AAAA
680 * and IPv6 addresses as A... There comes the work around.
682 if ((hints.ai_flags & AI_NUMERICHOST) == 0)
684 hints.ai_flags |= AI_NUMERICHOST;
686 if (ws2_getaddrinfo (psz_node, psz_service, &hints, res) == 0)
689 hints.ai_flags &= ~AI_NUMERICHOST;
692 return ws2_getaddrinfo (psz_node, psz_service, &hints, res);
694 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
696 /* Run-time I18n Domain Names support */
698 static vlc_bool_t i_idn = VLC_TRUE; /* beware of thread-safety */
704 hints.ai_flags |= AI_IDN;
705 i_ret = getaddrinfo( psz_node, psz_service, &hints, res );
707 if( i_ret != EAI_BADFLAGS )
710 /* libidn not available: disable and retry without it */
712 /* NOTE: Using i_idn here would not be thread-safe */
713 hints.ai_flags &= ~AI_IDN;
715 msg_Dbg( p_this, "International Domain Names not supported - " \
720 return getaddrinfo( psz_node, psz_service, &hints, res );
727 var_Create( p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX );
728 var_Get( p_this->p_libvlc, "getaddrinfo_mutex", &lock );
729 vlc_mutex_lock( lock.p_address );
731 i_ret = __getaddrinfo( psz_node, psz_service, &hints, res );
732 vlc_mutex_unlock( lock.p_address );
739 void vlc_freeaddrinfo( struct addrinfo *infos )
741 #if defined( WIN32 ) && !defined( UNDER_CE )
742 ws2_freeaddrinfo( infos );
744 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
745 freeaddrinfo( infos );
747 __freeaddrinfo( infos );