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