2 * A rewrite of Darren Reeds original res.c As there is nothing
3 * left of Darrens original code, this is now licensed by the hybrid group.
4 * (Well, some of the function names are the same, and bits of the structs..)
5 * You can use it where it is useful, free even. Buy us a beer and stuff.
7 * The authors takes no responsibility for any damage or loss
8 * of property which results from the use of this software.
12 * July 1999 - Rewrote a bunch of stuff here. Change hostent builder code,
13 * added callbacks and reference counting of returned hostents.
14 * --Bleep (Thomas Helvey <tomh@inxpress.net>)
16 * This was all needlessly complicated for irc. Simplified. No more hostent
17 * All we really care about is the IP -> hostname mappings. Thats all.
19 * Apr 28, 2003 --cryogen and Dianora
23 #include "ircd_alloc.h"
25 #include "ircd_osdep.h"
26 #include "ircd_reply.h"
27 #include "ircd_string.h"
28 #include "ircd_snprintf.h"
31 #include "fileio.h" /* for fbopen / fbclose / fbputs */
38 #include "ircd_reslib.h"
43 #include <sys/socket.h>
47 #error this code needs to be able to address individual octets
50 static struct Socket res_socket;
51 static struct Timer res_timeout;
53 #define MAXPACKET 1024 /* rfc sez 512 but we expand names so ... */
54 #define RES_MAXALIASES 35 /* maximum aliases allowed */
55 #define RES_MAXADDRS 35 /* maximum addresses allowed */
56 #define AR_TTL 600 /* TTL in seconds for dns cache entries */
58 /* RFC 1104/1105 wasn't very helpful about what these fields
59 * should be named, so for now, we'll just name them this way.
60 * we probably should look at what named calls them or something.
62 #define TYPE_SIZE (size_t)2
63 #define CLASS_SIZE (size_t)2
64 #define TTL_SIZE (size_t)4
65 #define RDLENGTH_SIZE (size_t)2
66 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
70 REQ_IDLE, /* We're doing not much at all */
71 REQ_PTR, /* Looking up a PTR */
72 REQ_A, /* Looking up an A, possibly because AAAA failed */
73 REQ_AAAA, /* Looking up an AAAA */
74 REQ_CNAME, /* We got a CNAME in response, we better get a real answer next */
75 REQ_INT /* ip6.arpa failed, falling back to ip6.int */
88 int sent; /* number of requests sent */
89 request_state state; /* State the resolver machine is in */
92 char retries; /* retry counter */
93 char sends; /* number of sends (>1 means resent) */
94 char resend; /* send flag. 0 == dont resend */
97 struct irc_in_addr addr;
99 struct DNSQuery query; /* query callback for this request */
102 static struct dlink request_list;
104 static void rem_request(struct reslist *request);
105 static struct reslist *make_request(const struct DNSQuery *query);
106 static void do_query_name(const struct DNSQuery *query,
107 const char* name, struct reslist *request, int);
108 static void do_query_number(const struct DNSQuery *query,
109 const struct irc_in_addr *,
110 struct reslist *request);
111 static void query_name(const char *name, int query_class, int query_type,
112 struct reslist *request);
113 static int send_res_msg(const char *buf, int len, int count);
114 static void resend_query(struct reslist *request);
115 static int proc_answer(struct reslist *request, HEADER *header, char *, char *);
116 static struct reslist *find_id(int id);
117 static struct DNSReply *make_dnsreply(struct reslist *request);
118 static void res_readreply(struct Event *ev);
119 static void timeout_resolver(struct Event *notused);
121 extern struct irc_sockaddr irc_nsaddr_list[IRCD_MAXNS];
122 extern int irc_nscount;
123 extern char irc_domain[HOSTLEN];
128 * looks up "inp" in irc_nsaddr_list[]
133 * paul vixie, 29may94
134 * revised for ircd, cryogen(stu) may03
137 res_ourserver(const struct irc_sockaddr *inp)
141 for (ns = 0; ns < irc_nscount; ns++)
142 if (!irc_in_addr_cmp(&inp->addr, &irc_nsaddr_list[ns].addr)
143 && inp->port == irc_nsaddr_list[ns].port)
150 * start_resolver - do everything we need to read the resolv.conf file
151 * and initialize the resolver file descriptor if needed
158 if (!request_list.next)
159 request_list.next = request_list.prev = &request_list;
161 if (!s_active(&res_socket))
164 fd = os_socket(NULL, SOCK_DGRAM, "Resolver UDP socket");
166 if (!socket_add(&res_socket, res_readreply, NULL, SS_DATAGRAM,
167 SOCK_EVENT_READABLE, fd)) return;
168 timer_init(&res_timeout);
169 timer_add(&res_timeout, timeout_resolver, NULL, TT_PERIODIC, 1);
174 * init_resolver - initialize resolver and resolver library
180 srand48(CurrentTime);
183 return(s_fd(&res_socket));
187 * restart_resolver - reread resolv.conf, reopen socket
190 restart_resolver(void)
196 * add_local_domain - Add the domain to hostname, if it is missing
197 * (as suggested by eps@TOASTER.SFSU.EDU)
200 add_local_domain(char* hname, size_t size)
202 /* try to fix up unqualified names
204 if (strchr(hname, '.') == NULL)
208 size_t len = strlen(hname);
210 if ((strlen(irc_domain) + len + 2) < size)
213 strcpy(hname + len, irc_domain);
220 * remove_dlink - remove a link from a doubly linked list
223 remove_dlink(struct dlink *node)
225 node->prev->next = node->next;
226 node->next->prev = node->prev;
230 * add_dlink - add a link to a doubly linked list
233 add_dlink(struct dlink *node, struct dlink *next)
235 node->prev = next->prev;
237 node->prev->next = node;
238 node->next->prev = node;
242 * rem_request - remove a request from the list.
243 * This must also free any memory that has been allocated for
244 * temporary storage of DNS results.
247 rem_request(struct reslist *request)
249 remove_dlink(&request->node);
250 MyFree(request->name);
255 * make_request - Create a DNS request record for the server.
257 static struct reslist *
258 make_request(const struct DNSQuery* query)
260 struct reslist *request;
262 request = (struct reslist *)MyMalloc(sizeof(struct reslist));
263 memset(request, 0, sizeof(struct reslist));
265 request->sentat = CurrentTime;
266 request->retries = 3;
268 request->timeout = 4; /* start at 4 and exponential inc. */
269 memset(&request->addr, 0, sizeof(request->addr));
270 request->query.vptr = query->vptr;
271 request->query.callback = query->callback;
272 request->state = REQ_IDLE;
274 add_dlink(&request->node, &request_list);
279 * timeout_query_list - Remove queries from the list which have been
280 * there too long without being resolved.
283 timeout_query_list(time_t now)
285 struct dlink *ptr, *next_ptr;
286 struct reslist *request;
287 time_t next_time = 0;
290 for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
292 next_ptr = ptr->next;
293 request = (struct reslist*)ptr;
294 timeout = request->sentat + request->timeout;
298 if (--request->retries <= 0)
300 Debug((DEBUG_DNS, "Request %p out of retries; destroying", request));
301 (*request->query.callback)(request->query.vptr, 0);
302 rem_request(request);
307 request->sentat = now;
308 request->timeout += request->timeout;
309 resend_query(request);
313 if ((next_time == 0) || timeout < next_time)
319 return((next_time > now) ? next_time : (now + AR_TTL));
323 * timeout_resolver - check request list
326 timeout_resolver(struct Event *notused)
328 timeout_query_list(CurrentTime);
332 * delete_resolver_queries - cleanup outstanding queries
333 * for which there no longer exist clients or conf lines.
336 delete_resolver_queries(const void *vptr)
338 struct dlink *ptr, *next_ptr;
339 struct reslist *request;
341 for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
343 next_ptr = ptr->next;
344 request = (struct reslist*)ptr;
345 if (vptr == request->query.vptr) {
346 Debug((DEBUG_DNS, "Removing request %p with vptr %p", request, vptr));
347 rem_request(request);
353 * send_res_msg - sends msg to all nameservers found in the "_res" structure.
354 * This should reflect /etc/resolv.conf. We will get responses
355 * which arent needed but is easier than checking to see if nameserver
356 * isnt present. Returns number of messages successfully sent to
357 * nameservers or -1 if no successful sends.
360 send_res_msg(const char *msg, int len, int rcount)
364 int max_queries = IRCD_MIN(irc_nscount, rcount);
366 /* RES_PRIMARY option is not implemented
367 * if (res.options & RES_PRIMARY || 0 == max_queries)
369 if (max_queries == 0)
372 for (i = 0; i < max_queries; i++)
373 if (os_sendto_nonb(s_fd(&res_socket), msg, len, NULL, 0, &irc_nsaddr_list[i]) == IO_SUCCESS)
380 * find_id - find a dns request id (id is determined by dn_mkquery)
382 static struct reslist *
386 struct reslist *request;
388 for (ptr = request_list.next; ptr != &request_list; ptr = ptr->next)
390 request = (struct reslist*)ptr;
392 if (request->id == id) {
393 Debug((DEBUG_DNS, "find_id(%d) -> %p", id, request));
398 Debug((DEBUG_DNS, "find_id(%d) -> NULL", id, request));
403 * gethost_byname_type - get host address from name
407 gethost_byname_type(const char *name, const struct DNSQuery *query, int type)
410 do_query_name(query, name, NULL, type);
414 * gethost_byname - wrapper for _type - send T_AAAA first
417 gethost_byname(const char *name, const struct DNSQuery *query)
419 gethost_byname_type(name, query, T_AAAA);
423 * gethost_byaddr - get host name from address
426 gethost_byaddr(const struct irc_in_addr *addr, const struct DNSQuery *query)
428 do_query_number(query, addr, NULL);
432 * do_query_name - nameserver lookup name
435 do_query_name(const struct DNSQuery *query, const char *name,
436 struct reslist *request, int type)
438 char host_name[HOSTLEN + 1];
440 ircd_strncpy(host_name, name, HOSTLEN);
441 add_local_domain(host_name, HOSTLEN);
445 request = make_request(query);
446 request->name = (char *)MyMalloc(strlen(host_name) + 1);
447 request->type = type;
448 strcpy(request->name, host_name);
451 request->state = REQ_AAAA;
454 request->state = REQ_A;
457 request->type = type;
458 Debug((DEBUG_DNS, "Requesting DNS %s %s as %p", (request->state == REQ_AAAA ? "AAAA" : "A"), host_name, request));
459 query_name(host_name, C_IN, type, request);
463 * do_query_number - Use this to do reverse IP# lookups.
466 do_query_number(const struct DNSQuery *query, const struct irc_in_addr *addr,
467 struct reslist *request)
470 const unsigned char *cp;
472 if (irc_in_addr_is_ipv4(addr))
474 cp = (const unsigned char*)&addr->in6_16[6];
475 ircd_snprintf(NULL, ipbuf, sizeof(ipbuf), "%u.%u.%u.%u.in-addr.arpa.",
476 (unsigned int)(cp[3]), (unsigned int)(cp[2]),
477 (unsigned int)(cp[1]), (unsigned int)(cp[0]));
483 if (request != NULL && request->state == REQ_INT)
488 cp = (const unsigned char *)&addr->in6_16[0];
489 ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
490 "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x."
491 "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.%s.",
492 (unsigned int)(cp[15]&0xf), (unsigned int)(cp[15]>>4),
493 (unsigned int)(cp[14]&0xf), (unsigned int)(cp[14]>>4),
494 (unsigned int)(cp[13]&0xf), (unsigned int)(cp[13]>>4),
495 (unsigned int)(cp[12]&0xf), (unsigned int)(cp[12]>>4),
496 (unsigned int)(cp[11]&0xf), (unsigned int)(cp[11]>>4),
497 (unsigned int)(cp[10]&0xf), (unsigned int)(cp[10]>>4),
498 (unsigned int)(cp[9]&0xf), (unsigned int)(cp[9]>>4),
499 (unsigned int)(cp[8]&0xf), (unsigned int)(cp[8]>>4),
500 (unsigned int)(cp[7]&0xf), (unsigned int)(cp[7]>>4),
501 (unsigned int)(cp[6]&0xf), (unsigned int)(cp[6]>>4),
502 (unsigned int)(cp[5]&0xf), (unsigned int)(cp[5]>>4),
503 (unsigned int)(cp[4]&0xf), (unsigned int)(cp[4]>>4),
504 (unsigned int)(cp[3]&0xf), (unsigned int)(cp[3]>>4),
505 (unsigned int)(cp[2]&0xf), (unsigned int)(cp[2]>>4),
506 (unsigned int)(cp[1]&0xf), (unsigned int)(cp[1]>>4),
507 (unsigned int)(cp[0]&0xf), (unsigned int)(cp[0]>>4), intarpa);
511 request = make_request(query);
512 request->type = T_PTR;
513 memcpy(&request->addr, addr, sizeof(request->addr));
514 request->name = (char *)MyMalloc(HOSTLEN + 1);
516 Debug((DEBUG_DNS, "Requesting DNS PTR %s as %p", ipbuf, request));
517 query_name(ipbuf, C_IN, T_PTR, request);
521 * query_name - generate a query based on class, type and name.
524 query_name(const char *name, int query_class, int type,
525 struct reslist *request)
530 memset(buf, 0, sizeof(buf));
532 if ((request_len = irc_res_mkquery(name, query_class, type,
533 (unsigned char *)buf, sizeof(buf))) > 0)
535 HEADER *header = (HEADER *)buf;
541 * generate an unique id
542 * NOTE: we don't have to worry about converting this to and from
543 * network byte order, the nameserver does not interpret this value
544 * and returns it unchanged
549 header->id = (header->id + lrand48()) & 0xffff;
550 } while (find_id(header->id));
552 gettimeofday(&tv, NULL);
556 header->id = (header->id + k + tv.tv_usec) & 0xffff;
558 } while (find_id(header->id));
560 request->id = header->id;
563 request->sent += send_res_msg(buf, request_len, request->sends);
568 resend_query(struct reslist *request)
570 if (request->resend == 0)
573 switch(request->type)
576 do_query_number(NULL, &request->addr, request);
579 do_query_name(NULL, request->name, request, request->type);
582 /* didnt work, try A */
583 if (request->state == REQ_AAAA)
584 do_query_name(NULL, request->name, request, T_A);
591 * proc_answer - process name server reply
594 proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
596 char hostbuf[HOSTLEN + 100]; /* working buffer */
597 unsigned char *current; /* current position in buf */
598 int query_class; /* answer class */
599 int type; /* answer type */
600 int n; /* temp count */
603 current = (unsigned char *)buf + sizeof(HEADER);
605 for (; header->qdcount > 0; --header->qdcount)
607 if ((n = irc_dn_skipname(current, (unsigned char *)eob)) < 0)
610 current += (size_t) n + QFIXEDSZ;
614 * process each answer sent to us blech.
616 while (header->ancount > 0 && (char *)current < eob)
620 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob, current,
621 hostbuf, sizeof(hostbuf));
633 * no more answers left
638 hostbuf[HOSTLEN] = '\0';
640 /* With Address arithmetic you have to be very anal
641 * this code was not working on alpha due to that
642 * (spotted by rodder/jailbird/dianora)
644 current += (size_t) n;
646 if (!(((char *)current + ANSWER_FIXED_SIZE) < eob))
649 type = irc_ns_get16(current);
650 current += TYPE_SIZE;
652 query_class = irc_ns_get16(current);
653 current += CLASS_SIZE;
655 request->ttl = irc_ns_get32(current);
658 rd_length = irc_ns_get16(current);
659 current += RDLENGTH_SIZE;
662 * Wait to set request->type until we verify this structure
667 if (request->type != T_A)
671 * check for invalid rd_length or too many addresses
673 if (rd_length != sizeof(struct in_addr))
675 memset(&request->addr, 0, sizeof(request->addr));
676 memcpy(&request->addr.in6_16[6], current, sizeof(struct in_addr));
680 if (request->type != T_AAAA)
682 if (rd_length != sizeof(struct irc_in_addr))
684 memcpy(&request->addr, current, sizeof(struct irc_in_addr));
688 if (request->type != T_PTR)
690 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
691 current, hostbuf, sizeof(hostbuf));
693 return(0); /* broken message */
695 return(0); /* no more answers left */
697 ircd_strncpy(request->name, hostbuf, HOSTLEN);
701 case T_CNAME: /* first check we already havent started looking
703 if (request->type != T_PTR)
706 if (request->state == REQ_CNAME)
708 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
709 current, hostbuf, sizeof(hostbuf));
716 request->state = REQ_CNAME;
717 current += rd_length;
721 /* XXX I'd rather just throw away the entire bogus thing
722 * but its possible its just a broken nameserver with still
723 * valid answers. But lets do some rudimentary logging for now...
725 log_write(LS_RESOLVER, L_ERROR, 0, "irc_res.c bogus type %d", type);
734 * res_readreply - read a dns reply from the nameserver and process it.
737 res_readreply(struct Event *ev)
739 struct irc_sockaddr lsin;
741 char buf[sizeof(HEADER) + MAXPACKET];
743 struct reslist *request = NULL;
744 struct DNSReply *reply = NULL;
748 assert(ev_socket(ev) == &res_socket);
749 sock = ev_socket(ev);
751 if (IO_SUCCESS != os_recvfrom_nonb(s_fd(sock), buf, sizeof(buf), &rc, &lsin)
752 || (rc <= sizeof(HEADER)))
756 * convert DNS reply reader from Network byte order to CPU byte order.
758 header = (HEADER *)buf;
759 header->ancount = ntohs(header->ancount);
760 header->qdcount = ntohs(header->qdcount);
761 header->nscount = ntohs(header->nscount);
762 header->arcount = ntohs(header->arcount);
765 * response for an id which we have already received an answer for
766 * just ignore this response.
768 if (0 == (request = find_id(header->id)))
772 * check against possibly fake replies
774 if (!res_ourserver(&lsin))
777 if ((header->rcode != NO_ERRORS) || (header->ancount == 0))
779 if (SERVFAIL == header->rcode)
780 resend_query(request);
784 * If we havent already tried this, and we're looking up AAAA, try A
788 if (request->state == REQ_AAAA && request->type == T_AAAA)
790 request->timeout += 4;
791 resend_query(request);
793 else if (request->type == T_PTR && request->state != REQ_INT &&
794 !irc_in_addr_is_ipv4(&request->addr))
796 request->state = REQ_INT;
797 request->timeout += 4;
798 resend_query(request);
803 * If a bad error was returned, we stop here and dont send
804 * send any more (no retries granted).
806 Debug((DEBUG_DNS, "Request %p has bad response (state %d type %d)", request, request->state, request->type));
807 (*request->query.callback)(request->query.vptr, 0);
808 rem_request(request);
815 * If this fails there was an error decoding the received packet,
816 * try it again and hope it works the next time.
818 answer_count = proc_answer(request, header, buf, buf + rc);
822 if (request->type == T_PTR)
824 if (request->name == NULL)
827 * got a PTR response with no name, something bogus is happening
828 * don't bother trying again, the client address doesn't resolve
830 Debug((DEBUG_DNS, "Request %p PTR had empty name", request));
831 (*request->query.callback)(request->query.vptr, reply);
832 rem_request(request);
837 * Lookup the 'authoritative' name that we were given for the
841 if (!irc_in_addr_is_ipv4(&request->addr))
842 gethost_byname_type(request->name, &request->query, T_AAAA);
845 gethost_byname_type(request->name, &request->query, T_A);
846 Debug((DEBUG_DNS, "Request %p switching to forward resolution", request));
847 rem_request(request);
852 * got a name and address response, client resolved
854 reply = make_dnsreply(request);
855 (*request->query.callback)(request->query.vptr, (reply) ? reply : 0);
856 Debug((DEBUG_DNS, "Request %p got forward resolution", request));
857 rem_request(request);
860 else if (!request->sent)
862 /* XXX - we got a response for a query we didn't send with a valid id?
863 * this should never happen, bail here and leave the client unresolved
867 /* XXX don't leak it */
868 Debug((DEBUG_DNS, "Request %p was unexpected(!)", request));
869 rem_request(request);
873 static struct DNSReply *
874 make_dnsreply(struct reslist *request)
877 assert(request != 0);
879 cp = (struct DNSReply *)MyMalloc(sizeof(struct DNSReply));
881 DupString(cp->h_name, request->name);
882 memcpy(&cp->addr, &request->addr, sizeof(cp->addr));
887 report_dns_servers(struct Client *source_p, struct StatDesc *sd, int stat, char *param)
892 for (i = 0; i < irc_nscount; i++)
894 ircd_ntoa_r(ipaddr, &irc_nsaddr_list[i].addr);
895 send_reply(source_p, RPL_STATSALINE, ipaddr);
900 cres_mem(struct Client* sptr)
903 struct reslist *request;
904 size_t request_mem = 0;
905 int request_count = 0;
907 for (dlink = request_list.next; dlink != &request_list; dlink = dlink->next) {
908 request = (struct reslist*)dlink;
909 request_mem += sizeof(*request);
911 request_mem += strlen(request->name) + 1;
915 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
916 ":Resolver: requests %d(%d)", request_count, request_mem);
920 int irc_in_addr_valid(const struct irc_in_addr *addr)
925 val = addr->in6_16[0];
926 if (val != 0 || val != 0xffff)
928 for (ii = 1; ii < 8; ii++)
929 if (addr->in6_16[ii] != val)
934 int irc_in_addr_cmp(const struct irc_in_addr *a, const struct irc_in_addr *b)
936 if (irc_in_addr_is_ipv4(a))
937 return a->in6_16[6] != b->in6_16[6]
938 || a->in6_16[7] != b->in6_16[7]
939 || !irc_in_addr_is_ipv4(b);
941 return memcmp(a, b, sizeof(*a));
944 int irc_in_addr_is_loopback(const struct irc_in_addr *addr)
946 if (addr->in6_16[0] != 0
947 || addr->in6_16[1] != 0
948 || addr->in6_16[2] != 0
949 || addr->in6_16[3] != 0
950 || addr->in6_16[4] != 0)
952 if ((addr->in6_16[5] == 0xffff) || (addr->in6_16[5] == 0 && addr->in6_16[6] != 0))
953 return (ntohs(addr->in6_16[6]) & 0xff00) == 0x7f00;
955 return addr->in6_16[5] == 0 && addr->in6_16[6] == 0 && htons(addr->in6_16[7]) == 1;