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