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"
20 #include "ircd_osdep.h"
21 #include "ircd_reply.h"
22 #include "ircd_string.h"
29 #include "sprintf_irc.h"
39 #include <sys/socket.h>
44 #include <arpa/nameser.h>
47 #include <arpa/inet.h>
51 #error this code needs to be able to address individual octets
55 * Some systems do not define INADDR_NONE (255.255.255.255)
56 * INADDR_NONE is actually a valid address, but it should never
57 * be returned from any nameserver.
58 * NOTE: The bit pattern for INADDR_NONE and INADDR_ANY (0.0.0.0) should be
59 * the same on all hosts so we shouldn't need to use htonl or ntohl to
60 * compare or set the values.
63 #define INADDR_NONE ((unsigned int) 0xffffffff)
66 #define MAXPACKET 1024 /* rfc sez 512 but we expand names so ... */
67 #define RES_MAXALIASES 35 /* maximum aliases allowed */
68 #define RES_MAXADDRS 35 /* maximum addresses allowed */
70 * OSF1 doesn't have RES_NOALIASES
73 #define RES_NOALIASES 0
77 * macros used to calulate offsets into fixed query buffer
79 #define ALIAS_BLEN ((RES_MAXALIASES + 1) * sizeof(char*))
80 #define ADDRS_BLEN ((RES_MAXADDRS + 1) * sizeof(struct in_addr*))
82 #define ADDRS_OFFSET (ALIAS_BLEN + ADDRS_BLEN)
83 #define ADDRS_DLEN (RES_MAXADDRS * sizeof(struct in_addr))
84 #define NAMES_OFFSET (ADDRS_OFFSET + ADDRS_DLEN)
85 #define MAXGETHOSTLEN (NAMES_OFFSET + MAXPACKET)
87 #define AR_TTL 600 /* TTL in seconds for dns cache entries */
90 * the following values should be prime
92 #define ARES_CACSIZE 307
96 * RFC 1104/1105 wasn't very helpful about what these fields
97 * should be named, so for now, we'll just name them this way.
98 * we probably should look at what named calls them or something.
103 #define RDLENGTH_SIZE 2
104 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
107 * Building the Hostent
108 * The Hostent struct is arranged like this:
109 * +-------------------------------+
110 * Hostent: | struct hostent h |
111 * |-------------------------------|
113 * +-------------------------------+
117 * +-------------------------------+
118 * buf: | h_aliases pointer array | Max size: ALIAS_BLEN;
119 * | NULL | contains `char *'s
120 * |-------------------------------|
121 * | h_addr_list pointer array | Max size: ADDRS_BLEN;
122 * | NULL | contains `struct in_addr *'s
123 * |-------------------------------|
124 * | h_addr_list addresses | Max size: ADDRS_DLEN;
125 * | | contains `struct in_addr's
126 * |-------------------------------|
127 * | storage for hostname strings | Max size: ALIAS_DLEN;
128 * +-------------------------------+ contains `char's
130 * For requests the size of the h_aliases, and h_addr_list pointer
131 * array sizes are set to MAXALISES and MAXADDRS respectively, and
132 * buf is a fixed size with enough space to hold the largest expected
133 * reply from a nameserver, see RFC 1034 and RFC 1035.
134 * For cached entries the sizes are dependent on the actual number
135 * of aliases and addresses. If new aliases and addresses are found
136 * for cached entries, the buffer is grown and the new entries are added.
137 * The hostent struct is filled in with the addresses of the entries in
138 * the Hostent buf as follows:
139 * h_name - contains a pointer to the start of the hostname string area,
140 * or NULL if none is set. The h_name is followed by the
141 * aliases, in the storage for hostname strings area.
142 * h_aliases - contains a pointer to the start of h_aliases pointer array.
143 * This array contains pointers to the storage for hostname
144 * strings area and is terminated with a NULL. The first alias
145 * is stored directly after the h_name.
146 * h_addr_list - contains a pointer to the start of h_addr_list pointer array.
147 * This array contains pointers to in_addr structures in the
148 * h_addr_list addresses area and is terminated with a NULL.
150 * Filling the buffer this way allows for proper alignment of the h_addr_list
153 * This arrangement allows us to alias a Hostent struct pointer as a
154 * real struct hostent* without lying. It also allows us to change the
155 * values contained in the cached entries and requests without changing
156 * the actual hostent pointer, which is saved in a client struct and can't
157 * be changed without blowing things up or a lot more fiddling around.
158 * It also allows for defered allocation of the fixed size buffers until
159 * they are really needed.
160 * Nov. 17, 1997 --Bleep
164 struct hostent h; /* the hostent struct we are passing around */
165 char* buf; /* buffer for data pointed to from hostent */
169 struct ResRequest* next;
171 int sent; /* number of requests sent */
174 char retries; /* retry counter */
175 char sends; /* number of sends (>1 means resent) */
176 char resend; /* send flag. 0 == dont resend */
181 struct DNSQuery query; /* query callback for this request */
186 struct CacheEntry* hname_next;
187 struct CacheEntry* hnum_next;
188 struct CacheEntry* list_next;
192 struct DNSReply reply;
196 struct CacheEntry* num_list;
197 struct CacheEntry* name_list;
201 int ResolverFileDescriptor = -1; /* GLOBAL - used in s_bsd.c */
203 static time_t nextDNSCheck = 0;
204 static time_t nextCacheExpire = 1;
207 * Keep a spare file descriptor open. res_init calls fopen to read the
208 * resolv.conf file. If ircd is hogging all the file descriptors below 256,
209 * on systems with crippled FILE structures this will cause wierd bugs.
210 * This is definitely needed for Solaris which uses an unsigned char to
211 * hold the file descriptor. --Dianora
213 static int spare_fd = -1;
215 static int cachedCount = 0;
216 static struct CacheTable hashtable[ARES_CACSIZE];
217 static struct CacheEntry* cacheTop;
218 static struct ResRequest* requestListHead; /* head of resolver request list */
219 static struct ResRequest* requestListTail; /* tail of resolver request list */
222 static void add_request(struct ResRequest* request);
223 static void rem_request(struct ResRequest* request);
224 static struct ResRequest* make_request(const struct DNSQuery* query);
225 static void rem_cache(struct CacheEntry*);
226 static void do_query_name(const struct DNSQuery* query,
228 struct ResRequest* request);
229 static void do_query_number(const struct DNSQuery* query,
230 const struct in_addr*,
231 struct ResRequest* request);
232 static void query_name(const char* name,
235 struct ResRequest* request);
236 static void resend_query(struct ResRequest* request);
237 static struct CacheEntry* make_cache(struct ResRequest* request);
238 static struct CacheEntry* find_cache_name(const char* name);
239 static struct CacheEntry* find_cache_number(struct ResRequest* request,
241 static struct ResRequest* find_id(int);
243 static struct cacheinfo {
253 static struct resinfo {
268 * From bind 8.3, these aren't declared in earlier versions of bind
270 extern u_short _getshort(const u_char *);
271 extern u_int _getlong(const u_char *);
274 * res_isourserver(ina)
275 * looks up "ina" in _res.ns_addr_list[]
280 * paul vixie, 29may94
283 res_ourserver(const struct __res_state* statp, const struct sockaddr_in* inp)
285 struct sockaddr_in ina;
289 for (ns = 0; ns < statp->nscount; ns++) {
290 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
292 if (srv->sin_family == ina.sin_family &&
293 srv->sin_port == ina.sin_port &&
294 (srv->sin_addr.s_addr == INADDR_ANY ||
295 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
302 * start_resolver - do everything we need to read the resolv.conf file
303 * and initialize the resolver file descriptor if needed
305 static void start_resolver(void)
307 Debug((DEBUG_DNS, "Resolver: start_resolver"));
309 * close the spare file descriptor so res_init can read resolv.conf
310 * successfully. Needed on Solaris
315 res_init(); /* res_init always returns 0 */
317 * make sure we have a valid file descriptor below 256 so we can
318 * do this again. Needed on Solaris
320 spare_fd = open("/dev/null",O_RDONLY,0);
321 if ((spare_fd < 0) || (spare_fd > 255)) {
323 sprintf_irc(sparemsg, "invalid spare_fd %d", spare_fd);
324 server_restart(sparemsg);
329 _res.nsaddr_list[0].sin_addr.s_addr = inet_addr("127.0.0.1");
331 _res.options |= RES_NOALIASES;
333 if (ResolverFileDescriptor < 0) {
334 ResolverFileDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
335 if (-1 == ResolverFileDescriptor) {
336 report_error("Resolver: error creating socket for %s: %s",
337 cli_name(&me), errno);
340 if (!os_set_nonblocking(ResolverFileDescriptor))
341 report_error("Resolver: error setting non-blocking for %s: %s",
342 cli_name(&me), errno);
347 * init_resolver - initialize resolver and resolver library
349 int init_resolver(void)
351 Debug((DEBUG_DNS, "Resolver: init_resolver"));
353 srand48(CurrentTime);
355 memset(&cainfo, 0, sizeof(cainfo));
356 memset(hashtable, 0, sizeof(hashtable));
357 memset(&reinfo, 0, sizeof(reinfo));
359 requestListHead = requestListTail = 0;
364 Debug((DEBUG_DNS, "Resolver: fd %d errno: %d h_errno: %d: %s",
365 ResolverFileDescriptor, errno, h_errno,
366 (strerror(errno)) ? strerror(errno) : "Unknown"));
367 return ResolverFileDescriptor;
371 * restart_resolver - flush the cache, reread resolv.conf, reopen socket
373 void restart_resolver(void)
375 /* flush_cache(); flush the dns cache */
379 static int validate_hostent(const struct hostent* hp)
384 for (name = hp->h_name; name; name = hp->h_aliases[i++]) {
385 if (!string_is_hostname(name))
392 * add_request - place a new request in the request list
394 static void add_request(struct ResRequest* request)
396 assert(0 != request);
397 if (!requestListHead)
398 requestListHead = requestListTail = request;
400 requestListTail->next = request;
401 requestListTail = request;
403 request->next = NULL;
404 ++reinfo.re_requests;
408 * rem_request - remove a request from the list.
409 * This must also free any memory that has been allocated for
410 * temporary storage of DNS results.
412 static void rem_request(struct ResRequest* request)
414 struct ResRequest** current;
415 struct ResRequest* prev = NULL;
417 assert(0 != request);
418 for (current = &requestListHead; *current; ) {
419 if (*current == request) {
420 *current = request->next;
421 if (requestListTail == request)
422 requestListTail = prev;
426 current = &(*current)->next;
428 MyFree(request->he.buf);
429 MyFree(request->name);
434 * make_request - Create a DNS request record for the server.
436 static struct ResRequest* make_request(const struct DNSQuery* query)
438 struct ResRequest* request;
440 request = (struct ResRequest*) MyMalloc(sizeof(struct ResRequest));
441 memset(request, 0, sizeof(struct ResRequest));
443 request->sentat = CurrentTime;
444 request->retries = 3;
446 request->timeout = 5; /* start at 5 per RFC1123 */
447 request->addr.s_addr = INADDR_NONE;
448 request->he.h.h_addrtype = AF_INET;
449 request->he.h.h_length = sizeof(struct in_addr);
450 request->query.vptr = query->vptr;
451 request->query.callback = query->callback;
453 #if defined(NULL_POINTER_NOT_ZERO)
454 request->next = NULL;
455 request->he.buf = NULL;
456 request->he.h.h_name = NULL;
457 request->he.h.h_aliases = NULL;
458 request->he.h.h_addr_list = NULL;
460 add_request(request);
465 * timeout_query_list - Remove queries from the list which have been
466 * there too long without being resolved.
468 static time_t timeout_query_list(time_t now)
470 struct ResRequest* request;
471 struct ResRequest* next_request = 0;
472 time_t next_time = 0;
475 Debug((DEBUG_DNS, "Resolver: timeout_query_list at %s", myctime(now)));
476 for (request = requestListHead; request; request = next_request) {
477 next_request = request->next;
478 timeout = request->sentat + request->timeout;
480 if (--request->retries <= 0) {
481 ++reinfo.re_timeouts;
482 (*request->query.callback)(request->query.vptr, 0);
483 rem_request(request);
487 request->sentat = now;
488 request->timeout += request->timeout;
489 resend_query(request);
492 if (!next_time || timeout < next_time) {
496 return (next_time > now) ? next_time : (now + AR_TTL);
500 * expire_cache - removes entries from the cache which are older
501 * than their expiry times. returns the time at which the server
502 * should next poll the cache.
504 static time_t expire_cache(time_t now)
506 struct CacheEntry* cp;
507 struct CacheEntry* cp_next;
510 Debug((DEBUG_DNS, "Resolver: expire_cache at %s", myctime(now)));
511 for (cp = cacheTop; cp; cp = cp_next) {
512 cp_next = cp->list_next;
513 if (cp->expireat < now) {
517 else if (!expire || expire > cp->expireat)
518 expire = cp->expireat;
520 return (expire > now) ? expire : (now + AR_TTL);
524 * timeout_resolver - check request list and cache for expired entries
526 time_t timeout_resolver(time_t now)
528 if (nextDNSCheck < now)
529 nextDNSCheck = timeout_query_list(now);
530 if (nextCacheExpire < now)
531 nextCacheExpire = expire_cache(now);
532 return IRCD_MIN(nextDNSCheck, nextCacheExpire);
537 * delete_resolver_queries - cleanup outstanding queries
538 * for which there no longer exist clients or conf lines.
540 void delete_resolver_queries(const void* vptr)
542 struct ResRequest* request;
543 struct ResRequest* next_request;
545 for (request = requestListHead; request; request = next_request) {
546 next_request = request->next;
547 if (vptr == request->query.vptr)
548 rem_request(request);
553 * send_res_msg - sends msg to all nameservers found in the "_res" structure.
554 * This should reflect /etc/resolv.conf. We will get responses
555 * which arent needed but is easier than checking to see if nameserver
556 * isnt present. Returns number of messages successfully sent to
557 * nameservers or -1 if no successful sends.
559 static int send_res_msg(const u_char* msg, int len, int rcount)
563 int max_queries = IRCD_MIN(_res.nscount, rcount);
567 * RES_PRIMARY option is not implemented
568 * if (_res.options & RES_PRIMARY || 0 == max_queries)
570 if (0 == max_queries)
573 Debug((DEBUG_DNS, "Resolver: sendto %d", max_queries));
575 for (i = 0; i < max_queries; i++) {
576 if (sendto(ResolverFileDescriptor, msg, len, 0,
577 (struct sockaddr*) &(_res.nsaddr_list[i]),
578 sizeof(struct sockaddr_in)) == len) {
583 log_write(LS_RESOLVER, L_ERROR, 0, "Resolver: send failed %m");
589 * find_id - find a dns request id (id is determined by dn_mkquery)
591 static struct ResRequest* find_id(int id)
593 struct ResRequest* request;
595 for (request = requestListHead; request; request = request->next) {
596 if (request->id == id)
603 * gethost_byname - get host address from name
605 struct DNSReply* gethost_byname(const char* name,
606 const struct DNSQuery* query)
608 struct CacheEntry* cp;
611 Debug((DEBUG_DNS, "Resolver: gethost_byname %s", name));
613 if ((cp = find_cache_name(name)))
616 do_query_name(query, name, NULL);
622 * gethost_byaddr - get host name from address
624 struct DNSReply* gethost_byaddr(const char* addr,
625 const struct DNSQuery* query)
627 struct CacheEntry *cp;
631 Debug((DEBUG_DNS, "Resolver: gethost_byaddr %s", ircd_ntoa(addr)));
634 if ((cp = find_cache_number(NULL, addr)))
637 do_query_number(query, (const struct in_addr*) addr, NULL);
643 * do_query_name - nameserver lookup name
645 static void do_query_name(const struct DNSQuery* query,
646 const char* name, struct ResRequest* request)
648 char hname[HOSTLEN + 1];
651 ircd_strncpy(hname, name, HOSTLEN);
652 hname[HOSTLEN] = '\0';
655 request = make_request(query);
657 request->name = (char*) MyMalloc(strlen(hname) + 1);
658 strcpy(request->name, hname);
660 query_name(hname, C_IN, T_A, request);
664 * do_query_number - Use this to do reverse IP# lookups.
666 static void do_query_number(const struct DNSQuery* query,
667 const struct in_addr* addr,
668 struct ResRequest* request)
671 const unsigned char* cp;
674 cp = (const unsigned char*) &addr->s_addr;
675 sprintf_irc(ipbuf, "%u.%u.%u.%u.in-addr.arpa.",
676 (unsigned int)(cp[3]), (unsigned int)(cp[2]),
677 (unsigned int)(cp[1]), (unsigned int)(cp[0]));
680 request = make_request(query);
681 request->type = T_PTR;
682 request->addr.s_addr = addr->s_addr;
684 query_name(ipbuf, C_IN, T_PTR, request);
688 * query_name - generate a query based on class, type and name.
690 static void query_name(const char* name, int query_class,
691 int type, struct ResRequest* request)
697 assert(0 != request);
699 Debug((DEBUG_DNS, "Resolver: query_name: %s %d %d", name, query_class, type));
700 memset(buf, 0, sizeof(buf));
701 if ((request_len = res_mkquery(QUERY, name, query_class, type,
702 0, 0, 0, (unsigned char*) buf, sizeof(buf))) > 0) {
703 HEADER* header = (HEADER*) buf;
709 * generate a unique id
710 * NOTE: we don't have to worry about converting this to and from
711 * network byte order, the nameserver does not interpret this value
712 * and returns it unchanged
716 header->id = (header->id + lrand48()) & 0xffff;
717 } while (find_id(header->id));
719 gettimeofday(&tv, NULL);
721 header->id = (header->id + k + tv.tv_usec) & 0xffff;
723 } while (find_id(header->id));
725 request->id = header->id;
727 Debug((DEBUG_DNS, "Resolver: query_name %d: %s %d %d", request->id,
728 name, query_class, type));
729 request->sent += send_res_msg((const unsigned char*) buf, request_len, request->sends);
733 static void resend_query(struct ResRequest* request)
735 assert(0 != request);
737 if (request->resend == 0)
740 switch(request->type) {
742 do_query_number(NULL, &request->addr, request);
745 do_query_name(NULL, request->name, request);
753 * proc_answer - process name server reply
754 * build a hostent struct in the passed request
756 static int proc_answer(struct ResRequest* request, HEADER* header,
757 u_char* buf, u_char* eob)
759 char hostbuf[HOSTLEN + 1]; /* working buffer */
760 u_char* current; /* current position in buf */
761 char** alias; /* alias list */
762 char** addr; /* address list */
763 char* name; /* pointer to name string */
764 char* address; /* pointer to address */
765 char* endp; /* end of our buffer */
766 int query_class; /* answer class */
767 int type; /* answer type */
768 int rd_length; /* record data length */
769 int answer_count = 0; /* answer counter */
770 int n; /* temp count */
771 int addr_count = 0; /* number of addresses in hostent */
772 int alias_count = 0; /* number of aliases in hostent */
773 struct hostent* hp; /* hostent getting filled */
775 assert(0 != request);
780 current = buf + sizeof(HEADER);
781 hp = &(request->he.h);
783 * lazy allocation of request->he.buf, we don't allocate a buffer
784 * unless there is something to put in it.
786 if (!request->he.buf) {
787 request->he.buf = (char*) MyMalloc(MAXGETHOSTLEN + 1);
788 request->he.buf[MAXGETHOSTLEN] = '\0';
790 * array of alias list pointers starts at beginning of buf
792 hp->h_aliases = (char**) request->he.buf;
793 hp->h_aliases[0] = NULL;
795 * array of address list pointers starts after alias list pointers
796 * the actual addresses follow the the address list pointers
798 hp->h_addr_list = (char**)(request->he.buf + ALIAS_BLEN);
800 * don't copy the host address to the beginning of h_addr_list
802 hp->h_addr_list[0] = NULL;
804 endp = request->he.buf + MAXGETHOSTLEN;
806 * find the end of the address list
808 addr = hp->h_addr_list;
814 * make address point to first available address slot
816 address = request->he.buf + ADDRS_OFFSET +
817 (sizeof(struct in_addr) * addr_count);
819 * find the end of the alias list
821 alias = hp->h_aliases;
827 * make name point to first available space in request->buf
829 if (alias_count > 0) {
830 name = hp->h_aliases[alias_count - 1];
831 name += (strlen(name) + 1);
834 name = hp->h_name + strlen(hp->h_name) + 1;
836 name = request->he.buf + ADDRS_OFFSET + ADDRS_DLEN;
841 while (header->qdcount-- > 0) {
842 if ((n = dn_skipname(current, eob)) < 0)
844 current += (n + QFIXEDSZ);
847 * process each answer sent to us blech.
849 while (header->ancount-- > 0 && current < eob && name < endp) {
850 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
853 * no more answers left
857 hostbuf[HOSTLEN] = '\0';
859 * With Address arithmetic you have to be very anal
860 * this code was not working on alpha due to that
861 * (spotted by rodder/jailbird/dianora)
863 current += (size_t) n;
865 if (!((current + ANSWER_FIXED_SIZE) < eob))
868 type = _getshort(current);
869 current += TYPE_SIZE;
871 query_class = _getshort(current);
872 current += CLASS_SIZE;
874 request->ttl = _getlong(current);
877 rd_length = _getshort(current);
878 current += RDLENGTH_SIZE;
881 * Wait to set request->type until we verify this structure
886 * check for invalid rd_length or too many addresses
888 if (rd_length != sizeof(struct in_addr))
890 if (++addr_count < RES_MAXADDRS) {
891 if (answer_count == 1)
892 hp->h_addrtype = (query_class == C_IN) ? AF_INET : AF_UNSPEC;
894 memcpy(address, current, sizeof(struct in_addr));
897 address += sizeof(struct in_addr);
900 strcpy(name, hostbuf);
902 name += strlen(name) + 1;
904 Debug((DEBUG_DNS, "Resolver: A %s for %s",
905 ircd_ntoa((char*) hp->h_addr_list[addr_count - 1]), hostbuf));
907 current += rd_length;
911 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
920 * no more answers left
925 * This comment is based on analysis by Shadowfax, Wohali and johan,
926 * not me. (Dianora) I am only commenting it.
928 * dn_expand is guaranteed to not return more than sizeof(hostbuf)
929 * but do all implementations of dn_expand also guarantee
930 * buffer is terminated with null byte? Lets not take chances.
933 hostbuf[HOSTLEN] = '\0';
934 current += (size_t) n;
936 Debug((DEBUG_DNS, "Resolver: PTR %s", hostbuf));
938 * copy the returned hostname into the host name
939 * ignore duplicate ptr records
942 strcpy(name, hostbuf);
944 name += strlen(name) + 1;
949 Debug((DEBUG_DNS, "Resolver: CNAME %s", hostbuf));
950 if (++alias_count < RES_MAXALIASES) {
951 ircd_strncpy(name, hostbuf, endp - name);
954 name += strlen(name) + 1;
956 current += rd_length;
960 Debug((DEBUG_DNS,"Resolver: proc_answer type: %d for: %s", type, hostbuf));
968 * resolver_read - read a dns reply from the nameserver and process it.
969 * return 0 if nothing was read from the socket, otherwise return 1
971 int resolver_read(void)
973 u_char buf[sizeof(HEADER) + MAXPACKET];
975 struct ResRequest* request = 0;
976 struct CacheEntry* cp = 0;
978 int answer_count = 0;
979 struct sockaddr_in sin;
981 Debug((DEBUG_DNS, "Resolver: read"));
982 if (IO_SUCCESS != os_recvfrom_nonb(ResolverFileDescriptor,
983 (char*) buf, sizeof(buf), &rc, &sin)) {
986 if (rc < sizeof(HEADER)) {
987 Debug((DEBUG_DNS, "Resolver: short reply %d: %s", rc,
988 (strerror(errno)) ? strerror(errno) : "Unknown"));
992 * convert DNS reply reader from Network byte order to CPU byte order.
994 header = (HEADER*) buf;
995 /* header->id = ntohs(header->id); */
996 header->ancount = ntohs(header->ancount);
997 header->qdcount = ntohs(header->qdcount);
998 header->nscount = ntohs(header->nscount);
999 header->arcount = ntohs(header->arcount);
1000 ++reinfo.re_replies;
1002 * response for an id which we have already received an answer for
1003 * just ignore this response.
1005 if (0 == (request = find_id(header->id))) {
1006 Debug((DEBUG_DNS, "Resolver: can't find request id: %d", header->id));
1010 * check against possibly fake replies
1012 if (!res_ourserver(&_res, &sin)) {
1013 Debug((DEBUG_DNS, "Resolver: fake reply from: %s", (const char*) &sin.sin_addr));
1018 if ((header->rcode != NOERROR) || (header->ancount == 0)) {
1020 if (SERVFAIL == header->rcode)
1021 resend_query(request);
1024 * If a bad error was returned, we stop here and dont send
1025 * send any more (no retries granted).
1026 * Isomer: Perhaps we should return these error messages back to
1030 switch (header->rcode) {
1032 Debug((DEBUG_DNS, "Fatal DNS error: No Error"));
1035 Debug((DEBUG_DNS, "Fatal DNS error: Format Error"));
1038 Debug((DEBUG_DNS, "Fatal DNS error: Server Failure"));
1041 Debug((DEBUG_DNS, "DNS error: Non Existant Domain"));
1044 Debug((DEBUG_DNS, "Fatal DNS error: Not Implemented"));
1047 Debug((DEBUG_DNS, "Fatal DNS error: Query Refused"));
1050 Debug((DEBUG_DNS, "Unassigned fatal DNS error: %i", header->rcode));
1053 #endif /* DEBUGMODE */
1054 (*request->query.callback)(request->query.vptr, 0);
1055 rem_request(request);
1060 * If this fails there was an error decoding the received packet,
1061 * try it again and hope it works the next time.
1063 answer_count = proc_answer(request, header, buf, buf + rc);
1065 if (T_PTR == request->type) {
1066 struct DNSReply* reply = 0;
1067 if (0 == request->he.h.h_name) {
1069 * got a PTR response with no name, something bogus is happening
1070 * don't bother trying again, the client address doesn't resolve
1072 (*request->query.callback)(request->query.vptr, reply);
1073 rem_request(request);
1076 Debug((DEBUG_DNS, "relookup %s <-> %s",
1077 request->he.h.h_name, ircd_ntoa((char*) &request->addr)));
1079 * Lookup the 'authoritive' name that we were given for the
1080 * ip#. By using this call rather than regenerating the
1081 * type we automatically gain the use of the cache with no
1084 reply = gethost_byname(request->he.h.h_name, &request->query);
1086 (*request->query.callback)(request->query.vptr, reply);
1090 * If name wasn't found, a request has been queued and it will
1091 * be the last one queued. This is rather nasty way to keep
1092 * a host alias with the query. -avalon
1094 MyFree(requestListTail->he.buf);
1095 requestListTail->he.buf = request->he.buf;
1096 request->he.buf = 0;
1097 memcpy(&requestListTail->he.h, &request->he.h, sizeof(struct hostent));
1099 rem_request(request);
1103 * got a name and address response, client resolved
1104 * XXX - Bug found here by Dianora -
1105 * make_cache() occasionally returns a NULL pointer when a
1106 * PTR returned a CNAME, cp was not checked before so the
1107 * callback was being called with a value of 0x2C != NULL.
1109 struct DNSReply* reply = 0;
1110 if (validate_hostent(&request->he.h)) {
1111 if ((cp = make_cache(request)))
1114 (*request->query.callback)(request->query.vptr, reply);
1115 rem_request(request);
1118 else if (!request->sent) {
1120 * XXX - we got a response for a query we didn't send with a valid id?
1121 * this should never happen, bail here and leave the client unresolved
1123 (*request->query.callback)(request->query.vptr, 0);
1124 rem_request(request);
1130 * resolver_read_multiple - process up to count reads
1132 void resolver_read_multiple(int count)
1135 for ( ; i < count; ++i) {
1136 if (0 == resolver_read())
1141 static size_t calc_hostent_buffer_size(const struct hostent* hp)
1150 count += (strlen(hp->h_name) + 1);
1154 for (p = hp->h_aliases; *p; ++p)
1155 count += (strlen(*p) + 1 + sizeof(char*));
1157 * space for addresses
1159 for (p = hp->h_addr_list; *p; ++p)
1160 count += (hp->h_length + sizeof(char*));
1162 * space for 2 nulls to terminate h_aliases and h_addr_list
1164 count += (2 * sizeof(char*));
1170 * dup_hostent - Duplicate a hostent struct, allocate only enough memory for
1171 * the data we're putting in it.
1173 static void dup_hostent(struct Hostent* new_hp, struct hostent* hp)
1178 int alias_count = 0;
1180 size_t bytes_needed = 0;
1182 assert(0 != new_hp);
1185 /* how much buffer do we need? */
1186 bytes_needed += (strlen(hp->h_name) + 1);
1190 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1193 pp = hp->h_addr_list;
1195 bytes_needed += (hp->h_length + sizeof(char*));
1198 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1199 bytes_needed += (2 * sizeof(char*));
1201 /* Allocate memory */
1202 new_hp->buf = (char*) MyMalloc(bytes_needed);
1204 new_hp->h.h_addrtype = hp->h_addrtype;
1205 new_hp->h.h_length = hp->h_length;
1207 /* first write the address list */
1208 pp = hp->h_addr_list;
1209 ap = new_hp->h.h_addr_list =
1210 (char**)(new_hp->buf + ((alias_count + 1) * sizeof(char*)));
1211 p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1215 memcpy(p, *pp++, hp->h_length);
1219 /* next write the name */
1220 new_hp->h.h_name = p;
1221 strcpy(p, hp->h_name);
1222 p += (strlen(p) + 1);
1224 /* last write the alias list */
1226 ap = new_hp->h.h_aliases = (char**) new_hp->buf;
1230 p += (strlen(p) + 1);
1236 * update_hostent - Add records to a Hostent struct in place.
1238 static void update_hostent(struct Hostent* hp, char** addr, char** alias)
1243 int alias_count = 0;
1246 size_t bytes_needed = 0;
1248 if (!hp || !hp->buf)
1251 /* how much buffer do we need? */
1252 bytes_needed = strlen(hp->h.h_name) + 1;
1253 pp = hp->h.h_aliases;
1255 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1261 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1265 pp = hp->h.h_addr_list;
1267 bytes_needed += (hp->h.h_length + sizeof(char*));
1273 bytes_needed += (hp->h.h_length + sizeof(char*));
1277 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1278 bytes_needed += 2 * sizeof(char*);
1280 /* Allocate memory */
1281 buf = (char*) MyMalloc(bytes_needed);
1284 /* first write the address list */
1285 pp = hp->h.h_addr_list;
1286 ap = hp->h.h_addr_list =
1287 (char**)(buf + ((alias_count + 1) * sizeof(char*)));
1288 p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1290 memcpy(p, *pp++, hp->h.h_length);
1292 p += hp->h.h_length;
1296 memcpy(p, *addr++, hp->h.h_length);
1298 p += hp->h.h_length;
1303 /* next write the name */
1304 strcpy(p, hp->h.h_name);
1306 p += (strlen(p) + 1);
1308 /* last write the alias list */
1309 pp = hp->h.h_aliases;
1310 ap = hp->h.h_aliases = (char**) buf;
1314 p += (strlen(p) + 1);
1318 strcpy(p, *alias++);
1320 p += (strlen(p) + 1);
1324 /* release the old buffer */
1331 * hash_number - IP address hash function
1333 static int hash_number(const unsigned char* ip)
1335 /* could use loop but slower */
1337 const u_char* p = (const u_char*) ip;
1342 hashv += hashv + *p++;
1343 hashv += hashv + *p++;
1344 hashv += hashv + *p;
1345 hashv %= ARES_CACSIZE;
1350 * hash_name - hostname hash function
1352 static int hash_name(const char* name)
1354 unsigned int hashv = 0;
1355 const u_char* p = (const u_char*) name;
1359 for (; *p && *p != '.'; ++p)
1361 hashv %= ARES_CACSIZE;
1366 * add_to_cache - Add a new cache item to the queue and hash table.
1368 static struct CacheEntry* add_to_cache(struct CacheEntry* ocp)
1374 ocp->list_next = cacheTop;
1377 hashv = hash_name(ocp->he.h.h_name);
1379 ocp->hname_next = hashtable[hashv].name_list;
1380 hashtable[hashv].name_list = ocp;
1382 hashv = hash_number((const unsigned char*) ocp->he.h.h_addr);
1384 ocp->hnum_next = hashtable[hashv].num_list;
1385 hashtable[hashv].num_list = ocp;
1388 * LRU deletion of excessive cache entries.
1390 if (++cachedCount > MAXCACHED) {
1391 struct CacheEntry* cp;
1392 struct CacheEntry* cp_next;
1393 for (cp = ocp->list_next; cp; cp = cp_next) {
1394 cp_next = cp->list_next;
1403 * update_list - does not alter the cache structure passed. It is assumed that
1404 * it already contains the correct expire time, if it is a new entry. Old
1405 * entries have the expirey time updated.
1407 static void update_list(struct ResRequest* request, struct CacheEntry* cachep)
1410 struct CacheEntry** cpp;
1412 struct CacheEntry* cp = cachep;
1418 char* addrs[RES_MAXADDRS + 1];
1419 char* aliases[RES_MAXALIASES + 1];
1422 * search for the new cache item in the cache list by hostname.
1423 * If found, move the entry to the top of the list and return.
1425 ++cainfo.ca_updates;
1427 for (cpp = &cacheTop; *cpp; cpp = &((*cpp)->list_next)) {
1433 *cpp = cp->list_next;
1434 cp->list_next = cacheTop;
1441 * Compare the cache entry against the new record. Add any
1442 * previously missing names for this entry.
1446 for (i = 0, s = request->he.h.h_name; s; s = request->he.h.h_aliases[i++]) {
1447 for (j = 0, t = cp->he.h.h_name; t; t = cp->he.h.h_aliases[j++]) {
1448 if (0 == ircd_strcmp(t, s))
1457 * Do the same again for IP#'s.
1461 for (i = 0; (s = request->he.h.h_addr_list[i]); i++) {
1462 for (j = 0; (t = cp->he.h.h_addr_list[j]); j++) {
1463 if (!memcmp(t, s, sizeof(struct in_addr)))
1471 if (*addrs || *aliases)
1472 update_hostent(&cp->he, addrs, aliases);
1476 * find_cache_name - find name in nameserver cache
1478 static struct CacheEntry* find_cache_name(const char* name)
1480 struct CacheEntry* cp;
1486 hashv = hash_name(name);
1488 cp = hashtable[hashv].name_list;
1490 for (; cp; cp = cp->hname_next) {
1491 for (i = 0, s = cp->he.h.h_name; s; s = cp->he.h.h_aliases[i++]) {
1492 if (0 == ircd_strcmp(s, name)) {
1493 ++cainfo.ca_na_hits;
1499 for (cp = cacheTop; cp; cp = cp->list_next) {
1501 * if no aliases or the hash value matches, we've already
1502 * done this entry and all possiblilities concerning it.
1504 if (!cp->he.h.h_name || hashv == hash_name(cp->he.h.h_name))
1506 for (i = 0, s = cp->he.h.h_aliases[i]; s; s = cp->he.h.h_aliases[++i]) {
1507 if (0 == ircd_strcmp(name, s)) {
1508 ++cainfo.ca_na_hits;
1517 * find_cache_number - find a cache entry by ip# and update its expire time
1519 static struct CacheEntry* find_cache_number(struct ResRequest* request,
1522 struct CacheEntry* cp;
1527 hashv = hash_number((const unsigned char*) addr);
1528 cp = hashtable[hashv].num_list;
1530 for (; cp; cp = cp->hnum_next) {
1531 for (i = 0; cp->he.h.h_addr_list[i]; ++i) {
1532 if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1533 ++cainfo.ca_nu_hits;
1538 for (cp = cacheTop; cp; cp = cp->list_next) {
1540 * single address entry...would have been done by hashed
1542 * if the first IP# has the same hashnumber as the IP# we
1543 * are looking for, its been done already.
1545 if (!cp->he.h.h_addr_list[1] ||
1546 hashv == hash_number((const unsigned char*) cp->he.h.h_addr_list[0]))
1548 for (i = 1; cp->he.h.h_addr_list[i]; ++i) {
1549 if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1550 ++cainfo.ca_nu_hits;
1558 static struct CacheEntry* make_cache(struct ResRequest* request)
1560 struct CacheEntry* cp;
1563 assert(0 != request);
1565 hp = &request->he.h;
1567 * shouldn't happen but it just might...
1569 assert(0 != hp->h_name);
1570 assert(0 != hp->h_addr_list[0]);
1571 if (!hp->h_name || !hp->h_addr_list[0])
1574 * Make cache entry. First check to see if the cache already exists
1575 * and if so, return a pointer to it.
1577 for (i = 0; hp->h_addr_list[i]; ++i) {
1578 if ((cp = find_cache_number(request, hp->h_addr_list[i]))) {
1579 update_list(request, cp);
1584 * a matching entry wasnt found in the cache so go and make one up.
1586 cp = (struct CacheEntry*) MyMalloc(sizeof(struct CacheEntry));
1589 memset(cp, 0, sizeof(struct CacheEntry));
1590 dup_hostent(&cp->he, hp);
1591 cp->reply.hp = &cp->he.h;
1593 * hmmm... we could time out the cache after 10 minutes regardless
1594 * would that be reasonable since we don't save the reply?
1596 if (request->ttl < AR_TTL) {
1597 ++reinfo.re_shortttl;
1601 cp->ttl = request->ttl;
1602 cp->expireat = CurrentTime + cp->ttl;
1603 return add_to_cache(cp);
1607 * rem_cache - delete a cache entry from the cache structures
1608 * and lists and return all memory used for the cache back to the memory pool.
1610 static void rem_cache(struct CacheEntry* ocp)
1612 struct CacheEntry** cp;
1618 if (0 < ocp->reply.ref_count) {
1619 if (ocp->expireat < CurrentTime) {
1620 ocp->expireat = CurrentTime + AR_TTL;
1621 Debug((DEBUG_DNS, "Resolver: referenced cache entry not removed for: %s",
1627 * remove cache entry from linked list
1629 for (cp = &cacheTop; *cp; cp = &((*cp)->list_next)) {
1631 *cp = ocp->list_next;
1637 * remove cache entry from hashed name list
1639 assert(0 != hp->h_name);
1640 hashv = hash_name(hp->h_name);
1642 for (cp = &hashtable[hashv].name_list; *cp; cp = &((*cp)->hname_next)) {
1644 *cp = ocp->hname_next;
1649 * remove cache entry from hashed number list
1651 hashv = hash_number((const unsigned char*) hp->h_addr);
1654 for (cp = &hashtable[hashv].num_list; *cp; cp = &((*cp)->hnum_next)) {
1656 *cp = ocp->hnum_next;
1661 * free memory used to hold the various host names and the array
1662 * of alias pointers.
1664 MyFree(ocp->he.buf);
1670 void flush_resolver_cache(void)
1673 * stubbed - iterate cache and remove everything that isn't referenced
1678 * m_dns - dns status query
1680 int m_dns(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1682 #if !defined(NDEBUG)
1683 struct CacheEntry* cp;
1687 if (parv[1] && *parv[1] == 'l') {
1688 for(cp = cacheTop; cp; cp = cp->list_next) {
1690 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :Ex %d ttl %d host %s(%s)",
1691 sptr, cp->expireat - CurrentTime, cp->ttl,
1692 hp->h_name, ircd_ntoa(hp->h_addr));
1693 for (i = 0; hp->h_aliases[i]; i++)
1694 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C : %s = %s (CN)", sptr,
1695 hp->h_name, hp->h_aliases[i]);
1696 for (i = 1; hp->h_addr_list[i]; i++)
1697 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C : %s = %s (IP)", sptr,
1698 hp->h_name, ircd_ntoa(hp->h_addr_list[i]));
1702 if (parv[1] && *parv[1] == 'd') {
1703 sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :ResolverFileDescriptor = %d",
1704 sptr, ResolverFileDescriptor);
1707 sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ca %d Cd %d Ce %d Cl %d Ch %d:%d "
1709 cainfo.ca_adds, cainfo.ca_dels, cainfo.ca_expires,
1710 cainfo.ca_lookups, cainfo.ca_na_hits, cainfo.ca_nu_hits,
1713 sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Re %d Rl %d/%d Rp %d Rq %d",
1714 sptr, reinfo.re_errors, reinfo.re_nu_look,
1715 reinfo.re_na_look, reinfo.re_replies, reinfo.re_requests);
1716 sendcmdto_one(&me, CMD_NOTICE, sptr,"%C :Ru %d Rsh %d Rs %d(%d) Rt %d", sptr,
1717 reinfo.re_unkrep, reinfo.re_shortttl, reinfo.re_sent,
1718 reinfo.re_resends, reinfo.re_timeouts);
1723 size_t cres_mem(struct Client* sptr)
1725 struct CacheEntry* entry;
1726 struct ResRequest* request;
1727 size_t cache_mem = 0;
1728 size_t request_mem = 0;
1729 int cache_count = 0;
1730 int request_count = 0;
1732 for (entry = cacheTop; entry; entry = entry->list_next) {
1733 cache_mem += sizeof(struct CacheEntry);
1734 cache_mem += calc_hostent_buffer_size(&entry->he.h);
1737 for (request = requestListHead; request; request = request->next) {
1738 request_mem += sizeof(struct ResRequest);
1740 request_mem += strlen(request->name) + 1;
1741 if (request->he.buf)
1742 request_mem += MAXGETHOSTLEN + 1;
1746 if (cachedCount != cache_count) {
1747 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1748 ":Resolver: cache count mismatch: %d != %d", cachedCount,
1750 assert(cachedCount == cache_count);
1752 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
1753 ":Resolver: cache %d(%d) requests %d(%d)", cache_count,
1754 cache_mem, request_count, request_mem);
1755 return cache_mem + request_mem;