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