xref: /freebsd/lib/libc/net/getaddrinfo.c (revision ec65e4f8d0654361df5e97d4de3518edebf76b46)
1 /*	$KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * Issues to be discussed:
34  * - Return values.  There are nonstandard return values defined and used
35  *   in the source code.  This is because RFC2553 is silent about which error
36  *   code must be returned for which situation.
37  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
38  *   invalid.  current code - SEGV on freeaddrinfo(NULL)
39  *
40  * Note:
41  * - The code filters out AFs that are not supported by the kernel,
42  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
43  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
44  *   in ai_flags?
45  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
46  *   (1) what should we do against numeric hostname (2) what should we do
47  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
48  *   non-loopback address configured?  global address configured?
49  *
50  * OS specific notes for freebsd4:
51  * - FreeBSD supported $GAI.  The code does not.
52  */
53 
54 #include <sys/cdefs.h>
55 __FBSDID("$FreeBSD$");
56 
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 };
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 	do {
362 		next = ai->ai_next;
363 		if (ai->ai_canonname)
364 			free(ai->ai_canonname);
365 		/* no need to free(ai->ai_addr) */
366 		free(ai);
367 		ai = next;
368 	} while (ai);
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 = malloc(sizeof(*aio) * n)) == NULL)
694 		return(n);	/* give up reordering */
695 	memset(aio, 0, sizeof(*aio) * n);
696 
697 	/* retrieve address selection policy from the kernel */
698 	TAILQ_INIT(&policyhead);
699 	if (!get_addrselectpolicy(&policyhead)) {
700 		/* no policy is installed into kernel, we don't sort. */
701 		free(aio);
702 		return (n);
703 	}
704 
705 	for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
706 		aio[i].aio_ai = ai;
707 		aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
708 		aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
709 							      &policyhead);
710 		set_source(&aio[i], &policyhead);
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 < addrlen * 8) {
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 	return(-1);
1070 }
1071 
1072 /*
1073  * Copy from scope.c.
1074  * XXX: we should standardize the functions and link them as standard
1075  * library.
1076  */
1077 static int
1078 gai_addr2scopetype(struct sockaddr *sa)
1079 {
1080 #ifdef INET6
1081 	struct sockaddr_in6 *sa6;
1082 #endif
1083 	struct sockaddr_in *sa4;
1084 
1085 	switch(sa->sa_family) {
1086 #ifdef INET6
1087 	case AF_INET6:
1088 		sa6 = (struct sockaddr_in6 *)sa;
1089 		if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1090 			/* just use the scope field of the multicast address */
1091 			return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1092 		}
1093 		/*
1094 		 * Unicast addresses: map scope type to corresponding scope
1095 		 * value defined for multcast addresses.
1096 		 * XXX: hardcoded scope type values are bad...
1097 		 */
1098 		if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1099 			return(1); /* node local scope */
1100 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1101 			return(2); /* link-local scope */
1102 		if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1103 			return(5); /* site-local scope */
1104 		return(14);	/* global scope */
1105 		break;
1106 #endif
1107 	case AF_INET:
1108 		/*
1109 		 * IPv4 pseudo scoping according to RFC 3484.
1110 		 */
1111 		sa4 = (struct sockaddr_in *)sa;
1112 		/* IPv4 autoconfiguration addresses have link-local scope. */
1113 		if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1114 		    ((u_char *)&sa4->sin_addr)[1] == 254)
1115 			return(2);
1116 		/* Private addresses have site-local scope. */
1117 		if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1118 		    (((u_char *)&sa4->sin_addr)[0] == 172 &&
1119 		     (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1120 		    (((u_char *)&sa4->sin_addr)[0] == 192 &&
1121 		     ((u_char *)&sa4->sin_addr)[1] == 168))
1122 			return(14);	/* XXX: It should be 5 unless NAT */
1123 		/* Loopback addresses have link-local scope. */
1124 		if (((u_char *)&sa4->sin_addr)[0] == 127)
1125 			return(2);
1126 		return(14);
1127 		break;
1128 	default:
1129 		errno = EAFNOSUPPORT; /* is this a good error? */
1130 		return(-1);
1131 	}
1132 }
1133 
1134 static int
1135 explore_copy(const struct addrinfo *pai, const struct addrinfo *src0,
1136     struct addrinfo **res)
1137 {
1138 	int error;
1139 	struct addrinfo sentinel, *cur;
1140 	const struct addrinfo *src;
1141 
1142 	error = 0;
1143 	sentinel.ai_next = NULL;
1144 	cur = &sentinel;
1145 
1146 	for (src = src0; src != NULL; src = src->ai_next) {
1147 		if (src->ai_family != pai->ai_family)
1148 			continue;
1149 
1150 		cur->ai_next = copy_ai(src);
1151 		if (!cur->ai_next) {
1152 			error = EAI_MEMORY;
1153 			goto fail;
1154 		}
1155 
1156 		cur->ai_next->ai_socktype = pai->ai_socktype;
1157 		cur->ai_next->ai_protocol = pai->ai_protocol;
1158 		cur = cur->ai_next;
1159 	}
1160 
1161 	*res = sentinel.ai_next;
1162 	return 0;
1163 
1164 fail:
1165 	freeaddrinfo(sentinel.ai_next);
1166 	return error;
1167 }
1168 
1169 /*
1170  * hostname == NULL.
1171  * passive socket -> anyaddr (0.0.0.0 or ::)
1172  * non-passive socket -> localhost (127.0.0.1 or ::1)
1173  */
1174 static int
1175 explore_null(const struct addrinfo *pai, const char *servname,
1176     struct addrinfo **res)
1177 {
1178 	int s;
1179 	const struct afd *afd;
1180 	struct addrinfo *ai;
1181 	int error;
1182 
1183 	*res = NULL;
1184 	ai = NULL;
1185 
1186 	if (pai->ai_family == PF_LOCAL)
1187 		return (0);
1188 
1189 	/*
1190 	 * filter out AFs that are not supported by the kernel
1191 	 * XXX errno?
1192 	 */
1193 	s = _socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1194 	if (s < 0) {
1195 		if (errno != EMFILE)
1196 			return 0;
1197 	} else
1198 		_close(s);
1199 
1200 	afd = find_afd(pai->ai_family);
1201 	if (afd == NULL)
1202 		return 0;
1203 
1204 	if (pai->ai_flags & AI_PASSIVE) {
1205 		GET_AI(ai, afd, afd->a_addrany);
1206 		GET_PORT(ai, servname);
1207 	} else {
1208 		GET_AI(ai, afd, afd->a_loopback);
1209 		GET_PORT(ai, servname);
1210 	}
1211 
1212 	*res = ai;
1213 	return 0;
1214 
1215 free:
1216 	if (ai != NULL)
1217 		freeaddrinfo(ai);
1218 	return error;
1219 }
1220 
1221 /*
1222  * numeric hostname
1223  */
1224 static int
1225 explore_numeric(const struct addrinfo *pai, const char *hostname,
1226     const char *servname, struct addrinfo **res, const char *canonname)
1227 {
1228 	const struct afd *afd;
1229 	struct addrinfo *ai, ai0;
1230 	int error;
1231 	char pton[PTON_MAX], path[PATH_MAX], *p;
1232 
1233 #ifdef CTASSERT
1234 	CTASSERT(sizeofmember(struct sockaddr_un, sun_path) <= PATH_MAX);
1235 #endif
1236 	*res = NULL;
1237 	ai = NULL;
1238 
1239 	afd = find_afd(pai->ai_family);
1240 	if (afd == NULL)
1241 		return 0;
1242 
1243 	switch (afd->a_af) {
1244 	case AF_LOCAL:
1245 		if (hostname[0] != '/')
1246 			ERR(EAI_NONAME);
1247 		if (strlen(hostname) > afd->a_addrlen)
1248 			ERR(EAI_MEMORY);
1249 		/* NUL-termination does not need to be guaranteed. */
1250 		strncpy(path, hostname, afd->a_addrlen);
1251 		p = &path[0];
1252 		break;
1253 	case AF_INET:
1254 		/*
1255 		 * RFC3493 requires getaddrinfo() to accept AF_INET formats
1256 		 * that are accepted by inet_addr() and its family.  The
1257 		 * accepted forms includes the "classful" one, which inet_pton
1258 		 * does not accept.  So we need to separate the case for
1259 		 * AF_INET.
1260 		 */
1261 		if (inet_aton(hostname, (struct in_addr *)pton) != 1)
1262 			return 0;
1263 		p = pton;
1264 		break;
1265 	default:
1266 		if (inet_pton(afd->a_af, hostname, pton) != 1) {
1267 			if (pai->ai_family != AF_INET6 ||
1268 			    (pai->ai_flags & AI_V4MAPPED) != AI_V4MAPPED)
1269 				return 0;
1270 			if (inet_aton(hostname, (struct in_addr *)pton) != 1)
1271 				return 0;
1272 			afd = &afdl[N_INET];
1273 			ai0 = *pai;
1274 			ai0.ai_family = AF_INET;
1275 			pai = &ai0;
1276 		}
1277 		p = pton;
1278 		break;
1279 	}
1280 
1281 	if (pai->ai_family == afd->a_af) {
1282 		GET_AI(ai, afd, p);
1283 		GET_PORT(ai, servname);
1284 		if ((pai->ai_family == AF_INET ||
1285 		     pai->ai_family == AF_INET6) &&
1286 		    (pai->ai_flags & AI_CANONNAME)) {
1287 			/*
1288 			 * Set the numeric address itself as the canonical
1289 			 * name, based on a clarification in RFC3493.
1290 			 */
1291 			GET_CANONNAME(ai, canonname);
1292 		}
1293 	} else {
1294 		/*
1295 		 * XXX: This should not happen since we already matched the AF
1296 		 * by find_afd.
1297 		 */
1298 		ERR(EAI_FAMILY);
1299 	}
1300 
1301 	*res = ai;
1302 	return 0;
1303 
1304 free:
1305 bad:
1306 	if (ai != NULL)
1307 		freeaddrinfo(ai);
1308 	return error;
1309 }
1310 
1311 /*
1312  * numeric hostname with scope
1313  */
1314 static int
1315 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1316     const char *servname, struct addrinfo **res)
1317 {
1318 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
1319 	return explore_numeric(pai, hostname, servname, res, hostname);
1320 #else
1321 	const struct afd *afd;
1322 	struct addrinfo *cur;
1323 	int error;
1324 	char *cp, *hostname2 = NULL, *scope, *addr;
1325 	struct sockaddr_in6 *sin6;
1326 
1327 	afd = find_afd(pai->ai_family);
1328 	if (afd == NULL)
1329 		return 0;
1330 
1331 	if (!afd->a_scoped)
1332 		return explore_numeric(pai, hostname, servname, res, hostname);
1333 
1334 	cp = strchr(hostname, SCOPE_DELIMITER);
1335 	if (cp == NULL)
1336 		return explore_numeric(pai, hostname, servname, res, hostname);
1337 
1338 	/*
1339 	 * Handle special case of <scoped_address><delimiter><scope id>
1340 	 */
1341 	hostname2 = strdup(hostname);
1342 	if (hostname2 == NULL)
1343 		return EAI_MEMORY;
1344 	/* terminate at the delimiter */
1345 	hostname2[cp - hostname] = '\0';
1346 	addr = hostname2;
1347 	scope = cp + 1;
1348 
1349 	error = explore_numeric(pai, addr, servname, res, hostname);
1350 	if (error == 0) {
1351 		u_int32_t scopeid;
1352 
1353 		for (cur = *res; cur; cur = cur->ai_next) {
1354 			if (cur->ai_family != AF_INET6)
1355 				continue;
1356 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1357 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1358 				free(hostname2);
1359 				freeaddrinfo(*res);
1360 				*res = NULL;
1361 				return(EAI_NONAME); /* XXX: is return OK? */
1362 			}
1363 			sin6->sin6_scope_id = scopeid;
1364 		}
1365 	}
1366 
1367 	free(hostname2);
1368 
1369 	if (error && *res) {
1370 		freeaddrinfo(*res);
1371 		*res = NULL;
1372 	}
1373 	return error;
1374 #endif
1375 }
1376 
1377 static int
1378 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1379 {
1380 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
1381 		ai->ai_canonname = strdup(str);
1382 		if (ai->ai_canonname == NULL)
1383 			return EAI_MEMORY;
1384 	}
1385 	return 0;
1386 }
1387 
1388 static struct addrinfo *
1389 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1390 {
1391 	char *p;
1392 	struct addrinfo *ai;
1393 #ifdef INET6
1394 	struct in6_addr mapaddr;
1395 
1396 	if (afd->a_af == AF_INET && (pai->ai_flags & AI_V4MAPPED) != 0) {
1397 		afd = &afdl[N_INET6];
1398 		_map_v4v6_address(addr, (char *)&mapaddr);
1399 		addr = (char *)&mapaddr;
1400 	}
1401 #endif
1402 
1403 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1404 		+ (afd->a_socklen));
1405 	if (ai == NULL)
1406 		return NULL;
1407 
1408 	memcpy(ai, pai, sizeof(struct addrinfo));
1409 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1410 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1411 	ai->ai_addr->sa_len = afd->a_socklen;
1412 	ai->ai_addrlen = afd->a_socklen;
1413 	if (ai->ai_family == PF_LOCAL) {
1414 		size_t n = strnlen(addr, afd->a_addrlen);
1415 
1416 		ai->ai_addrlen -= afd->a_addrlen - n;
1417 		ai->ai_addr->sa_len -= afd->a_addrlen - n;
1418 	}
1419 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1420 	p = (char *)(void *)(ai->ai_addr);
1421 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1422 	return ai;
1423 }
1424 
1425 /* XXX need to malloc() the same way we do from other functions! */
1426 static struct addrinfo *
1427 copy_ai(const struct addrinfo *pai)
1428 {
1429 	struct addrinfo *ai;
1430 	size_t l;
1431 
1432 	l = sizeof(*ai) + pai->ai_addrlen;
1433 	if ((ai = (struct addrinfo *)malloc(l)) == NULL)
1434 		return NULL;
1435 	memset(ai, 0, l);
1436 	memcpy(ai, pai, sizeof(*ai));
1437 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1438 	memcpy(ai->ai_addr, pai->ai_addr, pai->ai_addrlen);
1439 
1440 	if (pai->ai_canonname) {
1441 		l = strlen(pai->ai_canonname) + 1;
1442 		if ((ai->ai_canonname = malloc(l)) == NULL) {
1443 			free(ai);
1444 			return NULL;
1445 		}
1446 		strlcpy(ai->ai_canonname, pai->ai_canonname, l);
1447 	} else {
1448 		/* just to make sure */
1449 		ai->ai_canonname = NULL;
1450 	}
1451 
1452 	ai->ai_next = NULL;
1453 
1454 	return ai;
1455 }
1456 
1457 static int
1458 get_portmatch(const struct addrinfo *ai, const char *servname)
1459 {
1460 
1461 	/* get_port does not touch first argument when matchonly == 1. */
1462 	/* LINTED const cast */
1463 	return get_port((struct addrinfo *)ai, servname, 1);
1464 }
1465 
1466 static int
1467 get_port(struct addrinfo *ai, const char *servname, int matchonly)
1468 {
1469 	const char *proto;
1470 	struct servent *sp;
1471 	int port, error;
1472 	int allownumeric;
1473 
1474 	if (servname == NULL)
1475 		return 0;
1476 	switch (ai->ai_family) {
1477 	case AF_LOCAL:
1478 		/* AF_LOCAL ignores servname silently. */
1479 		return (0);
1480 	case AF_INET:
1481 #ifdef AF_INET6
1482 	case AF_INET6:
1483 #endif
1484 		break;
1485 	default:
1486 		return 0;
1487 	}
1488 
1489 	switch (ai->ai_socktype) {
1490 	case SOCK_RAW:
1491 		return EAI_SERVICE;
1492 	case SOCK_DGRAM:
1493 	case SOCK_STREAM:
1494 	case SOCK_SEQPACKET:
1495 		allownumeric = 1;
1496 		break;
1497 	case ANY:
1498 		switch (ai->ai_family) {
1499 		case AF_INET:
1500 #ifdef AF_INET6
1501 		case AF_INET6:
1502 #endif
1503 			allownumeric = 1;
1504 			break;
1505 		default:
1506 			allownumeric = 0;
1507 			break;
1508 		}
1509 		break;
1510 	default:
1511 		return EAI_SOCKTYPE;
1512 	}
1513 
1514 	error = str2number(servname, &port);
1515 	if (error == 0) {
1516 		if (!allownumeric)
1517 			return EAI_SERVICE;
1518 		if (port < 0 || port > 65535)
1519 			return EAI_SERVICE;
1520 		port = htons(port);
1521 	} else {
1522 		if (ai->ai_flags & AI_NUMERICSERV)
1523 			return EAI_NONAME;
1524 
1525 		switch (ai->ai_protocol) {
1526 		case IPPROTO_UDP:
1527 			proto = "udp";
1528 			break;
1529 		case IPPROTO_TCP:
1530 			proto = "tcp";
1531 			break;
1532 		case IPPROTO_SCTP:
1533 			proto = "sctp";
1534 			break;
1535 		case IPPROTO_UDPLITE:
1536 			proto = "udplite";
1537 			break;
1538 		default:
1539 			proto = NULL;
1540 			break;
1541 		}
1542 
1543 		if ((sp = getservbyname(servname, proto)) == NULL)
1544 			return EAI_SERVICE;
1545 		port = sp->s_port;
1546 	}
1547 
1548 	if (!matchonly) {
1549 		switch (ai->ai_family) {
1550 		case AF_INET:
1551 			((struct sockaddr_in *)(void *)
1552 			    ai->ai_addr)->sin_port = port;
1553 			break;
1554 #ifdef INET6
1555 		case AF_INET6:
1556 			((struct sockaddr_in6 *)(void *)
1557 			    ai->ai_addr)->sin6_port = port;
1558 			break;
1559 #endif
1560 		}
1561 	}
1562 
1563 	return 0;
1564 }
1565 
1566 static const struct afd *
1567 find_afd(int af)
1568 {
1569 	const struct afd *afd;
1570 
1571 	if (af == PF_UNSPEC)
1572 		return NULL;
1573 	for (afd = afdl; afd->a_af; afd++) {
1574 		if (afd->a_af == af)
1575 			return afd;
1576 	}
1577 	return NULL;
1578 }
1579 
1580 /*
1581  * RFC 3493: AI_ADDRCONFIG check.  Determines which address families are
1582  * configured on the local system and correlates with pai->ai_family value.
1583  * If an address family is not configured on the system, it will not be
1584  * queried for.  For this purpose, loopback addresses are not considered
1585  * configured addresses.
1586  *
1587  * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1588  * _dns_getaddrinfo.
1589  */
1590 static int
1591 addrconfig(struct addrinfo *pai)
1592 {
1593 	struct ifaddrs *ifaddrs, *ifa;
1594 	struct sockaddr_in *sin;
1595 #ifdef INET6
1596 	struct sockaddr_in6 *sin6;
1597 #endif
1598 	int seen_inet = 0, seen_inet6 = 0;
1599 
1600 	if (getifaddrs(&ifaddrs) != 0)
1601 		return (0);
1602 
1603 	for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
1604 		if (ifa->ifa_addr == NULL || (ifa->ifa_flags & IFF_UP) == 0)
1605 			continue;
1606 		switch (ifa->ifa_addr->sa_family) {
1607 		case AF_INET:
1608 			if (seen_inet)
1609 				continue;
1610 			sin = (struct sockaddr_in *)(ifa->ifa_addr);
1611 			if (htonl(sin->sin_addr.s_addr) == INADDR_LOOPBACK)
1612 				continue;
1613 			seen_inet = 1;
1614 			break;
1615 #ifdef INET6
1616 		case AF_INET6:
1617 			if (seen_inet6)
1618 				continue;
1619 			sin6 = (struct sockaddr_in6 *)(ifa->ifa_addr);
1620 			if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
1621 				continue;
1622 			if ((ifa->ifa_flags & IFT_LOOP) != 0 &&
1623 			    IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
1624 				continue;
1625 			if (is_ifdisabled(ifa->ifa_name))
1626 				continue;
1627 			seen_inet6 = 1;
1628 			break;
1629 #endif
1630 		}
1631 	}
1632 	freeifaddrs(ifaddrs);
1633 
1634 	switch(pai->ai_family) {
1635 	case AF_INET6:
1636 		return (seen_inet6);
1637 	case AF_INET:
1638 		return (seen_inet);
1639 	case AF_UNSPEC:
1640 		if (seen_inet == seen_inet6)
1641 			return (seen_inet);
1642 		pai->ai_family = seen_inet ? AF_INET : AF_INET6;
1643 		return (1);
1644 	}
1645 	return (1);
1646 }
1647 
1648 #ifdef INET6
1649 static int
1650 is_ifdisabled(char *name)
1651 {
1652 	struct in6_ndireq nd;
1653 	int fd;
1654 
1655 	if ((fd = _socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
1656 		return (-1);
1657 	memset(&nd, 0, sizeof(nd));
1658 	strlcpy(nd.ifname, name, sizeof(nd.ifname));
1659 	if (_ioctl(fd, SIOCGIFINFO_IN6, &nd) < 0) {
1660 		_close(fd);
1661 		return (-1);
1662 	}
1663 	_close(fd);
1664 	return ((nd.ndi.flags & ND6_IFF_IFDISABLED) != 0);
1665 }
1666 
1667 /* convert a string to a scope identifier. XXX: IPv6 specific */
1668 static int
1669 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1670 {
1671 	u_long lscopeid;
1672 	struct in6_addr *a6;
1673 	char *ep;
1674 
1675 	a6 = &sin6->sin6_addr;
1676 
1677 	/* empty scopeid portion is invalid */
1678 	if (*scope == '\0')
1679 		return -1;
1680 
1681 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) ||
1682 	    IN6_IS_ADDR_MC_NODELOCAL(a6)) {
1683 		/*
1684 		 * We currently assume a one-to-one mapping between links
1685 		 * and interfaces, so we simply use interface indices for
1686 		 * like-local scopes.
1687 		 */
1688 		*scopeid = if_nametoindex(scope);
1689 		if (*scopeid == 0)
1690 			goto trynumeric;
1691 		return 0;
1692 	}
1693 
1694 	/* still unclear about literal, allow numeric only - placeholder */
1695 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1696 		goto trynumeric;
1697 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1698 		goto trynumeric;
1699 	else
1700 		goto trynumeric;	/* global */
1701 
1702 	/* try to convert to a numeric id as a last resort */
1703   trynumeric:
1704 	errno = 0;
1705 	lscopeid = strtoul(scope, &ep, 10);
1706 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1707 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1708 		return 0;
1709 	else
1710 		return -1;
1711 }
1712 #endif
1713 
1714 
1715 #ifdef NS_CACHING
1716 static int
1717 addrinfo_id_func(char *buffer, size_t *buffer_size, va_list ap,
1718     void *cache_mdata)
1719 {
1720 	res_state statp;
1721 	u_long res_options;
1722 
1723 	const int op_id = 0;	/* identifies the getaddrinfo for the cache */
1724 	char *hostname;
1725 	struct addrinfo *hints;
1726 
1727 	char *p;
1728 	int ai_flags, ai_family, ai_socktype, ai_protocol;
1729 	size_t desired_size, size;
1730 
1731 	statp = __res_state();
1732 	res_options = statp->options & (RES_RECURSE | RES_DEFNAMES |
1733 	    RES_DNSRCH | RES_NOALIASES | RES_USE_INET6);
1734 
1735 	hostname = va_arg(ap, char *);
1736 	hints = va_arg(ap, struct addrinfo *);
1737 
1738 	desired_size = sizeof(res_options) + sizeof(int) + sizeof(int) * 4;
1739 	if (hostname != NULL) {
1740 		size = strlen(hostname);
1741 		desired_size += size + 1;
1742 	} else
1743 		size = 0;
1744 
1745 	if (desired_size > *buffer_size) {
1746 		*buffer_size = desired_size;
1747 		return (NS_RETURN);
1748 	}
1749 
1750 	if (hints == NULL)
1751 		ai_flags = ai_family = ai_socktype = ai_protocol = 0;
1752 	else {
1753 		ai_flags = hints->ai_flags;
1754 		ai_family = hints->ai_family;
1755 		ai_socktype = hints->ai_socktype;
1756 		ai_protocol = hints->ai_protocol;
1757 	}
1758 
1759 	p = buffer;
1760 	memcpy(p, &res_options, sizeof(res_options));
1761 	p += sizeof(res_options);
1762 
1763 	memcpy(p, &op_id, sizeof(int));
1764 	p += sizeof(int);
1765 
1766 	memcpy(p, &ai_flags, sizeof(int));
1767 	p += sizeof(int);
1768 
1769 	memcpy(p, &ai_family, sizeof(int));
1770 	p += sizeof(int);
1771 
1772 	memcpy(p, &ai_socktype, sizeof(int));
1773 	p += sizeof(int);
1774 
1775 	memcpy(p, &ai_protocol, sizeof(int));
1776 	p += sizeof(int);
1777 
1778 	if (hostname != NULL)
1779 		memcpy(p, hostname, size);
1780 
1781 	*buffer_size = desired_size;
1782 	return (NS_SUCCESS);
1783 }
1784 
1785 static int
1786 addrinfo_marshal_func(char *buffer, size_t *buffer_size, void *retval,
1787     va_list ap, void *cache_mdata)
1788 {
1789 	struct addrinfo	*ai, *cai;
1790 	char *p;
1791 	size_t desired_size, size, ai_size;
1792 
1793 	ai = *((struct addrinfo **)retval);
1794 
1795 	desired_size = sizeof(size_t);
1796 	ai_size = 0;
1797 	for (cai = ai; cai != NULL; cai = cai->ai_next) {
1798 		desired_size += sizeof(struct addrinfo) + cai->ai_addrlen;
1799 		if (cai->ai_canonname != NULL)
1800 			desired_size += sizeof(size_t) +
1801 			    strlen(cai->ai_canonname);
1802 		++ai_size;
1803 	}
1804 
1805 	if (desired_size > *buffer_size) {
1806 		/* this assignment is here for future use */
1807 		errno = ERANGE;
1808 		*buffer_size = desired_size;
1809 		return (NS_RETURN);
1810 	}
1811 
1812 	memset(buffer, 0, desired_size);
1813 	p = buffer;
1814 
1815 	memcpy(p, &ai_size, sizeof(size_t));
1816 	p += sizeof(size_t);
1817 	for (cai = ai; cai != NULL; cai = cai->ai_next) {
1818 		memcpy(p, cai, sizeof(struct addrinfo));
1819 		p += sizeof(struct addrinfo);
1820 
1821 		memcpy(p, cai->ai_addr, cai->ai_addrlen);
1822 		p += cai->ai_addrlen;
1823 
1824 		if (cai->ai_canonname != NULL) {
1825 			size = strlen(cai->ai_canonname);
1826 			memcpy(p, &size, sizeof(size_t));
1827 			p += sizeof(size_t);
1828 
1829 			memcpy(p, cai->ai_canonname, size);
1830 			p += size;
1831 		}
1832 	}
1833 
1834 	return (NS_SUCCESS);
1835 }
1836 
1837 static int
1838 addrinfo_unmarshal_func(char *buffer, size_t buffer_size, void *retval,
1839     va_list ap, void *cache_mdata)
1840 {
1841 	struct addrinfo	new_ai, *result, *sentinel, *lasts;
1842 
1843 	char *p;
1844 	size_t ai_size, ai_i, size;
1845 
1846 	p = buffer;
1847 	memcpy(&ai_size, p, sizeof(size_t));
1848 	p += sizeof(size_t);
1849 
1850 	result = NULL;
1851 	lasts = NULL;
1852 	for (ai_i = 0; ai_i < ai_size; ++ai_i) {
1853 		memcpy(&new_ai, p, sizeof(struct addrinfo));
1854 		p += sizeof(struct addrinfo);
1855 		size = new_ai.ai_addrlen + sizeof(struct addrinfo) +
1856 			_ALIGNBYTES;
1857 
1858 		sentinel = (struct addrinfo *)malloc(size);
1859 		memset(sentinel, 0, size);
1860 
1861 		memcpy(sentinel, &new_ai, sizeof(struct addrinfo));
1862 		sentinel->ai_addr = (struct sockaddr *)_ALIGN((char *)sentinel +
1863 		    sizeof(struct addrinfo));
1864 
1865 		memcpy(sentinel->ai_addr, p, new_ai.ai_addrlen);
1866 		p += new_ai.ai_addrlen;
1867 
1868 		if (new_ai.ai_canonname != NULL) {
1869 			memcpy(&size, p, sizeof(size_t));
1870 			p += sizeof(size_t);
1871 
1872 			sentinel->ai_canonname = (char *)malloc(size + 1);
1873 			memset(sentinel->ai_canonname, 0, size + 1);
1874 
1875 			memcpy(sentinel->ai_canonname, p, size);
1876 			p += size;
1877 		}
1878 
1879 		if (result == NULL) {
1880 			result = sentinel;
1881 			lasts = sentinel;
1882 		} else {
1883 			lasts->ai_next = sentinel;
1884 			lasts = sentinel;
1885 		}
1886 	}
1887 
1888 	*((struct addrinfo **)retval) = result;
1889 	return (NS_SUCCESS);
1890 }
1891 #endif /* NS_CACHING */
1892 
1893 /*
1894  * FQDN hostname, DNS lookup
1895  */
1896 static int
1897 explore_fqdn(const struct addrinfo *pai, const char *hostname,
1898     const char *servname, struct addrinfo **res)
1899 {
1900 	struct addrinfo *result;
1901 	struct addrinfo *cur;
1902 	int error = 0;
1903 
1904 #ifdef NS_CACHING
1905 	static const nss_cache_info cache_info =
1906 	NS_COMMON_CACHE_INFO_INITIALIZER(
1907 		hosts, NULL, addrinfo_id_func, addrinfo_marshal_func,
1908 		addrinfo_unmarshal_func);
1909 #endif
1910 	static const ns_dtab dtab[] = {
1911 		NS_FILES_CB(_files_getaddrinfo, NULL)
1912 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
1913 		NS_NIS_CB(_yp_getaddrinfo, NULL)
1914 #ifdef NS_CACHING
1915 		NS_CACHE_CB(&cache_info)
1916 #endif
1917 		{ 0 }
1918 	};
1919 
1920 	result = NULL;
1921 
1922 	/*
1923 	 * if the servname does not match socktype/protocol, ignore it.
1924 	 */
1925 	if (get_portmatch(pai, servname) != 0)
1926 		return 0;
1927 
1928 	switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1929 			default_dns_files, hostname, pai)) {
1930 	case NS_TRYAGAIN:
1931 		error = EAI_AGAIN;
1932 		goto free;
1933 	case NS_UNAVAIL:
1934 		error = EAI_FAIL;
1935 		goto free;
1936 	case NS_NOTFOUND:
1937 		error = EAI_NONAME;
1938 		goto free;
1939 	case NS_SUCCESS:
1940 		error = 0;
1941 		for (cur = result; cur; cur = cur->ai_next) {
1942 			GET_PORT(cur, servname);
1943 			/* canonname should be filled already */
1944 		}
1945 		break;
1946 	}
1947 
1948 	*res = result;
1949 
1950 	return 0;
1951 
1952 free:
1953 	if (result)
1954 		freeaddrinfo(result);
1955 	return error;
1956 }
1957 
1958 #ifdef DEBUG
1959 static const char AskedForGot[] =
1960 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1961 #endif
1962 
1963 static struct addrinfo *
1964 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1965     const struct addrinfo *pai, res_state res)
1966 {
1967 	struct addrinfo sentinel, *cur;
1968 	struct addrinfo ai;
1969 	const struct afd *afd;
1970 	char *canonname;
1971 	const HEADER *hp;
1972 	const u_char *cp;
1973 	int n;
1974 	const u_char *eom;
1975 	char *bp, *ep;
1976 	int type, class, ancount, qdcount;
1977 	int haveanswer, had_error;
1978 	char tbuf[MAXDNAME];
1979 	int (*name_ok)(const char *);
1980 	char hostbuf[8*1024];
1981 
1982 	memset(&sentinel, 0, sizeof(sentinel));
1983 	cur = &sentinel;
1984 
1985 	canonname = NULL;
1986 	eom = answer->buf + anslen;
1987 	switch (qtype) {
1988 	case T_A:
1989 	case T_AAAA:
1990 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
1991 		name_ok = res_hnok;
1992 		break;
1993 	default:
1994 		return (NULL);	/* XXX should be abort(); */
1995 	}
1996 	/*
1997 	 * find first satisfactory answer
1998 	 */
1999 	hp = &answer->hdr;
2000 	ancount = ntohs(hp->ancount);
2001 	qdcount = ntohs(hp->qdcount);
2002 	bp = hostbuf;
2003 	ep = hostbuf + sizeof hostbuf;
2004 	cp = answer->buf + HFIXEDSZ;
2005 	if (qdcount != 1) {
2006 		RES_SET_H_ERRNO(res, NO_RECOVERY);
2007 		return (NULL);
2008 	}
2009 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
2010 	if ((n < 0) || !(*name_ok)(bp)) {
2011 		RES_SET_H_ERRNO(res, NO_RECOVERY);
2012 		return (NULL);
2013 	}
2014 	cp += n + QFIXEDSZ;
2015 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
2016 		/* res_send() has already verified that the query name is the
2017 		 * same as the one we sent; this just gets the expanded name
2018 		 * (i.e., with the succeeding search-domain tacked on).
2019 		 */
2020 		n = strlen(bp) + 1;		/* for the \0 */
2021 		if (n >= MAXHOSTNAMELEN) {
2022 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2023 			return (NULL);
2024 		}
2025 		canonname = bp;
2026 		bp += n;
2027 		/* The qname can be abbreviated, but h_name is now absolute. */
2028 		qname = canonname;
2029 	}
2030 	haveanswer = 0;
2031 	had_error = 0;
2032 	while (ancount-- > 0 && cp < eom && !had_error) {
2033 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
2034 		if ((n < 0) || !(*name_ok)(bp)) {
2035 			had_error++;
2036 			continue;
2037 		}
2038 		cp += n;			/* name */
2039 		type = _getshort(cp);
2040  		cp += INT16SZ;			/* type */
2041 		class = _getshort(cp);
2042  		cp += INT16SZ + INT32SZ;	/* class, TTL */
2043 		n = _getshort(cp);
2044 		cp += INT16SZ;			/* len */
2045 		if (class != C_IN) {
2046 			/* XXX - debug? syslog? */
2047 			cp += n;
2048 			continue;		/* XXX - had_error++ ? */
2049 		}
2050 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
2051 		    type == T_CNAME) {
2052 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
2053 			if ((n < 0) || !(*name_ok)(tbuf)) {
2054 				had_error++;
2055 				continue;
2056 			}
2057 			cp += n;
2058 			/* Get canonical name. */
2059 			n = strlen(tbuf) + 1;	/* for the \0 */
2060 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
2061 				had_error++;
2062 				continue;
2063 			}
2064 			strlcpy(bp, tbuf, ep - bp);
2065 			canonname = bp;
2066 			bp += n;
2067 			continue;
2068 		}
2069 		if (qtype == T_ANY) {
2070 			if (!(type == T_A || type == T_AAAA)) {
2071 				cp += n;
2072 				continue;
2073 			}
2074 		} else if (type != qtype) {
2075 #ifdef DEBUG
2076 			if (type != T_KEY && type != T_SIG &&
2077 			    type != ns_t_dname)
2078 				syslog(LOG_NOTICE|LOG_AUTH,
2079 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
2080 				       qname, p_class(C_IN), p_type(qtype),
2081 				       p_type(type));
2082 #endif
2083 			cp += n;
2084 			continue;		/* XXX - had_error++ ? */
2085 		}
2086 		switch (type) {
2087 		case T_A:
2088 		case T_AAAA:
2089 			if (strcasecmp(canonname, bp) != 0) {
2090 #ifdef DEBUG
2091 				syslog(LOG_NOTICE|LOG_AUTH,
2092 				       AskedForGot, canonname, bp);
2093 #endif
2094 				cp += n;
2095 				continue;	/* XXX - had_error++ ? */
2096 			}
2097 			if (type == T_A && n != INADDRSZ) {
2098 				cp += n;
2099 				continue;
2100 			}
2101 			if (type == T_AAAA && n != IN6ADDRSZ) {
2102 				cp += n;
2103 				continue;
2104 			}
2105 #ifdef FILTER_V4MAPPED
2106 			if (type == T_AAAA) {
2107 				struct in6_addr in6;
2108 				memcpy(&in6, cp, sizeof(in6));
2109 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
2110 					cp += n;
2111 					continue;
2112 				}
2113 			}
2114 #endif
2115 			if (!haveanswer) {
2116 				int nn;
2117 
2118 				canonname = bp;
2119 				nn = strlen(bp) + 1;	/* for the \0 */
2120 				bp += nn;
2121 			}
2122 
2123 			/* don't overwrite pai */
2124 			ai = *pai;
2125 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
2126 			afd = find_afd(ai.ai_family);
2127 			if (afd == NULL) {
2128 				cp += n;
2129 				continue;
2130 			}
2131 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
2132 			if (cur->ai_next == NULL)
2133 				had_error++;
2134 			while (cur && cur->ai_next)
2135 				cur = cur->ai_next;
2136 			cp += n;
2137 			break;
2138 		default:
2139 			abort();
2140 		}
2141 		if (!had_error)
2142 			haveanswer++;
2143 	}
2144 	if (haveanswer) {
2145 #if defined(RESOLVSORT)
2146 		/*
2147 		 * We support only IPv4 address for backward
2148 		 * compatibility against gethostbyname(3).
2149 		 */
2150 		if (res->nsort && qtype == T_A) {
2151 			if (addr4sort(&sentinel, res) < 0) {
2152 				freeaddrinfo(sentinel.ai_next);
2153 				RES_SET_H_ERRNO(res, NO_RECOVERY);
2154 				return NULL;
2155 			}
2156 		}
2157 #endif /*RESOLVSORT*/
2158 		if (!canonname)
2159 			(void)get_canonname(pai, sentinel.ai_next, qname);
2160 		else
2161 			(void)get_canonname(pai, sentinel.ai_next, canonname);
2162 		RES_SET_H_ERRNO(res, NETDB_SUCCESS);
2163 		return sentinel.ai_next;
2164 	}
2165 
2166 	/*
2167 	 * We could have walked a CNAME chain, but the ultimate target
2168 	 * may not have what we looked for.
2169 	 */
2170 	RES_SET_H_ERRNO(res, ntohs(hp->ancount) > 0 ? NO_DATA : NO_RECOVERY);
2171 	return NULL;
2172 }
2173 
2174 #ifdef RESOLVSORT
2175 struct addr_ptr {
2176 	struct addrinfo *ai;
2177 	int aval;
2178 };
2179 
2180 static int
2181 addr4sort(struct addrinfo *sentinel, res_state res)
2182 {
2183 	struct addrinfo *ai;
2184 	struct addr_ptr *addrs, addr;
2185 	struct sockaddr_in *sin;
2186 	int naddrs, i, j;
2187 	int needsort = 0;
2188 
2189 	if (!sentinel)
2190 		return -1;
2191 	naddrs = 0;
2192 	for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
2193 		naddrs++;
2194 	if (naddrs < 2)
2195 		return 0;		/* We don't need sorting. */
2196 	if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
2197 		return -1;
2198 	i = 0;
2199 	for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
2200 		sin = (struct sockaddr_in *)ai->ai_addr;
2201 		for (j = 0; (unsigned)j < res->nsort; j++) {
2202 			if (res->sort_list[j].addr.s_addr ==
2203 			    (sin->sin_addr.s_addr & res->sort_list[j].mask))
2204 				break;
2205 		}
2206 		addrs[i].ai = ai;
2207 		addrs[i].aval = j;
2208 		if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
2209 			needsort = i;
2210 		i++;
2211 	}
2212 	if (!needsort) {
2213 		free(addrs);
2214 		return 0;
2215 	}
2216 
2217 	while (needsort < naddrs) {
2218 		for (j = needsort - 1; j >= 0; j--) {
2219 			if (addrs[j].aval > addrs[j+1].aval) {
2220 				addr = addrs[j];
2221 				addrs[j] = addrs[j + 1];
2222 				addrs[j + 1] = addr;
2223 			} else
2224 				break;
2225 		}
2226 		needsort++;
2227 	}
2228 
2229 	ai = sentinel;
2230 	for (i = 0; i < naddrs; ++i) {
2231 		ai->ai_next = addrs[i].ai;
2232 		ai = ai->ai_next;
2233 	}
2234 	ai->ai_next = NULL;
2235 	free(addrs);
2236 	return 0;
2237 }
2238 #endif /*RESOLVSORT*/
2239 
2240 /*ARGSUSED*/
2241 static int
2242 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
2243 {
2244 	struct addrinfo *ai, ai0;
2245 	querybuf *buf, *buf2;
2246 	const char *hostname;
2247 	const struct addrinfo *pai;
2248 	struct addrinfo sentinel, *cur;
2249 	struct res_target q, q2;
2250 	res_state res;
2251 
2252 	hostname = va_arg(ap, char *);
2253 	pai = va_arg(ap, const struct addrinfo *);
2254 
2255 	memset(&q, 0, sizeof(q));
2256 	memset(&q2, 0, sizeof(q2));
2257 	memset(&sentinel, 0, sizeof(sentinel));
2258 	cur = &sentinel;
2259 
2260 	res = __res_state();
2261 
2262 	buf = malloc(sizeof(*buf));
2263 	if (!buf) {
2264 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2265 		return NS_NOTFOUND;
2266 	}
2267 	buf2 = malloc(sizeof(*buf2));
2268 	if (!buf2) {
2269 		free(buf);
2270 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2271 		return NS_NOTFOUND;
2272 	}
2273 
2274 	if (pai->ai_family == AF_INET6 &&
2275 	    (pai->ai_flags & AI_V4MAPPED) == AI_V4MAPPED) {
2276 		ai0 = *pai;
2277 		ai0.ai_family = AF_UNSPEC;
2278 		pai = &ai0;
2279 	}
2280 
2281 	switch (pai->ai_family) {
2282 	case AF_UNSPEC:
2283 		q.name = hostname;
2284 		q.qclass = C_IN;
2285 		q.qtype = T_A;
2286 		q.answer = buf->buf;
2287 		q.anslen = sizeof(buf->buf);
2288 		q.next = &q2;
2289 		q2.name = hostname;
2290 		q2.qclass = C_IN;
2291 		q2.qtype = T_AAAA;
2292 		q2.answer = buf2->buf;
2293 		q2.anslen = sizeof(buf2->buf);
2294 		break;
2295 	case AF_INET:
2296 		q.name = hostname;
2297 		q.qclass = C_IN;
2298 		q.qtype = T_A;
2299 		q.answer = buf->buf;
2300 		q.anslen = sizeof(buf->buf);
2301 		break;
2302 	case AF_INET6:
2303 		q.name = hostname;
2304 		q.qclass = C_IN;
2305 		q.qtype = T_AAAA;
2306 		q.answer = buf->buf;
2307 		q.anslen = sizeof(buf->buf);
2308 		break;
2309 	default:
2310 		free(buf);
2311 		free(buf2);
2312 		return NS_UNAVAIL;
2313 	}
2314 
2315 	if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) {
2316 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2317 		free(buf);
2318 		free(buf2);
2319 		return NS_NOTFOUND;
2320 	}
2321 
2322 	if (res_searchN(hostname, &q, res) < 0) {
2323 		free(buf);
2324 		free(buf2);
2325 		return NS_NOTFOUND;
2326 	}
2327 	/* prefer IPv6 */
2328 	if (q.next) {
2329 		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, res);
2330 		if (ai) {
2331 			cur->ai_next = ai;
2332 			while (cur && cur->ai_next)
2333 				cur = cur->ai_next;
2334 		}
2335 	}
2336 	if (!ai || pai->ai_family != AF_UNSPEC ||
2337 	    (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) != AI_V4MAPPED) {
2338 		ai = getanswer(buf, q.n, q.name, q.qtype, pai, res);
2339 		if (ai)
2340 			cur->ai_next = ai;
2341 	}
2342 	free(buf);
2343 	free(buf2);
2344 	if (sentinel.ai_next == NULL)
2345 		switch (res->res_h_errno) {
2346 		case HOST_NOT_FOUND:
2347 		case NO_DATA:
2348 			return NS_NOTFOUND;
2349 		case TRY_AGAIN:
2350 			return NS_TRYAGAIN;
2351 		default:
2352 			return NS_UNAVAIL;
2353 		}
2354 	*((struct addrinfo **)rv) = sentinel.ai_next;
2355 	return NS_SUCCESS;
2356 }
2357 
2358 static void
2359 _sethtent(FILE **hostf)
2360 {
2361 	if (!*hostf)
2362 		*hostf = fopen(_PATH_HOSTS, "re");
2363 	else
2364 		rewind(*hostf);
2365 }
2366 
2367 static void
2368 _endhtent(FILE **hostf)
2369 {
2370 	if (*hostf) {
2371 		(void) fclose(*hostf);
2372 		*hostf = NULL;
2373 	}
2374 }
2375 
2376 static struct addrinfo *
2377 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2378 {
2379 	char *p;
2380 	char *cp, *tname, *cname;
2381 	struct addrinfo hints, *res0, *res;
2382 	int error;
2383 	const char *addr;
2384 	char hostbuf[8*1024];
2385 
2386 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
2387 		return (NULL);
2388 again:
2389 	if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2390 		return (NULL);
2391 	if (*p == '#')
2392 		goto again;
2393 	cp = strpbrk(p, "#\n");
2394 	if (cp != NULL)
2395 		*cp = '\0';
2396 	if (!(cp = strpbrk(p, " \t")))
2397 		goto again;
2398 	*cp++ = '\0';
2399 	addr = p;
2400 	cname = NULL;
2401 	/* if this is not something we're looking for, skip it. */
2402 	while (cp && *cp) {
2403 		if (*cp == ' ' || *cp == '\t') {
2404 			cp++;
2405 			continue;
2406 		}
2407 		tname = cp;
2408 		if (cname == NULL)
2409 			cname = cp;
2410 		if ((cp = strpbrk(cp, " \t")) != NULL)
2411 			*cp++ = '\0';
2412 		if (strcasecmp(name, tname) == 0)
2413 			goto found;
2414 	}
2415 	goto again;
2416 
2417 found:
2418 	/* we should not glob socktype/protocol here */
2419 	memset(&hints, 0, sizeof(hints));
2420 	hints.ai_family = pai->ai_family;
2421 	hints.ai_socktype = SOCK_DGRAM;
2422 	hints.ai_protocol = 0;
2423 	hints.ai_flags = AI_NUMERICHOST;
2424 	if (pai->ai_family == AF_INET6 &&
2425 	    (pai->ai_flags & AI_V4MAPPED) == AI_V4MAPPED)
2426 		hints.ai_flags |= AI_V4MAPPED;
2427 	error = getaddrinfo(addr, "0", &hints, &res0);
2428 	if (error)
2429 		goto again;
2430 #ifdef FILTER_V4MAPPED
2431 	/* XXX should check all items in the chain */
2432 	if (res0->ai_family == AF_INET6 &&
2433 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2434 		freeaddrinfo(res0);
2435 		goto again;
2436 	}
2437 #endif
2438 	for (res = res0; res; res = res->ai_next) {
2439 		/* cover it up */
2440 		res->ai_flags = pai->ai_flags;
2441 		res->ai_socktype = pai->ai_socktype;
2442 		res->ai_protocol = pai->ai_protocol;
2443 
2444 		if (pai->ai_flags & AI_CANONNAME) {
2445 			if (get_canonname(pai, res, cname) != 0) {
2446 				freeaddrinfo(res0);
2447 				goto again;
2448 			}
2449 		}
2450 	}
2451 	return res0;
2452 }
2453 
2454 static struct addrinfo *
2455 _getht(FILE **hostf, const char *name, const struct addrinfo *pai,
2456      struct addrinfo *cur)
2457 {
2458 	struct addrinfo *p;
2459 
2460 	while ((p = _gethtent(hostf, name, pai)) != NULL) {
2461 		cur->ai_next = p;
2462 		while (cur && cur->ai_next)
2463 			cur = cur->ai_next;
2464 	}
2465 	return (cur);
2466 }
2467 
2468 /*ARGSUSED*/
2469 static int
2470 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2471 {
2472 	const char *name;
2473 	const struct addrinfo *pai;
2474 	struct addrinfo sentinel, *cur;
2475 	FILE *hostf = NULL;
2476 
2477 	name = va_arg(ap, char *);
2478 	pai = va_arg(ap, struct addrinfo *);
2479 
2480 	memset(&sentinel, 0, sizeof(sentinel));
2481 	cur = &sentinel;
2482 
2483 	_sethtent(&hostf);
2484 	if (pai->ai_family == AF_INET6 &&
2485 	    (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) == AI_V4MAPPED) {
2486 		struct addrinfo ai0 = *pai;
2487 
2488 		ai0.ai_flags &= ~AI_V4MAPPED;
2489 		cur = _getht(&hostf, name, &ai0, cur);
2490 		if (sentinel.ai_next == NULL) {
2491 			_sethtent(&hostf);
2492 			ai0.ai_flags |= AI_V4MAPPED;
2493 			cur = _getht(&hostf, name, &ai0, cur);
2494 		}
2495 	} else
2496 		cur = _getht(&hostf, name, pai, cur);
2497 	_endhtent(&hostf);
2498 
2499 	*((struct addrinfo **)rv) = sentinel.ai_next;
2500 	if (sentinel.ai_next == NULL)
2501 		return NS_NOTFOUND;
2502 	return NS_SUCCESS;
2503 }
2504 
2505 #ifdef YP
2506 /*ARGSUSED*/
2507 static struct addrinfo *
2508 _yphostent(char *line, const struct addrinfo *pai)
2509 {
2510 	struct addrinfo sentinel, *cur;
2511 	struct addrinfo hints, *res, *res0;
2512 	int error;
2513 	char *p = line;
2514 	const char *addr, *canonname;
2515 	char *nextline;
2516 	char *cp;
2517 
2518 	addr = canonname = NULL;
2519 
2520 	memset(&sentinel, 0, sizeof(sentinel));
2521 	cur = &sentinel;
2522 
2523 nextline:
2524 	/* terminate line */
2525 	cp = strchr(p, '\n');
2526 	if (cp) {
2527 		*cp++ = '\0';
2528 		nextline = cp;
2529 	} else
2530 		nextline = NULL;
2531 
2532 	cp = strpbrk(p, " \t");
2533 	if (cp == NULL) {
2534 		if (canonname == NULL)
2535 			return (NULL);
2536 		else
2537 			goto done;
2538 	}
2539 	*cp++ = '\0';
2540 
2541 	addr = p;
2542 
2543 	while (cp && *cp) {
2544 		if (*cp == ' ' || *cp == '\t') {
2545 			cp++;
2546 			continue;
2547 		}
2548 		if (!canonname)
2549 			canonname = cp;
2550 		if ((cp = strpbrk(cp, " \t")) != NULL)
2551 			*cp++ = '\0';
2552 	}
2553 
2554 	hints = *pai;
2555 	hints.ai_flags = AI_NUMERICHOST;
2556 	if (pai->ai_family == AF_INET6 &&
2557 	    (pai->ai_flags & AI_V4MAPPED) == AI_V4MAPPED)
2558 		hints.ai_flags |= AI_V4MAPPED;
2559 	error = getaddrinfo(addr, NULL, &hints, &res0);
2560 	if (error == 0) {
2561 		for (res = res0; res; res = res->ai_next) {
2562 			/* cover it up */
2563 			res->ai_flags = pai->ai_flags;
2564 
2565 			if (pai->ai_flags & AI_CANONNAME)
2566 				(void)get_canonname(pai, res, canonname);
2567 		}
2568 	} else
2569 		res0 = NULL;
2570 	if (res0) {
2571 		cur->ai_next = res0;
2572 		while (cur && cur->ai_next)
2573 			cur = cur->ai_next;
2574 	}
2575 
2576 	if (nextline) {
2577 		p = nextline;
2578 		goto nextline;
2579 	}
2580 
2581 done:
2582 	return sentinel.ai_next;
2583 }
2584 
2585 /*ARGSUSED*/
2586 static int
2587 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
2588 {
2589 	struct addrinfo sentinel, *cur;
2590 	struct addrinfo *ai = NULL;
2591 	char *ypbuf;
2592 	int ypbuflen, r;
2593 	const char *name;
2594 	const struct addrinfo *pai;
2595 	char *ypdomain;
2596 
2597 	if (_yp_check(&ypdomain) == 0)
2598 		return NS_UNAVAIL;
2599 
2600 	name = va_arg(ap, char *);
2601 	pai = va_arg(ap, const struct addrinfo *);
2602 
2603 	memset(&sentinel, 0, sizeof(sentinel));
2604 	cur = &sentinel;
2605 
2606 	/* ipnodes.byname can hold both IPv4/v6 */
2607 	r = yp_match(ypdomain, "ipnodes.byname", name,
2608 		(int)strlen(name), &ypbuf, &ypbuflen);
2609 	if (r == 0) {
2610 		ai = _yphostent(ypbuf, pai);
2611 		if (ai) {
2612 			cur->ai_next = ai;
2613 			while (cur && cur->ai_next)
2614 				cur = cur->ai_next;
2615 		}
2616 		free(ypbuf);
2617 	}
2618 
2619 	if (ai != NULL) {
2620 		struct sockaddr_in6 *sin6;
2621 
2622 		switch (ai->ai_family) {
2623 		case AF_INET:
2624 			goto done;
2625 		case AF_INET6:
2626 			sin6 = (struct sockaddr_in6 *)ai->ai_addr;
2627 			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2628 				goto done;
2629 			break;
2630 		}
2631 	}
2632 
2633 	/* hosts.byname is only for IPv4 (Solaris8) */
2634 	if (pai->ai_family == AF_UNSPEC || pai->ai_family == AF_INET ||
2635 	    ((pai->ai_family == AF_INET6 &&
2636 	     (pai->ai_flags & AI_V4MAPPED) == AI_V4MAPPED) &&
2637 	      (ai == NULL || (pai->ai_flags & AI_ALL) == AI_ALL))) {
2638 		r = yp_match(ypdomain, "hosts.byname", name,
2639 			(int)strlen(name), &ypbuf, &ypbuflen);
2640 		if (r == 0) {
2641 			struct addrinfo ai4;
2642 
2643 			ai4 = *pai;
2644 			if (pai->ai_family == AF_UNSPEC)
2645 				ai4.ai_family = AF_INET;
2646 			ai = _yphostent(ypbuf, &ai4);
2647 			if (ai) {
2648 				cur->ai_next = ai;
2649 				while (cur && cur->ai_next)
2650 					cur = cur->ai_next;
2651 			}
2652 			free(ypbuf);
2653 		}
2654 	}
2655 
2656 done:
2657 	if (sentinel.ai_next == NULL) {
2658 		RES_SET_H_ERRNO(__res_state(), HOST_NOT_FOUND);
2659 		return NS_NOTFOUND;
2660 	}
2661 	*((struct addrinfo **)rv) = sentinel.ai_next;
2662 	return NS_SUCCESS;
2663 }
2664 #endif
2665 
2666 /* resolver logic */
2667 
2668 /*
2669  * Formulate a normal query, send, and await answer.
2670  * Returned answer is placed in supplied buffer "answer".
2671  * Perform preliminary check of answer, returning success only
2672  * if no error is indicated and the answer count is nonzero.
2673  * Return the size of the response on success, -1 on error.
2674  * Error number is left in h_errno.
2675  *
2676  * Caller must parse answer and determine whether it answers the question.
2677  */
2678 static int
2679 res_queryN(const char *name, struct res_target *target, res_state res)
2680 {
2681 	u_char *buf;
2682 	HEADER *hp;
2683 	int n;
2684 	u_int oflags;
2685 	struct res_target *t;
2686 	int rcode;
2687 	int ancount;
2688 
2689 	rcode = NOERROR;
2690 	ancount = 0;
2691 
2692 	buf = malloc(MAXPACKET);
2693 	if (!buf) {
2694 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2695 		return -1;
2696 	}
2697 
2698 	for (t = target; t; t = t->next) {
2699 		int class, type;
2700 		u_char *answer;
2701 		int anslen;
2702 
2703 		hp = (HEADER *)(void *)t->answer;
2704 
2705 		/* make it easier... */
2706 		class = t->qclass;
2707 		type = t->qtype;
2708 		answer = t->answer;
2709 		anslen = t->anslen;
2710 
2711 		oflags = res->_flags;
2712 
2713 again:
2714 		hp->rcode = NOERROR;	/* default */
2715 
2716 #ifdef DEBUG
2717 		if (res->options & RES_DEBUG)
2718 			printf(";; res_query(%s, %d, %d)\n", name, class, type);
2719 #endif
2720 
2721 		n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2722 		    buf, MAXPACKET);
2723 		if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 &&
2724 		    (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U)
2725 			n = res_nopt(res, n, buf, MAXPACKET, anslen);
2726 		if (n <= 0) {
2727 #ifdef DEBUG
2728 			if (res->options & RES_DEBUG)
2729 				printf(";; res_query: mkquery failed\n");
2730 #endif
2731 			free(buf);
2732 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2733 			return (n);
2734 		}
2735 		n = res_nsend(res, buf, n, answer, anslen);
2736 		if (n < 0) {
2737 			/*
2738 			 * if the query choked with EDNS0, retry
2739 			 * without EDNS0
2740 			 */
2741 			if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC))
2742 			    != 0U &&
2743 			    ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) {
2744 				res->_flags |= RES_F_EDNS0ERR;
2745 				if (res->options & RES_DEBUG)
2746 					printf(";; res_nquery: retry without EDNS0\n");
2747 				goto again;
2748 			}
2749 			rcode = hp->rcode;	/* record most recent error */
2750 #ifdef DEBUG
2751 			if (res->options & RES_DEBUG)
2752 				printf(";; res_query: send error\n");
2753 #endif
2754 			continue;
2755 		}
2756 
2757 		if (n > anslen)
2758 			hp->rcode = FORMERR; /* XXX not very informative */
2759 		if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2760 			rcode = hp->rcode;	/* record most recent error */
2761 #ifdef DEBUG
2762 			if (res->options & RES_DEBUG)
2763 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2764 				    ntohs(hp->ancount));
2765 #endif
2766 			continue;
2767 		}
2768 
2769 		ancount += ntohs(hp->ancount);
2770 
2771 		t->n = n;
2772 	}
2773 
2774 	free(buf);
2775 
2776 	if (ancount == 0) {
2777 		switch (rcode) {
2778 		case NXDOMAIN:
2779 			RES_SET_H_ERRNO(res, HOST_NOT_FOUND);
2780 			break;
2781 		case SERVFAIL:
2782 			RES_SET_H_ERRNO(res, TRY_AGAIN);
2783 			break;
2784 		case NOERROR:
2785 			RES_SET_H_ERRNO(res, NO_DATA);
2786 			break;
2787 		case FORMERR:
2788 		case NOTIMP:
2789 		case REFUSED:
2790 		default:
2791 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2792 			break;
2793 		}
2794 		return (-1);
2795 	}
2796 	return (ancount);
2797 }
2798 
2799 /*
2800  * Formulate a normal query, send, and retrieve answer in supplied buffer.
2801  * Return the size of the response on success, -1 on error.
2802  * If enabled, implement search rules until answer or unrecoverable failure
2803  * is detected.  Error code, if any, is left in h_errno.
2804  */
2805 static int
2806 res_searchN(const char *name, struct res_target *target, res_state res)
2807 {
2808 	const char *cp, * const *domain;
2809 	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
2810 	u_int dots;
2811 	int trailing_dot, ret, saved_herrno;
2812 	int got_nodata = 0, got_servfail = 0, root_on_list = 0;
2813 	int tried_as_is = 0;
2814 	int searched = 0;
2815 	char abuf[MAXDNAME];
2816 
2817 	errno = 0;
2818 	RES_SET_H_ERRNO(res, HOST_NOT_FOUND); /* default, if we never query */
2819 	dots = 0;
2820 	for (cp = name; *cp; cp++)
2821 		dots += (*cp == '.');
2822 	trailing_dot = 0;
2823 	if (cp > name && *--cp == '.')
2824 		trailing_dot++;
2825 
2826 	/*
2827 	 * if there aren't any dots, it could be a user-level alias
2828 	 */
2829 	if (!dots &&
2830 	    (cp = res_hostalias(res, name, abuf, sizeof(abuf))) != NULL)
2831 		return (res_queryN(cp, target, res));
2832 
2833 	/*
2834 	 * If there are enough dots in the name, let's just give it a
2835 	 * try 'as is'. The threshold can be set with the "ndots" option.
2836 	 * Also, query 'as is', if there is a trailing dot in the name.
2837 	 */
2838 	saved_herrno = -1;
2839 	if (dots >= res->ndots || trailing_dot) {
2840 		ret = res_querydomainN(name, NULL, target, res);
2841 		if (ret > 0 || trailing_dot)
2842 			return (ret);
2843 		if (errno == ECONNREFUSED) {
2844 			RES_SET_H_ERRNO(res, TRY_AGAIN);
2845 			return (-1);
2846 		}
2847 		switch (res->res_h_errno) {
2848 		case NO_DATA:
2849 		case HOST_NOT_FOUND:
2850 			break;
2851 		case TRY_AGAIN:
2852 			if (hp->rcode == SERVFAIL)
2853 				break;
2854 			/* FALLTHROUGH */
2855 		default:
2856 			return (-1);
2857 		}
2858 		saved_herrno = res->res_h_errno;
2859 		tried_as_is++;
2860 	}
2861 
2862 	/*
2863 	 * We do at least one level of search if
2864 	 *	- there is no dot and RES_DEFNAME is set, or
2865 	 *	- there is at least one dot, there is no trailing dot,
2866 	 *	  and RES_DNSRCH is set.
2867 	 */
2868 	if ((!dots && (res->options & RES_DEFNAMES)) ||
2869 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2870 		int done = 0;
2871 
2872 		for (domain = (const char * const *)res->dnsrch;
2873 		   *domain && !done;
2874 		   domain++) {
2875 			searched = 1;
2876 
2877 			if (domain[0][0] == '\0' ||
2878 			    (domain[0][0] == '.' && domain[0][1] == '\0'))
2879 				root_on_list++;
2880 
2881 			if (root_on_list && tried_as_is)
2882 				continue;
2883 
2884 			ret = res_querydomainN(name, *domain, target, res);
2885 			if (ret > 0)
2886 				return (ret);
2887 
2888 			/*
2889 			 * If no server present, give up.
2890 			 * If name isn't found in this domain,
2891 			 * keep trying higher domains in the search list
2892 			 * (if that's enabled).
2893 			 * On a NO_DATA error, keep trying, otherwise
2894 			 * a wildcard entry of another type could keep us
2895 			 * from finding this entry higher in the domain.
2896 			 * If we get some other error (negative answer or
2897 			 * server failure), then stop searching up,
2898 			 * but try the input name below in case it's
2899 			 * fully-qualified.
2900 			 */
2901 			if (errno == ECONNREFUSED) {
2902 				RES_SET_H_ERRNO(res, TRY_AGAIN);
2903 				return (-1);
2904 			}
2905 
2906 			switch (res->res_h_errno) {
2907 			case NO_DATA:
2908 				got_nodata++;
2909 				/* FALLTHROUGH */
2910 			case HOST_NOT_FOUND:
2911 				/* keep trying */
2912 				break;
2913 			case TRY_AGAIN:
2914 				got_servfail++;
2915 				if (hp->rcode == SERVFAIL) {
2916 					/* try next search element, if any */
2917 					break;
2918 				}
2919 				/* FALLTHROUGH */
2920 			default:
2921 				/* anything else implies that we're done */
2922 				done++;
2923 			}
2924 			/*
2925 			 * if we got here for some reason other than DNSRCH,
2926 			 * we only wanted one iteration of the loop, so stop.
2927 			 */
2928 			if (!(res->options & RES_DNSRCH))
2929 			        done++;
2930 		}
2931 	}
2932 
2933 	switch (res->res_h_errno) {
2934 	case NO_DATA:
2935 	case HOST_NOT_FOUND:
2936 		break;
2937 	case TRY_AGAIN:
2938 		if (hp->rcode == SERVFAIL)
2939 			break;
2940 		/* FALLTHROUGH */
2941 	default:
2942 		goto giveup;
2943 	}
2944 
2945 	/*
2946 	 * If the query has not already been tried as is then try it
2947 	 * unless RES_NOTLDQUERY is set and there were no dots.
2948 	 */
2949 	if ((dots || !searched || !(res->options & RES_NOTLDQUERY)) &&
2950 	    !(tried_as_is || root_on_list)) {
2951 		ret = res_querydomainN(name, NULL, target, res);
2952 		if (ret > 0)
2953 			return (ret);
2954 	}
2955 
2956 	/*
2957 	 * if we got here, we didn't satisfy the search.
2958 	 * if we did an initial full query, return that query's h_errno
2959 	 * (note that we wouldn't be here if that query had succeeded).
2960 	 * else if we ever got a nodata, send that back as the reason.
2961 	 * else send back meaningless h_errno, that being the one from
2962 	 * the last DNSRCH we did.
2963 	 */
2964 giveup:
2965 	if (saved_herrno != -1)
2966 		RES_SET_H_ERRNO(res, saved_herrno);
2967 	else if (got_nodata)
2968 		RES_SET_H_ERRNO(res, NO_DATA);
2969 	else if (got_servfail)
2970 		RES_SET_H_ERRNO(res, TRY_AGAIN);
2971 	return (-1);
2972 }
2973 
2974 /*
2975  * Perform a call on res_query on the concatenation of name and domain,
2976  * removing a trailing dot from name if domain is NULL.
2977  */
2978 static int
2979 res_querydomainN(const char *name, const char *domain,
2980     struct res_target *target, res_state res)
2981 {
2982 	char nbuf[MAXDNAME];
2983 	const char *longname = nbuf;
2984 	size_t n, d;
2985 
2986 #ifdef DEBUG
2987 	if (res->options & RES_DEBUG)
2988 		printf(";; res_querydomain(%s, %s)\n",
2989 			name, domain?domain:"<Nil>");
2990 #endif
2991 	if (domain == NULL) {
2992 		/*
2993 		 * Check for trailing '.';
2994 		 * copy without '.' if present.
2995 		 */
2996 		n = strlen(name);
2997 		if (n >= MAXDNAME) {
2998 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2999 			return (-1);
3000 		}
3001 		if (n > 0 && name[--n] == '.') {
3002 			strncpy(nbuf, name, n);
3003 			nbuf[n] = '\0';
3004 		} else
3005 			longname = name;
3006 	} else {
3007 		n = strlen(name);
3008 		d = strlen(domain);
3009 		if (n + d + 1 >= MAXDNAME) {
3010 			RES_SET_H_ERRNO(res, NO_RECOVERY);
3011 			return (-1);
3012 		}
3013 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
3014 	}
3015 	return (res_queryN(longname, target, res));
3016 }
3017