feb1d82b8c04f512ed1e105141b84ae616b1d350
[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   if (request_list.next) {
333     for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
334     {
335       next_ptr = ptr->next;
336       request = (struct reslist*)ptr;
337       if (vptr == request->query.vptr) {
338         Debug((DEBUG_DNS, "Removing request %p with vptr %p", request, vptr));
339         rem_request(request);
340       }
341     }
342   }
343 }
344
345 /** Send a message to all of our nameservers.
346  * @param[in] msg Message to send.
347  * @param[in] len Length of message.
348  * @param[in] rcount Maximum number of servers to ask.
349  * @return Number of servers that were successfully asked.
350  */
351 static int
352 send_res_msg(const char *msg, int len, int rcount)
353 {
354   int i;
355   int sent = 0;
356   int max_queries = IRCD_MIN(irc_nscount, rcount);
357
358   /* RES_PRIMARY option is not implemented
359    * if (res.options & RES_PRIMARY || 0 == max_queries)
360    */
361   if (max_queries == 0)
362     max_queries = 1;
363
364   for (i = 0; i < max_queries; i++)
365     if (os_sendto_nonb(s_fd(&res_socket), msg, len, NULL, 0, &irc_nsaddr_list[i]) == IO_SUCCESS)
366       ++sent;
367
368   return(sent);
369 }
370
371 /** Find a DNS request by ID.
372  * @param[in] id Identifier to find.
373  * @return Matching DNS request, or NULL if none are found.
374  */
375 static struct reslist *
376 find_id(int id)
377 {
378   struct dlink *ptr;
379   struct reslist *request;
380
381   for (ptr = request_list.next; ptr != &request_list; ptr = ptr->next)
382   {
383     request = (struct reslist*)ptr;
384
385     if (request->id == id) {
386       Debug((DEBUG_DNS, "find_id(%d) -> %p", id, request));
387       return(request);
388     }
389   }
390
391   Debug((DEBUG_DNS, "find_id(%d) -> NULL", id));
392   return(NULL);
393 }
394
395 /** Try to look up address for a hostname, trying IPv6 (T_AAAA) first.
396  * @param[in] name Hostname to look up.
397  * @param[in] query Callback information.
398  */
399 void
400 gethost_byname(const char *name, const struct DNSQuery *query)
401 {
402   do_query_name(query, name, NULL, T_AAAA);
403 }
404
405 /** Try to look up hostname for an address.
406  * @param[in] addr Address to look up.
407  * @param[in] query Callback information.
408  */
409 void
410 gethost_byaddr(const struct irc_in_addr *addr, const struct DNSQuery *query)
411 {
412   do_query_number(query, addr, NULL);
413 }
414
415 /** Send a query to look up the address for a name.
416  * @param[in] query Callback information.
417  * @param[in] name Hostname to look up.
418  * @param[in] request DNS lookup structure (may be NULL).
419  * @param[in] type Preferred request type.
420  */
421 static void
422 do_query_name(const struct DNSQuery *query, const char *name,
423               struct reslist *request, int type)
424 {
425   char host_name[HOSTLEN + 1];
426
427   ircd_strncpy(host_name, name, HOSTLEN);
428   add_local_domain(host_name, HOSTLEN);
429
430   if (request == NULL)
431   {
432     request       = make_request(query);
433     DupString(request->name, host_name);
434 #ifdef IPV6
435     if (type != T_A)
436       request->state = REQ_AAAA;
437     else
438 #endif
439     request->state = REQ_A;
440   }
441
442   request->type = type;
443   Debug((DEBUG_DNS, "Requesting DNS %s %s as %p", (request->state == REQ_AAAA ? "AAAA" : "A"), host_name, request));
444   query_name(host_name, C_IN, type, request);
445 }
446
447 /** Send a query to look up the name for an address.
448  * @param[in] query Callback information.
449  * @param[in] addr Address to look up.
450  * @param[in] request DNS lookup structure (may be NULL).
451  */
452 static void
453 do_query_number(const struct DNSQuery *query, const struct irc_in_addr *addr,
454                 struct reslist *request)
455 {
456   char ipbuf[128];
457   const unsigned char *cp;
458
459   if (irc_in_addr_is_ipv4(addr))
460   {
461     cp = (const unsigned char*)&addr->in6_16[6];
462     ircd_snprintf(NULL, ipbuf, sizeof(ipbuf), "%u.%u.%u.%u.in-addr.arpa.",
463                   (unsigned int)(cp[3]), (unsigned int)(cp[2]),
464                   (unsigned int)(cp[1]), (unsigned int)(cp[0]));
465   }
466   else
467   {
468     const char *intarpa;
469
470     if (request != NULL && request->state == REQ_INT)
471       intarpa = "int";
472     else
473       intarpa = "arpa";
474
475     cp = (const unsigned char *)&addr->in6_16[0];
476     ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
477                   "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x."
478                   "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.%s.",
479                   (unsigned int)(cp[15]&0xf), (unsigned int)(cp[15]>>4),
480                   (unsigned int)(cp[14]&0xf), (unsigned int)(cp[14]>>4),
481                   (unsigned int)(cp[13]&0xf), (unsigned int)(cp[13]>>4),
482                   (unsigned int)(cp[12]&0xf), (unsigned int)(cp[12]>>4),
483                   (unsigned int)(cp[11]&0xf), (unsigned int)(cp[11]>>4),
484                   (unsigned int)(cp[10]&0xf), (unsigned int)(cp[10]>>4),
485                   (unsigned int)(cp[9]&0xf), (unsigned int)(cp[9]>>4),
486                   (unsigned int)(cp[8]&0xf), (unsigned int)(cp[8]>>4),
487                   (unsigned int)(cp[7]&0xf), (unsigned int)(cp[7]>>4),
488                   (unsigned int)(cp[6]&0xf), (unsigned int)(cp[6]>>4),
489                   (unsigned int)(cp[5]&0xf), (unsigned int)(cp[5]>>4),
490                   (unsigned int)(cp[4]&0xf), (unsigned int)(cp[4]>>4),
491                   (unsigned int)(cp[3]&0xf), (unsigned int)(cp[3]>>4),
492                   (unsigned int)(cp[2]&0xf), (unsigned int)(cp[2]>>4),
493                   (unsigned int)(cp[1]&0xf), (unsigned int)(cp[1]>>4),
494                   (unsigned int)(cp[0]&0xf), (unsigned int)(cp[0]>>4), intarpa);
495   }
496   if (request == NULL)
497   {
498     request       = make_request(query);
499     request->type = T_PTR;
500     memcpy(&request->addr, addr, sizeof(request->addr));
501     request->name = (char *)MyMalloc(HOSTLEN + 1);
502   }
503   Debug((DEBUG_DNS, "Requesting DNS PTR %s as %p", ipbuf, request));
504   query_name(ipbuf, C_IN, T_PTR, request);
505 }
506
507 /** Generate a query based on class, type and name.
508  * @param[in] name Domain name to look up.
509  * @param[in] query_class Query class (see RFC 1035).
510  * @param[in] type Query type (see RFC 1035).
511  * @param[in] request DNS request structure.
512  */
513 static void
514 query_name(const char *name, int query_class, int type,
515            struct reslist *request)
516 {
517   char buf[MAXPACKET];
518   int request_len = 0;
519
520   memset(buf, 0, sizeof(buf));
521
522   if ((request_len = irc_res_mkquery(name, query_class, type,
523       (unsigned char *)buf, sizeof(buf))) > 0)
524   {
525     HEADER *header = (HEADER *)buf;
526
527     /*
528      * generate an unique id
529      * NOTE: we don't have to worry about converting this to and from
530      * network byte order, the nameserver does not interpret this value
531      * and returns it unchanged
532      */
533     do
534     {
535       header->id = (header->id + ircrandom()) & 0xffff;
536     } while (find_id(header->id));
537     request->id = header->id;
538     ++request->sends;
539
540     request->sent += send_res_msg(buf, request_len, request->sends);
541     check_resolver_timeout(request->sentat + request->timeout);
542   }
543 }
544
545 /** Send a failed DNS lookup request again.
546  * @param[in] request Request to resend.
547  */
548 static void
549 resend_query(struct reslist *request)
550 {
551   if (request->resend == 0)
552     return;
553
554   switch(request->type)
555   {
556     case T_PTR:
557       do_query_number(NULL, &request->addr, request);
558       break;
559     case T_A:
560       do_query_name(NULL, request->name, request, request->type);
561       break;
562     case T_AAAA:
563       /* didnt work, try A */
564       if (request->state == REQ_AAAA)
565         do_query_name(NULL, request->name, request, T_A);
566     default:
567       break;
568   }
569 }
570
571 /** Process the answer for a lookup request.
572  * @param[in] request DNS request that got an answer.
573  * @param[in] header Header of DNS response.
574  * @param[in] buf DNS response body.
575  * @param[in] eob Pointer to end of DNS response.
576  * @return Number of answers read from \a buf.
577  */
578 static int
579 proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
580 {
581   char hostbuf[HOSTLEN + 100]; /* working buffer */
582   unsigned char *current;      /* current position in buf */
583   int query_class;             /* answer class */
584   int type;                    /* answer type */
585   int n;                       /* temp count */
586   int rd_length;
587
588   current = (unsigned char *)buf + sizeof(HEADER);
589
590   for (; header->qdcount > 0; --header->qdcount)
591   {
592     if ((n = irc_dn_skipname(current, (unsigned char *)eob)) < 0)
593       break;
594
595     current += (size_t) n + QFIXEDSZ;
596   }
597
598   /*
599    * process each answer sent to us blech.
600    */
601   while (header->ancount > 0 && (char *)current < eob)
602   {
603     header->ancount--;
604
605     n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob, current,
606         hostbuf, sizeof(hostbuf));
607
608     if (n < 0)
609     {
610       /*
611        * broken message
612        */
613       return(0);
614     }
615     else if (n == 0)
616     {
617       /*
618        * no more answers left
619        */
620       return(0);
621     }
622
623     hostbuf[HOSTLEN] = '\0';
624
625     /* With Address arithmetic you have to be very anal
626      * this code was not working on alpha due to that
627      * (spotted by rodder/jailbird/dianora)
628      */
629     current += (size_t) n;
630
631     if (!(((char *)current + ANSWER_FIXED_SIZE) < eob))
632       break;
633
634     type = irc_ns_get16(current);
635     current += TYPE_SIZE;
636
637     query_class = irc_ns_get16(current);
638     current += CLASS_SIZE;
639
640     current += TTL_SIZE;
641
642     rd_length = irc_ns_get16(current);
643     current += RDLENGTH_SIZE;
644
645     /*
646      * Wait to set request->type until we verify this structure
647      */
648     switch (type)
649     {
650       case T_A:
651         if (request->type != T_A)
652           return(0);
653
654         /*
655          * check for invalid rd_length or too many addresses
656          */
657         if (rd_length != sizeof(struct in_addr))
658           return(0);
659         memset(&request->addr, 0, sizeof(request->addr));
660         memcpy(&request->addr.in6_16[6], current, sizeof(struct in_addr));
661         return(1);
662         break;
663       case T_AAAA:
664         if (request->type != T_AAAA)
665           return(0);
666         if (rd_length != sizeof(struct irc_in_addr))
667           return(0);
668         memcpy(&request->addr, current, sizeof(struct irc_in_addr));
669         return(1);
670         break;
671       case T_PTR:
672         if (request->type != T_PTR)
673           return(0);
674         n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
675             current, hostbuf, sizeof(hostbuf));
676         if (n < 0)
677           return(0); /* broken message */
678         else if (n == 0)
679           return(0); /* no more answers left */
680
681         ircd_strncpy(request->name, hostbuf, HOSTLEN);
682
683         return(1);
684         break;
685       case T_CNAME: /* first check we already havent started looking
686                        into a cname */
687         if (request->type != T_PTR)
688           return(0);
689
690         if (request->state == REQ_CNAME)
691         {
692           n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
693                             current, hostbuf, sizeof(hostbuf));
694
695           if (n < 0)
696             return(0);
697           return(1);
698         }
699
700         request->state = REQ_CNAME;
701         current += rd_length;
702         break;
703
704       default:
705         /* XXX I'd rather just throw away the entire bogus thing
706          * but its possible its just a broken nameserver with still
707          * valid answers. But lets do some rudimentary logging for now...
708          */
709           log_write(LS_RESOLVER, L_ERROR, 0, "irc_res.c bogus type %d", type);
710         break;
711     }
712   }
713
714   return(1);
715 }
716
717 /** Read a DNS reply from the nameserver and process it.
718  * @param[in] ev I/O activity event for resolver socket.
719  */
720 static void
721 res_readreply(struct Event *ev)
722 {
723   struct irc_sockaddr lsin;
724   struct Socket *sock;
725   char buf[sizeof(HEADER) + MAXPACKET];
726   HEADER *header;
727   struct reslist *request = NULL;
728   struct DNSReply *reply  = NULL;
729   unsigned int rc;
730   int answer_count;
731
732   assert(ev_socket(ev) == &res_socket);
733   sock = ev_socket(ev);
734
735   if (IO_SUCCESS != os_recvfrom_nonb(s_fd(sock), buf, sizeof(buf), &rc, &lsin)
736       || (rc <= sizeof(HEADER)))
737     return;
738
739   /*
740    * convert DNS reply reader from Network byte order to CPU byte order.
741    */
742   header = (HEADER *)buf;
743   header->ancount = ntohs(header->ancount);
744   header->qdcount = ntohs(header->qdcount);
745   header->nscount = ntohs(header->nscount);
746   header->arcount = ntohs(header->arcount);
747
748   /*
749    * response for an id which we have already received an answer for
750    * just ignore this response.
751    */
752   if (0 == (request = find_id(header->id)))
753     return;
754
755   /*
756    * check against possibly fake replies
757    */
758   if (!res_ourserver(&lsin))
759     return;
760
761   if ((header->rcode != NO_ERRORS) || (header->ancount == 0))
762   {
763     if (SERVFAIL == header->rcode)
764       resend_query(request);
765     else
766     {
767       /*
768        * If we havent already tried this, and we're looking up AAAA, try A
769        * now
770        */
771
772       if (request->state == REQ_AAAA && request->type == T_AAAA)
773       {
774         request->timeout += feature_int(FEAT_IRCD_RES_TIMEOUT);
775         resend_query(request);
776       }
777       else if (request->type == T_PTR && request->state != REQ_INT &&
778                !irc_in_addr_is_ipv4(&request->addr))
779       {
780         request->state = REQ_INT;
781         request->timeout += feature_int(FEAT_IRCD_RES_TIMEOUT);
782         resend_query(request);
783       }
784       else
785       {
786         /*
787          * If a bad error was returned, we stop here and dont send
788          * send any more (no retries granted).
789          */
790           Debug((DEBUG_DNS, "Request %p has bad response (state %d type %d)", request, request->state, request->type));
791         (*request->query.callback)(request->query.vptr, 0);
792         rem_request(request);
793       }
794     }
795
796     return;
797   }
798   /*
799    * If this fails there was an error decoding the received packet,
800    * try it again and hope it works the next time.
801    */
802   answer_count = proc_answer(request, header, buf, buf + rc);
803
804   if (answer_count)
805   {
806     if (request->type == T_PTR)
807     {
808       if (request->name == NULL)
809       {
810         /*
811          * got a PTR response with no name, something bogus is happening
812          * don't bother trying again, the client address doesn't resolve
813          */
814         Debug((DEBUG_DNS, "Request %p PTR had empty name", request));
815         (*request->query.callback)(request->query.vptr, reply);
816         rem_request(request);
817         return;
818       }
819
820       /*
821        * Lookup the 'authoritative' name that we were given for the
822        * ip#.
823        */
824 #ifdef IPV6
825       if (!irc_in_addr_is_ipv4(&request->addr))
826         do_query_name(&request->query, request->name, NULL, T_AAAA);
827       else
828 #endif
829       do_query_name(&request->query, request->name, NULL, T_A);
830       Debug((DEBUG_DNS, "Request %p switching to forward resolution", request));
831       rem_request(request);
832     }
833     else
834     {
835       /*
836        * got a name and address response, client resolved
837        */
838       reply = make_dnsreply(request);
839       (*request->query.callback)(request->query.vptr, (reply) ? reply : 0);
840       Debug((DEBUG_DNS, "Request %p got forward resolution", request));
841       rem_request(request);
842     }
843   }
844   else if (!request->sent)
845   {
846     /* XXX - we got a response for a query we didn't send with a valid id?
847      * this should never happen, bail here and leave the client unresolved
848      */
849     assert(0);
850
851     /* XXX don't leak it */
852     Debug((DEBUG_DNS, "Request %p was unexpected(!)", request));
853     rem_request(request);
854   }
855 }
856
857 /** Build a DNSReply for a completed request.
858  * @param[in] request Completed DNS request.
859  * @return Newly allocated DNSReply containing host name and address.
860  */
861 static struct DNSReply *
862 make_dnsreply(struct reslist *request)
863 {
864   struct DNSReply *cp;
865   assert(request != 0);
866
867   cp = (struct DNSReply *)MyMalloc(sizeof(struct DNSReply));
868
869   DupString(cp->h_name, request->name);
870   memcpy(&cp->addr, &request->addr, sizeof(cp->addr));
871   return(cp);
872 }
873
874 /** Statistics callback to list DNS servers.
875  * @param[in] source_p Client requesting statistics.
876  * @param[in] sd Stats descriptor for request (ignored).
877  * @param[in] param Extra parameter from user (ignored).
878  */
879 void
880 report_dns_servers(struct Client *source_p, const struct StatDesc *sd, char *param)
881 {
882   int i;
883   char ipaddr[128];
884
885   for (i = 0; i < irc_nscount; i++)
886   {
887     ircd_ntoa_r(ipaddr, &irc_nsaddr_list[i].addr);
888     send_reply(source_p, RPL_STATSALINE, ipaddr);
889   }
890 }
891
892 /** Report memory usage to a client.
893  * @param[in] sptr Client requesting information.
894  * @return Total memory used by pending requests.
895  */
896 size_t
897 cres_mem(struct Client* sptr)
898 {
899   struct dlink *dlink;
900   struct reslist *request;
901   size_t request_mem   = 0;
902   int    request_count = 0;
903
904   if (request_list.next) {
905     for (dlink = request_list.next; dlink != &request_list; dlink = dlink->next) {
906       request = (struct reslist*)dlink;
907       request_mem += sizeof(*request);
908       if (request->name)
909         request_mem += strlen(request->name) + 1;
910       ++request_count;
911     }
912   }
913
914   send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
915              ":Resolver: requests %d(%d)", request_count, request_mem);
916   return request_mem;
917 }
918
919 /** Check whether an address looks valid.
920  * This means not all 0s and not all 1s.
921  * @param[in] addr Address to check for validity.
922  * @return Non-zero if the address looks valid.
923  */
924 int irc_in_addr_valid(const struct irc_in_addr *addr)
925 {
926   unsigned int ii;
927   unsigned short val;
928
929   val = addr->in6_16[0];
930   if (val != 0 && val != 0xffff)
931     return 1;
932   for (ii = 1; ii < 8; ii++)
933     if (addr->in6_16[ii] != val)
934       return 1;
935   return 0;
936 }
937
938 /** Compare two IP addresses.
939  * @param[in] a First address to compare.
940  * @param[in] b Second address to compare.
941  * @return Non-zero if the two addresses differ, zero if they are identical.
942  */
943 int irc_in_addr_cmp(const struct irc_in_addr *a, const struct irc_in_addr *b)
944 {
945   if (irc_in_addr_is_ipv4(a))
946     return a->in6_16[6] != b->in6_16[6]
947         || a->in6_16[7] != b->in6_16[7]
948         || !irc_in_addr_is_ipv4(b);
949   else
950     return memcmp(a, b, sizeof(*a));
951 }
952
953 /** Indicate whether an IP address is a loopback address.
954  * @param[in] addr Address to check.
955  * @return Non-zero if the address is loopback; zero if not.
956  */
957 int irc_in_addr_is_loopback(const struct irc_in_addr *addr)
958 {
959   if (addr->in6_16[0] != 0
960     || addr->in6_16[1] != 0
961     || addr->in6_16[2] != 0
962     || addr->in6_16[3] != 0
963     || addr->in6_16[4] != 0)
964     return 0;
965   if ((addr->in6_16[5] == 0xffff) || (addr->in6_16[5] == 0 && addr->in6_16[6] != 0))
966     return (ntohs(addr->in6_16[6]) & 0xff00) == 0x7f00;
967   else
968     return addr->in6_16[5] == 0 && addr->in6_16[6] == 0 && htons(addr->in6_16[7]) == 1;
969 }