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_snprintf.h"
24 #include "ircd_string.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 ircd_snprintf(0, sparemsg, sizeof(sparemsg), "invalid spare_fd %d",
340 server_restart(sparemsg);
345 _res.nsaddr_list[0].sin_addr.s_addr = inet_addr("127.0.0.1");
347 _res.options |= RES_NOALIASES;
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);
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);
366 /* Call the query timeout function */
367 static void expire_DNS_callback(struct Event* ev)
371 next = timeout_query_list(CurrentTime);
373 timer_add(&resExpireDNS, expire_DNS_callback, 0, TT_ABSOLUTE, next);
376 /* Call the cache expire function */
377 static void expire_cache_callback(struct Event* ev)
381 next = expire_cache(CurrentTime);
383 timer_add(&resExpireCache, expire_cache_callback, 0, TT_ABSOLUTE, next);
387 * init_resolver - initialize resolver and resolver library
389 int init_resolver(void)
391 Debug((DEBUG_DNS, "Resolver: init_resolver"));
393 srand48(CurrentTime);
395 memset(&cainfo, 0, sizeof(cainfo));
396 memset(hashtable, 0, sizeof(hashtable));
397 memset(&reinfo, 0, sizeof(reinfo));
399 requestListHead = requestListTail = 0;
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);
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;
415 * restart_resolver - flush the cache, reread resolv.conf, reopen socket
417 void restart_resolver(void)
419 /* flush_cache(); flush the dns cache */
423 static int validate_hostent(const struct hostent* hp)
428 for (name = hp->h_name; name; name = hp->h_aliases[i++]) {
429 if (!string_is_hostname(name))
436 * add_request - place a new request in the request list
438 static void add_request(struct ResRequest* request)
440 assert(0 != request);
441 if (!requestListHead)
442 requestListHead = requestListTail = request;
444 requestListTail->next = request;
445 requestListTail = request;
447 request->next = NULL;
448 ++reinfo.re_requests;
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.
456 static void rem_request(struct ResRequest* request)
458 struct ResRequest** current;
459 struct ResRequest* prev = NULL;
461 assert(0 != request);
462 for (current = &requestListHead; *current; ) {
463 if (*current == request) {
464 *current = request->next;
465 if (requestListTail == request)
466 requestListTail = prev;
470 current = &(*current)->next;
472 MyFree(request->he.buf);
473 MyFree(request->name);
478 * make_request - Create a DNS request record for the server.
480 static struct ResRequest* make_request(const struct DNSQuery* query)
482 struct ResRequest* request;
484 request = (struct ResRequest*) MyMalloc(sizeof(struct ResRequest));
485 memset(request, 0, sizeof(struct ResRequest));
487 request->sentat = CurrentTime;
488 request->retries = 3;
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;
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;
504 add_request(request);
509 * timeout_query_list - Remove queries from the list which have been
510 * there too long without being resolved.
512 static time_t timeout_query_list(time_t now)
514 struct ResRequest* request;
515 struct ResRequest* next_request = 0;
516 time_t next_time = 0;
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;
524 if (--request->retries <= 0) {
525 ++reinfo.re_timeouts;
526 (*request->query.callback)(request->query.vptr, 0);
527 rem_request(request);
531 request->sentat = now;
532 request->timeout += request->timeout;
533 resend_query(request);
536 if (!next_time || timeout < next_time) {
540 return (next_time > now) ? next_time : (now + AR_TTL);
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.
548 static time_t expire_cache(time_t now)
550 struct CacheEntry* cp;
551 struct CacheEntry* cp_next;
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) {
561 else if (!expire || expire > cp->expireat)
562 expire = cp->expireat;
564 return (expire > now) ? expire : (now + AR_TTL);
568 * timeout_resolver - check request list and cache for expired entries
570 time_t timeout_resolver(time_t now)
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);
581 * delete_resolver_queries - cleanup outstanding queries
582 * for which there no longer exist clients or conf lines.
584 void delete_resolver_queries(const void* vptr)
586 struct ResRequest* request;
587 struct ResRequest* next_request;
589 for (request = requestListHead; request; request = next_request) {
590 next_request = request->next;
591 if (vptr == request->query.vptr)
592 rem_request(request);
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.
603 static int send_res_msg(const u_char* msg, int len, int rcount)
607 int max_queries = IRCD_MIN(_res.nscount, rcount);
611 * RES_PRIMARY option is not implemented
612 * if (_res.options & RES_PRIMARY || 0 == max_queries)
614 if (0 == max_queries)
617 Debug((DEBUG_DNS, "Resolver: sendto %d", max_queries));
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) {
627 log_write(LS_RESOLVER, L_ERROR, 0, "Resolver: send failed %m");
633 * find_id - find a dns request id (id is determined by dn_mkquery)
635 static struct ResRequest* find_id(int id)
637 struct ResRequest* request;
639 for (request = requestListHead; request; request = request->next) {
640 if (request->id == id)
647 * gethost_byname - get host address from name
649 struct DNSReply* gethost_byname(const char* name,
650 const struct DNSQuery* query)
652 struct CacheEntry* cp;
655 Debug((DEBUG_DNS, "Resolver: gethost_byname %s", name));
657 if ((cp = find_cache_name(name)))
660 do_query_name(query, name, NULL);
666 * gethost_byaddr - get host name from address
668 struct DNSReply* gethost_byaddr(const char* addr,
669 const struct DNSQuery* query)
671 struct CacheEntry *cp;
675 Debug((DEBUG_DNS, "Resolver: gethost_byaddr %s", ircd_ntoa(addr)));
678 if ((cp = find_cache_number(NULL, addr)))
681 do_query_number(query, (const struct in_addr*) addr, NULL);
687 * do_query_name - nameserver lookup name
689 static void do_query_name(const struct DNSQuery* query,
690 const char* name, struct ResRequest* request)
692 char hname[HOSTLEN + 1];
695 ircd_strncpy(hname, name, HOSTLEN);
696 hname[HOSTLEN] = '\0';
699 request = make_request(query);
701 request->name = (char*) MyMalloc(strlen(hname) + 1);
702 strcpy(request->name, hname);
704 query_name(hname, C_IN, T_A, request);
708 * do_query_number - Use this to do reverse IP# lookups.
710 static void do_query_number(const struct DNSQuery* query,
711 const struct in_addr* addr,
712 struct ResRequest* request)
715 const unsigned char* cp;
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]));
724 request = make_request(query);
725 request->type = T_PTR;
726 request->addr.s_addr = addr->s_addr;
728 query_name(ipbuf, C_IN, T_PTR, request);
732 * query_name - generate a query based on class, type and name.
734 static void query_name(const char* name, int query_class,
735 int type, struct ResRequest* request)
741 assert(0 != request);
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;
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
760 header->id = (header->id + lrand48()) & 0xffff;
761 } while (find_id(header->id));
763 gettimeofday(&tv, NULL);
765 header->id = (header->id + k + tv.tv_usec) & 0xffff;
767 } while (find_id(header->id));
769 request->id = header->id;
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);
777 static void resend_query(struct ResRequest* request)
779 assert(0 != request);
781 if (request->resend == 0)
784 switch(request->type) {
786 do_query_number(NULL, &request->addr, request);
789 do_query_name(NULL, request->name, request);
797 * proc_answer - process name server reply
798 * build a hostent struct in the passed request
800 static int proc_answer(struct ResRequest* request, HEADER* header,
801 u_char* buf, u_char* eob)
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 */
819 assert(0 != request);
824 current = buf + sizeof(HEADER);
825 hp = &(request->he.h);
827 * lazy allocation of request->he.buf, we don't allocate a buffer
828 * unless there is something to put in it.
830 if (!request->he.buf) {
831 request->he.buf = (char*) MyMalloc(MAXGETHOSTLEN + 1);
832 request->he.buf[MAXGETHOSTLEN] = '\0';
834 * array of alias list pointers starts at beginning of buf
836 hp->h_aliases = (char**) request->he.buf;
837 hp->h_aliases[0] = NULL;
839 * array of address list pointers starts after alias list pointers
840 * the actual addresses follow the the address list pointers
842 hp->h_addr_list = (char**)(request->he.buf + ALIAS_BLEN);
844 * don't copy the host address to the beginning of h_addr_list
846 hp->h_addr_list[0] = NULL;
848 endp = request->he.buf + MAXGETHOSTLEN;
850 * find the end of the address list
852 addr = hp->h_addr_list;
858 * make address point to first available address slot
860 address = request->he.buf + ADDRS_OFFSET +
861 (sizeof(struct in_addr) * addr_count);
863 * find the end of the alias list
865 alias = hp->h_aliases;
871 * make name point to first available space in request->buf
873 if (alias_count > 0) {
874 name = hp->h_aliases[alias_count - 1];
875 name += (strlen(name) + 1);
878 name = hp->h_name + strlen(hp->h_name) + 1;
880 name = request->he.buf + ADDRS_OFFSET + ADDRS_DLEN;
885 while (header->qdcount-- > 0) {
886 if ((n = dn_skipname(current, eob)) < 0)
888 current += (n + QFIXEDSZ);
891 * process each answer sent to us blech.
893 while (header->ancount-- > 0 && current < eob && name < endp) {
894 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
897 * no more answers left
901 hostbuf[HOSTLEN] = '\0';
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)
907 current += (size_t) n;
909 if (!((current + ANSWER_FIXED_SIZE) < eob))
912 type = _getshort(current);
913 current += TYPE_SIZE;
915 query_class = _getshort(current);
916 current += CLASS_SIZE;
918 request->ttl = _getlong(current);
921 rd_length = _getshort(current);
922 current += RDLENGTH_SIZE;
925 * Wait to set request->type until we verify this structure
930 * check for invalid rd_length or too many addresses
932 if (rd_length != sizeof(struct in_addr))
934 if (++addr_count < RES_MAXADDRS) {
935 if (answer_count == 1)
936 hp->h_addrtype = (query_class == C_IN) ? AF_INET : AF_UNSPEC;
938 memcpy(address, current, sizeof(struct in_addr));
941 address += sizeof(struct in_addr);
944 strcpy(name, hostbuf);
946 name += strlen(name) + 1;
948 Debug((DEBUG_DNS, "Resolver: A %s for %s",
949 ircd_ntoa((char*) hp->h_addr_list[addr_count - 1]), hostbuf));
951 current += rd_length;
955 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
964 * no more answers left
969 * This comment is based on analysis by Shadowfax, Wohali and johan,
970 * not me. (Dianora) I am only commenting it.
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.
977 hostbuf[HOSTLEN] = '\0';
978 current += (size_t) n;
980 Debug((DEBUG_DNS, "Resolver: PTR %s", hostbuf));
982 * copy the returned hostname into the host name
983 * ignore duplicate ptr records
986 strcpy(name, hostbuf);
988 name += strlen(name) + 1;
993 Debug((DEBUG_DNS, "Resolver: CNAME %s", hostbuf));
994 if (++alias_count < RES_MAXALIASES) {
995 ircd_strncpy(name, hostbuf, endp - name);
998 name += strlen(name) + 1;
1000 current += rd_length;
1004 Debug((DEBUG_DNS,"Resolver: proc_answer type: %d for: %s", type, hostbuf));
1008 return answer_count;
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
1015 int resolver_read(void)
1017 u_char buf[sizeof(HEADER) + MAXPACKET];
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;
1025 Debug((DEBUG_DNS, "Resolver: read"));
1026 if (IO_SUCCESS != os_recvfrom_nonb(ResolverFileDescriptor,
1027 (char*) buf, sizeof(buf), &rc, &sin)) {
1030 if (rc < sizeof(HEADER)) {
1031 Debug((DEBUG_DNS, "Resolver: short reply %d: %s", rc,
1032 (strerror(errno)) ? strerror(errno) : "Unknown"));
1036 * convert DNS reply reader from Network byte order to CPU byte order.
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;
1046 * response for an id which we have already received an answer for
1047 * just ignore this response.
1049 if (0 == (request = find_id(header->id))) {
1050 Debug((DEBUG_DNS, "Resolver: can't find request id: %d", header->id));
1054 * check against possibly fake replies
1056 if (!res_ourserver(&_res, &sin)) {
1057 Debug((DEBUG_DNS, "Resolver: fake reply from: %s", (const char*) &sin.sin_addr));
1062 if ((header->rcode != NOERROR) || (header->ancount == 0)) {
1064 if (SERVFAIL == header->rcode)
1065 resend_query(request);
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
1074 switch (header->rcode) {
1076 Debug((DEBUG_DNS, "Fatal DNS error: No Error"));
1079 Debug((DEBUG_DNS, "Fatal DNS error: Format Error"));
1082 Debug((DEBUG_DNS, "Fatal DNS error: Server Failure"));
1085 Debug((DEBUG_DNS, "DNS error: Non Existant Domain"));
1088 Debug((DEBUG_DNS, "Fatal DNS error: Not Implemented"));
1091 Debug((DEBUG_DNS, "Fatal DNS error: Query Refused"));
1094 Debug((DEBUG_DNS, "Unassigned fatal DNS error: %i", header->rcode));
1097 #endif /* DEBUGMODE */
1098 (*request->query.callback)(request->query.vptr, 0);
1099 rem_request(request);
1104 * If this fails there was an error decoding the received packet,
1105 * try it again and hope it works the next time.
1107 answer_count = proc_answer(request, header, buf, buf + rc);
1109 if (T_PTR == request->type) {
1110 struct DNSReply* reply = 0;
1111 if (0 == request->he.h.h_name) {
1113 * got a PTR response with no name, something bogus is happening
1114 * don't bother trying again, the client address doesn't resolve
1116 (*request->query.callback)(request->query.vptr, reply);
1117 rem_request(request);
1120 Debug((DEBUG_DNS, "relookup %s <-> %s",
1121 request->he.h.h_name, ircd_ntoa((char*) &request->addr)));
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
1128 reply = gethost_byname(request->he.h.h_name, &request->query);
1130 (*request->query.callback)(request->query.vptr, reply);
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
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));
1143 rem_request(request);
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.
1153 struct DNSReply* reply = 0;
1154 if (validate_hostent(&request->he.h)) {
1155 if ((cp = make_cache(request)))
1158 (*request->query.callback)(request->query.vptr, reply);
1159 rem_request(request);
1162 else if (!request->sent) {
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
1167 (*request->query.callback)(request->query.vptr, 0);
1168 rem_request(request);
1174 * resolver_read_multiple - process up to count reads
1176 void resolver_read_multiple(int count)
1179 for ( ; i < count; ++i) {
1180 if (0 == resolver_read())
1185 static size_t calc_hostent_buffer_size(const struct hostent* hp)
1194 count += (strlen(hp->h_name) + 1);
1198 for (p = hp->h_aliases; *p; ++p)
1199 count += (strlen(*p) + 1 + sizeof(char*));
1201 * space for addresses
1203 for (p = hp->h_addr_list; *p; ++p)
1204 count += (hp->h_length + sizeof(char*));
1206 * space for 2 nulls to terminate h_aliases and h_addr_list
1208 count += (2 * sizeof(char*));
1214 * dup_hostent - Duplicate a hostent struct, allocate only enough memory for
1215 * the data we're putting in it.
1217 static void dup_hostent(struct Hostent* new_hp, struct hostent* hp)
1222 int alias_count = 0;
1224 size_t bytes_needed = 0;
1226 assert(0 != new_hp);
1229 /* how much buffer do we need? */
1230 bytes_needed += (strlen(hp->h_name) + 1);
1234 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1237 pp = hp->h_addr_list;
1239 bytes_needed += (hp->h_length + sizeof(char*));
1242 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1243 bytes_needed += (2 * sizeof(char*));
1245 /* Allocate memory */
1246 new_hp->buf = (char*) MyMalloc(bytes_needed);
1248 new_hp->h.h_addrtype = hp->h_addrtype;
1249 new_hp->h.h_length = hp->h_length;
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*));
1259 memcpy(p, *pp++, hp->h_length);
1263 /* next write the name */
1264 new_hp->h.h_name = p;
1265 strcpy(p, hp->h_name);
1266 p += (strlen(p) + 1);
1268 /* last write the alias list */
1270 ap = new_hp->h.h_aliases = (char**) new_hp->buf;
1274 p += (strlen(p) + 1);
1280 * update_hostent - Add records to a Hostent struct in place.
1282 static void update_hostent(struct Hostent* hp, char** addr, char** alias)
1287 int alias_count = 0;
1290 size_t bytes_needed = 0;
1292 if (!hp || !hp->buf)
1295 /* how much buffer do we need? */
1296 bytes_needed = strlen(hp->h.h_name) + 1;
1297 pp = hp->h.h_aliases;
1299 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1305 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1309 pp = hp->h.h_addr_list;
1311 bytes_needed += (hp->h.h_length + sizeof(char*));
1317 bytes_needed += (hp->h.h_length + sizeof(char*));
1321 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1322 bytes_needed += 2 * sizeof(char*);
1324 /* Allocate memory */
1325 buf = (char*) MyMalloc(bytes_needed);
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*));
1334 memcpy(p, *pp++, hp->h.h_length);
1336 p += hp->h.h_length;
1340 memcpy(p, *addr++, hp->h.h_length);
1342 p += hp->h.h_length;
1347 /* next write the name */
1348 strcpy(p, hp->h.h_name);
1350 p += (strlen(p) + 1);
1352 /* last write the alias list */
1353 pp = hp->h.h_aliases;
1354 ap = hp->h.h_aliases = (char**) buf;
1358 p += (strlen(p) + 1);
1362 strcpy(p, *alias++);
1364 p += (strlen(p) + 1);
1368 /* release the old buffer */
1375 * hash_number - IP address hash function
1377 static int hash_number(const unsigned char* ip)
1379 /* could use loop but slower */
1381 const u_char* p = (const u_char*) ip;
1386 hashv += hashv + *p++;
1387 hashv += hashv + *p++;
1388 hashv += hashv + *p;
1389 hashv %= ARES_CACSIZE;
1394 * hash_name - hostname hash function
1396 static int hash_name(const char* name)
1398 unsigned int hashv = 0;
1399 const u_char* p = (const u_char*) name;
1403 for (; *p && *p != '.'; ++p)
1405 hashv %= ARES_CACSIZE;
1410 * add_to_cache - Add a new cache item to the queue and hash table.
1412 static struct CacheEntry* add_to_cache(struct CacheEntry* ocp)
1418 ocp->list_next = cacheTop;
1421 hashv = hash_name(ocp->he.h.h_name);
1423 ocp->hname_next = hashtable[hashv].name_list;
1424 hashtable[hashv].name_list = ocp;
1426 hashv = hash_number((const unsigned char*) ocp->he.h.h_addr);
1428 ocp->hnum_next = hashtable[hashv].num_list;
1429 hashtable[hashv].num_list = ocp;
1432 * LRU deletion of excessive cache entries.
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;
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.
1451 static void update_list(struct ResRequest* request, struct CacheEntry* cachep)
1453 struct CacheEntry* cp = cachep;
1459 char* addrs[RES_MAXADDRS + 1];
1460 char* aliases[RES_MAXALIASES + 1];
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.
1466 ++cainfo.ca_updates;
1471 * Compare the cache entry against the new record. Add any
1472 * previously missing names for this entry.
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))
1487 * Do the same again for IP#'s.
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)))
1501 if (*addrs || *aliases)
1502 update_hostent(&cp->he, addrs, aliases);
1506 * find_cache_name - find name in nameserver cache
1508 static struct CacheEntry* find_cache_name(const char* name)
1510 struct CacheEntry* cp;
1516 hashv = hash_name(name);
1518 cp = hashtable[hashv].name_list;
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;
1529 for (cp = cacheTop; cp; cp = cp->list_next) {
1531 * if no aliases or the hash value matches, we've already
1532 * done this entry and all possiblilities concerning it.
1534 if (!cp->he.h.h_name || hashv == hash_name(cp->he.h.h_name))
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;
1547 * find_cache_number - find a cache entry by ip# and update its expire time
1549 static struct CacheEntry* find_cache_number(struct ResRequest* request,
1552 struct CacheEntry* cp;
1557 hashv = hash_number((const unsigned char*) addr);
1558 cp = hashtable[hashv].num_list;
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;
1568 for (cp = cacheTop; cp; cp = cp->list_next) {
1570 * single address entry...would have been done by hashed
1572 * if the first IP# has the same hashnumber as the IP# we
1573 * are looking for, its been done already.
1575 if (!cp->he.h.h_addr_list[1] ||
1576 hashv == hash_number((const unsigned char*) cp->he.h.h_addr_list[0]))
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;
1588 static struct CacheEntry* make_cache(struct ResRequest* request)
1590 struct CacheEntry* cp;
1593 assert(0 != request);
1595 hp = &request->he.h;
1597 * shouldn't happen but it just might...
1599 assert(0 != hp->h_name);
1600 assert(0 != hp->h_addr_list[0]);
1601 if (!hp->h_name || !hp->h_addr_list[0])
1604 * Make cache entry. First check to see if the cache already exists
1605 * and if so, return a pointer to it.
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);
1614 * a matching entry wasnt found in the cache so go and make one up.
1616 cp = (struct CacheEntry*) MyMalloc(sizeof(struct CacheEntry));
1619 memset(cp, 0, sizeof(struct CacheEntry));
1620 dup_hostent(&cp->he, hp);
1621 cp->reply.hp = &cp->he.h;
1623 * hmmm... we could time out the cache after 10 minutes regardless
1624 * would that be reasonable since we don't save the reply?
1626 if (request->ttl < AR_TTL) {
1627 ++reinfo.re_shortttl;
1631 cp->ttl = request->ttl;
1632 cp->expireat = CurrentTime + cp->ttl;
1633 return add_to_cache(cp);
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.
1640 static void rem_cache(struct CacheEntry* ocp)
1642 struct CacheEntry** cp;
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",
1657 * remove cache entry from linked list
1659 for (cp = &cacheTop; *cp; cp = &((*cp)->list_next)) {
1661 *cp = ocp->list_next;
1667 * remove cache entry from hashed name list
1669 assert(0 != hp->h_name);
1670 hashv = hash_name(hp->h_name);
1672 for (cp = &hashtable[hashv].name_list; *cp; cp = &((*cp)->hname_next)) {
1674 *cp = ocp->hname_next;
1679 * remove cache entry from hashed number list
1681 hashv = hash_number((const unsigned char*) hp->h_addr);
1684 for (cp = &hashtable[hashv].num_list; *cp; cp = &((*cp)->hnum_next)) {
1686 *cp = ocp->hnum_next;
1691 * free memory used to hold the various host names and the array
1692 * of alias pointers.
1694 MyFree(ocp->he.buf);
1700 void flush_resolver_cache(void)
1703 * stubbed - iterate cache and remove everything that isn't referenced
1708 * m_dns - dns status query
1710 int m_dns(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1712 #if !defined(NDEBUG)
1713 struct CacheEntry* cp;
1717 if (parv[1] && *parv[1] == 'l') {
1718 for(cp = cacheTop; cp; cp = cp->list_next) {
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]));
1732 if (parv[1] && *parv[1] == 'd') {
1733 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :ResolverFileDescriptor = %d",
1734 sptr, ResolverFileDescriptor);
1737 sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ca %d Cd %d Ce %d Cl %d Ch %d:%d "
1739 cainfo.ca_adds, cainfo.ca_dels, cainfo.ca_expires,
1740 cainfo.ca_lookups, cainfo.ca_na_hits, cainfo.ca_nu_hits,
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);
1753 size_t cres_mem(struct Client* sptr)
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;
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);
1767 for (request = requestListHead; request; request = request->next) {
1768 request_mem += sizeof(struct ResRequest);
1770 request_mem += strlen(request->name) + 1;
1771 if (request->he.buf)
1772 request_mem += MAXGETHOSTLEN + 1;
1776 if (cachedCount != cache_count) {
1777 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1778 ":Resolver: cache count mismatch: %d != %d", cachedCount,
1780 assert(cachedCount == cache_count);
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;