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 *****************************************************************************/
25 #define _WIN32_WINNT 0x501
28 #include <stddef.h> /* size_t */
29 #include <string.h> /* strlen(), memcpy(), memset(), strchr() */
30 #include <stdlib.h> /* malloc(), free(), strtoul() */
33 #ifdef HAVE_SYS_TYPES_H
34 # include <sys/types.h>
36 #ifdef HAVE_ARPA_INET_H
37 # include <arpa/inet.h>
39 #ifdef HAVE_NETINET_IN_H
40 # include <netinet/in.h>
46 #include <vlc_network.h>
49 # define NO_ADDRESS NO_DATA
52 # define INADDR_NONE 0xFFFFFFFF
58 #define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
60 #define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
63 #ifndef HAVE_GAI_STRERROR
68 } const __gai_errlist[] =
71 { EAI_BADFLAGS, "Invalid flag used" },
72 { EAI_NONAME, "Host or service not found" },
73 { EAI_AGAIN, "Temporary name service failure" },
74 { EAI_FAIL, "Non-recoverable name service failure" },
75 { EAI_NODATA, "No data for host name" },
76 { EAI_FAMILY, "Unsupported address family" },
77 { EAI_SOCKTYPE, "Unsupported socket type" },
78 { EAI_SERVICE, "Incompatible service for socket type" },
79 { EAI_ADDRFAMILY, "Unavailable address family for host name" },
80 { EAI_MEMORY, "Memory allocation failure" },
81 { EAI_OVERFLOW, "Buffer overflow" },
82 { EAI_SYSTEM, "System error" },
86 static const char *__gai_unknownerr = "Unrecognized error number";
88 /****************************************************************************
89 * Converts an EAI_* error code into human readable english text.
90 ****************************************************************************/
91 const char *vlc_gai_strerror (int errnum)
93 for (unsigned i = 0; __gai_errlist[i].msg != NULL; i++)
94 if (errnum == __gai_errlist[i].code)
95 return __gai_errlist[i].msg;
97 return __gai_unknownerr;
99 #else /* ifndef HAVE_GAI_STRERROR */
100 const char *vlc_gai_strerror (int errnum)
102 return gai_strerror (errnum);
107 #ifndef HAVE_GETNAMEINFO
109 * getnameinfo() non-thread-safe IPv4-only implementation,
110 * Address-family-independant 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
121 getnameinfo (const struct sockaddr *sa, socklen_t salen,
122 char *host, int hostlen, char *serv, int servlen, int flags)
124 if (((size_t)salen < sizeof (struct sockaddr_in))
125 || (sa->sa_family != AF_INET))
127 else if (flags & (~_NI_MASK))
131 const struct sockaddr_in *addr;
133 addr = (const struct sockaddr_in *)sa;
137 /* host name resolution */
138 if (!(flags & NI_NUMERICHOST))
140 if (flags & NI_NAMEREQD)
144 /* inet_ntoa() is not thread-safe, do not use it */
145 uint32_t ipv4 = ntohl (addr->sin_addr.s_addr);
147 if (snprintf (host, hostlen, "%u.%u.%u.%u", ipv4 >> 24,
148 (ipv4 >> 16) & 0xff, (ipv4 >> 8) & 0xff,
149 ipv4 & 0xff) >= hostlen)
155 if (snprintf (serv, servlen, "%u",
156 (unsigned int)ntohs (addr->sin_port)) >= servlen)
163 #endif /* if !HAVE_GETNAMEINFO */
165 #ifndef HAVE_GETADDRINFO
167 * Converts the current herrno error value into an EAI_* error code.
168 * That error code is normally returned by getnameinfo() or getaddrinfo().
171 gai_error_from_herrno (void)
179 # if (NO_ADDRESS != NO_DATA)
194 * This functions must be used to free the memory allocated by getaddrinfo().
196 static void freeaddrinfo (struct addrinfo *res)
200 if (res->ai_canonname != NULL)
201 free (res->ai_canonname);
202 if (res->ai_addr != NULL)
204 if (res->ai_next != NULL)
212 * Internal function that builds an addrinfo struct.
214 static struct addrinfo *
215 makeaddrinfo (int af, int type, int proto,
216 const struct sockaddr *addr, size_t addrlen,
217 const char *canonname)
219 struct addrinfo *res;
221 res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
226 res->ai_socktype = type;
227 res->ai_protocol = proto;
228 res->ai_addrlen = addrlen;
229 res->ai_addr = malloc (addrlen);
230 res->ai_canonname = NULL;
233 if (res->ai_addr != NULL)
235 memcpy (res->ai_addr, addr, addrlen);
237 if (canonname != NULL)
239 res->ai_canonname = strdup (canonname);
240 if (res->ai_canonname != NULL)
241 return res; /* success ! */
248 vlc_freeaddrinfo (res);
253 static struct addrinfo *
254 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
256 struct sockaddr_in addr;
258 memset (&addr, 0, sizeof (addr));
259 addr.sin_family = AF_INET;
261 addr.sin_len = sizeof (addr);
263 addr.sin_port = port;
264 addr.sin_addr.s_addr = ip;
266 return makeaddrinfo (AF_INET, type, proto,
267 (struct sockaddr*)&addr, sizeof (addr), name);
272 * getaddrinfo() non-thread-safe IPv4-only implementation
273 * Address-family-independant hostname to address resolution.
275 * This is meant for IPv6-unaware systems that do probably not provide
276 * getaddrinfo(), but still have old function gethostbyname().
278 * Only UDP and TCP over IPv4 are supported here.
281 getaddrinfo (const char *node, const char *service,
282 const struct addrinfo *hints, struct addrinfo **res)
284 struct addrinfo *info;
287 int protocol = 0, flags = 0;
288 const char *name = NULL;
292 * Maybe you knew already that Winsock does not handle TCP/RST packets
293 * properly, so that when a TCP connection fails, it will wait until it
294 * times out even if the remote host did return a TCP/RST. However, it
295 * still sees the TCP/RST as the error code is 10061 instead of 10060.
296 * Basically, we have the stupid brainfucked behavior with DNS queries...
297 * When the recursive DNS server returns an error, Winsock waits about
298 * 2 seconds before it returns to the callers, even though it should know
299 * that is pointless. I'd like to know how come this hasn't been fixed
300 * for the past decade, or maybe not.
302 * Anyway, this is causing a severe delay when the SAP listener tries
303 * to resolve more than ten IPv6 numeric addresses. Modern systems will
304 * eventually realize that it is an IPv6 address, and won't try to resolve
305 * it as a IPv4 address via the Domain Name Service. Old systems
306 * (including Windows XP without the IPv6 stack) will not. It is normally
307 * not an issue as the DNS server usually returns an error very quickly.
308 * But it IS a severe issue on Windows, given the bug explained above.
309 * So here comes one more bug-to-bug Windows compatibility fix.
311 if ((node != NULL) && (strchr (node, ':') != NULL))
317 flags = hints->ai_flags;
319 if (flags & ~_AI_MASK)
321 /* only accept AF_INET and AF_UNSPEC */
322 if (hints->ai_family && (hints->ai_family != AF_INET))
325 /* protocol sanity check */
326 switch (hints->ai_socktype)
329 protocol = IPPROTO_TCP;
333 protocol = IPPROTO_UDP;
345 if (hints->ai_protocol && protocol
346 && (protocol != hints->ai_protocol))
355 if (flags & AI_PASSIVE)
356 ip = htonl (INADDR_ANY);
358 ip = htonl (INADDR_LOOPBACK);
361 if ((ip = inet_addr (node)) == INADDR_NONE)
363 struct hostent *entry = NULL;
365 /* hostname resolution */
366 if (!(flags & AI_NUMERICHOST))
367 entry = gethostbyname (node);
370 return gai_error_from_herrno ();
372 if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
375 ip = *((u_long *) entry->h_addr);
376 if (flags & AI_CANONNAME)
377 name = entry->h_name;
380 if ((flags & AI_CANONNAME) && (name == NULL))
383 /* service resolution */
391 d = strtoul (service, &end, 0);
392 if (end[0] /* service is not a number */
395 struct servent *entry;
396 const char *protoname;
412 entry = getservbyname (service, protoname);
416 port = entry->s_port;
419 port = htons ((u_short)d);
422 /* building results... */
423 if ((!protocol) || (protocol == IPPROTO_UDP))
425 info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
431 if (flags & AI_PASSIVE)
432 info->ai_flags |= AI_PASSIVE;
435 if ((!protocol) || (protocol == IPPROTO_TCP))
437 info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
443 info->ai_next = *res;
444 if (flags & AI_PASSIVE)
445 info->ai_flags |= AI_PASSIVE;
451 #endif /* if !HAVE_GETADDRINFO */
454 #if 0 && defined( WIN32 ) && !defined( UNDER_CE )
456 * Here is the kind of kludge you need to keep binary compatibility among
457 * varying OS versions...
459 typedef int (CALLBACK * GETNAMEINFO) ( const struct sockaddr*, socklen_t,
460 char*, DWORD, char*, DWORD, int );
461 typedef int (CALLBACK * GETADDRINFO) (const char *, const char *,
462 const struct addrinfo *,
465 typedef void (CALLBACK * FREEADDRINFO) ( struct addrinfo * );
468 static WINAPI int _ws2_getnameinfo_bind( const struct sockaddr *sa, socklen_t salen,
469 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags );
471 static WINAPI int _ws2_getaddrinfo_bind(const char *node, const char *service,
472 const struct addrinfo *hints, struct addrinfo **res);
474 static GETNAMEINFO ws2_getnameinfo = _ws2_getnameinfo_bind;
475 static GETADDRINFO ws2_getaddrinfo = _ws2_getaddrinfo_bind;
476 static FREEADDRINFO ws2_freeaddrinfo;
478 static FARPROC ws2_find_api (const char *name)
482 HMODULE m = GetModuleHandle ("WS2_32");
484 f = GetProcAddress (m, name);
488 /* Windows 2K IPv6 preview */
489 m = LoadLibrary ("WSHIP6");
491 f = GetProcAddress (m, name);
497 static WINAPI int _ws2_getnameinfo_bind( const struct sockaddr *sa, socklen_t salen,
498 char *host, DWORD hostlen, char *serv, DWORD servlen, int flags )
500 GETNAMEINFO entry = (GETNAMEINFO)ws2_find_api ("getnameinfo");
503 ws2_getnameinfo = entry;
504 return entry (sa, salen, host, hostlen, serv, servlen, flags);
506 /* return a possible error if API is not found */
507 WSASetLastError (WSAEAFNOSUPPORT);
511 #define getnameinfo ws2_getnameinfo
513 static WINAPI int _ws2_getaddrinfo_bind(const char *node, const char *service,
514 const struct addrinfo *hints, struct addrinfo **res)
516 GETADDRINFO entry = (GETADDRINFO)ws2_find_api ("getaddrinfo");
517 FREEADDRINFO freentry = (FREEADDRINFO)ws2_find_api ("freeaddrinfo");
519 if ((entry != NULL) && (freentry != NULL))
521 ws2_freeaddrinfo = freentry;
522 ws2_getaddrinfo = entry;
523 return entry (node, service, hints, res);
525 /* return a possible error if API is not found */
526 WSASetLastError (WSAHOST_NOT_FOUND);
531 #define getaddrinfo ws2_getaddrinfo
532 #define freeaddrinfo ws2_freeaddrinfo
533 #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 );
565 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
566 int i_port, const struct addrinfo *p_hints,
567 struct addrinfo **res )
569 struct addrinfo hints;
570 char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
573 * In VLC, we always use port number as integer rather than strings
574 * for historical reasons (and portability).
576 if( ( i_port > 65535 ) || ( i_port < 0 ) )
578 msg_Err( p_this, "invalid port number %d specified", i_port );
582 /* cannot overflow */
583 snprintf( psz_service, 6, "%d", i_port );
585 /* Check if we have to force ipv4 or ipv6 */
586 if( p_hints == NULL )
587 memset( &hints, 0, sizeof( hints ) );
589 memcpy( &hints, p_hints, sizeof( hints ) );
591 if( hints.ai_family == AF_UNSPEC )
595 var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
596 var_Get( p_this, "ipv4", &val );
598 hints.ai_family = AF_INET;
601 var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
602 var_Get( p_this, "ipv6", &val );
604 hints.ai_family = AF_INET6;
610 * - accept "" as NULL
611 * - ignore square brackets
613 if( ( node == NULL ) || (node[0] == '\0' ) )
619 strlcpy( psz_buf, node, NI_MAXHOST );
623 if( psz_buf[0] == '[' )
627 ptr = strrchr( psz_buf, ']' );
628 if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
638 * Winsock tries to resolve numerical IPv4 addresses as AAAA
639 * and IPv6 addresses as A... There comes the bug-to-bug fix.
641 if ((hints.ai_flags & AI_NUMERICHOST) == 0)
643 hints.ai_flags |= AI_NUMERICHOST;
645 if (getaddrinfo (psz_node, psz_service, &hints, res) == 0)
648 hints.ai_flags &= ~AI_NUMERICHOST;
651 #if defined (HAVE_GETADDRINFO)
653 /* Run-time I18n Domain Names support */
654 static vlc_bool_t b_idn = VLC_TRUE; /* beware of thread-safety */
658 hints.ai_flags |= AI_IDN;
659 int ret = getaddrinfo (psz_node, psz_service, &hints, res);
661 if (ret != EAI_BADFLAGS)
664 /* IDN not available: disable and retry without it */
665 hints.ai_flags &= ~AI_IDN;
667 msg_Info (p_this, "International Domain Names not supported");
670 return getaddrinfo (psz_node, psz_service, &hints, res);
675 var_Create (p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX);
676 var_Get (p_this->p_libvlc, "getaddrinfo_mutex", &lock);
677 vlc_mutex_lock (lock.p_address);
679 ret = getaddrinfo (psz_node, psz_service, &hints, res);
680 vlc_mutex_unlock (lock.p_address);
686 void vlc_freeaddrinfo( struct addrinfo *infos )
688 freeaddrinfo (infos);