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