1/*	$NetBSD: gethnamaddr.c,v 1.95 2023/08/10 20:38:00 mrg Exp $	*/
2
3/*
4 * ++Copyright++ 1985, 1988, 1993
5 * -
6 * Copyright (c) 1985, 1988, 1993
7 *    The Regents of the University of California.  All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 * -
33 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
34 *
35 * Permission to use, copy, modify, and distribute this software for any
36 * purpose with or without fee is hereby granted, provided that the above
37 * copyright notice and this permission notice appear in all copies, and that
38 * the name of Digital Equipment Corporation not be used in advertising or
39 * publicity pertaining to distribution of the document or software without
40 * specific, written prior permission.
41 *
42 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
43 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
44 * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
45 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
46 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
47 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
48 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
49 * SOFTWARE.
50 * -
51 * --Copyright--
52 */
53
54#include <sys/cdefs.h>
55#if defined(LIBC_SCCS) && !defined(lint)
56#if 0
57static char sccsid[] = "@(#)gethostnamadr.c	8.1 (Berkeley) 6/4/93";
58static char rcsid[] = "Id: gethnamaddr.c,v 8.21 1997/06/01 20:34:37 vixie Exp ";
59#else
60__RCSID("$NetBSD: gethnamaddr.c,v 1.95 2023/08/10 20:38:00 mrg Exp $");
61#endif
62#endif /* LIBC_SCCS and not lint */
63
64#if defined(_LIBC)
65#include "namespace.h"
66#endif
67#include <sys/param.h>
68#include <sys/socket.h>
69#include <netinet/in.h>
70#include <arpa/inet.h>
71#include <arpa/nameser.h>
72
73#include <assert.h>
74#include <ctype.h>
75#include <errno.h>
76#include <netdb.h>
77#include <resolv.h>
78#include <stdarg.h>
79#include <stdio.h>
80#include <syslog.h>
81
82#ifndef LOG_AUTH
83# define LOG_AUTH 0
84#endif
85
86#define MULTI_PTRS_ARE_ALIASES 1	/* XXX - experimental */
87
88#include <nsswitch.h>
89#include <stdlib.h>
90#include <string.h>
91#include <libutil.h>
92
93#ifdef YP
94#include <rpc/rpc.h>
95#include <rpcsvc/yp_prot.h>
96#include <rpcsvc/ypclnt.h>
97#endif
98
99#include "hostent.h"
100
101#if defined(_LIBC) && defined(__weak_alias)
102__weak_alias(gethostbyaddr,_gethostbyaddr)
103__weak_alias(gethostbyname,_gethostbyname)
104__weak_alias(gethostent,_gethostent)
105#endif
106
107#define maybe_ok(res, nm, ok) (((res)->options & RES_NOCHECKNAME) != 0U || \
108                               (ok)(nm) != 0)
109#define maybe_hnok(res, hn) maybe_ok((res), (hn), res_hnok)
110#define maybe_dnok(res, dn) maybe_ok((res), (dn), res_dnok)
111
112#define addalias(d, s, arr, siz) do {			\
113	if (d >= &arr[siz]) {				\
114		ptrdiff_t _off = d - arr;		\
115		char **xptr = realloc(arr, (siz + 10) * sizeof(*arr)); \
116		if (xptr == NULL)			\
117			goto nospc;			\
118		d = xptr + _off;			\
119		arr = xptr;				\
120		siz += 10;				\
121	}						\
122	*d++ = s;					\
123} while (0)
124
125#define setup(arr, siz) do {				\
126	arr = malloc((siz = 10) * sizeof(*arr)); 	\
127	if (arr == NULL)				\
128		goto nospc;				\
129} while (0)
130
131
132static const char AskedForGot[] =
133    "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
134
135
136#ifdef YP
137static char *__ypdomain;
138#endif
139
140#define	MAXPACKET	(64*1024)
141
142typedef union {
143	HEADER hdr;
144	u_char buf[MAXPACKET];
145} querybuf;
146
147typedef union {
148	int32_t al;
149	char ac;
150} align;
151
152#ifdef DEBUG
153static void debugprintf(const char *, res_state, ...)
154	__attribute__((__format__(__printf__, 1, 3)));
155#endif
156static struct hostent *getanswer(const querybuf *, int, const char *, int,
157    res_state, struct hostent *, char *, size_t, int *);
158static void map_v4v6_address(const char *, char *);
159static void map_v4v6_hostent(struct hostent *, char **, char *);
160static void addrsort(char **, int, res_state);
161
162void dns_service(void);
163#undef dn_skipname
164int dn_skipname(const u_char *, const u_char *);
165
166#ifdef YP
167static struct hostent *_yp_hostent(char *, int, struct getnamaddr *);
168#endif
169
170static struct hostent *gethostbyname_internal(const char *, int, res_state,
171    struct hostent *, char *, size_t, int *);
172
173static const ns_src default_dns_files[] = {
174	{ NSSRC_FILES, 	NS_SUCCESS },
175	{ NSSRC_DNS, 	NS_SUCCESS },
176	{ 0, 0 }
177};
178
179
180#ifdef DEBUG
181static void
182debugprintf(const char *msg, res_state res, ...)
183{
184	_DIAGASSERT(msg != NULL);
185
186	if (res->options & RES_DEBUG) {
187		int save = errno;
188		va_list ap;
189
190		va_start (ap, res);
191		vprintf(msg, ap);
192		va_end (ap);
193
194		errno = save;
195	}
196}
197#else
198# define debugprintf(msg, res, num) /*nada*/
199#endif
200
201#define BOUNDED_INCR(x) \
202	do { \
203		cp += (x); \
204		if (cp > eom) \
205			goto no_recovery; \
206	} while (0)
207
208#define BOUNDS_CHECK(ptr, count) \
209	do { \
210		if ((ptr) + (count) > eom) \
211			goto no_recovery; \
212	} while (0)
213
214static struct hostent *
215getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
216    res_state res, struct hostent *hent, char *buf, size_t buflen, int *he)
217{
218	const HEADER *hp;
219	const u_char *cp;
220	int n;
221	size_t qlen;
222	const u_char *eom, *erdata;
223	char *bp, **ap, **hap, *ep;
224	int type, class, ancount, qdcount;
225	int haveanswer, had_error;
226	int toobig = 0;
227	char tbuf[MAXDNAME];
228	char **aliases;
229	size_t maxaliases;
230	char *addr_ptrs[MAXADDRS];
231	const char *tname;
232	int (*name_ok)(const char *);
233
234	_DIAGASSERT(answer != NULL);
235	_DIAGASSERT(qname != NULL);
236
237	tname = qname;
238	hent->h_name = NULL;
239	eom = answer->buf + anslen;
240	switch (qtype) {
241	case T_A:
242	case T_AAAA:
243		name_ok = res_hnok;
244		break;
245	case T_PTR:
246		name_ok = res_dnok;
247		break;
248	default:
249		*he = NO_RECOVERY;
250		return NULL;	/* XXX should be abort(); */
251	}
252
253	setup(aliases, maxaliases);
254	/*
255	 * find first satisfactory answer
256	 */
257	hp = &answer->hdr;
258	ancount = ntohs(hp->ancount);
259	qdcount = ntohs(hp->qdcount);
260	bp = buf;
261	ep = buf + buflen;
262	cp = answer->buf;
263	BOUNDED_INCR(HFIXEDSZ);
264	if (qdcount != 1)
265		goto no_recovery;
266
267	n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
268	if ((n < 0) || !maybe_ok(res, bp, name_ok))
269		goto no_recovery;
270
271	BOUNDED_INCR(n + QFIXEDSZ);
272	if (qtype == T_A || qtype == T_AAAA) {
273		/* res_send() has already verified that the query name is the
274		 * same as the one we sent; this just gets the expanded name
275		 * (i.e., with the succeeding search-domain tacked on).
276		 */
277		n = (int)strlen(bp) + 1;		/* for the \0 */
278		if (n >= MAXHOSTNAMELEN)
279			goto no_recovery;
280		hent->h_name = bp;
281		bp += n;
282		/* The qname can be abbreviated, but h_name is now absolute. */
283		qname = hent->h_name;
284	}
285	hent->h_aliases = ap = aliases;
286	hent->h_addr_list = hap = addr_ptrs;
287	*ap = NULL;
288	*hap = NULL;
289	haveanswer = 0;
290	had_error = 0;
291	while (ancount-- > 0 && cp < eom && !had_error) {
292		n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
293		if ((n < 0) || !maybe_ok(res, bp, name_ok)) {
294			had_error++;
295			continue;
296		}
297		cp += n;			/* name */
298		BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
299		type = _getshort(cp);
300 		cp += INT16SZ;			/* type */
301		class = _getshort(cp);
302 		cp += INT16SZ + INT32SZ;	/* class, TTL */
303		n = _getshort(cp);
304		cp += INT16SZ;			/* len */
305		BOUNDS_CHECK(cp, n);
306		erdata = cp + n;
307		if (class != C_IN) {
308			/* XXX - debug? syslog? */
309			cp += n;
310			continue;		/* XXX - had_error++ ? */
311		}
312		if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
313			n = dn_expand(answer->buf, eom, cp, tbuf,
314			    (int)sizeof tbuf);
315			if ((n < 0) || !maybe_ok(res, tbuf, name_ok)) {
316				had_error++;
317				continue;
318			}
319			cp += n;
320			if (cp != erdata)
321				goto no_recovery;
322			/* Store alias. */
323			addalias(ap, bp, aliases, maxaliases);
324			n = (int)strlen(bp) + 1;	/* for the \0 */
325			if (n >= MAXHOSTNAMELEN) {
326				had_error++;
327				continue;
328			}
329			bp += n;
330			/* Get canonical name. */
331			n = (int)strlen(tbuf) + 1;	/* for the \0 */
332			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
333				had_error++;
334				continue;
335			}
336			strlcpy(bp, tbuf, (size_t)(ep - bp));
337			hent->h_name = bp;
338			bp += n;
339			continue;
340		}
341		if (qtype == T_PTR && type == T_CNAME) {
342			n = dn_expand(answer->buf, eom, cp, tbuf,
343			    (int)sizeof tbuf);
344			if (n < 0 || !maybe_dnok(res, tbuf)) {
345				had_error++;
346				continue;
347			}
348			cp += n;
349			if (cp != erdata)
350				goto no_recovery;
351			/* Get canonical name. */
352			n = (int)strlen(tbuf) + 1;	/* for the \0 */
353			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
354				had_error++;
355				continue;
356			}
357			strlcpy(bp, tbuf, (size_t)(ep - bp));
358			tname = bp;
359			bp += n;
360			continue;
361		}
362		if (type != qtype) {
363			if (type != T_KEY && type != T_SIG && type != T_DNAME)
364				syslog(LOG_NOTICE|LOG_AUTH,
365	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
366				       qname, p_class(C_IN), p_type(qtype),
367				       p_type(type));
368			cp += n;
369			continue;		/* XXX - had_error++ ? */
370		}
371		switch (type) {
372		case T_PTR:
373			if (strcasecmp(tname, bp) != 0) {
374				syslog(LOG_NOTICE|LOG_AUTH,
375				       AskedForGot, qname, bp);
376				cp += n;
377				continue;	/* XXX - had_error++ ? */
378			}
379			n = dn_expand(answer->buf, eom, cp, bp, (int)(ep - bp));
380			if ((n < 0) || !maybe_hnok(res, bp)) {
381				had_error++;
382				break;
383			}
384#if MULTI_PTRS_ARE_ALIASES
385			cp += n;
386			if (cp != erdata)
387				goto no_recovery;
388			if (!haveanswer)
389				hent->h_name = bp;
390			else
391				addalias(ap, bp, aliases, maxaliases);
392			if (n != -1) {
393				n = (int)strlen(bp) + 1;	/* for the \0 */
394				if (n >= MAXHOSTNAMELEN) {
395					had_error++;
396					break;
397				}
398				bp += n;
399			}
400			break;
401#else
402			hent->h_name = bp;
403			if (res->options & RES_USE_INET6) {
404				n = strlen(bp) + 1;	/* for the \0 */
405				if (n >= MAXHOSTNAMELEN) {
406					had_error++;
407					break;
408				}
409				bp += n;
410				map_v4v6_hostent(hent, &bp, ep);
411			}
412			goto success;
413#endif
414		case T_A:
415		case T_AAAA:
416			if (strcasecmp(hent->h_name, bp) != 0) {
417				syslog(LOG_NOTICE|LOG_AUTH,
418				       AskedForGot, hent->h_name, bp);
419				cp += n;
420				continue;	/* XXX - had_error++ ? */
421			}
422			if (n != hent->h_length) {
423				cp += n;
424				continue;
425			}
426			if (type == T_AAAA) {
427				struct in6_addr in6;
428				memcpy(&in6, cp, NS_IN6ADDRSZ);
429				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
430					cp += n;
431					continue;
432				}
433			}
434			if (!haveanswer) {
435				int nn;
436
437				hent->h_name = bp;
438				nn = (int)strlen(bp) + 1;	/* for the \0 */
439				bp += nn;
440			}
441
442			bp += sizeof(align) -
443			    (size_t)((u_long)bp % sizeof(align));
444
445			if (bp + n >= ep) {
446				debugprintf("size (%d) too big\n", res, n);
447				had_error++;
448				continue;
449			}
450			if (hap >= &addr_ptrs[MAXADDRS - 1]) {
451				if (!toobig++) {
452					debugprintf("Too many addresses (%d)\n",
453						res, MAXADDRS);
454				}
455				cp += n;
456				continue;
457			}
458			(void)memcpy(*hap++ = bp, cp, (size_t)n);
459			bp += n;
460			cp += n;
461			if (cp != erdata)
462				goto no_recovery;
463			break;
464		default:
465			abort();
466		}
467		if (!had_error)
468			haveanswer++;
469	}
470	if (haveanswer) {
471		*ap = NULL;
472		*hap = NULL;
473		/*
474		 * Note: we sort even if host can take only one address
475		 * in its return structures - should give it the "best"
476		 * address in that case, not some random one
477		 */
478		if (res->nsort && haveanswer > 1 && qtype == T_A)
479			addrsort(addr_ptrs, haveanswer, res);
480		if (!hent->h_name) {
481			n = (int)strlen(qname) + 1;	/* for the \0 */
482			if (n > ep - bp || n >= MAXHOSTNAMELEN)
483				goto no_recovery;
484			strlcpy(bp, qname, (size_t)(ep - bp));
485			hent->h_name = bp;
486			bp += n;
487		}
488		if (res->options & RES_USE_INET6)
489			map_v4v6_hostent(hent, &bp, ep);
490	    	goto success;
491	}
492no_recovery:
493	free(aliases);
494	*he = NO_RECOVERY;
495	return NULL;
496success:
497	bp = (char *)ALIGN(bp);
498	n = (int)(ap - aliases);
499	qlen = (n + 1) * sizeof(*hent->h_aliases);
500	if ((size_t)(ep - bp) < qlen)
501		goto nospc;
502	hent->h_aliases = (void *)bp;
503	memcpy(bp, aliases, qlen);
504	free(aliases);
505	aliases = NULL;
506
507	bp += qlen;
508	n = (int)(hap - addr_ptrs);
509	qlen = (n + 1) * sizeof(*hent->h_addr_list);
510	if ((size_t)(ep - bp) < qlen)
511		goto nospc;
512	hent->h_addr_list = (void *)bp;
513	memcpy(bp, addr_ptrs, qlen);
514	*he = NETDB_SUCCESS;
515	return hent;
516nospc:
517	free(aliases);
518	errno = ENOSPC;
519	*he = NETDB_INTERNAL;
520	return NULL;
521}
522
523struct hostent *
524gethostbyname_r(const char *name, struct hostent *hp, char *buf, int buflen,
525    int *he)
526{
527	res_state res = __res_get_state();
528
529	if (res == NULL) {
530		*he = NETDB_INTERNAL;
531		return NULL;
532	}
533
534	_DIAGASSERT(name != NULL);
535
536	if (res->options & RES_USE_INET6) {
537		struct hostent *nhp = gethostbyname_internal(name, AF_INET6,
538		    res, hp, buf, buflen, he);
539		if (nhp) {
540			__res_put_state(res);
541			return nhp;
542		}
543	}
544	hp = gethostbyname_internal(name, AF_INET, res, hp, buf, buflen, he);
545	__res_put_state(res);
546	return hp;
547}
548
549struct hostent *
550gethostbyname2_r(const char *name, int af, struct hostent *hp, char *buf,
551    size_t buflen, int *he)
552{
553	res_state res = __res_get_state();
554
555	if (res == NULL) {
556		*he = NETDB_INTERNAL;
557		return NULL;
558	}
559	hp = gethostbyname_internal(name, af, res, hp, buf, buflen, he);
560	__res_put_state(res);
561	return hp;
562}
563
564static struct hostent *
565gethostbyname_internal(const char *name, int af, res_state res,
566    struct hostent *hp, char *buf, size_t buflen, int *he)
567{
568	const char *cp;
569	struct getnamaddr info;
570	char hbuf[MAXHOSTNAMELEN];
571	size_t size;
572	static const ns_dtab dtab[] = {
573		NS_FILES_CB(_hf_gethtbyname, NULL)
574		{ NSSRC_DNS, _dns_gethtbyname, NULL },	/* force -DHESIOD */
575		NS_NIS_CB(_yp_gethtbyname, NULL)
576		NS_NULL_CB
577	};
578
579	_DIAGASSERT(name != NULL);
580
581	switch (af) {
582	case AF_INET:
583		size = NS_INADDRSZ;
584		break;
585	case AF_INET6:
586		size = NS_IN6ADDRSZ;
587		break;
588	default:
589		*he = NETDB_INTERNAL;
590		errno = EAFNOSUPPORT;
591		return NULL;
592	}
593	if (buflen < size)
594		goto nospc;
595
596	hp->h_addrtype = af;
597	hp->h_length = (int)size;
598
599	/*
600	 * if there aren't any dots, it could be a user-level alias.
601	 * this is also done in res_nquery() since we are not the only
602	 * function that looks up host names.
603	 */
604	if (!strchr(name, '.') && (cp = res_hostalias(res, name,
605	    hbuf, sizeof(hbuf))))
606		name = cp;
607
608	/*
609	 * disallow names consisting only of digits/dots, unless
610	 * they end in a dot.
611	 */
612	if (isdigit((u_char) name[0]))
613		for (cp = name;; ++cp) {
614			if (!*cp) {
615				if (*--cp == '.')
616					break;
617				/*
618				 * All-numeric, no dot at the end.
619				 * Fake up a hostent as if we'd actually
620				 * done a lookup.
621				 */
622				goto fake;
623			}
624			if (!isdigit((u_char) *cp) && *cp != '.')
625				break;
626		}
627	if ((isxdigit((u_char) name[0]) && strchr(name, ':') != NULL) ||
628	    name[0] == ':')
629		for (cp = name;; ++cp) {
630			if (!*cp) {
631				if (*--cp == '.')
632					break;
633				/*
634				 * All-IPv6-legal, no dot at the end.
635				 * Fake up a hostent as if we'd actually
636				 * done a lookup.
637				 */
638				goto fake;
639			}
640			if (!isxdigit((u_char) *cp) && *cp != ':' && *cp != '.')
641				break;
642		}
643
644	*he = NETDB_INTERNAL;
645	info.hp = hp;
646	info.buf = buf;
647	info.buflen = buflen;
648	info.he = he;
649	if (nsdispatch(&info, dtab, NSDB_HOSTS, "gethostbyname",
650	    default_dns_files, name, strlen(name), af) != NS_SUCCESS)
651		return NULL;
652	*he = NETDB_SUCCESS;
653	return hp;
654nospc:
655	*he = NETDB_INTERNAL;
656	errno = ENOSPC;
657	return NULL;
658fake:
659	HENT_ARRAY(hp->h_addr_list, 1, buf, buflen);
660	HENT_ARRAY(hp->h_aliases, 0, buf, buflen);
661
662	hp->h_aliases[0] = NULL;
663	if (size > buflen)
664		goto nospc;
665
666	if (inet_pton(af, name, buf) <= 0) {
667		*he = HOST_NOT_FOUND;
668		return NULL;
669	}
670	hp->h_addr_list[0] = buf;
671	hp->h_addr_list[1] = NULL;
672	buf += size;
673	buflen -= size;
674	HENT_SCOPY(hp->h_name, name, buf, buflen);
675	if (res->options & RES_USE_INET6)
676		map_v4v6_hostent(hp, &buf, buf + buflen);
677	*he = NETDB_SUCCESS;
678	return hp;
679}
680
681struct hostent *
682gethostbyaddr_r(const void *addr, int len, int af,
683	struct hostent *hp, char *buf, int buflen, int *he)
684{
685	const u_char *uaddr = (const u_char *)addr;
686	socklen_t size;
687	struct getnamaddr info;
688	static const ns_dtab dtab[] = {
689		NS_FILES_CB(_hf_gethtbyaddr, NULL)
690		{ NSSRC_DNS, _dns_gethtbyaddr, NULL },	/* force -DHESIOD */
691		NS_NIS_CB(_yp_gethtbyaddr, NULL)
692		NS_NULL_CB
693	};
694
695	_DIAGASSERT(addr != NULL);
696
697	if (af == AF_INET6 && len == NS_IN6ADDRSZ &&
698	    (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr *)addr) ||
699	     IN6_IS_ADDR_SITELOCAL((const struct in6_addr *)addr))) {
700		*he = HOST_NOT_FOUND;
701		return NULL;
702	}
703	if (af == AF_INET6 && len == NS_IN6ADDRSZ &&
704	    (IN6_IS_ADDR_V4MAPPED((const struct in6_addr *)addr) ||
705	     IN6_IS_ADDR_V4COMPAT((const struct in6_addr *)addr))) {
706		/* Unmap. */
707		uaddr += NS_IN6ADDRSZ - NS_INADDRSZ;
708		addr = uaddr;
709		af = AF_INET;
710		len = NS_INADDRSZ;
711	}
712	switch (af) {
713	case AF_INET:
714		size = NS_INADDRSZ;
715		break;
716	case AF_INET6:
717		size = NS_IN6ADDRSZ;
718		break;
719	default:
720		errno = EAFNOSUPPORT;
721		*he = NETDB_INTERNAL;
722		return NULL;
723	}
724	if (size != len) {
725		errno = EINVAL;
726		*he = NETDB_INTERNAL;
727		return NULL;
728	}
729	info.hp = hp;
730	info.buf = buf;
731	info.buflen = buflen;
732	info.he = he;
733	*he = NETDB_INTERNAL;
734	if (nsdispatch(&info, dtab, NSDB_HOSTS, "gethostbyaddr",
735	    default_dns_files, uaddr, len, af) != NS_SUCCESS)
736		return NULL;
737	*he = NETDB_SUCCESS;
738	return hp;
739}
740
741struct hostent *
742gethostent_r(FILE *hf, struct hostent *hent, char *buf, size_t buflen, int *he)
743{
744	char *p, *name;
745	char *cp, **q;
746	int af, len;
747	size_t anum;
748	char **aliases;
749	size_t maxaliases;
750	struct in6_addr host_addr;
751
752	if (hf == NULL) {
753		*he = NETDB_INTERNAL;
754		errno = EINVAL;
755		return NULL;
756	}
757	p = NULL;
758	setup(aliases, maxaliases);
759	for (;;) {
760		free(p);
761		p = fparseln(hf, NULL, NULL, NULL, FPARSELN_UNESCALL);
762		if (p == NULL) {
763			free(aliases);
764			*he = HOST_NOT_FOUND;
765			return NULL;
766		}
767		if (!(cp = strpbrk(p, " \t")))
768			continue;
769		*cp++ = '\0';
770		if (inet_pton(AF_INET6, p, &host_addr) > 0) {
771			af = AF_INET6;
772			len = NS_IN6ADDRSZ;
773		} else {
774			if (inet_pton(AF_INET, p, &host_addr) <= 0)
775				continue;
776
777			{
778			res_state res = __res_get_state();
779			if (res == NULL)
780				goto nospc;
781			if (res->options & RES_USE_INET6) {
782				map_v4v6_address(buf, buf);
783				af = AF_INET6;
784				len = NS_IN6ADDRSZ;
785			} else {
786				af = AF_INET;
787				len = NS_INADDRSZ;
788			}
789			__res_put_state(res);
790			}
791		}
792
793		/* if this is not something we're looking for, skip it. */
794		if (hent->h_addrtype != 0 && hent->h_addrtype != af)
795			continue;
796		if (hent->h_length != 0 && hent->h_length != len)
797			continue;
798
799		while (*cp == ' ' || *cp == '\t')
800			cp++;
801		if ((cp = strpbrk(name = cp, " \t")) != NULL)
802			*cp++ = '\0';
803		q = aliases;
804		while (cp && *cp) {
805			if (*cp == ' ' || *cp == '\t') {
806				cp++;
807				continue;
808			}
809			addalias(q, cp, aliases, maxaliases);
810			if ((cp = strpbrk(cp, " \t")) != NULL)
811				*cp++ = '\0';
812		}
813		break;
814	}
815	hent->h_length = len;
816	hent->h_addrtype = af;
817	HENT_ARRAY(hent->h_addr_list, 1, buf, buflen);
818	anum = (size_t)(q - aliases);
819	HENT_ARRAY(hent->h_aliases, anum, buf, buflen);
820	HENT_COPY(hent->h_addr_list[0], &host_addr, hent->h_length, buf,
821	    buflen);
822	hent->h_addr_list[1] = NULL;
823
824	HENT_SCOPY(hent->h_name, name, buf, buflen);
825	{
826	size_t i;
827	for (i = 0; i < anum; i++)
828		HENT_SCOPY(hent->h_aliases[i], aliases[i], buf, buflen);
829	}
830	hent->h_aliases[anum] = NULL;
831
832	*he = NETDB_SUCCESS;
833	free(p);
834	free(aliases);
835	return hent;
836nospc:
837	free(p);
838	free(aliases);
839	errno = ENOSPC;
840	*he = NETDB_INTERNAL;
841	return NULL;
842}
843
844static void
845map_v4v6_address(const char *src, char *dst)
846{
847	u_char *p = (u_char *)dst;
848	char tmp[NS_INADDRSZ];
849	int i;
850
851	_DIAGASSERT(src != NULL);
852	_DIAGASSERT(dst != NULL);
853
854	/* Stash a temporary copy so our caller can update in place. */
855	(void)memcpy(tmp, src, NS_INADDRSZ);
856	/* Mark this ipv6 addr as a mapped ipv4. */
857	for (i = 0; i < 10; i++)
858		*p++ = 0x00;
859	*p++ = 0xff;
860	*p++ = 0xff;
861	/* Retrieve the saved copy and we're done. */
862	(void)memcpy(p, tmp, NS_INADDRSZ);
863}
864
865static void
866map_v4v6_hostent(struct hostent *hp, char **bpp, char *ep)
867{
868	char **ap;
869
870	_DIAGASSERT(hp != NULL);
871	_DIAGASSERT(bpp != NULL);
872	_DIAGASSERT(ep != NULL);
873
874	if (hp->h_addrtype != AF_INET || hp->h_length != NS_INADDRSZ)
875		return;
876	hp->h_addrtype = AF_INET6;
877	hp->h_length = NS_IN6ADDRSZ;
878	for (ap = hp->h_addr_list; *ap; ap++) {
879		int i = (int)(sizeof(align) -
880		    (size_t)((u_long)*bpp % sizeof(align)));
881
882		if (ep - *bpp < (i + NS_IN6ADDRSZ)) {
883			/* Out of memory.  Truncate address list here.  XXX */
884			*ap = NULL;
885			return;
886		}
887		*bpp += i;
888		map_v4v6_address(*ap, *bpp);
889		*ap = *bpp;
890		*bpp += NS_IN6ADDRSZ;
891	}
892}
893
894static void
895addrsort(char **ap, int num, res_state res)
896{
897	int i, j;
898	char **p;
899	short aval[MAXADDRS];
900	int needsort = 0;
901
902	_DIAGASSERT(ap != NULL);
903
904	p = ap;
905	for (i = 0; i < num; i++, p++) {
906	    for (j = 0 ; (unsigned)j < res->nsort; j++)
907		if (res->sort_list[j].addr.s_addr ==
908		    (((struct in_addr *)(void *)(*p))->s_addr &
909		    res->sort_list[j].mask))
910			break;
911	    aval[i] = j;
912	    if (needsort == 0 && i > 0 && j < aval[i-1])
913		needsort = i;
914	}
915	if (!needsort)
916	    return;
917
918	while (needsort < num) {
919	    for (j = needsort - 1; j >= 0; j--) {
920		if (aval[j] > aval[j+1]) {
921		    char *hp;
922
923		    i = aval[j];
924		    aval[j] = aval[j+1];
925		    aval[j+1] = i;
926
927		    hp = ap[j];
928		    ap[j] = ap[j+1];
929		    ap[j+1] = hp;
930		} else
931		    break;
932	    }
933	    needsort++;
934	}
935}
936
937
938/*ARGSUSED*/
939int
940_dns_gethtbyname(void *rv, void *cb_data, va_list ap)
941{
942	querybuf *buf;
943	int n, type;
944	struct hostent *hp;
945	const char *name;
946	res_state res;
947	struct getnamaddr *info = rv;
948
949	_DIAGASSERT(rv != NULL);
950
951	name = va_arg(ap, char *);
952	/* NOSTRICT skip string len */(void)va_arg(ap, int);
953	info->hp->h_addrtype = va_arg(ap, int);
954
955	switch (info->hp->h_addrtype) {
956	case AF_INET:
957		info->hp->h_length = NS_INADDRSZ;
958		type = T_A;
959		break;
960	case AF_INET6:
961		info->hp->h_length = NS_IN6ADDRSZ;
962		type = T_AAAA;
963		break;
964	default:
965		return NS_UNAVAIL;
966	}
967	buf = malloc(sizeof(*buf));
968	if (buf == NULL) {
969		*info->he = NETDB_INTERNAL;
970		return NS_NOTFOUND;
971	}
972	res = __res_get_state();
973	if (res == NULL) {
974		free(buf);
975		*info->he = NETDB_INTERNAL;
976		return NS_NOTFOUND;
977	}
978	n = res_nsearch(res, name, C_IN, type, buf->buf, (int)sizeof(buf->buf));
979	if (n < 0) {
980		free(buf);
981		debugprintf("res_nsearch failed (%d)\n", res, n);
982		__res_put_state(res);
983		return NS_NOTFOUND;
984	}
985	hp = getanswer(buf, n, name, type, res, info->hp, info->buf,
986	    info->buflen, info->he);
987	free(buf);
988	__res_put_state(res);
989	if (hp == NULL)
990		switch (*info->he) {
991		case HOST_NOT_FOUND:
992			return NS_NOTFOUND;
993		case TRY_AGAIN:
994			return NS_TRYAGAIN;
995		default:
996			return NS_UNAVAIL;
997		}
998	return NS_SUCCESS;
999}
1000
1001/*ARGSUSED*/
1002int
1003_dns_gethtbyaddr(void *rv, void	*cb_data, va_list ap)
1004{
1005	char qbuf[MAXDNAME + 1], *qp, *ep;
1006	int n;
1007	querybuf *buf;
1008	struct hostent *hp;
1009	const unsigned char *uaddr;
1010	int advance;
1011	res_state res;
1012	char *bf;
1013	size_t blen;
1014	struct getnamaddr *info = rv;
1015
1016	_DIAGASSERT(rv != NULL);
1017
1018	uaddr = va_arg(ap, unsigned char *);
1019	info->hp->h_length = va_arg(ap, int);
1020	info->hp->h_addrtype = va_arg(ap, int);
1021
1022	switch (info->hp->h_addrtype) {
1023	case AF_INET:
1024		(void)snprintf(qbuf, sizeof(qbuf), "%u.%u.%u.%u.in-addr.arpa",
1025		    (uaddr[3] & 0xff), (uaddr[2] & 0xff),
1026		    (uaddr[1] & 0xff), (uaddr[0] & 0xff));
1027		break;
1028
1029	case AF_INET6:
1030		qp = qbuf;
1031		ep = qbuf + sizeof(qbuf) - 1;
1032		for (n = NS_IN6ADDRSZ - 1; n >= 0; n--) {
1033			advance = snprintf(qp, (size_t)(ep - qp), "%x.%x.",
1034			    uaddr[n] & 0xf,
1035			    ((unsigned int)uaddr[n] >> 4) & 0xf);
1036			if (advance > 0 && qp + advance < ep)
1037				qp += advance;
1038			else
1039				goto norecovery;
1040		}
1041		if (strlcat(qbuf, "ip6.arpa", sizeof(qbuf)) >= sizeof(qbuf))
1042			goto norecovery;
1043		break;
1044	default:
1045		goto norecovery;
1046	}
1047
1048	buf = malloc(sizeof(*buf));
1049	if (buf == NULL) {
1050		goto nospc;
1051	}
1052	res = __res_get_state();
1053	if (res == NULL) {
1054		free(buf);
1055		goto nospc;
1056	}
1057	n = res_nquery(res, qbuf, C_IN, T_PTR, buf->buf, (int)sizeof(buf->buf));
1058	if (n < 0) {
1059		free(buf);
1060		debugprintf("res_nquery failed (%d)\n", res, n);
1061		__res_put_state(res);
1062		*info->he = HOST_NOT_FOUND;
1063		return NS_NOTFOUND;
1064	}
1065	hp = getanswer(buf, n, qbuf, T_PTR, res, info->hp, info->buf,
1066	    info->buflen, info->he);
1067	free(buf);
1068	if (hp == NULL) {
1069		__res_put_state(res);
1070		switch (*info->he) {
1071		case HOST_NOT_FOUND:
1072			return NS_NOTFOUND;
1073		case TRY_AGAIN:
1074			return NS_TRYAGAIN;
1075		default:
1076			return NS_UNAVAIL;
1077		}
1078	}
1079
1080	bf = (void *)(hp->h_addr_list + 2);
1081	blen = (size_t)(bf - info->buf);
1082	if (blen + info->hp->h_length > info->buflen)
1083		goto nospc;
1084	hp->h_addr_list[0] = bf;
1085	hp->h_addr_list[1] = NULL;
1086	(void)memcpy(bf, uaddr, (size_t)info->hp->h_length);
1087	if (info->hp->h_addrtype == AF_INET && (res->options & RES_USE_INET6)) {
1088		if (blen + NS_IN6ADDRSZ > info->buflen) {
1089			__res_put_state(res);
1090			goto nospc;
1091		}
1092		map_v4v6_address(bf, bf);
1093		hp->h_addrtype = AF_INET6;
1094		hp->h_length = NS_IN6ADDRSZ;
1095	}
1096
1097	__res_put_state(res);
1098	*info->he = NETDB_SUCCESS;
1099	return NS_SUCCESS;
1100nospc:
1101	*info->he = NETDB_INTERNAL;
1102	return NS_UNAVAIL;
1103norecovery:
1104	*info->he = NO_RECOVERY;
1105	return NS_UNAVAIL;
1106}
1107
1108#ifdef YP
1109/*ARGSUSED*/
1110static struct hostent *
1111_yp_hostent(char *line, int af, struct getnamaddr *info)
1112{
1113	struct in6_addr host_addrs[MAXADDRS];
1114	char **aliases;
1115	size_t maxaliases;
1116	char *p = line;
1117	char *cp, **q, *ptr;
1118	size_t len, anum, i;
1119	int addrok;
1120	int more;
1121	size_t naddrs;
1122	struct hostent *hp = info->hp;
1123
1124	_DIAGASSERT(line != NULL);
1125
1126	hp->h_name = NULL;
1127	hp->h_addrtype = af;
1128	switch (af) {
1129	case AF_INET:
1130		hp->h_length = NS_INADDRSZ;
1131		break;
1132	case AF_INET6:
1133		hp->h_length = NS_IN6ADDRSZ;
1134		break;
1135	default:
1136		return NULL;
1137	}
1138	setup(aliases, maxaliases);
1139	naddrs = 0;
1140	q = aliases;
1141
1142nextline:
1143	/* check for host_addrs overflow */
1144	if (naddrs >= __arraycount(host_addrs))
1145		goto done;
1146
1147	more = 0;
1148	cp = strpbrk(p, " \t");
1149	if (cp == NULL)
1150		goto done;
1151	*cp++ = '\0';
1152
1153	/* p has should have an address */
1154	addrok = inet_pton(af, p, &host_addrs[naddrs]);
1155	if (addrok != 1) {
1156		/* skip to the next line */
1157		while (cp && *cp) {
1158			if (*cp == '\n') {
1159				cp++;
1160				goto nextline;
1161			}
1162			cp++;
1163		}
1164		goto done;
1165	}
1166	naddrs++;
1167
1168	while (*cp == ' ' || *cp == '\t')
1169		cp++;
1170	p = cp;
1171	cp = strpbrk(p, " \t\n");
1172	if (cp != NULL) {
1173		if (*cp == '\n')
1174			more = 1;
1175		*cp++ = '\0';
1176	}
1177	if (!hp->h_name)
1178		hp->h_name = p;
1179	else if (strcmp(hp->h_name, p) == 0)
1180		;
1181	else
1182		addalias(q, p, aliases, maxaliases);
1183	p = cp;
1184	if (more)
1185		goto nextline;
1186
1187	while (cp && *cp) {
1188		if (*cp == ' ' || *cp == '\t') {
1189			cp++;
1190			continue;
1191		}
1192		if (*cp == '\n') {
1193			cp++;
1194			goto nextline;
1195		}
1196		addalias(q, cp, aliases, maxaliases);
1197		cp = strpbrk(cp, " \t");
1198		if (cp != NULL)
1199			*cp++ = '\0';
1200	}
1201
1202done:
1203	if (hp->h_name == NULL) {
1204		free(aliases);
1205		return NULL;
1206	}
1207
1208	ptr = info->buf;
1209	len = info->buflen;
1210
1211	anum = (size_t)(q - aliases);
1212	HENT_ARRAY(hp->h_addr_list, naddrs, ptr, len);
1213	HENT_ARRAY(hp->h_aliases, anum, ptr, len);
1214
1215	for (i = 0; i < naddrs; i++)
1216		HENT_COPY(hp->h_addr_list[i], &host_addrs[i], hp->h_length,
1217		    ptr, len);
1218	hp->h_addr_list[naddrs] = NULL;
1219
1220	HENT_SCOPY(hp->h_name, hp->h_name, ptr, len);
1221
1222	for (i = 0; i < anum; i++)
1223		HENT_SCOPY(hp->h_aliases[i], aliases[i], ptr, len);
1224	hp->h_aliases[anum] = NULL;
1225	free(aliases);
1226
1227	return hp;
1228nospc:
1229	free(aliases);
1230	*info->he = NETDB_INTERNAL;
1231	errno = ENOSPC;
1232	return NULL;
1233}
1234
1235/*ARGSUSED*/
1236int
1237_yp_gethtbyaddr(void *rv, void *cb_data, va_list ap)
1238{
1239	struct hostent *hp = NULL;
1240	char *ypcurrent;
1241	int ypcurrentlen, r;
1242	char name[INET6_ADDRSTRLEN];	/* XXX enough? */
1243	const unsigned char *uaddr;
1244	int af;
1245	const char *map;
1246	struct getnamaddr *info = rv;
1247
1248	_DIAGASSERT(rv != NULL);
1249
1250	uaddr = va_arg(ap, unsigned char *);
1251	/* NOSTRICT skip len */(void)va_arg(ap, int);
1252	af = va_arg(ap, int);
1253
1254	if (!__ypdomain) {
1255		if (_yp_check(&__ypdomain) == 0)
1256			return NS_UNAVAIL;
1257	}
1258	/*
1259	 * XXX unfortunately, we cannot support IPv6 extended scoped address
1260	 * notation here.  gethostbyaddr() is not scope-aware.  too bad.
1261	 */
1262	if (inet_ntop(af, uaddr, name, (socklen_t)sizeof(name)) == NULL)
1263		return NS_UNAVAIL;
1264	switch (af) {
1265	case AF_INET:
1266		map = "hosts.byaddr";
1267		break;
1268	default:
1269		map = "ipnodes.byaddr";
1270		break;
1271	}
1272	ypcurrent = NULL;
1273	r = yp_match(__ypdomain, map, name,
1274		(int)strlen(name), &ypcurrent, &ypcurrentlen);
1275	if (r == 0)
1276		hp = _yp_hostent(ypcurrent, af, info);
1277	else
1278		hp = NULL;
1279	free(ypcurrent);
1280	if (hp == NULL) {
1281		*info->he = HOST_NOT_FOUND;
1282		return NS_NOTFOUND;
1283	}
1284	return NS_SUCCESS;
1285}
1286
1287/*ARGSUSED*/
1288int
1289_yp_gethtbyname(void *rv, void *cb_data, va_list ap)
1290{
1291	struct hostent *hp;
1292	char *ypcurrent;
1293	int ypcurrentlen, r;
1294	const char *name;
1295	int af;
1296	const char *map;
1297	struct getnamaddr *info = rv;
1298
1299	_DIAGASSERT(rv != NULL);
1300
1301	name = va_arg(ap, char *);
1302	/* NOSTRICT skip string len */(void)va_arg(ap, int);
1303	af = va_arg(ap, int);
1304
1305	if (!__ypdomain) {
1306		if (_yp_check(&__ypdomain) == 0)
1307			return NS_UNAVAIL;
1308	}
1309	switch (af) {
1310	case AF_INET:
1311		map = "hosts.byname";
1312		break;
1313	default:
1314		map = "ipnodes.byname";
1315		break;
1316	}
1317	ypcurrent = NULL;
1318	r = yp_match(__ypdomain, map, name,
1319		(int)strlen(name), &ypcurrent, &ypcurrentlen);
1320	if (r == 0)
1321		hp = _yp_hostent(ypcurrent, af, info);
1322	else
1323		hp = NULL;
1324	free(ypcurrent);
1325	if (hp == NULL) {
1326		*info->he = HOST_NOT_FOUND;
1327		return NS_NOTFOUND;
1328	}
1329	return NS_SUCCESS;
1330}
1331#endif
1332
1333/*
1334 * Non-reentrant versions.
1335 */
1336FILE *_h_file;
1337static struct hostent h_ent;
1338static char h_buf[16384];
1339
1340struct hostent *
1341gethostbyaddr(const void *addr, socklen_t len, int af) {
1342	return gethostbyaddr_r(addr, len, af, &h_ent, h_buf, sizeof(h_buf),
1343	    &h_errno);
1344}
1345
1346struct hostent *
1347gethostbyname(const char *name) {
1348	return gethostbyname_r(name, &h_ent, h_buf, sizeof(h_buf), &h_errno);
1349}
1350
1351struct hostent *
1352gethostbyname2(const char *name, int af) {
1353	return gethostbyname2_r(name, af, &h_ent, h_buf, sizeof(h_buf),
1354	    &h_errno);
1355}
1356
1357struct hostent *
1358gethostent(void)
1359{
1360	if (_h_file == NULL) {
1361		sethostent_r(&_h_file);
1362		if (_h_file == NULL) {
1363			h_errno = NETDB_INTERNAL;
1364			return NULL;
1365		}
1366	}
1367	memset(&h_ent, 0, sizeof(h_ent));
1368	return gethostent_r(_h_file, &h_ent, h_buf, sizeof(h_buf), &h_errno);
1369}
1370
1371