Home | History | Annotate | Line # | Download | only in net
      1 /*	$NetBSD: getaddrinfo.c,v 1.128 2026/02/12 16:26:54 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.128 2026/02/12 16:26:54 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 	uint32_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(const char *, struct sockaddr_in6 *, uint32_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 	__USE(head);
    793 	return 0;
    794 #endif
    795 }
    796 
    797 static void
    798 free_addrselectpolicy(struct policyhead *head)
    799 {
    800 	struct policyqueue *ent, *nent;
    801 
    802 	for (ent = TAILQ_FIRST(head); ent; ent = nent) {
    803 		nent = TAILQ_NEXT(ent, pc_entry);
    804 		TAILQ_REMOVE(head, ent, pc_entry);
    805 		free(ent);
    806 	}
    807 }
    808 
    809 static struct policyqueue *
    810 match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head)
    811 {
    812 #ifdef INET6
    813 	struct policyqueue *ent, *bestent = NULL;
    814 	struct in6_addrpolicy *pol;
    815 	int curmatchlen, bestmatchlen = -1;
    816 	u_char *mp, *ep, *k, *p;
    817 	u_int m;
    818 	struct sockaddr_in6 key;
    819 
    820 	switch(addr->sa_family) {
    821 	case AF_INET6:
    822 		memcpy(&key, addr, sizeof(key));
    823 		break;
    824 	case AF_INET:
    825 		/* convert the address into IPv4-mapped IPv6 address. */
    826 		memset(&key, 0, sizeof(key));
    827 		key.sin6_family = AF_INET6;
    828 		key.sin6_len = sizeof(key);
    829 		key.sin6_addr.s6_addr[10] = 0xff;
    830 		key.sin6_addr.s6_addr[11] = 0xff;
    831 		memcpy(&key.sin6_addr.s6_addr[12], sa4addr(addr), 4);
    832 		break;
    833 	default:
    834 		return NULL;
    835 	}
    836 
    837 	for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
    838 		pol = &ent->pc_policy;
    839 		curmatchlen = 0;
    840 
    841 		mp = (void *)&pol->addrmask.sin6_addr;
    842 		ep = mp + 16;	/* XXX: scope field? */
    843 		k = (void *)&key.sin6_addr;
    844 		p = (void *)&pol->addr.sin6_addr;
    845 		for (; mp < ep && *mp; mp++, k++, p++) {
    846 			m = *mp;
    847 			if ((*k & m) != *p)
    848 				goto next; /* not match */
    849 			if (m == 0xff) /* short cut for a typical case */
    850 				curmatchlen += 8;
    851 			else {
    852 				while (m >= 0x80) {
    853 					curmatchlen++;
    854 					m <<= 1;
    855 				}
    856 			}
    857 		}
    858 
    859 		/* matched.  check if this is better than the current best. */
    860 		if (curmatchlen > bestmatchlen) {
    861 			bestent = ent;
    862 			bestmatchlen = curmatchlen;
    863 		}
    864 
    865 	  next:
    866 		continue;
    867 	}
    868 
    869 	return bestent;
    870 #else
    871 	__USE(addr);
    872 	__USE(head);
    873 	return NULL;
    874 #endif
    875 
    876 }
    877 
    878 static void
    879 set_source(struct ai_order *aio, struct policyhead *ph,
    880     struct servent_data *svd)
    881 {
    882 	struct addrinfo ai = *aio->aio_ai;
    883 	struct sockaddr_storage ss;
    884 	socklen_t srclen;
    885 	int s;
    886 
    887 	/* set unspec ("no source is available"), just in case */
    888 	aio->aio_srcsa.sa_family = AF_UNSPEC;
    889 	aio->aio_srcscope = -1;
    890 
    891 	switch(ai.ai_family) {
    892 	case AF_INET:
    893 #ifdef INET6
    894 	case AF_INET6:
    895 #endif
    896 		break;
    897 	default:		/* ignore unsupported AFs explicitly */
    898 		return;
    899 	}
    900 
    901 	/* XXX: make a dummy addrinfo to call connect() */
    902 	ai.ai_socktype = SOCK_DGRAM;
    903 	ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
    904 	ai.ai_next = NULL;
    905 	memset(&ss, 0, sizeof(ss));
    906 	memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
    907 	ai.ai_addr = (void *)&ss;
    908 	get_port(&ai, "1", 0, svd);
    909 
    910 	/* open a socket to get the source address for the given dst */
    911 	if ((s = socket(ai.ai_family, ai.ai_socktype | SOCK_CLOEXEC,
    912 	    ai.ai_protocol)) < 0)
    913 		return;		/* give up */
    914 	if (connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
    915 		goto cleanup;
    916 	srclen = ai.ai_addrlen;
    917 	if (getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
    918 		aio->aio_srcsa.sa_family = AF_UNSPEC;
    919 		goto cleanup;
    920 	}
    921 	aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
    922 	aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
    923 	aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
    924 #ifdef INET6
    925 	if (ai.ai_family == AF_INET6) {
    926 		struct in6_ifreq ifr6;
    927 		uint32_t flags6;
    928 
    929 		memset(&ifr6, 0, sizeof(ifr6));
    930 		memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
    931 		if (ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
    932 			flags6 = ifr6.ifr_ifru.ifru_flags6;
    933 			if ((flags6 & IN6_IFF_DEPRECATED))
    934 				aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
    935 		}
    936 	}
    937 #endif
    938 
    939   cleanup:
    940 	close(s);
    941 	return;
    942 }
    943 
    944 static int
    945 matchlen(struct sockaddr *src, struct sockaddr *dst)
    946 {
    947 	int match = 0;
    948 	u_char *s, *d;
    949 	u_char *lim;
    950 	u_int r, addrlen;
    951 
    952 	switch (src->sa_family) {
    953 #ifdef INET6
    954 	case AF_INET6:
    955 		s = sa6addr(src);
    956 		d = sa6addr(dst);
    957 		addrlen = sizeof(struct in6_addr);
    958 		lim = s + addrlen;
    959 		break;
    960 #endif
    961 	case AF_INET:
    962 		s = sa4addr(src);
    963 		d = sa4addr(dst);
    964 		addrlen = sizeof(struct in_addr);
    965 		lim = s + addrlen;
    966 		break;
    967 	default:
    968 		return 0;
    969 	}
    970 
    971 	while (s < lim)
    972 		if ((r = (*d++ ^ *s++)) != 0) {
    973 			while (r < addrlen * 8) {
    974 				match++;
    975 				r <<= 1;
    976 			}
    977 			break;
    978 		} else
    979 			match += 8;
    980 	return match;
    981 }
    982 
    983 static int
    984 comp_dst(const void *arg1, const void *arg2)
    985 {
    986 	const struct ai_order *dst1 = arg1, *dst2 = arg2;
    987 
    988 	/*
    989 	 * Rule 1: Avoid unusable destinations.
    990 	 * XXX: we currently do not consider if an appropriate route exists.
    991 	 */
    992 	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
    993 	    dst2->aio_srcsa.sa_family == AF_UNSPEC) {
    994 		return -1;
    995 	}
    996 	if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
    997 	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
    998 		return 1;
    999 	}
   1000 
   1001 	/* Rule 2: Prefer matching scope. */
   1002 	if (dst1->aio_dstscope == dst1->aio_srcscope &&
   1003 	    dst2->aio_dstscope != dst2->aio_srcscope) {
   1004 		return -1;
   1005 	}
   1006 	if (dst1->aio_dstscope != dst1->aio_srcscope &&
   1007 	    dst2->aio_dstscope == dst2->aio_srcscope) {
   1008 		return 1;
   1009 	}
   1010 
   1011 	/* Rule 3: Avoid deprecated addresses. */
   1012 	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
   1013 	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
   1014 		if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
   1015 		    (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
   1016 			return -1;
   1017 		}
   1018 		if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
   1019 		    !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
   1020 			return 1;
   1021 		}
   1022 	}
   1023 
   1024 	/* Rule 4: Prefer home addresses. */
   1025 	/* XXX: not implemented yet */
   1026 
   1027 	/* Rule 5: Prefer matching label. */
   1028 #ifdef INET6
   1029 	if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
   1030 	    dst1->aio_srcpolicy->pc_policy.label ==
   1031 	    dst1->aio_dstpolicy->pc_policy.label &&
   1032 	    (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
   1033 	     dst2->aio_srcpolicy->pc_policy.label !=
   1034 	     dst2->aio_dstpolicy->pc_policy.label)) {
   1035 		return -1;
   1036 	}
   1037 	if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
   1038 	    dst2->aio_srcpolicy->pc_policy.label ==
   1039 	    dst2->aio_dstpolicy->pc_policy.label &&
   1040 	    (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
   1041 	     dst1->aio_srcpolicy->pc_policy.label !=
   1042 	     dst1->aio_dstpolicy->pc_policy.label)) {
   1043 		return 1;
   1044 	}
   1045 #endif
   1046 
   1047 	/* Rule 6: Prefer higher precedence. */
   1048 #ifdef INET6
   1049 	if (dst1->aio_dstpolicy &&
   1050 	    (dst2->aio_dstpolicy == NULL ||
   1051 	     dst1->aio_dstpolicy->pc_policy.preced >
   1052 	     dst2->aio_dstpolicy->pc_policy.preced)) {
   1053 		return -1;
   1054 	}
   1055 	if (dst2->aio_dstpolicy &&
   1056 	    (dst1->aio_dstpolicy == NULL ||
   1057 	     dst2->aio_dstpolicy->pc_policy.preced >
   1058 	     dst1->aio_dstpolicy->pc_policy.preced)) {
   1059 		return 1;
   1060 	}
   1061 #endif
   1062 
   1063 	/* Rule 7: Prefer native transport. */
   1064 	/* XXX: not implemented yet */
   1065 
   1066 	/* Rule 8: Prefer smaller scope. */
   1067 	if (dst1->aio_dstscope >= 0 &&
   1068 	    dst1->aio_dstscope < dst2->aio_dstscope) {
   1069 		return -1;
   1070 	}
   1071 	if (dst2->aio_dstscope >= 0 &&
   1072 	    dst2->aio_dstscope < dst1->aio_dstscope) {
   1073 		return 1;
   1074 	}
   1075 
   1076 	/*
   1077 	 * Rule 9: Use longest matching prefix.
   1078 	 * We compare the match length in a same AF only.
   1079 	 */
   1080 	if (dst1->aio_ai->ai_addr->sa_family ==
   1081 	    dst2->aio_ai->ai_addr->sa_family &&
   1082 	    dst1->aio_ai->ai_addr->sa_family != AF_INET) {
   1083 		if (dst1->aio_matchlen > dst2->aio_matchlen) {
   1084 			return -1;
   1085 		}
   1086 		if (dst1->aio_matchlen < dst2->aio_matchlen) {
   1087 			return 1;
   1088 		}
   1089 	}
   1090 
   1091 	/* Rule 10: Otherwise, leave the order unchanged. */
   1092 	return -1;
   1093 }
   1094 
   1095 /*
   1096  * Copy from scope.c.
   1097  * XXX: we should standardize the functions and link them as standard
   1098  * library.
   1099  */
   1100 static int
   1101 gai_addr2scopetype(struct sockaddr *sa)
   1102 {
   1103 #ifdef INET6
   1104 	struct sockaddr_in6 *sa6;
   1105 #endif
   1106 	struct sockaddr_in *sa4;
   1107 	u_char *p;
   1108 
   1109 	switch(sa->sa_family) {
   1110 #ifdef INET6
   1111 	case AF_INET6:
   1112 		sa6 = (void *)sa;
   1113 		if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
   1114 			/* just use the scope field of the multicast address */
   1115 			return sa6->sin6_addr.s6_addr[2] & 0x0f;
   1116 		}
   1117 		/*
   1118 		 * Unicast addresses: map scope type to corresponding scope
   1119 		 * value defined for multcast addresses.
   1120 		 * XXX: hardcoded scope type values are bad...
   1121 		 */
   1122 		if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
   1123 			return 1; /* node local scope */
   1124 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
   1125 			return 2; /* link-local scope */
   1126 		if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
   1127 			return 5; /* site-local scope */
   1128 		return 14;	/* global scope */
   1129 #endif
   1130 	case AF_INET:
   1131 		/*
   1132 		 * IPv4 pseudo scoping according to RFC 3484.
   1133 		 */
   1134 		sa4 = (void *)sa;
   1135 		p = (u_char *)(void *)&sa4->sin_addr;
   1136 		/* IPv4 autoconfiguration addresses have link-local scope. */
   1137 		if (p[0] == 169 && p[1] == 254)
   1138 			return 2;
   1139 		/* Private addresses have site-local scope. */
   1140 		if (p[0] == 10 ||
   1141 		    (p[0] == 172 && (p[1] & 0xf0) == 16) ||
   1142 		    (p[0] == 192 && p[1] == 168))
   1143 			return 14;	/* XXX: It should be 5 unless NAT */
   1144 		/* Loopback addresses have link-local scope. */
   1145 		if (p[0] == 127)
   1146 			return 2;
   1147 		return 14;
   1148 	default:
   1149 		errno = EAFNOSUPPORT; /* is this a good error? */
   1150 		return -1;
   1151 	}
   1152 }
   1153 
   1154 /*
   1155  * FQDN hostname, DNS lookup
   1156  */
   1157 static int
   1158 explore_fqdn(const struct addrinfo *pai, const char *hostname,
   1159     const char *servname, struct addrinfo **res, struct servent_data *svd)
   1160 {
   1161 	struct addrinfo *result;
   1162 	struct addrinfo *cur;
   1163 	int error = 0;
   1164 	static const ns_dtab dtab[] = {
   1165 		NS_FILES_CB(_files_getaddrinfo, NULL)
   1166 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
   1167 		NS_NIS_CB(_yp_getaddrinfo, NULL)
   1168 		NS_NULL_CB
   1169 	};
   1170 
   1171 	_DIAGASSERT(pai != NULL);
   1172 	/* hostname may be NULL */
   1173 	/* servname may be NULL */
   1174 	_DIAGASSERT(res != NULL);
   1175 
   1176 	result = NULL;
   1177 
   1178 	/*
   1179 	 * if the servname does not match socktype/protocol, ignore it.
   1180 	 */
   1181 	if (get_portmatch(pai, servname, svd) != 0)
   1182 		return 0;
   1183 
   1184 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
   1185 	    default_dns_files, hostname, pai, servname)) {
   1186 	case NS_TRYAGAIN:
   1187 		error = EAI_AGAIN;
   1188 		goto free;
   1189 	case NS_UNAVAIL:
   1190 		error = EAI_FAIL;
   1191 		goto free;
   1192 	case NS_NOTFOUND:
   1193 		error = EAI_NODATA;
   1194 		goto free;
   1195 	case NS_SUCCESS:
   1196 		error = 0;
   1197 		for (cur = result; cur; cur = cur->ai_next) {
   1198 			/* Check for already filled port. */
   1199 			if (*getport(cur))
   1200 				continue;
   1201 			GET_PORT(cur, servname, svd);
   1202 			/* canonname should be filled already */
   1203 		}
   1204 		break;
   1205 	}
   1206 
   1207 	*res = result;
   1208 
   1209 	return 0;
   1210 
   1211 free:
   1212 	if (result)
   1213 		freeaddrinfo(result);
   1214 	return error;
   1215 }
   1216 
   1217 /*
   1218  * hostname == NULL.
   1219  * passive socket -> anyaddr (0.0.0.0 or ::)
   1220  * non-passive socket -> localhost (127.0.0.1 or ::1)
   1221  */
   1222 static int
   1223 explore_null(const struct addrinfo *pai, const char *servname,
   1224     struct addrinfo **res, struct servent_data *svd)
   1225 {
   1226 	int s;
   1227 	const struct afd *afd;
   1228 	struct addrinfo *cur;
   1229 	struct addrinfo sentinel;
   1230 	int error;
   1231 
   1232 	_DIAGASSERT(pai != NULL);
   1233 	/* servname may be NULL */
   1234 	_DIAGASSERT(res != NULL);
   1235 
   1236 	*res = NULL;
   1237 	sentinel.ai_next = NULL;
   1238 	cur = &sentinel;
   1239 
   1240 	/*
   1241 	 * filter out AFs that are not supported by the kernel
   1242 	 * XXX errno?
   1243 	 */
   1244 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
   1245 	if (s < 0) {
   1246 		if (errno != EMFILE)
   1247 			return 0;
   1248 	} else
   1249 		close(s);
   1250 
   1251 	/*
   1252 	 * if the servname does not match socktype/protocol, ignore it.
   1253 	 */
   1254 	if (get_portmatch(pai, servname, svd) != 0)
   1255 		return 0;
   1256 
   1257 	afd = find_afd(pai->ai_family);
   1258 	if (afd == NULL)
   1259 		return 0;
   1260 
   1261 	if (pai->ai_flags & AI_PASSIVE) {
   1262 		GET_AI(cur->ai_next, afd, afd->a_addrany);
   1263 		/* xxx meaningless?
   1264 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
   1265 		 */
   1266 		GET_PORT(cur->ai_next, servname, svd);
   1267 	} else {
   1268 		GET_AI(cur->ai_next, afd, afd->a_loopback);
   1269 		/* xxx meaningless?
   1270 		 * GET_CANONNAME(cur->ai_next, "localhost");
   1271 		 */
   1272 		GET_PORT(cur->ai_next, servname, svd);
   1273 	}
   1274 	cur = cur->ai_next;
   1275 
   1276 	*res = sentinel.ai_next;
   1277 	return 0;
   1278 
   1279 free:
   1280 	if (sentinel.ai_next)
   1281 		freeaddrinfo(sentinel.ai_next);
   1282 	return error;
   1283 }
   1284 
   1285 /*
   1286  * numeric hostname
   1287  */
   1288 static int
   1289 explore_numeric(const struct addrinfo *pai, const char *hostname,
   1290     const char *servname, struct addrinfo **res, const char *canonname,
   1291     struct servent_data *svd)
   1292 {
   1293 	const struct afd *afd;
   1294 	struct addrinfo *cur;
   1295 	struct addrinfo sentinel;
   1296 	int error;
   1297 	char pton[PTON_MAX];
   1298 
   1299 	_DIAGASSERT(pai != NULL);
   1300 	/* hostname may be NULL */
   1301 	/* servname may be NULL */
   1302 	_DIAGASSERT(res != NULL);
   1303 
   1304 	*res = NULL;
   1305 	sentinel.ai_next = NULL;
   1306 	cur = &sentinel;
   1307 
   1308 	/*
   1309 	 * if the servname does not match socktype/protocol, ignore it.
   1310 	 */
   1311 	if (get_portmatch(pai, servname, svd) != 0)
   1312 		return 0;
   1313 
   1314 	afd = find_afd(pai->ai_family);
   1315 	if (afd == NULL)
   1316 		return 0;
   1317 
   1318 	switch (afd->a_af) {
   1319 	case AF_INET:
   1320 	       /*
   1321 		* RFC3493 section 6.1, requires getaddrinfo() to accept
   1322 		* AF_INET formats that are accepted by inet_addr(); here
   1323 		* we use the equivalent inet_aton() function so we can
   1324 		* check for errors. inet_pton() only accepts addresses
   1325 		* in the dotted quad format and only in base 10, so we
   1326 		* need to treat AF_INET specially.
   1327 		*
   1328 		* We also check for trailing characters and fail if there
   1329 		* are any. This matches the inet_pton6(), but not the
   1330 		* inet_pton4() behavior. We choose to make the protocol
   1331 		* behavior consistent.
   1332 		*/
   1333 		if (inet_aton(hostname, (void *)pton) == 1 &&
   1334 		    hostname[strspn(hostname, "0123456789.xabcdefXABCDEF")]
   1335 		    == '\0') {
   1336 			if (pai->ai_family == afd->a_af ||
   1337 			    pai->ai_family == PF_UNSPEC /*?*/) {
   1338 				GET_AI(cur->ai_next, afd, pton);
   1339 				GET_PORT(cur->ai_next, servname, svd);
   1340 				if ((pai->ai_flags & AI_CANONNAME)) {
   1341 					/*
   1342 					 * Set the numeric address itself as
   1343 					 * the canonical name, based on a
   1344 					 * clarification in rfc2553bis-03.
   1345 					 */
   1346 					GET_CANONNAME(cur->ai_next, canonname);
   1347 				}
   1348 				while (cur && cur->ai_next)
   1349 					cur = cur->ai_next;
   1350 			} else
   1351 				ERR(EAI_FAMILY);	/*xxx*/
   1352 		}
   1353 		break;
   1354 	default:
   1355 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
   1356 			if (pai->ai_family == afd->a_af ||
   1357 			    pai->ai_family == PF_UNSPEC /*?*/) {
   1358 				GET_AI(cur->ai_next, afd, pton);
   1359 				GET_PORT(cur->ai_next, servname, svd);
   1360 				if ((pai->ai_flags & AI_CANONNAME)) {
   1361 					/*
   1362 					 * Set the numeric address itself as
   1363 					 * the canonical name, based on a
   1364 					 * clarification in rfc2553bis-03.
   1365 					 */
   1366 					GET_CANONNAME(cur->ai_next, canonname);
   1367 				}
   1368 				while (cur->ai_next)
   1369 					cur = cur->ai_next;
   1370 			} else
   1371 				ERR(EAI_FAMILY);	/*xxx*/
   1372 		}
   1373 		break;
   1374 	}
   1375 
   1376 	*res = sentinel.ai_next;
   1377 	return 0;
   1378 
   1379 free:
   1380 bad:
   1381 	if (sentinel.ai_next)
   1382 		freeaddrinfo(sentinel.ai_next);
   1383 	return error;
   1384 }
   1385 
   1386 /*
   1387  * numeric hostname with scope
   1388  */
   1389 static int
   1390 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
   1391     const char *servname, struct addrinfo **res, struct servent_data *svd)
   1392 {
   1393 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
   1394 	return explore_numeric(pai, hostname, servname, res, hostname, svd);
   1395 #else
   1396 	const struct afd *afd;
   1397 	struct addrinfo *cur;
   1398 	int error;
   1399 	char *hostname2 = NULL, *addr;
   1400 	const char *cp, *scope;
   1401 	struct sockaddr_in6 *sin6;
   1402 
   1403 	_DIAGASSERT(pai != NULL);
   1404 	/* hostname may be NULL */
   1405 	/* servname may be NULL */
   1406 	_DIAGASSERT(res != NULL);
   1407 
   1408 	/*
   1409 	 * if the servname does not match socktype/protocol, ignore it.
   1410 	 */
   1411 	if (get_portmatch(pai, servname, svd) != 0)
   1412 		return 0;
   1413 
   1414 	afd = find_afd(pai->ai_family);
   1415 	if (afd == NULL)
   1416 		return 0;
   1417 
   1418 	if (!afd->a_scoped)
   1419 		return explore_numeric(pai, hostname, servname, res, hostname,
   1420 		    svd);
   1421 
   1422 	cp = strchr(hostname, SCOPE_DELIMITER);
   1423 	if (cp == NULL)
   1424 		return explore_numeric(pai, hostname, servname, res, hostname,
   1425 		    svd);
   1426 
   1427 	/*
   1428 	 * Handle special case of <scoped_address><delimiter><scope id>
   1429 	 */
   1430 	hostname2 = strdup(hostname);
   1431 	if (hostname2 == NULL)
   1432 		return EAI_MEMORY;
   1433 	/* terminate at the delimiter */
   1434 	hostname2[cp - hostname] = '\0';
   1435 	addr = hostname2;
   1436 	scope = cp + 1;
   1437 
   1438 	error = explore_numeric(pai, addr, servname, res, hostname, svd);
   1439 	if (error == 0) {
   1440 		uint32_t scopeid;
   1441 
   1442 		for (cur = *res; cur; cur = cur->ai_next) {
   1443 			if (cur->ai_family != AF_INET6)
   1444 				continue;
   1445 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
   1446 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
   1447 				free(hostname2);
   1448 				return EAI_NODATA; /* XXX: is return OK? */
   1449 			}
   1450 			sin6->sin6_scope_id = scopeid;
   1451 		}
   1452 	}
   1453 
   1454 	free(hostname2);
   1455 
   1456 	return error;
   1457 #endif
   1458 }
   1459 
   1460 static int
   1461 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
   1462 {
   1463 
   1464 	_DIAGASSERT(pai != NULL);
   1465 	_DIAGASSERT(ai != NULL);
   1466 	_DIAGASSERT(str != NULL);
   1467 
   1468 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
   1469 		ai->ai_canonname = strdup(str);
   1470 		if (ai->ai_canonname == NULL)
   1471 			return EAI_MEMORY;
   1472 	}
   1473 	return 0;
   1474 }
   1475 
   1476 struct addrinfo *
   1477 allocaddrinfo(socklen_t addrlen)
   1478 {
   1479 	struct addrinfo *ai;
   1480 
   1481 	ai = calloc(sizeof(struct addrinfo) + addrlen, 1);
   1482 	if (ai) {
   1483 		ai->ai_addr = (void *)(ai+1);
   1484 		ai->ai_addrlen = ai->ai_addr->sa_len = addrlen;
   1485 	}
   1486 
   1487 	return ai;
   1488 }
   1489 
   1490 static struct addrinfo *
   1491 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
   1492 {
   1493 	char *p;
   1494 	struct addrinfo *ai;
   1495 	struct sockaddr *save;
   1496 
   1497 	_DIAGASSERT(pai != NULL);
   1498 	_DIAGASSERT(afd != NULL);
   1499 	_DIAGASSERT(addr != NULL);
   1500 
   1501 	ai = allocaddrinfo((socklen_t)afd->a_socklen);
   1502 	if (ai == NULL)
   1503 		return NULL;
   1504 
   1505 	save = ai->ai_addr;
   1506 	memcpy(ai, pai, sizeof(struct addrinfo));
   1507 
   1508 	/* since we just overwrote all of ai, we have
   1509 	   to restore ai_addr and ai_addrlen */
   1510 	ai->ai_addr = save;
   1511 	ai->ai_addrlen = (socklen_t)afd->a_socklen;
   1512 
   1513 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
   1514 	p = (char *)(void *)(ai->ai_addr);
   1515 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
   1516 	return ai;
   1517 }
   1518 
   1519 static int
   1520 get_portmatch(const struct addrinfo *ai, const char *servname,
   1521     struct servent_data *svd)
   1522 {
   1523 
   1524 	_DIAGASSERT(ai != NULL);
   1525 	/* servname may be NULL */
   1526 
   1527 	return get_port(ai, servname, 1, svd);
   1528 }
   1529 
   1530 static int
   1531 get_port(const struct addrinfo *ai, const char *servname, int matchonly,
   1532     struct servent_data *svd)
   1533 {
   1534 	const char *proto;
   1535 	struct servent *sp;
   1536 	int port;
   1537 	int allownumeric;
   1538 
   1539 	_DIAGASSERT(ai != NULL);
   1540 	/* servname may be NULL */
   1541 
   1542 	if (servname == NULL)
   1543 		return 0;
   1544 	switch (ai->ai_family) {
   1545 	case AF_INET:
   1546 #ifdef AF_INET6
   1547 	case AF_INET6:
   1548 #endif
   1549 		break;
   1550 	default:
   1551 		return 0;
   1552 	}
   1553 
   1554 	switch (ai->ai_socktype) {
   1555 	case SOCK_RAW:
   1556 		return EAI_SERVICE;
   1557 	case SOCK_DGRAM:
   1558 	case SOCK_STREAM:
   1559 		allownumeric = 1;
   1560 		break;
   1561 	case ANY:
   1562 		/*
   1563 		 * This was 0.	It is now 1 so that queries specifying
   1564 		 * a NULL hint, or hint without socktype (but, hopefully,
   1565 		 * with protocol) and numeric address actually work.
   1566 		 */
   1567 		allownumeric = 1;
   1568 		break;
   1569 	default:
   1570 		return EAI_SOCKTYPE;
   1571 	}
   1572 
   1573 	port = str2number(servname);
   1574 	if (port >= 0) {
   1575 		if (!allownumeric)
   1576 			return EAI_SERVICE;
   1577 		if (port < 0 || port > 65535)
   1578 			return EAI_SERVICE;
   1579 		port = htons(port);
   1580 	} else {
   1581 		struct servent sv;
   1582 		if (ai->ai_flags & AI_NUMERICSERV)
   1583 			return EAI_NONAME;
   1584 
   1585 		switch (ai->ai_socktype) {
   1586 		case SOCK_DGRAM:
   1587 			proto = "udp";
   1588 			break;
   1589 		case SOCK_STREAM:
   1590 			proto = "tcp";
   1591 			break;
   1592 		default:
   1593 			proto = NULL;
   1594 			break;
   1595 		}
   1596 
   1597 		sp = getservbyname_r(servname, proto, &sv, svd);
   1598 		if (sp == NULL)
   1599 			return EAI_SERVICE;
   1600 		port = sp->s_port;
   1601 	}
   1602 
   1603 	if (!matchonly)
   1604 		*getport(__UNCONST(ai)) = port;
   1605 	return 0;
   1606 }
   1607 
   1608 static const struct afd *
   1609 find_afd(int af)
   1610 {
   1611 	const struct afd *afd;
   1612 
   1613 	if (af == PF_UNSPEC)
   1614 		return NULL;
   1615 	for (afd = afdl; afd->a_af; afd++) {
   1616 		if (afd->a_af == af)
   1617 			return afd;
   1618 	}
   1619 	return NULL;
   1620 }
   1621 
   1622 /*
   1623  * AI_ADDRCONFIG check: Build a mask containing a bit set for each address
   1624  * family configured in the system.
   1625  *
   1626  */
   1627 static int
   1628 addrconfig(uint64_t *mask)
   1629 {
   1630 	struct ifaddrs *ifaddrs, *ifa;
   1631 
   1632 	if (getifaddrs(&ifaddrs) == -1)
   1633 		return -1;
   1634 
   1635 	*mask = 0;
   1636 	for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next)
   1637 		if (ifa->ifa_addr && (ifa->ifa_flags & IFF_UP)) {
   1638 			_DIAGASSERT(ifa->ifa_addr->sa_family < 64);
   1639 			*mask |= (uint64_t)1 << ifa->ifa_addr->sa_family;
   1640 		}
   1641 
   1642 	freeifaddrs(ifaddrs);
   1643 	return 0;
   1644 }
   1645 
   1646 #ifdef INET6
   1647 /* convert a string to a scope identifier. XXX: IPv6 specific */
   1648 static int
   1649 ip6_str2scopeid(const char *scope, struct sockaddr_in6 *sin6, uint32_t *scopeid)
   1650 {
   1651 	u_long lscopeid;
   1652 	struct in6_addr *a6;
   1653 	char *ep;
   1654 
   1655 	_DIAGASSERT(scope != NULL);
   1656 	_DIAGASSERT(sin6 != NULL);
   1657 	_DIAGASSERT(scopeid != NULL);
   1658 
   1659 	a6 = &sin6->sin6_addr;
   1660 
   1661 	/* empty scopeid portion is invalid */
   1662 	if (*scope == '\0')
   1663 		return -1;
   1664 
   1665 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
   1666 		/*
   1667 		 * We currently assume a one-to-one mapping between links
   1668 		 * and interfaces, so we simply use interface indices for
   1669 		 * like-local scopes.
   1670 		 */
   1671 		*scopeid = if_nametoindex(scope);
   1672 		if (*scopeid == 0)
   1673 			goto trynumeric;
   1674 		return 0;
   1675 	}
   1676 
   1677 	/* still unclear about literal, allow numeric only - placeholder */
   1678 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
   1679 		goto trynumeric;
   1680 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
   1681 		goto trynumeric;
   1682 	else
   1683 		goto trynumeric;	/* global */
   1684 
   1685 	/* try to convert to a numeric id as a last resort */
   1686   trynumeric:
   1687 	errno = 0;
   1688 	lscopeid = strtoul(scope, &ep, 10);
   1689 	*scopeid = (uint32_t)(lscopeid & 0xffffffffUL);
   1690 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
   1691 		return 0;
   1692 	else
   1693 		return -1;
   1694 }
   1695 #endif
   1696 
   1697 /* code duplicate with gethnamaddr.c */
   1698 
   1699 static const char AskedForGot[] =
   1700 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
   1701 
   1702 #define maybe_ok(res, nm, ok) (((res)->options & RES_NOCHECKNAME) != 0U || \
   1703                                (ok)(nm) != 0)
   1704 static struct addrinfo *
   1705 getanswer(res_state res, const querybuf *answer, int anslen, const char *qname,
   1706     int qtype, const struct addrinfo *pai)
   1707 {
   1708 	struct addrinfo sentinel, *cur;
   1709 	struct addrinfo ai, *aip;
   1710 	const struct afd *afd;
   1711 	char *canonname;
   1712 	const HEADER *hp;
   1713 	const u_char *cp;
   1714 	int n;
   1715 	const u_char *eom;
   1716 	char *bp, *ep;
   1717 	int type, class, ancount, qdcount;
   1718 	int haveanswer, had_error;
   1719 	char tbuf[MAXDNAME];
   1720 	int (*name_ok) (const char *);
   1721 	char hostbuf[8*1024];
   1722 	int port, pri, weight;
   1723 	struct srvinfo *srvlist, *srv, *csrv;
   1724 
   1725 	_DIAGASSERT(answer != NULL);
   1726 	_DIAGASSERT(qname != NULL);
   1727 	_DIAGASSERT(pai != NULL);
   1728 	_DIAGASSERT(res != NULL);
   1729 
   1730 	memset(&sentinel, 0, sizeof(sentinel));
   1731 	cur = &sentinel;
   1732 
   1733 	canonname = NULL;
   1734 	eom = answer->buf + anslen;
   1735 	switch (qtype) {
   1736 	case T_A:
   1737 	case T_AAAA:
   1738 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
   1739 		name_ok = res_hnok;
   1740 		break;
   1741 	case T_SRV:
   1742 		name_ok = gai_srvok;
   1743 		break;
   1744 	default:
   1745 		return NULL;	/* XXX should be abort(); */
   1746 	}
   1747 	/*
   1748 	 * find first satisfactory answer
   1749 	 */
   1750 	hp = &answer->hdr;
   1751 	ancount = ntohs(hp->ancount);
   1752 	qdcount = ntohs(hp->qdcount);
   1753 	bp = hostbuf;
   1754 	ep = hostbuf + sizeof hostbuf;
   1755 	cp = answer->buf + HFIXEDSZ;
   1756 	if (qdcount != 1) {
   1757 		h_errno = NO_RECOVERY;
   1758 		return NULL;
   1759 	}
   1760 	n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
   1761 	if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
   1762 		h_errno = NO_RECOVERY;
   1763 		return NULL;
   1764 	}
   1765 	cp += n + QFIXEDSZ;
   1766 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
   1767 		/* res_send() has already verified that the query name is the
   1768 		 * same as the one we sent; this just gets the expanded name
   1769 		 * (i.e., with the succeeding search-domain tacked on).
   1770 		 */
   1771 		n = (int)strlen(bp) + 1;		/* for the \0 */
   1772 		if (n >= MAXHOSTNAMELEN) {
   1773 			h_errno = NO_RECOVERY;
   1774 			return NULL;
   1775 		}
   1776 		canonname = bp;
   1777 		bp += n;
   1778 		/* The qname can be abbreviated, but h_name is now absolute. */
   1779 		qname = canonname;
   1780 	}
   1781 	haveanswer = 0;
   1782 	had_error = 0;
   1783 	srvlist = NULL;
   1784 	while (ancount-- > 0 && cp < eom && !had_error) {
   1785 		n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
   1786 		if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
   1787 			had_error++;
   1788 			continue;
   1789 		}
   1790 		cp += n;			/* name */
   1791 		type = _getshort(cp);
   1792 		cp += INT16SZ;			/* type */
   1793 		class = _getshort(cp);
   1794 		cp += INT16SZ + INT32SZ;	/* class, TTL */
   1795 		n = _getshort(cp);
   1796 		cp += INT16SZ;			/* len */
   1797 		if (class != C_IN) {
   1798 			/* XXX - debug? syslog? */
   1799 			cp += n;
   1800 			continue;		/* XXX - had_error++ ? */
   1801 		}
   1802 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
   1803 		    type == T_CNAME) {
   1804 			n = dn_expand(answer->buf, eom, cp, tbuf, (int)sizeof tbuf);
   1805 			if ((n < 0) || !maybe_ok(res, tbuf, name_ok)) {
   1806 				had_error++;
   1807 				continue;
   1808 			}
   1809 			cp += n;
   1810 			/* Get canonical name. */
   1811 			n = (int)strlen(tbuf) + 1;	/* for the \0 */
   1812 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
   1813 				had_error++;
   1814 				continue;
   1815 			}
   1816 			strlcpy(bp, tbuf, (size_t)(ep - bp));
   1817 			canonname = bp;
   1818 			bp += n;
   1819 			continue;
   1820 		}
   1821 		if (qtype == T_ANY) {
   1822 			if (!(type == T_A || type == T_AAAA)) {
   1823 				cp += n;
   1824 				continue;
   1825 			}
   1826 		} else if (type != qtype) {
   1827 			if (type != T_KEY && type != T_SIG && type != T_DNAME) {
   1828 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1829 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1830 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
   1831 				       qname, p_class(C_IN), p_type(qtype),
   1832 				       p_type(type));
   1833 			}
   1834 			cp += n;
   1835 			continue;		/* XXX - had_error++ ? */
   1836 		}
   1837 		switch (type) {
   1838 		case T_A:
   1839 		case T_AAAA:
   1840 			if (strcasecmp(canonname, bp) != 0) {
   1841 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1842 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1843 				       AskedForGot, canonname, bp);
   1844 				cp += n;
   1845 				continue;	/* XXX - had_error++ ? */
   1846 			}
   1847 			if (type == T_A && n != INADDRSZ) {
   1848 				cp += n;
   1849 				continue;
   1850 			}
   1851 			if (type == T_AAAA && n != IN6ADDRSZ) {
   1852 				cp += n;
   1853 				continue;
   1854 			}
   1855 			if (type == T_AAAA) {
   1856 				struct in6_addr in6;
   1857 				memcpy(&in6, cp, IN6ADDRSZ);
   1858 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
   1859 					cp += n;
   1860 					continue;
   1861 				}
   1862 			}
   1863 			if (!haveanswer) {
   1864 				int nn;
   1865 
   1866 				canonname = bp;
   1867 				nn = (int)strlen(bp) + 1;	/* for the \0 */
   1868 				bp += nn;
   1869 			}
   1870 
   1871 			/* don't overwrite pai */
   1872 			ai = *pai;
   1873 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
   1874 			afd = find_afd(ai.ai_family);
   1875 			if (afd == NULL) {
   1876 				cp += n;
   1877 				continue;
   1878 			}
   1879 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
   1880 			if (cur->ai_next == NULL)
   1881 				had_error++;
   1882 			while (cur && cur->ai_next)
   1883 				cur = cur->ai_next;
   1884 			cp += n;
   1885 			break;
   1886 		case T_SRV:
   1887 			/* Add to SRV list. Insertion sort on priority. */
   1888 			pri = _getshort(cp);
   1889 			cp += INT16SZ;
   1890 			weight = _getshort(cp);
   1891 			cp += INT16SZ;
   1892 			port = _getshort(cp);
   1893 			cp += INT16SZ;
   1894 			n = dn_expand(answer->buf, eom, cp, tbuf,
   1895 			    (int)sizeof(tbuf));
   1896 			if ((n < 0) || !maybe_ok(res, tbuf, res_hnok)) {
   1897 				had_error++;
   1898 				continue;
   1899 			}
   1900 			cp += n;
   1901 			if (strlen(tbuf) + 1 >= MAXDNAME) {
   1902 				had_error++;
   1903 				continue;
   1904 			}
   1905 			srv = malloc(sizeof(*srv));
   1906 			if (!srv) {
   1907 				had_error++;
   1908 				continue;
   1909 			}
   1910 			strlcpy(srv->name, tbuf, sizeof(srv->name));
   1911 			srv->pri = pri;
   1912 			srv->weight = weight;
   1913 			srv->port = port;
   1914 			/* Weight 0 is sorted before other weights. */
   1915 			if (!srvlist
   1916 			    || srv->pri < srvlist->pri
   1917 			    || (srv->pri == srvlist->pri &&
   1918 			    (!srv->weight || srvlist->weight))) {
   1919 				srv->next = srvlist;
   1920 				srvlist = srv;
   1921 			} else {
   1922 				for (csrv = srvlist;
   1923 				    csrv->next && csrv->next->pri <= srv->pri;
   1924 				    csrv = csrv->next) {
   1925 					if (csrv->next->pri == srv->pri
   1926 					    && (!srv->weight ||
   1927 					    csrv->next->weight))
   1928 						break;
   1929 				}
   1930 				srv->next = csrv->next;
   1931 				csrv->next = srv;
   1932 			}
   1933 			continue; /* Don't add to haveanswer yet. */
   1934 		default:
   1935 			abort();
   1936 		}
   1937 		if (!had_error)
   1938 			haveanswer++;
   1939 	}
   1940 
   1941 	if (srvlist) {
   1942 		/*
   1943 		 * Check for explicit rejection.
   1944 		 */
   1945 		if (!srvlist->next && !srvlist->name[0]) {
   1946 			free(srvlist);
   1947 			h_errno = HOST_NOT_FOUND;
   1948 			return NULL;
   1949 		}
   1950 
   1951 		while (srvlist) {
   1952 			struct res_target q, q2;
   1953 
   1954 			srv = srvlist;
   1955 			srvlist = srvlist->next;
   1956 
   1957 			/*
   1958 			 * Since res_* doesn't give the additional
   1959 			 * section, we always look up.
   1960 			 */
   1961 			memset(&q, 0, sizeof(q));
   1962 			memset(&q2, 0, sizeof(q2));
   1963 
   1964 			q.name = srv->name;
   1965 			q.qclass = C_IN;
   1966 			q.qtype = T_AAAA;
   1967 			q.next = &q2;
   1968 			q2.name = srv->name;
   1969 			q2.qclass = C_IN;
   1970 			q2.qtype = T_A;
   1971 
   1972 			aip = _dns_query(&q, pai, res, 0);
   1973 
   1974 			if (aip != NULL) {
   1975 				cur->ai_next = aip;
   1976 				while (cur && cur->ai_next) {
   1977 					cur = cur->ai_next;
   1978 					*getport(cur) = htons(srv->port);
   1979 					haveanswer++;
   1980 				}
   1981 			}
   1982 			free(srv);
   1983 		}
   1984 	}
   1985 	if (haveanswer) {
   1986 		if (!sentinel.ai_next->ai_canonname)
   1987 		       (void)get_canonname(pai, sentinel.ai_next,
   1988 			   canonname ? canonname : qname);
   1989 		h_errno = NETDB_SUCCESS;
   1990 		return sentinel.ai_next;
   1991 	}
   1992 
   1993 	/* We could have walked a CNAME chain, */
   1994 	/* but the ultimate target may not have what we looked for */
   1995 	h_errno = ntohs(hp->ancount) > 0? NO_DATA : NO_RECOVERY;
   1996 	return NULL;
   1997 }
   1998 
   1999 #define SORTEDADDR(p)	(((struct sockaddr_in *)(void *)(p->ai_next->ai_addr))->sin_addr.s_addr)
   2000 #define SORTMATCH(p, s) ((SORTEDADDR(p) & (s).mask) == (s).addr.s_addr)
   2001 
   2002 static void
   2003 aisort(struct addrinfo *s, res_state res)
   2004 {
   2005 	struct addrinfo head, *t, *p;
   2006 	int i;
   2007 
   2008 	head.ai_next = NULL;
   2009 	t = &head;
   2010 
   2011 	for (i = 0; i < res->nsort; i++) {
   2012 		p = s;
   2013 		while (p->ai_next) {
   2014 			if ((p->ai_next->ai_family != AF_INET)
   2015 			|| SORTMATCH(p, res->sort_list[i])) {
   2016 				t->ai_next = p->ai_next;
   2017 				t = t->ai_next;
   2018 				p->ai_next = p->ai_next->ai_next;
   2019 			} else {
   2020 				p = p->ai_next;
   2021 			}
   2022 		}
   2023 	}
   2024 
   2025 	/* add rest of list and reset s to the new list*/
   2026 	t->ai_next = s->ai_next;
   2027 	s->ai_next = head.ai_next;
   2028 }
   2029 
   2030 static struct addrinfo *
   2031 _dns_query(struct res_target *q, const struct addrinfo *pai,
   2032     res_state res, int dosearch)
   2033 {
   2034 	struct res_target *q2 = q->next;
   2035  	querybuf *buf, *buf2;
   2036 	struct addrinfo sentinel, *cur, *ai;
   2037 
   2038 #ifdef DNS_DEBUG
   2039 	struct res_target *iter;
   2040 	for (iter = q; iter; iter = iter->next)
   2041 		printf("Query type %d for %s\n", iter->qtype, iter->name);
   2042 #endif
   2043 
   2044  	buf = malloc(sizeof(*buf));
   2045  	if (buf == NULL) {
   2046  		h_errno = NETDB_INTERNAL;
   2047 		return NULL;
   2048  	}
   2049  	buf2 = malloc(sizeof(*buf2));
   2050  	if (buf2 == NULL) {
   2051  		free(buf);
   2052  		h_errno = NETDB_INTERNAL;
   2053 		return NULL;
   2054 	}
   2055 
   2056 	memset(&sentinel, 0, sizeof(sentinel));
   2057 	cur = &sentinel;
   2058 
   2059 	q->answer = buf->buf;
   2060 	q->anslen = sizeof(buf->buf);
   2061 	if (q2) {
   2062 		q2->answer = buf2->buf;
   2063 		q2->anslen = sizeof(buf2->buf);
   2064 	}
   2065 
   2066 	if (dosearch) {
   2067 		if (res_searchN(q->name, q, res) < 0)
   2068 			goto out;
   2069 	} else {
   2070 		if (res_queryN(q->name, q, res) < 0)
   2071 			goto out;
   2072 	}
   2073 
   2074 	ai = getanswer(res, buf, q->n, q->name, q->qtype, pai);
   2075 	if (ai) {
   2076 		cur->ai_next = ai;
   2077 		while (cur && cur->ai_next)
   2078 			cur = cur->ai_next;
   2079 	}
   2080 	if (q2) {
   2081 		ai = getanswer(res, buf2, q2->n, q2->name, q2->qtype, pai);
   2082 		if (ai)
   2083 			cur->ai_next = ai;
   2084  	}
   2085 	free(buf);
   2086 	free(buf2);
   2087 	return sentinel.ai_next;
   2088 out:
   2089 	free(buf);
   2090 	free(buf2);
   2091 	return NULL;
   2092 }
   2093 
   2094 /*ARGSUSED*/
   2095 static struct addrinfo *
   2096 _dns_srv_lookup(const char *name, const char *servname,
   2097     const struct addrinfo *pai)
   2098 {
   2099 	static const char * const srvprotos[] = { "tcp", "udp" };
   2100 	static const int srvnottype[] = { SOCK_DGRAM, SOCK_STREAM };
   2101 	static const int nsrvprotos = 2;
   2102 	struct addrinfo sentinel, *cur, *ai;
   2103 	struct servent *serv, sv;
   2104 	struct servent_data svd;
   2105 	struct res_target q;
   2106 	res_state res;
   2107 	char *tname;
   2108 	int i;
   2109 
   2110 	res = __res_get_state();
   2111 	if (res == NULL)
   2112 		return NULL;
   2113 
   2114 	memset(&svd, 0, sizeof(svd));
   2115 	memset(&sentinel, 0, sizeof(sentinel));
   2116 	cur = &sentinel;
   2117 
   2118 	/*
   2119 	 * Iterate over supported SRV protocols.
   2120 	 * (currently UDP and TCP only)
   2121 	 */
   2122 	for (i = 0; i < nsrvprotos; i++) {
   2123 		/*
   2124 		 * Check that the caller didn't specify a hint
   2125 		 * which precludes this protocol.
   2126 		 */
   2127 		if (pai->ai_socktype == srvnottype[i])
   2128 			continue;
   2129 		/*
   2130 		 * If the caller specified a port,
   2131 		 * then lookup the database for the
   2132 		 * official service name.
   2133 		 */
   2134 		serv = getservbyname_r(servname, srvprotos[i], &sv, &svd);
   2135 		if (serv == NULL)
   2136 			continue;
   2137 
   2138 		/*
   2139 		 * Construct service DNS name.
   2140 		 */
   2141 		if (asprintf(&tname, "_%s._%s.%s", serv->s_name, serv->s_proto,
   2142 		    name) < 0)
   2143 			continue;
   2144 
   2145 		memset(&q, 0, sizeof(q));
   2146 		q.name = tname;
   2147 		q.qclass = C_IN;
   2148 		q.qtype = T_SRV;
   2149 
   2150 		/*
   2151 		 * Do SRV query.
   2152 		 */
   2153 		ai = _dns_query(&q, pai, res, 1);
   2154 		if (ai) {
   2155 			cur->ai_next = ai;
   2156 			while (cur && cur->ai_next)
   2157 				cur = cur->ai_next;
   2158 		}
   2159 		free(tname);
   2160 	}
   2161 
   2162 	if (res->nsort)
   2163 		aisort(&sentinel, res);
   2164 
   2165 	__res_put_state(res);
   2166 
   2167 	return sentinel.ai_next;
   2168 }
   2169 
   2170 /*ARGSUSED*/
   2171 static struct addrinfo *
   2172 _dns_host_lookup(const char *name, const struct addrinfo *pai)
   2173 {
   2174 	struct res_target q, q2;
   2175 	struct addrinfo sentinel, *ai;
   2176 	res_state res;
   2177 
   2178 	res = __res_get_state();
   2179 	if (res == NULL)
   2180 		return NULL;
   2181 
   2182 	memset(&q, 0, sizeof(q2));
   2183 	memset(&q2, 0, sizeof(q2));
   2184 
   2185 	switch (pai->ai_family) {
   2186 	case AF_UNSPEC:
   2187 		/* prefer IPv6 */
   2188 		q.name = name;
   2189 		q.qclass = C_IN;
   2190 		q.qtype = T_AAAA;
   2191 		q.next = &q2;
   2192 		q2.name = name;
   2193 		q2.qclass = C_IN;
   2194 		q2.qtype = T_A;
   2195 		break;
   2196 	case AF_INET:
   2197 		q.name = name;
   2198 		q.qclass = C_IN;
   2199 		q.qtype = T_A;
   2200 		break;
   2201 	case AF_INET6:
   2202 		q.name = name;
   2203 		q.qclass = C_IN;
   2204 		q.qtype = T_AAAA;
   2205 		break;
   2206 	default:
   2207 		__res_put_state(res);
   2208 		h_errno = NETDB_INTERNAL;
   2209 		return NULL;
   2210 	}
   2211 
   2212 	ai = _dns_query(&q, pai, res, 1);
   2213 
   2214 	memset(&sentinel, 0, sizeof(sentinel));
   2215 	sentinel.ai_next = ai;
   2216 
   2217 	if (ai != NULL && res->nsort)
   2218 		aisort(&sentinel, res);
   2219 
   2220 	__res_put_state(res);
   2221 
   2222 	return sentinel.ai_next;
   2223 }
   2224 
   2225 /*ARGSUSED*/
   2226 static int
   2227 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2228 {
   2229 	struct addrinfo *ai = NULL;
   2230 	const char *name, *servname;
   2231 	const struct addrinfo *pai;
   2232 
   2233 	name = va_arg(ap, char *);
   2234 	pai = va_arg(ap, const struct addrinfo *);
   2235 	servname = va_arg(ap, char *);
   2236 
   2237 	/*
   2238 	 * Try doing SRV lookup on service first.
   2239 	 */
   2240 	if (servname
   2241 #ifdef AI_SRV
   2242 	    && (pai->ai_flags & AI_SRV)
   2243 #endif
   2244 	    && !(pai->ai_flags & AI_NUMERICSERV)
   2245 	    && str2number(servname) == -1) {
   2246 
   2247 #ifdef DNS_DEBUG
   2248 		printf("%s: try SRV lookup\n", __func__);
   2249 #endif
   2250 		ai = _dns_srv_lookup(name, servname, pai);
   2251 	}
   2252 
   2253 	/*
   2254 	 * Do lookup on name.
   2255 	 */
   2256 	if (ai == NULL) {
   2257 
   2258 #ifdef DNS_DEBUG
   2259 		printf("%s: try HOST lookup\n", __func__);
   2260 #endif
   2261 		ai = _dns_host_lookup(name, pai);
   2262 
   2263 		if (ai == NULL) {
   2264 			switch (h_errno) {
   2265 			case HOST_NOT_FOUND:
   2266 			case NO_DATA:	// XXX: Perhaps we could differentiate
   2267 					// So that we could return EAI_NODATA?
   2268 				return NS_NOTFOUND;
   2269 			case TRY_AGAIN:
   2270 				return NS_TRYAGAIN;
   2271 			default:
   2272 				return NS_UNAVAIL;
   2273 			}
   2274 		}
   2275 	}
   2276 
   2277 	*((struct addrinfo **)rv) = ai;
   2278 	return NS_SUCCESS;
   2279 }
   2280 
   2281 static void
   2282 _sethtent(FILE **hostf)
   2283 {
   2284 
   2285 	if (!*hostf)
   2286 		*hostf = fopen(_PATH_HOSTS, "re");
   2287 	else
   2288 		rewind(*hostf);
   2289 }
   2290 
   2291 static void
   2292 _endhtent(FILE **hostf)
   2293 {
   2294 
   2295 	if (*hostf) {
   2296 		(void) fclose(*hostf);
   2297 		*hostf = NULL;
   2298 	}
   2299 }
   2300 
   2301 static struct addrinfo *
   2302 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
   2303 {
   2304 	char *p;
   2305 	char *cp, *tname, *cname;
   2306 	struct addrinfo hints, *res0, *res;
   2307 	int error;
   2308 	const char *addr;
   2309 	char hostbuf[8*1024];
   2310 
   2311 	_DIAGASSERT(name != NULL);
   2312 	_DIAGASSERT(pai != NULL);
   2313 
   2314 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
   2315 		return NULL;
   2316  again:
   2317 	if (!(p = fgets(hostbuf, (int)sizeof hostbuf, *hostf)))
   2318 		return NULL;
   2319 	if (*p == '#')
   2320 		goto again;
   2321 	if (!(cp = strpbrk(p, "#\n")))
   2322 		goto again;
   2323 	*cp = '\0';
   2324 	if (!(cp = strpbrk(p, " \t")))
   2325 		goto again;
   2326 	*cp++ = '\0';
   2327 	addr = p;
   2328 	/* if this is not something we're looking for, skip it. */
   2329 	cname = NULL;
   2330 	while (cp && *cp) {
   2331 		if (*cp == ' ' || *cp == '\t') {
   2332 			cp++;
   2333 			continue;
   2334 		}
   2335 		if (!cname)
   2336 			cname = cp;
   2337 		tname = cp;
   2338 		if ((cp = strpbrk(cp, " \t")) != NULL)
   2339 			*cp++ = '\0';
   2340 		if (strcasecmp(name, tname) == 0)
   2341 			goto found;
   2342 	}
   2343 	goto again;
   2344 
   2345 found:
   2346 	hints = *pai;
   2347 	hints.ai_flags = AI_NUMERICHOST;
   2348 	error = getaddrinfo(addr, NULL, &hints, &res0);
   2349 	if (error)
   2350 		goto again;
   2351 	for (res = res0; res; res = res->ai_next) {
   2352 		/* cover it up */
   2353 		res->ai_flags = pai->ai_flags;
   2354 
   2355 		if (pai->ai_flags & AI_CANONNAME) {
   2356 			if (get_canonname(pai, res, cname) != 0) {
   2357 				freeaddrinfo(res0);
   2358 				goto again;
   2359 			}
   2360 		}
   2361 	}
   2362 	return res0;
   2363 }
   2364 
   2365 /*ARGSUSED*/
   2366 static int
   2367 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2368 {
   2369 	const char *name;
   2370 	const struct addrinfo *pai;
   2371 	struct addrinfo sentinel, *cur;
   2372 	struct addrinfo *p;
   2373 #ifndef _REENTRANT
   2374 	static
   2375 #endif
   2376 	FILE *hostf = NULL;
   2377 
   2378 	name = va_arg(ap, char *);
   2379 	pai = va_arg(ap, const struct addrinfo *);
   2380 
   2381 	memset(&sentinel, 0, sizeof(sentinel));
   2382 	cur = &sentinel;
   2383 
   2384 	_sethtent(&hostf);
   2385 	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
   2386 		cur->ai_next = p;
   2387 		while (cur && cur->ai_next)
   2388 			cur = cur->ai_next;
   2389 	}
   2390 	_endhtent(&hostf);
   2391 
   2392 	*((struct addrinfo **)rv) = sentinel.ai_next;
   2393 	if (sentinel.ai_next == NULL)
   2394 		return NS_NOTFOUND;
   2395 	return NS_SUCCESS;
   2396 }
   2397 
   2398 #ifdef YP
   2399 /*ARGSUSED*/
   2400 static struct addrinfo *
   2401 _yphostent(char *line, const struct addrinfo *pai)
   2402 {
   2403 	struct addrinfo sentinel, *cur;
   2404 	struct addrinfo hints, *res, *res0;
   2405 	int error;
   2406 	char *p;
   2407 	const char *addr, *canonname;
   2408 	char *nextline;
   2409 	char *cp;
   2410 
   2411 	_DIAGASSERT(line != NULL);
   2412 	_DIAGASSERT(pai != NULL);
   2413 
   2414 	p = line;
   2415 	addr = canonname = NULL;
   2416 
   2417 	memset(&sentinel, 0, sizeof(sentinel));
   2418 	cur = &sentinel;
   2419 
   2420 nextline:
   2421 	/* terminate line */
   2422 	cp = strchr(p, '\n');
   2423 	if (cp) {
   2424 		*cp++ = '\0';
   2425 		nextline = cp;
   2426 	} else
   2427 		nextline = NULL;
   2428 
   2429 	cp = strpbrk(p, " \t");
   2430 	if (cp == NULL) {
   2431 		if (canonname == NULL)
   2432 			return NULL;
   2433 		else
   2434 			goto done;
   2435 	}
   2436 	*cp++ = '\0';
   2437 
   2438 	addr = p;
   2439 
   2440 	while (cp && *cp) {
   2441 		if (*cp == ' ' || *cp == '\t') {
   2442 			cp++;
   2443 			continue;
   2444 		}
   2445 		if (!canonname)
   2446 			canonname = cp;
   2447 		if ((cp = strpbrk(cp, " \t")) != NULL)
   2448 			*cp++ = '\0';
   2449 	}
   2450 
   2451 	hints = *pai;
   2452 	hints.ai_flags = AI_NUMERICHOST;
   2453 	error = getaddrinfo(addr, NULL, &hints, &res0);
   2454 	if (error == 0) {
   2455 		for (res = res0; res; res = res->ai_next) {
   2456 			/* cover it up */
   2457 			res->ai_flags = pai->ai_flags;
   2458 
   2459 			if (pai->ai_flags & AI_CANONNAME)
   2460 				(void)get_canonname(pai, res, canonname);
   2461 		}
   2462 	} else
   2463 		res0 = NULL;
   2464 	if (res0) {
   2465 		cur->ai_next = res0;
   2466 		while (cur->ai_next)
   2467 			cur = cur->ai_next;
   2468 	}
   2469 
   2470 	if (nextline) {
   2471 		p = nextline;
   2472 		goto nextline;
   2473 	}
   2474 
   2475 done:
   2476 	return sentinel.ai_next;
   2477 }
   2478 
   2479 /*ARGSUSED*/
   2480 static int
   2481 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2482 {
   2483 	struct addrinfo sentinel, *cur;
   2484 	struct addrinfo *ai = NULL;
   2485 	char *ypbuf;
   2486 	int ypbuflen, r;
   2487 	const char *name;
   2488 	const struct addrinfo *pai;
   2489 	char *ypdomain;
   2490 
   2491 	if (_yp_check(&ypdomain) == 0)
   2492 		return NS_UNAVAIL;
   2493 
   2494 	name = va_arg(ap, char *);
   2495 	pai = va_arg(ap, const struct addrinfo *);
   2496 
   2497 	memset(&sentinel, 0, sizeof(sentinel));
   2498 	cur = &sentinel;
   2499 
   2500 	/* hosts.byname is only for IPv4 (Solaris8) */
   2501 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
   2502 		r = yp_match(ypdomain, "hosts.byname", name,
   2503 			(int)strlen(name), &ypbuf, &ypbuflen);
   2504 		if (r == 0) {
   2505 			struct addrinfo ai4;
   2506 
   2507 			ai4 = *pai;
   2508 			ai4.ai_family = AF_INET;
   2509 			ai = _yphostent(ypbuf, &ai4);
   2510 			if (ai) {
   2511 				cur->ai_next = ai;
   2512 				while (cur && cur->ai_next)
   2513 					cur = cur->ai_next;
   2514 			}
   2515 		}
   2516 		free(ypbuf);
   2517 	}
   2518 
   2519 	/* ipnodes.byname can hold both IPv4/v6 */
   2520 	r = yp_match(ypdomain, "ipnodes.byname", name,
   2521 		(int)strlen(name), &ypbuf, &ypbuflen);
   2522 	if (r == 0) {
   2523 		ai = _yphostent(ypbuf, pai);
   2524 		if (ai)
   2525 			cur->ai_next = ai;
   2526 		free(ypbuf);
   2527 	}
   2528 
   2529 	if (sentinel.ai_next == NULL) {
   2530 		h_errno = HOST_NOT_FOUND;
   2531 		return NS_NOTFOUND;
   2532 	}
   2533 	*((struct addrinfo **)rv) = sentinel.ai_next;
   2534 	return NS_SUCCESS;
   2535 }
   2536 #endif
   2537 
   2538 /* resolver logic */
   2539 
   2540 /*
   2541  * Formulate a normal query, send, and await answer.
   2542  * Returned answer is placed in supplied buffer "answer".
   2543  * Perform preliminary check of answer, returning success only
   2544  * if no error is indicated and the answer count is nonzero.
   2545  * Return the size of the response on success, -1 on error.
   2546  * Error number is left in h_errno.
   2547  *
   2548  * Caller must parse answer and determine whether it answers the question.
   2549  */
   2550 static int
   2551 res_queryN(const char *name, /* domain name */ struct res_target *target,
   2552     res_state statp)
   2553 {
   2554 	u_char buf[MAXPACKET];
   2555 	HEADER *hp;
   2556 	int n;
   2557 	struct res_target *t;
   2558 	int rcode;
   2559 	u_char *rdata;
   2560 	int ancount;
   2561 
   2562 	_DIAGASSERT(name != NULL);
   2563 	/* XXX: target may be NULL??? */
   2564 
   2565 	rcode = NOERROR;
   2566 	ancount = 0;
   2567 
   2568 	for (t = target; t; t = t->next) {
   2569 		int class, type;
   2570 		u_char *answer;
   2571 		int anslen;
   2572 		u_int oflags;
   2573 
   2574 		hp = (HEADER *)(void *)t->answer;
   2575 		oflags = statp->_flags;
   2576 
   2577 again:
   2578 		hp->rcode = NOERROR;	/* default */
   2579 
   2580 		/* make it easier... */
   2581 		class = t->qclass;
   2582 		type = t->qtype;
   2583 		answer = t->answer;
   2584 		anslen = t->anslen;
   2585 #ifdef DEBUG
   2586 		if (statp->options & RES_DEBUG)
   2587 			printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
   2588 #endif
   2589 
   2590 		n = res_nmkquery(statp, QUERY, name, class, type, NULL, 0, NULL,
   2591 		    buf, (int)sizeof(buf));
   2592 #ifdef RES_USE_EDNS0
   2593 		if (n > 0 && (statp->_flags & RES_F_EDNS0ERR) == 0 &&
   2594 		    (statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0) {
   2595 			n = res_nopt(statp, n, buf, (int)sizeof(buf), anslen);
   2596 			rdata = &buf[n];
   2597 			if (n > 0 && (statp->options & RES_NSID) != 0U) {
   2598 				n = res_nopt_rdata(statp, n, buf,
   2599 				    (int)sizeof(buf),
   2600 				    rdata, NS_OPT_NSID, 0, NULL);
   2601 			}
   2602 		}
   2603 #endif
   2604 		if (n <= 0) {
   2605 #ifdef DEBUG
   2606 			if (statp->options & RES_DEBUG)
   2607 				printf(";; res_nquery: mkquery failed\n");
   2608 #endif
   2609 			h_errno = NO_RECOVERY;
   2610 			return n;
   2611 		}
   2612 		n = res_nsend(statp, buf, n, answer, anslen);
   2613 		if (n < 0) {
   2614 #ifdef RES_USE_EDNS0
   2615 			/* if the query choked with EDNS0, retry without EDNS0 */
   2616 			if ((statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U &&
   2617 			    ((oflags ^ statp->_flags) & RES_F_EDNS0ERR) != 0) {
   2618 				statp->_flags |= RES_F_EDNS0ERR;
   2619 				if (statp->options & RES_DEBUG)
   2620 					printf(";; res_nquery: retry without EDNS0\n");
   2621 				goto again;
   2622 			}
   2623 #endif
   2624 #if 0
   2625 #ifdef DEBUG
   2626 			if (statp->options & RES_DEBUG)
   2627 				printf(";; res_query: send error\n");
   2628 #endif
   2629 			h_errno = TRY_AGAIN;
   2630 			return n;
   2631 #endif
   2632 		}
   2633 
   2634 		if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
   2635 			rcode = hp->rcode;	/* record most recent error */
   2636 #ifdef DEBUG
   2637 			if (statp->options & RES_DEBUG)
   2638 				printf(";; rcode = (%s), counts = an:%d ns:%d ar:%d\n",
   2639 				       p_rcode(hp->rcode),
   2640 				       ntohs(hp->ancount),
   2641 				       ntohs(hp->nscount),
   2642 				       ntohs(hp->arcount));
   2643 #endif
   2644 			continue;
   2645 		}
   2646 
   2647 		ancount += ntohs(hp->ancount);
   2648 
   2649 		t->n = n;
   2650 	}
   2651 
   2652 	if (ancount == 0) {
   2653 		switch (rcode) {
   2654 		case NXDOMAIN:
   2655 			h_errno = HOST_NOT_FOUND;
   2656 			break;
   2657 		case SERVFAIL:
   2658 			h_errno = TRY_AGAIN;
   2659 			break;
   2660 		case NOERROR:
   2661 			h_errno = NO_DATA;
   2662 			break;
   2663 		case FORMERR:
   2664 		case NOTIMP:
   2665 		case REFUSED:
   2666 		default:
   2667 			h_errno = NO_RECOVERY;
   2668 			break;
   2669 		}
   2670 		return -1;
   2671 	}
   2672 	return ancount;
   2673 }
   2674 
   2675 /*
   2676  * Formulate a normal query, send, and retrieve answer in supplied buffer.
   2677  * Return the size of the response on success, -1 on error.
   2678  * If enabled, implement search rules until answer or unrecoverable failure
   2679  * is detected.	 Error code, if any, is left in h_errno.
   2680  */
   2681 static int
   2682 res_searchN(const char *name, struct res_target *target, res_state res)
   2683 {
   2684 	const char *cp, * const *domain;
   2685 	HEADER *hp;
   2686 	u_int dots;
   2687 	char buf[MAXHOSTNAMELEN];
   2688 	int trailing_dot, ret, saved_herrno;
   2689 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
   2690 
   2691 	_DIAGASSERT(name != NULL);
   2692 	_DIAGASSERT(target != NULL);
   2693 
   2694 	hp = (HEADER *)(void *)target->answer;	/*XXX*/
   2695 
   2696 	errno = 0;
   2697 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
   2698 	dots = 0;
   2699 	for (cp = name; *cp; cp++)
   2700 		dots += (*cp == '.');
   2701 	trailing_dot = 0;
   2702 	if (cp > name && *--cp == '.')
   2703 		trailing_dot++;
   2704 
   2705 	/*
   2706 	 * if there aren't any dots, it could be a user-level alias
   2707 	 */
   2708 	if (!dots && (cp = res_hostalias(res, name, buf, sizeof(buf))) != NULL) {
   2709 		ret = res_queryN(cp, target, res);
   2710 		return ret;
   2711 	}
   2712 
   2713 	/*
   2714 	 * If there are dots in the name already, let's just give it a try
   2715 	 * 'as is'.  The threshold can be set with the "ndots" option.
   2716 	 */
   2717 	saved_herrno = -1;
   2718 	if (dots >= res->ndots) {
   2719 		ret = res_querydomainN(name, NULL, target, res);
   2720 		if (ret > 0)
   2721 			return ret;
   2722 		saved_herrno = h_errno;
   2723 		tried_as_is++;
   2724 	}
   2725 
   2726 	/*
   2727 	 * We do at least one level of search if
   2728 	 *	- there is no dot and RES_DEFNAME is set, or
   2729 	 *	- there is at least one dot, there is no trailing dot,
   2730 	 *	  and RES_DNSRCH is set.
   2731 	 */
   2732 	if ((!dots && (res->options & RES_DEFNAMES)) ||
   2733 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
   2734 		int done = 0;
   2735 
   2736 		for (domain = (const char * const *)res->dnsrch;
   2737 		   *domain && !done;
   2738 		   domain++) {
   2739 
   2740 			ret = res_querydomainN(name, *domain, target, res);
   2741 			if (ret > 0)
   2742 				return ret;
   2743 
   2744 			/*
   2745 			 * If no server present, give up.
   2746 			 * If name isn't found in this domain,
   2747 			 * keep trying higher domains in the search list
   2748 			 * (if that's enabled).
   2749 			 * On a NO_DATA error, keep trying, otherwise
   2750 			 * a wildcard entry of another type could keep us
   2751 			 * from finding this entry higher in the domain.
   2752 			 * If we get some other error (negative answer or
   2753 			 * server failure), then stop searching up,
   2754 			 * but try the input name below in case it's
   2755 			 * fully-qualified.
   2756 			 */
   2757 			if (errno == ECONNREFUSED) {
   2758 				h_errno = TRY_AGAIN;
   2759 				return -1;
   2760 			}
   2761 
   2762 			switch (h_errno) {
   2763 			case NO_DATA:
   2764 				got_nodata++;
   2765 				/* FALLTHROUGH */
   2766 			case HOST_NOT_FOUND:
   2767 				/* keep trying */
   2768 				break;
   2769 			case TRY_AGAIN:
   2770 				if (hp->rcode == SERVFAIL) {
   2771 					/* try next search element, if any */
   2772 					got_servfail++;
   2773 					break;
   2774 				}
   2775 				/* FALLTHROUGH */
   2776 			default:
   2777 				/* anything else implies that we're done */
   2778 				done++;
   2779 			}
   2780 			/*
   2781 			 * if we got here for some reason other than DNSRCH,
   2782 			 * we only wanted one iteration of the loop, so stop.
   2783 			 */
   2784 			if (!(res->options & RES_DNSRCH))
   2785 				done++;
   2786 		}
   2787 	}
   2788 
   2789 	/*
   2790 	 * if we have not already tried the name "as is", do that now.
   2791 	 * note that we do this regardless of how many dots were in the
   2792 	 * name or whether it ends with a dot.
   2793 	 */
   2794 	if (!tried_as_is) {
   2795 		ret = res_querydomainN(name, NULL, target, res);
   2796 		if (ret > 0)
   2797 			return ret;
   2798 	}
   2799 
   2800 	/*
   2801 	 * if we got here, we didn't satisfy the search.
   2802 	 * if we did an initial full query, return that query's h_errno
   2803 	 * (note that we wouldn't be here if that query had succeeded).
   2804 	 * else if we ever got a nodata, send that back as the reason.
   2805 	 * else send back meaningless h_errno, that being the one from
   2806 	 * the last DNSRCH we did.
   2807 	 */
   2808 	if (saved_herrno != -1)
   2809 		h_errno = saved_herrno;
   2810 	else if (got_nodata)
   2811 		h_errno = NO_DATA;
   2812 	else if (got_servfail)
   2813 		h_errno = TRY_AGAIN;
   2814 	return -1;
   2815 }
   2816 
   2817 /*
   2818  * Perform a call on res_query on the concatenation of name and domain,
   2819  * removing a trailing dot from name if domain is NULL.
   2820  */
   2821 static int
   2822 res_querydomainN(const char *name, const char *domain,
   2823     struct res_target *target, res_state res)
   2824 {
   2825 	char nbuf[MAXDNAME];
   2826 	const char *longname = nbuf;
   2827 	size_t n;
   2828 
   2829 	_DIAGASSERT(name != NULL);
   2830 	/* XXX: target may be NULL??? */
   2831 
   2832 #ifdef DEBUG
   2833 	if (res->options & RES_DEBUG)
   2834 		printf(";; res_querydomain(%s, %s)\n",
   2835 			name, domain?domain:"<Nil>");
   2836 #endif
   2837 	if (domain == NULL) {
   2838 		/*
   2839 		 * Check for trailing '.';
   2840 		 * copy without '.' if present.
   2841 		 */
   2842 		n = strlen(name);
   2843 		if (n + 1 > sizeof(nbuf)) {
   2844 			h_errno = NO_RECOVERY;
   2845 			return -1;
   2846 		}
   2847 		if (n > 0 && name[--n] == '.') {
   2848 			snprintf(nbuf, sizeof(nbuf), "%*s", (int)n, name);
   2849 		} else
   2850 			longname = name;
   2851 	} else {
   2852 		if ((size_t)snprintf(nbuf, sizeof(nbuf), "%s.%s",
   2853 				name, domain) >= sizeof(nbuf)) {
   2854 			h_errno = NO_RECOVERY;
   2855 			return -1;
   2856 		}
   2857 	}
   2858 	return res_queryN(longname, target, res);
   2859 }
   2860 
   2861 #ifdef TEST
   2862 int
   2863 main(int argc, char *argv[]) {
   2864 	struct addrinfo *ai, *sai;
   2865 	int i, e;
   2866 	char buf[1024];
   2867 
   2868 	for (i = 1; i < argc; i++) {
   2869 		if ((e = getaddrinfo(argv[i], NULL, NULL, &sai)) != 0)
   2870 			warnx("%s: %s", argv[i], gai_strerror(e));
   2871 		for (ai = sai; ai; ai = ai->ai_next) {
   2872 			sockaddr_snprintf(buf, sizeof(buf), "%a", ai->ai_addr);
   2873              		printf("flags=0x%x family=%d socktype=%d protocol=%d "
   2874 			    "addrlen=%zu addr=%s canonname=%s next=%p\n",
   2875 			    ai->ai_flags,
   2876              		    ai->ai_family,
   2877              		    ai->ai_socktype,
   2878              		    ai->ai_protocol,
   2879              		    (size_t)ai->ai_addrlen,
   2880 			    buf,
   2881 			    ai->ai_canonname,
   2882 			    ai->ai_next);
   2883 		}
   2884 		if (sai)
   2885 			freeaddrinfo(sai);
   2886 	}
   2887 	return 0;
   2888 }
   2889 #endif
   2890