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