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