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