Home | History | Annotate | Line # | Download | only in net
getaddrinfo.c revision 1.42.4.5
      1 /*	$NetBSD: getaddrinfo.c,v 1.42.4.5 2002/09/04 02:30:49 itojun Exp $	*/
      2 /*	$KAME: getaddrinfo.c,v 1.29 2000/08/31 17:26:57 itojun Exp $	*/
      3 
      4 /*
      5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. Neither the name of the project nor the names of its contributors
     17  *    may be used to endorse or promote products derived from this software
     18  *    without specific prior written permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30  * SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Issues to be discussed:
     35  * - Thread safe-ness must be checked.
     36  * - Return values.  There are nonstandard return values defined and used
     37  *   in the source code.  This is because RFC2553 is silent about which error
     38  *   code must be returned for which situation.
     39  * - IPv4 classful (shortened) form.  RFC2553 is silent about it.  XNET 5.2
     40  *   says to use inet_aton() to convert IPv4 numeric to binary (alows
     41  *   classful form as a result).
     42  *   current code - disallow classful form for IPv4 (due to use of inet_pton).
     43  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
     44  *   invalid.
     45  *   current code - SEGV on freeaddrinfo(NULL)
     46  * Note:
     47  * - We use getipnodebyname() just for thread-safeness.  There's no intent
     48  *   to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
     49  *   getipnodebyname().
     50  * - The code filters out AFs that are not supported by the kernel,
     51  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
     52  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
     53  *   in ai_flags?
     54  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
     55  *   (1) what should we do against numeric hostname (2) what should we do
     56  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
     57  *   non-loopback address configured?  global address configured?
     58  * - To avoid search order issue, we have a big amount of code duplicate
     59  *   from gethnamaddr.c and some other places.  The issues that there's no
     60  *   lower layer function to lookup "IPv4 or IPv6" record.  Calling
     61  *   gethostbyname2 from getaddrinfo will end up in wrong search order, as
     62  *   follows:
     63  *	- The code makes use of following calls when asked to resolver with
     64  *	  ai_family  = PF_UNSPEC:
     65  *		getipnodebyname(host, AF_INET6);
     66  *		getipnodebyname(host, AF_INET);
     67  *	  This will result in the following queries if the node is configure to
     68  *	  prefer /etc/hosts than DNS:
     69  *		lookup /etc/hosts for IPv6 address
     70  *		lookup DNS for IPv6 address
     71  *		lookup /etc/hosts for IPv4 address
     72  *		lookup DNS for IPv4 address
     73  *	  which may not meet people's requirement.
     74  *	  The right thing to happen is to have underlying layer which does
     75  *	  PF_UNSPEC lookup (lookup both) and return chain of addrinfos.
     76  *	  This would result in a bit of code duplicate with _dns_ghbyname() and
     77  *	  friends.
     78  */
     79 
     80 #include <sys/cdefs.h>
     81 #if defined(LIBC_SCCS) && !defined(lint)
     82 __RCSID("$NetBSD: getaddrinfo.c,v 1.42.4.5 2002/09/04 02:30:49 itojun Exp $");
     83 #endif /* LIBC_SCCS and not lint */
     84 
     85 #include "namespace.h"
     86 #include <sys/types.h>
     87 #include <sys/param.h>
     88 #include <sys/socket.h>
     89 #include <net/if.h>
     90 #include <netinet/in.h>
     91 #include <arpa/inet.h>
     92 #include <arpa/nameser.h>
     93 #include <assert.h>
     94 #include <ctype.h>
     95 #include <errno.h>
     96 #include <netdb.h>
     97 #include <resolv.h>
     98 #include <stddef.h>
     99 #include <stdio.h>
    100 #include <stdlib.h>
    101 #include <string.h>
    102 #include <unistd.h>
    103 
    104 #include <syslog.h>
    105 #include <stdarg.h>
    106 #include <nsswitch.h>
    107 
    108 #ifdef YP
    109 #include <rpc/rpc.h>
    110 #include <rpcsvc/yp_prot.h>
    111 #include <rpcsvc/ypclnt.h>
    112 #endif
    113 
    114 #ifdef __weak_alias
    115 __weak_alias(getaddrinfo,_getaddrinfo)
    116 __weak_alias(freeaddrinfo,_freeaddrinfo)
    117 __weak_alias(gai_strerror,_gai_strerror)
    118 #endif
    119 
    120 #define SUCCESS 0
    121 #define ANY 0
    122 #define YES 1
    123 #define NO  0
    124 
    125 static const char in_addrany[] = { 0, 0, 0, 0 };
    126 static const char in6_addrany[] = {
    127 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    128 };
    129 static const char in_loopback[] = { 127, 0, 0, 1 };
    130 static const char in6_loopback[] = {
    131 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
    132 };
    133 
    134 static const struct afd {
    135 	int a_af;
    136 	int a_addrlen;
    137 	int a_socklen;
    138 	int a_off;
    139 	const char *a_addrany;
    140 	const char *a_loopback;
    141 	int a_scoped;
    142 } afdl [] = {
    143 #ifdef INET6
    144 	{PF_INET6, sizeof(struct in6_addr),
    145 	 sizeof(struct sockaddr_in6),
    146 	 offsetof(struct sockaddr_in6, sin6_addr),
    147 	 in6_addrany, in6_loopback, 1},
    148 #endif
    149 	{PF_INET, sizeof(struct in_addr),
    150 	 sizeof(struct sockaddr_in),
    151 	 offsetof(struct sockaddr_in, sin_addr),
    152 	 in_addrany, in_loopback, 0},
    153 	{0, 0, 0, 0, NULL, NULL, 0},
    154 };
    155 
    156 struct explore {
    157 	int e_af;
    158 	int e_socktype;
    159 	int e_protocol;
    160 	const char *e_protostr;
    161 	int e_wild;
    162 #define WILD_AF(ex)		((ex)->e_wild & 0x01)
    163 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
    164 #define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
    165 };
    166 
    167 static const struct explore explore[] = {
    168 #if 0
    169 	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
    170 #endif
    171 #ifdef INET6
    172 	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    173 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    174 	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
    175 #endif
    176 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    177 	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    178 	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
    179 	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    180 	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    181 	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
    182 	{ -1, 0, 0, NULL, 0 },
    183 };
    184 
    185 #ifdef INET6
    186 #define PTON_MAX	16
    187 #else
    188 #define PTON_MAX	4
    189 #endif
    190 
    191 static const ns_src default_dns_files[] = {
    192 	{ NSSRC_FILES, 	NS_SUCCESS },
    193 	{ NSSRC_DNS, 	NS_SUCCESS },
    194 	{ 0 }
    195 };
    196 
    197 #define MAXPACKET	(64*1024)
    198 
    199 typedef union {
    200 	HEADER hdr;
    201 	u_char buf[MAXPACKET];
    202 } querybuf;
    203 
    204 struct res_target {
    205 	struct res_target *next;
    206 	const char *name;	/* domain name */
    207 	int qclass, qtype;	/* class and type of query */
    208 	u_char *answer;		/* buffer to put answer */
    209 	int anslen;		/* size of answer buffer */
    210 	int n;			/* result length */
    211 };
    212 
    213 static int str_isnumber __P((const char *));
    214 static int explore_fqdn __P((const struct addrinfo *, const char *,
    215 	const char *, struct addrinfo **));
    216 static int explore_null __P((const struct addrinfo *,
    217 	const char *, struct addrinfo **));
    218 static int explore_numeric __P((const struct addrinfo *, const char *,
    219 	const char *, struct addrinfo **));
    220 static int explore_numeric_scope __P((const struct addrinfo *, const char *,
    221 	const char *, struct addrinfo **));
    222 static int get_canonname __P((const struct addrinfo *,
    223 	struct addrinfo *, const char *));
    224 static struct addrinfo *get_ai __P((const struct addrinfo *,
    225 	const struct afd *, const char *));
    226 static int get_portmatch __P((const struct addrinfo *, const char *));
    227 static int get_port __P((struct addrinfo *, const char *, int));
    228 static const struct afd *find_afd __P((int));
    229 #if 0
    230 static int addrconfig __P((const struct addrinfo *));
    231 #endif
    232 #ifdef INET6
    233 static int ip6_str2scopeid __P((char *, struct sockaddr_in6 *, u_int32_t *));
    234 #endif
    235 
    236 static struct addrinfo *getanswer __P((const querybuf *, int, const char *, int,
    237 	const struct addrinfo *));
    238 static int _dns_getaddrinfo __P((void *, void *, va_list));
    239 static void _sethtent __P((void));
    240 static void _endhtent __P((void));
    241 static struct addrinfo *_gethtent __P((const char *, const struct addrinfo *));
    242 static int _files_getaddrinfo __P((void *, void *, va_list));
    243 #ifdef YP
    244 static struct addrinfo *_yphostent __P((char *, const struct addrinfo *));
    245 static int _yp_getaddrinfo __P((void *, void *, va_list));
    246 #endif
    247 
    248 static int res_queryN __P((const char *, struct res_target *));
    249 static int res_searchN __P((const char *, struct res_target *));
    250 static int res_querydomainN __P((const char *, const char *,
    251 	struct res_target *));
    252 
    253 static char *ai_errlist[] = {
    254 	"Success",
    255 	"Address family for hostname not supported",	/* EAI_ADDRFAMILY */
    256 	"Temporary failure in name resolution",		/* EAI_AGAIN      */
    257 	"Invalid value for ai_flags",		       	/* EAI_BADFLAGS   */
    258 	"Non-recoverable failure in name resolution", 	/* EAI_FAIL       */
    259 	"ai_family not supported",			/* EAI_FAMILY     */
    260 	"Memory allocation failure", 			/* EAI_MEMORY     */
    261 	"No address associated with hostname", 		/* EAI_NODATA     */
    262 	"hostname nor servname provided, or not known",	/* EAI_NONAME     */
    263 	"servname not supported for ai_socktype",	/* EAI_SERVICE    */
    264 	"ai_socktype not supported", 			/* EAI_SOCKTYPE   */
    265 	"System error returned in errno", 		/* EAI_SYSTEM     */
    266 	"Invalid value for hints",			/* EAI_BADHINTS	  */
    267 	"Resolved protocol is unknown",			/* EAI_PROTOCOL   */
    268 	"Unknown error", 				/* EAI_MAX        */
    269 };
    270 
    271 /* XXX macros that make external reference is BAD. */
    272 
    273 #define GET_AI(ai, afd, addr) \
    274 do { \
    275 	/* external reference: pai, error, and label free */ \
    276 	(ai) = get_ai(pai, (afd), (addr)); \
    277 	if ((ai) == NULL) { \
    278 		error = EAI_MEMORY; \
    279 		goto free; \
    280 	} \
    281 } while (/*CONSTCOND*/0)
    282 
    283 #define GET_PORT(ai, serv) \
    284 do { \
    285 	/* external reference: error and label free */ \
    286 	error = get_port((ai), (serv), 0); \
    287 	if (error != 0) \
    288 		goto free; \
    289 } while (/*CONSTCOND*/0)
    290 
    291 #define GET_CANONNAME(ai, str) \
    292 do { \
    293 	/* external reference: pai, error and label free */ \
    294 	error = get_canonname(pai, (ai), (str)); \
    295 	if (error != 0) \
    296 		goto free; \
    297 } while (/*CONSTCOND*/0)
    298 
    299 #define ERR(err) \
    300 do { \
    301 	/* external reference: error, and label bad */ \
    302 	error = (err); \
    303 	goto bad; \
    304 	/*NOTREACHED*/ \
    305 } while (/*CONSTCOND*/0)
    306 
    307 #define MATCH_FAMILY(x, y, w) \
    308 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
    309 #define MATCH(x, y, w) \
    310 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
    311 
    312 char *
    313 gai_strerror(ecode)
    314 	int ecode;
    315 {
    316 	if (ecode < 0 || ecode > EAI_MAX)
    317 		ecode = EAI_MAX;
    318 	return ai_errlist[ecode];
    319 }
    320 
    321 void
    322 freeaddrinfo(ai)
    323 	struct addrinfo *ai;
    324 {
    325 	struct addrinfo *next;
    326 
    327 	do {
    328 		next = ai->ai_next;
    329 		if (ai->ai_canonname)
    330 			free(ai->ai_canonname);
    331 		/* no need to free(ai->ai_addr) */
    332 		free(ai);
    333 		ai = next;
    334 	} while (ai);
    335 }
    336 
    337 static int
    338 str_isnumber(p)
    339 	const char *p;
    340 {
    341 	char *ep;
    342 
    343 	if (*p == '\0')
    344 		return NO;
    345 	ep = NULL;
    346 	errno = 0;
    347 	(void)strtoul(p, &ep, 10);
    348 	if (errno == 0 && ep && *ep == '\0')
    349 		return YES;
    350 	else
    351 		return NO;
    352 }
    353 
    354 int
    355 getaddrinfo(hostname, servname, hints, res)
    356 	const char *hostname, *servname;
    357 	const struct addrinfo *hints;
    358 	struct addrinfo **res;
    359 {
    360 	struct addrinfo sentinel;
    361 	struct addrinfo *cur;
    362 	int error = 0;
    363 	struct addrinfo ai;
    364 	struct addrinfo ai0;
    365 	struct addrinfo *pai;
    366 	const struct explore *ex;
    367 
    368 	memset(&sentinel, 0, sizeof(sentinel));
    369 	cur = &sentinel;
    370 	pai = &ai;
    371 	pai->ai_flags = 0;
    372 	pai->ai_family = PF_UNSPEC;
    373 	pai->ai_socktype = ANY;
    374 	pai->ai_protocol = ANY;
    375 	pai->ai_addrlen = 0;
    376 	pai->ai_canonname = NULL;
    377 	pai->ai_addr = NULL;
    378 	pai->ai_next = NULL;
    379 
    380 	if (hostname == NULL && servname == NULL)
    381 		return EAI_NONAME;
    382 	if (hints) {
    383 		/* error check for hints */
    384 		if (hints->ai_addrlen || hints->ai_canonname ||
    385 		    hints->ai_addr || hints->ai_next)
    386 			ERR(EAI_BADHINTS); /* xxx */
    387 		if (hints->ai_flags & ~AI_MASK)
    388 			ERR(EAI_BADFLAGS);
    389 		switch (hints->ai_family) {
    390 		case PF_UNSPEC:
    391 		case PF_INET:
    392 #ifdef INET6
    393 		case PF_INET6:
    394 #endif
    395 			break;
    396 		default:
    397 			ERR(EAI_FAMILY);
    398 		}
    399 		memcpy(pai, hints, sizeof(*pai));
    400 
    401 		/*
    402 		 * if both socktype/protocol are specified, check if they
    403 		 * are meaningful combination.
    404 		 */
    405 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
    406 			for (ex = explore; ex->e_af >= 0; ex++) {
    407 				if (pai->ai_family != ex->e_af)
    408 					continue;
    409 				if (ex->e_socktype == ANY)
    410 					continue;
    411 				if (ex->e_protocol == ANY)
    412 					continue;
    413 				if (pai->ai_socktype == ex->e_socktype
    414 				 && pai->ai_protocol != ex->e_protocol) {
    415 					ERR(EAI_BADHINTS);
    416 				}
    417 			}
    418 		}
    419 	}
    420 
    421 	/*
    422 	 * check for special cases.  (1) numeric servname is disallowed if
    423 	 * socktype/protocol are left unspecified. (2) servname is disallowed
    424 	 * for raw and other inet{,6} sockets.
    425 	 */
    426 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
    427 #ifdef PF_INET6
    428 	 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
    429 #endif
    430 	    ) {
    431 		ai0 = *pai;	/* backup *pai */
    432 
    433 		if (pai->ai_family == PF_UNSPEC) {
    434 #ifdef PF_INET6
    435 			pai->ai_family = PF_INET6;
    436 #else
    437 			pai->ai_family = PF_INET;
    438 #endif
    439 		}
    440 		error = get_portmatch(pai, servname);
    441 		if (error)
    442 			ERR(error);
    443 
    444 		*pai = ai0;
    445 	}
    446 
    447 	ai0 = *pai;
    448 
    449 	/* NULL hostname, or numeric hostname */
    450 	for (ex = explore; ex->e_af >= 0; ex++) {
    451 		*pai = ai0;
    452 
    453 		/* PF_UNSPEC entries are prepared for DNS queries only */
    454 		if (ex->e_af == PF_UNSPEC)
    455 			continue;
    456 
    457 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    458 			continue;
    459 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
    460 			continue;
    461 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
    462 			continue;
    463 
    464 		if (pai->ai_family == PF_UNSPEC)
    465 			pai->ai_family = ex->e_af;
    466 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    467 			pai->ai_socktype = ex->e_socktype;
    468 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    469 			pai->ai_protocol = ex->e_protocol;
    470 
    471 		if (hostname == NULL)
    472 			error = explore_null(pai, servname, &cur->ai_next);
    473 		else
    474 			error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
    475 
    476 		if (error)
    477 			goto free;
    478 
    479 		while (cur && cur->ai_next)
    480 			cur = cur->ai_next;
    481 	}
    482 
    483 	/*
    484 	 * XXX
    485 	 * If numreic representation of AF1 can be interpreted as FQDN
    486 	 * representation of AF2, we need to think again about the code below.
    487 	 */
    488 	if (sentinel.ai_next)
    489 		goto good;
    490 
    491 	if (pai->ai_flags & AI_NUMERICHOST)
    492 		ERR(EAI_NODATA);
    493 	if (hostname == NULL)
    494 		ERR(EAI_NODATA);
    495 
    496 	/*
    497 	 * hostname as alphabetical name.
    498 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
    499 	 * outer loop by AFs.
    500 	 */
    501 	for (ex = explore; ex->e_af >= 0; ex++) {
    502 		*pai = ai0;
    503 
    504 		/* require exact match for family field */
    505 		if (pai->ai_family != ex->e_af)
    506 			continue;
    507 
    508 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
    509 				WILD_SOCKTYPE(ex))) {
    510 			continue;
    511 		}
    512 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
    513 				WILD_PROTOCOL(ex))) {
    514 			continue;
    515 		}
    516 
    517 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    518 			pai->ai_socktype = ex->e_socktype;
    519 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    520 			pai->ai_protocol = ex->e_protocol;
    521 
    522 		error = explore_fqdn(pai, hostname, servname,
    523 			&cur->ai_next);
    524 
    525 		while (cur && cur->ai_next)
    526 			cur = cur->ai_next;
    527 	}
    528 
    529 	/* XXX */
    530 	if (sentinel.ai_next)
    531 		error = 0;
    532 
    533 	if (error)
    534 		goto free;
    535 	if (error == 0) {
    536 		if (sentinel.ai_next) {
    537  good:
    538 			*res = sentinel.ai_next;
    539 			return SUCCESS;
    540 		} else
    541 			error = EAI_FAIL;
    542 	}
    543  free:
    544  bad:
    545 	if (sentinel.ai_next)
    546 		freeaddrinfo(sentinel.ai_next);
    547 	*res = NULL;
    548 	return error;
    549 }
    550 
    551 /*
    552  * FQDN hostname, DNS lookup
    553  */
    554 static int
    555 explore_fqdn(pai, hostname, servname, res)
    556 	const struct addrinfo *pai;
    557 	const char *hostname;
    558 	const char *servname;
    559 	struct addrinfo **res;
    560 {
    561 	struct addrinfo *result;
    562 	struct addrinfo *cur;
    563 	int error = 0;
    564 	static const ns_dtab dtab[] = {
    565 		NS_FILES_CB(_files_getaddrinfo, NULL)
    566 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
    567 		NS_NIS_CB(_yp_getaddrinfo, NULL)
    568 		{ 0 }
    569 	};
    570 
    571 	result = NULL;
    572 
    573 #if 0
    574 	/*
    575 	 * If AI_ADDRCONFIG is specified, check if we are expected to
    576 	 * return the address family or not.
    577 	 * XXX does not handle PF_UNSPEC - should filter out result from
    578 	 * nsdispatch()
    579 	 */
    580 	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(pai))
    581 		return 0;
    582 #endif
    583 
    584 	/*
    585 	 * if the servname does not match socktype/protocol, ignore it.
    586 	 */
    587 	if (get_portmatch(pai, servname) != 0)
    588 		return 0;
    589 
    590 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
    591 			default_dns_files, hostname, pai)) {
    592 	case NS_TRYAGAIN:
    593 		error = EAI_AGAIN;
    594 		goto free;
    595 	case NS_UNAVAIL:
    596 		error = EAI_FAIL;
    597 		goto free;
    598 	case NS_NOTFOUND:
    599 		error = EAI_NODATA;
    600 		goto free;
    601 	case NS_SUCCESS:
    602 		error = 0;
    603 		for (cur = result; cur; cur = cur->ai_next) {
    604 			GET_PORT(cur, servname);
    605 			/* canonname should be filled already */
    606 		}
    607 		break;
    608 	}
    609 
    610 	*res = result;
    611 
    612 	return 0;
    613 
    614 free:
    615 	if (result)
    616 		freeaddrinfo(result);
    617 	return error;
    618 }
    619 
    620 /*
    621  * hostname == NULL.
    622  * passive socket -> anyaddr (0.0.0.0 or ::)
    623  * non-passive socket -> localhost (127.0.0.1 or ::1)
    624  */
    625 static int
    626 explore_null(pai, servname, res)
    627 	const struct addrinfo *pai;
    628 	const char *servname;
    629 	struct addrinfo **res;
    630 {
    631 	int s;
    632 	const struct afd *afd;
    633 	struct addrinfo *cur;
    634 	struct addrinfo sentinel;
    635 	int error;
    636 
    637 	*res = NULL;
    638 	sentinel.ai_next = NULL;
    639 	cur = &sentinel;
    640 
    641 	/*
    642 	 * filter out AFs that are not supported by the kernel
    643 	 * XXX errno?
    644 	 */
    645 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    646 	if (s < 0) {
    647 		if (errno != EMFILE)
    648 			return 0;
    649 	} else
    650 		close(s);
    651 
    652 	/*
    653 	 * if the servname does not match socktype/protocol, ignore it.
    654 	 */
    655 	if (get_portmatch(pai, servname) != 0)
    656 		return 0;
    657 
    658 	afd = find_afd(pai->ai_family);
    659 	if (afd == NULL)
    660 		return 0;
    661 
    662 	if (pai->ai_flags & AI_PASSIVE) {
    663 		GET_AI(cur->ai_next, afd, afd->a_addrany);
    664 		/* xxx meaningless?
    665 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
    666 		 */
    667 		GET_PORT(cur->ai_next, servname);
    668 	} else {
    669 		GET_AI(cur->ai_next, afd, afd->a_loopback);
    670 		/* xxx meaningless?
    671 		 * GET_CANONNAME(cur->ai_next, "localhost");
    672 		 */
    673 		GET_PORT(cur->ai_next, servname);
    674 	}
    675 	cur = cur->ai_next;
    676 
    677 	*res = sentinel.ai_next;
    678 	return 0;
    679 
    680 free:
    681 	if (sentinel.ai_next)
    682 		freeaddrinfo(sentinel.ai_next);
    683 	return error;
    684 }
    685 
    686 /*
    687  * numeric hostname
    688  */
    689 static int
    690 explore_numeric(pai, hostname, servname, res)
    691 	const struct addrinfo *pai;
    692 	const char *hostname;
    693 	const char *servname;
    694 	struct addrinfo **res;
    695 {
    696 	const struct afd *afd;
    697 	struct addrinfo *cur;
    698 	struct addrinfo sentinel;
    699 	int error;
    700 	char pton[PTON_MAX];
    701 
    702 	*res = NULL;
    703 	sentinel.ai_next = NULL;
    704 	cur = &sentinel;
    705 
    706 	/*
    707 	 * if the servname does not match socktype/protocol, ignore it.
    708 	 */
    709 	if (get_portmatch(pai, servname) != 0)
    710 		return 0;
    711 
    712 	afd = find_afd(pai->ai_family);
    713 	if (afd == NULL)
    714 		return 0;
    715 
    716 	switch (afd->a_af) {
    717 #if 0 /*X/Open spec*/
    718 	case AF_INET:
    719 		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
    720 			if (pai->ai_family == afd->a_af ||
    721 			    pai->ai_family == PF_UNSPEC /*?*/) {
    722 				GET_AI(cur->ai_next, afd, pton);
    723 				GET_PORT(cur->ai_next, servname);
    724 				while (cur && cur->ai_next)
    725 					cur = cur->ai_next;
    726 			} else
    727 				ERR(EAI_FAMILY);	/*xxx*/
    728 		}
    729 		break;
    730 #endif
    731 	default:
    732 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
    733 			if (pai->ai_family == afd->a_af ||
    734 			    pai->ai_family == PF_UNSPEC /*?*/) {
    735 				GET_AI(cur->ai_next, afd, pton);
    736 				GET_PORT(cur->ai_next, servname);
    737 				while (cur && cur->ai_next)
    738 					cur = cur->ai_next;
    739 			} else
    740 				ERR(EAI_FAMILY);	/*xxx*/
    741 		}
    742 		break;
    743 	}
    744 
    745 	*res = sentinel.ai_next;
    746 	return 0;
    747 
    748 free:
    749 bad:
    750 	if (sentinel.ai_next)
    751 		freeaddrinfo(sentinel.ai_next);
    752 	return error;
    753 }
    754 
    755 /*
    756  * numeric hostname with scope
    757  */
    758 static int
    759 explore_numeric_scope(pai, hostname, servname, res)
    760 	const struct addrinfo *pai;
    761 	const char *hostname;
    762 	const char *servname;
    763 	struct addrinfo **res;
    764 {
    765 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
    766 	return explore_numeric(pai, hostname, servname, res);
    767 #else
    768 	const struct afd *afd;
    769 	struct addrinfo *cur;
    770 	int error;
    771 	char *cp, *hostname2 = NULL, *scope, *addr;
    772 	struct sockaddr_in6 *sin6;
    773 
    774 	/*
    775 	 * if the servname does not match socktype/protocol, ignore it.
    776 	 */
    777 	if (get_portmatch(pai, servname) != 0)
    778 		return 0;
    779 
    780 	afd = find_afd(pai->ai_family);
    781 	if (afd == NULL)
    782 		return 0;
    783 
    784 	if (!afd->a_scoped)
    785 		return explore_numeric(pai, hostname, servname, res);
    786 
    787 	cp = strchr(hostname, SCOPE_DELIMITER);
    788 	if (cp == NULL)
    789 		return explore_numeric(pai, hostname, servname, res);
    790 
    791 #if 0
    792 	/*
    793 	 * Handle special case of <scope id><delimiter><scoped_address>
    794 	 */
    795 	hostname2 = strdup(hostname);
    796 	if (hostname2 == NULL)
    797 		return EAI_MEMORY;
    798 	/* terminate at the delimiter */
    799 	hostname2[cp - hostname] = '\0';
    800 	scope = hostname2;
    801 	addr = cp + 1;
    802 #else
    803 	/*
    804 	 * Handle special case of <scoped_address><delimiter><scope id>
    805 	 */
    806 	hostname2 = strdup(hostname);
    807 	if (hostname2 == NULL)
    808 		return EAI_MEMORY;
    809 	/* terminate at the delimiter */
    810 	hostname2[cp - hostname] = '\0';
    811 	addr = hostname2;
    812 	scope = cp + 1;
    813 #endif
    814 
    815 	error = explore_numeric(pai, addr, servname, res);
    816 	if (error == 0) {
    817 		u_int32_t scopeid;
    818 
    819 		for (cur = *res; cur; cur = cur->ai_next) {
    820 			if (cur->ai_family != AF_INET6)
    821 				continue;
    822 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
    823 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
    824 				free(hostname2);
    825 				return(EAI_NODATA); /* XXX: is return OK? */
    826 			}
    827 			sin6->sin6_scope_id = scopeid;
    828 		}
    829 	}
    830 
    831 	free(hostname2);
    832 
    833 	return error;
    834 #endif
    835 }
    836 
    837 static int
    838 get_canonname(pai, ai, str)
    839 	const struct addrinfo *pai;
    840 	struct addrinfo *ai;
    841 	const char *str;
    842 {
    843 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
    844 		ai->ai_canonname = (char *)malloc(strlen(str) + 1);
    845 		if (ai->ai_canonname == NULL)
    846 			return EAI_MEMORY;
    847 		strcpy(ai->ai_canonname, str);
    848 	}
    849 	return 0;
    850 }
    851 
    852 static struct addrinfo *
    853 get_ai(pai, afd, addr)
    854 	const struct addrinfo *pai;
    855 	const struct afd *afd;
    856 	const char *addr;
    857 {
    858 	char *p;
    859 	struct addrinfo *ai;
    860 
    861 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
    862 		+ (afd->a_socklen));
    863 	if (ai == NULL)
    864 		return NULL;
    865 
    866 	memcpy(ai, pai, sizeof(struct addrinfo));
    867 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
    868 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
    869 	ai->ai_addr->sa_len = afd->a_socklen;
    870 	ai->ai_addrlen = afd->a_socklen;
    871 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
    872 	p = (char *)(void *)(ai->ai_addr);
    873 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
    874 	return ai;
    875 }
    876 
    877 static int
    878 get_portmatch(ai, servname)
    879 	const struct addrinfo *ai;
    880 	const char *servname;
    881 {
    882 
    883 	/* get_port does not touch first argument. when matchonly == 1. */
    884 	/* LINTED const cast */
    885 	return get_port((struct addrinfo *)ai, servname, 1);
    886 }
    887 
    888 static int
    889 get_port(ai, servname, matchonly)
    890 	struct addrinfo *ai;
    891 	const char *servname;
    892 	int matchonly;
    893 {
    894 	const char *proto;
    895 	struct servent *sp;
    896 	int port;
    897 	int allownumeric;
    898 
    899 	if (servname == NULL)
    900 		return 0;
    901 	switch (ai->ai_family) {
    902 	case AF_INET:
    903 #ifdef AF_INET6
    904 	case AF_INET6:
    905 #endif
    906 		break;
    907 	default:
    908 		return 0;
    909 	}
    910 
    911 	switch (ai->ai_socktype) {
    912 	case SOCK_RAW:
    913 		return EAI_SERVICE;
    914 	case SOCK_DGRAM:
    915 	case SOCK_STREAM:
    916 		allownumeric = 1;
    917 		break;
    918 	case ANY:
    919 		allownumeric = 0;
    920 		break;
    921 	default:
    922 		return EAI_SOCKTYPE;
    923 	}
    924 
    925 	if (str_isnumber(servname)) {
    926 		if (!allownumeric)
    927 			return EAI_SERVICE;
    928 		port = atoi(servname);
    929 		if (port < 0 || port > 65535)
    930 			return EAI_SERVICE;
    931 		port = htons(port);
    932 	} else {
    933 		switch (ai->ai_socktype) {
    934 		case SOCK_DGRAM:
    935 			proto = "udp";
    936 			break;
    937 		case SOCK_STREAM:
    938 			proto = "tcp";
    939 			break;
    940 		default:
    941 			proto = NULL;
    942 			break;
    943 		}
    944 
    945 		if ((sp = getservbyname(servname, proto)) == NULL)
    946 			return EAI_SERVICE;
    947 		port = sp->s_port;
    948 	}
    949 
    950 	if (!matchonly) {
    951 		switch (ai->ai_family) {
    952 		case AF_INET:
    953 			((struct sockaddr_in *)(void *)
    954 			    ai->ai_addr)->sin_port = port;
    955 			break;
    956 #ifdef INET6
    957 		case AF_INET6:
    958 			((struct sockaddr_in6 *)(void *)
    959 			    ai->ai_addr)->sin6_port = port;
    960 			break;
    961 #endif
    962 		}
    963 	}
    964 
    965 	return 0;
    966 }
    967 
    968 static const struct afd *
    969 find_afd(af)
    970 	int af;
    971 {
    972 	const struct afd *afd;
    973 
    974 	if (af == PF_UNSPEC)
    975 		return NULL;
    976 	for (afd = afdl; afd->a_af; afd++) {
    977 		if (afd->a_af == af)
    978 			return afd;
    979 	}
    980 	return NULL;
    981 }
    982 
    983 #if 0
    984 /*
    985  * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
    986  * will take care of it.
    987  * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
    988  * if the code is right or not.
    989  */
    990 static int
    991 addrconfig(pai)
    992 	const struct addrinfo *pai;
    993 {
    994 	int s;
    995 
    996 	/* XXX errno */
    997 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    998 	if (s < 0)
    999 		return 0;
   1000 	close(s);
   1001 	return 1;
   1002 }
   1003 #endif
   1004 
   1005 #ifdef INET6
   1006 /* convert a string to a scope identifier. XXX: IPv6 specific */
   1007 static int
   1008 ip6_str2scopeid(scope, sin6, scopeid)
   1009 	char *scope;
   1010 	struct sockaddr_in6 *sin6;
   1011 	u_int32_t *scopeid;
   1012 {
   1013 	u_long lscopeid;
   1014 	struct in6_addr *a6;
   1015 	char *ep;
   1016 
   1017 	a6 = &sin6->sin6_addr;
   1018 
   1019 	/* empty scopeid portion is invalid */
   1020 	if (*scope == '\0')
   1021 		return -1;
   1022 
   1023 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
   1024 		/*
   1025 		 * We currently assume a one-to-one mapping between links
   1026 		 * and interfaces, so we simply use interface indices for
   1027 		 * like-local scopes.
   1028 		 */
   1029 		*scopeid = if_nametoindex(scope);
   1030 		if (*scopeid == 0)
   1031 			goto trynumeric;
   1032 		return 0;
   1033 	}
   1034 
   1035 	/* still unclear about literal, allow numeric only - placeholder */
   1036 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
   1037 		goto trynumeric;
   1038 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
   1039 		goto trynumeric;
   1040 	else
   1041 		goto trynumeric;	/* global */
   1042 
   1043 	/* try to convert to a numeric id as a last resort */
   1044   trynumeric:
   1045 	errno = 0;
   1046 	lscopeid = strtoul(scope, &ep, 10);
   1047 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
   1048 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
   1049 		return 0;
   1050 	else
   1051 		return -1;
   1052 }
   1053 #endif
   1054 
   1055 /* code duplicate with gethnamaddr.c */
   1056 
   1057 static const char AskedForGot[] =
   1058 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
   1059 static FILE *hostf = NULL;
   1060 
   1061 static struct addrinfo *
   1062 getanswer(answer, anslen, qname, qtype, pai)
   1063 	const querybuf *answer;
   1064 	int anslen;
   1065 	const char *qname;
   1066 	int qtype;
   1067 	const struct addrinfo *pai;
   1068 {
   1069 	struct addrinfo sentinel, *cur;
   1070 	struct addrinfo ai;
   1071 	const struct afd *afd;
   1072 	char *canonname;
   1073 	const HEADER *hp;
   1074 	const u_char *cp;
   1075 	int n;
   1076 	const u_char *eom;
   1077 	char *bp, *ep;
   1078 	int type, class, ancount, qdcount;
   1079 	int haveanswer, had_error;
   1080 	char tbuf[MAXDNAME];
   1081 	int (*name_ok) __P((const char *));
   1082 	char hostbuf[8*1024];
   1083 
   1084 	memset(&sentinel, 0, sizeof(sentinel));
   1085 	cur = &sentinel;
   1086 
   1087 	canonname = NULL;
   1088 	eom = answer->buf + anslen;
   1089 	switch (qtype) {
   1090 	case T_A:
   1091 	case T_AAAA:
   1092 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
   1093 		name_ok = res_hnok;
   1094 		break;
   1095 	default:
   1096 		return (NULL);	/* XXX should be abort(); */
   1097 	}
   1098 	/*
   1099 	 * find first satisfactory answer
   1100 	 */
   1101 	hp = &answer->hdr;
   1102 	ancount = ntohs(hp->ancount);
   1103 	qdcount = ntohs(hp->qdcount);
   1104 	bp = hostbuf;
   1105 	ep = hostbuf + sizeof hostbuf;
   1106 	cp = answer->buf + HFIXEDSZ;
   1107 	if (qdcount != 1) {
   1108 		h_errno = NO_RECOVERY;
   1109 		return (NULL);
   1110 	}
   1111 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
   1112 	if ((n < 0) || !(*name_ok)(bp)) {
   1113 		h_errno = NO_RECOVERY;
   1114 		return (NULL);
   1115 	}
   1116 	cp += n + QFIXEDSZ;
   1117 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
   1118 		/* res_send() has already verified that the query name is the
   1119 		 * same as the one we sent; this just gets the expanded name
   1120 		 * (i.e., with the succeeding search-domain tacked on).
   1121 		 */
   1122 		n = strlen(bp) + 1;		/* for the \0 */
   1123 		if (n >= MAXHOSTNAMELEN) {
   1124 			h_errno = NO_RECOVERY;
   1125 			return (NULL);
   1126 		}
   1127 		canonname = bp;
   1128 		bp += n;
   1129 		/* The qname can be abbreviated, but h_name is now absolute. */
   1130 		qname = canonname;
   1131 	}
   1132 	haveanswer = 0;
   1133 	had_error = 0;
   1134 	while (ancount-- > 0 && cp < eom && !had_error) {
   1135 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
   1136 		if ((n < 0) || !(*name_ok)(bp)) {
   1137 			had_error++;
   1138 			continue;
   1139 		}
   1140 		cp += n;			/* name */
   1141 		type = _getshort(cp);
   1142  		cp += INT16SZ;			/* type */
   1143 		class = _getshort(cp);
   1144  		cp += INT16SZ + INT32SZ;	/* class, TTL */
   1145 		n = _getshort(cp);
   1146 		cp += INT16SZ;			/* len */
   1147 		if (class != C_IN) {
   1148 			/* XXX - debug? syslog? */
   1149 			cp += n;
   1150 			continue;		/* XXX - had_error++ ? */
   1151 		}
   1152 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
   1153 		    type == T_CNAME) {
   1154 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
   1155 			if ((n < 0) || !(*name_ok)(tbuf)) {
   1156 				had_error++;
   1157 				continue;
   1158 			}
   1159 			cp += n;
   1160 			/* Get canonical name. */
   1161 			n = strlen(tbuf) + 1;	/* for the \0 */
   1162 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
   1163 				had_error++;
   1164 				continue;
   1165 			}
   1166 			strcpy(bp, tbuf);
   1167 			canonname = bp;
   1168 			bp += n;
   1169 			continue;
   1170 		}
   1171 		if (qtype == T_ANY) {
   1172 			if (!(type == T_A || type == T_AAAA)) {
   1173 				cp += n;
   1174 				continue;
   1175 			}
   1176 		} else if (type != qtype) {
   1177 			if (type != T_KEY && type != T_SIG)
   1178 				syslog(LOG_NOTICE|LOG_AUTH,
   1179 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
   1180 				       qname, p_class(C_IN), p_type(qtype),
   1181 				       p_type(type));
   1182 			cp += n;
   1183 			continue;		/* XXX - had_error++ ? */
   1184 		}
   1185 		switch (type) {
   1186 		case T_A:
   1187 		case T_AAAA:
   1188 			if (strcasecmp(canonname, bp) != 0) {
   1189 				syslog(LOG_NOTICE|LOG_AUTH,
   1190 				       AskedForGot, canonname, bp);
   1191 				cp += n;
   1192 				continue;	/* XXX - had_error++ ? */
   1193 			}
   1194 			if (type == T_A && n != INADDRSZ) {
   1195 				cp += n;
   1196 				continue;
   1197 			}
   1198 			if (type == T_AAAA && n != IN6ADDRSZ) {
   1199 				cp += n;
   1200 				continue;
   1201 			}
   1202 			if (type == T_AAAA) {
   1203 				struct in6_addr in6;
   1204 				memcpy(&in6, cp, IN6ADDRSZ);
   1205 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
   1206 					cp += n;
   1207 					continue;
   1208 				}
   1209 			}
   1210 			if (!haveanswer) {
   1211 				int nn;
   1212 
   1213 				canonname = bp;
   1214 				nn = strlen(bp) + 1;	/* for the \0 */
   1215 				bp += nn;
   1216 			}
   1217 
   1218 			/* don't overwrite pai */
   1219 			ai = *pai;
   1220 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
   1221 			afd = find_afd(ai.ai_family);
   1222 			if (afd == NULL) {
   1223 				cp += n;
   1224 				continue;
   1225 			}
   1226 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
   1227 			if (cur->ai_next == NULL)
   1228 				had_error++;
   1229 			while (cur && cur->ai_next)
   1230 				cur = cur->ai_next;
   1231 			cp += n;
   1232 			break;
   1233 		default:
   1234 			abort();
   1235 		}
   1236 		if (!had_error)
   1237 			haveanswer++;
   1238 	}
   1239 	if (haveanswer) {
   1240 		if (!canonname)
   1241 			(void)get_canonname(pai, sentinel.ai_next, qname);
   1242 		else
   1243 			(void)get_canonname(pai, sentinel.ai_next, canonname);
   1244 		h_errno = NETDB_SUCCESS;
   1245 		return sentinel.ai_next;
   1246 	}
   1247 
   1248 	h_errno = NO_RECOVERY;
   1249 	return NULL;
   1250 }
   1251 
   1252 /*ARGSUSED*/
   1253 static int
   1254 _dns_getaddrinfo(rv, cb_data, ap)
   1255 	void	*rv;
   1256 	void	*cb_data;
   1257 	va_list	 ap;
   1258 {
   1259 	struct addrinfo *ai;
   1260 	querybuf *buf, *buf2;
   1261 	const char *name;
   1262 	const struct addrinfo *pai;
   1263 	struct addrinfo sentinel, *cur;
   1264 	struct res_target q, q2;
   1265 
   1266 	name = va_arg(ap, char *);
   1267 	pai = va_arg(ap, const struct addrinfo *);
   1268 
   1269 	memset(&q, 0, sizeof(q2));
   1270 	memset(&q2, 0, sizeof(q2));
   1271 	memset(&sentinel, 0, sizeof(sentinel));
   1272 	cur = &sentinel;
   1273 
   1274 	buf = malloc(sizeof(*buf));
   1275 	if (buf == NULL) {
   1276 		h_errno = NETDB_INTERNAL;
   1277 		return NS_NOTFOUND;
   1278 	}
   1279 	buf2 = malloc(sizeof(*buf2));
   1280 	if (buf2 == NULL) {
   1281 		free(buf);
   1282 		h_errno = NETDB_INTERNAL;
   1283 		return NS_NOTFOUND;
   1284 	}
   1285 
   1286 	switch (pai->ai_family) {
   1287 	case AF_UNSPEC:
   1288 		/* prefer IPv6 */
   1289 		q.name = name;
   1290 		q.qclass = C_IN;
   1291 		q.qtype = T_AAAA;
   1292 		q.answer = buf->buf;
   1293 		q.anslen = sizeof(buf->buf);
   1294 		q.next = &q2;
   1295 		q2.name = name;
   1296 		q2.qclass = C_IN;
   1297 		q2.qtype = T_A;
   1298 		q2.answer = buf2->buf;
   1299 		q2.anslen = sizeof(buf2->buf);
   1300 		break;
   1301 	case AF_INET:
   1302 		q.name = name;
   1303 		q.qclass = C_IN;
   1304 		q.qtype = T_A;
   1305 		q.answer = buf->buf;
   1306 		q.anslen = sizeof(buf->buf);
   1307 		break;
   1308 	case AF_INET6:
   1309 		q.name = name;
   1310 		q.qclass = C_IN;
   1311 		q.qtype = T_AAAA;
   1312 		q.answer = buf->buf;
   1313 		q.anslen = sizeof(buf->buf);
   1314 		break;
   1315 	default:
   1316 		free(buf);
   1317 		free(buf2);
   1318 		return NS_UNAVAIL;
   1319 	}
   1320 	if (res_searchN(name, &q) < 0) {
   1321 		free(buf);
   1322 		free(buf2);
   1323 		return NS_NOTFOUND;
   1324 	}
   1325 	ai = getanswer(buf, q.n, q.name, q.qtype, pai);
   1326 	if (ai) {
   1327 		cur->ai_next = ai;
   1328 		while (cur && cur->ai_next)
   1329 			cur = cur->ai_next;
   1330 	}
   1331 	if (q.next) {
   1332 		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
   1333 		if (ai)
   1334 			cur->ai_next = ai;
   1335 	}
   1336 	free(buf);
   1337 	free(buf2);
   1338 	if (sentinel.ai_next == NULL)
   1339 		switch (h_errno) {
   1340 		case HOST_NOT_FOUND:
   1341 			return NS_NOTFOUND;
   1342 		case TRY_AGAIN:
   1343 			return NS_TRYAGAIN;
   1344 		default:
   1345 			return NS_UNAVAIL;
   1346 		}
   1347 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1348 	return NS_SUCCESS;
   1349 }
   1350 
   1351 static void
   1352 _sethtent()
   1353 {
   1354 
   1355 	if (!hostf)
   1356 		hostf = fopen(_PATH_HOSTS, "r" );
   1357 	else
   1358 		rewind(hostf);
   1359 }
   1360 
   1361 static void
   1362 _endhtent()
   1363 {
   1364 
   1365 	if (hostf) {
   1366 		(void) fclose(hostf);
   1367 		hostf = NULL;
   1368 	}
   1369 }
   1370 
   1371 static struct addrinfo *
   1372 _gethtent(name, pai)
   1373 	const char *name;
   1374 	const struct addrinfo *pai;
   1375 {
   1376 	char *p;
   1377 	char *cp, *tname, *cname;
   1378 	struct addrinfo hints, *res0, *res;
   1379 	int error;
   1380 	const char *addr;
   1381 	char hostbuf[8*1024];
   1382 
   1383 	if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" )))
   1384 		return (NULL);
   1385  again:
   1386 	if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
   1387 		return (NULL);
   1388 	if (*p == '#')
   1389 		goto again;
   1390 	if (!(cp = strpbrk(p, "#\n")))
   1391 		goto again;
   1392 	*cp = '\0';
   1393 	if (!(cp = strpbrk(p, " \t")))
   1394 		goto again;
   1395 	*cp++ = '\0';
   1396 	addr = p;
   1397 	/* if this is not something we're looking for, skip it. */
   1398 	cname = NULL;
   1399 	while (cp && *cp) {
   1400 		if (*cp == ' ' || *cp == '\t') {
   1401 			cp++;
   1402 			continue;
   1403 		}
   1404 		if (!cname)
   1405 			cname = cp;
   1406 		tname = cp;
   1407 		if ((cp = strpbrk(cp, " \t")) != NULL)
   1408 			*cp++ = '\0';
   1409 		if (strcasecmp(name, tname) == 0)
   1410 			goto found;
   1411 	}
   1412 	goto again;
   1413 
   1414 found:
   1415 	hints = *pai;
   1416 	hints.ai_flags = AI_NUMERICHOST;
   1417 	error = getaddrinfo(addr, NULL, &hints, &res0);
   1418 	if (error)
   1419 		goto again;
   1420 	for (res = res0; res; res = res->ai_next) {
   1421 		/* cover it up */
   1422 		res->ai_flags = pai->ai_flags;
   1423 
   1424 		if (pai->ai_flags & AI_CANONNAME) {
   1425 			if (get_canonname(pai, res, cname) != 0) {
   1426 				freeaddrinfo(res0);
   1427 				goto again;
   1428 			}
   1429 		}
   1430 	}
   1431 	return res0;
   1432 }
   1433 
   1434 /*ARGSUSED*/
   1435 static int
   1436 _files_getaddrinfo(rv, cb_data, ap)
   1437 	void	*rv;
   1438 	void	*cb_data;
   1439 	va_list	 ap;
   1440 {
   1441 	const char *name;
   1442 	const struct addrinfo *pai;
   1443 	struct addrinfo sentinel, *cur;
   1444 	struct addrinfo *p;
   1445 
   1446 	name = va_arg(ap, char *);
   1447 	pai = va_arg(ap, struct addrinfo *);
   1448 
   1449 	memset(&sentinel, 0, sizeof(sentinel));
   1450 	cur = &sentinel;
   1451 
   1452 	_sethtent();
   1453 	while ((p = _gethtent(name, pai)) != NULL) {
   1454 		cur->ai_next = p;
   1455 		while (cur && cur->ai_next)
   1456 			cur = cur->ai_next;
   1457 	}
   1458 	_endhtent();
   1459 
   1460 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1461 	if (sentinel.ai_next == NULL)
   1462 		return NS_NOTFOUND;
   1463 	return NS_SUCCESS;
   1464 }
   1465 
   1466 #ifdef YP
   1467 static char *__ypdomain;
   1468 
   1469 /*ARGSUSED*/
   1470 static struct addrinfo *
   1471 _yphostent(line, pai)
   1472 	char *line;
   1473 	const struct addrinfo *pai;
   1474 {
   1475 	struct addrinfo sentinel, *cur;
   1476 	struct addrinfo hints, *res, *res0;
   1477 	int error;
   1478 	char *p = line;
   1479 	const char *addr, *canonname;
   1480 	char *nextline;
   1481 	char *cp;
   1482 
   1483 	addr = canonname = NULL;
   1484 
   1485 	memset(&sentinel, 0, sizeof(sentinel));
   1486 	cur = &sentinel;
   1487 
   1488 nextline:
   1489 	/* terminate line */
   1490 	cp = strchr(p, '\n');
   1491 	if (cp) {
   1492 		*cp++ = '\0';
   1493 		nextline = cp;
   1494 	} else
   1495 		nextline = NULL;
   1496 
   1497 	cp = strpbrk(p, " \t");
   1498 	if (cp == NULL) {
   1499 		if (canonname == NULL)
   1500 			return (NULL);
   1501 		else
   1502 			goto done;
   1503 	}
   1504 	*cp++ = '\0';
   1505 
   1506 	addr = p;
   1507 
   1508 	while (cp && *cp) {
   1509 		if (*cp == ' ' || *cp == '\t') {
   1510 			cp++;
   1511 			continue;
   1512 		}
   1513 		if (!canonname)
   1514 			canonname = cp;
   1515 		if ((cp = strpbrk(cp, " \t")) != NULL)
   1516 			*cp++ = '\0';
   1517 	}
   1518 
   1519 	hints = *pai;
   1520 	hints.ai_flags = AI_NUMERICHOST;
   1521 	error = getaddrinfo(addr, NULL, &hints, &res0);
   1522 	if (error == 0) {
   1523 		for (res = res0; res; res = res->ai_next) {
   1524 			/* cover it up */
   1525 			res->ai_flags = pai->ai_flags;
   1526 
   1527 			if (pai->ai_flags & AI_CANONNAME)
   1528 				(void)get_canonname(pai, res, canonname);
   1529 		}
   1530 	} else
   1531 		res0 = NULL;
   1532 	if (res0) {
   1533 		cur->ai_next = res0;
   1534 		while (cur && cur->ai_next)
   1535 			cur = cur->ai_next;
   1536 	}
   1537 
   1538 	if (nextline) {
   1539 		p = nextline;
   1540 		goto nextline;
   1541 	}
   1542 
   1543 done:
   1544 	return sentinel.ai_next;
   1545 }
   1546 
   1547 /*ARGSUSED*/
   1548 static int
   1549 _yp_getaddrinfo(rv, cb_data, ap)
   1550 	void	*rv;
   1551 	void	*cb_data;
   1552 	va_list	 ap;
   1553 {
   1554 	struct addrinfo sentinel, *cur;
   1555 	struct addrinfo *ai = NULL;
   1556 	static char *__ypcurrent;
   1557 	int __ypcurrentlen, r;
   1558 	const char *name;
   1559 	const struct addrinfo *pai;
   1560 
   1561 	name = va_arg(ap, char *);
   1562 	pai = va_arg(ap, const struct addrinfo *);
   1563 
   1564 	memset(&sentinel, 0, sizeof(sentinel));
   1565 	cur = &sentinel;
   1566 
   1567 	if (!__ypdomain) {
   1568 		if (_yp_check(&__ypdomain) == 0)
   1569 			return NS_UNAVAIL;
   1570 	}
   1571 	if (__ypcurrent)
   1572 		free(__ypcurrent);
   1573 	__ypcurrent = NULL;
   1574 
   1575 	/* hosts.byname is only for IPv4 (Solaris8) */
   1576 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
   1577 		r = yp_match(__ypdomain, "hosts.byname", name,
   1578 			(int)strlen(name), &__ypcurrent, &__ypcurrentlen);
   1579 		if (r == 0) {
   1580 			struct addrinfo ai4;
   1581 
   1582 			ai4 = *pai;
   1583 			ai4.ai_family = AF_INET;
   1584 			ai = _yphostent(__ypcurrent, &ai4);
   1585 			if (ai) {
   1586 				cur->ai_next = ai;
   1587 				while (cur && cur->ai_next)
   1588 					cur = cur->ai_next;
   1589 			}
   1590 		}
   1591 	}
   1592 
   1593 	/* ipnodes.byname can hold both IPv4/v6 */
   1594 	r = yp_match(__ypdomain, "ipnodes.byname", name,
   1595 		(int)strlen(name), &__ypcurrent, &__ypcurrentlen);
   1596 	if (r == 0) {
   1597 		ai = _yphostent(__ypcurrent, pai);
   1598 		if (ai) {
   1599 			cur->ai_next = ai;
   1600 			while (cur && cur->ai_next)
   1601 				cur = cur->ai_next;
   1602 		}
   1603 	}
   1604 
   1605 	if (sentinel.ai_next == NULL) {
   1606 		h_errno = HOST_NOT_FOUND;
   1607 		return NS_NOTFOUND;
   1608 	}
   1609 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1610 	return NS_SUCCESS;
   1611 }
   1612 #endif
   1613 
   1614 /* resolver logic */
   1615 
   1616 /*
   1617  * Formulate a normal query, send, and await answer.
   1618  * Returned answer is placed in supplied buffer "answer".
   1619  * Perform preliminary check of answer, returning success only
   1620  * if no error is indicated and the answer count is nonzero.
   1621  * Return the size of the response on success, -1 on error.
   1622  * Error number is left in h_errno.
   1623  *
   1624  * Caller must parse answer and determine whether it answers the question.
   1625  */
   1626 static int
   1627 res_queryN(name, target)
   1628 	const char *name;	/* domain name */
   1629 	struct res_target *target;
   1630 {
   1631 	u_char buf[MAXPACKET];
   1632 	HEADER *hp;
   1633 	int n;
   1634 	struct res_target *t;
   1635 	int rcode;
   1636 	int ancount;
   1637 
   1638 	rcode = NOERROR;
   1639 	ancount = 0;
   1640 
   1641 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
   1642 		h_errno = NETDB_INTERNAL;
   1643 		return (-1);
   1644 	}
   1645 
   1646 	for (t = target; t; t = t->next) {
   1647 		int class, type;
   1648 		u_char *answer;
   1649 		int anslen;
   1650 
   1651 		hp = (HEADER *)(void *)t->answer;
   1652 		hp->rcode = NOERROR;	/* default */
   1653 
   1654 		/* make it easier... */
   1655 		class = t->qclass;
   1656 		type = t->qtype;
   1657 		answer = t->answer;
   1658 		anslen = t->anslen;
   1659 #ifdef DEBUG
   1660 		if (_res.options & RES_DEBUG)
   1661 			printf(";; res_query(%s, %d, %d)\n", name, class, type);
   1662 #endif
   1663 
   1664 		n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
   1665 		    buf, sizeof(buf));
   1666 		if (n <= 0) {
   1667 #ifdef DEBUG
   1668 			if (_res.options & RES_DEBUG)
   1669 				printf(";; res_query: mkquery failed\n");
   1670 #endif
   1671 			h_errno = NO_RECOVERY;
   1672 			return (n);
   1673 		}
   1674 		n = res_send(buf, n, answer, anslen);
   1675 #if 0
   1676 		if (n < 0) {
   1677 #ifdef DEBUG
   1678 			if (_res.options & RES_DEBUG)
   1679 				printf(";; res_query: send error\n");
   1680 #endif
   1681 			h_errno = TRY_AGAIN;
   1682 			return (n);
   1683 		}
   1684 #endif
   1685 
   1686 		if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
   1687 			rcode = hp->rcode;	/* record most recent error */
   1688 #ifdef DEBUG
   1689 			if (_res.options & RES_DEBUG)
   1690 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
   1691 				    ntohs(hp->ancount));
   1692 #endif
   1693 			continue;
   1694 		}
   1695 
   1696 		ancount += ntohs(hp->ancount);
   1697 
   1698 		t->n = n;
   1699 	}
   1700 
   1701 	if (ancount == 0) {
   1702 		switch (rcode) {
   1703 		case NXDOMAIN:
   1704 			h_errno = HOST_NOT_FOUND;
   1705 			break;
   1706 		case SERVFAIL:
   1707 			h_errno = TRY_AGAIN;
   1708 			break;
   1709 		case NOERROR:
   1710 			h_errno = NO_DATA;
   1711 			break;
   1712 		case FORMERR:
   1713 		case NOTIMP:
   1714 		case REFUSED:
   1715 		default:
   1716 			h_errno = NO_RECOVERY;
   1717 			break;
   1718 		}
   1719 		return (-1);
   1720 	}
   1721 	return (ancount);
   1722 }
   1723 
   1724 /*
   1725  * Formulate a normal query, send, and retrieve answer in supplied buffer.
   1726  * Return the size of the response on success, -1 on error.
   1727  * If enabled, implement search rules until answer or unrecoverable failure
   1728  * is detected.  Error code, if any, is left in h_errno.
   1729  */
   1730 static int
   1731 res_searchN(name, target)
   1732 	const char *name;	/* domain name */
   1733 	struct res_target *target;
   1734 {
   1735 	const char *cp, * const *domain;
   1736 	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
   1737 	u_int dots;
   1738 	int trailing_dot, ret, saved_herrno;
   1739 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
   1740 
   1741 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
   1742 		h_errno = NETDB_INTERNAL;
   1743 		return (-1);
   1744 	}
   1745 
   1746 	errno = 0;
   1747 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
   1748 	dots = 0;
   1749 	for (cp = name; *cp; cp++)
   1750 		dots += (*cp == '.');
   1751 	trailing_dot = 0;
   1752 	if (cp > name && *--cp == '.')
   1753 		trailing_dot++;
   1754 
   1755 	/*
   1756 	 * if there aren't any dots, it could be a user-level alias
   1757 	 */
   1758 	if (!dots && (cp = __hostalias(name)) != NULL)
   1759 		return (res_queryN(cp, target));
   1760 
   1761 	/*
   1762 	 * If there are dots in the name already, let's just give it a try
   1763 	 * 'as is'.  The threshold can be set with the "ndots" option.
   1764 	 */
   1765 	saved_herrno = -1;
   1766 	if (dots >= _res.ndots) {
   1767 		ret = res_querydomainN(name, NULL, target);
   1768 		if (ret > 0)
   1769 			return (ret);
   1770 		saved_herrno = h_errno;
   1771 		tried_as_is++;
   1772 	}
   1773 
   1774 	/*
   1775 	 * We do at least one level of search if
   1776 	 *	- there is no dot and RES_DEFNAME is set, or
   1777 	 *	- there is at least one dot, there is no trailing dot,
   1778 	 *	  and RES_DNSRCH is set.
   1779 	 */
   1780 	if ((!dots && (_res.options & RES_DEFNAMES)) ||
   1781 	    (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
   1782 		int done = 0;
   1783 
   1784 		for (domain = (const char * const *)_res.dnsrch;
   1785 		   *domain && !done;
   1786 		   domain++) {
   1787 
   1788 			ret = res_querydomainN(name, *domain, target);
   1789 			if (ret > 0)
   1790 				return (ret);
   1791 
   1792 			/*
   1793 			 * If no server present, give up.
   1794 			 * If name isn't found in this domain,
   1795 			 * keep trying higher domains in the search list
   1796 			 * (if that's enabled).
   1797 			 * On a NO_DATA error, keep trying, otherwise
   1798 			 * a wildcard entry of another type could keep us
   1799 			 * from finding this entry higher in the domain.
   1800 			 * If we get some other error (negative answer or
   1801 			 * server failure), then stop searching up,
   1802 			 * but try the input name below in case it's
   1803 			 * fully-qualified.
   1804 			 */
   1805 			if (errno == ECONNREFUSED) {
   1806 				h_errno = TRY_AGAIN;
   1807 				return (-1);
   1808 			}
   1809 
   1810 			switch (h_errno) {
   1811 			case NO_DATA:
   1812 				got_nodata++;
   1813 				/* FALLTHROUGH */
   1814 			case HOST_NOT_FOUND:
   1815 				/* keep trying */
   1816 				break;
   1817 			case TRY_AGAIN:
   1818 				if (hp->rcode == SERVFAIL) {
   1819 					/* try next search element, if any */
   1820 					got_servfail++;
   1821 					break;
   1822 				}
   1823 				/* FALLTHROUGH */
   1824 			default:
   1825 				/* anything else implies that we're done */
   1826 				done++;
   1827 			}
   1828 			/*
   1829 			 * if we got here for some reason other than DNSRCH,
   1830 			 * we only wanted one iteration of the loop, so stop.
   1831 			 */
   1832 			if (!(_res.options & RES_DNSRCH))
   1833 			        done++;
   1834 		}
   1835 	}
   1836 
   1837 	/*
   1838 	 * if we have not already tried the name "as is", do that now.
   1839 	 * note that we do this regardless of how many dots were in the
   1840 	 * name or whether it ends with a dot.
   1841 	 */
   1842 	if (!tried_as_is) {
   1843 		ret = res_querydomainN(name, NULL, target);
   1844 		if (ret > 0)
   1845 			return (ret);
   1846 	}
   1847 
   1848 	/*
   1849 	 * if we got here, we didn't satisfy the search.
   1850 	 * if we did an initial full query, return that query's h_errno
   1851 	 * (note that we wouldn't be here if that query had succeeded).
   1852 	 * else if we ever got a nodata, send that back as the reason.
   1853 	 * else send back meaningless h_errno, that being the one from
   1854 	 * the last DNSRCH we did.
   1855 	 */
   1856 	if (saved_herrno != -1)
   1857 		h_errno = saved_herrno;
   1858 	else if (got_nodata)
   1859 		h_errno = NO_DATA;
   1860 	else if (got_servfail)
   1861 		h_errno = TRY_AGAIN;
   1862 	return (-1);
   1863 }
   1864 
   1865 /*
   1866  * Perform a call on res_query on the concatenation of name and domain,
   1867  * removing a trailing dot from name if domain is NULL.
   1868  */
   1869 static int
   1870 res_querydomainN(name, domain, target)
   1871 	const char *name, *domain;
   1872 	struct res_target *target;
   1873 {
   1874 	char nbuf[MAXDNAME];
   1875 	const char *longname = nbuf;
   1876 	size_t n, d;
   1877 
   1878 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
   1879 		h_errno = NETDB_INTERNAL;
   1880 		return (-1);
   1881 	}
   1882 #ifdef DEBUG
   1883 	if (_res.options & RES_DEBUG)
   1884 		printf(";; res_querydomain(%s, %s)\n",
   1885 			name, domain?domain:"<Nil>");
   1886 #endif
   1887 	if (domain == NULL) {
   1888 		/*
   1889 		 * Check for trailing '.';
   1890 		 * copy without '.' if present.
   1891 		 */
   1892 		n = strlen(name);
   1893 		if (n + 1 > sizeof(nbuf)) {
   1894 			h_errno = NO_RECOVERY;
   1895 			return (-1);
   1896 		}
   1897 		if (n > 0 && name[--n] == '.') {
   1898 			strncpy(nbuf, name, n);
   1899 			nbuf[n] = '\0';
   1900 		} else
   1901 			longname = name;
   1902 	} else {
   1903 		n = strlen(name);
   1904 		d = strlen(domain);
   1905 		if (n + 1 + d + 1 > sizeof(nbuf)) {
   1906 			h_errno = NO_RECOVERY;
   1907 			return (-1);
   1908 		}
   1909 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
   1910 	}
   1911 	return (res_queryN(longname, target));
   1912 }
   1913