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