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