Home | History | Annotate | Line # | Download | only in net
getaddrinfo.c revision 1.88
      1 /*	$NetBSD: getaddrinfo.c,v 1.88 2007/05/10 18:44:24 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.88 2007/05/10 18:44:24 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, 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 	memset(&ai, 0, sizeof(ai));
    357 	pai = &ai;
    358 	pai->ai_flags = 0;
    359 	pai->ai_family = PF_UNSPEC;
    360 	pai->ai_socktype = ANY;
    361 	pai->ai_protocol = ANY;
    362 	pai->ai_addrlen = 0;
    363 	pai->ai_canonname = NULL;
    364 	pai->ai_addr = NULL;
    365 	pai->ai_next = NULL;
    366 
    367 	if (hostname == NULL && servname == NULL)
    368 		return EAI_NONAME;
    369 	if (hints) {
    370 		/* error check for hints */
    371 		if (hints->ai_addrlen || hints->ai_canonname ||
    372 		    hints->ai_addr || hints->ai_next)
    373 			ERR(EAI_BADHINTS); /* xxx */
    374 		if (hints->ai_flags & ~AI_MASK)
    375 			ERR(EAI_BADFLAGS);
    376 		switch (hints->ai_family) {
    377 		case PF_UNSPEC:
    378 		case PF_INET:
    379 #ifdef INET6
    380 		case PF_INET6:
    381 #endif
    382 			break;
    383 		default:
    384 			ERR(EAI_FAMILY);
    385 		}
    386 		memcpy(pai, hints, sizeof(*pai));
    387 
    388 		/*
    389 		 * if both socktype/protocol are specified, check if they
    390 		 * are meaningful combination.
    391 		 */
    392 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
    393 			for (ex = explore; ex->e_af >= 0; ex++) {
    394 				if (pai->ai_family != ex->e_af)
    395 					continue;
    396 				if (ex->e_socktype == ANY)
    397 					continue;
    398 				if (ex->e_protocol == ANY)
    399 					continue;
    400 				if (pai->ai_socktype == ex->e_socktype
    401 				 && pai->ai_protocol != ex->e_protocol) {
    402 					ERR(EAI_BADHINTS);
    403 				}
    404 			}
    405 		}
    406 	}
    407 
    408 	/*
    409 	 * check for special cases.  (1) numeric servname is disallowed if
    410 	 * socktype/protocol are left unspecified. (2) servname is disallowed
    411 	 * for raw and other inet{,6} sockets.
    412 	 */
    413 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
    414 #ifdef PF_INET6
    415 	 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
    416 #endif
    417 	    ) {
    418 		ai0 = *pai;	/* backup *pai */
    419 
    420 		if (pai->ai_family == PF_UNSPEC) {
    421 #ifdef PF_INET6
    422 			pai->ai_family = PF_INET6;
    423 #else
    424 			pai->ai_family = PF_INET;
    425 #endif
    426 		}
    427 		error = get_portmatch(pai, servname);
    428 		if (error)
    429 			ERR(error);
    430 
    431 		*pai = ai0;
    432 	}
    433 
    434 	ai0 = *pai;
    435 
    436 	/* NULL hostname, or numeric hostname */
    437 	for (ex = explore; ex->e_af >= 0; ex++) {
    438 		*pai = ai0;
    439 
    440 		/* PF_UNSPEC entries are prepared for DNS queries only */
    441 		if (ex->e_af == PF_UNSPEC)
    442 			continue;
    443 
    444 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    445 			continue;
    446 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
    447 			continue;
    448 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
    449 			continue;
    450 
    451 		if (pai->ai_family == PF_UNSPEC)
    452 			pai->ai_family = ex->e_af;
    453 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    454 			pai->ai_socktype = ex->e_socktype;
    455 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    456 			pai->ai_protocol = ex->e_protocol;
    457 
    458 		if (hostname == NULL)
    459 			error = explore_null(pai, servname, &cur->ai_next);
    460 		else
    461 			error = explore_numeric_scope(pai, hostname, servname,
    462 			    &cur->ai_next);
    463 
    464 		if (error)
    465 			goto free;
    466 
    467 		while (cur->ai_next)
    468 			cur = cur->ai_next;
    469 	}
    470 
    471 	/*
    472 	 * XXX
    473 	 * If numeric representation of AF1 can be interpreted as FQDN
    474 	 * representation of AF2, we need to think again about the code below.
    475 	 */
    476 	if (sentinel.ai_next)
    477 		goto good;
    478 
    479 	if (hostname == NULL)
    480 		ERR(EAI_NODATA);
    481 	if (pai->ai_flags & AI_NUMERICHOST)
    482 		ERR(EAI_NONAME);
    483 
    484 	/*
    485 	 * hostname as alphabetical name.
    486 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
    487 	 * outer loop by AFs.
    488 	 */
    489 	for (ex = explore; ex->e_af >= 0; ex++) {
    490 		*pai = ai0;
    491 
    492 		/* require exact match for family field */
    493 		if (pai->ai_family != ex->e_af)
    494 			continue;
    495 
    496 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
    497 				WILD_SOCKTYPE(ex))) {
    498 			continue;
    499 		}
    500 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
    501 				WILD_PROTOCOL(ex))) {
    502 			continue;
    503 		}
    504 
    505 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    506 			pai->ai_socktype = ex->e_socktype;
    507 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    508 			pai->ai_protocol = ex->e_protocol;
    509 
    510 		error = explore_fqdn(pai, hostname, servname,
    511 			&cur->ai_next);
    512 
    513 		while (cur && cur->ai_next)
    514 			cur = cur->ai_next;
    515 	}
    516 
    517 	/* XXX */
    518 	if (sentinel.ai_next)
    519 		error = 0;
    520 
    521 	if (error)
    522 		goto free;
    523 	if (error == 0) {
    524 		if (sentinel.ai_next) {
    525  good:
    526 			*res = sentinel.ai_next;
    527 			return SUCCESS;
    528 		} else
    529 			error = EAI_FAIL;
    530 	}
    531  free:
    532  bad:
    533 	if (sentinel.ai_next)
    534 		freeaddrinfo(sentinel.ai_next);
    535 	*res = NULL;
    536 	return error;
    537 }
    538 
    539 /*
    540  * FQDN hostname, DNS lookup
    541  */
    542 static int
    543 explore_fqdn(const struct addrinfo *pai, const char *hostname,
    544     const char *servname, struct addrinfo **res)
    545 {
    546 	struct addrinfo *result;
    547 	struct addrinfo *cur;
    548 	int error = 0;
    549 	static const ns_dtab dtab[] = {
    550 		NS_FILES_CB(_files_getaddrinfo, NULL)
    551 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
    552 		NS_NIS_CB(_yp_getaddrinfo, NULL)
    553 		NS_NULL_CB
    554 	};
    555 
    556 	_DIAGASSERT(pai != NULL);
    557 	/* hostname may be NULL */
    558 	/* servname may be NULL */
    559 	_DIAGASSERT(res != NULL);
    560 
    561 	result = NULL;
    562 
    563 	/*
    564 	 * if the servname does not match socktype/protocol, ignore it.
    565 	 */
    566 	if (get_portmatch(pai, servname) != 0)
    567 		return 0;
    568 
    569 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
    570 			default_dns_files, hostname, pai)) {
    571 	case NS_TRYAGAIN:
    572 		error = EAI_AGAIN;
    573 		goto free;
    574 	case NS_UNAVAIL:
    575 		error = EAI_FAIL;
    576 		goto free;
    577 	case NS_NOTFOUND:
    578 		error = EAI_NODATA;
    579 		goto free;
    580 	case NS_SUCCESS:
    581 		error = 0;
    582 		for (cur = result; cur; cur = cur->ai_next) {
    583 			GET_PORT(cur, servname);
    584 			/* canonname should be filled already */
    585 		}
    586 		break;
    587 	}
    588 
    589 	*res = result;
    590 
    591 	return 0;
    592 
    593 free:
    594 	if (result)
    595 		freeaddrinfo(result);
    596 	return error;
    597 }
    598 
    599 /*
    600  * hostname == NULL.
    601  * passive socket -> anyaddr (0.0.0.0 or ::)
    602  * non-passive socket -> localhost (127.0.0.1 or ::1)
    603  */
    604 static int
    605 explore_null(const struct addrinfo *pai, const char *servname,
    606     struct addrinfo **res)
    607 {
    608 	int s;
    609 	const struct afd *afd;
    610 	struct addrinfo *cur;
    611 	struct addrinfo sentinel;
    612 	int error;
    613 
    614 	_DIAGASSERT(pai != NULL);
    615 	/* servname may be NULL */
    616 	_DIAGASSERT(res != NULL);
    617 
    618 	*res = NULL;
    619 	sentinel.ai_next = NULL;
    620 	cur = &sentinel;
    621 
    622 	/*
    623 	 * filter out AFs that are not supported by the kernel
    624 	 * XXX errno?
    625 	 */
    626 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    627 	if (s < 0) {
    628 		if (errno != EMFILE)
    629 			return 0;
    630 	} else
    631 		close(s);
    632 
    633 	/*
    634 	 * if the servname does not match socktype/protocol, ignore it.
    635 	 */
    636 	if (get_portmatch(pai, servname) != 0)
    637 		return 0;
    638 
    639 	afd = find_afd(pai->ai_family);
    640 	if (afd == NULL)
    641 		return 0;
    642 
    643 	if (pai->ai_flags & AI_PASSIVE) {
    644 		GET_AI(cur->ai_next, afd, afd->a_addrany);
    645 		/* xxx meaningless?
    646 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
    647 		 */
    648 		GET_PORT(cur->ai_next, servname);
    649 	} else {
    650 		GET_AI(cur->ai_next, afd, afd->a_loopback);
    651 		/* xxx meaningless?
    652 		 * GET_CANONNAME(cur->ai_next, "localhost");
    653 		 */
    654 		GET_PORT(cur->ai_next, servname);
    655 	}
    656 	cur = cur->ai_next;
    657 
    658 	*res = sentinel.ai_next;
    659 	return 0;
    660 
    661 free:
    662 	if (sentinel.ai_next)
    663 		freeaddrinfo(sentinel.ai_next);
    664 	return error;
    665 }
    666 
    667 /*
    668  * numeric hostname
    669  */
    670 static int
    671 explore_numeric(const struct addrinfo *pai, const char *hostname,
    672     const char *servname, struct addrinfo **res, const char *canonname)
    673 {
    674 	const struct afd *afd;
    675 	struct addrinfo *cur;
    676 	struct addrinfo sentinel;
    677 	int error;
    678 	char pton[PTON_MAX];
    679 
    680 	_DIAGASSERT(pai != NULL);
    681 	/* hostname may be NULL */
    682 	/* servname may be NULL */
    683 	_DIAGASSERT(res != NULL);
    684 
    685 	*res = NULL;
    686 	sentinel.ai_next = NULL;
    687 	cur = &sentinel;
    688 
    689 	/*
    690 	 * if the servname does not match socktype/protocol, ignore it.
    691 	 */
    692 	if (get_portmatch(pai, servname) != 0)
    693 		return 0;
    694 
    695 	afd = find_afd(pai->ai_family);
    696 	if (afd == NULL)
    697 		return 0;
    698 
    699 	switch (afd->a_af) {
    700 #if 0 /*X/Open spec*/
    701 	case AF_INET:
    702 		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
    703 			if (pai->ai_family == afd->a_af ||
    704 			    pai->ai_family == PF_UNSPEC /*?*/) {
    705 				GET_AI(cur->ai_next, afd, pton);
    706 				GET_PORT(cur->ai_next, servname);
    707 				if ((pai->ai_flags & AI_CANONNAME)) {
    708 					/*
    709 					 * Set the numeric address itself as
    710 					 * the canonical name, based on a
    711 					 * clarification in rfc2553bis-03.
    712 					 */
    713 					GET_CANONNAME(cur->ai_next, canonname);
    714 				}
    715 				while (cur && cur->ai_next)
    716 					cur = cur->ai_next;
    717 			} else
    718 				ERR(EAI_FAMILY);	/*xxx*/
    719 		}
    720 		break;
    721 #endif
    722 	default:
    723 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
    724 			if (pai->ai_family == afd->a_af ||
    725 			    pai->ai_family == PF_UNSPEC /*?*/) {
    726 				GET_AI(cur->ai_next, afd, pton);
    727 				GET_PORT(cur->ai_next, servname);
    728 				if ((pai->ai_flags & AI_CANONNAME)) {
    729 					/*
    730 					 * Set the numeric address itself as
    731 					 * the canonical name, based on a
    732 					 * clarification in rfc2553bis-03.
    733 					 */
    734 					GET_CANONNAME(cur->ai_next, canonname);
    735 				}
    736 				while (cur->ai_next)
    737 					cur = cur->ai_next;
    738 			} else
    739 				ERR(EAI_FAMILY);	/*xxx*/
    740 		}
    741 		break;
    742 	}
    743 
    744 	*res = sentinel.ai_next;
    745 	return 0;
    746 
    747 free:
    748 bad:
    749 	if (sentinel.ai_next)
    750 		freeaddrinfo(sentinel.ai_next);
    751 	return error;
    752 }
    753 
    754 /*
    755  * numeric hostname with scope
    756  */
    757 static int
    758 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
    759     const char *servname, struct addrinfo **res)
    760 {
    761 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
    762 	return explore_numeric(pai, hostname, servname, res, hostname);
    763 #else
    764 	const struct afd *afd;
    765 	struct addrinfo *cur;
    766 	int error;
    767 	char *cp, *hostname2 = NULL, *scope, *addr;
    768 	struct sockaddr_in6 *sin6;
    769 
    770 	_DIAGASSERT(pai != NULL);
    771 	/* hostname may be NULL */
    772 	/* servname may be NULL */
    773 	_DIAGASSERT(res != NULL);
    774 
    775 	/*
    776 	 * if the servname does not match socktype/protocol, ignore it.
    777 	 */
    778 	if (get_portmatch(pai, servname) != 0)
    779 		return 0;
    780 
    781 	afd = find_afd(pai->ai_family);
    782 	if (afd == NULL)
    783 		return 0;
    784 
    785 	if (!afd->a_scoped)
    786 		return explore_numeric(pai, hostname, servname, res, hostname);
    787 
    788 	cp = strchr(hostname, SCOPE_DELIMITER);
    789 	if (cp == NULL)
    790 		return explore_numeric(pai, hostname, servname, res, hostname);
    791 
    792 	/*
    793 	 * Handle special case of <scoped_address><delimiter><scope id>
    794 	 */
    795 	hostname2 = strdup(hostname);
    796 	if (hostname2 == NULL)
    797 		return EAI_MEMORY;
    798 	/* terminate at the delimiter */
    799 	hostname2[cp - hostname] = '\0';
    800 	addr = hostname2;
    801 	scope = cp + 1;
    802 
    803 	error = explore_numeric(pai, addr, servname, res, hostname);
    804 	if (error == 0) {
    805 		u_int32_t scopeid;
    806 
    807 		for (cur = *res; cur; cur = cur->ai_next) {
    808 			if (cur->ai_family != AF_INET6)
    809 				continue;
    810 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
    811 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
    812 				free(hostname2);
    813 				return(EAI_NODATA); /* XXX: is return OK? */
    814 			}
    815 			sin6->sin6_scope_id = scopeid;
    816 		}
    817 	}
    818 
    819 	free(hostname2);
    820 
    821 	return error;
    822 #endif
    823 }
    824 
    825 static int
    826 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
    827 {
    828 
    829 	_DIAGASSERT(pai != NULL);
    830 	_DIAGASSERT(ai != NULL);
    831 	_DIAGASSERT(str != NULL);
    832 
    833 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
    834 		ai->ai_canonname = strdup(str);
    835 		if (ai->ai_canonname == NULL)
    836 			return EAI_MEMORY;
    837 	}
    838 	return 0;
    839 }
    840 
    841 static struct addrinfo *
    842 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
    843 {
    844 	char *p;
    845 	struct addrinfo *ai;
    846 
    847 	_DIAGASSERT(pai != NULL);
    848 	_DIAGASSERT(afd != NULL);
    849 	_DIAGASSERT(addr != NULL);
    850 
    851 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
    852 		+ (afd->a_socklen));
    853 	if (ai == NULL)
    854 		return NULL;
    855 
    856 	memcpy(ai, pai, sizeof(struct addrinfo));
    857 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
    858 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
    859 	ai->ai_addr->sa_len = afd->a_socklen;
    860 	ai->ai_addrlen = afd->a_socklen;
    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 		struct servent_data svd;
    923 		struct servent sv;
    924 		if (ai->ai_flags & AI_NUMERICSERV)
    925 			return EAI_NONAME;
    926 
    927 		switch (ai->ai_socktype) {
    928 		case SOCK_DGRAM:
    929 			proto = "udp";
    930 			break;
    931 		case SOCK_STREAM:
    932 			proto = "tcp";
    933 			break;
    934 		default:
    935 			proto = NULL;
    936 			break;
    937 		}
    938 
    939 		(void)memset(&svd, 0, sizeof(svd));
    940 		sp = getservbyname_r(servname, proto, &sv, &svd);
    941 		endservent_r(&svd);
    942 		if (sp == 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 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1153 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1154 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
   1155 				       qname, p_class(C_IN), p_type(qtype),
   1156 				       p_type(type));
   1157 			}
   1158 			cp += n;
   1159 			continue;		/* XXX - had_error++ ? */
   1160 		}
   1161 		switch (type) {
   1162 		case T_A:
   1163 		case T_AAAA:
   1164 			if (strcasecmp(canonname, bp) != 0) {
   1165 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1166 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1167 				       AskedForGot, canonname, bp);
   1168 				cp += n;
   1169 				continue;	/* XXX - had_error++ ? */
   1170 			}
   1171 			if (type == T_A && n != INADDRSZ) {
   1172 				cp += n;
   1173 				continue;
   1174 			}
   1175 			if (type == T_AAAA && n != IN6ADDRSZ) {
   1176 				cp += n;
   1177 				continue;
   1178 			}
   1179 			if (type == T_AAAA) {
   1180 				struct in6_addr in6;
   1181 				memcpy(&in6, cp, IN6ADDRSZ);
   1182 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
   1183 					cp += n;
   1184 					continue;
   1185 				}
   1186 			}
   1187 			if (!haveanswer) {
   1188 				int nn;
   1189 
   1190 				canonname = bp;
   1191 				nn = strlen(bp) + 1;	/* for the \0 */
   1192 				bp += nn;
   1193 			}
   1194 
   1195 			/* don't overwrite pai */
   1196 			ai = *pai;
   1197 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
   1198 			afd = find_afd(ai.ai_family);
   1199 			if (afd == NULL) {
   1200 				cp += n;
   1201 				continue;
   1202 			}
   1203 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
   1204 			if (cur->ai_next == NULL)
   1205 				had_error++;
   1206 			while (cur && cur->ai_next)
   1207 				cur = cur->ai_next;
   1208 			cp += n;
   1209 			break;
   1210 		default:
   1211 			abort();
   1212 		}
   1213 		if (!had_error)
   1214 			haveanswer++;
   1215 	}
   1216 	if (haveanswer) {
   1217 		if (!canonname)
   1218 			(void)get_canonname(pai, sentinel.ai_next, qname);
   1219 		else
   1220 			(void)get_canonname(pai, sentinel.ai_next, canonname);
   1221 		h_errno = NETDB_SUCCESS;
   1222 		return sentinel.ai_next;
   1223 	}
   1224 
   1225 	h_errno = NO_RECOVERY;
   1226 	return NULL;
   1227 }
   1228 
   1229 #define SORTEDADDR(p)	(((struct sockaddr_in *)(void *)(p->ai_next->ai_addr))->sin_addr.s_addr)
   1230 #define SORTMATCH(p, s) ((SORTEDADDR(p) & (s).mask) == (s).addr.s_addr)
   1231 
   1232 static void
   1233 aisort(struct addrinfo *s, res_state res)
   1234 {
   1235 	struct addrinfo head, *t, *p;
   1236 	int i;
   1237 
   1238 	head.ai_next = NULL;
   1239 	t = &head;
   1240 
   1241 	for (i = 0; i < res->nsort; i++) {
   1242 		p = s;
   1243 		while (p->ai_next) {
   1244 			if ((p->ai_next->ai_family != AF_INET)
   1245 			|| SORTMATCH(p, res->sort_list[i])) {
   1246 				t->ai_next = p->ai_next;
   1247 				t = t->ai_next;
   1248 				p->ai_next = p->ai_next->ai_next;
   1249 			} else {
   1250 				p = p->ai_next;
   1251 			}
   1252 		}
   1253 	}
   1254 
   1255 	/* add rest of list and reset s to the new list*/
   1256 	t->ai_next = s->ai_next;
   1257 	s->ai_next = head.ai_next;
   1258 }
   1259 
   1260 /*ARGSUSED*/
   1261 static int
   1262 _dns_getaddrinfo(void *rv, void	*cb_data, va_list ap)
   1263 {
   1264 	struct addrinfo *ai;
   1265 	querybuf *buf, *buf2;
   1266 	const char *name;
   1267 	const struct addrinfo *pai;
   1268 	struct addrinfo sentinel, *cur;
   1269 	struct res_target q, q2;
   1270 	res_state res;
   1271 
   1272 	name = va_arg(ap, char *);
   1273 	pai = va_arg(ap, const struct addrinfo *);
   1274 
   1275 	memset(&q, 0, sizeof(q));
   1276 	memset(&q2, 0, sizeof(q2));
   1277 	memset(&sentinel, 0, sizeof(sentinel));
   1278 	cur = &sentinel;
   1279 
   1280 	buf = malloc(sizeof(*buf));
   1281 	if (buf == NULL) {
   1282 		h_errno = NETDB_INTERNAL;
   1283 		return NS_NOTFOUND;
   1284 	}
   1285 	buf2 = malloc(sizeof(*buf2));
   1286 	if (buf2 == NULL) {
   1287 		free(buf);
   1288 		h_errno = NETDB_INTERNAL;
   1289 		return NS_NOTFOUND;
   1290 	}
   1291 
   1292 	switch (pai->ai_family) {
   1293 	case AF_UNSPEC:
   1294 		/* prefer IPv6 */
   1295 		q.name = name;
   1296 		q.qclass = C_IN;
   1297 		q.qtype = T_AAAA;
   1298 		q.answer = buf->buf;
   1299 		q.anslen = sizeof(buf->buf);
   1300 		q.next = &q2;
   1301 		q2.name = name;
   1302 		q2.qclass = C_IN;
   1303 		q2.qtype = T_A;
   1304 		q2.answer = buf2->buf;
   1305 		q2.anslen = sizeof(buf2->buf);
   1306 		break;
   1307 	case AF_INET:
   1308 		q.name = name;
   1309 		q.qclass = C_IN;
   1310 		q.qtype = T_A;
   1311 		q.answer = buf->buf;
   1312 		q.anslen = sizeof(buf->buf);
   1313 		break;
   1314 	case AF_INET6:
   1315 		q.name = name;
   1316 		q.qclass = C_IN;
   1317 		q.qtype = T_AAAA;
   1318 		q.answer = buf->buf;
   1319 		q.anslen = sizeof(buf->buf);
   1320 		break;
   1321 	default:
   1322 		free(buf);
   1323 		free(buf2);
   1324 		return NS_UNAVAIL;
   1325 	}
   1326 
   1327 	res = __res_get_state();
   1328 	if (res == NULL) {
   1329 		free(buf);
   1330 		free(buf2);
   1331 		return NS_NOTFOUND;
   1332 	}
   1333 
   1334 	if (res_searchN(name, &q, res) < 0) {
   1335 		__res_put_state(res);
   1336 		free(buf);
   1337 		free(buf2);
   1338 		return NS_NOTFOUND;
   1339 	}
   1340 	ai = getanswer(buf, q.n, q.name, q.qtype, pai);
   1341 	if (ai) {
   1342 		cur->ai_next = ai;
   1343 		while (cur && cur->ai_next)
   1344 			cur = cur->ai_next;
   1345 	}
   1346 	if (q.next) {
   1347 		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
   1348 		if (ai)
   1349 			cur->ai_next = ai;
   1350 	}
   1351 	free(buf);
   1352 	free(buf2);
   1353 	if (sentinel.ai_next == NULL) {
   1354 		__res_put_state(res);
   1355 		switch (h_errno) {
   1356 		case HOST_NOT_FOUND:
   1357 			return NS_NOTFOUND;
   1358 		case TRY_AGAIN:
   1359 			return NS_TRYAGAIN;
   1360 		default:
   1361 			return NS_UNAVAIL;
   1362 		}
   1363 	}
   1364 
   1365 	if (res->nsort)
   1366 		aisort(&sentinel, res);
   1367 
   1368 	__res_put_state(res);
   1369 
   1370 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1371 	return NS_SUCCESS;
   1372 }
   1373 
   1374 static void
   1375 _sethtent(FILE **hostf)
   1376 {
   1377 
   1378 	if (!*hostf)
   1379 		*hostf = fopen(_PATH_HOSTS, "r" );
   1380 	else
   1381 		rewind(*hostf);
   1382 }
   1383 
   1384 static void
   1385 _endhtent(FILE **hostf)
   1386 {
   1387 
   1388 	if (*hostf) {
   1389 		(void) fclose(*hostf);
   1390 		*hostf = NULL;
   1391 	}
   1392 }
   1393 
   1394 static struct addrinfo *
   1395 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
   1396 {
   1397 	char *p;
   1398 	char *cp, *tname, *cname;
   1399 	struct addrinfo hints, *res0, *res;
   1400 	int error;
   1401 	const char *addr;
   1402 	char hostbuf[8*1024];
   1403 
   1404 	_DIAGASSERT(name != NULL);
   1405 	_DIAGASSERT(pai != NULL);
   1406 
   1407 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
   1408 		return (NULL);
   1409  again:
   1410 	if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
   1411 		return (NULL);
   1412 	if (*p == '#')
   1413 		goto again;
   1414 	if (!(cp = strpbrk(p, "#\n")))
   1415 		goto again;
   1416 	*cp = '\0';
   1417 	if (!(cp = strpbrk(p, " \t")))
   1418 		goto again;
   1419 	*cp++ = '\0';
   1420 	addr = p;
   1421 	/* if this is not something we're looking for, skip it. */
   1422 	cname = NULL;
   1423 	while (cp && *cp) {
   1424 		if (*cp == ' ' || *cp == '\t') {
   1425 			cp++;
   1426 			continue;
   1427 		}
   1428 		if (!cname)
   1429 			cname = cp;
   1430 		tname = cp;
   1431 		if ((cp = strpbrk(cp, " \t")) != NULL)
   1432 			*cp++ = '\0';
   1433 		if (strcasecmp(name, tname) == 0)
   1434 			goto found;
   1435 	}
   1436 	goto again;
   1437 
   1438 found:
   1439 	hints = *pai;
   1440 	hints.ai_flags = AI_NUMERICHOST;
   1441 	error = getaddrinfo(addr, NULL, &hints, &res0);
   1442 	if (error)
   1443 		goto again;
   1444 	for (res = res0; res; res = res->ai_next) {
   1445 		/* cover it up */
   1446 		res->ai_flags = pai->ai_flags;
   1447 
   1448 		if (pai->ai_flags & AI_CANONNAME) {
   1449 			if (get_canonname(pai, res, cname) != 0) {
   1450 				freeaddrinfo(res0);
   1451 				goto again;
   1452 			}
   1453 		}
   1454 	}
   1455 	return res0;
   1456 }
   1457 
   1458 /*ARGSUSED*/
   1459 static int
   1460 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
   1461 {
   1462 	const char *name;
   1463 	const struct addrinfo *pai;
   1464 	struct addrinfo sentinel, *cur;
   1465 	struct addrinfo *p;
   1466 #ifndef _REENTRANT
   1467 	static
   1468 #endif
   1469 	FILE *hostf = NULL;
   1470 
   1471 	name = va_arg(ap, char *);
   1472 	pai = va_arg(ap, struct addrinfo *);
   1473 
   1474 	memset(&sentinel, 0, sizeof(sentinel));
   1475 	cur = &sentinel;
   1476 
   1477 	_sethtent(&hostf);
   1478 	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
   1479 		cur->ai_next = p;
   1480 		while (cur && cur->ai_next)
   1481 			cur = cur->ai_next;
   1482 	}
   1483 	_endhtent(&hostf);
   1484 
   1485 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1486 	if (sentinel.ai_next == NULL)
   1487 		return NS_NOTFOUND;
   1488 	return NS_SUCCESS;
   1489 }
   1490 
   1491 #ifdef YP
   1492 /*ARGSUSED*/
   1493 static struct addrinfo *
   1494 _yphostent(char *line, const struct addrinfo *pai)
   1495 {
   1496 	struct addrinfo sentinel, *cur;
   1497 	struct addrinfo hints, *res, *res0;
   1498 	int error;
   1499 	char *p;
   1500 	const char *addr, *canonname;
   1501 	char *nextline;
   1502 	char *cp;
   1503 
   1504 	_DIAGASSERT(line != NULL);
   1505 	_DIAGASSERT(pai != NULL);
   1506 
   1507 	p = line;
   1508 	addr = canonname = NULL;
   1509 
   1510 	memset(&sentinel, 0, sizeof(sentinel));
   1511 	cur = &sentinel;
   1512 
   1513 nextline:
   1514 	/* terminate line */
   1515 	cp = strchr(p, '\n');
   1516 	if (cp) {
   1517 		*cp++ = '\0';
   1518 		nextline = cp;
   1519 	} else
   1520 		nextline = NULL;
   1521 
   1522 	cp = strpbrk(p, " \t");
   1523 	if (cp == NULL) {
   1524 		if (canonname == NULL)
   1525 			return (NULL);
   1526 		else
   1527 			goto done;
   1528 	}
   1529 	*cp++ = '\0';
   1530 
   1531 	addr = p;
   1532 
   1533 	while (cp && *cp) {
   1534 		if (*cp == ' ' || *cp == '\t') {
   1535 			cp++;
   1536 			continue;
   1537 		}
   1538 		if (!canonname)
   1539 			canonname = cp;
   1540 		if ((cp = strpbrk(cp, " \t")) != NULL)
   1541 			*cp++ = '\0';
   1542 	}
   1543 
   1544 	hints = *pai;
   1545 	hints.ai_flags = AI_NUMERICHOST;
   1546 	error = getaddrinfo(addr, NULL, &hints, &res0);
   1547 	if (error == 0) {
   1548 		for (res = res0; res; res = res->ai_next) {
   1549 			/* cover it up */
   1550 			res->ai_flags = pai->ai_flags;
   1551 
   1552 			if (pai->ai_flags & AI_CANONNAME)
   1553 				(void)get_canonname(pai, res, canonname);
   1554 		}
   1555 	} else
   1556 		res0 = NULL;
   1557 	if (res0) {
   1558 		cur->ai_next = res0;
   1559 		while (cur->ai_next)
   1560 			cur = cur->ai_next;
   1561 	}
   1562 
   1563 	if (nextline) {
   1564 		p = nextline;
   1565 		goto nextline;
   1566 	}
   1567 
   1568 done:
   1569 	return sentinel.ai_next;
   1570 }
   1571 
   1572 /*ARGSUSED*/
   1573 static int
   1574 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
   1575 {
   1576 	struct addrinfo sentinel, *cur;
   1577 	struct addrinfo *ai = NULL;
   1578 	char *ypbuf;
   1579 	int ypbuflen, r;
   1580 	const char *name;
   1581 	const struct addrinfo *pai;
   1582 	char *ypdomain;
   1583 
   1584 	if (_yp_check(&ypdomain) == 0)
   1585 		return NS_UNAVAIL;
   1586 
   1587 	name = va_arg(ap, char *);
   1588 	pai = va_arg(ap, const struct addrinfo *);
   1589 
   1590 	memset(&sentinel, 0, sizeof(sentinel));
   1591 	cur = &sentinel;
   1592 
   1593 	/* hosts.byname is only for IPv4 (Solaris8) */
   1594 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
   1595 		r = yp_match(ypdomain, "hosts.byname", name,
   1596 			(int)strlen(name), &ypbuf, &ypbuflen);
   1597 		if (r == 0) {
   1598 			struct addrinfo ai4;
   1599 
   1600 			ai4 = *pai;
   1601 			ai4.ai_family = AF_INET;
   1602 			ai = _yphostent(ypbuf, &ai4);
   1603 			if (ai) {
   1604 				cur->ai_next = ai;
   1605 				while (cur && cur->ai_next)
   1606 					cur = cur->ai_next;
   1607 			}
   1608 		}
   1609 		free(ypbuf);
   1610 	}
   1611 
   1612 	/* ipnodes.byname can hold both IPv4/v6 */
   1613 	r = yp_match(ypdomain, "ipnodes.byname", name,
   1614 		(int)strlen(name), &ypbuf, &ypbuflen);
   1615 	if (r == 0) {
   1616 		ai = _yphostent(ypbuf, pai);
   1617 		if (ai)
   1618 			cur->ai_next = ai;
   1619 		free(ypbuf);
   1620 	}
   1621 
   1622 	if (sentinel.ai_next == NULL) {
   1623 		h_errno = HOST_NOT_FOUND;
   1624 		return NS_NOTFOUND;
   1625 	}
   1626 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1627 	return NS_SUCCESS;
   1628 }
   1629 #endif
   1630 
   1631 /* resolver logic */
   1632 
   1633 /*
   1634  * Formulate a normal query, send, and await answer.
   1635  * Returned answer is placed in supplied buffer "answer".
   1636  * Perform preliminary check of answer, returning success only
   1637  * if no error is indicated and the answer count is nonzero.
   1638  * Return the size of the response on success, -1 on error.
   1639  * Error number is left in h_errno.
   1640  *
   1641  * Caller must parse answer and determine whether it answers the question.
   1642  */
   1643 static int
   1644 res_queryN(const char *name, /* domain name */ struct res_target *target,
   1645     res_state res)
   1646 {
   1647 	u_char buf[MAXPACKET];
   1648 	HEADER *hp;
   1649 	int n;
   1650 	struct res_target *t;
   1651 	int rcode;
   1652 	int ancount;
   1653 
   1654 	_DIAGASSERT(name != NULL);
   1655 	/* XXX: target may be NULL??? */
   1656 
   1657 	rcode = NOERROR;
   1658 	ancount = 0;
   1659 
   1660 	for (t = target; t; t = t->next) {
   1661 		int class, type;
   1662 		u_char *answer;
   1663 		int anslen;
   1664 
   1665 		hp = (HEADER *)(void *)t->answer;
   1666 		hp->rcode = NOERROR;	/* default */
   1667 
   1668 		/* make it easier... */
   1669 		class = t->qclass;
   1670 		type = t->qtype;
   1671 		answer = t->answer;
   1672 		anslen = t->anslen;
   1673 #ifdef DEBUG
   1674 		if (res->options & RES_DEBUG)
   1675 			printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
   1676 #endif
   1677 
   1678 		n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
   1679 		    buf, sizeof(buf));
   1680 #ifdef RES_USE_EDNS0
   1681 		if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
   1682 			n = res_nopt(res, n, buf, sizeof(buf), anslen);
   1683 #endif
   1684 		if (n <= 0) {
   1685 #ifdef DEBUG
   1686 			if (res->options & RES_DEBUG)
   1687 				printf(";; res_nquery: mkquery failed\n");
   1688 #endif
   1689 			h_errno = NO_RECOVERY;
   1690 			return n;
   1691 		}
   1692 		n = res_nsend(res, buf, n, answer, anslen);
   1693 #if 0
   1694 		if (n < 0) {
   1695 #ifdef DEBUG
   1696 			if (res->options & RES_DEBUG)
   1697 				printf(";; res_query: send error\n");
   1698 #endif
   1699 			h_errno = TRY_AGAIN;
   1700 			return n;
   1701 		}
   1702 #endif
   1703 
   1704 		if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
   1705 			rcode = hp->rcode;	/* record most recent error */
   1706 #ifdef DEBUG
   1707 			if (res->options & RES_DEBUG)
   1708 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
   1709 				    ntohs(hp->ancount));
   1710 #endif
   1711 			continue;
   1712 		}
   1713 
   1714 		ancount += ntohs(hp->ancount);
   1715 
   1716 		t->n = n;
   1717 	}
   1718 
   1719 	if (ancount == 0) {
   1720 		switch (rcode) {
   1721 		case NXDOMAIN:
   1722 			h_errno = HOST_NOT_FOUND;
   1723 			break;
   1724 		case SERVFAIL:
   1725 			h_errno = TRY_AGAIN;
   1726 			break;
   1727 		case NOERROR:
   1728 			h_errno = NO_DATA;
   1729 			break;
   1730 		case FORMERR:
   1731 		case NOTIMP:
   1732 		case REFUSED:
   1733 		default:
   1734 			h_errno = NO_RECOVERY;
   1735 			break;
   1736 		}
   1737 		return -1;
   1738 	}
   1739 	return ancount;
   1740 }
   1741 
   1742 /*
   1743  * Formulate a normal query, send, and retrieve answer in supplied buffer.
   1744  * Return the size of the response on success, -1 on error.
   1745  * If enabled, implement search rules until answer or unrecoverable failure
   1746  * is detected.  Error code, if any, is left in h_errno.
   1747  */
   1748 static int
   1749 res_searchN(const char *name, struct res_target *target, res_state res)
   1750 {
   1751 	const char *cp, * const *domain;
   1752 	HEADER *hp;
   1753 	u_int dots;
   1754 	int trailing_dot, ret, saved_herrno;
   1755 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
   1756 
   1757 	_DIAGASSERT(name != NULL);
   1758 	_DIAGASSERT(target != NULL);
   1759 
   1760 	hp = (HEADER *)(void *)target->answer;	/*XXX*/
   1761 
   1762 	errno = 0;
   1763 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
   1764 	dots = 0;
   1765 	for (cp = name; *cp; cp++)
   1766 		dots += (*cp == '.');
   1767 	trailing_dot = 0;
   1768 	if (cp > name && *--cp == '.')
   1769 		trailing_dot++;
   1770 
   1771 	/*
   1772 	 * if there aren't any dots, it could be a user-level alias
   1773 	 */
   1774 	if (!dots && (cp = __hostalias(name)) != NULL) {
   1775 		ret = res_queryN(cp, target, res);
   1776 		return ret;
   1777 	}
   1778 
   1779 	/*
   1780 	 * If there are dots in the name already, let's just give it a try
   1781 	 * 'as is'.  The threshold can be set with the "ndots" option.
   1782 	 */
   1783 	saved_herrno = -1;
   1784 	if (dots >= res->ndots) {
   1785 		ret = res_querydomainN(name, NULL, target, res);
   1786 		if (ret > 0)
   1787 			return (ret);
   1788 		saved_herrno = h_errno;
   1789 		tried_as_is++;
   1790 	}
   1791 
   1792 	/*
   1793 	 * We do at least one level of search if
   1794 	 *	- there is no dot and RES_DEFNAME is set, or
   1795 	 *	- there is at least one dot, there is no trailing dot,
   1796 	 *	  and RES_DNSRCH is set.
   1797 	 */
   1798 	if ((!dots && (res->options & RES_DEFNAMES)) ||
   1799 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
   1800 		int done = 0;
   1801 
   1802 		for (domain = (const char * const *)res->dnsrch;
   1803 		   *domain && !done;
   1804 		   domain++) {
   1805 
   1806 			ret = res_querydomainN(name, *domain, target, res);
   1807 			if (ret > 0)
   1808 				return ret;
   1809 
   1810 			/*
   1811 			 * If no server present, give up.
   1812 			 * If name isn't found in this domain,
   1813 			 * keep trying higher domains in the search list
   1814 			 * (if that's enabled).
   1815 			 * On a NO_DATA error, keep trying, otherwise
   1816 			 * a wildcard entry of another type could keep us
   1817 			 * from finding this entry higher in the domain.
   1818 			 * If we get some other error (negative answer or
   1819 			 * server failure), then stop searching up,
   1820 			 * but try the input name below in case it's
   1821 			 * fully-qualified.
   1822 			 */
   1823 			if (errno == ECONNREFUSED) {
   1824 				h_errno = TRY_AGAIN;
   1825 				return -1;
   1826 			}
   1827 
   1828 			switch (h_errno) {
   1829 			case NO_DATA:
   1830 				got_nodata++;
   1831 				/* FALLTHROUGH */
   1832 			case HOST_NOT_FOUND:
   1833 				/* keep trying */
   1834 				break;
   1835 			case TRY_AGAIN:
   1836 				if (hp->rcode == SERVFAIL) {
   1837 					/* try next search element, if any */
   1838 					got_servfail++;
   1839 					break;
   1840 				}
   1841 				/* FALLTHROUGH */
   1842 			default:
   1843 				/* anything else implies that we're done */
   1844 				done++;
   1845 			}
   1846 			/*
   1847 			 * if we got here for some reason other than DNSRCH,
   1848 			 * we only wanted one iteration of the loop, so stop.
   1849 			 */
   1850 			if (!(res->options & RES_DNSRCH))
   1851 			        done++;
   1852 		}
   1853 	}
   1854 
   1855 	/*
   1856 	 * if we have not already tried the name "as is", do that now.
   1857 	 * note that we do this regardless of how many dots were in the
   1858 	 * name or whether it ends with a dot.
   1859 	 */
   1860 	if (!tried_as_is) {
   1861 		ret = res_querydomainN(name, NULL, target, res);
   1862 		if (ret > 0)
   1863 			return ret;
   1864 	}
   1865 
   1866 	/*
   1867 	 * if we got here, we didn't satisfy the search.
   1868 	 * if we did an initial full query, return that query's h_errno
   1869 	 * (note that we wouldn't be here if that query had succeeded).
   1870 	 * else if we ever got a nodata, send that back as the reason.
   1871 	 * else send back meaningless h_errno, that being the one from
   1872 	 * the last DNSRCH we did.
   1873 	 */
   1874 	if (saved_herrno != -1)
   1875 		h_errno = saved_herrno;
   1876 	else if (got_nodata)
   1877 		h_errno = NO_DATA;
   1878 	else if (got_servfail)
   1879 		h_errno = TRY_AGAIN;
   1880 	return -1;
   1881 }
   1882 
   1883 /*
   1884  * Perform a call on res_query on the concatenation of name and domain,
   1885  * removing a trailing dot from name if domain is NULL.
   1886  */
   1887 static int
   1888 res_querydomainN(const char *name, const char *domain,
   1889     struct res_target *target, res_state res)
   1890 {
   1891 	char nbuf[MAXDNAME];
   1892 	const char *longname = nbuf;
   1893 	size_t n, d;
   1894 
   1895 	_DIAGASSERT(name != NULL);
   1896 	/* XXX: target may be NULL??? */
   1897 
   1898 #ifdef DEBUG
   1899 	if (res->options & RES_DEBUG)
   1900 		printf(";; res_querydomain(%s, %s)\n",
   1901 			name, domain?domain:"<Nil>");
   1902 #endif
   1903 	if (domain == NULL) {
   1904 		/*
   1905 		 * Check for trailing '.';
   1906 		 * copy without '.' if present.
   1907 		 */
   1908 		n = strlen(name);
   1909 		if (n + 1 > sizeof(nbuf)) {
   1910 			h_errno = NO_RECOVERY;
   1911 			return -1;
   1912 		}
   1913 		if (n > 0 && name[--n] == '.') {
   1914 			strncpy(nbuf, name, n);
   1915 			nbuf[n] = '\0';
   1916 		} else
   1917 			longname = name;
   1918 	} else {
   1919 		n = strlen(name);
   1920 		d = strlen(domain);
   1921 		if (n + 1 + d + 1 > sizeof(nbuf)) {
   1922 			h_errno = NO_RECOVERY;
   1923 			return -1;
   1924 		}
   1925 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
   1926 	}
   1927 	return res_queryN(longname, target, res);
   1928 }
   1929