Author: Kev <klmitch@mit.edu>
[ircu2.10.12-pk.git] / ircd / res.c
1 /*
2  * src/res.c (C)opyright 1992 Darren Reed. All rights reserved.
3  * This file may not be distributed without the author's permission in any
4  * shape or form. The author takes no responsibility for any damage or loss
5  * of property which results from the use of this software.
6  *
7  * $Id$
8  *
9  * July 1999 - Rewrote a bunch of stuff here. Change hostent builder code,
10  *     added callbacks and reference counting of returned hostents.
11  *     --Bleep (Thomas Helvey <tomh@inxpress.net>)
12  */
13 #include "config.h"
14
15 #include "res.h"
16 #include "client.h"
17 #include "ircd.h"
18 #include "ircd_alloc.h"
19 #include "ircd_events.h"
20 #include "ircd_log.h"
21 #include "ircd_osdep.h"
22 #include "ircd_reply.h"
23 #include "ircd_string.h"
24 #include "msg.h"
25 #include "numeric.h"
26 #include "s_bsd.h"
27 #include "s_debug.h"
28 #include "s_misc.h"
29 #include "send.h"
30 #include "sprintf_irc.h"
31 #include "struct.h"
32 #include "support.h"
33 #include "sys.h"
34
35 #include <assert.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <sys/time.h>
40 #include <sys/socket.h>
41 #include <fcntl.h>
42 #include <unistd.h>
43 #include <regex.h>
44
45 #include <arpa/nameser.h>
46 #include <resolv.h>
47 #include <netdb.h>
48 #include <arpa/inet.h>
49
50 #include <limits.h>
51 #if (CHAR_BIT != 8)
52 #error this code needs to be able to address individual octets 
53 #endif
54
55 /*
56  * Some systems do not define INADDR_NONE (255.255.255.255)
57  * INADDR_NONE is actually a valid address, but it should never
58  * be returned from any nameserver.
59  * NOTE: The bit pattern for INADDR_NONE and INADDR_ANY (0.0.0.0) should be 
60  * the same on all hosts so we shouldn't need to use htonl or ntohl to
61  * compare or set the values.
62  */ 
63 #ifndef INADDR_NONE
64 #define INADDR_NONE ((unsigned int) 0xffffffff)
65 #endif
66
67 #define MAXPACKET       1024  /* rfc sez 512 but we expand names so ... */
68 #define RES_MAXALIASES  35    /* maximum aliases allowed */
69 #define RES_MAXADDRS    35    /* maximum addresses allowed */
70 /*
71  * OSF1 doesn't have RES_NOALIASES
72  */
73 #ifndef RES_NOALIASES
74 #define RES_NOALIASES 0
75 #endif
76
77 /*
78  * macros used to calulate offsets into fixed query buffer
79  */
80 #define ALIAS_BLEN  ((RES_MAXALIASES + 1) * sizeof(char*))
81 #define ADDRS_BLEN  ((RES_MAXADDRS + 1) * sizeof(struct in_addr*))
82
83 #define ADDRS_OFFSET   (ALIAS_BLEN + ADDRS_BLEN)
84 #define ADDRS_DLEN     (RES_MAXADDRS * sizeof(struct in_addr))
85 #define NAMES_OFFSET   (ADDRS_OFFSET + ADDRS_DLEN)
86 #define MAXGETHOSTLEN  (NAMES_OFFSET + MAXPACKET)
87
88 #define AR_TTL          600   /* TTL in seconds for dns cache entries */
89
90 /*
91  * the following values should be prime
92  */
93 #define ARES_CACSIZE    307
94 #define MAXCACHED       281
95
96 /*
97  * RFC 1104/1105 wasn't very helpful about what these fields
98  * should be named, so for now, we'll just name them this way.
99  * we probably should look at what named calls them or something.
100  */
101 #define TYPE_SIZE       2
102 #define CLASS_SIZE      2
103 #define TTL_SIZE        4
104 #define RDLENGTH_SIZE   2
105 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
106
107 /*
108  * Building the Hostent
109  * The Hostent struct is arranged like this:
110  *          +-------------------------------+
111  * Hostent: | struct hostent h              |
112  *          |-------------------------------|
113  *          | char *buf                     |
114  *          +-------------------------------+
115  *
116  * allocated:
117  *
118  *          +-------------------------------+
119  * buf:     | h_aliases pointer array       | Max size: ALIAS_BLEN;
120  *          | NULL                          | contains `char *'s
121  *          |-------------------------------|
122  *          | h_addr_list pointer array     | Max size: ADDRS_BLEN;
123  *          | NULL                          | contains `struct in_addr *'s
124  *          |-------------------------------|
125  *          | h_addr_list addresses         | Max size: ADDRS_DLEN;
126  *          |                               | contains `struct in_addr's
127  *          |-------------------------------|
128  *          | storage for hostname strings  | Max size: ALIAS_DLEN;
129  *          +-------------------------------+ contains `char's
130  *
131  *  For requests the size of the h_aliases, and h_addr_list pointer
132  *  array sizes are set to MAXALISES and MAXADDRS respectively, and
133  *  buf is a fixed size with enough space to hold the largest expected
134  *  reply from a nameserver, see RFC 1034 and RFC 1035.
135  *  For cached entries the sizes are dependent on the actual number
136  *  of aliases and addresses. If new aliases and addresses are found
137  *  for cached entries, the buffer is grown and the new entries are added.
138  *  The hostent struct is filled in with the addresses of the entries in
139  *  the Hostent buf as follows:
140  *  h_name      - contains a pointer to the start of the hostname string area,
141  *                or NULL if none is set.  The h_name is followed by the
142  *                aliases, in the storage for hostname strings area.
143  *  h_aliases   - contains a pointer to the start of h_aliases pointer array.
144  *                This array contains pointers to the storage for hostname
145  *                strings area and is terminated with a NULL.  The first alias
146  *                is stored directly after the h_name.
147  *  h_addr_list - contains a pointer to the start of h_addr_list pointer array.
148  *                This array contains pointers to in_addr structures in the
149  *                h_addr_list addresses area and is terminated with a NULL.
150  *
151  *  Filling the buffer this way allows for proper alignment of the h_addr_list
152  *  addresses.
153  *
154  *  This arrangement allows us to alias a Hostent struct pointer as a
155  *  real struct hostent* without lying. It also allows us to change the
156  *  values contained in the cached entries and requests without changing
157  *  the actual hostent pointer, which is saved in a client struct and can't
158  *  be changed without blowing things up or a lot more fiddling around.
159  *  It also allows for defered allocation of the fixed size buffers until
160  *  they are really needed.
161  *  Nov. 17, 1997 --Bleep
162  */
163
164 struct Hostent {
165   struct hostent h;      /* the hostent struct we are passing around */
166   char*          buf;    /* buffer for data pointed to from hostent */
167 };
168
169 struct ResRequest {
170   struct ResRequest* next;
171   int                id;
172   int                sent;          /* number of requests sent */
173   time_t             ttl;
174   char               type;
175   char               retries;       /* retry counter */
176   char               sends;         /* number of sends (>1 means resent) */
177   char               resend;        /* send flag. 0 == dont resend */
178   time_t             sentat;
179   time_t             timeout;
180   struct in_addr     addr;
181   char*              name;
182   struct DNSQuery    query;         /* query callback for this request */
183   struct Hostent     he;
184 };
185
186 struct CacheEntry {
187   struct CacheEntry* hname_next;
188   struct CacheEntry* hnum_next;
189   struct CacheEntry* list_next;
190   time_t             expireat;
191   time_t             ttl;
192   struct Hostent     he;
193   struct DNSReply    reply;
194 };
195
196 struct CacheTable {
197   struct CacheEntry* num_list;
198   struct CacheEntry* name_list;
199 };
200
201
202 int ResolverFileDescriptor    = -1;   /* GLOBAL - used in s_bsd.c */
203
204 static struct Socket resSock;           /* Socket describing resolver */
205 static struct Timer  resExpireDNS;      /* Timer for DNS expiration */
206 static struct Timer  resExpireCache;    /* Timer for cache expiration */
207
208 static time_t nextDNSCheck    = 0;
209 static time_t nextCacheExpire = 1;
210
211 /*
212  * Keep a spare file descriptor open. res_init calls fopen to read the
213  * resolv.conf file. If ircd is hogging all the file descriptors below 256,
214  * on systems with crippled FILE structures this will cause wierd bugs.
215  * This is definitely needed for Solaris which uses an unsigned char to
216  * hold the file descriptor.  --Dianora
217  */ 
218 static int                spare_fd = -1;
219
220 static int                cachedCount = 0;
221 static struct CacheTable  hashtable[ARES_CACSIZE];
222 static struct CacheEntry* cacheTop;
223 static struct ResRequest* requestListHead;   /* head of resolver request list */
224 static struct ResRequest* requestListTail;   /* tail of resolver request list */
225
226
227 static void     add_request(struct ResRequest* request);
228 static void     rem_request(struct ResRequest* request);
229 static struct ResRequest*   make_request(const struct DNSQuery* query);
230 static time_t   timeout_query_list(time_t now);
231 static time_t   expire_cache(time_t now);
232 static void     rem_cache(struct CacheEntry*);
233 static void     do_query_name(const struct DNSQuery* query, 
234                               const char* name, 
235                               struct ResRequest* request);
236 static void     do_query_number(const struct DNSQuery* query,
237                                 const struct in_addr*, 
238                                 struct ResRequest* request);
239 static void     query_name(const char* name, 
240                            int query_class, 
241                            int query_type, 
242                            struct ResRequest* request);
243 static void     resend_query(struct ResRequest* request);
244 static struct CacheEntry*  make_cache(struct ResRequest* request);
245 static struct CacheEntry*  find_cache_name(const char* name);
246 static struct CacheEntry*  find_cache_number(struct ResRequest* request, 
247                                              const char* addr);
248 static struct ResRequest*   find_id(int);
249
250 static struct cacheinfo {
251   int  ca_adds;
252   int  ca_dels;
253   int  ca_expires;
254   int  ca_lookups;
255   int  ca_na_hits;
256   int  ca_nu_hits;
257   int  ca_updates;
258 } cainfo;
259
260 static  struct  resinfo {
261   int  re_errors;
262   int  re_nu_look;
263   int  re_na_look;
264   int  re_replies;
265   int  re_requests;
266   int  re_resends;
267   int  re_sent;
268   int  re_timeouts;
269   int  re_shortttl;
270   int  re_unkrep;
271 } reinfo;
272
273
274 /*
275  * From bind 8.3, these aren't declared in earlier versions of bind
276  */
277 extern u_short  _getshort(const u_char *);
278 extern u_int    _getlong(const u_char *);
279 /*
280  * int
281  * res_isourserver(ina)
282  *      looks up "ina" in _res.ns_addr_list[]
283  * returns:
284  *      0  : not found
285  *      >0 : found
286  * author:
287  *      paul vixie, 29may94
288  */
289 static int
290 res_ourserver(const struct __res_state* statp, const struct sockaddr_in* inp) 
291 {
292   struct sockaddr_in ina;
293   int ns;
294
295   ina = *inp;
296   for (ns = 0;  ns < statp->nscount;  ns++) {
297     const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
298
299     if (srv->sin_family == ina.sin_family &&
300          srv->sin_port == ina.sin_port &&
301          (srv->sin_addr.s_addr == INADDR_ANY ||
302           srv->sin_addr.s_addr == ina.sin_addr.s_addr))
303              return (1);
304   }
305   return (0);
306 }
307
308 /* Socket callback for resolver */
309 static void res_callback(struct Event* ev)
310 {
311   assert(ev_type(ev) == ET_READ);
312
313   resolver_read();
314 }
315
316 /*
317  * start_resolver - do everything we need to read the resolv.conf file
318  * and initialize the resolver file descriptor if needed
319  */
320 static void start_resolver(void)
321 {
322   Debug((DEBUG_DNS, "Resolver: start_resolver"));
323   /*
324    * close the spare file descriptor so res_init can read resolv.conf
325    * successfully. Needed on Solaris
326    */
327   if (spare_fd > -1)
328     close(spare_fd);
329
330   res_init();      /* res_init always returns 0 */
331   /*
332    * make sure we have a valid file descriptor below 256 so we can
333    * do this again. Needed on Solaris
334    */
335   spare_fd = open("/dev/null",O_RDONLY,0);
336   if ((spare_fd < 0) || (spare_fd > 255)) {
337     char sparemsg[80];
338     sprintf_irc(sparemsg, "invalid spare_fd %d", spare_fd);
339     server_restart(sparemsg);
340   }
341
342   if (!_res.nscount) {
343     _res.nscount = 1;
344     _res.nsaddr_list[0].sin_addr.s_addr = inet_addr("127.0.0.1");
345   }
346   _res.options |= RES_NOALIASES;
347
348   if (ResolverFileDescriptor < 0) {
349     ResolverFileDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
350     if (-1 == ResolverFileDescriptor) {
351       report_error("Resolver: error creating socket for %s: %s", 
352                    cli_name(&me), errno);
353       return;
354     }
355     if (!os_set_nonblocking(ResolverFileDescriptor))
356       report_error("Resolver: error setting non-blocking for %s: %s", 
357                    cli_name(&me), errno);
358     if (!socket_add(&resSock, res_callback, 0, SS_DATAGRAM,
359                     SOCK_EVENT_READABLE, ResolverFileDescriptor))
360       report_error("Resolver: unable to queue resolver file descriptor for %s",
361                    cli_name(&me), ENFILE);
362   }
363 }
364
365 /* Call the query timeout function */
366 static void expire_DNS_callback(struct Event* ev)
367 {
368   time_t next;
369
370   next = timeout_query_list(CurrentTime);
371
372   timer_add(&resExpireDNS, expire_DNS_callback, 0, TT_ABSOLUTE, next);
373 }
374
375 /* Call the cache expire function */
376 static void expire_cache_callback(struct Event* ev)
377 {
378   time_t next;
379
380   next = expire_cache(CurrentTime);
381
382   timer_add(&resExpireCache, expire_cache_callback, 0, TT_ABSOLUTE, next);
383 }
384
385 /*
386  * init_resolver - initialize resolver and resolver library
387  */
388 int init_resolver(void)
389 {
390   Debug((DEBUG_DNS, "Resolver: init_resolver"));
391 #ifdef  LRAND48
392   srand48(CurrentTime);
393 #endif
394   memset(&cainfo,   0, sizeof(cainfo));
395   memset(hashtable, 0, sizeof(hashtable));
396   memset(&reinfo,   0, sizeof(reinfo));
397
398   requestListHead = requestListTail = 0;
399
400   /* initiate the resolver timers */
401   timer_add(&resExpireDNS, expire_DNS_callback, 0, TT_RELATIVE, 1);
402   timer_add(&resExpireCache, expire_cache_callback, 0, TT_RELATIVE, 1);
403
404   errno = h_errno = 0;
405
406   start_resolver();
407   Debug((DEBUG_DNS, "Resolver: fd %d errno: %d h_errno: %d: %s",
408          ResolverFileDescriptor, errno, h_errno, 
409          (strerror(errno)) ? strerror(errno) : "Unknown"));
410   return ResolverFileDescriptor;
411 }
412
413 /*
414  * restart_resolver - flush the cache, reread resolv.conf, reopen socket
415  */
416 void restart_resolver(void)
417 {
418   /* flush_cache();  flush the dns cache */
419   start_resolver();
420 }
421
422 static int validate_hostent(const struct hostent* hp)
423 {
424   const char* name;
425   int  i = 0;
426   assert(0 != hp);
427   for (name = hp->h_name; name; name = hp->h_aliases[i++]) {
428     if (!string_is_hostname(name))
429       return 0;
430   }
431   return 1;
432 }
433
434 /*
435  * add_request - place a new request in the request list
436  */
437 static void add_request(struct ResRequest* request)
438 {
439   assert(0 != request);
440   if (!requestListHead)
441     requestListHead = requestListTail = request;
442   else {
443     requestListTail->next = request;
444     requestListTail = request;
445   }
446   request->next = NULL;
447   ++reinfo.re_requests;
448 }
449
450 /*
451  * rem_request - remove a request from the list. 
452  * This must also free any memory that has been allocated for 
453  * temporary storage of DNS results.
454  */
455 static void rem_request(struct ResRequest* request)
456 {
457   struct ResRequest** current;
458   struct ResRequest*  prev = NULL;
459
460   assert(0 != request);
461   for (current = &requestListHead; *current; ) {
462     if (*current == request) {
463       *current = request->next;
464       if (requestListTail == request)
465         requestListTail = prev;
466       break;
467     } 
468     prev    = *current;
469     current = &(*current)->next;
470   }
471   MyFree(request->he.buf);
472   MyFree(request->name);
473   MyFree(request);
474 }
475
476 /*
477  * make_request - Create a DNS request record for the server.
478  */
479 static struct ResRequest* make_request(const struct DNSQuery* query)
480 {
481   struct ResRequest* request;
482   assert(0 != query);
483   request = (struct ResRequest*) MyMalloc(sizeof(struct ResRequest));
484   memset(request, 0, sizeof(struct ResRequest));
485
486   request->sentat           = CurrentTime;
487   request->retries          = 3;
488   request->resend           = 1;
489   request->timeout          = 5;    /* start at 5 per RFC1123 */
490   request->addr.s_addr      = INADDR_NONE;
491   request->he.h.h_addrtype  = AF_INET;
492   request->he.h.h_length    = sizeof(struct in_addr);
493   request->query.vptr       = query->vptr;
494   request->query.callback   = query->callback;
495
496 #if defined(NULL_POINTER_NOT_ZERO)
497   request->next             = NULL;
498   request->he.buf           = NULL;
499   request->he.h.h_name      = NULL;
500   request->he.h.h_aliases   = NULL;
501   request->he.h.h_addr_list = NULL;
502 #endif
503   add_request(request);
504   return request;
505 }
506
507 /*
508  * timeout_query_list - Remove queries from the list which have been 
509  * there too long without being resolved.
510  */
511 static time_t timeout_query_list(time_t now)
512 {
513   struct ResRequest* request;
514   struct ResRequest* next_request = 0;
515   time_t             next_time    = 0;
516   time_t             timeout      = 0;
517
518   Debug((DEBUG_DNS, "Resolver: timeout_query_list at %s", myctime(now)));
519   for (request = requestListHead; request; request = next_request) {
520     next_request = request->next;
521     timeout = request->sentat + request->timeout;
522     if (timeout < now) {
523       if (--request->retries <= 0) {
524         ++reinfo.re_timeouts;
525         (*request->query.callback)(request->query.vptr, 0);
526         rem_request(request);
527         continue;
528       }
529       else {
530         request->sentat = now;
531         request->timeout += request->timeout;
532         resend_query(request);
533       }
534     }
535     if (!next_time || timeout < next_time) {
536       next_time = timeout;
537     }
538   }
539   return (next_time > now) ? next_time : (now + AR_TTL);
540 }
541
542 /*
543  * expire_cache - removes entries from the cache which are older 
544  * than their expiry times. returns the time at which the server 
545  * should next poll the cache.
546  */
547 static time_t expire_cache(time_t now)
548 {
549   struct CacheEntry* cp;
550   struct CacheEntry* cp_next;
551   time_t             expire = 0;
552
553   Debug((DEBUG_DNS, "Resolver: expire_cache at %s", myctime(now)));
554   for (cp = cacheTop; cp; cp = cp_next) {
555     cp_next = cp->list_next;
556     if (cp->expireat < now) {
557       ++cainfo.ca_expires;
558       rem_cache(cp);
559     }
560     else if (!expire || expire > cp->expireat)
561       expire = cp->expireat;
562   }
563   return (expire > now) ? expire : (now + AR_TTL);
564 }
565
566 /*
567  * timeout_resolver - check request list and cache for expired entries
568  */
569 time_t timeout_resolver(time_t now)
570 {
571   if (nextDNSCheck < now)
572     nextDNSCheck = timeout_query_list(now);
573   if (nextCacheExpire < now)
574     nextCacheExpire = expire_cache(now);
575   return IRCD_MIN(nextDNSCheck, nextCacheExpire);
576 }
577
578
579 /*
580  * delete_resolver_queries - cleanup outstanding queries 
581  * for which there no longer exist clients or conf lines.
582  */
583 void delete_resolver_queries(const void* vptr)
584 {
585   struct ResRequest* request;
586   struct ResRequest* next_request;
587
588   for (request = requestListHead; request; request = next_request) {
589     next_request = request->next;
590     if (vptr == request->query.vptr)
591       rem_request(request);
592   }
593 }
594
595 /*
596  * send_res_msg - sends msg to all nameservers found in the "_res" structure.
597  * This should reflect /etc/resolv.conf. We will get responses
598  * which arent needed but is easier than checking to see if nameserver
599  * isnt present. Returns number of messages successfully sent to 
600  * nameservers or -1 if no successful sends.
601  */
602 static int send_res_msg(const u_char* msg, int len, int rcount)
603 {
604   int i;
605   int sent = 0;
606   int max_queries = IRCD_MIN(_res.nscount, rcount);
607
608   assert(0 != msg);
609   /*
610    * RES_PRIMARY option is not implemented
611    * if (_res.options & RES_PRIMARY || 0 == max_queries)
612    */
613   if (0 == max_queries)
614     max_queries = 1;
615
616   Debug((DEBUG_DNS, "Resolver: sendto %d", max_queries));
617
618   for (i = 0; i < max_queries; i++) {
619     if (sendto(ResolverFileDescriptor, msg, len, 0, 
620                (struct sockaddr*) &(_res.nsaddr_list[i]),
621                sizeof(struct sockaddr_in)) == len) {
622       ++reinfo.re_sent;
623       ++sent;
624     }
625     else
626       log_write(LS_RESOLVER, L_ERROR, 0, "Resolver: send failed %m");
627   }
628   return sent;
629 }
630
631 /*
632  * find_id - find a dns request id (id is determined by dn_mkquery)
633  */
634 static struct ResRequest* find_id(int id)
635 {
636   struct ResRequest* request;
637
638   for (request = requestListHead; request; request = request->next) {
639     if (request->id == id)
640       return request;
641   }
642   return NULL;
643 }
644
645 /*
646  * gethost_byname - get host address from name
647  */
648 struct DNSReply* gethost_byname(const char* name, 
649                                const struct DNSQuery* query)
650 {
651   struct CacheEntry* cp;
652   assert(0 != name);
653
654   Debug((DEBUG_DNS, "Resolver: gethost_byname %s", name));
655   ++reinfo.re_na_look;
656   if ((cp = find_cache_name(name)))
657     return &(cp->reply);
658
659   do_query_name(query, name, NULL);
660   nextDNSCheck = 1;
661   return NULL;
662 }
663
664 /*
665  * gethost_byaddr - get host name from address
666  */
667 struct DNSReply* gethost_byaddr(const char* addr,
668                                 const struct DNSQuery* query)
669 {
670   struct CacheEntry *cp;
671
672   assert(0 != addr);
673
674   Debug((DEBUG_DNS, "Resolver: gethost_byaddr %s", ircd_ntoa(addr)));
675
676   ++reinfo.re_nu_look;
677   if ((cp = find_cache_number(NULL, addr)))
678     return &(cp->reply);
679
680   do_query_number(query, (const struct in_addr*) addr, NULL);
681   nextDNSCheck = 1;
682   return NULL;
683 }
684
685 /*
686  * do_query_name - nameserver lookup name
687  */
688 static void do_query_name(const struct DNSQuery* query, 
689                           const char* name, struct ResRequest* request)
690 {
691   char  hname[HOSTLEN + 1];
692   assert(0 != name);
693
694   ircd_strncpy(hname, name, HOSTLEN);
695   hname[HOSTLEN] = '\0';
696
697   if (!request) {
698     request       = make_request(query);
699     request->type = T_A;
700     request->name = (char*) MyMalloc(strlen(hname) + 1);
701     strcpy(request->name, hname);
702   }
703   query_name(hname, C_IN, T_A, request);
704 }
705
706 /*
707  * do_query_number - Use this to do reverse IP# lookups.
708  */
709 static void do_query_number(const struct DNSQuery* query, 
710                             const struct in_addr* addr,
711                             struct ResRequest* request)
712 {
713   char  ipbuf[32];
714   const unsigned char* cp;
715
716   assert(0 != addr);
717   cp = (const unsigned char*) &addr->s_addr;
718   sprintf_irc(ipbuf, "%u.%u.%u.%u.in-addr.arpa.",
719               (unsigned int)(cp[3]), (unsigned int)(cp[2]),
720               (unsigned int)(cp[1]), (unsigned int)(cp[0]));
721
722   if (!request) {
723     request              = make_request(query);
724     request->type        = T_PTR;
725     request->addr.s_addr = addr->s_addr;
726   }
727   query_name(ipbuf, C_IN, T_PTR, request);
728 }
729
730 /*
731  * query_name - generate a query based on class, type and name.
732  */
733 static void query_name(const char* name, int query_class,
734                        int type, struct ResRequest* request)
735 {
736   char buf[MAXPACKET];
737   int  request_len = 0;
738
739   assert(0 != name);
740   assert(0 != request);
741
742   Debug((DEBUG_DNS, "Resolver: query_name: %s %d %d", name, query_class, type));
743   memset(buf, 0, sizeof(buf));
744   if ((request_len = res_mkquery(QUERY, name, query_class, type, 
745                                  0, 0, 0, (unsigned char*) buf, sizeof(buf))) > 0) {
746     HEADER* header = (HEADER*) buf;
747 #ifndef LRAND48
748     int            k = 0;
749     struct timeval tv;
750 #endif
751     /*
752      * generate a unique id
753      * NOTE: we don't have to worry about converting this to and from
754      * network byte order, the nameserver does not interpret this value
755      * and returns it unchanged
756      */
757 #ifdef LRAND48
758     do {
759       header->id = (header->id + lrand48()) & 0xffff;
760     } while (find_id(header->id));
761 #else
762     gettimeofday(&tv, NULL);
763     do {
764       header->id = (header->id + k + tv.tv_usec) & 0xffff;
765       ++k;
766     } while (find_id(header->id));
767 #endif /* LRAND48 */
768     request->id = header->id;
769     ++request->sends;
770     Debug((DEBUG_DNS, "Resolver: query_name %d: %s %d %d", request->id, 
771           name, query_class, type));
772     request->sent += send_res_msg((const unsigned char*) buf, request_len, request->sends);
773   }
774 }
775
776 static void resend_query(struct ResRequest* request)
777 {
778   assert(0 != request);
779
780   if (request->resend == 0)
781     return;
782   ++reinfo.re_resends;
783   switch(request->type) {
784   case T_PTR:
785     do_query_number(NULL, &request->addr, request);
786     break;
787   case T_A:
788     do_query_name(NULL, request->name, request);
789     break;
790   default:
791     break;
792   }
793 }
794
795 /*
796  * proc_answer - process name server reply
797  * build a hostent struct in the passed request
798  */
799 static int proc_answer(struct ResRequest* request, HEADER* header,
800                        u_char* buf, u_char* eob)
801 {
802   char   hostbuf[HOSTLEN + 1]; /* working buffer */
803   u_char* current;             /* current position in buf */
804   char** alias;                /* alias list */
805   char** addr;                 /* address list */
806   char*  name;                 /* pointer to name string */
807   char*  address;              /* pointer to address */
808   char*  endp;                 /* end of our buffer */
809   int    query_class;          /* answer class */
810   int    type;                 /* answer type */
811   int    rd_length;            /* record data length */
812   int    answer_count = 0;     /* answer counter */
813   int    n;                    /* temp count */
814   int    addr_count  = 0;      /* number of addresses in hostent */
815   int    alias_count = 0;      /* number of aliases in hostent */
816   struct hostent* hp;          /* hostent getting filled */
817
818   assert(0 != request);
819   assert(0 != header);
820   assert(0 != buf);
821   assert(0 != eob);
822   
823   current = buf + sizeof(HEADER);
824   hp = &(request->he.h);
825   /*
826    * lazy allocation of request->he.buf, we don't allocate a buffer
827    * unless there is something to put in it.
828    */
829   if (!request->he.buf) {
830     request->he.buf = (char*) MyMalloc(MAXGETHOSTLEN + 1);
831     request->he.buf[MAXGETHOSTLEN] = '\0';
832     /*
833      * array of alias list pointers starts at beginning of buf
834      */
835     hp->h_aliases = (char**) request->he.buf;
836     hp->h_aliases[0] = NULL;
837     /*
838      * array of address list pointers starts after alias list pointers
839      * the actual addresses follow the the address list pointers
840      */ 
841     hp->h_addr_list = (char**)(request->he.buf + ALIAS_BLEN);
842     /*
843      * don't copy the host address to the beginning of h_addr_list
844      */
845     hp->h_addr_list[0] = NULL;
846   }
847   endp = request->he.buf + MAXGETHOSTLEN;
848   /*
849    * find the end of the address list
850    */
851   addr = hp->h_addr_list;
852   while (*addr) {
853     ++addr;
854     ++addr_count;
855   }
856   /*
857    * make address point to first available address slot
858    */
859   address = request->he.buf + ADDRS_OFFSET +
860                     (sizeof(struct in_addr) * addr_count);
861   /*
862    * find the end of the alias list
863    */
864   alias = hp->h_aliases;
865   while (*alias) {
866     ++alias;
867     ++alias_count;
868   }
869   /*
870    * make name point to first available space in request->buf
871    */
872   if (alias_count > 0) {
873     name = hp->h_aliases[alias_count - 1];
874     name += (strlen(name) + 1);
875   }
876   else if (hp->h_name)
877     name = hp->h_name + strlen(hp->h_name) + 1;
878   else
879     name = request->he.buf + ADDRS_OFFSET + ADDRS_DLEN;
880  
881   /*
882    * skip past queries
883    */ 
884   while (header->qdcount-- > 0) {
885     if ((n = dn_skipname(current, eob)) < 0)
886       break;
887     current += (n + QFIXEDSZ);
888   }
889   /*
890    * process each answer sent to us blech.
891    */
892   while (header->ancount-- > 0 && current < eob && name < endp) {
893     n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
894     if (n <= 0) {
895       /*
896        * no more answers left
897        */
898       return answer_count;
899     }
900     hostbuf[HOSTLEN] = '\0';
901     /* 
902      * With Address arithmetic you have to be very anal
903      * this code was not working on alpha due to that
904      * (spotted by rodder/jailbird/dianora)
905      */
906     current += (size_t) n;
907
908     if (!((current + ANSWER_FIXED_SIZE) < eob))
909       break;
910
911     type = _getshort(current);
912     current += TYPE_SIZE;
913
914     query_class = _getshort(current);
915     current += CLASS_SIZE;
916
917     request->ttl = _getlong(current);
918     current += TTL_SIZE;
919
920     rd_length = _getshort(current);
921     current += RDLENGTH_SIZE;
922
923     /* 
924      * Wait to set request->type until we verify this structure 
925      */
926     switch(type) {
927     case T_A:
928       /*
929        * check for invalid rd_length or too many addresses
930        */
931       if (rd_length != sizeof(struct in_addr))
932         return answer_count;
933       if (++addr_count < RES_MAXADDRS) {
934         if (answer_count == 1)
935           hp->h_addrtype = (query_class == C_IN) ?  AF_INET : AF_UNSPEC;
936
937         memcpy(address, current, sizeof(struct in_addr));
938         *addr++ = address;
939         *addr = 0;
940         address += sizeof(struct in_addr);
941
942         if (!hp->h_name) {
943           strcpy(name, hostbuf);
944           hp->h_name = name;
945           name += strlen(name) + 1;
946         }
947         Debug((DEBUG_DNS, "Resolver: A %s for %s", 
948                ircd_ntoa((char*) hp->h_addr_list[addr_count - 1]), hostbuf));
949       }
950       current += rd_length;
951       ++answer_count;
952       break;
953     case T_PTR:
954       n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
955       if (n < 0) {
956         /*
957          * broken message
958          */
959         return 0;
960       }
961       else if (n == 0) {
962         /*
963          * no more answers left
964          */
965         return answer_count;
966       }
967       /*
968        * This comment is based on analysis by Shadowfax, Wohali and johan, 
969        * not me.  (Dianora) I am only commenting it.
970        *
971        * dn_expand is guaranteed to not return more than sizeof(hostbuf)
972        * but do all implementations of dn_expand also guarantee
973        * buffer is terminated with null byte? Lets not take chances.
974        *  -Dianora
975        */
976       hostbuf[HOSTLEN] = '\0';
977       current += (size_t) n;
978
979       Debug((DEBUG_DNS, "Resolver: PTR %s", hostbuf));
980       /*
981        * copy the returned hostname into the host name
982        * ignore duplicate ptr records
983        */
984       if (!hp->h_name) {
985         strcpy(name, hostbuf);
986         hp->h_name = name;
987         name += strlen(name) + 1;
988       }
989       ++answer_count;
990       break;
991     case T_CNAME:
992       Debug((DEBUG_DNS, "Resolver: CNAME %s", hostbuf));
993       if (++alias_count < RES_MAXALIASES) {
994         ircd_strncpy(name, hostbuf, endp - name);
995         *alias++ = name;
996         *alias   = 0;
997         name += strlen(name) + 1;
998       }
999       current += rd_length;
1000       ++answer_count;
1001       break;
1002     default :
1003       Debug((DEBUG_DNS,"Resolver: proc_answer type: %d for: %s", type, hostbuf));
1004       break;
1005     }
1006   }
1007   return answer_count;
1008 }
1009
1010 /*
1011  * resolver_read - read a dns reply from the nameserver and process it.
1012  * return 0 if nothing was read from the socket, otherwise return 1
1013  */
1014 int resolver_read(void)
1015 {
1016   u_char             buf[sizeof(HEADER) + MAXPACKET];
1017   HEADER*            header       = 0;
1018   struct ResRequest* request      = 0;
1019   struct CacheEntry* cp           = 0;
1020   unsigned int       rc           = 0;
1021   int                answer_count = 0;
1022   struct sockaddr_in sin;
1023
1024   Debug((DEBUG_DNS, "Resolver: read"));
1025   if (IO_SUCCESS != os_recvfrom_nonb(ResolverFileDescriptor,
1026                                      (char*) buf, sizeof(buf), &rc, &sin)) {
1027     return 0;
1028   }
1029   if (rc < sizeof(HEADER)) {
1030     Debug((DEBUG_DNS, "Resolver: short reply %d: %s", rc, 
1031            (strerror(errno)) ? strerror(errno) : "Unknown"));
1032     return 0;
1033   }
1034   /*
1035    * convert DNS reply reader from Network byte order to CPU byte order.
1036    */
1037   header = (HEADER*) buf;
1038   /* header->id = ntohs(header->id); */
1039   header->ancount = ntohs(header->ancount);
1040   header->qdcount = ntohs(header->qdcount);
1041   header->nscount = ntohs(header->nscount);
1042   header->arcount = ntohs(header->arcount);
1043   ++reinfo.re_replies;
1044   /*
1045    * response for an id which we have already received an answer for
1046    * just ignore this response.
1047    */
1048   if (0 == (request = find_id(header->id))) {
1049     Debug((DEBUG_DNS, "Resolver: can't find request id: %d", header->id));
1050     return 1;
1051   }
1052   /*
1053    * check against possibly fake replies
1054    */
1055   if (!res_ourserver(&_res, &sin)) {
1056     Debug((DEBUG_DNS, "Resolver: fake reply from: %s", (const char*) &sin.sin_addr));
1057     ++reinfo.re_unkrep;
1058     return 1;
1059   }
1060
1061   if ((header->rcode != NOERROR) || (header->ancount == 0)) {
1062     ++reinfo.re_errors;
1063     if (SERVFAIL == header->rcode)
1064       resend_query(request);
1065     else {
1066       /*
1067        * If a bad error was returned, we stop here and dont send
1068        * send any more (no retries granted).
1069        * Isomer: Perhaps we should return these error messages back to
1070        *         the client?
1071        */
1072 #ifdef DEBUGMODE
1073       switch (header->rcode) {
1074         case NOERROR:
1075           Debug((DEBUG_DNS, "Fatal DNS error: No Error"));
1076           break;
1077         case FORMERR:
1078           Debug((DEBUG_DNS, "Fatal DNS error: Format Error"));
1079           break;
1080         case SERVFAIL:
1081           Debug((DEBUG_DNS, "Fatal DNS error: Server Failure"));
1082           break;
1083         case NXDOMAIN:
1084           Debug((DEBUG_DNS, "DNS error: Non Existant Domain"));
1085           break;
1086         case NOTIMP:
1087           Debug((DEBUG_DNS, "Fatal DNS error: Not Implemented"));
1088           break;
1089         case REFUSED:
1090           Debug((DEBUG_DNS, "Fatal DNS error: Query Refused"));
1091           break;
1092         default:
1093           Debug((DEBUG_DNS, "Unassigned fatal DNS error: %i", header->rcode));
1094           break;
1095       }
1096 #endif /* DEBUGMODE */
1097       (*request->query.callback)(request->query.vptr, 0);
1098       rem_request(request);
1099     } 
1100     return 1;
1101   }
1102   /*
1103    * If this fails there was an error decoding the received packet, 
1104    * try it again and hope it works the next time.
1105    */
1106   answer_count = proc_answer(request, header, buf, buf + rc);
1107   if (answer_count) {
1108     if (T_PTR == request->type) {
1109       struct DNSReply* reply = 0;
1110       if (0 == request->he.h.h_name) {
1111         /*
1112          * got a PTR response with no name, something bogus is happening
1113          * don't bother trying again, the client address doesn't resolve 
1114          */
1115         (*request->query.callback)(request->query.vptr, reply);
1116         rem_request(request); 
1117         return 1;
1118       }
1119       Debug((DEBUG_DNS, "relookup %s <-> %s",
1120              request->he.h.h_name, ircd_ntoa((char*) &request->addr)));
1121       /*
1122        * Lookup the 'authoritive' name that we were given for the
1123        * ip#.  By using this call rather than regenerating the
1124        * type we automatically gain the use of the cache with no
1125        * extra kludges.
1126        */
1127       reply = gethost_byname(request->he.h.h_name, &request->query);
1128       if (reply) {
1129         (*request->query.callback)(request->query.vptr, reply);
1130       }
1131       else {
1132         /*
1133          * If name wasn't found, a request has been queued and it will
1134          * be the last one queued.  This is rather nasty way to keep
1135          * a host alias with the query. -avalon
1136          */
1137         MyFree(requestListTail->he.buf);
1138         requestListTail->he.buf = request->he.buf;
1139         request->he.buf = 0;
1140         memcpy(&requestListTail->he.h, &request->he.h, sizeof(struct hostent));
1141       }
1142       rem_request(request);
1143     }
1144     else {
1145       /*
1146        * got a name and address response, client resolved
1147        * XXX - Bug found here by Dianora -
1148        * make_cache() occasionally returns a NULL pointer when a
1149        * PTR returned a CNAME, cp was not checked before so the
1150        * callback was being called with a value of 0x2C != NULL.
1151        */
1152       struct DNSReply* reply = 0;
1153       if (validate_hostent(&request->he.h)) {
1154         if ((cp = make_cache(request)))
1155           reply = &cp->reply;
1156       }
1157       (*request->query.callback)(request->query.vptr, reply);
1158       rem_request(request);
1159     }
1160   }
1161   else if (!request->sent) {
1162     /*
1163      * XXX - we got a response for a query we didn't send with a valid id?
1164      * this should never happen, bail here and leave the client unresolved
1165      */
1166     (*request->query.callback)(request->query.vptr, 0);
1167     rem_request(request);
1168   }
1169   return 1;
1170 }
1171
1172 /*
1173  * resolver_read_multiple - process up to count reads
1174  */
1175 void resolver_read_multiple(int count)
1176 {
1177   int i = 0;
1178   for ( ; i < count; ++i) {
1179     if (0 == resolver_read())
1180       return;
1181   }
1182 }
1183
1184 static size_t calc_hostent_buffer_size(const struct hostent* hp)
1185 {
1186   char** p;
1187   size_t count = 0;
1188   assert(0 != hp);
1189
1190   /*
1191    * space for name
1192    */
1193   count += (strlen(hp->h_name) + 1);
1194   /*
1195    * space for aliases
1196    */
1197   for (p = hp->h_aliases; *p; ++p)
1198     count += (strlen(*p) + 1 + sizeof(char*));
1199   /*
1200    * space for addresses
1201    */
1202   for (p = hp->h_addr_list; *p; ++p)
1203     count += (hp->h_length + sizeof(char*));
1204   /*
1205    * space for 2 nulls to terminate h_aliases and h_addr_list 
1206    */
1207   count += (2 * sizeof(char*));
1208   return count;
1209 }
1210
1211
1212 /*
1213  * dup_hostent - Duplicate a hostent struct, allocate only enough memory for
1214  * the data we're putting in it.
1215  */
1216 static void dup_hostent(struct Hostent* new_hp, struct hostent* hp)
1217 {
1218   char*  p;
1219   char** ap;
1220   char** pp;
1221   int    alias_count = 0;
1222   int    addr_count = 0;
1223   size_t bytes_needed = 0;
1224
1225   assert(0 != new_hp);
1226   assert(0 != hp);
1227
1228   /* how much buffer do we need? */
1229   bytes_needed += (strlen(hp->h_name) + 1);
1230
1231   pp = hp->h_aliases;
1232   while (*pp) {
1233     bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1234     ++alias_count;
1235   }
1236   pp = hp->h_addr_list;
1237   while (*pp++) {
1238     bytes_needed += (hp->h_length + sizeof(char*));
1239     ++addr_count;
1240   }
1241   /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1242   bytes_needed += (2 * sizeof(char*));
1243
1244   /* Allocate memory */
1245   new_hp->buf = (char*) MyMalloc(bytes_needed);
1246
1247   new_hp->h.h_addrtype = hp->h_addrtype;
1248   new_hp->h.h_length = hp->h_length;
1249
1250   /* first write the address list */
1251   pp = hp->h_addr_list;
1252   ap = new_hp->h.h_addr_list =
1253       (char**)(new_hp->buf + ((alias_count + 1) * sizeof(char*)));
1254   p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1255   while (*pp)
1256   {
1257     *ap++ = p;
1258     memcpy(p, *pp++, hp->h_length);
1259     p += hp->h_length;
1260   }
1261   *ap = 0;
1262   /* next write the name */
1263   new_hp->h.h_name = p;
1264   strcpy(p, hp->h_name);
1265   p += (strlen(p) + 1);
1266
1267   /* last write the alias list */
1268   pp = hp->h_aliases;
1269   ap = new_hp->h.h_aliases = (char**) new_hp->buf;
1270   while (*pp) {
1271     *ap++ = p;
1272     strcpy(p, *pp++);
1273     p += (strlen(p) + 1);
1274   }
1275   *ap = 0;
1276 }
1277
1278 /*
1279  * update_hostent - Add records to a Hostent struct in place.
1280  */
1281 static void update_hostent(struct Hostent* hp, char** addr, char** alias)
1282 {
1283   char*  p;
1284   char** ap;
1285   char** pp;
1286   int    alias_count = 0;
1287   int    addr_count = 0;
1288   char*  buf = NULL;
1289   size_t bytes_needed = 0;
1290
1291   if (!hp || !hp->buf)
1292     return;
1293
1294   /* how much buffer do we need? */
1295   bytes_needed = strlen(hp->h.h_name) + 1;
1296   pp = hp->h.h_aliases;
1297   while (*pp) {
1298     bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1299     ++alias_count;
1300   }
1301   if (alias) {
1302     pp = alias;
1303     while (*pp) {
1304       bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1305       ++alias_count;
1306     }
1307   }
1308   pp = hp->h.h_addr_list;
1309   while (*pp++) {
1310     bytes_needed += (hp->h.h_length + sizeof(char*));
1311     ++addr_count;
1312   }
1313   if (addr) {
1314     pp = addr;
1315     while (*pp++) {
1316       bytes_needed += (hp->h.h_length + sizeof(char*));
1317       ++addr_count;
1318     }
1319   }
1320   /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1321   bytes_needed += 2 * sizeof(char*);
1322
1323   /* Allocate memory */
1324   buf = (char*) MyMalloc(bytes_needed);
1325   assert(0 != buf);
1326
1327   /* first write the address list */
1328   pp = hp->h.h_addr_list;
1329   ap = hp->h.h_addr_list =
1330       (char**)(buf + ((alias_count + 1) * sizeof(char*)));
1331   p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1332   while (*pp) {
1333     memcpy(p, *pp++, hp->h.h_length);
1334     *ap++ = p;
1335     p += hp->h.h_length;
1336   }
1337   if (addr) {
1338     while (*addr) {
1339       memcpy(p, *addr++, hp->h.h_length);
1340       *ap++ = p;
1341       p += hp->h.h_length;
1342     }
1343   }
1344   *ap = 0;
1345
1346   /* next write the name */
1347   strcpy(p, hp->h.h_name);
1348   hp->h.h_name = p;
1349   p += (strlen(p) + 1);
1350
1351   /* last write the alias list */
1352   pp = hp->h.h_aliases;
1353   ap = hp->h.h_aliases = (char**) buf;
1354   while (*pp) {
1355     strcpy(p, *pp++);
1356     *ap++ = p;
1357     p += (strlen(p) + 1);
1358   }
1359   if (alias) {
1360     while (*alias) {
1361       strcpy(p, *alias++);
1362       *ap++ = p;
1363       p += (strlen(p) + 1);
1364     }
1365   }
1366   *ap = 0;
1367   /* release the old buffer */
1368   p = hp->buf;
1369   hp->buf = buf;
1370   MyFree(p);
1371 }
1372
1373 /*
1374  * hash_number - IP address hash function
1375  */
1376 static int hash_number(const unsigned char* ip)
1377 {
1378   /* could use loop but slower */
1379   unsigned int hashv;
1380   const u_char* p = (const u_char*) ip;
1381
1382   assert(0 != p);
1383
1384   hashv = *p++;
1385   hashv += hashv + *p++;
1386   hashv += hashv + *p++;
1387   hashv += hashv + *p;
1388   hashv %= ARES_CACSIZE;
1389   return hashv;
1390 }
1391
1392 /*
1393  * hash_name - hostname hash function
1394  */
1395 static int hash_name(const char* name)
1396 {
1397   unsigned int hashv = 0;
1398   const u_char* p = (const u_char*) name;
1399
1400   assert(0 != p);
1401
1402   for (; *p && *p != '.'; ++p)
1403     hashv += *p;
1404   hashv %= ARES_CACSIZE;
1405   return hashv;
1406 }
1407
1408 /*
1409  * add_to_cache - Add a new cache item to the queue and hash table.
1410  */
1411 static struct CacheEntry* add_to_cache(struct CacheEntry* ocp)
1412 {
1413   int  hashv;
1414
1415   assert(0 != ocp);
1416
1417   ocp->list_next = cacheTop;
1418   cacheTop = ocp;
1419
1420   hashv = hash_name(ocp->he.h.h_name);
1421
1422   ocp->hname_next = hashtable[hashv].name_list;
1423   hashtable[hashv].name_list = ocp;
1424
1425   hashv = hash_number((const unsigned char*) ocp->he.h.h_addr);
1426
1427   ocp->hnum_next = hashtable[hashv].num_list;
1428   hashtable[hashv].num_list = ocp;
1429
1430   /*
1431    * LRU deletion of excessive cache entries.
1432    */
1433   if (++cachedCount > MAXCACHED) {
1434     struct CacheEntry* cp;
1435     struct CacheEntry* cp_next;
1436     for (cp = ocp->list_next; cp; cp = cp_next) {
1437       cp_next = cp->list_next;
1438       rem_cache(cp);
1439     }
1440   }
1441   ++cainfo.ca_adds;
1442   return ocp;
1443 }
1444
1445 /*
1446  * update_list - does not alter the cache structure passed. It is assumed that
1447  * it already contains the correct expire time, if it is a new entry. Old
1448  * entries have the expirey time updated.
1449 */
1450 static void update_list(struct ResRequest* request, struct CacheEntry* cachep)
1451 {
1452 #if 0
1453   struct CacheEntry** cpp;
1454 #endif
1455   struct CacheEntry*  cp = cachep;
1456   char*    s;
1457   char*    t;
1458   int      i;
1459   int      j;
1460   char**   ap;
1461   char*    addrs[RES_MAXADDRS + 1];
1462   char*    aliases[RES_MAXALIASES + 1];
1463
1464   /*
1465    * search for the new cache item in the cache list by hostname.
1466    * If found, move the entry to the top of the list and return.
1467    */
1468   ++cainfo.ca_updates;
1469 #if 0
1470   for (cpp = &cacheTop; *cpp; cpp = &((*cpp)->list_next)) {
1471     if (cp == *cpp)
1472       break;
1473   }
1474   if (!*cpp)
1475     return;
1476   *cpp = cp->list_next;
1477   cp->list_next = cacheTop;
1478   cacheTop = cp;
1479 #endif
1480
1481   if (!request)
1482     return;
1483   /*
1484    * Compare the cache entry against the new record.  Add any
1485    * previously missing names for this entry.
1486    */
1487   *aliases = 0;
1488   ap = aliases;
1489   for (i = 0, s = request->he.h.h_name; s; s = request->he.h.h_aliases[i++]) {
1490     for (j = 0, t = cp->he.h.h_name; t; t = cp->he.h.h_aliases[j++]) {
1491       if (0 == ircd_strcmp(t, s))
1492         break;
1493     }
1494     if (!t) {
1495       *ap++ = s;
1496       *ap = 0;
1497     }
1498   }
1499   /*
1500    * Do the same again for IP#'s.
1501    */
1502   *addrs = 0;
1503   ap = addrs;
1504   for (i = 0; (s = request->he.h.h_addr_list[i]); i++) {
1505     for (j = 0; (t = cp->he.h.h_addr_list[j]); j++) {
1506       if (!memcmp(t, s, sizeof(struct in_addr)))
1507         break;
1508     }
1509     if (!t) {
1510       *ap++ = s;
1511       *ap = 0;
1512     }
1513   }
1514   if (*addrs || *aliases)
1515     update_hostent(&cp->he, addrs, aliases);
1516 }
1517
1518 /*
1519  * find_cache_name - find name in nameserver cache
1520  */
1521 static struct CacheEntry* find_cache_name(const char* name)
1522 {
1523   struct CacheEntry* cp;
1524   char*   s;
1525   int     hashv;
1526   int     i;
1527
1528   assert(0 != name);
1529   hashv = hash_name(name);
1530
1531   cp = hashtable[hashv].name_list;
1532
1533   for (; cp; cp = cp->hname_next) {
1534     for (i = 0, s = cp->he.h.h_name; s; s = cp->he.h.h_aliases[i++]) {
1535       if (0 == ircd_strcmp(s, name)) {
1536         ++cainfo.ca_na_hits;
1537         return cp;
1538       }
1539     }
1540   }
1541
1542   for (cp = cacheTop; cp; cp = cp->list_next) {
1543     /*
1544      * if no aliases or the hash value matches, we've already
1545      * done this entry and all possiblilities concerning it.
1546      */
1547     if (!cp->he.h.h_name || hashv == hash_name(cp->he.h.h_name))
1548       continue;
1549     for (i = 0, s = cp->he.h.h_aliases[i]; s; s = cp->he.h.h_aliases[++i]) {
1550       if (0 == ircd_strcmp(name, s)) {
1551         ++cainfo.ca_na_hits;
1552         return cp;
1553       }
1554     }
1555   }
1556   return NULL;
1557 }
1558
1559 /*
1560  * find_cache_number - find a cache entry by ip# and update its expire time
1561  */
1562 static struct CacheEntry* find_cache_number(struct ResRequest* request,
1563                                             const char* addr)
1564 {
1565   struct CacheEntry* cp;
1566   int     hashv;
1567   int     i;
1568
1569   assert(0 != addr);
1570   hashv = hash_number((const unsigned char*) addr);
1571   cp = hashtable[hashv].num_list;
1572
1573   for (; cp; cp = cp->hnum_next) {
1574     for (i = 0; cp->he.h.h_addr_list[i]; ++i) {
1575       if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1576         ++cainfo.ca_nu_hits;
1577         return cp;
1578       }
1579     }
1580   }
1581   for (cp = cacheTop; cp; cp = cp->list_next) {
1582     /*
1583      * single address entry...would have been done by hashed
1584      * search above...
1585      * if the first IP# has the same hashnumber as the IP# we
1586      * are looking for, its been done already.
1587      */
1588     if (!cp->he.h.h_addr_list[1] || 
1589         hashv == hash_number((const unsigned char*) cp->he.h.h_addr_list[0]))
1590       continue;
1591     for (i = 1; cp->he.h.h_addr_list[i]; ++i) {
1592       if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1593         ++cainfo.ca_nu_hits;
1594         return cp;
1595       }
1596     }
1597   }
1598   return NULL;
1599 }
1600
1601 static struct CacheEntry* make_cache(struct ResRequest* request)
1602 {
1603   struct CacheEntry* cp;
1604   int     i;
1605   struct hostent* hp;
1606   assert(0 != request);
1607
1608   hp = &request->he.h;
1609   /*
1610    * shouldn't happen but it just might...
1611    */
1612   assert(0 != hp->h_name);
1613   assert(0 != hp->h_addr_list[0]);
1614   if (!hp->h_name || !hp->h_addr_list[0])
1615     return NULL;
1616   /*
1617    * Make cache entry.  First check to see if the cache already exists
1618    * and if so, return a pointer to it.
1619    */
1620   for (i = 0; hp->h_addr_list[i]; ++i) {
1621     if ((cp = find_cache_number(request, hp->h_addr_list[i]))) {
1622       update_list(request, cp);
1623       return cp;
1624     }
1625   }
1626   /*
1627    * a matching entry wasnt found in the cache so go and make one up.
1628    */ 
1629   cp = (struct CacheEntry*) MyMalloc(sizeof(struct CacheEntry));
1630   assert(0 != cp);
1631
1632   memset(cp, 0, sizeof(struct CacheEntry));
1633   dup_hostent(&cp->he, hp);
1634   cp->reply.hp = &cp->he.h;
1635   /*
1636    * hmmm... we could time out the cache after 10 minutes regardless
1637    * would that be reasonable since we don't save the reply?
1638    */ 
1639   if (request->ttl < AR_TTL) {
1640     ++reinfo.re_shortttl;
1641     cp->ttl = AR_TTL;
1642   }
1643   else
1644     cp->ttl = request->ttl;
1645   cp->expireat = CurrentTime + cp->ttl;
1646   return add_to_cache(cp);
1647 }
1648
1649 /*
1650  * rem_cache - delete a cache entry from the cache structures 
1651  * and lists and return all memory used for the cache back to the memory pool.
1652  */
1653 static void rem_cache(struct CacheEntry* ocp)
1654 {
1655   struct CacheEntry** cp;
1656   int                 hashv;
1657   struct hostent*     hp;
1658   assert(0 != ocp);
1659
1660
1661   if (0 < ocp->reply.ref_count) {
1662     if (ocp->expireat < CurrentTime) {
1663       ocp->expireat = CurrentTime + AR_TTL;
1664       Debug((DEBUG_DNS, "Resolver: referenced cache entry not removed for: %s",
1665             ocp->he.h.h_name));
1666     }
1667     return;
1668   }
1669   /*
1670    * remove cache entry from linked list
1671    */
1672   for (cp = &cacheTop; *cp; cp = &((*cp)->list_next)) {
1673     if (*cp == ocp) {
1674       *cp = ocp->list_next;
1675       break;
1676     }
1677   }
1678   hp = &ocp->he.h;
1679   /*
1680    * remove cache entry from hashed name list
1681    */
1682   assert(0 != hp->h_name);
1683   hashv = hash_name(hp->h_name);
1684
1685   for (cp = &hashtable[hashv].name_list; *cp; cp = &((*cp)->hname_next)) {
1686     if (*cp == ocp) {
1687       *cp = ocp->hname_next;
1688       break;
1689     }
1690   }
1691   /*
1692    * remove cache entry from hashed number list
1693    */
1694   hashv = hash_number((const unsigned char*) hp->h_addr);
1695   assert(-1 < hashv);
1696
1697   for (cp = &hashtable[hashv].num_list; *cp; cp = &((*cp)->hnum_next)) {
1698     if (*cp == ocp) {
1699       *cp = ocp->hnum_next;
1700       break;
1701     }
1702   }
1703   /*
1704    * free memory used to hold the various host names and the array
1705    * of alias pointers.
1706    */
1707   MyFree(ocp->he.buf);
1708   MyFree(ocp);
1709   --cachedCount;
1710   ++cainfo.ca_dels;
1711 }
1712
1713 void flush_resolver_cache(void)
1714 {
1715   /*
1716    * stubbed - iterate cache and remove everything that isn't referenced
1717    */
1718 }
1719
1720 /*
1721  * m_dns - dns status query
1722  */
1723 int m_dns(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1724 {
1725 #if !defined(NDEBUG)
1726   struct CacheEntry* cp;
1727   int     i;
1728   struct hostent* hp;
1729
1730   if (parv[1] && *parv[1] == 'l') {
1731     for(cp = cacheTop; cp; cp = cp->list_next) {
1732       hp = &cp->he.h;
1733       sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :Ex %d ttl %d host %s(%s)",
1734                     sptr, cp->expireat - CurrentTime, cp->ttl,
1735                     hp->h_name, ircd_ntoa(hp->h_addr));
1736       for (i = 0; hp->h_aliases[i]; i++)
1737         sendcmdto_one(&me, CMD_NOTICE, sptr, "%C : %s = %s (CN)", sptr,
1738                       hp->h_name, hp->h_aliases[i]);
1739       for (i = 1; hp->h_addr_list[i]; i++)
1740         sendcmdto_one(&me, CMD_NOTICE, sptr, "%C : %s = %s (IP)", sptr,
1741                       hp->h_name, ircd_ntoa(hp->h_addr_list[i]));
1742     }
1743     return 0;
1744   }
1745   if (parv[1] && *parv[1] == 'd') {
1746     sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :ResolverFileDescriptor = %d", 
1747                   sptr, ResolverFileDescriptor);
1748     return 0;
1749   }
1750   sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ca %d Cd %d Ce %d Cl %d Ch %d:%d "
1751                 "Cu %d", sptr,
1752                 cainfo.ca_adds, cainfo.ca_dels, cainfo.ca_expires,
1753                 cainfo.ca_lookups, cainfo.ca_na_hits, cainfo.ca_nu_hits, 
1754                 cainfo.ca_updates);
1755   
1756   sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Re %d Rl %d/%d Rp %d Rq %d",
1757                 sptr, reinfo.re_errors, reinfo.re_nu_look,
1758                 reinfo.re_na_look, reinfo.re_replies, reinfo.re_requests);
1759   sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ru %d Rsh %d Rs %d(%d) Rt %d", sptr,
1760                 reinfo.re_unkrep, reinfo.re_shortttl, reinfo.re_sent,
1761                 reinfo.re_resends, reinfo.re_timeouts);
1762 #endif
1763   return 0;
1764 }
1765
1766 size_t cres_mem(struct Client* sptr)
1767 {
1768   struct CacheEntry* entry;
1769   struct ResRequest* request;
1770   size_t cache_mem     = 0;
1771   size_t request_mem   = 0;
1772   int    cache_count   = 0;
1773   int    request_count = 0;
1774
1775   for (entry = cacheTop; entry; entry = entry->list_next) {
1776     cache_mem += sizeof(struct CacheEntry);
1777     cache_mem += calc_hostent_buffer_size(&entry->he.h); 
1778     ++cache_count;
1779   }
1780   for (request = requestListHead; request; request = request->next) {
1781     request_mem += sizeof(struct ResRequest);
1782     if (request->name)
1783       request_mem += strlen(request->name) + 1; 
1784     if (request->he.buf)
1785       request_mem += MAXGETHOSTLEN + 1;
1786     ++request_count;
1787   }
1788
1789   if (cachedCount != cache_count) {
1790     send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1791                ":Resolver: cache count mismatch: %d != %d", cachedCount,
1792                cache_count);
1793     assert(cachedCount == cache_count);
1794   }
1795   send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1796              ":Resolver: cache %d(%d) requests %d(%d)", cache_count,
1797              cache_mem, request_count, request_mem);
1798   return cache_mem + request_mem;
1799 }
1800