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);
173 * init_resolver - initialize resolver and resolver library
180 return(s_fd(&res_socket));
184 * restart_resolver - reread resolv.conf, reopen socket
187 restart_resolver(void)
193 * add_local_domain - Add the domain to hostname, if it is missing
194 * (as suggested by eps@TOASTER.SFSU.EDU)
197 add_local_domain(char* hname, size_t size)
199 /* try to fix up unqualified names
201 if (strchr(hname, '.') == NULL)
205 size_t len = strlen(hname);
207 if ((strlen(irc_domain) + len + 2) < size)
210 strcpy(hname + len, irc_domain);
217 * add_dlink - add a link to a doubly linked list
220 add_dlink(struct dlink *node, struct dlink *next)
222 node->prev = next->prev;
224 node->prev->next = node;
225 node->next->prev = node;
229 * rem_request - remove a request from the list.
230 * This must also free any memory that has been allocated for
231 * temporary storage of DNS results.
234 rem_request(struct reslist *request)
236 /* remove from dlist */
237 request->node.prev->next = request->node.next;
238 request->node.next->prev = request->node.prev;
240 MyFree(request->name);
245 * make_request - Create a DNS request record for the server.
247 static struct reslist *
248 make_request(const struct DNSQuery* query)
250 struct reslist *request;
252 request = (struct reslist *)MyMalloc(sizeof(struct reslist));
253 memset(request, 0, sizeof(struct reslist));
255 request->sentat = CurrentTime;
256 request->retries = feature_int(FEAT_IRCD_RES_RETRIES);
258 request->timeout = feature_int(FEAT_IRCD_RES_TIMEOUT);
259 memset(&request->addr, 0, sizeof(request->addr));
260 request->query.vptr = query->vptr;
261 request->query.callback = query->callback;
262 request->state = REQ_IDLE;
264 add_dlink(&request->node, &request_list);
269 * check_resolver_timeout - Make sure that a timeout event will
270 * happen by the given time.
273 check_resolver_timeout(time_t when)
275 if (when > CurrentTime + AR_TTL)
276 when = CurrentTime + AR_TTL;
277 if (!t_active(&res_timeout))
278 timer_add(&res_timeout, timeout_resolver, NULL, TT_ABSOLUTE, when);
279 else if (when < t_expire(&res_timeout))
280 timer_chg(&res_timeout, TT_ABSOLUTE, when);
284 * timeout_resolver - Remove queries from the list which have been
285 * there too long without being resolved.
288 timeout_resolver(struct Event *notused)
290 struct dlink *ptr, *next_ptr;
291 struct reslist *request;
292 time_t next_time = 0;
295 for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
297 next_ptr = ptr->next;
298 request = (struct reslist*)ptr;
299 timeout = request->sentat + request->timeout;
301 if (CurrentTime >= timeout)
303 if (--request->retries <= 0)
305 Debug((DEBUG_DNS, "Request %p out of retries; destroying", request));
306 (*request->query.callback)(request->query.vptr, 0);
307 rem_request(request);
312 request->sentat = CurrentTime;
313 request->timeout += request->timeout;
314 resend_query(request);
318 if ((next_time == 0) || timeout < next_time)
324 if (next_time <= CurrentTime)
325 next_time = CurrentTime + AR_TTL;
326 check_resolver_timeout(next_time);
330 * delete_resolver_queries - cleanup outstanding queries
331 * for which there no longer exist clients or conf lines.
334 delete_resolver_queries(const void *vptr)
336 struct dlink *ptr, *next_ptr;
337 struct reslist *request;
339 for (ptr = request_list.next; ptr != &request_list; ptr = next_ptr)
341 next_ptr = ptr->next;
342 request = (struct reslist*)ptr;
343 if (vptr == request->query.vptr) {
344 Debug((DEBUG_DNS, "Removing request %p with vptr %p", request, vptr));
345 rem_request(request);
351 * send_res_msg - sends msg to all nameservers found in the "_res" structure.
352 * This should reflect /etc/resolv.conf. We will get responses
353 * which arent needed but is easier than checking to see if nameserver
354 * isnt present. Returns number of messages successfully sent to
355 * nameservers or -1 if no successful sends.
358 send_res_msg(const char *msg, int len, int rcount)
362 int max_queries = IRCD_MIN(irc_nscount, rcount);
364 /* RES_PRIMARY option is not implemented
365 * if (res.options & RES_PRIMARY || 0 == max_queries)
367 if (max_queries == 0)
370 for (i = 0; i < max_queries; i++)
371 if (os_sendto_nonb(s_fd(&res_socket), msg, len, NULL, 0, &irc_nsaddr_list[i]) == IO_SUCCESS)
378 * find_id - find a dns request id (id is determined by dn_mkquery)
380 static struct reslist *
384 struct reslist *request;
386 for (ptr = request_list.next; ptr != &request_list; ptr = ptr->next)
388 request = (struct reslist*)ptr;
390 if (request->id == id) {
391 Debug((DEBUG_DNS, "find_id(%d) -> %p", id, request));
396 Debug((DEBUG_DNS, "find_id(%d) -> NULL", id));
401 * gethost_byname - wrapper for _type - send T_AAAA first
404 gethost_byname(const char *name, const struct DNSQuery *query)
406 do_query_name(query, name, NULL, T_AAAA);
410 * gethost_byaddr - get host name from address
413 gethost_byaddr(const struct irc_in_addr *addr, const struct DNSQuery *query)
415 do_query_number(query, addr, NULL);
419 * do_query_name - nameserver lookup name
422 do_query_name(const struct DNSQuery *query, const char *name,
423 struct reslist *request, int type)
425 char host_name[HOSTLEN + 1];
427 ircd_strncpy(host_name, name, HOSTLEN);
428 add_local_domain(host_name, HOSTLEN);
432 request = make_request(query);
433 request->name = (char *)MyMalloc(strlen(host_name) + 1);
434 request->type = type;
435 strcpy(request->name, host_name);
438 request->state = REQ_AAAA;
441 request->state = REQ_A;
444 request->type = type;
445 Debug((DEBUG_DNS, "Requesting DNS %s %s as %p", (request->state == REQ_AAAA ? "AAAA" : "A"), host_name, request));
446 query_name(host_name, C_IN, type, request);
450 * do_query_number - Use this to do reverse IP# lookups.
453 do_query_number(const struct DNSQuery *query, const struct irc_in_addr *addr,
454 struct reslist *request)
457 const unsigned char *cp;
459 if (irc_in_addr_is_ipv4(addr))
461 cp = (const unsigned char*)&addr->in6_16[6];
462 ircd_snprintf(NULL, ipbuf, sizeof(ipbuf), "%u.%u.%u.%u.in-addr.arpa.",
463 (unsigned int)(cp[3]), (unsigned int)(cp[2]),
464 (unsigned int)(cp[1]), (unsigned int)(cp[0]));
470 if (request != NULL && request->state == REQ_INT)
475 cp = (const unsigned char *)&addr->in6_16[0];
476 ircd_snprintf(NULL, ipbuf, sizeof(ipbuf),
477 "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x."
478 "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.ip6.%s.",
479 (unsigned int)(cp[15]&0xf), (unsigned int)(cp[15]>>4),
480 (unsigned int)(cp[14]&0xf), (unsigned int)(cp[14]>>4),
481 (unsigned int)(cp[13]&0xf), (unsigned int)(cp[13]>>4),
482 (unsigned int)(cp[12]&0xf), (unsigned int)(cp[12]>>4),
483 (unsigned int)(cp[11]&0xf), (unsigned int)(cp[11]>>4),
484 (unsigned int)(cp[10]&0xf), (unsigned int)(cp[10]>>4),
485 (unsigned int)(cp[9]&0xf), (unsigned int)(cp[9]>>4),
486 (unsigned int)(cp[8]&0xf), (unsigned int)(cp[8]>>4),
487 (unsigned int)(cp[7]&0xf), (unsigned int)(cp[7]>>4),
488 (unsigned int)(cp[6]&0xf), (unsigned int)(cp[6]>>4),
489 (unsigned int)(cp[5]&0xf), (unsigned int)(cp[5]>>4),
490 (unsigned int)(cp[4]&0xf), (unsigned int)(cp[4]>>4),
491 (unsigned int)(cp[3]&0xf), (unsigned int)(cp[3]>>4),
492 (unsigned int)(cp[2]&0xf), (unsigned int)(cp[2]>>4),
493 (unsigned int)(cp[1]&0xf), (unsigned int)(cp[1]>>4),
494 (unsigned int)(cp[0]&0xf), (unsigned int)(cp[0]>>4), intarpa);
498 request = make_request(query);
499 request->type = T_PTR;
500 memcpy(&request->addr, addr, sizeof(request->addr));
501 request->name = (char *)MyMalloc(HOSTLEN + 1);
503 Debug((DEBUG_DNS, "Requesting DNS PTR %s as %p", ipbuf, request));
504 query_name(ipbuf, C_IN, T_PTR, request);
508 * query_name - generate a query based on class, type and name.
511 query_name(const char *name, int query_class, int type,
512 struct reslist *request)
517 memset(buf, 0, sizeof(buf));
519 if ((request_len = irc_res_mkquery(name, query_class, type,
520 (unsigned char *)buf, sizeof(buf))) > 0)
522 HEADER *header = (HEADER *)buf;
525 * generate an unique id
526 * NOTE: we don't have to worry about converting this to and from
527 * network byte order, the nameserver does not interpret this value
528 * and returns it unchanged
532 header->id = (header->id + rand()) & 0xffff;
533 } while (find_id(header->id));
534 request->id = header->id;
537 request->sent += send_res_msg(buf, request_len, request->sends);
538 check_resolver_timeout(request->sentat + request->timeout);
543 resend_query(struct reslist *request)
545 if (request->resend == 0)
548 switch(request->type)
551 do_query_number(NULL, &request->addr, request);
554 do_query_name(NULL, request->name, request, request->type);
557 /* didnt work, try A */
558 if (request->state == REQ_AAAA)
559 do_query_name(NULL, request->name, request, T_A);
566 * proc_answer - process name server reply
569 proc_answer(struct reslist *request, HEADER* header, char* buf, char* eob)
571 char hostbuf[HOSTLEN + 100]; /* working buffer */
572 unsigned char *current; /* current position in buf */
573 int query_class; /* answer class */
574 int type; /* answer type */
575 int n; /* temp count */
578 current = (unsigned char *)buf + sizeof(HEADER);
580 for (; header->qdcount > 0; --header->qdcount)
582 if ((n = irc_dn_skipname(current, (unsigned char *)eob)) < 0)
585 current += (size_t) n + QFIXEDSZ;
589 * process each answer sent to us blech.
591 while (header->ancount > 0 && (char *)current < eob)
595 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob, current,
596 hostbuf, sizeof(hostbuf));
608 * no more answers left
613 hostbuf[HOSTLEN] = '\0';
615 /* With Address arithmetic you have to be very anal
616 * this code was not working on alpha due to that
617 * (spotted by rodder/jailbird/dianora)
619 current += (size_t) n;
621 if (!(((char *)current + ANSWER_FIXED_SIZE) < eob))
624 type = irc_ns_get16(current);
625 current += TYPE_SIZE;
627 query_class = irc_ns_get16(current);
628 current += CLASS_SIZE;
630 request->ttl = irc_ns_get32(current);
633 rd_length = irc_ns_get16(current);
634 current += RDLENGTH_SIZE;
637 * Wait to set request->type until we verify this structure
642 if (request->type != T_A)
646 * check for invalid rd_length or too many addresses
648 if (rd_length != sizeof(struct in_addr))
650 memset(&request->addr, 0, sizeof(request->addr));
651 memcpy(&request->addr.in6_16[6], current, sizeof(struct in_addr));
655 if (request->type != T_AAAA)
657 if (rd_length != sizeof(struct irc_in_addr))
659 memcpy(&request->addr, current, sizeof(struct irc_in_addr));
663 if (request->type != T_PTR)
665 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
666 current, hostbuf, sizeof(hostbuf));
668 return(0); /* broken message */
670 return(0); /* no more answers left */
672 ircd_strncpy(request->name, hostbuf, HOSTLEN);
676 case T_CNAME: /* first check we already havent started looking
678 if (request->type != T_PTR)
681 if (request->state == REQ_CNAME)
683 n = irc_dn_expand((unsigned char *)buf, (unsigned char *)eob,
684 current, hostbuf, sizeof(hostbuf));
691 request->state = REQ_CNAME;
692 current += rd_length;
696 /* XXX I'd rather just throw away the entire bogus thing
697 * but its possible its just a broken nameserver with still
698 * valid answers. But lets do some rudimentary logging for now...
700 log_write(LS_RESOLVER, L_ERROR, 0, "irc_res.c bogus type %d", type);
709 * res_readreply - read a dns reply from the nameserver and process it.
712 res_readreply(struct Event *ev)
714 struct irc_sockaddr lsin;
716 char buf[sizeof(HEADER) + MAXPACKET];
718 struct reslist *request = NULL;
719 struct DNSReply *reply = NULL;
723 assert(ev_socket(ev) == &res_socket);
724 sock = ev_socket(ev);
726 if (IO_SUCCESS != os_recvfrom_nonb(s_fd(sock), buf, sizeof(buf), &rc, &lsin)
727 || (rc <= sizeof(HEADER)))
731 * convert DNS reply reader from Network byte order to CPU byte order.
733 header = (HEADER *)buf;
734 header->ancount = ntohs(header->ancount);
735 header->qdcount = ntohs(header->qdcount);
736 header->nscount = ntohs(header->nscount);
737 header->arcount = ntohs(header->arcount);
740 * response for an id which we have already received an answer for
741 * just ignore this response.
743 if (0 == (request = find_id(header->id)))
747 * check against possibly fake replies
749 if (!res_ourserver(&lsin))
752 if ((header->rcode != NO_ERRORS) || (header->ancount == 0))
754 if (SERVFAIL == header->rcode)
755 resend_query(request);
759 * If we havent already tried this, and we're looking up AAAA, try A
763 if (request->state == REQ_AAAA && request->type == T_AAAA)
765 request->timeout += feature_int(FEAT_IRCD_RES_TIMEOUT);
766 resend_query(request);
768 else if (request->type == T_PTR && request->state != REQ_INT &&
769 !irc_in_addr_is_ipv4(&request->addr))
771 request->state = REQ_INT;
772 request->timeout += feature_int(FEAT_IRCD_RES_TIMEOUT);
773 resend_query(request);
778 * If a bad error was returned, we stop here and dont send
779 * send any more (no retries granted).
781 Debug((DEBUG_DNS, "Request %p has bad response (state %d type %d)", request, request->state, request->type));
782 (*request->query.callback)(request->query.vptr, 0);
783 rem_request(request);
790 * If this fails there was an error decoding the received packet,
791 * try it again and hope it works the next time.
793 answer_count = proc_answer(request, header, buf, buf + rc);
797 if (request->type == T_PTR)
799 if (request->name == NULL)
802 * got a PTR response with no name, something bogus is happening
803 * don't bother trying again, the client address doesn't resolve
805 Debug((DEBUG_DNS, "Request %p PTR had empty name", request));
806 (*request->query.callback)(request->query.vptr, reply);
807 rem_request(request);
812 * Lookup the 'authoritative' name that we were given for the
816 if (!irc_in_addr_is_ipv4(&request->addr))
817 do_query_name(&request->query, request->name, NULL, T_AAAA);
820 do_query_name(&request->query, request->name, NULL, T_A);
821 Debug((DEBUG_DNS, "Request %p switching to forward resolution", request));
822 rem_request(request);
827 * got a name and address response, client resolved
829 reply = make_dnsreply(request);
830 (*request->query.callback)(request->query.vptr, (reply) ? reply : 0);
831 Debug((DEBUG_DNS, "Request %p got forward resolution", request));
832 rem_request(request);
835 else if (!request->sent)
837 /* XXX - we got a response for a query we didn't send with a valid id?
838 * this should never happen, bail here and leave the client unresolved
842 /* XXX don't leak it */
843 Debug((DEBUG_DNS, "Request %p was unexpected(!)", request));
844 rem_request(request);
848 static struct DNSReply *
849 make_dnsreply(struct reslist *request)
852 assert(request != 0);
854 cp = (struct DNSReply *)MyMalloc(sizeof(struct DNSReply));
856 DupString(cp->h_name, request->name);
857 memcpy(&cp->addr, &request->addr, sizeof(cp->addr));
862 report_dns_servers(struct Client *source_p, const struct StatDesc *sd, char *param)
867 for (i = 0; i < irc_nscount; i++)
869 ircd_ntoa_r(ipaddr, &irc_nsaddr_list[i].addr);
870 send_reply(source_p, RPL_STATSALINE, ipaddr);
875 cres_mem(struct Client* sptr)
878 struct reslist *request;
879 size_t request_mem = 0;
880 int request_count = 0;
882 for (dlink = request_list.next; dlink != &request_list; dlink = dlink->next) {
883 request = (struct reslist*)dlink;
884 request_mem += sizeof(*request);
886 request_mem += strlen(request->name) + 1;
890 send_reply(sptr, SND_EXPLICIT | RPL_STATSDEBUG,
891 ":Resolver: requests %d(%d)", request_count, request_mem);
895 int irc_in_addr_valid(const struct irc_in_addr *addr)
900 val = addr->in6_16[0];
901 if (val != 0 || val != 0xffff)
903 for (ii = 1; ii < 8; ii++)
904 if (addr->in6_16[ii] != val)
909 int irc_in_addr_cmp(const struct irc_in_addr *a, const struct irc_in_addr *b)
911 if (irc_in_addr_is_ipv4(a))
912 return a->in6_16[6] != b->in6_16[6]
913 || a->in6_16[7] != b->in6_16[7]
914 || !irc_in_addr_is_ipv4(b);
916 return memcmp(a, b, sizeof(*a));
919 int irc_in_addr_is_loopback(const struct irc_in_addr *addr)
921 if (addr->in6_16[0] != 0
922 || addr->in6_16[1] != 0
923 || addr->in6_16[2] != 0
924 || addr->in6_16[3] != 0
925 || addr->in6_16[4] != 0)
927 if ((addr->in6_16[5] == 0xffff) || (addr->in6_16[5] == 0 && addr->in6_16[6] != 0))
928 return (ntohs(addr->in6_16[6]) & 0xff00) == 0x7f00;
930 return addr->in6_16[5] == 0 && addr->in6_16[6] == 0 && htons(addr->in6_16[7]) == 1;