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