1 /*	$OpenBSD: gethostnamadr.c,v 1.68 2005/08/06 20:30:03 espie Exp $ */
2 /*-
3  * Copyright (c) 1985, 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  * -
30  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
31  *
32  * Permission to use, copy, modify, and distribute this software for any
33  * purpose with or without fee is hereby granted, provided that the above
34  * copyright notice and this permission notice appear in all copies, and that
35  * the name of Digital Equipment Corporation not be used in advertising or
36  * publicity pertaining to distribution of the document or software without
37  * specific, written prior permission.
38  *
39  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
40  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
41  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
42  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
43  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
44  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
45  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
46  * SOFTWARE.
47  * -
48  * --Copyright--
49  */
50 
51 #include <sys/param.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 #include <arpa/nameser.h>
56 #include <netdb.h>
57 #include <resolv.h>
58 #include <stdio.h>
59 #include <ctype.h>
60 #include <errno.h>
61 #include <string.h>
62 #include <syslog.h>
63 #include <stdlib.h>
64 #include "thread_private.h"
65 
66 __RCSID("$MirOS: src/lib/libc/net/gethostnamadr.c,v 1.8 2009/11/09 21:30:49 tg Exp $");
67 
68 #define MULTI_PTRS_ARE_ALIASES 1	/* XXX - experimental */
69 
70 #define	MAXALIASES	35
71 #define	MAXADDRS	35
72 
73 static char *h_addr_ptrs[MAXADDRS + 1];
74 
75 static struct hostent host;
76 static char *host_aliases[MAXALIASES];
77 static char hostbuf[BUFSIZ+1];
78 static union {
79 	struct in_addr _host_in_addr;
80 	u_char _host_addr[16];		/* IPv4 or IPv6 */
81 } _host_addr_u;
82 #define host_addr _host_addr_u._host_addr
83 static FILE *hostf = NULL;
84 static int stayopen = 0;
85 
86 static void map_v4v6_address(const char *src, char *dst);
87 static void map_v4v6_hostent(struct hostent *hp, char **bp, char *);
88 
89 #ifdef RESOLVSORT
90 static void addrsort(char **, int);
91 #endif
92 
93 int _hokchar(const char *);
94 
95 static const char AskedForGot[] =
96 			  "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
97 
98 #define	MAXPACKET	(64*1024)
99 
100 typedef union {
101 	HEADER hdr;
102 	u_char buf[MAXPACKET];
103 } querybuf;
104 
105 typedef union {
106 	int32_t al;
107 	char ac;
108 } align;
109 
110 static struct hostent *getanswer(const querybuf *, int, const char *, int);
111 
112 int
_hokchar(const char * p)113 _hokchar(const char *p)
114 {
115 	char c;
116 
117 	/*
118 	 * Many people do not obey RFC 822 and 1035.  The valid
119 	 * characters are a-z, A-Z, 0-9, '-' and . But the others
120 	 * tested for below can happen, and we must be more permissive
121 	 * than the resolver until those idiots clean up their act.
122 	 * We let '/' through, but not '..'
123 	 */
124 	while ((c = *p++)) {
125 		if (('a' <= c && c <= 'z') ||
126 		    ('A' <= c && c <= 'Z') ||
127 		    ('0' <= c && c <= '9'))
128 			continue;
129 		if (strchr("-_/", c))
130 			continue;
131 		if (c == '.' && *p != '.')
132 			continue;
133 		return 0;
134 	}
135 	return 1;
136 }
137 
138 static struct hostent *
getanswer(const querybuf * answer,int anslen,const char * qname,int qtype)139 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype)
140 {
141 	struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
142 	const HEADER *hp;
143 	const u_char *cp, *eom;
144 	char tbuf[MAXDNAME];
145 	char *bp, **ap, **hap, *ep;
146 	int type, class, ancount, qdcount, n;
147 	int haveanswer, had_error, toobig = 0;
148 	const char *tname;
149 	int (*name_ok)(const char *);
150 
151 	tname = qname;
152 	host.h_name = NULL;
153 	eom = answer->buf + anslen;
154 	switch (qtype) {
155 	case T_A:
156 	case T_AAAA:
157 #ifdef USE_RESOLV_NAME_OK
158 		name_ok = res_hnok;
159 		break;
160 #endif
161 	case T_PTR:
162 #ifdef USE_RESOLV_NAME_OK
163 		name_ok = res_dnok;
164 #else
165 		name_ok = _hokchar;
166 #endif
167 		break;
168 	default:
169 		return (NULL);
170 	}
171 	/*
172 	 * find first satisfactory answer
173 	 */
174 	hp = &answer->hdr;
175 	ancount = ntohs(hp->ancount);
176 	qdcount = ntohs(hp->qdcount);
177 	bp = hostbuf;
178 	ep = hostbuf + sizeof hostbuf;
179 	cp = answer->buf + HFIXEDSZ;
180 	if (qdcount != 1) {
181 		h_errno = NO_RECOVERY;
182 		return (NULL);
183 	}
184 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
185 	if ((n < 0) || !(*name_ok)(bp)) {
186 		h_errno = NO_RECOVERY;
187 		return (NULL);
188 	}
189 	cp += n + QFIXEDSZ;
190 	if (qtype == T_A || qtype == T_AAAA) {
191 		/* res_send() has already verified that the query name is the
192 		 * same as the one we sent; this just gets the expanded name
193 		 * (i.e., with the succeeding search-domain tacked on).
194 		 */
195 		n = strlen(bp) + 1;		/* for the \0 */
196 		host.h_name = bp;
197 		bp += n;
198 		/* The qname can be abbreviated, but h_name is now absolute. */
199 		qname = host.h_name;
200 	}
201 	ap = host_aliases;
202 	*ap = NULL;
203 	host.h_aliases = host_aliases;
204 	hap = h_addr_ptrs;
205 	*hap = NULL;
206 	host.h_addr_list = h_addr_ptrs;
207 	haveanswer = 0;
208 	had_error = 0;
209 	while (ancount-- > 0 && cp < eom && !had_error) {
210 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
211 		if ((n < 0) || !(*name_ok)(bp)) {
212 			had_error++;
213 			continue;
214 		}
215 		cp += n;			/* name */
216 		if (cp >= eom)
217 			break;
218 		type = _getshort(cp);
219 		cp += INT16SZ;			/* type */
220 		if (cp >= eom)
221 			break;
222 		class = _getshort(cp);
223  		cp += INT16SZ + INT32SZ;	/* class, TTL */
224 		if (cp >= eom)
225 			break;
226 		n = _getshort(cp);
227 		cp += INT16SZ;			/* len */
228 		if (cp >= eom)
229 			break;
230 		if (type == T_SIG) {
231 			/* XXX - ignore signatures as we don't use them yet */
232 			cp += n;
233 			continue;
234 		}
235 		if (class != C_IN) {
236 			/* XXX - debug? syslog? */
237 			cp += n;
238 			continue;		/* XXX - had_error++ ? */
239 		}
240 		if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
241 			if (ap >= &host_aliases[MAXALIASES-1])
242 				continue;
243 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
244 			if ((n < 0) || !(*name_ok)(tbuf)) {
245 				had_error++;
246 				continue;
247 			}
248 			cp += n;
249 			/* Store alias. */
250 			*ap++ = bp;
251 			n = strlen(bp) + 1;	/* for the \0 */
252 			bp += n;
253 			/* Get canonical name. */
254 			n = strlen(tbuf) + 1;	/* for the \0 */
255 			if (n > ep - bp) {
256 				had_error++;
257 				continue;
258 			}
259 			strlcpy(bp, tbuf, ep - bp);
260 			host.h_name = bp;
261 			bp += n;
262 			continue;
263 		}
264 		if (qtype == T_PTR && type == T_CNAME) {
265 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
266 #ifdef USE_RESOLV_NAME_OK
267 			if ((n < 0) || !res_hnok(tbuf)) {
268 #else
269 			if ((n < 0) || !_hokchar(tbuf)) {
270 #endif
271 				had_error++;
272 				continue;
273 			}
274 			cp += n;
275 			/* Get canonical name. */
276 			n = strlen(tbuf) + 1;	/* for the \0 */
277 			if (n > ep - bp) {
278 				had_error++;
279 				continue;
280 			}
281 			strlcpy(bp, tbuf, ep - bp);
282 			tname = bp;
283 			bp += n;
284 			continue;
285 		}
286 		if (type != qtype) {
287 			syslog(LOG_NOTICE|LOG_AUTH,
288 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
289 			       qname, p_class(C_IN), p_type(qtype),
290 			       p_type(type));
291 			cp += n;
292 			continue;		/* XXX - had_error++ ? */
293 		}
294 		switch (type) {
295 		case T_PTR:
296 			if (strcasecmp(tname, bp) != 0) {
297 				syslog(LOG_NOTICE|LOG_AUTH,
298 				       AskedForGot, qname, bp);
299 				cp += n;
300 				continue;	/* XXX - had_error++ ? */
301 			}
302 			n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
303 #ifdef USE_RESOLV_NAME_OK
304 			if ((n < 0) || !res_hnok(bp)) {
305 #else
306 			if ((n < 0) || !_hokchar(bp)) {
307 #endif
308 				had_error++;
309 				break;
310 			}
311 #if MULTI_PTRS_ARE_ALIASES
312 			cp += n;
313 			if (!haveanswer)
314 				host.h_name = bp;
315 			else if (ap < &host_aliases[MAXALIASES-1])
316 				*ap++ = bp;
317 			else
318 				n = -1;
319 			if (n != -1) {
320 				n = strlen(bp) + 1;	/* for the \0 */
321 				bp += n;
322 			}
323 			break;
324 #else
325 			host.h_name = bp;
326 			if (_resp->options & RES_USE_INET6) {
327 				n = strlen(bp) + 1;	/* for the \0 */
328 				bp += n;
329 				map_v4v6_hostent(&host, &bp, ep);
330 			}
331 			h_errno = NETDB_SUCCESS;
332 			return (&host);
333 #endif
334 		case T_A:
335 		case T_AAAA:
336 			if (strcasecmp(host.h_name, bp) != 0) {
337 				syslog(LOG_NOTICE|LOG_AUTH,
338 				       AskedForGot, host.h_name, bp);
339 				cp += n;
340 				continue;	/* XXX - had_error++ ? */
341 			}
342 			if (n != host.h_length) {
343 				cp += n;
344 				continue;
345 			}
346 			if (type == T_AAAA) {
347 				struct in6_addr in6;
348 				memcpy(&in6, cp, IN6ADDRSZ);
349 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
350 					cp += n;
351 					continue;
352 				}
353 			}
354 			if (!haveanswer) {
355 				int nn;
356 
357 				host.h_name = bp;
358 				nn = strlen(bp) + 1;	/* for the \0 */
359 				bp += nn;
360 			}
361 
362 			bp += sizeof(align) - ((u_long)bp % sizeof(align));
363 
364 			if (bp + n >= &hostbuf[sizeof hostbuf]) {
365 #ifdef DEBUG
366 				if (_resp->options & RES_DEBUG)
367 					printf("size (%d) too big\n", n);
368 #endif
369 				had_error++;
370 				continue;
371 			}
372 			if (hap >= &h_addr_ptrs[MAXADDRS-1]) {
373 				if (!toobig++)
374 #ifdef DEBUG
375 					if (_resp->options & RES_DEBUG)
376 						printf("Too many addresses (%d)\n", MAXADDRS);
377 #endif
378 				cp += n;
379 				continue;
380 			}
381 			memmove(*hap++ = bp, cp, n);
382 			bp += n;
383 			cp += n;
384 			break;
385 		}
386 		if (!had_error)
387 			haveanswer++;
388 	}
389 	if (haveanswer) {
390 		*ap = NULL;
391 		*hap = NULL;
392 # if defined(RESOLVSORT)
393 		/*
394 		 * Note: we sort even if host can take only one address
395 		 * in its return structures - should give it the "best"
396 		 * address in that case, not some random one
397 		 */
398 		if (_resp->nsort && haveanswer > 1 && qtype == T_A)
399 			addrsort(h_addr_ptrs, haveanswer);
400 # endif /*RESOLVSORT*/
401 		if (!host.h_name) {
402 			n = strlen(qname) + 1;	/* for the \0 */
403 			if (n > ep - bp)
404 				goto try_again;
405 			strlcpy(bp, qname, ep - bp);
406 			host.h_name = bp;
407 			bp += n;
408 		}
409 		if (_resp->options & RES_USE_INET6)
410 			map_v4v6_hostent(&host, &bp, ep);
411 		h_errno = NETDB_SUCCESS;
412 		return (&host);
413 	}
414  try_again:
415 	h_errno = TRY_AGAIN;
416 	return (NULL);
417 }
418 
419 #ifdef notyet
420 /*
421  * XXX This is an extremely bogus implementation.
422  *
423  * FreeBSD has this interface:
424  *    int gethostbyaddr_r(const char *addr, int len, int type,
425  *             struct hostent *result, struct hostent_data *buffer)
426  */
427 
428 struct hostent *
429 gethostbyname_r(const char *name, struct hostent *hp, char *buf, int buflen,
430     int *errorp)
431 {
432 	struct hostent *res;
433 
434 	res = gethostbyname(name);
435 	*errorp = h_errno;
436 	if (res == NULL)
437 		return NULL;
438 	memcpy(hp, res, sizeof *hp); /* XXX not sufficient */
439 	return hp;
440 }
441 
442 /*
443  * XXX This is an extremely bogus implementation.
444  */
445 struct hostent *
446 gethostbyaddr_r(const char *addr, int len, int af, struct hostent *he,
447     char *buf, int buflen, int *errorp)
448 {
449 	struct hostent * res;
450 
451 	res = gethostbyaddr(addr, len, af);
452 	*errorp = h_errno;
453 	if (res == NULL)
454 		return NULL;
455 	memcpy(he, res, sizeof *he); /* XXX not sufficient */
456 	return he;
457 }
458 
459 /* XXX RFC2133 expects a gethostbyname2_r() -- unimplemented */
460 #endif
461 
462 struct hostent *
463 gethostbyname(const char *name)
464 {
465 	struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
466 	struct hostent *hp;
467 	extern struct hostent *_gethtbyname2(const char *, int);
468 
469 	if (_res_init(0) == -1)
470 		hp = _gethtbyname2(name, AF_INET);
471 
472 	else if (_resp->options & RES_USE_INET6) {
473 		hp = gethostbyname2(name, AF_INET6);
474 		if (hp == NULL)
475 			hp = gethostbyname2(name, AF_INET);
476 	}
477 	else
478 		hp = gethostbyname2(name, AF_INET);
479 	return hp;
480 }
481 
482 struct hostent *
483 gethostbyname2(const char *name, int af)
484 {
485 	struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
486 	querybuf *buf;
487 	const char *cp;
488 	char *bp, *ep;
489 	int n, size, type, i;
490 	struct hostent *hp;
491 	char lookups[MAXDNSLUS];
492 	extern struct hostent *_gethtbyname2(const char *, int);
493 	extern struct hostent *_yp_gethtbyname(const char *);
494 
495 	if (_res_init(0) == -1)
496 		return (_gethtbyname2(name, af));
497 
498 	switch (af) {
499 	case AF_INET:
500 		size = INADDRSZ;
501 		type = T_A;
502 		break;
503 	case AF_INET6:
504 		size = IN6ADDRSZ;
505 		type = T_AAAA;
506 		break;
507 	default:
508 		h_errno = NETDB_INTERNAL;
509 		errno = EAFNOSUPPORT;
510 		return (NULL);
511 	}
512 
513 	host.h_addrtype = af;
514 	host.h_length = size;
515 
516 	/*
517 	 * if there aren't any dots, it could be a user-level alias.
518 	 * this is also done in res_query() since we are not the only
519 	 * function that looks up host names.
520 	 */
521 	if (!strchr(name, '.') && (cp = __hostalias(name)))
522 		name = cp;
523 
524 	/*
525 	 * disallow names consisting only of digits/dots, unless
526 	 * they end in a dot.
527 	 */
528 	if (isdigit(name[0]))
529 		for (cp = name;; ++cp) {
530 			if (!*cp) {
531 				if (*--cp == '.')
532 					break;
533 				/*
534 				 * All-numeric, no dot at the end.
535 				 * Fake up a hostent as if we'd actually
536 				 * done a lookup.
537 				 */
538 				if (inet_pton(af, name, host_addr) <= 0) {
539 					h_errno = HOST_NOT_FOUND;
540 					return (NULL);
541 				}
542 				strlcpy(hostbuf, name, MAXHOSTNAMELEN);
543 				bp = hostbuf + MAXHOSTNAMELEN;
544 				ep = hostbuf + sizeof(hostbuf);
545 				host.h_name = hostbuf;
546 				host.h_aliases = host_aliases;
547 				host_aliases[0] = NULL;
548 				h_addr_ptrs[0] = (char *)host_addr;
549 				h_addr_ptrs[1] = NULL;
550 				host.h_addr_list = h_addr_ptrs;
551 				if (_resp->options & RES_USE_INET6)
552 					map_v4v6_hostent(&host, &bp, ep);
553 				h_errno = NETDB_SUCCESS;
554 				return (&host);
555 			}
556 			if (!isdigit(*cp) && *cp != '.')
557 				break;
558 		}
559 	if ((isxdigit(name[0]) && strchr(name, ':') != NULL) ||
560 	    name[0] == ':')
561 		for (cp = name;; ++cp) {
562 			if (!*cp) {
563 				if (*--cp == '.')
564 					break;
565 				/*
566 				 * All-IPv6-legal, no dot at the end.
567 				 * Fake up a hostent as if we'd actually
568 				 * done a lookup.
569 				 */
570 				if (inet_pton(af, name, host_addr) <= 0) {
571 					h_errno = HOST_NOT_FOUND;
572 					return (NULL);
573 				}
574 				strlcpy(hostbuf, name, MAXHOSTNAMELEN);
575 				bp = hostbuf + MAXHOSTNAMELEN;
576 				ep = hostbuf + sizeof(hostbuf);
577 				host.h_name = hostbuf;
578 				host.h_aliases = host_aliases;
579 				host_aliases[0] = NULL;
580 				h_addr_ptrs[0] = (char *)host_addr;
581 				h_addr_ptrs[1] = NULL;
582 				host.h_addr_list = h_addr_ptrs;
583 				h_errno = NETDB_SUCCESS;
584 				return (&host);
585 			}
586 			if (!isxdigit(*cp) && *cp != ':' && *cp != '.')
587 				break;
588 		}
589 
590 	memmove(lookups, _resp->lookups, sizeof lookups);
591 	if (lookups[0] == '\0')
592 		strlcpy(lookups, "bf", sizeof lookups);
593 
594 	hp = (struct hostent *)NULL;
595 	for (i = 0; i < MAXDNSLUS && hp == NULL && lookups[i]; i++) {
596 		switch (lookups[i]) {
597 		case 'b':
598 			buf = malloc(sizeof(*buf));
599 			if (buf == NULL)
600 				break;
601 			if ((n = res_search(name, C_IN, type, buf->buf,
602 			    sizeof(buf->buf))) < 0) {
603 				free(buf);
604 #ifdef DEBUG
605 				if (_resp->options & RES_DEBUG)
606 					printf("res_search failed\n");
607 #endif
608 				break;
609 			}
610 			hp = getanswer(buf, n, name, type);
611 			free(buf);
612 			break;
613 		case 'f':
614 			hp = _gethtbyname2(name, af);
615 			break;
616 		}
617 	}
618 	/* XXX h_errno not correct in all cases... */
619 	return (hp);
620 }
621 
622 struct hostent *
623 gethostbyaddr(const void *addr, socklen_t len, int af)
624 {
625 	struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
626 	const u_char *uaddr = (const u_char *)addr;
627 	int n, size, i;
628 	querybuf *buf;
629 	struct hostent *hp;
630 	char qbuf[MAXDNAME+1], *qp, *ep;
631 	char lookups[MAXDNSLUS];
632 	struct hostent *res;
633 	extern struct hostent *_gethtbyaddr(const void *, socklen_t, int);
634 
635 	if (_res_init(0) == -1) {
636 		res = _gethtbyaddr(addr, len, af);
637 		return (res);
638 	}
639 
640 	if (af == AF_INET6 && len == IN6ADDRSZ &&
641 	    (IN6_IS_ADDR_LINKLOCAL((struct in6_addr *)uaddr) ||
642 	     IN6_IS_ADDR_SITELOCAL((struct in6_addr *)uaddr))) {
643 		h_errno = HOST_NOT_FOUND;
644 		return (NULL);
645 	}
646 	if (af == AF_INET6 && len == IN6ADDRSZ &&
647 	    (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)uaddr) ||
648 	     IN6_IS_ADDR_V4COMPAT((struct in6_addr *)uaddr))) {
649 		/* Unmap. */
650 		uaddr += IN6ADDRSZ - INADDRSZ;
651 		af = AF_INET;
652 		len = INADDRSZ;
653 	}
654 	switch (af) {
655 	case AF_INET:
656 		size = INADDRSZ;
657 		break;
658 	case AF_INET6:
659 		size = IN6ADDRSZ;
660 		break;
661 	default:
662 		errno = EAFNOSUPPORT;
663 		h_errno = NETDB_INTERNAL;
664 		return (NULL);
665 	}
666 	if (size != len) {
667 		errno = EINVAL;
668 		h_errno = NETDB_INTERNAL;
669 		return (NULL);
670 	}
671 	ep = qbuf + sizeof(qbuf);
672 	switch (af) {
673 	case AF_INET:
674 		(void) snprintf(qbuf, sizeof qbuf, "%u.%u.%u.%u.in-addr.arpa",
675 		    (uaddr[3] & 0xff), (uaddr[2] & 0xff),
676 		    (uaddr[1] & 0xff), (uaddr[0] & 0xff));
677 		break;
678 	case AF_INET6:
679 		qp = qbuf;
680 		for (n = IN6ADDRSZ - 1; n >= 0; n--) {
681 			i = snprintf(qp, ep - qp, "%x.%x.",
682 			    uaddr[n] & 0xf, (uaddr[n] >> 4) & 0xf);
683 			if (i <= 0 || i >= ep - qp) {
684 				errno = EINVAL;
685 				h_errno = NETDB_INTERNAL;
686 				return (NULL);
687 			}
688 			qp += i;
689 		}
690 		strlcpy(qp, "ip6.arpa", ep - qp);
691 		break;
692 	}
693 
694 	memmove(lookups, _resp->lookups, sizeof lookups);
695 	if (lookups[0] == '\0')
696 		strlcpy(lookups, "bf", sizeof lookups);
697 
698 	hp = (struct hostent *)NULL;
699 	for (i = 0; i < MAXDNSLUS && hp == NULL && lookups[i]; i++) {
700 		switch (lookups[i]) {
701 		case 'b':
702 			buf = malloc(sizeof(*buf));
703 			if (!buf)
704 				break;
705 			n = res_query(qbuf, C_IN, T_PTR, buf->buf,
706 			    sizeof(buf->buf));
707 			if (n < 0) {
708 				free(buf);
709 #ifdef DEBUG
710 				if (_resp->options & RES_DEBUG)
711 					printf("res_query failed\n");
712 #endif
713 				break;
714 			}
715 			if (!(hp = getanswer(buf, n, qbuf, T_PTR))) {
716 				free(buf);
717 				break;
718 			}
719 			free(buf);
720 			hp->h_addrtype = af;
721 			hp->h_length = len;
722 			memmove(host_addr, uaddr, len);
723 			h_addr_ptrs[0] = (char *)host_addr;
724 			h_addr_ptrs[1] = NULL;
725 			if (af == AF_INET && (_resp->options & RES_USE_INET6)) {
726 				map_v4v6_address((char*)host_addr,
727 				    (char*)host_addr);
728 				hp->h_addrtype = AF_INET6;
729 				hp->h_length = IN6ADDRSZ;
730 			}
731 			h_errno = NETDB_SUCCESS;
732 			break;
733 		case 'f':
734 			hp = _gethtbyaddr(uaddr, len, af);
735 			break;
736 		}
737 	}
738 	/* XXX h_errno not correct in all cases... */
739 	return (hp);
740 }
741 
742 void
743 _sethtent(int f)
744 {
745 	if (hostf == NULL)
746 		hostf = fopen(_PATH_HOSTS, "r" );
747 	else
748 		rewind(hostf);
749 	stayopen = f;
750 }
751 
752 void
753 _endhtent(void)
754 {
755 	if (hostf && !stayopen) {
756 		(void) fclose(hostf);
757 		hostf = NULL;
758 	}
759 }
760 
761 static struct hostent *
762 _gethtent(void)
763 {
764 	struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
765 	char *p, *cp, **q;
766 	int af;
767 	size_t len;
768 
769 	if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" ))) {
770 		h_errno = NETDB_INTERNAL;
771 		return (NULL);
772 	}
773  again:
774 	if ((p = fgetln(hostf, &len)) == NULL) {
775 		h_errno = HOST_NOT_FOUND;
776 		return (NULL);
777 	}
778 	if (p[len-1] == '\n')
779 		len--;
780 	if (len >= sizeof(hostbuf) || len == 0)
781 		goto again;
782 	p = memcpy(hostbuf, p, len);
783 	hostbuf[len] = '\0';
784 	if (*p == '#')
785 		goto again;
786 	if ((cp = strchr(p, '#')))
787 		*cp = '\0';
788 	if (!(cp = strpbrk(p, " \t")))
789 		goto again;
790 	*cp++ = '\0';
791 	if (inet_pton(AF_INET6, p, host_addr) > 0) {
792 		af = AF_INET6;
793 		len = IN6ADDRSZ;
794 	} else if (inet_pton(AF_INET, p, host_addr) > 0) {
795 		if (_resp->options & RES_USE_INET6) {
796 			map_v4v6_address((char*)host_addr, (char*)host_addr);
797 			af = AF_INET6;
798 			len = IN6ADDRSZ;
799 		} else {
800 			af = AF_INET;
801 			len = INADDRSZ;
802 		}
803 	} else {
804 		goto again;
805 	}
806 	/* if this is not something we're looking for, skip it. */
807 	if (host.h_addrtype != AF_UNSPEC && host.h_addrtype != af)
808 		goto again;
809 	if (host.h_length != 0 && host.h_length != len)
810 		goto again;
811 	h_addr_ptrs[0] = (char *)host_addr;
812 	h_addr_ptrs[1] = NULL;
813 	host.h_addr_list = h_addr_ptrs;
814 	host.h_length = len;
815 	host.h_addrtype = af;
816 	while (*cp == ' ' || *cp == '\t')
817 		cp++;
818 	host.h_name = cp;
819 	q = host.h_aliases = host_aliases;
820 	if ((cp = strpbrk(cp, " \t")))
821 		*cp++ = '\0';
822 	while (cp && *cp) {
823 		if (*cp == ' ' || *cp == '\t') {
824 			cp++;
825 			continue;
826 		}
827 		if (q < &host_aliases[MAXALIASES - 1])
828 			*q++ = cp;
829 		if ((cp = strpbrk(cp, " \t")))
830 			*cp++ = '\0';
831 	}
832 	*q = NULL;
833 	if (_resp->options & RES_USE_INET6) {
834 		char *bp = hostbuf;
835 		char *ep = hostbuf + sizeof hostbuf;
836 
837 		map_v4v6_hostent(&host, &bp, ep);
838 	}
839 	h_errno = NETDB_SUCCESS;
840 	return (&host);
841 }
842 
843 struct hostent *
844 _gethtbyname2(const char *name, int af)
845 {
846 	struct hostent *p;
847 	char **cp;
848 
849 	_sethtent(0);
850 	while ((p = _gethtent())) {
851 		if (p->h_addrtype != af)
852 			continue;
853 		if (strcasecmp(p->h_name, name) == 0)
854 			break;
855 		for (cp = p->h_aliases; *cp != 0; cp++)
856 			if (strcasecmp(*cp, name) == 0)
857 				goto found;
858 	}
859  found:
860 	_endhtent();
861 	return (p);
862 }
863 
864 struct hostent *
865 _gethtbyaddr(const void *addr, socklen_t len, int af)
866 {
867 	struct hostent *p;
868 
869 	host.h_length = len;
870 	host.h_addrtype = af;
871 
872 	_sethtent(0);
873 	while ((p = _gethtent()))
874 		if (p->h_addrtype == af && p->h_length == len &&
875 		    !memcmp(p->h_addr, addr, len))
876 			break;
877 	_endhtent();
878 	return (p);
879 }
880 
881 static void
882 map_v4v6_address(const char *src, char *dst)
883 {
884 	u_char *p = (u_char *)dst;
885 	char tmp[INADDRSZ];
886 	int i;
887 
888 	/* Stash a temporary copy so our caller can update in place. */
889 	memmove(tmp, src, INADDRSZ);
890 	/* Mark this ipv6 addr as a mapped ipv4. */
891 	for (i = 0; i < 10; i++)
892 		*p++ = 0x00;
893 	*p++ = 0xff;
894 	*p++ = 0xff;
895 	/* Retrieve the saved copy and we're done. */
896 	memmove((void*)p, tmp, INADDRSZ);
897 }
898 
899 static void
900 map_v4v6_hostent(struct hostent *hp, char **bpp, char *ep)
901 {
902 	char **ap;
903 
904 	if (hp->h_addrtype != AF_INET || hp->h_length != INADDRSZ)
905 		return;
906 	hp->h_addrtype = AF_INET6;
907 	hp->h_length = IN6ADDRSZ;
908 	for (ap = hp->h_addr_list; *ap; ap++) {
909 		int i = sizeof(align) - ((u_long)*bpp % sizeof(align));
910 
911 		if (ep - *bpp < (i + IN6ADDRSZ)) {
912 			/* Out of memory.  Truncate address list here.  XXX */
913 			*ap = NULL;
914 			return;
915 		}
916 		*bpp += i;
917 		map_v4v6_address(*ap, *bpp);
918 		*ap = *bpp;
919 		*bpp += IN6ADDRSZ;
920 	}
921 }
922 
923 struct hostent *
924 gethostent(void)
925 {
926 	host.h_addrtype = AF_UNSPEC;
927 	host.h_length = 0;
928 	return (_gethtent());
929 }
930 
931 #ifdef RESOLVSORT
932 static void
933 addrsort(char **ap, int num)
934 {
935 	struct __res_state *_resp = _THREAD_PRIVATE(_res, _res, &_res);
936 	int i, j;
937 	char **p;
938 	short aval[MAXADDRS];
939 	int needsort = 0;
940 
941 	p = ap;
942 	for (i = 0; i < num; i++, p++) {
943 		for (j = 0 ; (unsigned)j < _resp->nsort; j++)
944 			if (_resp->sort_list[j].addr.s_addr ==
945 			    (((struct in_addr *)(*p))->s_addr &
946 			    _resp->sort_list[j].mask))
947 				break;
948 		aval[i] = j;
949 		if (needsort == 0 && i > 0 && j < aval[i-1])
950 			needsort = i;
951 	}
952 	if (!needsort)
953 		return;
954 
955 	while (needsort < num) {
956 		for (j = needsort - 1; j >= 0; j--) {
957 			if (aval[j] > aval[j+1]) {
958 				char *hp;
959 
960 				i = aval[j];
961 				aval[j] = aval[j+1];
962 				aval[j+1] = i;
963 
964 				hp = ap[j];
965 				ap[j] = ap[j+1];
966 				ap[j+1] = hp;
967 			} else
968 				break;
969 		}
970 		needsort++;
971 	}
972 }
973 #endif
974