1/*	$NetBSD: gethnamaddr.c,v 1.70 2006/03/22 00:03:51 christos 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#include <sys/types.h>
56
57#include <sys/param.h>
58#include <sys/socket.h>
59#include <netinet/in.h>
60#include <arpa/inet.h>
61#include "arpa_nameser.h"
62#include "resolv_private.h"
63#include "resolv_cache.h"
64#include <assert.h>
65#include <ctype.h>
66#include <errno.h>
67#include <netdb.h>
68#include <stdarg.h>
69#include <stdio.h>
70#include <syslog.h>
71
72#ifndef LOG_AUTH
73# define LOG_AUTH 0
74#endif
75
76#define MULTI_PTRS_ARE_ALIASES 1	/* XXX - experimental */
77
78#include "nsswitch.h"
79#include <stdlib.h>
80#include <string.h>
81
82static const char const AskedForGot[] =
83			  "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
84
85#define	MAXPACKET	(64*1024)
86
87typedef union {
88    HEADER hdr;
89    u_char buf[MAXPACKET];
90} querybuf;
91
92typedef union {
93    int32_t al;
94    char ac;
95} align;
96
97#ifdef DEBUG
98static void dprintf(const char *, res_state, ...)
99	__attribute__((__format__(__printf__, 1, 3)));
100#endif
101static struct hostent *getanswer(const querybuf *, int, const char *, int,
102    res_state);
103static void map_v4v6_address(const char *, char *);
104static void map_v4v6_hostent(struct hostent *, char **, char *);
105static void addrsort(char **, int, res_state);
106
107void _sethtent(int);
108void _endhtent(void);
109struct hostent *_gethtent(void);
110void ht_sethostent(int);
111void ht_endhostent(void);
112struct hostent *ht_gethostbyname(char *);
113struct hostent *ht_gethostbyaddr(const char *, int, int);
114void dns_service(void);
115#undef dn_skipname
116int dn_skipname(const u_char *, const u_char *);
117int _gethtbyaddr(void *, void *, va_list);
118int _gethtbyname(void *, void *, va_list);
119struct hostent *_gethtbyname2(const char *, int);
120int _dns_gethtbyaddr(void *, void *, va_list);
121int _dns_gethtbyname(void *, void *, va_list);
122
123static struct hostent *gethostbyname_internal(const char *, int, res_state);
124
125static const ns_src default_dns_files[] = {
126	{ NSSRC_FILES, 	NS_SUCCESS },
127	{ NSSRC_DNS, 	NS_SUCCESS },
128	{ 0, 0 }
129};
130
131
132#ifdef DEBUG
133static void
134dprintf(const char *msg, res_state res, ...)
135{
136	assert(msg != NULL);
137
138	if (res->options & RES_DEBUG) {
139		int save = errno;
140		va_list ap;
141
142		va_start (ap, res);
143		vprintf(msg, ap);
144		va_end (ap);
145
146		errno = save;
147	}
148}
149#else
150# define dprintf(msg, res, num) ((void)0) /*nada*/
151#endif
152
153#define BOUNDED_INCR(x) \
154	do { \
155		cp += (x); \
156		if (cp > eom) { \
157			h_errno = NO_RECOVERY; \
158			return NULL; \
159		} \
160	} while (/*CONSTCOND*/0)
161
162#define BOUNDS_CHECK(ptr, count) \
163	do { \
164		if ((ptr) + (count) > eom) { \
165			h_errno = NO_RECOVERY; \
166			return NULL; \
167		} \
168	} while (/*CONSTCOND*/0)
169
170static struct hostent *
171getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
172    res_state res)
173{
174	const HEADER *hp;
175	const u_char *cp;
176	int n;
177	const u_char *eom, *erdata;
178	char *bp, **ap, **hap, *ep;
179	int type, class, ancount, qdcount;
180	int haveanswer, had_error;
181	int toobig = 0;
182	char tbuf[MAXDNAME];
183	const char *tname;
184	int (*name_ok)(const char *);
185	res_static  rs = __res_get_static();
186
187	assert(answer != NULL);
188	assert(qname != NULL);
189
190	tname = qname;
191	rs->host.h_name = NULL;
192	eom = answer->buf + anslen;
193	switch (qtype) {
194	case T_A:
195	case T_AAAA:
196		name_ok = res_hnok;
197		break;
198	case T_PTR:
199		name_ok = res_dnok;
200		break;
201	default:
202		return NULL;	/* XXX should be abort(); */
203	}
204	/*
205	 * find first satisfactory answer
206	 */
207	hp = &answer->hdr;
208	ancount = ntohs(hp->ancount);
209	qdcount = ntohs(hp->qdcount);
210	bp = rs->hostbuf;
211	ep = rs->hostbuf + sizeof rs->hostbuf;
212	cp = answer->buf;
213	BOUNDED_INCR(HFIXEDSZ);
214	if (qdcount != 1) {
215		h_errno = NO_RECOVERY;
216		return NULL;
217	}
218	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
219	if ((n < 0) || !(*name_ok)(bp)) {
220		h_errno = NO_RECOVERY;
221		return NULL;
222	}
223	BOUNDED_INCR(n + QFIXEDSZ);
224	if (qtype == T_A || qtype == T_AAAA) {
225		/* res_send() has already verified that the query name is the
226		 * same as the one we sent; this just gets the expanded name
227		 * (i.e., with the succeeding search-domain tacked on).
228		 */
229		n = strlen(bp) + 1;		/* for the \0 */
230		if (n >= MAXHOSTNAMELEN) {
231			h_errno = NO_RECOVERY;
232			return NULL;
233		}
234		rs->host.h_name = bp;
235		bp += n;
236		/* The qname can be abbreviated, but h_name is now absolute. */
237		qname = rs->host.h_name;
238	}
239	ap = rs->host_aliases;
240	*ap = NULL;
241	rs->host.h_aliases = rs->host_aliases;
242	hap = rs->h_addr_ptrs;
243	*hap = NULL;
244	rs->host.h_addr_list = rs->h_addr_ptrs;
245	haveanswer = 0;
246	had_error = 0;
247	while (ancount-- > 0 && cp < eom && !had_error) {
248		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
249		if ((n < 0) || !(*name_ok)(bp)) {
250			had_error++;
251			continue;
252		}
253		cp += n;			/* name */
254		BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
255		type = _getshort(cp);
256 		cp += INT16SZ;			/* type */
257		class = _getshort(cp);
258 		cp += INT16SZ + INT32SZ;	/* class, TTL */
259		n = _getshort(cp);
260		cp += INT16SZ;			/* len */
261		BOUNDS_CHECK(cp, n);
262		erdata = cp + n;
263		if (class != C_IN) {
264			/* XXX - debug? syslog? */
265			cp += n;
266			continue;		/* XXX - had_error++ ? */
267		}
268		if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
269			if (ap >= &rs->host_aliases[MAXALIASES-1])
270				continue;
271			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
272			if ((n < 0) || !(*name_ok)(tbuf)) {
273				had_error++;
274				continue;
275			}
276			cp += n;
277			if (cp != erdata) {
278				h_errno = NO_RECOVERY;
279				return NULL;
280			}
281			/* Store alias. */
282			*ap++ = bp;
283			n = strlen(bp) + 1;	/* for the \0 */
284			if (n >= MAXHOSTNAMELEN) {
285				had_error++;
286				continue;
287			}
288			bp += n;
289			/* Get canonical name. */
290			n = strlen(tbuf) + 1;	/* for the \0 */
291			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
292				had_error++;
293				continue;
294			}
295			strlcpy(bp, tbuf, (size_t)(ep - bp));
296			rs->host.h_name = bp;
297			bp += n;
298			continue;
299		}
300		if (qtype == T_PTR && type == T_CNAME) {
301			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
302			if (n < 0 || !res_dnok(tbuf)) {
303				had_error++;
304				continue;
305			}
306			cp += n;
307			if (cp != erdata) {
308				h_errno = NO_RECOVERY;
309				return NULL;
310			}
311			/* Get canonical name. */
312			n = strlen(tbuf) + 1;	/* for the \0 */
313			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
314				had_error++;
315				continue;
316			}
317			strlcpy(bp, tbuf, (size_t)(ep - bp));
318			tname = bp;
319			bp += n;
320			continue;
321		}
322		if (type != qtype) {
323			if (type != T_KEY && type != T_SIG)
324				syslog(LOG_NOTICE|LOG_AUTH,
325	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
326				       qname, p_class(C_IN), p_type(qtype),
327				       p_type(type));
328			cp += n;
329			continue;		/* XXX - had_error++ ? */
330		}
331		switch (type) {
332		case T_PTR:
333			if (strcasecmp(tname, bp) != 0) {
334				syslog(LOG_NOTICE|LOG_AUTH,
335				       AskedForGot, qname, bp);
336				cp += n;
337				continue;	/* XXX - had_error++ ? */
338			}
339			n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
340			if ((n < 0) || !res_hnok(bp)) {
341				had_error++;
342				break;
343			}
344#if MULTI_PTRS_ARE_ALIASES
345			cp += n;
346			if (cp != erdata) {
347				h_errno = NO_RECOVERY;
348				return NULL;
349			}
350			if (!haveanswer)
351				rs->host.h_name = bp;
352			else if (ap < &rs->host_aliases[MAXALIASES-1])
353				*ap++ = bp;
354			else
355				n = -1;
356			if (n != -1) {
357				n = strlen(bp) + 1;	/* for the \0 */
358				if (n >= MAXHOSTNAMELEN) {
359					had_error++;
360					break;
361				}
362				bp += n;
363			}
364			break;
365#else
366			rs->host.h_name = bp;
367			if (res->options & RES_USE_INET6) {
368				n = strlen(bp) + 1;	/* for the \0 */
369				if (n >= MAXHOSTNAMELEN) {
370					had_error++;
371					break;
372				}
373				bp += n;
374				map_v4v6_hostent(&rs->host, &bp, ep);
375			}
376			h_errno = NETDB_SUCCESS;
377			return &rs->host;
378#endif
379		case T_A:
380		case T_AAAA:
381			if (strcasecmp(rs->host.h_name, bp) != 0) {
382				syslog(LOG_NOTICE|LOG_AUTH,
383				       AskedForGot, rs->host.h_name, bp);
384				cp += n;
385				continue;	/* XXX - had_error++ ? */
386			}
387			if (n != rs->host.h_length) {
388				cp += n;
389				continue;
390			}
391			if (type == T_AAAA) {
392				struct in6_addr in6;
393				memcpy(&in6, cp, IN6ADDRSZ);
394				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
395					cp += n;
396					continue;
397				}
398			}
399			if (!haveanswer) {
400				int nn;
401
402				rs->host.h_name = bp;
403				nn = strlen(bp) + 1;	/* for the \0 */
404				bp += nn;
405			}
406
407			bp += sizeof(align) -
408			    (size_t)((u_long)bp % sizeof(align));
409
410			if (bp + n >= &rs->hostbuf[sizeof rs->hostbuf]) {
411				dprintf("size (%d) too big\n", res, n);
412				had_error++;
413				continue;
414			}
415			if (hap >= &rs->h_addr_ptrs[MAXADDRS-1]) {
416				if (!toobig++)
417					dprintf("Too many addresses (%d)\n",
418						res, MAXADDRS);
419				cp += n;
420				continue;
421			}
422			(void)memcpy(*hap++ = bp, cp, (size_t)n);
423			bp += n;
424			cp += n;
425			if (cp != erdata) {
426				h_errno = NO_RECOVERY;
427				return NULL;
428			}
429			break;
430		default:
431			abort();
432		}
433		if (!had_error)
434			haveanswer++;
435	}
436	if (haveanswer) {
437		*ap = NULL;
438		*hap = NULL;
439		/*
440		 * Note: we sort even if host can take only one address
441		 * in its return structures - should give it the "best"
442		 * address in that case, not some random one
443		 */
444		if (res->nsort && haveanswer > 1 && qtype == T_A)
445			addrsort(rs->h_addr_ptrs, haveanswer, res);
446		if (!rs->host.h_name) {
447			n = strlen(qname) + 1;	/* for the \0 */
448			if (n > ep - bp || n >= MAXHOSTNAMELEN)
449				goto no_recovery;
450			strlcpy(bp, qname, (size_t)(ep - bp));
451			rs->host.h_name = bp;
452			bp += n;
453		}
454		if (res->options & RES_USE_INET6)
455			map_v4v6_hostent(&rs->host, &bp, ep);
456		h_errno = NETDB_SUCCESS;
457		return &rs->host;
458	}
459 no_recovery:
460	h_errno = NO_RECOVERY;
461	return NULL;
462}
463
464int
465gethostbyname_r(const char *name, struct hostent *hp, char *buf, size_t buflen,
466    struct hostent**result, int *errorp)
467{
468        struct hostent *res;
469
470        res = gethostbyname(name);
471        *errorp = h_errno;
472        if (res == NULL) {
473                *result = NULL;
474                return -1;
475        }
476        memcpy(hp, res, sizeof *hp);
477        *result = hp;
478        return 0;
479}
480
481struct hostent *
482gethostbyname(const char *name)
483{
484	struct hostent *hp;
485	res_state res = __res_get_state();
486
487	if (res == NULL)
488		return NULL;
489
490	assert(name != NULL);
491
492	if (res->options & RES_USE_INET6) {
493		hp = gethostbyname_internal(name, AF_INET6, res);
494		if (hp) {
495			__res_put_state(res);
496			return hp;
497		}
498	}
499	hp = gethostbyname_internal(name, AF_INET, res);
500	__res_put_state(res);
501	return hp;
502}
503
504struct hostent *
505gethostbyname2(const char *name, int af)
506{
507	struct hostent *hp;
508	res_state res = __res_get_state();
509
510	if (res == NULL)
511		return NULL;
512	hp = gethostbyname_internal(name, af, res);
513	__res_put_state(res);
514	return hp;
515}
516
517static struct hostent *
518gethostbyname_internal(const char *name, int af, res_state res)
519{
520	const char *cp;
521	char *bp, *ep;
522	int size;
523	struct hostent *hp;
524        struct resolv_cache*  cache;
525        res_static  rs = __res_get_static();
526
527	static const ns_dtab dtab[] = {
528		NS_FILES_CB(_gethtbyname, NULL)
529		{ NSSRC_DNS, _dns_gethtbyname, NULL },	/* force -DHESIOD */
530		{ 0, 0, 0 }
531	};
532
533	assert(name != NULL);
534
535	switch (af) {
536	case AF_INET:
537		size = INADDRSZ;
538		break;
539	case AF_INET6:
540		size = IN6ADDRSZ;
541		break;
542	default:
543		h_errno = NETDB_INTERNAL;
544		errno = EAFNOSUPPORT;
545		return NULL;
546	}
547
548	rs->host.h_addrtype = af;
549	rs->host.h_length = size;
550
551	/*
552	 * if there aren't any dots, it could be a user-level alias.
553	 * this is also done in res_nquery() since we are not the only
554	 * function that looks up host names.
555	 */
556	if (!strchr(name, '.') && (cp = __hostalias(name)))
557		name = cp;
558
559	/*
560	 * disallow names consisting only of digits/dots, unless
561	 * they end in a dot.
562	 */
563	if (isdigit((u_char) name[0]))
564		for (cp = name;; ++cp) {
565			if (!*cp) {
566				if (*--cp == '.')
567					break;
568				/*
569				 * All-numeric, no dot at the end.
570				 * Fake up a hostent as if we'd actually
571				 * done a lookup.
572				 */
573				if (inet_pton(af, name,
574				    (char *)(void *)rs->host_addr) <= 0) {
575					h_errno = HOST_NOT_FOUND;
576					return NULL;
577				}
578				strncpy(rs->hostbuf, name, MAXDNAME);
579				rs->hostbuf[MAXDNAME] = '\0';
580				bp = rs->hostbuf + MAXDNAME;
581				ep = rs->hostbuf + sizeof rs->hostbuf;
582				rs->host.h_name = rs->hostbuf;
583				rs->host.h_aliases = rs->host_aliases;
584				rs->host_aliases[0] = NULL;
585				rs->h_addr_ptrs[0] = (char *)(void *)rs->host_addr;
586				rs->h_addr_ptrs[1] = NULL;
587				rs->host.h_addr_list = rs->h_addr_ptrs;
588				if (res->options & RES_USE_INET6)
589					map_v4v6_hostent(&rs->host, &bp, ep);
590				h_errno = NETDB_SUCCESS;
591				return &rs->host;
592			}
593			if (!isdigit((u_char) *cp) && *cp != '.')
594				break;
595		}
596	if ((isxdigit((u_char) name[0]) && strchr(name, ':') != NULL) ||
597	    name[0] == ':')
598		for (cp = name;; ++cp) {
599			if (!*cp) {
600				if (*--cp == '.')
601					break;
602				/*
603				 * All-IPv6-legal, no dot at the end.
604				 * Fake up a hostent as if we'd actually
605				 * done a lookup.
606				 */
607				if (inet_pton(af, name,
608				    (char *)(void *)rs->host_addr) <= 0) {
609					h_errno = HOST_NOT_FOUND;
610					return NULL;
611				}
612				strncpy(rs->hostbuf, name, MAXDNAME);
613				rs->hostbuf[MAXDNAME] = '\0';
614				bp = rs->hostbuf + MAXDNAME;
615				ep = rs->hostbuf + sizeof rs->hostbuf;
616				rs->host.h_name = rs->hostbuf;
617				rs->host.h_aliases = rs->host_aliases;
618				rs->host_aliases[0] = NULL;
619				rs->h_addr_ptrs[0] = (char *)(void *)rs->host_addr;
620				rs->h_addr_ptrs[1] = NULL;
621				rs->host.h_addr_list = rs->h_addr_ptrs;
622				h_errno = NETDB_SUCCESS;
623				return &rs->host;
624			}
625			if (!isxdigit((u_char) *cp) && *cp != ':' && *cp != '.')
626				break;
627		}
628
629	hp = NULL;
630	h_errno = NETDB_INTERNAL;
631	if (nsdispatch(&hp, dtab, NSDB_HOSTS, "gethostbyname",
632	    default_dns_files, name, strlen(name), af) != NS_SUCCESS) {
633		return NULL;
634        }
635	h_errno = NETDB_SUCCESS;
636	return hp;
637}
638
639struct hostent *
640gethostbyaddr(const char *addr,	/* XXX should have been def'd as u_char! */
641    socklen_t len, int af)
642{
643	const u_char *uaddr = (const u_char *)addr;
644	socklen_t size;
645	struct hostent *hp;
646	static const ns_dtab dtab[] = {
647		NS_FILES_CB(_gethtbyaddr, NULL)
648		{ NSSRC_DNS, _dns_gethtbyaddr, NULL },	/* force -DHESIOD */
649		{ 0, 0, 0 }
650	};
651
652	assert(addr != NULL);
653
654	if (af == AF_INET6 && len == IN6ADDRSZ &&
655	    (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr *)(const void *)uaddr) ||
656	     IN6_IS_ADDR_SITELOCAL((const struct in6_addr *)(const void *)uaddr))) {
657		h_errno = HOST_NOT_FOUND;
658		return NULL;
659	}
660	if (af == AF_INET6 && len == IN6ADDRSZ &&
661	    (IN6_IS_ADDR_V4MAPPED((const struct in6_addr *)(const void *)uaddr) ||
662	     IN6_IS_ADDR_V4COMPAT((const struct in6_addr *)(const void *)uaddr))) {
663		/* Unmap. */
664		addr += IN6ADDRSZ - INADDRSZ;
665		uaddr += IN6ADDRSZ - INADDRSZ;
666		af = AF_INET;
667		len = INADDRSZ;
668	}
669	switch (af) {
670	case AF_INET:
671		size = INADDRSZ;
672		break;
673	case AF_INET6:
674		size = IN6ADDRSZ;
675		break;
676	default:
677		errno = EAFNOSUPPORT;
678		h_errno = NETDB_INTERNAL;
679		return NULL;
680	}
681	if (size != len) {
682		errno = EINVAL;
683		h_errno = NETDB_INTERNAL;
684		return NULL;
685	}
686	hp = NULL;
687	h_errno = NETDB_INTERNAL;
688	if (nsdispatch(&hp, dtab, NSDB_HOSTS, "gethostbyaddr",
689	    default_dns_files, uaddr, len, af) != NS_SUCCESS)
690		return NULL;
691	h_errno = NETDB_SUCCESS;
692	return hp;
693}
694
695void
696_sethtent(int f)
697{
698    res_static  rs = __res_get_static();
699    if (rs == NULL) return;
700	if (!rs->hostf)
701		rs->hostf = fopen(_PATH_HOSTS, "r" );
702	else
703		rewind(rs->hostf);
704	rs->stayopen = f;
705}
706
707void
708_endhtent(void)
709{
710    res_static  rs = __res_get_static();
711    if (rs == NULL) return;
712
713	if (rs->hostf && !rs->stayopen) {
714		(void) fclose(rs->hostf);
715		rs->hostf = NULL;
716	}
717}
718
719struct hostent *
720_gethtent(void)
721{
722	char *p;
723	char *cp, **q;
724	int af, len;
725	res_static  rs = __res_get_static();
726
727	if (!rs->hostf && !(rs->hostf = fopen(_PATH_HOSTS, "r" ))) {
728		h_errno = NETDB_INTERNAL;
729		return NULL;
730	}
731 again:
732	if (!(p = fgets(rs->hostbuf, sizeof rs->hostbuf, rs->hostf))) {
733		h_errno = HOST_NOT_FOUND;
734		return NULL;
735	}
736	if (*p == '#')
737		goto again;
738	if (!(cp = strpbrk(p, "#\n")))
739		goto again;
740	*cp = '\0';
741	if (!(cp = strpbrk(p, " \t")))
742		goto again;
743	*cp++ = '\0';
744	if (inet_pton(AF_INET6, p, (char *)(void *)rs->host_addr) > 0) {
745		af = AF_INET6;
746		len = IN6ADDRSZ;
747	} else if (inet_pton(AF_INET, p, (char *)(void *)rs->host_addr) > 0) {
748		res_state res = __res_get_state();
749		if (res == NULL)
750			return NULL;
751		if (res->options & RES_USE_INET6) {
752			map_v4v6_address((char *)(void *)rs->host_addr,
753			    (char *)(void *)rs->host_addr);
754			af = AF_INET6;
755			len = IN6ADDRSZ;
756		} else {
757			af = AF_INET;
758			len = INADDRSZ;
759		}
760		__res_put_state(res);
761	} else {
762		goto again;
763	}
764	/* if this is not something we're looking for, skip it. */
765	if (rs->host.h_addrtype != 0 && rs->host.h_addrtype != af)
766		goto again;
767	if (rs->host.h_length != 0 && rs->host.h_length != len)
768		goto again;
769	rs->h_addr_ptrs[0] = (char *)(void *)rs->host_addr;
770	rs->h_addr_ptrs[1] = NULL;
771	rs->host.h_addr_list = rs->h_addr_ptrs;
772	rs->host.h_length = len;
773	rs->host.h_addrtype = af;
774	while (*cp == ' ' || *cp == '\t')
775		cp++;
776	rs->host.h_name = cp;
777	q = rs->host.h_aliases = rs->host_aliases;
778	if ((cp = strpbrk(cp, " \t")) != NULL)
779		*cp++ = '\0';
780	while (cp && *cp) {
781		if (*cp == ' ' || *cp == '\t') {
782			cp++;
783			continue;
784		}
785		if (q < &rs->host_aliases[MAXALIASES - 1])
786			*q++ = cp;
787		if ((cp = strpbrk(cp, " \t")) != NULL)
788			*cp++ = '\0';
789	}
790	*q = NULL;
791	h_errno = NETDB_SUCCESS;
792	return &rs->host;
793}
794
795/*ARGSUSED*/
796int
797_gethtbyname(void *rv, void *cb_data, va_list ap)
798{
799	struct hostent *hp;
800	const char *name;
801	int af;
802
803	assert(rv != NULL);
804
805	name = va_arg(ap, char *);
806	/* NOSTRICT skip len */(void)va_arg(ap, int);
807	af = va_arg(ap, int);
808
809	hp = NULL;
810#if 0
811	{
812		res_state res = __res_get_state();
813		if (res == NULL)
814			return NS_NOTFOUND;
815		if (res->options & RES_USE_INET6)
816			hp = _gethtbyname2(name, AF_INET6);
817		if (hp==NULL)
818			hp = _gethtbyname2(name, AF_INET);
819		__res_put_state(res);
820	}
821#else
822	hp = _gethtbyname2(name, af);
823#endif
824	*((struct hostent **)rv) = hp;
825	if (hp == NULL) {
826		h_errno = HOST_NOT_FOUND;
827		return NS_NOTFOUND;
828	}
829	return NS_SUCCESS;
830}
831
832struct hostent *
833_gethtbyname2(const char *name, int af)
834{
835	struct hostent *p;
836	char *tmpbuf, *ptr, **cp;
837	int num;
838	size_t len;
839	res_static rs = __res_get_static();
840
841	assert(name != NULL);
842
843	_sethtent(rs->stayopen);
844	ptr = tmpbuf = NULL;
845	num = 0;
846	while ((p = _gethtent()) != NULL && num < MAXADDRS) {
847		if (p->h_addrtype != af)
848			continue;
849		if (strcasecmp(p->h_name, name) != 0) {
850			for (cp = p->h_aliases; *cp != NULL; cp++)
851				if (strcasecmp(*cp, name) == 0)
852					break;
853			if (*cp == NULL) continue;
854		}
855
856		if (num == 0) {
857			size_t bufsize;
858			char *src;
859
860			bufsize = strlen(p->h_name) + 2 +
861				  MAXADDRS * p->h_length +
862				  ALIGNBYTES;
863			for (cp = p->h_aliases; *cp != NULL; cp++)
864				bufsize += strlen(*cp) + 1;
865
866			if ((tmpbuf = malloc(bufsize)) == NULL) {
867				h_errno = NETDB_INTERNAL;
868				return NULL;
869			}
870
871			ptr = tmpbuf;
872			src = p->h_name;
873			while ((*ptr++ = *src++) != '\0');
874			for (cp = p->h_aliases; *cp != NULL; cp++) {
875				src = *cp;
876				while ((*ptr++ = *src++) != '\0');
877			}
878			*ptr++ = '\0';
879
880			ptr = (char *)(void *)ALIGN(ptr);
881		}
882
883		(void)memcpy(ptr, p->h_addr_list[0], (size_t)p->h_length);
884		ptr += p->h_length;
885		num++;
886	}
887	_endhtent();
888	if (num == 0) return NULL;
889
890	len = ptr - tmpbuf;
891	if (len > (sizeof(rs->hostbuf) - ALIGNBYTES)) {
892		free(tmpbuf);
893		errno = ENOSPC;
894		h_errno = NETDB_INTERNAL;
895		return NULL;
896	}
897	ptr = memcpy((void *)ALIGN(rs->hostbuf), tmpbuf, len);
898	free(tmpbuf);
899
900	rs->host.h_name = ptr;
901	while (*ptr++);
902
903	cp = rs->host_aliases;
904	while (*ptr) {
905		*cp++ = ptr;
906		while (*ptr++);
907	}
908	ptr++;
909	*cp = NULL;
910
911	ptr = (char *)(void *)ALIGN(ptr);
912	cp = rs->h_addr_ptrs;
913	while (num--) {
914		*cp++ = ptr;
915		ptr += rs->host.h_length;
916	}
917	*cp = NULL;
918
919	return &rs->host;
920}
921
922/*ARGSUSED*/
923int
924_gethtbyaddr(void *rv, void *cb_data, va_list ap)
925{
926	struct hostent *p;
927	const unsigned char *addr;
928	int len, af;
929	res_static  rs = __res_get_static();
930
931	assert(rv != NULL);
932
933	addr = va_arg(ap, unsigned char *);
934	len = va_arg(ap, int);
935	af = va_arg(ap, int);
936
937	rs->host.h_length = len;
938	rs->host.h_addrtype = af;
939
940	_sethtent(rs->stayopen);
941	while ((p = _gethtent()) != NULL)
942		if (p->h_addrtype == af && !memcmp(p->h_addr, addr,
943		    (size_t)len))
944			break;
945	_endhtent();
946	*((struct hostent **)rv) = p;
947	if (p==NULL) {
948		h_errno = HOST_NOT_FOUND;
949		return NS_NOTFOUND;
950	}
951	return NS_SUCCESS;
952}
953
954static void
955map_v4v6_address(const char *src, char *dst)
956{
957	u_char *p = (u_char *)dst;
958	char tmp[INADDRSZ];
959	int i;
960
961	assert(src != NULL);
962	assert(dst != NULL);
963
964	/* Stash a temporary copy so our caller can update in place. */
965	(void)memcpy(tmp, src, INADDRSZ);
966	/* Mark this ipv6 addr as a mapped ipv4. */
967	for (i = 0; i < 10; i++)
968		*p++ = 0x00;
969	*p++ = 0xff;
970	*p++ = 0xff;
971	/* Retrieve the saved copy and we're done. */
972	(void)memcpy((void *)p, tmp, INADDRSZ);
973}
974
975static void
976map_v4v6_hostent(struct hostent *hp, char **bpp, char *ep)
977{
978	char **ap;
979
980	assert(hp != NULL);
981	assert(bpp != NULL);
982	assert(ep != NULL);
983
984	if (hp->h_addrtype != AF_INET || hp->h_length != INADDRSZ)
985		return;
986	hp->h_addrtype = AF_INET6;
987	hp->h_length = IN6ADDRSZ;
988	for (ap = hp->h_addr_list; *ap; ap++) {
989		int i = sizeof(align) - (size_t)((u_long)*bpp % sizeof(align));
990
991		if (ep - *bpp < (i + IN6ADDRSZ)) {
992			/* Out of memory.  Truncate address list here.  XXX */
993			*ap = NULL;
994			return;
995		}
996		*bpp += i;
997		map_v4v6_address(*ap, *bpp);
998		*ap = *bpp;
999		*bpp += IN6ADDRSZ;
1000	}
1001}
1002
1003static void
1004addrsort(char **ap, int num, res_state res)
1005{
1006	int i, j;
1007	char **p;
1008	short aval[MAXADDRS];
1009	int needsort = 0;
1010
1011	assert(ap != NULL);
1012
1013	p = ap;
1014	for (i = 0; i < num; i++, p++) {
1015	    for (j = 0 ; (unsigned)j < res->nsort; j++)
1016		if (res->sort_list[j].addr.s_addr ==
1017		    (((struct in_addr *)(void *)(*p))->s_addr &
1018		    res->sort_list[j].mask))
1019			break;
1020	    aval[i] = j;
1021	    if (needsort == 0 && i > 0 && j < aval[i-1])
1022		needsort = i;
1023	}
1024	if (!needsort)
1025	    return;
1026
1027	while (needsort < num) {
1028	    for (j = needsort - 1; j >= 0; j--) {
1029		if (aval[j] > aval[j+1]) {
1030		    char *hp;
1031
1032		    i = aval[j];
1033		    aval[j] = aval[j+1];
1034		    aval[j+1] = i;
1035
1036		    hp = ap[j];
1037		    ap[j] = ap[j+1];
1038		    ap[j+1] = hp;
1039		} else
1040		    break;
1041	    }
1042	    needsort++;
1043	}
1044}
1045
1046struct hostent *
1047gethostent(void)
1048{
1049    res_static  rs = __res_get_static();
1050	rs->host.h_addrtype = 0;
1051	rs->host.h_length = 0;
1052	return _gethtent();
1053}
1054
1055/*ARGSUSED*/
1056int
1057_dns_gethtbyname(void *rv, void *cb_data, va_list ap)
1058{
1059	querybuf *buf;
1060	int n, type;
1061	struct hostent *hp;
1062	const char *name;
1063	int af;
1064	res_state res;
1065
1066	assert(rv != NULL);
1067
1068	name = va_arg(ap, char *);
1069	/* NOSTRICT skip len */(void)va_arg(ap, int);
1070	af = va_arg(ap, int);
1071
1072	switch (af) {
1073	case AF_INET:
1074		type = T_A;
1075		break;
1076	case AF_INET6:
1077		type = T_AAAA;
1078		break;
1079	default:
1080		return NS_UNAVAIL;
1081	}
1082	buf = malloc(sizeof(*buf));
1083	if (buf == NULL) {
1084		h_errno = NETDB_INTERNAL;
1085		return NS_NOTFOUND;
1086	}
1087	res = __res_get_state();
1088	if (res == NULL) {
1089		free(buf);
1090		return NS_NOTFOUND;
1091	}
1092	n = res_nsearch(res, name, C_IN, type, buf->buf, sizeof(buf->buf));
1093	if (n < 0) {
1094		free(buf);
1095		dprintf("res_nsearch failed (%d)\n", res, n);
1096		__res_put_state(res);
1097		return NS_NOTFOUND;
1098	}
1099	hp = getanswer(buf, n, name, type, res);
1100	free(buf);
1101	__res_put_state(res);
1102	if (hp == NULL)
1103		switch (h_errno) {
1104		case HOST_NOT_FOUND:
1105			return NS_NOTFOUND;
1106		case TRY_AGAIN:
1107			return NS_TRYAGAIN;
1108		default:
1109			return NS_UNAVAIL;
1110		}
1111	*((struct hostent **)rv) = hp;
1112	return NS_SUCCESS;
1113}
1114
1115/*ARGSUSED*/
1116int
1117_dns_gethtbyaddr(void *rv, void	*cb_data, va_list ap)
1118{
1119	char qbuf[MAXDNAME + 1], *qp, *ep;
1120	int n;
1121	querybuf *buf;
1122	struct hostent *hp;
1123	const unsigned char *uaddr;
1124	int len, af, advance;
1125	res_state res;
1126	res_static rs = __res_get_static();
1127
1128	assert(rv != NULL);
1129
1130	uaddr = va_arg(ap, unsigned char *);
1131	len = va_arg(ap, int);
1132	af = va_arg(ap, int);
1133
1134	switch (af) {
1135	case AF_INET:
1136		(void)snprintf(qbuf, sizeof(qbuf), "%u.%u.%u.%u.in-addr.arpa",
1137		    (uaddr[3] & 0xff), (uaddr[2] & 0xff),
1138		    (uaddr[1] & 0xff), (uaddr[0] & 0xff));
1139		break;
1140
1141	case AF_INET6:
1142		qp = qbuf;
1143		ep = qbuf + sizeof(qbuf) - 1;
1144		for (n = IN6ADDRSZ - 1; n >= 0; n--) {
1145			advance = snprintf(qp, (size_t)(ep - qp), "%x.%x.",
1146			    uaddr[n] & 0xf,
1147			    ((unsigned int)uaddr[n] >> 4) & 0xf);
1148			if (advance > 0 && qp + advance < ep)
1149				qp += advance;
1150			else {
1151				h_errno = NETDB_INTERNAL;
1152				return NS_NOTFOUND;
1153			}
1154		}
1155		if (strlcat(qbuf, "ip6.arpa", sizeof(qbuf)) >= sizeof(qbuf)) {
1156			h_errno = NETDB_INTERNAL;
1157			return NS_NOTFOUND;
1158		}
1159		break;
1160	default:
1161		abort();
1162	}
1163
1164	buf = malloc(sizeof(*buf));
1165	if (buf == NULL) {
1166		h_errno = NETDB_INTERNAL;
1167		return NS_NOTFOUND;
1168	}
1169	res = __res_get_state();
1170	if (res == NULL) {
1171		free(buf);
1172		return NS_NOTFOUND;
1173	}
1174	n = res_nquery(res, qbuf, C_IN, T_PTR, buf->buf, sizeof(buf->buf));
1175	if (n < 0) {
1176		free(buf);
1177		dprintf("res_nquery failed (%d)\n", res, n);
1178		__res_put_state(res);
1179		return NS_NOTFOUND;
1180	}
1181	hp = getanswer(buf, n, qbuf, T_PTR, res);
1182	free(buf);
1183	if (hp == NULL) {
1184		__res_put_state(res);
1185		switch (h_errno) {
1186		case HOST_NOT_FOUND:
1187			return NS_NOTFOUND;
1188		case TRY_AGAIN:
1189			return NS_TRYAGAIN;
1190		default:
1191			return NS_UNAVAIL;
1192		}
1193	}
1194	hp->h_addrtype = af;
1195	hp->h_length = len;
1196	(void)memcpy(rs->host_addr, uaddr, (size_t)len);
1197	rs->h_addr_ptrs[0] = (char *)(void *)rs->host_addr;
1198	rs->h_addr_ptrs[1] = NULL;
1199	if (af == AF_INET && (res->options & RES_USE_INET6)) {
1200		map_v4v6_address((char *)(void *)rs->host_addr,
1201		    (char *)(void *)rs->host_addr);
1202		hp->h_addrtype = AF_INET6;
1203		hp->h_length = IN6ADDRSZ;
1204	}
1205
1206	__res_put_state(res);
1207	*((struct hostent **)rv) = hp;
1208	h_errno = NETDB_SUCCESS;
1209	return NS_SUCCESS;
1210}
1211