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