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