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