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