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>
48 # define NO_ADDRESS NO_DATA
51 # define INADDR_NONE 0xFFFFFFFF
57 #define _NI_MASK (NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|\
59 #define _AI_MASK (AI_PASSIVE|AI_CANONNAME|AI_NUMERICHOST)
62 #ifndef HAVE_GAI_STRERROR
67 } const __gai_errlist[] =
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_SYSTEM, "System error" },
84 static const char *__gai_unknownerr = "Unrecognized error number";
86 /****************************************************************************
87 * Converts an EAI_* error code into human readable english text.
88 ****************************************************************************/
89 const char *vlc_gai_strerror( int errnum )
93 for (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 # undef _EAI_POSITIVE_MAX
100 #else /* ifndef HAVE_GAI_STRERROR */
101 const char *vlc_gai_strerror( int errnum )
103 return gai_strerror( errnum );
107 #if !(defined (HAVE_GETNAMEINFO) && defined (HAVE_GETADDRINFO))
109 * Converts the current herrno error value into an EAI_* error code.
110 * That error code is normally returned by getnameinfo() or getaddrinfo().
113 gai_error_from_herrno( void )
121 # if (NO_ADDRESS != NO_DATA)
134 #endif /* if !(HAVE_GETNAMEINFO && HAVE_GETADDRINFO) */
136 #ifndef HAVE_GETNAMEINFO
138 * getnameinfo() non-thread-safe IPv4-only implementation,
139 * Address-family-independant address to hostname translation
140 * (reverse DNS lookup in case of IPv4).
142 * This is meant for use on old IP-enabled systems that are not IPv6-aware,
143 * and probably do not have getnameinfo(), but have the old gethostbyaddr()
146 * GNU C library 2.0.x is known to lack this function, even though it defines
150 __getnameinfo( const struct sockaddr *sa, socklen_t salen,
151 char *host, int hostlen, char *serv, int servlen, int flags )
153 if (((unsigned)salen < sizeof (struct sockaddr_in))
154 || (sa->sa_family != AF_INET))
156 else if (flags & (~_NI_MASK))
160 const struct sockaddr_in *addr;
162 addr = (const struct sockaddr_in *)sa;
168 /* host name resolution */
169 if (!(flags & NI_NUMERICHOST))
171 struct hostent *hent;
173 hent = gethostbyaddr ((const void*)&addr->sin_addr,
178 strlcpy (host, hent->h_name, hostlen);
181 * only keep first part of hostname
182 * if user don't want fully qualified
185 if (flags & NI_NOFQDN)
189 ptr = strchr (host, '.');
196 else if (flags & NI_NAMEREQD)
197 return gai_error_from_herrno ();
201 /* inet_ntoa() can't fail */
202 strlcpy (host, inet_ntoa (addr->sin_addr), hostlen);
207 struct servent *sent = NULL;
209 #ifndef SYS_BEOS /* No getservbyport() */
212 /* service name resolution */
213 if (!(flags & NI_NUMERICSERV))
216 sent = getservbyport(addr->sin_port,
221 strlcpy (serv, sent->s_name, servlen);
228 snprintf (serv, servlen, "%u",
229 (unsigned int)ntohs (addr->sin_port));
230 serv[servlen - 1] = '\0';
237 #endif /* if !HAVE_GETNAMEINFO */
240 #ifndef HAVE_GETADDRINFO
242 * This functions must be used to free the memory allocated by getaddrinfo().
245 __freeaddrinfo (struct addrinfo *res)
249 if (res->ai_canonname != NULL)
250 free (res->ai_canonname);
251 if (res->ai_addr != NULL)
253 if (res->ai_next != NULL)
261 * Internal function that builds an addrinfo struct.
263 static struct addrinfo *
264 makeaddrinfo (int af, int type, int proto,
265 const struct sockaddr *addr, size_t addrlen,
266 const char *canonname)
268 struct addrinfo *res;
270 res = (struct addrinfo *)malloc (sizeof (struct addrinfo));
275 res->ai_socktype = type;
276 res->ai_protocol = proto;
277 res->ai_addrlen = addrlen;
278 res->ai_addr = malloc (addrlen);
279 res->ai_canonname = NULL;
282 if (res->ai_addr != NULL)
284 memcpy (res->ai_addr, addr, addrlen);
286 if (canonname != NULL)
288 res->ai_canonname = strdup (canonname);
289 if (res->ai_canonname != NULL)
290 return res; /* success ! */
297 vlc_freeaddrinfo (res);
302 static struct addrinfo *
303 makeipv4info (int type, int proto, u_long ip, u_short port, const char *name)
305 struct sockaddr_in addr;
307 memset (&addr, 0, sizeof (addr));
308 addr.sin_family = AF_INET;
310 addr.sin_len = sizeof (addr);
312 addr.sin_port = port;
313 addr.sin_addr.s_addr = ip;
315 return makeaddrinfo (AF_INET, type, proto,
316 (struct sockaddr*)&addr, sizeof (addr), name);
321 * getaddrinfo() non-thread-safe IPv4-only implementation
322 * Address-family-independant hostname to address resolution.
324 * This is meant for IPv6-unaware systems that do probably not provide
325 * getaddrinfo(), but still have old function gethostbyname().
327 * Only UDP and TCP over IPv4 are supported here.
330 __getaddrinfo (const char *node, const char *service,
331 const struct addrinfo *hints, struct addrinfo **res)
333 struct addrinfo *info;
336 int protocol = 0, flags = 0;
337 const char *name = NULL;
341 * Maybe you knew already that Winsock does not handle TCP/RST packets
342 * properly, so that when a TCP connection fails, it will wait until it
343 * times out even if the remote host did return a TCP/RST. However, it
344 * still sees the TCP/RST as the error code is 10061 instead of 10060.
345 * Basically, we have the stupid brainfucked behavior with DNS queries...
346 * When the recursive DNS server returns an error, Winsock waits about
347 * 2 seconds before it returns to the callers, even though it should know
348 * that is pointless. I'd like to know how come this hasn't been fixed
349 * for the past decade, or maybe not.
351 * Anyway, this is causing a severe delay when the SAP listener tries
352 * to resolve more than ten IPv6 numeric addresses. Modern systems will
353 * eventually realize that it is an IPv6 address, and won't try to resolve
354 * it as a IPv4 address via the Domain Name Service. Old systems
355 * (including Windows XP without the IPv6 stack) will not. It is normally
356 * not an issue as the DNS server usually returns an error very quickly.
357 * But it IS a severe issue on Windows, given the bug explained above.
358 * So here comes one more bug-to-bug Windows compatibility fix.
360 if ((node != NULL) && (strchr (node, ':') != NULL))
366 flags = hints->ai_flags;
368 if (flags & ~_AI_MASK)
370 /* only accept AF_INET and AF_UNSPEC */
371 if (hints->ai_family && (hints->ai_family != AF_INET))
374 /* protocol sanity check */
375 switch (hints->ai_socktype)
378 protocol = IPPROTO_TCP;
382 protocol = IPPROTO_UDP;
394 if (hints->ai_protocol && protocol
395 && (protocol != hints->ai_protocol))
404 if (flags & AI_PASSIVE)
405 ip = htonl (INADDR_ANY);
407 ip = htonl (INADDR_LOOPBACK);
410 if ((ip = inet_addr (node)) == INADDR_NONE)
412 struct hostent *entry = NULL;
414 /* hostname resolution */
415 if (!(flags & AI_NUMERICHOST))
416 entry = gethostbyname (node);
421 if ((entry->h_length != 4) || (entry->h_addrtype != AF_INET))
424 ip = *((u_long *) entry->h_addr);
425 if (flags & AI_CANONNAME)
426 name = entry->h_name;
429 if ((flags & AI_CANONNAME) && (name == NULL))
432 /* service resolution */
440 d = strtoul (service, &end, 0);
441 if (end[0] /* service is not a number */
444 struct servent *entry;
445 const char *protoname;
461 entry = getservbyname (service, protoname);
465 port = entry->s_port;
468 port = htons ((u_short)d);
471 /* building results... */
472 if ((!protocol) || (protocol == IPPROTO_UDP))
474 info = makeipv4info (SOCK_DGRAM, IPPROTO_UDP, ip, port, name);
480 if (flags & AI_PASSIVE)
481 info->ai_flags |= AI_PASSIVE;
484 if ((!protocol) || (protocol == IPPROTO_TCP))
486 info = makeipv4info (SOCK_STREAM, IPPROTO_TCP, ip, port, name);
492 info->ai_next = *res;
493 if (flags & AI_PASSIVE)
494 info->ai_flags |= AI_PASSIVE;
500 #endif /* if !HAVE_GETADDRINFO */
503 int vlc_getnameinfo( const struct sockaddr *sa, int salen,
504 char *host, int hostlen, int *portnum, int flags )
506 char psz_servbuf[6], *psz_serv;
507 int i_servlen, i_val;
508 #if defined( WIN32 ) && !defined( UNDER_CE )
510 * Here is the kind of kludge you need to keep binary compatibility among
511 * varying OS versions...
513 typedef int (CALLBACK * GETNAMEINFO) ( const struct sockaddr*, socklen_t,
514 char*, DWORD, char*, DWORD, int );
515 HINSTANCE wship6_module;
516 GETNAMEINFO ws2_getnameinfo;
519 flags |= NI_NUMERICSERV;
520 if( portnum != NULL )
522 psz_serv = psz_servbuf;
523 i_servlen = sizeof( psz_servbuf );
530 #if defined( WIN32 ) && !defined( UNDER_CE )
531 wship6_module = LoadLibrary( "wship6.dll" );
532 if( wship6_module != NULL )
534 ws2_getnameinfo = (GETNAMEINFO)GetProcAddress( wship6_module,
537 if( ws2_getnameinfo != NULL )
539 i_val = ws2_getnameinfo( sa, salen, host, hostlen, psz_serv,
541 FreeLibrary( wship6_module );
543 if( portnum != NULL )
544 *portnum = atoi( psz_serv );
548 FreeLibrary( wship6_module );
551 #if defined( HAVE_GETNAMEINFO ) || defined( UNDER_CE )
552 i_val = getnameinfo(sa, salen, host, hostlen, psz_serv, i_servlen, flags);
555 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
556 static vlc_value_t lock;
558 /* my getnameinfo implementation is not thread-safe as it uses
559 * gethostbyaddr and the likes */
560 vlc_mutex_lock( lock.p_address );
562 //# warning FIXME : This is not thread-safe!
564 i_val = __getnameinfo( sa, salen, host, hostlen, psz_serv, i_servlen,
566 # ifdef HAVE_USABLE_MUTEX_THAT_DONT_NEED_LIBVLC_POINTER
567 vlc_mutex_unlock( lock.p_address );
572 if( portnum != NULL )
573 *portnum = atoi( psz_serv );
579 /* TODO: support for setting sin6_scope_id */
580 int vlc_getaddrinfo( vlc_object_t *p_this, const char *node,
581 int i_port, const struct addrinfo *p_hints,
582 struct addrinfo **res )
584 struct addrinfo hints;
585 char psz_buf[NI_MAXHOST], *psz_node, psz_service[6];
588 * In VLC, we always use port number as integer rather than strings
589 * for historical reasons (and portability).
591 if( ( i_port > 65535 ) || ( i_port < 0 ) )
593 msg_Err( p_this, "invalid port number %d specified", i_port );
597 /* cannot overflow */
598 snprintf( psz_service, 6, "%d", i_port );
600 /* Check if we have to force ipv4 or ipv6 */
601 if( p_hints == NULL )
602 memset( &hints, 0, sizeof( hints ) );
604 memcpy( &hints, p_hints, sizeof( hints ) );
606 if( hints.ai_family == AF_UNSPEC )
610 var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
611 var_Get( p_this, "ipv4", &val );
613 hints.ai_family = AF_INET;
616 var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
617 var_Get( p_this, "ipv6", &val );
619 hints.ai_family = AF_INET6;
625 * - accept "" as NULL
626 * - ignore square brackets
628 if( ( node == NULL ) || (node[0] == '\0' ) )
634 strlcpy( psz_buf, node, NI_MAXHOST );
638 if( psz_buf[0] == '[' )
642 ptr = strrchr( psz_buf, ']' );
643 if( ( ptr != NULL ) && (ptr[1] == '\0' ) )
651 #if defined( WIN32 ) && !defined( UNDER_CE )
653 typedef int (CALLBACK * GETADDRINFO) ( const char *, const char *,
654 const struct addrinfo *,
655 struct addrinfo ** );
656 HINSTANCE wship6_module;
657 GETADDRINFO ws2_getaddrinfo;
659 wship6_module = LoadLibrary( "wship6.dll" );
660 if( wship6_module != NULL )
662 ws2_getaddrinfo = (GETADDRINFO)GetProcAddress( wship6_module,
665 if( ws2_getaddrinfo != NULL )
669 i_ret = ws2_getaddrinfo( psz_node, psz_service, &hints, res );
670 FreeLibrary( wship6_module ); /* is this wise ? */
674 FreeLibrary( wship6_module );
678 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
680 /* Run-time I18n Domain Names support */
682 static vlc_bool_t i_idn = VLC_TRUE; /* beware of thread-safety */
688 hints.ai_flags |= AI_IDN;
689 i_ret = getaddrinfo( psz_node, psz_service, &hints, res );
691 if( i_ret != EAI_BADFLAGS )
694 /* libidn not available: disable and retry without it */
696 /* NOTE: Using i_idn here would not be thread-safe */
697 hints.ai_flags &= ~AI_IDN;
699 msg_Dbg( p_this, "localized Domain Names not supported - " \
704 return getaddrinfo( psz_node, psz_service, &hints, res );
711 var_Create( p_this->p_libvlc, "getaddrinfo_mutex", VLC_VAR_MUTEX );
712 var_Get( p_this->p_libvlc, "getaddrinfo_mutex", &lock );
713 vlc_mutex_lock( lock.p_address );
715 i_ret = __getaddrinfo( psz_node, psz_service, &hints, res );
716 vlc_mutex_unlock( lock.p_address );
723 void vlc_freeaddrinfo( struct addrinfo *infos )
725 #if defined( WIN32 ) && !defined( UNDER_CE )
726 typedef void (CALLBACK * FREEADDRINFO) ( struct addrinfo * );
727 HINSTANCE wship6_module;
728 FREEADDRINFO ws2_freeaddrinfo;
730 wship6_module = LoadLibrary( "wship6.dll" );
731 if( wship6_module != NULL )
733 ws2_freeaddrinfo = (FREEADDRINFO)GetProcAddress( wship6_module,
737 * NOTE: it is assumed that wship6.dll defines either both
738 * getaddrinfo and freeaddrinfo or none of them.
740 if( ws2_freeaddrinfo != NULL )
742 ws2_freeaddrinfo( infos );
743 FreeLibrary( wship6_module );
747 FreeLibrary( wship6_module );
750 #if defined( HAVE_GETADDRINFO ) || defined( UNDER_CE )
751 freeaddrinfo( infos );
753 __freeaddrinfo( infos );