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