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