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