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