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