Home | History | Annotate | Line # | Download | only in net
getaddrinfo.c revision 1.125
      1 /*	$NetBSD: getaddrinfo.c,v 1.125 2024/01/20 14:52:48 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 (allows
     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.125 2024/01/20 14:52:48 christos Exp $");
     59 #endif /* LIBC_SCCS and not lint */
     60 
     61 #ifndef RUMP_ACTION
     62 #include "namespace.h"
     63 #endif
     64 #include <sys/types.h>
     65 #include <sys/param.h>
     66 #include <sys/socket.h>
     67 #include <sys/ioctl.h>
     68 #include <sys/sysctl.h>
     69 #include <net/if.h>
     70 #include <netinet/in.h>
     71 #include <netinet6/in6_var.h>
     72 #include <arpa/inet.h>
     73 #include <arpa/nameser.h>
     74 #include <assert.h>
     75 #include <ctype.h>
     76 #include <errno.h>
     77 #include <netdb.h>
     78 #include <resolv.h>
     79 #include <stddef.h>
     80 #include <stdio.h>
     81 #include <stdlib.h>
     82 #include <string.h>
     83 #include <unistd.h>
     84 #include <ifaddrs.h>
     85 
     86 #include <syslog.h>
     87 #include <stdarg.h>
     88 #include <nsswitch.h>
     89 
     90 #ifdef YP
     91 #include <rpc/rpc.h>
     92 #include <rpcsvc/yp_prot.h>
     93 #include <rpcsvc/ypclnt.h>
     94 #endif
     95 
     96 #include "servent.h"
     97 
     98 #ifndef RUMP_ACTION
     99 #ifdef __weak_alias
    100 __weak_alias(getaddrinfo,_getaddrinfo)
    101 __weak_alias(allocaddrinfo,_allocaddrinfo)
    102 __weak_alias(freeaddrinfo,_freeaddrinfo)
    103 __weak_alias(gai_strerror,_gai_strerror)
    104 #endif
    105 #endif
    106 
    107 #define SUCCESS 0
    108 #define ANY 0
    109 #define YES 1
    110 #define NO  0
    111 
    112 #define sa4addr(sa) ((void *)&((struct sockaddr_in *)(void *)sa)->sin_addr)
    113 #define sa6addr(sa) ((void *)&((struct sockaddr_in6 *)(void *)sa)->sin6_addr)
    114 
    115 static const char in_addrany[] = { 0, 0, 0, 0 };
    116 static const char in_loopback[] = { 127, 0, 0, 1 };
    117 #ifdef INET6
    118 static const char in6_addrany[] = {
    119 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    120 };
    121 static const char in6_loopback[] = {
    122 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
    123 };
    124 #endif
    125 
    126 struct policyqueue {
    127 	TAILQ_ENTRY(policyqueue) pc_entry;
    128 #ifdef INET6
    129 	struct in6_addrpolicy pc_policy;
    130 #endif
    131 };
    132 TAILQ_HEAD(policyhead, policyqueue);
    133 
    134 static const struct afd {
    135 	int a_af;
    136 	int a_addrlen;
    137 	int a_socklen;
    138 	int a_off;
    139 	const char *a_addrany;
    140 	const char *a_loopback;
    141 	int a_scoped;
    142 } afdl [] = {
    143 #ifdef INET6
    144 	{PF_INET6, sizeof(struct in6_addr),
    145 	 sizeof(struct sockaddr_in6),
    146 	 offsetof(struct sockaddr_in6, sin6_addr),
    147 	 in6_addrany, in6_loopback, 1},
    148 #endif
    149 	{PF_INET, sizeof(struct in_addr),
    150 	 sizeof(struct sockaddr_in),
    151 	 offsetof(struct sockaddr_in, sin_addr),
    152 	 in_addrany, in_loopback, 0},
    153 	{0, 0, 0, 0, NULL, NULL, 0},
    154 };
    155 
    156 struct explore {
    157 	int e_af;
    158 	int e_socktype;
    159 	int e_protocol;
    160 	const char *e_protostr;
    161 	int e_wild;
    162 #define WILD_AF(ex)		((ex)->e_wild & 0x01)
    163 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
    164 #define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
    165 };
    166 
    167 static const struct explore explore[] = {
    168 #if 0
    169 	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
    170 #endif
    171 #ifdef INET6
    172 	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    173 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    174 	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
    175 #endif
    176 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    177 	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    178 	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
    179 	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    180 	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    181 	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
    182 	{ -1, 0, 0, NULL, 0 },
    183 };
    184 
    185 #ifdef INET6
    186 #define PTON_MAX	16
    187 #else
    188 #define PTON_MAX	4
    189 #endif
    190 
    191 #define AIO_SRCFLAG_DEPRECATED	0x1
    192 
    193 struct ai_order {
    194 	union {
    195 		struct sockaddr_storage aiou_ss;
    196 		struct sockaddr aiou_sa;
    197 	} aio_src_un;
    198 #define aio_srcsa aio_src_un.aiou_sa
    199 	u_int32_t aio_srcflag;
    200 	int aio_srcscope;
    201 	int aio_dstscope;
    202 	struct policyqueue *aio_srcpolicy;
    203 	struct policyqueue *aio_dstpolicy;
    204 	struct addrinfo *aio_ai;
    205 	int aio_matchlen;
    206 };
    207 
    208 static const ns_src default_dns_files[] = {
    209 	{ NSSRC_FILES,	NS_SUCCESS },
    210 	{ NSSRC_DNS,	NS_SUCCESS },
    211 	{ 0, 0 }
    212 };
    213 
    214 #define MAXPACKET	(64*1024)
    215 
    216 typedef union {
    217 	HEADER hdr;
    218 	u_char buf[MAXPACKET];
    219 } querybuf;
    220 
    221 struct res_target {
    222 	struct res_target *next;
    223 	const char *name;	/* domain name */
    224 	int qclass, qtype;	/* class and type of query */
    225 	u_char *answer;		/* buffer to put answer */
    226 	int anslen;		/* size of answer buffer */
    227 	int n;			/* result length */
    228 };
    229 
    230 struct srvinfo {
    231        struct srvinfo *next;
    232        char name[MAXDNAME];
    233        int port, pri, weight;
    234 };
    235 
    236 static int gai_srvok(const char *);
    237 static int str2number(const char *);
    238 static int explore_fqdn(const struct addrinfo *, const char *,
    239     const char *, struct addrinfo **, struct servent_data *);
    240 static int explore_null(const struct addrinfo *,
    241     const char *, struct addrinfo **, struct servent_data *);
    242 static int explore_numeric(const struct addrinfo *, const char *,
    243     const char *, struct addrinfo **, const char *, struct servent_data *);
    244 static int explore_numeric_scope(const struct addrinfo *, const char *,
    245     const char *, struct addrinfo **, struct servent_data *);
    246 static int get_canonname(const struct addrinfo *,
    247     struct addrinfo *, const char *);
    248 static struct addrinfo *get_ai(const struct addrinfo *,
    249     const struct afd *, const char *);
    250 static int get_portmatch(const struct addrinfo *, const char *,
    251     struct servent_data *);
    252 static int get_port(const struct addrinfo *, const char *, int,
    253     struct servent_data *);
    254 static const struct afd *find_afd(int);
    255 static int addrconfig(uint64_t *);
    256 static void set_source(struct ai_order *, struct policyhead *,
    257     struct servent_data *);
    258 static int comp_dst(const void *, const void *);
    259 #ifdef INET6
    260 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
    261 #endif
    262 static int gai_addr2scopetype(struct sockaddr *);
    263 
    264 static int reorder(struct addrinfo *, struct servent_data *);
    265 static int get_addrselectpolicy(struct policyhead *);
    266 static void free_addrselectpolicy(struct policyhead *);
    267 static struct policyqueue *match_addrselectpolicy(struct sockaddr *,
    268 	struct policyhead *);
    269 static int matchlen(struct sockaddr *, struct sockaddr *);
    270 
    271 static struct addrinfo *getanswer(res_state, const querybuf *, int,
    272     const char *, int, const struct addrinfo *);
    273 static void aisort(struct addrinfo *s, res_state res);
    274 static struct addrinfo * _dns_query(struct res_target *,
    275     const struct addrinfo *, res_state, int);
    276 static struct addrinfo * _dns_srv_lookup(const char *, const char *,
    277     const struct addrinfo *);
    278 static struct addrinfo * _dns_host_lookup(const char *,
    279     const struct addrinfo *);
    280 static int _dns_getaddrinfo(void *, void *, va_list);
    281 static void _sethtent(FILE **);
    282 static void _endhtent(FILE **);
    283 static struct addrinfo *_gethtent(FILE **, const char *,
    284     const struct addrinfo *);
    285 static int _files_getaddrinfo(void *, void *, va_list);
    286 #ifdef YP
    287 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
    288 static int _yp_getaddrinfo(void *, void *, va_list);
    289 #endif
    290 
    291 static int res_queryN(const char *, struct res_target *, res_state);
    292 static int res_searchN(const char *, struct res_target *, res_state);
    293 static int res_querydomainN(const char *, const char *,
    294     struct res_target *, res_state);
    295 
    296 static const char * const ai_errlist[] = {
    297 	"Success",
    298 	"Address family for hostname not supported",	/* EAI_ADDRFAMILY */
    299 	"Temporary failure in name resolution",		/* EAI_AGAIN	  */
    300 	"Invalid value for ai_flags",			/* EAI_BADFLAGS	  */
    301 	"Non-recoverable failure in name resolution",	/* EAI_FAIL	  */
    302 	"ai_family not supported",			/* EAI_FAMILY	  */
    303 	"Memory allocation failure",			/* EAI_MEMORY	  */
    304 	"No address associated with hostname",		/* EAI_NODATA	  */
    305 	"hostname or servname not provided or not known", /* EAI_NONAME	  */
    306 	"servname not supported for ai_socktype",	/* EAI_SERVICE	  */
    307 	"ai_socktype not supported",			/* EAI_SOCKTYPE	  */
    308 	"System error returned in errno",		/* EAI_SYSTEM	  */
    309 	"Invalid value for hints",			/* EAI_BADHINTS	  */
    310 	"Resolved protocol is unknown",			/* EAI_PROTOCOL	  */
    311 	"Argument buffer overflow",			/* EAI_OVERFLOW	  */
    312 	"Unknown error",				/* EAI_MAX	  */
    313 };
    314 
    315 /* XXX macros that make external reference is BAD. */
    316 
    317 #define GET_AI(ai, afd, addr)					\
    318 do {								\
    319 	/* external reference: pai, error, and label free */	\
    320 	(ai) = get_ai(pai, (afd), (addr));			\
    321 	if ((ai) == NULL) {					\
    322 		error = EAI_MEMORY;				\
    323 		goto free;					\
    324 	}							\
    325 } while (0)
    326 
    327 #define GET_PORT(ai, serv, svd)					\
    328 do {								\
    329 	/* external reference: error and label free */		\
    330 	error = get_port((ai), (serv), 0, (svd));		\
    331 	if (error != 0)						\
    332 		goto free;					\
    333 } while (0)
    334 
    335 #define GET_CANONNAME(ai, str)					\
    336 do {								\
    337 	/* external reference: pai, error and label free */	\
    338 	error = get_canonname(pai, (ai), (str));		\
    339 	if (error != 0)						\
    340 		goto free;					\
    341 } while (0)
    342 
    343 #define ERR(err)						\
    344 do {								\
    345 	/* external reference: error, and label bad */		\
    346 	error = (err);						\
    347 	goto bad;						\
    348 	/*NOTREACHED*/						\
    349 } while (0)
    350 
    351 #define MATCH_FAMILY(x, y, w)						\
    352 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC ||	\
    353 	    (y) == PF_UNSPEC)))
    354 #define MATCH(x, y, w)							\
    355 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
    356 
    357 const char *
    358 gai_strerror(int ecode)
    359 {
    360 	if (ecode < 0 || ecode > EAI_MAX)
    361 		ecode = EAI_MAX;
    362 	return ai_errlist[ecode];
    363 }
    364 
    365 void
    366 freeaddrinfo(struct addrinfo *ai)
    367 {
    368 	struct addrinfo *next;
    369 
    370 	_DIAGASSERT(ai != NULL);
    371 
    372 	do {
    373 		next = ai->ai_next;
    374 		if (ai->ai_canonname)
    375 			free(ai->ai_canonname);
    376 		/* no need to free(ai->ai_addr) */
    377 		free(ai);
    378 		ai = next;
    379 	} while (ai);
    380 }
    381 
    382 /*
    383  * We don't want localization to affect us
    384  */
    385 #define PERIOD '.'
    386 #define hyphenchar(c) ((c) == '-')
    387 #define periodchar(c) ((c) == PERIOD)
    388 #define underschar(c) ((c) == '_')
    389 #define alphachar(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
    390 #define digitchar(c) ((c) >= '0' && (c) <= '9')
    391 
    392 #define firstchar(c)  (alphachar(c) || digitchar(c) || underschar(c))
    393 #define lastchar(c)   (alphachar(c) || digitchar(c))
    394 #define middlechar(c) (lastchar(c) || hyphenchar(c))
    395 
    396 static int
    397 gai_srvok(const char *dn)
    398 {
    399 	int nch, pch, ch;
    400 
    401 	for (pch = PERIOD, nch = ch = *dn++; ch != '\0'; pch = ch, ch = nch) {
    402 		if (periodchar(ch))
    403 			continue;
    404 		if (periodchar(pch)) {
    405 			if (!firstchar(ch))
    406 				return 0;
    407 		} else if (periodchar(nch) || nch == '\0') {
    408 			if (!lastchar(ch))
    409 				return 0;
    410 		} else if (!middlechar(ch))
    411 			return 0;
    412        }
    413        return 1;
    414 }
    415 
    416 static in_port_t *
    417 getport(struct addrinfo *ai) {
    418 	static in_port_t p;
    419 
    420 	switch (ai->ai_family) {
    421 	case AF_INET:
    422 		return &((struct sockaddr_in *)(void *)ai->ai_addr)->sin_port;
    423 #ifdef INET6
    424 	case AF_INET6:
    425 		return &((struct sockaddr_in6 *)(void *)ai->ai_addr)->sin6_port;
    426 #endif
    427 	default:
    428 		p = 0;
    429 		/* XXX: abort()? */
    430 		return &p;
    431 	}
    432 }
    433 
    434 static int
    435 str2number(const char *p)
    436 {
    437 	char *ep;
    438 	unsigned long v;
    439 
    440 	_DIAGASSERT(p != NULL);
    441 
    442 	if (*p == '\0')
    443 		return -1;
    444 	ep = NULL;
    445 	errno = 0;
    446 	v = strtoul(p, &ep, 10);
    447 	if (errno == 0 && ep && *ep == '\0' && v <= INT_MAX)
    448 		return (int)v;
    449 	else
    450 		return -1;
    451 }
    452 
    453 int
    454 getaddrinfo(const char *hostname, const char *servname,
    455     const struct addrinfo *hints, struct addrinfo **res)
    456 {
    457 	struct addrinfo sentinel;
    458 	struct addrinfo *cur;
    459 	int error = 0;
    460 	struct addrinfo ai;
    461 	struct addrinfo ai0;
    462 	struct addrinfo *pai;
    463 	const struct explore *ex;
    464 	struct servent_data svd;
    465 	uint64_t mask = (uint64_t)~0ULL;
    466 	int numeric = 0;
    467 
    468 	/* hostname is allowed to be NULL */
    469 	/* servname is allowed to be NULL */
    470 	/* hints is allowed to be NULL */
    471 	_DIAGASSERT(res != NULL);
    472 
    473 	(void)memset(&svd, 0, sizeof(svd));
    474 	memset(&sentinel, 0, sizeof(sentinel));
    475 	cur = &sentinel;
    476 	memset(&ai, 0, sizeof(ai));
    477 	pai = &ai;
    478 	pai->ai_flags = 0;
    479 	pai->ai_family = PF_UNSPEC;
    480 	pai->ai_socktype = ANY;
    481 	pai->ai_protocol = ANY;
    482 	pai->ai_addrlen = 0;
    483 	pai->ai_canonname = NULL;
    484 	pai->ai_addr = NULL;
    485 	pai->ai_next = NULL;
    486 
    487 	if (hostname == NULL && servname == NULL)
    488 		return EAI_NONAME;
    489 	if (hints) {
    490 		/* error check for hints */
    491 		if (hints->ai_addrlen || hints->ai_canonname ||
    492 		    hints->ai_addr || hints->ai_next)
    493 			ERR(EAI_BADHINTS); /* xxx */
    494 		if (hints->ai_flags & ~AI_MASK)
    495 			ERR(EAI_BADFLAGS);
    496 		switch (hints->ai_family) {
    497 		case PF_UNSPEC:
    498 		case PF_INET:
    499 #ifdef INET6
    500 		case PF_INET6:
    501 #endif
    502 			break;
    503 		default:
    504 			ERR(EAI_FAMILY);
    505 		}
    506 		memcpy(pai, hints, sizeof(*pai));
    507 
    508 		/*
    509 		 * if both socktype/protocol are specified, check if they
    510 		 * are meaningful combination.
    511 		 */
    512 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
    513 			for (ex = explore; ex->e_af >= 0; ex++) {
    514 				if (pai->ai_family != ex->e_af)
    515 					continue;
    516 				if (ex->e_socktype == ANY)
    517 					continue;
    518 				if (ex->e_protocol == ANY)
    519 					continue;
    520 				if (pai->ai_socktype == ex->e_socktype
    521 				 && pai->ai_protocol != ex->e_protocol) {
    522 					ERR(EAI_BADHINTS);
    523 				}
    524 			}
    525 		}
    526 	}
    527 
    528 	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && addrconfig(&mask) == -1)
    529 		ERR(EAI_FAIL);
    530 
    531 	/*
    532 	 * check for special cases.  (1) numeric servname is disallowed if
    533 	 * socktype/protocol are left unspecified. (2) servname is disallowed
    534 	 * for raw and other inet{,6} sockets.
    535 	 */
    536 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
    537 #ifdef PF_INET6
    538 	 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
    539 #endif
    540 	    ) {
    541 		ai0 = *pai;	/* backup *pai */
    542 
    543 		if (pai->ai_family == PF_UNSPEC) {
    544 #ifdef PF_INET6
    545 			pai->ai_family = PF_INET6;
    546 #else
    547 			pai->ai_family = PF_INET;
    548 #endif
    549 		}
    550 		error = get_portmatch(pai, servname, &svd);
    551 		if (error)
    552 			goto bad;
    553 
    554 		*pai = ai0;
    555 	}
    556 
    557 	ai0 = *pai;
    558 
    559 	/* NULL hostname, or numeric hostname */
    560 	for (ex = explore; ex->e_af >= 0; ex++) {
    561 		*pai = ai0;
    562 
    563 		/* ADDRCONFIG check */
    564 		if ((((uint64_t)1 << ex->e_af) & mask) == 0)
    565 			continue;
    566 
    567 		/* PF_UNSPEC entries are prepared for DNS queries only */
    568 		if (ex->e_af == PF_UNSPEC)
    569 			continue;
    570 
    571 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    572 			continue;
    573 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
    574 			continue;
    575 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
    576 			continue;
    577 		if (pai->ai_family == PF_UNSPEC)
    578 			pai->ai_family = ex->e_af;
    579 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    580 			pai->ai_socktype = ex->e_socktype;
    581 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    582 			pai->ai_protocol = ex->e_protocol;
    583 
    584 		if (hostname == NULL)
    585 			error = explore_null(pai, servname, &cur->ai_next,
    586 			    &svd);
    587 		else
    588 			error = explore_numeric_scope(pai, hostname, servname,
    589 			    &cur->ai_next, &svd);
    590 
    591 		if (error)
    592 			goto free;
    593 
    594 		while (cur->ai_next)
    595 			cur = cur->ai_next;
    596 	}
    597 
    598 	/*
    599 	 * XXX
    600 	 * If numeric representation of AF1 can be interpreted as FQDN
    601 	 * representation of AF2, we need to think again about the code below.
    602 	 */
    603 	if (sentinel.ai_next) {
    604 		numeric = 1;
    605 		goto good;
    606 	}
    607 
    608 	if (hostname == NULL)
    609 		ERR(EAI_NODATA);
    610 	if (pai->ai_flags & AI_NUMERICHOST)
    611 		ERR(EAI_NONAME);
    612 
    613 	/*
    614 	 * hostname as alphabetical name.
    615 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
    616 	 * outer loop by AFs.
    617 	 */
    618 	for (ex = explore; ex->e_af >= 0; ex++) {
    619 		*pai = ai0;
    620 
    621 
    622 		/* ADDRCONFIG check */
    623 		/* PF_UNSPEC entries are prepared for DNS queries only */
    624 		if (ex->e_af != PF_UNSPEC &&
    625 		    (((uint64_t)1 << ex->e_af) & mask) == 0)
    626 			continue;
    627 
    628 		/* require exact match for family field */
    629 		if (pai->ai_family != ex->e_af)
    630 			continue;
    631 
    632 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
    633 				WILD_SOCKTYPE(ex))) {
    634 			continue;
    635 		}
    636 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
    637 				WILD_PROTOCOL(ex))) {
    638 			continue;
    639 		}
    640 
    641 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    642 			pai->ai_socktype = ex->e_socktype;
    643 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    644 			pai->ai_protocol = ex->e_protocol;
    645 
    646 		error = explore_fqdn(pai, hostname, servname, &cur->ai_next,
    647 		    &svd);
    648 
    649 		while (cur && cur->ai_next)
    650 			cur = cur->ai_next;
    651 	}
    652 
    653 	/* XXX */
    654 	if (sentinel.ai_next)
    655 		error = 0;
    656 
    657 	if (error)
    658 		goto free;
    659 
    660 	if (sentinel.ai_next) {
    661  good:
    662 		/*
    663 		 * If the returned entry is for an active connection,
    664 		 * and the given name is not numeric, reorder the
    665 		 * list, so that the application would try the list
    666 		 * in the most efficient order.  Since the head entry
    667 		 * of the original list may contain ai_canonname and
    668 		 * that entry may be moved elsewhere in the new list,
    669 		 * we keep the pointer and will  restore it in the new
    670 		 * head entry.  (Note that RFC3493 requires the head
    671 		 * entry store it when requested by the caller).
    672 		 */
    673 		if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
    674 			if (!numeric) {
    675 				char *canonname;
    676 
    677 				canonname = sentinel.ai_next->ai_canonname;
    678 				sentinel.ai_next->ai_canonname = NULL;
    679 				(void)reorder(&sentinel, &svd);
    680 				if (sentinel.ai_next->ai_canonname == NULL) {
    681 					sentinel.ai_next->ai_canonname
    682 					    = canonname;
    683 				} else if (canonname != NULL)
    684 					free(canonname);
    685 			}
    686 		}
    687 		endservent_r(&svd);
    688 		*res = sentinel.ai_next;
    689 		return SUCCESS;
    690 	} else
    691 		error = EAI_FAIL;
    692  free:
    693  bad:
    694 	endservent_r(&svd);
    695 	if (sentinel.ai_next)
    696 		freeaddrinfo(sentinel.ai_next);
    697 	*res = NULL;
    698 	return error;
    699 }
    700 
    701 static int
    702 reorder(struct addrinfo *sentinel, struct servent_data *svd)
    703 {
    704 	struct addrinfo *ai, **aip;
    705 	struct ai_order *aio;
    706 	int i, n;
    707 	struct policyhead policyhead;
    708 
    709 	/* count the number of addrinfo elements for sorting. */
    710 	for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
    711 		;
    712 
    713 	/*
    714 	 * If the number is small enough, we can skip the reordering process.
    715 	 */
    716 	if (n <= 1)
    717 		return n;
    718 
    719 	/* allocate a temporary array for sort and initialization of it. */
    720 	if ((aio = calloc(n, sizeof(*aio))) == NULL)
    721 		return n;	/* give up reordering */
    722 
    723 	/* retrieve address selection policy from the kernel */
    724 	TAILQ_INIT(&policyhead);
    725 	if (!get_addrselectpolicy(&policyhead)) {
    726 		/* no policy is installed into kernel, we don't sort. */
    727 		free(aio);
    728 		return n;
    729 	}
    730 
    731 	for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
    732 		aio[i].aio_ai = ai;
    733 		aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
    734 		aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
    735 							      &policyhead);
    736 		set_source(&aio[i], &policyhead, svd);
    737 	}
    738 
    739 	/* perform sorting. */
    740 	qsort(aio, n, sizeof(*aio), comp_dst);
    741 
    742 	/* reorder the addrinfo chain. */
    743 	for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
    744 		*aip = aio[i].aio_ai;
    745 		aip = &aio[i].aio_ai->ai_next;
    746 	}
    747 	*aip = NULL;
    748 
    749 	/* cleanup and return */
    750 	free(aio);
    751 	free_addrselectpolicy(&policyhead);
    752 	return n;
    753 }
    754 
    755 static int
    756 get_addrselectpolicy(struct policyhead *head)
    757 {
    758 #ifdef INET6
    759 	static const int mib[] = {
    760 	    CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
    761 	static const u_int miblen = (u_int)__arraycount(mib);
    762 	size_t l;
    763 	char *buf;
    764 	struct in6_addrpolicy *pol, *ep;
    765 
    766 	if (sysctl(mib, miblen, NULL, &l, NULL, 0) < 0)
    767 		return 0;
    768 	if (l == 0)
    769 		return 0;
    770 	if ((buf = malloc(l)) == NULL)
    771 		return 0;
    772 	if (sysctl(mib, miblen, buf, &l, NULL, 0) < 0) {
    773 		free(buf);
    774 		return 0;
    775 	}
    776 
    777 	ep = (void *)(buf + l);
    778 	for (pol = (void *)buf; pol + 1 <= ep; pol++) {
    779 		struct policyqueue *new;
    780 
    781 		if ((new = malloc(sizeof(*new))) == NULL) {
    782 			free_addrselectpolicy(head); /* make the list empty */
    783 			break;
    784 		}
    785 		new->pc_policy = *pol;
    786 		TAILQ_INSERT_TAIL(head, new, pc_entry);
    787 	}
    788 
    789 	free(buf);
    790 	return 1;
    791 #else
    792 	return 0;
    793 #endif
    794 }
    795 
    796 static void
    797 free_addrselectpolicy(struct policyhead *head)
    798 {
    799 	struct policyqueue *ent, *nent;
    800 
    801 	for (ent = TAILQ_FIRST(head); ent; ent = nent) {
    802 		nent = TAILQ_NEXT(ent, pc_entry);
    803 		TAILQ_REMOVE(head, ent, pc_entry);
    804 		free(ent);
    805 	}
    806 }
    807 
    808 static struct policyqueue *
    809 match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head)
    810 {
    811 #ifdef INET6
    812 	struct policyqueue *ent, *bestent = NULL;
    813 	struct in6_addrpolicy *pol;
    814 	int curmatchlen, bestmatchlen = -1;
    815 	u_char *mp, *ep, *k, *p;
    816 	u_int m;
    817 	struct sockaddr_in6 key;
    818 
    819 	switch(addr->sa_family) {
    820 	case AF_INET6:
    821 		memcpy(&key, addr, sizeof(key));
    822 		break;
    823 	case AF_INET:
    824 		/* convert the address into IPv4-mapped IPv6 address. */
    825 		memset(&key, 0, sizeof(key));
    826 		key.sin6_family = AF_INET6;
    827 		key.sin6_len = sizeof(key);
    828 		key.sin6_addr.s6_addr[10] = 0xff;
    829 		key.sin6_addr.s6_addr[11] = 0xff;
    830 		memcpy(&key.sin6_addr.s6_addr[12], sa4addr(addr), 4);
    831 		break;
    832 	default:
    833 		return NULL;
    834 	}
    835 
    836 	for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
    837 		pol = &ent->pc_policy;
    838 		curmatchlen = 0;
    839 
    840 		mp = (void *)&pol->addrmask.sin6_addr;
    841 		ep = mp + 16;	/* XXX: scope field? */
    842 		k = (void *)&key.sin6_addr;
    843 		p = (void *)&pol->addr.sin6_addr;
    844 		for (; mp < ep && *mp; mp++, k++, p++) {
    845 			m = *mp;
    846 			if ((*k & m) != *p)
    847 				goto next; /* not match */
    848 			if (m == 0xff) /* short cut for a typical case */
    849 				curmatchlen += 8;
    850 			else {
    851 				while (m >= 0x80) {
    852 					curmatchlen++;
    853 					m <<= 1;
    854 				}
    855 			}
    856 		}
    857 
    858 		/* matched.  check if this is better than the current best. */
    859 		if (curmatchlen > bestmatchlen) {
    860 			bestent = ent;
    861 			bestmatchlen = curmatchlen;
    862 		}
    863 
    864 	  next:
    865 		continue;
    866 	}
    867 
    868 	return bestent;
    869 #else
    870 	return NULL;
    871 #endif
    872 
    873 }
    874 
    875 static void
    876 set_source(struct ai_order *aio, struct policyhead *ph,
    877     struct servent_data *svd)
    878 {
    879 	struct addrinfo ai = *aio->aio_ai;
    880 	struct sockaddr_storage ss;
    881 	socklen_t srclen;
    882 	int s;
    883 
    884 	/* set unspec ("no source is available"), just in case */
    885 	aio->aio_srcsa.sa_family = AF_UNSPEC;
    886 	aio->aio_srcscope = -1;
    887 
    888 	switch(ai.ai_family) {
    889 	case AF_INET:
    890 #ifdef INET6
    891 	case AF_INET6:
    892 #endif
    893 		break;
    894 	default:		/* ignore unsupported AFs explicitly */
    895 		return;
    896 	}
    897 
    898 	/* XXX: make a dummy addrinfo to call connect() */
    899 	ai.ai_socktype = SOCK_DGRAM;
    900 	ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
    901 	ai.ai_next = NULL;
    902 	memset(&ss, 0, sizeof(ss));
    903 	memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
    904 	ai.ai_addr = (void *)&ss;
    905 	get_port(&ai, "1", 0, svd);
    906 
    907 	/* open a socket to get the source address for the given dst */
    908 	if ((s = socket(ai.ai_family, ai.ai_socktype | SOCK_CLOEXEC,
    909 	    ai.ai_protocol)) < 0)
    910 		return;		/* give up */
    911 	if (connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
    912 		goto cleanup;
    913 	srclen = ai.ai_addrlen;
    914 	if (getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
    915 		aio->aio_srcsa.sa_family = AF_UNSPEC;
    916 		goto cleanup;
    917 	}
    918 	aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
    919 	aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
    920 	aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
    921 #ifdef INET6
    922 	if (ai.ai_family == AF_INET6) {
    923 		struct in6_ifreq ifr6;
    924 		u_int32_t flags6;
    925 
    926 		memset(&ifr6, 0, sizeof(ifr6));
    927 		memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
    928 		if (ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
    929 			flags6 = ifr6.ifr_ifru.ifru_flags6;
    930 			if ((flags6 & IN6_IFF_DEPRECATED))
    931 				aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
    932 		}
    933 	}
    934 #endif
    935 
    936   cleanup:
    937 	close(s);
    938 	return;
    939 }
    940 
    941 static int
    942 matchlen(struct sockaddr *src, struct sockaddr *dst)
    943 {
    944 	int match = 0;
    945 	u_char *s, *d;
    946 	u_char *lim;
    947 	u_int r, addrlen;
    948 
    949 	switch (src->sa_family) {
    950 #ifdef INET6
    951 	case AF_INET6:
    952 		s = sa6addr(src);
    953 		d = sa6addr(dst);
    954 		addrlen = sizeof(struct in6_addr);
    955 		lim = s + addrlen;
    956 		break;
    957 #endif
    958 	case AF_INET:
    959 		s = sa4addr(src);
    960 		d = sa4addr(dst);
    961 		addrlen = sizeof(struct in_addr);
    962 		lim = s + addrlen;
    963 		break;
    964 	default:
    965 		return 0;
    966 	}
    967 
    968 	while (s < lim)
    969 		if ((r = (*d++ ^ *s++)) != 0) {
    970 			while (r < addrlen * 8) {
    971 				match++;
    972 				r <<= 1;
    973 			}
    974 			break;
    975 		} else
    976 			match += 8;
    977 	return match;
    978 }
    979 
    980 static int
    981 comp_dst(const void *arg1, const void *arg2)
    982 {
    983 	const struct ai_order *dst1 = arg1, *dst2 = arg2;
    984 
    985 	/*
    986 	 * Rule 1: Avoid unusable destinations.
    987 	 * XXX: we currently do not consider if an appropriate route exists.
    988 	 */
    989 	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
    990 	    dst2->aio_srcsa.sa_family == AF_UNSPEC) {
    991 		return -1;
    992 	}
    993 	if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
    994 	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
    995 		return 1;
    996 	}
    997 
    998 	/* Rule 2: Prefer matching scope. */
    999 	if (dst1->aio_dstscope == dst1->aio_srcscope &&
   1000 	    dst2->aio_dstscope != dst2->aio_srcscope) {
   1001 		return -1;
   1002 	}
   1003 	if (dst1->aio_dstscope != dst1->aio_srcscope &&
   1004 	    dst2->aio_dstscope == dst2->aio_srcscope) {
   1005 		return 1;
   1006 	}
   1007 
   1008 	/* Rule 3: Avoid deprecated addresses. */
   1009 	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
   1010 	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
   1011 		if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
   1012 		    (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
   1013 			return -1;
   1014 		}
   1015 		if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
   1016 		    !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
   1017 			return 1;
   1018 		}
   1019 	}
   1020 
   1021 	/* Rule 4: Prefer home addresses. */
   1022 	/* XXX: not implemented yet */
   1023 
   1024 	/* Rule 5: Prefer matching label. */
   1025 #ifdef INET6
   1026 	if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
   1027 	    dst1->aio_srcpolicy->pc_policy.label ==
   1028 	    dst1->aio_dstpolicy->pc_policy.label &&
   1029 	    (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
   1030 	     dst2->aio_srcpolicy->pc_policy.label !=
   1031 	     dst2->aio_dstpolicy->pc_policy.label)) {
   1032 		return -1;
   1033 	}
   1034 	if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
   1035 	    dst2->aio_srcpolicy->pc_policy.label ==
   1036 	    dst2->aio_dstpolicy->pc_policy.label &&
   1037 	    (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
   1038 	     dst1->aio_srcpolicy->pc_policy.label !=
   1039 	     dst1->aio_dstpolicy->pc_policy.label)) {
   1040 		return 1;
   1041 	}
   1042 #endif
   1043 
   1044 	/* Rule 6: Prefer higher precedence. */
   1045 #ifdef INET6
   1046 	if (dst1->aio_dstpolicy &&
   1047 	    (dst2->aio_dstpolicy == NULL ||
   1048 	     dst1->aio_dstpolicy->pc_policy.preced >
   1049 	     dst2->aio_dstpolicy->pc_policy.preced)) {
   1050 		return -1;
   1051 	}
   1052 	if (dst2->aio_dstpolicy &&
   1053 	    (dst1->aio_dstpolicy == NULL ||
   1054 	     dst2->aio_dstpolicy->pc_policy.preced >
   1055 	     dst1->aio_dstpolicy->pc_policy.preced)) {
   1056 		return 1;
   1057 	}
   1058 #endif
   1059 
   1060 	/* Rule 7: Prefer native transport. */
   1061 	/* XXX: not implemented yet */
   1062 
   1063 	/* Rule 8: Prefer smaller scope. */
   1064 	if (dst1->aio_dstscope >= 0 &&
   1065 	    dst1->aio_dstscope < dst2->aio_dstscope) {
   1066 		return -1;
   1067 	}
   1068 	if (dst2->aio_dstscope >= 0 &&
   1069 	    dst2->aio_dstscope < dst1->aio_dstscope) {
   1070 		return 1;
   1071 	}
   1072 
   1073 	/*
   1074 	 * Rule 9: Use longest matching prefix.
   1075 	 * We compare the match length in a same AF only.
   1076 	 */
   1077 	if (dst1->aio_ai->ai_addr->sa_family ==
   1078 	    dst2->aio_ai->ai_addr->sa_family &&
   1079 	    dst1->aio_ai->ai_addr->sa_family != AF_INET) {
   1080 		if (dst1->aio_matchlen > dst2->aio_matchlen) {
   1081 			return -1;
   1082 		}
   1083 		if (dst1->aio_matchlen < dst2->aio_matchlen) {
   1084 			return 1;
   1085 		}
   1086 	}
   1087 
   1088 	/* Rule 10: Otherwise, leave the order unchanged. */
   1089 	return -1;
   1090 }
   1091 
   1092 /*
   1093  * Copy from scope.c.
   1094  * XXX: we should standardize the functions and link them as standard
   1095  * library.
   1096  */
   1097 static int
   1098 gai_addr2scopetype(struct sockaddr *sa)
   1099 {
   1100 #ifdef INET6
   1101 	struct sockaddr_in6 *sa6;
   1102 #endif
   1103 	struct sockaddr_in *sa4;
   1104 	u_char *p;
   1105 
   1106 	switch(sa->sa_family) {
   1107 #ifdef INET6
   1108 	case AF_INET6:
   1109 		sa6 = (void *)sa;
   1110 		if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
   1111 			/* just use the scope field of the multicast address */
   1112 			return sa6->sin6_addr.s6_addr[2] & 0x0f;
   1113 		}
   1114 		/*
   1115 		 * Unicast addresses: map scope type to corresponding scope
   1116 		 * value defined for multcast addresses.
   1117 		 * XXX: hardcoded scope type values are bad...
   1118 		 */
   1119 		if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
   1120 			return 1; /* node local scope */
   1121 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
   1122 			return 2; /* link-local scope */
   1123 		if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
   1124 			return 5; /* site-local scope */
   1125 		return 14;	/* global scope */
   1126 #endif
   1127 	case AF_INET:
   1128 		/*
   1129 		 * IPv4 pseudo scoping according to RFC 3484.
   1130 		 */
   1131 		sa4 = (void *)sa;
   1132 		p = (u_char *)(void *)&sa4->sin_addr;
   1133 		/* IPv4 autoconfiguration addresses have link-local scope. */
   1134 		if (p[0] == 169 && p[1] == 254)
   1135 			return 2;
   1136 		/* Private addresses have site-local scope. */
   1137 		if (p[0] == 10 ||
   1138 		    (p[0] == 172 && (p[1] & 0xf0) == 16) ||
   1139 		    (p[0] == 192 && p[1] == 168))
   1140 			return 14;	/* XXX: It should be 5 unless NAT */
   1141 		/* Loopback addresses have link-local scope. */
   1142 		if (p[0] == 127)
   1143 			return 2;
   1144 		return 14;
   1145 	default:
   1146 		errno = EAFNOSUPPORT; /* is this a good error? */
   1147 		return -1;
   1148 	}
   1149 }
   1150 
   1151 /*
   1152  * FQDN hostname, DNS lookup
   1153  */
   1154 static int
   1155 explore_fqdn(const struct addrinfo *pai, const char *hostname,
   1156     const char *servname, struct addrinfo **res, struct servent_data *svd)
   1157 {
   1158 	struct addrinfo *result;
   1159 	struct addrinfo *cur;
   1160 	int error = 0;
   1161 	static const ns_dtab dtab[] = {
   1162 		NS_FILES_CB(_files_getaddrinfo, NULL)
   1163 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
   1164 		NS_NIS_CB(_yp_getaddrinfo, NULL)
   1165 		NS_NULL_CB
   1166 	};
   1167 
   1168 	_DIAGASSERT(pai != NULL);
   1169 	/* hostname may be NULL */
   1170 	/* servname may be NULL */
   1171 	_DIAGASSERT(res != NULL);
   1172 
   1173 	result = NULL;
   1174 
   1175 	/*
   1176 	 * if the servname does not match socktype/protocol, ignore it.
   1177 	 */
   1178 	if (get_portmatch(pai, servname, svd) != 0)
   1179 		return 0;
   1180 
   1181 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
   1182 	    default_dns_files, hostname, pai, servname)) {
   1183 	case NS_TRYAGAIN:
   1184 		error = EAI_AGAIN;
   1185 		goto free;
   1186 	case NS_UNAVAIL:
   1187 		error = EAI_FAIL;
   1188 		goto free;
   1189 	case NS_NOTFOUND:
   1190 		error = EAI_NODATA;
   1191 		goto free;
   1192 	case NS_SUCCESS:
   1193 		error = 0;
   1194 		for (cur = result; cur; cur = cur->ai_next) {
   1195 			/* Check for already filled port. */
   1196 			if (*getport(cur))
   1197 				continue;
   1198 			GET_PORT(cur, servname, svd);
   1199 			/* canonname should be filled already */
   1200 		}
   1201 		break;
   1202 	}
   1203 
   1204 	*res = result;
   1205 
   1206 	return 0;
   1207 
   1208 free:
   1209 	if (result)
   1210 		freeaddrinfo(result);
   1211 	return error;
   1212 }
   1213 
   1214 /*
   1215  * hostname == NULL.
   1216  * passive socket -> anyaddr (0.0.0.0 or ::)
   1217  * non-passive socket -> localhost (127.0.0.1 or ::1)
   1218  */
   1219 static int
   1220 explore_null(const struct addrinfo *pai, const char *servname,
   1221     struct addrinfo **res, struct servent_data *svd)
   1222 {
   1223 	int s;
   1224 	const struct afd *afd;
   1225 	struct addrinfo *cur;
   1226 	struct addrinfo sentinel;
   1227 	int error;
   1228 
   1229 	_DIAGASSERT(pai != NULL);
   1230 	/* servname may be NULL */
   1231 	_DIAGASSERT(res != NULL);
   1232 
   1233 	*res = NULL;
   1234 	sentinel.ai_next = NULL;
   1235 	cur = &sentinel;
   1236 
   1237 	/*
   1238 	 * filter out AFs that are not supported by the kernel
   1239 	 * XXX errno?
   1240 	 */
   1241 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
   1242 	if (s < 0) {
   1243 		if (errno != EMFILE)
   1244 			return 0;
   1245 	} else
   1246 		close(s);
   1247 
   1248 	/*
   1249 	 * if the servname does not match socktype/protocol, ignore it.
   1250 	 */
   1251 	if (get_portmatch(pai, servname, svd) != 0)
   1252 		return 0;
   1253 
   1254 	afd = find_afd(pai->ai_family);
   1255 	if (afd == NULL)
   1256 		return 0;
   1257 
   1258 	if (pai->ai_flags & AI_PASSIVE) {
   1259 		GET_AI(cur->ai_next, afd, afd->a_addrany);
   1260 		/* xxx meaningless?
   1261 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
   1262 		 */
   1263 		GET_PORT(cur->ai_next, servname, svd);
   1264 	} else {
   1265 		GET_AI(cur->ai_next, afd, afd->a_loopback);
   1266 		/* xxx meaningless?
   1267 		 * GET_CANONNAME(cur->ai_next, "localhost");
   1268 		 */
   1269 		GET_PORT(cur->ai_next, servname, svd);
   1270 	}
   1271 	cur = cur->ai_next;
   1272 
   1273 	*res = sentinel.ai_next;
   1274 	return 0;
   1275 
   1276 free:
   1277 	if (sentinel.ai_next)
   1278 		freeaddrinfo(sentinel.ai_next);
   1279 	return error;
   1280 }
   1281 
   1282 /*
   1283  * numeric hostname
   1284  */
   1285 static int
   1286 explore_numeric(const struct addrinfo *pai, const char *hostname,
   1287     const char *servname, struct addrinfo **res, const char *canonname,
   1288     struct servent_data *svd)
   1289 {
   1290 	const struct afd *afd;
   1291 	struct addrinfo *cur;
   1292 	struct addrinfo sentinel;
   1293 	int error;
   1294 	char pton[PTON_MAX];
   1295 
   1296 	_DIAGASSERT(pai != NULL);
   1297 	/* hostname may be NULL */
   1298 	/* servname may be NULL */
   1299 	_DIAGASSERT(res != NULL);
   1300 
   1301 	*res = NULL;
   1302 	sentinel.ai_next = NULL;
   1303 	cur = &sentinel;
   1304 
   1305 	/*
   1306 	 * if the servname does not match socktype/protocol, ignore it.
   1307 	 */
   1308 	if (get_portmatch(pai, servname, svd) != 0)
   1309 		return 0;
   1310 
   1311 	afd = find_afd(pai->ai_family);
   1312 	if (afd == NULL)
   1313 		return 0;
   1314 
   1315 	switch (afd->a_af) {
   1316 	case AF_INET:
   1317 	       /*
   1318 		* RFC3493 section 6.1, requires getaddrinfo() to accept
   1319 		* AF_INET formats that are accepted by inet_addr(); here
   1320 		* we use the equivalent inet_aton() function so we can
   1321 		* check for errors. inet_pton() only accepts addresses
   1322 		* in the dotted quad format and only in base 10, so we
   1323 		* need to treat AF_INET specially.
   1324 		*
   1325 		* We also check for trailing characters and fail if there
   1326 		* are any. This matches the inet_pton6(), but not the
   1327 		* inet_pton4() behavior. We choose to make the protocol
   1328 		* behavior consistent.
   1329 		*/
   1330 		if (inet_aton(hostname, (void *)pton) == 1 &&
   1331 		    hostname[strspn(hostname, "0123456789.xabcdefXABCDEF")]
   1332 		    == '\0') {
   1333 			if (pai->ai_family == afd->a_af ||
   1334 			    pai->ai_family == PF_UNSPEC /*?*/) {
   1335 				GET_AI(cur->ai_next, afd, pton);
   1336 				GET_PORT(cur->ai_next, servname, svd);
   1337 				if ((pai->ai_flags & AI_CANONNAME)) {
   1338 					/*
   1339 					 * Set the numeric address itself as
   1340 					 * the canonical name, based on a
   1341 					 * clarification in rfc2553bis-03.
   1342 					 */
   1343 					GET_CANONNAME(cur->ai_next, canonname);
   1344 				}
   1345 				while (cur && cur->ai_next)
   1346 					cur = cur->ai_next;
   1347 			} else
   1348 				ERR(EAI_FAMILY);	/*xxx*/
   1349 		}
   1350 		break;
   1351 	default:
   1352 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
   1353 			if (pai->ai_family == afd->a_af ||
   1354 			    pai->ai_family == PF_UNSPEC /*?*/) {
   1355 				GET_AI(cur->ai_next, afd, pton);
   1356 				GET_PORT(cur->ai_next, servname, svd);
   1357 				if ((pai->ai_flags & AI_CANONNAME)) {
   1358 					/*
   1359 					 * Set the numeric address itself as
   1360 					 * the canonical name, based on a
   1361 					 * clarification in rfc2553bis-03.
   1362 					 */
   1363 					GET_CANONNAME(cur->ai_next, canonname);
   1364 				}
   1365 				while (cur->ai_next)
   1366 					cur = cur->ai_next;
   1367 			} else
   1368 				ERR(EAI_FAMILY);	/*xxx*/
   1369 		}
   1370 		break;
   1371 	}
   1372 
   1373 	*res = sentinel.ai_next;
   1374 	return 0;
   1375 
   1376 free:
   1377 bad:
   1378 	if (sentinel.ai_next)
   1379 		freeaddrinfo(sentinel.ai_next);
   1380 	return error;
   1381 }
   1382 
   1383 /*
   1384  * numeric hostname with scope
   1385  */
   1386 static int
   1387 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
   1388     const char *servname, struct addrinfo **res, struct servent_data *svd)
   1389 {
   1390 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
   1391 	return explore_numeric(pai, hostname, servname, res, hostname, svd);
   1392 #else
   1393 	const struct afd *afd;
   1394 	struct addrinfo *cur;
   1395 	int error;
   1396 	char *hostname2 = NULL, *addr;
   1397 	const char *cp, *scope;
   1398 	struct sockaddr_in6 *sin6;
   1399 
   1400 	_DIAGASSERT(pai != NULL);
   1401 	/* hostname may be NULL */
   1402 	/* servname may be NULL */
   1403 	_DIAGASSERT(res != NULL);
   1404 
   1405 	/*
   1406 	 * if the servname does not match socktype/protocol, ignore it.
   1407 	 */
   1408 	if (get_portmatch(pai, servname, svd) != 0)
   1409 		return 0;
   1410 
   1411 	afd = find_afd(pai->ai_family);
   1412 	if (afd == NULL)
   1413 		return 0;
   1414 
   1415 	if (!afd->a_scoped)
   1416 		return explore_numeric(pai, hostname, servname, res, hostname,
   1417 		    svd);
   1418 
   1419 	cp = strchr(hostname, SCOPE_DELIMITER);
   1420 	if (cp == NULL)
   1421 		return explore_numeric(pai, hostname, servname, res, hostname,
   1422 		    svd);
   1423 
   1424 	/*
   1425 	 * Handle special case of <scoped_address><delimiter><scope id>
   1426 	 */
   1427 	hostname2 = strdup(hostname);
   1428 	if (hostname2 == NULL)
   1429 		return EAI_MEMORY;
   1430 	/* terminate at the delimiter */
   1431 	hostname2[cp - hostname] = '\0';
   1432 	addr = hostname2;
   1433 	scope = cp + 1;
   1434 
   1435 	error = explore_numeric(pai, addr, servname, res, hostname, svd);
   1436 	if (error == 0) {
   1437 		u_int32_t scopeid;
   1438 
   1439 		for (cur = *res; cur; cur = cur->ai_next) {
   1440 			if (cur->ai_family != AF_INET6)
   1441 				continue;
   1442 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
   1443 			if (ip6_str2scopeid(__UNCONST(scope), sin6, &scopeid)
   1444 			    == -1) {
   1445 				free(hostname2);
   1446 				return EAI_NODATA; /* XXX: is return OK? */
   1447 			}
   1448 			sin6->sin6_scope_id = scopeid;
   1449 		}
   1450 	}
   1451 
   1452 	free(hostname2);
   1453 
   1454 	return error;
   1455 #endif
   1456 }
   1457 
   1458 static int
   1459 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
   1460 {
   1461 
   1462 	_DIAGASSERT(pai != NULL);
   1463 	_DIAGASSERT(ai != NULL);
   1464 	_DIAGASSERT(str != NULL);
   1465 
   1466 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
   1467 		ai->ai_canonname = strdup(str);
   1468 		if (ai->ai_canonname == NULL)
   1469 			return EAI_MEMORY;
   1470 	}
   1471 	return 0;
   1472 }
   1473 
   1474 struct addrinfo *
   1475 allocaddrinfo(socklen_t addrlen)
   1476 {
   1477 	struct addrinfo *ai;
   1478 
   1479 	ai = calloc(sizeof(struct addrinfo) + addrlen, 1);
   1480 	if (ai) {
   1481 		ai->ai_addr = (void *)(ai+1);
   1482 		ai->ai_addrlen = ai->ai_addr->sa_len = addrlen;
   1483 	}
   1484 
   1485 	return ai;
   1486 }
   1487 
   1488 static struct addrinfo *
   1489 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
   1490 {
   1491 	char *p;
   1492 	struct addrinfo *ai;
   1493 	struct sockaddr *save;
   1494 
   1495 	_DIAGASSERT(pai != NULL);
   1496 	_DIAGASSERT(afd != NULL);
   1497 	_DIAGASSERT(addr != NULL);
   1498 
   1499 	ai = allocaddrinfo((socklen_t)afd->a_socklen);
   1500 	if (ai == NULL)
   1501 		return NULL;
   1502 
   1503 	save = ai->ai_addr;
   1504 	memcpy(ai, pai, sizeof(struct addrinfo));
   1505 
   1506 	/* since we just overwrote all of ai, we have
   1507 	   to restore ai_addr and ai_addrlen */
   1508 	ai->ai_addr = save;
   1509 	ai->ai_addrlen = (socklen_t)afd->a_socklen;
   1510 
   1511 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
   1512 	p = (char *)(void *)(ai->ai_addr);
   1513 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
   1514 	return ai;
   1515 }
   1516 
   1517 static int
   1518 get_portmatch(const struct addrinfo *ai, const char *servname,
   1519     struct servent_data *svd)
   1520 {
   1521 
   1522 	_DIAGASSERT(ai != NULL);
   1523 	/* servname may be NULL */
   1524 
   1525 	return get_port(ai, servname, 1, svd);
   1526 }
   1527 
   1528 static int
   1529 get_port(const struct addrinfo *ai, const char *servname, int matchonly,
   1530     struct servent_data *svd)
   1531 {
   1532 	const char *proto;
   1533 	struct servent *sp;
   1534 	int port;
   1535 	int allownumeric;
   1536 
   1537 	_DIAGASSERT(ai != NULL);
   1538 	/* servname may be NULL */
   1539 
   1540 	if (servname == NULL)
   1541 		return 0;
   1542 	switch (ai->ai_family) {
   1543 	case AF_INET:
   1544 #ifdef AF_INET6
   1545 	case AF_INET6:
   1546 #endif
   1547 		break;
   1548 	default:
   1549 		return 0;
   1550 	}
   1551 
   1552 	switch (ai->ai_socktype) {
   1553 	case SOCK_RAW:
   1554 		return EAI_SERVICE;
   1555 	case SOCK_DGRAM:
   1556 	case SOCK_STREAM:
   1557 		allownumeric = 1;
   1558 		break;
   1559 	case ANY:
   1560 		/*
   1561 		 * This was 0.	It is now 1 so that queries specifying
   1562 		 * a NULL hint, or hint without socktype (but, hopefully,
   1563 		 * with protocol) and numeric address actually work.
   1564 		 */
   1565 		allownumeric = 1;
   1566 		break;
   1567 	default:
   1568 		return EAI_SOCKTYPE;
   1569 	}
   1570 
   1571 	port = str2number(servname);
   1572 	if (port >= 0) {
   1573 		if (!allownumeric)
   1574 			return EAI_SERVICE;
   1575 		if (port < 0 || port > 65535)
   1576 			return EAI_SERVICE;
   1577 		port = htons(port);
   1578 	} else {
   1579 		struct servent sv;
   1580 		if (ai->ai_flags & AI_NUMERICSERV)
   1581 			return EAI_NONAME;
   1582 
   1583 		switch (ai->ai_socktype) {
   1584 		case SOCK_DGRAM:
   1585 			proto = "udp";
   1586 			break;
   1587 		case SOCK_STREAM:
   1588 			proto = "tcp";
   1589 			break;
   1590 		default:
   1591 			proto = NULL;
   1592 			break;
   1593 		}
   1594 
   1595 		sp = getservbyname_r(servname, proto, &sv, svd);
   1596 		if (sp == NULL)
   1597 			return EAI_SERVICE;
   1598 		port = sp->s_port;
   1599 	}
   1600 
   1601 	if (!matchonly)
   1602 		*getport(__UNCONST(ai)) = port;
   1603 	return 0;
   1604 }
   1605 
   1606 static const struct afd *
   1607 find_afd(int af)
   1608 {
   1609 	const struct afd *afd;
   1610 
   1611 	if (af == PF_UNSPEC)
   1612 		return NULL;
   1613 	for (afd = afdl; afd->a_af; afd++) {
   1614 		if (afd->a_af == af)
   1615 			return afd;
   1616 	}
   1617 	return NULL;
   1618 }
   1619 
   1620 /*
   1621  * AI_ADDRCONFIG check: Build a mask containing a bit set for each address
   1622  * family configured in the system.
   1623  *
   1624  */
   1625 static int
   1626 addrconfig(uint64_t *mask)
   1627 {
   1628 	struct ifaddrs *ifaddrs, *ifa;
   1629 
   1630 	if (getifaddrs(&ifaddrs) == -1)
   1631 		return -1;
   1632 
   1633 	*mask = 0;
   1634 	for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next)
   1635 		if (ifa->ifa_addr && (ifa->ifa_flags & IFF_UP)) {
   1636 			_DIAGASSERT(ifa->ifa_addr->sa_family < 64);
   1637 			*mask |= (uint64_t)1 << ifa->ifa_addr->sa_family;
   1638 		}
   1639 
   1640 	freeifaddrs(ifaddrs);
   1641 	return 0;
   1642 }
   1643 
   1644 #ifdef INET6
   1645 /* convert a string to a scope identifier. XXX: IPv6 specific */
   1646 static int
   1647 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
   1648 {
   1649 	u_long lscopeid;
   1650 	struct in6_addr *a6;
   1651 	char *ep;
   1652 
   1653 	_DIAGASSERT(scope != NULL);
   1654 	_DIAGASSERT(sin6 != NULL);
   1655 	_DIAGASSERT(scopeid != NULL);
   1656 
   1657 	a6 = &sin6->sin6_addr;
   1658 
   1659 	/* empty scopeid portion is invalid */
   1660 	if (*scope == '\0')
   1661 		return -1;
   1662 
   1663 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
   1664 		/*
   1665 		 * We currently assume a one-to-one mapping between links
   1666 		 * and interfaces, so we simply use interface indices for
   1667 		 * like-local scopes.
   1668 		 */
   1669 		*scopeid = if_nametoindex(scope);
   1670 		if (*scopeid == 0)
   1671 			goto trynumeric;
   1672 		return 0;
   1673 	}
   1674 
   1675 	/* still unclear about literal, allow numeric only - placeholder */
   1676 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
   1677 		goto trynumeric;
   1678 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
   1679 		goto trynumeric;
   1680 	else
   1681 		goto trynumeric;	/* global */
   1682 
   1683 	/* try to convert to a numeric id as a last resort */
   1684   trynumeric:
   1685 	errno = 0;
   1686 	lscopeid = strtoul(scope, &ep, 10);
   1687 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
   1688 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
   1689 		return 0;
   1690 	else
   1691 		return -1;
   1692 }
   1693 #endif
   1694 
   1695 /* code duplicate with gethnamaddr.c */
   1696 
   1697 static const char AskedForGot[] =
   1698 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
   1699 
   1700 #define maybe_ok(res, nm, ok) (((res)->options & RES_NOCHECKNAME) != 0U || \
   1701                                (ok)(nm) != 0)
   1702 static struct addrinfo *
   1703 getanswer(res_state res, const querybuf *answer, int anslen, const char *qname,
   1704     int qtype, const struct addrinfo *pai)
   1705 {
   1706 	struct addrinfo sentinel, *cur;
   1707 	struct addrinfo ai, *aip;
   1708 	const struct afd *afd;
   1709 	char *canonname;
   1710 	const HEADER *hp;
   1711 	const u_char *cp;
   1712 	int n;
   1713 	const u_char *eom;
   1714 	char *bp, *ep;
   1715 	int type, class, ancount, qdcount;
   1716 	int haveanswer, had_error;
   1717 	char tbuf[MAXDNAME];
   1718 	int (*name_ok) (const char *);
   1719 	char hostbuf[8*1024];
   1720 	int port, pri, weight;
   1721 	struct srvinfo *srvlist, *srv, *csrv;
   1722 
   1723 	_DIAGASSERT(answer != NULL);
   1724 	_DIAGASSERT(qname != NULL);
   1725 	_DIAGASSERT(pai != NULL);
   1726 	_DIAGASSERT(res != NULL);
   1727 
   1728 	memset(&sentinel, 0, sizeof(sentinel));
   1729 	cur = &sentinel;
   1730 
   1731 	canonname = NULL;
   1732 	eom = answer->buf + anslen;
   1733 	switch (qtype) {
   1734 	case T_A:
   1735 	case T_AAAA:
   1736 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
   1737 		name_ok = res_hnok;
   1738 		break;
   1739 	case T_SRV:
   1740 		name_ok = gai_srvok;
   1741 		break;
   1742 	default:
   1743 		return NULL;	/* XXX should be abort(); */
   1744 	}
   1745 	/*
   1746 	 * find first satisfactory answer
   1747 	 */
   1748 	hp = &answer->hdr;
   1749 	ancount = ntohs(hp->ancount);
   1750 	qdcount = ntohs(hp->qdcount);
   1751 	bp = hostbuf;
   1752 	ep = hostbuf + sizeof hostbuf;
   1753 	cp = answer->buf + HFIXEDSZ;
   1754 	if (qdcount != 1) {
   1755 		h_errno = NO_RECOVERY;
   1756 		return NULL;
   1757 	}
   1758 	n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
   1759 	if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
   1760 		h_errno = NO_RECOVERY;
   1761 		return NULL;
   1762 	}
   1763 	cp += n + QFIXEDSZ;
   1764 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
   1765 		/* res_send() has already verified that the query name is the
   1766 		 * same as the one we sent; this just gets the expanded name
   1767 		 * (i.e., with the succeeding search-domain tacked on).
   1768 		 */
   1769 		n = (int)strlen(bp) + 1;		/* for the \0 */
   1770 		if (n >= MAXHOSTNAMELEN) {
   1771 			h_errno = NO_RECOVERY;
   1772 			return NULL;
   1773 		}
   1774 		canonname = bp;
   1775 		bp += n;
   1776 		/* The qname can be abbreviated, but h_name is now absolute. */
   1777 		qname = canonname;
   1778 	}
   1779 	haveanswer = 0;
   1780 	had_error = 0;
   1781 	srvlist = NULL;
   1782 	while (ancount-- > 0 && cp < eom && !had_error) {
   1783 		n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
   1784 		if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
   1785 			had_error++;
   1786 			continue;
   1787 		}
   1788 		cp += n;			/* name */
   1789 		type = _getshort(cp);
   1790 		cp += INT16SZ;			/* type */
   1791 		class = _getshort(cp);
   1792 		cp += INT16SZ + INT32SZ;	/* class, TTL */
   1793 		n = _getshort(cp);
   1794 		cp += INT16SZ;			/* len */
   1795 		if (class != C_IN) {
   1796 			/* XXX - debug? syslog? */
   1797 			cp += n;
   1798 			continue;		/* XXX - had_error++ ? */
   1799 		}
   1800 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
   1801 		    type == T_CNAME) {
   1802 			n = dn_expand(answer->buf, eom, cp, tbuf, (int)sizeof tbuf);
   1803 			if ((n < 0) || !maybe_ok(res, tbuf, name_ok)) {
   1804 				had_error++;
   1805 				continue;
   1806 			}
   1807 			cp += n;
   1808 			/* Get canonical name. */
   1809 			n = (int)strlen(tbuf) + 1;	/* for the \0 */
   1810 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
   1811 				had_error++;
   1812 				continue;
   1813 			}
   1814 			strlcpy(bp, tbuf, (size_t)(ep - bp));
   1815 			canonname = bp;
   1816 			bp += n;
   1817 			continue;
   1818 		}
   1819 		if (qtype == T_ANY) {
   1820 			if (!(type == T_A || type == T_AAAA)) {
   1821 				cp += n;
   1822 				continue;
   1823 			}
   1824 		} else if (type != qtype) {
   1825 			if (type != T_KEY && type != T_SIG && type != T_DNAME) {
   1826 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1827 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1828 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
   1829 				       qname, p_class(C_IN), p_type(qtype),
   1830 				       p_type(type));
   1831 			}
   1832 			cp += n;
   1833 			continue;		/* XXX - had_error++ ? */
   1834 		}
   1835 		switch (type) {
   1836 		case T_A:
   1837 		case T_AAAA:
   1838 			if (strcasecmp(canonname, bp) != 0) {
   1839 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1840 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1841 				       AskedForGot, canonname, bp);
   1842 				cp += n;
   1843 				continue;	/* XXX - had_error++ ? */
   1844 			}
   1845 			if (type == T_A && n != INADDRSZ) {
   1846 				cp += n;
   1847 				continue;
   1848 			}
   1849 			if (type == T_AAAA && n != IN6ADDRSZ) {
   1850 				cp += n;
   1851 				continue;
   1852 			}
   1853 			if (type == T_AAAA) {
   1854 				struct in6_addr in6;
   1855 				memcpy(&in6, cp, IN6ADDRSZ);
   1856 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
   1857 					cp += n;
   1858 					continue;
   1859 				}
   1860 			}
   1861 			if (!haveanswer) {
   1862 				int nn;
   1863 
   1864 				canonname = bp;
   1865 				nn = (int)strlen(bp) + 1;	/* for the \0 */
   1866 				bp += nn;
   1867 			}
   1868 
   1869 			/* don't overwrite pai */
   1870 			ai = *pai;
   1871 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
   1872 			afd = find_afd(ai.ai_family);
   1873 			if (afd == NULL) {
   1874 				cp += n;
   1875 				continue;
   1876 			}
   1877 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
   1878 			if (cur->ai_next == NULL)
   1879 				had_error++;
   1880 			while (cur && cur->ai_next)
   1881 				cur = cur->ai_next;
   1882 			cp += n;
   1883 			break;
   1884 		case T_SRV:
   1885 			/* Add to SRV list. Insertion sort on priority. */
   1886 			pri = _getshort(cp);
   1887 			cp += INT16SZ;
   1888 			weight = _getshort(cp);
   1889 			cp += INT16SZ;
   1890 			port = _getshort(cp);
   1891 			cp += INT16SZ;
   1892 			n = dn_expand(answer->buf, eom, cp, tbuf,
   1893 			    (int)sizeof(tbuf));
   1894 			if ((n < 0) || !maybe_ok(res, tbuf, res_hnok)) {
   1895 				had_error++;
   1896 				continue;
   1897 			}
   1898 			cp += n;
   1899 			if (strlen(tbuf) + 1 >= MAXDNAME) {
   1900 				had_error++;
   1901 				continue;
   1902 			}
   1903 			srv = malloc(sizeof(*srv));
   1904 			if (!srv) {
   1905 				had_error++;
   1906 				continue;
   1907 			}
   1908 			strlcpy(srv->name, tbuf, sizeof(srv->name));
   1909 			srv->pri = pri;
   1910 			srv->weight = weight;
   1911 			srv->port = port;
   1912 			/* Weight 0 is sorted before other weights. */
   1913 			if (!srvlist
   1914 			    || srv->pri < srvlist->pri
   1915 			    || (srv->pri == srvlist->pri &&
   1916 			    (!srv->weight || srvlist->weight))) {
   1917 				srv->next = srvlist;
   1918 				srvlist = srv;
   1919 			} else {
   1920 				for (csrv = srvlist;
   1921 				    csrv->next && csrv->next->pri <= srv->pri;
   1922 				    csrv = csrv->next) {
   1923 					if (csrv->next->pri == srv->pri
   1924 					    && (!srv->weight ||
   1925 					    csrv->next->weight))
   1926 						break;
   1927 				}
   1928 				srv->next = csrv->next;
   1929 				csrv->next = srv;
   1930 			}
   1931 			continue; /* Don't add to haveanswer yet. */
   1932 		default:
   1933 			abort();
   1934 		}
   1935 		if (!had_error)
   1936 			haveanswer++;
   1937 	}
   1938 
   1939 	if (srvlist) {
   1940 		/*
   1941 		 * Check for explicit rejection.
   1942 		 */
   1943 		if (!srvlist->next && !srvlist->name[0]) {
   1944 			free(srvlist);
   1945 			h_errno = HOST_NOT_FOUND;
   1946 			return NULL;
   1947 		}
   1948 
   1949 		while (srvlist) {
   1950 			struct res_target q, q2;
   1951 
   1952 			srv = srvlist;
   1953 			srvlist = srvlist->next;
   1954 
   1955 			/*
   1956 			 * Since res_* doesn't give the additional
   1957 			 * section, we always look up.
   1958 			 */
   1959 			memset(&q, 0, sizeof(q));
   1960 			memset(&q2, 0, sizeof(q2));
   1961 
   1962 			q.name = srv->name;
   1963 			q.qclass = C_IN;
   1964 			q.qtype = T_AAAA;
   1965 			q.next = &q2;
   1966 			q2.name = srv->name;
   1967 			q2.qclass = C_IN;
   1968 			q2.qtype = T_A;
   1969 
   1970 			aip = _dns_query(&q, pai, res, 0);
   1971 
   1972 			if (aip != NULL) {
   1973 				cur->ai_next = aip;
   1974 				while (cur && cur->ai_next) {
   1975 					cur = cur->ai_next;
   1976 					*getport(cur) = htons(srv->port);
   1977 					haveanswer++;
   1978 				}
   1979 			}
   1980 			free(srv);
   1981 		}
   1982 	}
   1983 	if (haveanswer) {
   1984 		if (!sentinel.ai_next->ai_canonname)
   1985 		       (void)get_canonname(pai, sentinel.ai_next,
   1986 			   canonname ? canonname : qname);
   1987 		h_errno = NETDB_SUCCESS;
   1988 		return sentinel.ai_next;
   1989 	}
   1990 
   1991 	/* We could have walked a CNAME chain, */
   1992 	/* but the ultimate target may not have what we looked for */
   1993 	h_errno = ntohs(hp->ancount) > 0? NO_DATA : NO_RECOVERY;
   1994 	return NULL;
   1995 }
   1996 
   1997 #define SORTEDADDR(p)	(((struct sockaddr_in *)(void *)(p->ai_next->ai_addr))->sin_addr.s_addr)
   1998 #define SORTMATCH(p, s) ((SORTEDADDR(p) & (s).mask) == (s).addr.s_addr)
   1999 
   2000 static void
   2001 aisort(struct addrinfo *s, res_state res)
   2002 {
   2003 	struct addrinfo head, *t, *p;
   2004 	int i;
   2005 
   2006 	head.ai_next = NULL;
   2007 	t = &head;
   2008 
   2009 	for (i = 0; i < res->nsort; i++) {
   2010 		p = s;
   2011 		while (p->ai_next) {
   2012 			if ((p->ai_next->ai_family != AF_INET)
   2013 			|| SORTMATCH(p, res->sort_list[i])) {
   2014 				t->ai_next = p->ai_next;
   2015 				t = t->ai_next;
   2016 				p->ai_next = p->ai_next->ai_next;
   2017 			} else {
   2018 				p = p->ai_next;
   2019 			}
   2020 		}
   2021 	}
   2022 
   2023 	/* add rest of list and reset s to the new list*/
   2024 	t->ai_next = s->ai_next;
   2025 	s->ai_next = head.ai_next;
   2026 }
   2027 
   2028 static struct addrinfo *
   2029 _dns_query(struct res_target *q, const struct addrinfo *pai,
   2030     res_state res, int dosearch)
   2031 {
   2032 	struct res_target *q2 = q->next;
   2033  	querybuf *buf, *buf2;
   2034 	struct addrinfo sentinel, *cur, *ai;
   2035 
   2036 #ifdef DNS_DEBUG
   2037 	struct res_target *iter;
   2038 	for (iter = q; iter; iter = iter->next)
   2039 		printf("Query type %d for %s\n", iter->qtype, iter->name);
   2040 #endif
   2041 
   2042  	buf = malloc(sizeof(*buf));
   2043  	if (buf == NULL) {
   2044  		h_errno = NETDB_INTERNAL;
   2045 		return NULL;
   2046  	}
   2047  	buf2 = malloc(sizeof(*buf2));
   2048  	if (buf2 == NULL) {
   2049  		free(buf);
   2050  		h_errno = NETDB_INTERNAL;
   2051 		return NULL;
   2052 	}
   2053 
   2054 	memset(&sentinel, 0, sizeof(sentinel));
   2055 	cur = &sentinel;
   2056 
   2057 	q->answer = buf->buf;
   2058 	q->anslen = sizeof(buf->buf);
   2059 	if (q2) {
   2060 		q2->answer = buf2->buf;
   2061 		q2->anslen = sizeof(buf2->buf);
   2062 	}
   2063 
   2064 	if (dosearch) {
   2065 		if (res_searchN(q->name, q, res) < 0)
   2066 			goto out;
   2067 	} else {
   2068 		if (res_queryN(q->name, q, res) < 0)
   2069 			goto out;
   2070 	}
   2071 
   2072 	ai = getanswer(res, buf, q->n, q->name, q->qtype, pai);
   2073 	if (ai) {
   2074 		cur->ai_next = ai;
   2075 		while (cur && cur->ai_next)
   2076 			cur = cur->ai_next;
   2077 	}
   2078 	if (q2) {
   2079 		ai = getanswer(res, buf2, q2->n, q2->name, q2->qtype, pai);
   2080 		if (ai)
   2081 			cur->ai_next = ai;
   2082  	}
   2083 	free(buf);
   2084 	free(buf2);
   2085 	return sentinel.ai_next;
   2086 out:
   2087 	free(buf);
   2088 	free(buf2);
   2089 	return NULL;
   2090 }
   2091 
   2092 /*ARGSUSED*/
   2093 static struct addrinfo *
   2094 _dns_srv_lookup(const char *name, const char *servname,
   2095     const struct addrinfo *pai)
   2096 {
   2097 	static const char * const srvprotos[] = { "tcp", "udp" };
   2098 	static const int srvnottype[] = { SOCK_DGRAM, SOCK_STREAM };
   2099 	static const int nsrvprotos = 2;
   2100 	struct addrinfo sentinel, *cur, *ai;
   2101 	struct servent *serv, sv;
   2102 	struct servent_data svd;
   2103 	struct res_target q;
   2104 	res_state res;
   2105 	char *tname;
   2106 	int i;
   2107 
   2108 	res = __res_get_state();
   2109 	if (res == NULL)
   2110 		return NULL;
   2111 
   2112 	memset(&svd, 0, sizeof(svd));
   2113 	memset(&sentinel, 0, sizeof(sentinel));
   2114 	cur = &sentinel;
   2115 
   2116 	/*
   2117 	 * Iterate over supported SRV protocols.
   2118 	 * (currently UDP and TCP only)
   2119 	 */
   2120 	for (i = 0; i < nsrvprotos; i++) {
   2121 		/*
   2122 		 * Check that the caller didn't specify a hint
   2123 		 * which precludes this protocol.
   2124 		 */
   2125 		if (pai->ai_socktype == srvnottype[i])
   2126 			continue;
   2127 		/*
   2128 		 * If the caller specified a port,
   2129 		 * then lookup the database for the
   2130 		 * official service name.
   2131 		 */
   2132 		serv = getservbyname_r(servname, srvprotos[i], &sv, &svd);
   2133 		if (serv == NULL)
   2134 			continue;
   2135 
   2136 		/*
   2137 		 * Construct service DNS name.
   2138 		 */
   2139 		if (asprintf(&tname, "_%s._%s.%s", serv->s_name, serv->s_proto,
   2140 		    name) < 0)
   2141 			continue;
   2142 
   2143 		memset(&q, 0, sizeof(q));
   2144 		q.name = tname;
   2145 		q.qclass = C_IN;
   2146 		q.qtype = T_SRV;
   2147 
   2148 		/*
   2149 		 * Do SRV query.
   2150 		 */
   2151 		ai = _dns_query(&q, pai, res, 1);
   2152 		if (ai) {
   2153 			cur->ai_next = ai;
   2154 			while (cur && cur->ai_next)
   2155 				cur = cur->ai_next;
   2156 		}
   2157 		free(tname);
   2158 	}
   2159 
   2160 	if (res->nsort)
   2161 		aisort(&sentinel, res);
   2162 
   2163 	__res_put_state(res);
   2164 
   2165 	return sentinel.ai_next;
   2166 }
   2167 
   2168 /*ARGSUSED*/
   2169 static struct addrinfo *
   2170 _dns_host_lookup(const char *name, const struct addrinfo *pai)
   2171 {
   2172 	struct res_target q, q2;
   2173 	struct addrinfo sentinel, *ai;
   2174 	res_state res;
   2175 
   2176 	res = __res_get_state();
   2177 	if (res == NULL)
   2178 		return NULL;
   2179 
   2180 	memset(&q, 0, sizeof(q2));
   2181 	memset(&q2, 0, sizeof(q2));
   2182 
   2183 	switch (pai->ai_family) {
   2184 	case AF_UNSPEC:
   2185 		/* prefer IPv6 */
   2186 		q.name = name;
   2187 		q.qclass = C_IN;
   2188 		q.qtype = T_AAAA;
   2189 		q.next = &q2;
   2190 		q2.name = name;
   2191 		q2.qclass = C_IN;
   2192 		q2.qtype = T_A;
   2193 		break;
   2194 	case AF_INET:
   2195 		q.name = name;
   2196 		q.qclass = C_IN;
   2197 		q.qtype = T_A;
   2198 		break;
   2199 	case AF_INET6:
   2200 		q.name = name;
   2201 		q.qclass = C_IN;
   2202 		q.qtype = T_AAAA;
   2203 		break;
   2204 	default:
   2205 		__res_put_state(res);
   2206 		h_errno = NETDB_INTERNAL;
   2207 		return NULL;
   2208 	}
   2209 
   2210 	ai = _dns_query(&q, pai, res, 1);
   2211 
   2212 	memset(&sentinel, 0, sizeof(sentinel));
   2213 	sentinel.ai_next = ai;
   2214 
   2215 	if (ai != NULL && res->nsort)
   2216 		aisort(&sentinel, res);
   2217 
   2218 	__res_put_state(res);
   2219 
   2220 	return sentinel.ai_next;
   2221 }
   2222 
   2223 /*ARGSUSED*/
   2224 static int
   2225 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2226 {
   2227 	struct addrinfo *ai = NULL;
   2228 	const char *name, *servname;
   2229 	const struct addrinfo *pai;
   2230 
   2231 	name = va_arg(ap, char *);
   2232 	pai = va_arg(ap, const struct addrinfo *);
   2233 	servname = va_arg(ap, char *);
   2234 
   2235 	/*
   2236 	 * Try doing SRV lookup on service first.
   2237 	 */
   2238 	if (servname
   2239 #ifdef AI_SRV
   2240 	    && (pai->ai_flags & AI_SRV)
   2241 #endif
   2242 	    && !(pai->ai_flags & AI_NUMERICSERV)
   2243 	    && str2number(servname) == -1) {
   2244 
   2245 #ifdef DNS_DEBUG
   2246 		printf("%s: try SRV lookup\n", __func__);
   2247 #endif
   2248 		ai = _dns_srv_lookup(name, servname, pai);
   2249 	}
   2250 
   2251 	/*
   2252 	 * Do lookup on name.
   2253 	 */
   2254 	if (ai == NULL) {
   2255 
   2256 #ifdef DNS_DEBUG
   2257 		printf("%s: try HOST lookup\n", __func__);
   2258 #endif
   2259 		ai = _dns_host_lookup(name, pai);
   2260 
   2261 		if (ai == NULL) {
   2262 			switch (h_errno) {
   2263 			case HOST_NOT_FOUND:
   2264 			case NO_DATA:	// XXX: Perhaps we could differentiate
   2265 					// So that we could return EAI_NODATA?
   2266 				return NS_NOTFOUND;
   2267 			case TRY_AGAIN:
   2268 				return NS_TRYAGAIN;
   2269 			default:
   2270 				return NS_UNAVAIL;
   2271 			}
   2272 		}
   2273 	}
   2274 
   2275 	*((struct addrinfo **)rv) = ai;
   2276 	return NS_SUCCESS;
   2277 }
   2278 
   2279 static void
   2280 _sethtent(FILE **hostf)
   2281 {
   2282 
   2283 	if (!*hostf)
   2284 		*hostf = fopen(_PATH_HOSTS, "re");
   2285 	else
   2286 		rewind(*hostf);
   2287 }
   2288 
   2289 static void
   2290 _endhtent(FILE **hostf)
   2291 {
   2292 
   2293 	if (*hostf) {
   2294 		(void) fclose(*hostf);
   2295 		*hostf = NULL;
   2296 	}
   2297 }
   2298 
   2299 static struct addrinfo *
   2300 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
   2301 {
   2302 	char *p;
   2303 	char *cp, *tname, *cname;
   2304 	struct addrinfo hints, *res0, *res;
   2305 	int error;
   2306 	const char *addr;
   2307 	char hostbuf[8*1024];
   2308 
   2309 	_DIAGASSERT(name != NULL);
   2310 	_DIAGASSERT(pai != NULL);
   2311 
   2312 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
   2313 		return NULL;
   2314  again:
   2315 	if (!(p = fgets(hostbuf, (int)sizeof hostbuf, *hostf)))
   2316 		return NULL;
   2317 	if (*p == '#')
   2318 		goto again;
   2319 	if (!(cp = strpbrk(p, "#\n")))
   2320 		goto again;
   2321 	*cp = '\0';
   2322 	if (!(cp = strpbrk(p, " \t")))
   2323 		goto again;
   2324 	*cp++ = '\0';
   2325 	addr = p;
   2326 	/* if this is not something we're looking for, skip it. */
   2327 	cname = NULL;
   2328 	while (cp && *cp) {
   2329 		if (*cp == ' ' || *cp == '\t') {
   2330 			cp++;
   2331 			continue;
   2332 		}
   2333 		if (!cname)
   2334 			cname = cp;
   2335 		tname = cp;
   2336 		if ((cp = strpbrk(cp, " \t")) != NULL)
   2337 			*cp++ = '\0';
   2338 		if (strcasecmp(name, tname) == 0)
   2339 			goto found;
   2340 	}
   2341 	goto again;
   2342 
   2343 found:
   2344 	hints = *pai;
   2345 	hints.ai_flags = AI_NUMERICHOST;
   2346 	error = getaddrinfo(addr, NULL, &hints, &res0);
   2347 	if (error)
   2348 		goto again;
   2349 	for (res = res0; res; res = res->ai_next) {
   2350 		/* cover it up */
   2351 		res->ai_flags = pai->ai_flags;
   2352 
   2353 		if (pai->ai_flags & AI_CANONNAME) {
   2354 			if (get_canonname(pai, res, cname) != 0) {
   2355 				freeaddrinfo(res0);
   2356 				goto again;
   2357 			}
   2358 		}
   2359 	}
   2360 	return res0;
   2361 }
   2362 
   2363 /*ARGSUSED*/
   2364 static int
   2365 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2366 {
   2367 	const char *name;
   2368 	const struct addrinfo *pai;
   2369 	struct addrinfo sentinel, *cur;
   2370 	struct addrinfo *p;
   2371 #ifndef _REENTRANT
   2372 	static
   2373 #endif
   2374 	FILE *hostf = NULL;
   2375 
   2376 	name = va_arg(ap, char *);
   2377 	pai = va_arg(ap, const struct addrinfo *);
   2378 
   2379 	memset(&sentinel, 0, sizeof(sentinel));
   2380 	cur = &sentinel;
   2381 
   2382 	_sethtent(&hostf);
   2383 	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
   2384 		cur->ai_next = p;
   2385 		while (cur && cur->ai_next)
   2386 			cur = cur->ai_next;
   2387 	}
   2388 	_endhtent(&hostf);
   2389 
   2390 	*((struct addrinfo **)rv) = sentinel.ai_next;
   2391 	if (sentinel.ai_next == NULL)
   2392 		return NS_NOTFOUND;
   2393 	return NS_SUCCESS;
   2394 }
   2395 
   2396 #ifdef YP
   2397 /*ARGSUSED*/
   2398 static struct addrinfo *
   2399 _yphostent(char *line, const struct addrinfo *pai)
   2400 {
   2401 	struct addrinfo sentinel, *cur;
   2402 	struct addrinfo hints, *res, *res0;
   2403 	int error;
   2404 	char *p;
   2405 	const char *addr, *canonname;
   2406 	char *nextline;
   2407 	char *cp;
   2408 
   2409 	_DIAGASSERT(line != NULL);
   2410 	_DIAGASSERT(pai != NULL);
   2411 
   2412 	p = line;
   2413 	addr = canonname = NULL;
   2414 
   2415 	memset(&sentinel, 0, sizeof(sentinel));
   2416 	cur = &sentinel;
   2417 
   2418 nextline:
   2419 	/* terminate line */
   2420 	cp = strchr(p, '\n');
   2421 	if (cp) {
   2422 		*cp++ = '\0';
   2423 		nextline = cp;
   2424 	} else
   2425 		nextline = NULL;
   2426 
   2427 	cp = strpbrk(p, " \t");
   2428 	if (cp == NULL) {
   2429 		if (canonname == NULL)
   2430 			return NULL;
   2431 		else
   2432 			goto done;
   2433 	}
   2434 	*cp++ = '\0';
   2435 
   2436 	addr = p;
   2437 
   2438 	while (cp && *cp) {
   2439 		if (*cp == ' ' || *cp == '\t') {
   2440 			cp++;
   2441 			continue;
   2442 		}
   2443 		if (!canonname)
   2444 			canonname = cp;
   2445 		if ((cp = strpbrk(cp, " \t")) != NULL)
   2446 			*cp++ = '\0';
   2447 	}
   2448 
   2449 	hints = *pai;
   2450 	hints.ai_flags = AI_NUMERICHOST;
   2451 	error = getaddrinfo(addr, NULL, &hints, &res0);
   2452 	if (error == 0) {
   2453 		for (res = res0; res; res = res->ai_next) {
   2454 			/* cover it up */
   2455 			res->ai_flags = pai->ai_flags;
   2456 
   2457 			if (pai->ai_flags & AI_CANONNAME)
   2458 				(void)get_canonname(pai, res, canonname);
   2459 		}
   2460 	} else
   2461 		res0 = NULL;
   2462 	if (res0) {
   2463 		cur->ai_next = res0;
   2464 		while (cur->ai_next)
   2465 			cur = cur->ai_next;
   2466 	}
   2467 
   2468 	if (nextline) {
   2469 		p = nextline;
   2470 		goto nextline;
   2471 	}
   2472 
   2473 done:
   2474 	return sentinel.ai_next;
   2475 }
   2476 
   2477 /*ARGSUSED*/
   2478 static int
   2479 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2480 {
   2481 	struct addrinfo sentinel, *cur;
   2482 	struct addrinfo *ai = NULL;
   2483 	char *ypbuf;
   2484 	int ypbuflen, r;
   2485 	const char *name;
   2486 	const struct addrinfo *pai;
   2487 	char *ypdomain;
   2488 
   2489 	if (_yp_check(&ypdomain) == 0)
   2490 		return NS_UNAVAIL;
   2491 
   2492 	name = va_arg(ap, char *);
   2493 	pai = va_arg(ap, const struct addrinfo *);
   2494 
   2495 	memset(&sentinel, 0, sizeof(sentinel));
   2496 	cur = &sentinel;
   2497 
   2498 	/* hosts.byname is only for IPv4 (Solaris8) */
   2499 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
   2500 		r = yp_match(ypdomain, "hosts.byname", name,
   2501 			(int)strlen(name), &ypbuf, &ypbuflen);
   2502 		if (r == 0) {
   2503 			struct addrinfo ai4;
   2504 
   2505 			ai4 = *pai;
   2506 			ai4.ai_family = AF_INET;
   2507 			ai = _yphostent(ypbuf, &ai4);
   2508 			if (ai) {
   2509 				cur->ai_next = ai;
   2510 				while (cur && cur->ai_next)
   2511 					cur = cur->ai_next;
   2512 			}
   2513 		}
   2514 		free(ypbuf);
   2515 	}
   2516 
   2517 	/* ipnodes.byname can hold both IPv4/v6 */
   2518 	r = yp_match(ypdomain, "ipnodes.byname", name,
   2519 		(int)strlen(name), &ypbuf, &ypbuflen);
   2520 	if (r == 0) {
   2521 		ai = _yphostent(ypbuf, pai);
   2522 		if (ai)
   2523 			cur->ai_next = ai;
   2524 		free(ypbuf);
   2525 	}
   2526 
   2527 	if (sentinel.ai_next == NULL) {
   2528 		h_errno = HOST_NOT_FOUND;
   2529 		return NS_NOTFOUND;
   2530 	}
   2531 	*((struct addrinfo **)rv) = sentinel.ai_next;
   2532 	return NS_SUCCESS;
   2533 }
   2534 #endif
   2535 
   2536 /* resolver logic */
   2537 
   2538 /*
   2539  * Formulate a normal query, send, and await answer.
   2540  * Returned answer is placed in supplied buffer "answer".
   2541  * Perform preliminary check of answer, returning success only
   2542  * if no error is indicated and the answer count is nonzero.
   2543  * Return the size of the response on success, -1 on error.
   2544  * Error number is left in h_errno.
   2545  *
   2546  * Caller must parse answer and determine whether it answers the question.
   2547  */
   2548 static int
   2549 res_queryN(const char *name, /* domain name */ struct res_target *target,
   2550     res_state statp)
   2551 {
   2552 	u_char buf[MAXPACKET];
   2553 	HEADER *hp;
   2554 	int n;
   2555 	struct res_target *t;
   2556 	int rcode;
   2557 	u_char *rdata;
   2558 	int ancount;
   2559 
   2560 	_DIAGASSERT(name != NULL);
   2561 	/* XXX: target may be NULL??? */
   2562 
   2563 	rcode = NOERROR;
   2564 	ancount = 0;
   2565 
   2566 	for (t = target; t; t = t->next) {
   2567 		int class, type;
   2568 		u_char *answer;
   2569 		int anslen;
   2570 		u_int oflags;
   2571 
   2572 		hp = (HEADER *)(void *)t->answer;
   2573 		oflags = statp->_flags;
   2574 
   2575 again:
   2576 		hp->rcode = NOERROR;	/* default */
   2577 
   2578 		/* make it easier... */
   2579 		class = t->qclass;
   2580 		type = t->qtype;
   2581 		answer = t->answer;
   2582 		anslen = t->anslen;
   2583 #ifdef DEBUG
   2584 		if (statp->options & RES_DEBUG)
   2585 			printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
   2586 #endif
   2587 
   2588 		n = res_nmkquery(statp, QUERY, name, class, type, NULL, 0, NULL,
   2589 		    buf, (int)sizeof(buf));
   2590 #ifdef RES_USE_EDNS0
   2591 		if (n > 0 && (statp->_flags & RES_F_EDNS0ERR) == 0 &&
   2592 		    (statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0) {
   2593 			n = res_nopt(statp, n, buf, (int)sizeof(buf), anslen);
   2594 			rdata = &buf[n];
   2595 			if (n > 0 && (statp->options & RES_NSID) != 0U) {
   2596 				n = res_nopt_rdata(statp, n, buf,
   2597 				    (int)sizeof(buf),
   2598 				    rdata, NS_OPT_NSID, 0, NULL);
   2599 			}
   2600 		}
   2601 #endif
   2602 		if (n <= 0) {
   2603 #ifdef DEBUG
   2604 			if (statp->options & RES_DEBUG)
   2605 				printf(";; res_nquery: mkquery failed\n");
   2606 #endif
   2607 			h_errno = NO_RECOVERY;
   2608 			return n;
   2609 		}
   2610 		n = res_nsend(statp, buf, n, answer, anslen);
   2611 		if (n < 0) {
   2612 #ifdef RES_USE_EDNS0
   2613 			/* if the query choked with EDNS0, retry without EDNS0 */
   2614 			if ((statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U &&
   2615 			    ((oflags ^ statp->_flags) & RES_F_EDNS0ERR) != 0) {
   2616 				statp->_flags |= RES_F_EDNS0ERR;
   2617 				if (statp->options & RES_DEBUG)
   2618 					printf(";; res_nquery: retry without EDNS0\n");
   2619 				goto again;
   2620 			}
   2621 #endif
   2622 #if 0
   2623 #ifdef DEBUG
   2624 			if (statp->options & RES_DEBUG)
   2625 				printf(";; res_query: send error\n");
   2626 #endif
   2627 			h_errno = TRY_AGAIN;
   2628 			return n;
   2629 #endif
   2630 		}
   2631 
   2632 		if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
   2633 			rcode = hp->rcode;	/* record most recent error */
   2634 #ifdef DEBUG
   2635 			if (statp->options & RES_DEBUG)
   2636 				printf(";; rcode = (%s), counts = an:%d ns:%d ar:%d\n",
   2637 				       p_rcode(hp->rcode),
   2638 				       ntohs(hp->ancount),
   2639 				       ntohs(hp->nscount),
   2640 				       ntohs(hp->arcount));
   2641 #endif
   2642 			continue;
   2643 		}
   2644 
   2645 		ancount += ntohs(hp->ancount);
   2646 
   2647 		t->n = n;
   2648 	}
   2649 
   2650 	if (ancount == 0) {
   2651 		switch (rcode) {
   2652 		case NXDOMAIN:
   2653 			h_errno = HOST_NOT_FOUND;
   2654 			break;
   2655 		case SERVFAIL:
   2656 			h_errno = TRY_AGAIN;
   2657 			break;
   2658 		case NOERROR:
   2659 			h_errno = NO_DATA;
   2660 			break;
   2661 		case FORMERR:
   2662 		case NOTIMP:
   2663 		case REFUSED:
   2664 		default:
   2665 			h_errno = NO_RECOVERY;
   2666 			break;
   2667 		}
   2668 		return -1;
   2669 	}
   2670 	return ancount;
   2671 }
   2672 
   2673 /*
   2674  * Formulate a normal query, send, and retrieve answer in supplied buffer.
   2675  * Return the size of the response on success, -1 on error.
   2676  * If enabled, implement search rules until answer or unrecoverable failure
   2677  * is detected.	 Error code, if any, is left in h_errno.
   2678  */
   2679 static int
   2680 res_searchN(const char *name, struct res_target *target, res_state res)
   2681 {
   2682 	const char *cp, * const *domain;
   2683 	HEADER *hp;
   2684 	u_int dots;
   2685 	char buf[MAXHOSTNAMELEN];
   2686 	int trailing_dot, ret, saved_herrno;
   2687 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
   2688 
   2689 	_DIAGASSERT(name != NULL);
   2690 	_DIAGASSERT(target != NULL);
   2691 
   2692 	hp = (HEADER *)(void *)target->answer;	/*XXX*/
   2693 
   2694 	errno = 0;
   2695 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
   2696 	dots = 0;
   2697 	for (cp = name; *cp; cp++)
   2698 		dots += (*cp == '.');
   2699 	trailing_dot = 0;
   2700 	if (cp > name && *--cp == '.')
   2701 		trailing_dot++;
   2702 
   2703 	/*
   2704 	 * if there aren't any dots, it could be a user-level alias
   2705 	 */
   2706 	if (!dots && (cp = res_hostalias(res, name, buf, sizeof(buf))) != NULL) {
   2707 		ret = res_queryN(cp, target, res);
   2708 		return ret;
   2709 	}
   2710 
   2711 	/*
   2712 	 * If there are dots in the name already, let's just give it a try
   2713 	 * 'as is'.  The threshold can be set with the "ndots" option.
   2714 	 */
   2715 	saved_herrno = -1;
   2716 	if (dots >= res->ndots) {
   2717 		ret = res_querydomainN(name, NULL, target, res);
   2718 		if (ret > 0)
   2719 			return ret;
   2720 		saved_herrno = h_errno;
   2721 		tried_as_is++;
   2722 	}
   2723 
   2724 	/*
   2725 	 * We do at least one level of search if
   2726 	 *	- there is no dot and RES_DEFNAME is set, or
   2727 	 *	- there is at least one dot, there is no trailing dot,
   2728 	 *	  and RES_DNSRCH is set.
   2729 	 */
   2730 	if ((!dots && (res->options & RES_DEFNAMES)) ||
   2731 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
   2732 		int done = 0;
   2733 
   2734 		for (domain = (const char * const *)res->dnsrch;
   2735 		   *domain && !done;
   2736 		   domain++) {
   2737 
   2738 			ret = res_querydomainN(name, *domain, target, res);
   2739 			if (ret > 0)
   2740 				return ret;
   2741 
   2742 			/*
   2743 			 * If no server present, give up.
   2744 			 * If name isn't found in this domain,
   2745 			 * keep trying higher domains in the search list
   2746 			 * (if that's enabled).
   2747 			 * On a NO_DATA error, keep trying, otherwise
   2748 			 * a wildcard entry of another type could keep us
   2749 			 * from finding this entry higher in the domain.
   2750 			 * If we get some other error (negative answer or
   2751 			 * server failure), then stop searching up,
   2752 			 * but try the input name below in case it's
   2753 			 * fully-qualified.
   2754 			 */
   2755 			if (errno == ECONNREFUSED) {
   2756 				h_errno = TRY_AGAIN;
   2757 				return -1;
   2758 			}
   2759 
   2760 			switch (h_errno) {
   2761 			case NO_DATA:
   2762 				got_nodata++;
   2763 				/* FALLTHROUGH */
   2764 			case HOST_NOT_FOUND:
   2765 				/* keep trying */
   2766 				break;
   2767 			case TRY_AGAIN:
   2768 				if (hp->rcode == SERVFAIL) {
   2769 					/* try next search element, if any */
   2770 					got_servfail++;
   2771 					break;
   2772 				}
   2773 				/* FALLTHROUGH */
   2774 			default:
   2775 				/* anything else implies that we're done */
   2776 				done++;
   2777 			}
   2778 			/*
   2779 			 * if we got here for some reason other than DNSRCH,
   2780 			 * we only wanted one iteration of the loop, so stop.
   2781 			 */
   2782 			if (!(res->options & RES_DNSRCH))
   2783 				done++;
   2784 		}
   2785 	}
   2786 
   2787 	/*
   2788 	 * if we have not already tried the name "as is", do that now.
   2789 	 * note that we do this regardless of how many dots were in the
   2790 	 * name or whether it ends with a dot.
   2791 	 */
   2792 	if (!tried_as_is) {
   2793 		ret = res_querydomainN(name, NULL, target, res);
   2794 		if (ret > 0)
   2795 			return ret;
   2796 	}
   2797 
   2798 	/*
   2799 	 * if we got here, we didn't satisfy the search.
   2800 	 * if we did an initial full query, return that query's h_errno
   2801 	 * (note that we wouldn't be here if that query had succeeded).
   2802 	 * else if we ever got a nodata, send that back as the reason.
   2803 	 * else send back meaningless h_errno, that being the one from
   2804 	 * the last DNSRCH we did.
   2805 	 */
   2806 	if (saved_herrno != -1)
   2807 		h_errno = saved_herrno;
   2808 	else if (got_nodata)
   2809 		h_errno = NO_DATA;
   2810 	else if (got_servfail)
   2811 		h_errno = TRY_AGAIN;
   2812 	return -1;
   2813 }
   2814 
   2815 /*
   2816  * Perform a call on res_query on the concatenation of name and domain,
   2817  * removing a trailing dot from name if domain is NULL.
   2818  */
   2819 static int
   2820 res_querydomainN(const char *name, const char *domain,
   2821     struct res_target *target, res_state res)
   2822 {
   2823 	char nbuf[MAXDNAME];
   2824 	const char *longname = nbuf;
   2825 	size_t n;
   2826 
   2827 	_DIAGASSERT(name != NULL);
   2828 	/* XXX: target may be NULL??? */
   2829 
   2830 #ifdef DEBUG
   2831 	if (res->options & RES_DEBUG)
   2832 		printf(";; res_querydomain(%s, %s)\n",
   2833 			name, domain?domain:"<Nil>");
   2834 #endif
   2835 	if (domain == NULL) {
   2836 		/*
   2837 		 * Check for trailing '.';
   2838 		 * copy without '.' if present.
   2839 		 */
   2840 		n = strlen(name);
   2841 		if (n + 1 > sizeof(nbuf)) {
   2842 			h_errno = NO_RECOVERY;
   2843 			return -1;
   2844 		}
   2845 		if (n > 0 && name[--n] == '.') {
   2846 			snprintf(nbuf, sizeof(nbuf), "%*s", (int)n, name);
   2847 		} else
   2848 			longname = name;
   2849 	} else {
   2850 		if ((size_t)snprintf(nbuf, sizeof(nbuf), "%s.%s",
   2851 				name, domain) >= sizeof(nbuf)) {
   2852 			h_errno = NO_RECOVERY;
   2853 			return -1;
   2854 		}
   2855 	}
   2856 	return res_queryN(longname, target, res);
   2857 }
   2858 
   2859 #ifdef TEST
   2860 int
   2861 main(int argc, char *argv[]) {
   2862 	struct addrinfo *ai, *sai;
   2863 	int i, e;
   2864 	char buf[1024];
   2865 
   2866 	for (i = 1; i < argc; i++) {
   2867 		if ((e = getaddrinfo(argv[i], NULL, NULL, &sai)) != 0)
   2868 			warnx("%s: %s", argv[i], gai_strerror(e));
   2869 		for (ai = sai; ai; ai = ai->ai_next) {
   2870 			sockaddr_snprintf(buf, sizeof(buf), "%a", ai->ai_addr);
   2871              		printf("flags=0x%x family=%d socktype=%d protocol=%d "
   2872 			    "addrlen=%zu addr=%s canonname=%s next=%p\n",
   2873 			    ai->ai_flags,
   2874              		    ai->ai_family,
   2875              		    ai->ai_socktype,
   2876              		    ai->ai_protocol,
   2877              		    (size_t)ai->ai_addrlen,
   2878 			    buf,
   2879 			    ai->ai_canonname,
   2880 			    ai->ai_next);
   2881 		}
   2882 		if (sai)
   2883 			freeaddrinfo(sai);
   2884 	}
   2885 	return 0;
   2886 }
   2887 #endif
   2888