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