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