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>)
16 #include "ircd_alloc.h"
18 #include "ircd_osdep.h"
19 #include "ircd_reply.h"
20 #include "ircd_string.h"
27 #include "sprintf_irc.h"
37 #include <sys/socket.h>
42 #include <arpa/nameser.h>
45 #include <arpa/inet.h>
49 #error this code needs to be able to address individual octets
53 * Some systems do not define INADDR_NONE (255.255.255.255)
54 * INADDR_NONE is actually a valid address, but it should never
55 * be returned from any nameserver.
56 * NOTE: The bit pattern for INADDR_NONE and INADDR_ANY (0.0.0.0) should be
57 * the same on all hosts so we shouldn't need to use htonl or ntohl to
58 * compare or set the values.
61 #define INADDR_NONE ((unsigned int) 0xffffffff)
64 #define MAXPACKET 1024 /* rfc sez 512 but we expand names so ... */
65 #define RES_MAXALIASES 35 /* maximum aliases allowed */
66 #define RES_MAXADDRS 35 /* maximum addresses allowed */
68 * OSF1 doesn't have RES_NOALIASES
71 #define RES_NOALIASES 0
75 * macros used to calulate offsets into fixed query buffer
77 #define ALIAS_BLEN ((RES_MAXALIASES + 1) * sizeof(char*))
78 #define ADDRS_BLEN ((RES_MAXADDRS + 1) * sizeof(struct in_addr*))
80 #define ADDRS_OFFSET (ALIAS_BLEN + ADDRS_BLEN)
81 #define ADDRS_DLEN (RES_MAXADDRS * sizeof(struct in_addr))
82 #define NAMES_OFFSET (ADDRS_OFFSET + ADDRS_DLEN)
83 #define MAXGETHOSTLEN (NAMES_OFFSET + MAXPACKET)
85 #define AR_TTL 600 /* TTL in seconds for dns cache entries */
88 * the following values should be prime
90 #define ARES_CACSIZE 307
94 * RFC 1104/1105 wasn't very helpful about what these fields
95 * should be named, so for now, we'll just name them this way.
96 * we probably should look at what named calls them or something.
101 #define RDLENGTH_SIZE 2
102 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
105 * Building the Hostent
106 * The Hostent struct is arranged like this:
107 * +-------------------------------+
108 * Hostent: | struct hostent h |
109 * |-------------------------------|
111 * +-------------------------------+
115 * +-------------------------------+
116 * buf: | h_aliases pointer array | Max size: ALIAS_BLEN;
117 * | NULL | contains `char *'s
118 * |-------------------------------|
119 * | h_addr_list pointer array | Max size: ADDRS_BLEN;
120 * | NULL | contains `struct in_addr *'s
121 * |-------------------------------|
122 * | h_addr_list addresses | Max size: ADDRS_DLEN;
123 * | | contains `struct in_addr's
124 * |-------------------------------|
125 * | storage for hostname strings | Max size: ALIAS_DLEN;
126 * +-------------------------------+ contains `char's
128 * For requests the size of the h_aliases, and h_addr_list pointer
129 * array sizes are set to MAXALISES and MAXADDRS respectively, and
130 * buf is a fixed size with enough space to hold the largest expected
131 * reply from a nameserver, see RFC 1034 and RFC 1035.
132 * For cached entries the sizes are dependent on the actual number
133 * of aliases and addresses. If new aliases and addresses are found
134 * for cached entries, the buffer is grown and the new entries are added.
135 * The hostent struct is filled in with the addresses of the entries in
136 * the Hostent buf as follows:
137 * h_name - contains a pointer to the start of the hostname string area,
138 * or NULL if none is set. The h_name is followed by the
139 * aliases, in the storage for hostname strings area.
140 * h_aliases - contains a pointer to the start of h_aliases pointer array.
141 * This array contains pointers to the storage for hostname
142 * strings area and is terminated with a NULL. The first alias
143 * is stored directly after the h_name.
144 * h_addr_list - contains a pointer to the start of h_addr_list pointer array.
145 * This array contains pointers to in_addr structures in the
146 * h_addr_list addresses area and is terminated with a NULL.
148 * Filling the buffer this way allows for proper alignment of the h_addr_list
151 * This arrangement allows us to alias a Hostent struct pointer as a
152 * real struct hostent* without lying. It also allows us to change the
153 * values contained in the cached entries and requests without changing
154 * the actual hostent pointer, which is saved in a client struct and can't
155 * be changed without blowing things up or a lot more fiddling around.
156 * It also allows for defered allocation of the fixed size buffers until
157 * they are really needed.
158 * Nov. 17, 1997 --Bleep
162 struct hostent h; /* the hostent struct we are passing around */
163 char* buf; /* buffer for data pointed to from hostent */
167 struct ResRequest* next;
169 int sent; /* number of requests sent */
172 char retries; /* retry counter */
173 char sends; /* number of sends (>1 means resent) */
174 char resend; /* send flag. 0 == dont resend */
179 struct DNSQuery query; /* query callback for this request */
184 struct CacheEntry* hname_next;
185 struct CacheEntry* hnum_next;
186 struct CacheEntry* list_next;
190 struct DNSReply reply;
194 struct CacheEntry* num_list;
195 struct CacheEntry* name_list;
199 int ResolverFileDescriptor = -1; /* GLOBAL - used in s_bsd.c */
201 static time_t nextDNSCheck = 0;
202 static time_t nextCacheExpire = 1;
205 * Keep a spare file descriptor open. res_init calls fopen to read the
206 * resolv.conf file. If ircd is hogging all the file descriptors below 256,
207 * on systems with crippled FILE structures this will cause wierd bugs.
208 * This is definitely needed for Solaris which uses an unsigned char to
209 * hold the file descriptor. --Dianora
211 static int spare_fd = -1;
213 static int cachedCount = 0;
214 static struct CacheTable hashtable[ARES_CACSIZE];
215 static struct CacheEntry* cacheTop;
216 static struct ResRequest* requestListHead; /* head of resolver request list */
217 static struct ResRequest* requestListTail; /* tail of resolver request list */
220 static void add_request(struct ResRequest* request);
221 static void rem_request(struct ResRequest* request);
222 static struct ResRequest* make_request(const struct DNSQuery* query);
223 static void rem_cache(struct CacheEntry*);
224 static void do_query_name(const struct DNSQuery* query,
226 struct ResRequest* request);
227 static void do_query_number(const struct DNSQuery* query,
228 const struct in_addr*,
229 struct ResRequest* request);
230 static void query_name(const char* name,
233 struct ResRequest* request);
234 static void resend_query(struct ResRequest* request);
235 static struct CacheEntry* make_cache(struct ResRequest* request);
236 static struct CacheEntry* find_cache_name(const char* name);
237 static struct CacheEntry* find_cache_number(struct ResRequest* request,
239 static struct ResRequest* find_id(int);
241 static struct cacheinfo {
251 static struct resinfo {
266 * From bind 8.3, these aren't declared in earlier versions of bind
268 extern u_short _getshort(const u_char *);
269 extern u_int _getlong(const u_char *);
272 * res_isourserver(ina)
273 * looks up "ina" in _res.ns_addr_list[]
278 * paul vixie, 29may94
281 res_ourserver(const struct __res_state* statp, const struct sockaddr_in* inp)
283 struct sockaddr_in ina;
287 for (ns = 0; ns < statp->nscount; ns++) {
288 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
290 if (srv->sin_family == ina.sin_family &&
291 srv->sin_port == ina.sin_port &&
292 (srv->sin_addr.s_addr == INADDR_ANY ||
293 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
300 * start_resolver - do everything we need to read the resolv.conf file
301 * and initialize the resolver file descriptor if needed
303 static void start_resolver(void)
305 Debug((DEBUG_DNS, "Resolver: start_resolver"));
307 * close the spare file descriptor so res_init can read resolv.conf
308 * successfully. Needed on Solaris
313 res_init(); /* res_init always returns 0 */
315 * make sure we have a valid file descriptor below 256 so we can
316 * do this again. Needed on Solaris
318 spare_fd = open("/dev/null",O_RDONLY,0);
319 if ((spare_fd < 0) || (spare_fd > 255)) {
321 sprintf_irc(sparemsg, "invalid spare_fd %d", spare_fd);
322 server_restart(sparemsg);
327 _res.nsaddr_list[0].sin_addr.s_addr = inet_addr("127.0.0.1");
329 _res.options |= RES_NOALIASES;
331 if (ResolverFileDescriptor < 0) {
332 ResolverFileDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
333 if (-1 == ResolverFileDescriptor) {
334 report_error("Resolver: error creating socket for %s: %s",
335 cli_name(&me), errno);
338 if (!os_set_nonblocking(ResolverFileDescriptor))
339 report_error("Resolver: error setting non-blocking for %s: %s",
340 cli_name(&me), errno);
345 * init_resolver - initialize resolver and resolver library
347 int init_resolver(void)
349 Debug((DEBUG_DNS, "Resolver: init_resolver"));
351 srand48(CurrentTime);
353 memset(&cainfo, 0, sizeof(cainfo));
354 memset(hashtable, 0, sizeof(hashtable));
355 memset(&reinfo, 0, sizeof(reinfo));
357 requestListHead = requestListTail = 0;
362 Debug((DEBUG_DNS, "Resolver: fd %d errno: %d h_errno: %d: %s",
363 ResolverFileDescriptor, errno, h_errno,
364 (strerror(errno)) ? strerror(errno) : "Unknown"));
365 return ResolverFileDescriptor;
369 * restart_resolver - flush the cache, reread resolv.conf, reopen socket
371 void restart_resolver(void)
373 /* flush_cache(); flush the dns cache */
377 static int validate_hostent(const struct hostent* hp)
382 for (name = hp->h_name; name; name = hp->h_aliases[i++]) {
383 if (!string_is_hostname(name))
390 * add_request - place a new request in the request list
392 static void add_request(struct ResRequest* request)
394 assert(0 != request);
395 if (!requestListHead)
396 requestListHead = requestListTail = request;
398 requestListTail->next = request;
399 requestListTail = request;
401 request->next = NULL;
402 ++reinfo.re_requests;
406 * rem_request - remove a request from the list.
407 * This must also free any memory that has been allocated for
408 * temporary storage of DNS results.
410 static void rem_request(struct ResRequest* request)
412 struct ResRequest** current;
413 struct ResRequest* prev = NULL;
415 assert(0 != request);
416 for (current = &requestListHead; *current; ) {
417 if (*current == request) {
418 *current = request->next;
419 if (requestListTail == request)
420 requestListTail = prev;
424 current = &(*current)->next;
426 MyFree(request->he.buf);
427 MyFree(request->name);
432 * make_request - Create a DNS request record for the server.
434 static struct ResRequest* make_request(const struct DNSQuery* query)
436 struct ResRequest* request;
438 request = (struct ResRequest*) MyMalloc(sizeof(struct ResRequest));
439 memset(request, 0, sizeof(struct ResRequest));
441 request->sentat = CurrentTime;
442 request->retries = 3;
444 request->timeout = 5; /* start at 5 per RFC1123 */
445 request->addr.s_addr = INADDR_NONE;
446 request->he.h.h_addrtype = AF_INET;
447 request->he.h.h_length = sizeof(struct in_addr);
448 request->query.vptr = query->vptr;
449 request->query.callback = query->callback;
451 #if defined(NULL_POINTER_NOT_ZERO)
452 request->next = NULL;
453 request->he.buf = NULL;
454 request->he.h.h_name = NULL;
455 request->he.h.h_aliases = NULL;
456 request->he.h.h_addr_list = NULL;
458 add_request(request);
463 * timeout_query_list - Remove queries from the list which have been
464 * there too long without being resolved.
466 static time_t timeout_query_list(time_t now)
468 struct ResRequest* request;
469 struct ResRequest* next_request = 0;
470 time_t next_time = 0;
473 Debug((DEBUG_DNS, "Resolver: timeout_query_list at %s", myctime(now)));
474 for (request = requestListHead; request; request = next_request) {
475 next_request = request->next;
476 timeout = request->sentat + request->timeout;
478 if (--request->retries <= 0) {
479 ++reinfo.re_timeouts;
480 (*request->query.callback)(request->query.vptr, 0);
481 rem_request(request);
485 request->sentat = now;
486 request->timeout += request->timeout;
487 resend_query(request);
490 if (!next_time || timeout < next_time) {
494 return (next_time > now) ? next_time : (now + AR_TTL);
498 * expire_cache - removes entries from the cache which are older
499 * than their expiry times. returns the time at which the server
500 * should next poll the cache.
502 static time_t expire_cache(time_t now)
504 struct CacheEntry* cp;
505 struct CacheEntry* cp_next;
508 Debug((DEBUG_DNS, "Resolver: expire_cache at %s", myctime(now)));
509 for (cp = cacheTop; cp; cp = cp_next) {
510 cp_next = cp->list_next;
511 if (cp->expireat < now) {
515 else if (!expire || expire > cp->expireat)
516 expire = cp->expireat;
518 return (expire > now) ? expire : (now + AR_TTL);
522 * timeout_resolver - check request list and cache for expired entries
524 time_t timeout_resolver(time_t now)
526 if (nextDNSCheck < now)
527 nextDNSCheck = timeout_query_list(now);
528 if (nextCacheExpire < now)
529 nextCacheExpire = expire_cache(now);
530 return IRCD_MIN(nextDNSCheck, nextCacheExpire);
535 * delete_resolver_queries - cleanup outstanding queries
536 * for which there no longer exist clients or conf lines.
538 void delete_resolver_queries(const void* vptr)
540 struct ResRequest* request;
541 struct ResRequest* next_request;
543 for (request = requestListHead; request; request = next_request) {
544 next_request = request->next;
545 if (vptr == request->query.vptr)
546 rem_request(request);
551 * send_res_msg - sends msg to all nameservers found in the "_res" structure.
552 * This should reflect /etc/resolv.conf. We will get responses
553 * which arent needed but is easier than checking to see if nameserver
554 * isnt present. Returns number of messages successfully sent to
555 * nameservers or -1 if no successful sends.
557 static int send_res_msg(const u_char* msg, int len, int rcount)
561 int max_queries = IRCD_MIN(_res.nscount, rcount);
565 * RES_PRIMARY option is not implemented
566 * if (_res.options & RES_PRIMARY || 0 == max_queries)
568 if (0 == max_queries)
571 Debug((DEBUG_DNS, "Resolver: sendto %d", max_queries));
573 for (i = 0; i < max_queries; i++) {
574 if (sendto(ResolverFileDescriptor, msg, len, 0,
575 (struct sockaddr*) &(_res.nsaddr_list[i]),
576 sizeof(struct sockaddr_in)) == len) {
581 log_write(LS_RESOLVER, L_ERROR, 0, "Resolver: send failed %m");
587 * find_id - find a dns request id (id is determined by dn_mkquery)
589 static struct ResRequest* find_id(int id)
591 struct ResRequest* request;
593 for (request = requestListHead; request; request = request->next) {
594 if (request->id == id)
601 * gethost_byname - get host address from name
603 struct DNSReply* gethost_byname(const char* name,
604 const struct DNSQuery* query)
606 struct CacheEntry* cp;
609 Debug((DEBUG_DNS, "Resolver: gethost_byname %s", name));
611 if ((cp = find_cache_name(name)))
614 do_query_name(query, name, NULL);
620 * gethost_byaddr - get host name from address
622 struct DNSReply* gethost_byaddr(const char* addr,
623 const struct DNSQuery* query)
625 struct CacheEntry *cp;
629 Debug((DEBUG_DNS, "Resolver: gethost_byaddr %s", ircd_ntoa(addr)));
632 if ((cp = find_cache_number(NULL, addr)))
635 do_query_number(query, (const struct in_addr*) addr, NULL);
641 * do_query_name - nameserver lookup name
643 static void do_query_name(const struct DNSQuery* query,
644 const char* name, struct ResRequest* request)
646 char hname[HOSTLEN + 1];
649 ircd_strncpy(hname, name, HOSTLEN);
650 hname[HOSTLEN] = '\0';
653 request = make_request(query);
655 request->name = (char*) MyMalloc(strlen(hname) + 1);
656 strcpy(request->name, hname);
658 query_name(hname, C_IN, T_A, request);
662 * do_query_number - Use this to do reverse IP# lookups.
664 static void do_query_number(const struct DNSQuery* query,
665 const struct in_addr* addr,
666 struct ResRequest* request)
669 const unsigned char* cp;
672 cp = (const unsigned char*) &addr->s_addr;
673 sprintf_irc(ipbuf, "%u.%u.%u.%u.in-addr.arpa.",
674 (unsigned int)(cp[3]), (unsigned int)(cp[2]),
675 (unsigned int)(cp[1]), (unsigned int)(cp[0]));
678 request = make_request(query);
679 request->type = T_PTR;
680 request->addr.s_addr = addr->s_addr;
682 query_name(ipbuf, C_IN, T_PTR, request);
686 * query_name - generate a query based on class, type and name.
688 static void query_name(const char* name, int query_class,
689 int type, struct ResRequest* request)
695 assert(0 != request);
697 Debug((DEBUG_DNS, "Resolver: query_name: %s %d %d", name, query_class, type));
698 memset(buf, 0, sizeof(buf));
699 if ((request_len = res_mkquery(QUERY, name, query_class, type,
700 0, 0, 0, (unsigned char*) buf, sizeof(buf))) > 0) {
701 HEADER* header = (HEADER*) buf;
707 * generate a unique id
708 * NOTE: we don't have to worry about converting this to and from
709 * network byte order, the nameserver does not interpret this value
710 * and returns it unchanged
714 header->id = (header->id + lrand48()) & 0xffff;
715 } while (find_id(header->id));
717 gettimeofday(&tv, NULL);
719 header->id = (header->id + k + tv.tv_usec) & 0xffff;
721 } while (find_id(header->id));
723 request->id = header->id;
725 Debug((DEBUG_DNS, "Resolver: query_name %d: %s %d %d", request->id,
726 name, query_class, type));
727 request->sent += send_res_msg((const unsigned char*) buf, request_len, request->sends);
731 static void resend_query(struct ResRequest* request)
733 assert(0 != request);
735 if (request->resend == 0)
738 switch(request->type) {
740 do_query_number(NULL, &request->addr, request);
743 do_query_name(NULL, request->name, request);
751 * proc_answer - process name server reply
752 * build a hostent struct in the passed request
754 static int proc_answer(struct ResRequest* request, HEADER* header,
755 u_char* buf, u_char* eob)
757 char hostbuf[HOSTLEN + 1]; /* working buffer */
758 u_char* current; /* current position in buf */
759 char** alias; /* alias list */
760 char** addr; /* address list */
761 char* name; /* pointer to name string */
762 char* address; /* pointer to address */
763 char* endp; /* end of our buffer */
764 int query_class; /* answer class */
765 int type; /* answer type */
766 int rd_length; /* record data length */
767 int answer_count = 0; /* answer counter */
768 int n; /* temp count */
769 int addr_count = 0; /* number of addresses in hostent */
770 int alias_count = 0; /* number of aliases in hostent */
771 struct hostent* hp; /* hostent getting filled */
773 assert(0 != request);
778 current = buf + sizeof(HEADER);
779 hp = &(request->he.h);
781 * lazy allocation of request->he.buf, we don't allocate a buffer
782 * unless there is something to put in it.
784 if (!request->he.buf) {
785 request->he.buf = (char*) MyMalloc(MAXGETHOSTLEN + 1);
786 request->he.buf[MAXGETHOSTLEN] = '\0';
788 * array of alias list pointers starts at beginning of buf
790 hp->h_aliases = (char**) request->he.buf;
791 hp->h_aliases[0] = NULL;
793 * array of address list pointers starts after alias list pointers
794 * the actual addresses follow the the address list pointers
796 hp->h_addr_list = (char**)(request->he.buf + ALIAS_BLEN);
798 * don't copy the host address to the beginning of h_addr_list
800 hp->h_addr_list[0] = NULL;
802 endp = request->he.buf + MAXGETHOSTLEN;
804 * find the end of the address list
806 addr = hp->h_addr_list;
812 * make address point to first available address slot
814 address = request->he.buf + ADDRS_OFFSET +
815 (sizeof(struct in_addr) * addr_count);
817 * find the end of the alias list
819 alias = hp->h_aliases;
825 * make name point to first available space in request->buf
827 if (alias_count > 0) {
828 name = hp->h_aliases[alias_count - 1];
829 name += (strlen(name) + 1);
832 name = hp->h_name + strlen(hp->h_name) + 1;
834 name = request->he.buf + ADDRS_OFFSET + ADDRS_DLEN;
839 while (header->qdcount-- > 0) {
840 if ((n = dn_skipname(current, eob)) < 0)
842 current += (n + QFIXEDSZ);
845 * process each answer sent to us blech.
847 while (header->ancount-- > 0 && current < eob && name < endp) {
848 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
851 * no more answers left
855 hostbuf[HOSTLEN] = '\0';
857 * With Address arithmetic you have to be very anal
858 * this code was not working on alpha due to that
859 * (spotted by rodder/jailbird/dianora)
861 current += (size_t) n;
863 if (!((current + ANSWER_FIXED_SIZE) < eob))
866 type = _getshort(current);
867 current += TYPE_SIZE;
869 query_class = _getshort(current);
870 current += CLASS_SIZE;
872 request->ttl = _getlong(current);
875 rd_length = _getshort(current);
876 current += RDLENGTH_SIZE;
879 * Wait to set request->type until we verify this structure
884 * check for invalid rd_length or too many addresses
886 if (rd_length != sizeof(struct in_addr))
888 if (++addr_count < RES_MAXADDRS) {
889 if (answer_count == 1)
890 hp->h_addrtype = (query_class == C_IN) ? AF_INET : AF_UNSPEC;
892 memcpy(address, current, sizeof(struct in_addr));
895 address += sizeof(struct in_addr);
898 strcpy(name, hostbuf);
900 name += strlen(name) + 1;
902 Debug((DEBUG_DNS, "Resolver: A %s for %s",
903 ircd_ntoa((char*) hp->h_addr_list[addr_count - 1]), hostbuf));
905 current += rd_length;
909 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
918 * no more answers left
923 * This comment is based on analysis by Shadowfax, Wohali and johan,
924 * not me. (Dianora) I am only commenting it.
926 * dn_expand is guaranteed to not return more than sizeof(hostbuf)
927 * but do all implementations of dn_expand also guarantee
928 * buffer is terminated with null byte? Lets not take chances.
931 hostbuf[HOSTLEN] = '\0';
932 current += (size_t) n;
934 Debug((DEBUG_DNS, "Resolver: PTR %s", hostbuf));
936 * copy the returned hostname into the host name
937 * ignore duplicate ptr records
940 strcpy(name, hostbuf);
942 name += strlen(name) + 1;
947 Debug((DEBUG_DNS, "Resolver: CNAME %s", hostbuf));
948 if (++alias_count < RES_MAXALIASES) {
949 ircd_strncpy(name, hostbuf, endp - name);
952 name += strlen(name) + 1;
954 current += rd_length;
958 Debug((DEBUG_DNS,"Resolver: proc_answer type: %d for: %s", type, hostbuf));
966 * resolver_read - read a dns reply from the nameserver and process it.
967 * return 0 if nothing was read from the socket, otherwise return 1
969 int resolver_read(void)
971 u_char buf[sizeof(HEADER) + MAXPACKET];
973 struct ResRequest* request = 0;
974 struct CacheEntry* cp = 0;
976 int answer_count = 0;
977 struct sockaddr_in sin;
979 Debug((DEBUG_DNS, "Resolver: read"));
980 if (IO_SUCCESS != os_recvfrom_nonb(ResolverFileDescriptor,
981 (char*) buf, sizeof(buf), &rc, &sin)) {
984 if (rc < sizeof(HEADER)) {
985 Debug((DEBUG_DNS, "Resolver: short reply %d: %s", rc,
986 (strerror(errno)) ? strerror(errno) : "Unknown"));
990 * convert DNS reply reader from Network byte order to CPU byte order.
992 header = (HEADER*) buf;
993 /* header->id = ntohs(header->id); */
994 header->ancount = ntohs(header->ancount);
995 header->qdcount = ntohs(header->qdcount);
996 header->nscount = ntohs(header->nscount);
997 header->arcount = ntohs(header->arcount);
1000 * response for an id which we have already received an answer for
1001 * just ignore this response.
1003 if (0 == (request = find_id(header->id))) {
1004 Debug((DEBUG_DNS, "Resolver: can't find request id: %d", header->id));
1008 * check against possibly fake replies
1010 if (!res_ourserver(&_res, &sin)) {
1011 Debug((DEBUG_DNS, "Resolver: fake reply from: %s", (const char*) &sin.sin_addr));
1016 if ((header->rcode != NOERROR) || (header->ancount == 0)) {
1018 if (SERVFAIL == header->rcode)
1019 resend_query(request);
1022 * If a bad error was returned, we stop here and dont send
1023 * send any more (no retries granted).
1024 * Isomer: Perhaps we should return these error messages back to
1028 switch (header->rcode) {
1030 Debug((DEBUG_DNS, "Fatal DNS error: No Error"));
1033 Debug((DEBUG_DNS, "Fatal DNS error: Format Error"));
1036 Debug((DEBUG_DNS, "Fatal DNS error: Server Failure"));
1039 Debug((DEBUG_DNS, "DNS error: Non Existant Domain"));
1042 Debug((DEBUG_DNS, "Fatal DNS error: Not Implemented"));
1045 Debug((DEBUG_DNS, "Fatal DNS error: Query Refused"));
1048 Debug((DEBUG_DNS, "Unassigned fatal DNS error: %i", header->rcode));
1051 #endif /* DEBUGMODE */
1052 (*request->query.callback)(request->query.vptr, 0);
1053 rem_request(request);
1058 * If this fails there was an error decoding the received packet,
1059 * try it again and hope it works the next time.
1061 answer_count = proc_answer(request, header, buf, buf + rc);
1063 if (T_PTR == request->type) {
1064 struct DNSReply* reply = 0;
1065 if (0 == request->he.h.h_name) {
1067 * got a PTR response with no name, something bogus is happening
1068 * don't bother trying again, the client address doesn't resolve
1070 (*request->query.callback)(request->query.vptr, reply);
1071 rem_request(request);
1074 Debug((DEBUG_DNS, "relookup %s <-> %s",
1075 request->he.h.h_name, ircd_ntoa((char*) &request->addr)));
1077 * Lookup the 'authoritive' name that we were given for the
1078 * ip#. By using this call rather than regenerating the
1079 * type we automatically gain the use of the cache with no
1082 reply = gethost_byname(request->he.h.h_name, &request->query);
1084 (*request->query.callback)(request->query.vptr, reply);
1088 * If name wasn't found, a request has been queued and it will
1089 * be the last one queued. This is rather nasty way to keep
1090 * a host alias with the query. -avalon
1092 MyFree(requestListTail->he.buf);
1093 requestListTail->he.buf = request->he.buf;
1094 request->he.buf = 0;
1095 memcpy(&requestListTail->he.h, &request->he.h, sizeof(struct hostent));
1097 rem_request(request);
1101 * got a name and address response, client resolved
1102 * XXX - Bug found here by Dianora -
1103 * make_cache() occasionally returns a NULL pointer when a
1104 * PTR returned a CNAME, cp was not checked before so the
1105 * callback was being called with a value of 0x2C != NULL.
1107 struct DNSReply* reply = 0;
1108 if (validate_hostent(&request->he.h)) {
1109 if ((cp = make_cache(request)))
1112 (*request->query.callback)(request->query.vptr, reply);
1113 rem_request(request);
1116 else if (!request->sent) {
1118 * XXX - we got a response for a query we didn't send with a valid id?
1119 * this should never happen, bail here and leave the client unresolved
1121 (*request->query.callback)(request->query.vptr, 0);
1122 rem_request(request);
1128 * resolver_read_multiple - process up to count reads
1130 void resolver_read_multiple(int count)
1133 for ( ; i < count; ++i) {
1134 if (0 == resolver_read())
1139 static size_t calc_hostent_buffer_size(const struct hostent* hp)
1148 count += (strlen(hp->h_name) + 1);
1152 for (p = hp->h_aliases; *p; ++p)
1153 count += (strlen(*p) + 1 + sizeof(char*));
1155 * space for addresses
1157 for (p = hp->h_addr_list; *p; ++p)
1158 count += (hp->h_length + sizeof(char*));
1160 * space for 2 nulls to terminate h_aliases and h_addr_list
1162 count += (2 * sizeof(char*));
1168 * dup_hostent - Duplicate a hostent struct, allocate only enough memory for
1169 * the data we're putting in it.
1171 static void dup_hostent(struct Hostent* new_hp, struct hostent* hp)
1176 int alias_count = 0;
1178 size_t bytes_needed = 0;
1180 assert(0 != new_hp);
1183 /* how much buffer do we need? */
1184 bytes_needed += (strlen(hp->h_name) + 1);
1188 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1191 pp = hp->h_addr_list;
1193 bytes_needed += (hp->h_length + sizeof(char*));
1196 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1197 bytes_needed += (2 * sizeof(char*));
1199 /* Allocate memory */
1200 new_hp->buf = (char*) MyMalloc(bytes_needed);
1202 new_hp->h.h_addrtype = hp->h_addrtype;
1203 new_hp->h.h_length = hp->h_length;
1205 /* first write the address list */
1206 pp = hp->h_addr_list;
1207 ap = new_hp->h.h_addr_list =
1208 (char**)(new_hp->buf + ((alias_count + 1) * sizeof(char*)));
1209 p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1213 memcpy(p, *pp++, hp->h_length);
1217 /* next write the name */
1218 new_hp->h.h_name = p;
1219 strcpy(p, hp->h_name);
1220 p += (strlen(p) + 1);
1222 /* last write the alias list */
1224 ap = new_hp->h.h_aliases = (char**) new_hp->buf;
1228 p += (strlen(p) + 1);
1234 * update_hostent - Add records to a Hostent struct in place.
1236 static void update_hostent(struct Hostent* hp, char** addr, char** alias)
1241 int alias_count = 0;
1244 size_t bytes_needed = 0;
1246 if (!hp || !hp->buf)
1249 /* how much buffer do we need? */
1250 bytes_needed = strlen(hp->h.h_name) + 1;
1251 pp = hp->h.h_aliases;
1253 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1259 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1263 pp = hp->h.h_addr_list;
1265 bytes_needed += (hp->h.h_length + sizeof(char*));
1271 bytes_needed += (hp->h.h_length + sizeof(char*));
1275 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1276 bytes_needed += 2 * sizeof(char*);
1278 /* Allocate memory */
1279 buf = (char*) MyMalloc(bytes_needed);
1282 /* first write the address list */
1283 pp = hp->h.h_addr_list;
1284 ap = hp->h.h_addr_list =
1285 (char**)(buf + ((alias_count + 1) * sizeof(char*)));
1286 p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1288 memcpy(p, *pp++, hp->h.h_length);
1290 p += hp->h.h_length;
1294 memcpy(p, *addr++, hp->h.h_length);
1296 p += hp->h.h_length;
1301 /* next write the name */
1302 strcpy(p, hp->h.h_name);
1304 p += (strlen(p) + 1);
1306 /* last write the alias list */
1307 pp = hp->h.h_aliases;
1308 ap = hp->h.h_aliases = (char**) buf;
1312 p += (strlen(p) + 1);
1316 strcpy(p, *alias++);
1318 p += (strlen(p) + 1);
1322 /* release the old buffer */
1329 * hash_number - IP address hash function
1331 static int hash_number(const unsigned char* ip)
1333 /* could use loop but slower */
1335 const u_char* p = (const u_char*) ip;
1340 hashv += hashv + *p++;
1341 hashv += hashv + *p++;
1342 hashv += hashv + *p;
1343 hashv %= ARES_CACSIZE;
1348 * hash_name - hostname hash function
1350 static int hash_name(const char* name)
1352 unsigned int hashv = 0;
1353 const u_char* p = (const u_char*) name;
1357 for (; *p && *p != '.'; ++p)
1359 hashv %= ARES_CACSIZE;
1364 * add_to_cache - Add a new cache item to the queue and hash table.
1366 static struct CacheEntry* add_to_cache(struct CacheEntry* ocp)
1372 ocp->list_next = cacheTop;
1375 hashv = hash_name(ocp->he.h.h_name);
1377 ocp->hname_next = hashtable[hashv].name_list;
1378 hashtable[hashv].name_list = ocp;
1380 hashv = hash_number((const unsigned char*) ocp->he.h.h_addr);
1382 ocp->hnum_next = hashtable[hashv].num_list;
1383 hashtable[hashv].num_list = ocp;
1386 * LRU deletion of excessive cache entries.
1388 if (++cachedCount > MAXCACHED) {
1389 struct CacheEntry* cp;
1390 struct CacheEntry* cp_next;
1391 for (cp = ocp->list_next; cp; cp = cp_next) {
1392 cp_next = cp->list_next;
1401 * update_list - does not alter the cache structure passed. It is assumed that
1402 * it already contains the correct expire time, if it is a new entry. Old
1403 * entries have the expirey time updated.
1405 static void update_list(struct ResRequest* request, struct CacheEntry* cachep)
1408 struct CacheEntry** cpp;
1410 struct CacheEntry* cp = cachep;
1416 char* addrs[RES_MAXADDRS + 1];
1417 char* aliases[RES_MAXALIASES + 1];
1420 * search for the new cache item in the cache list by hostname.
1421 * If found, move the entry to the top of the list and return.
1423 ++cainfo.ca_updates;
1425 for (cpp = &cacheTop; *cpp; cpp = &((*cpp)->list_next)) {
1431 *cpp = cp->list_next;
1432 cp->list_next = cacheTop;
1439 * Compare the cache entry against the new record. Add any
1440 * previously missing names for this entry.
1444 for (i = 0, s = request->he.h.h_name; s; s = request->he.h.h_aliases[i++]) {
1445 for (j = 0, t = cp->he.h.h_name; t; t = cp->he.h.h_aliases[j++]) {
1446 if (0 == ircd_strcmp(t, s))
1455 * Do the same again for IP#'s.
1459 for (i = 0; (s = request->he.h.h_addr_list[i]); i++) {
1460 for (j = 0; (t = cp->he.h.h_addr_list[j]); j++) {
1461 if (!memcmp(t, s, sizeof(struct in_addr)))
1469 if (*addrs || *aliases)
1470 update_hostent(&cp->he, addrs, aliases);
1474 * find_cache_name - find name in nameserver cache
1476 static struct CacheEntry* find_cache_name(const char* name)
1478 struct CacheEntry* cp;
1484 hashv = hash_name(name);
1486 cp = hashtable[hashv].name_list;
1488 for (; cp; cp = cp->hname_next) {
1489 for (i = 0, s = cp->he.h.h_name; s; s = cp->he.h.h_aliases[i++]) {
1490 if (0 == ircd_strcmp(s, name)) {
1491 ++cainfo.ca_na_hits;
1497 for (cp = cacheTop; cp; cp = cp->list_next) {
1499 * if no aliases or the hash value matches, we've already
1500 * done this entry and all possiblilities concerning it.
1502 if (!cp->he.h.h_name || hashv == hash_name(cp->he.h.h_name))
1504 for (i = 0, s = cp->he.h.h_aliases[i]; s; s = cp->he.h.h_aliases[++i]) {
1505 if (0 == ircd_strcmp(name, s)) {
1506 ++cainfo.ca_na_hits;
1515 * find_cache_number - find a cache entry by ip# and update its expire time
1517 static struct CacheEntry* find_cache_number(struct ResRequest* request,
1520 struct CacheEntry* cp;
1525 hashv = hash_number((const unsigned char*) addr);
1526 cp = hashtable[hashv].num_list;
1528 for (; cp; cp = cp->hnum_next) {
1529 for (i = 0; cp->he.h.h_addr_list[i]; ++i) {
1530 if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1531 ++cainfo.ca_nu_hits;
1536 for (cp = cacheTop; cp; cp = cp->list_next) {
1538 * single address entry...would have been done by hashed
1540 * if the first IP# has the same hashnumber as the IP# we
1541 * are looking for, its been done already.
1543 if (!cp->he.h.h_addr_list[1] ||
1544 hashv == hash_number((const unsigned char*) cp->he.h.h_addr_list[0]))
1546 for (i = 1; cp->he.h.h_addr_list[i]; ++i) {
1547 if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1548 ++cainfo.ca_nu_hits;
1556 static struct CacheEntry* make_cache(struct ResRequest* request)
1558 struct CacheEntry* cp;
1561 assert(0 != request);
1563 hp = &request->he.h;
1565 * shouldn't happen but it just might...
1567 assert(0 != hp->h_name);
1568 assert(0 != hp->h_addr_list[0]);
1569 if (!hp->h_name || !hp->h_addr_list[0])
1572 * Make cache entry. First check to see if the cache already exists
1573 * and if so, return a pointer to it.
1575 for (i = 0; hp->h_addr_list[i]; ++i) {
1576 if ((cp = find_cache_number(request, hp->h_addr_list[i]))) {
1577 update_list(request, cp);
1582 * a matching entry wasnt found in the cache so go and make one up.
1584 cp = (struct CacheEntry*) MyMalloc(sizeof(struct CacheEntry));
1587 memset(cp, 0, sizeof(struct CacheEntry));
1588 dup_hostent(&cp->he, hp);
1589 cp->reply.hp = &cp->he.h;
1591 * hmmm... we could time out the cache after 10 minutes regardless
1592 * would that be reasonable since we don't save the reply?
1594 if (request->ttl < AR_TTL) {
1595 ++reinfo.re_shortttl;
1599 cp->ttl = request->ttl;
1600 cp->expireat = CurrentTime + cp->ttl;
1601 return add_to_cache(cp);
1605 * rem_cache - delete a cache entry from the cache structures
1606 * and lists and return all memory used for the cache back to the memory pool.
1608 static void rem_cache(struct CacheEntry* ocp)
1610 struct CacheEntry** cp;
1616 if (0 < ocp->reply.ref_count) {
1617 if (ocp->expireat < CurrentTime) {
1618 ocp->expireat = CurrentTime + AR_TTL;
1619 Debug((DEBUG_DNS, "Resolver: referenced cache entry not removed for: %s",
1625 * remove cache entry from linked list
1627 for (cp = &cacheTop; *cp; cp = &((*cp)->list_next)) {
1629 *cp = ocp->list_next;
1635 * remove cache entry from hashed name list
1637 assert(0 != hp->h_name);
1638 hashv = hash_name(hp->h_name);
1640 for (cp = &hashtable[hashv].name_list; *cp; cp = &((*cp)->hname_next)) {
1642 *cp = ocp->hname_next;
1647 * remove cache entry from hashed number list
1649 hashv = hash_number((const unsigned char*) hp->h_addr);
1652 for (cp = &hashtable[hashv].num_list; *cp; cp = &((*cp)->hnum_next)) {
1654 *cp = ocp->hnum_next;
1659 * free memory used to hold the various host names and the array
1660 * of alias pointers.
1662 MyFree(ocp->he.buf);
1668 void flush_resolver_cache(void)
1671 * stubbed - iterate cache and remove everything that isn't referenced
1676 * m_dns - dns status query
1678 int m_dns(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1680 #if !defined(NDEBUG)
1681 struct CacheEntry* cp;
1685 if (parv[1] && *parv[1] == 'l') {
1686 for(cp = cacheTop; cp; cp = cp->list_next) {
1688 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :Ex %d ttl %d host %s(%s)",
1689 sptr, cp->expireat - CurrentTime, cp->ttl,
1690 hp->h_name, ircd_ntoa(hp->h_addr));
1691 for (i = 0; hp->h_aliases[i]; i++)
1692 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C : %s = %s (CN)", sptr,
1693 hp->h_name, hp->h_aliases[i]);
1694 for (i = 1; hp->h_addr_list[i]; i++)
1695 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C : %s = %s (IP)", sptr,
1696 hp->h_name, ircd_ntoa(hp->h_addr_list[i]));
1700 if (parv[1] && *parv[1] == 'd') {
1701 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :ResolverFileDescriptor = %d",
1702 sptr, ResolverFileDescriptor);
1705 sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ca %d Cd %d Ce %d Cl %d Ch %d:%d "
1707 cainfo.ca_adds, cainfo.ca_dels, cainfo.ca_expires,
1708 cainfo.ca_lookups, cainfo.ca_na_hits, cainfo.ca_nu_hits,
1711 sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Re %d Rl %d/%d Rp %d Rq %d",
1712 sptr, reinfo.re_errors, reinfo.re_nu_look,
1713 reinfo.re_na_look, reinfo.re_replies, reinfo.re_requests);
1714 sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ru %d Rsh %d Rs %d(%d) Rt %d", sptr,
1715 reinfo.re_unkrep, reinfo.re_shortttl, reinfo.re_sent,
1716 reinfo.re_resends, reinfo.re_timeouts);
1721 size_t cres_mem(struct Client* sptr)
1723 struct CacheEntry* entry;
1724 struct ResRequest* request;
1725 size_t cache_mem = 0;
1726 size_t request_mem = 0;
1727 int cache_count = 0;
1728 int request_count = 0;
1730 for (entry = cacheTop; entry; entry = entry->list_next) {
1731 cache_mem += sizeof(struct CacheEntry);
1732 cache_mem += calc_hostent_buffer_size(&entry->he.h);
1735 for (request = requestListHead; request; request = request->next) {
1736 request_mem += sizeof(struct ResRequest);
1738 request_mem += strlen(request->name) + 1;
1739 if (request->he.buf)
1740 request_mem += MAXGETHOSTLEN + 1;
1744 if (cachedCount != cache_count) {
1745 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1746 ":Resolver: cache count mismatch: %d != %d", cachedCount,
1748 assert(cachedCount == cache_count);
1750 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1751 ":Resolver: cache %d(%d) requests %d(%d)", cache_count,
1752 cache_mem, request_count, request_mem);
1753 return cache_mem + request_mem;