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