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