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