xref: /dragonfly/lib/libc/net/getaddrinfo.c (revision e6d22e9b)
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 		switch(ai->ai_family) {
1296 		case AF_INET:
1297 #ifdef AF_INET6
1298 		case AF_INET6:
1299 #endif
1300 			allownumeric = 1;
1301 			break;
1302 		default:
1303 			allownumeric = 0;
1304 			break;
1305 		}
1306 		break;
1307 	default:
1308 		return EAI_SOCKTYPE;
1309 	}
1310 
1311 	error = str2number(servname, &port);
1312 	if (error == 0) {
1313 		if (!allownumeric)
1314 			return EAI_SERVICE;
1315 		if (port < 0 || port > 65535)
1316 			return EAI_SERVICE;
1317 		port = htons(port);
1318 	} else {
1319 		if (ai->ai_flags & AI_NUMERICSERV)
1320 			return EAI_NONAME;
1321 		switch (ai->ai_socktype) {
1322 		case SOCK_DGRAM:
1323 			proto = "udp";
1324 			break;
1325 		case SOCK_STREAM:
1326 			proto = "tcp";
1327 			break;
1328 		default:
1329 			proto = NULL;
1330 			break;
1331 		}
1332 
1333 		if ((sp = getservbyname(servname, proto)) == NULL)
1334 			return EAI_SERVICE;
1335 		port = sp->s_port;
1336 	}
1337 
1338 	if (!matchonly) {
1339 		switch (ai->ai_family) {
1340 		case AF_INET:
1341 			((struct sockaddr_in *)(void *)
1342 			    ai->ai_addr)->sin_port = port;
1343 			break;
1344 #ifdef INET6
1345 		case AF_INET6:
1346 			((struct sockaddr_in6 *)(void *)
1347 			    ai->ai_addr)->sin6_port = port;
1348 			break;
1349 #endif
1350 		}
1351 	}
1352 
1353 	return 0;
1354 }
1355 
1356 static const struct afd *
1357 find_afd(int af)
1358 {
1359 	const struct afd *afd;
1360 
1361 	if (af == PF_UNSPEC)
1362 		return NULL;
1363 	for (afd = afdl; afd->a_af; afd++) {
1364 		if (afd->a_af == af)
1365 			return afd;
1366 	}
1367 	return NULL;
1368 }
1369 
1370 /*
1371  * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
1372  * will take care of it.
1373  * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
1374  * if the code is right or not.
1375  *
1376  * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1377  * _dns_getaddrinfo.
1378  */
1379 static int
1380 addrconfig(struct addrinfo *pai)
1381 {
1382 	int s, af;
1383 
1384 	/*
1385 	 * TODO:
1386 	 * Note that implementation dependent test for address
1387 	 * configuration should be done everytime called
1388 	 * (or apropriate interval),
1389 	 * because addresses will be dynamically assigned or deleted.
1390 	 */
1391 	af = pai->ai_family;
1392 	if (af == AF_UNSPEC) {
1393 		if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1394 			af = AF_INET;
1395 		else {
1396 			_close(s);
1397 			if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1398 				af = AF_INET6;
1399 			else
1400 				_close(s);
1401 		}
1402 	}
1403 	if (af != AF_UNSPEC) {
1404 		if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
1405 			return 0;
1406 		_close(s);
1407 	}
1408 	pai->ai_family = af;
1409 	return 1;
1410 }
1411 
1412 #ifdef INET6
1413 /* convert a string to a scope identifier. XXX: IPv6 specific */
1414 static int
1415 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1416 {
1417 	u_long lscopeid;
1418 	struct in6_addr *a6;
1419 	char *ep;
1420 
1421 	a6 = &sin6->sin6_addr;
1422 
1423 	/* empty scopeid portion is invalid */
1424 	if (*scope == '\0')
1425 		return -1;
1426 
1427 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1428 		/*
1429 		 * We currently assume a one-to-one mapping between links
1430 		 * and interfaces, so we simply use interface indices for
1431 		 * like-local scopes.
1432 		 */
1433 		*scopeid = if_nametoindex(scope);
1434 		if (*scopeid == 0)
1435 			goto trynumeric;
1436 		return 0;
1437 	}
1438 
1439 	/* still unclear about literal, allow numeric only - placeholder */
1440 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1441 		goto trynumeric;
1442 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1443 		goto trynumeric;
1444 	else
1445 		goto trynumeric;	/* global */
1446 
1447 	/* try to convert to a numeric id as a last resort */
1448   trynumeric:
1449 	errno = 0;
1450 	lscopeid = strtoul(scope, &ep, 10);
1451 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1452 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1453 		return 0;
1454 	else
1455 		return -1;
1456 }
1457 #endif
1458 
1459 
1460 #ifdef NS_CACHING
1461 static int
1462 addrinfo_id_func(char *buffer, size_t *buffer_size, va_list ap,
1463 		 void *cache_mdata __unused)
1464 {
1465 	res_state statp;
1466 	u_long res_options;
1467 
1468 	const int op_id = 0;	/* identifies the getaddrinfo for the cache */
1469 	char *hostname;
1470 	struct addrinfo *hints;
1471 
1472 	char *p;
1473 	int ai_flags, ai_family, ai_socktype, ai_protocol;
1474 	size_t desired_size, size;
1475 
1476 	statp = __res_state();
1477 	res_options = statp->options & (RES_RECURSE | RES_DEFNAMES |
1478 	    RES_DNSRCH | RES_NOALIASES | RES_USE_INET6);
1479 
1480 	hostname = va_arg(ap, char *);
1481 	hints = va_arg(ap, struct addrinfo *);
1482 
1483 	desired_size = sizeof(res_options) + sizeof(int) + sizeof(int) * 4;
1484 	if (hostname != NULL) {
1485 		size = strlen(hostname);
1486 		desired_size += size + 1;
1487 	} else
1488 		size = 0;
1489 
1490 	if (desired_size > *buffer_size) {
1491 		*buffer_size = desired_size;
1492 		return (NS_RETURN);
1493 	}
1494 
1495 	if (hints == NULL)
1496 		ai_flags = ai_family = ai_socktype = ai_protocol = 0;
1497 	else {
1498 		ai_flags = hints->ai_flags;
1499 		ai_family = hints->ai_family;
1500 		ai_socktype = hints->ai_socktype;
1501 		ai_protocol = hints->ai_protocol;
1502 	}
1503 
1504 	p = buffer;
1505 	memcpy(p, &res_options, sizeof(res_options));
1506 	p += sizeof(res_options);
1507 
1508 	memcpy(p, &op_id, sizeof(int));
1509 	p += sizeof(int);
1510 
1511 	memcpy(p, &ai_flags, sizeof(int));
1512 	p += sizeof(int);
1513 
1514 	memcpy(p, &ai_family, sizeof(int));
1515 	p += sizeof(int);
1516 
1517 	memcpy(p, &ai_socktype, sizeof(int));
1518 	p += sizeof(int);
1519 
1520 	memcpy(p, &ai_protocol, sizeof(int));
1521 	p += sizeof(int);
1522 
1523 	if (hostname != NULL)
1524 		memcpy(p, hostname, size);
1525 
1526 	*buffer_size = desired_size;
1527 	return (NS_SUCCESS);
1528 }
1529 
1530 static int
1531 addrinfo_marshal_func(char *buffer, size_t *buffer_size, void *retval,
1532 		      va_list ap __unused, void *cache_mdata __unused)
1533 {
1534 	struct addrinfo	*ai, *cai;
1535 	char *p;
1536 	size_t desired_size, size, ai_size;
1537 
1538 	ai = *((struct addrinfo **)retval);
1539 
1540 	desired_size = sizeof(size_t);
1541 	ai_size = 0;
1542 	for (cai = ai; cai != NULL; cai = cai->ai_next) {
1543 		desired_size += sizeof(struct addrinfo) + cai->ai_addrlen;
1544 		if (cai->ai_canonname != NULL)
1545 			desired_size += sizeof(size_t) +
1546 			    strlen(cai->ai_canonname);
1547 		++ai_size;
1548 	}
1549 
1550 	if (desired_size > *buffer_size) {
1551 		/* this assignment is here for future use */
1552 		errno = ERANGE;
1553 		*buffer_size = desired_size;
1554 		return (NS_RETURN);
1555 	}
1556 
1557 	memset(buffer, 0, desired_size);
1558 	p = buffer;
1559 
1560 	memcpy(p, &ai_size, sizeof(size_t));
1561 	p += sizeof(size_t);
1562 	for (cai = ai; cai != NULL; cai = cai->ai_next) {
1563 		memcpy(p, cai, sizeof(struct addrinfo));
1564 		p += sizeof(struct addrinfo);
1565 
1566 		memcpy(p, cai->ai_addr, cai->ai_addrlen);
1567 		p += cai->ai_addrlen;
1568 
1569 		if (cai->ai_canonname != NULL) {
1570 			size = strlen(cai->ai_canonname);
1571 			memcpy(p, &size, sizeof(size_t));
1572 			p += sizeof(size_t);
1573 
1574 			memcpy(p, cai->ai_canonname, size);
1575 			p += size;
1576 		}
1577 	}
1578 
1579 	return (NS_SUCCESS);
1580 }
1581 
1582 static int
1583 addrinfo_unmarshal_func(char *buffer, size_t buffer_size __unused, void *retval,
1584 			va_list ap __unused, void *cache_mdata __unused)
1585 {
1586 	struct addrinfo	new_ai, *result, *sentinel, *lasts;
1587 
1588 	char *p;
1589 	size_t ai_size, ai_i, size;
1590 
1591 	p = buffer;
1592 	memcpy(&ai_size, p, sizeof(size_t));
1593 	p += sizeof(size_t);
1594 
1595 	result = NULL;
1596 	lasts = NULL;
1597 	for (ai_i = 0; ai_i < ai_size; ++ai_i) {
1598 		memcpy(&new_ai, p, sizeof(struct addrinfo));
1599 		p += sizeof(struct addrinfo);
1600 		size = new_ai.ai_addrlen + sizeof(struct addrinfo) +
1601 			_ALIGNBYTES;
1602 
1603 		sentinel = (struct addrinfo *)malloc(size);
1604 		memset(sentinel, 0, size);
1605 
1606 		memcpy(sentinel, &new_ai, sizeof(struct addrinfo));
1607 		sentinel->ai_addr = (struct sockaddr *)_ALIGN((char *)sentinel +
1608 		    sizeof(struct addrinfo));
1609 
1610 		memcpy(sentinel->ai_addr, p, new_ai.ai_addrlen);
1611 		p += new_ai.ai_addrlen;
1612 
1613 		if (new_ai.ai_canonname != NULL) {
1614 			memcpy(&size, p, sizeof(size_t));
1615 			p += sizeof(size_t);
1616 
1617 			sentinel->ai_canonname = (char *)malloc(size + 1);
1618 			memset(sentinel->ai_canonname, 0, size + 1);
1619 
1620 			memcpy(sentinel->ai_canonname, p, size);
1621 			p += size;
1622 		}
1623 
1624 		if (result == NULL) {
1625 			result = sentinel;
1626 			lasts = sentinel;
1627 		} else {
1628 			lasts->ai_next = sentinel;
1629 			lasts = sentinel;
1630 		}
1631 	}
1632 
1633 	*((struct addrinfo **)retval) = result;
1634 	return (NS_SUCCESS);
1635 }
1636 #endif /* NS_CACHING */
1637 
1638 /*
1639  * FQDN hostname, DNS lookup
1640  */
1641 static int
1642 explore_fqdn(const struct addrinfo *pai, const char *hostname,
1643 	     const char *servname, struct addrinfo **res)
1644 {
1645 	struct addrinfo *result;
1646 	struct addrinfo *cur;
1647 	int error = 0;
1648 
1649 #ifdef NS_CACHING
1650 	static const nss_cache_info cache_info =
1651 	NS_COMMON_CACHE_INFO_INITIALIZER(
1652 		hosts, NULL, addrinfo_id_func, addrinfo_marshal_func,
1653 		addrinfo_unmarshal_func);
1654 #endif
1655 	static const ns_dtab dtab[] = {
1656 		NS_FILES_CB(_files_getaddrinfo, NULL)
1657 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
1658 		NS_NIS_CB(_yp_getaddrinfo, NULL)
1659 #ifdef NS_CACHING
1660 		NS_CACHE_CB(&cache_info)
1661 #endif
1662 		{ 0 }
1663 	};
1664 
1665 	result = NULL;
1666 
1667 	/*
1668 	 * if the servname does not match socktype/protocol, ignore it.
1669 	 */
1670 	if (get_portmatch(pai, servname) != 0)
1671 		return 0;
1672 
1673 	switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1674 			default_dns_files, hostname, pai)) {
1675 	case NS_TRYAGAIN:
1676 		error = EAI_AGAIN;
1677 		goto free;
1678 	case NS_UNAVAIL:
1679 		error = EAI_FAIL;
1680 		goto free;
1681 	case NS_NOTFOUND:
1682 		error = EAI_NONAME;
1683 		goto free;
1684 	case NS_SUCCESS:
1685 		error = 0;
1686 		for (cur = result; cur; cur = cur->ai_next) {
1687 			GET_PORT(cur, servname);
1688 			/* canonname should be filled already */
1689 		}
1690 		break;
1691 	}
1692 
1693 	*res = result;
1694 
1695 	return 0;
1696 
1697 free:
1698 	if (result)
1699 		freeaddrinfo(result);
1700 	return error;
1701 }
1702 
1703 #ifdef DEBUG
1704 static const char AskedForGot[] =
1705 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1706 #endif
1707 
1708 static struct addrinfo *
1709 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1710 	  const struct addrinfo *pai, res_state res)
1711 {
1712 	struct addrinfo sentinel, *cur;
1713 	struct addrinfo ai;
1714 	const struct afd *afd;
1715 	char *canonname;
1716 	const HEADER *hp;
1717 	const u_char *cp;
1718 	int n;
1719 	const u_char *eom;
1720 	char *bp, *ep;
1721 	int type, class, ancount, qdcount;
1722 	int haveanswer, had_error;
1723 	char tbuf[MAXDNAME];
1724 	int (*name_ok)(const char *);
1725 	char hostbuf[8*1024];
1726 
1727 	memset(&sentinel, 0, sizeof(sentinel));
1728 	cur = &sentinel;
1729 
1730 	canonname = NULL;
1731 	eom = answer->buf + anslen;
1732 	switch (qtype) {
1733 	case T_A:
1734 	case T_AAAA:
1735 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
1736 		name_ok = res_hnok;
1737 		break;
1738 	default:
1739 		return (NULL);	/* XXX should be abort(); */
1740 	}
1741 	/*
1742 	 * find first satisfactory answer
1743 	 */
1744 	hp = &answer->hdr;
1745 	ancount = ntohs(hp->ancount);
1746 	qdcount = ntohs(hp->qdcount);
1747 	bp = hostbuf;
1748 	ep = hostbuf + sizeof hostbuf;
1749 	cp = answer->buf + HFIXEDSZ;
1750 	if (qdcount != 1) {
1751 		RES_SET_H_ERRNO(res, NO_RECOVERY);
1752 		return (NULL);
1753 	}
1754 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1755 	if ((n < 0) || !(*name_ok)(bp)) {
1756 		RES_SET_H_ERRNO(res, NO_RECOVERY);
1757 		return (NULL);
1758 	}
1759 	cp += n + QFIXEDSZ;
1760 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1761 		/* res_send() has already verified that the query name is the
1762 		 * same as the one we sent; this just gets the expanded name
1763 		 * (i.e., with the succeeding search-domain tacked on).
1764 		 */
1765 		n = strlen(bp) + 1;		/* for the \0 */
1766 		if (n >= MAXHOSTNAMELEN) {
1767 			RES_SET_H_ERRNO(res, NO_RECOVERY);
1768 			return (NULL);
1769 		}
1770 		canonname = bp;
1771 		bp += n;
1772 		/* The qname can be abbreviated, but h_name is now absolute. */
1773 		qname = canonname;
1774 	}
1775 	haveanswer = 0;
1776 	had_error = 0;
1777 	while (ancount-- > 0 && cp < eom && !had_error) {
1778 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1779 		if ((n < 0) || !(*name_ok)(bp)) {
1780 			had_error++;
1781 			continue;
1782 		}
1783 		cp += n;			/* name */
1784 		type = _getshort(cp);
1785 		cp += INT16SZ;			/* type */
1786 		class = _getshort(cp);
1787 		cp += INT16SZ + INT32SZ;	/* class, TTL */
1788 		n = _getshort(cp);
1789 		cp += INT16SZ;			/* len */
1790 		if (class != C_IN) {
1791 			/* XXX - debug? syslog? */
1792 			cp += n;
1793 			continue;		/* XXX - had_error++ ? */
1794 		}
1795 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1796 		    type == T_CNAME) {
1797 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1798 			if ((n < 0) || !(*name_ok)(tbuf)) {
1799 				had_error++;
1800 				continue;
1801 			}
1802 			cp += n;
1803 			/* Get canonical name. */
1804 			n = strlen(tbuf) + 1;	/* for the \0 */
1805 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1806 				had_error++;
1807 				continue;
1808 			}
1809 			strlcpy(bp, tbuf, ep - bp);
1810 			canonname = bp;
1811 			bp += n;
1812 			continue;
1813 		}
1814 		if (qtype == T_ANY) {
1815 			if (!(type == T_A || type == T_AAAA)) {
1816 				cp += n;
1817 				continue;
1818 			}
1819 		} else if (type != qtype) {
1820 #ifdef DEBUG
1821 			if (type != T_KEY && type != T_SIG)
1822 				syslog(LOG_NOTICE|LOG_AUTH,
1823 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1824 				       qname, p_class(C_IN), p_type(qtype),
1825 				       p_type(type));
1826 #endif
1827 			cp += n;
1828 			continue;		/* XXX - had_error++ ? */
1829 		}
1830 		switch (type) {
1831 		case T_A:
1832 		case T_AAAA:
1833 			if (strcasecmp(canonname, bp) != 0) {
1834 #ifdef DEBUG
1835 				syslog(LOG_NOTICE|LOG_AUTH,
1836 				       AskedForGot, canonname, bp);
1837 #endif
1838 				cp += n;
1839 				continue;	/* XXX - had_error++ ? */
1840 			}
1841 			if (type == T_A && n != INADDRSZ) {
1842 				cp += n;
1843 				continue;
1844 			}
1845 			if (type == T_AAAA && n != IN6ADDRSZ) {
1846 				cp += n;
1847 				continue;
1848 			}
1849 #ifdef FILTER_V4MAPPED
1850 			if (type == T_AAAA) {
1851 				struct in6_addr in6;
1852 				memcpy(&in6, cp, sizeof(in6));
1853 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1854 					cp += n;
1855 					continue;
1856 				}
1857 			}
1858 #endif
1859 			if (!haveanswer) {
1860 				int nn;
1861 
1862 				canonname = bp;
1863 				nn = strlen(bp) + 1;	/* for the \0 */
1864 				bp += nn;
1865 			}
1866 
1867 			/* don't overwrite pai */
1868 			ai = *pai;
1869 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1870 			afd = find_afd(ai.ai_family);
1871 			if (afd == NULL) {
1872 				cp += n;
1873 				continue;
1874 			}
1875 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1876 			if (cur->ai_next == NULL)
1877 				had_error++;
1878 			while (cur && cur->ai_next)
1879 				cur = cur->ai_next;
1880 			cp += n;
1881 			break;
1882 		default:
1883 			abort();
1884 		}
1885 		if (!had_error)
1886 			haveanswer++;
1887 	}
1888 	if (haveanswer) {
1889 #if defined(RESOLVSORT)
1890 		/*
1891 		 * We support only IPv4 address for backward
1892 		 * compatibility against gethostbyname(3).
1893 		 */
1894 		if (res->nsort && qtype == T_A) {
1895 			if (addr4sort(&sentinel, res) < 0) {
1896 				freeaddrinfo(sentinel.ai_next);
1897 				RES_SET_H_ERRNO(res, NO_RECOVERY);
1898 				return NULL;
1899 			}
1900 		}
1901 #endif /*RESOLVSORT*/
1902 		if (!canonname)
1903 			get_canonname(pai, sentinel.ai_next, qname);
1904 		else
1905 			get_canonname(pai, sentinel.ai_next, canonname);
1906 		RES_SET_H_ERRNO(res, NETDB_SUCCESS);
1907 		return sentinel.ai_next;
1908 	}
1909 
1910 	RES_SET_H_ERRNO(res, NO_RECOVERY);
1911 	return NULL;
1912 }
1913 
1914 #ifdef RESOLVSORT
1915 struct addr_ptr {
1916 	struct addrinfo *ai;
1917 	int aval;
1918 };
1919 
1920 static int
1921 addr4sort(struct addrinfo *sentinel, res_state res)
1922 {
1923 	struct addrinfo *ai;
1924 	struct addr_ptr *addrs, addr;
1925 	struct sockaddr_in *sin;
1926 	int naddrs, i, j;
1927 	int needsort = 0;
1928 
1929 	if (!sentinel)
1930 		return -1;
1931 	naddrs = 0;
1932 	for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
1933 		naddrs++;
1934 	if (naddrs < 2)
1935 		return 0;		/* We don't need sorting. */
1936 	if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
1937 		return -1;
1938 	i = 0;
1939 	for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
1940 		sin = (struct sockaddr_in *)ai->ai_addr;
1941 		for (j = 0; (unsigned)j < res->nsort; j++) {
1942 			if (res->sort_list[j].addr.s_addr ==
1943 			    (sin->sin_addr.s_addr & res->sort_list[j].mask))
1944 				break;
1945 		}
1946 		addrs[i].ai = ai;
1947 		addrs[i].aval = j;
1948 		if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
1949 			needsort = i;
1950 		i++;
1951 	}
1952 	if (!needsort) {
1953 		free(addrs);
1954 		return 0;
1955 	}
1956 
1957 	while (needsort < naddrs) {
1958 		for (j = needsort - 1; j >= 0; j--) {
1959 			if (addrs[j].aval > addrs[j+1].aval) {
1960 				addr = addrs[j];
1961 				addrs[j] = addrs[j + 1];
1962 				addrs[j + 1] = addr;
1963 			} else
1964 				break;
1965 		}
1966 		needsort++;
1967 	}
1968 
1969 	ai = sentinel;
1970 	for (i = 0; i < naddrs; ++i) {
1971 		ai->ai_next = addrs[i].ai;
1972 		ai = ai->ai_next;
1973 	}
1974 	ai->ai_next = NULL;
1975 	free(addrs);
1976 	return 0;
1977 }
1978 #endif /*RESOLVSORT*/
1979 
1980 /*ARGSUSED*/
1981 static int
1982 _dns_getaddrinfo(void *rv, void *cb_data __unused, va_list ap)
1983 {
1984 	struct addrinfo *ai;
1985 	querybuf *buf, *buf2;
1986 	const char *hostname;
1987 	const struct addrinfo *pai;
1988 	struct addrinfo sentinel, *cur;
1989 	struct res_target q, q2;
1990 	res_state res;
1991 
1992 	hostname = va_arg(ap, char *);
1993 	pai = va_arg(ap, const struct addrinfo *);
1994 
1995 	memset(&q, 0, sizeof(q));
1996 	memset(&q2, 0, sizeof(q2));
1997 	memset(&sentinel, 0, sizeof(sentinel));
1998 	cur = &sentinel;
1999 
2000 	buf = malloc(sizeof(*buf));
2001 	if (!buf) {
2002 		h_errno = NETDB_INTERNAL;
2003 		return NS_NOTFOUND;
2004 	}
2005 	buf2 = malloc(sizeof(*buf2));
2006 	if (!buf2) {
2007 		free(buf);
2008 		h_errno = NETDB_INTERNAL;
2009 		return NS_NOTFOUND;
2010 	}
2011 
2012 	switch (pai->ai_family) {
2013 	case AF_UNSPEC:
2014 		q.name = hostname;
2015 		q.qclass = C_IN;
2016 		q.qtype = T_A;
2017 		q.answer = buf->buf;
2018 		q.anslen = sizeof(buf->buf);
2019 		q.next = &q2;
2020 		q2.name = hostname;
2021 		q2.qclass = C_IN;
2022 		q2.qtype = T_AAAA;
2023 		q2.answer = buf2->buf;
2024 		q2.anslen = sizeof(buf2->buf);
2025 		break;
2026 	case AF_INET:
2027 		q.name = hostname;
2028 		q.qclass = C_IN;
2029 		q.qtype = T_A;
2030 		q.answer = buf->buf;
2031 		q.anslen = sizeof(buf->buf);
2032 		break;
2033 	case AF_INET6:
2034 		q.name = hostname;
2035 		q.qclass = C_IN;
2036 		q.qtype = T_AAAA;
2037 		q.answer = buf->buf;
2038 		q.anslen = sizeof(buf->buf);
2039 		break;
2040 	default:
2041 		free(buf);
2042 		free(buf2);
2043 		return NS_UNAVAIL;
2044 	}
2045 
2046 	res = __res_state();
2047 	if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) {
2048 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2049 		free(buf);
2050 		free(buf2);
2051 		return NS_NOTFOUND;
2052 	}
2053 
2054 	if (res_searchN(hostname, &q, res) < 0) {
2055 		free(buf);
2056 		free(buf2);
2057 		return NS_NOTFOUND;
2058 	}
2059 	/* prefer IPv6 */
2060 	if (q.next) {
2061 		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, res);
2062 		if (ai) {
2063 			cur->ai_next = ai;
2064 			while (cur && cur->ai_next)
2065 				cur = cur->ai_next;
2066 		}
2067 	}
2068 	ai = getanswer(buf, q.n, q.name, q.qtype, pai, res);
2069 	if (ai)
2070 		cur->ai_next = ai;
2071 	free(buf);
2072 	free(buf2);
2073 	if (sentinel.ai_next == NULL)
2074 		switch (res->res_h_errno) {
2075 		case HOST_NOT_FOUND:
2076 			return NS_NOTFOUND;
2077 		case TRY_AGAIN:
2078 			return NS_TRYAGAIN;
2079 		default:
2080 			return NS_UNAVAIL;
2081 		}
2082 	*((struct addrinfo **)rv) = sentinel.ai_next;
2083 	return NS_SUCCESS;
2084 }
2085 
2086 static void
2087 _sethtent(FILE **hostf)
2088 {
2089 	if (!*hostf)
2090 		*hostf = fopen(_PATH_HOSTS, "r");
2091 	else
2092 		rewind(*hostf);
2093 }
2094 
2095 static void
2096 _endhtent(FILE **hostf)
2097 {
2098 	if (*hostf) {
2099 		fclose(*hostf);
2100 		*hostf = NULL;
2101 	}
2102 }
2103 
2104 static struct addrinfo *
2105 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2106 {
2107 	char *p;
2108 	char *cp, *tname, *cname;
2109 	struct addrinfo hints, *res0, *res;
2110 	int error;
2111 	const char *addr;
2112 	char hostbuf[8*1024];
2113 
2114 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r")))
2115 		return (NULL);
2116 again:
2117 	if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2118 		return (NULL);
2119 	if (*p == '#')
2120 		goto again;
2121 	cp = strpbrk(p, "#\n");
2122 	if (cp != NULL)
2123 		*cp = '\0';
2124 	if (!(cp = strpbrk(p, " \t")))
2125 		goto again;
2126 	*cp++ = '\0';
2127 	addr = p;
2128 	cname = NULL;
2129 	/* if this is not something we're looking for, skip it. */
2130 	while (cp && *cp) {
2131 		if (*cp == ' ' || *cp == '\t') {
2132 			cp++;
2133 			continue;
2134 		}
2135 		tname = cp;
2136 		if (cname == NULL)
2137 			cname = cp;
2138 		if ((cp = strpbrk(cp, " \t")) != NULL)
2139 			*cp++ = '\0';
2140 		if (strcasecmp(name, tname) == 0)
2141 			goto found;
2142 	}
2143 	goto again;
2144 
2145 found:
2146 	/* we should not glob socktype/protocol here */
2147 	memset(&hints, 0, sizeof(hints));
2148 	hints.ai_family = pai->ai_family;
2149 	hints.ai_socktype = SOCK_DGRAM;
2150 	hints.ai_protocol = 0;
2151 	hints.ai_flags = AI_NUMERICHOST;
2152 	error = getaddrinfo(addr, "0", &hints, &res0);
2153 	if (error)
2154 		goto again;
2155 #ifdef FILTER_V4MAPPED
2156 	/* XXX should check all items in the chain */
2157 	if (res0->ai_family == AF_INET6 &&
2158 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2159 		freeaddrinfo(res0);
2160 		goto again;
2161 	}
2162 #endif
2163 	for (res = res0; res; res = res->ai_next) {
2164 		/* cover it up */
2165 		res->ai_flags = pai->ai_flags;
2166 		res->ai_socktype = pai->ai_socktype;
2167 		res->ai_protocol = pai->ai_protocol;
2168 
2169 		if (pai->ai_flags & AI_CANONNAME) {
2170 			if (get_canonname(pai, res, cname) != 0) {
2171 				freeaddrinfo(res0);
2172 				goto again;
2173 			}
2174 		}
2175 	}
2176 	return res0;
2177 }
2178 
2179 /*ARGSUSED*/
2180 static int
2181 _files_getaddrinfo(void *rv, void *cb_data __unused, va_list ap)
2182 {
2183 	const char *name;
2184 	const struct addrinfo *pai;
2185 	struct addrinfo sentinel, *cur;
2186 	struct addrinfo *p;
2187 	FILE *hostf = NULL;
2188 
2189 	name = va_arg(ap, char *);
2190 	pai = va_arg(ap, struct addrinfo *);
2191 
2192 	memset(&sentinel, 0, sizeof(sentinel));
2193 	cur = &sentinel;
2194 
2195 	_sethtent(&hostf);
2196 	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2197 		cur->ai_next = p;
2198 		while (cur && cur->ai_next)
2199 			cur = cur->ai_next;
2200 	}
2201 	_endhtent(&hostf);
2202 
2203 	*((struct addrinfo **)rv) = sentinel.ai_next;
2204 	if (sentinel.ai_next == NULL)
2205 		return NS_NOTFOUND;
2206 	return NS_SUCCESS;
2207 }
2208 
2209 #ifdef YP
2210 /*ARGSUSED*/
2211 static struct addrinfo *
2212 _yphostent(char *line, const struct addrinfo *pai)
2213 {
2214 	struct addrinfo sentinel, *cur;
2215 	struct addrinfo hints, *res, *res0;
2216 	int error;
2217 	char *p = line;
2218 	const char *addr, *canonname;
2219 	char *nextline;
2220 	char *cp;
2221 
2222 	addr = canonname = NULL;
2223 
2224 	memset(&sentinel, 0, sizeof(sentinel));
2225 	cur = &sentinel;
2226 
2227 nextline:
2228 	/* terminate line */
2229 	cp = strchr(p, '\n');
2230 	if (cp) {
2231 		*cp++ = '\0';
2232 		nextline = cp;
2233 	} else
2234 		nextline = NULL;
2235 
2236 	cp = strpbrk(p, " \t");
2237 	if (cp == NULL) {
2238 		if (canonname == NULL)
2239 			return (NULL);
2240 		else
2241 			goto done;
2242 	}
2243 	*cp++ = '\0';
2244 
2245 	addr = p;
2246 
2247 	while (cp && *cp) {
2248 		if (*cp == ' ' || *cp == '\t') {
2249 			cp++;
2250 			continue;
2251 		}
2252 		if (!canonname)
2253 			canonname = cp;
2254 		if ((cp = strpbrk(cp, " \t")) != NULL)
2255 			*cp++ = '\0';
2256 	}
2257 
2258 	hints = *pai;
2259 	hints.ai_flags = AI_NUMERICHOST;
2260 	error = getaddrinfo(addr, NULL, &hints, &res0);
2261 	if (error == 0) {
2262 		for (res = res0; res; res = res->ai_next) {
2263 			/* cover it up */
2264 			res->ai_flags = pai->ai_flags;
2265 
2266 			if (pai->ai_flags & AI_CANONNAME)
2267 				get_canonname(pai, res, canonname);
2268 		}
2269 	} else
2270 		res0 = NULL;
2271 	if (res0) {
2272 		cur->ai_next = res0;
2273 		while (cur && cur->ai_next)
2274 			cur = cur->ai_next;
2275 	}
2276 
2277 	if (nextline) {
2278 		p = nextline;
2279 		goto nextline;
2280 	}
2281 
2282 done:
2283 	return sentinel.ai_next;
2284 }
2285 
2286 /*ARGSUSED*/
2287 static int
2288 _yp_getaddrinfo(void *rv, void *cb_data __unused, va_list ap)
2289 {
2290 	struct addrinfo sentinel, *cur;
2291 	struct addrinfo *ai = NULL;
2292 	char *ypbuf;
2293 	int ypbuflen, r;
2294 	const char *name;
2295 	const struct addrinfo *pai;
2296 	char *ypdomain;
2297 
2298 	if (_yp_check(&ypdomain) == 0)
2299 		return NS_UNAVAIL;
2300 
2301 	name = va_arg(ap, char *);
2302 	pai = va_arg(ap, const struct addrinfo *);
2303 
2304 	memset(&sentinel, 0, sizeof(sentinel));
2305 	cur = &sentinel;
2306 
2307 	/* hosts.byname is only for IPv4 (Solaris8) */
2308 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
2309 		r = yp_match(ypdomain, "hosts.byname", name,
2310 			(int)strlen(name), &ypbuf, &ypbuflen);
2311 		if (r == 0) {
2312 			struct addrinfo ai4;
2313 
2314 			ai4 = *pai;
2315 			ai4.ai_family = AF_INET;
2316 			ai = _yphostent(ypbuf, &ai4);
2317 			if (ai) {
2318 				cur->ai_next = ai;
2319 				while (cur && cur->ai_next)
2320 					cur = cur->ai_next;
2321 			}
2322 			free(ypbuf);
2323 		}
2324 	}
2325 
2326 	/* ipnodes.byname can hold both IPv4/v6 */
2327 	r = yp_match(ypdomain, "ipnodes.byname", name,
2328 		(int)strlen(name), &ypbuf, &ypbuflen);
2329 	if (r == 0) {
2330 		ai = _yphostent(ypbuf, pai);
2331 		if (ai)
2332 			cur->ai_next = ai;
2333 		free(ypbuf);
2334 	}
2335 
2336 	if (sentinel.ai_next == NULL) {
2337 		RES_SET_H_ERRNO(__res_state(), HOST_NOT_FOUND);
2338 		return NS_NOTFOUND;
2339 	}
2340 	*((struct addrinfo **)rv) = sentinel.ai_next;
2341 	return NS_SUCCESS;
2342 }
2343 #endif
2344 
2345 /* resolver logic */
2346 
2347 /*
2348  * Formulate a normal query, send, and await answer.
2349  * Returned answer is placed in supplied buffer "answer".
2350  * Perform preliminary check of answer, returning success only
2351  * if no error is indicated and the answer count is nonzero.
2352  * Return the size of the response on success, -1 on error.
2353  * Error number is left in h_errno.
2354  *
2355  * Caller must parse answer and determine whether it answers the question.
2356  */
2357 static int
2358 res_queryN(const char *name, struct res_target *target, res_state res)
2359 {
2360 	u_char *buf;
2361 	HEADER *hp;
2362 	int n;
2363 	u_int oflags;
2364 	struct res_target *t;
2365 	int rcode;
2366 	int ancount;
2367 
2368 	rcode = NOERROR;
2369 	ancount = 0;
2370 
2371 	buf = malloc(MAXPACKET);
2372 	if (!buf) {
2373 		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2374 		return -1;
2375 	}
2376 
2377 	for (t = target; t; t = t->next) {
2378 		int class, type;
2379 		u_char *answer;
2380 		int anslen;
2381 
2382 		hp = (HEADER *)(void *)t->answer;
2383 
2384 		/* make it easier... */
2385 		class = t->qclass;
2386 		type = t->qtype;
2387 		answer = t->answer;
2388 		anslen = t->anslen;
2389 
2390 		oflags = res->_flags;
2391 
2392 again:
2393 		hp->rcode = NOERROR;	/* default */
2394 
2395 #ifdef DEBUG
2396 		if (res->options & RES_DEBUG)
2397 			printf(";; res_query(%s, %d, %d)\n", name, class, type);
2398 #endif
2399 
2400 		n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2401 		    buf, MAXPACKET);
2402 		if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 &&
2403 		    (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U)
2404 			n = res_nopt(res, n, buf, MAXPACKET, anslen);
2405 		if (n <= 0) {
2406 #ifdef DEBUG
2407 			if (res->options & RES_DEBUG)
2408 				printf(";; res_query: mkquery failed\n");
2409 #endif
2410 			free(buf);
2411 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2412 			return (n);
2413 		}
2414 		n = res_nsend(res, buf, n, answer, anslen);
2415 		if (n < 0) {
2416 			/*
2417 			 * if the query choked with EDNS0, retry
2418 			 * without EDNS0
2419 			 */
2420 			if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC))
2421 			    != 0U &&
2422 			    ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) {
2423 				res->_flags |= RES_F_EDNS0ERR;
2424 				if (res->options & RES_DEBUG)
2425 					printf(";; res_nquery: retry without EDNS0\n");
2426 				goto again;
2427 			}
2428 			rcode = hp->rcode;	/* record most recent error */
2429 #ifdef DEBUG
2430 			if (res->options & RES_DEBUG)
2431 				printf(";; res_query: send error\n");
2432 #endif
2433 			continue;
2434 		}
2435 
2436 		if (n > anslen)
2437 			hp->rcode = FORMERR; /* XXX not very informative */
2438 		if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2439 			rcode = hp->rcode;	/* record most recent error */
2440 #ifdef DEBUG
2441 			if (res->options & RES_DEBUG)
2442 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2443 				    ntohs(hp->ancount));
2444 #endif
2445 			continue;
2446 		}
2447 
2448 		ancount += ntohs(hp->ancount);
2449 
2450 		t->n = n;
2451 	}
2452 
2453 	free(buf);
2454 
2455 	if (ancount == 0) {
2456 		switch (rcode) {
2457 		case NXDOMAIN:
2458 			RES_SET_H_ERRNO(res, HOST_NOT_FOUND);
2459 			break;
2460 		case SERVFAIL:
2461 			RES_SET_H_ERRNO(res, TRY_AGAIN);
2462 			break;
2463 		case NOERROR:
2464 			RES_SET_H_ERRNO(res, NO_DATA);
2465 			break;
2466 		case FORMERR:
2467 		case NOTIMP:
2468 		case REFUSED:
2469 		default:
2470 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2471 			break;
2472 		}
2473 		return (-1);
2474 	}
2475 	return (ancount);
2476 }
2477 
2478 /*
2479  * Formulate a normal query, send, and retrieve answer in supplied buffer.
2480  * Return the size of the response on success, -1 on error.
2481  * If enabled, implement search rules until answer or unrecoverable failure
2482  * is detected.  Error code, if any, is left in h_errno.
2483  */
2484 static int
2485 res_searchN(const char *name, struct res_target *target, res_state res)
2486 {
2487 	const char *cp, * const *domain;
2488 	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
2489 	u_int dots;
2490 	int trailing_dot, ret, saved_herrno;
2491 	int got_nodata = 0, got_servfail = 0, root_on_list = 0;
2492 	int tried_as_is = 0;
2493 	int searched = 0;
2494 	char abuf[MAXDNAME];
2495 
2496 	errno = 0;
2497 	RES_SET_H_ERRNO(res, HOST_NOT_FOUND); /* default, if we never query */
2498 	dots = 0;
2499 	for (cp = name; *cp; cp++)
2500 		dots += (*cp == '.');
2501 	trailing_dot = 0;
2502 	if (cp > name && *--cp == '.')
2503 		trailing_dot++;
2504 
2505 	/*
2506 	 * if there aren't any dots, it could be a user-level alias
2507 	 */
2508 	if (!dots &&
2509 	    (cp = res_hostalias(res, name, abuf, sizeof(abuf))) != NULL)
2510 		return (res_queryN(cp, target, res));
2511 
2512 	/*
2513 	 * If there are enough dots in the name, let's just give it a
2514 	 * try 'as is'. The threshold can be set with the "ndots" option.
2515 	 * Also, query 'as is', if there is a trailing dot in the name.
2516 	 */
2517 	saved_herrno = -1;
2518 	if (dots >= res->ndots || trailing_dot) {
2519 		ret = res_querydomainN(name, NULL, target, res);
2520 		if (ret > 0 || trailing_dot)
2521 			return (ret);
2522 		if (errno == ECONNREFUSED) {
2523 			RES_SET_H_ERRNO(res, TRY_AGAIN);
2524 			return (-1);
2525 		}
2526 		switch (res->res_h_errno) {
2527 		case NO_DATA:
2528 		case HOST_NOT_FOUND:
2529 			break;
2530 		case TRY_AGAIN:
2531 			if (hp->rcode == SERVFAIL)
2532 				break;
2533 			/* FALLTHROUGH */
2534 		default:
2535 			return (-1);
2536 		}
2537 		saved_herrno = res->res_h_errno;
2538 		tried_as_is++;
2539 	}
2540 
2541 	/*
2542 	 * We do at least one level of search if
2543 	 *	- there is no dot and RES_DEFNAME is set, or
2544 	 *	- there is at least one dot, there is no trailing dot,
2545 	 *	  and RES_DNSRCH is set.
2546 	 */
2547 	if ((!dots && (res->options & RES_DEFNAMES)) ||
2548 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2549 		int done = 0;
2550 
2551 		for (domain = (const char * const *)res->dnsrch;
2552 		   *domain && !done;
2553 		   domain++) {
2554 			searched = 1;
2555 
2556 			if (domain[0][0] == '\0' ||
2557 			    (domain[0][0] == '.' && domain[0][1] == '\0'))
2558 				root_on_list++;
2559 
2560 			if (root_on_list && tried_as_is)
2561 				continue;
2562 
2563 			ret = res_querydomainN(name, *domain, target, res);
2564 			if (ret > 0)
2565 				return (ret);
2566 
2567 			/*
2568 			 * If no server present, give up.
2569 			 * If name isn't found in this domain,
2570 			 * keep trying higher domains in the search list
2571 			 * (if that's enabled).
2572 			 * On a NO_DATA error, keep trying, otherwise
2573 			 * a wildcard entry of another type could keep us
2574 			 * from finding this entry higher in the domain.
2575 			 * If we get some other error (negative answer or
2576 			 * server failure), then stop searching up,
2577 			 * but try the input name below in case it's
2578 			 * fully-qualified.
2579 			 */
2580 			if (errno == ECONNREFUSED) {
2581 				RES_SET_H_ERRNO(res, TRY_AGAIN);
2582 				return (-1);
2583 			}
2584 
2585 			switch (res->res_h_errno) {
2586 			case NO_DATA:
2587 				got_nodata++;
2588 				/* FALLTHROUGH */
2589 			case HOST_NOT_FOUND:
2590 				/* keep trying */
2591 				break;
2592 			case TRY_AGAIN:
2593 				got_servfail++;
2594 				if (hp->rcode == SERVFAIL) {
2595 					/* try next search element, if any */
2596 					break;
2597 				}
2598 				/* FALLTHROUGH */
2599 			default:
2600 				/* anything else implies that we're done */
2601 				done++;
2602 			}
2603 			/*
2604 			 * if we got here for some reason other than DNSRCH,
2605 			 * we only wanted one iteration of the loop, so stop.
2606 			 */
2607 			if (!(res->options & RES_DNSRCH))
2608 			        done++;
2609 		}
2610 	}
2611 
2612 	switch (res->res_h_errno) {
2613 	case NO_DATA:
2614 	case HOST_NOT_FOUND:
2615 		break;
2616 	case TRY_AGAIN:
2617 		if (hp->rcode == SERVFAIL)
2618 			break;
2619 		/* FALLTHROUGH */
2620 	default:
2621 		goto giveup;
2622 	}
2623 
2624 	/*
2625 	 * If the query has not already been tried as is then try it
2626 	 * unless RES_NOTLDQUERY is set and there were no dots.
2627 	 */
2628 	if ((dots || !searched || !(res->options & RES_NOTLDQUERY)) &&
2629 	    !(tried_as_is || root_on_list)) {
2630 		ret = res_querydomainN(name, NULL, target, res);
2631 		if (ret > 0)
2632 			return (ret);
2633 	}
2634 
2635 	/*
2636 	 * if we got here, we didn't satisfy the search.
2637 	 * if we did an initial full query, return that query's h_errno
2638 	 * (note that we wouldn't be here if that query had succeeded).
2639 	 * else if we ever got a nodata, send that back as the reason.
2640 	 * else send back meaningless h_errno, that being the one from
2641 	 * the last DNSRCH we did.
2642 	 */
2643 giveup:
2644 	if (saved_herrno != -1)
2645 		RES_SET_H_ERRNO(res, saved_herrno);
2646 	else if (got_nodata)
2647 		RES_SET_H_ERRNO(res, NO_DATA);
2648 	else if (got_servfail)
2649 		RES_SET_H_ERRNO(res, TRY_AGAIN);
2650 	return (-1);
2651 }
2652 
2653 /*
2654  * Perform a call on res_query on the concatenation of name and domain,
2655  * removing a trailing dot from name if domain is NULL.
2656  */
2657 static int
2658 res_querydomainN(const char *name, const char *domain,
2659 		 struct res_target *target, res_state res)
2660 {
2661 	char nbuf[MAXDNAME];
2662 	const char *longname = nbuf;
2663 	size_t n, d;
2664 
2665 #ifdef DEBUG
2666 	if (res->options & RES_DEBUG)
2667 		printf(";; res_querydomain(%s, %s)\n",
2668 			name, domain?domain:"<Nil>");
2669 #endif
2670 	if (domain == NULL) {
2671 		/*
2672 		 * Check for trailing '.';
2673 		 * copy without '.' if present.
2674 		 */
2675 		n = strlen(name);
2676 		if (n >= MAXDNAME) {
2677 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2678 			return (-1);
2679 		}
2680 		if (n > 0 && name[--n] == '.') {
2681 			strncpy(nbuf, name, n);
2682 			nbuf[n] = '\0';
2683 		} else
2684 			longname = name;
2685 	} else {
2686 		n = strlen(name);
2687 		d = strlen(domain);
2688 		if (n + d + 1 >= MAXDNAME) {
2689 			RES_SET_H_ERRNO(res, NO_RECOVERY);
2690 			return (-1);
2691 		}
2692 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2693 	}
2694 	return (res_queryN(longname, target, res));
2695 }
2696