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