Home | History | Annotate | Line # | Download | only in net
getaddrinfo.c revision 1.124
      1 /*	$NetBSD: getaddrinfo.c,v 1.124 2023/08/01 08:47:25 mrg 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.124 2023/08/01 08:47:25 mrg 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 *cp, *hostname2 = NULL, *scope, *addr;
   1397 	struct sockaddr_in6 *sin6;
   1398 
   1399 	_DIAGASSERT(pai != NULL);
   1400 	/* hostname may be NULL */
   1401 	/* servname may be NULL */
   1402 	_DIAGASSERT(res != NULL);
   1403 
   1404 	/*
   1405 	 * if the servname does not match socktype/protocol, ignore it.
   1406 	 */
   1407 	if (get_portmatch(pai, servname, svd) != 0)
   1408 		return 0;
   1409 
   1410 	afd = find_afd(pai->ai_family);
   1411 	if (afd == NULL)
   1412 		return 0;
   1413 
   1414 	if (!afd->a_scoped)
   1415 		return explore_numeric(pai, hostname, servname, res, hostname,
   1416 		    svd);
   1417 
   1418 	cp = strchr(hostname, SCOPE_DELIMITER);
   1419 	if (cp == NULL)
   1420 		return explore_numeric(pai, hostname, servname, res, hostname,
   1421 		    svd);
   1422 
   1423 	/*
   1424 	 * Handle special case of <scoped_address><delimiter><scope id>
   1425 	 */
   1426 	hostname2 = strdup(hostname);
   1427 	if (hostname2 == NULL)
   1428 		return EAI_MEMORY;
   1429 	/* terminate at the delimiter */
   1430 	hostname2[cp - hostname] = '\0';
   1431 	addr = hostname2;
   1432 	scope = cp + 1;
   1433 
   1434 	error = explore_numeric(pai, addr, servname, res, hostname, svd);
   1435 	if (error == 0) {
   1436 		u_int32_t scopeid;
   1437 
   1438 		for (cur = *res; cur; cur = cur->ai_next) {
   1439 			if (cur->ai_family != AF_INET6)
   1440 				continue;
   1441 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
   1442 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
   1443 				free(hostname2);
   1444 				return EAI_NODATA; /* XXX: is return OK? */
   1445 			}
   1446 			sin6->sin6_scope_id = scopeid;
   1447 		}
   1448 	}
   1449 
   1450 	free(hostname2);
   1451 
   1452 	return error;
   1453 #endif
   1454 }
   1455 
   1456 static int
   1457 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
   1458 {
   1459 
   1460 	_DIAGASSERT(pai != NULL);
   1461 	_DIAGASSERT(ai != NULL);
   1462 	_DIAGASSERT(str != NULL);
   1463 
   1464 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
   1465 		ai->ai_canonname = strdup(str);
   1466 		if (ai->ai_canonname == NULL)
   1467 			return EAI_MEMORY;
   1468 	}
   1469 	return 0;
   1470 }
   1471 
   1472 struct addrinfo *
   1473 allocaddrinfo(socklen_t addrlen)
   1474 {
   1475 	struct addrinfo *ai;
   1476 
   1477 	ai = calloc(sizeof(struct addrinfo) + addrlen, 1);
   1478 	if (ai) {
   1479 		ai->ai_addr = (void *)(ai+1);
   1480 		ai->ai_addrlen = ai->ai_addr->sa_len = addrlen;
   1481 	}
   1482 
   1483 	return ai;
   1484 }
   1485 
   1486 static struct addrinfo *
   1487 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
   1488 {
   1489 	char *p;
   1490 	struct addrinfo *ai;
   1491 	struct sockaddr *save;
   1492 
   1493 	_DIAGASSERT(pai != NULL);
   1494 	_DIAGASSERT(afd != NULL);
   1495 	_DIAGASSERT(addr != NULL);
   1496 
   1497 	ai = allocaddrinfo((socklen_t)afd->a_socklen);
   1498 	if (ai == NULL)
   1499 		return NULL;
   1500 
   1501 	save = ai->ai_addr;
   1502 	memcpy(ai, pai, sizeof(struct addrinfo));
   1503 
   1504 	/* since we just overwrote all of ai, we have
   1505 	   to restore ai_addr and ai_addrlen */
   1506 	ai->ai_addr = save;
   1507 	ai->ai_addrlen = (socklen_t)afd->a_socklen;
   1508 
   1509 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
   1510 	p = (char *)(void *)(ai->ai_addr);
   1511 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
   1512 	return ai;
   1513 }
   1514 
   1515 static int
   1516 get_portmatch(const struct addrinfo *ai, const char *servname,
   1517     struct servent_data *svd)
   1518 {
   1519 
   1520 	_DIAGASSERT(ai != NULL);
   1521 	/* servname may be NULL */
   1522 
   1523 	return get_port(ai, servname, 1, svd);
   1524 }
   1525 
   1526 static int
   1527 get_port(const struct addrinfo *ai, const char *servname, int matchonly,
   1528     struct servent_data *svd)
   1529 {
   1530 	const char *proto;
   1531 	struct servent *sp;
   1532 	int port;
   1533 	int allownumeric;
   1534 
   1535 	_DIAGASSERT(ai != NULL);
   1536 	/* servname may be NULL */
   1537 
   1538 	if (servname == NULL)
   1539 		return 0;
   1540 	switch (ai->ai_family) {
   1541 	case AF_INET:
   1542 #ifdef AF_INET6
   1543 	case AF_INET6:
   1544 #endif
   1545 		break;
   1546 	default:
   1547 		return 0;
   1548 	}
   1549 
   1550 	switch (ai->ai_socktype) {
   1551 	case SOCK_RAW:
   1552 		return EAI_SERVICE;
   1553 	case SOCK_DGRAM:
   1554 	case SOCK_STREAM:
   1555 		allownumeric = 1;
   1556 		break;
   1557 	case ANY:
   1558 		/*
   1559 		 * This was 0.	It is now 1 so that queries specifying
   1560 		 * a NULL hint, or hint without socktype (but, hopefully,
   1561 		 * with protocol) and numeric address actually work.
   1562 		 */
   1563 		allownumeric = 1;
   1564 		break;
   1565 	default:
   1566 		return EAI_SOCKTYPE;
   1567 	}
   1568 
   1569 	port = str2number(servname);
   1570 	if (port >= 0) {
   1571 		if (!allownumeric)
   1572 			return EAI_SERVICE;
   1573 		if (port < 0 || port > 65535)
   1574 			return EAI_SERVICE;
   1575 		port = htons(port);
   1576 	} else {
   1577 		struct servent sv;
   1578 		if (ai->ai_flags & AI_NUMERICSERV)
   1579 			return EAI_NONAME;
   1580 
   1581 		switch (ai->ai_socktype) {
   1582 		case SOCK_DGRAM:
   1583 			proto = "udp";
   1584 			break;
   1585 		case SOCK_STREAM:
   1586 			proto = "tcp";
   1587 			break;
   1588 		default:
   1589 			proto = NULL;
   1590 			break;
   1591 		}
   1592 
   1593 		sp = getservbyname_r(servname, proto, &sv, svd);
   1594 		if (sp == NULL)
   1595 			return EAI_SERVICE;
   1596 		port = sp->s_port;
   1597 	}
   1598 
   1599 	if (!matchonly)
   1600 		*getport(__UNCONST(ai)) = port;
   1601 	return 0;
   1602 }
   1603 
   1604 static const struct afd *
   1605 find_afd(int af)
   1606 {
   1607 	const struct afd *afd;
   1608 
   1609 	if (af == PF_UNSPEC)
   1610 		return NULL;
   1611 	for (afd = afdl; afd->a_af; afd++) {
   1612 		if (afd->a_af == af)
   1613 			return afd;
   1614 	}
   1615 	return NULL;
   1616 }
   1617 
   1618 /*
   1619  * AI_ADDRCONFIG check: Build a mask containing a bit set for each address
   1620  * family configured in the system.
   1621  *
   1622  */
   1623 static int
   1624 addrconfig(uint64_t *mask)
   1625 {
   1626 	struct ifaddrs *ifaddrs, *ifa;
   1627 
   1628 	if (getifaddrs(&ifaddrs) == -1)
   1629 		return -1;
   1630 
   1631 	*mask = 0;
   1632 	for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next)
   1633 		if (ifa->ifa_addr && (ifa->ifa_flags & IFF_UP)) {
   1634 			_DIAGASSERT(ifa->ifa_addr->sa_family < 64);
   1635 			*mask |= (uint64_t)1 << ifa->ifa_addr->sa_family;
   1636 		}
   1637 
   1638 	freeifaddrs(ifaddrs);
   1639 	return 0;
   1640 }
   1641 
   1642 #ifdef INET6
   1643 /* convert a string to a scope identifier. XXX: IPv6 specific */
   1644 static int
   1645 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
   1646 {
   1647 	u_long lscopeid;
   1648 	struct in6_addr *a6;
   1649 	char *ep;
   1650 
   1651 	_DIAGASSERT(scope != NULL);
   1652 	_DIAGASSERT(sin6 != NULL);
   1653 	_DIAGASSERT(scopeid != NULL);
   1654 
   1655 	a6 = &sin6->sin6_addr;
   1656 
   1657 	/* empty scopeid portion is invalid */
   1658 	if (*scope == '\0')
   1659 		return -1;
   1660 
   1661 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
   1662 		/*
   1663 		 * We currently assume a one-to-one mapping between links
   1664 		 * and interfaces, so we simply use interface indices for
   1665 		 * like-local scopes.
   1666 		 */
   1667 		*scopeid = if_nametoindex(scope);
   1668 		if (*scopeid == 0)
   1669 			goto trynumeric;
   1670 		return 0;
   1671 	}
   1672 
   1673 	/* still unclear about literal, allow numeric only - placeholder */
   1674 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
   1675 		goto trynumeric;
   1676 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
   1677 		goto trynumeric;
   1678 	else
   1679 		goto trynumeric;	/* global */
   1680 
   1681 	/* try to convert to a numeric id as a last resort */
   1682   trynumeric:
   1683 	errno = 0;
   1684 	lscopeid = strtoul(scope, &ep, 10);
   1685 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
   1686 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
   1687 		return 0;
   1688 	else
   1689 		return -1;
   1690 }
   1691 #endif
   1692 
   1693 /* code duplicate with gethnamaddr.c */
   1694 
   1695 static const char AskedForGot[] =
   1696 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
   1697 
   1698 #define maybe_ok(res, nm, ok) (((res)->options & RES_NOCHECKNAME) != 0U || \
   1699                                (ok)(nm) != 0)
   1700 static struct addrinfo *
   1701 getanswer(res_state res, const querybuf *answer, int anslen, const char *qname,
   1702     int qtype, const struct addrinfo *pai)
   1703 {
   1704 	struct addrinfo sentinel, *cur;
   1705 	struct addrinfo ai, *aip;
   1706 	const struct afd *afd;
   1707 	char *canonname;
   1708 	const HEADER *hp;
   1709 	const u_char *cp;
   1710 	int n;
   1711 	const u_char *eom;
   1712 	char *bp, *ep;
   1713 	int type, class, ancount, qdcount;
   1714 	int haveanswer, had_error;
   1715 	char tbuf[MAXDNAME];
   1716 	int (*name_ok) (const char *);
   1717 	char hostbuf[8*1024];
   1718 	int port, pri, weight;
   1719 	struct srvinfo *srvlist, *srv, *csrv;
   1720 
   1721 	_DIAGASSERT(answer != NULL);
   1722 	_DIAGASSERT(qname != NULL);
   1723 	_DIAGASSERT(pai != NULL);
   1724 	_DIAGASSERT(res != NULL);
   1725 
   1726 	memset(&sentinel, 0, sizeof(sentinel));
   1727 	cur = &sentinel;
   1728 
   1729 	canonname = NULL;
   1730 	eom = answer->buf + anslen;
   1731 	switch (qtype) {
   1732 	case T_A:
   1733 	case T_AAAA:
   1734 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
   1735 		name_ok = res_hnok;
   1736 		break;
   1737 	case T_SRV:
   1738 		name_ok = gai_srvok;
   1739 		break;
   1740 	default:
   1741 		return NULL;	/* XXX should be abort(); */
   1742 	}
   1743 	/*
   1744 	 * find first satisfactory answer
   1745 	 */
   1746 	hp = &answer->hdr;
   1747 	ancount = ntohs(hp->ancount);
   1748 	qdcount = ntohs(hp->qdcount);
   1749 	bp = hostbuf;
   1750 	ep = hostbuf + sizeof hostbuf;
   1751 	cp = answer->buf + HFIXEDSZ;
   1752 	if (qdcount != 1) {
   1753 		h_errno = NO_RECOVERY;
   1754 		return NULL;
   1755 	}
   1756 	n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
   1757 	if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
   1758 		h_errno = NO_RECOVERY;
   1759 		return NULL;
   1760 	}
   1761 	cp += n + QFIXEDSZ;
   1762 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
   1763 		/* res_send() has already verified that the query name is the
   1764 		 * same as the one we sent; this just gets the expanded name
   1765 		 * (i.e., with the succeeding search-domain tacked on).
   1766 		 */
   1767 		n = (int)strlen(bp) + 1;		/* for the \0 */
   1768 		if (n >= MAXHOSTNAMELEN) {
   1769 			h_errno = NO_RECOVERY;
   1770 			return NULL;
   1771 		}
   1772 		canonname = bp;
   1773 		bp += n;
   1774 		/* The qname can be abbreviated, but h_name is now absolute. */
   1775 		qname = canonname;
   1776 	}
   1777 	haveanswer = 0;
   1778 	had_error = 0;
   1779 	srvlist = NULL;
   1780 	while (ancount-- > 0 && cp < eom && !had_error) {
   1781 		n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
   1782 		if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
   1783 			had_error++;
   1784 			continue;
   1785 		}
   1786 		cp += n;			/* name */
   1787 		type = _getshort(cp);
   1788 		cp += INT16SZ;			/* type */
   1789 		class = _getshort(cp);
   1790 		cp += INT16SZ + INT32SZ;	/* class, TTL */
   1791 		n = _getshort(cp);
   1792 		cp += INT16SZ;			/* len */
   1793 		if (class != C_IN) {
   1794 			/* XXX - debug? syslog? */
   1795 			cp += n;
   1796 			continue;		/* XXX - had_error++ ? */
   1797 		}
   1798 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
   1799 		    type == T_CNAME) {
   1800 			n = dn_expand(answer->buf, eom, cp, tbuf, (int)sizeof tbuf);
   1801 			if ((n < 0) || !maybe_ok(res, tbuf, name_ok)) {
   1802 				had_error++;
   1803 				continue;
   1804 			}
   1805 			cp += n;
   1806 			/* Get canonical name. */
   1807 			n = (int)strlen(tbuf) + 1;	/* for the \0 */
   1808 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
   1809 				had_error++;
   1810 				continue;
   1811 			}
   1812 			strlcpy(bp, tbuf, (size_t)(ep - bp));
   1813 			canonname = bp;
   1814 			bp += n;
   1815 			continue;
   1816 		}
   1817 		if (qtype == T_ANY) {
   1818 			if (!(type == T_A || type == T_AAAA)) {
   1819 				cp += n;
   1820 				continue;
   1821 			}
   1822 		} else if (type != qtype) {
   1823 			if (type != T_KEY && type != T_SIG && type != T_DNAME) {
   1824 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1825 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1826 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
   1827 				       qname, p_class(C_IN), p_type(qtype),
   1828 				       p_type(type));
   1829 			}
   1830 			cp += n;
   1831 			continue;		/* XXX - had_error++ ? */
   1832 		}
   1833 		switch (type) {
   1834 		case T_A:
   1835 		case T_AAAA:
   1836 			if (strcasecmp(canonname, bp) != 0) {
   1837 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1838 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1839 				       AskedForGot, canonname, bp);
   1840 				cp += n;
   1841 				continue;	/* XXX - had_error++ ? */
   1842 			}
   1843 			if (type == T_A && n != INADDRSZ) {
   1844 				cp += n;
   1845 				continue;
   1846 			}
   1847 			if (type == T_AAAA && n != IN6ADDRSZ) {
   1848 				cp += n;
   1849 				continue;
   1850 			}
   1851 			if (type == T_AAAA) {
   1852 				struct in6_addr in6;
   1853 				memcpy(&in6, cp, IN6ADDRSZ);
   1854 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
   1855 					cp += n;
   1856 					continue;
   1857 				}
   1858 			}
   1859 			if (!haveanswer) {
   1860 				int nn;
   1861 
   1862 				canonname = bp;
   1863 				nn = (int)strlen(bp) + 1;	/* for the \0 */
   1864 				bp += nn;
   1865 			}
   1866 
   1867 			/* don't overwrite pai */
   1868 			ai = *pai;
   1869 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
   1870 			afd = find_afd(ai.ai_family);
   1871 			if (afd == NULL) {
   1872 				cp += n;
   1873 				continue;
   1874 			}
   1875 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
   1876 			if (cur->ai_next == NULL)
   1877 				had_error++;
   1878 			while (cur && cur->ai_next)
   1879 				cur = cur->ai_next;
   1880 			cp += n;
   1881 			break;
   1882 		case T_SRV:
   1883 			/* Add to SRV list. Insertion sort on priority. */
   1884 			pri = _getshort(cp);
   1885 			cp += INT16SZ;
   1886 			weight = _getshort(cp);
   1887 			cp += INT16SZ;
   1888 			port = _getshort(cp);
   1889 			cp += INT16SZ;
   1890 			n = dn_expand(answer->buf, eom, cp, tbuf,
   1891 			    (int)sizeof(tbuf));
   1892 			if ((n < 0) || !maybe_ok(res, tbuf, res_hnok)) {
   1893 				had_error++;
   1894 				continue;
   1895 			}
   1896 			cp += n;
   1897 			if (strlen(tbuf) + 1 >= MAXDNAME) {
   1898 				had_error++;
   1899 				continue;
   1900 			}
   1901 			srv = malloc(sizeof(*srv));
   1902 			if (!srv) {
   1903 				had_error++;
   1904 				continue;
   1905 			}
   1906 			strlcpy(srv->name, tbuf, sizeof(srv->name));
   1907 			srv->pri = pri;
   1908 			srv->weight = weight;
   1909 			srv->port = port;
   1910 			/* Weight 0 is sorted before other weights. */
   1911 			if (!srvlist
   1912 			    || srv->pri < srvlist->pri
   1913 			    || (srv->pri == srvlist->pri &&
   1914 			    (!srv->weight || srvlist->weight))) {
   1915 				srv->next = srvlist;
   1916 				srvlist = srv;
   1917 			} else {
   1918 				for (csrv = srvlist;
   1919 				    csrv->next && csrv->next->pri <= srv->pri;
   1920 				    csrv = csrv->next) {
   1921 					if (csrv->next->pri == srv->pri
   1922 					    && (!srv->weight ||
   1923 					    csrv->next->weight))
   1924 						break;
   1925 				}
   1926 				srv->next = csrv->next;
   1927 				csrv->next = srv;
   1928 			}
   1929 			continue; /* Don't add to haveanswer yet. */
   1930 		default:
   1931 			abort();
   1932 		}
   1933 		if (!had_error)
   1934 			haveanswer++;
   1935 	}
   1936 
   1937 	if (srvlist) {
   1938 		/*
   1939 		 * Check for explicit rejection.
   1940 		 */
   1941 		if (!srvlist->next && !srvlist->name[0]) {
   1942 			free(srvlist);
   1943 			h_errno = HOST_NOT_FOUND;
   1944 			return NULL;
   1945 		}
   1946 
   1947 		while (srvlist) {
   1948 			struct res_target q, q2;
   1949 
   1950 			srv = srvlist;
   1951 			srvlist = srvlist->next;
   1952 
   1953 			/*
   1954 			 * Since res_* doesn't give the additional
   1955 			 * section, we always look up.
   1956 			 */
   1957 			memset(&q, 0, sizeof(q));
   1958 			memset(&q2, 0, sizeof(q2));
   1959 
   1960 			q.name = srv->name;
   1961 			q.qclass = C_IN;
   1962 			q.qtype = T_AAAA;
   1963 			q.next = &q2;
   1964 			q2.name = srv->name;
   1965 			q2.qclass = C_IN;
   1966 			q2.qtype = T_A;
   1967 
   1968 			aip = _dns_query(&q, pai, res, 0);
   1969 
   1970 			if (aip != NULL) {
   1971 				cur->ai_next = aip;
   1972 				while (cur && cur->ai_next) {
   1973 					cur = cur->ai_next;
   1974 					*getport(cur) = htons(srv->port);
   1975 					haveanswer++;
   1976 				}
   1977 			}
   1978 			free(srv);
   1979 		}
   1980 	}
   1981 	if (haveanswer) {
   1982 		if (!sentinel.ai_next->ai_canonname)
   1983 		       (void)get_canonname(pai, sentinel.ai_next,
   1984 			   canonname ? canonname : qname);
   1985 		h_errno = NETDB_SUCCESS;
   1986 		return sentinel.ai_next;
   1987 	}
   1988 
   1989 	/* We could have walked a CNAME chain, */
   1990 	/* but the ultimate target may not have what we looked for */
   1991 	h_errno = ntohs(hp->ancount) > 0? NO_DATA : NO_RECOVERY;
   1992 	return NULL;
   1993 }
   1994 
   1995 #define SORTEDADDR(p)	(((struct sockaddr_in *)(void *)(p->ai_next->ai_addr))->sin_addr.s_addr)
   1996 #define SORTMATCH(p, s) ((SORTEDADDR(p) & (s).mask) == (s).addr.s_addr)
   1997 
   1998 static void
   1999 aisort(struct addrinfo *s, res_state res)
   2000 {
   2001 	struct addrinfo head, *t, *p;
   2002 	int i;
   2003 
   2004 	head.ai_next = NULL;
   2005 	t = &head;
   2006 
   2007 	for (i = 0; i < res->nsort; i++) {
   2008 		p = s;
   2009 		while (p->ai_next) {
   2010 			if ((p->ai_next->ai_family != AF_INET)
   2011 			|| SORTMATCH(p, res->sort_list[i])) {
   2012 				t->ai_next = p->ai_next;
   2013 				t = t->ai_next;
   2014 				p->ai_next = p->ai_next->ai_next;
   2015 			} else {
   2016 				p = p->ai_next;
   2017 			}
   2018 		}
   2019 	}
   2020 
   2021 	/* add rest of list and reset s to the new list*/
   2022 	t->ai_next = s->ai_next;
   2023 	s->ai_next = head.ai_next;
   2024 }
   2025 
   2026 static struct addrinfo *
   2027 _dns_query(struct res_target *q, const struct addrinfo *pai,
   2028     res_state res, int dosearch)
   2029 {
   2030 	struct res_target *q2 = q->next;
   2031  	querybuf *buf, *buf2;
   2032 	struct addrinfo sentinel, *cur, *ai;
   2033 
   2034 #ifdef DNS_DEBUG
   2035 	struct res_target *iter;
   2036 	for (iter = q; iter; iter = iter->next)
   2037 		printf("Query type %d for %s\n", iter->qtype, iter->name);
   2038 #endif
   2039 
   2040  	buf = malloc(sizeof(*buf));
   2041  	if (buf == NULL) {
   2042  		h_errno = NETDB_INTERNAL;
   2043 		return NULL;
   2044  	}
   2045  	buf2 = malloc(sizeof(*buf2));
   2046  	if (buf2 == NULL) {
   2047  		free(buf);
   2048  		h_errno = NETDB_INTERNAL;
   2049 		return NULL;
   2050 	}
   2051 
   2052 	memset(&sentinel, 0, sizeof(sentinel));
   2053 	cur = &sentinel;
   2054 
   2055 	q->answer = buf->buf;
   2056 	q->anslen = sizeof(buf->buf);
   2057 	if (q2) {
   2058 		q2->answer = buf2->buf;
   2059 		q2->anslen = sizeof(buf2->buf);
   2060 	}
   2061 
   2062 	if (dosearch) {
   2063 		if (res_searchN(q->name, q, res) < 0)
   2064 			goto out;
   2065 	} else {
   2066 		if (res_queryN(q->name, q, res) < 0)
   2067 			goto out;
   2068 	}
   2069 
   2070 	ai = getanswer(res, buf, q->n, q->name, q->qtype, pai);
   2071 	if (ai) {
   2072 		cur->ai_next = ai;
   2073 		while (cur && cur->ai_next)
   2074 			cur = cur->ai_next;
   2075 	}
   2076 	if (q2) {
   2077 		ai = getanswer(res, buf2, q2->n, q2->name, q2->qtype, pai);
   2078 		if (ai)
   2079 			cur->ai_next = ai;
   2080  	}
   2081 	free(buf);
   2082 	free(buf2);
   2083 	return sentinel.ai_next;
   2084 out:
   2085 	free(buf);
   2086 	free(buf2);
   2087 	return NULL;
   2088 }
   2089 
   2090 /*ARGSUSED*/
   2091 static struct addrinfo *
   2092 _dns_srv_lookup(const char *name, const char *servname,
   2093     const struct addrinfo *pai)
   2094 {
   2095 	static const char * const srvprotos[] = { "tcp", "udp" };
   2096 	static const int srvnottype[] = { SOCK_DGRAM, SOCK_STREAM };
   2097 	static const int nsrvprotos = 2;
   2098 	struct addrinfo sentinel, *cur, *ai;
   2099 	struct servent *serv, sv;
   2100 	struct servent_data svd;
   2101 	struct res_target q;
   2102 	res_state res;
   2103 	char *tname;
   2104 	int i;
   2105 
   2106 	res = __res_get_state();
   2107 	if (res == NULL)
   2108 		return NULL;
   2109 
   2110 	memset(&svd, 0, sizeof(svd));
   2111 	memset(&sentinel, 0, sizeof(sentinel));
   2112 	cur = &sentinel;
   2113 
   2114 	/*
   2115 	 * Iterate over supported SRV protocols.
   2116 	 * (currently UDP and TCP only)
   2117 	 */
   2118 	for (i = 0; i < nsrvprotos; i++) {
   2119 		/*
   2120 		 * Check that the caller didn't specify a hint
   2121 		 * which precludes this protocol.
   2122 		 */
   2123 		if (pai->ai_socktype == srvnottype[i])
   2124 			continue;
   2125 		/*
   2126 		 * If the caller specified a port,
   2127 		 * then lookup the database for the
   2128 		 * official service name.
   2129 		 */
   2130 		serv = getservbyname_r(servname, srvprotos[i], &sv, &svd);
   2131 		if (serv == NULL)
   2132 			continue;
   2133 
   2134 		/*
   2135 		 * Construct service DNS name.
   2136 		 */
   2137 		if (asprintf(&tname, "_%s._%s.%s", serv->s_name, serv->s_proto,
   2138 		    name) < 0)
   2139 			continue;
   2140 
   2141 		memset(&q, 0, sizeof(q));
   2142 		q.name = tname;
   2143 		q.qclass = C_IN;
   2144 		q.qtype = T_SRV;
   2145 
   2146 		/*
   2147 		 * Do SRV query.
   2148 		 */
   2149 		ai = _dns_query(&q, pai, res, 1);
   2150 		if (ai) {
   2151 			cur->ai_next = ai;
   2152 			while (cur && cur->ai_next)
   2153 				cur = cur->ai_next;
   2154 		}
   2155 		free(tname);
   2156 	}
   2157 
   2158 	if (res->nsort)
   2159 		aisort(&sentinel, res);
   2160 
   2161 	__res_put_state(res);
   2162 
   2163 	return sentinel.ai_next;
   2164 }
   2165 
   2166 /*ARGSUSED*/
   2167 static struct addrinfo *
   2168 _dns_host_lookup(const char *name, const struct addrinfo *pai)
   2169 {
   2170 	struct res_target q, q2;
   2171 	struct addrinfo sentinel, *ai;
   2172 	res_state res;
   2173 
   2174 	res = __res_get_state();
   2175 	if (res == NULL)
   2176 		return NULL;
   2177 
   2178 	memset(&q, 0, sizeof(q2));
   2179 	memset(&q2, 0, sizeof(q2));
   2180 
   2181 	switch (pai->ai_family) {
   2182 	case AF_UNSPEC:
   2183 		/* prefer IPv6 */
   2184 		q.name = name;
   2185 		q.qclass = C_IN;
   2186 		q.qtype = T_AAAA;
   2187 		q.next = &q2;
   2188 		q2.name = name;
   2189 		q2.qclass = C_IN;
   2190 		q2.qtype = T_A;
   2191 		break;
   2192 	case AF_INET:
   2193 		q.name = name;
   2194 		q.qclass = C_IN;
   2195 		q.qtype = T_A;
   2196 		break;
   2197 	case AF_INET6:
   2198 		q.name = name;
   2199 		q.qclass = C_IN;
   2200 		q.qtype = T_AAAA;
   2201 		break;
   2202 	default:
   2203 		__res_put_state(res);
   2204 		h_errno = NETDB_INTERNAL;
   2205 		return NULL;
   2206 	}
   2207 
   2208 	ai = _dns_query(&q, pai, res, 1);
   2209 
   2210 	memset(&sentinel, 0, sizeof(sentinel));
   2211 	sentinel.ai_next = ai;
   2212 
   2213 	if (ai != NULL && res->nsort)
   2214 		aisort(&sentinel, res);
   2215 
   2216 	__res_put_state(res);
   2217 
   2218 	return sentinel.ai_next;
   2219 }
   2220 
   2221 /*ARGSUSED*/
   2222 static int
   2223 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2224 {
   2225 	struct addrinfo *ai = NULL;
   2226 	const char *name, *servname;
   2227 	const struct addrinfo *pai;
   2228 
   2229 	name = va_arg(ap, char *);
   2230 	pai = va_arg(ap, const struct addrinfo *);
   2231 	servname = va_arg(ap, char *);
   2232 
   2233 	/*
   2234 	 * Try doing SRV lookup on service first.
   2235 	 */
   2236 	if (servname
   2237 #ifdef AI_SRV
   2238 	    && (pai->ai_flags & AI_SRV)
   2239 #endif
   2240 	    && !(pai->ai_flags & AI_NUMERICSERV)
   2241 	    && str2number(servname) == -1) {
   2242 
   2243 #ifdef DNS_DEBUG
   2244 		printf("%s: try SRV lookup\n", __func__);
   2245 #endif
   2246 		ai = _dns_srv_lookup(name, servname, pai);
   2247 	}
   2248 
   2249 	/*
   2250 	 * Do lookup on name.
   2251 	 */
   2252 	if (ai == NULL) {
   2253 
   2254 #ifdef DNS_DEBUG
   2255 		printf("%s: try HOST lookup\n", __func__);
   2256 #endif
   2257 		ai = _dns_host_lookup(name, pai);
   2258 
   2259 		if (ai == NULL) {
   2260 			switch (h_errno) {
   2261 			case HOST_NOT_FOUND:
   2262 			case NO_DATA:	// XXX: Perhaps we could differentiate
   2263 					// So that we could return EAI_NODATA?
   2264 				return NS_NOTFOUND;
   2265 			case TRY_AGAIN:
   2266 				return NS_TRYAGAIN;
   2267 			default:
   2268 				return NS_UNAVAIL;
   2269 			}
   2270 		}
   2271 	}
   2272 
   2273 	*((struct addrinfo **)rv) = ai;
   2274 	return NS_SUCCESS;
   2275 }
   2276 
   2277 static void
   2278 _sethtent(FILE **hostf)
   2279 {
   2280 
   2281 	if (!*hostf)
   2282 		*hostf = fopen(_PATH_HOSTS, "re");
   2283 	else
   2284 		rewind(*hostf);
   2285 }
   2286 
   2287 static void
   2288 _endhtent(FILE **hostf)
   2289 {
   2290 
   2291 	if (*hostf) {
   2292 		(void) fclose(*hostf);
   2293 		*hostf = NULL;
   2294 	}
   2295 }
   2296 
   2297 static struct addrinfo *
   2298 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
   2299 {
   2300 	char *p;
   2301 	char *cp, *tname, *cname;
   2302 	struct addrinfo hints, *res0, *res;
   2303 	int error;
   2304 	const char *addr;
   2305 	char hostbuf[8*1024];
   2306 
   2307 	_DIAGASSERT(name != NULL);
   2308 	_DIAGASSERT(pai != NULL);
   2309 
   2310 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
   2311 		return NULL;
   2312  again:
   2313 	if (!(p = fgets(hostbuf, (int)sizeof hostbuf, *hostf)))
   2314 		return NULL;
   2315 	if (*p == '#')
   2316 		goto again;
   2317 	if (!(cp = strpbrk(p, "#\n")))
   2318 		goto again;
   2319 	*cp = '\0';
   2320 	if (!(cp = strpbrk(p, " \t")))
   2321 		goto again;
   2322 	*cp++ = '\0';
   2323 	addr = p;
   2324 	/* if this is not something we're looking for, skip it. */
   2325 	cname = NULL;
   2326 	while (cp && *cp) {
   2327 		if (*cp == ' ' || *cp == '\t') {
   2328 			cp++;
   2329 			continue;
   2330 		}
   2331 		if (!cname)
   2332 			cname = cp;
   2333 		tname = cp;
   2334 		if ((cp = strpbrk(cp, " \t")) != NULL)
   2335 			*cp++ = '\0';
   2336 		if (strcasecmp(name, tname) == 0)
   2337 			goto found;
   2338 	}
   2339 	goto again;
   2340 
   2341 found:
   2342 	hints = *pai;
   2343 	hints.ai_flags = AI_NUMERICHOST;
   2344 	error = getaddrinfo(addr, NULL, &hints, &res0);
   2345 	if (error)
   2346 		goto again;
   2347 	for (res = res0; res; res = res->ai_next) {
   2348 		/* cover it up */
   2349 		res->ai_flags = pai->ai_flags;
   2350 
   2351 		if (pai->ai_flags & AI_CANONNAME) {
   2352 			if (get_canonname(pai, res, cname) != 0) {
   2353 				freeaddrinfo(res0);
   2354 				goto again;
   2355 			}
   2356 		}
   2357 	}
   2358 	return res0;
   2359 }
   2360 
   2361 /*ARGSUSED*/
   2362 static int
   2363 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2364 {
   2365 	const char *name;
   2366 	const struct addrinfo *pai;
   2367 	struct addrinfo sentinel, *cur;
   2368 	struct addrinfo *p;
   2369 #ifndef _REENTRANT
   2370 	static
   2371 #endif
   2372 	FILE *hostf = NULL;
   2373 
   2374 	name = va_arg(ap, char *);
   2375 	pai = va_arg(ap, const struct addrinfo *);
   2376 
   2377 	memset(&sentinel, 0, sizeof(sentinel));
   2378 	cur = &sentinel;
   2379 
   2380 	_sethtent(&hostf);
   2381 	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
   2382 		cur->ai_next = p;
   2383 		while (cur && cur->ai_next)
   2384 			cur = cur->ai_next;
   2385 	}
   2386 	_endhtent(&hostf);
   2387 
   2388 	*((struct addrinfo **)rv) = sentinel.ai_next;
   2389 	if (sentinel.ai_next == NULL)
   2390 		return NS_NOTFOUND;
   2391 	return NS_SUCCESS;
   2392 }
   2393 
   2394 #ifdef YP
   2395 /*ARGSUSED*/
   2396 static struct addrinfo *
   2397 _yphostent(char *line, const struct addrinfo *pai)
   2398 {
   2399 	struct addrinfo sentinel, *cur;
   2400 	struct addrinfo hints, *res, *res0;
   2401 	int error;
   2402 	char *p;
   2403 	const char *addr, *canonname;
   2404 	char *nextline;
   2405 	char *cp;
   2406 
   2407 	_DIAGASSERT(line != NULL);
   2408 	_DIAGASSERT(pai != NULL);
   2409 
   2410 	p = line;
   2411 	addr = canonname = NULL;
   2412 
   2413 	memset(&sentinel, 0, sizeof(sentinel));
   2414 	cur = &sentinel;
   2415 
   2416 nextline:
   2417 	/* terminate line */
   2418 	cp = strchr(p, '\n');
   2419 	if (cp) {
   2420 		*cp++ = '\0';
   2421 		nextline = cp;
   2422 	} else
   2423 		nextline = NULL;
   2424 
   2425 	cp = strpbrk(p, " \t");
   2426 	if (cp == NULL) {
   2427 		if (canonname == NULL)
   2428 			return NULL;
   2429 		else
   2430 			goto done;
   2431 	}
   2432 	*cp++ = '\0';
   2433 
   2434 	addr = p;
   2435 
   2436 	while (cp && *cp) {
   2437 		if (*cp == ' ' || *cp == '\t') {
   2438 			cp++;
   2439 			continue;
   2440 		}
   2441 		if (!canonname)
   2442 			canonname = cp;
   2443 		if ((cp = strpbrk(cp, " \t")) != NULL)
   2444 			*cp++ = '\0';
   2445 	}
   2446 
   2447 	hints = *pai;
   2448 	hints.ai_flags = AI_NUMERICHOST;
   2449 	error = getaddrinfo(addr, NULL, &hints, &res0);
   2450 	if (error == 0) {
   2451 		for (res = res0; res; res = res->ai_next) {
   2452 			/* cover it up */
   2453 			res->ai_flags = pai->ai_flags;
   2454 
   2455 			if (pai->ai_flags & AI_CANONNAME)
   2456 				(void)get_canonname(pai, res, canonname);
   2457 		}
   2458 	} else
   2459 		res0 = NULL;
   2460 	if (res0) {
   2461 		cur->ai_next = res0;
   2462 		while (cur->ai_next)
   2463 			cur = cur->ai_next;
   2464 	}
   2465 
   2466 	if (nextline) {
   2467 		p = nextline;
   2468 		goto nextline;
   2469 	}
   2470 
   2471 done:
   2472 	return sentinel.ai_next;
   2473 }
   2474 
   2475 /*ARGSUSED*/
   2476 static int
   2477 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
   2478 {
   2479 	struct addrinfo sentinel, *cur;
   2480 	struct addrinfo *ai = NULL;
   2481 	char *ypbuf;
   2482 	int ypbuflen, r;
   2483 	const char *name;
   2484 	const struct addrinfo *pai;
   2485 	char *ypdomain;
   2486 
   2487 	if (_yp_check(&ypdomain) == 0)
   2488 		return NS_UNAVAIL;
   2489 
   2490 	name = va_arg(ap, char *);
   2491 	pai = va_arg(ap, const struct addrinfo *);
   2492 
   2493 	memset(&sentinel, 0, sizeof(sentinel));
   2494 	cur = &sentinel;
   2495 
   2496 	/* hosts.byname is only for IPv4 (Solaris8) */
   2497 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
   2498 		r = yp_match(ypdomain, "hosts.byname", name,
   2499 			(int)strlen(name), &ypbuf, &ypbuflen);
   2500 		if (r == 0) {
   2501 			struct addrinfo ai4;
   2502 
   2503 			ai4 = *pai;
   2504 			ai4.ai_family = AF_INET;
   2505 			ai = _yphostent(ypbuf, &ai4);
   2506 			if (ai) {
   2507 				cur->ai_next = ai;
   2508 				while (cur && cur->ai_next)
   2509 					cur = cur->ai_next;
   2510 			}
   2511 		}
   2512 		free(ypbuf);
   2513 	}
   2514 
   2515 	/* ipnodes.byname can hold both IPv4/v6 */
   2516 	r = yp_match(ypdomain, "ipnodes.byname", name,
   2517 		(int)strlen(name), &ypbuf, &ypbuflen);
   2518 	if (r == 0) {
   2519 		ai = _yphostent(ypbuf, pai);
   2520 		if (ai)
   2521 			cur->ai_next = ai;
   2522 		free(ypbuf);
   2523 	}
   2524 
   2525 	if (sentinel.ai_next == NULL) {
   2526 		h_errno = HOST_NOT_FOUND;
   2527 		return NS_NOTFOUND;
   2528 	}
   2529 	*((struct addrinfo **)rv) = sentinel.ai_next;
   2530 	return NS_SUCCESS;
   2531 }
   2532 #endif
   2533 
   2534 /* resolver logic */
   2535 
   2536 /*
   2537  * Formulate a normal query, send, and await answer.
   2538  * Returned answer is placed in supplied buffer "answer".
   2539  * Perform preliminary check of answer, returning success only
   2540  * if no error is indicated and the answer count is nonzero.
   2541  * Return the size of the response on success, -1 on error.
   2542  * Error number is left in h_errno.
   2543  *
   2544  * Caller must parse answer and determine whether it answers the question.
   2545  */
   2546 static int
   2547 res_queryN(const char *name, /* domain name */ struct res_target *target,
   2548     res_state statp)
   2549 {
   2550 	u_char buf[MAXPACKET];
   2551 	HEADER *hp;
   2552 	int n;
   2553 	struct res_target *t;
   2554 	int rcode;
   2555 	u_char *rdata;
   2556 	int ancount;
   2557 
   2558 	_DIAGASSERT(name != NULL);
   2559 	/* XXX: target may be NULL??? */
   2560 
   2561 	rcode = NOERROR;
   2562 	ancount = 0;
   2563 
   2564 	for (t = target; t; t = t->next) {
   2565 		int class, type;
   2566 		u_char *answer;
   2567 		int anslen;
   2568 		u_int oflags;
   2569 
   2570 		hp = (HEADER *)(void *)t->answer;
   2571 		oflags = statp->_flags;
   2572 
   2573 again:
   2574 		hp->rcode = NOERROR;	/* default */
   2575 
   2576 		/* make it easier... */
   2577 		class = t->qclass;
   2578 		type = t->qtype;
   2579 		answer = t->answer;
   2580 		anslen = t->anslen;
   2581 #ifdef DEBUG
   2582 		if (statp->options & RES_DEBUG)
   2583 			printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
   2584 #endif
   2585 
   2586 		n = res_nmkquery(statp, QUERY, name, class, type, NULL, 0, NULL,
   2587 		    buf, (int)sizeof(buf));
   2588 #ifdef RES_USE_EDNS0
   2589 		if (n > 0 && (statp->_flags & RES_F_EDNS0ERR) == 0 &&
   2590 		    (statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0) {
   2591 			n = res_nopt(statp, n, buf, (int)sizeof(buf), anslen);
   2592 			rdata = &buf[n];
   2593 			if (n > 0 && (statp->options & RES_NSID) != 0U) {
   2594 				n = res_nopt_rdata(statp, n, buf,
   2595 				    (int)sizeof(buf),
   2596 				    rdata, NS_OPT_NSID, 0, NULL);
   2597 			}
   2598 		}
   2599 #endif
   2600 		if (n <= 0) {
   2601 #ifdef DEBUG
   2602 			if (statp->options & RES_DEBUG)
   2603 				printf(";; res_nquery: mkquery failed\n");
   2604 #endif
   2605 			h_errno = NO_RECOVERY;
   2606 			return n;
   2607 		}
   2608 		n = res_nsend(statp, buf, n, answer, anslen);
   2609 		if (n < 0) {
   2610 #ifdef RES_USE_EDNS0
   2611 			/* if the query choked with EDNS0, retry without EDNS0 */
   2612 			if ((statp->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U &&
   2613 			    ((oflags ^ statp->_flags) & RES_F_EDNS0ERR) != 0) {
   2614 				statp->_flags |= RES_F_EDNS0ERR;
   2615 				if (statp->options & RES_DEBUG)
   2616 					printf(";; res_nquery: retry without EDNS0\n");
   2617 				goto again;
   2618 			}
   2619 #endif
   2620 #if 0
   2621 #ifdef DEBUG
   2622 			if (statp->options & RES_DEBUG)
   2623 				printf(";; res_query: send error\n");
   2624 #endif
   2625 			h_errno = TRY_AGAIN;
   2626 			return n;
   2627 #endif
   2628 		}
   2629 
   2630 		if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
   2631 			rcode = hp->rcode;	/* record most recent error */
   2632 #ifdef DEBUG
   2633 			if (statp->options & RES_DEBUG)
   2634 				printf(";; rcode = (%s), counts = an:%d ns:%d ar:%d\n",
   2635 				       p_rcode(hp->rcode),
   2636 				       ntohs(hp->ancount),
   2637 				       ntohs(hp->nscount),
   2638 				       ntohs(hp->arcount));
   2639 #endif
   2640 			continue;
   2641 		}
   2642 
   2643 		ancount += ntohs(hp->ancount);
   2644 
   2645 		t->n = n;
   2646 	}
   2647 
   2648 	if (ancount == 0) {
   2649 		switch (rcode) {
   2650 		case NXDOMAIN:
   2651 			h_errno = HOST_NOT_FOUND;
   2652 			break;
   2653 		case SERVFAIL:
   2654 			h_errno = TRY_AGAIN;
   2655 			break;
   2656 		case NOERROR:
   2657 			h_errno = NO_DATA;
   2658 			break;
   2659 		case FORMERR:
   2660 		case NOTIMP:
   2661 		case REFUSED:
   2662 		default:
   2663 			h_errno = NO_RECOVERY;
   2664 			break;
   2665 		}
   2666 		return -1;
   2667 	}
   2668 	return ancount;
   2669 }
   2670 
   2671 /*
   2672  * Formulate a normal query, send, and retrieve answer in supplied buffer.
   2673  * Return the size of the response on success, -1 on error.
   2674  * If enabled, implement search rules until answer or unrecoverable failure
   2675  * is detected.	 Error code, if any, is left in h_errno.
   2676  */
   2677 static int
   2678 res_searchN(const char *name, struct res_target *target, res_state res)
   2679 {
   2680 	const char *cp, * const *domain;
   2681 	HEADER *hp;
   2682 	u_int dots;
   2683 	char buf[MAXHOSTNAMELEN];
   2684 	int trailing_dot, ret, saved_herrno;
   2685 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
   2686 
   2687 	_DIAGASSERT(name != NULL);
   2688 	_DIAGASSERT(target != NULL);
   2689 
   2690 	hp = (HEADER *)(void *)target->answer;	/*XXX*/
   2691 
   2692 	errno = 0;
   2693 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
   2694 	dots = 0;
   2695 	for (cp = name; *cp; cp++)
   2696 		dots += (*cp == '.');
   2697 	trailing_dot = 0;
   2698 	if (cp > name && *--cp == '.')
   2699 		trailing_dot++;
   2700 
   2701 	/*
   2702 	 * if there aren't any dots, it could be a user-level alias
   2703 	 */
   2704 	if (!dots && (cp = res_hostalias(res, name, buf, sizeof(buf))) != NULL) {
   2705 		ret = res_queryN(cp, target, res);
   2706 		return ret;
   2707 	}
   2708 
   2709 	/*
   2710 	 * If there are dots in the name already, let's just give it a try
   2711 	 * 'as is'.  The threshold can be set with the "ndots" option.
   2712 	 */
   2713 	saved_herrno = -1;
   2714 	if (dots >= res->ndots) {
   2715 		ret = res_querydomainN(name, NULL, target, res);
   2716 		if (ret > 0)
   2717 			return ret;
   2718 		saved_herrno = h_errno;
   2719 		tried_as_is++;
   2720 	}
   2721 
   2722 	/*
   2723 	 * We do at least one level of search if
   2724 	 *	- there is no dot and RES_DEFNAME is set, or
   2725 	 *	- there is at least one dot, there is no trailing dot,
   2726 	 *	  and RES_DNSRCH is set.
   2727 	 */
   2728 	if ((!dots && (res->options & RES_DEFNAMES)) ||
   2729 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
   2730 		int done = 0;
   2731 
   2732 		for (domain = (const char * const *)res->dnsrch;
   2733 		   *domain && !done;
   2734 		   domain++) {
   2735 
   2736 			ret = res_querydomainN(name, *domain, target, res);
   2737 			if (ret > 0)
   2738 				return ret;
   2739 
   2740 			/*
   2741 			 * If no server present, give up.
   2742 			 * If name isn't found in this domain,
   2743 			 * keep trying higher domains in the search list
   2744 			 * (if that's enabled).
   2745 			 * On a NO_DATA error, keep trying, otherwise
   2746 			 * a wildcard entry of another type could keep us
   2747 			 * from finding this entry higher in the domain.
   2748 			 * If we get some other error (negative answer or
   2749 			 * server failure), then stop searching up,
   2750 			 * but try the input name below in case it's
   2751 			 * fully-qualified.
   2752 			 */
   2753 			if (errno == ECONNREFUSED) {
   2754 				h_errno = TRY_AGAIN;
   2755 				return -1;
   2756 			}
   2757 
   2758 			switch (h_errno) {
   2759 			case NO_DATA:
   2760 				got_nodata++;
   2761 				/* FALLTHROUGH */
   2762 			case HOST_NOT_FOUND:
   2763 				/* keep trying */
   2764 				break;
   2765 			case TRY_AGAIN:
   2766 				if (hp->rcode == SERVFAIL) {
   2767 					/* try next search element, if any */
   2768 					got_servfail++;
   2769 					break;
   2770 				}
   2771 				/* FALLTHROUGH */
   2772 			default:
   2773 				/* anything else implies that we're done */
   2774 				done++;
   2775 			}
   2776 			/*
   2777 			 * if we got here for some reason other than DNSRCH,
   2778 			 * we only wanted one iteration of the loop, so stop.
   2779 			 */
   2780 			if (!(res->options & RES_DNSRCH))
   2781 				done++;
   2782 		}
   2783 	}
   2784 
   2785 	/*
   2786 	 * if we have not already tried the name "as is", do that now.
   2787 	 * note that we do this regardless of how many dots were in the
   2788 	 * name or whether it ends with a dot.
   2789 	 */
   2790 	if (!tried_as_is) {
   2791 		ret = res_querydomainN(name, NULL, target, res);
   2792 		if (ret > 0)
   2793 			return ret;
   2794 	}
   2795 
   2796 	/*
   2797 	 * if we got here, we didn't satisfy the search.
   2798 	 * if we did an initial full query, return that query's h_errno
   2799 	 * (note that we wouldn't be here if that query had succeeded).
   2800 	 * else if we ever got a nodata, send that back as the reason.
   2801 	 * else send back meaningless h_errno, that being the one from
   2802 	 * the last DNSRCH we did.
   2803 	 */
   2804 	if (saved_herrno != -1)
   2805 		h_errno = saved_herrno;
   2806 	else if (got_nodata)
   2807 		h_errno = NO_DATA;
   2808 	else if (got_servfail)
   2809 		h_errno = TRY_AGAIN;
   2810 	return -1;
   2811 }
   2812 
   2813 /*
   2814  * Perform a call on res_query on the concatenation of name and domain,
   2815  * removing a trailing dot from name if domain is NULL.
   2816  */
   2817 static int
   2818 res_querydomainN(const char *name, const char *domain,
   2819     struct res_target *target, res_state res)
   2820 {
   2821 	char nbuf[MAXDNAME];
   2822 	const char *longname = nbuf;
   2823 	size_t n;
   2824 
   2825 	_DIAGASSERT(name != NULL);
   2826 	/* XXX: target may be NULL??? */
   2827 
   2828 #ifdef DEBUG
   2829 	if (res->options & RES_DEBUG)
   2830 		printf(";; res_querydomain(%s, %s)\n",
   2831 			name, domain?domain:"<Nil>");
   2832 #endif
   2833 	if (domain == NULL) {
   2834 		/*
   2835 		 * Check for trailing '.';
   2836 		 * copy without '.' if present.
   2837 		 */
   2838 		n = strlen(name);
   2839 		if (n + 1 > sizeof(nbuf)) {
   2840 			h_errno = NO_RECOVERY;
   2841 			return -1;
   2842 		}
   2843 		if (n > 0 && name[--n] == '.') {
   2844 			snprintf(nbuf, sizeof(nbuf), "%*s", (int)n, name);
   2845 		} else
   2846 			longname = name;
   2847 	} else {
   2848 		if ((size_t)snprintf(nbuf, sizeof(nbuf), "%s.%s",
   2849 				name, domain) >= sizeof(nbuf)) {
   2850 			h_errno = NO_RECOVERY;
   2851 			return -1;
   2852 		}
   2853 	}
   2854 	return res_queryN(longname, target, res);
   2855 }
   2856 
   2857 #ifdef TEST
   2858 int
   2859 main(int argc, char *argv[]) {
   2860 	struct addrinfo *ai, *sai;
   2861 	int i, e;
   2862 	char buf[1024];
   2863 
   2864 	for (i = 1; i < argc; i++) {
   2865 		if ((e = getaddrinfo(argv[i], NULL, NULL, &sai)) != 0)
   2866 			warnx("%s: %s", argv[i], gai_strerror(e));
   2867 		for (ai = sai; ai; ai = ai->ai_next) {
   2868 			sockaddr_snprintf(buf, sizeof(buf), "%a", ai->ai_addr);
   2869              		printf("flags=0x%x family=%d socktype=%d protocol=%d "
   2870 			    "addrlen=%zu addr=%s canonname=%s next=%p\n",
   2871 			    ai->ai_flags,
   2872              		    ai->ai_family,
   2873              		    ai->ai_socktype,
   2874              		    ai->ai_protocol,
   2875              		    (size_t)ai->ai_addrlen,
   2876 			    buf,
   2877 			    ai->ai_canonname,
   2878 			    ai->ai_next);
   2879 		}
   2880 		if (sai)
   2881 			freeaddrinfo(sai);
   2882 	}
   2883 	return 0;
   2884 }
   2885 #endif
   2886