xref: /freebsd/lib/libc/net/gethostbydns.c (revision 4b2eaea43fec8e8792be611dea204071a10b655a)
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 #ifdef RESOLVSORT
100 static void addrsort(char **, int);
101 #endif
102 
103 #ifdef DEBUG
104 static void dprintf(char *, int) __printflike(1, 0);
105 #endif
106 
107 #define MAXPACKET	(64*1024)
108 
109 typedef union {
110     HEADER hdr;
111     u_char buf[MAXPACKET];
112 } querybuf;
113 
114 typedef union {
115     int32_t al;
116     char ac;
117 } align;
118 
119 extern int h_errno;
120 int _dns_ttl_;
121 
122 #ifdef DEBUG
123 static void
124 dprintf(msg, num)
125 	char *msg;
126 	int num;
127 {
128 	if (_res.options & RES_DEBUG) {
129 		int save = errno;
130 
131 		printf(msg, num);
132 		errno = save;
133 	}
134 }
135 #else
136 # define dprintf(msg, num) /*nada*/
137 #endif
138 
139 #define BOUNDED_INCR(x) \
140 	do { \
141 		cp += x; \
142 		if (cp > eom) { \
143 			h_errno = NO_RECOVERY; \
144 			return (NULL); \
145 		} \
146 	} while (0)
147 
148 #define BOUNDS_CHECK(ptr, count) \
149 	do { \
150 		if ((ptr) + (count) > eom) { \
151 			h_errno = NO_RECOVERY; \
152 			return (NULL); \
153 		} \
154 	} while (0)
155 
156 static struct hostent *
157 gethostanswer(answer, anslen, qname, qtype)
158 	const querybuf *answer;
159 	int anslen;
160 	const char *qname;
161 	int qtype;
162 {
163 	const HEADER *hp;
164 	const u_char *cp;
165 	int n;
166 	const u_char *eom, *erdata;
167 	char *bp, *ep, **ap, **hap;
168 	int type, class, ancount, qdcount;
169 	int haveanswer, had_error;
170 	int toobig = 0;
171 	char tbuf[MAXDNAME];
172 	const char *tname;
173 	int (*name_ok)(const char *);
174 
175 	tname = qname;
176 	host.h_name = NULL;
177 	eom = answer->buf + anslen;
178 	switch (qtype) {
179 	case T_A:
180 	case T_AAAA:
181 		name_ok = res_hnok;
182 		break;
183 	case T_PTR:
184 		name_ok = res_dnok;
185 		break;
186 	default:
187 		h_errno = NO_RECOVERY;
188 		return (NULL);	/* XXX should be abort(); */
189 	}
190 	/*
191 	 * find first satisfactory answer
192 	 */
193 	hp = &answer->hdr;
194 	ancount = ntohs(hp->ancount);
195 	qdcount = ntohs(hp->qdcount);
196 	bp = hostbuf;
197 	ep = hostbuf + sizeof hostbuf;
198 	cp = answer->buf;
199 	BOUNDED_INCR(HFIXEDSZ);
200 	if (qdcount != 1) {
201 		h_errno = NO_RECOVERY;
202 		return (NULL);
203 	}
204 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
205 	if ((n < 0) || !(*name_ok)(bp)) {
206 		h_errno = NO_RECOVERY;
207 		return (NULL);
208 	}
209 	BOUNDED_INCR(n + QFIXEDSZ);
210 	if (qtype == T_A || qtype == T_AAAA) {
211 		/* res_send() has already verified that the query name is the
212 		 * same as the one we sent; this just gets the expanded name
213 		 * (i.e., with the succeeding search-domain tacked on).
214 		 */
215 		n = strlen(bp) + 1;		/* for the \0 */
216 		if (n >= MAXHOSTNAMELEN) {
217 			h_errno = NO_RECOVERY;
218 			return (NULL);
219 		}
220 		host.h_name = bp;
221 		bp += n;
222 		/* The qname can be abbreviated, but h_name is now absolute. */
223 		qname = host.h_name;
224 	}
225 	ap = host_aliases;
226 	*ap = NULL;
227 	host.h_aliases = host_aliases;
228 	hap = h_addr_ptrs;
229 	*hap = NULL;
230 	host.h_addr_list = h_addr_ptrs;
231 	haveanswer = 0;
232 	had_error = 0;
233 	_dns_ttl_ = -1;
234 	while (ancount-- > 0 && cp < eom && !had_error) {
235 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
236 		if ((n < 0) || !(*name_ok)(bp)) {
237 			had_error++;
238 			continue;
239 		}
240 		cp += n;			/* name */
241 		BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
242 		type = _getshort(cp);
243  		cp += INT16SZ;			/* type */
244 		class = _getshort(cp);
245  		cp += INT16SZ;			/* class */
246 		if (qtype == T_A  && type == T_A)
247 			_dns_ttl_ = _getlong(cp);
248 		cp += INT32SZ;			/* TTL */
249 		n = _getshort(cp);
250 		cp += INT16SZ;			/* len */
251 		BOUNDS_CHECK(cp, n);
252 		erdata = cp + n;
253 		if (class != C_IN) {
254 			/* XXX - debug? syslog? */
255 			cp += n;
256 			continue;		/* XXX - had_error++ ? */
257 		}
258 		if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) {
259 			if (ap >= &host_aliases[MAXALIASES-1])
260 				continue;
261 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
262 			if ((n < 0) || !(*name_ok)(tbuf)) {
263 				had_error++;
264 				continue;
265 			}
266 			cp += n;
267 			if (cp != erdata) {
268 				h_errno = NO_RECOVERY;
269 				return (NULL);
270 			}
271 			/* Store alias. */
272 			*ap++ = bp;
273 			n = strlen(bp) + 1;	/* for the \0 */
274 			if (n >= MAXHOSTNAMELEN) {
275 				had_error++;
276 				continue;
277 			}
278 			bp += n;
279 			/* Get canonical name. */
280 			n = strlen(tbuf) + 1;	/* for the \0 */
281 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
282 				had_error++;
283 				continue;
284 			}
285 			strcpy(bp, tbuf);
286 			host.h_name = bp;
287 			bp += n;
288 			continue;
289 		}
290 		if (qtype == T_PTR && type == T_CNAME) {
291 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
292 			if (n < 0 || !res_dnok(tbuf)) {
293 				had_error++;
294 				continue;
295 			}
296 			cp += n;
297 			if (cp != erdata) {
298 				h_errno = NO_RECOVERY;
299 				return (NULL);
300 			}
301 			/* Get canonical name. */
302 			n = strlen(tbuf) + 1;	/* for the \0 */
303 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
304 				had_error++;
305 				continue;
306 			}
307 			strcpy(bp, tbuf);
308 			tname = bp;
309 			bp += n;
310 			continue;
311 		}
312 		if (type != qtype) {
313 			if (type != T_SIG)
314 				syslog(LOG_NOTICE|LOG_AUTH,
315 	"gethostby*.gethostanswer: asked for \"%s %s %s\", got type \"%s\"",
316 				       qname, p_class(C_IN), p_type(qtype),
317 				       p_type(type));
318 			cp += n;
319 			continue;		/* XXX - had_error++ ? */
320 		}
321 		switch (type) {
322 		case T_PTR:
323 			if (strcasecmp(tname, bp) != 0) {
324 				syslog(LOG_NOTICE|LOG_AUTH,
325 				       AskedForGot, qname, bp);
326 				cp += n;
327 				continue;	/* XXX - had_error++ ? */
328 			}
329 			n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
330 			if ((n < 0) || !res_hnok(bp)) {
331 				had_error++;
332 				break;
333 			}
334 #if MULTI_PTRS_ARE_ALIASES
335 			cp += n;
336 			if (cp != erdata) {
337 				h_errno = NO_RECOVERY;
338 				return (NULL);
339 			}
340 			if (!haveanswer)
341 				host.h_name = bp;
342 			else if (ap < &host_aliases[MAXALIASES-1])
343 				*ap++ = bp;
344 			else
345 				n = -1;
346 			if (n != -1) {
347 				n = strlen(bp) + 1;	/* for the \0 */
348 				if (n >= MAXHOSTNAMELEN) {
349 					had_error++;
350 					break;
351 				}
352 				bp += n;
353 			}
354 			break;
355 #else
356 			host.h_name = bp;
357 			if (_res.options & RES_USE_INET6) {
358 				n = strlen(bp) + 1;	/* for the \0 */
359 				if (n >= MAXHOSTNAMELEN) {
360 					had_error++;
361 					break;
362 				}
363 				bp += n;
364 				_map_v4v6_hostent(&host, &bp, &ep);
365 			}
366 			h_errno = NETDB_SUCCESS;
367 			return (&host);
368 #endif
369 		case T_A:
370 		case T_AAAA:
371 			if (strcasecmp(host.h_name, bp) != 0) {
372 				syslog(LOG_NOTICE|LOG_AUTH,
373 				       AskedForGot, host.h_name, bp);
374 				cp += n;
375 				continue;	/* XXX - had_error++ ? */
376 			}
377 			if (n != host.h_length) {
378 				cp += n;
379 				continue;
380 			}
381 			if (!haveanswer) {
382 				int nn;
383 
384 				host.h_name = bp;
385 				nn = strlen(bp) + 1;	/* for the \0 */
386 				bp += nn;
387 			}
388 
389 			bp += sizeof(align) - ((u_long)bp % sizeof(align));
390 
391 			if (bp + n >= ep) {
392 				dprintf("size (%d) too big\n", n);
393 				had_error++;
394 				continue;
395 			}
396 			if (hap >= &h_addr_ptrs[MAXADDRS-1]) {
397 				if (!toobig++)
398 					dprintf("Too many addresses (%d)\n",
399 						MAXADDRS);
400 				cp += n;
401 				continue;
402 			}
403 			bcopy(cp, *hap++ = bp, n);
404 			bp += n;
405 			cp += n;
406 			if (cp != erdata) {
407 				h_errno = NO_RECOVERY;
408 				return (NULL);
409 			}
410 			break;
411 		default:
412 			dprintf("Impossible condition (type=%d)\n", type);
413 			h_errno = NO_RECOVERY;
414 			return (NULL);
415 			/* BIND has abort() here, too risky on bad data */
416 		}
417 		if (!had_error)
418 			haveanswer++;
419 	}
420 	if (haveanswer) {
421 		*ap = NULL;
422 		*hap = NULL;
423 # if defined(RESOLVSORT)
424 		/*
425 		 * Note: we sort even if host can take only one address
426 		 * in its return structures - should give it the "best"
427 		 * address in that case, not some random one
428 		 */
429 		if (_res.nsort && haveanswer > 1 && qtype == T_A)
430 			addrsort(h_addr_ptrs, haveanswer);
431 # endif /*RESOLVSORT*/
432 		if (!host.h_name) {
433 			n = strlen(qname) + 1;	/* for the \0 */
434 			if (n > ep - bp || n >= MAXHOSTNAMELEN)
435 				goto no_recovery;
436 			strcpy(bp, qname);
437 			host.h_name = bp;
438 			bp += n;
439 		}
440 		if (_res.options & RES_USE_INET6)
441 			_map_v4v6_hostent(&host, &bp, &ep);
442 		h_errno = NETDB_SUCCESS;
443 		return (&host);
444 	}
445  no_recovery:
446 	h_errno = NO_RECOVERY;
447 	return (NULL);
448 }
449 
450 struct hostent *
451 __dns_getanswer(answer, anslen, qname, qtype)
452 	const char *answer;
453 	int anslen;
454 	const char *qname;
455 	int qtype;
456 {
457 	switch(qtype) {
458 	case T_AAAA:
459 		host.h_addrtype = AF_INET6;
460 		host.h_length = IN6ADDRSZ;
461 		break;
462 	case T_A:
463 	default:
464 		host.h_addrtype = AF_INET;
465 		host.h_length = INADDRSZ;
466 		break;
467 	}
468 
469 	return(gethostanswer((const querybuf *)answer, anslen, qname, qtype));
470 }
471 
472 int
473 _dns_gethostbyname(void *rval, void *cb_data, va_list ap)
474 {
475 	const char *name;
476 	int af;
477 	querybuf *buf;
478 	const char *cp;
479 	char *bp, *ep;
480 	int n, size, type, len;
481 
482 	name = va_arg(ap, const char *);
483 	af = va_arg(ap, int);
484 	*(struct hostent **)rval = NULL;
485 
486 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
487 		h_errno = NETDB_INTERNAL;
488 		return NS_UNAVAIL;
489 	}
490 
491 	switch (af) {
492 	case AF_INET:
493 		size = INADDRSZ;
494 		type = T_A;
495 		break;
496 	case AF_INET6:
497 		size = IN6ADDRSZ;
498 		type = T_AAAA;
499 		break;
500 	default:
501 		h_errno = NETDB_INTERNAL;
502 		errno = EAFNOSUPPORT;
503 		return NS_UNAVAIL;
504 	}
505 
506 	host.h_addrtype = af;
507 	host.h_length = size;
508 
509 	/*
510 	 * if there aren't any dots, it could be a user-level alias.
511 	 * this is also done in res_query() since we are not the only
512 	 * function that looks up host names.
513 	 */
514 	if (!strchr(name, '.') && (cp = __hostalias(name)))
515 		name = cp;
516 
517 	/*
518 	 * disallow names consisting only of digits/dots, unless
519 	 * they end in a dot.
520 	 */
521 	if (isdigit((unsigned char)name[0]))
522 		for (cp = name;; ++cp) {
523 			if (!*cp) {
524 				if (*--cp == '.')
525 					break;
526 				/*
527 				 * All-numeric, no dot at the end.
528 				 * Fake up a hostent as if we'd actually
529 				 * done a lookup.
530 				 */
531 				if (inet_pton(af, name, host_addr) <= 0) {
532 					h_errno = HOST_NOT_FOUND;
533 					return NS_NOTFOUND;
534 				}
535 				strncpy(hostbuf, name, MAXDNAME);
536 				hostbuf[MAXDNAME] = '\0';
537 				bp = hostbuf + MAXDNAME;
538 				ep = hostbuf + sizeof hostbuf;
539 				host.h_name = hostbuf;
540 				host.h_aliases = host_aliases;
541 				host_aliases[0] = NULL;
542 				h_addr_ptrs[0] = (char *)host_addr;
543 				h_addr_ptrs[1] = NULL;
544 				host.h_addr_list = h_addr_ptrs;
545 				if (_res.options & RES_USE_INET6)
546 					_map_v4v6_hostent(&host, &bp, &ep);
547 				h_errno = NETDB_SUCCESS;
548 				*(struct hostent **)rval = &host;
549 				return NS_SUCCESS;
550 			}
551 			if (!isdigit((unsigned char)*cp) && *cp != '.')
552 				break;
553 		}
554 	if ((isxdigit((unsigned char)name[0]) && strchr(name, ':') != NULL) ||
555 	    name[0] == ':')
556 		for (cp = name;; ++cp) {
557 			if (!*cp) {
558 				if (*--cp == '.')
559 					break;
560 				/*
561 				 * All-IPv6-legal, no dot at the end.
562 				 * Fake up a hostent as if we'd actually
563 				 * done a lookup.
564 				 */
565 				if (inet_pton(af, name, host_addr) <= 0) {
566 					h_errno = HOST_NOT_FOUND;
567 					return NS_NOTFOUND;
568 				}
569 				strncpy(hostbuf, name, MAXDNAME);
570 				hostbuf[MAXDNAME] = '\0';
571 				bp = hostbuf + MAXDNAME;
572 				len = sizeof hostbuf - MAXDNAME;
573 				host.h_name = hostbuf;
574 				host.h_aliases = host_aliases;
575 				host_aliases[0] = NULL;
576 				h_addr_ptrs[0] = (char *)host_addr;
577 				h_addr_ptrs[1] = NULL;
578 				host.h_addr_list = h_addr_ptrs;
579 				h_errno = NETDB_SUCCESS;
580 				*(struct hostent **)rval = &host;
581 				return NS_SUCCESS;
582 			}
583 			if (!isxdigit((unsigned char)*cp) && *cp != ':' && *cp != '.')
584 				break;
585 		}
586 
587 	if ((buf = malloc(sizeof(*buf))) == NULL) {
588 		h_errno = NETDB_INTERNAL;
589 		return NS_NOTFOUND;
590 	}
591 	n = res_search(name, C_IN, type, buf->buf, sizeof(buf->buf));
592 	if (n < 0) {
593 		free(buf);
594 		dprintf("res_search failed (%d)\n", n);
595 		return (NULL);
596 	} else if (n > sizeof(buf->buf)) {
597 		free(buf);
598 		dprintf("static buffer is too small (%d)\n", n);
599 		return (NULL);
600 	}
601 	*(struct hostent **)rval = gethostanswer(buf, n, name, type);
602 	free(buf);
603 	return (*(struct hostent **)rval != NULL) ? NS_SUCCESS : NS_NOTFOUND;
604 }
605 
606 int
607 _dns_gethostbyaddr(void *rval, void *cb_data, va_list ap)
608 {
609 	const char *addr;	/* XXX should have been def'd as u_char! */
610 	int len, af;
611 	const u_char *uaddr;
612 	static const u_char mapped[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
613 	static const u_char tunnelled[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0,0 };
614 	int n, size;
615 	querybuf *buf;
616 	struct hostent *hp;
617 	char qbuf[MAXDNAME+1], *qp;
618 #ifdef SUNSECURITY
619 	struct hostent *rhp;
620 	char **haddr;
621 	u_long old_options;
622 	char hname2[MAXDNAME+1];
623 #endif /*SUNSECURITY*/
624 
625 	addr = va_arg(ap, const char *);
626 	uaddr = (const u_char *)addr;
627 	len = va_arg(ap, int);
628 	af = va_arg(ap, int);
629 
630 	*(struct hostent **)rval = NULL;
631 
632 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
633 		h_errno = NETDB_INTERNAL;
634 		return NS_UNAVAIL;
635 	}
636 	if (af == AF_INET6 && len == IN6ADDRSZ &&
637 	    (!bcmp(uaddr, mapped, sizeof mapped) ||
638 	     !bcmp(uaddr, tunnelled, sizeof tunnelled))) {
639 		/* Unmap. */
640 		addr += sizeof mapped;
641 		uaddr += sizeof mapped;
642 		af = AF_INET;
643 		len = INADDRSZ;
644 	}
645 	switch (af) {
646 	case AF_INET:
647 		size = INADDRSZ;
648 		break;
649 	case AF_INET6:
650 		size = IN6ADDRSZ;
651 		break;
652 	default:
653 		errno = EAFNOSUPPORT;
654 		h_errno = NETDB_INTERNAL;
655 		return NS_UNAVAIL;
656 	}
657 	if (size != len) {
658 		errno = EINVAL;
659 		h_errno = NETDB_INTERNAL;
660 		return NS_UNAVAIL;
661 	}
662 	switch (af) {
663 	case AF_INET:
664 		(void) sprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa",
665 			       (uaddr[3] & 0xff),
666 			       (uaddr[2] & 0xff),
667 			       (uaddr[1] & 0xff),
668 			       (uaddr[0] & 0xff));
669 		break;
670 	case AF_INET6:
671 		qp = qbuf;
672 		for (n = IN6ADDRSZ - 1; n >= 0; n--) {
673 			qp += SPRINTF((qp, "%x.%x.",
674 				       uaddr[n] & 0xf,
675 				       (uaddr[n] >> 4) & 0xf));
676 		}
677 		strlcat(qbuf, "ip6.arpa", sizeof(qbuf));
678 		break;
679 	default:
680 		abort();
681 	}
682 	if ((buf = malloc(sizeof(*buf))) == NULL) {
683 		h_errno = NETDB_INTERNAL;
684 		return NS_NOTFOUND;
685 	}
686 	n = res_query(qbuf, C_IN, T_PTR, (u_char *)buf->buf, sizeof buf->buf);
687 	if (n < 0 && af == AF_INET6) {
688 		*qp = '\0';
689 		strlcat(qbuf, "ip6.int", sizeof(qbuf));
690 		n = res_query(qbuf, C_IN, T_PTR, (u_char *)buf->buf,
691 			      sizeof buf->buf);
692 	}
693 	if (n < 0) {
694 		free(buf);
695 		dprintf("res_query failed (%d)\n", n);
696 		return NS_UNAVAIL;
697 	}
698 	if (n > sizeof buf->buf) {
699 		free(buf);
700 		dprintf("static buffer is too small (%d)\n", n);
701 		return NS_UNAVAIL;
702 	}
703 	if (!(hp = gethostanswer(buf, n, qbuf, T_PTR))) {
704 		free(buf);
705 		return NS_NOTFOUND;   /* h_errno was set by gethostanswer() */
706 	}
707 	free(buf);
708 #ifdef SUNSECURITY
709 	if (af == AF_INET) {
710 	    /*
711 	     * turn off search as the name should be absolute,
712 	     * 'localhost' should be matched by defnames
713 	     */
714 	    strncpy(hname2, hp->h_name, MAXDNAME);
715 	    hname2[MAXDNAME] = '\0';
716 	    old_options = _res.options;
717 	    _res.options &= ~RES_DNSRCH;
718 	    _res.options |= RES_DEFNAMES;
719 	    if (!(rhp = gethostbyname(hname2))) {
720 		syslog(LOG_NOTICE|LOG_AUTH,
721 		       "gethostbyaddr: No A record for %s (verifying [%s])",
722 		       hname2, inet_ntoa(*((struct in_addr *)addr)));
723 		_res.options = old_options;
724 		h_errno = HOST_NOT_FOUND;
725 		return NS_NOTFOUND;
726 	    }
727 	    _res.options = old_options;
728 	    for (haddr = rhp->h_addr_list; *haddr; haddr++)
729 		if (!memcmp(*haddr, addr, INADDRSZ))
730 			break;
731 	    if (!*haddr) {
732 		syslog(LOG_NOTICE|LOG_AUTH,
733 		       "gethostbyaddr: A record of %s != PTR record [%s]",
734 		       hname2, inet_ntoa(*((struct in_addr *)addr)));
735 		h_errno = HOST_NOT_FOUND;
736 		return NS_NOTFOUND;
737 	    }
738 	}
739 #endif /*SUNSECURITY*/
740 	hp->h_addrtype = af;
741 	hp->h_length = len;
742 	bcopy(addr, host_addr, len);
743 	h_addr_ptrs[0] = (char *)host_addr;
744 	h_addr_ptrs[1] = NULL;
745 	if (af == AF_INET && (_res.options & RES_USE_INET6)) {
746 		_map_v4v6_address((char*)host_addr, (char*)host_addr);
747 		hp->h_addrtype = AF_INET6;
748 		hp->h_length = IN6ADDRSZ;
749 	}
750 	h_errno = NETDB_SUCCESS;
751 	*(struct hostent **)rval = hp;
752 	return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND;
753 }
754 
755 #ifdef RESOLVSORT
756 static void
757 addrsort(ap, num)
758 	char **ap;
759 	int num;
760 {
761 	int i, j;
762 	char **p;
763 	short aval[MAXADDRS];
764 	int needsort = 0;
765 
766 	p = ap;
767 	for (i = 0; i < num; i++, p++) {
768 	    for (j = 0 ; (unsigned)j < _res.nsort; j++)
769 		if (_res.sort_list[j].addr.s_addr ==
770 		    (((struct in_addr *)(*p))->s_addr & _res.sort_list[j].mask))
771 			break;
772 	    aval[i] = j;
773 	    if (needsort == 0 && i > 0 && j < aval[i-1])
774 		needsort = i;
775 	}
776 	if (!needsort)
777 	    return;
778 
779 	while (needsort < num) {
780 	    for (j = needsort - 1; j >= 0; j--) {
781 		if (aval[j] > aval[j+1]) {
782 		    char *hp;
783 
784 		    i = aval[j];
785 		    aval[j] = aval[j+1];
786 		    aval[j+1] = i;
787 
788 		    hp = ap[j];
789 		    ap[j] = ap[j+1];
790 		    ap[j+1] = hp;
791 
792 		} else
793 		    break;
794 	    }
795 	    needsort++;
796 	}
797 }
798 #endif
799 void
800 _sethostdnsent(stayopen)
801 	int stayopen;
802 {
803 	if ((_res.options & RES_INIT) == 0 && res_init() == -1)
804 		return;
805 	if (stayopen)
806 		_res.options |= RES_STAYOPEN | RES_USEVC;
807 }
808 
809 void
810 _endhostdnsent()
811 {
812 	_res.options &= ~(RES_STAYOPEN | RES_USEVC);
813 	res_close();
814 }
815