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