getaddrinfo.c revision 160593
1121474Sume/*	$KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $	*/
262614Sitojun
355163Sshin/*
455163Sshin * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
555163Sshin * All rights reserved.
655163Sshin *
755163Sshin * Redistribution and use in source and binary forms, with or without
855163Sshin * modification, are permitted provided that the following conditions
955163Sshin * are met:
1055163Sshin * 1. Redistributions of source code must retain the above copyright
1155163Sshin *    notice, this list of conditions and the following disclaimer.
1255163Sshin * 2. Redistributions in binary form must reproduce the above copyright
1355163Sshin *    notice, this list of conditions and the following disclaimer in the
1455163Sshin *    documentation and/or other materials provided with the distribution.
1555163Sshin * 3. Neither the name of the project nor the names of its contributors
1655163Sshin *    may be used to endorse or promote products derived from this software
1755163Sshin *    without specific prior written permission.
1855163Sshin *
1955163Sshin * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
2055163Sshin * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2155163Sshin * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2255163Sshin * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
2355163Sshin * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2455163Sshin * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2555163Sshin * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2655163Sshin * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2755163Sshin * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2855163Sshin * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2955163Sshin * SUCH DAMAGE.
3055163Sshin */
3155163Sshin
3255163Sshin/*
3355163Sshin * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
3455163Sshin *
3555163Sshin * Issues to be discussed:
3655163Sshin * - Return values.  There are nonstandard return values defined and used
3755163Sshin *   in the source code.  This is because RFC2553 is silent about which error
3855163Sshin *   code must be returned for which situation.
3961877Sume * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
40105940Sume *   invalid.  current code - SEGV on freeaddrinfo(NULL)
41105940Sume *
4256627Sshin * Note:
4356627Sshin * - The code filters out AFs that are not supported by the kernel,
4456627Sshin *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
4556627Sshin *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
4656627Sshin *   in ai_flags?
4761877Sume * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
4861877Sume *   (1) what should we do against numeric hostname (2) what should we do
4961877Sume *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
5061877Sume *   non-loopback address configured?  global address configured?
51105940Sume *
52105940Sume * OS specific notes for freebsd4:
53105940Sume * - FreeBSD supported $GAI.  The code does not.
5455163Sshin */
5555163Sshin
5692986Sobrien#include <sys/cdefs.h>
5792986Sobrien__FBSDID("$FreeBSD: head/lib/libc/net/getaddrinfo.c 160593 2006-07-23 15:31:03Z ume $");
5892986Sobrien
5971579Sdeischen#include "namespace.h"
6055163Sshin#include <sys/types.h>
6155163Sshin#include <sys/param.h>
6255163Sshin#include <sys/socket.h>
6355163Sshin#include <net/if.h>
6455163Sshin#include <netinet/in.h>
65121747Sume#include <sys/queue.h>
66121747Sume#ifdef INET6
67121747Sume#include <net/if_var.h>
68121747Sume#include <sys/sysctl.h>
69129901Sume#include <sys/ioctl.h>
70121747Sume#include <netinet6/in6_var.h>	/* XXX */
71121747Sume#endif
7255163Sshin#include <arpa/inet.h>
7355163Sshin#include <arpa/nameser.h>
74121474Sume#include <rpc/rpc.h>
75121474Sume#include <rpcsvc/yp_prot.h>
76121474Sume#include <rpcsvc/ypclnt.h>
7755163Sshin#include <netdb.h>
7855163Sshin#include <resolv.h>
7955163Sshin#include <string.h>
8055163Sshin#include <stdlib.h>
8155163Sshin#include <stddef.h>
8255163Sshin#include <ctype.h>
8355163Sshin#include <unistd.h>
8455163Sshin#include <stdio.h>
8561877Sume#include <errno.h>
86102237Spirzyk
87102237Spirzyk#include "res_config.h"
88102237Spirzyk
8978012Sume#ifdef DEBUG
9078012Sume#include <syslog.h>
9178012Sume#endif
9255163Sshin
9365532Snectar#include <stdarg.h>
9465532Snectar#include <nsswitch.h>
9571579Sdeischen#include "un-namespace.h"
96111618Snectar#include "libc_private.h"
97158115Sume#ifdef NS_CACHING
98158115Sume#include "nscache.h"
99158115Sume#endif
10065532Snectar
10155163Sshin#if defined(__KAME__) && defined(INET6)
10255163Sshin# define FAITH
10355163Sshin#endif
10455163Sshin
105105940Sume#define SUCCESS 0
106105940Sume#define ANY 0
107105940Sume#define YES 1
108105940Sume#define NO  0
10955163Sshin
11055163Sshinstatic const char in_addrany[] = { 0, 0, 0, 0 };
111105940Sumestatic const char in_loopback[] = { 127, 0, 0, 1 };
112105940Sume#ifdef INET6
11355163Sshinstatic const char in6_addrany[] = {
11455163Sshin	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
11555163Sshin};
11655163Sshinstatic const char in6_loopback[] = {
11755163Sshin	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
11855163Sshin};
119105940Sume#endif
12055163Sshin
121121747Sumestruct policyqueue {
122121747Sume	TAILQ_ENTRY(policyqueue) pc_entry;
123121747Sume#ifdef INET6
124121747Sume	struct in6_addrpolicy pc_policy;
125121747Sume#endif
126121747Sume};
127121747SumeTAILQ_HEAD(policyhead, policyqueue);
128121747Sume
12955163Sshinstatic const struct afd {
13055163Sshin	int a_af;
13155163Sshin	int a_addrlen;
132146244Sume	socklen_t a_socklen;
13355163Sshin	int a_off;
13455163Sshin	const char *a_addrany;
13573665Sobrien	const char *a_loopback;
13655163Sshin	int a_scoped;
13755163Sshin} afdl [] = {
13855163Sshin#ifdef INET6
13955163Sshin#define	N_INET6 0
14055163Sshin	{PF_INET6, sizeof(struct in6_addr),
14155163Sshin	 sizeof(struct sockaddr_in6),
14255163Sshin	 offsetof(struct sockaddr_in6, sin6_addr),
14355163Sshin	 in6_addrany, in6_loopback, 1},
14455163Sshin#define	N_INET 1
14555163Sshin#else
14655163Sshin#define	N_INET 0
14755163Sshin#endif
14855163Sshin	{PF_INET, sizeof(struct in_addr),
14955163Sshin	 sizeof(struct sockaddr_in),
15055163Sshin	 offsetof(struct sockaddr_in, sin_addr),
15155163Sshin	 in_addrany, in_loopback, 0},
15255163Sshin	{0, 0, 0, 0, NULL, NULL, 0},
15355163Sshin};
15455163Sshin
15555163Sshinstruct explore {
15661877Sume	int e_af;
15755163Sshin	int e_socktype;
15855163Sshin	int e_protocol;
15955163Sshin	const char *e_protostr;
16055163Sshin	int e_wild;
161105940Sume#define WILD_AF(ex)		((ex)->e_wild & 0x01)
162105940Sume#define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
163105940Sume#define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
16455163Sshin};
16555163Sshin
16655163Sshinstatic const struct explore explore[] = {
16761877Sume#if 0
168121474Sume	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
16961877Sume#endif
17061877Sume#ifdef INET6
171121474Sume	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
172121474Sume	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
173121474Sume	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
17461877Sume#endif
175121474Sume	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
176121474Sume	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
177121474Sume	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
178121474Sume	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
179121474Sume	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
180121474Sume	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
18161877Sume	{ -1, 0, 0, NULL, 0 },
18255163Sshin};
18355163Sshin
18455163Sshin#ifdef INET6
185105940Sume#define PTON_MAX	16
18655163Sshin#else
187105940Sume#define PTON_MAX	4
18855163Sshin#endif
18955163Sshin
190121747Sume#define AIO_SRCFLAG_DEPRECATED	0x1
191121747Sume
192121747Sumestruct ai_order {
193121747Sume	union {
194121747Sume		struct sockaddr_storage aiou_ss;
195121747Sume		struct sockaddr aiou_sa;
196121747Sume	} aio_src_un;
197121747Sume#define aio_srcsa aio_src_un.aiou_sa
198121747Sume	u_int32_t aio_srcflag;
199121747Sume	int aio_srcscope;
200121747Sume	int aio_dstscope;
201121747Sume	struct policyqueue *aio_srcpolicy;
202121747Sume	struct policyqueue *aio_dstpolicy;
203121747Sume	struct addrinfo *aio_ai;
204121747Sume	int aio_matchlen;
205121747Sume};
206121747Sume
20765532Snectarstatic const ns_src default_dns_files[] = {
20865532Snectar	{ NSSRC_FILES, 	NS_SUCCESS },
20965532Snectar	{ NSSRC_DNS, 	NS_SUCCESS },
21065532Snectar	{ 0 }
21165532Snectar};
21265532Snectar
21361877Sumestruct res_target {
21461877Sume	struct res_target *next;
21561877Sume	const char *name;	/* domain name */
21662614Sitojun	int qclass, qtype;	/* class and type of query */
21761877Sume	u_char *answer;		/* buffer to put answer */
21861877Sume	int anslen;		/* size of answer buffer */
21961877Sume	int n;			/* result length */
22061877Sume};
22161877Sume
222121426Sume#define MAXPACKET	(64*1024)
223121426Sume
224121426Sumetypedef union {
225121426Sume	HEADER hdr;
226121426Sume	u_char buf[MAXPACKET];
227121426Sume} querybuf;
228121426Sume
229160593Sumestatic int str2number(const char *, int *);
23092941Sobrienstatic int explore_null(const struct addrinfo *,
23192941Sobrien	const char *, struct addrinfo **);
23292941Sobrienstatic int explore_numeric(const struct addrinfo *, const char *,
233140906Sume	const char *, struct addrinfo **, const char *);
23492941Sobrienstatic int explore_numeric_scope(const struct addrinfo *, const char *,
23592941Sobrien	const char *, struct addrinfo **);
23692941Sobrienstatic int get_canonname(const struct addrinfo *,
23792941Sobrien	struct addrinfo *, const char *);
23892941Sobrienstatic struct addrinfo *get_ai(const struct addrinfo *,
23992941Sobrien	const struct afd *, const char *);
24092905Sobrienstatic int get_portmatch(const struct addrinfo *, const char *);
24192905Sobrienstatic int get_port(struct addrinfo *, const char *, int);
24292905Sobrienstatic const struct afd *find_afd(int);
243121474Sumestatic int addrconfig(struct addrinfo *);
244129901Sumestatic void set_source(struct ai_order *, struct policyhead *);
245121747Sumestatic int comp_dst(const void *, const void *);
24661877Sume#ifdef INET6
247105943Sumestatic int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
24861877Sume#endif
249121747Sumestatic int gai_addr2scopetype(struct sockaddr *);
25055163Sshin
251121426Sumestatic int explore_fqdn(const struct addrinfo *, const char *,
252121426Sume	const char *, struct addrinfo **);
253121426Sume
254121747Sumestatic int reorder(struct addrinfo *);
255121747Sumestatic int get_addrselectpolicy(struct policyhead *);
256121747Sumestatic void free_addrselectpolicy(struct policyhead *);
257121747Sumestatic struct policyqueue *match_addrselectpolicy(struct sockaddr *,
258121747Sume	struct policyhead *);
259129901Sumestatic int matchlen(struct sockaddr *, struct sockaddr *);
260121747Sume
26192941Sobrienstatic struct addrinfo *getanswer(const querybuf *, int, const char *, int,
262156960Sume	const struct addrinfo *, res_state);
263121426Sume#if defined(RESOLVSORT)
264156960Sumestatic int addr4sort(struct addrinfo *, res_state);
265121426Sume#endif
266105943Sumestatic int _dns_getaddrinfo(void *, void *, va_list);
267144634Sumestatic void _sethtent(FILE **);
268144634Sumestatic void _endhtent(FILE **);
269144634Sumestatic struct addrinfo *_gethtent(FILE **, const char *,
270144634Sume	const struct addrinfo *);
27192905Sobrienstatic int _files_getaddrinfo(void *, void *, va_list);
27261877Sume#ifdef YP
27392905Sobrienstatic struct addrinfo *_yphostent(char *, const struct addrinfo *);
27492905Sobrienstatic int _yp_getaddrinfo(void *, void *, va_list);
27561877Sume#endif
276158115Sume#ifdef NS_CACHING
277158115Sumestatic int addrinfo_id_func(char *, size_t *, va_list, void *);
278158115Sumestatic int addrinfo_marshal_func(char *, size_t *, void *, va_list, void *);
279158115Sumestatic int addrinfo_unmarshal_func(char *, size_t, void *, va_list, void *);
280158115Sume#endif
28161877Sume
282156960Sumestatic int res_queryN(const char *, struct res_target *, res_state);
283156960Sumestatic int res_searchN(const char *, struct res_target *, res_state);
28492941Sobrienstatic int res_querydomainN(const char *, const char *,
285156960Sume	struct res_target *, res_state);
28661877Sume
28755163Sshin/* XXX macros that make external reference is BAD. */
28855163Sshin
289105940Sume#define GET_AI(ai, afd, addr) \
29055163Sshindo { \
29155163Sshin	/* external reference: pai, error, and label free */ \
29255163Sshin	(ai) = get_ai(pai, (afd), (addr)); \
29355163Sshin	if ((ai) == NULL) { \
29455163Sshin		error = EAI_MEMORY; \
29555163Sshin		goto free; \
29655163Sshin	} \
29761877Sume} while (/*CONSTCOND*/0)
29855163Sshin
299105940Sume#define GET_PORT(ai, serv) \
30055163Sshindo { \
30155163Sshin	/* external reference: error and label free */ \
30255163Sshin	error = get_port((ai), (serv), 0); \
30355163Sshin	if (error != 0) \
30455163Sshin		goto free; \
30561877Sume} while (/*CONSTCOND*/0)
30655163Sshin
307105940Sume#define GET_CANONNAME(ai, str) \
30855163Sshindo { \
30955163Sshin	/* external reference: pai, error and label free */ \
31055163Sshin	error = get_canonname(pai, (ai), (str)); \
31155163Sshin	if (error != 0) \
31255163Sshin		goto free; \
31361877Sume} while (/*CONSTCOND*/0)
31455163Sshin
315105940Sume#define ERR(err) \
31655163Sshindo { \
31755163Sshin	/* external reference: error, and label bad */ \
31855163Sshin	error = (err); \
31955163Sshin	goto bad; \
32061877Sume	/*NOTREACHED*/ \
32161877Sume} while (/*CONSTCOND*/0)
32255163Sshin
323105940Sume#define MATCH_FAMILY(x, y, w) \
32461877Sume	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
325105940Sume#define MATCH(x, y, w) \
32661877Sume	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
32755163Sshin
32855163Sshinvoid
329157119Sumefreeaddrinfo(struct addrinfo *ai)
33055163Sshin{
33155163Sshin	struct addrinfo *next;
33255163Sshin
33355163Sshin	do {
33455163Sshin		next = ai->ai_next;
33555163Sshin		if (ai->ai_canonname)
33655163Sshin			free(ai->ai_canonname);
33755163Sshin		/* no need to free(ai->ai_addr) */
33855163Sshin		free(ai);
33961877Sume		ai = next;
34061877Sume	} while (ai);
34155163Sshin}
34255163Sshin
34355163Sshinstatic int
344160593Sumestr2number(const char *p, int *portp)
34555163Sshin{
34662836Sitojun	char *ep;
347140908Sume	unsigned long v;
34862836Sitojun
34962836Sitojun	if (*p == '\0')
350140908Sume		return -1;
35162836Sitojun	ep = NULL;
352105943Sume	errno = 0;
353140908Sume	v = strtoul(p, &ep, 10);
354160593Sume	if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX) {
355160593Sume		*portp = v;
356160593Sume		return 0;
357160593Sume	} else
358140908Sume		return -1;
35955163Sshin}
36055163Sshin
36155163Sshinint
362157119Sumegetaddrinfo(const char *hostname, const char *servname,
363157119Sume    const struct addrinfo *hints, struct addrinfo **res)
36455163Sshin{
36555163Sshin	struct addrinfo sentinel;
36655163Sshin	struct addrinfo *cur;
36755163Sshin	int error = 0;
368121474Sume	struct addrinfo ai;
369121474Sume	struct addrinfo ai0;
37055163Sshin	struct addrinfo *pai;
37155163Sshin	const struct explore *ex;
372121747Sume	int numeric = 0;
37355163Sshin
37461877Sume	memset(&sentinel, 0, sizeof(sentinel));
37555163Sshin	cur = &sentinel;
37655163Sshin	pai = &ai;
37755163Sshin	pai->ai_flags = 0;
37855163Sshin	pai->ai_family = PF_UNSPEC;
37955163Sshin	pai->ai_socktype = ANY;
38055163Sshin	pai->ai_protocol = ANY;
38155163Sshin	pai->ai_addrlen = 0;
38255163Sshin	pai->ai_canonname = NULL;
38355163Sshin	pai->ai_addr = NULL;
38455163Sshin	pai->ai_next = NULL;
38555163Sshin
38655163Sshin	if (hostname == NULL && servname == NULL)
38755163Sshin		return EAI_NONAME;
38855163Sshin	if (hints) {
38955163Sshin		/* error check for hints */
39055163Sshin		if (hints->ai_addrlen || hints->ai_canonname ||
39155163Sshin		    hints->ai_addr || hints->ai_next)
39255163Sshin			ERR(EAI_BADHINTS); /* xxx */
39355163Sshin		if (hints->ai_flags & ~AI_MASK)
39455163Sshin			ERR(EAI_BADFLAGS);
39555163Sshin		switch (hints->ai_family) {
39655163Sshin		case PF_UNSPEC:
39755163Sshin		case PF_INET:
39855163Sshin#ifdef INET6
39955163Sshin		case PF_INET6:
40055163Sshin#endif
40155163Sshin			break;
40255163Sshin		default:
40355163Sshin			ERR(EAI_FAMILY);
40455163Sshin		}
40555163Sshin		memcpy(pai, hints, sizeof(*pai));
40655163Sshin
40755163Sshin		/*
40855163Sshin		 * if both socktype/protocol are specified, check if they
40955163Sshin		 * are meaningful combination.
41055163Sshin		 */
41155163Sshin		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
41261877Sume			for (ex = explore; ex->e_af >= 0; ex++) {
413121474Sume				if (pai->ai_family != ex->e_af)
41461877Sume					continue;
415121474Sume				if (ex->e_socktype == ANY)
41655163Sshin					continue;
417121474Sume				if (ex->e_protocol == ANY)
41855163Sshin					continue;
419121474Sume				if (pai->ai_socktype == ex->e_socktype &&
420121474Sume				    pai->ai_protocol != ex->e_protocol) {
421121474Sume					ERR(EAI_BADHINTS);
422121474Sume				}
42355163Sshin			}
42455163Sshin		}
42555163Sshin	}
42655163Sshin
42761877Sume	/*
42861877Sume	 * post-2553: AI_ALL and AI_V4MAPPED are effective only against
429105940Sume	 * AF_INET6 query.  They need to be ignored if specified in other
43061877Sume	 * occassions.
43161877Sume	 */
43261877Sume	switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
43361877Sume	case AI_V4MAPPED:
43461877Sume	case AI_ALL | AI_V4MAPPED:
43561877Sume		if (pai->ai_family != AF_INET6)
43661877Sume			pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
43761877Sume		break;
43861877Sume	case AI_ALL:
43961877Sume#if 1
44061877Sume		/* illegal */
44161877Sume		ERR(EAI_BADFLAGS);
44261877Sume#else
44361877Sume		pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
44461877Sume#endif
44561877Sume		break;
44661877Sume	}
44755163Sshin
44855163Sshin	/*
44961877Sume	 * check for special cases.  (1) numeric servname is disallowed if
45061877Sume	 * socktype/protocol are left unspecified. (2) servname is disallowed
45161877Sume	 * for raw and other inet{,6} sockets.
45255163Sshin	 */
45355163Sshin	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
45461877Sume#ifdef PF_INET6
455121474Sume	    || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
45655163Sshin#endif
45755163Sshin	    ) {
45861877Sume		ai0 = *pai;	/* backup *pai */
45955163Sshin
46061877Sume		if (pai->ai_family == PF_UNSPEC) {
46161877Sume#ifdef PF_INET6
46255163Sshin			pai->ai_family = PF_INET6;
46355163Sshin#else
46455163Sshin			pai->ai_family = PF_INET;
46555163Sshin#endif
46661877Sume		}
46755163Sshin		error = get_portmatch(pai, servname);
46855163Sshin		if (error)
46955163Sshin			ERR(error);
47061877Sume
47161877Sume		*pai = ai0;
47255163Sshin	}
47355163Sshin
47461877Sume	ai0 = *pai;
47561877Sume
476121474Sume	/* NULL hostname, or numeric hostname */
477121474Sume	for (ex = explore; ex->e_af >= 0; ex++) {
47855163Sshin		*pai = ai0;
47955163Sshin
480121474Sume		/* PF_UNSPEC entries are prepared for DNS queries only */
481121474Sume		if (ex->e_af == PF_UNSPEC)
48255163Sshin			continue;
48361877Sume
484121474Sume		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
485121474Sume			continue;
486121474Sume		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
487121474Sume			continue;
488121474Sume		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
489121474Sume			continue;
490121474Sume
49155163Sshin		if (pai->ai_family == PF_UNSPEC)
492121474Sume			pai->ai_family = ex->e_af;
493121474Sume		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
494121474Sume			pai->ai_socktype = ex->e_socktype;
495121474Sume		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
496121474Sume			pai->ai_protocol = ex->e_protocol;
49755163Sshin
498121474Sume		if (hostname == NULL)
499121474Sume			error = explore_null(pai, servname, &cur->ai_next);
500121474Sume		else
501140906Sume			error = explore_numeric_scope(pai, hostname, servname,
502140906Sume			    &cur->ai_next);
50355163Sshin
504121474Sume		if (error)
505121474Sume			goto free;
506121474Sume
507121474Sume		while (cur && cur->ai_next)
508121474Sume			cur = cur->ai_next;
50955163Sshin	}
51055163Sshin
511121474Sume	/*
512121474Sume	 * XXX
513121474Sume	 * If numreic representation of AF1 can be interpreted as FQDN
514121474Sume	 * representation of AF2, we need to think again about the code below.
515121474Sume	 */
516121747Sume	if (sentinel.ai_next) {
517121747Sume		numeric = 1;
518121474Sume		goto good;
519121747Sume	}
520121474Sume
521121425Sume	if (hostname == NULL)
522121425Sume		ERR(EAI_NONAME);	/* used to be EAI_NODATA */
52355163Sshin	if (pai->ai_flags & AI_NUMERICHOST)
52490053Sroam		ERR(EAI_NONAME);
52555163Sshin
526121474Sume	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
527121474Sume		ERR(EAI_FAIL);
528121474Sume
52961877Sume	/*
53061877Sume	 * hostname as alphabetical name.
531121474Sume	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
532121474Sume	 * outer loop by AFs.
53361877Sume	 */
53461877Sume	for (ex = explore; ex->e_af >= 0; ex++) {
53561877Sume		*pai = ai0;
53655163Sshin
537121474Sume		/* require exact match for family field */
538121474Sume		if (pai->ai_family != ex->e_af)
53961877Sume			continue;
54055163Sshin
541121474Sume		if (!MATCH(pai->ai_socktype, ex->e_socktype,
542121474Sume				WILD_SOCKTYPE(ex))) {
54361877Sume			continue;
544121474Sume		}
545121474Sume		if (!MATCH(pai->ai_protocol, ex->e_protocol,
546121474Sume				WILD_PROTOCOL(ex))) {
54761877Sume			continue;
548121474Sume		}
54955163Sshin
55061877Sume		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
55161877Sume			pai->ai_socktype = ex->e_socktype;
55261877Sume		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
55361877Sume			pai->ai_protocol = ex->e_protocol;
55461877Sume
555121474Sume		error = explore_fqdn(pai, hostname, servname,
556121474Sume			&cur->ai_next);
55761877Sume
55861877Sume		while (cur && cur->ai_next)
55961877Sume			cur = cur->ai_next;
56055163Sshin	}
56155163Sshin
562121747Sume	/* XXX inhibit errors if we have the result */
56361877Sume	if (sentinel.ai_next)
56461877Sume		error = 0;
56561877Sume
566121747Sumegood:
567121747Sume	/*
568121747Sume	 * ensure we return either:
569121747Sume	 * - error == 0, non-NULL *res
570121747Sume	 * - error != 0, NULL *res
571121747Sume	 */
57261877Sume	if (error == 0) {
57361877Sume		if (sentinel.ai_next) {
574121747Sume			/*
575121747Sume			 * If the returned entry is for an active connection,
576121747Sume			 * and the given name is not numeric, reorder the
577121747Sume			 * list, so that the application would try the list
578121747Sume			 * in the most efficient order.
579121747Sume			 */
580121747Sume			if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
581121747Sume				if (!numeric)
582121747Sume					(void)reorder(&sentinel);
583121747Sume			}
58461877Sume			*res = sentinel.ai_next;
585121474Sume			return SUCCESS;
58661877Sume		} else
58761877Sume			error = EAI_FAIL;
58855163Sshin	}
589121747Sumefree:
590121747Sumebad:
591121474Sume	if (sentinel.ai_next)
592121474Sume		freeaddrinfo(sentinel.ai_next);
593121474Sume	*res = NULL;
59455163Sshin	return error;
59555163Sshin}
59655163Sshin
597121747Sumestatic int
598157119Sumereorder(struct addrinfo *sentinel)
599121747Sume{
600121747Sume	struct addrinfo *ai, **aip;
601121747Sume	struct ai_order *aio;
602121747Sume	int i, n;
603121747Sume	struct policyhead policyhead;
604121747Sume
605121747Sume	/* count the number of addrinfo elements for sorting. */
606121747Sume	for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
607121747Sume		;
608121747Sume
609121747Sume	/*
610121747Sume	 * If the number is small enough, we can skip the reordering process.
611121747Sume	 */
612121747Sume	if (n <= 1)
613121747Sume		return(n);
614121747Sume
615121747Sume	/* allocate a temporary array for sort and initialization of it. */
616121747Sume	if ((aio = malloc(sizeof(*aio) * n)) == NULL)
617121747Sume		return(n);	/* give up reordering */
618121747Sume	memset(aio, 0, sizeof(*aio) * n);
619121747Sume
620121747Sume	/* retrieve address selection policy from the kernel */
621121747Sume	TAILQ_INIT(&policyhead);
622121747Sume	if (!get_addrselectpolicy(&policyhead)) {
623121747Sume		/* no policy is installed into kernel, we don't sort. */
624121747Sume		free(aio);
625121747Sume		return (n);
626121747Sume	}
627121747Sume
628121747Sume	for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
629121747Sume		aio[i].aio_ai = ai;
630121747Sume		aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
631121747Sume		aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
632121747Sume							      &policyhead);
633129901Sume		set_source(&aio[i], &policyhead);
634121747Sume	}
635121747Sume
636121747Sume	/* perform sorting. */
637121747Sume	qsort(aio, n, sizeof(*aio), comp_dst);
638121747Sume
639121747Sume	/* reorder the addrinfo chain. */
640121747Sume	for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
641121747Sume		*aip = aio[i].aio_ai;
642121747Sume		aip = &aio[i].aio_ai->ai_next;
643121747Sume	}
644121747Sume	*aip = NULL;
645121747Sume
646121747Sume	/* cleanup and return */
647121747Sume	free(aio);
648121747Sume	free_addrselectpolicy(&policyhead);
649121747Sume	return(n);
650121747Sume}
651121747Sume
652121747Sumestatic int
653157119Sumeget_addrselectpolicy(struct policyhead *head)
654121747Sume{
655121747Sume#ifdef INET6
656121747Sume	int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
657121747Sume	size_t l;
658121747Sume	char *buf;
659121747Sume	struct in6_addrpolicy *pol, *ep;
660121747Sume
661121747Sume	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0)
662121747Sume		return (0);
663121747Sume	if ((buf = malloc(l)) == NULL)
664121747Sume		return (0);
665121747Sume	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
666121747Sume		free(buf);
667121747Sume		return (0);
668121747Sume	}
669121747Sume
670121747Sume	ep = (struct in6_addrpolicy *)(buf + l);
671121747Sume	for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
672121747Sume		struct policyqueue *new;
673121747Sume
674121747Sume		if ((new = malloc(sizeof(*new))) == NULL) {
675121747Sume			free_addrselectpolicy(head); /* make the list empty */
676121747Sume			break;
677121747Sume		}
678121747Sume		new->pc_policy = *pol;
679121747Sume		TAILQ_INSERT_TAIL(head, new, pc_entry);
680121747Sume	}
681121747Sume
682121747Sume	free(buf);
683121747Sume	return (1);
684121747Sume#else
685121747Sume	return (0);
686121747Sume#endif
687121747Sume}
688121747Sume
689121747Sumestatic void
690157119Sumefree_addrselectpolicy(struct policyhead *head)
691121747Sume{
692121747Sume	struct policyqueue *ent, *nent;
693121747Sume
694121747Sume	for (ent = TAILQ_FIRST(head); ent; ent = nent) {
695121747Sume		nent = TAILQ_NEXT(ent, pc_entry);
696121747Sume		TAILQ_REMOVE(head, ent, pc_entry);
697121747Sume		free(ent);
698121747Sume	}
699121747Sume}
700121747Sume
701121747Sumestatic struct policyqueue *
702157119Sumematch_addrselectpolicy(struct sockaddr *addr, struct policyhead *head)
703121747Sume{
704121747Sume#ifdef INET6
705121747Sume	struct policyqueue *ent, *bestent = NULL;
706121747Sume	struct in6_addrpolicy *pol;
707121747Sume	int matchlen, bestmatchlen = -1;
708121747Sume	u_char *mp, *ep, *k, *p, m;
709121747Sume	struct sockaddr_in6 key;
710121747Sume
711121747Sume	switch(addr->sa_family) {
712121747Sume	case AF_INET6:
713121747Sume		key = *(struct sockaddr_in6 *)addr;
714121747Sume		break;
715121747Sume	case AF_INET:
716121747Sume		/* convert the address into IPv4-mapped IPv6 address. */
717121747Sume		memset(&key, 0, sizeof(key));
718121747Sume		key.sin6_family = AF_INET6;
719121747Sume		key.sin6_len = sizeof(key);
720121747Sume		key.sin6_addr.s6_addr[10] = 0xff;
721121747Sume		key.sin6_addr.s6_addr[11] = 0xff;
722121747Sume		memcpy(&key.sin6_addr.s6_addr[12],
723121747Sume		       &((struct sockaddr_in *)addr)->sin_addr, 4);
724121747Sume		break;
725121747Sume	default:
726121747Sume		return(NULL);
727121747Sume	}
728121747Sume
729121747Sume	for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
730121747Sume		pol = &ent->pc_policy;
731121747Sume		matchlen = 0;
732121747Sume
733121747Sume		mp = (u_char *)&pol->addrmask.sin6_addr;
734121747Sume		ep = mp + 16;	/* XXX: scope field? */
735121747Sume		k = (u_char *)&key.sin6_addr;
736121747Sume		p = (u_char *)&pol->addr.sin6_addr;
737121747Sume		for (; mp < ep && *mp; mp++, k++, p++) {
738121747Sume			m = *mp;
739121747Sume			if ((*k & m) != *p)
740121747Sume				goto next; /* not match */
741121747Sume			if (m == 0xff) /* short cut for a typical case */
742121747Sume				matchlen += 8;
743121747Sume			else {
744121747Sume				while (m >= 0x80) {
745121747Sume					matchlen++;
746121747Sume					m <<= 1;
747121747Sume				}
748121747Sume			}
749121747Sume		}
750121747Sume
751121747Sume		/* matched.  check if this is better than the current best. */
752121747Sume		if (matchlen > bestmatchlen) {
753121747Sume			bestent = ent;
754121747Sume			bestmatchlen = matchlen;
755121747Sume		}
756121747Sume
757121747Sume	  next:
758121747Sume		continue;
759121747Sume	}
760121747Sume
761121747Sume	return(bestent);
762121747Sume#else
763121747Sume	return(NULL);
764121747Sume#endif
765121747Sume
766121747Sume}
767121747Sume
768129901Sumestatic void
769157119Sumeset_source(struct ai_order *aio, struct policyhead *ph)
770129901Sume{
771129901Sume	struct addrinfo ai = *aio->aio_ai;
772129901Sume	struct sockaddr_storage ss;
773145786Sume	socklen_t srclen;
774145786Sume	int s;
775129901Sume
776129901Sume	/* set unspec ("no source is available"), just in case */
777129901Sume	aio->aio_srcsa.sa_family = AF_UNSPEC;
778129901Sume	aio->aio_srcscope = -1;
779129901Sume
780129901Sume	switch(ai.ai_family) {
781129901Sume	case AF_INET:
782129901Sume#ifdef INET6
783129901Sume	case AF_INET6:
784129901Sume#endif
785129901Sume		break;
786129901Sume	default:		/* ignore unsupported AFs explicitly */
787129901Sume		return;
788129901Sume	}
789129901Sume
790129901Sume	/* XXX: make a dummy addrinfo to call connect() */
791129901Sume	ai.ai_socktype = SOCK_DGRAM;
792129901Sume	ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
793129901Sume	ai.ai_next = NULL;
794129901Sume	memset(&ss, 0, sizeof(ss));
795129901Sume	memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
796129901Sume	ai.ai_addr = (struct sockaddr *)&ss;
797129901Sume	get_port(&ai, "1", 0);
798129901Sume
799129901Sume	/* open a socket to get the source address for the given dst */
800129901Sume	if ((s = _socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)) < 0)
801129901Sume		return;		/* give up */
802129901Sume	if (_connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
803129901Sume		goto cleanup;
804129901Sume	srclen = ai.ai_addrlen;
805129901Sume	if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
806129901Sume		aio->aio_srcsa.sa_family = AF_UNSPEC;
807129901Sume		goto cleanup;
808129901Sume	}
809129901Sume	aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
810129901Sume	aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
811129901Sume	aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
812129901Sume#ifdef INET6
813129901Sume	if (ai.ai_family == AF_INET6) {
814129901Sume		struct in6_ifreq ifr6;
815129901Sume		u_int32_t flags6;
816129901Sume
817129901Sume		/* XXX: interface name should not be hardcoded */
818129901Sume		strncpy(ifr6.ifr_name, "lo0", sizeof(ifr6.ifr_name));
819129901Sume		memset(&ifr6, 0, sizeof(ifr6));
820129901Sume		memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
821129901Sume		if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
822129901Sume			flags6 = ifr6.ifr_ifru.ifru_flags6;
823129901Sume			if ((flags6 & IN6_IFF_DEPRECATED))
824129901Sume				aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
825129901Sume		}
826129901Sume	}
827129901Sume#endif
828129901Sume
829129901Sume  cleanup:
830129901Sume	_close(s);
831129901Sume	return;
832129901Sume}
833129901Sume
834121747Sumestatic int
835157119Sumematchlen(struct sockaddr *src, struct sockaddr *dst)
836129901Sume{
837129901Sume	int match = 0;
838129901Sume	u_char *s, *d;
839129901Sume	u_char *lim, r;
840129901Sume	int addrlen;
841129901Sume
842129901Sume	switch (src->sa_family) {
843129901Sume#ifdef INET6
844129901Sume	case AF_INET6:
845129901Sume		s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
846129901Sume		d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
847129901Sume		addrlen = sizeof(struct in6_addr);
848129901Sume		lim = s + addrlen;
849129901Sume		break;
850129901Sume#endif
851129901Sume	case AF_INET:
852146222Sgnn		s = (u_char *)&((struct sockaddr_in *)src)->sin_addr;
853146222Sgnn		d = (u_char *)&((struct sockaddr_in *)dst)->sin_addr;
854129901Sume		addrlen = sizeof(struct in_addr);
855129901Sume		lim = s + addrlen;
856129901Sume		break;
857129901Sume	default:
858129901Sume		return(0);
859129901Sume	}
860129901Sume
861129901Sume	while (s < lim)
862129901Sume		if ((r = (*d++ ^ *s++)) != 0) {
863129901Sume			while (r < addrlen * 8) {
864129901Sume				match++;
865129901Sume				r <<= 1;
866129901Sume			}
867129901Sume			break;
868129901Sume		} else
869129901Sume			match += 8;
870129901Sume	return(match);
871129901Sume}
872129901Sume
873129901Sumestatic int
874157119Sumecomp_dst(const void *arg1, const void *arg2)
875121747Sume{
876121747Sume	const struct ai_order *dst1 = arg1, *dst2 = arg2;
877121747Sume
878121747Sume	/*
879121747Sume	 * Rule 1: Avoid unusable destinations.
880121747Sume	 * XXX: we currently do not consider if an appropriate route exists.
881121747Sume	 */
882121747Sume	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
883121747Sume	    dst2->aio_srcsa.sa_family == AF_UNSPEC) {
884121747Sume		return(-1);
885121747Sume	}
886121747Sume	if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
887121747Sume	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
888121747Sume		return(1);
889121747Sume	}
890121747Sume
891121747Sume	/* Rule 2: Prefer matching scope. */
892121747Sume	if (dst1->aio_dstscope == dst1->aio_srcscope &&
893121747Sume	    dst2->aio_dstscope != dst2->aio_srcscope) {
894121747Sume		return(-1);
895121747Sume	}
896121747Sume	if (dst1->aio_dstscope != dst1->aio_srcscope &&
897121747Sume	    dst2->aio_dstscope == dst2->aio_srcscope) {
898121747Sume		return(1);
899121747Sume	}
900121747Sume
901121747Sume	/* Rule 3: Avoid deprecated addresses. */
902121747Sume	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
903121747Sume	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
904121747Sume		if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
905121747Sume		    (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
906121747Sume			return(-1);
907121747Sume		}
908121747Sume		if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
909121747Sume		    !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
910121747Sume			return(1);
911121747Sume		}
912121747Sume	}
913121747Sume
914121747Sume	/* Rule 4: Prefer home addresses. */
915121747Sume	/* XXX: not implemented yet */
916121747Sume
917121747Sume	/* Rule 5: Prefer matching label. */
918121747Sume#ifdef INET6
919121747Sume	if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
920121747Sume	    dst1->aio_srcpolicy->pc_policy.label ==
921121747Sume	    dst1->aio_dstpolicy->pc_policy.label &&
922121747Sume	    (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
923121747Sume	     dst2->aio_srcpolicy->pc_policy.label !=
924121747Sume	     dst2->aio_dstpolicy->pc_policy.label)) {
925121747Sume		return(-1);
926121747Sume	}
927121747Sume	if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
928121747Sume	    dst2->aio_srcpolicy->pc_policy.label ==
929121747Sume	    dst2->aio_dstpolicy->pc_policy.label &&
930121747Sume	    (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
931121747Sume	     dst1->aio_srcpolicy->pc_policy.label !=
932121747Sume	     dst1->aio_dstpolicy->pc_policy.label)) {
933121747Sume		return(1);
934121747Sume	}
935121747Sume#endif
936121747Sume
937121747Sume	/* Rule 6: Prefer higher precedence. */
938121747Sume#ifdef INET6
939121747Sume	if (dst1->aio_dstpolicy &&
940121747Sume	    (dst2->aio_dstpolicy == NULL ||
941121747Sume	     dst1->aio_dstpolicy->pc_policy.preced >
942121747Sume	     dst2->aio_dstpolicy->pc_policy.preced)) {
943121747Sume		return(-1);
944121747Sume	}
945121747Sume	if (dst2->aio_dstpolicy &&
946121747Sume	    (dst1->aio_dstpolicy == NULL ||
947121747Sume	     dst2->aio_dstpolicy->pc_policy.preced >
948121747Sume	     dst1->aio_dstpolicy->pc_policy.preced)) {
949121747Sume		return(1);
950121747Sume	}
951121747Sume#endif
952121747Sume
953121747Sume	/* Rule 7: Prefer native transport. */
954121747Sume	/* XXX: not implemented yet */
955121747Sume
956121747Sume	/* Rule 8: Prefer smaller scope. */
957121747Sume	if (dst1->aio_dstscope >= 0 &&
958121747Sume	    dst1->aio_dstscope < dst2->aio_dstscope) {
959121747Sume		return(-1);
960121747Sume	}
961121747Sume	if (dst2->aio_dstscope >= 0 &&
962121747Sume	    dst2->aio_dstscope < dst1->aio_dstscope) {
963121747Sume		return(1);
964121747Sume	}
965121747Sume
966121747Sume	/*
967121747Sume	 * Rule 9: Use longest matching prefix.
968121747Sume	 * We compare the match length in a same AF only.
969121747Sume	 */
970121747Sume	if (dst1->aio_ai->ai_addr->sa_family ==
971121747Sume	    dst2->aio_ai->ai_addr->sa_family) {
972121747Sume		if (dst1->aio_matchlen > dst2->aio_matchlen) {
973121747Sume			return(-1);
974121747Sume		}
975121747Sume		if (dst1->aio_matchlen < dst2->aio_matchlen) {
976121747Sume			return(1);
977121747Sume		}
978121747Sume	}
979121747Sume
980121747Sume	/* Rule 10: Otherwise, leave the order unchanged. */
981121747Sume	return(-1);
982121747Sume}
983121747Sume
98455163Sshin/*
985121747Sume * Copy from scope.c.
986121747Sume * XXX: we should standardize the functions and link them as standard
987121747Sume * library.
988121747Sume */
989121747Sumestatic int
990157119Sumegai_addr2scopetype(struct sockaddr *sa)
991121747Sume{
992121747Sume#ifdef INET6
993121747Sume	struct sockaddr_in6 *sa6;
994121747Sume#endif
995121747Sume	struct sockaddr_in *sa4;
996121747Sume
997121747Sume	switch(sa->sa_family) {
998121747Sume#ifdef INET6
999121747Sume	case AF_INET6:
1000121747Sume		sa6 = (struct sockaddr_in6 *)sa;
1001121747Sume		if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1002121747Sume			/* just use the scope field of the multicast address */
1003121747Sume			return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1004121747Sume		}
1005121747Sume		/*
1006121747Sume		 * Unicast addresses: map scope type to corresponding scope
1007121747Sume		 * value defined for multcast addresses.
1008121747Sume		 * XXX: hardcoded scope type values are bad...
1009121747Sume		 */
1010121747Sume		if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1011121747Sume			return(1); /* node local scope */
1012121747Sume		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1013121747Sume			return(2); /* link-local scope */
1014121747Sume		if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1015121747Sume			return(5); /* site-local scope */
1016121747Sume		return(14);	/* global scope */
1017121747Sume		break;
1018121747Sume#endif
1019121747Sume	case AF_INET:
1020121747Sume		/*
1021121747Sume		 * IPv4 pseudo scoping according to RFC 3484.
1022121747Sume		 */
1023121747Sume		sa4 = (struct sockaddr_in *)sa;
1024121747Sume		/* IPv4 autoconfiguration addresses have link-local scope. */
1025121747Sume		if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1026121747Sume		    ((u_char *)&sa4->sin_addr)[1] == 254)
1027121747Sume			return(2);
1028121747Sume		/* Private addresses have site-local scope. */
1029121747Sume		if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1030121747Sume		    (((u_char *)&sa4->sin_addr)[0] == 172 &&
1031121747Sume		     (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1032121747Sume		    (((u_char *)&sa4->sin_addr)[0] == 192 &&
1033121747Sume		     ((u_char *)&sa4->sin_addr)[1] == 168))
1034129905Sume			return(14);	/* XXX: It should be 5 unless NAT */
1035121747Sume		/* Loopback addresses have link-local scope. */
1036121747Sume		if (((u_char *)&sa4->sin_addr)[0] == 127)
1037121747Sume			return(2);
1038121747Sume		return(14);
1039121747Sume		break;
1040121747Sume	default:
1041121747Sume		errno = EAFNOSUPPORT; /* is this a good error? */
1042121747Sume		return(-1);
1043121747Sume	}
1044121747Sume}
1045121747Sume
1046121747Sume/*
104755163Sshin * hostname == NULL.
104855163Sshin * passive socket -> anyaddr (0.0.0.0 or ::)
104955163Sshin * non-passive socket -> localhost (127.0.0.1 or ::1)
105055163Sshin */
105155163Sshinstatic int
1052157119Sumeexplore_null(const struct addrinfo *pai, const char *servname,
1053157119Sume    struct addrinfo **res)
105455163Sshin{
1055121474Sume	int s;
105655163Sshin	const struct afd *afd;
1057160551Sume	struct addrinfo *ai;
105855163Sshin	int error;
105955163Sshin
106055163Sshin	*res = NULL;
1061160551Sume	ai = NULL;
106255163Sshin
106355163Sshin	/*
1064121474Sume	 * filter out AFs that are not supported by the kernel
1065121474Sume	 * XXX errno?
1066121474Sume	 */
1067121474Sume	s = _socket(pai->ai_family, SOCK_DGRAM, 0);
1068121474Sume	if (s < 0) {
1069121474Sume		if (errno != EMFILE)
1070121474Sume			return 0;
1071121474Sume	} else
1072121474Sume		_close(s);
1073121474Sume
1074121474Sume	/*
107561877Sume	 * if the servname does not match socktype/protocol, ignore it.
107661877Sume	 */
107761877Sume	if (get_portmatch(pai, servname) != 0)
107855163Sshin		return 0;
107961877Sume
108055163Sshin	afd = find_afd(pai->ai_family);
108155163Sshin	if (afd == NULL)
108255163Sshin		return 0;
108355163Sshin
108461877Sume	if (pai->ai_flags & AI_PASSIVE) {
1085160551Sume		GET_AI(ai, afd, afd->a_addrany);
1086160551Sume		GET_PORT(ai, servname);
108761877Sume	} else {
1088160551Sume		GET_AI(ai, afd, afd->a_loopback);
1089160551Sume		GET_PORT(ai, servname);
109061877Sume	}
109155163Sshin
1092160551Sume	*res = ai;
109355163Sshin	return 0;
109455163Sshin
109555163Sshinfree:
1096160551Sume	if (ai != NULL)
1097160551Sume		freeaddrinfo(ai);
109855163Sshin	return error;
109955163Sshin}
110055163Sshin
110155163Sshin/*
110255163Sshin * numeric hostname
110355163Sshin */
110455163Sshinstatic int
1105157119Sumeexplore_numeric(const struct addrinfo *pai, const char *hostname,
1106157119Sume    const char *servname, struct addrinfo **res, const char *canonname)
110755163Sshin{
110855163Sshin	const struct afd *afd;
1109160551Sume	struct addrinfo *ai;
111055163Sshin	int error;
111155163Sshin	char pton[PTON_MAX];
111255163Sshin
111355163Sshin	*res = NULL;
1114160551Sume	ai = NULL;
111555163Sshin
1116121474Sume	/*
1117121474Sume	 * if the servname does not match socktype/protocol, ignore it.
1118121474Sume	 */
1119121474Sume	if (get_portmatch(pai, servname) != 0)
1120121474Sume		return 0;
1121121474Sume
112255163Sshin	afd = find_afd(pai->ai_family);
112355163Sshin	if (afd == NULL)
112455163Sshin		return 0;
112555163Sshin
112662614Sitojun	switch (afd->a_af) {
112762614Sitojun	case AF_INET:
1128160552Sume		/*
1129160552Sume		 * RFC3493 requires getaddrinfo() to accept AF_INET formats
1130160552Sume		 * that are accepted by inet_addr() and its family.  The
1131160552Sume		 * accepted forms includes the "classful" one, which inet_pton
1132160552Sume		 * does not accept.  So we need to separate the case for
1133160552Sume		 * AF_INET.
1134160552Sume		 */
1135160553Sume		if (inet_aton(hostname, (struct in_addr *)pton) != 1)
1136160553Sume			return 0;
113762614Sitojun		break;
113862614Sitojun	default:
1139160553Sume		if (inet_pton(afd->a_af, hostname, pton) != 1)
1140160553Sume			return 0;
114162614Sitojun		break;
114255163Sshin	}
114355163Sshin
1144160553Sume	if (pai->ai_family == afd->a_af) {
1145160553Sume		GET_AI(ai, afd, pton);
1146160553Sume		GET_PORT(ai, servname);
1147160553Sume		if ((pai->ai_flags & AI_CANONNAME)) {
1148160553Sume			/*
1149160553Sume			 * Set the numeric address itself as the canonical
1150160553Sume			 * name, based on a clarification in RFC3493.
1151160553Sume			 */
1152160553Sume			GET_CANONNAME(ai, canonname);
1153160553Sume		}
1154160553Sume	} else {
1155160553Sume		/*
1156160553Sume		 * XXX: This should not happen since we already matched the AF
1157160553Sume		 * by find_afd.
1158160553Sume		 */
1159160553Sume		ERR(EAI_FAMILY);
1160160553Sume	}
1161160553Sume
1162160551Sume	*res = ai;
116355163Sshin	return 0;
116455163Sshin
116555163Sshinfree:
116655163Sshinbad:
1167160551Sume	if (ai != NULL)
1168160551Sume		freeaddrinfo(ai);
116955163Sshin	return error;
117055163Sshin}
117155163Sshin
117255163Sshin/*
117355163Sshin * numeric hostname with scope
117455163Sshin */
117555163Sshinstatic int
1176157119Sumeexplore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1177157119Sume    const char *servname, struct addrinfo **res)
117855163Sshin{
117961877Sume#if !defined(SCOPE_DELIMITER) || !defined(INET6)
1180140906Sume	return explore_numeric(pai, hostname, servname, res, hostname);
118155163Sshin#else
118255163Sshin	const struct afd *afd;
118355163Sshin	struct addrinfo *cur;
118455163Sshin	int error;
118561877Sume	char *cp, *hostname2 = NULL, *scope, *addr;
118655163Sshin	struct sockaddr_in6 *sin6;
118755163Sshin
1188121474Sume	/*
1189121474Sume	 * if the servname does not match socktype/protocol, ignore it.
1190121474Sume	 */
1191121474Sume	if (get_portmatch(pai, servname) != 0)
1192121474Sume		return 0;
1193121474Sume
119455163Sshin	afd = find_afd(pai->ai_family);
119555163Sshin	if (afd == NULL)
119655163Sshin		return 0;
119765532Snectar
119855163Sshin	if (!afd->a_scoped)
1199140906Sume		return explore_numeric(pai, hostname, servname, res, hostname);
120055163Sshin
120155163Sshin	cp = strchr(hostname, SCOPE_DELIMITER);
120255163Sshin	if (cp == NULL)
1203140906Sume		return explore_numeric(pai, hostname, servname, res, hostname);
120455163Sshin
120555163Sshin	/*
120655163Sshin	 * Handle special case of <scoped_address><delimiter><scope id>
120755163Sshin	 */
120855163Sshin	hostname2 = strdup(hostname);
120955163Sshin	if (hostname2 == NULL)
121055163Sshin		return EAI_MEMORY;
121155163Sshin	/* terminate at the delimiter */
121255163Sshin	hostname2[cp - hostname] = '\0';
121361877Sume	addr = hostname2;
121461877Sume	scope = cp + 1;
121555163Sshin
1216140906Sume	error = explore_numeric(pai, addr, servname, res, hostname);
121761877Sume	if (error == 0) {
1218105943Sume		u_int32_t scopeid;
121955163Sshin
122055163Sshin		for (cur = *res; cur; cur = cur->ai_next) {
122155163Sshin			if (cur->ai_family != AF_INET6)
122255163Sshin				continue;
122361877Sume			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1224105943Sume			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
122561877Sume				free(hostname2);
1226121425Sume				return(EAI_NONAME); /* XXX: is return OK? */
122761877Sume			}
122861877Sume			sin6->sin6_scope_id = scopeid;
122955163Sshin		}
123055163Sshin	}
123155163Sshin
123255163Sshin	free(hostname2);
123355163Sshin
123455163Sshin	return error;
123555163Sshin#endif
123655163Sshin}
123755163Sshin
123855163Sshinstatic int
1239157119Sumeget_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
124055163Sshin{
124155163Sshin	if ((pai->ai_flags & AI_CANONNAME) != 0) {
1242140947Sume		ai->ai_canonname = strdup(str);
124355163Sshin		if (ai->ai_canonname == NULL)
124455163Sshin			return EAI_MEMORY;
124555163Sshin	}
124655163Sshin	return 0;
124755163Sshin}
124855163Sshin
124955163Sshinstatic struct addrinfo *
1250157119Sumeget_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
125155163Sshin{
125255163Sshin	char *p;
125355163Sshin	struct addrinfo *ai;
125455163Sshin#ifdef FAITH
125555163Sshin	struct in6_addr faith_prefix;
125655163Sshin	char *fp_str;
125755163Sshin	int translate = 0;
125855163Sshin#endif
125955163Sshin
126055163Sshin#ifdef FAITH
126155163Sshin	/*
126255163Sshin	 * Transfrom an IPv4 addr into a special IPv6 addr format for
126355163Sshin	 * IPv6->IPv4 translation gateway. (only TCP is supported now)
126455163Sshin	 *
126555163Sshin	 * +-----------------------------------+------------+
126655163Sshin	 * | faith prefix part (12 bytes)      | embedded   |
126755163Sshin	 * |                                   | IPv4 addr part (4 bytes)
126855163Sshin	 * +-----------------------------------+------------+
126955163Sshin	 *
127055163Sshin	 * faith prefix part is specified as ascii IPv6 addr format
127155163Sshin	 * in environmental variable GAI.
127255163Sshin	 * For FAITH to work correctly, routing to faith prefix must be
127355163Sshin	 * setup toward a machine where a FAITH daemon operates.
127455163Sshin	 * Also, the machine must enable some mechanizm
127555163Sshin	 * (e.g. faith interface hack) to divert those packet with
127655163Sshin	 * faith prefixed destination addr to user-land FAITH daemon.
127755163Sshin	 */
127855163Sshin	fp_str = getenv("GAI");
127955163Sshin	if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
128055163Sshin	    afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
128155163Sshin		u_int32_t v4a;
128255163Sshin		u_int8_t v4a_top;
128355163Sshin
128455163Sshin		memcpy(&v4a, addr, sizeof v4a);
128555163Sshin		v4a_top = v4a >> IN_CLASSA_NSHIFT;
128655163Sshin		if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
128755163Sshin		    v4a_top != 0 && v4a != IN_LOOPBACKNET) {
128855163Sshin			afd = &afdl[N_INET6];
128955163Sshin			memcpy(&faith_prefix.s6_addr[12], addr,
129055163Sshin			       sizeof(struct in_addr));
129155163Sshin			translate = 1;
129255163Sshin		}
129355163Sshin	}
129455163Sshin#endif
129555163Sshin
129655163Sshin	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
129755163Sshin		+ (afd->a_socklen));
129855163Sshin	if (ai == NULL)
129955163Sshin		return NULL;
130055163Sshin
130155163Sshin	memcpy(ai, pai, sizeof(struct addrinfo));
130261877Sume	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
130361877Sume	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
130455163Sshin	ai->ai_addr->sa_len = afd->a_socklen;
130555163Sshin	ai->ai_addrlen = afd->a_socklen;
130655163Sshin	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
130765532Snectar	p = (char *)(void *)(ai->ai_addr);
130855163Sshin#ifdef FAITH
130955163Sshin	if (translate == 1)
131065532Snectar		memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
131155163Sshin	else
131255163Sshin#endif
131365532Snectar	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
131455163Sshin	return ai;
131555163Sshin}
131655163Sshin
131755163Sshinstatic int
1318157119Sumeget_portmatch(const struct addrinfo *ai, const char *servname)
131955163Sshin{
132061877Sume
1321140908Sume	/* get_port does not touch first argument when matchonly == 1. */
132261877Sume	/* LINTED const cast */
132355163Sshin	return get_port((struct addrinfo *)ai, servname, 1);
132455163Sshin}
132555163Sshin
132655163Sshinstatic int
1327157119Sumeget_port(struct addrinfo *ai, const char *servname, int matchonly)
132855163Sshin{
132955163Sshin	const char *proto;
133055163Sshin	struct servent *sp;
1331160593Sume	int port, error;
133255163Sshin	int allownumeric;
133355163Sshin
133455163Sshin	if (servname == NULL)
133555163Sshin		return 0;
133661877Sume	switch (ai->ai_family) {
133761877Sume	case AF_INET:
133861877Sume#ifdef AF_INET6
133961877Sume	case AF_INET6:
134055163Sshin#endif
134161877Sume		break;
134261877Sume	default:
134355163Sshin		return 0;
134461877Sume	}
134555163Sshin
134655163Sshin	switch (ai->ai_socktype) {
134755163Sshin	case SOCK_RAW:
134855163Sshin		return EAI_SERVICE;
134955163Sshin	case SOCK_DGRAM:
135055163Sshin	case SOCK_STREAM:
135155163Sshin		allownumeric = 1;
135255163Sshin		break;
135355163Sshin	case ANY:
135455163Sshin		allownumeric = 0;
135555163Sshin		break;
135655163Sshin	default:
135755163Sshin		return EAI_SOCKTYPE;
135855163Sshin	}
135955163Sshin
1360160593Sume	error = str2number(servname, &port);
1361160593Sume	if (error == 0) {
136255163Sshin		if (!allownumeric)
136355163Sshin			return EAI_SERVICE;
136455163Sshin		if (port < 0 || port > 65535)
136555163Sshin			return EAI_SERVICE;
1366105940Sume		port = htons(port);
136755163Sshin	} else {
1368140908Sume		if (ai->ai_flags & AI_NUMERICSERV)
1369140908Sume			return EAI_NONAME;
1370121474Sume		switch (ai->ai_socktype) {
1371121474Sume		case SOCK_DGRAM:
137255163Sshin			proto = "udp";
137355163Sshin			break;
1374121474Sume		case SOCK_STREAM:
137555163Sshin			proto = "tcp";
137655163Sshin			break;
137755163Sshin		default:
137855163Sshin			proto = NULL;
137955163Sshin			break;
138055163Sshin		}
138155163Sshin
1382145118Sume		if ((sp = getservbyname(servname, proto)) == NULL)
138355163Sshin			return EAI_SERVICE;
138455163Sshin		port = sp->s_port;
138555163Sshin	}
138655163Sshin
138755163Sshin	if (!matchonly) {
138855163Sshin		switch (ai->ai_family) {
138955163Sshin		case AF_INET:
139061877Sume			((struct sockaddr_in *)(void *)
139161877Sume			    ai->ai_addr)->sin_port = port;
139255163Sshin			break;
139355163Sshin#ifdef INET6
139455163Sshin		case AF_INET6:
139561877Sume			((struct sockaddr_in6 *)(void *)
139661877Sume			    ai->ai_addr)->sin6_port = port;
139755163Sshin			break;
139855163Sshin#endif
139955163Sshin		}
140055163Sshin	}
140155163Sshin
140255163Sshin	return 0;
140355163Sshin}
140455163Sshin
140555163Sshinstatic const struct afd *
1406157119Sumefind_afd(int af)
140755163Sshin{
140855163Sshin	const struct afd *afd;
140955163Sshin
141055163Sshin	if (af == PF_UNSPEC)
141155163Sshin		return NULL;
141255163Sshin	for (afd = afdl; afd->a_af; afd++) {
141355163Sshin		if (afd->a_af == af)
141455163Sshin			return afd;
141555163Sshin	}
141655163Sshin	return NULL;
141755163Sshin}
141861877Sume
141961877Sume/*
142061877Sume * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
142161877Sume * will take care of it.
142261877Sume * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
142361877Sume * if the code is right or not.
1424121474Sume *
1425121474Sume * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1426121474Sume * _dns_getaddrinfo.
142761877Sume */
142861877Sumestatic int
1429157119Sumeaddrconfig(struct addrinfo *pai)
143061877Sume{
1431121474Sume	int s, af;
143261877Sume
1433121474Sume	/*
1434121474Sume	 * TODO:
1435121474Sume	 * Note that implementation dependent test for address
1436121474Sume	 * configuration should be done everytime called
1437121474Sume	 * (or apropriate interval),
1438121474Sume	 * because addresses will be dynamically assigned or deleted.
1439121474Sume	 */
1440121474Sume	af = pai->ai_family;
1441121474Sume	if (af == AF_UNSPEC) {
1442121474Sume		if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1443121474Sume			af = AF_INET;
1444121474Sume		else {
1445121474Sume			_close(s);
1446121474Sume			if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1447121474Sume				af = AF_INET6;
1448121474Sume			else
1449121474Sume				_close(s);
1450121474Sume		}
1451121474Sume	}
1452121474Sume	if (af != AF_UNSPEC) {
1453121474Sume		if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
145461877Sume			return 0;
1455121474Sume		_close(s);
1456121474Sume	}
1457121474Sume	pai->ai_family = af;
145861877Sume	return 1;
145961877Sume}
146061877Sume
146161877Sume#ifdef INET6
146261877Sume/* convert a string to a scope identifier. XXX: IPv6 specific */
146361877Sumestatic int
1464157119Sumeip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
146561877Sume{
1466105943Sume	u_long lscopeid;
1467121474Sume	struct in6_addr *a6;
146861877Sume	char *ep;
146961877Sume
1470121474Sume	a6 = &sin6->sin6_addr;
1471121474Sume
147262836Sitojun	/* empty scopeid portion is invalid */
147362836Sitojun	if (*scope == '\0')
147462836Sitojun		return -1;
147562836Sitojun
1476121474Sume	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
147761877Sume		/*
147861877Sume		 * We currently assume a one-to-one mapping between links
147961877Sume		 * and interfaces, so we simply use interface indices for
148061877Sume		 * like-local scopes.
148161877Sume		 */
1482105943Sume		*scopeid = if_nametoindex(scope);
1483105943Sume		if (*scopeid == 0)
148461877Sume			goto trynumeric;
1485105943Sume		return 0;
148661877Sume	}
148761877Sume
148861877Sume	/* still unclear about literal, allow numeric only - placeholder */
148961877Sume	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
149061877Sume		goto trynumeric;
149161877Sume	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
149261877Sume		goto trynumeric;
149361877Sume	else
149461877Sume		goto trynumeric;	/* global */
149561877Sume
149661877Sume	/* try to convert to a numeric id as a last resort */
1497121474Sume  trynumeric:
1498105943Sume	errno = 0;
1499105943Sume	lscopeid = strtoul(scope, &ep, 10);
1500105943Sume	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1501105943Sume	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1502105943Sume		return 0;
150361877Sume	else
150461877Sume		return -1;
150561877Sume}
150661877Sume#endif
150761877Sume
1508158115Sume
1509158115Sume#ifdef NS_CACHING
1510158115Sumestatic int
1511158115Sumeaddrinfo_id_func(char *buffer, size_t *buffer_size, va_list ap,
1512158115Sume    void *cache_mdata)
1513158115Sume{
1514158115Sume	res_state statp;
1515158115Sume	u_long res_options;
1516158115Sume
1517158115Sume	const int op_id = 0;	/* identifies the getaddrinfo for the cache */
1518158115Sume	char *hostname;
1519158115Sume	struct addrinfo *hints;
1520158115Sume
1521158115Sume	char *p;
1522158115Sume	int ai_flags, ai_family, ai_socktype, ai_protocol;
1523158115Sume	size_t desired_size, size;
1524158115Sume
1525158115Sume	statp = __res_state();
1526158115Sume	res_options = statp->options & (RES_RECURSE | RES_DEFNAMES |
1527158115Sume	    RES_DNSRCH | RES_NOALIASES | RES_USE_INET6);
1528158115Sume
1529158115Sume	hostname = va_arg(ap, char *);
1530158115Sume	hints = va_arg(ap, struct addrinfo *);
1531158115Sume
1532158115Sume	desired_size = sizeof(res_options) + sizeof(int) + sizeof(int) * 4;
1533158115Sume	if (hostname != NULL) {
1534158115Sume		size = strlen(hostname);
1535158115Sume		desired_size += size + 1;
1536158115Sume	} else
1537158115Sume		size = 0;
1538158115Sume
1539158115Sume	if (desired_size > *buffer_size) {
1540158115Sume		*buffer_size = desired_size;
1541158115Sume		return (NS_RETURN);
1542158115Sume	}
1543158115Sume
1544158115Sume	if (hints == NULL)
1545158115Sume		ai_flags = ai_family = ai_socktype = ai_protocol = 0;
1546158115Sume	else {
1547158115Sume		ai_flags = hints->ai_flags;
1548158115Sume		ai_family = hints->ai_family;
1549158115Sume		ai_socktype = hints->ai_socktype;
1550158115Sume		ai_protocol = hints->ai_protocol;
1551158115Sume	}
1552158115Sume
1553158115Sume	p = buffer;
1554158115Sume	memcpy(p, &res_options, sizeof(res_options));
1555158115Sume	p += sizeof(res_options);
1556158115Sume
1557158115Sume	memcpy(p, &op_id, sizeof(int));
1558158115Sume	p += sizeof(int);
1559158115Sume
1560158115Sume	memcpy(p, &ai_flags, sizeof(int));
1561158115Sume	p += sizeof(int);
1562158115Sume
1563158115Sume	memcpy(p, &ai_family, sizeof(int));
1564158115Sume	p += sizeof(int);
1565158115Sume
1566158115Sume	memcpy(p, &ai_socktype, sizeof(int));
1567158115Sume	p += sizeof(int);
1568158115Sume
1569158115Sume	memcpy(p, &ai_protocol, sizeof(int));
1570158115Sume	p += sizeof(int);
1571158115Sume
1572158115Sume	if (hostname != NULL)
1573158115Sume		memcpy(p, hostname, size);
1574158115Sume
1575158115Sume	*buffer_size = desired_size;
1576158115Sume	return (NS_SUCCESS);
1577158115Sume}
1578158115Sume
1579158115Sumestatic int
1580158115Sumeaddrinfo_marshal_func(char *buffer, size_t *buffer_size, void *retval,
1581158115Sume    va_list ap, void *cache_mdata)
1582158115Sume{
1583158115Sume	struct addrinfo	*ai, *cai;
1584158115Sume	char *p;
1585158115Sume	size_t desired_size, size, ai_size;
1586158115Sume
1587158115Sume	ai = *((struct addrinfo **)retval);
1588158115Sume
1589158115Sume	desired_size = sizeof(size_t);
1590158115Sume	ai_size = 0;
1591158115Sume	for (cai = ai; cai != NULL; cai = cai->ai_next) {
1592158115Sume		desired_size += sizeof(struct addrinfo) + cai->ai_addrlen;
1593158115Sume		if (cai->ai_canonname != NULL)
1594158115Sume			desired_size += sizeof(size_t) +
1595158115Sume			    strlen(cai->ai_canonname);
1596158115Sume		++ai_size;
1597158115Sume	}
1598158115Sume
1599158115Sume	if (desired_size > *buffer_size) {
1600158115Sume		/* this assignment is here for future use */
1601158115Sume		errno = ERANGE;
1602158115Sume		*buffer_size = desired_size;
1603158115Sume		return (NS_RETURN);
1604158115Sume	}
1605158115Sume
1606158115Sume	memset(buffer, 0, desired_size);
1607158115Sume	p = buffer;
1608158115Sume
1609158115Sume	memcpy(p, &ai_size, sizeof(size_t));
1610158115Sume	p += sizeof(size_t);
1611158115Sume	for (cai = ai; cai != NULL; cai = cai->ai_next) {
1612158115Sume		memcpy(p, cai, sizeof(struct addrinfo));
1613158115Sume		p += sizeof(struct addrinfo);
1614158115Sume
1615158115Sume		memcpy(p, cai->ai_addr, cai->ai_addrlen);
1616158115Sume		p += cai->ai_addrlen;
1617158115Sume
1618158115Sume		if (cai->ai_canonname != NULL) {
1619158115Sume			size = strlen(cai->ai_canonname);
1620158115Sume			memcpy(p, &size, sizeof(size_t));
1621158115Sume			p += sizeof(size_t);
1622158115Sume
1623158115Sume			memcpy(p, cai->ai_canonname, size);
1624158115Sume			p += size;
1625158115Sume		}
1626158115Sume	}
1627158115Sume
1628158115Sume	return (NS_SUCCESS);
1629158115Sume}
1630158115Sume
1631158115Sumestatic int
1632158115Sumeaddrinfo_unmarshal_func(char *buffer, size_t buffer_size, void *retval,
1633158115Sume    va_list ap, void *cache_mdata)
1634158115Sume{
1635158115Sume	struct addrinfo	new_ai, *result, *sentinel, *lasts;
1636158115Sume
1637158115Sume	char *p;
1638158115Sume	size_t ai_size, ai_i, size;
1639158115Sume
1640158115Sume	p = buffer;
1641158115Sume	memcpy(&ai_size, p, sizeof(size_t));
1642158115Sume	p += sizeof(size_t);
1643158115Sume
1644158115Sume	result = NULL;
1645158115Sume	lasts = NULL;
1646158115Sume	for (ai_i = 0; ai_i < ai_size; ++ai_i) {
1647158115Sume		memcpy(&new_ai, p, sizeof(struct addrinfo));
1648158115Sume		p += sizeof(struct addrinfo);
1649158115Sume		size = new_ai.ai_addrlen + sizeof(struct addrinfo) +
1650158115Sume			_ALIGNBYTES;
1651158115Sume
1652158115Sume		sentinel = (struct addrinfo *)malloc(size);
1653158115Sume		memset(sentinel, 0, size);
1654158115Sume
1655158115Sume		memcpy(sentinel, &new_ai, sizeof(struct addrinfo));
1656158115Sume		sentinel->ai_addr = (struct sockaddr *)_ALIGN((char *)sentinel +
1657158115Sume		    sizeof(struct addrinfo));
1658158115Sume
1659158115Sume		memcpy(sentinel->ai_addr, p, new_ai.ai_addrlen);
1660158115Sume		p += new_ai.ai_addrlen;
1661158115Sume
1662158115Sume		if (new_ai.ai_canonname != NULL) {
1663158115Sume			memcpy(&size, p, sizeof(size_t));
1664158115Sume			p += sizeof(size_t);
1665158115Sume
1666158115Sume			sentinel->ai_canonname = (char *)malloc(size + 1);
1667158115Sume			memset(sentinel->ai_canonname, 0, size + 1);
1668158115Sume
1669158115Sume			memcpy(sentinel->ai_canonname, p, size);
1670158115Sume			p += size;
1671158115Sume		}
1672158115Sume
1673158115Sume		if (result == NULL) {
1674158115Sume			result = sentinel;
1675158115Sume			lasts = sentinel;
1676158115Sume		} else {
1677158115Sume			lasts->ai_next = sentinel;
1678158115Sume			lasts = sentinel;
1679158115Sume		}
1680158115Sume	}
1681158115Sume
1682158115Sume	*((struct addrinfo **)retval) = result;
1683158115Sume	return (NS_SUCCESS);
1684158115Sume}
1685158115Sume#endif /* NS_CACHING */
1686158115Sume
1687121426Sume/*
1688121426Sume * FQDN hostname, DNS lookup
1689121426Sume */
1690102237Spirzykstatic int
1691157119Sumeexplore_fqdn(const struct addrinfo *pai, const char *hostname,
1692157119Sume    const char *servname, struct addrinfo **res)
1693102237Spirzyk{
1694121426Sume	struct addrinfo *result;
1695121426Sume	struct addrinfo *cur;
1696121426Sume	int error = 0;
1697158115Sume
1698158115Sume#ifdef NS_CACHING
1699158115Sume	static const nss_cache_info cache_info =
1700158115Sume	NS_COMMON_CACHE_INFO_INITIALIZER(
1701158115Sume		hosts, NULL, addrinfo_id_func, addrinfo_marshal_func,
1702158115Sume		addrinfo_unmarshal_func);
1703158115Sume#endif
1704121426Sume	static const ns_dtab dtab[] = {
1705121426Sume		NS_FILES_CB(_files_getaddrinfo, NULL)
1706121426Sume		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
1707121426Sume		NS_NIS_CB(_yp_getaddrinfo, NULL)
1708158115Sume#ifdef NS_CACHING
1709158115Sume		NS_CACHE_CB(&cache_info)
1710158115Sume#endif
1711121426Sume		{ 0 }
1712121426Sume	};
1713102237Spirzyk
1714121426Sume	result = NULL;
1715121426Sume
1716121426Sume	/*
1717121426Sume	 * if the servname does not match socktype/protocol, ignore it.
1718121426Sume	 */
1719126243Sgreen	if (get_portmatch(pai, servname) != 0)
1720102237Spirzyk		return 0;
1721102237Spirzyk
1722121426Sume	switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1723121426Sume			default_dns_files, hostname, pai)) {
1724121426Sume	case NS_TRYAGAIN:
1725121426Sume		error = EAI_AGAIN;
1726121426Sume		goto free;
1727121426Sume	case NS_UNAVAIL:
1728121426Sume		error = EAI_FAIL;
1729121426Sume		goto free;
1730121426Sume	case NS_NOTFOUND:
1731121426Sume		error = EAI_NONAME;
1732121426Sume		goto free;
1733121426Sume	case NS_SUCCESS:
1734121426Sume		error = 0;
1735121426Sume		for (cur = result; cur; cur = cur->ai_next) {
1736121426Sume			GET_PORT(cur, servname);
1737121426Sume			/* canonname should be filled already */
1738121426Sume		}
1739121426Sume		break;
1740102237Spirzyk	}
1741102237Spirzyk
1742121426Sume	*res = result;
1743121426Sume
1744102237Spirzyk	return 0;
1745121426Sume
1746121426Sumefree:
1747121426Sume	if (result)
1748121426Sume		freeaddrinfo(result);
1749121426Sume	return error;
1750102237Spirzyk}
1751102237Spirzyk
175261877Sume#ifdef DEBUG
175361877Sumestatic const char AskedForGot[] =
175461877Sume	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
175561877Sume#endif
175661877Sume
175761877Sumestatic struct addrinfo *
1758157119Sumegetanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1759157119Sume    const struct addrinfo *pai, res_state res)
176061877Sume{
176161877Sume	struct addrinfo sentinel, *cur;
176261877Sume	struct addrinfo ai;
176361877Sume	const struct afd *afd;
176461877Sume	char *canonname;
176561877Sume	const HEADER *hp;
176661877Sume	const u_char *cp;
176761877Sume	int n;
176861877Sume	const u_char *eom;
1769105940Sume	char *bp, *ep;
1770105940Sume	int type, class, ancount, qdcount;
177161877Sume	int haveanswer, had_error;
177261877Sume	char tbuf[MAXDNAME];
177392905Sobrien	int (*name_ok)(const char *);
177461877Sume	char hostbuf[8*1024];
177561877Sume
177661877Sume	memset(&sentinel, 0, sizeof(sentinel));
177761877Sume	cur = &sentinel;
177861877Sume
177961877Sume	canonname = NULL;
178061877Sume	eom = answer->buf + anslen;
178161877Sume	switch (qtype) {
178261877Sume	case T_A:
178361877Sume	case T_AAAA:
178461877Sume	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
178561877Sume		name_ok = res_hnok;
178661877Sume		break;
178761877Sume	default:
178861877Sume		return (NULL);	/* XXX should be abort(); */
178961877Sume	}
179061877Sume	/*
179161877Sume	 * find first satisfactory answer
179261877Sume	 */
179361877Sume	hp = &answer->hdr;
179461877Sume	ancount = ntohs(hp->ancount);
179561877Sume	qdcount = ntohs(hp->qdcount);
179661877Sume	bp = hostbuf;
1797105940Sume	ep = hostbuf + sizeof hostbuf;
179861877Sume	cp = answer->buf + HFIXEDSZ;
179961877Sume	if (qdcount != 1) {
1800156960Sume		RES_SET_H_ERRNO(res, NO_RECOVERY);
180161877Sume		return (NULL);
180261877Sume	}
1803105940Sume	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
180461877Sume	if ((n < 0) || !(*name_ok)(bp)) {
1805156960Sume		RES_SET_H_ERRNO(res, NO_RECOVERY);
180661877Sume		return (NULL);
180761877Sume	}
180861877Sume	cp += n + QFIXEDSZ;
180961877Sume	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
181061877Sume		/* res_send() has already verified that the query name is the
181161877Sume		 * same as the one we sent; this just gets the expanded name
181261877Sume		 * (i.e., with the succeeding search-domain tacked on).
181361877Sume		 */
181461877Sume		n = strlen(bp) + 1;		/* for the \0 */
181561877Sume		if (n >= MAXHOSTNAMELEN) {
1816156960Sume			RES_SET_H_ERRNO(res, NO_RECOVERY);
181761877Sume			return (NULL);
181861877Sume		}
181961877Sume		canonname = bp;
182061877Sume		bp += n;
182161877Sume		/* The qname can be abbreviated, but h_name is now absolute. */
182261877Sume		qname = canonname;
182361877Sume	}
182461877Sume	haveanswer = 0;
182561877Sume	had_error = 0;
182661877Sume	while (ancount-- > 0 && cp < eom && !had_error) {
1827105940Sume		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
182861877Sume		if ((n < 0) || !(*name_ok)(bp)) {
182961877Sume			had_error++;
183061877Sume			continue;
183161877Sume		}
183261877Sume		cp += n;			/* name */
183361877Sume		type = _getshort(cp);
183461877Sume 		cp += INT16SZ;			/* type */
183561877Sume		class = _getshort(cp);
183661877Sume 		cp += INT16SZ + INT32SZ;	/* class, TTL */
183761877Sume		n = _getshort(cp);
183861877Sume		cp += INT16SZ;			/* len */
183961877Sume		if (class != C_IN) {
184061877Sume			/* XXX - debug? syslog? */
184161877Sume			cp += n;
184261877Sume			continue;		/* XXX - had_error++ ? */
184361877Sume		}
184461877Sume		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
184561877Sume		    type == T_CNAME) {
184661877Sume			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
184761877Sume			if ((n < 0) || !(*name_ok)(tbuf)) {
184861877Sume				had_error++;
184961877Sume				continue;
185061877Sume			}
185161877Sume			cp += n;
185261877Sume			/* Get canonical name. */
185361877Sume			n = strlen(tbuf) + 1;	/* for the \0 */
1854105940Sume			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
185561877Sume				had_error++;
185661877Sume				continue;
185761877Sume			}
1858114443Snectar			strlcpy(bp, tbuf, ep - bp);
185961877Sume			canonname = bp;
186061877Sume			bp += n;
186161877Sume			continue;
186261877Sume		}
186361877Sume		if (qtype == T_ANY) {
186461877Sume			if (!(type == T_A || type == T_AAAA)) {
186561877Sume				cp += n;
186661877Sume				continue;
186761877Sume			}
186861877Sume		} else if (type != qtype) {
186961877Sume#ifdef DEBUG
187061877Sume			if (type != T_KEY && type != T_SIG)
187161877Sume				syslog(LOG_NOTICE|LOG_AUTH,
187261877Sume	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
187361877Sume				       qname, p_class(C_IN), p_type(qtype),
187461877Sume				       p_type(type));
187561877Sume#endif
187661877Sume			cp += n;
187761877Sume			continue;		/* XXX - had_error++ ? */
187861877Sume		}
187961877Sume		switch (type) {
188061877Sume		case T_A:
188161877Sume		case T_AAAA:
188261877Sume			if (strcasecmp(canonname, bp) != 0) {
188361877Sume#ifdef DEBUG
188461877Sume				syslog(LOG_NOTICE|LOG_AUTH,
188561877Sume				       AskedForGot, canonname, bp);
188661877Sume#endif
188761877Sume				cp += n;
188861877Sume				continue;	/* XXX - had_error++ ? */
188961877Sume			}
189061877Sume			if (type == T_A && n != INADDRSZ) {
189161877Sume				cp += n;
189261877Sume				continue;
189361877Sume			}
189461877Sume			if (type == T_AAAA && n != IN6ADDRSZ) {
189561877Sume				cp += n;
189661877Sume				continue;
189761877Sume			}
189861877Sume#ifdef FILTER_V4MAPPED
189961877Sume			if (type == T_AAAA) {
190061877Sume				struct in6_addr in6;
190161877Sume				memcpy(&in6, cp, sizeof(in6));
190261877Sume				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
190361877Sume					cp += n;
190461877Sume					continue;
190561877Sume				}
190661877Sume			}
190761877Sume#endif
190861877Sume			if (!haveanswer) {
190961877Sume				int nn;
191061877Sume
191161877Sume				canonname = bp;
191261877Sume				nn = strlen(bp) + 1;	/* for the \0 */
191361877Sume				bp += nn;
191461877Sume			}
191561877Sume
191661877Sume			/* don't overwrite pai */
191761877Sume			ai = *pai;
191861877Sume			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
191961877Sume			afd = find_afd(ai.ai_family);
192061877Sume			if (afd == NULL) {
192161877Sume				cp += n;
192261877Sume				continue;
192361877Sume			}
192461877Sume			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
192561877Sume			if (cur->ai_next == NULL)
192661877Sume				had_error++;
192761877Sume			while (cur && cur->ai_next)
192861877Sume				cur = cur->ai_next;
192961877Sume			cp += n;
193061877Sume			break;
193161877Sume		default:
193261877Sume			abort();
193361877Sume		}
193461877Sume		if (!had_error)
193561877Sume			haveanswer++;
193661877Sume	}
193761877Sume	if (haveanswer) {
1938102237Spirzyk#if defined(RESOLVSORT)
1939102237Spirzyk		/*
1940102237Spirzyk		 * We support only IPv4 address for backward
1941102237Spirzyk		 * compatibility against gethostbyname(3).
1942102237Spirzyk		 */
1943156960Sume		if (res->nsort && qtype == T_A) {
1944156960Sume			if (addr4sort(&sentinel, res) < 0) {
1945102237Spirzyk				freeaddrinfo(sentinel.ai_next);
1946156960Sume				RES_SET_H_ERRNO(res, NO_RECOVERY);
1947102237Spirzyk				return NULL;
1948102237Spirzyk			}
1949102237Spirzyk		}
1950102237Spirzyk#endif /*RESOLVSORT*/
195161877Sume		if (!canonname)
195261877Sume			(void)get_canonname(pai, sentinel.ai_next, qname);
195361877Sume		else
195461877Sume			(void)get_canonname(pai, sentinel.ai_next, canonname);
1955156960Sume		RES_SET_H_ERRNO(res, NETDB_SUCCESS);
195661877Sume		return sentinel.ai_next;
195761877Sume	}
195861877Sume
1959156960Sume	RES_SET_H_ERRNO(res, NO_RECOVERY);
196061877Sume	return NULL;
196161877Sume}
196261877Sume
1963121426Sume#ifdef RESOLVSORT
1964121426Sumestruct addr_ptr {
1965121426Sume	struct addrinfo *ai;
1966121426Sume	int aval;
1967121426Sume};
1968121426Sume
1969121426Sumestatic int
1970156960Sumeaddr4sort(struct addrinfo *sentinel, res_state res)
1971121426Sume{
1972121426Sume	struct addrinfo *ai;
1973121426Sume	struct addr_ptr *addrs, addr;
1974121426Sume	struct sockaddr_in *sin;
1975121426Sume	int naddrs, i, j;
1976121426Sume	int needsort = 0;
1977121426Sume
1978121426Sume	if (!sentinel)
1979121426Sume		return -1;
1980121426Sume	naddrs = 0;
1981121426Sume	for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
1982121426Sume		naddrs++;
1983121426Sume	if (naddrs < 2)
1984121426Sume		return 0;		/* We don't need sorting. */
1985121426Sume	if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
1986121426Sume		return -1;
1987121426Sume	i = 0;
1988121426Sume	for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
1989121426Sume		sin = (struct sockaddr_in *)ai->ai_addr;
1990156960Sume		for (j = 0; (unsigned)j < res->nsort; j++) {
1991157119Sume			if (res->sort_list[j].addr.s_addr ==
1992156960Sume			    (sin->sin_addr.s_addr & res->sort_list[j].mask))
1993121426Sume				break;
1994121426Sume		}
1995121426Sume		addrs[i].ai = ai;
1996121426Sume		addrs[i].aval = j;
1997121426Sume		if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
1998121426Sume			needsort = i;
1999121426Sume		i++;
2000121426Sume	}
2001121426Sume	if (!needsort) {
2002121426Sume		free(addrs);
2003121426Sume		return 0;
2004121426Sume	}
2005121426Sume
2006121426Sume	while (needsort < naddrs) {
2007157371Sume		for (j = needsort - 1; j >= 0; j--) {
2008157371Sume			if (addrs[j].aval > addrs[j+1].aval) {
2009157371Sume				addr = addrs[j];
2010157371Sume				addrs[j] = addrs[j + 1];
2011157371Sume				addrs[j + 1] = addr;
2012157371Sume			} else
2013157371Sume				break;
2014157371Sume		}
2015157371Sume		needsort++;
2016121426Sume	}
2017121426Sume
2018121426Sume	ai = sentinel;
2019121426Sume	for (i = 0; i < naddrs; ++i) {
2020121426Sume		ai->ai_next = addrs[i].ai;
2021121426Sume		ai = ai->ai_next;
2022121426Sume	}
2023121426Sume	ai->ai_next = NULL;
2024121426Sume	free(addrs);
2025121426Sume	return 0;
2026121426Sume}
2027121426Sume#endif /*RESOLVSORT*/
2028121426Sume
202961877Sume/*ARGSUSED*/
203061877Sumestatic int
2031157119Sume_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
203261877Sume{
203361877Sume	struct addrinfo *ai;
2034103357Sume	querybuf *buf, *buf2;
2035130600Sume	const char *hostname;
203665532Snectar	const struct addrinfo *pai;
203761877Sume	struct addrinfo sentinel, *cur;
203861877Sume	struct res_target q, q2;
2039156960Sume	res_state res;
204061877Sume
2041130600Sume	hostname = va_arg(ap, char *);
204265532Snectar	pai = va_arg(ap, const struct addrinfo *);
204365532Snectar
2044156946Sdelphij	memset(&q, 0, sizeof(q));
204561877Sume	memset(&q2, 0, sizeof(q2));
204661877Sume	memset(&sentinel, 0, sizeof(sentinel));
204761877Sume	cur = &sentinel;
204861877Sume
2049103357Sume	buf = malloc(sizeof(*buf));
2050103357Sume	if (!buf) {
2051156960Sume		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2052103357Sume		return NS_NOTFOUND;
2053103357Sume	}
2054103357Sume	buf2 = malloc(sizeof(*buf2));
2055103357Sume	if (!buf2) {
2056103357Sume		free(buf);
2057156960Sume		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2058103357Sume		return NS_NOTFOUND;
2059103357Sume	}
2060103357Sume
206161877Sume	switch (pai->ai_family) {
206261877Sume	case AF_UNSPEC:
2063130600Sume		q.name = hostname;
206462614Sitojun		q.qclass = C_IN;
2065140896Sume		q.qtype = T_A;
2066103357Sume		q.answer = buf->buf;
2067103357Sume		q.anslen = sizeof(buf->buf);
206861877Sume		q.next = &q2;
2069130600Sume		q2.name = hostname;
207062614Sitojun		q2.qclass = C_IN;
2071140896Sume		q2.qtype = T_AAAA;
2072103357Sume		q2.answer = buf2->buf;
2073103357Sume		q2.anslen = sizeof(buf2->buf);
207461877Sume		break;
207561877Sume	case AF_INET:
2076130600Sume		q.name = hostname;
207762614Sitojun		q.qclass = C_IN;
207862614Sitojun		q.qtype = T_A;
2079103357Sume		q.answer = buf->buf;
2080103357Sume		q.anslen = sizeof(buf->buf);
208161877Sume		break;
208261877Sume	case AF_INET6:
2083130600Sume		q.name = hostname;
208462614Sitojun		q.qclass = C_IN;
208562614Sitojun		q.qtype = T_AAAA;
2086103357Sume		q.answer = buf->buf;
2087103357Sume		q.anslen = sizeof(buf->buf);
208861877Sume		break;
208961877Sume	default:
2090103357Sume		free(buf);
2091103357Sume		free(buf2);
209265532Snectar		return NS_UNAVAIL;
209361877Sume	}
2094156960Sume
2095156960Sume	res = __res_state();
2096156960Sume	if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) {
2097156960Sume		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2098103357Sume		free(buf);
2099103357Sume		free(buf2);
210065532Snectar		return NS_NOTFOUND;
2101103357Sume	}
2102156960Sume
2103156960Sume	if (res_searchN(hostname, &q, res) < 0) {
2104156960Sume		free(buf);
2105156960Sume		free(buf2);
2106156960Sume		return NS_NOTFOUND;
2107156960Sume	}
2108140896Sume	/* prefer IPv6 */
210961877Sume	if (q.next) {
2110156960Sume		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, res);
2111140896Sume		if (ai) {
211261877Sume			cur->ai_next = ai;
2113140896Sume			while (cur && cur->ai_next)
2114140896Sume				cur = cur->ai_next;
2115140896Sume		}
211661877Sume	}
2117156960Sume	ai = getanswer(buf, q.n, q.name, q.qtype, pai, res);
2118140896Sume	if (ai)
2119140896Sume		cur->ai_next = ai;
2120103357Sume	free(buf);
2121103357Sume	free(buf2);
212261877Sume	if (sentinel.ai_next == NULL)
2123156960Sume		switch (res->res_h_errno) {
212461877Sume		case HOST_NOT_FOUND:
212565532Snectar			return NS_NOTFOUND;
212661877Sume		case TRY_AGAIN:
212765532Snectar			return NS_TRYAGAIN;
212861877Sume		default:
212965532Snectar			return NS_UNAVAIL;
213061877Sume		}
213165532Snectar	*((struct addrinfo **)rv) = sentinel.ai_next;
213265532Snectar	return NS_SUCCESS;
213361877Sume}
213461877Sume
213565532Snectarstatic void
2136144634Sume_sethtent(FILE **hostf)
213765532Snectar{
2138144634Sume	if (!*hostf)
2139144634Sume		*hostf = fopen(_PATH_HOSTS, "r");
214065532Snectar	else
2141144634Sume		rewind(*hostf);
214265532Snectar}
214365532Snectar
214465532Snectarstatic void
2145144634Sume_endhtent(FILE **hostf)
214665532Snectar{
2147144634Sume	if (*hostf) {
2148144634Sume		(void) fclose(*hostf);
2149144634Sume		*hostf = NULL;
215065532Snectar	}
215165532Snectar}
215265532Snectar
215361877Sumestatic struct addrinfo *
2154144634Sume_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
215561877Sume{
215661877Sume	char *p;
215761877Sume	char *cp, *tname, *cname;
215861877Sume	struct addrinfo hints, *res0, *res;
215961877Sume	int error;
216061877Sume	const char *addr;
216161877Sume	char hostbuf[8*1024];
216261877Sume
2163144634Sume	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r")))
216465532Snectar		return (NULL);
2165105940Sumeagain:
2166144634Sume	if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
216761877Sume		return (NULL);
216861877Sume	if (*p == '#')
216961877Sume		goto again;
2170139612Ssobomax	cp = strpbrk(p, "#\n");
2171139612Ssobomax	if (cp != NULL)
2172139612Ssobomax		*cp = '\0';
217361877Sume	if (!(cp = strpbrk(p, " \t")))
217461877Sume		goto again;
217561877Sume	*cp++ = '\0';
217661877Sume	addr = p;
217761877Sume	cname = NULL;
217861877Sume	/* if this is not something we're looking for, skip it. */
217961877Sume	while (cp && *cp) {
218061877Sume		if (*cp == ' ' || *cp == '\t') {
218161877Sume			cp++;
218261877Sume			continue;
218361877Sume		}
218461877Sume		tname = cp;
218561877Sume		if (cname == NULL)
218661877Sume			cname = cp;
218761877Sume		if ((cp = strpbrk(cp, " \t")) != NULL)
218861877Sume			*cp++ = '\0';
218961877Sume		if (strcasecmp(name, tname) == 0)
219061877Sume			goto found;
219161877Sume	}
219261877Sume	goto again;
219361877Sume
219461877Sumefound:
2195105940Sume	/* we should not glob socktype/protocol here */
2196105940Sume	memset(&hints, 0, sizeof(hints));
2197105940Sume	hints.ai_family = pai->ai_family;
2198105940Sume	hints.ai_socktype = SOCK_DGRAM;
2199105940Sume	hints.ai_protocol = 0;
220061877Sume	hints.ai_flags = AI_NUMERICHOST;
2201105940Sume	error = getaddrinfo(addr, "0", &hints, &res0);
220261877Sume	if (error)
220361877Sume		goto again;
220461877Sume#ifdef FILTER_V4MAPPED
220561877Sume	/* XXX should check all items in the chain */
220661877Sume	if (res0->ai_family == AF_INET6 &&
220761877Sume	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
220861877Sume		freeaddrinfo(res0);
220961877Sume		goto again;
221061877Sume	}
221161877Sume#endif
221261877Sume	for (res = res0; res; res = res->ai_next) {
221361877Sume		/* cover it up */
221461877Sume		res->ai_flags = pai->ai_flags;
2215105940Sume		res->ai_socktype = pai->ai_socktype;
2216105940Sume		res->ai_protocol = pai->ai_protocol;
221761877Sume
221861877Sume		if (pai->ai_flags & AI_CANONNAME) {
221961877Sume			if (get_canonname(pai, res, cname) != 0) {
222061877Sume				freeaddrinfo(res0);
222161877Sume				goto again;
222261877Sume			}
222361877Sume		}
222461877Sume	}
222561877Sume	return res0;
222661877Sume}
222761877Sume
222861877Sume/*ARGSUSED*/
222961877Sumestatic int
2230157119Sume_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
223165532Snectar{
223265532Snectar	const char *name;
223361877Sume	const struct addrinfo *pai;
223461877Sume	struct addrinfo sentinel, *cur;
223561877Sume	struct addrinfo *p;
2236144634Sume	FILE *hostf = NULL;
223761877Sume
223865532Snectar	name = va_arg(ap, char *);
223965532Snectar	pai = va_arg(ap, struct addrinfo *);
224065532Snectar
224165532Snectar	memset(&sentinel, 0, sizeof(sentinel));
224261877Sume	cur = &sentinel;
224361877Sume
2244144634Sume	_sethtent(&hostf);
2245144634Sume	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
224661877Sume		cur->ai_next = p;
224761877Sume		while (cur && cur->ai_next)
224861877Sume			cur = cur->ai_next;
224961877Sume	}
2250144634Sume	_endhtent(&hostf);
225161877Sume
225265532Snectar	*((struct addrinfo **)rv) = sentinel.ai_next;
225365532Snectar	if (sentinel.ai_next == NULL)
225465532Snectar		return NS_NOTFOUND;
225565532Snectar	return NS_SUCCESS;
225661877Sume}
225761877Sume
225861877Sume#ifdef YP
225961877Sume/*ARGSUSED*/
226065532Snectarstatic struct addrinfo *
2261157119Sume_yphostent(char *line, const struct addrinfo *pai)
226261877Sume{
226361877Sume	struct addrinfo sentinel, *cur;
226465532Snectar	struct addrinfo hints, *res, *res0;
226561877Sume	int error;
226665532Snectar	char *p = line;
226765532Snectar	const char *addr, *canonname;
226865532Snectar	char *nextline;
226965532Snectar	char *cp;
227061877Sume
227165532Snectar	addr = canonname = NULL;
227265532Snectar
227365532Snectar	memset(&sentinel, 0, sizeof(sentinel));
227461877Sume	cur = &sentinel;
227561877Sume
227665532Snectarnextline:
227765532Snectar	/* terminate line */
227865532Snectar	cp = strchr(p, '\n');
227965532Snectar	if (cp) {
228065532Snectar		*cp++ = '\0';
228165532Snectar		nextline = cp;
228265532Snectar	} else
228365532Snectar		nextline = NULL;
228461877Sume
228565532Snectar	cp = strpbrk(p, " \t");
228665532Snectar	if (cp == NULL) {
228765532Snectar		if (canonname == NULL)
228865532Snectar			return (NULL);
228965532Snectar		else
229065532Snectar			goto done;
229161877Sume	}
229265532Snectar	*cp++ = '\0';
229361877Sume
229465532Snectar	addr = p;
229561877Sume
229665532Snectar	while (cp && *cp) {
229765532Snectar		if (*cp == ' ' || *cp == '\t') {
229865532Snectar			cp++;
229961877Sume			continue;
230065532Snectar		}
230165532Snectar		if (!canonname)
230265532Snectar			canonname = cp;
230365532Snectar		if ((cp = strpbrk(cp, " \t")) != NULL)
230465532Snectar			*cp++ = '\0';
230565532Snectar	}
230661877Sume
2307121474Sume	hints = *pai;
230865532Snectar	hints.ai_flags = AI_NUMERICHOST;
2309121474Sume	error = getaddrinfo(addr, NULL, &hints, &res0);
231065532Snectar	if (error == 0) {
231165532Snectar		for (res = res0; res; res = res->ai_next) {
231265532Snectar			/* cover it up */
231365532Snectar			res->ai_flags = pai->ai_flags;
231461877Sume
231565532Snectar			if (pai->ai_flags & AI_CANONNAME)
231665532Snectar				(void)get_canonname(pai, res, canonname);
231761877Sume		}
231865532Snectar	} else
231965532Snectar		res0 = NULL;
232065532Snectar	if (res0) {
232165532Snectar		cur->ai_next = res0;
232261877Sume		while (cur && cur->ai_next)
232361877Sume			cur = cur->ai_next;
232461877Sume	}
232561877Sume
232665532Snectar	if (nextline) {
232765532Snectar		p = nextline;
232865532Snectar		goto nextline;
232965532Snectar	}
233061877Sume
233165532Snectardone:
233265532Snectar	return sentinel.ai_next;
233361877Sume}
233465532Snectar
233565532Snectar/*ARGSUSED*/
233665532Snectarstatic int
2337157119Sume_yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
233865532Snectar{
233965532Snectar	struct addrinfo sentinel, *cur;
234065532Snectar	struct addrinfo *ai = NULL;
2341144679Sume	char *ypbuf;
2342144679Sume	int ypbuflen, r;
234365532Snectar	const char *name;
234465532Snectar	const struct addrinfo *pai;
2345144679Sume	char *ypdomain;
234665532Snectar
2347144679Sume	if (_yp_check(&ypdomain) == 0)
2348144679Sume		return NS_UNAVAIL;
2349144679Sume
235065532Snectar	name = va_arg(ap, char *);
235165532Snectar	pai = va_arg(ap, const struct addrinfo *);
235265532Snectar
235365532Snectar	memset(&sentinel, 0, sizeof(sentinel));
235465532Snectar	cur = &sentinel;
235565532Snectar
235665532Snectar	/* hosts.byname is only for IPv4 (Solaris8) */
235765532Snectar	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
2358144679Sume		r = yp_match(ypdomain, "hosts.byname", name,
2359144679Sume			(int)strlen(name), &ypbuf, &ypbuflen);
236065532Snectar		if (r == 0) {
236165532Snectar			struct addrinfo ai4;
236265532Snectar
236365532Snectar			ai4 = *pai;
236465532Snectar			ai4.ai_family = AF_INET;
2365144679Sume			ai = _yphostent(ypbuf, &ai4);
236665532Snectar			if (ai) {
236765532Snectar				cur->ai_next = ai;
236865532Snectar				while (cur && cur->ai_next)
236965532Snectar					cur = cur->ai_next;
237065532Snectar			}
2371146190Sume			free(ypbuf);
237265532Snectar		}
237365532Snectar	}
237465532Snectar
237565532Snectar	/* ipnodes.byname can hold both IPv4/v6 */
2376144679Sume	r = yp_match(ypdomain, "ipnodes.byname", name,
2377144679Sume		(int)strlen(name), &ypbuf, &ypbuflen);
237865532Snectar	if (r == 0) {
2379144679Sume		ai = _yphostent(ypbuf, pai);
2380144679Sume		if (ai)
238165532Snectar			cur->ai_next = ai;
2382144679Sume		free(ypbuf);
238365532Snectar	}
238465532Snectar
238565532Snectar	if (sentinel.ai_next == NULL) {
2386156960Sume		RES_SET_H_ERRNO(__res_state(), HOST_NOT_FOUND);
238765532Snectar		return NS_NOTFOUND;
238865532Snectar	}
238965532Snectar	*((struct addrinfo **)rv) = sentinel.ai_next;
239065532Snectar	return NS_SUCCESS;
239165532Snectar}
239261877Sume#endif
239361877Sume
239461877Sume/* resolver logic */
239561877Sume
239661877Sume/*
239761877Sume * Formulate a normal query, send, and await answer.
239861877Sume * Returned answer is placed in supplied buffer "answer".
239961877Sume * Perform preliminary check of answer, returning success only
240061877Sume * if no error is indicated and the answer count is nonzero.
240161877Sume * Return the size of the response on success, -1 on error.
240261877Sume * Error number is left in h_errno.
240361877Sume *
240461877Sume * Caller must parse answer and determine whether it answers the question.
240561877Sume */
240661877Sumestatic int
2407157119Sumeres_queryN(const char *name, struct res_target *target, res_state res)
240861877Sume{
2409103357Sume	u_char *buf;
241061877Sume	HEADER *hp;
241161877Sume	int n;
2412157203Sume	u_int oflags;
241361877Sume	struct res_target *t;
241461877Sume	int rcode;
241561877Sume	int ancount;
241661877Sume
241761877Sume	rcode = NOERROR;
241861877Sume	ancount = 0;
241961877Sume
2420103357Sume	buf = malloc(MAXPACKET);
2421103357Sume	if (!buf) {
2422156960Sume		RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2423103357Sume		return -1;
2424103357Sume	}
2425103357Sume
242661877Sume	for (t = target; t; t = t->next) {
242761877Sume		int class, type;
242861877Sume		u_char *answer;
242961877Sume		int anslen;
243061877Sume
243161877Sume		hp = (HEADER *)(void *)t->answer;
243261877Sume
243361877Sume		/* make it easier... */
243462614Sitojun		class = t->qclass;
243562614Sitojun		type = t->qtype;
243661877Sume		answer = t->answer;
243761877Sume		anslen = t->anslen;
2438157203Sume
2439157203Sume		oflags = res->_flags;
2440157203Sume
2441157203Sumeagain:
2442157203Sume		hp->rcode = NOERROR;	/* default */
2443157203Sume
244461877Sume#ifdef DEBUG
2445156960Sume		if (res->options & RES_DEBUG)
244661877Sume			printf(";; res_query(%s, %d, %d)\n", name, class, type);
244761877Sume#endif
244861877Sume
2449156960Sume		n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2450103357Sume		    buf, MAXPACKET);
2451157203Sume		if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 &&
2452157203Sume		    (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U)
2453156960Sume			n = res_nopt(res, n, buf, MAXPACKET, anslen);
245461877Sume		if (n <= 0) {
245561877Sume#ifdef DEBUG
2456156960Sume			if (res->options & RES_DEBUG)
245761877Sume				printf(";; res_query: mkquery failed\n");
245861877Sume#endif
2459103357Sume			free(buf);
2460156960Sume			RES_SET_H_ERRNO(res, NO_RECOVERY);
246161877Sume			return (n);
246261877Sume		}
2463156960Sume		n = res_nsend(res, buf, n, answer, anslen);
246461877Sume		if (n < 0) {
2465157203Sume			/*
2466157203Sume			 * if the query choked with EDNS0, retry
2467157203Sume			 * without EDNS0
2468157203Sume			 */
2469157203Sume			if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC))
2470157203Sume			    != 0U &&
2471157203Sume			    ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) {
2472157203Sume				res->_flags |= RES_F_EDNS0ERR;
2473157203Sume				if (res->options & RES_DEBUG)
2474157203Sume					printf(";; res_nquery: retry without EDNS0\n");
2475157203Sume				goto again;
2476157203Sume			}
2477157203Sume			rcode = hp->rcode;	/* record most recent error */
247861877Sume#ifdef DEBUG
2479156960Sume			if (res->options & RES_DEBUG)
248061877Sume				printf(";; res_query: send error\n");
248161877Sume#endif
2482157203Sume			continue;
248361877Sume		}
248461877Sume
2485157081Sume		if (n > anslen)
2486103350Snectar			hp->rcode = FORMERR; /* XXX not very informative */
2487157203Sume		if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
248861877Sume			rcode = hp->rcode;	/* record most recent error */
248961877Sume#ifdef DEBUG
2490156960Sume			if (res->options & RES_DEBUG)
2491105940Sume				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
249261877Sume				    ntohs(hp->ancount));
249361877Sume#endif
249461877Sume			continue;
249561877Sume		}
249661877Sume
249761877Sume		ancount += ntohs(hp->ancount);
249861877Sume
249961877Sume		t->n = n;
250061877Sume	}
250161877Sume
2502103357Sume	free(buf);
2503103357Sume
250461877Sume	if (ancount == 0) {
250561877Sume		switch (rcode) {
250661877Sume		case NXDOMAIN:
2507156960Sume			RES_SET_H_ERRNO(res, HOST_NOT_FOUND);
250861877Sume			break;
250961877Sume		case SERVFAIL:
2510156960Sume			RES_SET_H_ERRNO(res, TRY_AGAIN);
251161877Sume			break;
251261877Sume		case NOERROR:
2513156960Sume			RES_SET_H_ERRNO(res, NO_DATA);
251461877Sume			break;
251561877Sume		case FORMERR:
251661877Sume		case NOTIMP:
251761877Sume		case REFUSED:
251861877Sume		default:
2519156960Sume			RES_SET_H_ERRNO(res, NO_RECOVERY);
252061877Sume			break;
252161877Sume		}
252261877Sume		return (-1);
252361877Sume	}
252461877Sume	return (ancount);
252561877Sume}
252661877Sume
252761877Sume/*
252861877Sume * Formulate a normal query, send, and retrieve answer in supplied buffer.
252961877Sume * Return the size of the response on success, -1 on error.
253061877Sume * If enabled, implement search rules until answer or unrecoverable failure
253161877Sume * is detected.  Error code, if any, is left in h_errno.
253261877Sume */
253361877Sumestatic int
2534157119Sumeres_searchN(const char *name, struct res_target *target, res_state res)
253561877Sume{
253661877Sume	const char *cp, * const *domain;
253761877Sume	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
253861877Sume	u_int dots;
253961877Sume	int trailing_dot, ret, saved_herrno;
2540155983Sume	int got_nodata = 0, got_servfail = 0, root_on_list = 0;
2541155983Sume	int tried_as_is = 0;
2542155983Sume	int searched = 0;
2543145113Sume	char abuf[MAXDNAME];
254461877Sume
254561877Sume	errno = 0;
2546156960Sume	RES_SET_H_ERRNO(res, HOST_NOT_FOUND); /* default, if we never query */
254761877Sume	dots = 0;
254861877Sume	for (cp = name; *cp; cp++)
254961877Sume		dots += (*cp == '.');
255061877Sume	trailing_dot = 0;
255161877Sume	if (cp > name && *--cp == '.')
255261877Sume		trailing_dot++;
255361877Sume
255461877Sume	/*
255561877Sume	 * if there aren't any dots, it could be a user-level alias
255661877Sume	 */
2557156960Sume	if (!dots &&
2558156960Sume	    (cp = res_hostalias(res, name, abuf, sizeof(abuf))) != NULL)
2559156960Sume		return (res_queryN(cp, target, res));
256061877Sume
256161877Sume	/*
2562155983Sume	 * If there are enough dots in the name, let's just give it a
2563155983Sume	 * try 'as is'. The threshold can be set with the "ndots" option.
2564155983Sume	 * Also, query 'as is', if there is a trailing dot in the name.
256561877Sume	 */
256661877Sume	saved_herrno = -1;
2567156960Sume	if (dots >= res->ndots || trailing_dot) {
2568156960Sume		ret = res_querydomainN(name, NULL, target, res);
2569155983Sume		if (ret > 0 || trailing_dot)
257061877Sume			return (ret);
2571156155Sume		if (errno == ECONNREFUSED) {
2572156960Sume			RES_SET_H_ERRNO(res, TRY_AGAIN);
2573156155Sume			return (-1);
2574156155Sume		}
2575156960Sume		switch (res->res_h_errno) {
2576156155Sume		case NO_DATA:
2577156155Sume		case HOST_NOT_FOUND:
2578156155Sume			break;
2579157093Sume		case TRY_AGAIN:
2580157093Sume			if (hp->rcode == SERVFAIL)
2581157093Sume				break;
2582157093Sume			/* FALLTHROUGH */
2583156155Sume		default:
2584156155Sume			return (-1);
2585156155Sume		}
2586156960Sume		saved_herrno = res->res_h_errno;
258761877Sume		tried_as_is++;
258861877Sume	}
258961877Sume
259061877Sume	/*
259161877Sume	 * We do at least one level of search if
259261877Sume	 *	- there is no dot and RES_DEFNAME is set, or
259361877Sume	 *	- there is at least one dot, there is no trailing dot,
259461877Sume	 *	  and RES_DNSRCH is set.
259561877Sume	 */
2596156960Sume	if ((!dots && (res->options & RES_DEFNAMES)) ||
2597156960Sume	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
259861877Sume		int done = 0;
259961877Sume
2600156960Sume		for (domain = (const char * const *)res->dnsrch;
260161877Sume		   *domain && !done;
260261877Sume		   domain++) {
2603155983Sume			searched = 1;
260461877Sume
2605155983Sume			if (domain[0][0] == '\0' ||
2606155983Sume			    (domain[0][0] == '.' && domain[0][1] == '\0'))
2607155983Sume				root_on_list++;
2608155983Sume
2609155983Sume			if (root_on_list && tried_as_is)
2610155983Sume				continue;
2611155983Sume
2612156960Sume			ret = res_querydomainN(name, *domain, target, res);
261361877Sume			if (ret > 0)
261461877Sume				return (ret);
261561877Sume
261661877Sume			/*
261761877Sume			 * If no server present, give up.
261861877Sume			 * If name isn't found in this domain,
261961877Sume			 * keep trying higher domains in the search list
262061877Sume			 * (if that's enabled).
262161877Sume			 * On a NO_DATA error, keep trying, otherwise
262261877Sume			 * a wildcard entry of another type could keep us
262361877Sume			 * from finding this entry higher in the domain.
262461877Sume			 * If we get some other error (negative answer or
262561877Sume			 * server failure), then stop searching up,
262661877Sume			 * but try the input name below in case it's
262761877Sume			 * fully-qualified.
262861877Sume			 */
262961877Sume			if (errno == ECONNREFUSED) {
2630156960Sume				RES_SET_H_ERRNO(res, TRY_AGAIN);
263161877Sume				return (-1);
263261877Sume			}
263361877Sume
2634156960Sume			switch (res->res_h_errno) {
263561877Sume			case NO_DATA:
263661877Sume				got_nodata++;
263761877Sume				/* FALLTHROUGH */
263861877Sume			case HOST_NOT_FOUND:
263961877Sume				/* keep trying */
264061877Sume				break;
264161877Sume			case TRY_AGAIN:
2642157093Sume				got_servfail++;
264361877Sume				if (hp->rcode == SERVFAIL) {
264461877Sume					/* try next search element, if any */
264561877Sume					break;
264661877Sume				}
264761877Sume				/* FALLTHROUGH */
264861877Sume			default:
264961877Sume				/* anything else implies that we're done */
265061877Sume				done++;
265161877Sume			}
265261877Sume			/*
265361877Sume			 * if we got here for some reason other than DNSRCH,
265461877Sume			 * we only wanted one iteration of the loop, so stop.
265561877Sume			 */
2656156960Sume			if (!(res->options & RES_DNSRCH))
265761877Sume			        done++;
265861877Sume		}
265961877Sume	}
266061877Sume
2661156960Sume	switch (res->res_h_errno) {
2662156155Sume	case NO_DATA:
2663156155Sume	case HOST_NOT_FOUND:
2664156155Sume		break;
2665157093Sume	case TRY_AGAIN:
2666157093Sume		if (hp->rcode == SERVFAIL)
2667157093Sume			break;
2668157093Sume		/* FALLTHROUGH */
2669156155Sume	default:
2670156155Sume		goto giveup;
2671156155Sume	}
2672156155Sume
267361877Sume	/*
2674155983Sume	 * If the query has not already been tried as is then try it
2675155983Sume	 * unless RES_NOTLDQUERY is set and there were no dots.
267661877Sume	 */
2677156960Sume	if ((dots || !searched || !(res->options & RES_NOTLDQUERY)) &&
2678155983Sume	    !(tried_as_is || root_on_list)) {
2679156960Sume		ret = res_querydomainN(name, NULL, target, res);
268061877Sume		if (ret > 0)
268161877Sume			return (ret);
268261877Sume	}
268361877Sume
268461877Sume	/*
268561877Sume	 * if we got here, we didn't satisfy the search.
268661877Sume	 * if we did an initial full query, return that query's h_errno
268761877Sume	 * (note that we wouldn't be here if that query had succeeded).
268861877Sume	 * else if we ever got a nodata, send that back as the reason.
268961877Sume	 * else send back meaningless h_errno, that being the one from
269061877Sume	 * the last DNSRCH we did.
269161877Sume	 */
2692156155Sumegiveup:
269361877Sume	if (saved_herrno != -1)
2694156960Sume		RES_SET_H_ERRNO(res, saved_herrno);
269561877Sume	else if (got_nodata)
2696156960Sume		RES_SET_H_ERRNO(res, NO_DATA);
269761877Sume	else if (got_servfail)
2698156960Sume		RES_SET_H_ERRNO(res, TRY_AGAIN);
269961877Sume	return (-1);
270061877Sume}
270161877Sume
270261877Sume/*
270361877Sume * Perform a call on res_query on the concatenation of name and domain,
270461877Sume * removing a trailing dot from name if domain is NULL.
270561877Sume */
270661877Sumestatic int
2707157119Sumeres_querydomainN(const char *name, const char *domain,
2708157119Sume    struct res_target *target, res_state res)
270961877Sume{
271061877Sume	char nbuf[MAXDNAME];
271161877Sume	const char *longname = nbuf;
271261877Sume	size_t n, d;
271361877Sume
271461877Sume#ifdef DEBUG
2715156960Sume	if (res->options & RES_DEBUG)
271661877Sume		printf(";; res_querydomain(%s, %s)\n",
271761877Sume			name, domain?domain:"<Nil>");
271861877Sume#endif
271961877Sume	if (domain == NULL) {
272061877Sume		/*
272161877Sume		 * Check for trailing '.';
272261877Sume		 * copy without '.' if present.
272361877Sume		 */
272461877Sume		n = strlen(name);
272561877Sume		if (n >= MAXDNAME) {
2726156960Sume			RES_SET_H_ERRNO(res, NO_RECOVERY);
272761877Sume			return (-1);
272861877Sume		}
272961877Sume		if (n > 0 && name[--n] == '.') {
273061877Sume			strncpy(nbuf, name, n);
273161877Sume			nbuf[n] = '\0';
273261877Sume		} else
273361877Sume			longname = name;
273461877Sume	} else {
273561877Sume		n = strlen(name);
273661877Sume		d = strlen(domain);
273761877Sume		if (n + d + 1 >= MAXDNAME) {
2738156960Sume			RES_SET_H_ERRNO(res, NO_RECOVERY);
273961877Sume			return (-1);
274061877Sume		}
2741105940Sume		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
274261877Sume	}
2743156960Sume	return (res_queryN(longname, target, res));
274461877Sume}
2745