Home | History | Annotate | Line # | Download | only in net
getaddrinfo.c revision 1.111
      1 /*	$NetBSD: getaddrinfo.c,v 1.111 2015/12/02 18:09:53 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.111 2015/12/02 18:09:53 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 <net/if.h>
     68 #include <netinet/in.h>
     69 #include <arpa/inet.h>
     70 #include <arpa/nameser.h>
     71 #include <assert.h>
     72 #include <ctype.h>
     73 #include <errno.h>
     74 #include <netdb.h>
     75 #include <resolv.h>
     76 #include <stddef.h>
     77 #include <stdio.h>
     78 #include <stdlib.h>
     79 #include <string.h>
     80 #include <unistd.h>
     81 #include <ifaddrs.h>
     82 
     83 #include <syslog.h>
     84 #include <stdarg.h>
     85 #include <nsswitch.h>
     86 
     87 #ifdef YP
     88 #include <rpc/rpc.h>
     89 #include <rpcsvc/yp_prot.h>
     90 #include <rpcsvc/ypclnt.h>
     91 #endif
     92 
     93 #include "servent.h"
     94 
     95 #ifndef RUMP_ACTION
     96 #ifdef __weak_alias
     97 __weak_alias(getaddrinfo,_getaddrinfo)
     98 __weak_alias(allocaddrinfo,_allocaddrinfo)
     99 __weak_alias(freeaddrinfo,_freeaddrinfo)
    100 __weak_alias(gai_strerror,_gai_strerror)
    101 #endif
    102 #endif
    103 
    104 #define SUCCESS 0
    105 #define ANY 0
    106 #define YES 1
    107 #define NO  0
    108 
    109 static const char in_addrany[] = { 0, 0, 0, 0 };
    110 static const char in_loopback[] = { 127, 0, 0, 1 };
    111 #ifdef INET6
    112 static const char in6_addrany[] = {
    113 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    114 };
    115 static const char in6_loopback[] = {
    116 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
    117 };
    118 #endif
    119 
    120 static const struct afd {
    121 	int a_af;
    122 	int a_addrlen;
    123 	int a_socklen;
    124 	int a_off;
    125 	const char *a_addrany;
    126 	const char *a_loopback;
    127 	int a_scoped;
    128 } afdl [] = {
    129 #ifdef INET6
    130 	{PF_INET6, sizeof(struct in6_addr),
    131 	 sizeof(struct sockaddr_in6),
    132 	 offsetof(struct sockaddr_in6, sin6_addr),
    133 	 in6_addrany, in6_loopback, 1},
    134 #endif
    135 	{PF_INET, sizeof(struct in_addr),
    136 	 sizeof(struct sockaddr_in),
    137 	 offsetof(struct sockaddr_in, sin_addr),
    138 	 in_addrany, in_loopback, 0},
    139 	{0, 0, 0, 0, NULL, NULL, 0},
    140 };
    141 
    142 struct explore {
    143 	int e_af;
    144 	int e_socktype;
    145 	int e_protocol;
    146 	const char *e_protostr;
    147 	int e_wild;
    148 #define WILD_AF(ex)		((ex)->e_wild & 0x01)
    149 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
    150 #define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
    151 };
    152 
    153 static const struct explore explore[] = {
    154 #if 0
    155 	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
    156 #endif
    157 #ifdef INET6
    158 	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    159 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    160 	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
    161 #endif
    162 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    163 	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    164 	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
    165 	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    166 	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    167 	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
    168 	{ -1, 0, 0, NULL, 0 },
    169 };
    170 
    171 #ifdef INET6
    172 #define PTON_MAX	16
    173 #else
    174 #define PTON_MAX	4
    175 #endif
    176 
    177 static const ns_src default_dns_files[] = {
    178 	{ NSSRC_FILES,	NS_SUCCESS },
    179 	{ NSSRC_DNS,	NS_SUCCESS },
    180 	{ 0, 0 }
    181 };
    182 
    183 #define MAXPACKET	(64*1024)
    184 
    185 typedef union {
    186 	HEADER hdr;
    187 	u_char buf[MAXPACKET];
    188 } querybuf;
    189 
    190 struct res_target {
    191 	struct res_target *next;
    192 	const char *name;	/* domain name */
    193 	int qclass, qtype;	/* class and type of query */
    194 	u_char *answer;		/* buffer to put answer */
    195 	int anslen;		/* size of answer buffer */
    196 	int n;			/* result length */
    197 };
    198 
    199 struct srvinfo {
    200        struct srvinfo *next;
    201        char name[MAXDNAME];
    202        int port, pri, weight;
    203 };
    204 
    205 static int gai_srvok(const char *);
    206 static int str2number(const char *);
    207 static int explore_fqdn(const struct addrinfo *, const char *,
    208     const char *, struct addrinfo **, struct servent_data *);
    209 static int explore_null(const struct addrinfo *,
    210     const char *, struct addrinfo **, struct servent_data *);
    211 static int explore_numeric(const struct addrinfo *, const char *,
    212     const char *, struct addrinfo **, const char *, struct servent_data *);
    213 static int explore_numeric_scope(const struct addrinfo *, const char *,
    214     const char *, struct addrinfo **, struct servent_data *);
    215 static int get_canonname(const struct addrinfo *,
    216     struct addrinfo *, const char *);
    217 static struct addrinfo *get_ai(const struct addrinfo *,
    218     const struct afd *, const char *);
    219 static int get_portmatch(const struct addrinfo *, const char *,
    220     struct servent_data *);
    221 static int get_port(const struct addrinfo *, const char *, int,
    222     struct servent_data *);
    223 static const struct afd *find_afd(int);
    224 static int addrconfig(uint64_t *);
    225 #ifdef INET6
    226 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
    227 #endif
    228 
    229 static struct addrinfo *getanswer(res_state, const querybuf *, int,
    230     const char *, int, const struct addrinfo *);
    231 static void aisort(struct addrinfo *s, res_state res);
    232 static struct addrinfo * _dns_query(struct res_target *,
    233     const struct addrinfo *, res_state, int);
    234 static struct addrinfo * _dns_srv_lookup(const char *, const char *,
    235     const struct addrinfo *);
    236 static struct addrinfo * _dns_host_lookup(const char *,
    237     const struct addrinfo *);
    238 static int _dns_getaddrinfo(void *, void *, va_list);
    239 static void _sethtent(FILE **);
    240 static void _endhtent(FILE **);
    241 static struct addrinfo *_gethtent(FILE **, const char *,
    242     const struct addrinfo *);
    243 static int _files_getaddrinfo(void *, void *, va_list);
    244 #ifdef YP
    245 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
    246 static int _yp_getaddrinfo(void *, void *, va_list);
    247 #endif
    248 
    249 static int res_queryN(const char *, struct res_target *, res_state);
    250 static int res_searchN(const char *, struct res_target *, res_state);
    251 static int res_querydomainN(const char *, const char *,
    252     struct res_target *, res_state);
    253 
    254 static const char * const ai_errlist[] = {
    255 	"Success",
    256 	"Address family for hostname not supported",	/* EAI_ADDRFAMILY */
    257 	"Temporary failure in name resolution",		/* EAI_AGAIN	  */
    258 	"Invalid value for ai_flags",			/* EAI_BADFLAGS	  */
    259 	"Non-recoverable failure in name resolution",	/* EAI_FAIL	  */
    260 	"ai_family not supported",			/* EAI_FAMILY	  */
    261 	"Memory allocation failure",			/* EAI_MEMORY	  */
    262 	"No address associated with hostname",		/* EAI_NODATA	  */
    263 	"hostname nor servname provided, or not known", /* EAI_NONAME	  */
    264 	"servname not supported for ai_socktype",	/* EAI_SERVICE	  */
    265 	"ai_socktype not supported",			/* EAI_SOCKTYPE	  */
    266 	"System error returned in errno",		/* EAI_SYSTEM	  */
    267 	"Invalid value for hints",			/* EAI_BADHINTS	  */
    268 	"Resolved protocol is unknown",			/* EAI_PROTOCOL	  */
    269 	"Argument buffer overflow",			/* EAI_OVERFLOW	  */
    270 	"Unknown error",				/* EAI_MAX	  */
    271 };
    272 
    273 /* XXX macros that make external reference is BAD. */
    274 
    275 #define GET_AI(ai, afd, addr)					\
    276 do {								\
    277 	/* external reference: pai, error, and label free */	\
    278 	(ai) = get_ai(pai, (afd), (addr));			\
    279 	if ((ai) == NULL) {					\
    280 		error = EAI_MEMORY;				\
    281 		goto free;					\
    282 	}							\
    283 } while (/*CONSTCOND*/0)
    284 
    285 #define GET_PORT(ai, serv, svd)					\
    286 do {								\
    287 	/* external reference: error and label free */		\
    288 	error = get_port((ai), (serv), 0, (svd));		\
    289 	if (error != 0)						\
    290 		goto free;					\
    291 } while (/*CONSTCOND*/0)
    292 
    293 #define GET_CANONNAME(ai, str)					\
    294 do {								\
    295 	/* external reference: pai, error and label free */	\
    296 	error = get_canonname(pai, (ai), (str));		\
    297 	if (error != 0)						\
    298 		goto free;					\
    299 } while (/*CONSTCOND*/0)
    300 
    301 #define ERR(err)						\
    302 do {								\
    303 	/* external reference: error, and label bad */		\
    304 	error = (err);						\
    305 	goto bad;						\
    306 	/*NOTREACHED*/						\
    307 } while (/*CONSTCOND*/0)
    308 
    309 #define MATCH_FAMILY(x, y, w)						\
    310 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC ||	\
    311 	    (y) == PF_UNSPEC)))
    312 #define MATCH(x, y, w)							\
    313 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
    314 
    315 const char *
    316 gai_strerror(int ecode)
    317 {
    318 	if (ecode < 0 || ecode > EAI_MAX)
    319 		ecode = EAI_MAX;
    320 	return ai_errlist[ecode];
    321 }
    322 
    323 void
    324 freeaddrinfo(struct addrinfo *ai)
    325 {
    326 	struct addrinfo *next;
    327 
    328 	_DIAGASSERT(ai != NULL);
    329 
    330 	do {
    331 		next = ai->ai_next;
    332 		if (ai->ai_canonname)
    333 			free(ai->ai_canonname);
    334 		/* no need to free(ai->ai_addr) */
    335 		free(ai);
    336 		ai = next;
    337 	} while (ai);
    338 }
    339 
    340 /*
    341  * We don't want localization to affect us
    342  */
    343 #define PERIOD '.'
    344 #define hyphenchar(c) ((c) == '-')
    345 #define periodchar(c) ((c) == PERIOD)
    346 #define underschar(c) ((c) == '_')
    347 #define alphachar(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
    348 #define digitchar(c) ((c) >= '0' && (c) <= '9')
    349 
    350 #define firstchar(c)  (alphachar(c) || digitchar(c) || underschar(c))
    351 #define lastchar(c)   (alphachar(c) || digitchar(c))
    352 #define middlechar(c) (lastchar(c) || hyphenchar(c))
    353 
    354 static int
    355 gai_srvok(const char *dn)
    356 {
    357 	int nch, pch, ch;
    358 
    359 	for (pch = PERIOD, nch = ch = *dn++; ch != '\0'; pch = ch, ch = nch) {
    360 		if (periodchar(ch))
    361 			continue;
    362 		if (periodchar(pch)) {
    363 			if (!firstchar(ch))
    364 				return 0;
    365 		} else if (periodchar(nch) || nch == '\0') {
    366 			if (!lastchar(ch))
    367 				return 0;
    368 		} else if (!middlechar(ch))
    369 			return 0;
    370        }
    371        return 1;
    372 }
    373 
    374 static in_port_t *
    375 getport(struct addrinfo *ai) {
    376 	static in_port_t p;
    377 
    378 	switch (ai->ai_family) {
    379 	case AF_INET:
    380 		return &((struct sockaddr_in *)(void *)ai->ai_addr)->sin_port;
    381 #ifdef INET6
    382 	case AF_INET6:
    383 		return &((struct sockaddr_in6 *)(void *)ai->ai_addr)->sin6_port;
    384 #endif
    385 	default:
    386 		p = 0;
    387 		/* XXX: abort()? */
    388 		return &p;
    389 	}
    390 }
    391 
    392 static int
    393 str2number(const char *p)
    394 {
    395 	char *ep;
    396 	unsigned long v;
    397 
    398 	_DIAGASSERT(p != NULL);
    399 
    400 	if (*p == '\0')
    401 		return -1;
    402 	ep = NULL;
    403 	errno = 0;
    404 	v = strtoul(p, &ep, 10);
    405 	if (errno == 0 && ep && *ep == '\0' && v <= INT_MAX)
    406 		return (int)v;
    407 	else
    408 		return -1;
    409 }
    410 
    411 int
    412 getaddrinfo(const char *hostname, const char *servname,
    413     const struct addrinfo *hints, struct addrinfo **res)
    414 {
    415 	struct addrinfo sentinel;
    416 	struct addrinfo *cur;
    417 	int error = 0;
    418 	struct addrinfo ai;
    419 	struct addrinfo ai0;
    420 	struct addrinfo *pai;
    421 	const struct explore *ex;
    422 	struct servent_data svd;
    423 	uint64_t mask = (uint64_t)~0ULL;
    424 
    425 	/* hostname is allowed to be NULL */
    426 	/* servname is allowed to be NULL */
    427 	/* hints is allowed to be NULL */
    428 	_DIAGASSERT(res != NULL);
    429 
    430 	(void)memset(&svd, 0, sizeof(svd));
    431 	memset(&sentinel, 0, sizeof(sentinel));
    432 	cur = &sentinel;
    433 	memset(&ai, 0, sizeof(ai));
    434 	pai = &ai;
    435 	pai->ai_flags = 0;
    436 	pai->ai_family = PF_UNSPEC;
    437 	pai->ai_socktype = ANY;
    438 	pai->ai_protocol = ANY;
    439 	pai->ai_addrlen = 0;
    440 	pai->ai_canonname = NULL;
    441 	pai->ai_addr = NULL;
    442 	pai->ai_next = NULL;
    443 
    444 	if (hostname == NULL && servname == NULL)
    445 		return EAI_NONAME;
    446 	if (hints) {
    447 		/* error check for hints */
    448 		if (hints->ai_addrlen || hints->ai_canonname ||
    449 		    hints->ai_addr || hints->ai_next)
    450 			ERR(EAI_BADHINTS); /* xxx */
    451 		if (hints->ai_flags & ~AI_MASK)
    452 			ERR(EAI_BADFLAGS);
    453 		switch (hints->ai_family) {
    454 		case PF_UNSPEC:
    455 		case PF_INET:
    456 #ifdef INET6
    457 		case PF_INET6:
    458 #endif
    459 			break;
    460 		default:
    461 			ERR(EAI_FAMILY);
    462 		}
    463 		memcpy(pai, hints, sizeof(*pai));
    464 
    465 		/*
    466 		 * if both socktype/protocol are specified, check if they
    467 		 * are meaningful combination.
    468 		 */
    469 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
    470 			for (ex = explore; ex->e_af >= 0; ex++) {
    471 				if (pai->ai_family != ex->e_af)
    472 					continue;
    473 				if (ex->e_socktype == ANY)
    474 					continue;
    475 				if (ex->e_protocol == ANY)
    476 					continue;
    477 				if (pai->ai_socktype == ex->e_socktype
    478 				 && pai->ai_protocol != ex->e_protocol) {
    479 					ERR(EAI_BADHINTS);
    480 				}
    481 			}
    482 		}
    483 	}
    484 
    485 	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && addrconfig(&mask) == -1)
    486 		ERR(EAI_FAIL);
    487 
    488 	/*
    489 	 * check for special cases.  (1) numeric servname is disallowed if
    490 	 * socktype/protocol are left unspecified. (2) servname is disallowed
    491 	 * for raw and other inet{,6} sockets.
    492 	 */
    493 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
    494 #ifdef PF_INET6
    495 	 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
    496 #endif
    497 	    ) {
    498 		ai0 = *pai;	/* backup *pai */
    499 
    500 		if (pai->ai_family == PF_UNSPEC) {
    501 #ifdef PF_INET6
    502 			pai->ai_family = PF_INET6;
    503 #else
    504 			pai->ai_family = PF_INET;
    505 #endif
    506 		}
    507 		error = get_portmatch(pai, servname, &svd);
    508 		if (error)
    509 			goto bad;
    510 
    511 		*pai = ai0;
    512 	}
    513 
    514 	ai0 = *pai;
    515 
    516 	/* NULL hostname, or numeric hostname */
    517 	for (ex = explore; ex->e_af >= 0; ex++) {
    518 		*pai = ai0;
    519 
    520 		/* ADDRCONFIG check */
    521 		if ((((uint64_t)1 << ex->e_af) & mask) == 0)
    522 			continue;
    523 
    524 		/* PF_UNSPEC entries are prepared for DNS queries only */
    525 		if (ex->e_af == PF_UNSPEC)
    526 			continue;
    527 
    528 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    529 			continue;
    530 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
    531 			continue;
    532 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
    533 			continue;
    534 		if (pai->ai_family == PF_UNSPEC)
    535 			pai->ai_family = ex->e_af;
    536 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    537 			pai->ai_socktype = ex->e_socktype;
    538 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    539 			pai->ai_protocol = ex->e_protocol;
    540 
    541 		if (hostname == NULL)
    542 			error = explore_null(pai, servname, &cur->ai_next,
    543 			    &svd);
    544 		else
    545 			error = explore_numeric_scope(pai, hostname, servname,
    546 			    &cur->ai_next, &svd);
    547 
    548 		if (error)
    549 			goto free;
    550 
    551 		while (cur->ai_next)
    552 			cur = cur->ai_next;
    553 	}
    554 
    555 	/*
    556 	 * XXX
    557 	 * If numeric representation of AF1 can be interpreted as FQDN
    558 	 * representation of AF2, we need to think again about the code below.
    559 	 */
    560 	if (sentinel.ai_next)
    561 		goto good;
    562 
    563 	if (hostname == NULL)
    564 		ERR(EAI_NODATA);
    565 	if (pai->ai_flags & AI_NUMERICHOST)
    566 		ERR(EAI_NONAME);
    567 
    568 	/*
    569 	 * hostname as alphabetical name.
    570 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
    571 	 * outer loop by AFs.
    572 	 */
    573 	for (ex = explore; ex->e_af >= 0; ex++) {
    574 		*pai = ai0;
    575 
    576 
    577 		/* ADDRCONFIG check */
    578 		/* PF_UNSPEC entries are prepared for DNS queries only */
    579 		if (ex->e_af != PF_UNSPEC &&
    580 		    (((uint64_t)1 << ex->e_af) & mask) == 0)
    581 			continue;
    582 
    583 		/* require exact match for family field */
    584 		if (pai->ai_family != ex->e_af)
    585 			continue;
    586 
    587 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
    588 				WILD_SOCKTYPE(ex))) {
    589 			continue;
    590 		}
    591 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
    592 				WILD_PROTOCOL(ex))) {
    593 			continue;
    594 		}
    595 
    596 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    597 			pai->ai_socktype = ex->e_socktype;
    598 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    599 			pai->ai_protocol = ex->e_protocol;
    600 
    601 		error = explore_fqdn(pai, hostname, servname, &cur->ai_next,
    602 		    &svd);
    603 
    604 		while (cur && cur->ai_next)
    605 			cur = cur->ai_next;
    606 	}
    607 
    608 	/* XXX */
    609 	if (sentinel.ai_next)
    610 		error = 0;
    611 
    612 	if (error)
    613 		goto free;
    614 
    615 	if (sentinel.ai_next) {
    616  good:
    617 		endservent_r(&svd);
    618 		*res = sentinel.ai_next;
    619 		return SUCCESS;
    620 	} else
    621 		error = EAI_FAIL;
    622  free:
    623  bad:
    624 	endservent_r(&svd);
    625 	if (sentinel.ai_next)
    626 		freeaddrinfo(sentinel.ai_next);
    627 	*res = NULL;
    628 	return error;
    629 }
    630 
    631 /*
    632  * FQDN hostname, DNS lookup
    633  */
    634 static int
    635 explore_fqdn(const struct addrinfo *pai, const char *hostname,
    636     const char *servname, struct addrinfo **res, struct servent_data *svd)
    637 {
    638 	struct addrinfo *result;
    639 	struct addrinfo *cur;
    640 	int error = 0;
    641 	static const ns_dtab dtab[] = {
    642 		NS_FILES_CB(_files_getaddrinfo, NULL)
    643 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
    644 		NS_NIS_CB(_yp_getaddrinfo, NULL)
    645 		NS_NULL_CB
    646 	};
    647 
    648 	_DIAGASSERT(pai != NULL);
    649 	/* hostname may be NULL */
    650 	/* servname may be NULL */
    651 	_DIAGASSERT(res != NULL);
    652 
    653 	result = NULL;
    654 
    655 	/*
    656 	 * if the servname does not match socktype/protocol, ignore it.
    657 	 */
    658 	if (get_portmatch(pai, servname, svd) != 0)
    659 		return 0;
    660 
    661 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
    662 	    default_dns_files, hostname, pai, servname)) {
    663 	case NS_TRYAGAIN:
    664 		error = EAI_AGAIN;
    665 		goto free;
    666 	case NS_UNAVAIL:
    667 		error = EAI_FAIL;
    668 		goto free;
    669 	case NS_NOTFOUND:
    670 		error = EAI_NONAME;
    671 		goto free;
    672 	case NS_SUCCESS:
    673 		error = 0;
    674 		for (cur = result; cur; cur = cur->ai_next) {
    675 			/* Check for already filled port. */
    676 			if (*getport(cur))
    677 				continue;
    678 			GET_PORT(cur, servname, svd);
    679 			/* canonname should be filled already */
    680 		}
    681 		break;
    682 	}
    683 
    684 	*res = result;
    685 
    686 	return 0;
    687 
    688 free:
    689 	if (result)
    690 		freeaddrinfo(result);
    691 	return error;
    692 }
    693 
    694 /*
    695  * hostname == NULL.
    696  * passive socket -> anyaddr (0.0.0.0 or ::)
    697  * non-passive socket -> localhost (127.0.0.1 or ::1)
    698  */
    699 static int
    700 explore_null(const struct addrinfo *pai, const char *servname,
    701     struct addrinfo **res, struct servent_data *svd)
    702 {
    703 	int s;
    704 	const struct afd *afd;
    705 	struct addrinfo *cur;
    706 	struct addrinfo sentinel;
    707 	int error;
    708 
    709 	_DIAGASSERT(pai != NULL);
    710 	/* servname may be NULL */
    711 	_DIAGASSERT(res != NULL);
    712 
    713 	*res = NULL;
    714 	sentinel.ai_next = NULL;
    715 	cur = &sentinel;
    716 
    717 	/*
    718 	 * filter out AFs that are not supported by the kernel
    719 	 * XXX errno?
    720 	 */
    721 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    722 	if (s < 0) {
    723 		if (errno != EMFILE)
    724 			return 0;
    725 	} else
    726 		close(s);
    727 
    728 	/*
    729 	 * if the servname does not match socktype/protocol, ignore it.
    730 	 */
    731 	if (get_portmatch(pai, servname, svd) != 0)
    732 		return 0;
    733 
    734 	afd = find_afd(pai->ai_family);
    735 	if (afd == NULL)
    736 		return 0;
    737 
    738 	if (pai->ai_flags & AI_PASSIVE) {
    739 		GET_AI(cur->ai_next, afd, afd->a_addrany);
    740 		/* xxx meaningless?
    741 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
    742 		 */
    743 		GET_PORT(cur->ai_next, servname, svd);
    744 	} else {
    745 		GET_AI(cur->ai_next, afd, afd->a_loopback);
    746 		/* xxx meaningless?
    747 		 * GET_CANONNAME(cur->ai_next, "localhost");
    748 		 */
    749 		GET_PORT(cur->ai_next, servname, svd);
    750 	}
    751 	cur = cur->ai_next;
    752 
    753 	*res = sentinel.ai_next;
    754 	return 0;
    755 
    756 free:
    757 	if (sentinel.ai_next)
    758 		freeaddrinfo(sentinel.ai_next);
    759 	return error;
    760 }
    761 
    762 /*
    763  * numeric hostname
    764  */
    765 static int
    766 explore_numeric(const struct addrinfo *pai, const char *hostname,
    767     const char *servname, struct addrinfo **res, const char *canonname,
    768     struct servent_data *svd)
    769 {
    770 	const struct afd *afd;
    771 	struct addrinfo *cur;
    772 	struct addrinfo sentinel;
    773 	int error;
    774 	char pton[PTON_MAX];
    775 
    776 	_DIAGASSERT(pai != NULL);
    777 	/* hostname may be NULL */
    778 	/* servname may be NULL */
    779 	_DIAGASSERT(res != NULL);
    780 
    781 	*res = NULL;
    782 	sentinel.ai_next = NULL;
    783 	cur = &sentinel;
    784 
    785 	/*
    786 	 * if the servname does not match socktype/protocol, ignore it.
    787 	 */
    788 	if (get_portmatch(pai, servname, svd) != 0)
    789 		return 0;
    790 
    791 	afd = find_afd(pai->ai_family);
    792 	if (afd == NULL)
    793 		return 0;
    794 
    795 	switch (afd->a_af) {
    796 #if 0 /*X/Open spec*/
    797 	case AF_INET:
    798 		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
    799 			if (pai->ai_family == afd->a_af ||
    800 			    pai->ai_family == PF_UNSPEC /*?*/) {
    801 				GET_AI(cur->ai_next, afd, pton);
    802 				GET_PORT(cur->ai_next, servname, svd);
    803 				if ((pai->ai_flags & AI_CANONNAME)) {
    804 					/*
    805 					 * Set the numeric address itself as
    806 					 * the canonical name, based on a
    807 					 * clarification in rfc2553bis-03.
    808 					 */
    809 					GET_CANONNAME(cur->ai_next, canonname);
    810 				}
    811 				while (cur && cur->ai_next)
    812 					cur = cur->ai_next;
    813 			} else
    814 				ERR(EAI_FAMILY);	/*xxx*/
    815 		}
    816 		break;
    817 #endif
    818 	default:
    819 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
    820 			if (pai->ai_family == afd->a_af ||
    821 			    pai->ai_family == PF_UNSPEC /*?*/) {
    822 				GET_AI(cur->ai_next, afd, pton);
    823 				GET_PORT(cur->ai_next, servname, svd);
    824 				if ((pai->ai_flags & AI_CANONNAME)) {
    825 					/*
    826 					 * Set the numeric address itself as
    827 					 * the canonical name, based on a
    828 					 * clarification in rfc2553bis-03.
    829 					 */
    830 					GET_CANONNAME(cur->ai_next, canonname);
    831 				}
    832 				while (cur->ai_next)
    833 					cur = cur->ai_next;
    834 			} else
    835 				ERR(EAI_FAMILY);	/*xxx*/
    836 		}
    837 		break;
    838 	}
    839 
    840 	*res = sentinel.ai_next;
    841 	return 0;
    842 
    843 free:
    844 bad:
    845 	if (sentinel.ai_next)
    846 		freeaddrinfo(sentinel.ai_next);
    847 	return error;
    848 }
    849 
    850 /*
    851  * numeric hostname with scope
    852  */
    853 static int
    854 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
    855     const char *servname, struct addrinfo **res, struct servent_data *svd)
    856 {
    857 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
    858 	return explore_numeric(pai, hostname, servname, res, hostname, svd);
    859 #else
    860 	const struct afd *afd;
    861 	struct addrinfo *cur;
    862 	int error;
    863 	char *cp, *hostname2 = NULL, *scope, *addr;
    864 	struct sockaddr_in6 *sin6;
    865 
    866 	_DIAGASSERT(pai != NULL);
    867 	/* hostname may be NULL */
    868 	/* servname may be NULL */
    869 	_DIAGASSERT(res != NULL);
    870 
    871 	/*
    872 	 * if the servname does not match socktype/protocol, ignore it.
    873 	 */
    874 	if (get_portmatch(pai, servname, svd) != 0)
    875 		return 0;
    876 
    877 	afd = find_afd(pai->ai_family);
    878 	if (afd == NULL)
    879 		return 0;
    880 
    881 	if (!afd->a_scoped)
    882 		return explore_numeric(pai, hostname, servname, res, hostname,
    883 		    svd);
    884 
    885 	cp = strchr(hostname, SCOPE_DELIMITER);
    886 	if (cp == NULL)
    887 		return explore_numeric(pai, hostname, servname, res, hostname,
    888 		    svd);
    889 
    890 	/*
    891 	 * Handle special case of <scoped_address><delimiter><scope id>
    892 	 */
    893 	hostname2 = strdup(hostname);
    894 	if (hostname2 == NULL)
    895 		return EAI_MEMORY;
    896 	/* terminate at the delimiter */
    897 	hostname2[cp - hostname] = '\0';
    898 	addr = hostname2;
    899 	scope = cp + 1;
    900 
    901 	error = explore_numeric(pai, addr, servname, res, hostname, svd);
    902 	if (error == 0) {
    903 		u_int32_t scopeid;
    904 
    905 		for (cur = *res; cur; cur = cur->ai_next) {
    906 			if (cur->ai_family != AF_INET6)
    907 				continue;
    908 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
    909 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
    910 				free(hostname2);
    911 				return(EAI_NODATA); /* XXX: is return OK? */
    912 			}
    913 			sin6->sin6_scope_id = scopeid;
    914 		}
    915 	}
    916 
    917 	free(hostname2);
    918 
    919 	return error;
    920 #endif
    921 }
    922 
    923 static int
    924 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
    925 {
    926 
    927 	_DIAGASSERT(pai != NULL);
    928 	_DIAGASSERT(ai != NULL);
    929 	_DIAGASSERT(str != NULL);
    930 
    931 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
    932 		ai->ai_canonname = strdup(str);
    933 		if (ai->ai_canonname == NULL)
    934 			return EAI_MEMORY;
    935 	}
    936 	return 0;
    937 }
    938 
    939 struct addrinfo *
    940 allocaddrinfo(socklen_t addrlen)
    941 {
    942 	struct addrinfo *ai;
    943 
    944 	ai = calloc(sizeof(struct addrinfo) + addrlen, 1);
    945 	if (ai) {
    946 		ai->ai_addr = (void *)(ai+1);
    947 		ai->ai_addrlen = ai->ai_addr->sa_len = addrlen;
    948 	}
    949 
    950 	return ai;
    951 }
    952 
    953 static struct addrinfo *
    954 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
    955 {
    956 	char *p;
    957 	struct addrinfo *ai;
    958 	struct sockaddr *save;
    959 
    960 	_DIAGASSERT(pai != NULL);
    961 	_DIAGASSERT(afd != NULL);
    962 	_DIAGASSERT(addr != NULL);
    963 
    964 	ai = allocaddrinfo((socklen_t)afd->a_socklen);
    965 	if (ai == NULL)
    966 		return NULL;
    967 
    968 	save = ai->ai_addr;
    969 	memcpy(ai, pai, sizeof(struct addrinfo));
    970 
    971 	/* since we just overwrote all of ai, we have
    972 	   to restore ai_addr and ai_addrlen */
    973 	ai->ai_addr = save;
    974 	ai->ai_addrlen = (socklen_t)afd->a_socklen;
    975 
    976 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
    977 	p = (char *)(void *)(ai->ai_addr);
    978 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
    979 	return ai;
    980 }
    981 
    982 static int
    983 get_portmatch(const struct addrinfo *ai, const char *servname,
    984     struct servent_data *svd)
    985 {
    986 
    987 	_DIAGASSERT(ai != NULL);
    988 	/* servname may be NULL */
    989 
    990 	return get_port(ai, servname, 1, svd);
    991 }
    992 
    993 static int
    994 get_port(const struct addrinfo *ai, const char *servname, int matchonly,
    995     struct servent_data *svd)
    996 {
    997 	const char *proto;
    998 	struct servent *sp;
    999 	int port;
   1000 	int allownumeric;
   1001 
   1002 	_DIAGASSERT(ai != NULL);
   1003 	/* servname may be NULL */
   1004 
   1005 	if (servname == NULL)
   1006 		return 0;
   1007 	switch (ai->ai_family) {
   1008 	case AF_INET:
   1009 #ifdef AF_INET6
   1010 	case AF_INET6:
   1011 #endif
   1012 		break;
   1013 	default:
   1014 		return 0;
   1015 	}
   1016 
   1017 	switch (ai->ai_socktype) {
   1018 	case SOCK_RAW:
   1019 		return EAI_SERVICE;
   1020 	case SOCK_DGRAM:
   1021 	case SOCK_STREAM:
   1022 		allownumeric = 1;
   1023 		break;
   1024 	case ANY:
   1025 		/*
   1026 		 * This was 0.	It is now 1 so that queries specifying
   1027 		 * a NULL hint, or hint without socktype (but, hopefully,
   1028 		 * with protocol) and numeric address actually work.
   1029 		 */
   1030 		allownumeric = 1;
   1031 		break;
   1032 	default:
   1033 		return EAI_SOCKTYPE;
   1034 	}
   1035 
   1036 	port = str2number(servname);
   1037 	if (port >= 0) {
   1038 		if (!allownumeric)
   1039 			return EAI_SERVICE;
   1040 		if (port < 0 || port > 65535)
   1041 			return EAI_SERVICE;
   1042 		port = htons(port);
   1043 	} else {
   1044 		struct servent sv;
   1045 		if (ai->ai_flags & AI_NUMERICSERV)
   1046 			return EAI_NONAME;
   1047 
   1048 		switch (ai->ai_socktype) {
   1049 		case SOCK_DGRAM:
   1050 			proto = "udp";
   1051 			break;
   1052 		case SOCK_STREAM:
   1053 			proto = "tcp";
   1054 			break;
   1055 		default:
   1056 			proto = NULL;
   1057 			break;
   1058 		}
   1059 
   1060 		sp = getservbyname_r(servname, proto, &sv, svd);
   1061 		if (sp == NULL)
   1062 			return EAI_SERVICE;
   1063 		port = sp->s_port;
   1064 	}
   1065 
   1066 	if (!matchonly)
   1067 		*getport(__UNCONST(ai)) = port;
   1068 	return 0;
   1069 }
   1070 
   1071 static const struct afd *
   1072 find_afd(int af)
   1073 {
   1074 	const struct afd *afd;
   1075 
   1076 	if (af == PF_UNSPEC)
   1077 		return NULL;
   1078 	for (afd = afdl; afd->a_af; afd++) {
   1079 		if (afd->a_af == af)
   1080 			return afd;
   1081 	}
   1082 	return NULL;
   1083 }
   1084 
   1085 /*
   1086  * AI_ADDRCONFIG check: Build a mask containing a bit set for each address
   1087  * family configured in the system.
   1088  *
   1089  */
   1090 static int
   1091 addrconfig(uint64_t *mask)
   1092 {
   1093 	struct ifaddrs *ifaddrs, *ifa;
   1094 
   1095 	if (getifaddrs(&ifaddrs) == -1)
   1096 		return -1;
   1097 
   1098 	*mask = 0;
   1099 	for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next)
   1100 		if (ifa->ifa_addr && (ifa->ifa_flags & IFF_UP)) {
   1101 			_DIAGASSERT(ifa->ifa_addr->sa_family < 64);
   1102 			*mask |= (uint64_t)1 << ifa->ifa_addr->sa_family;
   1103 		}
   1104 
   1105 	freeifaddrs(ifaddrs);
   1106 	return 0;
   1107 }
   1108 
   1109 #ifdef INET6
   1110 /* convert a string to a scope identifier. XXX: IPv6 specific */
   1111 static int
   1112 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
   1113 {
   1114 	u_long lscopeid;
   1115 	struct in6_addr *a6;
   1116 	char *ep;
   1117 
   1118 	_DIAGASSERT(scope != NULL);
   1119 	_DIAGASSERT(sin6 != NULL);
   1120 	_DIAGASSERT(scopeid != NULL);
   1121 
   1122 	a6 = &sin6->sin6_addr;
   1123 
   1124 	/* empty scopeid portion is invalid */
   1125 	if (*scope == '\0')
   1126 		return -1;
   1127 
   1128 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
   1129 		/*
   1130 		 * We currently assume a one-to-one mapping between links
   1131 		 * and interfaces, so we simply use interface indices for
   1132 		 * like-local scopes.
   1133 		 */
   1134 		*scopeid = if_nametoindex(scope);
   1135 		if (*scopeid == 0)
   1136 			goto trynumeric;
   1137 		return 0;
   1138 	}
   1139 
   1140 	/* still unclear about literal, allow numeric only - placeholder */
   1141 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
   1142 		goto trynumeric;
   1143 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
   1144 		goto trynumeric;
   1145 	else
   1146 		goto trynumeric;	/* global */
   1147 
   1148 	/* try to convert to a numeric id as a last resort */
   1149   trynumeric:
   1150 	errno = 0;
   1151 	lscopeid = strtoul(scope, &ep, 10);
   1152 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
   1153 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
   1154 		return 0;
   1155 	else
   1156 		return -1;
   1157 }
   1158 #endif
   1159 
   1160 /* code duplicate with gethnamaddr.c */
   1161 
   1162 static const char AskedForGot[] =
   1163 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
   1164 
   1165 #define maybe_ok(res, nm, ok) (((res)->options & RES_NOCHECKNAME) != 0U || \
   1166                                (ok)(nm) != 0)
   1167 static struct addrinfo *
   1168 getanswer(res_state res, const querybuf *answer, int anslen, const char *qname,
   1169     int qtype, const struct addrinfo *pai)
   1170 {
   1171 	struct addrinfo sentinel, *cur;
   1172 	struct addrinfo ai, *aip;
   1173 	const struct afd *afd;
   1174 	char *canonname;
   1175 	const HEADER *hp;
   1176 	const u_char *cp;
   1177 	int n;
   1178 	const u_char *eom;
   1179 	char *bp, *ep;
   1180 	int type, class, ancount, qdcount;
   1181 	int haveanswer, had_error;
   1182 	char tbuf[MAXDNAME];
   1183 	int (*name_ok) (const char *);
   1184 	char hostbuf[8*1024];
   1185 	int port, pri, weight;
   1186 	struct srvinfo *srvlist, *srv, *csrv;
   1187 
   1188 	_DIAGASSERT(answer != NULL);
   1189 	_DIAGASSERT(qname != NULL);
   1190 	_DIAGASSERT(pai != NULL);
   1191 	_DIAGASSERT(res != NULL);
   1192 
   1193 	memset(&sentinel, 0, sizeof(sentinel));
   1194 	cur = &sentinel;
   1195 
   1196 	canonname = NULL;
   1197 	eom = answer->buf + anslen;
   1198 	switch (qtype) {
   1199 	case T_A:
   1200 	case T_AAAA:
   1201 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
   1202 		name_ok = res_hnok;
   1203 		break;
   1204 	case T_SRV:
   1205 		name_ok = gai_srvok;
   1206 		break;
   1207 	default:
   1208 		return NULL;	/* XXX should be abort(); */
   1209 	}
   1210 	/*
   1211 	 * find first satisfactory answer
   1212 	 */
   1213 	hp = &answer->hdr;
   1214 	ancount = ntohs(hp->ancount);
   1215 	qdcount = ntohs(hp->qdcount);
   1216 	bp = hostbuf;
   1217 	ep = hostbuf + sizeof hostbuf;
   1218 	cp = answer->buf + HFIXEDSZ;
   1219 	if (qdcount != 1) {
   1220 		h_errno = NO_RECOVERY;
   1221 		return (NULL);
   1222 	}
   1223 	n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
   1224 	if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
   1225 		h_errno = NO_RECOVERY;
   1226 		return (NULL);
   1227 	}
   1228 	cp += n + QFIXEDSZ;
   1229 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
   1230 		/* res_send() has already verified that the query name is the
   1231 		 * same as the one we sent; this just gets the expanded name
   1232 		 * (i.e., with the succeeding search-domain tacked on).
   1233 		 */
   1234 		n = (int)strlen(bp) + 1;		/* for the \0 */
   1235 		if (n >= MAXHOSTNAMELEN) {
   1236 			h_errno = NO_RECOVERY;
   1237 			return (NULL);
   1238 		}
   1239 		canonname = bp;
   1240 		bp += n;
   1241 		/* The qname can be abbreviated, but h_name is now absolute. */
   1242 		qname = canonname;
   1243 	}
   1244 	haveanswer = 0;
   1245 	had_error = 0;
   1246 	srvlist = NULL;
   1247 	while (ancount-- > 0 && cp < eom && !had_error) {
   1248 		n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
   1249 		if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
   1250 			had_error++;
   1251 			continue;
   1252 		}
   1253 		cp += n;			/* name */
   1254 		type = _getshort(cp);
   1255 		cp += INT16SZ;			/* type */
   1256 		class = _getshort(cp);
   1257 		cp += INT16SZ + INT32SZ;	/* class, TTL */
   1258 		n = _getshort(cp);
   1259 		cp += INT16SZ;			/* len */
   1260 		if (class != C_IN) {
   1261 			/* XXX - debug? syslog? */
   1262 			cp += n;
   1263 			continue;		/* XXX - had_error++ ? */
   1264 		}
   1265 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
   1266 		    type == T_CNAME) {
   1267 			n = dn_expand(answer->buf, eom, cp, tbuf, (int)sizeof tbuf);
   1268 			if ((n < 0) || !maybe_ok(res, tbuf, name_ok)) {
   1269 				had_error++;
   1270 				continue;
   1271 			}
   1272 			cp += n;
   1273 			/* Get canonical name. */
   1274 			n = (int)strlen(tbuf) + 1;	/* for the \0 */
   1275 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
   1276 				had_error++;
   1277 				continue;
   1278 			}
   1279 			strlcpy(bp, tbuf, (size_t)(ep - bp));
   1280 			canonname = bp;
   1281 			bp += n;
   1282 			continue;
   1283 		}
   1284 		if (qtype == T_ANY) {
   1285 			if (!(type == T_A || type == T_AAAA)) {
   1286 				cp += n;
   1287 				continue;
   1288 			}
   1289 		} else if (type != qtype) {
   1290 			if (type != T_KEY && type != T_SIG) {
   1291 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1292 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1293 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
   1294 				       qname, p_class(C_IN), p_type(qtype),
   1295 				       p_type(type));
   1296 			}
   1297 			cp += n;
   1298 			continue;		/* XXX - had_error++ ? */
   1299 		}
   1300 		switch (type) {
   1301 		case T_A:
   1302 		case T_AAAA:
   1303 			if (strcasecmp(canonname, bp) != 0) {
   1304 				struct syslog_data sd = SYSLOG_DATA_INIT;
   1305 				syslog_r(LOG_NOTICE|LOG_AUTH, &sd,
   1306 				       AskedForGot, canonname, bp);
   1307 				cp += n;
   1308 				continue;	/* XXX - had_error++ ? */
   1309 			}
   1310 			if (type == T_A && n != INADDRSZ) {
   1311 				cp += n;
   1312 				continue;
   1313 			}
   1314 			if (type == T_AAAA && n != IN6ADDRSZ) {
   1315 				cp += n;
   1316 				continue;
   1317 			}
   1318 			if (type == T_AAAA) {
   1319 				struct in6_addr in6;
   1320 				memcpy(&in6, cp, IN6ADDRSZ);
   1321 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
   1322 					cp += n;
   1323 					continue;
   1324 				}
   1325 			}
   1326 			if (!haveanswer) {
   1327 				int nn;
   1328 
   1329 				canonname = bp;
   1330 				nn = (int)strlen(bp) + 1;	/* for the \0 */
   1331 				bp += nn;
   1332 			}
   1333 
   1334 			/* don't overwrite pai */
   1335 			ai = *pai;
   1336 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
   1337 			afd = find_afd(ai.ai_family);
   1338 			if (afd == NULL) {
   1339 				cp += n;
   1340 				continue;
   1341 			}
   1342 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
   1343 			if (cur->ai_next == NULL)
   1344 				had_error++;
   1345 			while (cur && cur->ai_next)
   1346 				cur = cur->ai_next;
   1347 			cp += n;
   1348 			break;
   1349 		case T_SRV:
   1350 			/* Add to SRV list. Insertion sort on priority. */
   1351 			pri = _getshort(cp);
   1352 			cp += INT16SZ;
   1353 			weight = _getshort(cp);
   1354 			cp += INT16SZ;
   1355 			port = _getshort(cp);
   1356 			cp += INT16SZ;
   1357 			n = dn_expand(answer->buf, eom, cp, tbuf,
   1358 			    (int)sizeof(tbuf));
   1359 			if ((n < 0) || !maybe_ok(res, tbuf, res_hnok)) {
   1360 				had_error++;
   1361 				continue;
   1362 			}
   1363 			cp += n;
   1364 			if (strlen(tbuf) + 1 >= MAXDNAME) {
   1365 				had_error++;
   1366 				continue;
   1367 			}
   1368 			srv = malloc(sizeof(*srv));
   1369 			if (!srv) {
   1370 				had_error++;
   1371 				continue;
   1372 			}
   1373 			strlcpy(srv->name, tbuf, sizeof(srv->name));
   1374 			srv->pri = pri;
   1375 			srv->weight = weight;
   1376 			srv->port = port;
   1377 			/* Weight 0 is sorted before other weights. */
   1378 			if (!srvlist
   1379 			    || srv->pri < srvlist->pri
   1380 			    || (srv->pri == srvlist->pri &&
   1381 			    (!srv->weight || srvlist->weight))) {
   1382 				srv->next = srvlist;
   1383 				srvlist = srv;
   1384 			} else {
   1385 				for (csrv = srvlist;
   1386 				    csrv->next && csrv->next->pri <= srv->pri;
   1387 				    csrv = csrv->next) {
   1388 					if (csrv->next->pri == srv->pri
   1389 					    && (!srv->weight ||
   1390 					    csrv->next->weight))
   1391 						break;
   1392 				}
   1393 				srv->next = csrv->next;
   1394 				csrv->next = srv;
   1395 			}
   1396 			continue; /* Don't add to haveanswer yet. */
   1397 		default:
   1398 			abort();
   1399 		}
   1400 		if (!had_error)
   1401 			haveanswer++;
   1402 	}
   1403 
   1404 	if (srvlist) {
   1405 		/*
   1406 		 * Check for explicit rejection.
   1407 		 */
   1408 		if (!srvlist->next && !srvlist->name[0]) {
   1409 			free(srvlist);
   1410 			h_errno = HOST_NOT_FOUND;
   1411 			return NULL;
   1412 		}
   1413 
   1414 		while (srvlist) {
   1415 			struct res_target q, q2;
   1416 
   1417 			srv = srvlist;
   1418 			srvlist = srvlist->next;
   1419 
   1420 			/*
   1421 			 * Since res_* doesn't give the additional
   1422 			 * section, we always look up.
   1423 			 */
   1424 			memset(&q, 0, sizeof(q));
   1425 			memset(&q2, 0, sizeof(q2));
   1426 
   1427 			q.name = srv->name;
   1428 			q.qclass = C_IN;
   1429 			q.qtype = T_AAAA;
   1430 			q.next = &q2;
   1431 			q2.name = srv->name;
   1432 			q2.qclass = C_IN;
   1433 			q2.qtype = T_A;
   1434 
   1435 			aip = _dns_query(&q, pai, res, 0);
   1436 
   1437 			if (aip != NULL) {
   1438 				cur->ai_next = aip;
   1439 				while (cur && cur->ai_next) {
   1440 					cur = cur->ai_next;
   1441 					*getport(cur) = htons(srv->port);
   1442 					haveanswer++;
   1443 				}
   1444 			}
   1445 			free(srv);
   1446 		}
   1447 	}
   1448 	if (haveanswer) {
   1449 		if (!sentinel.ai_next->ai_canonname)
   1450 		       (void)get_canonname(pai, sentinel.ai_next,
   1451 			   canonname ? canonname : qname);
   1452 		h_errno = NETDB_SUCCESS;
   1453 		return sentinel.ai_next;
   1454 	}
   1455 
   1456 	/* We could have walked a CNAME chain, */
   1457 	/* but the ultimate target may not have what we looked for */
   1458 	h_errno = ntohs(hp->ancount) > 0? NO_DATA : NO_RECOVERY;
   1459 	return NULL;
   1460 }
   1461 
   1462 #define SORTEDADDR(p)	(((struct sockaddr_in *)(void *)(p->ai_next->ai_addr))->sin_addr.s_addr)
   1463 #define SORTMATCH(p, s) ((SORTEDADDR(p) & (s).mask) == (s).addr.s_addr)
   1464 
   1465 static void
   1466 aisort(struct addrinfo *s, res_state res)
   1467 {
   1468 	struct addrinfo head, *t, *p;
   1469 	int i;
   1470 
   1471 	head.ai_next = NULL;
   1472 	t = &head;
   1473 
   1474 	for (i = 0; i < res->nsort; i++) {
   1475 		p = s;
   1476 		while (p->ai_next) {
   1477 			if ((p->ai_next->ai_family != AF_INET)
   1478 			|| SORTMATCH(p, res->sort_list[i])) {
   1479 				t->ai_next = p->ai_next;
   1480 				t = t->ai_next;
   1481 				p->ai_next = p->ai_next->ai_next;
   1482 			} else {
   1483 				p = p->ai_next;
   1484 			}
   1485 		}
   1486 	}
   1487 
   1488 	/* add rest of list and reset s to the new list*/
   1489 	t->ai_next = s->ai_next;
   1490 	s->ai_next = head.ai_next;
   1491 }
   1492 
   1493 static struct addrinfo *
   1494 _dns_query(struct res_target *q, const struct addrinfo *pai,
   1495     res_state res, int dosearch)
   1496 {
   1497 	struct res_target *q2 = q->next;
   1498  	querybuf *buf, *buf2;
   1499 	struct addrinfo sentinel, *cur, *ai;
   1500 
   1501 #ifdef DNS_DEBUG
   1502 	struct res_target *iter;
   1503 	for (iter = q; iter; iter = iter->next)
   1504 		printf("Query type %d for %s\n", iter->qtype, iter->name);
   1505 #endif
   1506 
   1507  	buf = malloc(sizeof(*buf));
   1508  	if (buf == NULL) {
   1509  		h_errno = NETDB_INTERNAL;
   1510 		return NULL;
   1511  	}
   1512  	buf2 = malloc(sizeof(*buf2));
   1513  	if (buf2 == NULL) {
   1514  		free(buf);
   1515  		h_errno = NETDB_INTERNAL;
   1516 		return NULL;
   1517 	}
   1518 
   1519 	memset(&sentinel, 0, sizeof(sentinel));
   1520 	cur = &sentinel;
   1521 
   1522 	q->answer = buf->buf;
   1523 	q->anslen = sizeof(buf->buf);
   1524 	if (q2) {
   1525 		q2->answer = buf2->buf;
   1526 		q2->anslen = sizeof(buf2->buf);
   1527 	}
   1528 
   1529 	if (dosearch) {
   1530 		if (res_searchN(q->name, q, res) < 0)
   1531 			goto out;
   1532 	} else {
   1533 		if (res_queryN(q->name, q, res) < 0)
   1534 			goto out;
   1535 	}
   1536 
   1537 	ai = getanswer(res, buf, q->n, q->name, q->qtype, pai);
   1538 	if (ai) {
   1539 		cur->ai_next = ai;
   1540 		while (cur && cur->ai_next)
   1541 			cur = cur->ai_next;
   1542 	}
   1543 	if (q2) {
   1544 		ai = getanswer(res, buf2, q2->n, q2->name, q2->qtype, pai);
   1545 		if (ai)
   1546 			cur->ai_next = ai;
   1547  	}
   1548 	free(buf);
   1549 	free(buf2);
   1550 	return sentinel.ai_next;
   1551 out:
   1552 	free(buf);
   1553 	free(buf2);
   1554 	return NULL;
   1555 }
   1556 
   1557 /*ARGSUSED*/
   1558 static struct addrinfo *
   1559 _dns_srv_lookup(const char *name, const char *servname,
   1560     const struct addrinfo *pai)
   1561 {
   1562 	static const char * const srvprotos[] = { "tcp", "udp" };
   1563 	static const int srvnottype[] = { SOCK_DGRAM, SOCK_STREAM };
   1564 	static const int nsrvprotos = 2;
   1565 	struct addrinfo sentinel, *cur, *ai;
   1566 	struct servent *serv, sv;
   1567 	struct servent_data svd;
   1568 	struct res_target q;
   1569 	res_state res;
   1570 	char *tname;
   1571 	int i;
   1572 
   1573 	res = __res_get_state();
   1574 	if (res == NULL)
   1575 		return NULL;
   1576 
   1577 	memset(&svd, 0, sizeof(svd));
   1578 	memset(&sentinel, 0, sizeof(sentinel));
   1579 	cur = &sentinel;
   1580 
   1581 	/*
   1582 	 * Iterate over supported SRV protocols.
   1583 	 * (currently UDP and TCP only)
   1584 	 */
   1585 	for (i = 0; i < nsrvprotos; i++) {
   1586 		/*
   1587 		 * Check that the caller didn't specify a hint
   1588 		 * which precludes this protocol.
   1589 		 */
   1590 		if (pai->ai_socktype == srvnottype[i])
   1591 			continue;
   1592 		/*
   1593 		 * If the caller specified a port,
   1594 		 * then lookup the database for the
   1595 		 * official service name.
   1596 		 */
   1597 		serv = getservbyname_r(servname, srvprotos[i], &sv, &svd);
   1598 		if (serv == NULL)
   1599 			continue;
   1600 
   1601 		/*
   1602 		 * Construct service DNS name.
   1603 		 */
   1604 		if (asprintf(&tname, "_%s._%s.%s", serv->s_name, serv->s_proto,
   1605 		    name) < 0)
   1606 			continue;
   1607 
   1608 		memset(&q, 0, sizeof(q));
   1609 		q.name = tname;
   1610 		q.qclass = C_IN;
   1611 		q.qtype = T_SRV;
   1612 
   1613 		/*
   1614 		 * Do SRV query.
   1615 		 */
   1616 		ai = _dns_query(&q, pai, res, 1);
   1617 		if (ai) {
   1618 			cur->ai_next = ai;
   1619 			while (cur && cur->ai_next)
   1620 				cur = cur->ai_next;
   1621 		}
   1622 		free(tname);
   1623 	}
   1624 
   1625 	if (res->nsort)
   1626 		aisort(&sentinel, res);
   1627 
   1628 	__res_put_state(res);
   1629 
   1630 	return sentinel.ai_next;
   1631 }
   1632 
   1633 /*ARGSUSED*/
   1634 static struct addrinfo *
   1635 _dns_host_lookup(const char *name, const struct addrinfo *pai)
   1636 {
   1637 	struct res_target q, q2;
   1638 	struct addrinfo sentinel, *ai;
   1639 	res_state res;
   1640 
   1641 	res = __res_get_state();
   1642 	if (res == NULL)
   1643 		return NULL;
   1644 
   1645 	memset(&q, 0, sizeof(q2));
   1646 	memset(&q2, 0, sizeof(q2));
   1647 
   1648 	switch (pai->ai_family) {
   1649 	case AF_UNSPEC:
   1650 		/* prefer IPv6 */
   1651 		q.name = name;
   1652 		q.qclass = C_IN;
   1653 		q.qtype = T_AAAA;
   1654 		q.next = &q2;
   1655 		q2.name = name;
   1656 		q2.qclass = C_IN;
   1657 		q2.qtype = T_A;
   1658 		break;
   1659 	case AF_INET:
   1660 		q.name = name;
   1661 		q.qclass = C_IN;
   1662 		q.qtype = T_A;
   1663 		break;
   1664 	case AF_INET6:
   1665 		q.name = name;
   1666 		q.qclass = C_IN;
   1667 		q.qtype = T_AAAA;
   1668 		break;
   1669 	default:
   1670 		__res_put_state(res);
   1671 		h_errno = NETDB_INTERNAL;
   1672 		return NULL;
   1673 	}
   1674 
   1675 	ai = _dns_query(&q, pai, res, 1);
   1676 
   1677 	memset(&sentinel, 0, sizeof(sentinel));
   1678 	sentinel.ai_next = ai;
   1679 
   1680 	if (ai != NULL && res->nsort)
   1681 		aisort(&sentinel, res);
   1682 
   1683 	__res_put_state(res);
   1684 
   1685 	return sentinel.ai_next;
   1686 }
   1687 
   1688 /*ARGSUSED*/
   1689 static int
   1690 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
   1691 {
   1692 	struct addrinfo *ai = NULL;
   1693 	const char *name, *servname;
   1694 	const struct addrinfo *pai;
   1695 
   1696 	name = va_arg(ap, char *);
   1697 	pai = va_arg(ap, const struct addrinfo *);
   1698 	servname = va_arg(ap, char *);
   1699 
   1700 	/*
   1701 	 * Try doing SRV lookup on service first.
   1702 	 */
   1703 	if (servname
   1704 #ifdef AI_SRV
   1705 	    && (pai->ai_flags & AI_SRV)
   1706 #endif
   1707 	    && !(pai->ai_flags & AI_NUMERICSERV)
   1708 	    && str2number(servname) == -1) {
   1709 
   1710 #ifdef DNS_DEBUG
   1711 		printf("%s: try SRV lookup\n", __func__);
   1712 #endif
   1713 		ai = _dns_srv_lookup(name, servname, pai);
   1714 	}
   1715 
   1716 	/*
   1717 	 * Do lookup on name.
   1718 	 */
   1719 	if (ai == NULL) {
   1720 
   1721 #ifdef DNS_DEBUG
   1722 		printf("%s: try HOST lookup\n", __func__);
   1723 #endif
   1724 		ai = _dns_host_lookup(name, pai);
   1725 
   1726 		if (ai == NULL) {
   1727 			switch (h_errno) {
   1728 			case HOST_NOT_FOUND:
   1729 			case NO_DATA:	// XXX: Perhaps we could differentiate
   1730 					// So that we could return EAI_NODATA?
   1731 				return NS_NOTFOUND;
   1732 			case TRY_AGAIN:
   1733 				return NS_TRYAGAIN;
   1734 			default:
   1735 				return NS_UNAVAIL;
   1736 			}
   1737 		}
   1738 	}
   1739 
   1740 	*((struct addrinfo **)rv) = ai;
   1741 	return NS_SUCCESS;
   1742 }
   1743 
   1744 static void
   1745 _sethtent(FILE **hostf)
   1746 {
   1747 
   1748 	if (!*hostf)
   1749 		*hostf = fopen(_PATH_HOSTS, "re");
   1750 	else
   1751 		rewind(*hostf);
   1752 }
   1753 
   1754 static void
   1755 _endhtent(FILE **hostf)
   1756 {
   1757 
   1758 	if (*hostf) {
   1759 		(void) fclose(*hostf);
   1760 		*hostf = NULL;
   1761 	}
   1762 }
   1763 
   1764 static struct addrinfo *
   1765 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
   1766 {
   1767 	char *p;
   1768 	char *cp, *tname, *cname;
   1769 	struct addrinfo hints, *res0, *res;
   1770 	int error;
   1771 	const char *addr;
   1772 	char hostbuf[8*1024];
   1773 
   1774 	_DIAGASSERT(name != NULL);
   1775 	_DIAGASSERT(pai != NULL);
   1776 
   1777 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
   1778 		return (NULL);
   1779  again:
   1780 	if (!(p = fgets(hostbuf, (int)sizeof hostbuf, *hostf)))
   1781 		return (NULL);
   1782 	if (*p == '#')
   1783 		goto again;
   1784 	if (!(cp = strpbrk(p, "#\n")))
   1785 		goto again;
   1786 	*cp = '\0';
   1787 	if (!(cp = strpbrk(p, " \t")))
   1788 		goto again;
   1789 	*cp++ = '\0';
   1790 	addr = p;
   1791 	/* if this is not something we're looking for, skip it. */
   1792 	cname = NULL;
   1793 	while (cp && *cp) {
   1794 		if (*cp == ' ' || *cp == '\t') {
   1795 			cp++;
   1796 			continue;
   1797 		}
   1798 		if (!cname)
   1799 			cname = cp;
   1800 		tname = cp;
   1801 		if ((cp = strpbrk(cp, " \t")) != NULL)
   1802 			*cp++ = '\0';
   1803 		if (strcasecmp(name, tname) == 0)
   1804 			goto found;
   1805 	}
   1806 	goto again;
   1807 
   1808 found:
   1809 	hints = *pai;
   1810 	hints.ai_flags = AI_NUMERICHOST;
   1811 	error = getaddrinfo(addr, NULL, &hints, &res0);
   1812 	if (error)
   1813 		goto again;
   1814 	for (res = res0; res; res = res->ai_next) {
   1815 		/* cover it up */
   1816 		res->ai_flags = pai->ai_flags;
   1817 
   1818 		if (pai->ai_flags & AI_CANONNAME) {
   1819 			if (get_canonname(pai, res, cname) != 0) {
   1820 				freeaddrinfo(res0);
   1821 				goto again;
   1822 			}
   1823 		}
   1824 	}
   1825 	return res0;
   1826 }
   1827 
   1828 /*ARGSUSED*/
   1829 static int
   1830 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
   1831 {
   1832 	const char *name;
   1833 	const struct addrinfo *pai;
   1834 	struct addrinfo sentinel, *cur;
   1835 	struct addrinfo *p;
   1836 #ifndef _REENTRANT
   1837 	static
   1838 #endif
   1839 	FILE *hostf = NULL;
   1840 
   1841 	name = va_arg(ap, char *);
   1842 	pai = va_arg(ap, const struct addrinfo *);
   1843 
   1844 	memset(&sentinel, 0, sizeof(sentinel));
   1845 	cur = &sentinel;
   1846 
   1847 	_sethtent(&hostf);
   1848 	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
   1849 		cur->ai_next = p;
   1850 		while (cur && cur->ai_next)
   1851 			cur = cur->ai_next;
   1852 	}
   1853 	_endhtent(&hostf);
   1854 
   1855 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1856 	if (sentinel.ai_next == NULL)
   1857 		return NS_NOTFOUND;
   1858 	return NS_SUCCESS;
   1859 }
   1860 
   1861 #ifdef YP
   1862 /*ARGSUSED*/
   1863 static struct addrinfo *
   1864 _yphostent(char *line, const struct addrinfo *pai)
   1865 {
   1866 	struct addrinfo sentinel, *cur;
   1867 	struct addrinfo hints, *res, *res0;
   1868 	int error;
   1869 	char *p;
   1870 	const char *addr, *canonname;
   1871 	char *nextline;
   1872 	char *cp;
   1873 
   1874 	_DIAGASSERT(line != NULL);
   1875 	_DIAGASSERT(pai != NULL);
   1876 
   1877 	p = line;
   1878 	addr = canonname = NULL;
   1879 
   1880 	memset(&sentinel, 0, sizeof(sentinel));
   1881 	cur = &sentinel;
   1882 
   1883 nextline:
   1884 	/* terminate line */
   1885 	cp = strchr(p, '\n');
   1886 	if (cp) {
   1887 		*cp++ = '\0';
   1888 		nextline = cp;
   1889 	} else
   1890 		nextline = NULL;
   1891 
   1892 	cp = strpbrk(p, " \t");
   1893 	if (cp == NULL) {
   1894 		if (canonname == NULL)
   1895 			return (NULL);
   1896 		else
   1897 			goto done;
   1898 	}
   1899 	*cp++ = '\0';
   1900 
   1901 	addr = p;
   1902 
   1903 	while (cp && *cp) {
   1904 		if (*cp == ' ' || *cp == '\t') {
   1905 			cp++;
   1906 			continue;
   1907 		}
   1908 		if (!canonname)
   1909 			canonname = cp;
   1910 		if ((cp = strpbrk(cp, " \t")) != NULL)
   1911 			*cp++ = '\0';
   1912 	}
   1913 
   1914 	hints = *pai;
   1915 	hints.ai_flags = AI_NUMERICHOST;
   1916 	error = getaddrinfo(addr, NULL, &hints, &res0);
   1917 	if (error == 0) {
   1918 		for (res = res0; res; res = res->ai_next) {
   1919 			/* cover it up */
   1920 			res->ai_flags = pai->ai_flags;
   1921 
   1922 			if (pai->ai_flags & AI_CANONNAME)
   1923 				(void)get_canonname(pai, res, canonname);
   1924 		}
   1925 	} else
   1926 		res0 = NULL;
   1927 	if (res0) {
   1928 		cur->ai_next = res0;
   1929 		while (cur->ai_next)
   1930 			cur = cur->ai_next;
   1931 	}
   1932 
   1933 	if (nextline) {
   1934 		p = nextline;
   1935 		goto nextline;
   1936 	}
   1937 
   1938 done:
   1939 	return sentinel.ai_next;
   1940 }
   1941 
   1942 /*ARGSUSED*/
   1943 static int
   1944 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
   1945 {
   1946 	struct addrinfo sentinel, *cur;
   1947 	struct addrinfo *ai = NULL;
   1948 	char *ypbuf;
   1949 	int ypbuflen, r;
   1950 	const char *name;
   1951 	const struct addrinfo *pai;
   1952 	char *ypdomain;
   1953 
   1954 	if (_yp_check(&ypdomain) == 0)
   1955 		return NS_UNAVAIL;
   1956 
   1957 	name = va_arg(ap, char *);
   1958 	pai = va_arg(ap, const struct addrinfo *);
   1959 
   1960 	memset(&sentinel, 0, sizeof(sentinel));
   1961 	cur = &sentinel;
   1962 
   1963 	/* hosts.byname is only for IPv4 (Solaris8) */
   1964 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
   1965 		r = yp_match(ypdomain, "hosts.byname", name,
   1966 			(int)strlen(name), &ypbuf, &ypbuflen);
   1967 		if (r == 0) {
   1968 			struct addrinfo ai4;
   1969 
   1970 			ai4 = *pai;
   1971 			ai4.ai_family = AF_INET;
   1972 			ai = _yphostent(ypbuf, &ai4);
   1973 			if (ai) {
   1974 				cur->ai_next = ai;
   1975 				while (cur && cur->ai_next)
   1976 					cur = cur->ai_next;
   1977 			}
   1978 		}
   1979 		free(ypbuf);
   1980 	}
   1981 
   1982 	/* ipnodes.byname can hold both IPv4/v6 */
   1983 	r = yp_match(ypdomain, "ipnodes.byname", name,
   1984 		(int)strlen(name), &ypbuf, &ypbuflen);
   1985 	if (r == 0) {
   1986 		ai = _yphostent(ypbuf, pai);
   1987 		if (ai)
   1988 			cur->ai_next = ai;
   1989 		free(ypbuf);
   1990 	}
   1991 
   1992 	if (sentinel.ai_next == NULL) {
   1993 		h_errno = HOST_NOT_FOUND;
   1994 		return NS_NOTFOUND;
   1995 	}
   1996 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1997 	return NS_SUCCESS;
   1998 }
   1999 #endif
   2000 
   2001 /* resolver logic */
   2002 
   2003 /*
   2004  * Formulate a normal query, send, and await answer.
   2005  * Returned answer is placed in supplied buffer "answer".
   2006  * Perform preliminary check of answer, returning success only
   2007  * if no error is indicated and the answer count is nonzero.
   2008  * Return the size of the response on success, -1 on error.
   2009  * Error number is left in h_errno.
   2010  *
   2011  * Caller must parse answer and determine whether it answers the question.
   2012  */
   2013 static int
   2014 res_queryN(const char *name, /* domain name */ struct res_target *target,
   2015     res_state res)
   2016 {
   2017 	u_char buf[MAXPACKET];
   2018 	HEADER *hp;
   2019 	int n;
   2020 	struct res_target *t;
   2021 	int rcode;
   2022 	int ancount;
   2023 
   2024 	_DIAGASSERT(name != NULL);
   2025 	/* XXX: target may be NULL??? */
   2026 
   2027 	rcode = NOERROR;
   2028 	ancount = 0;
   2029 
   2030 	for (t = target; t; t = t->next) {
   2031 		int class, type;
   2032 		u_char *answer;
   2033 		int anslen;
   2034 
   2035 		hp = (HEADER *)(void *)t->answer;
   2036 		hp->rcode = NOERROR;	/* default */
   2037 
   2038 		/* make it easier... */
   2039 		class = t->qclass;
   2040 		type = t->qtype;
   2041 		answer = t->answer;
   2042 		anslen = t->anslen;
   2043 #ifdef DEBUG
   2044 		if (res->options & RES_DEBUG)
   2045 			printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
   2046 #endif
   2047 
   2048 		n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
   2049 		    buf, (int)sizeof(buf));
   2050 #ifdef RES_USE_EDNS0
   2051 		if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
   2052 			n = res_nopt(res, n, buf, (int)sizeof(buf), anslen);
   2053 #endif
   2054 		if (n <= 0) {
   2055 #ifdef DEBUG
   2056 			if (res->options & RES_DEBUG)
   2057 				printf(";; res_nquery: mkquery failed\n");
   2058 #endif
   2059 			h_errno = NO_RECOVERY;
   2060 			return n;
   2061 		}
   2062 		n = res_nsend(res, buf, n, answer, anslen);
   2063 #if 0
   2064 		if (n < 0) {
   2065 #ifdef DEBUG
   2066 			if (res->options & RES_DEBUG)
   2067 				printf(";; res_query: send error\n");
   2068 #endif
   2069 			h_errno = TRY_AGAIN;
   2070 			return n;
   2071 		}
   2072 #endif
   2073 
   2074 		if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
   2075 			rcode = hp->rcode;	/* record most recent error */
   2076 #ifdef DEBUG
   2077 			if (res->options & RES_DEBUG)
   2078 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
   2079 				    ntohs(hp->ancount));
   2080 #endif
   2081 			continue;
   2082 		}
   2083 
   2084 		ancount += ntohs(hp->ancount);
   2085 
   2086 		t->n = n;
   2087 	}
   2088 
   2089 	if (ancount == 0) {
   2090 		switch (rcode) {
   2091 		case NXDOMAIN:
   2092 			h_errno = HOST_NOT_FOUND;
   2093 			break;
   2094 		case SERVFAIL:
   2095 			h_errno = TRY_AGAIN;
   2096 			break;
   2097 		case NOERROR:
   2098 			h_errno = NO_DATA;
   2099 			break;
   2100 		case FORMERR:
   2101 		case NOTIMP:
   2102 		case REFUSED:
   2103 		default:
   2104 			h_errno = NO_RECOVERY;
   2105 			break;
   2106 		}
   2107 		return -1;
   2108 	}
   2109 	return ancount;
   2110 }
   2111 
   2112 /*
   2113  * Formulate a normal query, send, and retrieve answer in supplied buffer.
   2114  * Return the size of the response on success, -1 on error.
   2115  * If enabled, implement search rules until answer or unrecoverable failure
   2116  * is detected.	 Error code, if any, is left in h_errno.
   2117  */
   2118 static int
   2119 res_searchN(const char *name, struct res_target *target, res_state res)
   2120 {
   2121 	const char *cp, * const *domain;
   2122 	HEADER *hp;
   2123 	u_int dots;
   2124 	char buf[MAXHOSTNAMELEN];
   2125 	int trailing_dot, ret, saved_herrno;
   2126 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
   2127 
   2128 	_DIAGASSERT(name != NULL);
   2129 	_DIAGASSERT(target != NULL);
   2130 
   2131 	hp = (HEADER *)(void *)target->answer;	/*XXX*/
   2132 
   2133 	errno = 0;
   2134 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
   2135 	dots = 0;
   2136 	for (cp = name; *cp; cp++)
   2137 		dots += (*cp == '.');
   2138 	trailing_dot = 0;
   2139 	if (cp > name && *--cp == '.')
   2140 		trailing_dot++;
   2141 
   2142 	/*
   2143 	 * if there aren't any dots, it could be a user-level alias
   2144 	 */
   2145 	if (!dots && (cp = res_hostalias(res, name, buf, sizeof(buf))) != NULL) {
   2146 		ret = res_queryN(cp, target, res);
   2147 		return ret;
   2148 	}
   2149 
   2150 	/*
   2151 	 * If there are dots in the name already, let's just give it a try
   2152 	 * 'as is'.  The threshold can be set with the "ndots" option.
   2153 	 */
   2154 	saved_herrno = -1;
   2155 	if (dots >= res->ndots) {
   2156 		ret = res_querydomainN(name, NULL, target, res);
   2157 		if (ret > 0)
   2158 			return (ret);
   2159 		saved_herrno = h_errno;
   2160 		tried_as_is++;
   2161 	}
   2162 
   2163 	/*
   2164 	 * We do at least one level of search if
   2165 	 *	- there is no dot and RES_DEFNAME is set, or
   2166 	 *	- there is at least one dot, there is no trailing dot,
   2167 	 *	  and RES_DNSRCH is set.
   2168 	 */
   2169 	if ((!dots && (res->options & RES_DEFNAMES)) ||
   2170 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
   2171 		int done = 0;
   2172 
   2173 		for (domain = (const char * const *)res->dnsrch;
   2174 		   *domain && !done;
   2175 		   domain++) {
   2176 
   2177 			ret = res_querydomainN(name, *domain, target, res);
   2178 			if (ret > 0)
   2179 				return ret;
   2180 
   2181 			/*
   2182 			 * If no server present, give up.
   2183 			 * If name isn't found in this domain,
   2184 			 * keep trying higher domains in the search list
   2185 			 * (if that's enabled).
   2186 			 * On a NO_DATA error, keep trying, otherwise
   2187 			 * a wildcard entry of another type could keep us
   2188 			 * from finding this entry higher in the domain.
   2189 			 * If we get some other error (negative answer or
   2190 			 * server failure), then stop searching up,
   2191 			 * but try the input name below in case it's
   2192 			 * fully-qualified.
   2193 			 */
   2194 			if (errno == ECONNREFUSED) {
   2195 				h_errno = TRY_AGAIN;
   2196 				return -1;
   2197 			}
   2198 
   2199 			switch (h_errno) {
   2200 			case NO_DATA:
   2201 				got_nodata++;
   2202 				/* FALLTHROUGH */
   2203 			case HOST_NOT_FOUND:
   2204 				/* keep trying */
   2205 				break;
   2206 			case TRY_AGAIN:
   2207 				if (hp->rcode == SERVFAIL) {
   2208 					/* try next search element, if any */
   2209 					got_servfail++;
   2210 					break;
   2211 				}
   2212 				/* FALLTHROUGH */
   2213 			default:
   2214 				/* anything else implies that we're done */
   2215 				done++;
   2216 			}
   2217 			/*
   2218 			 * if we got here for some reason other than DNSRCH,
   2219 			 * we only wanted one iteration of the loop, so stop.
   2220 			 */
   2221 			if (!(res->options & RES_DNSRCH))
   2222 				done++;
   2223 		}
   2224 	}
   2225 
   2226 	/*
   2227 	 * if we have not already tried the name "as is", do that now.
   2228 	 * note that we do this regardless of how many dots were in the
   2229 	 * name or whether it ends with a dot.
   2230 	 */
   2231 	if (!tried_as_is) {
   2232 		ret = res_querydomainN(name, NULL, target, res);
   2233 		if (ret > 0)
   2234 			return ret;
   2235 	}
   2236 
   2237 	/*
   2238 	 * if we got here, we didn't satisfy the search.
   2239 	 * if we did an initial full query, return that query's h_errno
   2240 	 * (note that we wouldn't be here if that query had succeeded).
   2241 	 * else if we ever got a nodata, send that back as the reason.
   2242 	 * else send back meaningless h_errno, that being the one from
   2243 	 * the last DNSRCH we did.
   2244 	 */
   2245 	if (saved_herrno != -1)
   2246 		h_errno = saved_herrno;
   2247 	else if (got_nodata)
   2248 		h_errno = NO_DATA;
   2249 	else if (got_servfail)
   2250 		h_errno = TRY_AGAIN;
   2251 	return -1;
   2252 }
   2253 
   2254 /*
   2255  * Perform a call on res_query on the concatenation of name and domain,
   2256  * removing a trailing dot from name if domain is NULL.
   2257  */
   2258 static int
   2259 res_querydomainN(const char *name, const char *domain,
   2260     struct res_target *target, res_state res)
   2261 {
   2262 	char nbuf[MAXDNAME];
   2263 	const char *longname = nbuf;
   2264 	size_t n, d;
   2265 
   2266 	_DIAGASSERT(name != NULL);
   2267 	/* XXX: target may be NULL??? */
   2268 
   2269 #ifdef DEBUG
   2270 	if (res->options & RES_DEBUG)
   2271 		printf(";; res_querydomain(%s, %s)\n",
   2272 			name, domain?domain:"<Nil>");
   2273 #endif
   2274 	if (domain == NULL) {
   2275 		/*
   2276 		 * Check for trailing '.';
   2277 		 * copy without '.' if present.
   2278 		 */
   2279 		n = strlen(name);
   2280 		if (n + 1 > sizeof(nbuf)) {
   2281 			h_errno = NO_RECOVERY;
   2282 			return -1;
   2283 		}
   2284 		if (n > 0 && name[--n] == '.') {
   2285 			strncpy(nbuf, name, n);
   2286 			nbuf[n] = '\0';
   2287 		} else
   2288 			longname = name;
   2289 	} else {
   2290 		n = strlen(name);
   2291 		d = strlen(domain);
   2292 		if (n + 1 + d + 1 > sizeof(nbuf)) {
   2293 			h_errno = NO_RECOVERY;
   2294 			return -1;
   2295 		}
   2296 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
   2297 	}
   2298 	return res_queryN(longname, target, res);
   2299 }
   2300 
   2301 #ifdef TEST
   2302 int
   2303 main(int argc, char *argv[]) {
   2304 	struct addrinfo *ai, *sai;
   2305 	int i, e;
   2306 	char buf[1024];
   2307 
   2308 	for (i = 1; i < argc; i++) {
   2309 		if ((e = getaddrinfo(argv[i], NULL, NULL, &sai)) != 0)
   2310 			warnx("%s: %s", argv[i], gai_strerror(e));
   2311 		for (ai = sai; ai; ai = ai->ai_next) {
   2312 			sockaddr_snprintf(buf, sizeof(buf), "%a", ai->ai_addr);
   2313              		printf("flags=0x%x family=%d socktype=%d protocol=%d "
   2314 			    "addrlen=%zu addr=%s canonname=%s next=%p\n",
   2315 			    ai->ai_flags,
   2316              		    ai->ai_family,
   2317              		    ai->ai_socktype,
   2318              		    ai->ai_protocol,
   2319              		    (size_t)ai->ai_addrlen,
   2320 			    buf,
   2321 			    ai->ai_canonname,
   2322 			    ai->ai_next);
   2323 		}
   2324 		if (sai)
   2325 			freeaddrinfo(sai);
   2326 	}
   2327 	return 0;
   2328 }
   2329 #endif
   2330