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.
10 * July 1999 - Rewrote a bunch of stuff here. Change hostent builder code,
11 * added callbacks and reference counting of returned hostents.
12 * --Bleep (Thomas Helvey <tomh@inxpress.net>)
14 * This was all needlessly complicated for irc. Simplified. No more hostent
15 * All we really care about is the IP -> hostname mappings. Thats all.
17 * Apr 28, 2003 --cryogen and Dianora
19 * DNS server flooding lessened, AAAA-or-A lookup removed, ip6.int support
20 * removed, various robustness fixes
22 * 2006 --jilles and nenolod
24 * Resend queries to other servers if the DNS server replies with an error or
25 * an invalid response. Also, avoid servers that return errors or invalid
28 * October 2012 --mr_flea
30 * ircd-ratbox changes for random IDs merged back in.
32 * January 2016 --kaniini
41 #error this code needs to be able to address individual octets
44 static PF res_readreply
;
46 #define MAXPACKET 1024 /* rfc sez 512 but we expand names so ... */
47 #define RES_MAXALIASES 35 /* maximum aliases allowed */
48 #define RES_MAXADDRS 35 /* maximum addresses allowed */
49 #define AR_TTL 600 /* TTL in seconds for dns cache entries */
51 /* RFC 1104/1105 wasn't very helpful about what these fields
52 * should be named, so for now, we'll just name them this way.
53 * we probably should look at what named calls them or something.
55 #define TYPE_SIZE (size_t)2
56 #define CLASS_SIZE (size_t)2
57 #define TTL_SIZE (size_t)4
58 #define RDLENGTH_SIZE (size_t)2
59 #define ANSWER_FIXED_SIZE (TYPE_SIZE + CLASS_SIZE + TTL_SIZE + RDLENGTH_SIZE)
62 struct in6_addr ipv6_addr
;
64 struct in_addr ipv4_addr
;
72 char queryname
[IRCD_RES_HOSTLEN
+ 1]; /* name currently being queried */
73 char retries
; /* retry counter */
74 char sends
; /* number of sends (>1 means resent) */
77 int lastns
; /* index of last server sent to */
78 struct rb_sockaddr_storage addr
;
80 struct DNSQuery
*query
; /* query callback for this request */
83 static rb_fde_t
*res_fd
;
84 static rb_dlink_list request_list
= { NULL
, NULL
, 0 };
85 static int ns_failure_count
[IRCD_MAXNS
]; /* timeouts and invalid/failed replies */
87 static void rem_request(struct reslist
*request
);
88 static struct reslist
*make_request(struct DNSQuery
*query
);
89 static void gethost_byname_type_fqdn(const char *name
, struct DNSQuery
*query
,
91 static void do_query_name(struct DNSQuery
*query
, const char *name
, struct reslist
*request
, int);
92 static void do_query_number(struct DNSQuery
*query
, const struct rb_sockaddr_storage
*,
93 struct reslist
*request
);
94 static void query_name(struct reslist
*request
);
95 static int send_res_msg(const char *buf
, int len
, int count
);
96 static void resend_query(struct reslist
*request
);
97 static int check_question(struct reslist
*request
, HEADER
* header
, char *buf
, char *eob
);
98 static int proc_answer(struct reslist
*request
, HEADER
* header
, char *, char *);
99 static struct reslist
*find_id(int id
);
100 static struct DNSReply
*make_dnsreply(struct reslist
*request
);
101 static uint16_t generate_random_id(void);
107 #define RES_MIN(a, b) ((a) < (b) ? (a) : (b))
112 * looks up "inp" in irc_nsaddr_list[]
114 * server ID or -1 for not found
116 * paul vixie, 29may94
117 * revised for ircd, cryogen(stu) may03
118 * slightly modified for charybdis, mr_flea oct12
121 res_ourserver(const struct rb_sockaddr_storage
*inp
)
124 const struct sockaddr_in6
*v6
;
125 const struct sockaddr_in6
*v6in
= (const struct sockaddr_in6
*)inp
;
127 const struct sockaddr_in
*v4
;
128 const struct sockaddr_in
*v4in
= (const struct sockaddr_in
*)inp
;
131 for(ns
= 0; ns
< irc_nscount
; ns
++)
133 const struct rb_sockaddr_storage
*srv
= &irc_nsaddr_list
[ns
];
135 v6
= (const struct sockaddr_in6
*)srv
;
137 v4
= (const struct sockaddr_in
*)srv
;
139 /* could probably just memcmp(srv, inp, srv.ss_len) here
140 * but we'll air on the side of caution - stu
142 switch (GET_SS_FAMILY(srv
))
146 if(GET_SS_FAMILY(srv
) == GET_SS_FAMILY(inp
))
147 if(v6
->sin6_port
== v6in
->sin6_port
)
148 if((memcmp(&v6
->sin6_addr
.s6_addr
, &v6in
->sin6_addr
.s6_addr
,
149 sizeof(struct in6_addr
)) == 0) ||
150 (memcmp(&v6
->sin6_addr
.s6_addr
, &in6addr_any
,
151 sizeof(struct in6_addr
)) == 0))
156 if(GET_SS_FAMILY(srv
) == GET_SS_FAMILY(inp
))
157 if(v4
->sin_port
== v4in
->sin_port
)
158 if((v4
->sin_addr
.s_addr
== INADDR_ANY
)
159 || (v4
->sin_addr
.s_addr
== v4in
->sin_addr
.s_addr
))
171 * timeout_query_list - Remove queries from the list which have been
172 * there too long without being resolved.
174 static time_t timeout_query_list(time_t now
)
177 rb_dlink_node
*next_ptr
;
178 struct reslist
*request
;
179 time_t next_time
= 0;
182 RB_DLINK_FOREACH_SAFE(ptr
, next_ptr
, request_list
.head
)
185 timeout
= request
->sentat
+ request
->timeout
;
189 ns_failure_count
[request
->lastns
]++;
190 request
->sentat
= now
;
191 request
->timeout
+= request
->timeout
;
192 resend_query(request
);
195 if ((next_time
== 0) || timeout
< next_time
)
201 return (next_time
> now
) ? next_time
: (now
+ AR_TTL
);
205 * timeout_resolver - check request list
207 static void timeout_resolver(void *notused
)
209 timeout_query_list(rb_current_time());
212 static struct ev_entry
*timeout_resolver_ev
= NULL
;
215 * start_resolver - do everything we need to read the resolv.conf file
216 * and initialize the resolver file descriptor if needed
218 static void start_resolver(void)
223 for (i
= 0; i
< irc_nscount
; i
++)
224 ns_failure_count
[i
] = 0;
228 if ((res_fd
= rb_socket(GET_SS_FAMILY(&irc_nsaddr_list
[0]), SOCK_DGRAM
, 0,
229 "UDP resolver socket")) == NULL
)
232 /* At the moment, the resolver FD data is global .. */
233 rb_setselect(res_fd
, RB_SELECT_READ
, res_readreply
, NULL
);
234 timeout_resolver_ev
= rb_event_add("timeout_resolver", timeout_resolver
, NULL
, 1);
239 * init_resolver - initialize resolver and resolver library
241 void init_resolver(void)
244 srand48(rb_current_time());
250 * restart_resolver - reread resolv.conf, reopen socket
252 void restart_resolver(void)
256 rb_event_delete(timeout_resolver_ev
); /* -ddosen */
261 * add_local_domain - Add the domain to hostname, if it is missing
262 * (as suggested by eps@TOASTER.SFSU.EDU)
264 void add_local_domain(char *hname
, size_t size
)
266 /* try to fix up unqualified names */
267 if (strchr(hname
, '.') == NULL
)
271 size_t len
= strlen(hname
);
273 if ((strlen(irc_domain
) + len
+ 2) < size
)
276 strcpy(hname
+ len
, irc_domain
);
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.
287 static void rem_request(struct reslist
*request
)
289 rb_dlinkDelete(&request
->node
, &request_list
);
290 rb_free(request
->name
);
295 * make_request - Create a DNS request record for the server.
297 static struct reslist
*make_request(struct DNSQuery
*query
)
299 struct reslist
*request
= rb_malloc(sizeof(struct reslist
));
301 request
->sentat
= rb_current_time();
302 request
->retries
= 3;
303 request
->timeout
= 4; /* start at 4 and exponential inc. */
304 request
->query
= query
;
307 * generate a unique id
308 * NOTE: we don't have to worry about converting this to and from
309 * network byte order, the nameserver does not interpret this value
310 * and returns it unchanged
312 * we generate an id per request now (instead of per send) to allow
313 * late replies to be used.
315 request
->id
= generate_random_id();
317 rb_dlinkAdd(request
, &request
->node
, &request_list
);
323 * retryfreq - determine how many queries to wait before resending
324 * if there have been that many consecutive timeouts
326 * This is a cubic backoff btw, if anyone didn't pick up on it. --Elizafox
328 static int retryfreq(int timeouts
)
346 * send_res_msg - sends msg to a nameserver.
347 * This should reflect /etc/resolv.conf.
348 * Returns number of nameserver successfully sent to
349 * or -1 if no successful sends.
351 static int send_res_msg(const char *msg
, int len
, int rcount
)
358 /* First try a nameserver that seems to work.
359 * Every once in a while, try a possibly broken one to check
360 * if it is working again.
362 for (i
= 0; i
< irc_nscount
; i
++)
364 ns
= (i
+ rcount
- 1) % irc_nscount
;
365 if (ns_failure_count
[ns
] && retrycnt
% retryfreq(ns_failure_count
[ns
]))
367 if (sendto(rb_get_fd(res_fd
), msg
, len
, 0,
368 (struct sockaddr
*)&(irc_nsaddr_list
[ns
]),
369 GET_SS_LEN(&irc_nsaddr_list
[ns
])) == len
)
373 /* No known working nameservers, try some broken one. */
374 for (i
= 0; i
< irc_nscount
; i
++)
376 ns
= (i
+ rcount
- 1) % irc_nscount
;
377 if (!ns_failure_count
[ns
])
379 if (sendto(rb_get_fd(res_fd
), msg
, len
, 0,
380 (struct sockaddr
*)&(irc_nsaddr_list
[ns
]),
381 GET_SS_LEN(&irc_nsaddr_list
[ns
])) == len
)
389 * find_id - find a dns request id (id is determined by dn_mkquery)
391 static struct reslist
*find_id(int id
)
394 struct reslist
*request
;
396 RB_DLINK_FOREACH(ptr
, request_list
.head
)
400 if (request
->id
== id
)
408 generate_random_id(void)
414 rb_get_random(&id
, sizeof(id
));
423 * gethost_byname_type - get host address from name, adding domain if needed
425 void gethost_byname_type(const char *name
, struct DNSQuery
*query
, int type
)
427 char fqdn
[IRCD_RES_HOSTLEN
+ 1];
430 rb_strlcpy(fqdn
, name
, sizeof fqdn
);
431 add_local_domain(fqdn
, IRCD_RES_HOSTLEN
);
432 gethost_byname_type_fqdn(fqdn
, query
, type
);
436 * gethost_byname_type_fqdn - get host address from fqdn
438 static void gethost_byname_type_fqdn(const char *name
, struct DNSQuery
*query
,
442 do_query_name(query
, name
, NULL
, type
);
446 * gethost_byaddr - get host name from address
448 void gethost_byaddr(const struct rb_sockaddr_storage
*addr
, struct DNSQuery
*query
)
450 do_query_number(query
, addr
, NULL
);
454 * do_query_name - nameserver lookup name
456 static void do_query_name(struct DNSQuery
*query
, const char *name
, struct reslist
*request
,
461 request
= make_request(query
);
462 request
->name
= rb_strdup(name
);
465 rb_strlcpy(request
->queryname
, name
, sizeof(request
->queryname
));
466 request
->type
= type
;
470 /* Build an rDNS style query - if suffix is NULL, use the appropriate .arpa zone */
471 void build_rdns(char *buf
, size_t size
, const struct rb_sockaddr_storage
*addr
, const char *suffix
)
473 const unsigned char *cp
;
475 if (GET_SS_FAMILY(addr
) == AF_INET
)
477 const struct sockaddr_in
*v4
= (const struct sockaddr_in
*)addr
;
478 cp
= (const unsigned char *)&v4
->sin_addr
.s_addr
;
480 (void) snprintf(buf
, size
, "%u.%u.%u.%u.%s",
481 (unsigned int)(cp
[3]),
482 (unsigned int)(cp
[2]),
483 (unsigned int)(cp
[1]),
484 (unsigned int)(cp
[0]),
485 suffix
== NULL
? "in-addr.arpa" : suffix
);
488 else if (GET_SS_FAMILY(addr
) == AF_INET6
)
490 const struct sockaddr_in6
*v6
= (const struct sockaddr_in6
*)addr
;
491 cp
= (const unsigned char *)&v6
->sin6_addr
.s6_addr
;
493 (void) snprintf(buf
, size
,
494 "%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%s",
495 (unsigned int)(cp
[15] & 0xf), (unsigned int)(cp
[15] >> 4),
496 (unsigned int)(cp
[14] & 0xf), (unsigned int)(cp
[14] >> 4),
497 (unsigned int)(cp
[13] & 0xf), (unsigned int)(cp
[13] >> 4),
498 (unsigned int)(cp
[12] & 0xf), (unsigned int)(cp
[12] >> 4),
499 (unsigned int)(cp
[11] & 0xf), (unsigned int)(cp
[11] >> 4),
500 (unsigned int)(cp
[10] & 0xf), (unsigned int)(cp
[10] >> 4),
501 (unsigned int)(cp
[9] & 0xf), (unsigned int)(cp
[9] >> 4),
502 (unsigned int)(cp
[8] & 0xf), (unsigned int)(cp
[8] >> 4),
503 (unsigned int)(cp
[7] & 0xf), (unsigned int)(cp
[7] >> 4),
504 (unsigned int)(cp
[6] & 0xf), (unsigned int)(cp
[6] >> 4),
505 (unsigned int)(cp
[5] & 0xf), (unsigned int)(cp
[5] >> 4),
506 (unsigned int)(cp
[4] & 0xf), (unsigned int)(cp
[4] >> 4),
507 (unsigned int)(cp
[3] & 0xf), (unsigned int)(cp
[3] >> 4),
508 (unsigned int)(cp
[2] & 0xf), (unsigned int)(cp
[2] >> 4),
509 (unsigned int)(cp
[1] & 0xf), (unsigned int)(cp
[1] >> 4),
510 (unsigned int)(cp
[0] & 0xf), (unsigned int)(cp
[0] >> 4),
511 suffix
== NULL
? "ip6.arpa" : suffix
);
517 * do_query_number - Use this to do reverse IP# lookups.
519 static void do_query_number(struct DNSQuery
*query
, const struct rb_sockaddr_storage
*addr
,
520 struct reslist
*request
)
524 request
= make_request(query
);
525 memcpy(&request
->addr
, addr
, sizeof(struct rb_sockaddr_storage
));
526 request
->name
= (char *)rb_malloc(IRCD_RES_HOSTLEN
+ 1);
529 build_rdns(request
->queryname
, IRCD_RES_HOSTLEN
+ 1, addr
, NULL
);
531 request
->type
= T_PTR
;
536 * query_name - generate a query based on class, type and name.
538 static void query_name(struct reslist
*request
)
544 memset(buf
, 0, sizeof(buf
));
547 irc_res_mkquery(request
->queryname
, C_IN
, request
->type
, (unsigned char *)buf
, sizeof(buf
))) > 0)
549 HEADER
*header
= (HEADER
*)(void *)buf
;
550 header
->id
= request
->id
;
553 ns
= send_res_msg(buf
, request_len
, request
->sends
);
555 request
->lastns
= ns
;
559 static void resend_query(struct reslist
*request
)
561 if (--request
->retries
<= 0)
563 (*request
->query
->callback
) (request
->query
->ptr
, NULL
);
564 rem_request(request
);
568 switch (request
->type
)
571 do_query_number(NULL
, &request
->addr
, request
);
577 do_query_name(NULL
, request
->name
, request
, request
->type
);
585 * check_question - check if the reply really belongs to the
586 * name we queried (to guard against late replies from previous
587 * queries with the same id).
589 static int check_question(struct reslist
*request
, HEADER
* header
, char *buf
, char *eob
)
591 char hostbuf
[IRCD_RES_HOSTLEN
+ 1]; /* working buffer */
592 unsigned char *current
; /* current position in buf */
593 int n
; /* temp count */
595 current
= (unsigned char *)buf
+ sizeof(HEADER
);
596 if (header
->qdcount
!= 1)
598 n
= irc_dn_expand((unsigned char *)buf
, (unsigned char *)eob
, current
, hostbuf
,
602 if (rb_strcasecmp(hostbuf
, request
->queryname
))
608 * proc_answer - process name server reply
610 static int proc_answer(struct reslist
*request
, HEADER
* header
, char *buf
, char *eob
)
612 char hostbuf
[IRCD_RES_HOSTLEN
+ 100]; /* working buffer */
613 unsigned char *current
; /* current position in buf */
614 int type
; /* answer type */
615 int n
; /* temp count */
617 struct sockaddr_in
*v4
; /* conversion */
619 struct sockaddr_in6
*v6
;
621 current
= (unsigned char *)buf
+ sizeof(HEADER
);
623 for (; header
->qdcount
> 0; --header
->qdcount
)
625 if ((n
= irc_dn_skipname(current
, (unsigned char *)eob
)) < 0)
628 current
+= (size_t) n
+ QFIXEDSZ
;
632 * process each answer sent to us blech.
634 while (header
->ancount
> 0 && (char *)current
< eob
)
638 n
= irc_dn_expand((unsigned char *)buf
, (unsigned char *)eob
, current
, hostbuf
,
651 * no more answers left
656 hostbuf
[IRCD_RES_HOSTLEN
] = '\0';
658 /* With Address arithmetic you have to be very anal
659 * this code was not working on alpha due to that
660 * (spotted by rodder/jailbird/dianora)
662 current
+= (size_t) n
;
664 if (!(((char *)current
+ ANSWER_FIXED_SIZE
) < eob
))
667 type
= irc_ns_get16(current
);
668 current
+= TYPE_SIZE
;
670 (void) irc_ns_get16(current
);
671 current
+= CLASS_SIZE
;
673 request
->ttl
= irc_ns_get32(current
);
676 rd_length
= irc_ns_get16(current
);
677 current
+= RDLENGTH_SIZE
;
680 * Wait to set request->type until we verify this structure
685 if (request
->type
!= T_A
)
689 * check for invalid rd_length or too many addresses
691 if (rd_length
!= sizeof(struct in_addr
))
693 v4
= (struct sockaddr_in
*)&request
->addr
;
694 SET_SS_LEN(&request
->addr
, sizeof(struct sockaddr_in
));
695 v4
->sin_family
= AF_INET
;
696 memcpy(&v4
->sin_addr
, current
, sizeof(struct in_addr
));
701 if (request
->type
!= T_AAAA
)
703 if (rd_length
!= sizeof(struct in6_addr
))
705 SET_SS_LEN(&request
->addr
, sizeof(struct sockaddr_in6
));
706 v6
= (struct sockaddr_in6
*)&request
->addr
;
707 v6
->sin6_family
= AF_INET6
;
708 memcpy(&v6
->sin6_addr
, current
, sizeof(struct in6_addr
));
713 if (request
->type
!= T_PTR
)
715 n
= irc_dn_expand((unsigned char *)buf
, (unsigned char *)eob
, current
,
716 hostbuf
, sizeof(hostbuf
));
718 return (0); /* broken message */
720 return (0); /* no more answers left */
722 rb_strlcpy(request
->name
, hostbuf
, IRCD_RES_HOSTLEN
+ 1);
727 /* real answer will follow */
728 current
+= rd_length
;
739 * res_read_single_reply - read a dns reply from the nameserver and process it.
740 * Return value: 1 if a packet was read, 0 otherwise
742 static int res_read_single_reply(rb_fde_t
*F
, void *data
)
744 char buf
[sizeof(HEADER
) + MAXPACKET
]
745 /* Sparc and alpha need 16bit-alignment for accessing header->id
746 * (which is uint16_t). Because of the header = (HEADER*) buf;
747 * lateron, this is neeeded. --FaUl
749 #if defined(__sparc__) || defined(__alpha__)
750 __attribute__ ((aligned(16)))
754 struct reslist
*request
= NULL
;
755 struct DNSReply
*reply
= NULL
;
758 socklen_t len
= sizeof(struct rb_sockaddr_storage
);
759 struct rb_sockaddr_storage lsin
;
762 rc
= recvfrom(rb_get_fd(F
), buf
, sizeof(buf
), 0, (struct sockaddr
*)&lsin
, &len
);
765 if (rc
== 0 || rc
== -1)
769 if (rc
<= (int)(sizeof(HEADER
)))
773 * convert DNS reply reader from Network byte order to CPU byte order.
775 header
= (HEADER
*)(void *)buf
;
776 header
->ancount
= ntohs(header
->ancount
);
777 header
->qdcount
= ntohs(header
->qdcount
);
778 header
->nscount
= ntohs(header
->nscount
);
779 header
->arcount
= ntohs(header
->arcount
);
782 * response for an id which we have already received an answer for
783 * just ignore this response.
785 if (0 == (request
= find_id(header
->id
)))
789 * check against possibly fake replies
791 ns
= res_ourserver(&lsin
);
795 if (ns
!= request
->lastns
)
798 * We'll accept the late reply, but penalize it a little more to make
799 * sure a laggy server doesn't end up favored.
801 ns_failure_count
[ns
] += 3;
805 if (!check_question(request
, header
, buf
, buf
+ rc
))
808 if ((header
->rcode
!= NO_ERRORS
) || (header
->ancount
== 0))
811 * RFC 2136 states that in the event of a server returning SERVFAIL
812 * or NOTIMP, the request should be resent to the next server.
813 * Additionally, if the server refuses our query, resend it as well.
816 if (SERVFAIL
== header
->rcode
|| NOTIMP
== header
->rcode
||
817 REFUSED
== header
->rcode
)
819 ns_failure_count
[ns
]++;
820 resend_query(request
);
825 * Either a fatal error was returned or no answer. Cancel the
828 if (NXDOMAIN
== header
->rcode
)
830 /* If the rcode is NXDOMAIN, treat it as a good response. */
831 ns_failure_count
[ns
] /= 4;
833 (*request
->query
->callback
) (request
->query
->ptr
, NULL
);
834 rem_request(request
);
839 * If this fails there was an error decoding the received packet.
842 answer_count
= proc_answer(request
, header
, buf
, buf
+ rc
);
846 if (request
->type
== T_PTR
)
848 if (request
->name
== NULL
)
851 * Got a PTR response with no name, something strange is
852 * happening. Try another DNS server.
854 ns_failure_count
[ns
]++;
855 resend_query(request
);
860 * Lookup the 'authoritative' name that we were given for the
864 if (GET_SS_FAMILY(&request
->addr
) == AF_INET6
)
865 gethost_byname_type_fqdn(request
->name
, request
->query
, T_AAAA
);
868 gethost_byname_type_fqdn(request
->name
, request
->query
, T_A
);
869 rem_request(request
);
874 * got a name and address response, client resolved
876 reply
= make_dnsreply(request
);
877 (*request
->query
->callback
) (request
->query
->ptr
, reply
);
879 rem_request(request
);
882 ns_failure_count
[ns
] /= 4;
886 /* Invalid or corrupt reply - try another resolver. */
887 ns_failure_count
[ns
]++;
888 resend_query(request
);
894 res_readreply(rb_fde_t
*F
, void *data
)
896 while (res_read_single_reply(F
, data
))
898 rb_setselect(F
, RB_SELECT_READ
, res_readreply
, NULL
);
901 static struct DNSReply
*
902 make_dnsreply(struct reslist
*request
)
905 lrb_assert(request
!= 0);
907 cp
= (struct DNSReply
*)rb_malloc(sizeof(struct DNSReply
));
909 cp
->h_name
= request
->name
;
910 memcpy(&cp
->addr
, &request
->addr
, sizeof(cp
->addr
));