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 */
37 #include "ircd_reslib.h"
38 #include "ircd_addrinfo.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 */
74 REQ_AAAA, /* Looking up an AAAA */
76 REQ_CNAME, /* We got a CNAME in response, we better get a real answer next */
77 REQ_INT /* ip6.arpa failed, falling back to ip6.int */
90 int sent; /* number of requests sent */
91 request_state state; /* State the resolver machine is in */
94 char retries; /* retry counter */
95 char sends; /* number of sends (>1 means resent) */
96 char resend; /* send flag. 0 == dont resend */
99 struct irc_ssaddr addr;
101 struct DNSQuery query; /* query callback for this request */
104 static struct dlink request_list;
106 static void rem_request(struct reslist *request);
107 static struct reslist *make_request(const struct DNSQuery *query);
108 static void do_query_name(const struct DNSQuery *query,
109 const char* name, struct reslist *request, int);
110 static void do_query_number(const struct DNSQuery *query,
111 const struct irc_ssaddr *,
112 struct reslist *request);
113 static void query_name(const char *name, int query_class, int query_type,
114 struct reslist *request);
115 static int send_res_msg(const char *buf, int len, int count);
116 static void resend_query(struct reslist *request);
117 static int proc_answer(struct reslist *request, HEADER *header, char *, char *);
118 static struct reslist *find_id(int id);
119 static struct DNSReply *make_dnsreply(struct reslist *request);
120 static void res_readreply(struct Event *ev);
121 static void timeout_resolver(struct Event *notused);
123 extern struct irc_ssaddr irc_nsaddr_list[IRCD_MAXNS];
124 extern int irc_nscount;
125 extern char irc_domain[HOSTLEN];
130 * looks up "inp" in irc_nsaddr_list[]
135 * paul vixie, 29may94
136 * revised for ircd, cryogen(stu) may03
139 res_ourserver(const struct irc_ssaddr *inp)
142 struct sockaddr_in6 *v6;
143 struct sockaddr_in6 *v6in = (struct sockaddr_in6 *)inp;
145 struct sockaddr_in *v4;
146 struct sockaddr_in *v4in = (struct sockaddr_in *)inp;
149 for (ns = 0; ns < irc_nscount; ns++)
151 const struct irc_ssaddr *srv = &irc_nsaddr_list[ns];
153 v6 = (struct sockaddr_in6 *)srv;
155 v4 = (struct sockaddr_in *)srv;
157 /* could probably just memcmp(srv, inp, srv.ss_len) here
158 * but we'll air on the side of caution - stu
161 switch (srv->ss.ss_family)
165 if (srv->ss.ss_family == inp->ss.ss_family)
166 if (v6->sin6_port == v6in->sin6_port)
167 if ((memcmp(&v6->sin6_addr.s6_addr, &v6in->sin6_addr.s6_addr,
168 sizeof(struct in6_addr)) == 0) ||
169 (memcmp(&v6->sin6_addr.s6_addr, &in6addr_any,
170 sizeof(struct in6_addr)) == 0))
175 if (srv->ss.ss_family == inp->ss.ss_family)
176 if (v4->sin_port == v4in->sin_port)
177 if ((v4->sin_addr.s_addr == INADDR_ANY) ||
178 (v4->sin_addr.s_addr == v4in->sin_addr.s_addr))
190 * start_resolver - do everything we need to read the resolv.conf file
191 * and initialize the resolver file descriptor if needed
198 if (!request_list.next)
199 request_list.next = request_list.prev = &request_list;
201 if (!s_active(&res_socket))
204 fd = socket(irc_nsaddr_list[0].ss.ss_family, SOCK_DGRAM, 0);
205 if (fd < 0) {} /* TODO: bail on socket() failure */
206 if (!os_set_nonblocking(fd)) {} /* TODO: bail on failure */
207 if (!socket_add(&res_socket, res_readreply, NULL, SS_DATAGRAM,
208 SOCK_EVENT_READABLE, fd)) {} /* TODO: bail on socket_add() failure */
209 timer_init(&res_timeout);
210 timer_add(&res_timeout, timeout_resolver, NULL, TT_PERIODIC, 1);
215 * init_resolver - initialize resolver and resolver library
221 srand48(CurrentTime);
224 return(s_fd(&res_socket));
228 * restart_resolver - reread resolv.conf, reopen socket
231 restart_resolver(void)
237 * add_local_domain - Add the domain to hostname, if it is missing
238 * (as suggested by eps@TOASTER.SFSU.EDU)
241 add_local_domain(char* hname, size_t size)
243 /* try to fix up unqualified names
245 if (strchr(hname, '.') == NULL)
249 size_t len = strlen(hname);
251 if ((strlen(irc_domain) + len + 2) < size)
254 strcpy(hname + len, irc_domain);
261 * remove_dlink - remove a link from a doubly linked list
264 remove_dlink(struct dlink *node)
266 node->prev->next = node->next;
267 node->next->prev = node->prev;
271 * add_dlink - add a link to a doubly linked list
274 add_dlink(struct dlink *node, struct dlink *next)
276 node->prev = next->prev;
278 node->prev->next = node;
279 node->next->prev = node;
283 * rem_request - remove a request from the list.
284 * This must also free any memory that has been allocated for
285 * temporary storage of DNS results.
288 rem_request(struct reslist *request)
290 remove_dlink(&request->node);
291 MyFree(request->name);
296 * make_request - Create a DNS request record for the server.
298 static struct reslist *
299 make_request(const struct DNSQuery* query)
301 struct reslist *request;
303 request = (struct reslist *)MyMalloc(sizeof(struct reslist));
304 memset(request, 0, sizeof(struct reslist));
306 request->sentat = CurrentTime;
307 request->retries = 3;
309 request->timeout = 4; /* start at 4 and exponential inc. */
310 memset(&request->addr, 0, sizeof(request->addr));
311 request->query.vptr = query->vptr;
312 request->query.callback = query->callback;
313 request->state = REQ_IDLE;
315 add_dlink(&request->node, &request_list);
320 * timeout_query_list - Remove queries from the list which have been
321 * there too long without being resolved.
324 timeout_query_list(time_t now)
326 struct dlink *ptr, *next_ptr;
327 struct reslist *request;
328 time_t next_time = 0;
331 for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
333 next_ptr = ptr->next;
334 request = (struct reslist*)ptr;
335 timeout = request->sentat + request->timeout;
339 if (--request->retries <= 0)
341 (*request->query.callback)(request->query.vptr, 0);
342 rem_request(request);
347 request->sentat = now;
348 request->timeout += request->timeout;
349 resend_query(request);
353 if ((next_time == 0) || timeout < next_time)
359 return((next_time > now) ? next_time : (now + AR_TTL));
363 * timeout_resolver - check request list
366 timeout_resolver(struct Event *notused)
368 timeout_query_list(CurrentTime);
372 * delete_resolver_queries - cleanup outstanding queries
373 * for which there no longer exist clients or conf lines.
376 delete_resolver_queries(const void *vptr)
378 struct dlink *ptr, *next_ptr;
379 struct reslist *request;
381 for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
383 next_ptr = ptr->next;
384 request = (struct reslist*)ptr;
385 if (vptr == request->query.vptr)
386 rem_request(request);
391 * send_res_msg - sends msg to all nameservers found in the "_res" structure.
392 * This should reflect /etc/resolv.conf. We will get responses
393 * which arent needed but is easier than checking to see if nameserver
394 * isnt present. Returns number of messages successfully sent to
395 * nameservers or -1 if no successful sends.
398 send_res_msg(const char *msg, int len, int rcount)
402 int max_queries = IRCD_MIN(irc_nscount, rcount);
404 /* RES_PRIMARY option is not implemented
405 * if (res.options & RES_PRIMARY || 0 == max_queries)
407 if (max_queries == 0)
410 for (i = 0; i < max_queries; i++)
412 if (sendto(s_fd(&res_socket), msg, len, 0,
413 (struct sockaddr*)&(irc_nsaddr_list[i]),
414 irc_nsaddr_list[i].ss_len) == len)
422 * find_id - find a dns request id (id is determined by dn_mkquery)
424 static struct reslist *
428 struct reslist *request;
430 for (ptr = request_list.next; ptr != &request_list; ptr = ptr->next)
432 request = (struct reslist*)ptr;
434 if (request->id == id)
442 * gethost_byname_type - get host address from name
446 gethost_byname_type(const char *name, const struct DNSQuery *query, int type)
449 do_query_name(query, name, NULL, type);
453 * gethost_byname - wrapper for _type - send T_AAAA first
456 gethost_byname(const char *name, const struct DNSQuery *query)
458 gethost_byname_type(name, query, T_AAAA);
462 * gethost_byaddr - get host name from address
465 gethost_byaddr(const struct irc_ssaddr *addr, const struct DNSQuery *query)
467 do_query_number(query, addr, NULL);
471 * gethost_byinaddr - kludgy hack for IPv4-only compatibility
474 gethost_byinaddr(const struct in_addr *addr, const struct DNSQuery *query)
476 struct irc_ssaddr new_addr;
477 struct sockaddr_in *sin;
478 memset(&new_addr, 0, sizeof(new_addr));
479 sin = (struct sockaddr_in*)&new_addr.ss;
480 sin->sin_family = AF_INET;
481 memcpy(&sin->sin_addr, addr, sizeof(sin->sin_addr));
482 new_addr.ss_len = sizeof(*sin);
483 gethost_byaddr(&new_addr, query);
487 * do_query_name - nameserver lookup name
490 do_query_name(const struct DNSQuery *query, const char *name,
491 struct reslist *request, int type)
493 char host_name[HOSTLEN + 1];
495 ircd_strncpy(host_name, name, HOSTLEN);
496 add_local_domain(host_name, HOSTLEN);
500 request = make_request(query);
501 request->name = (char *)MyMalloc(strlen(host_name) + 1);
502 request->type = type;
503 strcpy(request->name, host_name);
506 request->state = REQ_AAAA;
509 request->state = REQ_A;
512 request->type = type;
513 query_name(host_name, C_IN, type, request);
517 * do_query_number - Use this to do reverse IP# lookups.
520 do_query_number(const struct DNSQuery *query, const struct irc_ssaddr *addr,
521 struct reslist *request)
524 const unsigned char *cp;
528 if (addr->ss.ss_family == AF_INET)
530 struct sockaddr_in *v4 = (struct sockaddr_in *)addr;
531 cp = (const unsigned char*)&v4->sin_addr.s_addr;
533 ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
534 "%u.%u.%u.%u.in-addr.arpa.",
535 (unsigned int)(cp[3]), (unsigned int)(cp[2]),
536 (unsigned int)(cp[1]), (unsigned int)(cp[0]));
539 else if (addr->ss.ss_family == AF_INET6)
541 struct sockaddr_in6 *v6 = (struct sockaddr_in6 *)addr;
542 cp = (const unsigned char *)&v6->sin6_addr.s6_addr;
544 if (request != NULL && request->state == REQ_INT)
549 ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
550 "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x."
551 "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.%s.",
552 (unsigned int)(cp[15]&0xf), (unsigned int)(cp[15]>>4),
553 (unsigned int)(cp[14]&0xf), (unsigned int)(cp[14]>>4),
554 (unsigned int)(cp[13]&0xf), (unsigned int)(cp[13]>>4),
555 (unsigned int)(cp[12]&0xf), (unsigned int)(cp[12]>>4),
556 (unsigned int)(cp[11]&0xf), (unsigned int)(cp[11]>>4),
557 (unsigned int)(cp[10]&0xf), (unsigned int)(cp[10]>>4),
558 (unsigned int)(cp[9]&0xf), (unsigned int)(cp[9]>>4),
559 (unsigned int)(cp[8]&0xf), (unsigned int)(cp[8]>>4),
560 (unsigned int)(cp[7]&0xf), (unsigned int)(cp[7]>>4),
561 (unsigned int)(cp[6]&0xf), (unsigned int)(cp[6]>>4),
562 (unsigned int)(cp[5]&0xf), (unsigned int)(cp[5]>>4),
563 (unsigned int)(cp[4]&0xf), (unsigned int)(cp[4]>>4),
564 (unsigned int)(cp[3]&0xf), (unsigned int)(cp[3]>>4),
565 (unsigned int)(cp[2]&0xf), (unsigned int)(cp[2]>>4),
566 (unsigned int)(cp[1]&0xf), (unsigned int)(cp[1]>>4),
567 (unsigned int)(cp[0]&0xf), (unsigned int)(cp[0]>>4), intarpa);
572 request = make_request(query);
573 request->type = T_PTR;
574 memcpy(&request->addr, addr, sizeof(struct irc_ssaddr));
575 request->name = (char *)MyMalloc(HOSTLEN + 1);
578 query_name(ipbuf, C_IN, T_PTR, request);
582 * query_name - generate a query based on class, type and name.
585 query_name(const char *name, int query_class, int type,
586 struct reslist *request)
591 memset(buf, 0, sizeof(buf));
593 if ((request_len = irc_res_mkquery(name, query_class, type,
594 (unsigned char *)buf, sizeof(buf))) > 0)
596 HEADER *header = (HEADER *)buf;
602 * generate an unique id
603 * NOTE: we don't have to worry about converting this to and from
604 * network byte order, the nameserver does not interpret this value
605 * and returns it unchanged
610 header->id = (header->id + lrand48()) & 0xffff;
611 } while (find_id(header->id));
613 gettimeofday(&tv, NULL);
617 header->id = (header->id + k + tv.tv_usec) & 0xffff;
619 } while (find_id(header->id));
621 request->id = header->id;
624 request->sent += send_res_msg(buf, request_len, request->sends);
629 resend_query(struct reslist *request)
631 if (request->resend == 0)
634 switch(request->type)
637 do_query_number(NULL, &request->addr, request);
640 do_query_name(NULL, request->name, request, request->type);
644 /* didnt work, try A */
645 if (request->state == REQ_AAAA)
646 do_query_name(NULL, request->name, request, T_A);
654 * proc_answer - process name server reply
657 proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
659 char hostbuf[HOSTLEN + 100]; /* working buffer */
660 unsigned char *current; /* current position in buf */
661 int query_class; /* answer class */
662 int type; /* answer type */
663 int n; /* temp count */
665 struct sockaddr_in *v4; /* conversion */
667 struct sockaddr_in6 *v6;
669 current = (unsigned char *)buf + sizeof(HEADER);
671 for (; header->qdcount > 0; --header->qdcount)
673 if ((n = irc_dn_skipname(current, (unsigned char *)eob)) < 0)
676 current += (size_t) n + QFIXEDSZ;
680 * process each answer sent to us blech.
682 while (header->ancount > 0 && (char *)current < eob)
686 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob, current,
687 hostbuf, sizeof(hostbuf));
699 * no more answers left
704 hostbuf[HOSTLEN] = '\0';
706 /* With Address arithmetic you have to be very anal
707 * this code was not working on alpha due to that
708 * (spotted by rodder/jailbird/dianora)
710 current += (size_t) n;
712 if (!(((char *)current + ANSWER_FIXED_SIZE) < eob))
715 type = irc_ns_get16(current);
716 current += TYPE_SIZE;
718 query_class = irc_ns_get16(current);
719 current += CLASS_SIZE;
721 request->ttl = irc_ns_get32(current);
724 rd_length = irc_ns_get16(current);
725 current += RDLENGTH_SIZE;
728 * Wait to set request->type until we verify this structure
733 if (request->type != T_A)
737 * check for invalid rd_length or too many addresses
739 if (rd_length != sizeof(struct in_addr))
741 v4 = (struct sockaddr_in *)&request->addr;
742 request->addr.ss_len = sizeof(struct sockaddr_in);
743 v4->sin_family = AF_INET;
744 memcpy(&v4->sin_addr, current, sizeof(struct in_addr));
749 if (request->type != T_AAAA)
751 if (rd_length != sizeof(struct in6_addr))
753 request->addr.ss_len = sizeof(struct sockaddr_in6);
754 v6 = (struct sockaddr_in6 *)&request->addr;
755 v6->sin6_family = AF_INET6;
756 memcpy(&v6->sin6_addr, current, sizeof(struct in6_addr));
761 if (request->type != T_PTR)
763 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
764 current, hostbuf, sizeof(hostbuf));
766 return(0); /* broken message */
768 return(0); /* no more answers left */
770 ircd_strncpy(request->name, hostbuf, HOSTLEN);
774 case T_CNAME: /* first check we already havent started looking
776 if (request->type != T_PTR)
779 if (request->state == REQ_CNAME)
781 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
782 current, hostbuf, sizeof(hostbuf));
789 request->state = REQ_CNAME;
790 current += rd_length;
794 /* XXX I'd rather just throw away the entire bogus thing
795 * but its possible its just a broken nameserver with still
796 * valid answers. But lets do some rudimentary logging for now...
798 log_write(LS_RESOLVER, L_ERROR, 0, "irc_res.c bogus type %d", type);
807 * res_readreply - read a dns reply from the nameserver and process it.
810 res_readreply(struct Event *ev)
813 char buf[sizeof(HEADER) + MAXPACKET];
815 struct reslist *request = NULL;
816 struct DNSReply *reply = NULL;
819 socklen_t len = sizeof(struct irc_ssaddr);
820 struct irc_ssaddr lsin;
822 assert(ev_socket(ev) == &res_socket);
823 sock = ev_socket(ev);
825 rc = recvfrom(s_fd(sock), buf, sizeof(buf), 0, (struct sockaddr *)&lsin, &len);
826 /* Better to cast the sizeof instead of rc */
827 if (rc <= (int)(sizeof(HEADER)))
831 * convert DNS reply reader from Network byte order to CPU byte order.
833 header = (HEADER *)buf;
834 header->ancount = ntohs(header->ancount);
835 header->qdcount = ntohs(header->qdcount);
836 header->nscount = ntohs(header->nscount);
837 header->arcount = ntohs(header->arcount);
840 * response for an id which we have already received an answer for
841 * just ignore this response.
843 if (0 == (request = find_id(header->id)))
847 * check against possibly fake replies
849 if (!res_ourserver(&lsin))
852 if ((header->rcode != NO_ERRORS) || (header->ancount == 0))
854 if (SERVFAIL == header->rcode)
855 resend_query(request);
859 * If we havent already tried this, and we're looking up AAAA, try A
864 if (request->state == REQ_AAAA && request->type == T_AAAA)
866 request->timeout += 4;
867 resend_query(request);
869 else if (request->type == T_PTR && request->state != REQ_INT &&
870 request->addr.ss.ss_family == AF_INET6)
872 request->state = REQ_INT;
873 request->timeout += 4;
874 resend_query(request);
880 * If a bad error was returned, we stop here and dont send
881 * send any more (no retries granted).
883 (*request->query.callback)(request->query.vptr, 0);
884 rem_request(request);
891 * If this fails there was an error decoding the received packet,
892 * try it again and hope it works the next time.
894 answer_count = proc_answer(request, header, buf, buf + rc);
898 if (request->type == T_PTR)
900 if (request->name == NULL)
903 * got a PTR response with no name, something bogus is happening
904 * don't bother trying again, the client address doesn't resolve
906 (*request->query.callback)(request->query.vptr, reply);
907 rem_request(request);
912 * Lookup the 'authoritative' name that we were given for the
917 if (request->addr.ss.ss_family == AF_INET6)
918 gethost_byname_type(request->name, &request->query, T_AAAA);
921 gethost_byname_type(request->name, &request->query, T_A);
922 rem_request(request);
927 * got a name and address response, client resolved
929 reply = make_dnsreply(request);
930 (*request->query.callback)(request->query.vptr, (reply) ? reply : 0);
931 rem_request(request);
934 else if (!request->sent)
936 /* XXX - we got a response for a query we didn't send with a valid id?
937 * this should never happen, bail here and leave the client unresolved
941 /* XXX don't leak it */
942 rem_request(request);
946 static struct DNSReply *
947 make_dnsreply(struct reslist *request)
950 assert(request != 0);
952 cp = (struct DNSReply *)MyMalloc(sizeof(struct DNSReply));
954 DupString(cp->h_name, request->name);
955 memcpy(&cp->addr, &request->addr, sizeof(cp->addr));
960 report_dns_servers(struct Client *source_p, struct StatDesc *sd, int stat, char *param)
965 for (i = 0; i < irc_nscount; i++)
967 irc_getnameinfo((struct sockaddr *)&(irc_nsaddr_list[i]),
968 irc_nsaddr_list[i].ss_len, ipaddr, sizeof(ipaddr), NULL, 0,
970 send_reply(source_p, RPL_STATSALINE, ipaddr);
975 cres_mem(struct Client* sptr)
978 struct reslist *request;
979 size_t request_mem = 0;
980 int request_count = 0;
982 for (dlink = request_list.next; dlink != &request_list; dlink = dlink->next) {
983 request = (struct reslist*)dlink;
984 request_mem += sizeof(*request);
986 request_mem += strlen(request->name) + 1;
990 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
991 ":Resolver: requests %d(%d)", request_count, request_mem);