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