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