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_snprintf.h"
24 #include "ircd_string.h"
25 #include "msg.h"
26 #include "numeric.h"
27 #include "s_bsd.h"
28 #include "s_debug.h"
29 #include "s_misc.h"
30 #include "send.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     ircd_snprintf(0, sparemsg, sizeof(sparemsg), "invalid spare_fd %d",
339                   spare_fd);
340     server_restart(sparemsg);
341   }
342
343   if (!_res.nscount) {
344     _res.nscount = 1;
345     _res.nsaddr_list[0].sin_addr.s_addr = inet_addr("127.0.0.1");
346   }
347   _res.options |= RES_NOALIASES;
348
349   if (ResolverFileDescriptor < 0) {
350     ResolverFileDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
351     if (-1 == ResolverFileDescriptor) {
352       report_error("Resolver: error creating socket for %s: %s", 
353                    cli_name(&me), errno);
354       return;
355     }
356     if (!os_set_nonblocking(ResolverFileDescriptor))
357       report_error("Resolver: error setting non-blocking for %s: %s", 
358                    cli_name(&me), errno);
359     if (!socket_add(&resSock, res_callback, 0, SS_DATAGRAM,
360                     SOCK_EVENT_READABLE, ResolverFileDescriptor))
361       report_error("Resolver: unable to queue resolver file descriptor for %s",
362                    cli_name(&me), ENFILE);
363   }
364 }
365
366 /* Call the query timeout function */
367 static void expire_DNS_callback(struct Event* ev)
368 {
369   time_t next;
370
371   next = timeout_query_list(CurrentTime);
372
373   timer_add(&resExpireDNS, expire_DNS_callback, 0, TT_ABSOLUTE, next);
374 }
375
376 /* Call the cache expire function */
377 static void expire_cache_callback(struct Event* ev)
378 {
379   time_t next;
380
381   next = expire_cache(CurrentTime);
382
383   timer_add(&resExpireCache, expire_cache_callback, 0, TT_ABSOLUTE, next);
384 }
385
386 /*
387  * init_resolver - initialize resolver and resolver library
388  */
389 int init_resolver(void)
390 {
391   Debug((DEBUG_DNS, "Resolver: init_resolver"));
392 #ifdef  LRAND48
393   srand48(CurrentTime);
394 #endif
395   memset(&cainfo,   0, sizeof(cainfo));
396   memset(hashtable, 0, sizeof(hashtable));
397   memset(&reinfo,   0, sizeof(reinfo));
398
399   requestListHead = requestListTail = 0;
400
401   /* initiate the resolver timers */
402   timer_add(&resExpireDNS, expire_DNS_callback, 0, TT_RELATIVE, 1);
403   timer_add(&resExpireCache, expire_cache_callback, 0, TT_RELATIVE, 1);
404
405   errno = h_errno = 0;
406
407   start_resolver();
408   Debug((DEBUG_DNS, "Resolver: fd %d errno: %d h_errno: %d: %s",
409          ResolverFileDescriptor, errno, h_errno, 
410          (strerror(errno)) ? strerror(errno) : "Unknown"));
411   return ResolverFileDescriptor;
412 }
413
414 /*
415  * restart_resolver - flush the cache, reread resolv.conf, reopen socket
416  */
417 void restart_resolver(void)
418 {
419   /* flush_cache();  flush the dns cache */
420   start_resolver();
421 }
422
423 static int validate_hostent(const struct hostent* hp)
424 {
425   const char* name;
426   int  i = 0;
427   assert(0 != hp);
428   for (name = hp->h_name; name; name = hp->h_aliases[i++]) {
429     if (!string_is_hostname(name))
430       return 0;
431   }
432   return 1;
433 }
434
435 /*
436  * add_request - place a new request in the request list
437  */
438 static void add_request(struct ResRequest* request)
439 {
440   assert(0 != request);
441   if (!requestListHead)
442     requestListHead = requestListTail = request;
443   else {
444     requestListTail->next = request;
445     requestListTail = request;
446   }
447   request->next = NULL;
448   ++reinfo.re_requests;
449 }
450
451 /*
452  * rem_request - remove a request from the list. 
453  * This must also free any memory that has been allocated for 
454  * temporary storage of DNS results.
455  */
456 static void rem_request(struct ResRequest* request)
457 {
458   struct ResRequest** current;
459   struct ResRequest*  prev = NULL;
460
461   assert(0 != request);
462   for (current = &requestListHead; *current; ) {
463     if (*current == request) {
464       *current = request->next;
465       if (requestListTail == request)
466         requestListTail = prev;
467       break;
468     } 
469     prev    = *current;
470     current = &(*current)->next;
471   }
472   MyFree(request->he.buf);
473   MyFree(request->name);
474   MyFree(request);
475 }
476
477 /*
478  * make_request - Create a DNS request record for the server.
479  */
480 static struct ResRequest* make_request(const struct DNSQuery* query)
481 {
482   struct ResRequest* request;
483   assert(0 != query);
484   request = (struct ResRequest*) MyMalloc(sizeof(struct ResRequest));
485   memset(request, 0, sizeof(struct ResRequest));
486
487   request->sentat           = CurrentTime;
488   request->retries          = 3;
489   request->resend           = 1;
490   request->timeout          = 5;    /* start at 5 per RFC1123 */
491   request->addr.s_addr      = INADDR_NONE;
492   request->he.h.h_addrtype  = AF_INET;
493   request->he.h.h_length    = sizeof(struct in_addr);
494   request->query.vptr       = query->vptr;
495   request->query.callback   = query->callback;
496
497 #if defined(NULL_POINTER_NOT_ZERO)
498   request->next             = NULL;
499   request->he.buf           = NULL;
500   request->he.h.h_name      = NULL;
501   request->he.h.h_aliases   = NULL;
502   request->he.h.h_addr_list = NULL;
503 #endif
504   add_request(request);
505   return request;
506 }
507
508 /*
509  * timeout_query_list - Remove queries from the list which have been 
510  * there too long without being resolved.
511  */
512 static time_t timeout_query_list(time_t now)
513 {
514   struct ResRequest* request;
515   struct ResRequest* next_request = 0;
516   time_t             next_time    = 0;
517   time_t             timeout      = 0;
518
519   Debug((DEBUG_DNS, "Resolver: timeout_query_list at %s", myctime(now)));
520   for (request = requestListHead; request; request = next_request) {
521     next_request = request->next;
522     timeout = request->sentat + request->timeout;
523     if (timeout < now) {
524       if (--request->retries <= 0) {
525         ++reinfo.re_timeouts;
526         (*request->query.callback)(request->query.vptr, 0);
527         rem_request(request);
528         continue;
529       }
530       else {
531         request->sentat = now;
532         request->timeout += request->timeout;
533         resend_query(request);
534       }
535     }
536     if (!next_time || timeout < next_time) {
537       next_time = timeout;
538     }
539   }
540   return (next_time > now) ? next_time : (now + AR_TTL);
541 }
542
543 /*
544  * expire_cache - removes entries from the cache which are older 
545  * than their expiry times. returns the time at which the server 
546  * should next poll the cache.
547  */
548 static time_t expire_cache(time_t now)
549 {
550   struct CacheEntry* cp;
551   struct CacheEntry* cp_next;
552   time_t             expire = 0;
553
554   Debug((DEBUG_DNS, "Resolver: expire_cache at %s", myctime(now)));
555   for (cp = cacheTop; cp; cp = cp_next) {
556     cp_next = cp->list_next;
557     if (cp->expireat < now) {
558       ++cainfo.ca_expires;
559       rem_cache(cp);
560     }
561     else if (!expire || expire > cp->expireat)
562       expire = cp->expireat;
563   }
564   return (expire > now) ? expire : (now + AR_TTL);
565 }
566
567 /*
568  * timeout_resolver - check request list and cache for expired entries
569  */
570 time_t timeout_resolver(time_t now)
571 {
572   if (nextDNSCheck < now)
573     nextDNSCheck = timeout_query_list(now);
574   if (nextCacheExpire < now)
575     nextCacheExpire = expire_cache(now);
576   return IRCD_MIN(nextDNSCheck, nextCacheExpire);
577 }
578
579
580 /*
581  * delete_resolver_queries - cleanup outstanding queries 
582  * for which there no longer exist clients or conf lines.
583  */
584 void delete_resolver_queries(const void* vptr)
585 {
586   struct ResRequest* request;
587   struct ResRequest* next_request;
588
589   for (request = requestListHead; request; request = next_request) {
590     next_request = request->next;
591     if (vptr == request->query.vptr)
592       rem_request(request);
593   }
594 }
595
596 /*
597  * send_res_msg - sends msg to all nameservers found in the "_res" structure.
598  * This should reflect /etc/resolv.conf. We will get responses
599  * which arent needed but is easier than checking to see if nameserver
600  * isnt present. Returns number of messages successfully sent to 
601  * nameservers or -1 if no successful sends.
602  */
603 static int send_res_msg(const u_char* msg, int len, int rcount)
604 {
605   int i;
606   int sent = 0;
607   int max_queries = IRCD_MIN(_res.nscount, rcount);
608
609   assert(0 != msg);
610   /*
611    * RES_PRIMARY option is not implemented
612    * if (_res.options & RES_PRIMARY || 0 == max_queries)
613    */
614   if (0 == max_queries)
615     max_queries = 1;
616
617   Debug((DEBUG_DNS, "Resolver: sendto %d", max_queries));
618
619   for (i = 0; i < max_queries; i++) {
620     if (sendto(ResolverFileDescriptor, msg, len, 0, 
621                (struct sockaddr*) &(_res.nsaddr_list[i]),
622                sizeof(struct sockaddr_in)) == len) {
623       ++reinfo.re_sent;
624       ++sent;
625     }
626     else
627       log_write(LS_RESOLVER, L_ERROR, 0, "Resolver: send failed %m");
628   }
629   return sent;
630 }
631
632 /*
633  * find_id - find a dns request id (id is determined by dn_mkquery)
634  */
635 static struct ResRequest* find_id(int id)
636 {
637   struct ResRequest* request;
638
639   for (request = requestListHead; request; request = request->next) {
640     if (request->id == id)
641       return request;
642   }
643   return NULL;
644 }
645
646 /*
647  * gethost_byname - get host address from name
648  */
649 struct DNSReply* gethost_byname(const char* name, 
650                                const struct DNSQuery* query)
651 {
652   struct CacheEntry* cp;
653   assert(0 != name);
654
655   Debug((DEBUG_DNS, "Resolver: gethost_byname %s", name));
656   ++reinfo.re_na_look;
657   if ((cp = find_cache_name(name)))
658     return &(cp->reply);
659
660   do_query_name(query, name, NULL);
661   nextDNSCheck = 1;
662   return NULL;
663 }
664
665 /*
666  * gethost_byaddr - get host name from address
667  */
668 struct DNSReply* gethost_byaddr(const char* addr,
669                                 const struct DNSQuery* query)
670 {
671   struct CacheEntry *cp;
672
673   assert(0 != addr);
674
675   Debug((DEBUG_DNS, "Resolver: gethost_byaddr %s", ircd_ntoa(addr)));
676
677   ++reinfo.re_nu_look;
678   if ((cp = find_cache_number(NULL, addr)))
679     return &(cp->reply);
680
681   do_query_number(query, (const struct in_addr*) addr, NULL);
682   nextDNSCheck = 1;
683   return NULL;
684 }
685
686 /*
687  * do_query_name - nameserver lookup name
688  */
689 static void do_query_name(const struct DNSQuery* query, 
690                           const char* name, struct ResRequest* request)
691 {
692   char  hname[HOSTLEN + 1];
693   assert(0 != name);
694
695   ircd_strncpy(hname, name, HOSTLEN);
696   hname[HOSTLEN] = '\0';
697
698   if (!request) {
699     request       = make_request(query);
700     request->type = T_A;
701     request->name = (char*) MyMalloc(strlen(hname) + 1);
702     strcpy(request->name, hname);
703   }
704   query_name(hname, C_IN, T_A, request);
705 }
706
707 /*
708  * do_query_number - Use this to do reverse IP# lookups.
709  */
710 static void do_query_number(const struct DNSQuery* query, 
711                             const struct in_addr* addr,
712                             struct ResRequest* request)
713 {
714   char  ipbuf[32];
715   const unsigned char* cp;
716
717   assert(0 != addr);
718   cp = (const unsigned char*) &addr->s_addr;
719   ircd_snprintf(0, ipbuf, sizeof(ipbuf), "%u.%u.%u.%u.in-addr.arpa.",
720                 (unsigned int)(cp[3]), (unsigned int)(cp[2]),
721                 (unsigned int)(cp[1]), (unsigned int)(cp[0]));
722
723   if (!request) {
724     request              = make_request(query);
725     request->type        = T_PTR;
726     request->addr.s_addr = addr->s_addr;
727   }
728   query_name(ipbuf, C_IN, T_PTR, request);
729 }
730
731 /*
732  * query_name - generate a query based on class, type and name.
733  */
734 static void query_name(const char* name, int query_class,
735                        int type, struct ResRequest* request)
736 {
737   char buf[MAXPACKET];
738   int  request_len = 0;
739
740   assert(0 != name);
741   assert(0 != request);
742
743   Debug((DEBUG_DNS, "Resolver: query_name: %s %d %d", name, query_class, type));
744   memset(buf, 0, sizeof(buf));
745   if ((request_len = res_mkquery(QUERY, name, query_class, type, 
746                                  0, 0, 0, (unsigned char*) buf, sizeof(buf))) > 0) {
747     HEADER* header = (HEADER*) buf;
748 #ifndef LRAND48
749     int            k = 0;
750     struct timeval tv;
751 #endif
752     /*
753      * generate a unique id
754      * NOTE: we don't have to worry about converting this to and from
755      * network byte order, the nameserver does not interpret this value
756      * and returns it unchanged
757      */
758 #ifdef LRAND48
759     do {
760       header->id = (header->id + lrand48()) & 0xffff;
761     } while (find_id(header->id));
762 #else
763     gettimeofday(&tv, NULL);
764     do {
765       header->id = (header->id + k + tv.tv_usec) & 0xffff;
766       ++k;
767     } while (find_id(header->id));
768 #endif /* LRAND48 */
769     request->id = header->id;
770     ++request->sends;
771     Debug((DEBUG_DNS, "Resolver: query_name %d: %s %d %d", request->id, 
772           name, query_class, type));
773     request->sent += send_res_msg((const unsigned char*) buf, request_len, request->sends);
774   }
775 }
776
777 static void resend_query(struct ResRequest* request)
778 {
779   assert(0 != request);
780
781   if (request->resend == 0)
782     return;
783   ++reinfo.re_resends;
784   switch(request->type) {
785   case T_PTR:
786     do_query_number(NULL, &request->addr, request);
787     break;
788   case T_A:
789     do_query_name(NULL, request->name, request);
790     break;
791   default:
792     break;
793   }
794 }
795
796 /*
797  * proc_answer - process name server reply
798  * build a hostent struct in the passed request
799  */
800 static int proc_answer(struct ResRequest* request, HEADER* header,
801                        u_char* buf, u_char* eob)
802 {
803   char   hostbuf[HOSTLEN + 1]; /* working buffer */
804   u_char* current;             /* current position in buf */
805   char** alias;                /* alias list */
806   char** addr;                 /* address list */
807   char*  name;                 /* pointer to name string */
808   char*  address;              /* pointer to address */
809   char*  endp;                 /* end of our buffer */
810   int    query_class;          /* answer class */
811   int    type;                 /* answer type */
812   int    rd_length;            /* record data length */
813   int    answer_count = 0;     /* answer counter */
814   int    n;                    /* temp count */
815   int    addr_count  = 0;      /* number of addresses in hostent */
816   int    alias_count = 0;      /* number of aliases in hostent */
817   struct hostent* hp;          /* hostent getting filled */
818
819   assert(0 != request);
820   assert(0 != header);
821   assert(0 != buf);
822   assert(0 != eob);
823   
824   current = buf + sizeof(HEADER);
825   hp = &(request->he.h);
826   /*
827    * lazy allocation of request->he.buf, we don't allocate a buffer
828    * unless there is something to put in it.
829    */
830   if (!request->he.buf) {
831     request->he.buf = (char*) MyMalloc(MAXGETHOSTLEN + 1);
832     request->he.buf[MAXGETHOSTLEN] = '\0';
833     /*
834      * array of alias list pointers starts at beginning of buf
835      */
836     hp->h_aliases = (char**) request->he.buf;
837     hp->h_aliases[0] = NULL;
838     /*
839      * array of address list pointers starts after alias list pointers
840      * the actual addresses follow the the address list pointers
841      */ 
842     hp->h_addr_list = (char**)(request->he.buf + ALIAS_BLEN);
843     /*
844      * don't copy the host address to the beginning of h_addr_list
845      */
846     hp->h_addr_list[0] = NULL;
847   }
848   endp = request->he.buf + MAXGETHOSTLEN;
849   /*
850    * find the end of the address list
851    */
852   addr = hp->h_addr_list;
853   while (*addr) {
854     ++addr;
855     ++addr_count;
856   }
857   /*
858    * make address point to first available address slot
859    */
860   address = request->he.buf + ADDRS_OFFSET +
861                     (sizeof(struct in_addr) * addr_count);
862   /*
863    * find the end of the alias list
864    */
865   alias = hp->h_aliases;
866   while (*alias) {
867     ++alias;
868     ++alias_count;
869   }
870   /*
871    * make name point to first available space in request->buf
872    */
873   if (alias_count > 0) {
874     name = hp->h_aliases[alias_count - 1];
875     name += (strlen(name) + 1);
876   }
877   else if (hp->h_name)
878     name = hp->h_name + strlen(hp->h_name) + 1;
879   else
880     name = request->he.buf + ADDRS_OFFSET + ADDRS_DLEN;
881  
882   /*
883    * skip past queries
884    */ 
885   while (header->qdcount-- > 0) {
886     if ((n = dn_skipname(current, eob)) < 0)
887       break;
888     current += (n + QFIXEDSZ);
889   }
890   /*
891    * process each answer sent to us blech.
892    */
893   while (header->ancount-- > 0 && current < eob && name < endp) {
894     n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
895     if (n <= 0) {
896       /*
897        * no more answers left
898        */
899       return answer_count;
900     }
901     hostbuf[HOSTLEN] = '\0';
902     /* 
903      * With Address arithmetic you have to be very anal
904      * this code was not working on alpha due to that
905      * (spotted by rodder/jailbird/dianora)
906      */
907     current += (size_t) n;
908
909     if (!((current + ANSWER_FIXED_SIZE) < eob))
910       break;
911
912     type = _getshort(current);
913     current += TYPE_SIZE;
914
915     query_class = _getshort(current);
916     current += CLASS_SIZE;
917
918     request->ttl = _getlong(current);
919     current += TTL_SIZE;
920
921     rd_length = _getshort(current);
922     current += RDLENGTH_SIZE;
923
924     /* 
925      * Wait to set request->type until we verify this structure 
926      */
927     switch(type) {
928     case T_A:
929       /*
930        * check for invalid rd_length or too many addresses
931        */
932       if (rd_length != sizeof(struct in_addr))
933         return answer_count;
934       if (++addr_count < RES_MAXADDRS) {
935         if (answer_count == 1)
936           hp->h_addrtype = (query_class == C_IN) ?  AF_INET : AF_UNSPEC;
937
938         memcpy(address, current, sizeof(struct in_addr));
939         *addr++ = address;
940         *addr = 0;
941         address += sizeof(struct in_addr);
942
943         if (!hp->h_name) {
944           strcpy(name, hostbuf);
945           hp->h_name = name;
946           name += strlen(name) + 1;
947         }
948         Debug((DEBUG_DNS, "Resolver: A %s for %s", 
949                ircd_ntoa((char*) hp->h_addr_list[addr_count - 1]), hostbuf));
950       }
951       current += rd_length;
952       ++answer_count;
953       break;
954     case T_PTR:
955       n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
956       if (n < 0) {
957         /*
958          * broken message
959          */
960         return 0;
961       }
962       else if (n == 0) {
963         /*
964          * no more answers left
965          */
966         return answer_count;
967       }
968       /*
969        * This comment is based on analysis by Shadowfax, Wohali and johan, 
970        * not me.  (Dianora) I am only commenting it.
971        *
972        * dn_expand is guaranteed to not return more than sizeof(hostbuf)
973        * but do all implementations of dn_expand also guarantee
974        * buffer is terminated with null byte? Lets not take chances.
975        *  -Dianora
976        */
977       hostbuf[HOSTLEN] = '\0';
978       current += (size_t) n;
979
980       Debug((DEBUG_DNS, "Resolver: PTR %s", hostbuf));
981       /*
982        * copy the returned hostname into the host name
983        * ignore duplicate ptr records
984        */
985       if (!hp->h_name) {
986         strcpy(name, hostbuf);
987         hp->h_name = name;
988         name += strlen(name) + 1;
989       }
990       ++answer_count;
991       break;
992     case T_CNAME:
993       Debug((DEBUG_DNS, "Resolver: CNAME %s", hostbuf));
994       if (++alias_count < RES_MAXALIASES) {
995         ircd_strncpy(name, hostbuf, endp - name);
996         *alias++ = name;
997         *alias   = 0;
998         name += strlen(name) + 1;
999       }
1000       current += rd_length;
1001       ++answer_count;
1002       break;
1003     default :
1004       Debug((DEBUG_DNS,"Resolver: proc_answer type: %d for: %s", type, hostbuf));
1005       break;
1006     }
1007   }
1008   return answer_count;
1009 }
1010
1011 /*
1012  * resolver_read - read a dns reply from the nameserver and process it.
1013  * return 0 if nothing was read from the socket, otherwise return 1
1014  */
1015 int resolver_read(void)
1016 {
1017   u_char             buf[sizeof(HEADER) + MAXPACKET];
1018   HEADER*            header       = 0;
1019   struct ResRequest* request      = 0;
1020   struct CacheEntry* cp           = 0;
1021   unsigned int       rc           = 0;
1022   int                answer_count = 0;
1023   struct sockaddr_in sin;
1024
1025   Debug((DEBUG_DNS, "Resolver: read"));
1026   if (IO_SUCCESS != os_recvfrom_nonb(ResolverFileDescriptor,
1027                                      (char*) buf, sizeof(buf), &rc, &sin)) {
1028     return 0;
1029   }
1030   if (rc < sizeof(HEADER)) {
1031     Debug((DEBUG_DNS, "Resolver: short reply %d: %s", rc, 
1032            (strerror(errno)) ? strerror(errno) : "Unknown"));
1033     return 0;
1034   }
1035   /*
1036    * convert DNS reply reader from Network byte order to CPU byte order.
1037    */
1038   header = (HEADER*) buf;
1039   /* header->id = ntohs(header->id); */
1040   header->ancount = ntohs(header->ancount);
1041   header->qdcount = ntohs(header->qdcount);
1042   header->nscount = ntohs(header->nscount);
1043   header->arcount = ntohs(header->arcount);
1044   ++reinfo.re_replies;
1045   /*
1046    * response for an id which we have already received an answer for
1047    * just ignore this response.
1048    */
1049   if (0 == (request = find_id(header->id))) {
1050     Debug((DEBUG_DNS, "Resolver: can't find request id: %d", header->id));
1051     return 1;
1052   }
1053   /*
1054    * check against possibly fake replies
1055    */
1056   if (!res_ourserver(&_res, &sin)) {
1057     Debug((DEBUG_DNS, "Resolver: fake reply from: %s", (const char*) &sin.sin_addr));
1058     ++reinfo.re_unkrep;
1059     return 1;
1060   }
1061
1062   if ((header->rcode != NOERROR) || (header->ancount == 0)) {
1063     ++reinfo.re_errors;
1064     if (SERVFAIL == header->rcode)
1065       resend_query(request);
1066     else {
1067       /*
1068        * If a bad error was returned, we stop here and dont send
1069        * send any more (no retries granted).
1070        * Isomer: Perhaps we should return these error messages back to
1071        *         the client?
1072        */
1073 #ifdef DEBUGMODE
1074       switch (header->rcode) {
1075         case NOERROR:
1076           Debug((DEBUG_DNS, "Fatal DNS error: No Error"));
1077           break;
1078         case FORMERR:
1079           Debug((DEBUG_DNS, "Fatal DNS error: Format Error"));
1080           break;
1081         case SERVFAIL:
1082           Debug((DEBUG_DNS, "Fatal DNS error: Server Failure"));
1083           break;
1084         case NXDOMAIN:
1085           Debug((DEBUG_DNS, "DNS error: Non Existant Domain"));
1086           break;
1087         case NOTIMP:
1088           Debug((DEBUG_DNS, "Fatal DNS error: Not Implemented"));
1089           break;
1090         case REFUSED:
1091           Debug((DEBUG_DNS, "Fatal DNS error: Query Refused"));
1092           break;
1093         default:
1094           Debug((DEBUG_DNS, "Unassigned fatal DNS error: %i", header->rcode));
1095           break;
1096       }
1097 #endif /* DEBUGMODE */
1098       (*request->query.callback)(request->query.vptr, 0);
1099       rem_request(request);
1100     } 
1101     return 1;
1102   }
1103   /*
1104    * If this fails there was an error decoding the received packet, 
1105    * try it again and hope it works the next time.
1106    */
1107   answer_count = proc_answer(request, header, buf, buf + rc);
1108   if (answer_count) {
1109     if (T_PTR == request->type) {
1110       struct DNSReply* reply = 0;
1111       if (0 == request->he.h.h_name) {
1112         /*
1113          * got a PTR response with no name, something bogus is happening
1114          * don't bother trying again, the client address doesn't resolve 
1115          */
1116         (*request->query.callback)(request->query.vptr, reply);
1117         rem_request(request); 
1118         return 1;
1119       }
1120       Debug((DEBUG_DNS, "relookup %s <-> %s",
1121              request->he.h.h_name, ircd_ntoa((char*) &request->addr)));
1122       /*
1123        * Lookup the 'authoritive' name that we were given for the
1124        * ip#.  By using this call rather than regenerating the
1125        * type we automatically gain the use of the cache with no
1126        * extra kludges.
1127        */
1128       reply = gethost_byname(request->he.h.h_name, &request->query);
1129       if (reply) {
1130         (*request->query.callback)(request->query.vptr, reply);
1131       }
1132       else {
1133         /*
1134          * If name wasn't found, a request has been queued and it will
1135          * be the last one queued.  This is rather nasty way to keep
1136          * a host alias with the query. -avalon
1137          */
1138         MyFree(requestListTail->he.buf);
1139         requestListTail->he.buf = request->he.buf;
1140         request->he.buf = 0;
1141         memcpy(&requestListTail->he.h, &request->he.h, sizeof(struct hostent));
1142       }
1143       rem_request(request);
1144     }
1145     else {
1146       /*
1147        * got a name and address response, client resolved
1148        * XXX - Bug found here by Dianora -
1149        * make_cache() occasionally returns a NULL pointer when a
1150        * PTR returned a CNAME, cp was not checked before so the
1151        * callback was being called with a value of 0x2C != NULL.
1152        */
1153       struct DNSReply* reply = 0;
1154       if (validate_hostent(&request->he.h)) {
1155         if ((cp = make_cache(request)))
1156           reply = &cp->reply;
1157       }
1158       (*request->query.callback)(request->query.vptr, reply);
1159       rem_request(request);
1160     }
1161   }
1162   else if (!request->sent) {
1163     /*
1164      * XXX - we got a response for a query we didn't send with a valid id?
1165      * this should never happen, bail here and leave the client unresolved
1166      */
1167     (*request->query.callback)(request->query.vptr, 0);
1168     rem_request(request);
1169   }
1170   return 1;
1171 }
1172
1173 /*
1174  * resolver_read_multiple - process up to count reads
1175  */
1176 void resolver_read_multiple(int count)
1177 {
1178   int i = 0;
1179   for ( ; i < count; ++i) {
1180     if (0 == resolver_read())
1181       return;
1182   }
1183 }
1184
1185 static size_t calc_hostent_buffer_size(const struct hostent* hp)
1186 {
1187   char** p;
1188   size_t count = 0;
1189   assert(0 != hp);
1190
1191   /*
1192    * space for name
1193    */
1194   count += (strlen(hp->h_name) + 1);
1195   /*
1196    * space for aliases
1197    */
1198   for (p = hp->h_aliases; *p; ++p)
1199     count += (strlen(*p) + 1 + sizeof(char*));
1200   /*
1201    * space for addresses
1202    */
1203   for (p = hp->h_addr_list; *p; ++p)
1204     count += (hp->h_length + sizeof(char*));
1205   /*
1206    * space for 2 nulls to terminate h_aliases and h_addr_list 
1207    */
1208   count += (2 * sizeof(char*));
1209   return count;
1210 }
1211
1212
1213 /*
1214  * dup_hostent - Duplicate a hostent struct, allocate only enough memory for
1215  * the data we're putting in it.
1216  */
1217 static void dup_hostent(struct Hostent* new_hp, struct hostent* hp)
1218 {
1219   char*  p;
1220   char** ap;
1221   char** pp;
1222   int    alias_count = 0;
1223   int    addr_count = 0;
1224   size_t bytes_needed = 0;
1225
1226   assert(0 != new_hp);
1227   assert(0 != hp);
1228
1229   /* how much buffer do we need? */
1230   bytes_needed += (strlen(hp->h_name) + 1);
1231
1232   pp = hp->h_aliases;
1233   while (*pp) {
1234     bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1235     ++alias_count;
1236   }
1237   pp = hp->h_addr_list;
1238   while (*pp++) {
1239     bytes_needed += (hp->h_length + sizeof(char*));
1240     ++addr_count;
1241   }
1242   /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1243   bytes_needed += (2 * sizeof(char*));
1244
1245   /* Allocate memory */
1246   new_hp->buf = (char*) MyMalloc(bytes_needed);
1247
1248   new_hp->h.h_addrtype = hp->h_addrtype;
1249   new_hp->h.h_length = hp->h_length;
1250
1251   /* first write the address list */
1252   pp = hp->h_addr_list;
1253   ap = new_hp->h.h_addr_list =
1254       (char**)(new_hp->buf + ((alias_count + 1) * sizeof(char*)));
1255   p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1256   while (*pp)
1257   {
1258     *ap++ = p;
1259     memcpy(p, *pp++, hp->h_length);
1260     p += hp->h_length;
1261   }
1262   *ap = 0;
1263   /* next write the name */
1264   new_hp->h.h_name = p;
1265   strcpy(p, hp->h_name);
1266   p += (strlen(p) + 1);
1267
1268   /* last write the alias list */
1269   pp = hp->h_aliases;
1270   ap = new_hp->h.h_aliases = (char**) new_hp->buf;
1271   while (*pp) {
1272     *ap++ = p;
1273     strcpy(p, *pp++);
1274     p += (strlen(p) + 1);
1275   }
1276   *ap = 0;
1277 }
1278
1279 /*
1280  * update_hostent - Add records to a Hostent struct in place.
1281  */
1282 static void update_hostent(struct Hostent* hp, char** addr, char** alias)
1283 {
1284   char*  p;
1285   char** ap;
1286   char** pp;
1287   int    alias_count = 0;
1288   int    addr_count = 0;
1289   char*  buf = NULL;
1290   size_t bytes_needed = 0;
1291
1292   if (!hp || !hp->buf)
1293     return;
1294
1295   /* how much buffer do we need? */
1296   bytes_needed = strlen(hp->h.h_name) + 1;
1297   pp = hp->h.h_aliases;
1298   while (*pp) {
1299     bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1300     ++alias_count;
1301   }
1302   if (alias) {
1303     pp = alias;
1304     while (*pp) {
1305       bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1306       ++alias_count;
1307     }
1308   }
1309   pp = hp->h.h_addr_list;
1310   while (*pp++) {
1311     bytes_needed += (hp->h.h_length + sizeof(char*));
1312     ++addr_count;
1313   }
1314   if (addr) {
1315     pp = addr;
1316     while (*pp++) {
1317       bytes_needed += (hp->h.h_length + sizeof(char*));
1318       ++addr_count;
1319     }
1320   }
1321   /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1322   bytes_needed += 2 * sizeof(char*);
1323
1324   /* Allocate memory */
1325   buf = (char*) MyMalloc(bytes_needed);
1326   assert(0 != buf);
1327
1328   /* first write the address list */
1329   pp = hp->h.h_addr_list;
1330   ap = hp->h.h_addr_list =
1331       (char**)(buf + ((alias_count + 1) * sizeof(char*)));
1332   p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1333   while (*pp) {
1334     memcpy(p, *pp++, hp->h.h_length);
1335     *ap++ = p;
1336     p += hp->h.h_length;
1337   }
1338   if (addr) {
1339     while (*addr) {
1340       memcpy(p, *addr++, hp->h.h_length);
1341       *ap++ = p;
1342       p += hp->h.h_length;
1343     }
1344   }
1345   *ap = 0;
1346
1347   /* next write the name */
1348   strcpy(p, hp->h.h_name);
1349   hp->h.h_name = p;
1350   p += (strlen(p) + 1);
1351
1352   /* last write the alias list */
1353   pp = hp->h.h_aliases;
1354   ap = hp->h.h_aliases = (char**) buf;
1355   while (*pp) {
1356     strcpy(p, *pp++);
1357     *ap++ = p;
1358     p += (strlen(p) + 1);
1359   }
1360   if (alias) {
1361     while (*alias) {
1362       strcpy(p, *alias++);
1363       *ap++ = p;
1364       p += (strlen(p) + 1);
1365     }
1366   }
1367   *ap = 0;
1368   /* release the old buffer */
1369   p = hp->buf;
1370   hp->buf = buf;
1371   MyFree(p);
1372 }
1373
1374 /*
1375  * hash_number - IP address hash function
1376  */
1377 static int hash_number(const unsigned char* ip)
1378 {
1379   /* could use loop but slower */
1380   unsigned int hashv;
1381   const u_char* p = (const u_char*) ip;
1382
1383   assert(0 != p);
1384
1385   hashv = *p++;
1386   hashv += hashv + *p++;
1387   hashv += hashv + *p++;
1388   hashv += hashv + *p;
1389   hashv %= ARES_CACSIZE;
1390   return hashv;
1391 }
1392
1393 /*
1394  * hash_name - hostname hash function
1395  */
1396 static int hash_name(const char* name)
1397 {
1398   unsigned int hashv = 0;
1399   const u_char* p = (const u_char*) name;
1400
1401   assert(0 != p);
1402
1403   for (; *p && *p != '.'; ++p)
1404     hashv += *p;
1405   hashv %= ARES_CACSIZE;
1406   return hashv;
1407 }
1408
1409 /*
1410  * add_to_cache - Add a new cache item to the queue and hash table.
1411  */
1412 static struct CacheEntry* add_to_cache(struct CacheEntry* ocp)
1413 {
1414   int  hashv;
1415
1416   assert(0 != ocp);
1417
1418   ocp->list_next = cacheTop;
1419   cacheTop = ocp;
1420
1421   hashv = hash_name(ocp->he.h.h_name);
1422
1423   ocp->hname_next = hashtable[hashv].name_list;
1424   hashtable[hashv].name_list = ocp;
1425
1426   hashv = hash_number((const unsigned char*) ocp->he.h.h_addr);
1427
1428   ocp->hnum_next = hashtable[hashv].num_list;
1429   hashtable[hashv].num_list = ocp;
1430
1431   /*
1432    * LRU deletion of excessive cache entries.
1433    */
1434   if (++cachedCount > MAXCACHED) {
1435     struct CacheEntry* cp;
1436     struct CacheEntry* cp_next;
1437     for (cp = ocp->list_next; cp; cp = cp_next) {
1438       cp_next = cp->list_next;
1439       rem_cache(cp);
1440     }
1441   }
1442   ++cainfo.ca_adds;
1443   return ocp;
1444 }
1445
1446 /*
1447  * update_list - does not alter the cache structure passed. It is assumed that
1448  * it already contains the correct expire time, if it is a new entry. Old
1449  * entries have the expirey time updated.
1450 */
1451 static void update_list(struct ResRequest* request, struct CacheEntry* cachep)
1452 {
1453   struct CacheEntry*  cp = cachep;
1454   char*    s;
1455   char*    t;
1456   int      i;
1457   int      j;
1458   char**   ap;
1459   char*    addrs[RES_MAXADDRS + 1];
1460   char*    aliases[RES_MAXALIASES + 1];
1461
1462   /*
1463    * search for the new cache item in the cache list by hostname.
1464    * If found, move the entry to the top of the list and return.
1465    */
1466   ++cainfo.ca_updates;
1467
1468   if (!request)
1469     return;
1470   /*
1471    * Compare the cache entry against the new record.  Add any
1472    * previously missing names for this entry.
1473    */
1474   *aliases = 0;
1475   ap = aliases;
1476   for (i = 0, s = request->he.h.h_name; s; s = request->he.h.h_aliases[i++]) {
1477     for (j = 0, t = cp->he.h.h_name; t; t = cp->he.h.h_aliases[j++]) {
1478       if (0 == ircd_strcmp(t, s))
1479         break;
1480     }
1481     if (!t) {
1482       *ap++ = s;
1483       *ap = 0;
1484     }
1485   }
1486   /*
1487    * Do the same again for IP#'s.
1488    */
1489   *addrs = 0;
1490   ap = addrs;
1491   for (i = 0; (s = request->he.h.h_addr_list[i]); i++) {
1492     for (j = 0; (t = cp->he.h.h_addr_list[j]); j++) {
1493       if (!memcmp(t, s, sizeof(struct in_addr)))
1494         break;
1495     }
1496     if (!t) {
1497       *ap++ = s;
1498       *ap = 0;
1499     }
1500   }
1501   if (*addrs || *aliases)
1502     update_hostent(&cp->he, addrs, aliases);
1503 }
1504
1505 /*
1506  * find_cache_name - find name in nameserver cache
1507  */
1508 static struct CacheEntry* find_cache_name(const char* name)
1509 {
1510   struct CacheEntry* cp;
1511   char*   s;
1512   int     hashv;
1513   int     i;
1514
1515   assert(0 != name);
1516   hashv = hash_name(name);
1517
1518   cp = hashtable[hashv].name_list;
1519
1520   for (; cp; cp = cp->hname_next) {
1521     for (i = 0, s = cp->he.h.h_name; s; s = cp->he.h.h_aliases[i++]) {
1522       if (0 == ircd_strcmp(s, name)) {
1523         ++cainfo.ca_na_hits;
1524         return cp;
1525       }
1526     }
1527   }
1528
1529   for (cp = cacheTop; cp; cp = cp->list_next) {
1530     /*
1531      * if no aliases or the hash value matches, we've already
1532      * done this entry and all possiblilities concerning it.
1533      */
1534     if (!cp->he.h.h_name || hashv == hash_name(cp->he.h.h_name))
1535       continue;
1536     for (i = 0, s = cp->he.h.h_aliases[i]; s; s = cp->he.h.h_aliases[++i]) {
1537       if (0 == ircd_strcmp(name, s)) {
1538         ++cainfo.ca_na_hits;
1539         return cp;
1540       }
1541     }
1542   }
1543   return NULL;
1544 }
1545
1546 /*
1547  * find_cache_number - find a cache entry by ip# and update its expire time
1548  */
1549 static struct CacheEntry* find_cache_number(struct ResRequest* request,
1550                                             const char* addr)
1551 {
1552   struct CacheEntry* cp;
1553   int     hashv;
1554   int     i;
1555
1556   assert(0 != addr);
1557   hashv = hash_number((const unsigned char*) addr);
1558   cp = hashtable[hashv].num_list;
1559
1560   for (; cp; cp = cp->hnum_next) {
1561     for (i = 0; cp->he.h.h_addr_list[i]; ++i) {
1562       if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1563         ++cainfo.ca_nu_hits;
1564         return cp;
1565       }
1566     }
1567   }
1568   for (cp = cacheTop; cp; cp = cp->list_next) {
1569     /*
1570      * single address entry...would have been done by hashed
1571      * search above...
1572      * if the first IP# has the same hashnumber as the IP# we
1573      * are looking for, its been done already.
1574      */
1575     if (!cp->he.h.h_addr_list[1] || 
1576         hashv == hash_number((const unsigned char*) cp->he.h.h_addr_list[0]))
1577       continue;
1578     for (i = 1; cp->he.h.h_addr_list[i]; ++i) {
1579       if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1580         ++cainfo.ca_nu_hits;
1581         return cp;
1582       }
1583     }
1584   }
1585   return NULL;
1586 }
1587
1588 static struct CacheEntry* make_cache(struct ResRequest* request)
1589 {
1590   struct CacheEntry* cp;
1591   int     i;
1592   struct hostent* hp;
1593   assert(0 != request);
1594
1595   hp = &request->he.h;
1596   /*
1597    * shouldn't happen but it just might...
1598    */
1599   assert(0 != hp->h_name);
1600   assert(0 != hp->h_addr_list[0]);
1601   if (!hp->h_name || !hp->h_addr_list[0])
1602     return NULL;
1603   /*
1604    * Make cache entry.  First check to see if the cache already exists
1605    * and if so, return a pointer to it.
1606    */
1607   for (i = 0; hp->h_addr_list[i]; ++i) {
1608     if ((cp = find_cache_number(request, hp->h_addr_list[i]))) {
1609       update_list(request, cp);
1610       return cp;
1611     }
1612   }
1613   /*
1614    * a matching entry wasnt found in the cache so go and make one up.
1615    */ 
1616   cp = (struct CacheEntry*) MyMalloc(sizeof(struct CacheEntry));
1617   assert(0 != cp);
1618
1619   memset(cp, 0, sizeof(struct CacheEntry));
1620   dup_hostent(&cp->he, hp);
1621   cp->reply.hp = &cp->he.h;
1622   /*
1623    * hmmm... we could time out the cache after 10 minutes regardless
1624    * would that be reasonable since we don't save the reply?
1625    */ 
1626   if (request->ttl < AR_TTL) {
1627     ++reinfo.re_shortttl;
1628     cp->ttl = AR_TTL;
1629   }
1630   else
1631     cp->ttl = request->ttl;
1632   cp->expireat = CurrentTime + cp->ttl;
1633   return add_to_cache(cp);
1634 }
1635
1636 /*
1637  * rem_cache - delete a cache entry from the cache structures 
1638  * and lists and return all memory used for the cache back to the memory pool.
1639  */
1640 static void rem_cache(struct CacheEntry* ocp)
1641 {
1642   struct CacheEntry** cp;
1643   int                 hashv;
1644   struct hostent*     hp;
1645   assert(0 != ocp);
1646
1647
1648   if (0 < ocp->reply.ref_count) {
1649     if (ocp->expireat < CurrentTime) {
1650       ocp->expireat = CurrentTime + AR_TTL;
1651       Debug((DEBUG_DNS, "Resolver: referenced cache entry not removed for: %s",
1652             ocp->he.h.h_name));
1653     }
1654     return;
1655   }
1656   /*
1657    * remove cache entry from linked list
1658    */
1659   for (cp = &cacheTop; *cp; cp = &((*cp)->list_next)) {
1660     if (*cp == ocp) {
1661       *cp = ocp->list_next;
1662       break;
1663     }
1664   }
1665   hp = &ocp->he.h;
1666   /*
1667    * remove cache entry from hashed name list
1668    */
1669   assert(0 != hp->h_name);
1670   hashv = hash_name(hp->h_name);
1671
1672   for (cp = &hashtable[hashv].name_list; *cp; cp = &((*cp)->hname_next)) {
1673     if (*cp == ocp) {
1674       *cp = ocp->hname_next;
1675       break;
1676     }
1677   }
1678   /*
1679    * remove cache entry from hashed number list
1680    */
1681   hashv = hash_number((const unsigned char*) hp->h_addr);
1682   assert(-1 < hashv);
1683
1684   for (cp = &hashtable[hashv].num_list; *cp; cp = &((*cp)->hnum_next)) {
1685     if (*cp == ocp) {
1686       *cp = ocp->hnum_next;
1687       break;
1688     }
1689   }
1690   /*
1691    * free memory used to hold the various host names and the array
1692    * of alias pointers.
1693    */
1694   MyFree(ocp->he.buf);
1695   MyFree(ocp);
1696   --cachedCount;
1697   ++cainfo.ca_dels;
1698 }
1699
1700 void flush_resolver_cache(void)
1701 {
1702   /*
1703    * stubbed - iterate cache and remove everything that isn't referenced
1704    */
1705 }
1706
1707 /*
1708  * m_dns - dns status query
1709  */
1710 int m_dns(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1711 {
1712 #if !defined(NDEBUG)
1713   struct CacheEntry* cp;
1714   int     i;
1715   struct hostent* hp;
1716
1717   if (parv[1] && *parv[1] == 'l') {
1718     for(cp = cacheTop; cp; cp = cp->list_next) {
1719       hp = &cp->he.h;
1720       sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :Ex %d ttl %d host %s(%s)",
1721                     sptr, cp->expireat - CurrentTime, cp->ttl,
1722                     hp->h_name, ircd_ntoa(hp->h_addr));
1723       for (i = 0; hp->h_aliases[i]; i++)
1724         sendcmdto_one(&me, CMD_NOTICE, sptr, "%C : %s = %s (CN)", sptr,
1725                       hp->h_name, hp->h_aliases[i]);
1726       for (i = 1; hp->h_addr_list[i]; i++)
1727         sendcmdto_one(&me, CMD_NOTICE, sptr, "%C : %s = %s (IP)", sptr,
1728                       hp->h_name, ircd_ntoa(hp->h_addr_list[i]));
1729     }
1730     return 0;
1731   }
1732   if (parv[1] && *parv[1] == 'd') {
1733     sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :ResolverFileDescriptor = %d", 
1734                   sptr, ResolverFileDescriptor);
1735     return 0;
1736   }
1737   sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ca %d Cd %d Ce %d Cl %d Ch %d:%d "
1738                 "Cu %d", sptr,
1739                 cainfo.ca_adds, cainfo.ca_dels, cainfo.ca_expires,
1740                 cainfo.ca_lookups, cainfo.ca_na_hits, cainfo.ca_nu_hits, 
1741                 cainfo.ca_updates);
1742   
1743   sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Re %d Rl %d/%d Rp %d Rq %d",
1744                 sptr, reinfo.re_errors, reinfo.re_nu_look,
1745                 reinfo.re_na_look, reinfo.re_replies, reinfo.re_requests);
1746   sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ru %d Rsh %d Rs %d(%d) Rt %d", sptr,
1747                 reinfo.re_unkrep, reinfo.re_shortttl, reinfo.re_sent,
1748                 reinfo.re_resends, reinfo.re_timeouts);
1749 #endif
1750   return 0;
1751 }
1752
1753 size_t cres_mem(struct Client* sptr)
1754 {
1755   struct CacheEntry* entry;
1756   struct ResRequest* request;
1757   size_t cache_mem     = 0;
1758   size_t request_mem   = 0;
1759   int    cache_count   = 0;
1760   int    request_count = 0;
1761
1762   for (entry = cacheTop; entry; entry = entry->list_next) {
1763     cache_mem += sizeof(struct CacheEntry);
1764     cache_mem += calc_hostent_buffer_size(&entry->he.h); 
1765     ++cache_count;
1766   }
1767   for (request = requestListHead; request; request = request->next) {
1768     request_mem += sizeof(struct ResRequest);
1769     if (request->name)
1770       request_mem += strlen(request->name) + 1; 
1771     if (request->he.buf)
1772       request_mem += MAXGETHOSTLEN + 1;
1773     ++request_count;
1774   }
1775
1776   if (cachedCount != cache_count) {
1777     send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1778                ":Resolver: cache count mismatch: %d != %d", cachedCount,
1779                cache_count);
1780     assert(cachedCount == cache_count);
1781   }
1782   send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1783              ":Resolver: cache %d(%d) requests %d(%d)", cache_count,
1784              cache_mem, request_count, request_mem);
1785   return cache_mem + request_mem;
1786 }
1787