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