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