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