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