xref: /freebsd/lib/libc/net/name6.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
1 /*	$KAME: name6.c,v 1.25 2000/06/26 16:44:40 itojun Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, 1998, and 1999 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  * ++Copyright++ 1985, 1988, 1993
33  * -
34  * Copyright (c) 1985, 1988, 1993
35  *    The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  * 	This product includes software developed by the University of
48  * 	California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  * -
65  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
66  *
67  * Permission to use, copy, modify, and distribute this software for any
68  * purpose with or without fee is hereby granted, provided that the above
69  * copyright notice and this permission notice appear in all copies, and that
70  * the name of Digital Equipment Corporation not be used in advertising or
71  * publicity pertaining to distribution of the document or software without
72  * specific, written prior permission.
73  *
74  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
75  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
76  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
77  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
78  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
79  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
80  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
81  * SOFTWARE.
82  * -
83  * --Copyright--
84  */
85 
86 /*
87  *	Atsushi Onoe <onoe@sm.sony.co.jp>
88  */
89 
90 /*
91  * TODO for thread safe
92  *	use mutex for _hostconf, _hostconf_init.
93  *	rewrite resolvers to be thread safe
94  */
95 
96 #include <sys/cdefs.h>
97 __FBSDID("$FreeBSD$");
98 
99 #include "namespace.h"
100 #include <sys/param.h>
101 #include <sys/socket.h>
102 #include <sys/time.h>
103 #include <sys/queue.h>
104 #include <netinet/in.h>
105 
106 #include <arpa/inet.h>
107 #include <arpa/nameser.h>
108 
109 #include <errno.h>
110 #include <netdb.h>
111 #include <resolv.h>
112 #include <stdio.h>
113 #include <stdlib.h>
114 #include <string.h>
115 #include <stdarg.h>
116 #include <nsswitch.h>
117 #include <unistd.h>
118 #include "un-namespace.h"
119 
120 #ifndef _PATH_HOSTS
121 #define	_PATH_HOSTS	"/etc/hosts"
122 #endif
123 
124 #ifndef MAXALIASES
125 #define	MAXALIASES	10
126 #endif
127 #ifndef	MAXADDRS
128 #define	MAXADDRS	20
129 #endif
130 #ifndef MAXDNAME
131 #define	MAXDNAME	1025
132 #endif
133 
134 #ifdef INET6
135 #define	ADDRLEN(af)	((af) == AF_INET6 ? sizeof(struct in6_addr) : \
136 					    sizeof(struct in_addr))
137 #else
138 #define	ADDRLEN(af)	sizeof(struct in_addr)
139 #endif
140 
141 #define	MAPADDR(ab, ina) \
142 do {									\
143 	memcpy(&(ab)->map_inaddr, ina, sizeof(struct in_addr));		\
144 	memset((ab)->map_zero, 0, sizeof((ab)->map_zero));		\
145 	memset((ab)->map_one, 0xff, sizeof((ab)->map_one));		\
146 } while (0)
147 #define	MAPADDRENABLED(flags) \
148 	(((flags) & AI_V4MAPPED) || \
149 	 (((flags) & AI_V4MAPPED_CFG) && _mapped_addr_enabled()))
150 
151 union inx_addr {
152 	struct in_addr	in_addr;
153 #ifdef INET6
154 	struct in6_addr	in6_addr;
155 #endif
156 	struct {
157 		u_char	mau_zero[10];
158 		u_char	mau_one[2];
159 		struct in_addr mau_inaddr;
160 	}		map_addr_un;
161 #define	map_zero	map_addr_un.mau_zero
162 #define	map_one		map_addr_un.mau_one
163 #define	map_inaddr	map_addr_un.mau_inaddr
164 };
165 
166 static struct	 hostent *_hpcopy(struct hostent *hp, int *errp);
167 static struct	 hostent *_hpaddr(int af, const char *name, void *addr, int *errp);
168 static struct	 hostent *_hpmerge(struct hostent *hp1, struct hostent *hp2, int *errp);
169 #ifdef INET6
170 static struct	 hostent *_hpmapv6(struct hostent *hp, int *errp);
171 #endif
172 static struct	 hostent *_hpsort(struct hostent *hp);
173 static struct	 hostent *_ghbyname(const char *name, int af, int flags, int *errp);
174 static char	*_hgetword(char **pp);
175 static int	 _mapped_addr_enabled(void);
176 
177 static FILE	*_files_open(int *errp);
178 static int	 _files_ghbyname(void *, void *, va_list);
179 static int	 _files_ghbyaddr(void *, void *, va_list);
180 #ifdef YP
181 static int	 _nis_ghbyname(void *, void *, va_list);
182 static int	 _nis_ghbyaddr(void *, void *, va_list);
183 #endif
184 static int	 _dns_ghbyname(void *, void *, va_list);
185 static int	 _dns_ghbyaddr(void *, void *, va_list);
186 static void	 _dns_shent(int stayopen) __unused;
187 static void	 _dns_ehent(void) __unused;
188 #ifdef ICMPNL
189 static int	 _icmp_ghbyaddr(void *, void *, va_list);
190 #endif /* ICMPNL */
191 
192 /* Make getipnodeby*() thread-safe in libc for use with kernel threads. */
193 #include "libc_private.h"
194 #include "spinlock.h"
195 /*
196  * XXX: Our res_*() is not thread-safe.  So, we share lock between
197  * getaddrinfo() and getipnodeby*().  Still, we cannot use
198  * getaddrinfo() and getipnodeby*() in conjunction with other
199  * functions which call res_*().
200  */
201 extern spinlock_t __getaddrinfo_thread_lock;
202 #define THREAD_LOCK() \
203 	if (__isthreaded) _SPINLOCK(&__getaddrinfo_thread_lock);
204 #define THREAD_UNLOCK() \
205 	if (__isthreaded) _SPINUNLOCK(&__getaddrinfo_thread_lock);
206 
207 /* Host lookup order if nsswitch.conf is broken or nonexistant */
208 static const ns_src default_src[] = {
209 	{ NSSRC_FILES, NS_SUCCESS },
210 	{ NSSRC_DNS, NS_SUCCESS },
211 #ifdef ICMPNL
212 #define NSSRC_ICMP "icmp"
213 	{ NSSRC_ICMP, NS_SUCCESS },
214 #endif
215 	{ 0 }
216 };
217 
218 /*
219  * Check if kernel supports mapped address.
220  *	implementation dependent
221  */
222 #ifdef __KAME__
223 #include <sys/sysctl.h>
224 #endif /* __KAME__ */
225 
226 static int
227 _mapped_addr_enabled(void)
228 {
229 	/* implementation dependent check */
230 #if defined(__KAME__) && defined(IPV6CTL_MAPPED_ADDR)
231 	int mib[4];
232 	size_t len;
233 	int val;
234 
235 	mib[0] = CTL_NET;
236 	mib[1] = PF_INET6;
237 	mib[2] = IPPROTO_IPV6;
238 	mib[3] = IPV6CTL_MAPPED_ADDR;
239 	len = sizeof(val);
240 	if (sysctl(mib, 4, &val, &len, 0, 0) == 0 && val != 0)
241 		return 1;
242 #endif /* __KAME__ && IPV6CTL_MAPPED_ADDR */
243 	return 0;
244 }
245 
246 /*
247  * Functions defined in RFC2553
248  *	getipnodebyname, getipnodebyaddr, freehostent
249  */
250 
251 static struct hostent *
252 _ghbyname(const char *name, int af, int flags, int *errp)
253 {
254 	struct hostent *hp;
255 	int rval;
256 
257 	static const ns_dtab dtab[] = {
258 		NS_FILES_CB(_files_ghbyname, NULL)
259 		{ NSSRC_DNS, _dns_ghbyname, NULL },
260 		NS_NIS_CB(_nis_ghbyname, NULL)
261 		{ 0 }
262 	};
263 
264 	if (flags & AI_ADDRCONFIG) {
265 		int s;
266 
267 		/*
268 		 * TODO:
269 		 * Note that implementation dependent test for address
270 		 * configuration should be done everytime called
271 		 * (or apropriate interval),
272 		 * because addresses will be dynamically assigned or deleted.
273 		 */
274 		if (af == AF_UNSPEC) {
275 			if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
276 				af = AF_INET;
277 			else {
278 				_close(s);
279 				if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
280 					af = AF_INET6;
281 				else
282 				_close(s);
283 			}
284 
285 		}
286 		if (af != AF_UNSPEC) {
287 			if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
288 				return NULL;
289 			_close(s);
290 		}
291 	}
292 
293 	THREAD_LOCK();
294 	rval = nsdispatch(&hp, dtab, NSDB_HOSTS, "ghbyname", default_src,
295 			  name, af, errp);
296 	THREAD_UNLOCK();
297 	return (rval == NS_SUCCESS) ? hp : NULL;
298 }
299 
300 /* getipnodebyname() internal routine for multiple query(PF_UNSPEC) support. */
301 struct hostent *
302 _getipnodebyname_multi(const char *name, int af, int flags, int *errp)
303 {
304 	struct hostent *hp;
305 	union inx_addr addrbuf;
306 
307 	/* XXX: PF_UNSPEC is only supposed to be passed from getaddrinfo() */
308 	if (af != AF_INET
309 #ifdef INET6
310 	    && af != AF_INET6
311 #endif
312 	    && af != PF_UNSPEC
313 		)
314 	{
315 		*errp = NO_RECOVERY;
316 		return NULL;
317 	}
318 
319 #ifdef INET6
320 	/* special case for literal address */
321 	if (inet_pton(AF_INET6, name, &addrbuf) == 1) {
322 		if (af != AF_INET6) {
323 			*errp = HOST_NOT_FOUND;
324 			return NULL;
325 		}
326 		return _hpaddr(af, name, &addrbuf, errp);
327 	}
328 #endif
329 	if (inet_aton(name, (struct in_addr *)&addrbuf) == 1) {
330 		if (af != AF_INET) {
331 			if (MAPADDRENABLED(flags)) {
332 				MAPADDR(&addrbuf, &addrbuf.in_addr);
333 			} else {
334 				*errp = HOST_NOT_FOUND;
335 				return NULL;
336 			}
337 		}
338 		return _hpaddr(af, name, &addrbuf, errp);
339 	}
340 
341 	*errp = HOST_NOT_FOUND;
342 	hp = _ghbyname(name, af, flags, errp);
343 
344 #ifdef INET6
345 	if (af == AF_INET6
346 	&&  ((flags & AI_ALL) || hp == NULL)
347 	&&  (MAPADDRENABLED(flags))) {
348 		struct hostent *hp2 = _ghbyname(name, AF_INET, flags, errp);
349 		if (hp == NULL)
350 			hp = _hpmapv6(hp2, errp);
351 		else {
352 			if (hp2 && strcmp(hp->h_name, hp2->h_name) != 0) {
353 				freehostent(hp2);
354 				hp2 = NULL;
355 			}
356 			hp = _hpmerge(hp, hp2, errp);
357 		}
358 	}
359 #endif
360 	return _hpsort(hp);
361 }
362 
363 struct hostent *
364 getipnodebyname(const char *name, int af, int flags, int *errp)
365 {
366 	if (af != AF_INET
367 #ifdef INET6
368 	    && af != AF_INET6
369 #endif
370 		)
371 	{
372 		*errp = NO_RECOVERY;
373 		return NULL;
374 	}
375 	return(_getipnodebyname_multi(name, af ,flags, errp));
376 }
377 
378 struct hostent *
379 getipnodebyaddr(const void *src, size_t len, int af, int *errp)
380 {
381 	struct hostent *hp;
382 	int rval;
383 #ifdef INET6
384 	struct in6_addr addrbuf;
385 #else
386 	struct in_addr addrbuf;
387 #endif
388 
389 	static const ns_dtab dtab[] = {
390 		NS_FILES_CB(_files_ghbyaddr, NULL)
391 		{ NSSRC_DNS, _dns_ghbyaddr, NULL },
392 		NS_NIS_CB(_nis_ghbyaddr, NULL)
393 #ifdef ICMPNL
394 		{ NSSRC_ICMP, _icmp_ghbyaddr, NULL },
395 #endif
396 		{ 0 }
397 	};
398 
399 	*errp = HOST_NOT_FOUND;
400 
401 	switch (af) {
402 	case AF_INET:
403 		if (len != sizeof(struct in_addr)) {
404 			*errp = NO_RECOVERY;
405 			return NULL;
406 		}
407 		if ((long)src & ~(sizeof(struct in_addr) - 1)) {
408 			memcpy(&addrbuf, src, len);
409 			src = &addrbuf;
410 		}
411 		if (((struct in_addr *)src)->s_addr == 0)
412 			return NULL;
413 		break;
414 #ifdef INET6
415 	case AF_INET6:
416 		if (len != sizeof(struct in6_addr)) {
417 			*errp = NO_RECOVERY;
418 			return NULL;
419 		}
420 		if ((long)src & ~(sizeof(struct in6_addr) / 2 - 1)) {	/*XXX*/
421 			memcpy(&addrbuf, src, len);
422 			src = &addrbuf;
423 		}
424 		if (IN6_IS_ADDR_UNSPECIFIED((struct in6_addr *)src))
425 			return NULL;
426 		if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)src)
427 		||  IN6_IS_ADDR_V4COMPAT((struct in6_addr *)src)) {
428 			src = (char *)src +
429 			    (sizeof(struct in6_addr) - sizeof(struct in_addr));
430 			af = AF_INET;
431 			len = sizeof(struct in_addr);
432 		}
433 		break;
434 #endif
435 	default:
436 		*errp = NO_RECOVERY;
437 		return NULL;
438 	}
439 
440 	THREAD_LOCK();
441 	rval = nsdispatch(&hp, dtab, NSDB_HOSTS, "ghbyaddr", default_src,
442 			  src, len, af, errp);
443 	THREAD_UNLOCK();
444 	return (rval == NS_SUCCESS) ? hp : NULL;
445 }
446 
447 void
448 freehostent(struct hostent *ptr)
449 {
450 	free(ptr);
451 }
452 
453 #if 0
454 
455 /* XXX: should be deprecated */
456 struct hostent *
457 getnodebyname(const char *name, int af, int flags)
458 {
459 	return getipnodebyname(name, af, flags, &h_errno);
460 }
461 
462 #ifdef __warn_references
463 __warn_references(getnodebyname,
464 	"warning: getnodebyname() deprecated, "
465 	"should use getaddrinfo() or getipnodebyname()");
466 #endif
467 
468 struct hostent *
469 getnodebyaddr(const void *src, size_t len, int af)
470 {
471 	return getipnodebyaddr(src, len, af, &h_errno);
472 }
473 
474 #ifdef __warn_references
475 __warn_references(getnodebyaddr,
476 	"warning: getnodebyaddr() deprecated, "
477 	"should use getnameinfo() or getipnodebyaddr()");
478 #endif
479 
480 #endif
481 
482 /*
483  * Private utility functions
484  */
485 
486 /*
487  * _hpcopy: allocate and copy hostent structure
488  */
489 static struct hostent *
490 _hpcopy(struct hostent *hp, int *errp)
491 {
492 	struct hostent *nhp;
493 	char *cp, **pp;
494 	int size, addrsize;
495 	int nalias = 0, naddr = 0;
496 	int al_off;
497 	int i;
498 
499 	if (hp == NULL)
500 		return hp;
501 
502 	/* count size to be allocated */
503 	size = sizeof(struct hostent);
504 	if (hp->h_name != NULL)
505 		size += strlen(hp->h_name) + 1;
506 	if ((pp = hp->h_aliases) != NULL) {
507 		for (i = 0; *pp != NULL; i++, pp++) {
508 			if (**pp != '\0') {
509 				size += strlen(*pp) + 1;
510 				nalias++;
511 			}
512 		}
513 	}
514 	/* adjust alignment */
515 	size = ALIGN(size);
516 	al_off = size;
517 	size += sizeof(char *) * (nalias + 1);
518 	addrsize = ALIGN(hp->h_length);
519 	if ((pp = hp->h_addr_list) != NULL) {
520 		while (*pp++ != NULL)
521 			naddr++;
522 	}
523 	size += addrsize * naddr;
524 	size += sizeof(char *) * (naddr + 1);
525 
526 	/* copy */
527 	if ((nhp = (struct hostent *)malloc(size)) == NULL) {
528 		*errp = TRY_AGAIN;
529 		return NULL;
530 	}
531 	cp = (char *)&nhp[1];
532 	if (hp->h_name != NULL) {
533 		nhp->h_name = cp;
534 		strcpy(cp, hp->h_name);
535 		cp += strlen(cp) + 1;
536 	} else
537 		nhp->h_name = NULL;
538 	nhp->h_aliases = (char **)((char *)nhp + al_off);
539 	if ((pp = hp->h_aliases) != NULL) {
540 		for (i = 0; *pp != NULL; pp++) {
541 			if (**pp != '\0') {
542 				nhp->h_aliases[i++] = cp;
543 				strcpy(cp, *pp);
544 				cp += strlen(cp) + 1;
545 			}
546 		}
547 	}
548 	nhp->h_aliases[nalias] = NULL;
549 	cp = (char *)&nhp->h_aliases[nalias + 1];
550 	nhp->h_addrtype = hp->h_addrtype;
551 	nhp->h_length = hp->h_length;
552 	nhp->h_addr_list = (char **)cp;
553 	if ((pp = hp->h_addr_list) != NULL) {
554 		cp = (char *)&nhp->h_addr_list[naddr + 1];
555 		for (i = 0; *pp != NULL; pp++) {
556 			nhp->h_addr_list[i++] = cp;
557 			memcpy(cp, *pp, hp->h_length);
558 			cp += addrsize;
559 		}
560 	}
561 	nhp->h_addr_list[naddr] = NULL;
562 	return nhp;
563 }
564 
565 /*
566  * _hpaddr: construct hostent structure with one address
567  */
568 static struct hostent *
569 _hpaddr(int af, const char *name, void *addr, int *errp)
570 {
571 	struct hostent *hp, hpbuf;
572 	char *addrs[2];
573 
574 	hp = &hpbuf;
575 	hp->h_name = (char *)name;
576 	hp->h_aliases = NULL;
577 	hp->h_addrtype = af;
578 	hp->h_length = ADDRLEN(af);
579 	hp->h_addr_list = addrs;
580 	addrs[0] = (char *)addr;
581 	addrs[1] = NULL;
582 	return _hpcopy(hp, errp);
583 }
584 
585 /*
586  * _hpmerge: merge 2 hostent structure, arguments will be freed
587  */
588 static struct hostent *
589 _hpmerge(struct hostent *hp1, struct hostent *hp2, int *errp)
590 {
591 	int i, j;
592 	int naddr, nalias;
593 	char **pp;
594 	struct hostent *hp, hpbuf;
595 	char *aliases[MAXALIASES + 1], *addrs[MAXADDRS + 1];
596 	union inx_addr addrbuf[MAXADDRS];
597 
598 	if (hp1 == NULL)
599 		return hp2;
600 	if (hp2 == NULL)
601 		return hp1;
602 
603 #define	HP(i)	(i == 1 ? hp1 : hp2)
604 	hp = &hpbuf;
605 	hp->h_name = (hp1->h_name != NULL ? hp1->h_name : hp2->h_name);
606 	hp->h_aliases = aliases;
607 	nalias = 0;
608 	for (i = 1; i <= 2; i++) {
609 		if ((pp = HP(i)->h_aliases) == NULL)
610 			continue;
611 		for (; nalias < MAXALIASES && *pp != NULL; pp++) {
612 			/* check duplicates */
613 			for (j = 0; j < nalias; j++)
614 				if (strcasecmp(*pp, aliases[j]) == 0)
615 					break;
616 			if (j == nalias)
617 				aliases[nalias++] = *pp;
618 		}
619 	}
620 	aliases[nalias] = NULL;
621 #ifdef INET6
622 	if (hp1->h_length != hp2->h_length) {
623 		hp->h_addrtype = AF_INET6;
624 		hp->h_length = sizeof(struct in6_addr);
625 	} else {
626 #endif
627 		hp->h_addrtype = hp1->h_addrtype;
628 		hp->h_length = hp1->h_length;
629 #ifdef INET6
630 	}
631 #endif
632 	hp->h_addr_list = addrs;
633 	naddr = 0;
634 	for (i = 1; i <= 2; i++) {
635 		if ((pp = HP(i)->h_addr_list) == NULL)
636 			continue;
637 		if (HP(i)->h_length == hp->h_length) {
638 			while (naddr < MAXADDRS && *pp != NULL)
639 				addrs[naddr++] = *pp++;
640 		} else {
641 			/* copy IPv4 addr as mapped IPv6 addr */
642 			while (naddr < MAXADDRS && *pp != NULL) {
643 				MAPADDR(&addrbuf[naddr], *pp++);
644 				addrs[naddr] = (char *)&addrbuf[naddr];
645 				naddr++;
646 			}
647 		}
648 	}
649 	addrs[naddr] = NULL;
650 	hp = _hpcopy(hp, errp);
651 	freehostent(hp1);
652 	freehostent(hp2);
653 	return hp;
654 }
655 
656 /*
657  * _hpmapv6: convert IPv4 hostent into IPv4-mapped IPv6 addresses
658  */
659 #ifdef INET6
660 static struct hostent *
661 _hpmapv6(struct hostent *hp, int *errp)
662 {
663 	struct hostent *hp6;
664 
665 	if (hp == NULL)
666 		return NULL;
667 	if (hp->h_addrtype == AF_INET6)
668 		return hp;
669 
670 	/* make dummy hostent to convert IPv6 address */
671 	if ((hp6 = (struct hostent *)malloc(sizeof(struct hostent))) == NULL) {
672 		*errp = TRY_AGAIN;
673 		return NULL;
674 	}
675 	hp6->h_name = NULL;
676 	hp6->h_aliases = NULL;
677 	hp6->h_addrtype = AF_INET6;
678 	hp6->h_length = sizeof(struct in6_addr);
679 	hp6->h_addr_list = NULL;
680 	return _hpmerge(hp6, hp, errp);
681 }
682 #endif
683 
684 /*
685  * _hpsort: sort address by sortlist
686  */
687 static struct hostent *
688 _hpsort(struct hostent *hp)
689 {
690 	int i, j, n;
691 	u_char *ap, *sp, *mp, **pp;
692 	char t;
693 	char order[MAXADDRS];
694 	int nsort = _res.nsort;
695 
696 	if (hp == NULL || hp->h_addr_list[1] == NULL || nsort == 0)
697 		return hp;
698 	for (i = 0; (ap = (u_char *)hp->h_addr_list[i]); i++) {
699 		for (j = 0; j < nsort; j++) {
700 #ifdef INET6
701 			if (_res_ext.sort_list[j].af != hp->h_addrtype)
702 				continue;
703 			sp = (u_char *)&_res_ext.sort_list[j].addr;
704 			mp = (u_char *)&_res_ext.sort_list[j].mask;
705 #else
706 			sp = (u_char *)&_res.sort_list[j].addr;
707 			mp = (u_char *)&_res.sort_list[j].mask;
708 #endif
709 			for (n = 0; n < hp->h_length; n++) {
710 				if ((ap[n] & mp[n]) != sp[n])
711 					break;
712 			}
713 			if (n == hp->h_length)
714 				break;
715 		}
716 		order[i] = j;
717 	}
718 	n = i;
719 	pp = (u_char **)hp->h_addr_list;
720 	for (i = 0; i < n - 1; i++) {
721 		for (j = i + 1; j < n; j++) {
722 			if (order[i] > order[j]) {
723 				ap = pp[i];
724 				pp[i] = pp[j];
725 				pp[j] = ap;
726 				t = order[i];
727 				order[i] = order[j];
728 				order[j] = t;
729 			}
730 		}
731 	}
732 	return hp;
733 }
734 
735 static char *
736 _hgetword(char **pp)
737 {
738 	char c, *p, *ret;
739 	const char *sp;
740 	static const char sep[] = "# \t\n";
741 
742 	ret = NULL;
743 	for (p = *pp; (c = *p) != '\0'; p++) {
744 		for (sp = sep; *sp != '\0'; sp++) {
745 			if (c == *sp)
746 				break;
747 		}
748 		if (c == '#')
749 			p[1] = '\0';	/* ignore rest of line */
750 		if (ret == NULL) {
751 			if (*sp == '\0')
752 				ret = p;
753 		} else {
754 			if (*sp != '\0') {
755 				*p++ = '\0';
756 				break;
757 			}
758 		}
759 	}
760 	*pp = p;
761 	if (ret == NULL || *ret == '\0')
762 		return NULL;
763 	return ret;
764 }
765 
766 /*
767  * FILES (/etc/hosts)
768  */
769 
770 static FILE *
771 _files_open(int *errp)
772 {
773 	FILE *fp;
774 	fp = fopen(_PATH_HOSTS, "r");
775 	if (fp == NULL)
776 		*errp = NO_RECOVERY;
777 	return fp;
778 }
779 
780 static int
781 _files_ghbyname(void *rval, void *cb_data, va_list ap)
782 {
783 	const char *name;
784 	int af;
785 	int *errp;
786 	int match, nalias;
787 	char *p, *line, *addrstr, *cname;
788 	FILE *fp;
789 	struct hostent *rethp, *hp, hpbuf;
790 	char *aliases[MAXALIASES + 1], *addrs[2];
791 	union inx_addr addrbuf;
792 	char buf[BUFSIZ];
793 	int af0;
794 
795 	name = va_arg(ap, const char *);
796 	af = va_arg(ap, int);
797 	errp = va_arg(ap, int *);
798 
799 	*(struct hostent **)rval = NULL;
800 
801 	if ((fp = _files_open(errp)) == NULL)
802 		return NS_UNAVAIL;
803 	rethp = hp = NULL;
804 
805 	af0 = af;
806 	while (fgets(buf, sizeof(buf), fp)) {
807 		line = buf;
808 		if ((addrstr = _hgetword(&line)) == NULL
809 		||  (cname = _hgetword(&line)) == NULL)
810 			continue;
811 		match = (strcasecmp(cname, name) == 0);
812 		nalias = 0;
813 		while ((p = _hgetword(&line)) != NULL) {
814 			if (!match)
815 				match = (strcasecmp(p, name) == 0);
816 			if (nalias < MAXALIASES)
817 				aliases[nalias++] = p;
818 		}
819 		if (!match)
820 			continue;
821 		switch (af0) {
822 		case AF_INET:
823 			if (inet_aton(addrstr, (struct in_addr *)&addrbuf)
824 			    != 1) {
825 				*errp = NO_DATA;	/* name found */
826 				continue;
827 			}
828 			af = af0;
829 			break;
830 #ifdef INET6
831 		case AF_INET6:
832 			if (inet_pton(af, addrstr, &addrbuf) != 1) {
833 				*errp = NO_DATA;	/* name found */
834 				continue;
835 			}
836 			af = af0;
837 			break;
838 #endif
839 		case AF_UNSPEC:
840 			if (inet_aton(addrstr, (struct in_addr *)&addrbuf)
841 			    == 1) {
842 				af = AF_INET;
843 				break;
844 			}
845 #ifdef INET6
846 			if (inet_pton(AF_INET6, addrstr, &addrbuf) == 1) {
847 				af = AF_INET6;
848 				break;
849 			}
850 #endif
851 			*errp = NO_DATA;	/* name found */
852 			continue;
853 			/* NOTREACHED */
854 		}
855 		hp = &hpbuf;
856 		hp->h_name = cname;
857 		hp->h_aliases = aliases;
858 		aliases[nalias] = NULL;
859 		hp->h_addrtype = af;
860 		hp->h_length = ADDRLEN(af);
861 		hp->h_addr_list = addrs;
862 		addrs[0] = (char *)&addrbuf;
863 		addrs[1] = NULL;
864 		hp = _hpcopy(hp, errp);
865 		rethp = _hpmerge(rethp, hp, errp);
866 	}
867 	fclose(fp);
868 	*(struct hostent **)rval = rethp;
869 	return (rethp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
870 }
871 
872 static int
873 _files_ghbyaddr(void *rval, void *cb_data, va_list ap)
874 {
875 	const void *addr;
876 	int addrlen;
877 	int af;
878 	int *errp;
879 	int nalias;
880 	char *p, *line;
881 	FILE *fp;
882 	struct hostent *hp, hpbuf;
883 	char *aliases[MAXALIASES + 1], *addrs[2];
884 	union inx_addr addrbuf;
885 	char buf[BUFSIZ];
886 
887 	addr = va_arg(ap, const void *);
888 	addrlen = va_arg(ap, int);
889 	af = va_arg(ap, int);
890 	errp = va_arg(ap, int *);
891 
892 	*(struct hostent**)rval = NULL;
893 
894 	if ((fp = _files_open(errp)) == NULL)
895 		return NS_UNAVAIL;
896 	hp = NULL;
897 	while (fgets(buf, sizeof(buf), fp)) {
898 		line = buf;
899 		if ((p = _hgetword(&line)) == NULL
900 		||  (af == AF_INET
901 		     ? inet_aton(p, (struct in_addr *)&addrbuf)
902 		     : inet_pton(af, p, &addrbuf)) != 1
903 		||  memcmp(addr, &addrbuf, addrlen) != 0
904 		||  (p = _hgetword(&line)) == NULL)
905 			continue;
906 		hp = &hpbuf;
907 		hp->h_name = p;
908 		hp->h_aliases = aliases;
909 		nalias = 0;
910 		while ((p = _hgetword(&line)) != NULL) {
911 			if (nalias < MAXALIASES)
912 				aliases[nalias++] = p;
913 		}
914 		aliases[nalias] = NULL;
915 		hp->h_addrtype = af;
916 		hp->h_length = addrlen;
917 		hp->h_addr_list = addrs;
918 		addrs[0] = (char *)&addrbuf;
919 		addrs[1] = NULL;
920 		hp = _hpcopy(hp, errp);
921 		break;
922 	}
923 	fclose(fp);
924 	*(struct hostent **)rval = hp;
925 	return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
926 }
927 
928 #ifdef YP
929 /*
930  * NIS
931  *
932  * XXX actually a hack, these are INET4 specific.
933  */
934 static int
935 _nis_ghbyname(void *rval, void *cb_data, va_list ap)
936 {
937 	const char *name;
938 	int af;
939 	int *errp;
940 	struct hostent *hp = NULL;
941 
942 	name = va_arg(ap, const char *);
943 	af = va_arg(ap, int);
944 	errp = va_arg(ap, int *);
945 
946 	if (af == AF_UNSPEC)
947 		af = AF_INET;
948 	if (af == AF_INET) {
949 		hp = _gethostbynisname(name, af);
950 		if (hp != NULL)
951 			hp = _hpcopy(hp, errp);
952 	}
953 
954 	*(struct hostent **)rval = hp;
955 	return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
956 
957 }
958 
959 static int
960 _nis_ghbyaddr(void *rval, void *cb_data, va_list ap)
961 {
962 	const void *addr;
963 	int addrlen;
964 	int af;
965 	int *errp;
966 	struct hostent *hp = NULL;
967 
968 	addr = va_arg(ap, const void *);
969 	addrlen = va_arg(ap, int);
970 	af = va_arg(ap, int);
971 
972 	if (af == AF_INET) {
973 		hp = _gethostbynisaddr(addr, addrlen, af);
974 		if (hp != NULL)
975 			hp = _hpcopy(hp, errp);
976 	}
977 	*(struct hostent **)rval = hp;
978 	return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
979 }
980 #endif
981 
982 struct __res_type_list {
983         SLIST_ENTRY(__res_type_list) rtl_entry;
984         int     rtl_type;
985 };
986 
987 #define	MAXPACKET	(64*1024)
988 
989 typedef union {
990 	HEADER hdr;
991 	u_char buf[MAXPACKET];
992 } querybuf;
993 
994 static struct hostent *getanswer(const querybuf *, int, const char *, int,
995 	    struct hostent *, int *);
996 
997 /*
998  * we don't need to take care about sorting, nor IPv4 mapped address here.
999  */
1000 static struct hostent *
1001 getanswer(answer, anslen, qname, qtype, template, errp)
1002 	const querybuf *answer;
1003 	int anslen;
1004 	const char *qname;
1005 	int qtype;
1006 	struct hostent *template;
1007 	int *errp;
1008 {
1009 	const HEADER *hp;
1010 	const u_char *cp;
1011 	int n;
1012 	const u_char *eom, *erdata;
1013 	char *bp, *ep, **ap, **hap;
1014 	int type, class, ancount, qdcount;
1015 	int haveanswer, had_error;
1016 	char tbuf[MAXDNAME];
1017 	const char *tname;
1018 	int (*name_ok)(const char *);
1019 	static char *h_addr_ptrs[MAXADDRS + 1];
1020 	static char *host_aliases[MAXALIASES];
1021 	static char hostbuf[8*1024];
1022 
1023 #define BOUNDED_INCR(x) \
1024 	do { \
1025 		cp += x; \
1026 		if (cp > eom) { \
1027 			*errp = NO_RECOVERY; \
1028 			return (NULL); \
1029 		} \
1030 	} while (0)
1031 
1032 #define BOUNDS_CHECK(ptr, count) \
1033 	do { \
1034 		if ((ptr) + (count) > eom) { \
1035 			*errp = NO_RECOVERY; \
1036 			return (NULL); \
1037 		} \
1038 	} while (0)
1039 
1040 /* XXX do {} while (0) cannot be put here */
1041 #define DNS_ASSERT(x) \
1042 	{				\
1043 		if (!(x)) {		\
1044 			cp += n;	\
1045 			continue;	\
1046 		}			\
1047 	}
1048 
1049 /* XXX do {} while (0) cannot be put here */
1050 #define DNS_FATAL(x) \
1051 	{				\
1052 		if (!(x)) {		\
1053 			had_error++;	\
1054 			continue;	\
1055 		}			\
1056 	}
1057 
1058 	tname = qname;
1059 	template->h_name = NULL;
1060 	eom = answer->buf + anslen;
1061 	switch (qtype) {
1062 	case T_A:
1063 	case T_AAAA:
1064 		name_ok = res_hnok;
1065 		break;
1066 	case T_PTR:
1067 		name_ok = res_dnok;
1068 		break;
1069 	default:
1070 		return (NULL);	/* XXX should be abort(); */
1071 	}
1072 	/*
1073 	 * find first satisfactory answer
1074 	 */
1075 	hp = &answer->hdr;
1076 	ancount = ntohs(hp->ancount);
1077 	qdcount = ntohs(hp->qdcount);
1078 	bp = hostbuf;
1079 	ep = hostbuf + sizeof hostbuf;
1080 	cp = answer->buf;
1081 	BOUNDED_INCR(HFIXEDSZ);
1082 	if (qdcount != 1) {
1083 		*errp = NO_RECOVERY;
1084 		return (NULL);
1085 	}
1086 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1087 	if ((n < 0) || !(*name_ok)(bp)) {
1088 		*errp = NO_RECOVERY;
1089 		return (NULL);
1090 	}
1091 	BOUNDED_INCR(n + QFIXEDSZ);
1092 	if (qtype == T_A || qtype == T_AAAA) {
1093 		/* res_send() has already verified that the query name is the
1094 		 * same as the one we sent; this just gets the expanded name
1095 		 * (i.e., with the succeeding search-domain tacked on).
1096 		 */
1097 		n = strlen(bp) + 1;		/* for the \0 */
1098 		if (n >= MAXHOSTNAMELEN) {
1099 			*errp = NO_RECOVERY;
1100 			return (NULL);
1101 		}
1102 		template->h_name = bp;
1103 		bp += n;
1104 		/* The qname can be abbreviated, but h_name is now absolute. */
1105 		qname = template->h_name;
1106 	}
1107 	ap = host_aliases;
1108 	*ap = NULL;
1109 	template->h_aliases = host_aliases;
1110 	hap = h_addr_ptrs;
1111 	*hap = NULL;
1112 	template->h_addr_list = h_addr_ptrs;
1113 	haveanswer = 0;
1114 	had_error = 0;
1115 	while (ancount-- > 0 && cp < eom && !had_error) {
1116 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1117 		DNS_FATAL(n >= 0);
1118 		DNS_FATAL((*name_ok)(bp));
1119 		cp += n;			/* name */
1120 		BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
1121 		type = _getshort(cp);
1122  		cp += INT16SZ;			/* type */
1123 		class = _getshort(cp);
1124  		cp += INT16SZ + INT32SZ;	/* class, TTL */
1125 		n = _getshort(cp);
1126 		cp += INT16SZ;			/* len */
1127 		BOUNDS_CHECK(cp, n);
1128 		erdata = cp + n;
1129 		DNS_ASSERT(class == C_IN);
1130 		if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
1131 			if (ap >= &host_aliases[MAXALIASES-1])
1132 				continue;
1133 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1134 			DNS_FATAL(n >= 0);
1135 			DNS_FATAL((*name_ok)(tbuf));
1136 			cp += n;
1137 			if (cp != erdata) {
1138 				*errp = NO_RECOVERY;
1139 				return (NULL);
1140 			}
1141 			/* Store alias. */
1142 			*ap++ = bp;
1143 			n = strlen(bp) + 1;	/* for the \0 */
1144 			DNS_FATAL(n < MAXHOSTNAMELEN);
1145 			bp += n;
1146 			/* Get canonical name. */
1147 			n = strlen(tbuf) + 1;	/* for the \0 */
1148 			DNS_FATAL(n <= ep - bp);
1149 			DNS_FATAL(n < MAXHOSTNAMELEN);
1150 			strcpy(bp, tbuf);
1151 			template->h_name = bp;
1152 			bp += n;
1153 			continue;
1154 		}
1155 		if (qtype == T_PTR && type == T_CNAME) {
1156 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1157 			if (n < 0 || !res_dnok(tbuf)) {
1158 				had_error++;
1159 				continue;
1160 			}
1161 			cp += n;
1162 			if (cp != erdata) {
1163 				*errp = NO_RECOVERY;
1164 				return (NULL);
1165 			}
1166 			/* Get canonical name. */
1167 			n = strlen(tbuf) + 1;	/* for the \0 */
1168 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1169 				had_error++;
1170 				continue;
1171 			}
1172 			strcpy(bp, tbuf);
1173 			tname = bp;
1174 			bp += n;
1175 			continue;
1176 		}
1177 		DNS_ASSERT(type == qtype);
1178 		switch (type) {
1179 		case T_PTR:
1180 			DNS_ASSERT(strcasecmp(tname, bp) == 0);
1181 			n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1182 			DNS_FATAL(n >= 0);
1183 			DNS_FATAL(res_hnok(bp));
1184 #if MULTI_PTRS_ARE_ALIASES
1185 			cp += n;
1186 			if (cp != erdata) {
1187 				*errp = NO_RECOVERY;
1188 				return (NULL);
1189 			}
1190 			if (!haveanswer)
1191 				template->h_name = bp;
1192 			else if (ap < &host_aliases[MAXALIASES-1])
1193 				*ap++ = bp;
1194 			else
1195 				n = -1;
1196 			if (n != -1) {
1197 				n = strlen(bp) + 1;	/* for the \0 */
1198 				if (n >= MAXHOSTNAMELEN) {
1199 					had_error++;
1200 					break;
1201 				}
1202 				bp += n;
1203 			}
1204 			break;
1205 #else
1206 			template->h_name = bp;
1207 			*errp = NETDB_SUCCESS;
1208 			return (template);
1209 #endif
1210 		case T_A:
1211 		case T_AAAA:
1212 			DNS_ASSERT(strcasecmp(template->h_name, bp) == 0);
1213 			DNS_ASSERT(n == template->h_length);
1214 			if (!haveanswer) {
1215 				int nn;
1216 
1217 				template->h_name = bp;
1218 				nn = strlen(bp) + 1;	/* for the \0 */
1219 				bp += nn;
1220 			}
1221 			bp = (char *)ALIGN(bp);
1222 
1223 			DNS_FATAL(bp + n < ep);
1224 			DNS_ASSERT(hap < &h_addr_ptrs[MAXADDRS-1]);
1225 #ifdef FILTER_V4MAPPED
1226 			if (type == T_AAAA) {
1227 				struct in6_addr in6;
1228 				memcpy(&in6, cp, sizeof(in6));
1229 				DNS_ASSERT(IN6_IS_ADDR_V4MAPPED(&in6) == 0);
1230 			}
1231 #endif
1232 			bcopy(cp, *hap++ = bp, n);
1233 			bp += n;
1234 			cp += n;
1235 			if (cp != erdata) {
1236 				*errp = NO_RECOVERY;
1237 				return (NULL);
1238 			}
1239 			break;
1240 		default:
1241 			abort();
1242 		}
1243 		if (!had_error)
1244 			haveanswer++;
1245 	}
1246 	if (haveanswer) {
1247 		*ap = NULL;
1248 		*hap = NULL;
1249 		if (!template->h_name) {
1250 			n = strlen(qname) + 1;	/* for the \0 */
1251 			if (n > ep - bp || n >= MAXHOSTNAMELEN)
1252 				goto no_recovery;
1253 			strcpy(bp, qname);
1254 			template->h_name = bp;
1255 			bp += n;
1256 		}
1257 		*errp = NETDB_SUCCESS;
1258 		return (template);
1259 	}
1260  no_recovery:
1261 	*errp = NO_RECOVERY;
1262 	return (NULL);
1263 
1264 #undef BOUNDED_INCR
1265 #undef BOUNDS_CHECK
1266 #undef DNS_ASSERT
1267 #undef DNS_FATAL
1268 }
1269 
1270 /* res_search() variant with multiple query support. */
1271 static struct hostent *
1272 _res_search_multi(name, rtl, errp)
1273 	const char *name;	/* domain name */
1274 	struct	__res_type_list *rtl; /* list of query types */
1275 	int *errp;
1276 {
1277 	const char *cp, * const *domain;
1278 	struct hostent *hp0 = NULL, *hp;
1279 	struct hostent hpbuf;
1280 	u_int dots;
1281 	int trailing_dot, ret, saved_herrno;
1282 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1283 	struct __res_type_list *rtl0 = rtl;
1284 	querybuf *buf;
1285 
1286 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1287 		*errp = NETDB_INTERNAL;
1288 		return (NULL);
1289 	}
1290 	dots = 0;
1291 	for (cp = name; *cp; cp++)
1292 		dots += (*cp == '.');
1293 	trailing_dot = 0;
1294 	if (cp > name && *--cp == '.')
1295 		trailing_dot++;
1296 
1297 	buf = malloc(sizeof(*buf));
1298 	if (buf == NULL) {
1299 		*errp = NETDB_INTERNAL;
1300 		return NULL;
1301 	}
1302 
1303 	/* If there aren't any dots, it could be a user-level alias */
1304 	if (!dots && (cp = hostalias(name)) != NULL) {
1305 		for(rtl = rtl0; rtl != NULL;
1306 		    rtl = SLIST_NEXT(rtl, rtl_entry)) {
1307 			ret = res_query(cp, C_IN, rtl->rtl_type, buf->buf,
1308 					     sizeof(buf->buf));
1309 			if (ret > 0 && ret < sizeof(buf->buf)) {
1310 				hpbuf.h_addrtype = (rtl->rtl_type == T_AAAA)
1311 				    ? AF_INET6 : AF_INET;
1312 				hpbuf.h_length = ADDRLEN(hpbuf.h_addrtype);
1313 				hp = getanswer(buf, ret, name, rtl->rtl_type,
1314 						    &hpbuf, errp);
1315 				if (!hp)
1316 					continue;
1317 				hp = _hpcopy(&hpbuf, errp);
1318 				hp0 = _hpmerge(hp0, hp, errp);
1319 			}
1320 		}
1321 		free(buf);
1322 		return (hp0);
1323 	}
1324 
1325 	/*
1326 	 * If there are dots in the name already, let's just give it a try
1327 	 * 'as is'.  The threshold can be set with the "ndots" option.
1328 	 */
1329 	saved_herrno = -1;
1330 	if (dots >= _res.ndots) {
1331 		for(rtl = rtl0; rtl != NULL;
1332 		    rtl = SLIST_NEXT(rtl, rtl_entry)) {
1333 			ret = res_querydomain(name, NULL, C_IN, rtl->rtl_type,
1334 					      buf->buf, sizeof(buf->buf));
1335 			if (ret > 0 && ret < sizeof(buf->buf)) {
1336 				hpbuf.h_addrtype = (rtl->rtl_type == T_AAAA)
1337 				    ? AF_INET6 : AF_INET;
1338 				hpbuf.h_length = ADDRLEN(hpbuf.h_addrtype);
1339 				hp = getanswer(buf, ret, name, rtl->rtl_type,
1340 						    &hpbuf, errp);
1341 				if (!hp)
1342 					continue;
1343 				hp = _hpcopy(&hpbuf, errp);
1344 				hp0 = _hpmerge(hp0, hp, errp);
1345 			}
1346 		}
1347 		if (hp0 != NULL) {
1348 			free(buf);
1349 			return (hp0);
1350 		}
1351 		saved_herrno = *errp;
1352 		tried_as_is++;
1353 	}
1354 
1355 	/*
1356 	 * We do at least one level of search if
1357 	 *	- there is no dot and RES_DEFNAME is set, or
1358 	 *	- there is at least one dot, there is no trailing dot,
1359 	 *	  and RES_DNSRCH is set.
1360 	 */
1361 	if ((!dots && (_res.options & RES_DEFNAMES)) ||
1362 	    (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
1363 		int done = 0;
1364 
1365 		for (domain = (const char * const *)_res.dnsrch;
1366 		     *domain && !done;
1367 		     domain++) {
1368 
1369 			for(rtl = rtl0; rtl != NULL;
1370 			    rtl = SLIST_NEXT(rtl, rtl_entry)) {
1371 				ret = res_querydomain(name, *domain, C_IN,
1372 						      rtl->rtl_type,
1373 						      buf->buf, sizeof(buf->buf));
1374 				if (ret > 0 && ret < sizeof(buf->buf)) {
1375 					hpbuf.h_addrtype = (rtl->rtl_type == T_AAAA)
1376 					    ? AF_INET6 : AF_INET;
1377 					hpbuf.h_length = ADDRLEN(hpbuf.h_addrtype);
1378 					hp = getanswer(buf, ret, name,
1379 					    rtl->rtl_type, &hpbuf, errp);
1380 					if (!hp)
1381 						continue;
1382 					hp = _hpcopy(&hpbuf, errp);
1383 					hp0 = _hpmerge(hp0, hp, errp);
1384 				}
1385 			}
1386 			if (hp0 != NULL) {
1387 				free(buf);
1388 				return (hp0);
1389 			}
1390 
1391 			/*
1392 			 * If no server present, give up.
1393 			 * If name isn't found in this domain,
1394 			 * keep trying higher domains in the search list
1395 			 * (if that's enabled).
1396 			 * On a NO_DATA error, keep trying, otherwise
1397 			 * a wildcard entry of another type could keep us
1398 			 * from finding this entry higher in the domain.
1399 			 * If we get some other error (negative answer or
1400 			 * server failure), then stop searching up,
1401 			 * but try the input name below in case it's
1402 			 * fully-qualified.
1403 			 */
1404 			if (errno == ECONNREFUSED) {
1405 				free(buf);
1406 				*errp = TRY_AGAIN;
1407 				return (NULL);
1408 			}
1409 
1410 			switch (*errp) {
1411 			case NO_DATA:
1412 				got_nodata++;
1413 				/* FALLTHROUGH */
1414 			case HOST_NOT_FOUND:
1415 				/* keep trying */
1416 				break;
1417 			case TRY_AGAIN:
1418 				if (buf->hdr.rcode == SERVFAIL) {
1419 					/* try next search element, if any */
1420 					got_servfail++;
1421 					break;
1422 				}
1423 				/* FALLTHROUGH */
1424 			default:
1425 				/* anything else implies that we're done */
1426 				done++;
1427 			}
1428 
1429 			/* if we got here for some reason other than DNSRCH,
1430 			 * we only wanted one iteration of the loop, so stop.
1431 			 */
1432 			if (!(_res.options & RES_DNSRCH))
1433 				done++;
1434 		}
1435 	}
1436 
1437 	/*
1438 	 * If we have not already tried the name "as is", do that now.
1439 	 * note that we do this regardless of how many dots were in the
1440 	 * name or whether it ends with a dot unless NOTLDQUERY is set.
1441 	 */
1442 	if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
1443 		for(rtl = rtl0; rtl != NULL;
1444 		    rtl = SLIST_NEXT(rtl, rtl_entry)) {
1445 			ret = res_querydomain(name, NULL, C_IN, rtl->rtl_type,
1446 					      buf->buf, sizeof(buf->buf));
1447 			if (ret > 0 && ret < sizeof(buf->buf)) {
1448 				hpbuf.h_addrtype = (rtl->rtl_type == T_AAAA)
1449 				    ? AF_INET6 : AF_INET;
1450 				hpbuf.h_length = ADDRLEN(hpbuf.h_addrtype);
1451 				hp = getanswer(buf, ret, name, rtl->rtl_type,
1452 				    &hpbuf, errp);
1453 				if (!hp)
1454 					continue;
1455 				hp = _hpcopy(&hpbuf, errp);
1456 				hp0 = _hpmerge(hp0, hp, errp);
1457 			}
1458 		}
1459 		if (hp0 != NULL) {
1460 			free(buf);
1461 			return (hp0);
1462 		}
1463 	}
1464 
1465 	free(buf);
1466 
1467 	/* if we got here, we didn't satisfy the search.
1468 	 * if we did an initial full query, return that query's h_errno
1469 	 * (note that we wouldn't be here if that query had succeeded).
1470 	 * else if we ever got a nodata, send that back as the reason.
1471 	 * else send back meaningless h_errno, that being the one from
1472 	 * the last DNSRCH we did.
1473 	 */
1474 	if (saved_herrno != -1)
1475 		*errp = saved_herrno;
1476 	else if (got_nodata)
1477 		*errp = NO_DATA;
1478 	else if (got_servfail)
1479 		*errp = TRY_AGAIN;
1480 	return (NULL);
1481 }
1482 
1483 static int
1484 _dns_ghbyname(void *rval, void *cb_data, va_list ap)
1485 {
1486 	const char *name;
1487 	int af;
1488 	int *errp;
1489 	struct __res_type_list *rtl, rtl4;
1490 #ifdef INET6
1491 	struct __res_type_list rtl6;
1492 #endif
1493 
1494 	name = va_arg(ap, const char *);
1495 	af = va_arg(ap, int);
1496 	errp = va_arg(ap, int *);
1497 
1498 #ifdef INET6
1499 	switch (af) {
1500 	case AF_UNSPEC:
1501 		SLIST_NEXT(&rtl4, rtl_entry) = NULL; rtl4.rtl_type = T_A;
1502 		SLIST_NEXT(&rtl6, rtl_entry) = &rtl4; rtl6.rtl_type = T_AAAA;
1503 		rtl = &rtl6;
1504 		break;
1505 	case AF_INET6:
1506 		SLIST_NEXT(&rtl6, rtl_entry) = NULL; rtl6.rtl_type = T_AAAA;
1507 		rtl = &rtl6;
1508 		break;
1509 	case AF_INET:
1510 		SLIST_NEXT(&rtl4, rtl_entry) = NULL; rtl4.rtl_type = T_A;
1511 		rtl = &rtl4;
1512 		break;
1513 	}
1514 #else
1515 	SLIST_NEXT(&rtl4, rtl_entry) = NULL; rtl4.rtl_type = T_A;
1516 	rtl = &rtl4;
1517 #endif
1518 	*(struct hostent **)rval = _res_search_multi(name, rtl, errp);
1519 	return (*(struct hostent **)rval != NULL) ? NS_SUCCESS : NS_NOTFOUND;
1520 }
1521 
1522 static int
1523 _dns_ghbyaddr(void *rval, void *cb_data, va_list ap)
1524 {
1525 	const void *addr;
1526 	int addrlen;
1527 	int af;
1528 	int *errp;
1529 	int n;
1530 	int err;
1531 	struct hostent *hp;
1532 	u_char c, *cp;
1533 	char *bp;
1534 	struct hostent hbuf;
1535 	int na;
1536 #ifdef INET6
1537 	static const char hex[] = "0123456789abcdef";
1538 #endif
1539 	querybuf *buf;
1540 	char qbuf[MAXDNAME+1];
1541 	char *hlist[2];
1542 	char *tld6[] = { "ip6.arpa", "ip6.int", NULL };
1543 	char *tld4[] = { "in-addr.arpa", NULL };
1544 	char **tld;
1545 
1546 	addr = va_arg(ap, const void *);
1547 	addrlen = va_arg(ap, int);
1548 	af = va_arg(ap, int);
1549 	errp = va_arg(ap, int *);
1550 
1551 	*(struct hostent **)rval = NULL;
1552 
1553 #ifdef INET6
1554 	/* XXX */
1555 	if (af == AF_INET6 && IN6_IS_ADDR_LINKLOCAL((struct in6_addr *)addr))
1556 		return NS_NOTFOUND;
1557 #endif
1558 
1559 	switch (af) {
1560 #ifdef INET6
1561 	case AF_INET6:
1562 		tld = tld6;
1563 		break;
1564 #endif
1565 	case AF_INET:
1566 		tld = tld4;
1567 		break;
1568 	default:
1569 		return NS_NOTFOUND;
1570 	}
1571 
1572 	if ((_res.options & RES_INIT) == 0) {
1573 		if (res_init() < 0) {
1574 			*errp = h_errno;
1575 			return NS_UNAVAIL;
1576 		}
1577 	}
1578 	memset(&hbuf, 0, sizeof(hbuf));
1579 	hbuf.h_name = NULL;
1580 	hbuf.h_addrtype = af;
1581 	hbuf.h_length = addrlen;
1582 	na = 0;
1583 
1584 	buf = malloc(sizeof(*buf));
1585 	if (buf == NULL) {
1586 		*errp = NETDB_INTERNAL;
1587 		return NS_UNAVAIL;
1588 	}
1589 	err = NS_SUCCESS;
1590 	for (/* nothing */; *tld; tld++) {
1591 		/*
1592 		 * XXX assumes that MAXDNAME is big enough - error checks
1593 		 * has been made by callers
1594 		 */
1595 		n = 0;
1596 		bp = qbuf;
1597 		cp = (u_char *)addr+addrlen-1;
1598 		switch (af) {
1599 #ifdef INET6
1600 		case AF_INET6:
1601 			for (; n < addrlen; n++, cp--) {
1602 				c = *cp;
1603 				*bp++ = hex[c & 0xf];
1604 				*bp++ = '.';
1605 				*bp++ = hex[c >> 4];
1606 				*bp++ = '.';
1607 			}
1608 			strcpy(bp, *tld);
1609 			break;
1610 #endif
1611 		case AF_INET:
1612 			for (; n < addrlen; n++, cp--) {
1613 				c = *cp;
1614 				if (c >= 100)
1615 					*bp++ = '0' + c / 100;
1616 				if (c >= 10)
1617 					*bp++ = '0' + (c % 100) / 10;
1618 				*bp++ = '0' + c % 10;
1619 				*bp++ = '.';
1620 			}
1621 			strcpy(bp, *tld);
1622 			break;
1623 		}
1624 
1625 		n = res_query(qbuf, C_IN, T_PTR, buf->buf, sizeof buf->buf);
1626 		if (n < 0) {
1627 			*errp = h_errno;
1628 			err = NS_UNAVAIL;
1629 			continue;
1630 		} else if (n > sizeof(buf->buf)) {
1631 #if 0
1632 			errno = ERANGE; /* XXX is it OK to set errno here? */
1633 #endif
1634 			*errp = NETDB_INTERNAL;
1635 			err = NS_UNAVAIL;
1636 			continue;
1637 		}
1638 		hp = getanswer(buf, n, qbuf, T_PTR, &hbuf, errp);
1639 		if (!hp) {
1640 			err = NS_NOTFOUND;
1641 			continue;
1642 		}
1643 		free(buf);
1644 		hbuf.h_addrtype = af;
1645 		hbuf.h_length = addrlen;
1646 		hbuf.h_addr_list = hlist;
1647 		hlist[0] = (char *)addr;
1648 		hlist[1] = NULL;
1649 		*(struct hostent **)rval = _hpcopy(&hbuf, errp);
1650 		return NS_SUCCESS;
1651 	}
1652 	free(buf);
1653 	return err;
1654 }
1655 
1656 static void
1657 _dns_shent(int stayopen)
1658 {
1659 	if ((_res.options & RES_INIT) == 0) {
1660 		if (res_init() < 0)
1661 			return;
1662 	}
1663 	if (stayopen)
1664 		_res.options |= RES_STAYOPEN | RES_USEVC;
1665 }
1666 
1667 static void
1668 _dns_ehent(void)
1669 {
1670 	_res.options &= ~(RES_STAYOPEN | RES_USEVC);
1671 	res_close();
1672 }
1673 
1674 #ifdef ICMPNL
1675 
1676 /*
1677  * experimental:
1678  *	draft-ietf-ipngwg-icmp-namelookups-02.txt
1679  *	ifindex is assumed to be encoded in addr.
1680  */
1681 #include <sys/uio.h>
1682 #include <netinet/ip6.h>
1683 #include <netinet/icmp6.h>
1684 
1685 struct _icmp_host_cache {
1686 	struct _icmp_host_cache *hc_next;
1687 	int hc_ifindex;
1688 	struct in6_addr hc_addr;
1689 	char *hc_name;
1690 };
1691 
1692 static char *
1693 _icmp_fqdn_query(const struct in6_addr *addr, int ifindex)
1694 {
1695 	int s;
1696 	struct icmp6_filter filter;
1697 	struct msghdr msg;
1698 	struct cmsghdr *cmsg;
1699 	struct in6_pktinfo *pkt;
1700 	char cbuf[256];
1701 	char buf[1024];
1702 	int cc;
1703 	struct icmp6_fqdn_query *fq;
1704 	struct icmp6_fqdn_reply *fr;
1705 	struct _icmp_host_cache *hc;
1706 	struct sockaddr_in6 sin6;
1707 	struct iovec iov;
1708 	fd_set s_fds, fds;
1709 	struct timeval tout;
1710 	int len;
1711 	char *name;
1712 	static int pid;
1713 	static struct _icmp_host_cache *hc_head;
1714 
1715 	for (hc = hc_head; hc; hc = hc->hc_next) {
1716 		if (hc->hc_ifindex == ifindex
1717 		&&  IN6_ARE_ADDR_EQUAL(&hc->hc_addr, addr))
1718 			return hc->hc_name;
1719 	}
1720 
1721 	if (pid == 0)
1722 		pid = getpid();
1723 
1724 	ICMP6_FILTER_SETBLOCKALL(&filter);
1725 	ICMP6_FILTER_SETPASS(ICMP6_FQDN_REPLY, &filter);
1726 
1727 	FD_ZERO(&s_fds);
1728 	tout.tv_sec = 0;
1729 	tout.tv_usec = 200000;	/*XXX: 200ms*/
1730 
1731 	fq = (struct icmp6_fqdn_query *)buf;
1732 	fq->icmp6_fqdn_type = ICMP6_FQDN_QUERY;
1733 	fq->icmp6_fqdn_code = 0;
1734 	fq->icmp6_fqdn_cksum = 0;
1735 	fq->icmp6_fqdn_id = (u_short)pid;
1736 	fq->icmp6_fqdn_unused = 0;
1737 	fq->icmp6_fqdn_cookie[0] = 0;
1738 	fq->icmp6_fqdn_cookie[1] = 0;
1739 
1740 	memset(&sin6, 0, sizeof(sin6));
1741 	sin6.sin6_family = AF_INET6;
1742 	sin6.sin6_addr = *addr;
1743 
1744 	memset(&msg, 0, sizeof(msg));
1745 	msg.msg_name = (caddr_t)&sin6;
1746 	msg.msg_namelen = sizeof(sin6);
1747 	msg.msg_iov = &iov;
1748 	msg.msg_iovlen = 1;
1749 	msg.msg_control = NULL;
1750 	msg.msg_controllen = 0;
1751 	iov.iov_base = (caddr_t)buf;
1752 	iov.iov_len = sizeof(struct icmp6_fqdn_query);
1753 
1754 	if (ifindex) {
1755 		msg.msg_control = cbuf;
1756 		msg.msg_controllen = sizeof(cbuf);
1757 		cmsg = CMSG_FIRSTHDR(&msg);
1758 		cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
1759 		cmsg->cmsg_level = IPPROTO_IPV6;
1760 		cmsg->cmsg_type = IPV6_PKTINFO;
1761 		pkt = (struct in6_pktinfo *)&cmsg[1];
1762 		memset(&pkt->ipi6_addr, 0, sizeof(struct in6_addr));
1763 		pkt->ipi6_ifindex = ifindex;
1764 		cmsg = CMSG_NXTHDR(&msg, cmsg);
1765 		msg.msg_controllen = (char *)cmsg - cbuf;
1766 	}
1767 
1768 	if ((s = _socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0)
1769 		return NULL;
1770 	(void)_setsockopt(s, IPPROTO_ICMPV6, ICMP6_FILTER,
1771 			 (char *)&filter, sizeof(filter));
1772 	cc = _sendmsg(s, &msg, 0);
1773 	if (cc < 0) {
1774 		_close(s);
1775 		return NULL;
1776 	}
1777 	FD_SET(s, &s_fds);
1778 	for (;;) {
1779 		fds = s_fds;
1780 		if (_select(s + 1, &fds, NULL, NULL, &tout) <= 0) {
1781 			_close(s);
1782 			return NULL;
1783 		}
1784 		len = sizeof(sin6);
1785 		cc = _recvfrom(s, buf, sizeof(buf), 0,
1786 			      (struct sockaddr *)&sin6, &len);
1787 		if (cc <= 0) {
1788 			_close(s);
1789 			return NULL;
1790 		}
1791 		if (cc < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr))
1792 			continue;
1793 		if (!IN6_ARE_ADDR_EQUAL(addr, &sin6.sin6_addr))
1794 			continue;
1795 		fr = (struct icmp6_fqdn_reply *)(buf + sizeof(struct ip6_hdr));
1796 		if (fr->icmp6_fqdn_type == ICMP6_FQDN_REPLY)
1797 			break;
1798 	}
1799 	_close(s);
1800 	if (fr->icmp6_fqdn_cookie[1] != 0) {
1801 		/* rfc1788 type */
1802 		name = buf + sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) + 4;
1803 		len = (buf + cc) - name;
1804 	} else {
1805 		len = fr->icmp6_fqdn_namelen;
1806 		name = fr->icmp6_fqdn_name;
1807 	}
1808 	if (len <= 0)
1809 		return NULL;
1810 	name[len] = 0;
1811 
1812 	if ((hc = (struct _icmp_host_cache *)malloc(sizeof(*hc))) == NULL)
1813 		return NULL;
1814 	/* XXX: limit number of cached entries */
1815 	hc->hc_ifindex = ifindex;
1816 	hc->hc_addr = *addr;
1817 	hc->hc_name = strdup(name);
1818 	hc->hc_next = hc_head;
1819 	hc_head = hc;
1820 	return hc->hc_name;
1821 }
1822 
1823 static struct hostent *
1824 _icmp_ghbyaddr(const void *addr, int addrlen, int af, int *errp)
1825 {
1826 	char *hname;
1827 	int ifindex;
1828 	struct in6_addr addr6;
1829 
1830 	if (af != AF_INET6) {
1831 		/*
1832 		 * Note: rfc1788 defines Who Are You for IPv4,
1833 		 * but no one implements it.
1834 		 */
1835 		return NULL;
1836 	}
1837 
1838 	memcpy(&addr6, addr, addrlen);
1839 	ifindex = (addr6.s6_addr[2] << 8) | addr6.s6_addr[3];
1840 	addr6.s6_addr[2] = addr6.s6_addr[3] = 0;
1841 
1842 	if (!IN6_IS_ADDR_LINKLOCAL(&addr6))
1843 		return NULL;	/*XXX*/
1844 
1845 	if ((hname = _icmp_fqdn_query(&addr6, ifindex)) == NULL)
1846 		return NULL;
1847 	return _hpaddr(af, hname, &addr6, errp);
1848 }
1849 #endif /* ICMPNL */
1850