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