xref: /freebsd/lib/libc/net/getaddrinfo.c (revision 2357939bc239bd5334a169b62313806178dd8f30)
1 /*	$KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
34  *
35  * Issues to be discussed:
36  * - Thread safe-ness must be checked.
37  * - Return values.  There are nonstandard return values defined and used
38  *   in the source code.  This is because RFC2553 is silent about which error
39  *   code must be returned for which situation.
40  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
41  *   invalid.  current code - SEGV on freeaddrinfo(NULL)
42  *
43  * Note:
44  * - The code filters out AFs that are not supported by the kernel,
45  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
46  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
47  *   in ai_flags?
48  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
49  *   (1) what should we do against numeric hostname (2) what should we do
50  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
51  *   non-loopback address configured?  global address configured?
52  *
53  * OS specific notes for netbsd/openbsd/freebsd4/bsdi4:
54  * - To avoid search order issue, we have a big amount of code duplicate
55  *   from gethnamaddr.c and some other places.  The issues that there's no
56  *   lower layer function to lookup "IPv4 or IPv6" record.  Calling
57  *   gethostbyname2 from getaddrinfo will end up in wrong search order, as
58  *   presented above.
59  *
60  * OS specific notes for freebsd4:
61  * - FreeBSD supported $GAI.  The code does not.
62  * - FreeBSD allowed classful IPv4 numeric (127.1), the code does not.
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include "namespace.h"
69 #include <sys/types.h>
70 #include <sys/param.h>
71 #include <sys/socket.h>
72 #include <net/if.h>
73 #include <netinet/in.h>
74 #include <sys/queue.h>
75 #ifdef INET6
76 #include <net/if_var.h>
77 #include <sys/sysctl.h>
78 #include <netinet6/in6_var.h>	/* XXX */
79 #endif
80 #include <arpa/inet.h>
81 #include <arpa/nameser.h>
82 #include <rpc/rpc.h>
83 #include <rpcsvc/yp_prot.h>
84 #include <rpcsvc/ypclnt.h>
85 #include <netdb.h>
86 #include <pthread.h>
87 #include <resolv.h>
88 #include <string.h>
89 #include <stdlib.h>
90 #include <stddef.h>
91 #include <ctype.h>
92 #include <unistd.h>
93 #include <stdio.h>
94 #include <errno.h>
95 
96 #include "res_config.h"
97 
98 #ifdef DEBUG
99 #include <syslog.h>
100 #endif
101 
102 #include <stdarg.h>
103 #include <nsswitch.h>
104 #include "un-namespace.h"
105 #include "libc_private.h"
106 
107 #if defined(__KAME__) && defined(INET6)
108 # define FAITH
109 #endif
110 
111 #define SUCCESS 0
112 #define ANY 0
113 #define YES 1
114 #define NO  0
115 
116 static const char in_addrany[] = { 0, 0, 0, 0 };
117 static const char in_loopback[] = { 127, 0, 0, 1 };
118 #ifdef INET6
119 static const char in6_addrany[] = {
120 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
121 };
122 static const char in6_loopback[] = {
123 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
124 };
125 #endif
126 
127 struct policyqueue {
128 	TAILQ_ENTRY(policyqueue) pc_entry;
129 #ifdef INET6
130 	struct in6_addrpolicy pc_policy;
131 #endif
132 };
133 TAILQ_HEAD(policyhead, policyqueue);
134 
135 static const struct afd {
136 	int a_af;
137 	int a_addrlen;
138 	int a_socklen;
139 	int a_off;
140 	const char *a_addrany;
141 	const char *a_loopback;
142 	int a_scoped;
143 } afdl [] = {
144 #ifdef INET6
145 #define	N_INET6 0
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 #define	N_INET 1
151 #else
152 #define	N_INET 0
153 #endif
154 	{PF_INET, sizeof(struct in_addr),
155 	 sizeof(struct sockaddr_in),
156 	 offsetof(struct sockaddr_in, sin_addr),
157 	 in_addrany, in_loopback, 0},
158 	{0, 0, 0, 0, NULL, NULL, 0},
159 };
160 
161 struct explore {
162 	int e_af;
163 	int e_socktype;
164 	int e_protocol;
165 	const char *e_protostr;
166 	int e_wild;
167 #define WILD_AF(ex)		((ex)->e_wild & 0x01)
168 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
169 #define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
170 };
171 
172 static const struct explore explore[] = {
173 #if 0
174 	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
175 #endif
176 #ifdef INET6
177 	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
178 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
179 	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
180 #endif
181 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
182 	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
183 	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
184 	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
185 	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
186 	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
187 	{ -1, 0, 0, NULL, 0 },
188 };
189 
190 #ifdef INET6
191 #define PTON_MAX	16
192 #else
193 #define PTON_MAX	4
194 #endif
195 
196 #define AIO_SRCFLAG_DEPRECATED	0x1
197 
198 struct ai_order {
199 	union {
200 		struct sockaddr_storage aiou_ss;
201 		struct sockaddr aiou_sa;
202 	} aio_src_un;
203 #define aio_srcsa aio_src_un.aiou_sa
204 	u_int32_t aio_srcflag;
205 	int aio_srcscope;
206 	int aio_dstscope;
207 	struct policyqueue *aio_srcpolicy;
208 	struct policyqueue *aio_dstpolicy;
209 	struct addrinfo *aio_ai;
210 	int aio_matchlen;
211 };
212 
213 static const ns_src default_dns_files[] = {
214 	{ NSSRC_FILES, 	NS_SUCCESS },
215 	{ NSSRC_DNS, 	NS_SUCCESS },
216 	{ 0 }
217 };
218 
219 struct res_target {
220 	struct res_target *next;
221 	const char *name;	/* domain name */
222 	int qclass, qtype;	/* class and type of query */
223 	u_char *answer;		/* buffer to put answer */
224 	int anslen;		/* size of answer buffer */
225 	int n;			/* result length */
226 };
227 
228 #define MAXPACKET	(64*1024)
229 
230 typedef union {
231 	HEADER hdr;
232 	u_char buf[MAXPACKET];
233 } querybuf;
234 
235 static int str_isnumber(const char *);
236 static int explore_null(const struct addrinfo *,
237 	const char *, struct addrinfo **);
238 static int explore_numeric(const struct addrinfo *, const char *,
239 	const char *, struct addrinfo **);
240 static int explore_numeric_scope(const struct addrinfo *, const char *,
241 	const char *, struct addrinfo **);
242 static int get_canonname(const struct addrinfo *,
243 	struct addrinfo *, const char *);
244 static struct addrinfo *get_ai(const struct addrinfo *,
245 	const struct afd *, const char *);
246 static int get_portmatch(const struct addrinfo *, const char *);
247 static int get_port(struct addrinfo *, const char *, int);
248 static const struct afd *find_afd(int);
249 static int addrconfig(struct addrinfo *);
250 static int comp_dst(const void *, const void *);
251 #ifdef INET6
252 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
253 #endif
254 static int gai_addr2scopetype(struct sockaddr *);
255 
256 static int explore_fqdn(const struct addrinfo *, const char *,
257 	const char *, struct addrinfo **);
258 
259 static int reorder(struct addrinfo *);
260 static int get_addrselectpolicy(struct policyhead *);
261 static void free_addrselectpolicy(struct policyhead *);
262 static struct policyqueue *match_addrselectpolicy(struct sockaddr *,
263 	struct policyhead *);
264 
265 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
266 	const struct addrinfo *);
267 #if defined(RESOLVSORT)
268 static int addr4sort(struct addrinfo *);
269 #endif
270 static int _dns_getaddrinfo(void *, void *, va_list);
271 static void _sethtent(void);
272 static void _endhtent(void);
273 static struct addrinfo *_gethtent(const char *, const struct addrinfo *);
274 static int _files_getaddrinfo(void *, void *, va_list);
275 #ifdef YP
276 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
277 static int _yp_getaddrinfo(void *, void *, va_list);
278 #endif
279 
280 static int res_queryN(const char *, struct res_target *);
281 static int res_searchN(const char *, struct res_target *);
282 static int res_querydomainN(const char *, const char *,
283 	struct res_target *);
284 
285 static struct ai_errlist {
286 	const char *str;
287 	int code;
288 } ai_errlist[] = {
289 	{ "Success",					0, },
290 	{ "Temporary failure in name resolution",	EAI_AGAIN, },
291 	{ "Invalid value for ai_flags",		       	EAI_BADFLAGS, },
292 	{ "Non-recoverable failure in name resolution", EAI_FAIL, },
293 	{ "ai_family not supported",			EAI_FAMILY, },
294 	{ "Memory allocation failure", 			EAI_MEMORY, },
295 	{ "hostname nor servname provided, or not known", EAI_NONAME, },
296 	{ "servname not supported for ai_socktype",	EAI_SERVICE, },
297 	{ "ai_socktype not supported", 			EAI_SOCKTYPE, },
298 	{ "System error returned in errno", 		EAI_SYSTEM, },
299 	{ "Invalid value for hints",			EAI_BADHINTS, },
300 	{ "Resolved protocol is unknown",		EAI_PROTOCOL, },
301 	/* backward compatibility with userland code prior to 2553bis-02 */
302 	{ "Address family for hostname not supported",	1, },
303 	{ "No address associated with hostname", 	7, },
304 	{ NULL,						-1, },
305 };
306 
307 /*
308  * XXX: Many dependencies are not thread-safe.  So, we share lock between
309  * getaddrinfo() and getipnodeby*().  Still, we cannot use
310  * getaddrinfo() and getipnodeby*() in conjunction with other
311  * functions which call them.
312  */
313 pthread_mutex_t __getaddrinfo_thread_lock = PTHREAD_MUTEX_INITIALIZER;
314 #define THREAD_LOCK() \
315 	if (__isthreaded) _pthread_mutex_lock(&__getaddrinfo_thread_lock);
316 #define THREAD_UNLOCK() \
317 	if (__isthreaded) _pthread_mutex_unlock(&__getaddrinfo_thread_lock);
318 
319 /* XXX macros that make external reference is BAD. */
320 
321 #define GET_AI(ai, afd, addr) \
322 do { \
323 	/* external reference: pai, error, and label free */ \
324 	(ai) = get_ai(pai, (afd), (addr)); \
325 	if ((ai) == NULL) { \
326 		error = EAI_MEMORY; \
327 		goto free; \
328 	} \
329 } while (/*CONSTCOND*/0)
330 
331 #define GET_PORT(ai, serv) \
332 do { \
333 	/* external reference: error and label free */ \
334 	error = get_port((ai), (serv), 0); \
335 	if (error != 0) \
336 		goto free; \
337 } while (/*CONSTCOND*/0)
338 
339 #define GET_CANONNAME(ai, str) \
340 do { \
341 	/* external reference: pai, error and label free */ \
342 	error = get_canonname(pai, (ai), (str)); \
343 	if (error != 0) \
344 		goto free; \
345 } while (/*CONSTCOND*/0)
346 
347 #define ERR(err) \
348 do { \
349 	/* external reference: error, and label bad */ \
350 	error = (err); \
351 	goto bad; \
352 	/*NOTREACHED*/ \
353 } while (/*CONSTCOND*/0)
354 
355 #define MATCH_FAMILY(x, y, w) \
356 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
357 #define MATCH(x, y, w) \
358 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
359 
360 char *
361 gai_strerror(ecode)
362 	int ecode;
363 {
364 	struct ai_errlist *p;
365 
366 	for (p = ai_errlist; p->str; p++) {
367 		if (p->code == ecode)
368 			return (char *)p->str;
369 	}
370 	return "Unknown error";
371 }
372 
373 void
374 freeaddrinfo(ai)
375 	struct addrinfo *ai;
376 {
377 	struct addrinfo *next;
378 
379 	do {
380 		next = ai->ai_next;
381 		if (ai->ai_canonname)
382 			free(ai->ai_canonname);
383 		/* no need to free(ai->ai_addr) */
384 		free(ai);
385 		ai = next;
386 	} while (ai);
387 }
388 
389 static int
390 str_isnumber(p)
391 	const char *p;
392 {
393 	char *ep;
394 
395 	if (*p == '\0')
396 		return NO;
397 	ep = NULL;
398 	errno = 0;
399 	(void)strtoul(p, &ep, 10);
400 	if (errno == 0 && ep && *ep == '\0')
401 		return YES;
402 	else
403 		return NO;
404 }
405 
406 int
407 getaddrinfo(hostname, servname, hints, res)
408 	const char *hostname, *servname;
409 	const struct addrinfo *hints;
410 	struct addrinfo **res;
411 {
412 	struct addrinfo sentinel;
413 	struct addrinfo *cur;
414 	int error = 0;
415 	struct addrinfo ai;
416 	struct addrinfo ai0;
417 	struct addrinfo *pai;
418 	const struct explore *ex;
419 	int numeric = 0;
420 
421 	memset(&sentinel, 0, sizeof(sentinel));
422 	cur = &sentinel;
423 	pai = &ai;
424 	pai->ai_flags = 0;
425 	pai->ai_family = PF_UNSPEC;
426 	pai->ai_socktype = ANY;
427 	pai->ai_protocol = ANY;
428 	pai->ai_addrlen = 0;
429 	pai->ai_canonname = NULL;
430 	pai->ai_addr = NULL;
431 	pai->ai_next = NULL;
432 
433 	if (hostname == NULL && servname == NULL)
434 		return EAI_NONAME;
435 	if (hints) {
436 		/* error check for hints */
437 		if (hints->ai_addrlen || hints->ai_canonname ||
438 		    hints->ai_addr || hints->ai_next)
439 			ERR(EAI_BADHINTS); /* xxx */
440 		if (hints->ai_flags & ~AI_MASK)
441 			ERR(EAI_BADFLAGS);
442 		switch (hints->ai_family) {
443 		case PF_UNSPEC:
444 		case PF_INET:
445 #ifdef INET6
446 		case PF_INET6:
447 #endif
448 			break;
449 		default:
450 			ERR(EAI_FAMILY);
451 		}
452 		memcpy(pai, hints, sizeof(*pai));
453 
454 		/*
455 		 * if both socktype/protocol are specified, check if they
456 		 * are meaningful combination.
457 		 */
458 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
459 			for (ex = explore; ex->e_af >= 0; ex++) {
460 				if (pai->ai_family != ex->e_af)
461 					continue;
462 				if (ex->e_socktype == ANY)
463 					continue;
464 				if (ex->e_protocol == ANY)
465 					continue;
466 				if (pai->ai_socktype == ex->e_socktype &&
467 				    pai->ai_protocol != ex->e_protocol) {
468 					ERR(EAI_BADHINTS);
469 				}
470 			}
471 		}
472 	}
473 
474 	/*
475 	 * post-2553: AI_ALL and AI_V4MAPPED are effective only against
476 	 * AF_INET6 query.  They need to be ignored if specified in other
477 	 * occassions.
478 	 */
479 	switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
480 	case AI_V4MAPPED:
481 	case AI_ALL | AI_V4MAPPED:
482 		if (pai->ai_family != AF_INET6)
483 			pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
484 		break;
485 	case AI_ALL:
486 #if 1
487 		/* illegal */
488 		ERR(EAI_BADFLAGS);
489 #else
490 		pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
491 #endif
492 		break;
493 	}
494 
495 	/*
496 	 * check for special cases.  (1) numeric servname is disallowed if
497 	 * socktype/protocol are left unspecified. (2) servname is disallowed
498 	 * for raw and other inet{,6} sockets.
499 	 */
500 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
501 #ifdef PF_INET6
502 	    || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
503 #endif
504 	    ) {
505 		ai0 = *pai;	/* backup *pai */
506 
507 		if (pai->ai_family == PF_UNSPEC) {
508 #ifdef PF_INET6
509 			pai->ai_family = PF_INET6;
510 #else
511 			pai->ai_family = PF_INET;
512 #endif
513 		}
514 		error = get_portmatch(pai, servname);
515 		if (error)
516 			ERR(error);
517 
518 		*pai = ai0;
519 	}
520 
521 	ai0 = *pai;
522 
523 	/* NULL hostname, or numeric hostname */
524 	for (ex = explore; ex->e_af >= 0; ex++) {
525 		*pai = ai0;
526 
527 		/* PF_UNSPEC entries are prepared for DNS queries only */
528 		if (ex->e_af == PF_UNSPEC)
529 			continue;
530 
531 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
532 			continue;
533 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
534 			continue;
535 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
536 			continue;
537 
538 		if (pai->ai_family == PF_UNSPEC)
539 			pai->ai_family = ex->e_af;
540 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
541 			pai->ai_socktype = ex->e_socktype;
542 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
543 			pai->ai_protocol = ex->e_protocol;
544 
545 		if (hostname == NULL)
546 			error = explore_null(pai, servname, &cur->ai_next);
547 		else
548 			error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
549 
550 		if (error)
551 			goto free;
552 
553 		while (cur && cur->ai_next)
554 			cur = cur->ai_next;
555 	}
556 
557 	/*
558 	 * XXX
559 	 * If numreic representation of AF1 can be interpreted as FQDN
560 	 * representation of AF2, we need to think again about the code below.
561 	 */
562 	if (sentinel.ai_next) {
563 		numeric = 1;
564 		goto good;
565 	}
566 
567 	if (hostname == NULL)
568 		ERR(EAI_NONAME);	/* used to be EAI_NODATA */
569 	if (pai->ai_flags & AI_NUMERICHOST)
570 		ERR(EAI_NONAME);
571 
572 	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
573 		ERR(EAI_FAIL);
574 
575 	/*
576 	 * hostname as alphabetical name.
577 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
578 	 * outer loop by AFs.
579 	 */
580 	for (ex = explore; ex->e_af >= 0; ex++) {
581 		*pai = ai0;
582 
583 		/* require exact match for family field */
584 		if (pai->ai_family != ex->e_af)
585 			continue;
586 
587 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
588 				WILD_SOCKTYPE(ex))) {
589 			continue;
590 		}
591 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
592 				WILD_PROTOCOL(ex))) {
593 			continue;
594 		}
595 
596 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
597 			pai->ai_socktype = ex->e_socktype;
598 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
599 			pai->ai_protocol = ex->e_protocol;
600 
601 		error = explore_fqdn(pai, hostname, servname,
602 			&cur->ai_next);
603 
604 		while (cur && cur->ai_next)
605 			cur = cur->ai_next;
606 	}
607 
608 	/* XXX inhibit errors if we have the result */
609 	if (sentinel.ai_next)
610 		error = 0;
611 
612 good:
613 	/*
614 	 * ensure we return either:
615 	 * - error == 0, non-NULL *res
616 	 * - error != 0, NULL *res
617 	 */
618 	if (error == 0) {
619 		if (sentinel.ai_next) {
620 			/*
621 			 * If the returned entry is for an active connection,
622 			 * and the given name is not numeric, reorder the
623 			 * list, so that the application would try the list
624 			 * in the most efficient order.
625 			 */
626 			if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
627 				if (!numeric)
628 					(void)reorder(&sentinel);
629 			}
630 			*res = sentinel.ai_next;
631 			return SUCCESS;
632 		} else
633 			error = EAI_FAIL;
634 	}
635 free:
636 bad:
637 	if (sentinel.ai_next)
638 		freeaddrinfo(sentinel.ai_next);
639 	*res = NULL;
640 	return error;
641 }
642 
643 static int
644 reorder(sentinel)
645 	struct addrinfo *sentinel;
646 {
647 	struct addrinfo *ai, **aip;
648 	struct ai_order *aio;
649 	int i, n;
650 	struct policyhead policyhead;
651 
652 	/* count the number of addrinfo elements for sorting. */
653 	for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
654 		;
655 
656 	/*
657 	 * If the number is small enough, we can skip the reordering process.
658 	 */
659 	if (n <= 1)
660 		return(n);
661 
662 	/* allocate a temporary array for sort and initialization of it. */
663 	if ((aio = malloc(sizeof(*aio) * n)) == NULL)
664 		return(n);	/* give up reordering */
665 	memset(aio, 0, sizeof(*aio) * n);
666 
667 	/* retrieve address selection policy from the kernel */
668 	TAILQ_INIT(&policyhead);
669 	if (!get_addrselectpolicy(&policyhead)) {
670 		/* no policy is installed into kernel, we don't sort. */
671 		free(aio);
672 		return (n);
673 	}
674 
675 	for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
676 		aio[i].aio_ai = ai;
677 		aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
678 		aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
679 							      &policyhead);
680 	}
681 
682 	/* perform sorting. */
683 	qsort(aio, n, sizeof(*aio), comp_dst);
684 
685 	/* reorder the addrinfo chain. */
686 	for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
687 		*aip = aio[i].aio_ai;
688 		aip = &aio[i].aio_ai->ai_next;
689 	}
690 	*aip = NULL;
691 
692 	/* cleanup and return */
693 	free(aio);
694 	free_addrselectpolicy(&policyhead);
695 	return(n);
696 }
697 
698 static int
699 get_addrselectpolicy(head)
700 	struct policyhead *head;
701 {
702 #ifdef INET6
703 	int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
704 	size_t l;
705 	char *buf;
706 	struct in6_addrpolicy *pol, *ep;
707 
708 	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0)
709 		return (0);
710 	if ((buf = malloc(l)) == NULL)
711 		return (0);
712 	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
713 		free(buf);
714 		return (0);
715 	}
716 
717 	ep = (struct in6_addrpolicy *)(buf + l);
718 	for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
719 		struct policyqueue *new;
720 
721 		if ((new = malloc(sizeof(*new))) == NULL) {
722 			free_addrselectpolicy(head); /* make the list empty */
723 			break;
724 		}
725 		new->pc_policy = *pol;
726 		TAILQ_INSERT_TAIL(head, new, pc_entry);
727 	}
728 
729 	free(buf);
730 	return (1);
731 #else
732 	return (0);
733 #endif
734 }
735 
736 static void
737 free_addrselectpolicy(head)
738 	struct policyhead *head;
739 {
740 	struct policyqueue *ent, *nent;
741 
742 	for (ent = TAILQ_FIRST(head); ent; ent = nent) {
743 		nent = TAILQ_NEXT(ent, pc_entry);
744 		TAILQ_REMOVE(head, ent, pc_entry);
745 		free(ent);
746 	}
747 }
748 
749 static struct policyqueue *
750 match_addrselectpolicy(addr, head)
751 	struct sockaddr *addr;
752 	struct policyhead *head;
753 {
754 #ifdef INET6
755 	struct policyqueue *ent, *bestent = NULL;
756 	struct in6_addrpolicy *pol;
757 	int matchlen, bestmatchlen = -1;
758 	u_char *mp, *ep, *k, *p, m;
759 	struct sockaddr_in6 key;
760 
761 	switch(addr->sa_family) {
762 	case AF_INET6:
763 		key = *(struct sockaddr_in6 *)addr;
764 		break;
765 	case AF_INET:
766 		/* convert the address into IPv4-mapped IPv6 address. */
767 		memset(&key, 0, sizeof(key));
768 		key.sin6_family = AF_INET6;
769 		key.sin6_len = sizeof(key);
770 		key.sin6_addr.s6_addr[10] = 0xff;
771 		key.sin6_addr.s6_addr[11] = 0xff;
772 		memcpy(&key.sin6_addr.s6_addr[12],
773 		       &((struct sockaddr_in *)addr)->sin_addr, 4);
774 		break;
775 	default:
776 		return(NULL);
777 	}
778 
779 	for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
780 		pol = &ent->pc_policy;
781 		matchlen = 0;
782 
783 		mp = (u_char *)&pol->addrmask.sin6_addr;
784 		ep = mp + 16;	/* XXX: scope field? */
785 		k = (u_char *)&key.sin6_addr;
786 		p = (u_char *)&pol->addr.sin6_addr;
787 		for (; mp < ep && *mp; mp++, k++, p++) {
788 			m = *mp;
789 			if ((*k & m) != *p)
790 				goto next; /* not match */
791 			if (m == 0xff) /* short cut for a typical case */
792 				matchlen += 8;
793 			else {
794 				while (m >= 0x80) {
795 					matchlen++;
796 					m <<= 1;
797 				}
798 			}
799 		}
800 
801 		/* matched.  check if this is better than the current best. */
802 		if (matchlen > bestmatchlen) {
803 			bestent = ent;
804 			bestmatchlen = matchlen;
805 		}
806 
807 	  next:
808 		continue;
809 	}
810 
811 	return(bestent);
812 #else
813 	return(NULL);
814 #endif
815 
816 }
817 
818 static int
819 comp_dst(arg1, arg2)
820 	const void *arg1, *arg2;
821 {
822 	const struct ai_order *dst1 = arg1, *dst2 = arg2;
823 
824 	/*
825 	 * Rule 1: Avoid unusable destinations.
826 	 * XXX: we currently do not consider if an appropriate route exists.
827 	 */
828 	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
829 	    dst2->aio_srcsa.sa_family == AF_UNSPEC) {
830 		return(-1);
831 	}
832 	if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
833 	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
834 		return(1);
835 	}
836 
837 	/* Rule 2: Prefer matching scope. */
838 	if (dst1->aio_dstscope == dst1->aio_srcscope &&
839 	    dst2->aio_dstscope != dst2->aio_srcscope) {
840 		return(-1);
841 	}
842 	if (dst1->aio_dstscope != dst1->aio_srcscope &&
843 	    dst2->aio_dstscope == dst2->aio_srcscope) {
844 		return(1);
845 	}
846 
847 	/* Rule 3: Avoid deprecated addresses. */
848 	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
849 	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
850 		if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
851 		    (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
852 			return(-1);
853 		}
854 		if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
855 		    !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
856 			return(1);
857 		}
858 	}
859 
860 	/* Rule 4: Prefer home addresses. */
861 	/* XXX: not implemented yet */
862 
863 	/* Rule 5: Prefer matching label. */
864 #ifdef INET6
865 	if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
866 	    dst1->aio_srcpolicy->pc_policy.label ==
867 	    dst1->aio_dstpolicy->pc_policy.label &&
868 	    (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
869 	     dst2->aio_srcpolicy->pc_policy.label !=
870 	     dst2->aio_dstpolicy->pc_policy.label)) {
871 		return(-1);
872 	}
873 	if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
874 	    dst2->aio_srcpolicy->pc_policy.label ==
875 	    dst2->aio_dstpolicy->pc_policy.label &&
876 	    (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
877 	     dst1->aio_srcpolicy->pc_policy.label !=
878 	     dst1->aio_dstpolicy->pc_policy.label)) {
879 		return(1);
880 	}
881 #endif
882 
883 	/* Rule 6: Prefer higher precedence. */
884 #ifdef INET6
885 	if (dst1->aio_dstpolicy &&
886 	    (dst2->aio_dstpolicy == NULL ||
887 	     dst1->aio_dstpolicy->pc_policy.preced >
888 	     dst2->aio_dstpolicy->pc_policy.preced)) {
889 		return(-1);
890 	}
891 	if (dst2->aio_dstpolicy &&
892 	    (dst1->aio_dstpolicy == NULL ||
893 	     dst2->aio_dstpolicy->pc_policy.preced >
894 	     dst1->aio_dstpolicy->pc_policy.preced)) {
895 		return(1);
896 	}
897 #endif
898 
899 	/* Rule 7: Prefer native transport. */
900 	/* XXX: not implemented yet */
901 
902 	/* Rule 8: Prefer smaller scope. */
903 	if (dst1->aio_dstscope >= 0 &&
904 	    dst1->aio_dstscope < dst2->aio_dstscope) {
905 		return(-1);
906 	}
907 	if (dst2->aio_dstscope >= 0 &&
908 	    dst2->aio_dstscope < dst1->aio_dstscope) {
909 		return(1);
910 	}
911 
912 	/*
913 	 * Rule 9: Use longest matching prefix.
914 	 * We compare the match length in a same AF only.
915 	 */
916 	if (dst1->aio_ai->ai_addr->sa_family ==
917 	    dst2->aio_ai->ai_addr->sa_family) {
918 		if (dst1->aio_matchlen > dst2->aio_matchlen) {
919 			return(-1);
920 		}
921 		if (dst1->aio_matchlen < dst2->aio_matchlen) {
922 			return(1);
923 		}
924 	}
925 
926 	/* Rule 10: Otherwise, leave the order unchanged. */
927 	return(-1);
928 }
929 
930 /*
931  * Copy from scope.c.
932  * XXX: we should standardize the functions and link them as standard
933  * library.
934  */
935 static int
936 gai_addr2scopetype(sa)
937 	struct sockaddr *sa;
938 {
939 #ifdef INET6
940 	struct sockaddr_in6 *sa6;
941 #endif
942 	struct sockaddr_in *sa4;
943 
944 	switch(sa->sa_family) {
945 #ifdef INET6
946 	case AF_INET6:
947 		sa6 = (struct sockaddr_in6 *)sa;
948 		if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
949 			/* just use the scope field of the multicast address */
950 			return(sa6->sin6_addr.s6_addr[2] & 0x0f);
951 		}
952 		/*
953 		 * Unicast addresses: map scope type to corresponding scope
954 		 * value defined for multcast addresses.
955 		 * XXX: hardcoded scope type values are bad...
956 		 */
957 		if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
958 			return(1); /* node local scope */
959 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
960 			return(2); /* link-local scope */
961 		if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
962 			return(5); /* site-local scope */
963 		return(14);	/* global scope */
964 		break;
965 #endif
966 	case AF_INET:
967 		/*
968 		 * IPv4 pseudo scoping according to RFC 3484.
969 		 */
970 		sa4 = (struct sockaddr_in *)sa;
971 		/* IPv4 autoconfiguration addresses have link-local scope. */
972 		if (((u_char *)&sa4->sin_addr)[0] == 169 &&
973 		    ((u_char *)&sa4->sin_addr)[1] == 254)
974 			return(2);
975 		/* Private addresses have site-local scope. */
976 		if (((u_char *)&sa4->sin_addr)[0] == 10 ||
977 		    (((u_char *)&sa4->sin_addr)[0] == 172 &&
978 		     (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
979 		    (((u_char *)&sa4->sin_addr)[0] == 192 &&
980 		     ((u_char *)&sa4->sin_addr)[1] == 168))
981 			return(5);
982 		/* Loopback addresses have link-local scope. */
983 		if (((u_char *)&sa4->sin_addr)[0] == 127)
984 			return(2);
985 		return(14);
986 		break;
987 	default:
988 		errno = EAFNOSUPPORT; /* is this a good error? */
989 		return(-1);
990 	}
991 }
992 
993 /*
994  * hostname == NULL.
995  * passive socket -> anyaddr (0.0.0.0 or ::)
996  * non-passive socket -> localhost (127.0.0.1 or ::1)
997  */
998 static int
999 explore_null(pai, servname, res)
1000 	const struct addrinfo *pai;
1001 	const char *servname;
1002 	struct addrinfo **res;
1003 {
1004 	int s;
1005 	const struct afd *afd;
1006 	struct addrinfo *cur;
1007 	struct addrinfo sentinel;
1008 	int error;
1009 
1010 	*res = NULL;
1011 	sentinel.ai_next = NULL;
1012 	cur = &sentinel;
1013 
1014 	/*
1015 	 * filter out AFs that are not supported by the kernel
1016 	 * XXX errno?
1017 	 */
1018 	s = _socket(pai->ai_family, SOCK_DGRAM, 0);
1019 	if (s < 0) {
1020 		if (errno != EMFILE)
1021 			return 0;
1022 	} else
1023 		_close(s);
1024 
1025 	/*
1026 	 * if the servname does not match socktype/protocol, ignore it.
1027 	 */
1028 	if (get_portmatch(pai, servname) != 0)
1029 		return 0;
1030 
1031 	afd = find_afd(pai->ai_family);
1032 	if (afd == NULL)
1033 		return 0;
1034 
1035 	if (pai->ai_flags & AI_PASSIVE) {
1036 		GET_AI(cur->ai_next, afd, afd->a_addrany);
1037 		/* xxx meaningless?
1038 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
1039 		 */
1040 		GET_PORT(cur->ai_next, servname);
1041 	} else {
1042 		GET_AI(cur->ai_next, afd, afd->a_loopback);
1043 		/* xxx meaningless?
1044 		 * GET_CANONNAME(cur->ai_next, "localhost");
1045 		 */
1046 		GET_PORT(cur->ai_next, servname);
1047 	}
1048 	cur = cur->ai_next;
1049 
1050 	*res = sentinel.ai_next;
1051 	return 0;
1052 
1053 free:
1054 	if (sentinel.ai_next)
1055 		freeaddrinfo(sentinel.ai_next);
1056 	return error;
1057 }
1058 
1059 /*
1060  * numeric hostname
1061  */
1062 static int
1063 explore_numeric(pai, hostname, servname, res)
1064 	const struct addrinfo *pai;
1065 	const char *hostname;
1066 	const char *servname;
1067 	struct addrinfo **res;
1068 {
1069 	const struct afd *afd;
1070 	struct addrinfo *cur;
1071 	struct addrinfo sentinel;
1072 	int error;
1073 	char pton[PTON_MAX];
1074 
1075 	*res = NULL;
1076 	sentinel.ai_next = NULL;
1077 	cur = &sentinel;
1078 
1079 	/*
1080 	 * if the servname does not match socktype/protocol, ignore it.
1081 	 */
1082 	if (get_portmatch(pai, servname) != 0)
1083 		return 0;
1084 
1085 	afd = find_afd(pai->ai_family);
1086 	if (afd == NULL)
1087 		return 0;
1088 
1089 	switch (afd->a_af) {
1090 #if 1 /*X/Open spec*/
1091 	case AF_INET:
1092 		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
1093 			if (pai->ai_family == afd->a_af ||
1094 			    pai->ai_family == PF_UNSPEC /*?*/) {
1095 				GET_AI(cur->ai_next, afd, pton);
1096 				GET_PORT(cur->ai_next, servname);
1097 				while (cur && cur->ai_next)
1098 					cur = cur->ai_next;
1099 			} else
1100 				ERR(EAI_FAMILY);	/*xxx*/
1101 		}
1102 		break;
1103 #endif
1104 	default:
1105 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
1106 			if (pai->ai_family == afd->a_af ||
1107 			    pai->ai_family == PF_UNSPEC /*?*/) {
1108 				GET_AI(cur->ai_next, afd, pton);
1109 				GET_PORT(cur->ai_next, servname);
1110 				while (cur && cur->ai_next)
1111 					cur = cur->ai_next;
1112 			} else
1113 				ERR(EAI_FAMILY);	/* XXX */
1114 		}
1115 		break;
1116 	}
1117 
1118 	*res = sentinel.ai_next;
1119 	return 0;
1120 
1121 free:
1122 bad:
1123 	if (sentinel.ai_next)
1124 		freeaddrinfo(sentinel.ai_next);
1125 	return error;
1126 }
1127 
1128 /*
1129  * numeric hostname with scope
1130  */
1131 static int
1132 explore_numeric_scope(pai, hostname, servname, res)
1133 	const struct addrinfo *pai;
1134 	const char *hostname;
1135 	const char *servname;
1136 	struct addrinfo **res;
1137 {
1138 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
1139 	return explore_numeric(pai, hostname, servname, res);
1140 #else
1141 	const struct afd *afd;
1142 	struct addrinfo *cur;
1143 	int error;
1144 	char *cp, *hostname2 = NULL, *scope, *addr;
1145 	struct sockaddr_in6 *sin6;
1146 
1147 	/*
1148 	 * if the servname does not match socktype/protocol, ignore it.
1149 	 */
1150 	if (get_portmatch(pai, servname) != 0)
1151 		return 0;
1152 
1153 	afd = find_afd(pai->ai_family);
1154 	if (afd == NULL)
1155 		return 0;
1156 
1157 	if (!afd->a_scoped)
1158 		return explore_numeric(pai, hostname, servname, res);
1159 
1160 	cp = strchr(hostname, SCOPE_DELIMITER);
1161 	if (cp == NULL)
1162 		return explore_numeric(pai, hostname, servname, res);
1163 
1164 	/*
1165 	 * Handle special case of <scoped_address><delimiter><scope id>
1166 	 */
1167 	hostname2 = strdup(hostname);
1168 	if (hostname2 == NULL)
1169 		return EAI_MEMORY;
1170 	/* terminate at the delimiter */
1171 	hostname2[cp - hostname] = '\0';
1172 	addr = hostname2;
1173 	scope = cp + 1;
1174 
1175 	error = explore_numeric(pai, addr, servname, res);
1176 	if (error == 0) {
1177 		u_int32_t scopeid;
1178 
1179 		for (cur = *res; cur; cur = cur->ai_next) {
1180 			if (cur->ai_family != AF_INET6)
1181 				continue;
1182 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1183 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1184 				free(hostname2);
1185 				return(EAI_NONAME); /* XXX: is return OK? */
1186 			}
1187 			sin6->sin6_scope_id = scopeid;
1188 		}
1189 	}
1190 
1191 	free(hostname2);
1192 
1193 	return error;
1194 #endif
1195 }
1196 
1197 static int
1198 get_canonname(pai, ai, str)
1199 	const struct addrinfo *pai;
1200 	struct addrinfo *ai;
1201 	const char *str;
1202 {
1203 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
1204 		ai->ai_canonname = (char *)malloc(strlen(str) + 1);
1205 		if (ai->ai_canonname == NULL)
1206 			return EAI_MEMORY;
1207 		strlcpy(ai->ai_canonname, str, strlen(str) + 1);
1208 	}
1209 	return 0;
1210 }
1211 
1212 static struct addrinfo *
1213 get_ai(pai, afd, addr)
1214 	const struct addrinfo *pai;
1215 	const struct afd *afd;
1216 	const char *addr;
1217 {
1218 	char *p;
1219 	struct addrinfo *ai;
1220 #ifdef FAITH
1221 	struct in6_addr faith_prefix;
1222 	char *fp_str;
1223 	int translate = 0;
1224 #endif
1225 
1226 #ifdef FAITH
1227 	/*
1228 	 * Transfrom an IPv4 addr into a special IPv6 addr format for
1229 	 * IPv6->IPv4 translation gateway. (only TCP is supported now)
1230 	 *
1231 	 * +-----------------------------------+------------+
1232 	 * | faith prefix part (12 bytes)      | embedded   |
1233 	 * |                                   | IPv4 addr part (4 bytes)
1234 	 * +-----------------------------------+------------+
1235 	 *
1236 	 * faith prefix part is specified as ascii IPv6 addr format
1237 	 * in environmental variable GAI.
1238 	 * For FAITH to work correctly, routing to faith prefix must be
1239 	 * setup toward a machine where a FAITH daemon operates.
1240 	 * Also, the machine must enable some mechanizm
1241 	 * (e.g. faith interface hack) to divert those packet with
1242 	 * faith prefixed destination addr to user-land FAITH daemon.
1243 	 */
1244 	fp_str = getenv("GAI");
1245 	if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
1246 	    afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
1247 		u_int32_t v4a;
1248 		u_int8_t v4a_top;
1249 
1250 		memcpy(&v4a, addr, sizeof v4a);
1251 		v4a_top = v4a >> IN_CLASSA_NSHIFT;
1252 		if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
1253 		    v4a_top != 0 && v4a != IN_LOOPBACKNET) {
1254 			afd = &afdl[N_INET6];
1255 			memcpy(&faith_prefix.s6_addr[12], addr,
1256 			       sizeof(struct in_addr));
1257 			translate = 1;
1258 		}
1259 	}
1260 #endif
1261 
1262 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1263 		+ (afd->a_socklen));
1264 	if (ai == NULL)
1265 		return NULL;
1266 
1267 	memcpy(ai, pai, sizeof(struct addrinfo));
1268 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1269 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1270 	ai->ai_addr->sa_len = afd->a_socklen;
1271 	ai->ai_addrlen = afd->a_socklen;
1272 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1273 	p = (char *)(void *)(ai->ai_addr);
1274 #ifdef FAITH
1275 	if (translate == 1)
1276 		memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
1277 	else
1278 #endif
1279 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1280 	return ai;
1281 }
1282 
1283 static int
1284 get_portmatch(ai, servname)
1285 	const struct addrinfo *ai;
1286 	const char *servname;
1287 {
1288 
1289 	/* get_port does not touch first argument. when matchonly == 1. */
1290 	/* LINTED const cast */
1291 	return get_port((struct addrinfo *)ai, servname, 1);
1292 }
1293 
1294 static int
1295 get_port(ai, servname, matchonly)
1296 	struct addrinfo *ai;
1297 	const char *servname;
1298 	int matchonly;
1299 {
1300 	const char *proto;
1301 	struct servent *sp;
1302 	int port;
1303 	int allownumeric;
1304 
1305 	if (servname == NULL)
1306 		return 0;
1307 	switch (ai->ai_family) {
1308 	case AF_INET:
1309 #ifdef AF_INET6
1310 	case AF_INET6:
1311 #endif
1312 		break;
1313 	default:
1314 		return 0;
1315 	}
1316 
1317 	switch (ai->ai_socktype) {
1318 	case SOCK_RAW:
1319 		return EAI_SERVICE;
1320 	case SOCK_DGRAM:
1321 	case SOCK_STREAM:
1322 		allownumeric = 1;
1323 		break;
1324 	case ANY:
1325 		allownumeric = 0;
1326 		break;
1327 	default:
1328 		return EAI_SOCKTYPE;
1329 	}
1330 
1331 	if (str_isnumber(servname)) {
1332 		if (!allownumeric)
1333 			return EAI_SERVICE;
1334 		port = atoi(servname);
1335 		if (port < 0 || port > 65535)
1336 			return EAI_SERVICE;
1337 		port = htons(port);
1338 	} else {
1339 		switch (ai->ai_socktype) {
1340 		case SOCK_DGRAM:
1341 			proto = "udp";
1342 			break;
1343 		case SOCK_STREAM:
1344 			proto = "tcp";
1345 			break;
1346 		default:
1347 			proto = NULL;
1348 			break;
1349 		}
1350 
1351 		THREAD_LOCK();
1352 		if ((sp = getservbyname(servname, proto)) == NULL) {
1353 			THREAD_UNLOCK();
1354 			return EAI_SERVICE;
1355 		}
1356 		port = sp->s_port;
1357 		THREAD_UNLOCK();
1358 	}
1359 
1360 	if (!matchonly) {
1361 		switch (ai->ai_family) {
1362 		case AF_INET:
1363 			((struct sockaddr_in *)(void *)
1364 			    ai->ai_addr)->sin_port = port;
1365 			break;
1366 #ifdef INET6
1367 		case AF_INET6:
1368 			((struct sockaddr_in6 *)(void *)
1369 			    ai->ai_addr)->sin6_port = port;
1370 			break;
1371 #endif
1372 		}
1373 	}
1374 
1375 	return 0;
1376 }
1377 
1378 static const struct afd *
1379 find_afd(af)
1380 	int af;
1381 {
1382 	const struct afd *afd;
1383 
1384 	if (af == PF_UNSPEC)
1385 		return NULL;
1386 	for (afd = afdl; afd->a_af; afd++) {
1387 		if (afd->a_af == af)
1388 			return afd;
1389 	}
1390 	return NULL;
1391 }
1392 
1393 /*
1394  * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
1395  * will take care of it.
1396  * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
1397  * if the code is right or not.
1398  *
1399  * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1400  * _dns_getaddrinfo.
1401  */
1402 static int
1403 addrconfig(pai)
1404 	struct addrinfo *pai;
1405 {
1406 	int s, af;
1407 
1408 	/*
1409 	 * TODO:
1410 	 * Note that implementation dependent test for address
1411 	 * configuration should be done everytime called
1412 	 * (or apropriate interval),
1413 	 * because addresses will be dynamically assigned or deleted.
1414 	 */
1415 	af = pai->ai_family;
1416 	if (af == AF_UNSPEC) {
1417 		if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1418 			af = AF_INET;
1419 		else {
1420 			_close(s);
1421 			if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1422 				af = AF_INET6;
1423 			else
1424 				_close(s);
1425 		}
1426 	}
1427 	if (af != AF_UNSPEC) {
1428 		if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
1429 			return 0;
1430 		_close(s);
1431 	}
1432 	pai->ai_family = af;
1433 	return 1;
1434 }
1435 
1436 #ifdef INET6
1437 /* convert a string to a scope identifier. XXX: IPv6 specific */
1438 static int
1439 ip6_str2scopeid(scope, sin6, scopeid)
1440 	char *scope;
1441 	struct sockaddr_in6 *sin6;
1442 	u_int32_t *scopeid;
1443 {
1444 	u_long lscopeid;
1445 	struct in6_addr *a6;
1446 	char *ep;
1447 
1448 	a6 = &sin6->sin6_addr;
1449 
1450 	/* empty scopeid portion is invalid */
1451 	if (*scope == '\0')
1452 		return -1;
1453 
1454 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1455 		/*
1456 		 * We currently assume a one-to-one mapping between links
1457 		 * and interfaces, so we simply use interface indices for
1458 		 * like-local scopes.
1459 		 */
1460 		*scopeid = if_nametoindex(scope);
1461 		if (*scopeid == 0)
1462 			goto trynumeric;
1463 		return 0;
1464 	}
1465 
1466 	/* still unclear about literal, allow numeric only - placeholder */
1467 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1468 		goto trynumeric;
1469 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1470 		goto trynumeric;
1471 	else
1472 		goto trynumeric;	/* global */
1473 
1474 	/* try to convert to a numeric id as a last resort */
1475   trynumeric:
1476 	errno = 0;
1477 	lscopeid = strtoul(scope, &ep, 10);
1478 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1479 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1480 		return 0;
1481 	else
1482 		return -1;
1483 }
1484 #endif
1485 
1486 /*
1487  * FQDN hostname, DNS lookup
1488  */
1489 static int
1490 explore_fqdn(pai, hostname, servname, res)
1491 	const struct addrinfo *pai;
1492 	const char *hostname;
1493 	const char *servname;
1494 	struct addrinfo **res;
1495 {
1496 	struct addrinfo *result;
1497 	struct addrinfo *cur;
1498 	int error = 0;
1499 	static const ns_dtab dtab[] = {
1500 		NS_FILES_CB(_files_getaddrinfo, NULL)
1501 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
1502 		NS_NIS_CB(_yp_getaddrinfo, NULL)
1503 		{ 0 }
1504 	};
1505 
1506 	result = NULL;
1507 
1508 	/*
1509 	 * if the servname does not match socktype/protocol, ignore it.
1510 	 */
1511 	if (get_portmatch(pai, servname) != 0)
1512 		return 0;
1513 
1514 	switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1515 			default_dns_files, hostname, pai)) {
1516 	case NS_TRYAGAIN:
1517 		error = EAI_AGAIN;
1518 		goto free;
1519 	case NS_UNAVAIL:
1520 		error = EAI_FAIL;
1521 		goto free;
1522 	case NS_NOTFOUND:
1523 		error = EAI_NONAME;
1524 		goto free;
1525 	case NS_SUCCESS:
1526 		error = 0;
1527 		for (cur = result; cur; cur = cur->ai_next) {
1528 			GET_PORT(cur, servname);
1529 			/* canonname should be filled already */
1530 		}
1531 		break;
1532 	}
1533 
1534 	*res = result;
1535 
1536 	return 0;
1537 
1538 free:
1539 	if (result)
1540 		freeaddrinfo(result);
1541 	return error;
1542 }
1543 
1544 #ifdef DEBUG
1545 static const char AskedForGot[] =
1546 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1547 #endif
1548 static FILE *hostf = NULL;
1549 
1550 static struct addrinfo *
1551 getanswer(answer, anslen, qname, qtype, pai)
1552 	const querybuf *answer;
1553 	int anslen;
1554 	const char *qname;
1555 	int qtype;
1556 	const struct addrinfo *pai;
1557 {
1558 	struct addrinfo sentinel, *cur;
1559 	struct addrinfo ai;
1560 	const struct afd *afd;
1561 	char *canonname;
1562 	const HEADER *hp;
1563 	const u_char *cp;
1564 	int n;
1565 	const u_char *eom;
1566 	char *bp, *ep;
1567 	int type, class, ancount, qdcount;
1568 	int haveanswer, had_error;
1569 	char tbuf[MAXDNAME];
1570 	int (*name_ok)(const char *);
1571 	char hostbuf[8*1024];
1572 
1573 	memset(&sentinel, 0, sizeof(sentinel));
1574 	cur = &sentinel;
1575 
1576 	canonname = NULL;
1577 	eom = answer->buf + anslen;
1578 	switch (qtype) {
1579 	case T_A:
1580 	case T_AAAA:
1581 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
1582 		name_ok = res_hnok;
1583 		break;
1584 	default:
1585 		return (NULL);	/* XXX should be abort(); */
1586 	}
1587 	/*
1588 	 * find first satisfactory answer
1589 	 */
1590 	hp = &answer->hdr;
1591 	ancount = ntohs(hp->ancount);
1592 	qdcount = ntohs(hp->qdcount);
1593 	bp = hostbuf;
1594 	ep = hostbuf + sizeof hostbuf;
1595 	cp = answer->buf + HFIXEDSZ;
1596 	if (qdcount != 1) {
1597 		h_errno = NO_RECOVERY;
1598 		return (NULL);
1599 	}
1600 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1601 	if ((n < 0) || !(*name_ok)(bp)) {
1602 		h_errno = NO_RECOVERY;
1603 		return (NULL);
1604 	}
1605 	cp += n + QFIXEDSZ;
1606 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1607 		/* res_send() has already verified that the query name is the
1608 		 * same as the one we sent; this just gets the expanded name
1609 		 * (i.e., with the succeeding search-domain tacked on).
1610 		 */
1611 		n = strlen(bp) + 1;		/* for the \0 */
1612 		if (n >= MAXHOSTNAMELEN) {
1613 			h_errno = NO_RECOVERY;
1614 			return (NULL);
1615 		}
1616 		canonname = bp;
1617 		bp += n;
1618 		/* The qname can be abbreviated, but h_name is now absolute. */
1619 		qname = canonname;
1620 	}
1621 	haveanswer = 0;
1622 	had_error = 0;
1623 	while (ancount-- > 0 && cp < eom && !had_error) {
1624 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1625 		if ((n < 0) || !(*name_ok)(bp)) {
1626 			had_error++;
1627 			continue;
1628 		}
1629 		cp += n;			/* name */
1630 		type = _getshort(cp);
1631  		cp += INT16SZ;			/* type */
1632 		class = _getshort(cp);
1633  		cp += INT16SZ + INT32SZ;	/* class, TTL */
1634 		n = _getshort(cp);
1635 		cp += INT16SZ;			/* len */
1636 		if (class != C_IN) {
1637 			/* XXX - debug? syslog? */
1638 			cp += n;
1639 			continue;		/* XXX - had_error++ ? */
1640 		}
1641 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1642 		    type == T_CNAME) {
1643 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1644 			if ((n < 0) || !(*name_ok)(tbuf)) {
1645 				had_error++;
1646 				continue;
1647 			}
1648 			cp += n;
1649 			/* Get canonical name. */
1650 			n = strlen(tbuf) + 1;	/* for the \0 */
1651 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1652 				had_error++;
1653 				continue;
1654 			}
1655 			strlcpy(bp, tbuf, ep - bp);
1656 			canonname = bp;
1657 			bp += n;
1658 			continue;
1659 		}
1660 		if (qtype == T_ANY) {
1661 			if (!(type == T_A || type == T_AAAA)) {
1662 				cp += n;
1663 				continue;
1664 			}
1665 		} else if (type != qtype) {
1666 #ifdef DEBUG
1667 			if (type != T_KEY && type != T_SIG)
1668 				syslog(LOG_NOTICE|LOG_AUTH,
1669 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1670 				       qname, p_class(C_IN), p_type(qtype),
1671 				       p_type(type));
1672 #endif
1673 			cp += n;
1674 			continue;		/* XXX - had_error++ ? */
1675 		}
1676 		switch (type) {
1677 		case T_A:
1678 		case T_AAAA:
1679 			if (strcasecmp(canonname, bp) != 0) {
1680 #ifdef DEBUG
1681 				syslog(LOG_NOTICE|LOG_AUTH,
1682 				       AskedForGot, canonname, bp);
1683 #endif
1684 				cp += n;
1685 				continue;	/* XXX - had_error++ ? */
1686 			}
1687 			if (type == T_A && n != INADDRSZ) {
1688 				cp += n;
1689 				continue;
1690 			}
1691 			if (type == T_AAAA && n != IN6ADDRSZ) {
1692 				cp += n;
1693 				continue;
1694 			}
1695 #ifdef FILTER_V4MAPPED
1696 			if (type == T_AAAA) {
1697 				struct in6_addr in6;
1698 				memcpy(&in6, cp, sizeof(in6));
1699 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1700 					cp += n;
1701 					continue;
1702 				}
1703 			}
1704 #endif
1705 			if (!haveanswer) {
1706 				int nn;
1707 
1708 				canonname = bp;
1709 				nn = strlen(bp) + 1;	/* for the \0 */
1710 				bp += nn;
1711 			}
1712 
1713 			/* don't overwrite pai */
1714 			ai = *pai;
1715 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1716 			afd = find_afd(ai.ai_family);
1717 			if (afd == NULL) {
1718 				cp += n;
1719 				continue;
1720 			}
1721 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1722 			if (cur->ai_next == NULL)
1723 				had_error++;
1724 			while (cur && cur->ai_next)
1725 				cur = cur->ai_next;
1726 			cp += n;
1727 			break;
1728 		default:
1729 			abort();
1730 		}
1731 		if (!had_error)
1732 			haveanswer++;
1733 	}
1734 	if (haveanswer) {
1735 #if defined(RESOLVSORT)
1736 		/*
1737 		 * We support only IPv4 address for backward
1738 		 * compatibility against gethostbyname(3).
1739 		 */
1740 		if (_res.nsort && qtype == T_A) {
1741 			if (addr4sort(&sentinel) < 0) {
1742 				freeaddrinfo(sentinel.ai_next);
1743 				h_errno = NO_RECOVERY;
1744 				return NULL;
1745 			}
1746 		}
1747 #endif /*RESOLVSORT*/
1748 		if (!canonname)
1749 			(void)get_canonname(pai, sentinel.ai_next, qname);
1750 		else
1751 			(void)get_canonname(pai, sentinel.ai_next, canonname);
1752 		h_errno = NETDB_SUCCESS;
1753 		return sentinel.ai_next;
1754 	}
1755 
1756 	h_errno = NO_RECOVERY;
1757 	return NULL;
1758 }
1759 
1760 #ifdef RESOLVSORT
1761 struct addr_ptr {
1762 	struct addrinfo *ai;
1763 	int aval;
1764 };
1765 
1766 static int
1767 addr4sort(struct addrinfo *sentinel)
1768 {
1769 	struct addrinfo *ai;
1770 	struct addr_ptr *addrs, addr;
1771 	struct sockaddr_in *sin;
1772 	int naddrs, i, j;
1773 	int needsort = 0;
1774 
1775 	if (!sentinel)
1776 		return -1;
1777 	naddrs = 0;
1778 	for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
1779 		naddrs++;
1780 	if (naddrs < 2)
1781 		return 0;		/* We don't need sorting. */
1782 	if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
1783 		return -1;
1784 	i = 0;
1785 	for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
1786 		sin = (struct sockaddr_in *)ai->ai_addr;
1787 		for (j = 0; (unsigned)j < _res.nsort; j++) {
1788 			if (_res.sort_list[j].addr.s_addr ==
1789 			    (sin->sin_addr.s_addr & _res.sort_list[j].mask))
1790 				break;
1791 		}
1792 		addrs[i].ai = ai;
1793 		addrs[i].aval = j;
1794 		if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
1795 			needsort = i;
1796 		i++;
1797 	}
1798 	if (!needsort) {
1799 		free(addrs);
1800 		return 0;
1801 	}
1802 
1803 	while (needsort < naddrs) {
1804 	    for (j = needsort - 1; j >= 0; j--) {
1805 		if (addrs[j].aval > addrs[j+1].aval) {
1806 		    addr = addrs[j];
1807 		    addrs[j] = addrs[j + 1];
1808 		    addrs[j + 1] = addr;
1809 		} else
1810 		    break;
1811 	    }
1812 	    needsort++;
1813 	}
1814 
1815 	ai = sentinel;
1816 	for (i = 0; i < naddrs; ++i) {
1817 		ai->ai_next = addrs[i].ai;
1818 		ai = ai->ai_next;
1819 	}
1820 	ai->ai_next = NULL;
1821 	free(addrs);
1822 	return 0;
1823 }
1824 #endif /*RESOLVSORT*/
1825 
1826 /*ARGSUSED*/
1827 static int
1828 _dns_getaddrinfo(rv, cb_data, ap)
1829 	void	*rv;
1830 	void	*cb_data;
1831 	va_list	 ap;
1832 {
1833 	struct addrinfo *ai;
1834 	querybuf *buf, *buf2;
1835 	const char *name;
1836 	const struct addrinfo *pai;
1837 	struct addrinfo sentinel, *cur;
1838 	struct res_target q, q2;
1839 
1840 	name = va_arg(ap, char *);
1841 	pai = va_arg(ap, const struct addrinfo *);
1842 
1843 	memset(&q, 0, sizeof(q2));
1844 	memset(&q2, 0, sizeof(q2));
1845 	memset(&sentinel, 0, sizeof(sentinel));
1846 	cur = &sentinel;
1847 
1848 	buf = malloc(sizeof(*buf));
1849 	if (!buf) {
1850 		h_errno = NETDB_INTERNAL;
1851 		return NS_NOTFOUND;
1852 	}
1853 	buf2 = malloc(sizeof(*buf2));
1854 	if (!buf2) {
1855 		free(buf);
1856 		h_errno = NETDB_INTERNAL;
1857 		return NS_NOTFOUND;
1858 	}
1859 
1860 	switch (pai->ai_family) {
1861 	case AF_UNSPEC:
1862 		/* prefer IPv6 */
1863 		q.name = name;
1864 		q.qclass = C_IN;
1865 		q.qtype = T_AAAA;
1866 		q.answer = buf->buf;
1867 		q.anslen = sizeof(buf->buf);
1868 		q.next = &q2;
1869 		q2.name = name;
1870 		q2.qclass = C_IN;
1871 		q2.qtype = T_A;
1872 		q2.answer = buf2->buf;
1873 		q2.anslen = sizeof(buf2->buf);
1874 		break;
1875 	case AF_INET:
1876 		q.name = name;
1877 		q.qclass = C_IN;
1878 		q.qtype = T_A;
1879 		q.answer = buf->buf;
1880 		q.anslen = sizeof(buf->buf);
1881 		break;
1882 	case AF_INET6:
1883 		q.name = name;
1884 		q.qclass = C_IN;
1885 		q.qtype = T_AAAA;
1886 		q.answer = buf->buf;
1887 		q.anslen = sizeof(buf->buf);
1888 		break;
1889 	default:
1890 		free(buf);
1891 		free(buf2);
1892 		return NS_UNAVAIL;
1893 	}
1894 	if (res_searchN(name, &q) < 0) {
1895 		free(buf);
1896 		free(buf2);
1897 		return NS_NOTFOUND;
1898 	}
1899 	ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1900 	if (ai) {
1901 		cur->ai_next = ai;
1902 		while (cur && cur->ai_next)
1903 			cur = cur->ai_next;
1904 	}
1905 	if (q.next) {
1906 		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1907 		if (ai)
1908 			cur->ai_next = ai;
1909 	}
1910 	free(buf);
1911 	free(buf2);
1912 	if (sentinel.ai_next == NULL)
1913 		switch (h_errno) {
1914 		case HOST_NOT_FOUND:
1915 			return NS_NOTFOUND;
1916 		case TRY_AGAIN:
1917 			return NS_TRYAGAIN;
1918 		default:
1919 			return NS_UNAVAIL;
1920 		}
1921 	*((struct addrinfo **)rv) = sentinel.ai_next;
1922 	return NS_SUCCESS;
1923 }
1924 
1925 static void
1926 _sethtent()
1927 {
1928 	if (!hostf)
1929 		hostf = fopen(_PATH_HOSTS, "r" );
1930 	else
1931 		rewind(hostf);
1932 }
1933 
1934 static void
1935 _endhtent()
1936 {
1937 	if (hostf) {
1938 		(void) fclose(hostf);
1939 		hostf = NULL;
1940 	}
1941 }
1942 
1943 static struct addrinfo *
1944 _gethtent(name, pai)
1945 	const char *name;
1946 	const struct addrinfo *pai;
1947 {
1948 	char *p;
1949 	char *cp, *tname, *cname;
1950 	struct addrinfo hints, *res0, *res;
1951 	int error;
1952 	const char *addr;
1953 	char hostbuf[8*1024];
1954 
1955 	if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" )))
1956 		return (NULL);
1957 again:
1958 	if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
1959 		return (NULL);
1960 	if (*p == '#')
1961 		goto again;
1962 	if (!(cp = strpbrk(p, "#\n")))
1963 		goto again;
1964 	*cp = '\0';
1965 	if (!(cp = strpbrk(p, " \t")))
1966 		goto again;
1967 	*cp++ = '\0';
1968 	addr = p;
1969 	cname = NULL;
1970 	/* if this is not something we're looking for, skip it. */
1971 	while (cp && *cp) {
1972 		if (*cp == ' ' || *cp == '\t') {
1973 			cp++;
1974 			continue;
1975 		}
1976 		tname = cp;
1977 		if (cname == NULL)
1978 			cname = cp;
1979 		if ((cp = strpbrk(cp, " \t")) != NULL)
1980 			*cp++ = '\0';
1981 		if (strcasecmp(name, tname) == 0)
1982 			goto found;
1983 	}
1984 	goto again;
1985 
1986 found:
1987 	/* we should not glob socktype/protocol here */
1988 	memset(&hints, 0, sizeof(hints));
1989 	hints.ai_family = pai->ai_family;
1990 	hints.ai_socktype = SOCK_DGRAM;
1991 	hints.ai_protocol = 0;
1992 	hints.ai_flags = AI_NUMERICHOST;
1993 	error = getaddrinfo(addr, "0", &hints, &res0);
1994 	if (error)
1995 		goto again;
1996 #ifdef FILTER_V4MAPPED
1997 	/* XXX should check all items in the chain */
1998 	if (res0->ai_family == AF_INET6 &&
1999 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2000 		freeaddrinfo(res0);
2001 		goto again;
2002 	}
2003 #endif
2004 	for (res = res0; res; res = res->ai_next) {
2005 		/* cover it up */
2006 		res->ai_flags = pai->ai_flags;
2007 		res->ai_socktype = pai->ai_socktype;
2008 		res->ai_protocol = pai->ai_protocol;
2009 
2010 		if (pai->ai_flags & AI_CANONNAME) {
2011 			if (get_canonname(pai, res, cname) != 0) {
2012 				freeaddrinfo(res0);
2013 				goto again;
2014 			}
2015 		}
2016 	}
2017 	return res0;
2018 }
2019 
2020 /*ARGSUSED*/
2021 static int
2022 _files_getaddrinfo(rv, cb_data, ap)
2023 	void	*rv;
2024 	void	*cb_data;
2025 	va_list	 ap;
2026 {
2027 	const char *name;
2028 	const struct addrinfo *pai;
2029 	struct addrinfo sentinel, *cur;
2030 	struct addrinfo *p;
2031 
2032 	name = va_arg(ap, char *);
2033 	pai = va_arg(ap, struct addrinfo *);
2034 
2035 	memset(&sentinel, 0, sizeof(sentinel));
2036 	cur = &sentinel;
2037 
2038 	THREAD_LOCK();
2039 	_sethtent();
2040 	while ((p = _gethtent(name, pai)) != NULL) {
2041 		cur->ai_next = p;
2042 		while (cur && cur->ai_next)
2043 			cur = cur->ai_next;
2044 	}
2045 	_endhtent();
2046 	THREAD_UNLOCK();
2047 
2048 	*((struct addrinfo **)rv) = sentinel.ai_next;
2049 	if (sentinel.ai_next == NULL)
2050 		return NS_NOTFOUND;
2051 	return NS_SUCCESS;
2052 }
2053 
2054 #ifdef YP
2055 static char *__ypdomain;
2056 
2057 /*ARGSUSED*/
2058 static struct addrinfo *
2059 _yphostent(line, pai)
2060 	char *line;
2061 	const struct addrinfo *pai;
2062 {
2063 	struct addrinfo sentinel, *cur;
2064 	struct addrinfo hints, *res, *res0;
2065 	int error;
2066 	char *p = line;
2067 	const char *addr, *canonname;
2068 	char *nextline;
2069 	char *cp;
2070 
2071 	addr = canonname = NULL;
2072 
2073 	memset(&sentinel, 0, sizeof(sentinel));
2074 	cur = &sentinel;
2075 
2076 nextline:
2077 	/* terminate line */
2078 	cp = strchr(p, '\n');
2079 	if (cp) {
2080 		*cp++ = '\0';
2081 		nextline = cp;
2082 	} else
2083 		nextline = NULL;
2084 
2085 	cp = strpbrk(p, " \t");
2086 	if (cp == NULL) {
2087 		if (canonname == NULL)
2088 			return (NULL);
2089 		else
2090 			goto done;
2091 	}
2092 	*cp++ = '\0';
2093 
2094 	addr = p;
2095 
2096 	while (cp && *cp) {
2097 		if (*cp == ' ' || *cp == '\t') {
2098 			cp++;
2099 			continue;
2100 		}
2101 		if (!canonname)
2102 			canonname = cp;
2103 		if ((cp = strpbrk(cp, " \t")) != NULL)
2104 			*cp++ = '\0';
2105 	}
2106 
2107 	hints = *pai;
2108 	hints.ai_flags = AI_NUMERICHOST;
2109 	error = getaddrinfo(addr, NULL, &hints, &res0);
2110 	if (error == 0) {
2111 		for (res = res0; res; res = res->ai_next) {
2112 			/* cover it up */
2113 			res->ai_flags = pai->ai_flags;
2114 
2115 			if (pai->ai_flags & AI_CANONNAME)
2116 				(void)get_canonname(pai, res, canonname);
2117 		}
2118 	} else
2119 		res0 = NULL;
2120 	if (res0) {
2121 		cur->ai_next = res0;
2122 		while (cur && cur->ai_next)
2123 			cur = cur->ai_next;
2124 	}
2125 
2126 	if (nextline) {
2127 		p = nextline;
2128 		goto nextline;
2129 	}
2130 
2131 done:
2132 	return sentinel.ai_next;
2133 }
2134 
2135 /*ARGSUSED*/
2136 static int
2137 _yp_getaddrinfo(rv, cb_data, ap)
2138 	void	*rv;
2139 	void	*cb_data;
2140 	va_list	 ap;
2141 {
2142 	struct addrinfo sentinel, *cur;
2143 	struct addrinfo *ai = NULL;
2144 	static char *__ypcurrent;
2145 	int __ypcurrentlen, r;
2146 	const char *name;
2147 	const struct addrinfo *pai;
2148 
2149 	name = va_arg(ap, char *);
2150 	pai = va_arg(ap, const struct addrinfo *);
2151 
2152 	memset(&sentinel, 0, sizeof(sentinel));
2153 	cur = &sentinel;
2154 
2155 	THREAD_LOCK();
2156 	if (!__ypdomain) {
2157 		if (_yp_check(&__ypdomain) == 0) {
2158 			THREAD_UNLOCK();
2159 			return NS_UNAVAIL;
2160 		}
2161 	}
2162 	if (__ypcurrent)
2163 		free(__ypcurrent);
2164 	__ypcurrent = NULL;
2165 
2166 	/* hosts.byname is only for IPv4 (Solaris8) */
2167 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
2168 		r = yp_match(__ypdomain, "hosts.byname", name,
2169 			(int)strlen(name), &__ypcurrent, &__ypcurrentlen);
2170 		if (r == 0) {
2171 			struct addrinfo ai4;
2172 
2173 			ai4 = *pai;
2174 			ai4.ai_family = AF_INET;
2175 			ai = _yphostent(__ypcurrent, &ai4);
2176 			if (ai) {
2177 				cur->ai_next = ai;
2178 				while (cur && cur->ai_next)
2179 					cur = cur->ai_next;
2180 			}
2181 		}
2182 	}
2183 
2184 	/* ipnodes.byname can hold both IPv4/v6 */
2185 	r = yp_match(__ypdomain, "ipnodes.byname", name,
2186 		(int)strlen(name), &__ypcurrent, &__ypcurrentlen);
2187 	if (r == 0) {
2188 		ai = _yphostent(__ypcurrent, pai);
2189 		if (ai) {
2190 			cur->ai_next = ai;
2191 			while (cur && cur->ai_next)
2192 				cur = cur->ai_next;
2193 		}
2194 	}
2195 	THREAD_UNLOCK();
2196 
2197 	if (sentinel.ai_next == NULL) {
2198 		h_errno = HOST_NOT_FOUND;
2199 		return NS_NOTFOUND;
2200 	}
2201 	*((struct addrinfo **)rv) = sentinel.ai_next;
2202 	return NS_SUCCESS;
2203 }
2204 #endif
2205 
2206 /* resolver logic */
2207 
2208 extern const char *__hostalias(const char *);
2209 
2210 /*
2211  * Formulate a normal query, send, and await answer.
2212  * Returned answer is placed in supplied buffer "answer".
2213  * Perform preliminary check of answer, returning success only
2214  * if no error is indicated and the answer count is nonzero.
2215  * Return the size of the response on success, -1 on error.
2216  * Error number is left in h_errno.
2217  *
2218  * Caller must parse answer and determine whether it answers the question.
2219  */
2220 static int
2221 res_queryN(name, target)
2222 	const char *name;	/* domain name */
2223 	struct res_target *target;
2224 {
2225 	u_char *buf;
2226 	HEADER *hp;
2227 	int n;
2228 	struct res_target *t;
2229 	int rcode;
2230 	int ancount;
2231 
2232 	rcode = NOERROR;
2233 	ancount = 0;
2234 
2235 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
2236 		h_errno = NETDB_INTERNAL;
2237 		return (-1);
2238 	}
2239 
2240 	buf = malloc(MAXPACKET);
2241 	if (!buf) {
2242 		h_errno = NETDB_INTERNAL;
2243 		return -1;
2244 	}
2245 
2246 	for (t = target; t; t = t->next) {
2247 		int class, type;
2248 		u_char *answer;
2249 		int anslen;
2250 
2251 		hp = (HEADER *)(void *)t->answer;
2252 		hp->rcode = NOERROR;	/* default */
2253 
2254 		/* make it easier... */
2255 		class = t->qclass;
2256 		type = t->qtype;
2257 		answer = t->answer;
2258 		anslen = t->anslen;
2259 #ifdef DEBUG
2260 		if (_res.options & RES_DEBUG)
2261 			printf(";; res_query(%s, %d, %d)\n", name, class, type);
2262 #endif
2263 
2264 		n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
2265 		    buf, MAXPACKET);
2266 		if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
2267 			n = res_opt(n, buf, MAXPACKET, anslen);
2268 		if (n <= 0) {
2269 #ifdef DEBUG
2270 			if (_res.options & RES_DEBUG)
2271 				printf(";; res_query: mkquery failed\n");
2272 #endif
2273 			free(buf);
2274 			h_errno = NO_RECOVERY;
2275 			return (n);
2276 		}
2277 		n = res_send(buf, n, answer, anslen);
2278 #if 0
2279 		if (n < 0) {
2280 #ifdef DEBUG
2281 			if (_res.options & RES_DEBUG)
2282 				printf(";; res_query: send error\n");
2283 #endif
2284 			free(buf);
2285 			h_errno = TRY_AGAIN;
2286 			return (n);
2287 		}
2288 #endif
2289 
2290 		if (n < 0 || n > anslen)
2291 			hp->rcode = FORMERR; /* XXX not very informative */
2292 		if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2293 			rcode = hp->rcode;	/* record most recent error */
2294 #ifdef DEBUG
2295 			if (_res.options & RES_DEBUG)
2296 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2297 				    ntohs(hp->ancount));
2298 #endif
2299 			continue;
2300 		}
2301 
2302 		ancount += ntohs(hp->ancount);
2303 
2304 		t->n = n;
2305 	}
2306 
2307 	free(buf);
2308 
2309 	if (ancount == 0) {
2310 		switch (rcode) {
2311 		case NXDOMAIN:
2312 			h_errno = HOST_NOT_FOUND;
2313 			break;
2314 		case SERVFAIL:
2315 			h_errno = TRY_AGAIN;
2316 			break;
2317 		case NOERROR:
2318 			h_errno = NO_DATA;
2319 			break;
2320 		case FORMERR:
2321 		case NOTIMP:
2322 		case REFUSED:
2323 		default:
2324 			h_errno = NO_RECOVERY;
2325 			break;
2326 		}
2327 		return (-1);
2328 	}
2329 	return (ancount);
2330 }
2331 
2332 /*
2333  * Formulate a normal query, send, and retrieve answer in supplied buffer.
2334  * Return the size of the response on success, -1 on error.
2335  * If enabled, implement search rules until answer or unrecoverable failure
2336  * is detected.  Error code, if any, is left in h_errno.
2337  */
2338 static int
2339 res_searchN(name, target)
2340 	const char *name;	/* domain name */
2341 	struct res_target *target;
2342 {
2343 	const char *cp, * const *domain;
2344 	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
2345 	u_int dots;
2346 	int trailing_dot, ret, saved_herrno;
2347 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2348 
2349 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
2350 		h_errno = NETDB_INTERNAL;
2351 		return (-1);
2352 	}
2353 
2354 	errno = 0;
2355 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
2356 	dots = 0;
2357 	for (cp = name; *cp; cp++)
2358 		dots += (*cp == '.');
2359 	trailing_dot = 0;
2360 	if (cp > name && *--cp == '.')
2361 		trailing_dot++;
2362 
2363 	/*
2364 	 * if there aren't any dots, it could be a user-level alias
2365 	 */
2366 	if (!dots && (cp = __hostalias(name)) != NULL)
2367 		return (res_queryN(cp, target));
2368 
2369 	/*
2370 	 * If there are dots in the name already, let's just give it a try
2371 	 * 'as is'.  The threshold can be set with the "ndots" option.
2372 	 */
2373 	saved_herrno = -1;
2374 	if (dots >= _res.ndots) {
2375 		ret = res_querydomainN(name, NULL, target);
2376 		if (ret > 0)
2377 			return (ret);
2378 		saved_herrno = h_errno;
2379 		tried_as_is++;
2380 	}
2381 
2382 	/*
2383 	 * We do at least one level of search if
2384 	 *	- there is no dot and RES_DEFNAME is set, or
2385 	 *	- there is at least one dot, there is no trailing dot,
2386 	 *	  and RES_DNSRCH is set.
2387 	 */
2388 	if ((!dots && (_res.options & RES_DEFNAMES)) ||
2389 	    (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
2390 		int done = 0;
2391 
2392 		for (domain = (const char * const *)_res.dnsrch;
2393 		   *domain && !done;
2394 		   domain++) {
2395 
2396 			ret = res_querydomainN(name, *domain, target);
2397 			if (ret > 0)
2398 				return (ret);
2399 
2400 			/*
2401 			 * If no server present, give up.
2402 			 * If name isn't found in this domain,
2403 			 * keep trying higher domains in the search list
2404 			 * (if that's enabled).
2405 			 * On a NO_DATA error, keep trying, otherwise
2406 			 * a wildcard entry of another type could keep us
2407 			 * from finding this entry higher in the domain.
2408 			 * If we get some other error (negative answer or
2409 			 * server failure), then stop searching up,
2410 			 * but try the input name below in case it's
2411 			 * fully-qualified.
2412 			 */
2413 			if (errno == ECONNREFUSED) {
2414 				h_errno = TRY_AGAIN;
2415 				return (-1);
2416 			}
2417 
2418 			switch (h_errno) {
2419 			case NO_DATA:
2420 				got_nodata++;
2421 				/* FALLTHROUGH */
2422 			case HOST_NOT_FOUND:
2423 				/* keep trying */
2424 				break;
2425 			case TRY_AGAIN:
2426 				if (hp->rcode == SERVFAIL) {
2427 					/* try next search element, if any */
2428 					got_servfail++;
2429 					break;
2430 				}
2431 				/* FALLTHROUGH */
2432 			default:
2433 				/* anything else implies that we're done */
2434 				done++;
2435 			}
2436 			/*
2437 			 * if we got here for some reason other than DNSRCH,
2438 			 * we only wanted one iteration of the loop, so stop.
2439 			 */
2440 			if (!(_res.options & RES_DNSRCH))
2441 			        done++;
2442 		}
2443 	}
2444 
2445 	/*
2446 	 * if we have not already tried the name "as is", do that now.
2447 	 * note that we do this regardless of how many dots were in the
2448 	 * name or whether it ends with a dot.
2449 	 */
2450 	if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
2451 		ret = res_querydomainN(name, NULL, target);
2452 		if (ret > 0)
2453 			return (ret);
2454 	}
2455 
2456 	/*
2457 	 * if we got here, we didn't satisfy the search.
2458 	 * if we did an initial full query, return that query's h_errno
2459 	 * (note that we wouldn't be here if that query had succeeded).
2460 	 * else if we ever got a nodata, send that back as the reason.
2461 	 * else send back meaningless h_errno, that being the one from
2462 	 * the last DNSRCH we did.
2463 	 */
2464 	if (saved_herrno != -1)
2465 		h_errno = saved_herrno;
2466 	else if (got_nodata)
2467 		h_errno = NO_DATA;
2468 	else if (got_servfail)
2469 		h_errno = TRY_AGAIN;
2470 	return (-1);
2471 }
2472 
2473 /*
2474  * Perform a call on res_query on the concatenation of name and domain,
2475  * removing a trailing dot from name if domain is NULL.
2476  */
2477 static int
2478 res_querydomainN(name, domain, target)
2479 	const char *name, *domain;
2480 	struct res_target *target;
2481 {
2482 	char nbuf[MAXDNAME];
2483 	const char *longname = nbuf;
2484 	size_t n, d;
2485 
2486 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
2487 		h_errno = NETDB_INTERNAL;
2488 		return (-1);
2489 	}
2490 #ifdef DEBUG
2491 	if (_res.options & RES_DEBUG)
2492 		printf(";; res_querydomain(%s, %s)\n",
2493 			name, domain?domain:"<Nil>");
2494 #endif
2495 	if (domain == NULL) {
2496 		/*
2497 		 * Check for trailing '.';
2498 		 * copy without '.' if present.
2499 		 */
2500 		n = strlen(name);
2501 		if (n >= MAXDNAME) {
2502 			h_errno = NO_RECOVERY;
2503 			return (-1);
2504 		}
2505 		if (n > 0 && name[--n] == '.') {
2506 			strncpy(nbuf, name, n);
2507 			nbuf[n] = '\0';
2508 		} else
2509 			longname = name;
2510 	} else {
2511 		n = strlen(name);
2512 		d = strlen(domain);
2513 		if (n + d + 1 >= MAXDNAME) {
2514 			h_errno = NO_RECOVERY;
2515 			return (-1);
2516 		}
2517 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2518 	}
2519 	return (res_queryN(longname, target));
2520 }
2521