Fix DNS-related timer assertion failure.
[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  * July 1999 - Rewrote a bunch of stuff here. Change hostent builder code,
11  *     added callbacks and reference counting of returned hostents.
12  *     --Bleep (Thomas Helvey <tomh@inxpress.net>)
13  *
14  * This was all needlessly complicated for irc. Simplified. No more hostent
15  * All we really care about is the IP -> hostname mappings. Thats all.
16  *
17  * Apr 28, 2003 --cryogen and Dianora
18  */
19 /** @file
20  * @brief IRC resolver functions.
21  * @version $Id$
22  */
23
24 #include "client.h"
25 #include "ircd_alloc.h"
26 #include "ircd_log.h"
27 #include "ircd_osdep.h"
28 #include "ircd_reply.h"
29 #include "ircd_string.h"
30 #include "ircd_snprintf.h"
31 #include "ircd.h"
32 #include "numeric.h"
33 #include "fileio.h" /* for fbopen / fbclose / fbputs */
34 #include "random.h"
35 #include "s_bsd.h"
36 #include "s_debug.h"
37 #include "s_stats.h"
38 #include "send.h"
39 #include "sys.h"
40 #include "res.h"
41 #include "ircd_reslib.h"
42
43 /* #include <assert.h> -- Now using assert in ircd_log.h */
44 #include <string.h>
45 #include <sys/time.h>
46 #include <sys/socket.h>
47 #include <time.h>
48
49 #if (CHAR_BIT != 8)
50 #error this code needs to be able to address individual octets 
51 #endif
52
53 /** IPv4 resolver UDP socket. */
54 static struct Socket res_socket_v4;
55 /** IPv6 resolver UDP socket. */
56 static struct Socket res_socket_v6;
57 /** Next DNS lookup timeout. */
58 static struct Timer res_timeout;
59 /** Check for whether the resolver has been initialized yet. */
60 #define resolver_started() (request_list.next != NULL)
61
62 /** Maximum DNS packet length.
63  * RFC says 512, but we add extra for expanded names.
64  */
65 #define MAXPACKET      1024
66 #define AR_TTL         600   /**< TTL in seconds for dns cache entries */
67
68 /* RFC 1104/1105 wasn't very helpful about what these fields
69  * should be named, so for now, we'll just name them this way.
70  * we probably should look at what named calls them or something.
71  */
72 /** Size of TYPE field of a DNS RR header. */
73 #define TYPE_SIZE         (size_t)2
74 /** Size of CLASS field of a DNS RR header. */
75 #define CLASS_SIZE        (size_t)2
76 /** Size of TTL field of a DNS RR header. */
77 #define TTL_SIZE          (size_t)4
78 /** Size of RDLENGTH field of a DNS RR header. */
79 #define RDLENGTH_SIZE     (size_t)2
80 /** Size of fixed-format part of a DNS RR header. */
81 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
82
83 /** Current request state. */
84 typedef enum
85 {
86   REQ_IDLE,  /**< We're doing not much at all. */
87   REQ_PTR,   /**< Looking up a PTR. */
88   REQ_A,     /**< Looking up an A, possibly because AAAA failed. */
89   REQ_AAAA,  /**< Looking up an AAAA. */
90   REQ_CNAME, /**< We got a CNAME in response, we better get a real answer next. */
91   REQ_INT    /**< ip6.arpa failed, falling back to ip6.int. */
92 } request_state;
93
94 /** Doubly linked list node. */
95 struct dlink
96 {
97     struct dlink *prev; /**< Previous element in list. */
98     struct dlink *next; /**< Next element in list. */
99 };
100
101 /** A single resolver request.
102  * (Do not be fooled by the "list" in the name.)
103  */
104 struct reslist
105 {
106   struct dlink node;       /**< Doubly linked list node. */
107   int id;                  /**< Request ID (from request header). */
108   int sent;                /**< Number of requests sent. */
109   request_state state;     /**< State the resolver machine is in. */
110   char type;               /**< Current request type. */
111   char retries;            /**< Retry counter. */
112   char sends;              /**< Number of sends (>1 means resent). */
113   char resend;             /**< Send flag; 0 == don't resend. */
114   time_t sentat;           /**< Timestamp we last sent this request. */
115   time_t timeout;          /**< When this request times out. */
116   struct irc_in_addr addr; /**< Address for this request. */
117   char *name;              /**< Hostname for this request. */
118   struct DNSQuery query;   /**< Query callback for this request. */
119 };
120
121 /** Base of request list. */
122 static struct dlink request_list;
123
124 static void rem_request(struct reslist *request);
125 static struct reslist *make_request(const struct DNSQuery *query);
126 static void do_query_name(const struct DNSQuery *query,
127                           const char* name, struct reslist *request, int);
128 static void do_query_number(const struct DNSQuery *query,
129                             const struct irc_in_addr *,
130                             struct reslist *request);
131 static void query_name(const char *name, int query_class, int query_type,
132                        struct reslist *request);
133 static int send_res_msg(const char *buf, int len, int count);
134 static void resend_query(struct reslist *request);
135 static int proc_answer(struct reslist *request, HEADER *header, char *, char *);
136 static struct reslist *find_id(int id);
137 static struct DNSReply *make_dnsreply(struct reslist *request);
138 static void res_readreply(struct Event *ev);
139 static void timeout_resolver(struct Event *notused);
140
141 extern struct irc_sockaddr irc_nsaddr_list[IRCD_MAXNS];
142 extern int irc_nscount;
143 extern char irc_domain[HOSTLEN];
144
145 /** Check whether \a inp is a nameserver we use.
146  * @param[in] inp Nameserver address.
147  * @return Non-zero if we trust \a inp; zero if not.
148  */
149 static int
150 res_ourserver(const struct irc_sockaddr *inp)
151 {
152   int ns;
153
154   for (ns = 0;  ns < irc_nscount;  ns++)
155     if (!irc_in_addr_cmp(&inp->addr, &irc_nsaddr_list[ns].addr)
156         && inp->port == irc_nsaddr_list[ns].port)
157       return 1;
158
159   return(0);
160 }
161
162 /** Start (or re-start) resolver.
163  * This means read resolv.conf, initialize the list of pending
164  * requests, open the resolver socket and initialize its timeout.
165  */
166 void
167 restart_resolver(void)
168 {
169   irc_res_init();
170
171   if (!request_list.next)
172     request_list.next = request_list.prev = &request_list;
173
174   if (!s_active(&res_socket_v4))
175   {
176     int fd = os_socket(&VirtualHost_v4, SOCK_DGRAM, "Resolver UDPv4 socket");
177     if (fd >= 0)
178       socket_add(&res_socket_v4, res_readreply, NULL,
179                  SS_DATAGRAM, SOCK_EVENT_READABLE, fd);
180   }
181
182   if (!s_active(&res_socket_v6))
183   {
184     int fd = os_socket(&VirtualHost_v6, SOCK_DGRAM, "Resolver UDPv6 socket");
185     if (fd >= 0)
186       socket_add(&res_socket_v6, res_readreply, NULL,
187                  SS_DATAGRAM, SOCK_EVENT_READABLE, fd);
188   }
189
190   if (s_active(&res_socket_v4) || s_active(&res_socket_v6))
191     timer_init(&res_timeout);
192 }
193
194 /** Append local domain to hostname if needed.
195  * If \a hname does not contain any '.'s, append #irc_domain to it.
196  * @param[in,out] hname Hostname to check.
197  * @param[in] size Length of \a hname buffer.
198  */
199 void
200 add_local_domain(char* hname, size_t size)
201 {
202   /* try to fix up unqualified names 
203    */
204   if (strchr(hname, '.') == NULL)
205   {
206     if (irc_domain[0])
207     {
208       size_t len = strlen(hname);
209
210       if ((strlen(irc_domain) + len + 2) < size)
211       {
212         hname[len++] = '.';
213         strcpy(hname + len, irc_domain);
214       }
215     }
216   }
217 }
218
219 /** Add a node to a doubly linked list.
220  * @param[in,out] node Node to add to list.
221  * @param[in,out] next Add \a node before this one.
222  */
223 static void
224 add_dlink(struct dlink *node, struct dlink *next)
225 {
226     node->prev = next->prev;
227     node->next = next;
228     node->prev->next = node;
229     node->next->prev = node;
230 }
231
232 /** Remove a request from the list and free it.
233  * @param[in] request Node to free.
234  */
235 static void
236 rem_request(struct reslist *request)
237 {
238   /* remove from dlist */
239   request->node.prev->next = request->node.next;
240   request->node.next->prev = request->node.prev;
241   /* free memory */
242   MyFree(request->name);
243   MyFree(request);
244 }
245
246 /** Create a DNS request record for the server.
247  * @param[in] query Callback information for caller.
248  * @return Newly allocated and linked-in reslist.
249  */
250 static struct reslist *
251 make_request(const struct DNSQuery* query)
252 {
253   struct reslist *request;
254
255   if (!resolver_started())
256     restart_resolver();
257
258   request = (struct reslist *)MyMalloc(sizeof(struct reslist));
259   memset(request, 0, sizeof(struct reslist));
260
261   request->state   = REQ_IDLE;
262   request->sentat  = CurrentTime;
263   request->retries = feature_int(FEAT_IRCD_RES_RETRIES);
264   request->resend  = 1;
265   request->timeout = feature_int(FEAT_IRCD_RES_TIMEOUT);
266   memset(&request->addr, 0, sizeof(request->addr));
267   memcpy(&request->query, query, sizeof(request->query));
268
269   add_dlink(&request->node, &request_list);
270   return(request);
271 }
272
273 /** Make sure that a timeout event will happen by the given time.
274  * @param[in] when Latest time for timeout to run.
275  */
276 static void
277 check_resolver_timeout(time_t when)
278 {
279   if (when > CurrentTime + AR_TTL)
280     when = CurrentTime + AR_TTL;
281   if (t_onqueue(&res_timeout))
282     timer_chg(&res_timeout, TT_ABSOLUTE, when);
283   else
284     timer_add(&res_timeout, timeout_resolver, NULL, TT_ABSOLUTE, when);
285 }
286
287 /** Drop pending DNS lookups which have timed out.
288  * @param[in] notused Timer event data (ignored).
289  */
290 static void
291 timeout_resolver(struct Event *ev)
292 {
293   struct dlink *ptr, *next_ptr;
294   struct reslist *request;
295   time_t next_time = 0;
296   time_t timeout   = 0;
297
298   if (ev_type(ev) != ET_EXPIRE)
299     return;
300
301   for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
302   {
303     next_ptr = ptr->next;
304     request = (struct reslist*)ptr;
305     timeout = request->sentat + request->timeout;
306
307     if (CurrentTime >= timeout)
308     {
309       if (--request->retries <= 0)
310       {
311         Debug((DEBUG_DNS, "Request %p out of retries; destroying", request));
312         (*request->query.callback)(request->query.vptr, 0);
313         rem_request(request);
314         continue;
315       }
316       else
317       {
318         request->sentat = CurrentTime;
319         request->timeout += request->timeout;
320         resend_query(request);
321       }
322     }
323
324     if ((next_time == 0) || timeout < next_time)
325     {
326       next_time = timeout;
327     }
328   }
329
330   if (next_time <= CurrentTime)
331     next_time = CurrentTime + AR_TTL;
332   check_resolver_timeout(next_time);
333 }
334
335 /** Drop queries that are associated with a particular pointer.
336  * This is used to clean up lookups for clients or conf blocks
337  * that went away.
338  * @param[in] vptr User callback pointer to search for.
339  */
340 void
341 delete_resolver_queries(const void *vptr)
342 {
343   struct dlink *ptr, *next_ptr;
344   struct reslist *request;
345
346   if (request_list.next) {
347     for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
348     {
349       next_ptr = ptr->next;
350       request = (struct reslist*)ptr;
351       if (vptr == request->query.vptr) {
352         Debug((DEBUG_DNS, "Removing request %p with vptr %p", request, vptr));
353         rem_request(request);
354       }
355     }
356   }
357 }
358
359 /** Send a message to all of our nameservers.
360  * @param[in] msg Message to send.
361  * @param[in] len Length of message.
362  * @param[in] rcount Maximum number of servers to ask.
363  * @return Number of servers that were successfully asked.
364  */
365 static int
366 send_res_msg(const char *msg, int len, int rcount)
367 {
368   int i;
369   int sent = 0;
370   int max_queries = IRCD_MIN(irc_nscount, rcount);
371
372   /* RES_PRIMARY option is not implemented
373    * if (res.options & RES_PRIMARY || 0 == max_queries)
374    */
375   if (max_queries == 0)
376     max_queries = 1;
377
378   for (i = 0; i < max_queries; i++) {
379     int fd = irc_in_addr_is_ipv4(&irc_nsaddr_list[i].addr) ? s_fd(&res_socket_v4) : s_fd(&res_socket_v6);
380     if (os_sendto_nonb(fd, msg, len, NULL, 0, &irc_nsaddr_list[i]) == IO_SUCCESS)
381       ++sent;
382   }
383
384   return(sent);
385 }
386
387 /** Find a DNS request by ID.
388  * @param[in] id Identifier to find.
389  * @return Matching DNS request, or NULL if none are found.
390  */
391 static struct reslist *
392 find_id(int id)
393 {
394   struct dlink *ptr;
395   struct reslist *request;
396
397   for (ptr = request_list.next; ptr != &request_list; ptr = ptr->next)
398   {
399     request = (struct reslist*)ptr;
400
401     if (request->id == id) {
402       Debug((DEBUG_DNS, "find_id(%d) -> %p", id, request));
403       return(request);
404     }
405   }
406
407   Debug((DEBUG_DNS, "find_id(%d) -> NULL", id));
408   return(NULL);
409 }
410
411 /** Try to look up address for a hostname, trying IPv6 (T_AAAA) first.
412  * @param[in] name Hostname to look up.
413  * @param[in] query Callback information.
414  */
415 void
416 gethost_byname(const char *name, const struct DNSQuery *query)
417 {
418   do_query_name(query, name, NULL, T_AAAA);
419 }
420
421 /** Try to look up hostname for an address.
422  * @param[in] addr Address to look up.
423  * @param[in] query Callback information.
424  */
425 void
426 gethost_byaddr(const struct irc_in_addr *addr, const struct DNSQuery *query)
427 {
428   do_query_number(query, addr, NULL);
429 }
430
431 /** Send a query to look up the address for a name.
432  * @param[in] query Callback information.
433  * @param[in] name Hostname to look up.
434  * @param[in] request DNS lookup structure (may be NULL).
435  * @param[in] type Preferred request type.
436  */
437 static void
438 do_query_name(const struct DNSQuery *query, const char *name,
439               struct reslist *request, int type)
440 {
441   char host_name[HOSTLEN + 1];
442
443   ircd_strncpy(host_name, name, HOSTLEN);
444   add_local_domain(host_name, HOSTLEN);
445
446   if (request == NULL)
447   {
448     request       = make_request(query);
449     DupString(request->name, host_name);
450 #ifdef IPV6
451     if (type != T_A)
452       request->state = REQ_AAAA;
453     else
454 #endif
455     request->state = REQ_A;
456   }
457
458   request->type = type;
459   Debug((DEBUG_DNS, "Requesting DNS %s %s as %p", (request->state == REQ_AAAA ? "AAAA" : "A"), host_name, request));
460   query_name(host_name, C_IN, type, request);
461 }
462
463 /** Send a query to look up the name for an address.
464  * @param[in] query Callback information.
465  * @param[in] addr Address to look up.
466  * @param[in] request DNS lookup structure (may be NULL).
467  */
468 static void
469 do_query_number(const struct DNSQuery *query, const struct irc_in_addr *addr,
470                 struct reslist *request)
471 {
472   char ipbuf[128];
473   const unsigned char *cp;
474
475   if (irc_in_addr_is_ipv4(addr))
476   {
477     cp = (const unsigned char*)&addr->in6_16[6];
478     ircd_snprintf(NULL, ipbuf, sizeof(ipbuf), "%u.%u.%u.%u.in-addr.arpa.",
479                   (unsigned int)(cp[3]), (unsigned int)(cp[2]),
480                   (unsigned int)(cp[1]), (unsigned int)(cp[0]));
481   }
482   else
483   {
484     const char *intarpa;
485
486     if (request != NULL && request->state == REQ_INT)
487       intarpa = "int";
488     else
489       intarpa = "arpa";
490
491     cp = (const unsigned char *)&addr->in6_16[0];
492     ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
493                   "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x."
494                   "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.%s.",
495                   (unsigned int)(cp[15]&0xf), (unsigned int)(cp[15]>>4),
496                   (unsigned int)(cp[14]&0xf), (unsigned int)(cp[14]>>4),
497                   (unsigned int)(cp[13]&0xf), (unsigned int)(cp[13]>>4),
498                   (unsigned int)(cp[12]&0xf), (unsigned int)(cp[12]>>4),
499                   (unsigned int)(cp[11]&0xf), (unsigned int)(cp[11]>>4),
500                   (unsigned int)(cp[10]&0xf), (unsigned int)(cp[10]>>4),
501                   (unsigned int)(cp[9]&0xf), (unsigned int)(cp[9]>>4),
502                   (unsigned int)(cp[8]&0xf), (unsigned int)(cp[8]>>4),
503                   (unsigned int)(cp[7]&0xf), (unsigned int)(cp[7]>>4),
504                   (unsigned int)(cp[6]&0xf), (unsigned int)(cp[6]>>4),
505                   (unsigned int)(cp[5]&0xf), (unsigned int)(cp[5]>>4),
506                   (unsigned int)(cp[4]&0xf), (unsigned int)(cp[4]>>4),
507                   (unsigned int)(cp[3]&0xf), (unsigned int)(cp[3]>>4),
508                   (unsigned int)(cp[2]&0xf), (unsigned int)(cp[2]>>4),
509                   (unsigned int)(cp[1]&0xf), (unsigned int)(cp[1]>>4),
510                   (unsigned int)(cp[0]&0xf), (unsigned int)(cp[0]>>4), intarpa);
511   }
512   if (request == NULL)
513   {
514     request       = make_request(query);
515     request->state= REQ_PTR;
516     request->type = T_PTR;
517     memcpy(&request->addr, addr, sizeof(request->addr));
518     request->name = (char *)MyMalloc(HOSTLEN + 1);
519   }
520   Debug((DEBUG_DNS, "Requesting DNS PTR %s as %p", ipbuf, request));
521   query_name(ipbuf, C_IN, T_PTR, request);
522 }
523
524 /** Generate a query based on class, type and name.
525  * @param[in] name Domain name to look up.
526  * @param[in] query_class Query class (see RFC 1035).
527  * @param[in] type Query type (see RFC 1035).
528  * @param[in] request DNS request structure.
529  */
530 static void
531 query_name(const char *name, int query_class, int type,
532            struct reslist *request)
533 {
534   char buf[MAXPACKET];
535   int request_len = 0;
536
537   memset(buf, 0, sizeof(buf));
538
539   if ((request_len = irc_res_mkquery(name, query_class, type,
540       (unsigned char *)buf, sizeof(buf))) > 0)
541   {
542     HEADER *header = (HEADER *)buf;
543
544     /*
545      * generate an unique id
546      * NOTE: we don't have to worry about converting this to and from
547      * network byte order, the nameserver does not interpret this value
548      * and returns it unchanged
549      */
550     do
551     {
552       header->id = (header->id + ircrandom()) & 0xffff;
553     } while (find_id(header->id));
554     request->id = header->id;
555     ++request->sends;
556
557     request->sent += send_res_msg(buf, request_len, request->sends);
558     check_resolver_timeout(request->sentat + request->timeout);
559   }
560 }
561
562 /** Send a failed DNS lookup request again.
563  * @param[in] request Request to resend.
564  */
565 static void
566 resend_query(struct reslist *request)
567 {
568   if (request->resend == 0)
569     return;
570
571   switch(request->type)
572   {
573     case T_PTR:
574       do_query_number(NULL, &request->addr, request);
575       break;
576     case T_A:
577       do_query_name(NULL, request->name, request, request->type);
578       break;
579     case T_AAAA:
580       /* didn't work, try A */
581       if (request->state == REQ_AAAA)
582         do_query_name(NULL, request->name, request, T_A);
583     default:
584       break;
585   }
586 }
587
588 /** Process the answer for a lookup request.
589  * @param[in] request DNS request that got an answer.
590  * @param[in] header Header of DNS response.
591  * @param[in] buf DNS response body.
592  * @param[in] eob Pointer to end of DNS response.
593  * @return Number of answers read from \a buf.
594  */
595 static int
596 proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
597 {
598   char hostbuf[HOSTLEN + 100]; /* working buffer */
599   unsigned char *current;      /* current position in buf */
600   int query_class;             /* answer class */
601   int type;                    /* answer type */
602   int n;                       /* temp count */
603   int rd_length;
604
605   current = (unsigned char *)buf + sizeof(HEADER);
606
607   for (; header->qdcount > 0; --header->qdcount)
608   {
609     if ((n = irc_dn_skipname(current, (unsigned char *)eob)) < 0)
610       break;
611
612     current += (size_t) n + QFIXEDSZ;
613   }
614
615   /*
616    * process each answer sent to us blech.
617    */
618   while (header->ancount > 0 && (char *)current < eob)
619   {
620     header->ancount--;
621
622     n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob, current,
623         hostbuf, sizeof(hostbuf));
624
625     if (n < 0)
626     {
627       /*
628        * broken message
629        */
630       return(0);
631     }
632     else if (n == 0)
633     {
634       /*
635        * no more answers left
636        */
637       return(0);
638     }
639
640     hostbuf[HOSTLEN] = '\0';
641
642     /* With Address arithmetic you have to be very anal
643      * this code was not working on alpha due to that
644      * (spotted by rodder/jailbird/dianora)
645      */
646     current += (size_t) n;
647
648     if (!(((char *)current + ANSWER_FIXED_SIZE) < eob))
649       break;
650
651     type = irc_ns_get16(current);
652     current += TYPE_SIZE;
653
654     query_class = irc_ns_get16(current);
655     current += CLASS_SIZE;
656
657     current += TTL_SIZE;
658
659     rd_length = irc_ns_get16(current);
660     current += RDLENGTH_SIZE;
661
662     /*
663      * Wait to set request->type until we verify this structure
664      */
665     switch (type)
666     {
667       case T_A:
668         if (request->type != T_A)
669           return(0);
670
671         /*
672          * check for invalid rd_length or too many addresses
673          */
674         if (rd_length != sizeof(struct in_addr))
675           return(0);
676         memset(&request->addr, 0, sizeof(request->addr));
677         memcpy(&request->addr.in6_16[6], current, sizeof(struct in_addr));
678         return(1);
679         break;
680       case T_AAAA:
681         if (request->type != T_AAAA)
682           return(0);
683         if (rd_length != sizeof(struct irc_in_addr))
684           return(0);
685         memcpy(&request->addr, current, sizeof(struct irc_in_addr));
686         return(1);
687         break;
688       case T_PTR:
689         if (request->type != T_PTR)
690           return(0);
691         n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
692             current, hostbuf, sizeof(hostbuf));
693         if (n < 0)
694           return(0); /* broken message */
695         else if (n == 0)
696           return(0); /* no more answers left */
697
698         ircd_strncpy(request->name, hostbuf, HOSTLEN);
699
700         return(1);
701         break;
702       case T_CNAME: /* first check we already haven't started looking
703                        into a cname */
704         if (request->type != T_PTR)
705           return(0);
706
707         if (request->state == REQ_CNAME)
708         {
709           n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
710                             current, hostbuf, sizeof(hostbuf));
711
712           if (n < 0)
713             return(0);
714           return(1);
715         }
716
717         request->state = REQ_CNAME;
718         current += rd_length;
719         break;
720
721       default:
722         /* XXX I'd rather just throw away the entire bogus thing
723          * but its possible its just a broken nameserver with still
724          * valid answers. But lets do some rudimentary logging for now...
725          */
726           log_write(LS_RESOLVER, L_ERROR, 0, "irc_res.c bogus type %d", type);
727         break;
728     }
729   }
730
731   return(1);
732 }
733
734 /** Read a DNS reply from the nameserver and process it.
735  * @param[in] ev I/O activity event for resolver socket.
736  */
737 static void
738 res_readreply(struct Event *ev)
739 {
740   struct irc_sockaddr lsin;
741   struct Socket *sock;
742   char buf[sizeof(HEADER) + MAXPACKET];
743   HEADER *header;
744   struct reslist *request = NULL;
745   struct DNSReply *reply  = NULL;
746   unsigned int rc;
747   int answer_count;
748
749   assert((ev_socket(ev) == &res_socket_v4) || (ev_socket(ev) == &res_socket_v6));
750   sock = ev_socket(ev);
751
752   if (IO_SUCCESS != os_recvfrom_nonb(s_fd(sock), buf, sizeof(buf), &rc, &lsin)
753       || (rc <= sizeof(HEADER)))
754     return;
755
756   /*
757    * convert DNS reply reader from Network byte order to CPU byte order.
758    */
759   header = (HEADER *)buf;
760   header->ancount = ntohs(header->ancount);
761   header->qdcount = ntohs(header->qdcount);
762   header->nscount = ntohs(header->nscount);
763   header->arcount = ntohs(header->arcount);
764
765   /*
766    * response for an id which we have already received an answer for
767    * just ignore this response.
768    */
769   if (0 == (request = find_id(header->id)))
770     return;
771
772   /*
773    * check against possibly fake replies
774    */
775   if (!res_ourserver(&lsin))
776     return;
777
778   if ((header->rcode != NO_ERRORS) || (header->ancount == 0))
779   {
780     if (SERVFAIL == header->rcode)
781       resend_query(request);
782     else
783     {
784       /*
785        * If we haven't already tried this, and we're looking up AAAA, try A
786        * now
787        */
788
789       if (request->state == REQ_AAAA && request->type == T_AAAA)
790       {
791         request->timeout += feature_int(FEAT_IRCD_RES_TIMEOUT);
792         resend_query(request);
793       }
794       else if (request->type == T_PTR && request->state != REQ_INT &&
795                !irc_in_addr_is_ipv4(&request->addr))
796       {
797         request->state = REQ_INT;
798         request->timeout += feature_int(FEAT_IRCD_RES_TIMEOUT);
799         resend_query(request);
800       }
801       else
802       {
803         /*
804          * If a bad error was returned, we stop here and don't send
805          * send any more (no retries granted).
806          */
807         Debug((DEBUG_DNS, "Request %p has bad response (state %d type %d rcode %d)", request, request->state, request->type, header->rcode));
808         (*request->query.callback)(request->query.vptr, 0);
809         rem_request(request);
810       }
811     }
812
813     return;
814   }
815   /*
816    * If this fails there was an error decoding the received packet,
817    * try it again and hope it works the next time.
818    */
819   answer_count = proc_answer(request, header, buf, buf + rc);
820
821   if (answer_count)
822   {
823     if (request->type == T_PTR)
824     {
825       if (request->name == NULL)
826       {
827         /*
828          * got a PTR response with no name, something bogus is happening
829          * don't bother trying again, the client address doesn't resolve
830          */
831         Debug((DEBUG_DNS, "Request %p PTR had empty name", request));
832         (*request->query.callback)(request->query.vptr, reply);
833         rem_request(request);
834         return;
835       }
836
837       /*
838        * Lookup the 'authoritative' name that we were given for the
839        * ip#.
840        */
841 #ifdef IPV6
842       if (!irc_in_addr_is_ipv4(&request->addr))
843         do_query_name(&request->query, request->name, NULL, T_AAAA);
844       else
845 #endif
846       do_query_name(&request->query, request->name, NULL, T_A);
847       Debug((DEBUG_DNS, "Request %p switching to forward resolution", request));
848       rem_request(request);
849     }
850     else
851     {
852       /*
853        * got a name and address response, client resolved
854        */
855       reply = make_dnsreply(request);
856       (*request->query.callback)(request->query.vptr, (reply) ? reply : 0);
857       Debug((DEBUG_DNS, "Request %p got forward resolution", request));
858       rem_request(request);
859     }
860   }
861   else if (!request->sent)
862   {
863     /* XXX - we got a response for a query we didn't send with a valid id?
864      * this should never happen, bail here and leave the client unresolved
865      */
866     assert(0);
867
868     /* XXX don't leak it */
869     Debug((DEBUG_DNS, "Request %p was unexpected(!)", request));
870     rem_request(request);
871   }
872 }
873
874 /** Build a DNSReply for a completed request.
875  * @param[in] request Completed DNS request.
876  * @return Newly allocated DNSReply containing host name and address.
877  */
878 static struct DNSReply *
879 make_dnsreply(struct reslist *request)
880 {
881   struct DNSReply *cp;
882   assert(request != 0);
883
884   cp = (struct DNSReply *)MyMalloc(sizeof(struct DNSReply));
885
886   DupString(cp->h_name, request->name);
887   memcpy(&cp->addr, &request->addr, sizeof(cp->addr));
888   return(cp);
889 }
890
891 /** Statistics callback to list DNS servers.
892  * @param[in] source_p Client requesting statistics.
893  * @param[in] sd Stats descriptor for request (ignored).
894  * @param[in] param Extra parameter from user (ignored).
895  */
896 void
897 report_dns_servers(struct Client *source_p, const struct StatDesc *sd, char *param)
898 {
899   int i;
900   char ipaddr[128];
901
902   for (i = 0; i < irc_nscount; i++)
903   {
904     ircd_ntoa_r(ipaddr, &irc_nsaddr_list[i].addr);
905     send_reply(source_p, RPL_STATSALINE, ipaddr);
906   }
907 }
908
909 /** Report memory usage to a client.
910  * @param[in] sptr Client requesting information.
911  * @return Total memory used by pending requests.
912  */
913 size_t
914 cres_mem(struct Client* sptr)
915 {
916   struct dlink *dlink;
917   struct reslist *request;
918   size_t request_mem   = 0;
919   int    request_count = 0;
920
921   if (request_list.next) {
922     for (dlink = request_list.next; dlink != &request_list; dlink = dlink->next) {
923       request = (struct reslist*)dlink;
924       request_mem += sizeof(*request);
925       if (request->name)
926         request_mem += strlen(request->name) + 1;
927       ++request_count;
928     }
929   }
930
931   send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
932              ":Resolver: requests %d(%d)", request_count, request_mem);
933   return request_mem;
934 }