Import new (much simpler) resolver code from Hybrid.
[ircu2.10.12-pk.git] / ircd / ircd_res.c
1 /*
2  * A rewrite of Darren Reeds original res.c As there is nothing
3  * left of Darrens original code, this is now licensed by the hybrid group.
4  * (Well, some of the function names are the same, and bits of the structs..)
5  * You can use it where it is useful, free even. Buy us a beer and stuff.
6  *
7  * The authors takes no responsibility for any damage or loss
8  * of property which results from the use of this software.
9  *
10  * $Id$
11  *
12  * July 1999 - Rewrote a bunch of stuff here. Change hostent builder code,
13  *     added callbacks and reference counting of returned hostents.
14  *     --Bleep (Thomas Helvey <tomh@inxpress.net>)
15  *
16  * This was all needlessly complicated for irc. Simplified. No more hostent
17  * All we really care about is the IP -> hostname mappings. Thats all. 
18  *
19  * Apr 28, 2003 --cryogen and Dianora
20  */
21
22 #include "client.h"
23 #include "ircd_alloc.h"
24 #include "ircd_log.h"
25 #include "ircd_osdep.h"
26 #include "ircd_reply.h"
27 #include "ircd_string.h"
28 #include "ircd_snprintf.h"
29 #include "ircd.h"
30 #include "numeric.h"
31 #include "fileio.h" /* for fbopen / fbclose / fbputs */
32 #include "s_bsd.h"
33 #include "s_stats.h"
34 #include "send.h"
35 #include "sys.h"
36 #include "res.h"
37 #include "ircd_reslib.h"
38 #include "ircd_addrinfo.h"
39
40 #include <assert.h>
41 #include <string.h>
42 #include <sys/time.h>
43 #include <sys/socket.h>
44 #include <time.h>
45
46 #if (CHAR_BIT != 8)
47 #error this code needs to be able to address individual octets 
48 #endif
49
50 static struct Socket res_socket;
51 static struct Timer res_timeout;
52
53 #define MAXPACKET      1024  /* rfc sez 512 but we expand names so ... */
54 #define RES_MAXALIASES 35    /* maximum aliases allowed */
55 #define RES_MAXADDRS   35    /* maximum addresses allowed */
56 #define AR_TTL         600   /* TTL in seconds for dns cache entries */
57
58 /* RFC 1104/1105 wasn't very helpful about what these fields
59  * should be named, so for now, we'll just name them this way.
60  * we probably should look at what named calls them or something.
61  */
62 #define TYPE_SIZE         (size_t)2
63 #define CLASS_SIZE        (size_t)2
64 #define TTL_SIZE          (size_t)4
65 #define RDLENGTH_SIZE     (size_t)2
66 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
67
68 typedef enum 
69 {
70   REQ_IDLE,  /* We're doing not much at all */
71   REQ_PTR,   /* Looking up a PTR */
72   REQ_A,     /* Looking up an A, possibly because AAAA failed */
73 #ifdef IPV6
74   REQ_AAAA,  /* Looking up an AAAA */
75 #endif
76   REQ_CNAME, /* We got a CNAME in response, we better get a real answer next */
77   REQ_INT    /* ip6.arpa failed, falling back to ip6.int */
78 } request_state;
79
80 struct dlink
81 {
82     struct dlink *prev;
83     struct dlink *next;
84 };
85
86 struct reslist 
87 {
88   struct dlink node;
89   int id;
90   int sent;                /* number of requests sent */
91   request_state state;     /* State the resolver machine is in */
92   time_t ttl;
93   char type;
94   char retries;            /* retry counter */
95   char sends;              /* number of sends (>1 means resent) */
96   char resend;             /* send flag. 0 == dont resend */
97   time_t sentat;
98   time_t timeout;
99   struct irc_ssaddr addr;
100   char *name;
101   struct DNSQuery query;   /* query callback for this request */
102 };
103
104 static struct dlink request_list;
105
106 static void rem_request(struct reslist *request);
107 static struct reslist *make_request(const struct DNSQuery *query);
108 static void do_query_name(const struct DNSQuery *query,
109                           const char* name, struct reslist *request, int);
110 static void do_query_number(const struct DNSQuery *query,
111                             const struct irc_ssaddr *,
112                             struct reslist *request);
113 static void query_name(const char *name, int query_class, int query_type, 
114                        struct reslist *request);
115 static int send_res_msg(const char *buf, int len, int count);
116 static void resend_query(struct reslist *request);
117 static int proc_answer(struct reslist *request, HEADER *header, char *, char *);
118 static struct reslist *find_id(int id);
119 static struct DNSReply *make_dnsreply(struct reslist *request);
120 static void res_readreply(struct Event *ev);
121 static void timeout_resolver(struct Event *notused);
122
123 extern struct irc_ssaddr irc_nsaddr_list[IRCD_MAXNS];
124 extern int irc_nscount;
125 extern char irc_domain[HOSTLEN];
126
127 /*
128  * int
129  * res_ourserver(inp)
130  *      looks up "inp" in irc_nsaddr_list[]
131  * returns:
132  *      0  : not found
133  *      >0 : found
134  * author:
135  *      paul vixie, 29may94
136  *      revised for ircd, cryogen(stu) may03
137  */
138 static int
139 res_ourserver(const struct irc_ssaddr *inp) 
140 {
141 #ifdef IPV6
142   struct sockaddr_in6 *v6;
143   struct sockaddr_in6 *v6in = (struct sockaddr_in6 *)inp;
144 #endif
145   struct sockaddr_in *v4;
146   struct sockaddr_in *v4in = (struct sockaddr_in *)inp; 
147   int ns;
148
149   for (ns = 0;  ns < irc_nscount;  ns++)
150   {
151     const struct irc_ssaddr *srv = &irc_nsaddr_list[ns];
152 #ifdef IPV6
153     v6 = (struct sockaddr_in6 *)srv;
154 #endif
155     v4 = (struct sockaddr_in *)srv;
156
157     /* could probably just memcmp(srv, inp, srv.ss_len) here
158      * but we'll air on the side of caution - stu
159      *
160      */
161     switch (srv->ss.ss_family)
162     {
163 #ifdef IPV6
164       case AF_INET6:
165         if (srv->ss.ss_family == inp->ss.ss_family)
166           if (v6->sin6_port == v6in->sin6_port)
167             if ((memcmp(&v6->sin6_addr.s6_addr, &v6in->sin6_addr.s6_addr, 
168                     sizeof(struct in6_addr)) == 0) || 
169                 (memcmp(&v6->sin6_addr.s6_addr, &in6addr_any, 
170                         sizeof(struct in6_addr)) == 0))
171               return(1);
172         break;
173 #endif
174       case AF_INET:
175         if (srv->ss.ss_family == inp->ss.ss_family)
176           if (v4->sin_port == v4in->sin_port)
177             if ((v4->sin_addr.s_addr == INADDR_ANY) || 
178                 (v4->sin_addr.s_addr == v4in->sin_addr.s_addr))
179               return(1);
180         break;
181       default:
182         break;
183     }
184   }
185
186   return(0);
187 }
188
189 /*
190  * start_resolver - do everything we need to read the resolv.conf file
191  * and initialize the resolver file descriptor if needed
192  */
193 static void
194 start_resolver(void)
195 {
196   irc_res_init();
197
198   if (!request_list.next)
199       request_list.next = request_list.prev = &request_list;
200
201   if (!s_active(&res_socket))
202   {
203     int fd;
204     fd = socket(irc_nsaddr_list[0].ss.ss_family, SOCK_DGRAM, 0);
205     if (fd < 0) {} /* TODO: bail on socket() failure */
206     if (!os_set_nonblocking(fd)) {} /* TODO: bail on failure */
207     if (!socket_add(&res_socket, res_readreply, NULL, SS_DATAGRAM,
208                     SOCK_EVENT_READABLE, fd)) {} /* TODO: bail on socket_add() failure */
209     timer_init(&res_timeout);
210     timer_add(&res_timeout, timeout_resolver, NULL, TT_PERIODIC, 1);
211   }
212 }
213
214 /*
215  * init_resolver - initialize resolver and resolver library
216  */
217 int
218 init_resolver(void)
219 {
220 #ifdef LRAND48
221   srand48(CurrentTime);
222 #endif
223   start_resolver();
224   return(s_fd(&res_socket));
225 }
226
227 /*
228  * restart_resolver - reread resolv.conf, reopen socket
229  */
230 void
231 restart_resolver(void)
232 {
233   start_resolver();
234 }
235
236 /*
237  * add_local_domain - Add the domain to hostname, if it is missing
238  * (as suggested by eps@TOASTER.SFSU.EDU)
239  */
240 void
241 add_local_domain(char* hname, size_t size)
242 {
243   /* try to fix up unqualified names 
244    */
245   if (strchr(hname, '.') == NULL)
246   {
247     if (irc_domain[0])
248     {
249       size_t len = strlen(hname);
250
251       if ((strlen(irc_domain) + len + 2) < size)
252       {
253         hname[len++] = '.';
254         strcpy(hname + len, irc_domain);
255       }
256     }
257   }
258 }
259
260 /*
261  * remove_dlink - remove a link from a doubly linked list
262  */
263 static void
264 remove_dlink(struct dlink *node)
265 {
266     node->prev->next = node->next;
267     node->next->prev = node->prev;
268 }
269
270 /*
271  * add_dlink - add a link to a doubly linked list
272  */
273 static void
274 add_dlink(struct dlink *node, struct dlink *next)
275 {
276     node->prev = next->prev;
277     node->next = next;
278     node->prev->next = node;
279     node->next->prev = node;
280 }
281
282 /*
283  * rem_request - remove a request from the list. 
284  * This must also free any memory that has been allocated for 
285  * temporary storage of DNS results.
286  */
287 static void
288 rem_request(struct reslist *request)
289 {
290   remove_dlink(&request->node);
291   MyFree(request->name);
292   MyFree(request);
293 }
294
295 /*
296  * make_request - Create a DNS request record for the server.
297  */
298 static struct reslist *
299 make_request(const struct DNSQuery* query)
300 {
301   struct reslist *request;
302
303   request = (struct reslist *)MyMalloc(sizeof(struct reslist));
304   memset(request, 0, sizeof(struct reslist));
305
306   request->sentat  = CurrentTime;
307   request->retries = 3;
308   request->resend  = 1;
309   request->timeout = 4;    /* start at 4 and exponential inc. */
310   memset(&request->addr, 0, sizeof(request->addr));
311   request->query.vptr     = query->vptr;
312   request->query.callback = query->callback;
313   request->state          = REQ_IDLE;
314
315   add_dlink(&request->node, &request_list);
316   return(request);
317 }
318
319 /*
320  * timeout_query_list - Remove queries from the list which have been 
321  * there too long without being resolved.
322  */
323 static time_t
324 timeout_query_list(time_t now)
325 {
326   struct dlink *ptr, *next_ptr;
327   struct reslist *request;
328   time_t next_time = 0;
329   time_t timeout   = 0;
330
331   for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
332   {
333     next_ptr = ptr->next;
334     request = (struct reslist*)ptr;
335     timeout = request->sentat + request->timeout;
336
337     if (now >= timeout)
338     {
339       if (--request->retries <= 0)
340       {
341         (*request->query.callback)(request->query.vptr, 0);
342         rem_request(request);
343         continue;
344       }
345       else
346       {
347         request->sentat = now;
348         request->timeout += request->timeout;
349         resend_query(request);
350       }
351     }
352
353     if ((next_time == 0) || timeout < next_time)
354     {
355       next_time = timeout;
356     }
357   }
358
359   return((next_time > now) ? next_time : (now + AR_TTL));
360 }
361
362 /*
363  * timeout_resolver - check request list
364  */
365 static void
366 timeout_resolver(struct Event *notused)
367 {
368   timeout_query_list(CurrentTime);
369 }
370
371 /*
372  * delete_resolver_queries - cleanup outstanding queries 
373  * for which there no longer exist clients or conf lines.
374  */
375 void
376 delete_resolver_queries(const void *vptr)
377 {
378   struct dlink *ptr, *next_ptr;
379   struct reslist *request;
380
381   for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
382   {
383     next_ptr = ptr->next;
384     request = (struct reslist*)ptr;
385     if (vptr == request->query.vptr)
386       rem_request(request);
387   }
388 }
389
390 /*
391  * send_res_msg - sends msg to all nameservers found in the "_res" structure.
392  * This should reflect /etc/resolv.conf. We will get responses
393  * which arent needed but is easier than checking to see if nameserver
394  * isnt present. Returns number of messages successfully sent to 
395  * nameservers or -1 if no successful sends.
396  */
397 static int
398 send_res_msg(const char *msg, int len, int rcount)
399 {
400   int i;
401   int sent = 0;
402   int max_queries = IRCD_MIN(irc_nscount, rcount);
403
404   /* RES_PRIMARY option is not implemented
405    * if (res.options & RES_PRIMARY || 0 == max_queries)
406    */
407   if (max_queries == 0)
408     max_queries = 1;
409
410   for (i = 0; i < max_queries; i++)
411   {
412     if (sendto(s_fd(&res_socket), msg, len, 0, 
413         (struct sockaddr*)&(irc_nsaddr_list[i]), 
414         irc_nsaddr_list[i].ss_len) == len) 
415       ++sent;
416   }
417
418   return(sent);
419 }
420
421 /*
422  * find_id - find a dns request id (id is determined by dn_mkquery)
423  */
424 static struct reslist *
425 find_id(int id)
426 {
427   struct dlink *ptr;
428   struct reslist *request;
429
430   for (ptr = request_list.next; ptr != &request_list; ptr = ptr->next)
431   {
432     request = (struct reslist*)ptr;
433
434     if (request->id == id)
435       return(request);
436   }
437
438   return(NULL);
439 }
440
441 /* 
442  * gethost_byname_type - get host address from name
443  *
444  */
445 void
446 gethost_byname_type(const char *name, const struct DNSQuery *query, int type)
447 {
448   assert(name != 0);
449   do_query_name(query, name, NULL, type);
450 }
451
452 /*
453  * gethost_byname - wrapper for _type - send T_AAAA first
454  */
455 void
456 gethost_byname(const char *name, const struct DNSQuery *query)
457 {
458   gethost_byname_type(name, query, T_AAAA);
459 }
460
461 /*
462  * gethost_byaddr - get host name from address
463  */
464 void
465 gethost_byaddr(const struct irc_ssaddr *addr, const struct DNSQuery *query)
466 {
467   do_query_number(query, addr, NULL);
468 }
469
470 /*
471  * gethost_byinaddr - kludgy hack for IPv4-only compatibility
472  */
473 void
474 gethost_byinaddr(const struct in_addr *addr, const struct DNSQuery *query)
475 {
476   struct irc_ssaddr new_addr;
477   struct sockaddr_in *sin;
478   memset(&new_addr, 0, sizeof(new_addr));
479   sin = (struct sockaddr_in*)&new_addr.ss;
480   sin->sin_family = AF_INET;
481   memcpy(&sin->sin_addr, addr, sizeof(sin->sin_addr));
482   new_addr.ss_len = sizeof(*sin);
483   gethost_byaddr(&new_addr, query);
484 }
485
486 /*
487  * do_query_name - nameserver lookup name
488  */
489 static void
490 do_query_name(const struct DNSQuery *query, const char *name,
491               struct reslist *request, int type)
492 {
493   char host_name[HOSTLEN + 1];
494
495   ircd_strncpy(host_name, name, HOSTLEN);
496   add_local_domain(host_name, HOSTLEN);
497
498   if (request == NULL)
499   {
500     request       = make_request(query);
501     request->name = (char *)MyMalloc(strlen(host_name) + 1);
502     request->type = type;
503     strcpy(request->name, host_name);
504 #ifdef IPV6
505     if (type != T_A)
506       request->state = REQ_AAAA;
507     else
508 #endif
509     request->state = REQ_A;
510   }
511
512   request->type = type;
513   query_name(host_name, C_IN, type, request);
514 }
515
516 /*
517  * do_query_number - Use this to do reverse IP# lookups.
518  */
519 static void
520 do_query_number(const struct DNSQuery *query, const struct irc_ssaddr *addr,
521                 struct reslist *request)
522 {
523   char ipbuf[128];
524   const unsigned char *cp;
525 #ifdef IPV6
526   const char *intarpa;
527 #endif
528   if (addr->ss.ss_family == AF_INET)
529   {
530     struct sockaddr_in *v4 = (struct sockaddr_in *)addr;
531     cp = (const unsigned char*)&v4->sin_addr.s_addr;
532
533     ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
534                   "%u.%u.%u.%u.in-addr.arpa.",
535                   (unsigned int)(cp[3]), (unsigned int)(cp[2]),
536                   (unsigned int)(cp[1]), (unsigned int)(cp[0]));
537   }
538 #ifdef IPV6
539   else if (addr->ss.ss_family == AF_INET6)
540   {
541     struct sockaddr_in6 *v6 = (struct sockaddr_in6 *)addr;
542     cp = (const unsigned char *)&v6->sin6_addr.s6_addr;
543
544     if (request != NULL && request->state == REQ_INT)
545       intarpa = "int";
546     else
547       intarpa = "arpa";
548
549     ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
550                   "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x."
551                   "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.%s.",
552                   (unsigned int)(cp[15]&0xf), (unsigned int)(cp[15]>>4),
553                   (unsigned int)(cp[14]&0xf), (unsigned int)(cp[14]>>4),
554                   (unsigned int)(cp[13]&0xf), (unsigned int)(cp[13]>>4),
555                   (unsigned int)(cp[12]&0xf), (unsigned int)(cp[12]>>4),
556                   (unsigned int)(cp[11]&0xf), (unsigned int)(cp[11]>>4),
557                   (unsigned int)(cp[10]&0xf), (unsigned int)(cp[10]>>4),
558                   (unsigned int)(cp[9]&0xf), (unsigned int)(cp[9]>>4),
559                   (unsigned int)(cp[8]&0xf), (unsigned int)(cp[8]>>4),
560                   (unsigned int)(cp[7]&0xf), (unsigned int)(cp[7]>>4),
561                   (unsigned int)(cp[6]&0xf), (unsigned int)(cp[6]>>4),
562                   (unsigned int)(cp[5]&0xf), (unsigned int)(cp[5]>>4),
563                   (unsigned int)(cp[4]&0xf), (unsigned int)(cp[4]>>4),
564                   (unsigned int)(cp[3]&0xf), (unsigned int)(cp[3]>>4),
565                   (unsigned int)(cp[2]&0xf), (unsigned int)(cp[2]>>4),
566                   (unsigned int)(cp[1]&0xf), (unsigned int)(cp[1]>>4),
567                   (unsigned int)(cp[0]&0xf), (unsigned int)(cp[0]>>4), intarpa);
568   }
569 #endif
570   if (request == NULL)
571   {
572     request       = make_request(query);
573     request->type = T_PTR;
574     memcpy(&request->addr, addr, sizeof(struct irc_ssaddr));
575     request->name = (char *)MyMalloc(HOSTLEN + 1);
576   }
577
578   query_name(ipbuf, C_IN, T_PTR, request);
579 }
580
581 /*
582  * query_name - generate a query based on class, type and name.
583  */
584 static void
585 query_name(const char *name, int query_class, int type,
586            struct reslist *request)
587 {
588   char buf[MAXPACKET];
589   int request_len = 0;
590
591   memset(buf, 0, sizeof(buf));
592
593   if ((request_len = irc_res_mkquery(name, query_class, type, 
594       (unsigned char *)buf, sizeof(buf))) > 0)
595   {
596     HEADER *header = (HEADER *)buf;
597 #ifndef LRAND48
598     int k = 0;
599     struct timeval tv;
600 #endif
601     /*
602      * generate an unique id
603      * NOTE: we don't have to worry about converting this to and from
604      * network byte order, the nameserver does not interpret this value
605      * and returns it unchanged
606      */
607 #ifdef LRAND48
608     do
609     {
610       header->id = (header->id + lrand48()) & 0xffff;
611     } while (find_id(header->id));
612 #else
613     gettimeofday(&tv, NULL);
614
615     do
616     {
617       header->id = (header->id + k + tv.tv_usec) & 0xffff;
618       k++;
619     } while (find_id(header->id));
620 #endif /* LRAND48 */
621     request->id = header->id;
622     ++request->sends;
623
624     request->sent += send_res_msg(buf, request_len, request->sends);
625   }
626 }
627
628 static void
629 resend_query(struct reslist *request)
630 {
631   if (request->resend == 0)
632     return;
633
634   switch(request->type)
635   {
636     case T_PTR:
637       do_query_number(NULL, &request->addr, request);
638       break;
639     case T_A:
640       do_query_name(NULL, request->name, request, request->type);
641       break;
642 #ifdef IPV6
643     case T_AAAA:
644       /* didnt work, try A */
645       if (request->state == REQ_AAAA)
646         do_query_name(NULL, request->name, request, T_A);
647 #endif
648     default:
649       break;
650   }
651 }
652
653 /*
654  * proc_answer - process name server reply
655  */
656 static int
657 proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
658 {
659   char hostbuf[HOSTLEN + 100]; /* working buffer */
660   unsigned char *current;      /* current position in buf */
661   int query_class;             /* answer class */
662   int type;                    /* answer type */
663   int n;                       /* temp count */
664   int rd_length;
665   struct sockaddr_in *v4;      /* conversion */
666 #ifdef IPV6
667   struct sockaddr_in6 *v6;
668 #endif
669   current = (unsigned char *)buf + sizeof(HEADER);
670
671   for (; header->qdcount > 0; --header->qdcount)
672   {
673     if ((n = irc_dn_skipname(current, (unsigned char *)eob)) < 0)
674       break;
675
676     current += (size_t) n + QFIXEDSZ;
677   }
678
679   /*
680    * process each answer sent to us blech.
681    */
682   while (header->ancount > 0 && (char *)current < eob)
683   {
684     header->ancount--;
685
686     n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob, current,
687         hostbuf, sizeof(hostbuf));
688
689     if (n < 0)
690     {
691       /*
692        * broken message
693        */
694       return(0);
695     }
696     else if (n == 0)
697     {
698       /*
699        * no more answers left
700        */
701       return(0);
702     }
703
704     hostbuf[HOSTLEN] = '\0';
705
706     /* With Address arithmetic you have to be very anal
707      * this code was not working on alpha due to that
708      * (spotted by rodder/jailbird/dianora)
709      */
710     current += (size_t) n;
711
712     if (!(((char *)current + ANSWER_FIXED_SIZE) < eob))
713       break;
714
715     type = irc_ns_get16(current);
716     current += TYPE_SIZE;
717
718     query_class = irc_ns_get16(current);
719     current += CLASS_SIZE;
720
721     request->ttl = irc_ns_get32(current);
722     current += TTL_SIZE;
723
724     rd_length = irc_ns_get16(current);
725     current += RDLENGTH_SIZE;
726
727     /* 
728      * Wait to set request->type until we verify this structure 
729      */
730     switch (type)
731     {
732       case T_A:
733         if (request->type != T_A)
734           return(0);
735
736         /*
737          * check for invalid rd_length or too many addresses
738          */
739         if (rd_length != sizeof(struct in_addr))
740           return(0);
741         v4 = (struct sockaddr_in *)&request->addr;
742         request->addr.ss_len = sizeof(struct sockaddr_in);
743         v4->sin_family = AF_INET;
744         memcpy(&v4->sin_addr, current, sizeof(struct in_addr));
745         return(1);
746         break;
747 #ifdef IPV6
748       case T_AAAA:
749         if (request->type != T_AAAA)
750           return(0);
751         if (rd_length != sizeof(struct in6_addr))
752           return(0);
753         request->addr.ss_len = sizeof(struct sockaddr_in6);
754         v6 = (struct sockaddr_in6 *)&request->addr;
755         v6->sin6_family = AF_INET6;
756         memcpy(&v6->sin6_addr, current, sizeof(struct in6_addr));
757         return(1);
758         break;
759 #endif
760       case T_PTR:
761         if (request->type != T_PTR)
762           return(0);
763         n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
764             current, hostbuf, sizeof(hostbuf));
765         if (n < 0)
766           return(0); /* broken message */
767         else if (n == 0)
768           return(0); /* no more answers left */
769
770         ircd_strncpy(request->name, hostbuf, HOSTLEN);
771
772         return(1);
773         break;
774       case T_CNAME: /* first check we already havent started looking 
775                        into a cname */
776         if (request->type != T_PTR) 
777           return(0);
778
779         if (request->state == REQ_CNAME)
780         {
781           n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
782                             current, hostbuf, sizeof(hostbuf));
783
784           if (n < 0)
785             return(0);
786           return(1);
787         }
788
789         request->state = REQ_CNAME;
790         current += rd_length;
791         break;
792         
793       default:
794         /* XXX I'd rather just throw away the entire bogus thing
795          * but its possible its just a broken nameserver with still
796          * valid answers. But lets do some rudimentary logging for now...
797          */
798           log_write(LS_RESOLVER, L_ERROR, 0, "irc_res.c bogus type %d", type);
799         break;
800     }
801   }
802
803   return(1);
804 }
805
806 /*
807  * res_readreply - read a dns reply from the nameserver and process it.
808  */
809 static void
810 res_readreply(struct Event *ev)
811 {
812   struct Socket *sock;
813   char buf[sizeof(HEADER) + MAXPACKET];
814   HEADER *header;
815   struct reslist *request = NULL;
816   struct DNSReply *reply  = NULL;
817   int rc;
818   int answer_count;
819   socklen_t len = sizeof(struct irc_ssaddr);
820   struct irc_ssaddr lsin;
821
822   assert(ev_socket(ev) == &res_socket);
823   sock = ev_socket(ev);
824
825   rc = recvfrom(s_fd(sock), buf, sizeof(buf), 0, (struct sockaddr *)&lsin, &len);
826   /* Better to cast the sizeof instead of rc */
827   if (rc <= (int)(sizeof(HEADER)))
828     return;
829
830   /*
831    * convert DNS reply reader from Network byte order to CPU byte order.
832    */
833   header = (HEADER *)buf;
834   header->ancount = ntohs(header->ancount);
835   header->qdcount = ntohs(header->qdcount);
836   header->nscount = ntohs(header->nscount);
837   header->arcount = ntohs(header->arcount);
838
839   /*
840    * response for an id which we have already received an answer for
841    * just ignore this response.
842    */
843   if (0 == (request = find_id(header->id)))
844     return;
845
846   /*
847    * check against possibly fake replies
848    */
849   if (!res_ourserver(&lsin))
850     return;
851
852   if ((header->rcode != NO_ERRORS) || (header->ancount == 0))
853   {
854     if (SERVFAIL == header->rcode)
855       resend_query(request);
856     else
857     {
858       /* 
859        * If we havent already tried this, and we're looking up AAAA, try A
860        * now
861        */
862
863 #ifdef IPV6
864       if (request->state == REQ_AAAA && request->type == T_AAAA)
865       {
866         request->timeout += 4;
867         resend_query(request);
868       }
869       else if (request->type == T_PTR && request->state != REQ_INT &&
870                request->addr.ss.ss_family == AF_INET6)
871       {
872         request->state = REQ_INT;
873         request->timeout += 4;
874         resend_query(request);
875       }
876       else
877 #endif
878       {
879         /*
880          * If a bad error was returned, we stop here and dont send
881          * send any more (no retries granted).
882          */
883         (*request->query.callback)(request->query.vptr, 0);
884         rem_request(request);
885       } 
886     }
887
888     return;
889   }
890   /*
891    * If this fails there was an error decoding the received packet, 
892    * try it again and hope it works the next time.
893    */
894   answer_count = proc_answer(request, header, buf, buf + rc);
895
896   if (answer_count)
897   {
898     if (request->type == T_PTR)
899     {
900       if (request->name == NULL)
901       {
902         /*
903          * got a PTR response with no name, something bogus is happening
904          * don't bother trying again, the client address doesn't resolve
905          */
906         (*request->query.callback)(request->query.vptr, reply);
907         rem_request(request);
908         return;
909       }
910
911       /*
912        * Lookup the 'authoritative' name that we were given for the
913        * ip#. 
914        *
915        */
916 #ifdef IPV6
917       if (request->addr.ss.ss_family == AF_INET6)
918         gethost_byname_type(request->name, &request->query, T_AAAA);
919       else
920 #endif
921       gethost_byname_type(request->name, &request->query, T_A);
922       rem_request(request);
923     }
924     else
925     {
926       /*
927        * got a name and address response, client resolved
928        */
929       reply = make_dnsreply(request);
930       (*request->query.callback)(request->query.vptr, (reply) ? reply : 0);
931       rem_request(request);
932     }
933   }
934   else if (!request->sent)
935   {
936     /* XXX - we got a response for a query we didn't send with a valid id?
937      * this should never happen, bail here and leave the client unresolved
938      */
939     assert(0);
940
941     /* XXX don't leak it */
942     rem_request(request);
943   }
944 }
945
946 static struct DNSReply *
947 make_dnsreply(struct reslist *request)
948 {
949   struct DNSReply *cp;
950   assert(request != 0);
951
952   cp = (struct DNSReply *)MyMalloc(sizeof(struct DNSReply));
953
954   DupString(cp->h_name, request->name);
955   memcpy(&cp->addr, &request->addr, sizeof(cp->addr));
956   return(cp);
957 }
958
959 void
960 report_dns_servers(struct Client *source_p, struct StatDesc *sd, int stat, char *param)
961 {
962   int i;
963   char ipaddr[128];
964
965   for (i = 0; i < irc_nscount; i++)
966   {
967     irc_getnameinfo((struct sockaddr *)&(irc_nsaddr_list[i]),
968                     irc_nsaddr_list[i].ss_len, ipaddr, sizeof(ipaddr), NULL, 0,
969                     NI_NUMERICHOST);
970     send_reply(source_p, RPL_STATSALINE, ipaddr); 
971   }
972 }
973
974 size_t
975 cres_mem(struct Client* sptr)
976 {
977   struct dlink *dlink;
978   struct reslist *request;
979   size_t request_mem   = 0;
980   int    request_count = 0;
981
982   for (dlink = request_list.next; dlink != &request_list; dlink = dlink->next) {
983     request = (struct reslist*)dlink;
984     request_mem += sizeof(*request);
985     if (request->name)
986       request_mem += strlen(request->name) + 1; 
987     ++request_count;
988   }
989
990   send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
991              ":Resolver: requests %d(%d)", request_count, request_mem);
992   return request_mem;
993 }