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