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_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 )
96 for (i = 0; __gai_errlist[i].msg != NULL; i++)
97 if (errnum == __gai_errlist[i].code)
98 return __gai_errlist[i].msg;
100 return __gai_unknownerr;
102 # undef _EAI_POSITIVE_MAX
103 #else /* ifndef HAVE_GAI_STRERROR */
104 const char *vlc_gai_strerror( int errnum )
106 return gai_strerror( errnum );
110 #if !(defined (HAVE_GETNAMEINFO) && defined (HAVE_GETADDRINFO))
112 * Converts the current herrno error value into an EAI_* error code.
113 * That error code is normally returned by getnameinfo() or getaddrinfo().
116 gai_error_from_herrno( void )
124 # if (NO_ADDRESS != NO_DATA)
137 #endif /* if !(HAVE_GETNAMEINFO && HAVE_GETADDRINFO) */
139 #ifndef HAVE_GETNAMEINFO
141 * getnameinfo() non-thread-safe IPv4-only implementation,
142 * Address-family-independant address to hostname translation
143 * (reverse DNS lookup in case of IPv4).
145 * This is meant for use on old IP-enabled systems that are not IPv6-aware,
146 * and probably do not have getnameinfo(), but have the old gethostbyaddr()
149 * GNU C library 2.0.x is known to lack this function, even though it defines
153 __getnameinfo( const struct sockaddr *sa, socklen_t salen,
154 char *host, int hostlen, char *serv, int servlen, int flags )
156 if (((unsigned)salen < sizeof (struct sockaddr_in))
157 || (sa->sa_family != AF_INET))
159 else if (flags & (~_NI_MASK))
163 const struct sockaddr_in *addr;
165 addr = (const struct sockaddr_in *)sa;
169 /* host name resolution */
170 if (!(flags & NI_NUMERICHOST))
172 if (flags & NI_NAMEREQD)
176 /* inet_ntoa() is not thread-safe, do not use it */
177 uint32_t ipv4 = ntohl (addr->sin_addr.s_addr);
179 if (snprintf (host, hostlen, "%u.%u.%u.%u", ipv4 >> 24,
180 (ipv4 >> 16) & 0xff, (ipv4 >> 8) & 0xff,
181 ipv4 & 0xff) >= hostlen)
187 if (snprintf (serv, servlen, "%u",
188 (unsigned int)ntohs (addr->sin_port)) >= servlen)
195 #endif /* if !HAVE_GETNAMEINFO */
197 #if defined( WIN32 ) && !defined( UNDER_CE )
199 * Here is the kind of kludge you need to keep binary compatibility among
200 * varying OS versions...
202 typedef int (CALLBACK * GETNAMEINFO) ( const struct sockaddr*, socklen_t,
203 char*, DWORD, char*, DWORD, int );
204 typedef int (CALLBACK * GETADDRINFO) (const char *, const char *,
205 const struct addrinfo *,
208 typedef void (CALLBACK * FREEADDRINFO) ( struct addrinfo * );
211 static WINAPI int _ws2_getnameinfo_bind( const struct sockaddr *sa, socklen_t salen,
212 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags );
214 static WINAPI int _ws2_getaddrinfo_bind(const char *node, const char *service,
215 const struct addrinfo *hints, struct addrinfo **res);
217 static WINAPI void _ws2_freeaddrinfo_bind( struct addrinfo *infos );
219 static GETNAMEINFO ws2_getnameinfo = _ws2_getnameinfo_bind;
220 static GETADDRINFO ws2_getaddrinfo = _ws2_getaddrinfo_bind;
221 static FREEADDRINFO ws2_freeaddrinfo = _ws2_freeaddrinfo_bind;
223 static int _ws2_find_ipv6_api(void)
225 /* For Windows XP and above, IPv6 stack is in WS2_32.DLL */
226 HINSTANCE module = LoadLibrary( "ws2_32.dll" );
229 ws2_getnameinfo = (GETNAMEINFO)GetProcAddress( module, "getnameinfo" );
230 ws2_getaddrinfo = (GETADDRINFO)GetProcAddress( module, "getaddrinfo" );
231 ws2_freeaddrinfo = (FREEADDRINFO)GetProcAddress( module, "freeaddrinfo" );
232 if( ws2_getnameinfo && ws2_getaddrinfo && ws2_freeaddrinfo )
237 FreeLibrary( module );
239 /* For Windows 2000 and below, try IPv6 stack in in WSHIP6.DLL */
240 module = LoadLibrary( "wship6.dll" );
243 ws2_getnameinfo = (GETNAMEINFO)GetProcAddress( module, "getnameinfo" );
244 ws2_getaddrinfo = (GETADDRINFO)GetProcAddress( module, "getaddrinfo" );
245 ws2_freeaddrinfo = (FREEADDRINFO)GetProcAddress( module, "freeaddrinfo" );
246 if( ws2_getnameinfo && ws2_getaddrinfo && ws2_freeaddrinfo )
251 FreeLibrary( module );
258 static WINAPI int _ws2_getnameinfo_bind( const struct sockaddr *sa, socklen_t salen,
259 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags )
261 if( _ws2_find_ipv6_api() )
263 return ws2_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
265 /* return a possible error if API is not found */
266 WSASetLastError(WSAHOST_NOT_FOUND);
267 return WSAHOST_NOT_FOUND;
270 static WINAPI int _ws2_getaddrinfo_bind(const char *node, const char *service,
271 const struct addrinfo *hints, struct addrinfo **res)
273 if( _ws2_find_ipv6_api() )
275 return ws2_getaddrinfo(node, service, hints, res);
277 /* return a possible error if API is not found */
278 WSASetLastError(WSAHOST_NOT_FOUND);
279 return WSAHOST_NOT_FOUND;
282 static WINAPI void _ws2_freeaddrinfo_bind( struct addrinfo *infos )
284 if( _ws2_find_ipv6_api() )
286 ws2_freeaddrinfo(infos);
292 #ifndef HAVE_GETADDRINFO
294 * This functions must be used to free the memory allocated by getaddrinfo().
297 __freeaddrinfo (struct addrinfo *res)
301 if (res->ai_canonname != NULL)
302 free (res->ai_canonname);
303 if (res->ai_addr != NULL)
305 if (res->ai_next != NULL)
313 * Internal function that builds an addrinfo struct.
315 static struct addrinfo *
316 makeaddrinfo (int af, int type, int proto,
317 const struct sockaddr *addr, size_t addrlen,
318 const char *canonname)
320 struct addrinfo *res;
322 res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
327 res->ai_socktype = type;
328 res->ai_protocol = proto;
329 res->ai_addrlen = addrlen;
330 res->ai_addr = malloc (addrlen);
331 res->ai_canonname = NULL;
334 if (res->ai_addr != NULL)
336 memcpy (res->ai_addr, addr, addrlen);
338 if (canonname != NULL)
340 res->ai_canonname = strdup (canonname);
341 if (res->ai_canonname != NULL)
342 return res; /* success ! */
349 vlc_freeaddrinfo (res);
354 static struct addrinfo *
355 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
357 struct sockaddr_in addr;
359 memset (&addr, 0, sizeof (addr));
360 addr.sin_family = AF_INET;
362 addr.sin_len = sizeof (addr);
364 addr.sin_port = port;
365 addr.sin_addr.s_addr = ip;
367 return makeaddrinfo (AF_INET, type, proto,
368 (struct sockaddr*)&addr, sizeof (addr), name);
373 * getaddrinfo() non-thread-safe IPv4-only implementation
374 * Address-family-independant hostname to address resolution.
376 * This is meant for IPv6-unaware systems that do probably not provide
377 * getaddrinfo(), but still have old function gethostbyname().
379 * Only UDP and TCP over IPv4 are supported here.
382 __getaddrinfo (const char *node, const char *service,
383 const struct addrinfo *hints, struct addrinfo **res)
385 struct addrinfo *info;
388 int protocol = 0, flags = 0;
389 const char *name = NULL;
393 * Maybe you knew already that Winsock does not handle TCP/RST packets
394 * properly, so that when a TCP connection fails, it will wait until it
395 * times out even if the remote host did return a TCP/RST. However, it
396 * still sees the TCP/RST as the error code is 10061 instead of 10060.
397 * Basically, we have the stupid brainfucked behavior with DNS queries...
398 * When the recursive DNS server returns an error, Winsock waits about
399 * 2 seconds before it returns to the callers, even though it should know
400 * that is pointless. I'd like to know how come this hasn't been fixed
401 * for the past decade, or maybe not.
403 * Anyway, this is causing a severe delay when the SAP listener tries
404 * to resolve more than ten IPv6 numeric addresses. Modern systems will
405 * eventually realize that it is an IPv6 address, and won't try to resolve
406 * it as a IPv4 address via the Domain Name Service. Old systems
407 * (including Windows XP without the IPv6 stack) will not. It is normally
408 * not an issue as the DNS server usually returns an error very quickly.
409 * But it IS a severe issue on Windows, given the bug explained above.
410 * So here comes one more bug-to-bug Windows compatibility fix.
412 if ((node != NULL) && (strchr (node, ':') != NULL))
418 flags = hints->ai_flags;
420 if (flags & ~_AI_MASK)
422 /* only accept AF_INET and AF_UNSPEC */
423 if (hints->ai_family && (hints->ai_family != AF_INET))
426 /* protocol sanity check */
427 switch (hints->ai_socktype)
430 protocol = IPPROTO_TCP;
434 protocol = IPPROTO_UDP;
446 if (hints->ai_protocol && protocol
447 && (protocol != hints->ai_protocol))
456 if (flags & AI_PASSIVE)
457 ip = htonl (INADDR_ANY);
459 ip = htonl (INADDR_LOOPBACK);
462 if ((ip = inet_addr (node)) == INADDR_NONE)
464 struct hostent *entry = NULL;
466 /* hostname resolution */
467 if (!(flags & AI_NUMERICHOST))
468 entry = gethostbyname (node);
473 if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
476 ip = *((u_long *) entry->h_addr);
477 if (flags & AI_CANONNAME)
478 name = entry->h_name;
481 if ((flags & AI_CANONNAME) && (name == NULL))
484 /* service resolution */
492 d = strtoul (service, &end, 0);
493 if (end[0] /* service is not a number */
496 struct servent *entry;
497 const char *protoname;
513 entry = getservbyname (service, protoname);
517 port = entry->s_port;
520 port = htons ((u_short)d);
523 /* building results... */
524 if ((!protocol) || (protocol == IPPROTO_UDP))
526 info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
532 if (flags & AI_PASSIVE)
533 info->ai_flags |= AI_PASSIVE;
536 if ((!protocol) || (protocol == IPPROTO_TCP))
538 info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
544 info->ai_next = *res;
545 if (flags & AI_PASSIVE)
546 info->ai_flags |= AI_PASSIVE;
552 #endif /* if !HAVE_GETADDRINFO */
555 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
556 char *host, int hostlen, int *portnum, int flags )
558 char psz_servbuf[6], *psz_serv;
559 int i_servlen, i_val;
561 flags |= NI_NUMERICSERV;
562 if( portnum != NULL )
564 psz_serv = psz_servbuf;
565 i_servlen = sizeof( psz_servbuf );
572 #if defined( WIN32 ) && !defined( UNDER_CE )
573 i_val = ws2_getnameinfo( sa, salen, host, hostlen, psz_serv,
576 #if defined( HAVE_GETNAMEINFO ) || defined( UNDER_CE )
577 i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
580 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
581 static vlc_value_t lock;
583 /* my getnameinfo implementation is not thread-safe as it uses
584 * gethostbyaddr and the likes */
585 vlc_mutex_lock( lock.p_address );
587 # warning FIXME : This is not thread-safe!
589 i_val = __getnameinfo( sa, salen, host, hostlen, psz_serv, i_servlen,
591 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
592 vlc_mutex_unlock( lock.p_address );
597 if( portnum != NULL )
598 *portnum = atoi( psz_serv );
604 /* TODO: support for setting sin6_scope_id */
605 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
606 int i_port, const struct addrinfo *p_hints,
607 struct addrinfo **res )
609 struct addrinfo hints;
610 char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
613 * In VLC, we always use port number as integer rather than strings
614 * for historical reasons (and portability).
616 if( ( i_port > 65535 ) || ( i_port < 0 ) )
618 msg_Err( p_this, "invalid port number %d specified", i_port );
622 /* cannot overflow */
623 snprintf( psz_service, 6, "%d", i_port );
625 /* Check if we have to force ipv4 or ipv6 */
626 if( p_hints == NULL )
627 memset( &hints, 0, sizeof( hints ) );
629 memcpy( &hints, p_hints, sizeof( hints ) );
631 if( hints.ai_family == AF_UNSPEC )
635 var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
636 var_Get( p_this, "ipv4", &val );
638 hints.ai_family = AF_INET;
641 var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
642 var_Get( p_this, "ipv6", &val );
644 hints.ai_family = AF_INET6;
650 * - accept "" as NULL
651 * - ignore square brackets
653 if( ( node == NULL ) || (node[0] == '\0' ) )
659 strlcpy( psz_buf, node, NI_MAXHOST );
663 if( psz_buf[0] == '[' )
667 ptr = strrchr( psz_buf, ']' );
668 if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
676 #if defined( WIN32 ) && !defined( UNDER_CE )
678 * Winsock tries to resolve numerical IPv4 addresses as AAAA
679 * and IPv6 addresses as A... There comes the work around.
681 if ((hints.ai_flags & AI_NUMERICHOST) == 0)
683 hints.ai_flags |= AI_NUMERICHOST;
685 if (ws2_getaddrinfo (psz_node, psz_service, &hints, res) == 0)
688 hints.ai_flags &= ~AI_NUMERICHOST;
691 return ws2_getaddrinfo (psz_node, psz_service, &hints, res);
693 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
695 /* Run-time I18n Domain Names support */
697 static vlc_bool_t i_idn = VLC_TRUE; /* beware of thread-safety */
703 hints.ai_flags |= AI_IDN;
704 i_ret = getaddrinfo( psz_node, psz_service, &hints, res );
706 if( i_ret != EAI_BADFLAGS )
709 /* libidn not available: disable and retry without it */
711 /* NOTE: Using i_idn here would not be thread-safe */
712 hints.ai_flags &= ~AI_IDN;
714 msg_Dbg( p_this, "International Domain Names not supported - " \
719 return getaddrinfo( psz_node, psz_service, &hints, res );
726 var_Create( p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX );
727 var_Get( p_this->p_libvlc, "getaddrinfo_mutex", &lock );
728 vlc_mutex_lock( lock.p_address );
730 i_ret = __getaddrinfo( psz_node, psz_service, &hints, res );
731 vlc_mutex_unlock( lock.p_address );
738 void vlc_freeaddrinfo( struct addrinfo *infos )
740 #if defined( WIN32 ) && !defined( UNDER_CE )
741 ws2_freeaddrinfo( infos );
743 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
744 freeaddrinfo( infos );
746 __freeaddrinfo( infos );