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