xref: /freebsd/lib/libc/net/gethostbydns.c (revision ebccf1e3a6b11b97cbf5f813dd76636e892a9035)
1 /*
2  * ++Copyright++ 1985, 1988, 1993
3  * -
4  * Copyright (c) 1985, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  * -
35  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
36  *
37  * Permission to use, copy, modify, and distribute this software for any
38  * purpose with or without fee is hereby granted, provided that the above
39  * copyright notice and this permission notice appear in all copies, and that
40  * the name of Digital Equipment Corporation not be used in advertising or
41  * publicity pertaining to distribution of the document or software without
42  * specific, written prior permission.
43  *
44  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
45  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
46  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
47  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
48  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
49  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
50  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
51  * SOFTWARE.
52  * -
53  * --Copyright--
54  */
55 
56 #if defined(LIBC_SCCS) && !defined(lint)
57 static char sccsid[] = "@(#)gethostnamadr.c	8.1 (Berkeley) 6/4/93";
58 static char fromrcsid[] = "From: Id: gethnamaddr.c,v 8.23 1998/04/07 04:59:46 vixie Exp $";
59 #endif /* LIBC_SCCS and not lint */
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
62 
63 #include <sys/types.h>
64 #include <sys/param.h>
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 #include <arpa/nameser.h>
69 
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <unistd.h>
73 #include <string.h>
74 #include <netdb.h>
75 #include <resolv.h>
76 #include <ctype.h>
77 #include <errno.h>
78 #include <syslog.h>
79 #include <stdarg.h>
80 #include <nsswitch.h>
81 
82 #include "res_config.h"
83 
84 #define SPRINTF(x) ((size_t)sprintf x)
85 
86 #define	MAXALIASES	35
87 #define	MAXADDRS	35
88 
89 static const char AskedForGot[] =
90 		"gethostby*.gethostanswer: asked for \"%s\", got \"%s\"";
91 
92 static char *h_addr_ptrs[MAXADDRS + 1];
93 
94 static struct hostent host;
95 static char *host_aliases[MAXALIASES];
96 static char hostbuf[8*1024];
97 static u_char host_addr[16];	/* IPv4 or IPv6 */
98 
99 extern const char *_res_hostalias(const char *, char *, size_t);
100 
101 #ifdef RESOLVSORT
102 static void addrsort(char **, int);
103 #endif
104 
105 #ifdef DEBUG
106 static void dprintf(char *, int) __printflike(1, 0);
107 #endif
108 
109 #define MAXPACKET	(64*1024)
110 
111 typedef union {
112     HEADER hdr;
113     u_char buf[MAXPACKET];
114 } querybuf;
115 
116 typedef union {
117     int32_t al;
118     char ac;
119 } align;
120 
121 int _dns_ttl_;
122 
123 #ifdef DEBUG
124 static void
125 dprintf(msg, num)
126 	char *msg;
127 	int num;
128 {
129 	if (_res.options & RES_DEBUG) {
130 		int save = errno;
131 
132 		printf(msg, num);
133 		errno = save;
134 	}
135 }
136 #else
137 # define dprintf(msg, num) /*nada*/
138 #endif
139 
140 #define BOUNDED_INCR(x) \
141 	do { \
142 		cp += x; \
143 		if (cp > eom) { \
144 			h_errno = NO_RECOVERY; \
145 			return (NULL); \
146 		} \
147 	} while (0)
148 
149 #define BOUNDS_CHECK(ptr, count) \
150 	do { \
151 		if ((ptr) + (count) > eom) { \
152 			h_errno = NO_RECOVERY; \
153 			return (NULL); \
154 		} \
155 	} while (0)
156 
157 static struct hostent *
158 gethostanswer(answer, anslen, qname, qtype)
159 	const querybuf *answer;
160 	int anslen;
161 	const char *qname;
162 	int qtype;
163 {
164 	const HEADER *hp;
165 	const u_char *cp;
166 	int n;
167 	const u_char *eom, *erdata;
168 	char *bp, *ep, **ap, **hap;
169 	int type, class, ancount, qdcount;
170 	int haveanswer, had_error;
171 	int toobig = 0;
172 	char tbuf[MAXDNAME];
173 	const char *tname;
174 	int (*name_ok)(const char *);
175 
176 	tname = qname;
177 	host.h_name = NULL;
178 	eom = answer->buf + anslen;
179 	switch (qtype) {
180 	case T_A:
181 	case T_AAAA:
182 		name_ok = res_hnok;
183 		break;
184 	case T_PTR:
185 		name_ok = res_dnok;
186 		break;
187 	default:
188 		h_errno = NO_RECOVERY;
189 		return (NULL);	/* XXX should be abort(); */
190 	}
191 	/*
192 	 * find first satisfactory answer
193 	 */
194 	hp = &answer->hdr;
195 	ancount = ntohs(hp->ancount);
196 	qdcount = ntohs(hp->qdcount);
197 	bp = hostbuf;
198 	ep = hostbuf + sizeof hostbuf;
199 	cp = answer->buf;
200 	BOUNDED_INCR(HFIXEDSZ);
201 	if (qdcount != 1) {
202 		h_errno = NO_RECOVERY;
203 		return (NULL);
204 	}
205 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
206 	if ((n < 0) || !(*name_ok)(bp)) {
207 		h_errno = NO_RECOVERY;
208 		return (NULL);
209 	}
210 	BOUNDED_INCR(n + QFIXEDSZ);
211 	if (qtype == T_A || qtype == T_AAAA) {
212 		/* res_send() has already verified that the query name is the
213 		 * same as the one we sent; this just gets the expanded name
214 		 * (i.e., with the succeeding search-domain tacked on).
215 		 */
216 		n = strlen(bp) + 1;		/* for the \0 */
217 		if (n >= MAXHOSTNAMELEN) {
218 			h_errno = NO_RECOVERY;
219 			return (NULL);
220 		}
221 		host.h_name = bp;
222 		bp += n;
223 		/* The qname can be abbreviated, but h_name is now absolute. */
224 		qname = host.h_name;
225 	}
226 	ap = host_aliases;
227 	*ap = NULL;
228 	host.h_aliases = host_aliases;
229 	hap = h_addr_ptrs;
230 	*hap = NULL;
231 	host.h_addr_list = h_addr_ptrs;
232 	haveanswer = 0;
233 	had_error = 0;
234 	_dns_ttl_ = -1;
235 	while (ancount-- > 0 && cp < eom && !had_error) {
236 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
237 		if ((n < 0) || !(*name_ok)(bp)) {
238 			had_error++;
239 			continue;
240 		}
241 		cp += n;			/* name */
242 		BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
243 		type = _getshort(cp);
244  		cp += INT16SZ;			/* type */
245 		class = _getshort(cp);
246  		cp += INT16SZ;			/* class */
247 		if (qtype == T_A  && type == T_A)
248 			_dns_ttl_ = _getlong(cp);
249 		cp += INT32SZ;			/* TTL */
250 		n = _getshort(cp);
251 		cp += INT16SZ;			/* len */
252 		BOUNDS_CHECK(cp, n);
253 		erdata = cp + n;
254 		if (class != C_IN) {
255 			/* XXX - debug? syslog? */
256 			cp += n;
257 			continue;		/* XXX - had_error++ ? */
258 		}
259 		if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
260 			if (ap >= &host_aliases[MAXALIASES-1])
261 				continue;
262 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
263 			if ((n < 0) || !(*name_ok)(tbuf)) {
264 				had_error++;
265 				continue;
266 			}
267 			cp += n;
268 			if (cp != erdata) {
269 				h_errno = NO_RECOVERY;
270 				return (NULL);
271 			}
272 			/* Store alias. */
273 			*ap++ = bp;
274 			n = strlen(bp) + 1;	/* for the \0 */
275 			if (n >= MAXHOSTNAMELEN) {
276 				had_error++;
277 				continue;
278 			}
279 			bp += n;
280 			/* Get canonical name. */
281 			n = strlen(tbuf) + 1;	/* for the \0 */
282 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
283 				had_error++;
284 				continue;
285 			}
286 			strcpy(bp, tbuf);
287 			host.h_name = bp;
288 			bp += n;
289 			continue;
290 		}
291 		if (qtype == T_PTR && type == T_CNAME) {
292 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
293 			if (n < 0 || !res_dnok(tbuf)) {
294 				had_error++;
295 				continue;
296 			}
297 			cp += n;
298 			if (cp != erdata) {
299 				h_errno = NO_RECOVERY;
300 				return (NULL);
301 			}
302 			/* Get canonical name. */
303 			n = strlen(tbuf) + 1;	/* for the \0 */
304 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
305 				had_error++;
306 				continue;
307 			}
308 			strcpy(bp, tbuf);
309 			tname = bp;
310 			bp += n;
311 			continue;
312 		}
313 		if (type != qtype) {
314 			if (type != T_SIG)
315 				syslog(LOG_NOTICE|LOG_AUTH,
316 	"gethostby*.gethostanswer: asked for \"%s %s %s\", got type \"%s\"",
317 				       qname, p_class(C_IN), p_type(qtype),
318 				       p_type(type));
319 			cp += n;
320 			continue;		/* XXX - had_error++ ? */
321 		}
322 		switch (type) {
323 		case T_PTR:
324 			if (strcasecmp(tname, bp) != 0) {
325 				syslog(LOG_NOTICE|LOG_AUTH,
326 				       AskedForGot, qname, bp);
327 				cp += n;
328 				continue;	/* XXX - had_error++ ? */
329 			}
330 			n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
331 			if ((n < 0) || !res_hnok(bp)) {
332 				had_error++;
333 				break;
334 			}
335 #if MULTI_PTRS_ARE_ALIASES
336 			cp += n;
337 			if (cp != erdata) {
338 				h_errno = NO_RECOVERY;
339 				return (NULL);
340 			}
341 			if (!haveanswer)
342 				host.h_name = bp;
343 			else if (ap < &host_aliases[MAXALIASES-1])
344 				*ap++ = bp;
345 			else
346 				n = -1;
347 			if (n != -1) {
348 				n = strlen(bp) + 1;	/* for the \0 */
349 				if (n >= MAXHOSTNAMELEN) {
350 					had_error++;
351 					break;
352 				}
353 				bp += n;
354 			}
355 			break;
356 #else
357 			host.h_name = bp;
358 			if (_res.options & RES_USE_INET6) {
359 				n = strlen(bp) + 1;	/* for the \0 */
360 				if (n >= MAXHOSTNAMELEN) {
361 					had_error++;
362 					break;
363 				}
364 				bp += n;
365 				_map_v4v6_hostent(&host, &bp, &ep);
366 			}
367 			h_errno = NETDB_SUCCESS;
368 			return (&host);
369 #endif
370 		case T_A:
371 		case T_AAAA:
372 			if (strcasecmp(host.h_name, bp) != 0) {
373 				syslog(LOG_NOTICE|LOG_AUTH,
374 				       AskedForGot, host.h_name, bp);
375 				cp += n;
376 				continue;	/* XXX - had_error++ ? */
377 			}
378 			if (n != host.h_length) {
379 				cp += n;
380 				continue;
381 			}
382 			if (!haveanswer) {
383 				int nn;
384 
385 				host.h_name = bp;
386 				nn = strlen(bp) + 1;	/* for the \0 */
387 				bp += nn;
388 			}
389 
390 			bp += sizeof(align) - ((u_long)bp % sizeof(align));
391 
392 			if (bp + n >= ep) {
393 				dprintf("size (%d) too big\n", n);
394 				had_error++;
395 				continue;
396 			}
397 			if (hap >= &h_addr_ptrs[MAXADDRS-1]) {
398 				if (!toobig++)
399 					dprintf("Too many addresses (%d)\n",
400 						MAXADDRS);
401 				cp += n;
402 				continue;
403 			}
404 			bcopy(cp, *hap++ = bp, n);
405 			bp += n;
406 			cp += n;
407 			if (cp != erdata) {
408 				h_errno = NO_RECOVERY;
409 				return (NULL);
410 			}
411 			break;
412 		default:
413 			dprintf("Impossible condition (type=%d)\n", type);
414 			h_errno = NO_RECOVERY;
415 			return (NULL);
416 			/* BIND has abort() here, too risky on bad data */
417 		}
418 		if (!had_error)
419 			haveanswer++;
420 	}
421 	if (haveanswer) {
422 		*ap = NULL;
423 		*hap = NULL;
424 # if defined(RESOLVSORT)
425 		/*
426 		 * Note: we sort even if host can take only one address
427 		 * in its return structures - should give it the "best"
428 		 * address in that case, not some random one
429 		 */
430 		if (_res.nsort && haveanswer > 1 && qtype == T_A)
431 			addrsort(h_addr_ptrs, haveanswer);
432 # endif /*RESOLVSORT*/
433 		if (!host.h_name) {
434 			n = strlen(qname) + 1;	/* for the \0 */
435 			if (n > ep - bp || n >= MAXHOSTNAMELEN)
436 				goto no_recovery;
437 			strcpy(bp, qname);
438 			host.h_name = bp;
439 			bp += n;
440 		}
441 		if (_res.options & RES_USE_INET6)
442 			_map_v4v6_hostent(&host, &bp, &ep);
443 		h_errno = NETDB_SUCCESS;
444 		return (&host);
445 	}
446  no_recovery:
447 	h_errno = NO_RECOVERY;
448 	return (NULL);
449 }
450 
451 struct hostent *
452 __dns_getanswer(answer, anslen, qname, qtype)
453 	const char *answer;
454 	int anslen;
455 	const char *qname;
456 	int qtype;
457 {
458 	switch(qtype) {
459 	case T_AAAA:
460 		host.h_addrtype = AF_INET6;
461 		host.h_length = IN6ADDRSZ;
462 		break;
463 	case T_A:
464 	default:
465 		host.h_addrtype = AF_INET;
466 		host.h_length = INADDRSZ;
467 		break;
468 	}
469 
470 	return(gethostanswer((const querybuf *)answer, anslen, qname, qtype));
471 }
472 
473 int
474 _dns_gethostbyname(void *rval, void *cb_data, va_list ap)
475 {
476 	const char *name;
477 	int af;
478 	querybuf *buf;
479 	const char *cp;
480 	char *bp, *ep;
481 	int n, size, type, len;
482 	char abuf[MAXDNAME];
483 
484 	name = va_arg(ap, const char *);
485 	af = va_arg(ap, int);
486 	*(struct hostent **)rval = NULL;
487 
488 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
489 		h_errno = NETDB_INTERNAL;
490 		return NS_UNAVAIL;
491 	}
492 
493 	switch (af) {
494 	case AF_INET:
495 		size = INADDRSZ;
496 		type = T_A;
497 		break;
498 	case AF_INET6:
499 		size = IN6ADDRSZ;
500 		type = T_AAAA;
501 		break;
502 	default:
503 		h_errno = NETDB_INTERNAL;
504 		errno = EAFNOSUPPORT;
505 		return NS_UNAVAIL;
506 	}
507 
508 	host.h_addrtype = af;
509 	host.h_length = size;
510 
511 	/*
512 	 * if there aren't any dots, it could be a user-level alias.
513 	 * this is also done in res_query() since we are not the only
514 	 * function that looks up host names.
515 	 */
516 	if (!strchr(name, '.') &&
517 	    (cp = _res_hostalias(name, abuf, sizeof abuf)))
518 		name = cp;
519 
520 	/*
521 	 * disallow names consisting only of digits/dots, unless
522 	 * they end in a dot.
523 	 */
524 	if (isdigit((unsigned char)name[0]))
525 		for (cp = name;; ++cp) {
526 			if (!*cp) {
527 				if (*--cp == '.')
528 					break;
529 				/*
530 				 * All-numeric, no dot at the end.
531 				 * Fake up a hostent as if we'd actually
532 				 * done a lookup.
533 				 */
534 				if (inet_pton(af, name, host_addr) <= 0) {
535 					h_errno = HOST_NOT_FOUND;
536 					return NS_NOTFOUND;
537 				}
538 				strncpy(hostbuf, name, MAXDNAME);
539 				hostbuf[MAXDNAME] = '\0';
540 				bp = hostbuf + MAXDNAME;
541 				ep = hostbuf + sizeof hostbuf;
542 				host.h_name = hostbuf;
543 				host.h_aliases = host_aliases;
544 				host_aliases[0] = NULL;
545 				h_addr_ptrs[0] = (char *)host_addr;
546 				h_addr_ptrs[1] = NULL;
547 				host.h_addr_list = h_addr_ptrs;
548 				if (_res.options & RES_USE_INET6)
549 					_map_v4v6_hostent(&host, &bp, &ep);
550 				h_errno = NETDB_SUCCESS;
551 				*(struct hostent **)rval = &host;
552 				return NS_SUCCESS;
553 			}
554 			if (!isdigit((unsigned char)*cp) && *cp != '.')
555 				break;
556 		}
557 	if ((isxdigit((unsigned char)name[0]) && strchr(name, ':') != NULL) ||
558 	    name[0] == ':')
559 		for (cp = name;; ++cp) {
560 			if (!*cp) {
561 				if (*--cp == '.')
562 					break;
563 				/*
564 				 * All-IPv6-legal, no dot at the end.
565 				 * Fake up a hostent as if we'd actually
566 				 * done a lookup.
567 				 */
568 				if (inet_pton(af, name, host_addr) <= 0) {
569 					h_errno = HOST_NOT_FOUND;
570 					return NS_NOTFOUND;
571 				}
572 				strncpy(hostbuf, name, MAXDNAME);
573 				hostbuf[MAXDNAME] = '\0';
574 				bp = hostbuf + MAXDNAME;
575 				len = sizeof hostbuf - MAXDNAME;
576 				host.h_name = hostbuf;
577 				host.h_aliases = host_aliases;
578 				host_aliases[0] = NULL;
579 				h_addr_ptrs[0] = (char *)host_addr;
580 				h_addr_ptrs[1] = NULL;
581 				host.h_addr_list = h_addr_ptrs;
582 				h_errno = NETDB_SUCCESS;
583 				*(struct hostent **)rval = &host;
584 				return NS_SUCCESS;
585 			}
586 			if (!isxdigit((unsigned char)*cp) && *cp != ':' && *cp != '.')
587 				break;
588 		}
589 
590 	if ((buf = malloc(sizeof(*buf))) == NULL) {
591 		h_errno = NETDB_INTERNAL;
592 		return NS_NOTFOUND;
593 	}
594 	n = res_search(name, C_IN, type, buf->buf, sizeof(buf->buf));
595 	if (n < 0) {
596 		free(buf);
597 		dprintf("res_search failed (%d)\n", n);
598 		return (0);
599 	} else if (n > sizeof(buf->buf)) {
600 		free(buf);
601 		dprintf("static buffer is too small (%d)\n", n);
602 		return (0);
603 	}
604 	*(struct hostent **)rval = gethostanswer(buf, n, name, type);
605 	free(buf);
606 	return (*(struct hostent **)rval != NULL) ? NS_SUCCESS : NS_NOTFOUND;
607 }
608 
609 int
610 _dns_gethostbyaddr(void *rval, void *cb_data, va_list ap)
611 {
612 	const char *addr;	/* XXX should have been def'd as u_char! */
613 	int len, af;
614 	const u_char *uaddr;
615 	static const u_char mapped[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
616 	static const u_char tunnelled[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0,0 };
617 	int n, size;
618 	querybuf *buf;
619 	struct hostent *hp;
620 	char qbuf[MAXDNAME+1], *qp;
621 #ifdef SUNSECURITY
622 	struct hostent *rhp;
623 	char **haddr;
624 	u_long old_options;
625 	char hname2[MAXDNAME+1];
626 #endif /*SUNSECURITY*/
627 
628 	addr = va_arg(ap, const char *);
629 	uaddr = (const u_char *)addr;
630 	len = va_arg(ap, int);
631 	af = va_arg(ap, int);
632 
633 	*(struct hostent **)rval = NULL;
634 
635 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
636 		h_errno = NETDB_INTERNAL;
637 		return NS_UNAVAIL;
638 	}
639 	if (af == AF_INET6 && len == IN6ADDRSZ &&
640 	    (!bcmp(uaddr, mapped, sizeof mapped) ||
641 	     !bcmp(uaddr, tunnelled, sizeof tunnelled))) {
642 		/* Unmap. */
643 		addr += sizeof mapped;
644 		uaddr += sizeof mapped;
645 		af = AF_INET;
646 		len = INADDRSZ;
647 	}
648 	switch (af) {
649 	case AF_INET:
650 		size = INADDRSZ;
651 		break;
652 	case AF_INET6:
653 		size = IN6ADDRSZ;
654 		break;
655 	default:
656 		errno = EAFNOSUPPORT;
657 		h_errno = NETDB_INTERNAL;
658 		return NS_UNAVAIL;
659 	}
660 	if (size != len) {
661 		errno = EINVAL;
662 		h_errno = NETDB_INTERNAL;
663 		return NS_UNAVAIL;
664 	}
665 	switch (af) {
666 	case AF_INET:
667 		(void) sprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa",
668 			       (uaddr[3] & 0xff),
669 			       (uaddr[2] & 0xff),
670 			       (uaddr[1] & 0xff),
671 			       (uaddr[0] & 0xff));
672 		break;
673 	case AF_INET6:
674 		qp = qbuf;
675 		for (n = IN6ADDRSZ - 1; n >= 0; n--) {
676 			qp += SPRINTF((qp, "%x.%x.",
677 				       uaddr[n] & 0xf,
678 				       (uaddr[n] >> 4) & 0xf));
679 		}
680 		strlcat(qbuf, "ip6.arpa", sizeof(qbuf));
681 		break;
682 	default:
683 		abort();
684 	}
685 	if ((buf = malloc(sizeof(*buf))) == NULL) {
686 		h_errno = NETDB_INTERNAL;
687 		return NS_NOTFOUND;
688 	}
689 	n = res_query(qbuf, C_IN, T_PTR, (u_char *)buf->buf, sizeof buf->buf);
690 	if (n < 0) {
691 		free(buf);
692 		dprintf("res_query failed (%d)\n", n);
693 		return NS_UNAVAIL;
694 	}
695 	if (n > sizeof buf->buf) {
696 		free(buf);
697 		dprintf("static buffer is too small (%d)\n", n);
698 		return NS_UNAVAIL;
699 	}
700 	if (!(hp = gethostanswer(buf, n, qbuf, T_PTR))) {
701 		free(buf);
702 		return NS_NOTFOUND;   /* h_errno was set by gethostanswer() */
703 	}
704 	free(buf);
705 #ifdef SUNSECURITY
706 	if (af == AF_INET) {
707 	    /*
708 	     * turn off search as the name should be absolute,
709 	     * 'localhost' should be matched by defnames
710 	     */
711 	    strncpy(hname2, hp->h_name, MAXDNAME);
712 	    hname2[MAXDNAME] = '\0';
713 	    old_options = _res.options;
714 	    _res.options &= ~RES_DNSRCH;
715 	    _res.options |= RES_DEFNAMES;
716 	    if (!(rhp = gethostbyname(hname2))) {
717 		syslog(LOG_NOTICE|LOG_AUTH,
718 		       "gethostbyaddr: No A record for %s (verifying [%s])",
719 		       hname2, inet_ntoa(*((struct in_addr *)addr)));
720 		_res.options = old_options;
721 		h_errno = HOST_NOT_FOUND;
722 		return NS_NOTFOUND;
723 	    }
724 	    _res.options = old_options;
725 	    for (haddr = rhp->h_addr_list; *haddr; haddr++)
726 		if (!memcmp(*haddr, addr, INADDRSZ))
727 			break;
728 	    if (!*haddr) {
729 		syslog(LOG_NOTICE|LOG_AUTH,
730 		       "gethostbyaddr: A record of %s != PTR record [%s]",
731 		       hname2, inet_ntoa(*((struct in_addr *)addr)));
732 		h_errno = HOST_NOT_FOUND;
733 		return NS_NOTFOUND;
734 	    }
735 	}
736 #endif /*SUNSECURITY*/
737 	hp->h_addrtype = af;
738 	hp->h_length = len;
739 	bcopy(addr, host_addr, len);
740 	h_addr_ptrs[0] = (char *)host_addr;
741 	h_addr_ptrs[1] = NULL;
742 	if (af == AF_INET && (_res.options & RES_USE_INET6)) {
743 		_map_v4v6_address((char*)host_addr, (char*)host_addr);
744 		hp->h_addrtype = AF_INET6;
745 		hp->h_length = IN6ADDRSZ;
746 	}
747 	h_errno = NETDB_SUCCESS;
748 	*(struct hostent **)rval = hp;
749 	return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
750 }
751 
752 #ifdef RESOLVSORT
753 static void
754 addrsort(ap, num)
755 	char **ap;
756 	int num;
757 {
758 	int i, j;
759 	char **p;
760 	short aval[MAXADDRS];
761 	int needsort = 0;
762 
763 	p = ap;
764 	for (i = 0; i < num; i++, p++) {
765 	    for (j = 0 ; (unsigned)j < _res.nsort; j++)
766 		if (_res.sort_list[j].addr.s_addr ==
767 		    (((struct in_addr *)(*p))->s_addr & _res.sort_list[j].mask))
768 			break;
769 	    aval[i] = j;
770 	    if (needsort == 0 && i > 0 && j < aval[i-1])
771 		needsort = i;
772 	}
773 	if (!needsort)
774 	    return;
775 
776 	while (needsort < num) {
777 	    for (j = needsort - 1; j >= 0; j--) {
778 		if (aval[j] > aval[j+1]) {
779 		    char *hp;
780 
781 		    i = aval[j];
782 		    aval[j] = aval[j+1];
783 		    aval[j+1] = i;
784 
785 		    hp = ap[j];
786 		    ap[j] = ap[j+1];
787 		    ap[j+1] = hp;
788 
789 		} else
790 		    break;
791 	    }
792 	    needsort++;
793 	}
794 }
795 #endif
796 void
797 _sethostdnsent(stayopen)
798 	int stayopen;
799 {
800 	if ((_res.options & RES_INIT) == 0 && res_init() == -1)
801 		return;
802 	if (stayopen)
803 		_res.options |= RES_STAYOPEN | RES_USEVC;
804 }
805 
806 void
807 _endhostdnsent()
808 {
809 	_res.options &= ~(RES_STAYOPEN | RES_USEVC);
810 	res_close();
811 }
812