getaddrinfo.c revision 144708
1227825Stheraven/*	$KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $	*/
2227825Stheraven
3227825Stheraven/*
4227825Stheraven * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5227825Stheraven * All rights reserved.
6227825Stheraven *
7227825Stheraven * Redistribution and use in source and binary forms, with or without
8227825Stheraven * modification, are permitted provided that the following conditions
9227825Stheraven * are met:
10227825Stheraven * 1. Redistributions of source code must retain the above copyright
11227825Stheraven *    notice, this list of conditions and the following disclaimer.
12227825Stheraven * 2. Redistributions in binary form must reproduce the above copyright
13227825Stheraven *    notice, this list of conditions and the following disclaimer in the
14227825Stheraven *    documentation and/or other materials provided with the distribution.
15227825Stheraven * 3. Neither the name of the project nor the names of its contributors
16227825Stheraven *    may be used to endorse or promote products derived from this software
17232950Stheraven *    without specific prior written permission.
18232950Stheraven *
19227825Stheraven * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20227825Stheraven * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21227825Stheraven * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22227825Stheraven * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23227825Stheraven * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24227825Stheraven * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25243376Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26232950Stheraven * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27227825Stheraven * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28227825Stheraven * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29227825Stheraven * SUCH DAMAGE.
30227825Stheraven */
31227825Stheraven
32227825Stheraven/*
33227825Stheraven * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
34232950Stheraven *
35227825Stheraven * Issues to be discussed:
36227825Stheraven * - Thread safe-ness must be checked.
37232950Stheraven * - Return values.  There are nonstandard return values defined and used
38232950Stheraven *   in the source code.  This is because RFC2553 is silent about which error
39227825Stheraven *   code must be returned for which situation.
40227825Stheraven * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
41227825Stheraven *   invalid.  current code - SEGV on freeaddrinfo(NULL)
42227825Stheraven *
43262801Sdim * Note:
44232950Stheraven * - The code filters out AFs that are not supported by the kernel,
45227825Stheraven *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
46232950Stheraven *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
47227825Stheraven *   in ai_flags?
48232950Stheraven * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
49232950Stheraven *   (1) what should we do against numeric hostname (2) what should we do
50227825Stheraven *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
51227825Stheraven *   non-loopback address configured?  global address configured?
52227825Stheraven *
53227825Stheraven * OS specific notes for netbsd/openbsd/freebsd4/bsdi4:
54227825Stheraven * - To avoid search order issue, we have a big amount of code duplicate
55227825Stheraven *   from gethnamaddr.c and some other places.  The issues that there's no
56227825Stheraven *   lower layer function to lookup "IPv4 or IPv6" record.  Calling
57227825Stheraven *   gethostbyname2 from getaddrinfo will end up in wrong search order, as
58227825Stheraven *   presented above.
59227825Stheraven *
60227825Stheraven * OS specific notes for freebsd4:
61227825Stheraven * - FreeBSD supported $GAI.  The code does not.
62227825Stheraven * - FreeBSD allowed classful IPv4 numeric (127.1), the code does not.
63227825Stheraven */
64227825Stheraven
65227825Stheraven#include <sys/cdefs.h>
66227825Stheraven__FBSDID("$FreeBSD: head/lib/libc/net/getaddrinfo.c 144708 2005-04-06 12:45:51Z ume $");
67227825Stheraven
68227825Stheraven#include "namespace.h"
69227825Stheraven#include <sys/types.h>
70227825Stheraven#include <sys/param.h>
71232950Stheraven#include <sys/socket.h>
72232950Stheraven#include <net/if.h>
73227825Stheraven#include <netinet/in.h>
74227825Stheraven#include <sys/queue.h>
75227825Stheraven#ifdef INET6
76227825Stheraven#include <net/if_var.h>
77227825Stheraven#include <sys/sysctl.h>
78227825Stheraven#include <sys/ioctl.h>
79232950Stheraven#include <netinet6/in6_var.h>	/* XXX */
80232950Stheraven#endif
81227825Stheraven#include <arpa/inet.h>
82227825Stheraven#include <arpa/nameser.h>
83227825Stheraven#include <rpc/rpc.h>
84250514Sdim#include <rpcsvc/yp_prot.h>
85262801Sdim#include <rpcsvc/ypclnt.h>
86250514Sdim#include <netdb.h>
87250514Sdim#include <pthread.h>
88250514Sdim#include <resolv.h>
89250514Sdim#include <string.h>
90250514Sdim#include <stdlib.h>
91250514Sdim#include <stddef.h>
92250514Sdim#include <ctype.h>
93250514Sdim#include <unistd.h>
94232950Stheraven#include <stdio.h>
95262801Sdim#include <errno.h>
96227825Stheraven
97232950Stheraven#include "res_config.h"
98227825Stheraven
99227825Stheraven#ifdef DEBUG
100227825Stheraven#include <syslog.h>
101227825Stheraven#endif
102227825Stheraven
103227825Stheraven#include <stdarg.h>
104232950Stheraven#include <nsswitch.h>
105262801Sdim#include "un-namespace.h"
106227825Stheraven#include "libc_private.h"
107232950Stheraven
108227825Stheraven#if defined(__KAME__) && defined(INET6)
109227825Stheraven# define FAITH
110227825Stheraven#endif
111227825Stheraven
112227825Stheraven#define SUCCESS 0
113227825Stheraven#define ANY 0
114232950Stheraven#define YES 1
115262801Sdim#define NO  0
116227825Stheraven
117232950Stheravenstatic const char in_addrany[] = { 0, 0, 0, 0 };
118227825Stheravenstatic const char in_loopback[] = { 127, 0, 0, 1 };
119227825Stheraven#ifdef INET6
120227825Stheravenstatic const char in6_addrany[] = {
121227825Stheraven	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
122227825Stheraven};
123227825Stheravenstatic const char in6_loopback[] = {
124232950Stheraven	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
125227825Stheraven};
126227825Stheraven#endif
127232950Stheraven
128232950Stheravenstruct policyqueue {
129227825Stheraven	TAILQ_ENTRY(policyqueue) pc_entry;
130227825Stheraven#ifdef INET6
131227825Stheraven	struct in6_addrpolicy pc_policy;
132227825Stheraven#endif
133262801Sdim};
134232950StheravenTAILQ_HEAD(policyhead, policyqueue);
135227825Stheraven
136232950Stheravenstatic const struct afd {
137227825Stheraven	int a_af;
138232950Stheraven	int a_addrlen;
139227825Stheraven	int a_socklen;
140227825Stheraven	int a_off;
141232950Stheraven	const char *a_addrany;
142227825Stheraven	const char *a_loopback;
143227825Stheraven	int a_scoped;
144243376Sdim} afdl [] = {
145227825Stheraven#ifdef INET6
146227825Stheraven#define	N_INET6 0
147232950Stheraven	{PF_INET6, sizeof(struct in6_addr),
148232950Stheraven	 sizeof(struct sockaddr_in6),
149227825Stheraven	 offsetof(struct sockaddr_in6, sin6_addr),
150227825Stheraven	 in6_addrany, in6_loopback, 1},
151243376Sdim#define	N_INET 1
152227825Stheraven#else
153227825Stheraven#define	N_INET 0
154227825Stheraven#endif
155227825Stheraven	{PF_INET, sizeof(struct in_addr),
156227825Stheraven	 sizeof(struct sockaddr_in),
157227825Stheraven	 offsetof(struct sockaddr_in, sin_addr),
158227825Stheraven	 in_addrany, in_loopback, 0},
159227825Stheraven	{0, 0, 0, 0, NULL, NULL, 0},
160243376Sdim};
161243376Sdim
162243376Sdimstruct explore {
163227825Stheraven	int e_af;
164243376Sdim	int e_socktype;
165227825Stheraven	int e_protocol;
166227825Stheraven	const char *e_protostr;
167227825Stheraven	int e_wild;
168227825Stheraven#define WILD_AF(ex)		((ex)->e_wild & 0x01)
169227825Stheraven#define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
170227825Stheraven#define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
171227825Stheraven};
172227825Stheraven
173227825Stheravenstatic const struct explore explore[] = {
174227825Stheraven#if 0
175227825Stheraven	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
176262801Sdim#endif
177262801Sdim#ifdef INET6
178227825Stheraven	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
179227825Stheraven	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
180227825Stheraven	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
181227825Stheraven#endif
182227825Stheraven	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
183227825Stheraven	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
184227825Stheraven	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
185227825Stheraven	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
186227825Stheraven	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
187227825Stheraven	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
188227825Stheraven	{ -1, 0, 0, NULL, 0 },
189227825Stheraven};
190227825Stheraven
191227825Stheraven#ifdef INET6
192227825Stheraven#define PTON_MAX	16
193227825Stheraven#else
194227825Stheraven#define PTON_MAX	4
195227825Stheraven#endif
196243376Sdim
197243376Sdim#define AIO_SRCFLAG_DEPRECATED	0x1
198243376Sdim
199227825Stheravenstruct ai_order {
200243376Sdim	union {
201227825Stheraven		struct sockaddr_storage aiou_ss;
202227825Stheraven		struct sockaddr aiou_sa;
203227825Stheraven	} aio_src_un;
204227825Stheraven#define aio_srcsa aio_src_un.aiou_sa
205227825Stheraven	u_int32_t aio_srcflag;
206227825Stheraven	int aio_srcscope;
207227825Stheraven	int aio_dstscope;
208227825Stheraven	struct policyqueue *aio_srcpolicy;
209243376Sdim	struct policyqueue *aio_dstpolicy;
210227825Stheraven	struct addrinfo *aio_ai;
211227825Stheraven	int aio_matchlen;
212262801Sdim};
213262801Sdim
214227825Stheravenstatic const ns_src default_dns_files[] = {
215227825Stheraven	{ NSSRC_FILES, 	NS_SUCCESS },
216227825Stheraven	{ NSSRC_DNS, 	NS_SUCCESS },
217227825Stheraven	{ 0 }
218227825Stheraven};
219227825Stheraven
220227825Stheravenstruct res_target {
221227825Stheraven	struct res_target *next;
222227825Stheraven	const char *name;	/* domain name */
223227825Stheraven	int qclass, qtype;	/* class and type of query */
224227825Stheraven	u_char *answer;		/* buffer to put answer */
225227825Stheraven	int anslen;		/* size of answer buffer */
226227825Stheraven	int n;			/* result length */
227227825Stheraven};
228243376Sdim
229227825Stheraven#define MAXPACKET	(64*1024)
230227825Stheraven
231227825Stheraventypedef union {
232227825Stheraven	HEADER hdr;
233227825Stheraven	u_char buf[MAXPACKET];
234227825Stheraven} querybuf;
235243376Sdim
236227825Stheravenstatic int str2number(const char *);
237243376Sdimstatic int explore_null(const struct addrinfo *,
238243376Sdim	const char *, struct addrinfo **);
239227825Stheravenstatic int explore_numeric(const struct addrinfo *, const char *,
240227825Stheraven	const char *, struct addrinfo **, const char *);
241232950Stheravenstatic int explore_numeric_scope(const struct addrinfo *, const char *,
242232950Stheraven	const char *, struct addrinfo **);
243227825Stheravenstatic int get_canonname(const struct addrinfo *,
244227825Stheraven	struct addrinfo *, const char *);
245227825Stheravenstatic struct addrinfo *get_ai(const struct addrinfo *,
246227825Stheraven	const struct afd *, const char *);
247243376Sdimstatic int get_portmatch(const struct addrinfo *, const char *);
248243376Sdimstatic int get_port(struct addrinfo *, const char *, int);
249243376Sdimstatic const struct afd *find_afd(int);
250227825Stheravenstatic int addrconfig(struct addrinfo *);
251243376Sdimstatic void set_source(struct ai_order *, struct policyhead *);
252227825Stheravenstatic int comp_dst(const void *, const void *);
253227825Stheraven#ifdef INET6
254227825Stheravenstatic int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
255227825Stheraven#endif
256227825Stheravenstatic int gai_addr2scopetype(struct sockaddr *);
257227825Stheraven
258227825Stheravenstatic int explore_fqdn(const struct addrinfo *, const char *,
259227825Stheraven	const char *, struct addrinfo **);
260227825Stheraven
261227825Stheravenstatic int reorder(struct addrinfo *);
262227825Stheravenstatic int get_addrselectpolicy(struct policyhead *);
263227825Stheravenstatic void free_addrselectpolicy(struct policyhead *);
264227825Stheravenstatic struct policyqueue *match_addrselectpolicy(struct sockaddr *,
265227825Stheraven	struct policyhead *);
266227825Stheravenstatic int matchlen(struct sockaddr *, struct sockaddr *);
267227825Stheraven
268227825Stheravenstatic struct addrinfo *getanswer(const querybuf *, int, const char *, int,
269227825Stheraven	const struct addrinfo *);
270227825Stheraven#if defined(RESOLVSORT)
271227825Stheravenstatic int addr4sort(struct addrinfo *);
272227825Stheraven#endif
273227825Stheravenstatic int _dns_getaddrinfo(void *, void *, va_list);
274227825Stheravenstatic void _sethtent(FILE **);
275227825Stheravenstatic void _endhtent(FILE **);
276227825Stheravenstatic struct addrinfo *_gethtent(FILE **, const char *,
277227825Stheraven	const struct addrinfo *);
278243376Sdimstatic int _files_getaddrinfo(void *, void *, va_list);
279243376Sdim#ifdef YP
280243376Sdimstatic struct addrinfo *_yphostent(char *, const struct addrinfo *);
281227825Stheravenstatic int _yp_getaddrinfo(void *, void *, va_list);
282243376Sdim#endif
283227825Stheraven
284227825Stheravenstatic int res_queryN(const char *, struct res_target *);
285227825Stheravenstatic int res_searchN(const char *, struct res_target *);
286227825Stheravenstatic int res_querydomainN(const char *, const char *,
287227825Stheraven	struct res_target *);
288227825Stheraven
289227825Stheraven/*
290227825Stheraven * XXX: Many dependencies are not thread-safe.  So, we share lock between
291227825Stheraven * getaddrinfo() and getipnodeby*().  Still, we cannot use
292227825Stheraven * getaddrinfo() and getipnodeby*() in conjunction with other
293243376Sdim * functions which call them.
294227825Stheraven */
295227825Stheravenpthread_mutex_t __getaddrinfo_thread_lock = PTHREAD_MUTEX_INITIALIZER;
296227825Stheraven#define THREAD_LOCK() \
297227825Stheraven	if (__isthreaded) _pthread_mutex_lock(&__getaddrinfo_thread_lock);
298227825Stheraven#define THREAD_UNLOCK() \
299227825Stheraven	if (__isthreaded) _pthread_mutex_unlock(&__getaddrinfo_thread_lock);
300227825Stheraven
301227825Stheraven/* XXX macros that make external reference is BAD. */
302227825Stheraven
303227825Stheraven#define GET_AI(ai, afd, addr) \
304243376Sdimdo { \
305227825Stheraven	/* external reference: pai, error, and label free */ \
306227825Stheraven	(ai) = get_ai(pai, (afd), (addr)); \
307227825Stheraven	if ((ai) == NULL) { \
308227825Stheraven		error = EAI_MEMORY; \
309243376Sdim		goto free; \
310227825Stheraven	} \
311243376Sdim} while (/*CONSTCOND*/0)
312243376Sdim
313227825Stheraven#define GET_PORT(ai, serv) \
314227825Stheravendo { \
315232950Stheraven	/* external reference: error and label free */ \
316232950Stheraven	error = get_port((ai), (serv), 0); \
317227825Stheraven	if (error != 0) \
318227825Stheraven		goto free; \
319227825Stheraven} while (/*CONSTCOND*/0)
320227825Stheraven
321232950Stheraven#define GET_CANONNAME(ai, str) \
322227825Stheravendo { \
323232950Stheraven	/* external reference: pai, error and label free */ \
324227825Stheraven	error = get_canonname(pai, (ai), (str)); \
325232950Stheraven	if (error != 0) \
326227825Stheraven		goto free; \
327227825Stheraven} while (/*CONSTCOND*/0)
328227825Stheraven
329227825Stheraven#define ERR(err) \
330227825Stheravendo { \
331227825Stheraven	/* external reference: error, and label bad */ \
332227825Stheraven	error = (err); \
333227825Stheraven	goto bad; \
334227825Stheraven	/*NOTREACHED*/ \
335227825Stheraven} while (/*CONSTCOND*/0)
336227825Stheraven
337227825Stheraven#define MATCH_FAMILY(x, y, w) \
338227825Stheraven	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
339227825Stheraven#define MATCH(x, y, w) \
340253222Sdim	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
341227825Stheraven
342227825Stheravenvoid
343227825Stheravenfreeaddrinfo(ai)
344227825Stheraven	struct addrinfo *ai;
345227825Stheraven{
346227825Stheraven	struct addrinfo *next;
347227825Stheraven
348227825Stheraven	do {
349227825Stheraven		next = ai->ai_next;
350227825Stheraven		if (ai->ai_canonname)
351232950Stheraven			free(ai->ai_canonname);
352227825Stheraven		/* no need to free(ai->ai_addr) */
353232950Stheraven		free(ai);
354227825Stheraven		ai = next;
355232950Stheraven	} while (ai);
356227825Stheraven}
357227825Stheraven
358227825Stheravenstatic int
359227825Stheravenstr2number(p)
360227825Stheraven	const char *p;
361227825Stheraven{
362227825Stheraven	char *ep;
363227825Stheraven	unsigned long v;
364227825Stheraven
365227825Stheraven	if (*p == '\0')
366227825Stheraven		return -1;
367227825Stheraven	ep = NULL;
368227825Stheraven	errno = 0;
369227825Stheraven	v = strtoul(p, &ep, 10);
370253222Sdim	if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
371227825Stheraven		return v;
372227825Stheraven	else
373227825Stheraven		return -1;
374227825Stheraven}
375227825Stheraven
376227825Stheravenint
377227825Stheravengetaddrinfo(hostname, servname, hints, res)
378227825Stheraven	const char *hostname, *servname;
379227825Stheraven	const struct addrinfo *hints;
380227825Stheraven	struct addrinfo **res;
381232950Stheraven{
382262801Sdim	struct addrinfo sentinel;
383227825Stheraven	struct addrinfo *cur;
384232950Stheraven	int error = 0;
385227825Stheraven	struct addrinfo ai;
386227825Stheraven	struct addrinfo ai0;
387227825Stheraven	struct addrinfo *pai;
388227825Stheraven	const struct explore *ex;
389227825Stheraven	int numeric = 0;
390227825Stheraven
391227825Stheraven	memset(&sentinel, 0, sizeof(sentinel));
392227825Stheraven	cur = &sentinel;
393227825Stheraven	pai = &ai;
394227825Stheraven	pai->ai_flags = 0;
395227825Stheraven	pai->ai_family = PF_UNSPEC;
396227825Stheraven	pai->ai_socktype = ANY;
397232950Stheraven	pai->ai_protocol = ANY;
398227825Stheraven	pai->ai_addrlen = 0;
399227825Stheraven	pai->ai_canonname = NULL;
400232950Stheraven	pai->ai_addr = NULL;
401227825Stheraven	pai->ai_next = NULL;
402232950Stheraven
403227825Stheraven	if (hostname == NULL && servname == NULL)
404227825Stheraven		return EAI_NONAME;
405227825Stheraven	if (hints) {
406227825Stheraven		/* error check for hints */
407232950Stheraven		if (hints->ai_addrlen || hints->ai_canonname ||
408232950Stheraven		    hints->ai_addr || hints->ai_next)
409232950Stheraven			ERR(EAI_BADHINTS); /* xxx */
410232950Stheraven		if (hints->ai_flags & ~AI_MASK)
411227825Stheraven			ERR(EAI_BADFLAGS);
412232950Stheraven		switch (hints->ai_family) {
413227825Stheraven		case PF_UNSPEC:
414227825Stheraven		case PF_INET:
415227825Stheraven#ifdef INET6
416227825Stheraven		case PF_INET6:
417227825Stheraven#endif
418227825Stheraven			break;
419227825Stheraven		default:
420227825Stheraven			ERR(EAI_FAMILY);
421227825Stheraven		}
422227825Stheraven		memcpy(pai, hints, sizeof(*pai));
423227825Stheraven
424227825Stheraven		/*
425227825Stheraven		 * if both socktype/protocol are specified, check if they
426227825Stheraven		 * are meaningful combination.
427227825Stheraven		 */
428227825Stheraven		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
429227825Stheraven			for (ex = explore; ex->e_af >= 0; ex++) {
430227825Stheraven				if (pai->ai_family != ex->e_af)
431227825Stheraven					continue;
432227825Stheraven				if (ex->e_socktype == ANY)
433227825Stheraven					continue;
434227825Stheraven				if (ex->e_protocol == ANY)
435227825Stheraven					continue;
436227825Stheraven				if (pai->ai_socktype == ex->e_socktype &&
437253222Sdim				    pai->ai_protocol != ex->e_protocol) {
438253222Sdim					ERR(EAI_BADHINTS);
439253222Sdim				}
440227825Stheraven			}
441227825Stheraven		}
442227825Stheraven	}
443227825Stheraven
444227825Stheraven	/*
445227825Stheraven	 * post-2553: AI_ALL and AI_V4MAPPED are effective only against
446227825Stheraven	 * AF_INET6 query.  They need to be ignored if specified in other
447227825Stheraven	 * occassions.
448227825Stheraven	 */
449227825Stheraven	switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
450227825Stheraven	case AI_V4MAPPED:
451227825Stheraven	case AI_ALL | AI_V4MAPPED:
452227825Stheraven		if (pai->ai_family != AF_INET6)
453227825Stheraven			pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
454227825Stheraven		break;
455227825Stheraven	case AI_ALL:
456232950Stheraven#if 1
457232950Stheraven		/* illegal */
458232950Stheraven		ERR(EAI_BADFLAGS);
459232950Stheraven#else
460227825Stheraven		pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
461232950Stheraven#endif
462227825Stheraven		break;
463227825Stheraven	}
464227825Stheraven
465227825Stheraven	/*
466227825Stheraven	 * check for special cases.  (1) numeric servname is disallowed if
467227825Stheraven	 * socktype/protocol are left unspecified. (2) servname is disallowed
468227825Stheraven	 * for raw and other inet{,6} sockets.
469227825Stheraven	 */
470227825Stheraven	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
471227825Stheraven#ifdef PF_INET6
472227825Stheraven	    || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
473227825Stheraven#endif
474227825Stheraven	    ) {
475227825Stheraven		ai0 = *pai;	/* backup *pai */
476227825Stheraven
477227825Stheraven		if (pai->ai_family == PF_UNSPEC) {
478227825Stheraven#ifdef PF_INET6
479227825Stheraven			pai->ai_family = PF_INET6;
480227825Stheraven#else
481227825Stheraven			pai->ai_family = PF_INET;
482227825Stheraven#endif
483227825Stheraven		}
484227825Stheraven		error = get_portmatch(pai, servname);
485227825Stheraven		if (error)
486227825Stheraven			ERR(error);
487227825Stheraven
488227825Stheraven		*pai = ai0;
489227825Stheraven	}
490227825Stheraven
491227825Stheraven	ai0 = *pai;
492227825Stheraven
493227825Stheraven	/* NULL hostname, or numeric hostname */
494227825Stheraven	for (ex = explore; ex->e_af >= 0; ex++) {
495227825Stheraven		*pai = ai0;
496227825Stheraven
497227825Stheraven		/* PF_UNSPEC entries are prepared for DNS queries only */
498227825Stheraven		if (ex->e_af == PF_UNSPEC)
499227825Stheraven			continue;
500227825Stheraven
501227825Stheraven		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
502227825Stheraven			continue;
503227825Stheraven		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
504227825Stheraven			continue;
505227825Stheraven		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
506227825Stheraven			continue;
507227825Stheraven
508227825Stheraven		if (pai->ai_family == PF_UNSPEC)
509227825Stheraven			pai->ai_family = ex->e_af;
510227825Stheraven		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
511227825Stheraven			pai->ai_socktype = ex->e_socktype;
512227825Stheraven		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
513227825Stheraven			pai->ai_protocol = ex->e_protocol;
514227825Stheraven
515227825Stheraven		if (hostname == NULL)
516227825Stheraven			error = explore_null(pai, servname, &cur->ai_next);
517227825Stheraven		else
518227825Stheraven			error = explore_numeric_scope(pai, hostname, servname,
519227825Stheraven			    &cur->ai_next);
520227825Stheraven
521227825Stheraven		if (error)
522227825Stheraven			goto free;
523227825Stheraven
524227825Stheraven		while (cur && cur->ai_next)
525227825Stheraven			cur = cur->ai_next;
526227825Stheraven	}
527227825Stheraven
528227825Stheraven	/*
529227825Stheraven	 * XXX
530227825Stheraven	 * If numreic representation of AF1 can be interpreted as FQDN
531227825Stheraven	 * representation of AF2, we need to think again about the code below.
532227825Stheraven	 */
533227825Stheraven	if (sentinel.ai_next) {
534232950Stheraven		numeric = 1;
535227825Stheraven		goto good;
536232950Stheraven	}
537232950Stheraven
538227825Stheraven	if (hostname == NULL)
539227825Stheraven		ERR(EAI_NONAME);	/* used to be EAI_NODATA */
540227825Stheraven	if (pai->ai_flags & AI_NUMERICHOST)
541227825Stheraven		ERR(EAI_NONAME);
542227825Stheraven
543227825Stheraven	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
544227825Stheraven		ERR(EAI_FAIL);
545227825Stheraven
546232950Stheraven	/*
547232950Stheraven	 * hostname as alphabetical name.
548232950Stheraven	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
549232950Stheraven	 * outer loop by AFs.
550227825Stheraven	 */
551232950Stheraven	for (ex = explore; ex->e_af >= 0; ex++) {
552227825Stheraven		*pai = ai0;
553227825Stheraven
554227825Stheraven		/* require exact match for family field */
555227825Stheraven		if (pai->ai_family != ex->e_af)
556227825Stheraven			continue;
557227825Stheraven
558227825Stheraven		if (!MATCH(pai->ai_socktype, ex->e_socktype,
559227825Stheraven				WILD_SOCKTYPE(ex))) {
560227825Stheraven			continue;
561227825Stheraven		}
562227825Stheraven		if (!MATCH(pai->ai_protocol, ex->e_protocol,
563227825Stheraven				WILD_PROTOCOL(ex))) {
564227825Stheraven			continue;
565227825Stheraven		}
566227825Stheraven
567227825Stheraven		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
568227825Stheraven			pai->ai_socktype = ex->e_socktype;
569227825Stheraven		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
570227825Stheraven			pai->ai_protocol = ex->e_protocol;
571227825Stheraven
572227825Stheraven		error = explore_fqdn(pai, hostname, servname,
573227825Stheraven			&cur->ai_next);
574227825Stheraven
575227825Stheraven		while (cur && cur->ai_next)
576227825Stheraven			cur = cur->ai_next;
577227825Stheraven	}
578253222Sdim
579253222Sdim	/* XXX inhibit errors if we have the result */
580253222Sdim	if (sentinel.ai_next)
581227825Stheraven		error = 0;
582227825Stheraven
583227825Stheravengood:
584227825Stheraven	/*
585227825Stheraven	 * ensure we return either:
586227825Stheraven	 * - error == 0, non-NULL *res
587227825Stheraven	 * - error != 0, NULL *res
588227825Stheraven	 */
589227825Stheraven	if (error == 0) {
590227825Stheraven		if (sentinel.ai_next) {
591227825Stheraven			/*
592227825Stheraven			 * If the returned entry is for an active connection,
593227825Stheraven			 * and the given name is not numeric, reorder the
594227825Stheraven			 * list, so that the application would try the list
595232950Stheraven			 * in the most efficient order.
596232950Stheraven			 */
597232950Stheraven			if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
598232950Stheraven				if (!numeric)
599227825Stheraven					(void)reorder(&sentinel);
600232950Stheraven			}
601227825Stheraven			*res = sentinel.ai_next;
602227825Stheraven			return SUCCESS;
603227825Stheraven		} else
604227825Stheraven			error = EAI_FAIL;
605227825Stheraven	}
606227825Stheravenfree:
607227825Stheravenbad:
608227825Stheraven	if (sentinel.ai_next)
609227825Stheraven		freeaddrinfo(sentinel.ai_next);
610227825Stheraven	*res = NULL;
611227825Stheraven	return error;
612227825Stheraven}
613227825Stheraven
614227825Stheravenstatic int
615227825Stheravenreorder(sentinel)
616227825Stheraven	struct addrinfo *sentinel;
617227825Stheraven{
618227825Stheraven	struct addrinfo *ai, **aip;
619227825Stheraven	struct ai_order *aio;
620227825Stheraven	int i, n;
621227825Stheraven	struct policyhead policyhead;
622227825Stheraven
623227825Stheraven	/* count the number of addrinfo elements for sorting. */
624227825Stheraven	for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
625227825Stheraven		;
626227825Stheraven
627227825Stheraven	/*
628227825Stheraven	 * If the number is small enough, we can skip the reordering process.
629227825Stheraven	 */
630227825Stheraven	if (n <= 1)
631227825Stheraven		return(n);
632227825Stheraven
633227825Stheraven	/* allocate a temporary array for sort and initialization of it. */
634227825Stheraven	if ((aio = malloc(sizeof(*aio) * n)) == NULL)
635227825Stheraven		return(n);	/* give up reordering */
636227825Stheraven	memset(aio, 0, sizeof(*aio) * n);
637227825Stheraven
638227825Stheraven	/* retrieve address selection policy from the kernel */
639227825Stheraven	TAILQ_INIT(&policyhead);
640227825Stheraven	if (!get_addrselectpolicy(&policyhead)) {
641227825Stheraven		/* no policy is installed into kernel, we don't sort. */
642227825Stheraven		free(aio);
643227825Stheraven		return (n);
644227825Stheraven	}
645227825Stheraven
646227825Stheraven	for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
647227825Stheraven		aio[i].aio_ai = ai;
648227825Stheraven		aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
649227825Stheraven		aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
650227825Stheraven							      &policyhead);
651227825Stheraven		set_source(&aio[i], &policyhead);
652227825Stheraven	}
653227825Stheraven
654227825Stheraven	/* perform sorting. */
655227825Stheraven	qsort(aio, n, sizeof(*aio), comp_dst);
656227825Stheraven
657227825Stheraven	/* reorder the addrinfo chain. */
658227825Stheraven	for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
659232950Stheraven		*aip = aio[i].aio_ai;
660227825Stheraven		aip = &aio[i].aio_ai->ai_next;
661227825Stheraven	}
662227825Stheraven	*aip = NULL;
663227825Stheraven
664227825Stheraven	/* cleanup and return */
665227825Stheraven	free(aio);
666227825Stheraven	free_addrselectpolicy(&policyhead);
667227825Stheraven	return(n);
668227825Stheraven}
669227825Stheraven
670227825Stheravenstatic int
671227825Stheravenget_addrselectpolicy(head)
672227825Stheraven	struct policyhead *head;
673227825Stheraven{
674227825Stheraven#ifdef INET6
675227825Stheraven	int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
676227825Stheraven	size_t l;
677227825Stheraven	char *buf;
678227825Stheraven	struct in6_addrpolicy *pol, *ep;
679227825Stheraven
680227825Stheraven	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0)
681232950Stheraven		return (0);
682227825Stheraven	if ((buf = malloc(l)) == NULL)
683232950Stheraven		return (0);
684232950Stheraven	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
685227825Stheraven		free(buf);
686227825Stheraven		return (0);
687227825Stheraven	}
688227825Stheraven
689227825Stheraven	ep = (struct in6_addrpolicy *)(buf + l);
690227825Stheraven	for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
691227825Stheraven		struct policyqueue *new;
692227825Stheraven
693232950Stheraven		if ((new = malloc(sizeof(*new))) == NULL) {
694227825Stheraven			free_addrselectpolicy(head); /* make the list empty */
695232950Stheraven			break;
696232950Stheraven		}
697227825Stheraven		new->pc_policy = *pol;
698227825Stheraven		TAILQ_INSERT_TAIL(head, new, pc_entry);
699227825Stheraven	}
700227825Stheraven
701227825Stheraven	free(buf);
702227825Stheraven	return (1);
703232950Stheraven#else
704227825Stheraven	return (0);
705232950Stheraven#endif
706232950Stheraven}
707227825Stheraven
708227825Stheravenstatic void
709227825Stheravenfree_addrselectpolicy(head)
710227825Stheraven	struct policyhead *head;
711227825Stheraven{
712227825Stheraven	struct policyqueue *ent, *nent;
713227825Stheraven
714227825Stheraven	for (ent = TAILQ_FIRST(head); ent; ent = nent) {
715227825Stheraven		nent = TAILQ_NEXT(ent, pc_entry);
716227825Stheraven		TAILQ_REMOVE(head, ent, pc_entry);
717227825Stheraven		free(ent);
718227825Stheraven	}
719227825Stheraven}
720227825Stheraven
721227825Stheravenstatic struct policyqueue *
722227825Stheravenmatch_addrselectpolicy(addr, head)
723227825Stheraven	struct sockaddr *addr;
724227825Stheraven	struct policyhead *head;
725227825Stheraven{
726227825Stheraven#ifdef INET6
727227825Stheraven	struct policyqueue *ent, *bestent = NULL;
728227825Stheraven	struct in6_addrpolicy *pol;
729227825Stheraven	int matchlen, bestmatchlen = -1;
730227825Stheraven	u_char *mp, *ep, *k, *p, m;
731227825Stheraven	struct sockaddr_in6 key;
732227825Stheraven
733227825Stheraven	switch(addr->sa_family) {
734227825Stheraven	case AF_INET6:
735227825Stheraven		key = *(struct sockaddr_in6 *)addr;
736227825Stheraven		break;
737227825Stheraven	case AF_INET:
738227825Stheraven		/* convert the address into IPv4-mapped IPv6 address. */
739227825Stheraven		memset(&key, 0, sizeof(key));
740227825Stheraven		key.sin6_family = AF_INET6;
741227825Stheraven		key.sin6_len = sizeof(key);
742227825Stheraven		key.sin6_addr.s6_addr[10] = 0xff;
743227825Stheraven		key.sin6_addr.s6_addr[11] = 0xff;
744227825Stheraven		memcpy(&key.sin6_addr.s6_addr[12],
745227825Stheraven		       &((struct sockaddr_in *)addr)->sin_addr, 4);
746227825Stheraven		break;
747227825Stheraven	default:
748227825Stheraven		return(NULL);
749227825Stheraven	}
750227825Stheraven
751227825Stheraven	for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
752227825Stheraven		pol = &ent->pc_policy;
753227825Stheraven		matchlen = 0;
754227825Stheraven
755227825Stheraven		mp = (u_char *)&pol->addrmask.sin6_addr;
756227825Stheraven		ep = mp + 16;	/* XXX: scope field? */
757227825Stheraven		k = (u_char *)&key.sin6_addr;
758227825Stheraven		p = (u_char *)&pol->addr.sin6_addr;
759227825Stheraven		for (; mp < ep && *mp; mp++, k++, p++) {
760227825Stheraven			m = *mp;
761227825Stheraven			if ((*k & m) != *p)
762227825Stheraven				goto next; /* not match */
763227825Stheraven			if (m == 0xff) /* short cut for a typical case */
764227825Stheraven				matchlen += 8;
765227825Stheraven			else {
766227825Stheraven				while (m >= 0x80) {
767227825Stheraven					matchlen++;
768227825Stheraven					m <<= 1;
769227825Stheraven				}
770227825Stheraven			}
771227825Stheraven		}
772227825Stheraven
773227825Stheraven		/* matched.  check if this is better than the current best. */
774227825Stheraven		if (matchlen > bestmatchlen) {
775227825Stheraven			bestent = ent;
776227825Stheraven			bestmatchlen = matchlen;
777227825Stheraven		}
778227825Stheraven
779227825Stheraven	  next:
780227825Stheraven		continue;
781227825Stheraven	}
782227825Stheraven
783227825Stheraven	return(bestent);
784227825Stheraven#else
785227825Stheraven	return(NULL);
786227825Stheraven#endif
787227825Stheraven
788227825Stheraven}
789227825Stheraven
790227825Stheravenstatic void
791227825Stheravenset_source(aio, ph)
792227825Stheraven	struct ai_order *aio;
793227825Stheraven	struct policyhead *ph;
794227825Stheraven{
795227825Stheraven	struct addrinfo ai = *aio->aio_ai;
796227825Stheraven	struct sockaddr_storage ss;
797227825Stheraven	int s, srclen;
798227825Stheraven
799227825Stheraven	/* set unspec ("no source is available"), just in case */
800227825Stheraven	aio->aio_srcsa.sa_family = AF_UNSPEC;
801227825Stheraven	aio->aio_srcscope = -1;
802227825Stheraven
803227825Stheraven	switch(ai.ai_family) {
804227825Stheraven	case AF_INET:
805227825Stheraven#ifdef INET6
806227825Stheraven	case AF_INET6:
807227825Stheraven#endif
808227825Stheraven		break;
809227825Stheraven	default:		/* ignore unsupported AFs explicitly */
810227825Stheraven		return;
811227825Stheraven	}
812227825Stheraven
813227825Stheraven	/* XXX: make a dummy addrinfo to call connect() */
814227825Stheraven	ai.ai_socktype = SOCK_DGRAM;
815227825Stheraven	ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
816227825Stheraven	ai.ai_next = NULL;
817227825Stheraven	memset(&ss, 0, sizeof(ss));
818227825Stheraven	memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
819227825Stheraven	ai.ai_addr = (struct sockaddr *)&ss;
820227825Stheraven	get_port(&ai, "1", 0);
821227825Stheraven
822227825Stheraven	/* open a socket to get the source address for the given dst */
823227825Stheraven	if ((s = _socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)) < 0)
824227825Stheraven		return;		/* give up */
825227825Stheraven	if (_connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
826227825Stheraven		goto cleanup;
827227825Stheraven	srclen = ai.ai_addrlen;
828227825Stheraven	if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
829227825Stheraven		aio->aio_srcsa.sa_family = AF_UNSPEC;
830227825Stheraven		goto cleanup;
831227825Stheraven	}
832227825Stheraven	aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
833227825Stheraven	aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
834227825Stheraven	aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
835227825Stheraven#ifdef INET6
836227825Stheraven	if (ai.ai_family == AF_INET6) {
837227825Stheraven		struct in6_ifreq ifr6;
838227825Stheraven		u_int32_t flags6;
839227825Stheraven
840227825Stheraven		/* XXX: interface name should not be hardcoded */
841227825Stheraven		strncpy(ifr6.ifr_name, "lo0", sizeof(ifr6.ifr_name));
842227825Stheraven		memset(&ifr6, 0, sizeof(ifr6));
843227825Stheraven		memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
844227825Stheraven		if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
845227825Stheraven			flags6 = ifr6.ifr_ifru.ifru_flags6;
846227825Stheraven			if ((flags6 & IN6_IFF_DEPRECATED))
847227825Stheraven				aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
848227825Stheraven		}
849227825Stheraven	}
850227825Stheraven#endif
851227825Stheraven
852227825Stheraven  cleanup:
853227825Stheraven	_close(s);
854227825Stheraven	return;
855227825Stheraven}
856227825Stheraven
857227825Stheravenstatic int
858227825Stheravenmatchlen(src, dst)
859227825Stheraven	struct sockaddr *src, *dst;
860227825Stheraven{
861227825Stheraven	int match = 0;
862227825Stheraven	u_char *s, *d;
863227825Stheraven	u_char *lim, r;
864227825Stheraven	int addrlen;
865227825Stheraven
866227825Stheraven	switch (src->sa_family) {
867227825Stheraven#ifdef INET6
868227825Stheraven	case AF_INET6:
869227825Stheraven		s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
870227825Stheraven		d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
871227825Stheraven		addrlen = sizeof(struct in6_addr);
872227825Stheraven		lim = s + addrlen;
873227825Stheraven		break;
874227825Stheraven#endif
875227825Stheraven	case AF_INET:
876232950Stheraven		s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
877227825Stheraven		d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
878227825Stheraven		addrlen = sizeof(struct in_addr);
879232950Stheraven		lim = s + addrlen;
880232950Stheraven		break;
881253222Sdim	default:
882232950Stheraven		return(0);
883232950Stheraven	}
884232950Stheraven
885227825Stheraven	while (s < lim)
886227825Stheraven		if ((r = (*d++ ^ *s++)) != 0) {
887232950Stheraven			while (r < addrlen * 8) {
888227825Stheraven				match++;
889227825Stheraven				r <<= 1;
890232950Stheraven			}
891227825Stheraven			break;
892253222Sdim		} else
893253222Sdim			match += 8;
894253222Sdim	return(match);
895253222Sdim}
896253222Sdim
897253222Sdimstatic int
898253222Sdimcomp_dst(arg1, arg2)
899253222Sdim	const void *arg1, *arg2;
900253222Sdim{
901227825Stheraven	const struct ai_order *dst1 = arg1, *dst2 = arg2;
902227825Stheraven
903232950Stheraven	/*
904232950Stheraven	 * Rule 1: Avoid unusable destinations.
905232950Stheraven	 * XXX: we currently do not consider if an appropriate route exists.
906227825Stheraven	 */
907232950Stheraven	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
908227825Stheraven	    dst2->aio_srcsa.sa_family == AF_UNSPEC) {
909227825Stheraven		return(-1);
910227825Stheraven	}
911227825Stheraven	if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
912227825Stheraven	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
913227825Stheraven		return(1);
914227825Stheraven	}
915227825Stheraven
916227825Stheraven	/* Rule 2: Prefer matching scope. */
917232950Stheraven	if (dst1->aio_dstscope == dst1->aio_srcscope &&
918227825Stheraven	    dst2->aio_dstscope != dst2->aio_srcscope) {
919232950Stheraven		return(-1);
920227825Stheraven	}
921227825Stheraven	if (dst1->aio_dstscope != dst1->aio_srcscope &&
922227825Stheraven	    dst2->aio_dstscope == dst2->aio_srcscope) {
923227825Stheraven		return(1);
924227825Stheraven	}
925227825Stheraven
926232950Stheraven	/* Rule 3: Avoid deprecated addresses. */
927227825Stheraven	if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
928227825Stheraven	    dst2->aio_srcsa.sa_family != AF_UNSPEC) {
929227825Stheraven		if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
930227825Stheraven		    (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
931227825Stheraven			return(-1);
932227825Stheraven		}
933227825Stheraven		if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
934232950Stheraven		    !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
935227825Stheraven			return(1);
936232950Stheraven		}
937227825Stheraven	}
938227825Stheraven
939227825Stheraven	/* Rule 4: Prefer home addresses. */
940227825Stheraven	/* XXX: not implemented yet */
941227825Stheraven
942227825Stheraven	/* Rule 5: Prefer matching label. */
943232950Stheraven#ifdef INET6
944227825Stheraven	if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
945227825Stheraven	    dst1->aio_srcpolicy->pc_policy.label ==
946227825Stheraven	    dst1->aio_dstpolicy->pc_policy.label &&
947227825Stheraven	    (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
948227825Stheraven	     dst2->aio_srcpolicy->pc_policy.label !=
949227825Stheraven	     dst2->aio_dstpolicy->pc_policy.label)) {
950227825Stheraven		return(-1);
951227825Stheraven	}
952227825Stheraven	if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
953227825Stheraven	    dst2->aio_srcpolicy->pc_policy.label ==
954227825Stheraven	    dst2->aio_dstpolicy->pc_policy.label &&
955243376Sdim	    (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
956227825Stheraven	     dst1->aio_srcpolicy->pc_policy.label !=
957243376Sdim	     dst1->aio_dstpolicy->pc_policy.label)) {
958243376Sdim		return(1);
959227825Stheraven	}
960243376Sdim#endif
961227825Stheraven
962227825Stheraven	/* Rule 6: Prefer higher precedence. */
963227825Stheraven#ifdef INET6
964227825Stheraven	if (dst1->aio_dstpolicy &&
965227825Stheraven	    (dst2->aio_dstpolicy == NULL ||
966227825Stheraven	     dst1->aio_dstpolicy->pc_policy.preced >
967227825Stheraven	     dst2->aio_dstpolicy->pc_policy.preced)) {
968227825Stheraven		return(-1);
969227825Stheraven	}
970227825Stheraven	if (dst2->aio_dstpolicy &&
971227825Stheraven	    (dst1->aio_dstpolicy == NULL ||
972227825Stheraven	     dst2->aio_dstpolicy->pc_policy.preced >
973227825Stheraven	     dst1->aio_dstpolicy->pc_policy.preced)) {
974227825Stheraven		return(1);
975227825Stheraven	}
976227825Stheraven#endif
977227825Stheraven
978227825Stheraven	/* Rule 7: Prefer native transport. */
979236539Sdim	/* XXX: not implemented yet */
980227825Stheraven
981227825Stheraven	/* Rule 8: Prefer smaller scope. */
982236539Sdim	if (dst1->aio_dstscope >= 0 &&
983227825Stheraven	    dst1->aio_dstscope < dst2->aio_dstscope) {
984236539Sdim		return(-1);
985227825Stheraven	}
986227825Stheraven	if (dst2->aio_dstscope >= 0 &&
987236539Sdim	    dst2->aio_dstscope < dst1->aio_dstscope) {
988227825Stheraven		return(1);
989227825Stheraven	}
990227825Stheraven
991227825Stheraven	/*
992227825Stheraven	 * Rule 9: Use longest matching prefix.
993227825Stheraven	 * We compare the match length in a same AF only.
994227825Stheraven	 */
995227825Stheraven	if (dst1->aio_ai->ai_addr->sa_family ==
996227825Stheraven	    dst2->aio_ai->ai_addr->sa_family) {
997227825Stheraven		if (dst1->aio_matchlen > dst2->aio_matchlen) {
998227825Stheraven			return(-1);
999227825Stheraven		}
1000227825Stheraven		if (dst1->aio_matchlen < dst2->aio_matchlen) {
1001227825Stheraven			return(1);
1002227825Stheraven		}
1003227825Stheraven	}
1004227825Stheraven
1005227825Stheraven	/* Rule 10: Otherwise, leave the order unchanged. */
1006227825Stheraven	return(-1);
1007227825Stheraven}
1008227825Stheraven
1009227825Stheraven/*
1010227825Stheraven * Copy from scope.c.
1011227825Stheraven * XXX: we should standardize the functions and link them as standard
1012227825Stheraven * library.
1013227825Stheraven */
1014227825Stheravenstatic int
1015227825Stheravengai_addr2scopetype(sa)
1016227825Stheraven	struct sockaddr *sa;
1017227825Stheraven{
1018227825Stheraven#ifdef INET6
1019227825Stheraven	struct sockaddr_in6 *sa6;
1020227825Stheraven#endif
1021227825Stheraven	struct sockaddr_in *sa4;
1022227825Stheraven
1023227825Stheraven	switch(sa->sa_family) {
1024227825Stheraven#ifdef INET6
1025227825Stheraven	case AF_INET6:
1026227825Stheraven		sa6 = (struct sockaddr_in6 *)sa;
1027227825Stheraven		if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1028227825Stheraven			/* just use the scope field of the multicast address */
1029227825Stheraven			return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1030227825Stheraven		}
1031227825Stheraven		/*
1032227825Stheraven		 * Unicast addresses: map scope type to corresponding scope
1033227825Stheraven		 * value defined for multcast addresses.
1034227825Stheraven		 * XXX: hardcoded scope type values are bad...
1035227825Stheraven		 */
1036227825Stheraven		if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1037243376Sdim			return(1); /* node local scope */
1038227825Stheraven		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1039243376Sdim			return(2); /* link-local scope */
1040243376Sdim		if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1041227825Stheraven			return(5); /* site-local scope */
1042243376Sdim		return(14);	/* global scope */
1043227825Stheraven		break;
1044227825Stheraven#endif
1045227825Stheraven	case AF_INET:
1046227825Stheraven		/*
1047227825Stheraven		 * IPv4 pseudo scoping according to RFC 3484.
1048227825Stheraven		 */
1049227825Stheraven		sa4 = (struct sockaddr_in *)sa;
1050227825Stheraven		/* IPv4 autoconfiguration addresses have link-local scope. */
1051227825Stheraven		if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1052227825Stheraven		    ((u_char *)&sa4->sin_addr)[1] == 254)
1053227825Stheraven			return(2);
1054227825Stheraven		/* Private addresses have site-local scope. */
1055227825Stheraven		if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1056227825Stheraven		    (((u_char *)&sa4->sin_addr)[0] == 172 &&
1057227825Stheraven		     (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1058227825Stheraven		    (((u_char *)&sa4->sin_addr)[0] == 192 &&
1059227825Stheraven		     ((u_char *)&sa4->sin_addr)[1] == 168))
1060227825Stheraven			return(14);	/* XXX: It should be 5 unless NAT */
1061227825Stheraven		/* Loopback addresses have link-local scope. */
1062227825Stheraven		if (((u_char *)&sa4->sin_addr)[0] == 127)
1063227825Stheraven			return(2);
1064227825Stheraven		return(14);
1065227825Stheraven		break;
1066227825Stheraven	default:
1067227825Stheraven		errno = EAFNOSUPPORT; /* is this a good error? */
1068227825Stheraven		return(-1);
1069227825Stheraven	}
1070227825Stheraven}
1071227825Stheraven
1072227825Stheraven/*
1073227825Stheraven * hostname == NULL.
1074227825Stheraven * passive socket -> anyaddr (0.0.0.0 or ::)
1075227825Stheraven * non-passive socket -> localhost (127.0.0.1 or ::1)
1076227825Stheraven */
1077227825Stheravenstatic int
1078227825Stheravenexplore_null(pai, servname, res)
1079227825Stheraven	const struct addrinfo *pai;
1080232950Stheraven	const char *servname;
1081227825Stheraven	struct addrinfo **res;
1082227825Stheraven{
1083232950Stheraven	int s;
1084227825Stheraven	const struct afd *afd;
1085227825Stheraven	struct addrinfo *cur;
1086227825Stheraven	struct addrinfo sentinel;
1087227825Stheraven	int error;
1088227825Stheraven
1089227825Stheraven	*res = NULL;
1090243376Sdim	sentinel.ai_next = NULL;
1091243376Sdim	cur = &sentinel;
1092227825Stheraven
1093227825Stheraven	/*
1094227825Stheraven	 * filter out AFs that are not supported by the kernel
1095232950Stheraven	 * XXX errno?
1096227825Stheraven	 */
1097227825Stheraven	s = _socket(pai->ai_family, SOCK_DGRAM, 0);
1098232950Stheraven	if (s < 0) {
1099227825Stheraven		if (errno != EMFILE)
1100227825Stheraven			return 0;
1101227825Stheraven	} else
1102232950Stheraven		_close(s);
1103232950Stheraven
1104232950Stheraven	/*
1105232950Stheraven	 * if the servname does not match socktype/protocol, ignore it.
1106227825Stheraven	 */
1107227825Stheraven	if (get_portmatch(pai, servname) != 0)
1108227825Stheraven		return 0;
1109227825Stheraven
1110227825Stheraven	afd = find_afd(pai->ai_family);
1111262801Sdim	if (afd == NULL)
1112262801Sdim		return 0;
1113262801Sdim
1114262801Sdim	if (pai->ai_flags & AI_PASSIVE) {
1115262801Sdim		GET_AI(cur->ai_next, afd, afd->a_addrany);
1116227825Stheraven		/* xxx meaningless?
1117227825Stheraven		 * GET_CANONNAME(cur->ai_next, "anyaddr");
1118232950Stheraven		 */
1119227825Stheraven		GET_PORT(cur->ai_next, servname);
1120227825Stheraven	} else {
1121227825Stheraven		GET_AI(cur->ai_next, afd, afd->a_loopback);
1122227825Stheraven		/* xxx meaningless?
1123227825Stheraven		 * GET_CANONNAME(cur->ai_next, "localhost");
1124227825Stheraven		 */
1125227825Stheraven		GET_PORT(cur->ai_next, servname);
1126227825Stheraven	}
1127227825Stheraven	cur = cur->ai_next;
1128227825Stheraven
1129227825Stheraven	*res = sentinel.ai_next;
1130227825Stheraven	return 0;
1131227825Stheraven
1132227825Stheravenfree:
1133227825Stheraven	if (sentinel.ai_next)
1134227825Stheraven		freeaddrinfo(sentinel.ai_next);
1135227825Stheraven	return error;
1136227825Stheraven}
1137227825Stheraven
1138227825Stheraven/*
1139227825Stheraven * numeric hostname
1140227825Stheraven */
1141227825Stheravenstatic int
1142227825Stheravenexplore_numeric(pai, hostname, servname, res, canonname)
1143227825Stheraven	const struct addrinfo *pai;
1144227825Stheraven	const char *hostname;
1145227825Stheraven	const char *servname;
1146227825Stheraven	struct addrinfo **res;
1147227825Stheraven	const char *canonname;
1148227825Stheraven{
1149227825Stheraven	const struct afd *afd;
1150227825Stheraven	struct addrinfo *cur;
1151227825Stheraven	struct addrinfo sentinel;
1152227825Stheraven	int error;
1153227825Stheraven	char pton[PTON_MAX];
1154227825Stheraven
1155227825Stheraven	*res = NULL;
1156227825Stheraven	sentinel.ai_next = NULL;
1157227825Stheraven	cur = &sentinel;
1158227825Stheraven
1159227825Stheraven	/*
1160227825Stheraven	 * if the servname does not match socktype/protocol, ignore it.
1161227825Stheraven	 */
1162227825Stheraven	if (get_portmatch(pai, servname) != 0)
1163227825Stheraven		return 0;
1164227825Stheraven
1165227825Stheraven	afd = find_afd(pai->ai_family);
1166227825Stheraven	if (afd == NULL)
1167227825Stheraven		return 0;
1168227825Stheraven
1169227825Stheraven	switch (afd->a_af) {
1170227825Stheraven#if 1 /*X/Open spec*/
1171227825Stheraven	case AF_INET:
1172227825Stheraven		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
1173227825Stheraven			if (pai->ai_family == afd->a_af ||
1174227825Stheraven			    pai->ai_family == PF_UNSPEC /*?*/) {
1175227825Stheraven				GET_AI(cur->ai_next, afd, pton);
1176227825Stheraven				GET_PORT(cur->ai_next, servname);
1177227825Stheraven				if ((pai->ai_flags & AI_CANONNAME)) {
1178227825Stheraven					/*
1179227825Stheraven					 * Set the numeric address itself as
1180227825Stheraven					 * the canonical name, based on a
1181227825Stheraven					 * clarification in rfc3493.
1182227825Stheraven					 */
1183227825Stheraven					GET_CANONNAME(cur->ai_next, canonname);
1184227825Stheraven				}
1185227825Stheraven				while (cur && cur->ai_next)
1186227825Stheraven					cur = cur->ai_next;
1187227825Stheraven			} else
1188227825Stheraven				ERR(EAI_FAMILY);	/*xxx*/
1189227825Stheraven		}
1190227825Stheraven		break;
1191227825Stheraven#endif
1192227825Stheraven	default:
1193227825Stheraven		if (inet_pton(afd->a_af, hostname, pton) == 1) {
1194227825Stheraven			if (pai->ai_family == afd->a_af ||
1195227825Stheraven			    pai->ai_family == PF_UNSPEC /*?*/) {
1196227825Stheraven				GET_AI(cur->ai_next, afd, pton);
1197227825Stheraven				GET_PORT(cur->ai_next, servname);
1198227825Stheraven				if ((pai->ai_flags & AI_CANONNAME)) {
1199227825Stheraven					/*
1200227825Stheraven					 * Set the numeric address itself as
1201227825Stheraven					 * the canonical name, based on a
1202227825Stheraven					 * clarification in rfc3493.
1203227825Stheraven					 */
1204227825Stheraven					GET_CANONNAME(cur->ai_next, canonname);
1205227825Stheraven				}
1206227825Stheraven				while (cur && cur->ai_next)
1207227825Stheraven					cur = cur->ai_next;
1208227825Stheraven			} else
1209227825Stheraven				ERR(EAI_FAMILY);	/* XXX */
1210227825Stheraven		}
1211227825Stheraven		break;
1212227825Stheraven	}
1213227825Stheraven
1214227825Stheraven	*res = sentinel.ai_next;
1215227825Stheraven	return 0;
1216227825Stheraven
1217227825Stheravenfree:
1218227825Stheravenbad:
1219227825Stheraven	if (sentinel.ai_next)
1220227825Stheraven		freeaddrinfo(sentinel.ai_next);
1221227825Stheraven	return error;
1222227825Stheraven}
1223227825Stheraven
1224227825Stheraven/*
1225262801Sdim * numeric hostname with scope
1226232950Stheraven */
1227227825Stheravenstatic int
1228232950Stheravenexplore_numeric_scope(pai, hostname, servname, res)
1229227825Stheraven	const struct addrinfo *pai;
1230232950Stheraven	const char *hostname;
1231232950Stheraven	const char *servname;
1232232950Stheraven	struct addrinfo **res;
1233232950Stheraven{
1234232950Stheraven#if !defined(SCOPE_DELIMITER) || !defined(INET6)
1235232950Stheraven	return explore_numeric(pai, hostname, servname, res, hostname);
1236232950Stheraven#else
1237232950Stheraven	const struct afd *afd;
1238232950Stheraven	struct addrinfo *cur;
1239232950Stheraven	int error;
1240232950Stheraven	char *cp, *hostname2 = NULL, *scope, *addr;
1241232950Stheraven	struct sockaddr_in6 *sin6;
1242232950Stheraven
1243232950Stheraven	/*
1244232950Stheraven	 * if the servname does not match socktype/protocol, ignore it.
1245232950Stheraven	 */
1246232950Stheraven	if (get_portmatch(pai, servname) != 0)
1247232950Stheraven		return 0;
1248232950Stheraven
1249232950Stheraven	afd = find_afd(pai->ai_family);
1250232950Stheraven	if (afd == NULL)
1251232950Stheraven		return 0;
1252232950Stheraven
1253232950Stheraven	if (!afd->a_scoped)
1254227825Stheraven		return explore_numeric(pai, hostname, servname, res, hostname);
1255227825Stheraven
1256227825Stheraven	cp = strchr(hostname, SCOPE_DELIMITER);
1257227825Stheraven	if (cp == NULL)
1258227825Stheraven		return explore_numeric(pai, hostname, servname, res, hostname);
1259227825Stheraven
1260227825Stheraven	/*
1261227825Stheraven	 * Handle special case of <scoped_address><delimiter><scope id>
1262227825Stheraven	 */
1263232950Stheraven	hostname2 = strdup(hostname);
1264232950Stheraven	if (hostname2 == NULL)
1265232950Stheraven		return EAI_MEMORY;
1266243376Sdim	/* terminate at the delimiter */
1267243376Sdim	hostname2[cp - hostname] = '\0';
1268243376Sdim	addr = hostname2;
1269243376Sdim	scope = cp + 1;
1270243376Sdim
1271243376Sdim	error = explore_numeric(pai, addr, servname, res, hostname);
1272232950Stheraven	if (error == 0) {
1273232950Stheraven		u_int32_t scopeid;
1274232950Stheraven
1275243376Sdim		for (cur = *res; cur; cur = cur->ai_next) {
1276232950Stheraven			if (cur->ai_family != AF_INET6)
1277243376Sdim				continue;
1278232950Stheraven			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1279243376Sdim			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1280243376Sdim				free(hostname2);
1281243376Sdim				return(EAI_NONAME); /* XXX: is return OK? */
1282243376Sdim			}
1283227825Stheraven			sin6->sin6_scope_id = scopeid;
1284227825Stheraven		}
1285227825Stheraven	}
1286227825Stheraven
1287227825Stheraven	free(hostname2);
1288
1289	return error;
1290#endif
1291}
1292
1293static int
1294get_canonname(pai, ai, str)
1295	const struct addrinfo *pai;
1296	struct addrinfo *ai;
1297	const char *str;
1298{
1299	if ((pai->ai_flags & AI_CANONNAME) != 0) {
1300		ai->ai_canonname = strdup(str);
1301		if (ai->ai_canonname == NULL)
1302			return EAI_MEMORY;
1303	}
1304	return 0;
1305}
1306
1307static struct addrinfo *
1308get_ai(pai, afd, addr)
1309	const struct addrinfo *pai;
1310	const struct afd *afd;
1311	const char *addr;
1312{
1313	char *p;
1314	struct addrinfo *ai;
1315#ifdef FAITH
1316	struct in6_addr faith_prefix;
1317	char *fp_str;
1318	int translate = 0;
1319#endif
1320
1321#ifdef FAITH
1322	/*
1323	 * Transfrom an IPv4 addr into a special IPv6 addr format for
1324	 * IPv6->IPv4 translation gateway. (only TCP is supported now)
1325	 *
1326	 * +-----------------------------------+------------+
1327	 * | faith prefix part (12 bytes)      | embedded   |
1328	 * |                                   | IPv4 addr part (4 bytes)
1329	 * +-----------------------------------+------------+
1330	 *
1331	 * faith prefix part is specified as ascii IPv6 addr format
1332	 * in environmental variable GAI.
1333	 * For FAITH to work correctly, routing to faith prefix must be
1334	 * setup toward a machine where a FAITH daemon operates.
1335	 * Also, the machine must enable some mechanizm
1336	 * (e.g. faith interface hack) to divert those packet with
1337	 * faith prefixed destination addr to user-land FAITH daemon.
1338	 */
1339	fp_str = getenv("GAI");
1340	if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
1341	    afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
1342		u_int32_t v4a;
1343		u_int8_t v4a_top;
1344
1345		memcpy(&v4a, addr, sizeof v4a);
1346		v4a_top = v4a >> IN_CLASSA_NSHIFT;
1347		if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
1348		    v4a_top != 0 && v4a != IN_LOOPBACKNET) {
1349			afd = &afdl[N_INET6];
1350			memcpy(&faith_prefix.s6_addr[12], addr,
1351			       sizeof(struct in_addr));
1352			translate = 1;
1353		}
1354	}
1355#endif
1356
1357	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1358		+ (afd->a_socklen));
1359	if (ai == NULL)
1360		return NULL;
1361
1362	memcpy(ai, pai, sizeof(struct addrinfo));
1363	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1364	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1365	ai->ai_addr->sa_len = afd->a_socklen;
1366	ai->ai_addrlen = afd->a_socklen;
1367	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1368	p = (char *)(void *)(ai->ai_addr);
1369#ifdef FAITH
1370	if (translate == 1)
1371		memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
1372	else
1373#endif
1374	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1375	return ai;
1376}
1377
1378static int
1379get_portmatch(ai, servname)
1380	const struct addrinfo *ai;
1381	const char *servname;
1382{
1383
1384	/* get_port does not touch first argument when matchonly == 1. */
1385	/* LINTED const cast */
1386	return get_port((struct addrinfo *)ai, servname, 1);
1387}
1388
1389static int
1390get_port(ai, servname, matchonly)
1391	struct addrinfo *ai;
1392	const char *servname;
1393	int matchonly;
1394{
1395	const char *proto;
1396	struct servent *sp;
1397	int port;
1398	int allownumeric;
1399
1400	if (servname == NULL)
1401		return 0;
1402	switch (ai->ai_family) {
1403	case AF_INET:
1404#ifdef AF_INET6
1405	case AF_INET6:
1406#endif
1407		break;
1408	default:
1409		return 0;
1410	}
1411
1412	switch (ai->ai_socktype) {
1413	case SOCK_RAW:
1414		return EAI_SERVICE;
1415	case SOCK_DGRAM:
1416	case SOCK_STREAM:
1417		allownumeric = 1;
1418		break;
1419	case ANY:
1420		allownumeric = 0;
1421		break;
1422	default:
1423		return EAI_SOCKTYPE;
1424	}
1425
1426	port = str2number(servname);
1427	if (port >= 0) {
1428		if (!allownumeric)
1429			return EAI_SERVICE;
1430		if (port < 0 || port > 65535)
1431			return EAI_SERVICE;
1432		port = htons(port);
1433	} else {
1434		if (ai->ai_flags & AI_NUMERICSERV)
1435			return EAI_NONAME;
1436		switch (ai->ai_socktype) {
1437		case SOCK_DGRAM:
1438			proto = "udp";
1439			break;
1440		case SOCK_STREAM:
1441			proto = "tcp";
1442			break;
1443		default:
1444			proto = NULL;
1445			break;
1446		}
1447
1448		THREAD_LOCK();
1449		if ((sp = getservbyname(servname, proto)) == NULL) {
1450			THREAD_UNLOCK();
1451			return EAI_SERVICE;
1452		}
1453		port = sp->s_port;
1454		THREAD_UNLOCK();
1455	}
1456
1457	if (!matchonly) {
1458		switch (ai->ai_family) {
1459		case AF_INET:
1460			((struct sockaddr_in *)(void *)
1461			    ai->ai_addr)->sin_port = port;
1462			break;
1463#ifdef INET6
1464		case AF_INET6:
1465			((struct sockaddr_in6 *)(void *)
1466			    ai->ai_addr)->sin6_port = port;
1467			break;
1468#endif
1469		}
1470	}
1471
1472	return 0;
1473}
1474
1475static const struct afd *
1476find_afd(af)
1477	int af;
1478{
1479	const struct afd *afd;
1480
1481	if (af == PF_UNSPEC)
1482		return NULL;
1483	for (afd = afdl; afd->a_af; afd++) {
1484		if (afd->a_af == af)
1485			return afd;
1486	}
1487	return NULL;
1488}
1489
1490/*
1491 * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
1492 * will take care of it.
1493 * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
1494 * if the code is right or not.
1495 *
1496 * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1497 * _dns_getaddrinfo.
1498 */
1499static int
1500addrconfig(pai)
1501	struct addrinfo *pai;
1502{
1503	int s, af;
1504
1505	/*
1506	 * TODO:
1507	 * Note that implementation dependent test for address
1508	 * configuration should be done everytime called
1509	 * (or apropriate interval),
1510	 * because addresses will be dynamically assigned or deleted.
1511	 */
1512	af = pai->ai_family;
1513	if (af == AF_UNSPEC) {
1514		if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1515			af = AF_INET;
1516		else {
1517			_close(s);
1518			if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1519				af = AF_INET6;
1520			else
1521				_close(s);
1522		}
1523	}
1524	if (af != AF_UNSPEC) {
1525		if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
1526			return 0;
1527		_close(s);
1528	}
1529	pai->ai_family = af;
1530	return 1;
1531}
1532
1533#ifdef INET6
1534/* convert a string to a scope identifier. XXX: IPv6 specific */
1535static int
1536ip6_str2scopeid(scope, sin6, scopeid)
1537	char *scope;
1538	struct sockaddr_in6 *sin6;
1539	u_int32_t *scopeid;
1540{
1541	u_long lscopeid;
1542	struct in6_addr *a6;
1543	char *ep;
1544
1545	a6 = &sin6->sin6_addr;
1546
1547	/* empty scopeid portion is invalid */
1548	if (*scope == '\0')
1549		return -1;
1550
1551	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1552		/*
1553		 * We currently assume a one-to-one mapping between links
1554		 * and interfaces, so we simply use interface indices for
1555		 * like-local scopes.
1556		 */
1557		*scopeid = if_nametoindex(scope);
1558		if (*scopeid == 0)
1559			goto trynumeric;
1560		return 0;
1561	}
1562
1563	/* still unclear about literal, allow numeric only - placeholder */
1564	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1565		goto trynumeric;
1566	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1567		goto trynumeric;
1568	else
1569		goto trynumeric;	/* global */
1570
1571	/* try to convert to a numeric id as a last resort */
1572  trynumeric:
1573	errno = 0;
1574	lscopeid = strtoul(scope, &ep, 10);
1575	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1576	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1577		return 0;
1578	else
1579		return -1;
1580}
1581#endif
1582
1583/*
1584 * FQDN hostname, DNS lookup
1585 */
1586static int
1587explore_fqdn(pai, hostname, servname, res)
1588	const struct addrinfo *pai;
1589	const char *hostname;
1590	const char *servname;
1591	struct addrinfo **res;
1592{
1593	struct addrinfo *result;
1594	struct addrinfo *cur;
1595	int error = 0;
1596	static const ns_dtab dtab[] = {
1597		NS_FILES_CB(_files_getaddrinfo, NULL)
1598		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
1599		NS_NIS_CB(_yp_getaddrinfo, NULL)
1600		{ 0 }
1601	};
1602
1603	result = NULL;
1604
1605	/*
1606	 * if the servname does not match socktype/protocol, ignore it.
1607	 */
1608	if (get_portmatch(pai, servname) != 0)
1609		return 0;
1610
1611	switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1612			default_dns_files, hostname, pai)) {
1613	case NS_TRYAGAIN:
1614		error = EAI_AGAIN;
1615		goto free;
1616	case NS_UNAVAIL:
1617		error = EAI_FAIL;
1618		goto free;
1619	case NS_NOTFOUND:
1620		error = EAI_NONAME;
1621		goto free;
1622	case NS_SUCCESS:
1623		error = 0;
1624		for (cur = result; cur; cur = cur->ai_next) {
1625			GET_PORT(cur, servname);
1626			/* canonname should be filled already */
1627		}
1628		break;
1629	}
1630
1631	*res = result;
1632
1633	return 0;
1634
1635free:
1636	if (result)
1637		freeaddrinfo(result);
1638	return error;
1639}
1640
1641#ifdef DEBUG
1642static const char AskedForGot[] =
1643	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1644#endif
1645
1646static struct addrinfo *
1647getanswer(answer, anslen, qname, qtype, pai)
1648	const querybuf *answer;
1649	int anslen;
1650	const char *qname;
1651	int qtype;
1652	const struct addrinfo *pai;
1653{
1654	struct addrinfo sentinel, *cur;
1655	struct addrinfo ai;
1656	const struct afd *afd;
1657	char *canonname;
1658	const HEADER *hp;
1659	const u_char *cp;
1660	int n;
1661	const u_char *eom;
1662	char *bp, *ep;
1663	int type, class, ancount, qdcount;
1664	int haveanswer, had_error;
1665	char tbuf[MAXDNAME];
1666	int (*name_ok)(const char *);
1667	char hostbuf[8*1024];
1668
1669	memset(&sentinel, 0, sizeof(sentinel));
1670	cur = &sentinel;
1671
1672	canonname = NULL;
1673	eom = answer->buf + anslen;
1674	switch (qtype) {
1675	case T_A:
1676	case T_AAAA:
1677	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
1678		name_ok = res_hnok;
1679		break;
1680	default:
1681		return (NULL);	/* XXX should be abort(); */
1682	}
1683	/*
1684	 * find first satisfactory answer
1685	 */
1686	hp = &answer->hdr;
1687	ancount = ntohs(hp->ancount);
1688	qdcount = ntohs(hp->qdcount);
1689	bp = hostbuf;
1690	ep = hostbuf + sizeof hostbuf;
1691	cp = answer->buf + HFIXEDSZ;
1692	if (qdcount != 1) {
1693		h_errno = NO_RECOVERY;
1694		return (NULL);
1695	}
1696	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1697	if ((n < 0) || !(*name_ok)(bp)) {
1698		h_errno = NO_RECOVERY;
1699		return (NULL);
1700	}
1701	cp += n + QFIXEDSZ;
1702	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1703		/* res_send() has already verified that the query name is the
1704		 * same as the one we sent; this just gets the expanded name
1705		 * (i.e., with the succeeding search-domain tacked on).
1706		 */
1707		n = strlen(bp) + 1;		/* for the \0 */
1708		if (n >= MAXHOSTNAMELEN) {
1709			h_errno = NO_RECOVERY;
1710			return (NULL);
1711		}
1712		canonname = bp;
1713		bp += n;
1714		/* The qname can be abbreviated, but h_name is now absolute. */
1715		qname = canonname;
1716	}
1717	haveanswer = 0;
1718	had_error = 0;
1719	while (ancount-- > 0 && cp < eom && !had_error) {
1720		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1721		if ((n < 0) || !(*name_ok)(bp)) {
1722			had_error++;
1723			continue;
1724		}
1725		cp += n;			/* name */
1726		type = _getshort(cp);
1727 		cp += INT16SZ;			/* type */
1728		class = _getshort(cp);
1729 		cp += INT16SZ + INT32SZ;	/* class, TTL */
1730		n = _getshort(cp);
1731		cp += INT16SZ;			/* len */
1732		if (class != C_IN) {
1733			/* XXX - debug? syslog? */
1734			cp += n;
1735			continue;		/* XXX - had_error++ ? */
1736		}
1737		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1738		    type == T_CNAME) {
1739			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1740			if ((n < 0) || !(*name_ok)(tbuf)) {
1741				had_error++;
1742				continue;
1743			}
1744			cp += n;
1745			/* Get canonical name. */
1746			n = strlen(tbuf) + 1;	/* for the \0 */
1747			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1748				had_error++;
1749				continue;
1750			}
1751			strlcpy(bp, tbuf, ep - bp);
1752			canonname = bp;
1753			bp += n;
1754			continue;
1755		}
1756		if (qtype == T_ANY) {
1757			if (!(type == T_A || type == T_AAAA)) {
1758				cp += n;
1759				continue;
1760			}
1761		} else if (type != qtype) {
1762#ifdef DEBUG
1763			if (type != T_KEY && type != T_SIG)
1764				syslog(LOG_NOTICE|LOG_AUTH,
1765	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1766				       qname, p_class(C_IN), p_type(qtype),
1767				       p_type(type));
1768#endif
1769			cp += n;
1770			continue;		/* XXX - had_error++ ? */
1771		}
1772		switch (type) {
1773		case T_A:
1774		case T_AAAA:
1775			if (strcasecmp(canonname, bp) != 0) {
1776#ifdef DEBUG
1777				syslog(LOG_NOTICE|LOG_AUTH,
1778				       AskedForGot, canonname, bp);
1779#endif
1780				cp += n;
1781				continue;	/* XXX - had_error++ ? */
1782			}
1783			if (type == T_A && n != INADDRSZ) {
1784				cp += n;
1785				continue;
1786			}
1787			if (type == T_AAAA && n != IN6ADDRSZ) {
1788				cp += n;
1789				continue;
1790			}
1791#ifdef FILTER_V4MAPPED
1792			if (type == T_AAAA) {
1793				struct in6_addr in6;
1794				memcpy(&in6, cp, sizeof(in6));
1795				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1796					cp += n;
1797					continue;
1798				}
1799			}
1800#endif
1801			if (!haveanswer) {
1802				int nn;
1803
1804				canonname = bp;
1805				nn = strlen(bp) + 1;	/* for the \0 */
1806				bp += nn;
1807			}
1808
1809			/* don't overwrite pai */
1810			ai = *pai;
1811			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1812			afd = find_afd(ai.ai_family);
1813			if (afd == NULL) {
1814				cp += n;
1815				continue;
1816			}
1817			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1818			if (cur->ai_next == NULL)
1819				had_error++;
1820			while (cur && cur->ai_next)
1821				cur = cur->ai_next;
1822			cp += n;
1823			break;
1824		default:
1825			abort();
1826		}
1827		if (!had_error)
1828			haveanswer++;
1829	}
1830	if (haveanswer) {
1831#if defined(RESOLVSORT)
1832		/*
1833		 * We support only IPv4 address for backward
1834		 * compatibility against gethostbyname(3).
1835		 */
1836		if (_res.nsort && qtype == T_A) {
1837			if (addr4sort(&sentinel) < 0) {
1838				freeaddrinfo(sentinel.ai_next);
1839				h_errno = NO_RECOVERY;
1840				return NULL;
1841			}
1842		}
1843#endif /*RESOLVSORT*/
1844		if (!canonname)
1845			(void)get_canonname(pai, sentinel.ai_next, qname);
1846		else
1847			(void)get_canonname(pai, sentinel.ai_next, canonname);
1848		h_errno = NETDB_SUCCESS;
1849		return sentinel.ai_next;
1850	}
1851
1852	h_errno = NO_RECOVERY;
1853	return NULL;
1854}
1855
1856#ifdef RESOLVSORT
1857struct addr_ptr {
1858	struct addrinfo *ai;
1859	int aval;
1860};
1861
1862static int
1863addr4sort(struct addrinfo *sentinel)
1864{
1865	struct addrinfo *ai;
1866	struct addr_ptr *addrs, addr;
1867	struct sockaddr_in *sin;
1868	int naddrs, i, j;
1869	int needsort = 0;
1870
1871	if (!sentinel)
1872		return -1;
1873	naddrs = 0;
1874	for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
1875		naddrs++;
1876	if (naddrs < 2)
1877		return 0;		/* We don't need sorting. */
1878	if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
1879		return -1;
1880	i = 0;
1881	for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
1882		sin = (struct sockaddr_in *)ai->ai_addr;
1883		for (j = 0; (unsigned)j < _res.nsort; j++) {
1884			if (_res.sort_list[j].addr.s_addr ==
1885			    (sin->sin_addr.s_addr & _res.sort_list[j].mask))
1886				break;
1887		}
1888		addrs[i].ai = ai;
1889		addrs[i].aval = j;
1890		if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
1891			needsort = i;
1892		i++;
1893	}
1894	if (!needsort) {
1895		free(addrs);
1896		return 0;
1897	}
1898
1899	while (needsort < naddrs) {
1900	    for (j = needsort - 1; j >= 0; j--) {
1901		if (addrs[j].aval > addrs[j+1].aval) {
1902		    addr = addrs[j];
1903		    addrs[j] = addrs[j + 1];
1904		    addrs[j + 1] = addr;
1905		} else
1906		    break;
1907	    }
1908	    needsort++;
1909	}
1910
1911	ai = sentinel;
1912	for (i = 0; i < naddrs; ++i) {
1913		ai->ai_next = addrs[i].ai;
1914		ai = ai->ai_next;
1915	}
1916	ai->ai_next = NULL;
1917	free(addrs);
1918	return 0;
1919}
1920#endif /*RESOLVSORT*/
1921
1922/*ARGSUSED*/
1923static int
1924_dns_getaddrinfo(rv, cb_data, ap)
1925	void	*rv;
1926	void	*cb_data;
1927	va_list	 ap;
1928{
1929	struct addrinfo *ai;
1930	querybuf *buf, *buf2;
1931	const char *hostname;
1932	const struct addrinfo *pai;
1933	struct addrinfo sentinel, *cur;
1934	struct res_target q, q2;
1935
1936	hostname = va_arg(ap, char *);
1937	pai = va_arg(ap, const struct addrinfo *);
1938
1939	memset(&q, 0, sizeof(q2));
1940	memset(&q2, 0, sizeof(q2));
1941	memset(&sentinel, 0, sizeof(sentinel));
1942	cur = &sentinel;
1943
1944	buf = malloc(sizeof(*buf));
1945	if (!buf) {
1946		h_errno = NETDB_INTERNAL;
1947		return NS_NOTFOUND;
1948	}
1949	buf2 = malloc(sizeof(*buf2));
1950	if (!buf2) {
1951		free(buf);
1952		h_errno = NETDB_INTERNAL;
1953		return NS_NOTFOUND;
1954	}
1955
1956	switch (pai->ai_family) {
1957	case AF_UNSPEC:
1958		q.name = hostname;
1959		q.qclass = C_IN;
1960		q.qtype = T_A;
1961		q.answer = buf->buf;
1962		q.anslen = sizeof(buf->buf);
1963		q.next = &q2;
1964		q2.name = hostname;
1965		q2.qclass = C_IN;
1966		q2.qtype = T_AAAA;
1967		q2.answer = buf2->buf;
1968		q2.anslen = sizeof(buf2->buf);
1969		break;
1970	case AF_INET:
1971		q.name = hostname;
1972		q.qclass = C_IN;
1973		q.qtype = T_A;
1974		q.answer = buf->buf;
1975		q.anslen = sizeof(buf->buf);
1976		break;
1977	case AF_INET6:
1978		q.name = hostname;
1979		q.qclass = C_IN;
1980		q.qtype = T_AAAA;
1981		q.answer = buf->buf;
1982		q.anslen = sizeof(buf->buf);
1983		break;
1984	default:
1985		free(buf);
1986		free(buf2);
1987		return NS_UNAVAIL;
1988	}
1989	if (res_searchN(hostname, &q) < 0) {
1990		free(buf);
1991		free(buf2);
1992		return NS_NOTFOUND;
1993	}
1994	/* prefer IPv6 */
1995	if (q.next) {
1996		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1997		if (ai) {
1998			cur->ai_next = ai;
1999			while (cur && cur->ai_next)
2000				cur = cur->ai_next;
2001		}
2002	}
2003	ai = getanswer(buf, q.n, q.name, q.qtype, pai);
2004	if (ai)
2005		cur->ai_next = ai;
2006	free(buf);
2007	free(buf2);
2008	if (sentinel.ai_next == NULL)
2009		switch (h_errno) {
2010		case HOST_NOT_FOUND:
2011			return NS_NOTFOUND;
2012		case TRY_AGAIN:
2013			return NS_TRYAGAIN;
2014		default:
2015			return NS_UNAVAIL;
2016		}
2017	*((struct addrinfo **)rv) = sentinel.ai_next;
2018	return NS_SUCCESS;
2019}
2020
2021static void
2022_sethtent(FILE **hostf)
2023{
2024	if (!*hostf)
2025		*hostf = fopen(_PATH_HOSTS, "r");
2026	else
2027		rewind(*hostf);
2028}
2029
2030static void
2031_endhtent(FILE **hostf)
2032{
2033	if (*hostf) {
2034		(void) fclose(*hostf);
2035		*hostf = NULL;
2036	}
2037}
2038
2039static struct addrinfo *
2040_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2041{
2042	char *p;
2043	char *cp, *tname, *cname;
2044	struct addrinfo hints, *res0, *res;
2045	int error;
2046	const char *addr;
2047	char hostbuf[8*1024];
2048
2049	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r")))
2050		return (NULL);
2051again:
2052	if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2053		return (NULL);
2054	if (*p == '#')
2055		goto again;
2056	cp = strpbrk(p, "#\n");
2057	if (cp != NULL)
2058		*cp = '\0';
2059	if (!(cp = strpbrk(p, " \t")))
2060		goto again;
2061	*cp++ = '\0';
2062	addr = p;
2063	cname = NULL;
2064	/* if this is not something we're looking for, skip it. */
2065	while (cp && *cp) {
2066		if (*cp == ' ' || *cp == '\t') {
2067			cp++;
2068			continue;
2069		}
2070		tname = cp;
2071		if (cname == NULL)
2072			cname = cp;
2073		if ((cp = strpbrk(cp, " \t")) != NULL)
2074			*cp++ = '\0';
2075		if (strcasecmp(name, tname) == 0)
2076			goto found;
2077	}
2078	goto again;
2079
2080found:
2081	/* we should not glob socktype/protocol here */
2082	memset(&hints, 0, sizeof(hints));
2083	hints.ai_family = pai->ai_family;
2084	hints.ai_socktype = SOCK_DGRAM;
2085	hints.ai_protocol = 0;
2086	hints.ai_flags = AI_NUMERICHOST;
2087	error = getaddrinfo(addr, "0", &hints, &res0);
2088	if (error)
2089		goto again;
2090#ifdef FILTER_V4MAPPED
2091	/* XXX should check all items in the chain */
2092	if (res0->ai_family == AF_INET6 &&
2093	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2094		freeaddrinfo(res0);
2095		goto again;
2096	}
2097#endif
2098	for (res = res0; res; res = res->ai_next) {
2099		/* cover it up */
2100		res->ai_flags = pai->ai_flags;
2101		res->ai_socktype = pai->ai_socktype;
2102		res->ai_protocol = pai->ai_protocol;
2103
2104		if (pai->ai_flags & AI_CANONNAME) {
2105			if (get_canonname(pai, res, cname) != 0) {
2106				freeaddrinfo(res0);
2107				goto again;
2108			}
2109		}
2110	}
2111	return res0;
2112}
2113
2114/*ARGSUSED*/
2115static int
2116_files_getaddrinfo(rv, cb_data, ap)
2117	void	*rv;
2118	void	*cb_data;
2119	va_list	 ap;
2120{
2121	const char *name;
2122	const struct addrinfo *pai;
2123	struct addrinfo sentinel, *cur;
2124	struct addrinfo *p;
2125	FILE *hostf = NULL;
2126
2127	name = va_arg(ap, char *);
2128	pai = va_arg(ap, struct addrinfo *);
2129
2130	memset(&sentinel, 0, sizeof(sentinel));
2131	cur = &sentinel;
2132
2133	_sethtent(&hostf);
2134	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2135		cur->ai_next = p;
2136		while (cur && cur->ai_next)
2137			cur = cur->ai_next;
2138	}
2139	_endhtent(&hostf);
2140
2141	*((struct addrinfo **)rv) = sentinel.ai_next;
2142	if (sentinel.ai_next == NULL)
2143		return NS_NOTFOUND;
2144	return NS_SUCCESS;
2145}
2146
2147#ifdef YP
2148/*ARGSUSED*/
2149static struct addrinfo *
2150_yphostent(line, pai)
2151	char *line;
2152	const struct addrinfo *pai;
2153{
2154	struct addrinfo sentinel, *cur;
2155	struct addrinfo hints, *res, *res0;
2156	int error;
2157	char *p = line;
2158	const char *addr, *canonname;
2159	char *nextline;
2160	char *cp;
2161
2162	addr = canonname = NULL;
2163
2164	memset(&sentinel, 0, sizeof(sentinel));
2165	cur = &sentinel;
2166
2167nextline:
2168	/* terminate line */
2169	cp = strchr(p, '\n');
2170	if (cp) {
2171		*cp++ = '\0';
2172		nextline = cp;
2173	} else
2174		nextline = NULL;
2175
2176	cp = strpbrk(p, " \t");
2177	if (cp == NULL) {
2178		if (canonname == NULL)
2179			return (NULL);
2180		else
2181			goto done;
2182	}
2183	*cp++ = '\0';
2184
2185	addr = p;
2186
2187	while (cp && *cp) {
2188		if (*cp == ' ' || *cp == '\t') {
2189			cp++;
2190			continue;
2191		}
2192		if (!canonname)
2193			canonname = cp;
2194		if ((cp = strpbrk(cp, " \t")) != NULL)
2195			*cp++ = '\0';
2196	}
2197
2198	hints = *pai;
2199	hints.ai_flags = AI_NUMERICHOST;
2200	error = getaddrinfo(addr, NULL, &hints, &res0);
2201	if (error == 0) {
2202		for (res = res0; res; res = res->ai_next) {
2203			/* cover it up */
2204			res->ai_flags = pai->ai_flags;
2205
2206			if (pai->ai_flags & AI_CANONNAME)
2207				(void)get_canonname(pai, res, canonname);
2208		}
2209	} else
2210		res0 = NULL;
2211	if (res0) {
2212		cur->ai_next = res0;
2213		while (cur && cur->ai_next)
2214			cur = cur->ai_next;
2215	}
2216
2217	if (nextline) {
2218		p = nextline;
2219		goto nextline;
2220	}
2221
2222done:
2223	return sentinel.ai_next;
2224}
2225
2226/*ARGSUSED*/
2227static int
2228_yp_getaddrinfo(rv, cb_data, ap)
2229	void	*rv;
2230	void	*cb_data;
2231	va_list	 ap;
2232{
2233	struct addrinfo sentinel, *cur;
2234	struct addrinfo *ai = NULL;
2235	char *ypbuf;
2236	int ypbuflen, r;
2237	const char *name;
2238	const struct addrinfo *pai;
2239	char *ypdomain;
2240
2241	if (_yp_check(&ypdomain) == 0)
2242		return NS_UNAVAIL;
2243
2244	name = va_arg(ap, char *);
2245	pai = va_arg(ap, const struct addrinfo *);
2246
2247	memset(&sentinel, 0, sizeof(sentinel));
2248	cur = &sentinel;
2249
2250	/* hosts.byname is only for IPv4 (Solaris8) */
2251	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
2252		r = yp_match(ypdomain, "hosts.byname", name,
2253			(int)strlen(name), &ypbuf, &ypbuflen);
2254		if (r == 0) {
2255			struct addrinfo ai4;
2256
2257			ai4 = *pai;
2258			ai4.ai_family = AF_INET;
2259			ai = _yphostent(ypbuf, &ai4);
2260			if (ai) {
2261				cur->ai_next = ai;
2262				while (cur && cur->ai_next)
2263					cur = cur->ai_next;
2264			}
2265		}
2266		free(ypbuf);
2267	}
2268
2269	/* ipnodes.byname can hold both IPv4/v6 */
2270	r = yp_match(ypdomain, "ipnodes.byname", name,
2271		(int)strlen(name), &ypbuf, &ypbuflen);
2272	if (r == 0) {
2273		ai = _yphostent(ypbuf, pai);
2274		if (ai)
2275			cur->ai_next = ai;
2276		free(ypbuf);
2277	}
2278
2279	if (sentinel.ai_next == NULL) {
2280		h_errno = HOST_NOT_FOUND;
2281		return NS_NOTFOUND;
2282	}
2283	*((struct addrinfo **)rv) = sentinel.ai_next;
2284	return NS_SUCCESS;
2285}
2286#endif
2287
2288/* resolver logic */
2289
2290extern const char *__hostalias(const char *);
2291
2292/*
2293 * Formulate a normal query, send, and await answer.
2294 * Returned answer is placed in supplied buffer "answer".
2295 * Perform preliminary check of answer, returning success only
2296 * if no error is indicated and the answer count is nonzero.
2297 * Return the size of the response on success, -1 on error.
2298 * Error number is left in h_errno.
2299 *
2300 * Caller must parse answer and determine whether it answers the question.
2301 */
2302static int
2303res_queryN(name, target)
2304	const char *name;	/* domain name */
2305	struct res_target *target;
2306{
2307	u_char *buf;
2308	HEADER *hp;
2309	int n;
2310	struct res_target *t;
2311	int rcode;
2312	int ancount;
2313
2314	rcode = NOERROR;
2315	ancount = 0;
2316
2317	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
2318		h_errno = NETDB_INTERNAL;
2319		return (-1);
2320	}
2321
2322	buf = malloc(MAXPACKET);
2323	if (!buf) {
2324		h_errno = NETDB_INTERNAL;
2325		return -1;
2326	}
2327
2328	for (t = target; t; t = t->next) {
2329		int class, type;
2330		u_char *answer;
2331		int anslen;
2332
2333		hp = (HEADER *)(void *)t->answer;
2334		hp->rcode = NOERROR;	/* default */
2335
2336		/* make it easier... */
2337		class = t->qclass;
2338		type = t->qtype;
2339		answer = t->answer;
2340		anslen = t->anslen;
2341#ifdef DEBUG
2342		if (_res.options & RES_DEBUG)
2343			printf(";; res_query(%s, %d, %d)\n", name, class, type);
2344#endif
2345
2346		n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
2347		    buf, MAXPACKET);
2348		if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
2349			n = res_opt(n, buf, MAXPACKET, anslen);
2350		if (n <= 0) {
2351#ifdef DEBUG
2352			if (_res.options & RES_DEBUG)
2353				printf(";; res_query: mkquery failed\n");
2354#endif
2355			free(buf);
2356			h_errno = NO_RECOVERY;
2357			return (n);
2358		}
2359		n = res_send(buf, n, answer, anslen);
2360#if 0
2361		if (n < 0) {
2362#ifdef DEBUG
2363			if (_res.options & RES_DEBUG)
2364				printf(";; res_query: send error\n");
2365#endif
2366			free(buf);
2367			h_errno = TRY_AGAIN;
2368			return (n);
2369		}
2370#endif
2371
2372		if (n < 0 || n > anslen)
2373			hp->rcode = FORMERR; /* XXX not very informative */
2374		if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2375			rcode = hp->rcode;	/* record most recent error */
2376#ifdef DEBUG
2377			if (_res.options & RES_DEBUG)
2378				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2379				    ntohs(hp->ancount));
2380#endif
2381			continue;
2382		}
2383
2384		ancount += ntohs(hp->ancount);
2385
2386		t->n = n;
2387	}
2388
2389	free(buf);
2390
2391	if (ancount == 0) {
2392		switch (rcode) {
2393		case NXDOMAIN:
2394			h_errno = HOST_NOT_FOUND;
2395			break;
2396		case SERVFAIL:
2397			h_errno = TRY_AGAIN;
2398			break;
2399		case NOERROR:
2400			h_errno = NO_DATA;
2401			break;
2402		case FORMERR:
2403		case NOTIMP:
2404		case REFUSED:
2405		default:
2406			h_errno = NO_RECOVERY;
2407			break;
2408		}
2409		return (-1);
2410	}
2411	return (ancount);
2412}
2413
2414/*
2415 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2416 * Return the size of the response on success, -1 on error.
2417 * If enabled, implement search rules until answer or unrecoverable failure
2418 * is detected.  Error code, if any, is left in h_errno.
2419 */
2420static int
2421res_searchN(name, target)
2422	const char *name;	/* domain name */
2423	struct res_target *target;
2424{
2425	const char *cp, * const *domain;
2426	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
2427	u_int dots;
2428	int trailing_dot, ret, saved_herrno;
2429	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2430
2431	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
2432		h_errno = NETDB_INTERNAL;
2433		return (-1);
2434	}
2435
2436	errno = 0;
2437	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
2438	dots = 0;
2439	for (cp = name; *cp; cp++)
2440		dots += (*cp == '.');
2441	trailing_dot = 0;
2442	if (cp > name && *--cp == '.')
2443		trailing_dot++;
2444
2445	/*
2446	 * if there aren't any dots, it could be a user-level alias
2447	 */
2448	if (!dots && (cp = __hostalias(name)) != NULL)
2449		return (res_queryN(cp, target));
2450
2451	/*
2452	 * If there are dots in the name already, let's just give it a try
2453	 * 'as is'.  The threshold can be set with the "ndots" option.
2454	 */
2455	saved_herrno = -1;
2456	if (dots >= _res.ndots) {
2457		ret = res_querydomainN(name, NULL, target);
2458		if (ret > 0)
2459			return (ret);
2460		saved_herrno = h_errno;
2461		tried_as_is++;
2462	}
2463
2464	/*
2465	 * We do at least one level of search if
2466	 *	- there is no dot and RES_DEFNAME is set, or
2467	 *	- there is at least one dot, there is no trailing dot,
2468	 *	  and RES_DNSRCH is set.
2469	 */
2470	if ((!dots && (_res.options & RES_DEFNAMES)) ||
2471	    (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
2472		int done = 0;
2473
2474		for (domain = (const char * const *)_res.dnsrch;
2475		   *domain && !done;
2476		   domain++) {
2477
2478			ret = res_querydomainN(name, *domain, target);
2479			if (ret > 0)
2480				return (ret);
2481
2482			/*
2483			 * If no server present, give up.
2484			 * If name isn't found in this domain,
2485			 * keep trying higher domains in the search list
2486			 * (if that's enabled).
2487			 * On a NO_DATA error, keep trying, otherwise
2488			 * a wildcard entry of another type could keep us
2489			 * from finding this entry higher in the domain.
2490			 * If we get some other error (negative answer or
2491			 * server failure), then stop searching up,
2492			 * but try the input name below in case it's
2493			 * fully-qualified.
2494			 */
2495			if (errno == ECONNREFUSED) {
2496				h_errno = TRY_AGAIN;
2497				return (-1);
2498			}
2499
2500			switch (h_errno) {
2501			case NO_DATA:
2502				got_nodata++;
2503				/* FALLTHROUGH */
2504			case HOST_NOT_FOUND:
2505				/* keep trying */
2506				break;
2507			case TRY_AGAIN:
2508				if (hp->rcode == SERVFAIL) {
2509					/* try next search element, if any */
2510					got_servfail++;
2511					break;
2512				}
2513				/* FALLTHROUGH */
2514			default:
2515				/* anything else implies that we're done */
2516				done++;
2517			}
2518			/*
2519			 * if we got here for some reason other than DNSRCH,
2520			 * we only wanted one iteration of the loop, so stop.
2521			 */
2522			if (!(_res.options & RES_DNSRCH))
2523			        done++;
2524		}
2525	}
2526
2527	/*
2528	 * if we have not already tried the name "as is", do that now.
2529	 * note that we do this regardless of how many dots were in the
2530	 * name or whether it ends with a dot.
2531	 */
2532	if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
2533		ret = res_querydomainN(name, NULL, target);
2534		if (ret > 0)
2535			return (ret);
2536	}
2537
2538	/*
2539	 * if we got here, we didn't satisfy the search.
2540	 * if we did an initial full query, return that query's h_errno
2541	 * (note that we wouldn't be here if that query had succeeded).
2542	 * else if we ever got a nodata, send that back as the reason.
2543	 * else send back meaningless h_errno, that being the one from
2544	 * the last DNSRCH we did.
2545	 */
2546	if (saved_herrno != -1)
2547		h_errno = saved_herrno;
2548	else if (got_nodata)
2549		h_errno = NO_DATA;
2550	else if (got_servfail)
2551		h_errno = TRY_AGAIN;
2552	return (-1);
2553}
2554
2555/*
2556 * Perform a call on res_query on the concatenation of name and domain,
2557 * removing a trailing dot from name if domain is NULL.
2558 */
2559static int
2560res_querydomainN(name, domain, target)
2561	const char *name, *domain;
2562	struct res_target *target;
2563{
2564	char nbuf[MAXDNAME];
2565	const char *longname = nbuf;
2566	size_t n, d;
2567
2568	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
2569		h_errno = NETDB_INTERNAL;
2570		return (-1);
2571	}
2572#ifdef DEBUG
2573	if (_res.options & RES_DEBUG)
2574		printf(";; res_querydomain(%s, %s)\n",
2575			name, domain?domain:"<Nil>");
2576#endif
2577	if (domain == NULL) {
2578		/*
2579		 * Check for trailing '.';
2580		 * copy without '.' if present.
2581		 */
2582		n = strlen(name);
2583		if (n >= MAXDNAME) {
2584			h_errno = NO_RECOVERY;
2585			return (-1);
2586		}
2587		if (n > 0 && name[--n] == '.') {
2588			strncpy(nbuf, name, n);
2589			nbuf[n] = '\0';
2590		} else
2591			longname = name;
2592	} else {
2593		n = strlen(name);
2594		d = strlen(domain);
2595		if (n + d + 1 >= MAXDNAME) {
2596			h_errno = NO_RECOVERY;
2597			return (-1);
2598		}
2599		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2600	}
2601	return (res_queryN(longname, target));
2602}
2603