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