getaddrinfo.c revision 121426
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 121426 2003-10-23 14:32:03Z 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 <arpa/inet.h>
75#include <arpa/nameser.h>
76#include <rpc/rpc.h>
77#include <rpcsvc/yp_prot.h>
78#include <rpcsvc/ypclnt.h>
79#include <netdb.h>
80#include <pthread.h>
81#include <resolv.h>
82#include <string.h>
83#include <stdlib.h>
84#include <stddef.h>
85#include <ctype.h>
86#include <unistd.h>
87#include <stdio.h>
88#include <errno.h>
89
90#include "res_config.h"
91
92#ifdef DEBUG
93#include <syslog.h>
94#endif
95
96#include <stdarg.h>
97#include <nsswitch.h>
98#include "un-namespace.h"
99#include "libc_private.h"
100
101#if defined(__KAME__) && defined(INET6)
102# define FAITH
103#endif
104
105#define SUCCESS 0
106#define ANY 0
107#define YES 1
108#define NO  0
109
110static const char in_addrany[] = { 0, 0, 0, 0 };
111static const char in_loopback[] = { 127, 0, 0, 1 };
112#ifdef INET6
113static const char in6_addrany[] = {
114	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
115};
116static const char in6_loopback[] = {
117	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
118};
119#endif
120
121static const struct afd {
122	int a_af;
123	int a_addrlen;
124	int a_socklen;
125	int a_off;
126	const char *a_addrany;
127	const char *a_loopback;
128	int a_scoped;
129} afdl [] = {
130#ifdef INET6
131#define	N_INET6 0
132	{PF_INET6, sizeof(struct in6_addr),
133	 sizeof(struct sockaddr_in6),
134	 offsetof(struct sockaddr_in6, sin6_addr),
135	 in6_addrany, in6_loopback, 1},
136#define	N_INET 1
137#else
138#define	N_INET 0
139#endif
140	{PF_INET, sizeof(struct in_addr),
141	 sizeof(struct sockaddr_in),
142	 offsetof(struct sockaddr_in, sin_addr),
143	 in_addrany, in_loopback, 0},
144	{0, 0, 0, 0, NULL, NULL, 0},
145};
146
147struct explore {
148	int e_af;
149	int e_socktype;
150	int e_protocol;
151	const char *e_protostr;
152	int e_wild;
153#define WILD_AF(ex)		((ex)->e_wild & 0x01)
154#define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
155#define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
156};
157
158static const struct explore explore[] = {
159#if 0
160	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
161#endif
162#ifdef INET6
163	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
164	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
165	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
166#endif
167	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
168	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
169	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
170	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
171	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
172	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
173	{ -1, 0, 0, NULL, 0 },
174};
175
176#ifdef INET6
177#define PTON_MAX	16
178#else
179#define PTON_MAX	4
180#endif
181
182static const ns_src default_dns_files[] = {
183	{ NSSRC_FILES, 	NS_SUCCESS },
184	{ NSSRC_DNS, 	NS_SUCCESS },
185	{ 0 }
186};
187
188struct res_target {
189	struct res_target *next;
190	const char *name;	/* domain name */
191	int qclass, qtype;	/* class and type of query */
192	u_char *answer;		/* buffer to put answer */
193	int anslen;		/* size of answer buffer */
194	int n;			/* result length */
195};
196
197#define MAXPACKET	(64*1024)
198
199typedef union {
200	HEADER hdr;
201	u_char buf[MAXPACKET];
202} querybuf;
203
204static int str_isnumber(const char *);
205static int explore_null(const struct addrinfo *,
206	const char *, struct addrinfo **);
207static int explore_numeric(const struct addrinfo *, const char *,
208	const char *, struct addrinfo **);
209static int explore_numeric_scope(const struct addrinfo *, const char *,
210	const char *, struct addrinfo **);
211static int get_canonname(const struct addrinfo *,
212	struct addrinfo *, const char *);
213static struct addrinfo *get_ai(const struct addrinfo *,
214	const struct afd *, const char *);
215static int get_portmatch(const struct addrinfo *, const char *);
216static int get_port(struct addrinfo *, const char *, int);
217static const struct afd *find_afd(int);
218static int addrconfig(struct addrinfo *);
219#ifdef INET6
220static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
221#endif
222
223static int explore_fqdn(const struct addrinfo *, const char *,
224	const char *, struct addrinfo **);
225
226static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
227	const struct addrinfo *);
228#if defined(RESOLVSORT)
229static int addr4sort(struct addrinfo *);
230#endif
231static int _dns_getaddrinfo(void *, void *, va_list);
232static void _sethtent(void);
233static void _endhtent(void);
234static struct addrinfo *_gethtent(const char *, const struct addrinfo *);
235static int _files_getaddrinfo(void *, void *, va_list);
236#ifdef YP
237static struct addrinfo *_yphostent(char *, const struct addrinfo *);
238static int _yp_getaddrinfo(void *, void *, va_list);
239#endif
240
241static int res_queryN(const char *, struct res_target *);
242static int res_searchN(const char *, struct res_target *);
243static int res_querydomainN(const char *, const char *,
244	struct res_target *);
245
246static struct ai_errlist {
247	const char *str;
248	int code;
249} ai_errlist[] = {
250	{ "Success",					0, },
251	{ "Temporary failure in name resolution",	EAI_AGAIN, },
252	{ "Invalid value for ai_flags",		       	EAI_BADFLAGS, },
253	{ "Non-recoverable failure in name resolution", EAI_FAIL, },
254	{ "ai_family not supported",			EAI_FAMILY, },
255	{ "Memory allocation failure", 			EAI_MEMORY, },
256	{ "hostname nor servname provided, or not known", EAI_NONAME, },
257	{ "servname not supported for ai_socktype",	EAI_SERVICE, },
258	{ "ai_socktype not supported", 			EAI_SOCKTYPE, },
259	{ "System error returned in errno", 		EAI_SYSTEM, },
260	{ "Invalid value for hints",			EAI_BADHINTS, },
261	{ "Resolved protocol is unknown",		EAI_PROTOCOL, },
262	/* backward compatibility with userland code prior to 2553bis-02 */
263	{ "Address family for hostname not supported",	1, },
264	{ "No address associated with hostname", 	7, },
265	{ NULL,						-1, },
266};
267
268/*
269 * XXX: Our res_*() is not thread-safe.  So, we share lock between
270 * getaddrinfo() and getipnodeby*().  Still, we cannot use
271 * getaddrinfo() and getipnodeby*() in conjunction with other
272 * functions which call res_*().
273 */
274pthread_mutex_t __getaddrinfo_thread_lock = PTHREAD_MUTEX_INITIALIZER;
275#define THREAD_LOCK() \
276	if (__isthreaded) _pthread_mutex_lock(&__getaddrinfo_thread_lock);
277#define THREAD_UNLOCK() \
278	if (__isthreaded) _pthread_mutex_unlock(&__getaddrinfo_thread_lock);
279
280/* XXX macros that make external reference is BAD. */
281
282#define GET_AI(ai, afd, addr) \
283do { \
284	/* external reference: pai, error, and label free */ \
285	(ai) = get_ai(pai, (afd), (addr)); \
286	if ((ai) == NULL) { \
287		error = EAI_MEMORY; \
288		goto free; \
289	} \
290} while (/*CONSTCOND*/0)
291
292#define GET_PORT(ai, serv) \
293do { \
294	/* external reference: error and label free */ \
295	error = get_port((ai), (serv), 0); \
296	if (error != 0) \
297		goto free; \
298} while (/*CONSTCOND*/0)
299
300#define GET_CANONNAME(ai, str) \
301do { \
302	/* external reference: pai, error and label free */ \
303	error = get_canonname(pai, (ai), (str)); \
304	if (error != 0) \
305		goto free; \
306} while (/*CONSTCOND*/0)
307
308#define ERR(err) \
309do { \
310	/* external reference: error, and label bad */ \
311	error = (err); \
312	goto bad; \
313	/*NOTREACHED*/ \
314} while (/*CONSTCOND*/0)
315
316#define MATCH_FAMILY(x, y, w) \
317	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
318#define MATCH(x, y, w) \
319	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
320
321char *
322gai_strerror(ecode)
323	int ecode;
324{
325	struct ai_errlist *p;
326
327	for (p = ai_errlist; p->str; p++) {
328		if (p->code == ecode)
329			return (char *)p->str;
330	}
331	return "Unknown error";
332}
333
334void
335freeaddrinfo(ai)
336	struct addrinfo *ai;
337{
338	struct addrinfo *next;
339
340	do {
341		next = ai->ai_next;
342		if (ai->ai_canonname)
343			free(ai->ai_canonname);
344		/* no need to free(ai->ai_addr) */
345		free(ai);
346		ai = next;
347	} while (ai);
348}
349
350static int
351str_isnumber(p)
352	const char *p;
353{
354	char *ep;
355
356	if (*p == '\0')
357		return NO;
358	ep = NULL;
359	errno = 0;
360	(void)strtoul(p, &ep, 10);
361	if (errno == 0 && ep && *ep == '\0')
362		return YES;
363	else
364		return NO;
365}
366
367int
368getaddrinfo(hostname, servname, hints, res)
369	const char *hostname, *servname;
370	const struct addrinfo *hints;
371	struct addrinfo **res;
372{
373	struct addrinfo sentinel;
374	struct addrinfo *cur;
375	int error = 0;
376	struct addrinfo ai;
377	struct addrinfo ai0;
378	struct addrinfo *pai;
379	const struct explore *ex;
380
381	memset(&sentinel, 0, sizeof(sentinel));
382	cur = &sentinel;
383	pai = &ai;
384	pai->ai_flags = 0;
385	pai->ai_family = PF_UNSPEC;
386	pai->ai_socktype = ANY;
387	pai->ai_protocol = ANY;
388	pai->ai_addrlen = 0;
389	pai->ai_canonname = NULL;
390	pai->ai_addr = NULL;
391	pai->ai_next = NULL;
392
393	if (hostname == NULL && servname == NULL)
394		return EAI_NONAME;
395	if (hints) {
396		/* error check for hints */
397		if (hints->ai_addrlen || hints->ai_canonname ||
398		    hints->ai_addr || hints->ai_next)
399			ERR(EAI_BADHINTS); /* xxx */
400		if (hints->ai_flags & ~AI_MASK)
401			ERR(EAI_BADFLAGS);
402		switch (hints->ai_family) {
403		case PF_UNSPEC:
404		case PF_INET:
405#ifdef INET6
406		case PF_INET6:
407#endif
408			break;
409		default:
410			ERR(EAI_FAMILY);
411		}
412		memcpy(pai, hints, sizeof(*pai));
413
414		/*
415		 * if both socktype/protocol are specified, check if they
416		 * are meaningful combination.
417		 */
418		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
419			for (ex = explore; ex->e_af >= 0; ex++) {
420				if (pai->ai_family != ex->e_af)
421					continue;
422				if (ex->e_socktype == ANY)
423					continue;
424				if (ex->e_protocol == ANY)
425					continue;
426				if (pai->ai_socktype == ex->e_socktype &&
427				    pai->ai_protocol != ex->e_protocol) {
428					ERR(EAI_BADHINTS);
429				}
430			}
431		}
432	}
433
434	/*
435	 * post-2553: AI_ALL and AI_V4MAPPED are effective only against
436	 * AF_INET6 query.  They need to be ignored if specified in other
437	 * occassions.
438	 */
439	switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
440	case AI_V4MAPPED:
441	case AI_ALL | AI_V4MAPPED:
442		if (pai->ai_family != AF_INET6)
443			pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
444		break;
445	case AI_ALL:
446#if 1
447		/* illegal */
448		ERR(EAI_BADFLAGS);
449#else
450		pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
451#endif
452		break;
453	}
454
455	/*
456	 * check for special cases.  (1) numeric servname is disallowed if
457	 * socktype/protocol are left unspecified. (2) servname is disallowed
458	 * for raw and other inet{,6} sockets.
459	 */
460	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
461#ifdef PF_INET6
462	    || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
463#endif
464	    ) {
465		ai0 = *pai;	/* backup *pai */
466
467		if (pai->ai_family == PF_UNSPEC) {
468#ifdef PF_INET6
469			pai->ai_family = PF_INET6;
470#else
471			pai->ai_family = PF_INET;
472#endif
473		}
474		error = get_portmatch(pai, servname);
475		if (error)
476			ERR(error);
477
478		*pai = ai0;
479	}
480
481	ai0 = *pai;
482
483	/* NULL hostname, or numeric hostname */
484	for (ex = explore; ex->e_af >= 0; ex++) {
485		*pai = ai0;
486
487		/* PF_UNSPEC entries are prepared for DNS queries only */
488		if (ex->e_af == PF_UNSPEC)
489			continue;
490
491		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
492			continue;
493		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
494			continue;
495		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
496			continue;
497
498		if (pai->ai_family == PF_UNSPEC)
499			pai->ai_family = ex->e_af;
500		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
501			pai->ai_socktype = ex->e_socktype;
502		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
503			pai->ai_protocol = ex->e_protocol;
504
505		if (hostname == NULL)
506			error = explore_null(pai, servname, &cur->ai_next);
507		else
508			error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
509
510		if (error)
511			goto free;
512
513		while (cur && cur->ai_next)
514			cur = cur->ai_next;
515	}
516
517	/*
518	 * XXX
519	 * If numreic representation of AF1 can be interpreted as FQDN
520	 * representation of AF2, we need to think again about the code below.
521	 */
522	if (sentinel.ai_next)
523		goto good;
524
525	if (hostname == NULL)
526		ERR(EAI_NONAME);	/* used to be EAI_NODATA */
527	if (pai->ai_flags & AI_NUMERICHOST)
528		ERR(EAI_NONAME);
529
530	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
531		ERR(EAI_FAIL);
532
533	/*
534	 * hostname as alphabetical name.
535	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
536	 * outer loop by AFs.
537	 */
538	for (ex = explore; ex->e_af >= 0; ex++) {
539		*pai = ai0;
540
541		/* require exact match for family field */
542		if (pai->ai_family != ex->e_af)
543			continue;
544
545		if (!MATCH(pai->ai_socktype, ex->e_socktype,
546				WILD_SOCKTYPE(ex))) {
547			continue;
548		}
549		if (!MATCH(pai->ai_protocol, ex->e_protocol,
550				WILD_PROTOCOL(ex))) {
551			continue;
552		}
553
554		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
555			pai->ai_socktype = ex->e_socktype;
556		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
557			pai->ai_protocol = ex->e_protocol;
558
559		error = explore_fqdn(pai, hostname, servname,
560			&cur->ai_next);
561
562		while (cur && cur->ai_next)
563			cur = cur->ai_next;
564	}
565
566	/* XXX */
567	if (sentinel.ai_next)
568		error = 0;
569
570	if (error)
571		goto free;
572	if (error == 0) {
573		if (sentinel.ai_next) {
574 good:
575			*res = sentinel.ai_next;
576			return SUCCESS;
577		} else
578			error = EAI_FAIL;
579	}
580 free:
581 bad:
582	if (sentinel.ai_next)
583		freeaddrinfo(sentinel.ai_next);
584	*res = NULL;
585	return error;
586}
587
588/*
589 * hostname == NULL.
590 * passive socket -> anyaddr (0.0.0.0 or ::)
591 * non-passive socket -> localhost (127.0.0.1 or ::1)
592 */
593static int
594explore_null(pai, servname, res)
595	const struct addrinfo *pai;
596	const char *servname;
597	struct addrinfo **res;
598{
599	int s;
600	const struct afd *afd;
601	struct addrinfo *cur;
602	struct addrinfo sentinel;
603	int error;
604
605	*res = NULL;
606	sentinel.ai_next = NULL;
607	cur = &sentinel;
608
609	/*
610	 * filter out AFs that are not supported by the kernel
611	 * XXX errno?
612	 */
613	s = _socket(pai->ai_family, SOCK_DGRAM, 0);
614	if (s < 0) {
615		if (errno != EMFILE)
616			return 0;
617	} else
618		_close(s);
619
620	/*
621	 * if the servname does not match socktype/protocol, ignore it.
622	 */
623	if (get_portmatch(pai, servname) != 0)
624		return 0;
625
626	afd = find_afd(pai->ai_family);
627	if (afd == NULL)
628		return 0;
629
630	if (pai->ai_flags & AI_PASSIVE) {
631		GET_AI(cur->ai_next, afd, afd->a_addrany);
632		/* xxx meaningless?
633		 * GET_CANONNAME(cur->ai_next, "anyaddr");
634		 */
635		GET_PORT(cur->ai_next, servname);
636	} else {
637		GET_AI(cur->ai_next, afd, afd->a_loopback);
638		/* xxx meaningless?
639		 * GET_CANONNAME(cur->ai_next, "localhost");
640		 */
641		GET_PORT(cur->ai_next, servname);
642	}
643	cur = cur->ai_next;
644
645	*res = sentinel.ai_next;
646	return 0;
647
648free:
649	if (sentinel.ai_next)
650		freeaddrinfo(sentinel.ai_next);
651	return error;
652}
653
654/*
655 * numeric hostname
656 */
657static int
658explore_numeric(pai, hostname, servname, res)
659	const struct addrinfo *pai;
660	const char *hostname;
661	const char *servname;
662	struct addrinfo **res;
663{
664	const struct afd *afd;
665	struct addrinfo *cur;
666	struct addrinfo sentinel;
667	int error;
668	char pton[PTON_MAX];
669
670	*res = NULL;
671	sentinel.ai_next = NULL;
672	cur = &sentinel;
673
674	/*
675	 * if the servname does not match socktype/protocol, ignore it.
676	 */
677	if (get_portmatch(pai, servname) != 0)
678		return 0;
679
680	afd = find_afd(pai->ai_family);
681	if (afd == NULL)
682		return 0;
683
684	switch (afd->a_af) {
685#if 1 /*X/Open spec*/
686	case AF_INET:
687		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
688			if (pai->ai_family == afd->a_af ||
689			    pai->ai_family == PF_UNSPEC /*?*/) {
690				GET_AI(cur->ai_next, afd, pton);
691				GET_PORT(cur->ai_next, servname);
692				while (cur && cur->ai_next)
693					cur = cur->ai_next;
694			} else
695				ERR(EAI_FAMILY);	/*xxx*/
696		}
697		break;
698#endif
699	default:
700		if (inet_pton(afd->a_af, hostname, pton) == 1) {
701			if (pai->ai_family == afd->a_af ||
702			    pai->ai_family == PF_UNSPEC /*?*/) {
703				GET_AI(cur->ai_next, afd, pton);
704				GET_PORT(cur->ai_next, servname);
705				while (cur && cur->ai_next)
706					cur = cur->ai_next;
707			} else
708				ERR(EAI_FAMILY);	/* XXX */
709		}
710		break;
711	}
712
713	*res = sentinel.ai_next;
714	return 0;
715
716free:
717bad:
718	if (sentinel.ai_next)
719		freeaddrinfo(sentinel.ai_next);
720	return error;
721}
722
723/*
724 * numeric hostname with scope
725 */
726static int
727explore_numeric_scope(pai, hostname, servname, res)
728	const struct addrinfo *pai;
729	const char *hostname;
730	const char *servname;
731	struct addrinfo **res;
732{
733#if !defined(SCOPE_DELIMITER) || !defined(INET6)
734	return explore_numeric(pai, hostname, servname, res);
735#else
736	const struct afd *afd;
737	struct addrinfo *cur;
738	int error;
739	char *cp, *hostname2 = NULL, *scope, *addr;
740	struct sockaddr_in6 *sin6;
741
742	/*
743	 * if the servname does not match socktype/protocol, ignore it.
744	 */
745	if (get_portmatch(pai, servname) != 0)
746		return 0;
747
748	afd = find_afd(pai->ai_family);
749	if (afd == NULL)
750		return 0;
751
752	if (!afd->a_scoped)
753		return explore_numeric(pai, hostname, servname, res);
754
755	cp = strchr(hostname, SCOPE_DELIMITER);
756	if (cp == NULL)
757		return explore_numeric(pai, hostname, servname, res);
758
759	/*
760	 * Handle special case of <scoped_address><delimiter><scope id>
761	 */
762	hostname2 = strdup(hostname);
763	if (hostname2 == NULL)
764		return EAI_MEMORY;
765	/* terminate at the delimiter */
766	hostname2[cp - hostname] = '\0';
767	addr = hostname2;
768	scope = cp + 1;
769
770	error = explore_numeric(pai, addr, servname, res);
771	if (error == 0) {
772		u_int32_t scopeid;
773
774		for (cur = *res; cur; cur = cur->ai_next) {
775			if (cur->ai_family != AF_INET6)
776				continue;
777			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
778			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
779				free(hostname2);
780				return(EAI_NONAME); /* XXX: is return OK? */
781			}
782			sin6->sin6_scope_id = scopeid;
783		}
784	}
785
786	free(hostname2);
787
788	return error;
789#endif
790}
791
792static int
793get_canonname(pai, ai, str)
794	const struct addrinfo *pai;
795	struct addrinfo *ai;
796	const char *str;
797{
798	if ((pai->ai_flags & AI_CANONNAME) != 0) {
799		ai->ai_canonname = (char *)malloc(strlen(str) + 1);
800		if (ai->ai_canonname == NULL)
801			return EAI_MEMORY;
802		strlcpy(ai->ai_canonname, str, strlen(str) + 1);
803	}
804	return 0;
805}
806
807static struct addrinfo *
808get_ai(pai, afd, addr)
809	const struct addrinfo *pai;
810	const struct afd *afd;
811	const char *addr;
812{
813	char *p;
814	struct addrinfo *ai;
815#ifdef FAITH
816	struct in6_addr faith_prefix;
817	char *fp_str;
818	int translate = 0;
819#endif
820
821#ifdef FAITH
822	/*
823	 * Transfrom an IPv4 addr into a special IPv6 addr format for
824	 * IPv6->IPv4 translation gateway. (only TCP is supported now)
825	 *
826	 * +-----------------------------------+------------+
827	 * | faith prefix part (12 bytes)      | embedded   |
828	 * |                                   | IPv4 addr part (4 bytes)
829	 * +-----------------------------------+------------+
830	 *
831	 * faith prefix part is specified as ascii IPv6 addr format
832	 * in environmental variable GAI.
833	 * For FAITH to work correctly, routing to faith prefix must be
834	 * setup toward a machine where a FAITH daemon operates.
835	 * Also, the machine must enable some mechanizm
836	 * (e.g. faith interface hack) to divert those packet with
837	 * faith prefixed destination addr to user-land FAITH daemon.
838	 */
839	fp_str = getenv("GAI");
840	if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
841	    afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
842		u_int32_t v4a;
843		u_int8_t v4a_top;
844
845		memcpy(&v4a, addr, sizeof v4a);
846		v4a_top = v4a >> IN_CLASSA_NSHIFT;
847		if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
848		    v4a_top != 0 && v4a != IN_LOOPBACKNET) {
849			afd = &afdl[N_INET6];
850			memcpy(&faith_prefix.s6_addr[12], addr,
851			       sizeof(struct in_addr));
852			translate = 1;
853		}
854	}
855#endif
856
857	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
858		+ (afd->a_socklen));
859	if (ai == NULL)
860		return NULL;
861
862	memcpy(ai, pai, sizeof(struct addrinfo));
863	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
864	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
865	ai->ai_addr->sa_len = afd->a_socklen;
866	ai->ai_addrlen = afd->a_socklen;
867	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
868	p = (char *)(void *)(ai->ai_addr);
869#ifdef FAITH
870	if (translate == 1)
871		memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
872	else
873#endif
874	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
875	return ai;
876}
877
878static int
879get_portmatch(ai, servname)
880	const struct addrinfo *ai;
881	const char *servname;
882{
883
884	/* get_port does not touch first argument. when matchonly == 1. */
885	/* LINTED const cast */
886	return get_port((struct addrinfo *)ai, servname, 1);
887}
888
889static int
890get_port(ai, servname, matchonly)
891	struct addrinfo *ai;
892	const char *servname;
893	int matchonly;
894{
895	const char *proto;
896	struct servent *sp;
897	int port;
898	int allownumeric;
899
900	if (servname == NULL)
901		return 0;
902	switch (ai->ai_family) {
903	case AF_INET:
904#ifdef AF_INET6
905	case AF_INET6:
906#endif
907		break;
908	default:
909		return 0;
910	}
911
912	switch (ai->ai_socktype) {
913	case SOCK_RAW:
914		return EAI_SERVICE;
915	case SOCK_DGRAM:
916	case SOCK_STREAM:
917		allownumeric = 1;
918		break;
919	case ANY:
920		allownumeric = 0;
921		break;
922	default:
923		return EAI_SOCKTYPE;
924	}
925
926	if (str_isnumber(servname)) {
927		if (!allownumeric)
928			return EAI_SERVICE;
929		port = atoi(servname);
930		if (port < 0 || port > 65535)
931			return EAI_SERVICE;
932		port = htons(port);
933	} else {
934		switch (ai->ai_socktype) {
935		case SOCK_DGRAM:
936			proto = "udp";
937			break;
938		case SOCK_STREAM:
939			proto = "tcp";
940			break;
941		default:
942			proto = NULL;
943			break;
944		}
945
946		if ((sp = getservbyname(servname, proto)) == NULL)
947			return EAI_SERVICE;
948		port = sp->s_port;
949	}
950
951	if (!matchonly) {
952		switch (ai->ai_family) {
953		case AF_INET:
954			((struct sockaddr_in *)(void *)
955			    ai->ai_addr)->sin_port = port;
956			break;
957#ifdef INET6
958		case AF_INET6:
959			((struct sockaddr_in6 *)(void *)
960			    ai->ai_addr)->sin6_port = port;
961			break;
962#endif
963		}
964	}
965
966	return 0;
967}
968
969static const struct afd *
970find_afd(af)
971	int af;
972{
973	const struct afd *afd;
974
975	if (af == PF_UNSPEC)
976		return NULL;
977	for (afd = afdl; afd->a_af; afd++) {
978		if (afd->a_af == af)
979			return afd;
980	}
981	return NULL;
982}
983
984/*
985 * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
986 * will take care of it.
987 * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
988 * if the code is right or not.
989 *
990 * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
991 * _dns_getaddrinfo.
992 */
993static int
994addrconfig(pai)
995	struct addrinfo *pai;
996{
997	int s, af;
998
999	/*
1000	 * TODO:
1001	 * Note that implementation dependent test for address
1002	 * configuration should be done everytime called
1003	 * (or apropriate interval),
1004	 * because addresses will be dynamically assigned or deleted.
1005	 */
1006	af = pai->ai_family;
1007	if (af == AF_UNSPEC) {
1008		if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1009			af = AF_INET;
1010		else {
1011			_close(s);
1012			if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1013				af = AF_INET6;
1014			else
1015				_close(s);
1016		}
1017	}
1018	if (af != AF_UNSPEC) {
1019		if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
1020			return 0;
1021		_close(s);
1022	}
1023	pai->ai_family = af;
1024	return 1;
1025}
1026
1027#ifdef INET6
1028/* convert a string to a scope identifier. XXX: IPv6 specific */
1029static int
1030ip6_str2scopeid(scope, sin6, scopeid)
1031	char *scope;
1032	struct sockaddr_in6 *sin6;
1033	u_int32_t *scopeid;
1034{
1035	u_long lscopeid;
1036	struct in6_addr *a6;
1037	char *ep;
1038
1039	a6 = &sin6->sin6_addr;
1040
1041	/* empty scopeid portion is invalid */
1042	if (*scope == '\0')
1043		return -1;
1044
1045	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1046		/*
1047		 * We currently assume a one-to-one mapping between links
1048		 * and interfaces, so we simply use interface indices for
1049		 * like-local scopes.
1050		 */
1051		*scopeid = if_nametoindex(scope);
1052		if (*scopeid == 0)
1053			goto trynumeric;
1054		return 0;
1055	}
1056
1057	/* still unclear about literal, allow numeric only - placeholder */
1058	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1059		goto trynumeric;
1060	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1061		goto trynumeric;
1062	else
1063		goto trynumeric;	/* global */
1064
1065	/* try to convert to a numeric id as a last resort */
1066  trynumeric:
1067	errno = 0;
1068	lscopeid = strtoul(scope, &ep, 10);
1069	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1070	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1071		return 0;
1072	else
1073		return -1;
1074}
1075#endif
1076
1077/*
1078 * FQDN hostname, DNS lookup
1079 */
1080static int
1081explore_fqdn(pai, hostname, servname, res)
1082	const struct addrinfo *pai;
1083	const char *hostname;
1084	const char *servname;
1085	struct addrinfo **res;
1086{
1087	struct addrinfo *result;
1088	struct addrinfo *cur;
1089	int error = 0;
1090	static const ns_dtab dtab[] = {
1091		NS_FILES_CB(_files_getaddrinfo, NULL)
1092		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
1093		NS_NIS_CB(_yp_getaddrinfo, NULL)
1094		{ 0 }
1095	};
1096
1097	result = NULL;
1098
1099	THREAD_LOCK();
1100
1101	/*
1102	 * if the servname does not match socktype/protocol, ignore it.
1103	 */
1104	if (get_portmatch(pai, servname) != 0) {
1105		THREAD_UNLOCK();
1106		return 0;
1107	}
1108
1109	switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1110			default_dns_files, hostname, pai)) {
1111	case NS_TRYAGAIN:
1112		error = EAI_AGAIN;
1113		goto free;
1114	case NS_UNAVAIL:
1115		error = EAI_FAIL;
1116		goto free;
1117	case NS_NOTFOUND:
1118		error = EAI_NONAME;
1119		goto free;
1120	case NS_SUCCESS:
1121		error = 0;
1122		for (cur = result; cur; cur = cur->ai_next) {
1123			GET_PORT(cur, servname);
1124			/* canonname should be filled already */
1125		}
1126		break;
1127	}
1128	THREAD_UNLOCK();
1129
1130	*res = result;
1131
1132	return 0;
1133
1134free:
1135	THREAD_UNLOCK();
1136	if (result)
1137		freeaddrinfo(result);
1138	return error;
1139}
1140
1141#ifdef DEBUG
1142static const char AskedForGot[] =
1143	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1144#endif
1145static FILE *hostf = NULL;
1146
1147static struct addrinfo *
1148getanswer(answer, anslen, qname, qtype, pai)
1149	const querybuf *answer;
1150	int anslen;
1151	const char *qname;
1152	int qtype;
1153	const struct addrinfo *pai;
1154{
1155	struct addrinfo sentinel, *cur;
1156	struct addrinfo ai;
1157	const struct afd *afd;
1158	char *canonname;
1159	const HEADER *hp;
1160	const u_char *cp;
1161	int n;
1162	const u_char *eom;
1163	char *bp, *ep;
1164	int type, class, ancount, qdcount;
1165	int haveanswer, had_error;
1166	char tbuf[MAXDNAME];
1167	int (*name_ok)(const char *);
1168	char hostbuf[8*1024];
1169
1170	memset(&sentinel, 0, sizeof(sentinel));
1171	cur = &sentinel;
1172
1173	canonname = NULL;
1174	eom = answer->buf + anslen;
1175	switch (qtype) {
1176	case T_A:
1177	case T_AAAA:
1178	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
1179		name_ok = res_hnok;
1180		break;
1181	default:
1182		return (NULL);	/* XXX should be abort(); */
1183	}
1184	/*
1185	 * find first satisfactory answer
1186	 */
1187	hp = &answer->hdr;
1188	ancount = ntohs(hp->ancount);
1189	qdcount = ntohs(hp->qdcount);
1190	bp = hostbuf;
1191	ep = hostbuf + sizeof hostbuf;
1192	cp = answer->buf + HFIXEDSZ;
1193	if (qdcount != 1) {
1194		h_errno = NO_RECOVERY;
1195		return (NULL);
1196	}
1197	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1198	if ((n < 0) || !(*name_ok)(bp)) {
1199		h_errno = NO_RECOVERY;
1200		return (NULL);
1201	}
1202	cp += n + QFIXEDSZ;
1203	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1204		/* res_send() has already verified that the query name is the
1205		 * same as the one we sent; this just gets the expanded name
1206		 * (i.e., with the succeeding search-domain tacked on).
1207		 */
1208		n = strlen(bp) + 1;		/* for the \0 */
1209		if (n >= MAXHOSTNAMELEN) {
1210			h_errno = NO_RECOVERY;
1211			return (NULL);
1212		}
1213		canonname = bp;
1214		bp += n;
1215		/* The qname can be abbreviated, but h_name is now absolute. */
1216		qname = canonname;
1217	}
1218	haveanswer = 0;
1219	had_error = 0;
1220	while (ancount-- > 0 && cp < eom && !had_error) {
1221		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1222		if ((n < 0) || !(*name_ok)(bp)) {
1223			had_error++;
1224			continue;
1225		}
1226		cp += n;			/* name */
1227		type = _getshort(cp);
1228 		cp += INT16SZ;			/* type */
1229		class = _getshort(cp);
1230 		cp += INT16SZ + INT32SZ;	/* class, TTL */
1231		n = _getshort(cp);
1232		cp += INT16SZ;			/* len */
1233		if (class != C_IN) {
1234			/* XXX - debug? syslog? */
1235			cp += n;
1236			continue;		/* XXX - had_error++ ? */
1237		}
1238		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1239		    type == T_CNAME) {
1240			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1241			if ((n < 0) || !(*name_ok)(tbuf)) {
1242				had_error++;
1243				continue;
1244			}
1245			cp += n;
1246			/* Get canonical name. */
1247			n = strlen(tbuf) + 1;	/* for the \0 */
1248			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1249				had_error++;
1250				continue;
1251			}
1252			strlcpy(bp, tbuf, ep - bp);
1253			canonname = bp;
1254			bp += n;
1255			continue;
1256		}
1257		if (qtype == T_ANY) {
1258			if (!(type == T_A || type == T_AAAA)) {
1259				cp += n;
1260				continue;
1261			}
1262		} else if (type != qtype) {
1263#ifdef DEBUG
1264			if (type != T_KEY && type != T_SIG)
1265				syslog(LOG_NOTICE|LOG_AUTH,
1266	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1267				       qname, p_class(C_IN), p_type(qtype),
1268				       p_type(type));
1269#endif
1270			cp += n;
1271			continue;		/* XXX - had_error++ ? */
1272		}
1273		switch (type) {
1274		case T_A:
1275		case T_AAAA:
1276			if (strcasecmp(canonname, bp) != 0) {
1277#ifdef DEBUG
1278				syslog(LOG_NOTICE|LOG_AUTH,
1279				       AskedForGot, canonname, bp);
1280#endif
1281				cp += n;
1282				continue;	/* XXX - had_error++ ? */
1283			}
1284			if (type == T_A && n != INADDRSZ) {
1285				cp += n;
1286				continue;
1287			}
1288			if (type == T_AAAA && n != IN6ADDRSZ) {
1289				cp += n;
1290				continue;
1291			}
1292#ifdef FILTER_V4MAPPED
1293			if (type == T_AAAA) {
1294				struct in6_addr in6;
1295				memcpy(&in6, cp, sizeof(in6));
1296				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1297					cp += n;
1298					continue;
1299				}
1300			}
1301#endif
1302			if (!haveanswer) {
1303				int nn;
1304
1305				canonname = bp;
1306				nn = strlen(bp) + 1;	/* for the \0 */
1307				bp += nn;
1308			}
1309
1310			/* don't overwrite pai */
1311			ai = *pai;
1312			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1313			afd = find_afd(ai.ai_family);
1314			if (afd == NULL) {
1315				cp += n;
1316				continue;
1317			}
1318			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1319			if (cur->ai_next == NULL)
1320				had_error++;
1321			while (cur && cur->ai_next)
1322				cur = cur->ai_next;
1323			cp += n;
1324			break;
1325		default:
1326			abort();
1327		}
1328		if (!had_error)
1329			haveanswer++;
1330	}
1331	if (haveanswer) {
1332#if defined(RESOLVSORT)
1333		/*
1334		 * We support only IPv4 address for backward
1335		 * compatibility against gethostbyname(3).
1336		 */
1337		if (_res.nsort && qtype == T_A) {
1338			if (addr4sort(&sentinel) < 0) {
1339				freeaddrinfo(sentinel.ai_next);
1340				h_errno = NO_RECOVERY;
1341				return NULL;
1342			}
1343		}
1344#endif /*RESOLVSORT*/
1345		if (!canonname)
1346			(void)get_canonname(pai, sentinel.ai_next, qname);
1347		else
1348			(void)get_canonname(pai, sentinel.ai_next, canonname);
1349		h_errno = NETDB_SUCCESS;
1350		return sentinel.ai_next;
1351	}
1352
1353	h_errno = NO_RECOVERY;
1354	return NULL;
1355}
1356
1357#ifdef RESOLVSORT
1358struct addr_ptr {
1359	struct addrinfo *ai;
1360	int aval;
1361};
1362
1363static int
1364addr4sort(struct addrinfo *sentinel)
1365{
1366	struct addrinfo *ai;
1367	struct addr_ptr *addrs, addr;
1368	struct sockaddr_in *sin;
1369	int naddrs, i, j;
1370	int needsort = 0;
1371
1372	if (!sentinel)
1373		return -1;
1374	naddrs = 0;
1375	for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
1376		naddrs++;
1377	if (naddrs < 2)
1378		return 0;		/* We don't need sorting. */
1379	if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
1380		return -1;
1381	i = 0;
1382	for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
1383		sin = (struct sockaddr_in *)ai->ai_addr;
1384		for (j = 0; (unsigned)j < _res.nsort; j++) {
1385			if (_res.sort_list[j].addr.s_addr ==
1386			    (sin->sin_addr.s_addr & _res.sort_list[j].mask))
1387				break;
1388		}
1389		addrs[i].ai = ai;
1390		addrs[i].aval = j;
1391		if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
1392			needsort = i;
1393		i++;
1394	}
1395	if (!needsort) {
1396		free(addrs);
1397		return 0;
1398	}
1399
1400	while (needsort < naddrs) {
1401	    for (j = needsort - 1; j >= 0; j--) {
1402		if (addrs[j].aval > addrs[j+1].aval) {
1403		    addr = addrs[j];
1404		    addrs[j] = addrs[j + 1];
1405		    addrs[j + 1] = addr;
1406		} else
1407		    break;
1408	    }
1409	    needsort++;
1410	}
1411
1412	ai = sentinel;
1413	for (i = 0; i < naddrs; ++i) {
1414		ai->ai_next = addrs[i].ai;
1415		ai = ai->ai_next;
1416	}
1417	ai->ai_next = NULL;
1418	free(addrs);
1419	return 0;
1420}
1421#endif /*RESOLVSORT*/
1422
1423/*ARGSUSED*/
1424static int
1425_dns_getaddrinfo(rv, cb_data, ap)
1426	void	*rv;
1427	void	*cb_data;
1428	va_list	 ap;
1429{
1430	struct addrinfo *ai;
1431	querybuf *buf, *buf2;
1432	const char *name;
1433	const struct addrinfo *pai;
1434	struct addrinfo sentinel, *cur;
1435	struct res_target q, q2;
1436
1437	name = va_arg(ap, char *);
1438	pai = va_arg(ap, const struct addrinfo *);
1439
1440	memset(&q, 0, sizeof(q2));
1441	memset(&q2, 0, sizeof(q2));
1442	memset(&sentinel, 0, sizeof(sentinel));
1443	cur = &sentinel;
1444
1445	buf = malloc(sizeof(*buf));
1446	if (!buf) {
1447		h_errno = NETDB_INTERNAL;
1448		return NS_NOTFOUND;
1449	}
1450	buf2 = malloc(sizeof(*buf2));
1451	if (!buf2) {
1452		free(buf);
1453		h_errno = NETDB_INTERNAL;
1454		return NS_NOTFOUND;
1455	}
1456
1457	switch (pai->ai_family) {
1458	case AF_UNSPEC:
1459		/* prefer IPv6 */
1460		q.name = name;
1461		q.qclass = C_IN;
1462		q.qtype = T_AAAA;
1463		q.answer = buf->buf;
1464		q.anslen = sizeof(buf->buf);
1465		q.next = &q2;
1466		q2.name = name;
1467		q2.qclass = C_IN;
1468		q2.qtype = T_A;
1469		q2.answer = buf2->buf;
1470		q2.anslen = sizeof(buf2->buf);
1471		break;
1472	case AF_INET:
1473		q.name = name;
1474		q.qclass = C_IN;
1475		q.qtype = T_A;
1476		q.answer = buf->buf;
1477		q.anslen = sizeof(buf->buf);
1478		break;
1479	case AF_INET6:
1480		q.name = name;
1481		q.qclass = C_IN;
1482		q.qtype = T_AAAA;
1483		q.answer = buf->buf;
1484		q.anslen = sizeof(buf->buf);
1485		break;
1486	default:
1487		free(buf);
1488		free(buf2);
1489		return NS_UNAVAIL;
1490	}
1491	if (res_searchN(name, &q) < 0) {
1492		free(buf);
1493		free(buf2);
1494		return NS_NOTFOUND;
1495	}
1496	ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1497	if (ai) {
1498		cur->ai_next = ai;
1499		while (cur && cur->ai_next)
1500			cur = cur->ai_next;
1501	}
1502	if (q.next) {
1503		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1504		if (ai)
1505			cur->ai_next = ai;
1506	}
1507	free(buf);
1508	free(buf2);
1509	if (sentinel.ai_next == NULL)
1510		switch (h_errno) {
1511		case HOST_NOT_FOUND:
1512			return NS_NOTFOUND;
1513		case TRY_AGAIN:
1514			return NS_TRYAGAIN;
1515		default:
1516			return NS_UNAVAIL;
1517		}
1518	*((struct addrinfo **)rv) = sentinel.ai_next;
1519	return NS_SUCCESS;
1520}
1521
1522static void
1523_sethtent()
1524{
1525	if (!hostf)
1526		hostf = fopen(_PATH_HOSTS, "r" );
1527	else
1528		rewind(hostf);
1529}
1530
1531static void
1532_endhtent()
1533{
1534	if (hostf) {
1535		(void) fclose(hostf);
1536		hostf = NULL;
1537	}
1538}
1539
1540static struct addrinfo *
1541_gethtent(name, pai)
1542	const char *name;
1543	const struct addrinfo *pai;
1544{
1545	char *p;
1546	char *cp, *tname, *cname;
1547	struct addrinfo hints, *res0, *res;
1548	int error;
1549	const char *addr;
1550	char hostbuf[8*1024];
1551
1552	if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" )))
1553		return (NULL);
1554again:
1555	if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
1556		return (NULL);
1557	if (*p == '#')
1558		goto again;
1559	if (!(cp = strpbrk(p, "#\n")))
1560		goto again;
1561	*cp = '\0';
1562	if (!(cp = strpbrk(p, " \t")))
1563		goto again;
1564	*cp++ = '\0';
1565	addr = p;
1566	cname = NULL;
1567	/* if this is not something we're looking for, skip it. */
1568	while (cp && *cp) {
1569		if (*cp == ' ' || *cp == '\t') {
1570			cp++;
1571			continue;
1572		}
1573		tname = cp;
1574		if (cname == NULL)
1575			cname = cp;
1576		if ((cp = strpbrk(cp, " \t")) != NULL)
1577			*cp++ = '\0';
1578		if (strcasecmp(name, tname) == 0)
1579			goto found;
1580	}
1581	goto again;
1582
1583found:
1584	/* we should not glob socktype/protocol here */
1585	memset(&hints, 0, sizeof(hints));
1586	hints.ai_family = pai->ai_family;
1587	hints.ai_socktype = SOCK_DGRAM;
1588	hints.ai_protocol = 0;
1589	hints.ai_flags = AI_NUMERICHOST;
1590	error = getaddrinfo(addr, "0", &hints, &res0);
1591	if (error)
1592		goto again;
1593#ifdef FILTER_V4MAPPED
1594	/* XXX should check all items in the chain */
1595	if (res0->ai_family == AF_INET6 &&
1596	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
1597		freeaddrinfo(res0);
1598		goto again;
1599	}
1600#endif
1601	for (res = res0; res; res = res->ai_next) {
1602		/* cover it up */
1603		res->ai_flags = pai->ai_flags;
1604		res->ai_socktype = pai->ai_socktype;
1605		res->ai_protocol = pai->ai_protocol;
1606
1607		if (pai->ai_flags & AI_CANONNAME) {
1608			if (get_canonname(pai, res, cname) != 0) {
1609				freeaddrinfo(res0);
1610				goto again;
1611			}
1612		}
1613	}
1614	return res0;
1615}
1616
1617/*ARGSUSED*/
1618static int
1619_files_getaddrinfo(rv, cb_data, ap)
1620	void	*rv;
1621	void	*cb_data;
1622	va_list	 ap;
1623{
1624	const char *name;
1625	const struct addrinfo *pai;
1626	struct addrinfo sentinel, *cur;
1627	struct addrinfo *p;
1628
1629	name = va_arg(ap, char *);
1630	pai = va_arg(ap, struct addrinfo *);
1631
1632	memset(&sentinel, 0, sizeof(sentinel));
1633	cur = &sentinel;
1634
1635	_sethtent();
1636	while ((p = _gethtent(name, pai)) != NULL) {
1637		cur->ai_next = p;
1638		while (cur && cur->ai_next)
1639			cur = cur->ai_next;
1640	}
1641	_endhtent();
1642
1643	*((struct addrinfo **)rv) = sentinel.ai_next;
1644	if (sentinel.ai_next == NULL)
1645		return NS_NOTFOUND;
1646	return NS_SUCCESS;
1647}
1648
1649#ifdef YP
1650static char *__ypdomain;
1651
1652/*ARGSUSED*/
1653static struct addrinfo *
1654_yphostent(line, pai)
1655	char *line;
1656	const struct addrinfo *pai;
1657{
1658	struct addrinfo sentinel, *cur;
1659	struct addrinfo hints, *res, *res0;
1660	int error;
1661	char *p = line;
1662	const char *addr, *canonname;
1663	char *nextline;
1664	char *cp;
1665
1666	addr = canonname = NULL;
1667
1668	memset(&sentinel, 0, sizeof(sentinel));
1669	cur = &sentinel;
1670
1671nextline:
1672	/* terminate line */
1673	cp = strchr(p, '\n');
1674	if (cp) {
1675		*cp++ = '\0';
1676		nextline = cp;
1677	} else
1678		nextline = NULL;
1679
1680	cp = strpbrk(p, " \t");
1681	if (cp == NULL) {
1682		if (canonname == NULL)
1683			return (NULL);
1684		else
1685			goto done;
1686	}
1687	*cp++ = '\0';
1688
1689	addr = p;
1690
1691	while (cp && *cp) {
1692		if (*cp == ' ' || *cp == '\t') {
1693			cp++;
1694			continue;
1695		}
1696		if (!canonname)
1697			canonname = cp;
1698		if ((cp = strpbrk(cp, " \t")) != NULL)
1699			*cp++ = '\0';
1700	}
1701
1702	hints = *pai;
1703	hints.ai_flags = AI_NUMERICHOST;
1704	error = getaddrinfo(addr, NULL, &hints, &res0);
1705	if (error == 0) {
1706		for (res = res0; res; res = res->ai_next) {
1707			/* cover it up */
1708			res->ai_flags = pai->ai_flags;
1709
1710			if (pai->ai_flags & AI_CANONNAME)
1711				(void)get_canonname(pai, res, canonname);
1712		}
1713	} else
1714		res0 = NULL;
1715	if (res0) {
1716		cur->ai_next = res0;
1717		while (cur && cur->ai_next)
1718			cur = cur->ai_next;
1719	}
1720
1721	if (nextline) {
1722		p = nextline;
1723		goto nextline;
1724	}
1725
1726done:
1727	return sentinel.ai_next;
1728}
1729
1730/*ARGSUSED*/
1731static int
1732_yp_getaddrinfo(rv, cb_data, ap)
1733	void	*rv;
1734	void	*cb_data;
1735	va_list	 ap;
1736{
1737	struct addrinfo sentinel, *cur;
1738	struct addrinfo *ai = NULL;
1739	static char *__ypcurrent;
1740	int __ypcurrentlen, r;
1741	const char *name;
1742	const struct addrinfo *pai;
1743
1744	name = va_arg(ap, char *);
1745	pai = va_arg(ap, const struct addrinfo *);
1746
1747	memset(&sentinel, 0, sizeof(sentinel));
1748	cur = &sentinel;
1749
1750	if (!__ypdomain) {
1751		if (_yp_check(&__ypdomain) == 0)
1752			return NS_UNAVAIL;
1753	}
1754	if (__ypcurrent)
1755		free(__ypcurrent);
1756	__ypcurrent = NULL;
1757
1758	/* hosts.byname is only for IPv4 (Solaris8) */
1759	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
1760		r = yp_match(__ypdomain, "hosts.byname", name,
1761			(int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1762		if (r == 0) {
1763			struct addrinfo ai4;
1764
1765			ai4 = *pai;
1766			ai4.ai_family = AF_INET;
1767			ai = _yphostent(__ypcurrent, &ai4);
1768			if (ai) {
1769				cur->ai_next = ai;
1770				while (cur && cur->ai_next)
1771					cur = cur->ai_next;
1772			}
1773		}
1774	}
1775
1776	/* ipnodes.byname can hold both IPv4/v6 */
1777	r = yp_match(__ypdomain, "ipnodes.byname", name,
1778		(int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1779	if (r == 0) {
1780		ai = _yphostent(__ypcurrent, pai);
1781		if (ai) {
1782			cur->ai_next = ai;
1783			while (cur && cur->ai_next)
1784				cur = cur->ai_next;
1785		}
1786	}
1787
1788	if (sentinel.ai_next == NULL) {
1789		h_errno = HOST_NOT_FOUND;
1790		return NS_NOTFOUND;
1791	}
1792	*((struct addrinfo **)rv) = sentinel.ai_next;
1793	return NS_SUCCESS;
1794}
1795#endif
1796
1797/* resolver logic */
1798
1799extern const char *__hostalias(const char *);
1800extern int h_errno;
1801
1802/*
1803 * Formulate a normal query, send, and await answer.
1804 * Returned answer is placed in supplied buffer "answer".
1805 * Perform preliminary check of answer, returning success only
1806 * if no error is indicated and the answer count is nonzero.
1807 * Return the size of the response on success, -1 on error.
1808 * Error number is left in h_errno.
1809 *
1810 * Caller must parse answer and determine whether it answers the question.
1811 */
1812static int
1813res_queryN(name, target)
1814	const char *name;	/* domain name */
1815	struct res_target *target;
1816{
1817	u_char *buf;
1818	HEADER *hp;
1819	int n;
1820	struct res_target *t;
1821	int rcode;
1822	int ancount;
1823
1824	rcode = NOERROR;
1825	ancount = 0;
1826
1827	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1828		h_errno = NETDB_INTERNAL;
1829		return (-1);
1830	}
1831
1832	buf = malloc(MAXPACKET);
1833	if (!buf) {
1834		h_errno = NETDB_INTERNAL;
1835		return -1;
1836	}
1837
1838	for (t = target; t; t = t->next) {
1839		int class, type;
1840		u_char *answer;
1841		int anslen;
1842
1843		hp = (HEADER *)(void *)t->answer;
1844		hp->rcode = NOERROR;	/* default */
1845
1846		/* make it easier... */
1847		class = t->qclass;
1848		type = t->qtype;
1849		answer = t->answer;
1850		anslen = t->anslen;
1851#ifdef DEBUG
1852		if (_res.options & RES_DEBUG)
1853			printf(";; res_query(%s, %d, %d)\n", name, class, type);
1854#endif
1855
1856		n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
1857		    buf, MAXPACKET);
1858		if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
1859			n = res_opt(n, buf, MAXPACKET, anslen);
1860		if (n <= 0) {
1861#ifdef DEBUG
1862			if (_res.options & RES_DEBUG)
1863				printf(";; res_query: mkquery failed\n");
1864#endif
1865			free(buf);
1866			h_errno = NO_RECOVERY;
1867			return (n);
1868		}
1869		n = res_send(buf, n, answer, anslen);
1870#if 0
1871		if (n < 0) {
1872#ifdef DEBUG
1873			if (_res.options & RES_DEBUG)
1874				printf(";; res_query: send error\n");
1875#endif
1876			free(buf);
1877			h_errno = TRY_AGAIN;
1878			return (n);
1879		}
1880#endif
1881
1882		if (n < 0 || n > anslen)
1883			hp->rcode = FORMERR; /* XXX not very informative */
1884		if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1885			rcode = hp->rcode;	/* record most recent error */
1886#ifdef DEBUG
1887			if (_res.options & RES_DEBUG)
1888				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
1889				    ntohs(hp->ancount));
1890#endif
1891			continue;
1892		}
1893
1894		ancount += ntohs(hp->ancount);
1895
1896		t->n = n;
1897	}
1898
1899	free(buf);
1900
1901	if (ancount == 0) {
1902		switch (rcode) {
1903		case NXDOMAIN:
1904			h_errno = HOST_NOT_FOUND;
1905			break;
1906		case SERVFAIL:
1907			h_errno = TRY_AGAIN;
1908			break;
1909		case NOERROR:
1910			h_errno = NO_DATA;
1911			break;
1912		case FORMERR:
1913		case NOTIMP:
1914		case REFUSED:
1915		default:
1916			h_errno = NO_RECOVERY;
1917			break;
1918		}
1919		return (-1);
1920	}
1921	return (ancount);
1922}
1923
1924/*
1925 * Formulate a normal query, send, and retrieve answer in supplied buffer.
1926 * Return the size of the response on success, -1 on error.
1927 * If enabled, implement search rules until answer or unrecoverable failure
1928 * is detected.  Error code, if any, is left in h_errno.
1929 */
1930static int
1931res_searchN(name, target)
1932	const char *name;	/* domain name */
1933	struct res_target *target;
1934{
1935	const char *cp, * const *domain;
1936	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
1937	u_int dots;
1938	int trailing_dot, ret, saved_herrno;
1939	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1940
1941	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1942		h_errno = NETDB_INTERNAL;
1943		return (-1);
1944	}
1945
1946	errno = 0;
1947	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
1948	dots = 0;
1949	for (cp = name; *cp; cp++)
1950		dots += (*cp == '.');
1951	trailing_dot = 0;
1952	if (cp > name && *--cp == '.')
1953		trailing_dot++;
1954
1955	/*
1956	 * if there aren't any dots, it could be a user-level alias
1957	 */
1958	if (!dots && (cp = __hostalias(name)) != NULL)
1959		return (res_queryN(cp, target));
1960
1961	/*
1962	 * If there are dots in the name already, let's just give it a try
1963	 * 'as is'.  The threshold can be set with the "ndots" option.
1964	 */
1965	saved_herrno = -1;
1966	if (dots >= _res.ndots) {
1967		ret = res_querydomainN(name, NULL, target);
1968		if (ret > 0)
1969			return (ret);
1970		saved_herrno = h_errno;
1971		tried_as_is++;
1972	}
1973
1974	/*
1975	 * We do at least one level of search if
1976	 *	- there is no dot and RES_DEFNAME is set, or
1977	 *	- there is at least one dot, there is no trailing dot,
1978	 *	  and RES_DNSRCH is set.
1979	 */
1980	if ((!dots && (_res.options & RES_DEFNAMES)) ||
1981	    (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
1982		int done = 0;
1983
1984		for (domain = (const char * const *)_res.dnsrch;
1985		   *domain && !done;
1986		   domain++) {
1987
1988			ret = res_querydomainN(name, *domain, target);
1989			if (ret > 0)
1990				return (ret);
1991
1992			/*
1993			 * If no server present, give up.
1994			 * If name isn't found in this domain,
1995			 * keep trying higher domains in the search list
1996			 * (if that's enabled).
1997			 * On a NO_DATA error, keep trying, otherwise
1998			 * a wildcard entry of another type could keep us
1999			 * from finding this entry higher in the domain.
2000			 * If we get some other error (negative answer or
2001			 * server failure), then stop searching up,
2002			 * but try the input name below in case it's
2003			 * fully-qualified.
2004			 */
2005			if (errno == ECONNREFUSED) {
2006				h_errno = TRY_AGAIN;
2007				return (-1);
2008			}
2009
2010			switch (h_errno) {
2011			case NO_DATA:
2012				got_nodata++;
2013				/* FALLTHROUGH */
2014			case HOST_NOT_FOUND:
2015				/* keep trying */
2016				break;
2017			case TRY_AGAIN:
2018				if (hp->rcode == SERVFAIL) {
2019					/* try next search element, if any */
2020					got_servfail++;
2021					break;
2022				}
2023				/* FALLTHROUGH */
2024			default:
2025				/* anything else implies that we're done */
2026				done++;
2027			}
2028			/*
2029			 * if we got here for some reason other than DNSRCH,
2030			 * we only wanted one iteration of the loop, so stop.
2031			 */
2032			if (!(_res.options & RES_DNSRCH))
2033			        done++;
2034		}
2035	}
2036
2037	/*
2038	 * if we have not already tried the name "as is", do that now.
2039	 * note that we do this regardless of how many dots were in the
2040	 * name or whether it ends with a dot.
2041	 */
2042	if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
2043		ret = res_querydomainN(name, NULL, target);
2044		if (ret > 0)
2045			return (ret);
2046	}
2047
2048	/*
2049	 * if we got here, we didn't satisfy the search.
2050	 * if we did an initial full query, return that query's h_errno
2051	 * (note that we wouldn't be here if that query had succeeded).
2052	 * else if we ever got a nodata, send that back as the reason.
2053	 * else send back meaningless h_errno, that being the one from
2054	 * the last DNSRCH we did.
2055	 */
2056	if (saved_herrno != -1)
2057		h_errno = saved_herrno;
2058	else if (got_nodata)
2059		h_errno = NO_DATA;
2060	else if (got_servfail)
2061		h_errno = TRY_AGAIN;
2062	return (-1);
2063}
2064
2065/*
2066 * Perform a call on res_query on the concatenation of name and domain,
2067 * removing a trailing dot from name if domain is NULL.
2068 */
2069static int
2070res_querydomainN(name, domain, target)
2071	const char *name, *domain;
2072	struct res_target *target;
2073{
2074	char nbuf[MAXDNAME];
2075	const char *longname = nbuf;
2076	size_t n, d;
2077
2078	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
2079		h_errno = NETDB_INTERNAL;
2080		return (-1);
2081	}
2082#ifdef DEBUG
2083	if (_res.options & RES_DEBUG)
2084		printf(";; res_querydomain(%s, %s)\n",
2085			name, domain?domain:"<Nil>");
2086#endif
2087	if (domain == NULL) {
2088		/*
2089		 * Check for trailing '.';
2090		 * copy without '.' if present.
2091		 */
2092		n = strlen(name);
2093		if (n >= MAXDNAME) {
2094			h_errno = NO_RECOVERY;
2095			return (-1);
2096		}
2097		if (n > 0 && name[--n] == '.') {
2098			strncpy(nbuf, name, n);
2099			nbuf[n] = '\0';
2100		} else
2101			longname = name;
2102	} else {
2103		n = strlen(name);
2104		d = strlen(domain);
2105		if (n + d + 1 >= MAXDNAME) {
2106			h_errno = NO_RECOVERY;
2107			return (-1);
2108		}
2109		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2110	}
2111	return (res_queryN(longname, target));
2112}
2113