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