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