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