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