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_string.h"
25 #include "sprintf_irc.h"
35 #include <sys/socket.h>
39 #include <arpa/nameser.h>
42 #include <arpa/inet.h>
46 #error this code needs to be able to address individual octets
50 * Some systems do not define INADDR_NONE (255.255.255.255)
51 * INADDR_NONE is actually a valid address, but it should never
52 * be returned from any nameserver.
53 * NOTE: The bit pattern for INADDR_NONE and INADDR_ANY (0.0.0.0) should be
54 * the same on all hosts so we shouldn't need to use htonl or ntohl to
55 * compare or set the values.
58 #define INADDR_NONE ((unsigned int) 0xffffffff)
61 #define MAXPACKET 1024 /* rfc sez 512 but we expand names so ... */
62 #define RES_MAXALIASES 35 /* maximum aliases allowed */
63 #define RES_MAXADDRS 35 /* maximum addresses allowed */
65 * OSF1 doesn't have RES_NOALIASES
68 #define RES_NOALIASES 0
72 * macros used to calulate offsets into fixed query buffer
74 #define ALIAS_BLEN ((RES_MAXALIASES + 1) * sizeof(char*))
75 #define ADDRS_BLEN ((RES_MAXADDRS + 1) * sizeof(struct in_addr*))
77 #define ADDRS_OFFSET (ALIAS_BLEN + ADDRS_BLEN)
78 #define ADDRS_DLEN (RES_MAXADDRS * sizeof(struct in_addr))
79 #define NAMES_OFFSET (ADDRS_OFFSET + ADDRS_DLEN)
80 #define MAXGETHOSTLEN (NAMES_OFFSET + MAXPACKET)
82 #define AR_TTL 600 /* TTL in seconds for dns cache entries */
85 * the following values should be prime
87 #define ARES_CACSIZE 307
91 * RFC 1104/1105 wasn't very helpful about what these fields
92 * should be named, so for now, we'll just name them this way.
93 * we probably should look at what named calls them or something.
98 #define RDLENGTH_SIZE 2
99 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
102 * Building the Hostent
103 * The Hostent struct is arranged like this:
104 * +-------------------------------+
105 * Hostent: | struct hostent h |
106 * |-------------------------------|
108 * +-------------------------------+
112 * +-------------------------------+
113 * buf: | h_aliases pointer array | Max size: ALIAS_BLEN;
114 * | NULL | contains `char *'s
115 * |-------------------------------|
116 * | h_addr_list pointer array | Max size: ADDRS_BLEN;
117 * | NULL | contains `struct in_addr *'s
118 * |-------------------------------|
119 * | h_addr_list addresses | Max size: ADDRS_DLEN;
120 * | | contains `struct in_addr's
121 * |-------------------------------|
122 * | storage for hostname strings | Max size: ALIAS_DLEN;
123 * +-------------------------------+ contains `char's
125 * For requests the size of the h_aliases, and h_addr_list pointer
126 * array sizes are set to MAXALISES and MAXADDRS respectively, and
127 * buf is a fixed size with enough space to hold the largest expected
128 * reply from a nameserver, see RFC 1034 and RFC 1035.
129 * For cached entries the sizes are dependent on the actual number
130 * of aliases and addresses. If new aliases and addresses are found
131 * for cached entries, the buffer is grown and the new entries are added.
132 * The hostent struct is filled in with the addresses of the entries in
133 * the Hostent buf as follows:
134 * h_name - contains a pointer to the start of the hostname string area,
135 * or NULL if none is set. The h_name is followed by the
136 * aliases, in the storage for hostname strings area.
137 * h_aliases - contains a pointer to the start of h_aliases pointer array.
138 * This array contains pointers to the storage for hostname
139 * strings area and is terminated with a NULL. The first alias
140 * is stored directly after the h_name.
141 * h_addr_list - contains a pointer to the start of h_addr_list pointer array.
142 * This array contains pointers to in_addr structures in the
143 * h_addr_list addresses area and is terminated with a NULL.
145 * Filling the buffer this way allows for proper alignment of the h_addr_list
148 * This arrangement allows us to alias a Hostent struct pointer as a
149 * real struct hostent* without lying. It also allows us to change the
150 * values contained in the cached entries and requests without changing
151 * the actual hostent pointer, which is saved in a client struct and can't
152 * be changed without blowing things up or a lot more fiddling around.
153 * It also allows for defered allocation of the fixed size buffers until
154 * they are really needed.
155 * Nov. 17, 1997 --Bleep
158 typedef struct Hostent {
159 struct hostent h; /* the hostent struct we are passing around */
160 char* buf; /* buffer for data pointed to from hostent */
164 struct ResRequest* next;
166 int sent; /* number of requests sent */
169 char retries; /* retry counter */
170 char sends; /* number of sends (>1 means resent) */
171 char resend; /* send flag. 0 == dont resend */
176 struct DNSQuery query; /* query callback for this request */
181 struct CacheEntry* hname_next;
182 struct CacheEntry* hnum_next;
183 struct CacheEntry* list_next;
187 struct DNSReply reply;
191 struct CacheEntry* num_list;
192 struct CacheEntry* name_list;
196 int ResolverFileDescriptor = -1; /* GLOBAL - used in s_bsd.c */
198 static time_t nextDNSCheck = 0;
199 static time_t nextCacheExpire = 1;
202 * Keep a spare file descriptor open. res_init calls fopen to read the
203 * resolv.conf file. If ircd is hogging all the file descriptors below 256,
204 * on systems with crippled FILE structures this will cause wierd bugs.
205 * This is definitely needed for Solaris which uses an unsigned char to
206 * hold the file descriptor. --Dianora
208 static int spare_fd = -1;
210 static int cachedCount = 0;
211 static struct CacheTable hashtable[ARES_CACSIZE];
212 static struct CacheEntry* cacheTop;
213 static struct ResRequest* requestListHead; /* head of resolver request list */
214 static struct ResRequest* requestListTail; /* tail of resolver request list */
217 static void add_request(struct ResRequest* request);
218 static void rem_request(struct ResRequest* request);
219 static struct ResRequest* make_request(const struct DNSQuery* query);
220 static void rem_cache(struct CacheEntry*);
221 static void do_query_name(const struct DNSQuery* query,
223 struct ResRequest* request);
224 static void do_query_number(const struct DNSQuery* query,
225 const struct in_addr*,
226 struct ResRequest* request);
227 static void query_name(const char* name,
230 struct ResRequest* request);
231 static void resend_query(struct ResRequest* request);
232 static struct CacheEntry* make_cache(struct ResRequest* request);
233 static struct CacheEntry* find_cache_name(const char* name);
234 static struct CacheEntry* find_cache_number(struct ResRequest* request,
236 static struct ResRequest* find_id(int);
238 static struct cacheinfo {
248 static struct resinfo {
263 * From bind 8.3, these aren't declared in earlier versions of bind
265 extern u_short _getshort(const u_char *);
266 extern u_int _getlong(const u_char *);
269 * res_isourserver(ina)
270 * looks up "ina" in _res.ns_addr_list[]
275 * paul vixie, 29may94
278 res_ourserver(const struct __res_state* statp, const struct sockaddr_in *inp)
280 struct sockaddr_in ina;
284 for (ns = 0; ns < statp->nscount; ns++) {
285 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
287 if (srv->sin_family == ina.sin_family &&
288 srv->sin_port == ina.sin_port &&
289 (srv->sin_addr.s_addr == INADDR_ANY ||
290 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
297 * start_resolver - do everything we need to read the resolv.conf file
298 * and initialize the resolver file descriptor if needed
300 static void start_resolver(void)
302 Debug((DEBUG_DNS, "Resolver: start_resolver"));
304 * close the spare file descriptor so res_init can read resolv.conf
305 * successfully. Needed on Solaris
310 res_init(); /* res_init always returns 0 */
312 * make sure we have a valid file descriptor below 256 so we can
313 * do this again. Needed on Solaris
315 spare_fd = open("/dev/null",O_RDONLY,0);
316 if ((spare_fd < 0) || (spare_fd > 255)) {
318 sprintf_irc(sparemsg, "invalid spare_fd %d", spare_fd);
319 server_restart(sparemsg);
324 _res.nsaddr_list[0].sin_addr.s_addr = inet_addr("127.0.0.1");
326 _res.options |= RES_NOALIASES;
328 if (ResolverFileDescriptor < 0) {
329 ResolverFileDescriptor = socket(AF_INET, SOCK_DGRAM, 0);
330 if (-1 == ResolverFileDescriptor) {
331 report_error("Resolver: error creating socket for %s: %s",
335 if (!os_set_nonblocking(ResolverFileDescriptor))
336 report_error("Resolver: error setting non-blocking for %s: %s",
342 * init_resolver - initialize resolver and resolver library
344 int init_resolver(void)
346 Debug((DEBUG_DNS, "Resolver: init_resolver"));
348 srand48(CurrentTime);
350 memset(&cainfo, 0, sizeof(cainfo));
351 memset(hashtable, 0, sizeof(hashtable));
352 memset(&reinfo, 0, sizeof(reinfo));
354 requestListHead = requestListTail = NULL;
358 Debug((DEBUG_DNS, "Resolver: fd %d errno: %d h_errno: %d: %s",
359 ResolverFileDescriptor, errno, h_errno, strerror(errno)));
360 return ResolverFileDescriptor;
364 * restart_resolver - flush the cache, reread resolv.conf, reopen socket
366 void restart_resolver(void)
368 /* flush_cache(); flush the dns cache */
373 * add_local_domain - Add the domain to hostname, if it is missing
374 * (as suggested by eps@TOASTER.SFSU.EDU)
376 void add_local_domain(char* hname, unsigned int size)
380 * try to fix up unqualified names
382 if ((_res.options & RES_DEFNAMES) && !strchr(hname, '.')) {
383 if (_res.defdname[0]) {
384 unsigned len = strlen(hname);
385 if ((strlen(_res.defdname) + len + 2) < size) {
387 strcpy(hname + len, _res.defdname);
394 * add_request - place a new request in the request list
396 static void add_request(struct ResRequest* request)
398 assert(0 != request);
399 if (!requestListHead)
400 requestListHead = requestListTail = request;
402 requestListTail->next = request;
403 requestListTail = request;
405 request->next = NULL;
406 ++reinfo.re_requests;
410 * rem_request - remove a request from the list.
411 * This must also free any memory that has been allocated for
412 * temporary storage of DNS results.
414 static void rem_request(struct ResRequest* request)
416 struct ResRequest** current;
417 struct ResRequest* prev = NULL;
419 assert(0 != request);
420 for (current = &requestListHead; *current; ) {
421 if (*current == request) {
422 *current = request->next;
423 if (requestListTail == request)
424 requestListTail = prev;
428 current = &(*current)->next;
430 MyFree(request->he.buf);
431 MyFree(request->name);
436 * make_request - Create a DNS request record for the server.
438 static struct ResRequest* make_request(const struct DNSQuery* query)
440 struct ResRequest* request;
442 request = (struct ResRequest*) MyMalloc(sizeof(struct ResRequest));
443 memset(request, 0, sizeof(struct ResRequest));
445 request->sentat = CurrentTime;
446 request->retries = 3;
448 request->timeout = 5; /* start at 5 per RFC1123 */
449 request->addr.s_addr = INADDR_NONE;
450 request->he.h.h_addrtype = AF_INET;
451 request->he.h.h_length = sizeof(struct in_addr);
452 request->query.vptr = query->vptr;
453 request->query.callback = query->callback;
455 #if defined(NULL_POINTER_NOT_ZERO)
456 request->next = NULL;
457 request->he.buf = NULL;
458 request->he.h.h_name = NULL;
459 request->he.h.h_aliases = NULL;
460 request->he.h.h_addr_list = NULL;
462 add_request(request);
467 * timeout_query_list - Remove queries from the list which have been
468 * there too long without being resolved.
470 static time_t timeout_query_list(time_t now)
472 struct ResRequest* request;
473 struct ResRequest* next_request = 0;
474 time_t next_time = 0;
477 Debug((DEBUG_DNS, "Resolver: timeout_query_list at %s", myctime(now)));
478 for (request = requestListHead; request; request = next_request) {
479 next_request = request->next;
480 timeout = request->sentat + request->timeout;
482 if (--request->retries <= 0) {
483 ++reinfo.re_timeouts;
484 (*request->query.callback)(request->query.vptr, 0);
485 rem_request(request);
489 request->sentat = now;
490 request->timeout += request->timeout;
491 resend_query(request);
494 if (!next_time || timeout < next_time) {
498 return (next_time > now) ? next_time : (now + AR_TTL);
502 * expire_cache - removes entries from the cache which are older
503 * than their expiry times. returns the time at which the server
504 * should next poll the cache.
506 static time_t expire_cache(time_t now)
508 struct CacheEntry* cp;
509 struct CacheEntry* cp_next;
512 Debug((DEBUG_DNS, "Resolver: expire_cache at %s", myctime(now)));
513 for (cp = cacheTop; cp; cp = cp_next) {
514 cp_next = cp->list_next;
515 if (cp->expireat < now) {
519 else if (!expire || expire > cp->expireat)
520 expire = cp->expireat;
522 return (expire > now) ? expire : (now + AR_TTL);
526 * timeout_resolver - check request list and cache for expired entries
528 time_t timeout_resolver(time_t now)
530 if (nextDNSCheck < now)
531 nextDNSCheck = timeout_query_list(now);
532 if (nextCacheExpire < now)
533 nextCacheExpire = expire_cache(now);
534 return IRCD_MIN(nextDNSCheck, nextCacheExpire);
539 * delete_resolver_queries - cleanup outstanding queries
540 * for which there no longer exist clients or conf lines.
542 void delete_resolver_queries(const void* vptr)
544 struct ResRequest* request;
545 struct ResRequest* next_request;
547 for (request = requestListHead; request; request = next_request) {
548 next_request = request->next;
549 if (vptr == request->query.vptr)
550 rem_request(request);
555 * send_res_msg - sends msg to all nameservers found in the "_res" structure.
556 * This should reflect /etc/resolv.conf. We will get responses
557 * which arent needed but is easier than checking to see if nameserver
558 * isnt present. Returns number of messages successfully sent to
559 * nameservers or -1 if no successful sends.
561 static int send_res_msg(const u_char* msg, int len, int rcount)
565 int max_queries = IRCD_MIN(_res.nscount, rcount);
569 * RES_PRIMARY option is not implemented
570 * if (_res.options & RES_PRIMARY || 0 == max_queries)
572 if (0 == max_queries)
575 Debug((DEBUG_DNS, "Resolver: sendto %d", max_queries));
577 for (i = 0; i < max_queries; i++) {
578 if (sendto(ResolverFileDescriptor, msg, len, 0,
579 (struct sockaddr*) &(_res.nsaddr_list[i]),
580 sizeof(struct sockaddr_in)) == len) {
585 ircd_log(L_ERROR, "Resolver: send failed %s", strerror(errno));
591 * find_id - find a dns request id (id is determined by dn_mkquery)
593 static struct ResRequest* find_id(int id)
595 struct ResRequest* request;
597 for (request = requestListHead; request; request = request->next) {
598 if (request->id == id)
605 * gethost_byname - get host address from name
607 struct DNSReply* gethost_byname(const char* name,
608 const struct DNSQuery* query)
610 struct CacheEntry* cp;
613 Debug((DEBUG_DNS, "Resolver: gethost_byname %s", name));
615 if ((cp = find_cache_name(name)))
618 do_query_name(query, name, NULL);
624 * gethost_byaddr - get host name from address
626 struct DNSReply* gethost_byaddr(const char* addr,
627 const struct DNSQuery* query)
629 struct CacheEntry *cp;
633 Debug((DEBUG_DNS, "Resolver: gethost_byaddr %s", ircd_ntoa(addr)));
636 if ((cp = find_cache_number(NULL, addr)))
639 do_query_number(query, (const struct in_addr*) addr, NULL);
645 * do_query_name - nameserver lookup name
647 static void do_query_name(const struct DNSQuery* query,
648 const char* name, struct ResRequest* request)
650 char hname[HOSTLEN + 1];
653 ircd_strncpy(hname, name, HOSTLEN);
654 hname[HOSTLEN] = '\0';
657 * removed, this is incorrect for anything it's used for
659 add_local_domain(hname, HOSTLEN);
663 request = make_request(query);
665 request->name = (char*) MyMalloc(strlen(hname) + 1);
666 strcpy(request->name, hname);
668 query_name(hname, C_IN, T_A, request);
672 * do_query_number - Use this to do reverse IP# lookups.
674 static void do_query_number(const struct DNSQuery* query,
675 const struct in_addr* addr,
676 struct ResRequest* request)
679 const unsigned char* cp;
682 cp = (const unsigned char*) &addr->s_addr;
683 sprintf_irc(ipbuf, "%u.%u.%u.%u.in-addr.arpa.",
684 (unsigned int)(cp[3]), (unsigned int)(cp[2]),
685 (unsigned int)(cp[1]), (unsigned int)(cp[0]));
688 request = make_request(query);
689 request->type = T_PTR;
690 request->addr.s_addr = addr->s_addr;
692 query_name(ipbuf, C_IN, T_PTR, request);
696 * query_name - generate a query based on class, type and name.
698 static void query_name(const char* name, int query_class,
699 int type, struct ResRequest* request)
705 assert(0 != request);
707 Debug((DEBUG_DNS, "Resolver: query_name: %s %d %d", name, query_class, type));
708 memset(buf, 0, sizeof(buf));
709 if ((request_len = res_mkquery(QUERY, name, query_class, type,
710 NULL, 0, NULL, buf, sizeof(buf))) > 0) {
711 HEADER* header = (HEADER*) buf;
717 * generate a unique id
718 * NOTE: we don't have to worry about converting this to and from
719 * network byte order, the nameserver does not interpret this value
720 * and returns it unchanged
724 header->id = (header->id + lrand48()) & 0xffff;
725 } while (find_id(header->id));
727 gettimeofday(&tv, NULL);
729 header->id = (header->id + k + tv.tv_usec) & 0xffff;
731 } while (find_id(header->id));
733 request->id = header->id;
735 Debug((DEBUG_DNS, "Resolver: query_name %d: %s %d %d", request->id,
736 name, query_class, type));
737 request->sent += send_res_msg(buf, request_len, request->sends);
741 static void resend_query(struct ResRequest* request)
743 assert(0 != request);
745 if (request->resend == 0)
748 switch(request->type) {
750 do_query_number(NULL, &request->addr, request);
753 do_query_name(NULL, request->name, request);
761 * proc_answer - process name server reply
762 * build a hostent struct in the passed request
764 static int proc_answer(struct ResRequest* request, HEADER* header,
765 u_char* buf, u_char* eob)
767 char hostbuf[HOSTLEN + 1]; /* working buffer */
768 u_char* current; /* current position in buf */
769 char** alias; /* alias list */
770 char** addr; /* address list */
771 char* name; /* pointer to name string */
772 char* address; /* pointer to address */
773 char* endp; /* end of our buffer */
774 int query_class; /* answer class */
775 int type; /* answer type */
776 int rd_length; /* record data length */
777 int answer_count = 0; /* answer counter */
778 int n; /* temp count */
779 int addr_count = 0; /* number of addresses in hostent */
780 int alias_count = 0; /* number of aliases in hostent */
781 struct hostent* hp; /* hostent getting filled */
783 assert(0 != request);
788 current = buf + sizeof(HEADER);
789 hp = &(request->he.h);
791 * lazy allocation of request->he.buf, we don't allocate a buffer
792 * unless there is something to put in it.
794 if (!request->he.buf) {
795 request->he.buf = (char*) MyMalloc(MAXGETHOSTLEN + 1);
796 request->he.buf[MAXGETHOSTLEN] = '\0';
798 * array of alias list pointers starts at beginning of buf
800 hp->h_aliases = (char**) request->he.buf;
801 hp->h_aliases[0] = NULL;
803 * array of address list pointers starts after alias list pointers
804 * the actual addresses follow the the address list pointers
806 hp->h_addr_list = (char**)(request->he.buf + ALIAS_BLEN);
808 * don't copy the host address to the beginning of h_addr_list
810 hp->h_addr_list[0] = NULL;
812 endp = request->he.buf + MAXGETHOSTLEN;
814 * find the end of the address list
816 addr = hp->h_addr_list;
822 * make address point to first available address slot
824 address = request->he.buf + ADDRS_OFFSET +
825 (sizeof(struct in_addr) * addr_count);
827 * find the end of the alias list
829 alias = hp->h_aliases;
835 * make name point to first available space in request->buf
837 if (alias_count > 0) {
838 name = hp->h_aliases[alias_count - 1];
839 name += (strlen(name) + 1);
842 name = hp->h_name + strlen(hp->h_name) + 1;
844 name = request->he.buf + ADDRS_OFFSET + ADDRS_DLEN;
849 while (header->qdcount-- > 0) {
850 if ((n = dn_skipname(current, eob)) < 0)
852 current += (n + QFIXEDSZ);
855 * process each answer sent to us blech.
857 while (header->ancount-- > 0 && current < eob && name < endp) {
858 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
861 * no more answers left
865 hostbuf[HOSTLEN] = '\0';
867 * With Address arithmetic you have to be very anal
868 * this code was not working on alpha due to that
869 * (spotted by rodder/jailbird/dianora)
871 current += (size_t) n;
873 if (!((current + ANSWER_FIXED_SIZE) < eob))
876 type = _getshort(current);
877 current += TYPE_SIZE;
879 query_class = _getshort(current);
880 current += CLASS_SIZE;
882 request->ttl = _getlong(current);
885 rd_length = _getshort(current);
886 current += RDLENGTH_SIZE;
889 * Wait to set request->type until we verify this structure
892 add_local_domain(hostbuf, HOSTLEN);
898 * check for invalid rd_length or too many addresses
900 if (rd_length != sizeof(struct in_addr))
902 if (++addr_count < RES_MAXADDRS) {
903 if (answer_count == 1)
904 hp->h_addrtype = (query_class == C_IN) ? AF_INET : AF_UNSPEC;
906 memcpy(address, current, sizeof(struct in_addr));
909 address += sizeof(struct in_addr);
912 strcpy(name, hostbuf);
914 name += strlen(name) + 1;
916 Debug((DEBUG_DNS, "Resolver: A %s for %s",
917 ircd_ntoa((char*) hp->h_addr_list[addr_count - 1]), hostbuf));
919 current += rd_length;
923 n = dn_expand(buf, eob, current, hostbuf, sizeof(hostbuf));
932 * no more answers left
937 * This comment is based on analysis by Shadowfax, Wohali and johan,
938 * not me. (Dianora) I am only commenting it.
940 * dn_expand is guaranteed to not return more than sizeof(hostbuf)
941 * but do all implementations of dn_expand also guarantee
942 * buffer is terminated with null byte? Lets not take chances.
945 hostbuf[HOSTLEN] = '\0';
946 current += (size_t) n;
948 Debug((DEBUG_DNS, "Resolver: PTR %s", hostbuf));
950 * copy the returned hostname into the host name
951 * ignore duplicate ptr records
954 strcpy(name, hostbuf);
956 name += strlen(name) + 1;
961 Debug((DEBUG_DNS, "Resolver: CNAME %s", hostbuf));
962 if (++alias_count < RES_MAXALIASES) {
963 ircd_strncpy(name, hostbuf, endp - name);
966 name += strlen(name) + 1;
968 current += rd_length;
972 Debug((DEBUG_DNS,"Resolver: proc_answer type: %d for: %s", type, hostbuf));
980 * resolver_read - read a dns reply from the nameserver and process it.
981 * return 0 if nothing was read from the socket, otherwise return 1
983 int resolver_read(void)
985 u_char buf[sizeof(HEADER) + MAXPACKET];
987 struct ResRequest* request = 0;
988 struct CacheEntry* cp = 0;
990 int answer_count = 0;
991 struct sockaddr_in sin;
993 Debug((DEBUG_DNS, "Resolver: read"));
994 if (IO_SUCCESS != os_recvfrom_nonb(ResolverFileDescriptor,
995 buf, sizeof(buf), &rc, &sin)) {
998 if (rc < sizeof(HEADER)) {
999 Debug((DEBUG_DNS, "Resolver: short reply %d: %s", rc, strerror(errno)));
1003 * convert DNS reply reader from Network byte order to CPU byte order.
1005 header = (HEADER*) buf;
1006 /* header->id = ntohs(header->id); */
1007 header->ancount = ntohs(header->ancount);
1008 header->qdcount = ntohs(header->qdcount);
1009 header->nscount = ntohs(header->nscount);
1010 header->arcount = ntohs(header->arcount);
1011 ++reinfo.re_replies;
1013 * response for an id which we have already received an answer for
1014 * just ignore this response.
1016 if (0 == (request = find_id(header->id))) {
1017 Debug((DEBUG_DNS, "Resolver: can't find request id: %d", header->id));
1021 * check against possibly fake replies
1023 if (!res_ourserver(&_res, &sin)) {
1024 Debug((DEBUG_DNS, "Resolver: fake reply from: %s",
1025 (const char*) &sin.sin_addr));
1030 if ((header->rcode != NOERROR) || (header->ancount == 0)) {
1032 if (SERVFAIL == header->rcode)
1033 resend_query(request);
1036 * If a bad error was returned, we stop here and dont send
1037 * send any more (no retries granted).
1038 * Isomer: Perhaps we should return these error messages back to
1042 switch (header->rcode) {
1044 Debug((DEBUG_DNS, "Fatal DNS error: No Error"));
1047 Debug((DEBUG_DNS, "Fatal DNS error: Format Error"));
1050 Debug((DEBUG_DNS, "Fatal DNS error: Server Failure"));
1053 Debug((DEBUG_DNS, "DNS error: Non Existant Domain"));
1056 Debug((DEBUG_DNS, "Fatal DNS error: Not Implemented"));
1059 Debug((DEBUG_DNS, "Fatal DNS error: Query Refused"));
1062 Debug((DEBUG_DNS, "Unassigned fatal DNS error: %i", header->rcode));
1065 #endif /* DEBUGMODE */
1066 (*request->query.callback)(request->query.vptr, 0);
1067 rem_request(request);
1072 * If this fails there was an error decoding the received packet,
1073 * try it again and hope it works the next time.
1075 answer_count = proc_answer(request, header, buf, buf + rc);
1077 if (T_PTR == request->type) {
1078 struct DNSReply* reply = NULL;
1079 if (0 == request->he.h.h_name) {
1081 * got a PTR response with no name, something bogus is happening
1082 * don't bother trying again, the client address doesn't resolve
1084 (*request->query.callback)(request->query.vptr, reply);
1085 rem_request(request);
1088 Debug((DEBUG_DNS, "relookup %s <-> %s",
1089 request->he.h.h_name, ircd_ntoa((char*) &request->addr)));
1091 * Lookup the 'authoritive' name that we were given for the
1092 * ip#. By using this call rather than regenerating the
1093 * type we automatically gain the use of the cache with no
1096 reply = gethost_byname(request->he.h.h_name, &request->query);
1099 * If name wasn't found, a request has been queued and it will
1100 * be the last one queued. This is rather nasty way to keep
1101 * a host alias with the query. -avalon
1103 MyFree(requestListTail->he.buf);
1104 requestListTail->he.buf = request->he.buf;
1105 request->he.buf = 0;
1106 memcpy(&requestListTail->he.h, &request->he.h, sizeof(struct hostent));
1109 (*request->query.callback)(request->query.vptr, reply);
1110 rem_request(request);
1114 * got a name and address response, client resolved
1115 * XXX - Bug found here by Dianora -
1116 * make_cache() occasionally returns a NULL pointer when a
1117 * PTR returned a CNAME, cp was not checked before so the
1118 * callback was being called with a value of 0x2C != NULL.
1120 cp = make_cache(request);
1121 (*request->query.callback)(request->query.vptr,
1122 (cp) ? &cp->reply : 0);
1123 rem_request(request);
1126 else if (!request->sent) {
1128 * XXX - we got a response for a query we didn't send with a valid id?
1129 * this should never happen, bail here and leave the client unresolved
1131 (*request->query.callback)(request->query.vptr, 0);
1132 rem_request(request);
1138 * resolver_read_multiple - process up to count reads
1140 void resolver_read_multiple(int count)
1143 for ( ; i < count; ++i) {
1144 if (0 == resolver_read())
1149 static size_t calc_hostent_buffer_size(const struct hostent* hp)
1158 count += (strlen(hp->h_name) + 1);
1162 for (p = hp->h_aliases; *p; ++p)
1163 count += (strlen(*p) + 1 + sizeof(char*));
1165 * space for addresses
1167 for (p = hp->h_addr_list; *p; ++p)
1168 count += (hp->h_length + sizeof(char*));
1170 * space for 2 nulls to terminate h_aliases and h_addr_list
1172 count += (2 * sizeof(char*));
1178 * dup_hostent - Duplicate a hostent struct, allocate only enough memory for
1179 * the data we're putting in it.
1181 static void dup_hostent(aHostent* new_hp, struct hostent* hp)
1186 int alias_count = 0;
1188 size_t bytes_needed = 0;
1190 assert(0 != new_hp);
1193 /* how much buffer do we need? */
1194 bytes_needed += (strlen(hp->h_name) + 1);
1198 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1201 pp = hp->h_addr_list;
1203 bytes_needed += (hp->h_length + sizeof(char*));
1206 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1207 bytes_needed += (2 * sizeof(char*));
1209 /* Allocate memory */
1210 new_hp->buf = (char*) MyMalloc(bytes_needed);
1212 new_hp->h.h_addrtype = hp->h_addrtype;
1213 new_hp->h.h_length = hp->h_length;
1215 /* first write the address list */
1216 pp = hp->h_addr_list;
1217 ap = new_hp->h.h_addr_list =
1218 (char**)(new_hp->buf + ((alias_count + 1) * sizeof(char*)));
1219 p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1223 memcpy(p, *pp++, hp->h_length);
1227 /* next write the name */
1228 new_hp->h.h_name = p;
1229 strcpy(p, hp->h_name);
1230 p += (strlen(p) + 1);
1232 /* last write the alias list */
1234 ap = new_hp->h.h_aliases = (char**) new_hp->buf;
1238 p += (strlen(p) + 1);
1244 * update_hostent - Add records to a Hostent struct in place.
1246 static void update_hostent(aHostent* hp, char** addr, char** alias)
1251 int alias_count = 0;
1254 size_t bytes_needed = 0;
1256 if (!hp || !hp->buf)
1259 /* how much buffer do we need? */
1260 bytes_needed = strlen(hp->h.h_name) + 1;
1261 pp = hp->h.h_aliases;
1263 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1269 bytes_needed += (strlen(*pp++) + 1 + sizeof(char*));
1273 pp = hp->h.h_addr_list;
1275 bytes_needed += (hp->h.h_length + sizeof(char*));
1281 bytes_needed += (hp->h.h_length + sizeof(char*));
1285 /* Reserve space for 2 nulls to terminate h_aliases and h_addr_list */
1286 bytes_needed += 2 * sizeof(char*);
1288 /* Allocate memory */
1289 buf = (char*) MyMalloc(bytes_needed);
1292 /* first write the address list */
1293 pp = hp->h.h_addr_list;
1294 ap = hp->h.h_addr_list =
1295 (char**)(buf + ((alias_count + 1) * sizeof(char*)));
1296 p = (char*)ap + ((addr_count + 1) * sizeof(char*));
1298 memcpy(p, *pp++, hp->h.h_length);
1300 p += hp->h.h_length;
1304 memcpy(p, *addr++, hp->h.h_length);
1306 p += hp->h.h_length;
1311 /* next write the name */
1312 strcpy(p, hp->h.h_name);
1314 p += (strlen(p) + 1);
1316 /* last write the alias list */
1317 pp = hp->h.h_aliases;
1318 ap = hp->h.h_aliases = (char**) buf;
1322 p += (strlen(p) + 1);
1326 strcpy(p, *alias++);
1328 p += (strlen(p) + 1);
1332 /* release the old buffer */
1339 * hash_number - IP address hash function
1341 static int hash_number(const unsigned char* ip)
1343 /* could use loop but slower */
1345 const u_char* p = (const u_char*) ip;
1350 hashv += hashv + *p++;
1351 hashv += hashv + *p++;
1352 hashv += hashv + *p;
1353 hashv %= ARES_CACSIZE;
1358 * hash_name - hostname hash function
1360 static int hash_name(const char* name)
1362 unsigned int hashv = 0;
1363 const u_char* p = (const u_char*) name;
1367 for (; *p && *p != '.'; ++p)
1369 hashv %= ARES_CACSIZE;
1374 * add_to_cache - Add a new cache item to the queue and hash table.
1376 static struct CacheEntry* add_to_cache(struct CacheEntry* ocp)
1382 ocp->list_next = cacheTop;
1385 hashv = hash_name(ocp->he.h.h_name);
1387 ocp->hname_next = hashtable[hashv].name_list;
1388 hashtable[hashv].name_list = ocp;
1390 hashv = hash_number(ocp->he.h.h_addr);
1392 ocp->hnum_next = hashtable[hashv].num_list;
1393 hashtable[hashv].num_list = ocp;
1396 * LRU deletion of excessive cache entries.
1398 if (++cachedCount > MAXCACHED) {
1399 struct CacheEntry* cp;
1400 struct CacheEntry* cp_next;
1401 for (cp = ocp->list_next; cp; cp = cp_next) {
1402 cp_next = cp->list_next;
1411 * update_list - does not alter the cache structure passed. It is assumed that
1412 * it already contains the correct expire time, if it is a new entry. Old
1413 * entries have the expirey time updated.
1415 static void update_list(struct ResRequest* request, struct CacheEntry* cachep)
1418 struct CacheEntry** cpp;
1420 struct CacheEntry* cp = cachep;
1426 char* addrs[RES_MAXADDRS + 1];
1427 char* aliases[RES_MAXALIASES + 1];
1430 * search for the new cache item in the cache list by hostname.
1431 * If found, move the entry to the top of the list and return.
1433 ++cainfo.ca_updates;
1435 for (cpp = &cacheTop; *cpp; cpp = &((*cpp)->list_next)) {
1441 *cpp = cp->list_next;
1442 cp->list_next = cacheTop;
1449 * Compare the cache entry against the new record. Add any
1450 * previously missing names for this entry.
1454 for (i = 0, s = request->he.h.h_name; s; s = request->he.h.h_aliases[i++]) {
1455 for (j = 0, t = cp->he.h.h_name; t; t = cp->he.h.h_aliases[j++]) {
1456 if (0 == ircd_strcmp(t, s))
1465 * Do the same again for IP#'s.
1469 for (i = 0; (s = request->he.h.h_addr_list[i]); i++) {
1470 for (j = 0; (t = cp->he.h.h_addr_list[j]); j++) {
1471 if (!memcmp(t, s, sizeof(struct in_addr)))
1479 if (*addrs || *aliases)
1480 update_hostent(&cp->he, addrs, aliases);
1484 * find_cache_name - find name in nameserver cache
1486 static struct CacheEntry* find_cache_name(const char* name)
1488 struct CacheEntry* cp;
1494 hashv = hash_name(name);
1496 cp = hashtable[hashv].name_list;
1498 for (; cp; cp = cp->hname_next) {
1499 for (i = 0, s = cp->he.h.h_name; s; s = cp->he.h.h_aliases[i++]) {
1500 if (0 == ircd_strcmp(s, name)) {
1501 ++cainfo.ca_na_hits;
1507 for (cp = cacheTop; cp; cp = cp->list_next) {
1509 * if no aliases or the hash value matches, we've already
1510 * done this entry and all possiblilities concerning it.
1512 if (!cp->he.h.h_name || hashv == hash_name(cp->he.h.h_name))
1514 for (i = 0, s = cp->he.h.h_aliases[i]; s; s = cp->he.h.h_aliases[++i]) {
1515 if (0 == ircd_strcmp(name, s)) {
1516 ++cainfo.ca_na_hits;
1525 * find_cache_number - find a cache entry by ip# and update its expire time
1527 static struct CacheEntry* find_cache_number(struct ResRequest* request,
1530 struct CacheEntry* cp;
1535 hashv = hash_number(addr);
1536 cp = hashtable[hashv].num_list;
1538 for (; cp; cp = cp->hnum_next) {
1539 for (i = 0; cp->he.h.h_addr_list[i]; ++i) {
1540 if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1541 ++cainfo.ca_nu_hits;
1546 for (cp = cacheTop; cp; cp = cp->list_next) {
1548 * single address entry...would have been done by hashed
1550 * if the first IP# has the same hashnumber as the IP# we
1551 * are looking for, its been done already.
1553 if (!cp->he.h.h_addr_list[1] ||
1554 hashv == hash_number(cp->he.h.h_addr_list[0]))
1556 for (i = 1; cp->he.h.h_addr_list[i]; ++i) {
1557 if (!memcmp(cp->he.h.h_addr_list[i], addr, sizeof(struct in_addr))) {
1558 ++cainfo.ca_nu_hits;
1566 static struct CacheEntry* make_cache(struct ResRequest* request)
1568 struct CacheEntry* cp;
1571 assert(0 != request);
1573 hp = &request->he.h;
1575 * shouldn't happen but it just might...
1577 assert(0 != hp->h_name);
1578 assert(0 != hp->h_addr_list[0]);
1579 if (!hp->h_name || !hp->h_addr_list[0])
1582 * Make cache entry. First check to see if the cache already exists
1583 * and if so, return a pointer to it.
1585 for (i = 0; hp->h_addr_list[i]; ++i) {
1586 if ((cp = find_cache_number(request, hp->h_addr_list[i]))) {
1587 update_list(request, cp);
1592 * a matching entry wasnt found in the cache so go and make one up.
1594 cp = (struct CacheEntry*) MyMalloc(sizeof(struct CacheEntry));
1597 memset(cp, 0, sizeof(struct CacheEntry));
1598 dup_hostent(&cp->he, hp);
1599 cp->reply.hp = &cp->he.h;
1601 * hmmm... we could time out the cache after 10 minutes regardless
1602 * would that be reasonable since we don't save the reply?
1604 if (request->ttl < AR_TTL) {
1605 ++reinfo.re_shortttl;
1609 cp->ttl = request->ttl;
1610 cp->expireat = CurrentTime + cp->ttl;
1611 return add_to_cache(cp);
1615 * rem_cache - delete a cache entry from the cache structures
1616 * and lists and return all memory used for the cache back to the memory pool.
1618 static void rem_cache(struct CacheEntry* ocp)
1620 struct CacheEntry** cp;
1626 if (0 < ocp->reply.ref_count) {
1627 if (ocp->expireat < CurrentTime) {
1628 ocp->expireat = CurrentTime + AR_TTL;
1629 Debug((DEBUG_DNS, "Resolver: referenced cache entry not removed for: %s",
1635 * remove cache entry from linked list
1637 for (cp = &cacheTop; *cp; cp = &((*cp)->list_next)) {
1639 *cp = ocp->list_next;
1645 * remove cache entry from hashed name list
1647 assert(0 != hp->h_name);
1648 hashv = hash_name(hp->h_name);
1650 for (cp = &hashtable[hashv].name_list; *cp; cp = &((*cp)->hname_next)) {
1652 *cp = ocp->hname_next;
1657 * remove cache entry from hashed number list
1659 hashv = hash_number(hp->h_addr);
1662 for (cp = &hashtable[hashv].num_list; *cp; cp = &((*cp)->hnum_next)) {
1664 *cp = ocp->hnum_next;
1669 * free memory used to hold the various host names and the array
1670 * of alias pointers.
1672 MyFree(ocp->he.buf);
1678 void flush_resolver_cache(void)
1681 * stubbed - iterate cache and remove everything that isn't referenced
1686 * m_dns - dns status query
1688 int m_dns(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1690 #if !defined(NDEBUG)
1691 struct CacheEntry* cp;
1695 if (parv[1] && *parv[1] == 'l') {
1696 for(cp = cacheTop; cp; cp = cp->list_next) {
1698 sendto_one(sptr, "NOTICE %s :Ex %d ttl %d host %s(%s)",
1699 parv[0], cp->expireat - CurrentTime, cp->ttl,
1700 hp->h_name, ircd_ntoa(hp->h_addr));
1701 for (i = 0; hp->h_aliases[i]; i++)
1702 sendto_one(sptr,"NOTICE %s : %s = %s (CN)",
1703 parv[0], hp->h_name, hp->h_aliases[i]);
1704 for (i = 1; hp->h_addr_list[i]; i++)
1705 sendto_one(sptr,"NOTICE %s : %s = %s (IP)",
1706 parv[0], hp->h_name, ircd_ntoa(hp->h_addr_list[i]));
1710 if (parv[1] && *parv[1] == 'd') {
1711 sendto_one(sptr, "NOTICE %s :ResolverFileDescriptor = %d",
1712 parv[0], ResolverFileDescriptor);
1715 sendto_one(sptr,"NOTICE %s :Ca %d Cd %d Ce %d Cl %d Ch %d:%d Cu %d",
1717 cainfo.ca_adds, cainfo.ca_dels, cainfo.ca_expires,
1718 cainfo.ca_lookups, cainfo.ca_na_hits, cainfo.ca_nu_hits,
1721 sendto_one(sptr,"NOTICE %s :Re %d Rl %d/%d Rp %d Rq %d",
1722 sptr->name, reinfo.re_errors, reinfo.re_nu_look,
1723 reinfo.re_na_look, reinfo.re_replies, reinfo.re_requests);
1724 sendto_one(sptr,"NOTICE %s :Ru %d Rsh %d Rs %d(%d) Rt %d", sptr->name,
1725 reinfo.re_unkrep, reinfo.re_shortttl, reinfo.re_sent,
1726 reinfo.re_resends, reinfo.re_timeouts);
1731 size_t cres_mem(struct Client* sptr)
1733 struct CacheEntry* entry;
1734 struct ResRequest* request;
1735 size_t cache_mem = 0;
1736 size_t request_mem = 0;
1737 int cache_count = 0;
1738 int request_count = 0;
1740 for (entry = cacheTop; entry; entry = entry->list_next) {
1741 cache_mem += sizeof(struct CacheEntry);
1742 cache_mem += calc_hostent_buffer_size(&entry->he.h);
1745 for (request = requestListHead; request; request = request->next) {
1746 request_mem += sizeof(struct ResRequest);
1748 request_mem += strlen(request->name) + 1;
1749 if (request->he.buf)
1750 request_mem += MAXGETHOSTLEN + 1;
1753 if (cachedCount != cache_count) {
1755 ":%s %d %s :Resolver: cache count mismatch: %d != %d",
1756 me.name, RPL_STATSDEBUG, sptr->name, cachedCount, cache_count);
1757 assert(cachedCount == cache_count);
1759 sendto_one(sptr, ":%s %d %s :Resolver: cache %d(%d) requests %d(%d)",
1760 me.name, RPL_STATSDEBUG, sptr->name, cache_count, cache_mem,
1761 request_count, request_mem);
1762 return cache_mem + request_mem;