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.
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>)
18 #include "ircd_alloc.h"
19 #include "ircd_events.h"
21 #include "ircd_osdep.h"
22 #include "ircd_reply.h"
23 #include "ircd_string.h"
30 #include "sprintf_irc.h"
40 #include <sys/socket.h>
45 #include <arpa/nameser.h>
48 #include <arpa/inet.h>
52 #error this code needs to be able to address individual octets
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.
64 #define INADDR_NONE ((unsigned int) 0xffffffff)
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 */
71 * OSF1 doesn't have RES_NOALIASES
74 #define RES_NOALIASES 0
78 * macros used to calulate offsets into fixed query buffer
80 #define ALIAS_BLEN ((RES_MAXALIASES + 1) * sizeof(char*))
81 #define ADDRS_BLEN ((RES_MAXADDRS + 1) * sizeof(struct in_addr*))
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)
88 #define AR_TTL 600 /* TTL in seconds for dns cache entries */
91 * the following values should be prime
93 #define ARES_CACSIZE 307
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.
104 #define RDLENGTH_SIZE 2
105 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
108 * Building the Hostent
109 * The Hostent struct is arranged like this:
110 * +-------------------------------+
111 * Hostent: | struct hostent h |
112 * |-------------------------------|
114 * +-------------------------------+
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
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.
151 * Filling the buffer this way allows for proper alignment of the h_addr_list
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
165 struct hostent h; /* the hostent struct we are passing around */
166 char* buf; /* buffer for data pointed to from hostent */
170 struct ResRequest* next;
172 int sent; /* number of requests sent */
175 char retries; /* retry counter */
176 char sends; /* number of sends (>1 means resent) */
177 char resend; /* send flag. 0 == dont resend */
182 struct DNSQuery query; /* query callback for this request */
187 struct CacheEntry* hname_next;
188 struct CacheEntry* hnum_next;
189 struct CacheEntry* list_next;
193 struct DNSReply reply;
197 struct CacheEntry* num_list;
198 struct CacheEntry* name_list;
202 int ResolverFileDescriptor = -1; /* GLOBAL - used in s_bsd.c */
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 */
208 static time_t nextDNSCheck = 0;
209 static time_t nextCacheExpire = 1;
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
218 static int spare_fd = -1;
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 */
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,
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,
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,
248 static struct ResRequest* find_id(int);
250 static struct cacheinfo {
260 static struct resinfo {
275 * From bind 8.3, these aren't declared in earlier versions of bind
277 extern u_short _getshort(const u_char *);
278 extern u_int _getlong(const u_char *);
281 * res_isourserver(ina)
282 * looks up "ina" in _res.ns_addr_list[]
287 * paul vixie, 29may94
290 res_ourserver(const struct __res_state* statp, const struct sockaddr_in* inp)
292 struct sockaddr_in ina;
296 for (ns = 0; ns < statp->nscount; ns++) {
297 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
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))
308 /* Socket callback for resolver */
309 static void res_callback(struct Event* ev)
311 assert(ev_type(ev) == ET_READ);
317 * start_resolver - do everything we need to read the resolv.conf file
318 * and initialize the resolver file descriptor if needed
320 static void start_resolver(void)
322 Debug((DEBUG_DNS, "Resolver: start_resolver"));
324 * close the spare file descriptor so res_init can read resolv.conf
325 * successfully. Needed on Solaris
330 res_init(); /* res_init always returns 0 */
332 * make sure we have a valid file descriptor below 256 so we can
333 * do this again. Needed on Solaris
335 spare_fd = open("/dev/null",O_RDONLY,0);
336 if ((spare_fd < 0) || (spare_fd > 255)) {
338 sprintf_irc(sparemsg, "invalid spare_fd %d", spare_fd);
339 server_restart(sparemsg);
344 _res.nsaddr_list[0].sin_addr.s_addr = inet_addr("127.0.0.1");
346 _res.options |= RES_NOALIASES;
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);
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);
365 /* Call the query timeout function */
366 static void expire_DNS_callback(struct Event* ev)
370 next = timeout_query_list(CurrentTime);
372 timer_add(&resExpireDNS, expire_DNS_callback, 0, TT_ABSOLUTE, next);
375 /* Call the cache expire function */
376 static void expire_cache_callback(struct Event* ev)
380 next = expire_cache(CurrentTime);
382 timer_add(&resExpireCache, expire_cache_callback, 0, TT_ABSOLUTE, next);
386 * init_resolver - initialize resolver and resolver library
388 int init_resolver(void)
390 Debug((DEBUG_DNS, "Resolver: init_resolver"));
392 srand48(CurrentTime);
394 memset(&cainfo, 0, sizeof(cainfo));
395 memset(hashtable, 0, sizeof(hashtable));
396 memset(&reinfo, 0, sizeof(reinfo));
398 requestListHead = requestListTail = 0;
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);
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;
414 * restart_resolver - flush the cache, reread resolv.conf, reopen socket
416 void restart_resolver(void)
418 /* flush_cache(); flush the dns cache */
422 static int validate_hostent(const struct hostent* hp)
427 for (name = hp->h_name; name; name = hp->h_aliases[i++]) {
428 if (!string_is_hostname(name))
435 * add_request - place a new request in the request list
437 static void add_request(struct ResRequest* request)
439 assert(0 != request);
440 if (!requestListHead)
441 requestListHead = requestListTail = request;
443 requestListTail->next = request;
444 requestListTail = request;
446 request->next = NULL;
447 ++reinfo.re_requests;
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.
455 static void rem_request(struct ResRequest* request)
457 struct ResRequest** current;
458 struct ResRequest* prev = NULL;
460 assert(0 != request);
461 for (current = &requestListHead; *current; ) {
462 if (*current == request) {
463 *current = request->next;
464 if (requestListTail == request)
465 requestListTail = prev;
469 current = &(*current)->next;
471 MyFree(request->he.buf);
472 MyFree(request->name);
477 * make_request - Create a DNS request record for the server.
479 static struct ResRequest* make_request(const struct DNSQuery* query)
481 struct ResRequest* request;
483 request = (struct ResRequest*) MyMalloc(sizeof(struct ResRequest));
484 memset(request, 0, sizeof(struct ResRequest));
486 request->sentat = CurrentTime;
487 request->retries = 3;
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;
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;
503 add_request(request);
508 * timeout_query_list - Remove queries from the list which have been
509 * there too long without being resolved.
511 static time_t timeout_query_list(time_t now)
513 struct ResRequest* request;
514 struct ResRequest* next_request = 0;
515 time_t next_time = 0;
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;
523 if (--request->retries <= 0) {
524 ++reinfo.re_timeouts;
525 (*request->query.callback)(request->query.vptr, 0);
526 rem_request(request);
530 request->sentat = now;
531 request->timeout += request->timeout;
532 resend_query(request);
535 if (!next_time || timeout < next_time) {
539 return (next_time > now) ? next_time : (now + AR_TTL);
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.
547 static time_t expire_cache(time_t now)
549 struct CacheEntry* cp;
550 struct CacheEntry* cp_next;
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) {
560 else if (!expire || expire > cp->expireat)
561 expire = cp->expireat;
563 return (expire > now) ? expire : (now + AR_TTL);
567 * timeout_resolver - check request list and cache for expired entries
569 time_t timeout_resolver(time_t now)
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);
580 * delete_resolver_queries - cleanup outstanding queries
581 * for which there no longer exist clients or conf lines.
583 void delete_resolver_queries(const void* vptr)
585 struct ResRequest* request;
586 struct ResRequest* next_request;
588 for (request = requestListHead; request; request = next_request) {
589 next_request = request->next;
590 if (vptr == request->query.vptr)
591 rem_request(request);
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.
602 static int send_res_msg(const u_char* msg, int len, int rcount)
606 int max_queries = IRCD_MIN(_res.nscount, rcount);
610 * RES_PRIMARY option is not implemented
611 * if (_res.options & RES_PRIMARY || 0 == max_queries)
613 if (0 == max_queries)
616 Debug((DEBUG_DNS, "Resolver: sendto %d", max_queries));
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) {
626 log_write(LS_RESOLVER, L_ERROR, 0, "Resolver: send failed %m");
632 * find_id - find a dns request id (id is determined by dn_mkquery)
634 static struct ResRequest* find_id(int id)
636 struct ResRequest* request;
638 for (request = requestListHead; request; request = request->next) {
639 if (request->id == id)
646 * gethost_byname - get host address from name
648 struct DNSReply* gethost_byname(const char* name,
649 const struct DNSQuery* query)
651 struct CacheEntry* cp;
654 Debug((DEBUG_DNS, "Resolver: gethost_byname %s", name));
656 if ((cp = find_cache_name(name)))
659 do_query_name(query, name, NULL);
665 * gethost_byaddr - get host name from address
667 struct DNSReply* gethost_byaddr(const char* addr,
668 const struct DNSQuery* query)
670 struct CacheEntry *cp;
674 Debug((DEBUG_DNS, "Resolver: gethost_byaddr %s", ircd_ntoa(addr)));
677 if ((cp = find_cache_number(NULL, addr)))
680 do_query_number(query, (const struct in_addr*) addr, NULL);
686 * do_query_name - nameserver lookup name
688 static void do_query_name(const struct DNSQuery* query,
689 const char* name, struct ResRequest* request)
691 char hname[HOSTLEN + 1];
694 ircd_strncpy(hname, name, HOSTLEN);
695 hname[HOSTLEN] = '\0';
698 request = make_request(query);
700 request->name = (char*) MyMalloc(strlen(hname) + 1);
701 strcpy(request->name, hname);
703 query_name(hname, C_IN, T_A, request);
707 * do_query_number - Use this to do reverse IP# lookups.
709 static void do_query_number(const struct DNSQuery* query,
710 const struct in_addr* addr,
711 struct ResRequest* request)
714 const unsigned char* cp;
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]));
723 request = make_request(query);
724 request->type = T_PTR;
725 request->addr.s_addr = addr->s_addr;
727 query_name(ipbuf, C_IN, T_PTR, request);
731 * query_name - generate a query based on class, type and name.
733 static void query_name(const char* name, int query_class,
734 int type, struct ResRequest* request)
740 assert(0 != request);
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;
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
759 header->id = (header->id + lrand48()) & 0xffff;
760 } while (find_id(header->id));
762 gettimeofday(&tv, NULL);
764 header->id = (header->id + k + tv.tv_usec) & 0xffff;
766 } while (find_id(header->id));
768 request->id = header->id;
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);
776 static void resend_query(struct ResRequest* request)
778 assert(0 != request);
780 if (request->resend == 0)
783 switch(request->type) {
785 do_query_number(NULL, &request->addr, request);
788 do_query_name(NULL, request->name, request);
796 * proc_answer - process name server reply
797 * build a hostent struct in the passed request
799 static int proc_answer(struct ResRequest* request, HEADER* header,
800 u_char* buf, u_char* eob)
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 */
818 assert(0 != request);
823 current = buf + sizeof(HEADER);
824 hp = &(request->he.h);
826 * lazy allocation of request->he.buf, we don't allocate a buffer
827 * unless there is something to put in it.
829 if (!request->he.buf) {
830 request->he.buf = (char*) MyMalloc(MAXGETHOSTLEN + 1);
831 request->he.buf[MAXGETHOSTLEN] = '\0';
833 * array of alias list pointers starts at beginning of buf
835 hp->h_aliases = (char**) request->he.buf;
836 hp->h_aliases[0] = NULL;
838 * array of address list pointers starts after alias list pointers
839 * the actual addresses follow the the address list pointers
841 hp->h_addr_list = (char**)(request->he.buf + ALIAS_BLEN);
843 * don't copy the host address to the beginning of h_addr_list
845 hp->h_addr_list[0] = NULL;
847 endp = request->he.buf + MAXGETHOSTLEN;
849 * find the end of the address list
851 addr = hp->h_addr_list;
857 * make address point to first available address slot
859 address = request->he.buf + ADDRS_OFFSET +
860 (sizeof(struct in_addr) * addr_count);
862 * find the end of the alias list
864 alias = hp->h_aliases;
870 * make name point to first available space in request->buf
872 if (alias_count > 0) {
873 name = hp->h_aliases[alias_count - 1];
874 name += (strlen(name) + 1);
877 name = hp->h_name + strlen(hp->h_name) + 1;
879 name = request->he.buf + ADDRS_OFFSET + ADDRS_DLEN;
884 while (header->qdcount-- > 0) {
885 if ((n = dn_skipname(current, eob)) < 0)
887 current += (n + QFIXEDSZ);
890 * process each answer sent to us blech.
892 while (header->ancount-- > 0 && current < eob && name < endp) {
893 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
896 * no more answers left
900 hostbuf[HOSTLEN] = '\0';
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)
906 current += (size_t) n;
908 if (!((current + ANSWER_FIXED_SIZE) < eob))
911 type = _getshort(current);
912 current += TYPE_SIZE;
914 query_class = _getshort(current);
915 current += CLASS_SIZE;
917 request->ttl = _getlong(current);
920 rd_length = _getshort(current);
921 current += RDLENGTH_SIZE;
924 * Wait to set request->type until we verify this structure
929 * check for invalid rd_length or too many addresses
931 if (rd_length != sizeof(struct in_addr))
933 if (++addr_count < RES_MAXADDRS) {
934 if (answer_count == 1)
935 hp->h_addrtype = (query_class == C_IN) ? AF_INET : AF_UNSPEC;
937 memcpy(address, current, sizeof(struct in_addr));
940 address += sizeof(struct in_addr);
943 strcpy(name, hostbuf);
945 name += strlen(name) + 1;
947 Debug((DEBUG_DNS, "Resolver: A %s for %s",
948 ircd_ntoa((char*) hp->h_addr_list[addr_count - 1]), hostbuf));
950 current += rd_length;
954 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
963 * no more answers left
968 * This comment is based on analysis by Shadowfax, Wohali and johan,
969 * not me. (Dianora) I am only commenting it.
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.
976 hostbuf[HOSTLEN] = '\0';
977 current += (size_t) n;
979 Debug((DEBUG_DNS, "Resolver: PTR %s", hostbuf));
981 * copy the returned hostname into the host name
982 * ignore duplicate ptr records
985 strcpy(name, hostbuf);
987 name += strlen(name) + 1;
992 Debug((DEBUG_DNS, "Resolver: CNAME %s", hostbuf));
993 if (++alias_count < RES_MAXALIASES) {
994 ircd_strncpy(name, hostbuf, endp - name);
997 name += strlen(name) + 1;
999 current += rd_length;
1003 Debug((DEBUG_DNS,"Resolver: proc_answer type: %d for: %s", type, hostbuf));
1007 return answer_count;
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
1014 int resolver_read(void)
1016 u_char buf[sizeof(HEADER) + MAXPACKET];
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;
1024 Debug((DEBUG_DNS, "Resolver: read"));
1025 if (IO_SUCCESS != os_recvfrom_nonb(ResolverFileDescriptor,
1026 (char*) buf, sizeof(buf), &rc, &sin)) {
1029 if (rc < sizeof(HEADER)) {
1030 Debug((DEBUG_DNS, "Resolver: short reply %d: %s", rc,
1031 (strerror(errno)) ? strerror(errno) : "Unknown"));
1035 * convert DNS reply reader from Network byte order to CPU byte order.
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;
1045 * response for an id which we have already received an answer for
1046 * just ignore this response.
1048 if (0 == (request = find_id(header->id))) {
1049 Debug((DEBUG_DNS, "Resolver: can't find request id: %d", header->id));
1053 * check against possibly fake replies
1055 if (!res_ourserver(&_res, &sin)) {
1056 Debug((DEBUG_DNS, "Resolver: fake reply from: %s", (const char*) &sin.sin_addr));
1061 if ((header->rcode != NOERROR) || (header->ancount == 0)) {
1063 if (SERVFAIL == header->rcode)
1064 resend_query(request);
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
1073 switch (header->rcode) {
1075 Debug((DEBUG_DNS, "Fatal DNS error: No Error"));
1078 Debug((DEBUG_DNS, "Fatal DNS error: Format Error"));
1081 Debug((DEBUG_DNS, "Fatal DNS error: Server Failure"));
1084 Debug((DEBUG_DNS, "DNS error: Non Existant Domain"));
1087 Debug((DEBUG_DNS, "Fatal DNS error: Not Implemented"));
1090 Debug((DEBUG_DNS, "Fatal DNS error: Query Refused"));
1093 Debug((DEBUG_DNS, "Unassigned fatal DNS error: %i", header->rcode));
1096 #endif /* DEBUGMODE */
1097 (*request->query.callback)(request->query.vptr, 0);
1098 rem_request(request);
1103 * If this fails there was an error decoding the received packet,
1104 * try it again and hope it works the next time.
1106 answer_count = proc_answer(request, header, buf, buf + rc);
1108 if (T_PTR == request->type) {
1109 struct DNSReply* reply = 0;
1110 if (0 == request->he.h.h_name) {
1112 * got a PTR response with no name, something bogus is happening
1113 * don't bother trying again, the client address doesn't resolve
1115 (*request->query.callback)(request->query.vptr, reply);
1116 rem_request(request);
1119 Debug((DEBUG_DNS, "relookup %s <-> %s",
1120 request->he.h.h_name, ircd_ntoa((char*) &request->addr)));
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
1127 reply = gethost_byname(request->he.h.h_name, &request->query);
1129 (*request->query.callback)(request->query.vptr, reply);
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
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));
1142 rem_request(request);
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.
1152 struct DNSReply* reply = 0;
1153 if (validate_hostent(&request->he.h)) {
1154 if ((cp = make_cache(request)))
1157 (*request->query.callback)(request->query.vptr, reply);
1158 rem_request(request);
1161 else if (!request->sent) {
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
1166 (*request->query.callback)(request->query.vptr, 0);
1167 rem_request(request);
1173 * resolver_read_multiple - process up to count reads
1175 void resolver_read_multiple(int count)
1178 for ( ; i < count; ++i) {
1179 if (0 == resolver_read())
1184 static size_t calc_hostent_buffer_size(const struct hostent* hp)
1193 count += (strlen(hp->h_name) + 1);
1197 for (p = hp->h_aliases; *p; ++p)
1198 count += (strlen(*p) + 1 + sizeof(char*));
1200 * space for addresses
1202 for (p = hp->h_addr_list; *p; ++p)
1203 count += (hp->h_length + sizeof(char*));
1205 * space for 2 nulls to terminate h_aliases and h_addr_list
1207 count += (2 * sizeof(char*));
1213 * dup_hostent - Duplicate a hostent struct, allocate only enough memory for
1214 * the data we're putting in it.
1216 static void dup_hostent(struct Hostent* new_hp, struct hostent* hp)
1221 int alias_count = 0;
1223 size_t bytes_needed = 0;
1225 assert(0 != new_hp);
1228 /* how much buffer do we need? */
1229 bytes_needed += (strlen(hp->h_name) + 1);
1233 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1236 pp = hp->h_addr_list;
1238 bytes_needed += (hp->h_length + sizeof(char*));
1241 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1242 bytes_needed += (2 * sizeof(char*));
1244 /* Allocate memory */
1245 new_hp->buf = (char*) MyMalloc(bytes_needed);
1247 new_hp->h.h_addrtype = hp->h_addrtype;
1248 new_hp->h.h_length = hp->h_length;
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*));
1258 memcpy(p, *pp++, hp->h_length);
1262 /* next write the name */
1263 new_hp->h.h_name = p;
1264 strcpy(p, hp->h_name);
1265 p += (strlen(p) + 1);
1267 /* last write the alias list */
1269 ap = new_hp->h.h_aliases = (char**) new_hp->buf;
1273 p += (strlen(p) + 1);
1279 * update_hostent - Add records to a Hostent struct in place.
1281 static void update_hostent(struct Hostent* hp, char** addr, char** alias)
1286 int alias_count = 0;
1289 size_t bytes_needed = 0;
1291 if (!hp || !hp->buf)
1294 /* how much buffer do we need? */
1295 bytes_needed = strlen(hp->h.h_name) + 1;
1296 pp = hp->h.h_aliases;
1298 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1304 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1308 pp = hp->h.h_addr_list;
1310 bytes_needed += (hp->h.h_length + sizeof(char*));
1316 bytes_needed += (hp->h.h_length + sizeof(char*));
1320 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1321 bytes_needed += 2 * sizeof(char*);
1323 /* Allocate memory */
1324 buf = (char*) MyMalloc(bytes_needed);
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*));
1333 memcpy(p, *pp++, hp->h.h_length);
1335 p += hp->h.h_length;
1339 memcpy(p, *addr++, hp->h.h_length);
1341 p += hp->h.h_length;
1346 /* next write the name */
1347 strcpy(p, hp->h.h_name);
1349 p += (strlen(p) + 1);
1351 /* last write the alias list */
1352 pp = hp->h.h_aliases;
1353 ap = hp->h.h_aliases = (char**) buf;
1357 p += (strlen(p) + 1);
1361 strcpy(p, *alias++);
1363 p += (strlen(p) + 1);
1367 /* release the old buffer */
1374 * hash_number - IP address hash function
1376 static int hash_number(const unsigned char* ip)
1378 /* could use loop but slower */
1380 const u_char* p = (const u_char*) ip;
1385 hashv += hashv + *p++;
1386 hashv += hashv + *p++;
1387 hashv += hashv + *p;
1388 hashv %= ARES_CACSIZE;
1393 * hash_name - hostname hash function
1395 static int hash_name(const char* name)
1397 unsigned int hashv = 0;
1398 const u_char* p = (const u_char*) name;
1402 for (; *p && *p != '.'; ++p)
1404 hashv %= ARES_CACSIZE;
1409 * add_to_cache - Add a new cache item to the queue and hash table.
1411 static struct CacheEntry* add_to_cache(struct CacheEntry* ocp)
1417 ocp->list_next = cacheTop;
1420 hashv = hash_name(ocp->he.h.h_name);
1422 ocp->hname_next = hashtable[hashv].name_list;
1423 hashtable[hashv].name_list = ocp;
1425 hashv = hash_number((const unsigned char*) ocp->he.h.h_addr);
1427 ocp->hnum_next = hashtable[hashv].num_list;
1428 hashtable[hashv].num_list = ocp;
1431 * LRU deletion of excessive cache entries.
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;
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.
1450 static void update_list(struct ResRequest* request, struct CacheEntry* cachep)
1453 struct CacheEntry** cpp;
1455 struct CacheEntry* cp = cachep;
1461 char* addrs[RES_MAXADDRS + 1];
1462 char* aliases[RES_MAXALIASES + 1];
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.
1468 ++cainfo.ca_updates;
1470 for (cpp = &cacheTop; *cpp; cpp = &((*cpp)->list_next)) {
1476 *cpp = cp->list_next;
1477 cp->list_next = cacheTop;
1484 * Compare the cache entry against the new record. Add any
1485 * previously missing names for this entry.
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))
1500 * Do the same again for IP#'s.
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)))
1514 if (*addrs || *aliases)
1515 update_hostent(&cp->he, addrs, aliases);
1519 * find_cache_name - find name in nameserver cache
1521 static struct CacheEntry* find_cache_name(const char* name)
1523 struct CacheEntry* cp;
1529 hashv = hash_name(name);
1531 cp = hashtable[hashv].name_list;
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;
1542 for (cp = cacheTop; cp; cp = cp->list_next) {
1544 * if no aliases or the hash value matches, we've already
1545 * done this entry and all possiblilities concerning it.
1547 if (!cp->he.h.h_name || hashv == hash_name(cp->he.h.h_name))
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;
1560 * find_cache_number - find a cache entry by ip# and update its expire time
1562 static struct CacheEntry* find_cache_number(struct ResRequest* request,
1565 struct CacheEntry* cp;
1570 hashv = hash_number((const unsigned char*) addr);
1571 cp = hashtable[hashv].num_list;
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;
1581 for (cp = cacheTop; cp; cp = cp->list_next) {
1583 * single address entry...would have been done by hashed
1585 * if the first IP# has the same hashnumber as the IP# we
1586 * are looking for, its been done already.
1588 if (!cp->he.h.h_addr_list[1] ||
1589 hashv == hash_number((const unsigned char*) cp->he.h.h_addr_list[0]))
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;
1601 static struct CacheEntry* make_cache(struct ResRequest* request)
1603 struct CacheEntry* cp;
1606 assert(0 != request);
1608 hp = &request->he.h;
1610 * shouldn't happen but it just might...
1612 assert(0 != hp->h_name);
1613 assert(0 != hp->h_addr_list[0]);
1614 if (!hp->h_name || !hp->h_addr_list[0])
1617 * Make cache entry. First check to see if the cache already exists
1618 * and if so, return a pointer to it.
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);
1627 * a matching entry wasnt found in the cache so go and make one up.
1629 cp = (struct CacheEntry*) MyMalloc(sizeof(struct CacheEntry));
1632 memset(cp, 0, sizeof(struct CacheEntry));
1633 dup_hostent(&cp->he, hp);
1634 cp->reply.hp = &cp->he.h;
1636 * hmmm... we could time out the cache after 10 minutes regardless
1637 * would that be reasonable since we don't save the reply?
1639 if (request->ttl < AR_TTL) {
1640 ++reinfo.re_shortttl;
1644 cp->ttl = request->ttl;
1645 cp->expireat = CurrentTime + cp->ttl;
1646 return add_to_cache(cp);
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.
1653 static void rem_cache(struct CacheEntry* ocp)
1655 struct CacheEntry** cp;
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",
1670 * remove cache entry from linked list
1672 for (cp = &cacheTop; *cp; cp = &((*cp)->list_next)) {
1674 *cp = ocp->list_next;
1680 * remove cache entry from hashed name list
1682 assert(0 != hp->h_name);
1683 hashv = hash_name(hp->h_name);
1685 for (cp = &hashtable[hashv].name_list; *cp; cp = &((*cp)->hname_next)) {
1687 *cp = ocp->hname_next;
1692 * remove cache entry from hashed number list
1694 hashv = hash_number((const unsigned char*) hp->h_addr);
1697 for (cp = &hashtable[hashv].num_list; *cp; cp = &((*cp)->hnum_next)) {
1699 *cp = ocp->hnum_next;
1704 * free memory used to hold the various host names and the array
1705 * of alias pointers.
1707 MyFree(ocp->he.buf);
1713 void flush_resolver_cache(void)
1716 * stubbed - iterate cache and remove everything that isn't referenced
1721 * m_dns - dns status query
1723 int m_dns(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1725 #if !defined(NDEBUG)
1726 struct CacheEntry* cp;
1730 if (parv[1] && *parv[1] == 'l') {
1731 for(cp = cacheTop; cp; cp = cp->list_next) {
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]));
1745 if (parv[1] && *parv[1] == 'd') {
1746 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :ResolverFileDescriptor = %d",
1747 sptr, ResolverFileDescriptor);
1750 sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ca %d Cd %d Ce %d Cl %d Ch %d:%d "
1752 cainfo.ca_adds, cainfo.ca_dels, cainfo.ca_expires,
1753 cainfo.ca_lookups, cainfo.ca_na_hits, cainfo.ca_nu_hits,
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);
1766 size_t cres_mem(struct Client* sptr)
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;
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);
1780 for (request = requestListHead; request; request = request->next) {
1781 request_mem += sizeof(struct ResRequest);
1783 request_mem += strlen(request->name) + 1;
1784 if (request->he.buf)
1785 request_mem += MAXGETHOSTLEN + 1;
1789 if (cachedCount != cache_count) {
1790 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1791 ":Resolver: cache count mismatch: %d != %d", cachedCount,
1793 assert(cachedCount == cache_count);
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;