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