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