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