xref: /netbsd-src/lib/libc/net/getaddrinfo.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: getaddrinfo.c,v 1.75 2005/12/02 11:22:09 yamt 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  * - Thread safe-ness must be checked.
36  * - Return values.  There are nonstandard return values defined and used
37  *   in the source code.  This is because RFC2553 is silent about which error
38  *   code must be returned for which situation.
39  * - IPv4 classful (shortened) form.  RFC2553 is silent about it.  XNET 5.2
40  *   says to use inet_aton() to convert IPv4 numeric to binary (alows
41  *   classful form as a result).
42  *   current code - disallow classful form for IPv4 (due to use of inet_pton).
43  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
44  *   invalid.
45  *   current code - SEGV on freeaddrinfo(NULL)
46  * Note:
47  * - We use getipnodebyname() just for thread-safeness.  There's no intent
48  *   to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
49  *   getipnodebyname().
50  * - The code filters out AFs that are not supported by the kernel,
51  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
52  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
53  *   in ai_flags?
54  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
55  *   (1) what should we do against numeric hostname (2) what should we do
56  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
57  *   non-loopback address configured?  global address configured?
58  * - To avoid search order issue, we have a big amount of code duplicate
59  *   from gethnamaddr.c and some other places.  The issues that there's no
60  *   lower layer function to lookup "IPv4 or IPv6" record.  Calling
61  *   gethostbyname2 from getaddrinfo will end up in wrong search order, as
62  *   follows:
63  *	- The code makes use of following calls when asked to resolver with
64  *	  ai_family  = PF_UNSPEC:
65  *		getipnodebyname(host, AF_INET6);
66  *		getipnodebyname(host, AF_INET);
67  *	  This will result in the following queries if the node is configure to
68  *	  prefer /etc/hosts than DNS:
69  *		lookup /etc/hosts for IPv6 address
70  *		lookup DNS for IPv6 address
71  *		lookup /etc/hosts for IPv4 address
72  *		lookup DNS for IPv4 address
73  *	  which may not meet people's requirement.
74  *	  The right thing to happen is to have underlying layer which does
75  *	  PF_UNSPEC lookup (lookup both) and return chain of addrinfos.
76  *	  This would result in a bit of code duplicate with _dns_ghbyname() and
77  *	  friends.
78  */
79 
80 #include <sys/cdefs.h>
81 #if defined(LIBC_SCCS) && !defined(lint)
82 __RCSID("$NetBSD: getaddrinfo.c,v 1.75 2005/12/02 11:22:09 yamt Exp $");
83 #endif /* LIBC_SCCS and not lint */
84 
85 #include "namespace.h"
86 #include <sys/types.h>
87 #include <sys/param.h>
88 #include <sys/socket.h>
89 #include <net/if.h>
90 #include <netinet/in.h>
91 #include <arpa/inet.h>
92 #include <arpa/nameser.h>
93 #include <assert.h>
94 #include <ctype.h>
95 #include <errno.h>
96 #include <netdb.h>
97 #include <resolv.h>
98 #include <stddef.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <unistd.h>
103 
104 #include <syslog.h>
105 #include <stdarg.h>
106 #include <nsswitch.h>
107 
108 #ifdef YP
109 #include <rpc/rpc.h>
110 #include <rpcsvc/yp_prot.h>
111 #include <rpcsvc/ypclnt.h>
112 #endif
113 
114 #ifdef __weak_alias
115 __weak_alias(getaddrinfo,_getaddrinfo)
116 __weak_alias(freeaddrinfo,_freeaddrinfo)
117 __weak_alias(gai_strerror,_gai_strerror)
118 #endif
119 
120 #define SUCCESS 0
121 #define ANY 0
122 #define YES 1
123 #define NO  0
124 
125 static const char in_addrany[] = { 0, 0, 0, 0 };
126 static const char in_loopback[] = { 127, 0, 0, 1 };
127 #ifdef INET6
128 static const char in6_addrany[] = {
129 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
130 };
131 static const char in6_loopback[] = {
132 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
133 };
134 #endif
135 
136 static const struct afd {
137 	int a_af;
138 	int a_addrlen;
139 	int a_socklen;
140 	int a_off;
141 	const char *a_addrany;
142 	const char *a_loopback;
143 	int a_scoped;
144 } afdl [] = {
145 #ifdef INET6
146 	{PF_INET6, sizeof(struct in6_addr),
147 	 sizeof(struct sockaddr_in6),
148 	 offsetof(struct sockaddr_in6, sin6_addr),
149 	 in6_addrany, in6_loopback, 1},
150 #endif
151 	{PF_INET, sizeof(struct in_addr),
152 	 sizeof(struct sockaddr_in),
153 	 offsetof(struct sockaddr_in, sin_addr),
154 	 in_addrany, in_loopback, 0},
155 	{0, 0, 0, 0, NULL, NULL, 0},
156 };
157 
158 struct explore {
159 	int e_af;
160 	int e_socktype;
161 	int e_protocol;
162 	const char *e_protostr;
163 	int e_wild;
164 #define WILD_AF(ex)		((ex)->e_wild & 0x01)
165 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
166 #define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
167 };
168 
169 static const struct explore explore[] = {
170 #if 0
171 	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
172 #endif
173 #ifdef INET6
174 	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
175 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
176 	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
177 #endif
178 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
179 	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
180 	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
181 	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
182 	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
183 	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
184 	{ -1, 0, 0, NULL, 0 },
185 };
186 
187 #ifdef INET6
188 #define PTON_MAX	16
189 #else
190 #define PTON_MAX	4
191 #endif
192 
193 static const ns_src default_dns_files[] = {
194 	{ NSSRC_FILES, 	NS_SUCCESS },
195 	{ NSSRC_DNS, 	NS_SUCCESS },
196 	{ 0 }
197 };
198 
199 #define MAXPACKET	(64*1024)
200 
201 typedef union {
202 	HEADER hdr;
203 	u_char buf[MAXPACKET];
204 } querybuf;
205 
206 struct res_target {
207 	struct res_target *next;
208 	const char *name;	/* domain name */
209 	int qclass, qtype;	/* class and type of query */
210 	u_char *answer;		/* buffer to put answer */
211 	int anslen;		/* size of answer buffer */
212 	int n;			/* result length */
213 };
214 
215 static int str2number(const char *);
216 static int explore_fqdn(const struct addrinfo *, const char *,
217 	const char *, struct addrinfo **);
218 static int explore_null(const struct addrinfo *,
219 	const char *, struct addrinfo **);
220 static int explore_numeric(const struct addrinfo *, const char *,
221 	const char *, struct addrinfo **, const char *);
222 static int explore_numeric_scope(const struct addrinfo *, const char *,
223 	const char *, struct addrinfo **);
224 static int get_canonname(const struct addrinfo *,
225 	struct addrinfo *, const char *);
226 static struct addrinfo *get_ai(const struct addrinfo *,
227 	const struct afd *, const char *);
228 static int get_portmatch(const struct addrinfo *, const char *);
229 static int get_port(const struct addrinfo *, const char *, int);
230 static const struct afd *find_afd(int);
231 #ifdef INET6
232 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
233 #endif
234 
235 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
236 	const struct addrinfo *);
237 static void aisort(struct addrinfo *s, res_state res);
238 static int _dns_getaddrinfo(void *, void *, va_list);
239 static void _sethtent(FILE **);
240 static void _endhtent(FILE **);
241 static struct addrinfo *_gethtent(FILE **, const char *,
242     const struct addrinfo *);
243 static int _files_getaddrinfo(void *, void *, va_list);
244 #ifdef YP
245 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
246 static int _yp_getaddrinfo(void *, void *, va_list);
247 #endif
248 
249 static int res_queryN(const char *, struct res_target *, res_state);
250 static int res_searchN(const char *, struct res_target *, res_state);
251 static int res_querydomainN(const char *, const char *,
252 	struct res_target *, res_state);
253 
254 static const char * const ai_errlist[] = {
255 	"Success",
256 	"Address family for hostname not supported",	/* EAI_ADDRFAMILY */
257 	"Temporary failure in name resolution",		/* EAI_AGAIN      */
258 	"Invalid value for ai_flags",		       	/* EAI_BADFLAGS   */
259 	"Non-recoverable failure in name resolution", 	/* EAI_FAIL       */
260 	"ai_family not supported",			/* EAI_FAMILY     */
261 	"Memory allocation failure", 			/* EAI_MEMORY     */
262 	"No address associated with hostname", 		/* EAI_NODATA     */
263 	"hostname nor servname provided, or not known",	/* EAI_NONAME     */
264 	"servname not supported for ai_socktype",	/* EAI_SERVICE    */
265 	"ai_socktype not supported", 			/* EAI_SOCKTYPE   */
266 	"System error returned in errno", 		/* EAI_SYSTEM     */
267 	"Invalid value for hints",			/* EAI_BADHINTS	  */
268 	"Resolved protocol is unknown",			/* EAI_PROTOCOL   */
269 	"Unknown error", 				/* EAI_MAX        */
270 };
271 
272 /* XXX macros that make external reference is BAD. */
273 
274 #define GET_AI(ai, afd, addr) \
275 do { \
276 	/* external reference: pai, error, and label free */ \
277 	(ai) = get_ai(pai, (afd), (addr)); \
278 	if ((ai) == NULL) { \
279 		error = EAI_MEMORY; \
280 		goto free; \
281 	} \
282 } while (/*CONSTCOND*/0)
283 
284 #define GET_PORT(ai, serv) \
285 do { \
286 	/* external reference: error and label free */ \
287 	error = get_port((ai), (serv), 0); \
288 	if (error != 0) \
289 		goto free; \
290 } while (/*CONSTCOND*/0)
291 
292 #define GET_CANONNAME(ai, str) \
293 do { \
294 	/* external reference: pai, error and label free */ \
295 	error = get_canonname(pai, (ai), (str)); \
296 	if (error != 0) \
297 		goto free; \
298 } while (/*CONSTCOND*/0)
299 
300 #define ERR(err) \
301 do { \
302 	/* external reference: error, and label bad */ \
303 	error = (err); \
304 	goto bad; \
305 	/*NOTREACHED*/ \
306 } while (/*CONSTCOND*/0)
307 
308 #define MATCH_FAMILY(x, y, w) \
309 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
310 #define MATCH(x, y, w) \
311 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
312 
313 const char *
314 gai_strerror(int ecode)
315 {
316 	if (ecode < 0 || ecode > EAI_MAX)
317 		ecode = EAI_MAX;
318 	return ai_errlist[ecode];
319 }
320 
321 void
322 freeaddrinfo(struct addrinfo *ai)
323 {
324 	struct addrinfo *next;
325 
326 	_DIAGASSERT(ai != NULL);
327 
328 	do {
329 		next = ai->ai_next;
330 		if (ai->ai_canonname)
331 			free(ai->ai_canonname);
332 		/* no need to free(ai->ai_addr) */
333 		free(ai);
334 		ai = next;
335 	} while (ai);
336 }
337 
338 static int
339 str2number(const char *p)
340 {
341 	char *ep;
342 	unsigned long v;
343 
344 	_DIAGASSERT(p != NULL);
345 
346 	if (*p == '\0')
347 		return -1;
348 	ep = NULL;
349 	errno = 0;
350 	v = strtoul(p, &ep, 10);
351 	if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
352 		return v;
353 	else
354 		return -1;
355 }
356 
357 int
358 getaddrinfo(const char *hostname, const char *servname,
359     const struct addrinfo *hints, struct addrinfo **res)
360 {
361 	struct addrinfo sentinel;
362 	struct addrinfo *cur;
363 	int error = 0;
364 	struct addrinfo ai;
365 	struct addrinfo ai0;
366 	struct addrinfo *pai;
367 	const struct explore *ex;
368 
369 	/* hostname is allowed to be NULL */
370 	/* servname is allowed to be NULL */
371 	/* hints is allowed to be NULL */
372 	_DIAGASSERT(res != NULL);
373 
374 	memset(&sentinel, 0, sizeof(sentinel));
375 	cur = &sentinel;
376 	pai = &ai;
377 	pai->ai_flags = 0;
378 	pai->ai_family = PF_UNSPEC;
379 	pai->ai_socktype = ANY;
380 	pai->ai_protocol = ANY;
381 	pai->ai_addrlen = 0;
382 	pai->ai_canonname = NULL;
383 	pai->ai_addr = NULL;
384 	pai->ai_next = NULL;
385 
386 	if (hostname == NULL && servname == NULL)
387 		return EAI_NONAME;
388 	if (hints) {
389 		/* error check for hints */
390 		if (hints->ai_addrlen || hints->ai_canonname ||
391 		    hints->ai_addr || hints->ai_next)
392 			ERR(EAI_BADHINTS); /* xxx */
393 		if (hints->ai_flags & ~AI_MASK)
394 			ERR(EAI_BADFLAGS);
395 		switch (hints->ai_family) {
396 		case PF_UNSPEC:
397 		case PF_INET:
398 #ifdef INET6
399 		case PF_INET6:
400 #endif
401 			break;
402 		default:
403 			ERR(EAI_FAMILY);
404 		}
405 		memcpy(pai, hints, sizeof(*pai));
406 
407 		/*
408 		 * if both socktype/protocol are specified, check if they
409 		 * are meaningful combination.
410 		 */
411 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
412 			for (ex = explore; ex->e_af >= 0; ex++) {
413 				if (pai->ai_family != ex->e_af)
414 					continue;
415 				if (ex->e_socktype == ANY)
416 					continue;
417 				if (ex->e_protocol == ANY)
418 					continue;
419 				if (pai->ai_socktype == ex->e_socktype
420 				 && pai->ai_protocol != ex->e_protocol) {
421 					ERR(EAI_BADHINTS);
422 				}
423 			}
424 		}
425 	}
426 
427 	/*
428 	 * check for special cases.  (1) numeric servname is disallowed if
429 	 * socktype/protocol are left unspecified. (2) servname is disallowed
430 	 * for raw and other inet{,6} sockets.
431 	 */
432 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
433 #ifdef PF_INET6
434 	 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
435 #endif
436 	    ) {
437 		ai0 = *pai;	/* backup *pai */
438 
439 		if (pai->ai_family == PF_UNSPEC) {
440 #ifdef PF_INET6
441 			pai->ai_family = PF_INET6;
442 #else
443 			pai->ai_family = PF_INET;
444 #endif
445 		}
446 		error = get_portmatch(pai, servname);
447 		if (error)
448 			ERR(error);
449 
450 		*pai = ai0;
451 	}
452 
453 	ai0 = *pai;
454 
455 	/* NULL hostname, or numeric hostname */
456 	for (ex = explore; ex->e_af >= 0; ex++) {
457 		*pai = ai0;
458 
459 		/* PF_UNSPEC entries are prepared for DNS queries only */
460 		if (ex->e_af == PF_UNSPEC)
461 			continue;
462 
463 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
464 			continue;
465 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
466 			continue;
467 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
468 			continue;
469 
470 		if (pai->ai_family == PF_UNSPEC)
471 			pai->ai_family = ex->e_af;
472 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
473 			pai->ai_socktype = ex->e_socktype;
474 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
475 			pai->ai_protocol = ex->e_protocol;
476 
477 		if (hostname == NULL)
478 			error = explore_null(pai, servname, &cur->ai_next);
479 		else
480 			error = explore_numeric_scope(pai, hostname, servname,
481 			    &cur->ai_next);
482 
483 		if (error)
484 			goto free;
485 
486 		while (cur && cur->ai_next)
487 			cur = cur->ai_next;
488 	}
489 
490 	/*
491 	 * XXX
492 	 * If numreic representation of AF1 can be interpreted as FQDN
493 	 * representation of AF2, we need to think again about the code below.
494 	 */
495 	if (sentinel.ai_next)
496 		goto good;
497 
498 	if (hostname == NULL)
499 		ERR(EAI_NODATA);
500 	if (pai->ai_flags & AI_NUMERICHOST)
501 		ERR(EAI_NONAME);
502 
503 	/*
504 	 * hostname as alphabetical name.
505 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
506 	 * outer loop by AFs.
507 	 */
508 	for (ex = explore; ex->e_af >= 0; ex++) {
509 		*pai = ai0;
510 
511 		/* require exact match for family field */
512 		if (pai->ai_family != ex->e_af)
513 			continue;
514 
515 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
516 				WILD_SOCKTYPE(ex))) {
517 			continue;
518 		}
519 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
520 				WILD_PROTOCOL(ex))) {
521 			continue;
522 		}
523 
524 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
525 			pai->ai_socktype = ex->e_socktype;
526 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
527 			pai->ai_protocol = ex->e_protocol;
528 
529 		error = explore_fqdn(pai, hostname, servname,
530 			&cur->ai_next);
531 
532 		while (cur && cur->ai_next)
533 			cur = cur->ai_next;
534 	}
535 
536 	/* XXX */
537 	if (sentinel.ai_next)
538 		error = 0;
539 
540 	if (error)
541 		goto free;
542 	if (error == 0) {
543 		if (sentinel.ai_next) {
544  good:
545 			*res = sentinel.ai_next;
546 			return SUCCESS;
547 		} else
548 			error = EAI_FAIL;
549 	}
550  free:
551  bad:
552 	if (sentinel.ai_next)
553 		freeaddrinfo(sentinel.ai_next);
554 	*res = NULL;
555 	return error;
556 }
557 
558 /*
559  * FQDN hostname, DNS lookup
560  */
561 static int
562 explore_fqdn(const struct addrinfo *pai, const char *hostname,
563     const char *servname, struct addrinfo **res)
564 {
565 	struct addrinfo *result;
566 	struct addrinfo *cur;
567 	int error = 0;
568 	static const ns_dtab dtab[] = {
569 		NS_FILES_CB(_files_getaddrinfo, NULL)
570 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
571 		NS_NIS_CB(_yp_getaddrinfo, NULL)
572 		{ 0 }
573 	};
574 
575 	_DIAGASSERT(pai != NULL);
576 	/* hostname may be NULL */
577 	/* servname may be NULL */
578 	_DIAGASSERT(res != NULL);
579 
580 	result = NULL;
581 
582 	/*
583 	 * if the servname does not match socktype/protocol, ignore it.
584 	 */
585 	if (get_portmatch(pai, servname) != 0)
586 		return 0;
587 
588 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
589 			default_dns_files, hostname, pai)) {
590 	case NS_TRYAGAIN:
591 		error = EAI_AGAIN;
592 		goto free;
593 	case NS_UNAVAIL:
594 		error = EAI_FAIL;
595 		goto free;
596 	case NS_NOTFOUND:
597 		error = EAI_NODATA;
598 		goto free;
599 	case NS_SUCCESS:
600 		error = 0;
601 		for (cur = result; cur; cur = cur->ai_next) {
602 			GET_PORT(cur, servname);
603 			/* canonname should be filled already */
604 		}
605 		break;
606 	}
607 
608 	*res = result;
609 
610 	return 0;
611 
612 free:
613 	if (result)
614 		freeaddrinfo(result);
615 	return error;
616 }
617 
618 /*
619  * hostname == NULL.
620  * passive socket -> anyaddr (0.0.0.0 or ::)
621  * non-passive socket -> localhost (127.0.0.1 or ::1)
622  */
623 static int
624 explore_null(const struct addrinfo *pai, const char *servname,
625     struct addrinfo **res)
626 {
627 	int s;
628 	const struct afd *afd;
629 	struct addrinfo *cur;
630 	struct addrinfo sentinel;
631 	int error;
632 
633 	_DIAGASSERT(pai != NULL);
634 	/* servname may be NULL */
635 	_DIAGASSERT(res != NULL);
636 
637 	*res = NULL;
638 	sentinel.ai_next = NULL;
639 	cur = &sentinel;
640 
641 	/*
642 	 * filter out AFs that are not supported by the kernel
643 	 * XXX errno?
644 	 */
645 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
646 	if (s < 0) {
647 		if (errno != EMFILE)
648 			return 0;
649 	} else
650 		close(s);
651 
652 	/*
653 	 * if the servname does not match socktype/protocol, ignore it.
654 	 */
655 	if (get_portmatch(pai, servname) != 0)
656 		return 0;
657 
658 	afd = find_afd(pai->ai_family);
659 	if (afd == NULL)
660 		return 0;
661 
662 	if (pai->ai_flags & AI_PASSIVE) {
663 		GET_AI(cur->ai_next, afd, afd->a_addrany);
664 		/* xxx meaningless?
665 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
666 		 */
667 		GET_PORT(cur->ai_next, servname);
668 	} else {
669 		GET_AI(cur->ai_next, afd, afd->a_loopback);
670 		/* xxx meaningless?
671 		 * GET_CANONNAME(cur->ai_next, "localhost");
672 		 */
673 		GET_PORT(cur->ai_next, servname);
674 	}
675 	cur = cur->ai_next;
676 
677 	*res = sentinel.ai_next;
678 	return 0;
679 
680 free:
681 	if (sentinel.ai_next)
682 		freeaddrinfo(sentinel.ai_next);
683 	return error;
684 }
685 
686 /*
687  * numeric hostname
688  */
689 static int
690 explore_numeric(const struct addrinfo *pai, const char *hostname,
691     const char *servname, struct addrinfo **res, const char *canonname)
692 {
693 	const struct afd *afd;
694 	struct addrinfo *cur;
695 	struct addrinfo sentinel;
696 	int error;
697 	char pton[PTON_MAX];
698 
699 	_DIAGASSERT(pai != NULL);
700 	/* hostname may be NULL */
701 	/* servname may be NULL */
702 	_DIAGASSERT(res != NULL);
703 
704 	*res = NULL;
705 	sentinel.ai_next = NULL;
706 	cur = &sentinel;
707 
708 	/*
709 	 * if the servname does not match socktype/protocol, ignore it.
710 	 */
711 	if (get_portmatch(pai, servname) != 0)
712 		return 0;
713 
714 	afd = find_afd(pai->ai_family);
715 	if (afd == NULL)
716 		return 0;
717 
718 	switch (afd->a_af) {
719 #if 0 /*X/Open spec*/
720 	case AF_INET:
721 		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
722 			if (pai->ai_family == afd->a_af ||
723 			    pai->ai_family == PF_UNSPEC /*?*/) {
724 				GET_AI(cur->ai_next, afd, pton);
725 				GET_PORT(cur->ai_next, servname);
726 				if ((pai->ai_flags & AI_CANONNAME)) {
727 					/*
728 					 * Set the numeric address itself as
729 					 * the canonical name, based on a
730 					 * clarification in rfc2553bis-03.
731 					 */
732 					GET_CANONNAME(cur->ai_next, canonname);
733 				}
734 				while (cur && cur->ai_next)
735 					cur = cur->ai_next;
736 			} else
737 				ERR(EAI_FAMILY);	/*xxx*/
738 		}
739 		break;
740 #endif
741 	default:
742 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
743 			if (pai->ai_family == afd->a_af ||
744 			    pai->ai_family == PF_UNSPEC /*?*/) {
745 				GET_AI(cur->ai_next, afd, pton);
746 				GET_PORT(cur->ai_next, servname);
747 				if ((pai->ai_flags & AI_CANONNAME)) {
748 					/*
749 					 * Set the numeric address itself as
750 					 * the canonical name, based on a
751 					 * clarification in rfc2553bis-03.
752 					 */
753 					GET_CANONNAME(cur->ai_next, canonname);
754 				}
755 				while (cur && cur->ai_next)
756 					cur = cur->ai_next;
757 			} else
758 				ERR(EAI_FAMILY);	/*xxx*/
759 		}
760 		break;
761 	}
762 
763 	*res = sentinel.ai_next;
764 	return 0;
765 
766 free:
767 bad:
768 	if (sentinel.ai_next)
769 		freeaddrinfo(sentinel.ai_next);
770 	return error;
771 }
772 
773 /*
774  * numeric hostname with scope
775  */
776 static int
777 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
778     const char *servname, struct addrinfo **res)
779 {
780 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
781 	return explore_numeric(pai, hostname, servname, res, hostname);
782 #else
783 	const struct afd *afd;
784 	struct addrinfo *cur;
785 	int error;
786 	char *cp, *hostname2 = NULL, *scope, *addr;
787 	struct sockaddr_in6 *sin6;
788 
789 	_DIAGASSERT(pai != NULL);
790 	/* hostname may be NULL */
791 	/* servname may be NULL */
792 	_DIAGASSERT(res != NULL);
793 
794 	/*
795 	 * if the servname does not match socktype/protocol, ignore it.
796 	 */
797 	if (get_portmatch(pai, servname) != 0)
798 		return 0;
799 
800 	afd = find_afd(pai->ai_family);
801 	if (afd == NULL)
802 		return 0;
803 
804 	if (!afd->a_scoped)
805 		return explore_numeric(pai, hostname, servname, res, hostname);
806 
807 	cp = strchr(hostname, SCOPE_DELIMITER);
808 	if (cp == NULL)
809 		return explore_numeric(pai, hostname, servname, res, hostname);
810 
811 	/*
812 	 * Handle special case of <scoped_address><delimiter><scope id>
813 	 */
814 	hostname2 = strdup(hostname);
815 	if (hostname2 == NULL)
816 		return EAI_MEMORY;
817 	/* terminate at the delimiter */
818 	hostname2[cp - hostname] = '\0';
819 	addr = hostname2;
820 	scope = cp + 1;
821 
822 	error = explore_numeric(pai, addr, servname, res, hostname);
823 	if (error == 0) {
824 		u_int32_t scopeid;
825 
826 		for (cur = *res; cur; cur = cur->ai_next) {
827 			if (cur->ai_family != AF_INET6)
828 				continue;
829 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
830 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
831 				free(hostname2);
832 				return(EAI_NODATA); /* XXX: is return OK? */
833 			}
834 			sin6->sin6_scope_id = scopeid;
835 		}
836 	}
837 
838 	free(hostname2);
839 
840 	return error;
841 #endif
842 }
843 
844 static int
845 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
846 {
847 
848 	_DIAGASSERT(pai != NULL);
849 	_DIAGASSERT(ai != NULL);
850 	_DIAGASSERT(str != NULL);
851 
852 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
853 		ai->ai_canonname = strdup(str);
854 		if (ai->ai_canonname == NULL)
855 			return EAI_MEMORY;
856 	}
857 	return 0;
858 }
859 
860 static struct addrinfo *
861 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
862 {
863 	char *p;
864 	struct addrinfo *ai;
865 
866 	_DIAGASSERT(pai != NULL);
867 	_DIAGASSERT(afd != NULL);
868 	_DIAGASSERT(addr != NULL);
869 
870 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
871 		+ (afd->a_socklen));
872 	if (ai == NULL)
873 		return NULL;
874 
875 	memcpy(ai, pai, sizeof(struct addrinfo));
876 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
877 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
878 	ai->ai_addr->sa_len = afd->a_socklen;
879 	ai->ai_addrlen = afd->a_socklen;
880 #if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
881 	ai->__ai_pad0 = 0;
882 #endif
883 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
884 	p = (char *)(void *)(ai->ai_addr);
885 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
886 	return ai;
887 }
888 
889 static int
890 get_portmatch(const struct addrinfo *ai, const char *servname)
891 {
892 
893 	_DIAGASSERT(ai != NULL);
894 	/* servname may be NULL */
895 
896 	return get_port(ai, servname, 1);
897 }
898 
899 static int
900 get_port(const struct addrinfo *ai, const char *servname, int matchonly)
901 {
902 	const char *proto;
903 	struct servent *sp;
904 	int port;
905 	int allownumeric;
906 
907 	_DIAGASSERT(ai != NULL);
908 	/* servname may be NULL */
909 
910 	if (servname == NULL)
911 		return 0;
912 	switch (ai->ai_family) {
913 	case AF_INET:
914 #ifdef AF_INET6
915 	case AF_INET6:
916 #endif
917 		break;
918 	default:
919 		return 0;
920 	}
921 
922 	switch (ai->ai_socktype) {
923 	case SOCK_RAW:
924 		return EAI_SERVICE;
925 	case SOCK_DGRAM:
926 	case SOCK_STREAM:
927 		allownumeric = 1;
928 		break;
929 	case ANY:
930 		allownumeric = 0;
931 		break;
932 	default:
933 		return EAI_SOCKTYPE;
934 	}
935 
936 	port = str2number(servname);
937 	if (port >= 0) {
938 		if (!allownumeric)
939 			return EAI_SERVICE;
940 		if (port < 0 || port > 65535)
941 			return EAI_SERVICE;
942 		port = htons(port);
943 	} else {
944 		if (ai->ai_flags & AI_NUMERICSERV)
945 			return EAI_NONAME;
946 
947 		switch (ai->ai_socktype) {
948 		case SOCK_DGRAM:
949 			proto = "udp";
950 			break;
951 		case SOCK_STREAM:
952 			proto = "tcp";
953 			break;
954 		default:
955 			proto = NULL;
956 			break;
957 		}
958 
959 		if ((sp = getservbyname(servname, proto)) == NULL)
960 			return EAI_SERVICE;
961 		port = sp->s_port;
962 	}
963 
964 	if (!matchonly) {
965 		switch (ai->ai_family) {
966 		case AF_INET:
967 			((struct sockaddr_in *)(void *)
968 			    ai->ai_addr)->sin_port = port;
969 			break;
970 #ifdef INET6
971 		case AF_INET6:
972 			((struct sockaddr_in6 *)(void *)
973 			    ai->ai_addr)->sin6_port = port;
974 			break;
975 #endif
976 		}
977 	}
978 
979 	return 0;
980 }
981 
982 static const struct afd *
983 find_afd(int af)
984 {
985 	const struct afd *afd;
986 
987 	if (af == PF_UNSPEC)
988 		return NULL;
989 	for (afd = afdl; afd->a_af; afd++) {
990 		if (afd->a_af == af)
991 			return afd;
992 	}
993 	return NULL;
994 }
995 
996 #ifdef INET6
997 /* convert a string to a scope identifier. XXX: IPv6 specific */
998 static int
999 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1000 {
1001 	u_long lscopeid;
1002 	struct in6_addr *a6;
1003 	char *ep;
1004 
1005 	_DIAGASSERT(scope != NULL);
1006 	_DIAGASSERT(sin6 != NULL);
1007 	_DIAGASSERT(scopeid != NULL);
1008 
1009 	a6 = &sin6->sin6_addr;
1010 
1011 	/* empty scopeid portion is invalid */
1012 	if (*scope == '\0')
1013 		return -1;
1014 
1015 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1016 		/*
1017 		 * We currently assume a one-to-one mapping between links
1018 		 * and interfaces, so we simply use interface indices for
1019 		 * like-local scopes.
1020 		 */
1021 		*scopeid = if_nametoindex(scope);
1022 		if (*scopeid == 0)
1023 			goto trynumeric;
1024 		return 0;
1025 	}
1026 
1027 	/* still unclear about literal, allow numeric only - placeholder */
1028 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1029 		goto trynumeric;
1030 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1031 		goto trynumeric;
1032 	else
1033 		goto trynumeric;	/* global */
1034 
1035 	/* try to convert to a numeric id as a last resort */
1036   trynumeric:
1037 	errno = 0;
1038 	lscopeid = strtoul(scope, &ep, 10);
1039 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1040 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1041 		return 0;
1042 	else
1043 		return -1;
1044 }
1045 #endif
1046 
1047 /* code duplicate with gethnamaddr.c */
1048 
1049 static const char AskedForGot[] =
1050 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1051 
1052 static struct addrinfo *
1053 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1054     const struct addrinfo *pai)
1055 {
1056 	struct addrinfo sentinel, *cur;
1057 	struct addrinfo ai;
1058 	const struct afd *afd;
1059 	char *canonname;
1060 	const HEADER *hp;
1061 	const u_char *cp;
1062 	int n;
1063 	const u_char *eom;
1064 	char *bp, *ep;
1065 	int type, class, ancount, qdcount;
1066 	int haveanswer, had_error;
1067 	char tbuf[MAXDNAME];
1068 	int (*name_ok) (const char *);
1069 	char hostbuf[8*1024];
1070 
1071 	_DIAGASSERT(answer != NULL);
1072 	_DIAGASSERT(qname != NULL);
1073 	_DIAGASSERT(pai != NULL);
1074 
1075 	memset(&sentinel, 0, sizeof(sentinel));
1076 	cur = &sentinel;
1077 
1078 	canonname = NULL;
1079 	eom = answer->buf + anslen;
1080 	switch (qtype) {
1081 	case T_A:
1082 	case T_AAAA:
1083 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
1084 		name_ok = res_hnok;
1085 		break;
1086 	default:
1087 		return NULL;	/* XXX should be abort(); */
1088 	}
1089 	/*
1090 	 * find first satisfactory answer
1091 	 */
1092 	hp = &answer->hdr;
1093 	ancount = ntohs(hp->ancount);
1094 	qdcount = ntohs(hp->qdcount);
1095 	bp = hostbuf;
1096 	ep = hostbuf + sizeof hostbuf;
1097 	cp = answer->buf + HFIXEDSZ;
1098 	if (qdcount != 1) {
1099 		h_errno = NO_RECOVERY;
1100 		return (NULL);
1101 	}
1102 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1103 	if ((n < 0) || !(*name_ok)(bp)) {
1104 		h_errno = NO_RECOVERY;
1105 		return (NULL);
1106 	}
1107 	cp += n + QFIXEDSZ;
1108 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1109 		/* res_send() has already verified that the query name is the
1110 		 * same as the one we sent; this just gets the expanded name
1111 		 * (i.e., with the succeeding search-domain tacked on).
1112 		 */
1113 		n = strlen(bp) + 1;		/* for the \0 */
1114 		if (n >= MAXHOSTNAMELEN) {
1115 			h_errno = NO_RECOVERY;
1116 			return (NULL);
1117 		}
1118 		canonname = bp;
1119 		bp += n;
1120 		/* The qname can be abbreviated, but h_name is now absolute. */
1121 		qname = canonname;
1122 	}
1123 	haveanswer = 0;
1124 	had_error = 0;
1125 	while (ancount-- > 0 && cp < eom && !had_error) {
1126 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1127 		if ((n < 0) || !(*name_ok)(bp)) {
1128 			had_error++;
1129 			continue;
1130 		}
1131 		cp += n;			/* name */
1132 		type = _getshort(cp);
1133  		cp += INT16SZ;			/* type */
1134 		class = _getshort(cp);
1135  		cp += INT16SZ + INT32SZ;	/* class, TTL */
1136 		n = _getshort(cp);
1137 		cp += INT16SZ;			/* len */
1138 		if (class != C_IN) {
1139 			/* XXX - debug? syslog? */
1140 			cp += n;
1141 			continue;		/* XXX - had_error++ ? */
1142 		}
1143 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1144 		    type == T_CNAME) {
1145 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1146 			if ((n < 0) || !(*name_ok)(tbuf)) {
1147 				had_error++;
1148 				continue;
1149 			}
1150 			cp += n;
1151 			/* Get canonical name. */
1152 			n = strlen(tbuf) + 1;	/* for the \0 */
1153 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1154 				had_error++;
1155 				continue;
1156 			}
1157 			strlcpy(bp, tbuf, (size_t)(ep - bp));
1158 			canonname = bp;
1159 			bp += n;
1160 			continue;
1161 		}
1162 		if (qtype == T_ANY) {
1163 			if (!(type == T_A || type == T_AAAA)) {
1164 				cp += n;
1165 				continue;
1166 			}
1167 		} else if (type != qtype) {
1168 			if (type != T_KEY && type != T_SIG)
1169 				syslog(LOG_NOTICE|LOG_AUTH,
1170 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1171 				       qname, p_class(C_IN), p_type(qtype),
1172 				       p_type(type));
1173 			cp += n;
1174 			continue;		/* XXX - had_error++ ? */
1175 		}
1176 		switch (type) {
1177 		case T_A:
1178 		case T_AAAA:
1179 			if (strcasecmp(canonname, bp) != 0) {
1180 				syslog(LOG_NOTICE|LOG_AUTH,
1181 				       AskedForGot, canonname, bp);
1182 				cp += n;
1183 				continue;	/* XXX - had_error++ ? */
1184 			}
1185 			if (type == T_A && n != INADDRSZ) {
1186 				cp += n;
1187 				continue;
1188 			}
1189 			if (type == T_AAAA && n != IN6ADDRSZ) {
1190 				cp += n;
1191 				continue;
1192 			}
1193 			if (type == T_AAAA) {
1194 				struct in6_addr in6;
1195 				memcpy(&in6, cp, IN6ADDRSZ);
1196 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1197 					cp += n;
1198 					continue;
1199 				}
1200 			}
1201 			if (!haveanswer) {
1202 				int nn;
1203 
1204 				canonname = bp;
1205 				nn = strlen(bp) + 1;	/* for the \0 */
1206 				bp += nn;
1207 			}
1208 
1209 			/* don't overwrite pai */
1210 			ai = *pai;
1211 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1212 			afd = find_afd(ai.ai_family);
1213 			if (afd == NULL) {
1214 				cp += n;
1215 				continue;
1216 			}
1217 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1218 			if (cur->ai_next == NULL)
1219 				had_error++;
1220 			while (cur && cur->ai_next)
1221 				cur = cur->ai_next;
1222 			cp += n;
1223 			break;
1224 		default:
1225 			abort();
1226 		}
1227 		if (!had_error)
1228 			haveanswer++;
1229 	}
1230 	if (haveanswer) {
1231 		if (!canonname)
1232 			(void)get_canonname(pai, sentinel.ai_next, qname);
1233 		else
1234 			(void)get_canonname(pai, sentinel.ai_next, canonname);
1235 		h_errno = NETDB_SUCCESS;
1236 		return sentinel.ai_next;
1237 	}
1238 
1239 	h_errno = NO_RECOVERY;
1240 	return NULL;
1241 }
1242 
1243 #define SORTEDADDR(p)	(((struct sockaddr_in *)(void *)(p->ai_next->ai_addr))->sin_addr.s_addr)
1244 #define SORTMATCH(p, s) ((SORTEDADDR(p) & (s).mask) == (s).addr.s_addr)
1245 
1246 static void
1247 aisort(struct addrinfo *s, res_state res)
1248 {
1249 	struct addrinfo head, *t, *p;
1250 	int i;
1251 
1252 	head.ai_next = NULL;
1253 	t = &head;
1254 
1255 	for (i = 0; i < res->nsort; i++) {
1256 		p = s;
1257 		while (p->ai_next) {
1258 			if ((p->ai_next->ai_family != AF_INET)
1259 			|| SORTMATCH(p, res->sort_list[i])) {
1260 				t->ai_next = p->ai_next;
1261 				t = t->ai_next;
1262 				p->ai_next = p->ai_next->ai_next;
1263 			} else {
1264 				p = p->ai_next;
1265 			}
1266 		}
1267 	}
1268 
1269 	/* add rest of list and reset s to the new list*/
1270 	t->ai_next = s->ai_next;
1271 	s->ai_next = head.ai_next;
1272 }
1273 
1274 /*ARGSUSED*/
1275 static int
1276 _dns_getaddrinfo(void *rv, void	*cb_data, va_list ap)
1277 {
1278 	struct addrinfo *ai;
1279 	querybuf *buf, *buf2;
1280 	const char *name;
1281 	const struct addrinfo *pai;
1282 	struct addrinfo sentinel, *cur;
1283 	struct res_target q, q2;
1284 	res_state res;
1285 
1286 	name = va_arg(ap, char *);
1287 	pai = va_arg(ap, const struct addrinfo *);
1288 
1289 	memset(&q, 0, sizeof(q2));
1290 	memset(&q2, 0, sizeof(q2));
1291 	memset(&sentinel, 0, sizeof(sentinel));
1292 	cur = &sentinel;
1293 
1294 	buf = malloc(sizeof(*buf));
1295 	if (buf == NULL) {
1296 		h_errno = NETDB_INTERNAL;
1297 		return NS_NOTFOUND;
1298 	}
1299 	buf2 = malloc(sizeof(*buf2));
1300 	if (buf2 == NULL) {
1301 		free(buf);
1302 		h_errno = NETDB_INTERNAL;
1303 		return NS_NOTFOUND;
1304 	}
1305 
1306 	switch (pai->ai_family) {
1307 	case AF_UNSPEC:
1308 		/* prefer IPv6 */
1309 		q.name = name;
1310 		q.qclass = C_IN;
1311 		q.qtype = T_AAAA;
1312 		q.answer = buf->buf;
1313 		q.anslen = sizeof(buf->buf);
1314 		q.next = &q2;
1315 		q2.name = name;
1316 		q2.qclass = C_IN;
1317 		q2.qtype = T_A;
1318 		q2.answer = buf2->buf;
1319 		q2.anslen = sizeof(buf2->buf);
1320 		break;
1321 	case AF_INET:
1322 		q.name = name;
1323 		q.qclass = C_IN;
1324 		q.qtype = T_A;
1325 		q.answer = buf->buf;
1326 		q.anslen = sizeof(buf->buf);
1327 		break;
1328 	case AF_INET6:
1329 		q.name = name;
1330 		q.qclass = C_IN;
1331 		q.qtype = T_AAAA;
1332 		q.answer = buf->buf;
1333 		q.anslen = sizeof(buf->buf);
1334 		break;
1335 	default:
1336 		free(buf);
1337 		free(buf2);
1338 		return NS_UNAVAIL;
1339 	}
1340 
1341 	res = __res_get_state();
1342 	if (res == NULL) {
1343 		free(buf);
1344 		free(buf2);
1345 		return NS_NOTFOUND;
1346 	}
1347 
1348 	if (res_searchN(name, &q, res) < 0) {
1349 		__res_put_state(res);
1350 		free(buf);
1351 		free(buf2);
1352 		return NS_NOTFOUND;
1353 	}
1354 	ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1355 	if (ai) {
1356 		cur->ai_next = ai;
1357 		while (cur && cur->ai_next)
1358 			cur = cur->ai_next;
1359 	}
1360 	if (q.next) {
1361 		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1362 		if (ai)
1363 			cur->ai_next = ai;
1364 	}
1365 	free(buf);
1366 	free(buf2);
1367 	if (sentinel.ai_next == NULL) {
1368 		__res_put_state(res);
1369 		switch (h_errno) {
1370 		case HOST_NOT_FOUND:
1371 			return NS_NOTFOUND;
1372 		case TRY_AGAIN:
1373 			return NS_TRYAGAIN;
1374 		default:
1375 			return NS_UNAVAIL;
1376 		}
1377 	}
1378 
1379 	if (res->nsort)
1380 		aisort(&sentinel, res);
1381 
1382 	__res_put_state(res);
1383 
1384 	*((struct addrinfo **)rv) = sentinel.ai_next;
1385 	return NS_SUCCESS;
1386 }
1387 
1388 static void
1389 _sethtent(FILE **hostf)
1390 {
1391 
1392 	if (!*hostf)
1393 		*hostf = fopen(_PATH_HOSTS, "r" );
1394 	else
1395 		rewind(*hostf);
1396 }
1397 
1398 static void
1399 _endhtent(FILE **hostf)
1400 {
1401 
1402 	if (*hostf) {
1403 		(void) fclose(*hostf);
1404 		*hostf = NULL;
1405 	}
1406 }
1407 
1408 static struct addrinfo *
1409 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
1410 {
1411 	char *p;
1412 	char *cp, *tname, *cname;
1413 	struct addrinfo hints, *res0, *res;
1414 	int error;
1415 	const char *addr;
1416 	char hostbuf[8*1024];
1417 
1418 	_DIAGASSERT(name != NULL);
1419 	_DIAGASSERT(pai != NULL);
1420 
1421 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
1422 		return (NULL);
1423  again:
1424 	if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
1425 		return (NULL);
1426 	if (*p == '#')
1427 		goto again;
1428 	if (!(cp = strpbrk(p, "#\n")))
1429 		goto again;
1430 	*cp = '\0';
1431 	if (!(cp = strpbrk(p, " \t")))
1432 		goto again;
1433 	*cp++ = '\0';
1434 	addr = p;
1435 	/* if this is not something we're looking for, skip it. */
1436 	cname = NULL;
1437 	while (cp && *cp) {
1438 		if (*cp == ' ' || *cp == '\t') {
1439 			cp++;
1440 			continue;
1441 		}
1442 		if (!cname)
1443 			cname = cp;
1444 		tname = cp;
1445 		if ((cp = strpbrk(cp, " \t")) != NULL)
1446 			*cp++ = '\0';
1447 		if (strcasecmp(name, tname) == 0)
1448 			goto found;
1449 	}
1450 	goto again;
1451 
1452 found:
1453 	hints = *pai;
1454 	hints.ai_flags = AI_NUMERICHOST;
1455 	error = getaddrinfo(addr, NULL, &hints, &res0);
1456 	if (error)
1457 		goto again;
1458 	for (res = res0; res; res = res->ai_next) {
1459 		/* cover it up */
1460 		res->ai_flags = pai->ai_flags;
1461 
1462 		if (pai->ai_flags & AI_CANONNAME) {
1463 			if (get_canonname(pai, res, cname) != 0) {
1464 				freeaddrinfo(res0);
1465 				goto again;
1466 			}
1467 		}
1468 	}
1469 	return res0;
1470 }
1471 
1472 /*ARGSUSED*/
1473 static int
1474 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
1475 {
1476 	const char *name;
1477 	const struct addrinfo *pai;
1478 	struct addrinfo sentinel, *cur;
1479 	struct addrinfo *p;
1480 #ifndef _REENTRANT
1481 	static
1482 #endif
1483 	FILE *hostf = NULL;
1484 
1485 	name = va_arg(ap, char *);
1486 	pai = va_arg(ap, struct addrinfo *);
1487 
1488 	memset(&sentinel, 0, sizeof(sentinel));
1489 	cur = &sentinel;
1490 
1491 	_sethtent(&hostf);
1492 	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
1493 		cur->ai_next = p;
1494 		while (cur && cur->ai_next)
1495 			cur = cur->ai_next;
1496 	}
1497 	_endhtent(&hostf);
1498 
1499 	*((struct addrinfo **)rv) = sentinel.ai_next;
1500 	if (sentinel.ai_next == NULL)
1501 		return NS_NOTFOUND;
1502 	return NS_SUCCESS;
1503 }
1504 
1505 #ifdef YP
1506 /*ARGSUSED*/
1507 static struct addrinfo *
1508 _yphostent(char *line, const struct addrinfo *pai)
1509 {
1510 	struct addrinfo sentinel, *cur;
1511 	struct addrinfo hints, *res, *res0;
1512 	int error;
1513 	char *p;
1514 	const char *addr, *canonname;
1515 	char *nextline;
1516 	char *cp;
1517 
1518 	_DIAGASSERT(line != NULL);
1519 	_DIAGASSERT(pai != NULL);
1520 
1521 	p = line;
1522 	addr = canonname = NULL;
1523 
1524 	memset(&sentinel, 0, sizeof(sentinel));
1525 	cur = &sentinel;
1526 
1527 nextline:
1528 	/* terminate line */
1529 	cp = strchr(p, '\n');
1530 	if (cp) {
1531 		*cp++ = '\0';
1532 		nextline = cp;
1533 	} else
1534 		nextline = NULL;
1535 
1536 	cp = strpbrk(p, " \t");
1537 	if (cp == NULL) {
1538 		if (canonname == NULL)
1539 			return (NULL);
1540 		else
1541 			goto done;
1542 	}
1543 	*cp++ = '\0';
1544 
1545 	addr = p;
1546 
1547 	while (cp && *cp) {
1548 		if (*cp == ' ' || *cp == '\t') {
1549 			cp++;
1550 			continue;
1551 		}
1552 		if (!canonname)
1553 			canonname = cp;
1554 		if ((cp = strpbrk(cp, " \t")) != NULL)
1555 			*cp++ = '\0';
1556 	}
1557 
1558 	hints = *pai;
1559 	hints.ai_flags = AI_NUMERICHOST;
1560 	error = getaddrinfo(addr, NULL, &hints, &res0);
1561 	if (error == 0) {
1562 		for (res = res0; res; res = res->ai_next) {
1563 			/* cover it up */
1564 			res->ai_flags = pai->ai_flags;
1565 
1566 			if (pai->ai_flags & AI_CANONNAME)
1567 				(void)get_canonname(pai, res, canonname);
1568 		}
1569 	} else
1570 		res0 = NULL;
1571 	if (res0) {
1572 		cur->ai_next = res0;
1573 		while (cur && cur->ai_next)
1574 			cur = cur->ai_next;
1575 	}
1576 
1577 	if (nextline) {
1578 		p = nextline;
1579 		goto nextline;
1580 	}
1581 
1582 done:
1583 	return sentinel.ai_next;
1584 }
1585 
1586 /*ARGSUSED*/
1587 static int
1588 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
1589 {
1590 	struct addrinfo sentinel, *cur;
1591 	struct addrinfo *ai = NULL;
1592 	char *ypbuf;
1593 	int ypbuflen, r;
1594 	const char *name;
1595 	const struct addrinfo *pai;
1596 	char *ypdomain;
1597 
1598 	if (_yp_check(&ypdomain) == 0)
1599 		return NS_UNAVAIL;
1600 
1601 	name = va_arg(ap, char *);
1602 	pai = va_arg(ap, const struct addrinfo *);
1603 
1604 	memset(&sentinel, 0, sizeof(sentinel));
1605 	cur = &sentinel;
1606 
1607 	/* hosts.byname is only for IPv4 (Solaris8) */
1608 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
1609 		r = yp_match(ypdomain, "hosts.byname", name,
1610 			(int)strlen(name), &ypbuf, &ypbuflen);
1611 		if (r == 0) {
1612 			struct addrinfo ai4;
1613 
1614 			ai4 = *pai;
1615 			ai4.ai_family = AF_INET;
1616 			ai = _yphostent(ypbuf, &ai4);
1617 			if (ai) {
1618 				cur->ai_next = ai;
1619 				while (cur && cur->ai_next)
1620 					cur = cur->ai_next;
1621 			}
1622 		}
1623 		free(ypbuf);
1624 	}
1625 
1626 	/* ipnodes.byname can hold both IPv4/v6 */
1627 	r = yp_match(ypdomain, "ipnodes.byname", name,
1628 		(int)strlen(name), &ypbuf, &ypbuflen);
1629 	if (r == 0) {
1630 		ai = _yphostent(ypbuf, pai);
1631 		if (ai)
1632 			cur->ai_next = ai;
1633 		free(ypbuf);
1634 	}
1635 
1636 	if (sentinel.ai_next == NULL) {
1637 		h_errno = HOST_NOT_FOUND;
1638 		return NS_NOTFOUND;
1639 	}
1640 	*((struct addrinfo **)rv) = sentinel.ai_next;
1641 	return NS_SUCCESS;
1642 }
1643 #endif
1644 
1645 /* resolver logic */
1646 
1647 /*
1648  * Formulate a normal query, send, and await answer.
1649  * Returned answer is placed in supplied buffer "answer".
1650  * Perform preliminary check of answer, returning success only
1651  * if no error is indicated and the answer count is nonzero.
1652  * Return the size of the response on success, -1 on error.
1653  * Error number is left in h_errno.
1654  *
1655  * Caller must parse answer and determine whether it answers the question.
1656  */
1657 static int
1658 res_queryN(const char *name, /* domain name */ struct res_target *target,
1659     res_state res)
1660 {
1661 	u_char buf[MAXPACKET];
1662 	HEADER *hp;
1663 	int n;
1664 	struct res_target *t;
1665 	int rcode;
1666 	int ancount;
1667 
1668 	_DIAGASSERT(name != NULL);
1669 	/* XXX: target may be NULL??? */
1670 
1671 	rcode = NOERROR;
1672 	ancount = 0;
1673 
1674 	for (t = target; t; t = t->next) {
1675 		int class, type;
1676 		u_char *answer;
1677 		int anslen;
1678 
1679 		hp = (HEADER *)(void *)t->answer;
1680 		hp->rcode = NOERROR;	/* default */
1681 
1682 		/* make it easier... */
1683 		class = t->qclass;
1684 		type = t->qtype;
1685 		answer = t->answer;
1686 		anslen = t->anslen;
1687 #ifdef DEBUG
1688 		if (res->options & RES_DEBUG)
1689 			printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
1690 #endif
1691 
1692 		n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
1693 		    buf, sizeof(buf));
1694 #ifdef RES_USE_EDNS0
1695 		if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
1696 			n = res_nopt(res, n, buf, sizeof(buf), anslen);
1697 #endif
1698 		if (n <= 0) {
1699 #ifdef DEBUG
1700 			if (res->options & RES_DEBUG)
1701 				printf(";; res_nquery: mkquery failed\n");
1702 #endif
1703 			h_errno = NO_RECOVERY;
1704 			return n;
1705 		}
1706 		n = res_nsend(res, buf, n, answer, anslen);
1707 #if 0
1708 		if (n < 0) {
1709 #ifdef DEBUG
1710 			if (res->options & RES_DEBUG)
1711 				printf(";; res_query: send error\n");
1712 #endif
1713 			h_errno = TRY_AGAIN;
1714 			return n;
1715 		}
1716 #endif
1717 
1718 		if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1719 			rcode = hp->rcode;	/* record most recent error */
1720 #ifdef DEBUG
1721 			if (res->options & RES_DEBUG)
1722 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
1723 				    ntohs(hp->ancount));
1724 #endif
1725 			continue;
1726 		}
1727 
1728 		ancount += ntohs(hp->ancount);
1729 
1730 		t->n = n;
1731 	}
1732 
1733 	if (ancount == 0) {
1734 		switch (rcode) {
1735 		case NXDOMAIN:
1736 			h_errno = HOST_NOT_FOUND;
1737 			break;
1738 		case SERVFAIL:
1739 			h_errno = TRY_AGAIN;
1740 			break;
1741 		case NOERROR:
1742 			h_errno = NO_DATA;
1743 			break;
1744 		case FORMERR:
1745 		case NOTIMP:
1746 		case REFUSED:
1747 		default:
1748 			h_errno = NO_RECOVERY;
1749 			break;
1750 		}
1751 		return -1;
1752 	}
1753 	return ancount;
1754 }
1755 
1756 /*
1757  * Formulate a normal query, send, and retrieve answer in supplied buffer.
1758  * Return the size of the response on success, -1 on error.
1759  * If enabled, implement search rules until answer or unrecoverable failure
1760  * is detected.  Error code, if any, is left in h_errno.
1761  */
1762 static int
1763 res_searchN(const char *name, struct res_target *target, res_state res)
1764 {
1765 	const char *cp, * const *domain;
1766 	HEADER *hp;
1767 	u_int dots;
1768 	int trailing_dot, ret, saved_herrno;
1769 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1770 
1771 	_DIAGASSERT(name != NULL);
1772 	_DIAGASSERT(target != NULL);
1773 
1774 	hp = (HEADER *)(void *)target->answer;	/*XXX*/
1775 
1776 	errno = 0;
1777 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
1778 	dots = 0;
1779 	for (cp = name; *cp; cp++)
1780 		dots += (*cp == '.');
1781 	trailing_dot = 0;
1782 	if (cp > name && *--cp == '.')
1783 		trailing_dot++;
1784 
1785 	/*
1786 	 * if there aren't any dots, it could be a user-level alias
1787 	 */
1788 	if (!dots && (cp = __hostalias(name)) != NULL) {
1789 		ret = res_queryN(cp, target, res);
1790 		return ret;
1791 	}
1792 
1793 	/*
1794 	 * If there are dots in the name already, let's just give it a try
1795 	 * 'as is'.  The threshold can be set with the "ndots" option.
1796 	 */
1797 	saved_herrno = -1;
1798 	if (dots >= res->ndots) {
1799 		ret = res_querydomainN(name, NULL, target, res);
1800 		if (ret > 0)
1801 			return (ret);
1802 		saved_herrno = h_errno;
1803 		tried_as_is++;
1804 	}
1805 
1806 	/*
1807 	 * We do at least one level of search if
1808 	 *	- there is no dot and RES_DEFNAME is set, or
1809 	 *	- there is at least one dot, there is no trailing dot,
1810 	 *	  and RES_DNSRCH is set.
1811 	 */
1812 	if ((!dots && (res->options & RES_DEFNAMES)) ||
1813 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
1814 		int done = 0;
1815 
1816 		for (domain = (const char * const *)res->dnsrch;
1817 		   *domain && !done;
1818 		   domain++) {
1819 
1820 			ret = res_querydomainN(name, *domain, target, res);
1821 			if (ret > 0)
1822 				return ret;
1823 
1824 			/*
1825 			 * If no server present, give up.
1826 			 * If name isn't found in this domain,
1827 			 * keep trying higher domains in the search list
1828 			 * (if that's enabled).
1829 			 * On a NO_DATA error, keep trying, otherwise
1830 			 * a wildcard entry of another type could keep us
1831 			 * from finding this entry higher in the domain.
1832 			 * If we get some other error (negative answer or
1833 			 * server failure), then stop searching up,
1834 			 * but try the input name below in case it's
1835 			 * fully-qualified.
1836 			 */
1837 			if (errno == ECONNREFUSED) {
1838 				h_errno = TRY_AGAIN;
1839 				return -1;
1840 			}
1841 
1842 			switch (h_errno) {
1843 			case NO_DATA:
1844 				got_nodata++;
1845 				/* FALLTHROUGH */
1846 			case HOST_NOT_FOUND:
1847 				/* keep trying */
1848 				break;
1849 			case TRY_AGAIN:
1850 				if (hp->rcode == SERVFAIL) {
1851 					/* try next search element, if any */
1852 					got_servfail++;
1853 					break;
1854 				}
1855 				/* FALLTHROUGH */
1856 			default:
1857 				/* anything else implies that we're done */
1858 				done++;
1859 			}
1860 			/*
1861 			 * if we got here for some reason other than DNSRCH,
1862 			 * we only wanted one iteration of the loop, so stop.
1863 			 */
1864 			if (!(res->options & RES_DNSRCH))
1865 			        done++;
1866 		}
1867 	}
1868 
1869 	/*
1870 	 * if we have not already tried the name "as is", do that now.
1871 	 * note that we do this regardless of how many dots were in the
1872 	 * name or whether it ends with a dot.
1873 	 */
1874 	if (!tried_as_is) {
1875 		ret = res_querydomainN(name, NULL, target, res);
1876 		if (ret > 0)
1877 			return ret;
1878 	}
1879 
1880 	/*
1881 	 * if we got here, we didn't satisfy the search.
1882 	 * if we did an initial full query, return that query's h_errno
1883 	 * (note that we wouldn't be here if that query had succeeded).
1884 	 * else if we ever got a nodata, send that back as the reason.
1885 	 * else send back meaningless h_errno, that being the one from
1886 	 * the last DNSRCH we did.
1887 	 */
1888 	if (saved_herrno != -1)
1889 		h_errno = saved_herrno;
1890 	else if (got_nodata)
1891 		h_errno = NO_DATA;
1892 	else if (got_servfail)
1893 		h_errno = TRY_AGAIN;
1894 	return -1;
1895 }
1896 
1897 /*
1898  * Perform a call on res_query on the concatenation of name and domain,
1899  * removing a trailing dot from name if domain is NULL.
1900  */
1901 static int
1902 res_querydomainN(const char *name, const char *domain,
1903     struct res_target *target, res_state res)
1904 {
1905 	char nbuf[MAXDNAME];
1906 	const char *longname = nbuf;
1907 	size_t n, d;
1908 
1909 	_DIAGASSERT(name != NULL);
1910 	/* XXX: target may be NULL??? */
1911 
1912 #ifdef DEBUG
1913 	if (res->options & RES_DEBUG)
1914 		printf(";; res_querydomain(%s, %s)\n",
1915 			name, domain?domain:"<Nil>");
1916 #endif
1917 	if (domain == NULL) {
1918 		/*
1919 		 * Check for trailing '.';
1920 		 * copy without '.' if present.
1921 		 */
1922 		n = strlen(name);
1923 		if (n + 1 > sizeof(nbuf)) {
1924 			h_errno = NO_RECOVERY;
1925 			return -1;
1926 		}
1927 		if (n > 0 && name[--n] == '.') {
1928 			strncpy(nbuf, name, n);
1929 			nbuf[n] = '\0';
1930 		} else
1931 			longname = name;
1932 	} else {
1933 		n = strlen(name);
1934 		d = strlen(domain);
1935 		if (n + 1 + d + 1 > sizeof(nbuf)) {
1936 			h_errno = NO_RECOVERY;
1937 			return -1;
1938 		}
1939 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1940 	}
1941 	return res_queryN(longname, target, res);
1942 }
1943