xref: /netbsd/external/bsd/libbind/dist/irs/dns_ho.c (revision 6550d01e)
1 /*	$NetBSD: dns_ho.c,v 1.1.1.1 2009/04/12 15:33:42 christos Exp $	*/
2 
3 /*
4  * Portions Copyright (C) 2004-2006, 2008  Internet Systems Consortium, Inc. ("ISC")
5  * Portions Copyright (C) 1996-2003  Internet Software Consortium.
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17  * PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*
21  * Copyright (c) 1985, 1988, 1993
22  *    The Regents of the University of California.  All rights reserved.
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in the
31  *    documentation and/or other materials provided with the distribution.
32  * 3. All advertising materials mentioning features or use of this software
33  *    must display the following acknowledgement:
34  * 	This product includes software developed by the University of
35  * 	California, Berkeley and its contributors.
36  * 4. Neither the name of the University nor the names of its contributors
37  *    may be used to endorse or promote products derived from this software
38  *    without specific prior written permission.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  */
52 
53 /* from gethostnamadr.c	8.1 (Berkeley) 6/4/93 */
54 /* BIND Id: gethnamaddr.c,v 8.15 1996/05/22 04:56:30 vixie Exp $ */
55 
56 #if defined(LIBC_SCCS) && !defined(lint)
57 static const char rcsid[] = "Id: dns_ho.c,v 1.23 2008/11/14 02:36:51 marka Exp";
58 #endif /* LIBC_SCCS and not lint */
59 
60 /* Imports. */
61 
62 #include "port_before.h"
63 
64 #include <sys/types.h>
65 #include <sys/param.h>
66 #include <sys/socket.h>
67 
68 #include <netinet/in.h>
69 #include <arpa/inet.h>
70 #include <arpa/nameser.h>
71 
72 #include <ctype.h>
73 #include <errno.h>
74 #include <stdlib.h>
75 #include <netdb.h>
76 #include <resolv.h>
77 #include <stdio.h>
78 #include <string.h>
79 #include <syslog.h>
80 
81 #include <isc/memcluster.h>
82 #include <irs.h>
83 
84 #include "port_after.h"
85 
86 #include "irs_p.h"
87 #include "dns_p.h"
88 
89 #ifdef SPRINTF_CHAR
90 # define SPRINTF(x) strlen(sprintf/**/x)
91 #else
92 # define SPRINTF(x) sprintf x
93 #endif
94 
95 /* Definitions. */
96 
97 #define	MAXALIASES	35
98 #define	MAXADDRS	35
99 
100 #define MAXPACKET (65535)	/*%< Maximum TCP message size */
101 #define BOUNDS_CHECK(ptr, count) \
102 	if ((ptr) + (count) > eom) { \
103 		had_error++; \
104 		continue; \
105 	} else (void)0
106 
107 typedef union {
108 	HEADER hdr;
109 	u_char buf[MAXPACKET];
110 } querybuf;
111 
112 struct dns_res_target {
113 	struct dns_res_target *next;
114 	querybuf qbuf;		/*%< query buffer */
115 	u_char *answer;		/*%< buffer to put answer */
116 	int anslen;		/*%< size of answer buffer */
117 	int qclass, qtype;	/*%< class and type of query */
118 	int action;		/*%< condition whether query is really issued */
119 	char qname[MAXDNAME +1]; /*%< domain name */
120 #if 0
121 	int n;			/*%< result length */
122 #endif
123 };
124 enum {RESTGT_DOALWAYS, RESTGT_AFTERFAILURE, RESTGT_IGNORE};
125 enum {RESQRY_SUCCESS, RESQRY_FAIL};
126 
127 struct pvt {
128 	struct hostent	host;
129 	char *		h_addr_ptrs[MAXADDRS + 1];
130 	char *		host_aliases[MAXALIASES];
131 	char		hostbuf[8*1024];
132 	u_char		host_addr[16];	/*%< IPv4 or IPv6 */
133 	struct __res_state  *res;
134 	void		(*free_res)(void *);
135 };
136 
137 typedef union {
138 	int32_t al;
139 	char ac;
140 } align;
141 
142 static const u_char mapped[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
143 static const u_char tunnelled[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0,0 };
144 /* Note: the IPv6 loopback address is in the "tunnel" space */
145 static const u_char v6local[] = { 0,0, 0,1 }; /*%< last 4 bytes of IPv6 addr */
146 /* Forwards. */
147 
148 static void		ho_close(struct irs_ho *this);
149 static struct hostent *	ho_byname(struct irs_ho *this, const char *name);
150 static struct hostent *	ho_byname2(struct irs_ho *this, const char *name,
151 				   int af);
152 static struct hostent *	ho_byaddr(struct irs_ho *this, const void *addr,
153 				  int len, int af);
154 static struct hostent *	ho_next(struct irs_ho *this);
155 static void		ho_rewind(struct irs_ho *this);
156 static void		ho_minimize(struct irs_ho *this);
157 static struct __res_state * ho_res_get(struct irs_ho *this);
158 static void		ho_res_set(struct irs_ho *this,
159 				   struct __res_state *res,
160 				   void (*free_res)(void *));
161 static struct addrinfo * ho_addrinfo(struct irs_ho *this, const char *name,
162 				     const struct addrinfo *pai);
163 
164 static void		map_v4v6_hostent(struct hostent *hp, char **bp,
165 					 char *ep);
166 static void		addrsort(res_state, char **, int);
167 static struct hostent *	gethostans(struct irs_ho *this,
168 				   const u_char *ansbuf, int anslen,
169 				   const char *qname, int qtype,
170 				   int af, int size,
171 				   struct addrinfo **ret_aip,
172 				   const struct addrinfo *pai);
173 static int add_hostent(struct pvt *pvt, char *bp, char **hap,
174 		       struct addrinfo *ai);
175 static int		init(struct irs_ho *this);
176 
177 /* Exports. */
178 
179 struct irs_ho *
180 irs_dns_ho(struct irs_acc *this) {
181 	struct irs_ho *ho;
182 	struct pvt *pvt;
183 
184 	UNUSED(this);
185 
186 	if (!(pvt = memget(sizeof *pvt))) {
187 		errno = ENOMEM;
188 		return (NULL);
189 	}
190 	memset(pvt, 0, sizeof *pvt);
191 
192 	if (!(ho = memget(sizeof *ho))) {
193 		memput(pvt, sizeof *pvt);
194 		errno = ENOMEM;
195 		return (NULL);
196 	}
197 	memset(ho, 0x5e, sizeof *ho);
198 	ho->private = pvt;
199 	ho->close = ho_close;
200 	ho->byname = ho_byname;
201 	ho->byname2 = ho_byname2;
202 	ho->byaddr = ho_byaddr;
203 	ho->next = ho_next;
204 	ho->rewind = ho_rewind;
205 	ho->minimize = ho_minimize;
206 	ho->res_get = ho_res_get;
207 	ho->res_set = ho_res_set;
208 	ho->addrinfo = ho_addrinfo;
209 	return (ho);
210 }
211 
212 /* Methods. */
213 
214 static void
215 ho_close(struct irs_ho *this) {
216 	struct pvt *pvt = (struct pvt *)this->private;
217 
218 	ho_minimize(this);
219 	if (pvt->res && pvt->free_res)
220 		(*pvt->free_res)(pvt->res);
221 	memput(pvt, sizeof *pvt);
222 	memput(this, sizeof *this);
223 }
224 
225 static struct hostent *
226 ho_byname(struct irs_ho *this, const char *name) {
227 	struct pvt *pvt = (struct pvt *)this->private;
228 	struct hostent *hp;
229 
230 	if (init(this) == -1)
231 		return (NULL);
232 
233 	if (pvt->res->options & RES_USE_INET6) {
234 		hp = ho_byname2(this, name, AF_INET6);
235 		if (hp)
236 			return (hp);
237 	}
238 	return (ho_byname2(this, name, AF_INET));
239 }
240 
241 static struct hostent *
242 ho_byname2(struct irs_ho *this, const char *name, int af)
243 {
244 	struct pvt *pvt = (struct pvt *)this->private;
245 	struct hostent *hp = NULL;
246 	int n, size;
247 	char tmp[NS_MAXDNAME];
248 	const char *cp;
249 	struct addrinfo ai;
250 	struct dns_res_target *q, *p;
251 	int querystate = RESQRY_FAIL;
252 
253 	if (init(this) == -1)
254 		return (NULL);
255 
256 	q = memget(sizeof(*q));
257 	if (q == NULL) {
258 		RES_SET_H_ERRNO(pvt->res, NETDB_INTERNAL);
259 		errno = ENOMEM;
260 		goto cleanup;
261 	}
262 	memset(q, 0, sizeof(*q));
263 
264 	switch (af) {
265 	case AF_INET:
266 		size = INADDRSZ;
267 		q->qclass = C_IN;
268 		q->qtype = T_A;
269 		q->answer = q->qbuf.buf;
270 		q->anslen = sizeof(q->qbuf);
271 		q->action = RESTGT_DOALWAYS;
272 		break;
273 	case AF_INET6:
274 		size = IN6ADDRSZ;
275 		q->qclass = C_IN;
276 		q->qtype = T_AAAA;
277 		q->answer = q->qbuf.buf;
278 		q->anslen = sizeof(q->qbuf);
279 		q->action = RESTGT_DOALWAYS;
280 		break;
281 	default:
282 		RES_SET_H_ERRNO(pvt->res, NETDB_INTERNAL);
283 		errno = EAFNOSUPPORT;
284 		hp = NULL;
285 		goto cleanup;
286 	}
287 
288 	/*
289 	 * if there aren't any dots, it could be a user-level alias.
290 	 * this is also done in res_nquery() since we are not the only
291 	 * function that looks up host names.
292 	 */
293 	if (!strchr(name, '.') && (cp = res_hostalias(pvt->res, name,
294 						      tmp, sizeof tmp)))
295 		name = cp;
296 
297 	for (p = q; p; p = p->next) {
298 		switch(p->action) {
299 		case RESTGT_DOALWAYS:
300 			break;
301 		case RESTGT_AFTERFAILURE:
302 			if (querystate == RESQRY_SUCCESS)
303 				continue;
304 			break;
305 		case RESTGT_IGNORE:
306 			continue;
307 		}
308 
309 		if ((n = res_nsearch(pvt->res, name, p->qclass, p->qtype,
310 				     p->answer, p->anslen)) < 0) {
311 			querystate = RESQRY_FAIL;
312 			continue;
313 		}
314 
315 		memset(&ai, 0, sizeof(ai));
316 		ai.ai_family = af;
317 		if ((hp = gethostans(this, p->answer, n, name, p->qtype,
318 				     af, size, NULL,
319 				     (const struct addrinfo *)&ai)) != NULL)
320 			goto cleanup;	/*%< no more loop is necessary */
321 		querystate = RESQRY_FAIL;
322 		continue;
323 	}
324 
325  cleanup:
326 	if (q != NULL)
327 		memput(q, sizeof(*q));
328 	return(hp);
329 }
330 
331 static struct hostent *
332 ho_byaddr(struct irs_ho *this, const void *addr, int len, int af)
333 {
334 	struct pvt *pvt = (struct pvt *)this->private;
335 	const u_char *uaddr = addr;
336 	char *qp;
337 	struct hostent *hp = NULL;
338 	struct addrinfo ai;
339 	struct dns_res_target *q, *q2, *p;
340 	int n, size, i;
341 	int querystate = RESQRY_FAIL;
342 
343 	if (init(this) == -1)
344 		return (NULL);
345 
346 	q = memget(sizeof(*q));
347 	q2 = memget(sizeof(*q2));
348 	if (q == NULL || q2 == NULL) {
349 		RES_SET_H_ERRNO(pvt->res, NETDB_INTERNAL);
350 		errno = ENOMEM;
351 		goto cleanup;
352 	}
353 	memset(q, 0, sizeof(*q));
354 	memset(q2, 0, sizeof(*q2));
355 
356 	if (af == AF_INET6 && len == IN6ADDRSZ &&
357 	    (!memcmp(uaddr, mapped, sizeof mapped) ||
358 	   (!memcmp(uaddr, tunnelled, sizeof tunnelled) &&
359 	    memcmp(&uaddr[sizeof tunnelled], v6local, sizeof(v6local))))) {
360 		/* Unmap. */
361 		addr = (const char *)addr + sizeof mapped;
362 		uaddr += sizeof mapped;
363 		af = AF_INET;
364 		len = INADDRSZ;
365 	}
366 	switch (af) {
367 	case AF_INET:
368 		size = INADDRSZ;
369 		q->qclass = C_IN;
370 		q->qtype = T_PTR;
371 		q->answer = q->qbuf.buf;
372 		q->anslen = sizeof(q->qbuf);
373 		q->action = RESTGT_DOALWAYS;
374 		break;
375 	case AF_INET6:
376 		size = IN6ADDRSZ;
377 		q->qclass = C_IN;
378 		q->qtype = T_PTR;
379 		q->answer = q->qbuf.buf;
380 		q->anslen = sizeof(q->qbuf);
381 		q->next = q2;
382 		q->action = RESTGT_DOALWAYS;
383 		q2->qclass = C_IN;
384 		q2->qtype = T_PTR;
385 		q2->answer = q2->qbuf.buf;
386 		q2->anslen = sizeof(q2->qbuf);
387 		if ((pvt->res->options & RES_NO_NIBBLE2) != 0U)
388 			q2->action = RESTGT_IGNORE;
389 		else
390 			q2->action = RESTGT_AFTERFAILURE;
391 		break;
392 	default:
393 		errno = EAFNOSUPPORT;
394 		RES_SET_H_ERRNO(pvt->res, NETDB_INTERNAL);
395 		hp = NULL;
396 		goto cleanup;
397 	}
398 	if (size > len) {
399 		errno = EINVAL;
400 		RES_SET_H_ERRNO(pvt->res, NETDB_INTERNAL);
401 		hp = NULL;
402 		goto cleanup;
403 	}
404 	switch (af) {
405 	case AF_INET:
406 		qp = q->qname;
407 		(void) sprintf(qp, "%u.%u.%u.%u.in-addr.arpa",
408 			       (uaddr[3] & 0xff),
409 			       (uaddr[2] & 0xff),
410 			       (uaddr[1] & 0xff),
411 			       (uaddr[0] & 0xff));
412 		break;
413 	case AF_INET6:
414 		if (q->action != RESTGT_IGNORE) {
415 			const char *nibsuff = res_get_nibblesuffix(pvt->res);
416 			qp = q->qname;
417 			for (n = IN6ADDRSZ - 1; n >= 0; n--) {
418 				i = SPRINTF((qp, "%x.%x.",
419 					       uaddr[n] & 0xf,
420 					       (uaddr[n] >> 4) & 0xf));
421 				if (i != 4)
422 					abort();
423 				qp += i;
424 			}
425 			if (strlen(q->qname) + strlen(nibsuff) + 1 >
426 			    sizeof q->qname) {
427 				errno = ENAMETOOLONG;
428 				RES_SET_H_ERRNO(pvt->res, NETDB_INTERNAL);
429 				hp = NULL;
430 				goto cleanup;
431 			}
432 			strcpy(qp, nibsuff);	/* (checked) */
433 		}
434 		if (q2->action != RESTGT_IGNORE) {
435 			const char *nibsuff2 = res_get_nibblesuffix2(pvt->res);
436 			qp = q2->qname;
437 			for (n = IN6ADDRSZ - 1; n >= 0; n--) {
438 				i = SPRINTF((qp, "%x.%x.",
439 					       uaddr[n] & 0xf,
440 					       (uaddr[n] >> 4) & 0xf));
441 				if (i != 4)
442 					abort();
443 				qp += i;
444 			}
445 			if (strlen(q2->qname) + strlen(nibsuff2) + 1 >
446 			    sizeof q2->qname) {
447 				errno = ENAMETOOLONG;
448 				RES_SET_H_ERRNO(pvt->res, NETDB_INTERNAL);
449 				hp = NULL;
450 				goto cleanup;
451 			}
452 			strcpy(qp, nibsuff2);	/* (checked) */
453 		}
454 		break;
455 	default:
456 		abort();
457 	}
458 
459 	for (p = q; p; p = p->next) {
460 		switch(p->action) {
461 		case RESTGT_DOALWAYS:
462 			break;
463 		case RESTGT_AFTERFAILURE:
464 			if (querystate == RESQRY_SUCCESS)
465 				continue;
466 			break;
467 		case RESTGT_IGNORE:
468 			continue;
469 		}
470 
471 		if ((n = res_nquery(pvt->res, p->qname, p->qclass, p->qtype,
472 				    p->answer, p->anslen)) < 0) {
473 			querystate = RESQRY_FAIL;
474 			continue;
475 		}
476 
477 		memset(&ai, 0, sizeof(ai));
478 		ai.ai_family = af;
479 		hp = gethostans(this, p->answer, n, p->qname, T_PTR, af, size,
480 				NULL, (const struct addrinfo *)&ai);
481 		if (!hp) {
482 			querystate = RESQRY_FAIL;
483 			continue;
484 		}
485 
486 		memcpy(pvt->host_addr, addr, len);
487 		pvt->h_addr_ptrs[0] = (char *)pvt->host_addr;
488 		pvt->h_addr_ptrs[1] = NULL;
489 		if (af == AF_INET && (pvt->res->options & RES_USE_INET6)) {
490 			map_v4v6_address((char*)pvt->host_addr,
491 					 (char*)pvt->host_addr);
492 			pvt->host.h_addrtype = AF_INET6;
493 			pvt->host.h_length = IN6ADDRSZ;
494 		}
495 
496 		RES_SET_H_ERRNO(pvt->res, NETDB_SUCCESS);
497 		goto cleanup;	/*%< no more loop is necessary. */
498 	}
499 	hp = NULL; /*%< H_ERRNO was set by subroutines */
500  cleanup:
501 	if (q != NULL)
502 		memput(q, sizeof(*q));
503 	if (q2 != NULL)
504 		memput(q2, sizeof(*q2));
505 	return(hp);
506 }
507 
508 static struct hostent *
509 ho_next(struct irs_ho *this) {
510 
511 	UNUSED(this);
512 
513 	return (NULL);
514 }
515 
516 static void
517 ho_rewind(struct irs_ho *this) {
518 
519 	UNUSED(this);
520 
521 	/* NOOP */
522 }
523 
524 static void
525 ho_minimize(struct irs_ho *this) {
526 	struct pvt *pvt = (struct pvt *)this->private;
527 
528 	if (pvt->res)
529 		res_nclose(pvt->res);
530 }
531 
532 static struct __res_state *
533 ho_res_get(struct irs_ho *this) {
534 	struct pvt *pvt = (struct pvt *)this->private;
535 
536 	if (!pvt->res) {
537 		struct __res_state *res;
538 		res = (struct __res_state *)malloc(sizeof *res);
539 		if (!res) {
540 			errno = ENOMEM;
541 			return (NULL);
542 		}
543 		memset(res, 0, sizeof *res);
544 		ho_res_set(this, res, free);
545 	}
546 
547 	return (pvt->res);
548 }
549 
550 /* XXX */
551 extern struct addrinfo *addr2addrinfo __P((const struct addrinfo *,
552 					   const char *));
553 
554 static struct addrinfo *
555 ho_addrinfo(struct irs_ho *this, const char *name, const struct addrinfo *pai)
556 {
557 	struct pvt *pvt = (struct pvt *)this->private;
558 	int n;
559 	char tmp[NS_MAXDNAME];
560 	const char *cp;
561 	struct dns_res_target *q, *q2, *p;
562 	struct addrinfo sentinel, *cur;
563 	int querystate = RESQRY_FAIL;
564 
565 	if (init(this) == -1)
566 		return (NULL);
567 
568 	memset(&sentinel, 0, sizeof(sentinel));
569 	cur = &sentinel;
570 
571 	q = memget(sizeof(*q));
572 	q2 = memget(sizeof(*q2));
573 	if (q == NULL || q2 == NULL) {
574 		RES_SET_H_ERRNO(pvt->res, NETDB_INTERNAL);
575 		errno = ENOMEM;
576 		goto cleanup;
577 	}
578 	memset(q, 0, sizeof(*q2));
579 	memset(q2, 0, sizeof(*q2));
580 
581 	switch (pai->ai_family) {
582 	case AF_UNSPEC:
583 		/* prefer IPv6 */
584 		q->qclass = C_IN;
585 		q->qtype = T_AAAA;
586 		q->answer = q->qbuf.buf;
587 		q->anslen = sizeof(q->qbuf);
588 		q->next = q2;
589 		q->action = RESTGT_DOALWAYS;
590 		q2->qclass = C_IN;
591 		q2->qtype = T_A;
592 		q2->answer = q2->qbuf.buf;
593 		q2->anslen = sizeof(q2->qbuf);
594 		q2->action = RESTGT_DOALWAYS;
595 		break;
596 	case AF_INET:
597 		q->qclass = C_IN;
598 		q->qtype = T_A;
599 		q->answer = q->qbuf.buf;
600 		q->anslen = sizeof(q->qbuf);
601 		q->action = RESTGT_DOALWAYS;
602 		break;
603 	case AF_INET6:
604 		q->qclass = C_IN;
605 		q->qtype = T_AAAA;
606 		q->answer = q->qbuf.buf;
607 		q->anslen = sizeof(q->qbuf);
608 		q->action = RESTGT_DOALWAYS;
609 		break;
610 	default:
611 		RES_SET_H_ERRNO(pvt->res, NO_RECOVERY); /*%< better error? */
612 		goto cleanup;
613 	}
614 
615 	/*
616 	 * if there aren't any dots, it could be a user-level alias.
617 	 * this is also done in res_nquery() since we are not the only
618 	 * function that looks up host names.
619 	 */
620 	if (!strchr(name, '.') && (cp = res_hostalias(pvt->res, name,
621 						      tmp, sizeof tmp)))
622 		name = cp;
623 
624 	for (p = q; p; p = p->next) {
625 		struct addrinfo *ai;
626 
627 		switch(p->action) {
628 		case RESTGT_DOALWAYS:
629 			break;
630 		case RESTGT_AFTERFAILURE:
631 			if (querystate == RESQRY_SUCCESS)
632 				continue;
633 			break;
634 		case RESTGT_IGNORE:
635 			continue;
636 		}
637 
638 		if ((n = res_nsearch(pvt->res, name, p->qclass, p->qtype,
639 				     p->answer, p->anslen)) < 0) {
640 			querystate = RESQRY_FAIL;
641 			continue;
642 		}
643 		(void)gethostans(this, p->answer, n, name, p->qtype,
644 				 pai->ai_family, /*%< XXX: meaningless */
645 				 0, &ai, pai);
646 		if (ai) {
647 			querystate = RESQRY_SUCCESS;
648 			cur->ai_next = ai;
649 			while (cur->ai_next)
650 				cur = cur->ai_next;
651 		} else
652 			querystate = RESQRY_FAIL;
653 	}
654 
655  cleanup:
656 	if (q != NULL)
657 		memput(q, sizeof(*q));
658 	if (q2 != NULL)
659 		memput(q2, sizeof(*q2));
660 	return(sentinel.ai_next);
661 }
662 
663 static void
664 ho_res_set(struct irs_ho *this, struct __res_state *res,
665 		void (*free_res)(void *)) {
666 	struct pvt *pvt = (struct pvt *)this->private;
667 
668 	if (pvt->res && pvt->free_res) {
669 		res_nclose(pvt->res);
670 		(*pvt->free_res)(pvt->res);
671 	}
672 
673 	pvt->res = res;
674 	pvt->free_res = free_res;
675 }
676 
677 /* Private. */
678 
679 static struct hostent *
680 gethostans(struct irs_ho *this,
681 	   const u_char *ansbuf, int anslen, const char *qname, int qtype,
682 	   int af, int size,	/*!< meaningless for addrinfo cases  */
683 	   struct addrinfo **ret_aip, const struct addrinfo *pai)
684 {
685 	struct pvt *pvt = (struct pvt *)this->private;
686 	int type, class, ancount, qdcount, n, haveanswer, had_error;
687 	int error = NETDB_SUCCESS;
688 	int (*name_ok)(const char *);
689 	const HEADER *hp;
690 	const u_char *eom;
691 	const u_char *eor;
692 	const u_char *cp;
693 	const char *tname;
694 	const char *hname;
695 	char *bp, *ep, **ap, **hap;
696 	char tbuf[MAXDNAME+1];
697 	struct addrinfo sentinel, *cur, ai;
698 
699 	if (pai == NULL) abort();
700 	if (ret_aip != NULL)
701 		*ret_aip = NULL;
702 	memset(&sentinel, 0, sizeof(sentinel));
703 	cur = &sentinel;
704 
705 	tname = qname;
706 	eom = ansbuf + anslen;
707 	switch (qtype) {
708 	case T_A:
709 	case T_AAAA:
710 	case T_ANY:	/*%< use T_ANY only for T_A/T_AAAA lookup */
711 		name_ok = res_hnok;
712 		break;
713 	case T_PTR:
714 		name_ok = res_dnok;
715 		break;
716 	default:
717 		abort();
718 	}
719 
720 	pvt->host.h_addrtype = af;
721 	pvt->host.h_length = size;
722 	hname = pvt->host.h_name = NULL;
723 
724 	/*
725 	 * Find first satisfactory answer.
726 	 */
727 	if (ansbuf + HFIXEDSZ > eom) {
728 		RES_SET_H_ERRNO(pvt->res, NO_RECOVERY);
729 		return (NULL);
730 	}
731 	hp = (const HEADER *)ansbuf;
732 	ancount = ntohs(hp->ancount);
733 	qdcount = ntohs(hp->qdcount);
734 	bp = pvt->hostbuf;
735 	ep = pvt->hostbuf + sizeof(pvt->hostbuf);
736 	cp = ansbuf + HFIXEDSZ;
737 	if (qdcount != 1) {
738 		RES_SET_H_ERRNO(pvt->res, NO_RECOVERY);
739 		return (NULL);
740 	}
741 	n = dn_expand(ansbuf, eom, cp, bp, ep - bp);
742 	if (n < 0 || !maybe_ok(pvt->res, bp, name_ok)) {
743 		RES_SET_H_ERRNO(pvt->res, NO_RECOVERY);
744 		return (NULL);
745 	}
746 	cp += n + QFIXEDSZ;
747 	if (cp > eom) {
748 		RES_SET_H_ERRNO(pvt->res, NO_RECOVERY);
749 		return (NULL);
750 	}
751 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
752 		/* res_nsend() has already verified that the query name is the
753 		 * same as the one we sent; this just gets the expanded name
754 		 * (i.e., with the succeeding search-domain tacked on).
755 		 */
756 		n = strlen(bp) + 1;		/*%< for the \\0 */
757 		if (n > MAXHOSTNAMELEN) {
758 			RES_SET_H_ERRNO(pvt->res, NO_RECOVERY);
759 			return (NULL);
760 		}
761 		pvt->host.h_name = bp;
762 		hname = bp;
763 		bp += n;
764 		/* The qname can be abbreviated, but hname is now absolute. */
765 		qname = pvt->host.h_name;
766 	}
767 	ap = pvt->host_aliases;
768 	*ap = NULL;
769 	pvt->host.h_aliases = pvt->host_aliases;
770 	hap = pvt->h_addr_ptrs;
771 	*hap = NULL;
772 	pvt->host.h_addr_list = pvt->h_addr_ptrs;
773 	haveanswer = 0;
774 	had_error = 0;
775 	while (ancount-- > 0 && cp < eom && !had_error) {
776 		n = dn_expand(ansbuf, eom, cp, bp, ep - bp);
777 		if (n < 0 || !maybe_ok(pvt->res, bp, name_ok)) {
778 			had_error++;
779 			continue;
780 		}
781 		cp += n;			/*%< name */
782 		BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
783 		type = ns_get16(cp);
784 		cp += INT16SZ;			/*%< type */
785 		class = ns_get16(cp);
786 		cp += INT16SZ + INT32SZ;	/*%< class, TTL */
787 		n = ns_get16(cp);
788 		cp += INT16SZ;			/*%< len */
789 		BOUNDS_CHECK(cp, n);
790 		if (class != C_IN) {
791 			cp += n;
792 			continue;
793 		}
794 		eor = cp + n;
795 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
796 		    type == T_CNAME) {
797 			if (haveanswer) {
798 				int level = LOG_CRIT;
799 #ifdef LOG_SECURITY
800 				level |= LOG_SECURITY;
801 #endif
802 				syslog(level,
803  "gethostans: possible attempt to exploit buffer overflow while looking up %s",
804 					*qname ? qname : ".");
805 			}
806 			n = dn_expand(ansbuf, eor, cp, tbuf, sizeof tbuf);
807 			if (n < 0 || !maybe_ok(pvt->res, tbuf, name_ok)) {
808 				had_error++;
809 				continue;
810 			}
811 			cp += n;
812 			/* Store alias. */
813 			if (ap >= &pvt->host_aliases[MAXALIASES-1])
814 				continue;
815 			*ap++ = bp;
816 			n = strlen(bp) + 1;	/*%< for the \\0 */
817 			bp += n;
818 			/* Get canonical name. */
819 			n = strlen(tbuf) + 1;	/*%< for the \\0 */
820 			if (n > (ep - bp) || n > MAXHOSTNAMELEN) {
821 				had_error++;
822 				continue;
823 			}
824 			strcpy(bp, tbuf);	/* (checked) */
825 			pvt->host.h_name = bp;
826 			hname = bp;
827 			bp += n;
828 			continue;
829 		}
830 		if (qtype == T_PTR && type == T_CNAME) {
831 			n = dn_expand(ansbuf, eor, cp, tbuf, sizeof tbuf);
832 			if (n < 0 || !maybe_dnok(pvt->res, tbuf)) {
833 				had_error++;
834 				continue;
835 			}
836 			cp += n;
837 #ifdef RES_USE_DNAME
838 			if ((pvt->res->options & RES_USE_DNAME) != 0U)
839 #endif
840 			{
841 				/*
842 				 * We may be able to check this regardless
843 				 * of the USE_DNAME bit, but we add the check
844 				 * for now since the DNAME support is
845 				 * experimental.
846 				 */
847 				if (ns_samename(tname, bp) != 1)
848 					continue;
849 			}
850 			/* Get canonical name. */
851 			n = strlen(tbuf) + 1;	/*%< for the \\0 */
852 			if (n > (ep - bp)) {
853 				had_error++;
854 				continue;
855 			}
856 			strcpy(bp, tbuf);	/* (checked) */
857 			tname = bp;
858 			bp += n;
859 			continue;
860 		}
861 		if (qtype == T_ANY) {
862 			if (!(type == T_A || type == T_AAAA)) {
863 				cp += n;
864 				continue;
865 			}
866 		} else if (type != qtype) {
867 			cp += n;
868 			continue;
869 		}
870 		switch (type) {
871 		case T_PTR:
872 			if (ret_aip != NULL) {
873 				/* addrinfo never needs T_PTR */
874 				cp += n;
875 				continue;
876 			}
877 			if (ns_samename(tname, bp) != 1) {
878 				cp += n;
879 				continue;
880 			}
881 			n = dn_expand(ansbuf, eor, cp, bp, ep - bp);
882 			if (n < 0 || !maybe_hnok(pvt->res, bp) ||
883 			    n >= MAXHOSTNAMELEN) {
884 				had_error++;
885 				break;
886 			}
887 			cp += n;
888 			if (!haveanswer) {
889 				pvt->host.h_name = bp;
890 				hname = bp;
891 			}
892 			else if (ap < &pvt->host_aliases[MAXALIASES-1])
893 				*ap++ = bp;
894 			else
895 				n = -1;
896 			if (n != -1) {
897 				n = strlen(bp) + 1;	/*%< for the \\0 */
898 				bp += n;
899 			}
900 			break;
901 		case T_A:
902 		case T_AAAA:
903 			if (ns_samename(hname, bp) != 1) {
904 				cp += n;
905 				continue;
906 			}
907 			if (type == T_A && n != INADDRSZ) {
908 				cp += n;
909 				continue;
910 			}
911 			if (type == T_AAAA && n != IN6ADDRSZ) {
912 				cp += n;
913 				continue;
914 			}
915 
916 			/* make addrinfo. don't overwrite constant PAI */
917 			ai = *pai;
918 			ai.ai_family = (type == T_AAAA) ? AF_INET6 : AF_INET;
919 			cur->ai_next = addr2addrinfo(
920 					(const struct addrinfo *)&ai,
921 					(const char *)cp);
922 			if (cur->ai_next == NULL)
923 				had_error++;
924 
925 			if (!haveanswer) {
926 				int nn;
927 
928 				nn = strlen(bp) + 1;	/*%< for the \\0 */
929 				if (nn >= MAXHOSTNAMELEN) {
930 					cp += n;
931 					had_error++;
932 					continue;
933 				}
934 				pvt->host.h_name = bp;
935 				hname = bp;
936 				bp += nn;
937 			}
938 			/* Ensure alignment. */
939 			bp = (char *)(((u_long)bp + (sizeof(align) - 1)) &
940 				      ~(sizeof(align) - 1));
941 			/* Avoid overflows. */
942 			if (bp + n > &pvt->hostbuf[sizeof(pvt->hostbuf) - 1]) {
943 				had_error++;
944 				continue;
945 			}
946 			if (ret_aip) { /*%< need addrinfo. keep it. */
947 				while (cur->ai_next)
948 					cur = cur->ai_next;
949 			} else if (cur->ai_next) { /*%< need hostent */
950 				struct addrinfo *aip = cur->ai_next;
951 
952 				for (aip = cur->ai_next; aip;
953 				     aip = aip->ai_next) {
954 					int m;
955 
956 					m = add_hostent(pvt, bp, hap, aip);
957 					if (m < 0) {
958 						had_error++;
959 						break;
960 					}
961 					if (m == 0)
962 						continue;
963 					if (hap < &pvt->h_addr_ptrs[MAXADDRS])
964 						hap++;
965 					*hap = NULL;
966 					bp += m;
967 				}
968 
969 				freeaddrinfo(cur->ai_next);
970 				cur->ai_next = NULL;
971 			}
972 			cp += n;
973 			break;
974 		default:
975 			abort();
976 		}
977 		if (!had_error)
978 			haveanswer++;
979 	}
980 	if (haveanswer) {
981 		if (ret_aip == NULL) {
982 			*ap = NULL;
983 			*hap = NULL;
984 
985 			if (pvt->res->nsort && hap != pvt->h_addr_ptrs &&
986 			    qtype == T_A)
987 				addrsort(pvt->res, pvt->h_addr_ptrs,
988 					 hap - pvt->h_addr_ptrs);
989 			if (pvt->host.h_name == NULL) {
990 				n = strlen(qname) + 1;	/*%< for the \\0 */
991 				if (n > (ep - bp) || n >= MAXHOSTNAMELEN)
992 					goto no_recovery;
993 				strcpy(bp, qname);	/* (checked) */
994 				pvt->host.h_name = bp;
995 				bp += n;
996 			}
997 			if (pvt->res->options & RES_USE_INET6)
998 				map_v4v6_hostent(&pvt->host, &bp, ep);
999 			RES_SET_H_ERRNO(pvt->res, NETDB_SUCCESS);
1000 			return (&pvt->host);
1001 		} else {
1002 			if ((pai->ai_flags & AI_CANONNAME) != 0) {
1003 				if (pvt->host.h_name == NULL) {
1004 					sentinel.ai_next->ai_canonname =
1005 						strdup(qname);
1006 				}
1007 				else {
1008 					sentinel.ai_next->ai_canonname =
1009 						strdup(pvt->host.h_name);
1010 				}
1011 			}
1012 			*ret_aip = sentinel.ai_next;
1013 			return(NULL);
1014 		}
1015 	}
1016  no_recovery:
1017 	if (sentinel.ai_next) {
1018 		/* this should be impossible, but check it for safety */
1019 		freeaddrinfo(sentinel.ai_next);
1020 	}
1021 	if (error == NETDB_SUCCESS)
1022 		RES_SET_H_ERRNO(pvt->res, NO_RECOVERY);
1023 	else
1024 		RES_SET_H_ERRNO(pvt->res, error);
1025 	return(NULL);
1026 }
1027 
1028 static int
1029 add_hostent(struct pvt *pvt, char *bp, char **hap, struct addrinfo *ai)
1030 {
1031 	int addrlen;
1032 	char *addrp;
1033 	const char **tap;
1034 	char *obp = bp;
1035 
1036 	switch(ai->ai_addr->sa_family) {
1037 	case AF_INET6:
1038 		addrlen = IN6ADDRSZ;
1039 		addrp = (char *)&((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
1040 		break;
1041 	case AF_INET:
1042 		addrlen = INADDRSZ;
1043 		addrp = (char *)&((struct sockaddr_in *)ai->ai_addr)->sin_addr;
1044 		break;
1045 	default:
1046 		return(-1);	/*%< abort? */
1047 	}
1048 
1049 	/* Ensure alignment. */
1050 	bp = (char *)(((u_long)bp + (sizeof(align) - 1)) &
1051 		      ~(sizeof(align) - 1));
1052 	/* Avoid overflows. */
1053 	if (bp + addrlen > &pvt->hostbuf[sizeof(pvt->hostbuf) - 1])
1054 		return(-1);
1055 	if (hap >= &pvt->h_addr_ptrs[MAXADDRS])
1056 		return(0); /*%< fail, but not treat it as an error. */
1057 	/* Suppress duplicates. */
1058 	for (tap = (const char **)pvt->h_addr_ptrs;
1059 	     *tap != NULL;
1060 	     tap++)
1061 		if (memcmp(*tap, addrp, addrlen) == 0)
1062 			break;
1063 	if (*tap != NULL)
1064 		return (0);
1065 
1066 	memcpy(*hap = bp, addrp, addrlen);
1067 	return((bp + addrlen) - obp);
1068 }
1069 
1070 static void
1071 map_v4v6_hostent(struct hostent *hp, char **bpp, char *ep) {
1072 	char **ap;
1073 
1074 	if (hp->h_addrtype != AF_INET || hp->h_length != INADDRSZ)
1075 		return;
1076 	hp->h_addrtype = AF_INET6;
1077 	hp->h_length = IN6ADDRSZ;
1078 	for (ap = hp->h_addr_list; *ap; ap++) {
1079 		int i = (u_long)*bpp % sizeof(align);
1080 
1081 		if (i != 0)
1082 			i = sizeof(align) - i;
1083 
1084 		if ((ep - *bpp) < (i + IN6ADDRSZ)) {
1085 			/* Out of memory.  Truncate address list here. */
1086 			*ap = NULL;
1087 			return;
1088 		}
1089 		*bpp += i;
1090 		map_v4v6_address(*ap, *bpp);
1091 		*ap = *bpp;
1092 		*bpp += IN6ADDRSZ;
1093 	}
1094 }
1095 
1096 static void
1097 addrsort(res_state statp, char **ap, int num) {
1098 	int i, j, needsort = 0, aval[MAXADDRS];
1099 	char **p;
1100 
1101 	p = ap;
1102 	for (i = 0; i < num; i++, p++) {
1103 		for (j = 0 ; (unsigned)j < statp->nsort; j++)
1104 			if (statp->sort_list[j].addr.s_addr ==
1105 			    (((struct in_addr *)(*p))->s_addr &
1106 			     statp->sort_list[j].mask))
1107 				break;
1108 		aval[i] = j;
1109 		if (needsort == 0 && i > 0 && j < aval[i-1])
1110 			needsort = i;
1111 	}
1112 	if (!needsort)
1113 		return;
1114 
1115 	while (needsort < num) {
1116 		for (j = needsort - 1; j >= 0; j--) {
1117 			if (aval[j] > aval[j+1]) {
1118 				char *hp;
1119 
1120 				i = aval[j];
1121 				aval[j] = aval[j+1];
1122 				aval[j+1] = i;
1123 
1124 				hp = ap[j];
1125 				ap[j] = ap[j+1];
1126 				ap[j+1] = hp;
1127 
1128 			} else
1129 				break;
1130 		}
1131 		needsort++;
1132 	}
1133 }
1134 
1135 static int
1136 init(struct irs_ho *this) {
1137 	struct pvt *pvt = (struct pvt *)this->private;
1138 
1139 	if (!pvt->res && !ho_res_get(this))
1140 		return (-1);
1141 	if (((pvt->res->options & RES_INIT) == 0U) &&
1142 	    res_ninit(pvt->res) == -1)
1143 		return (-1);
1144 	return (0);
1145 }
1146