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