2 dns.cpp - based on the firedns library Copyright (C) 2002 Ian Gulliver
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of version 2 of the GNU General Public License as
6 published by the Free Software Foundation.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include <sys/types.h>
26 #include <sys/socket.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
39 #include "helperfuncs.h"
40 #include "socketengine.h"
42 extern SocketEngine* SE;
45 #define max(a,b) (a > b ? a : b)
46 #define DNS_MAX 8 /* max number of nameservers used */
47 #define DNS_CONFIG_FBCK "/etc/resolv.conf" /* fallback config file */
48 #define DNS_PORT 53 /* DNS well known port */
49 #define DNS_QRY_A 1 /* name to IP address */
50 #define DNS_QRY_AAAA 28 /* name to IP6 address */
51 #define DNS_QRY_PTR 12 /* IP address to name */
52 #define DNS_QRY_MX 15 /* name to MX */
53 #define DNS_QRY_TXT 16 /* name to TXT */
54 #define DNS_QRY_CNAME 5
56 #define DNS_ALIGN (sizeof(void *) > sizeof(long) ? sizeof(void *) : sizeof(long))
58 #define RESULTSIZE 1024
59 #define min(a,b) (a < b ? a : b)
61 static struct in_addr servers4[DNS_MAX]; /* up to DNS_MAX nameservers; populated by dns_init() */
62 static int i4; /* actual count of nameservers; set by dns_init() */
64 static int initdone = 0; /* to ensure dns_init() only runs once (on the first call) */
65 static int wantclose = 0;
66 static int lastcreate = -1;
68 struct s_connection { /* open DNS query */
69 struct s_connection *next; /* next in list */
74 int fd; /* file descriptor returned from sockets */
81 unsigned int rdlength;
84 #define DNS_POINTER_VALUE 0xc000
86 static s_connection *connection_head = NULL; /* linked list of open DNS queries; populated by dns_add_query(), decimated by dns_getresult_s() */
88 struct s_header { /* DNS query header */
91 #define FLAGS1_MASK_QR 0x80
92 #define FLAGS1_MASK_OPCODE 0x78 /* bitshift right 3 */
93 #define FLAGS1_MASK_AA 0x04
94 #define FLAGS1_MASK_TC 0x02
95 #define FLAGS1_MASK_RD 0x01
97 #define FLAGS2_MASK_RA 0x80
98 #define FLAGS2_MASK_Z 0x70
99 #define FLAGS2_MASK_RCODE 0x0f
100 unsigned int qdcount;
101 unsigned int ancount;
102 unsigned int nscount;
103 unsigned int arcount;
104 unsigned char payload[512]; /* DNS question, populated by dns_build_query_payload() */
109 void *dns_align(void *inp) {
110 char *p = (char*)inp;
111 int offby = ((char *)p - (char *)0) % DNS_ALIGN;
113 return p + (DNS_ALIGN - offby);
119 * These little hacks are here to avoid alignment and type sizing issues completely by doing manual copies
121 void dns_fill_rr(s_rr_middle* rr, const unsigned char *input) {
122 rr->type = input[0] * 256 + input[1];
123 rr->_class = input[2] * 256 + input[3];
124 rr->ttl = input[4] * 16777216 + input[5] * 65536 + input[6] * 256 + input[7];
125 rr->rdlength = input[8] * 256 + input[9];
128 void dns_fill_header(s_header *header, const unsigned char *input, const int l) {
129 header->id[0] = input[0];
130 header->id[1] = input[1];
131 header->flags1 = input[2];
132 header->flags2 = input[3];
133 header->qdcount = input[4] * 256 + input[5];
134 header->ancount = input[6] * 256 + input[7];
135 header->nscount = input[8] * 256 + input[9];
136 header->arcount = input[10] * 256 + input[11];
137 memcpy(header->payload,&input[12],l);
140 void dns_empty_header(unsigned char *output, const s_header *header, const int l) {
141 output[0] = header->id[0];
142 output[1] = header->id[1];
143 output[2] = header->flags1;
144 output[3] = header->flags2;
145 output[4] = header->qdcount / 256;
146 output[5] = header->qdcount % 256;
147 output[6] = header->ancount / 256;
148 output[7] = header->ancount % 256;
149 output[8] = header->nscount / 256;
150 output[9] = header->nscount % 256;
151 output[10] = header->arcount / 256;
152 output[11] = header->arcount % 256;
153 memcpy(&output[12],header->payload,l);
156 void dns_close(int fd) { /* close query */
157 log(DEBUG,"DNS: dns_close on fd %d",fd);
158 if (fd == lastcreate) {
167 void DNS::dns_init() { /* on first call only: populates servers4 struct with up to DNS_MAX nameserver IP addresses from /etc/resolv.conf */
177 srand((unsigned int) TIME);
178 memset(servers4,'\0',sizeof(in_addr) * DNS_MAX);
179 f = fopen(DNS_CONFIG_FBCK,"r");
182 while (fgets(buf,1024,f) != NULL) {
183 if (strncmp(buf,"nameserver",10) == 0) {
185 while (buf[i] == ' ' || buf[i] == '\t')
188 if (dns_aton4_s(&buf[i],&addr4) != NULL)
189 memcpy(&servers4[i4++],&addr4,sizeof(in_addr));
196 void DNS::dns_init_2(const char* dnsserver)
200 srand((unsigned int) TIME);
201 memset(servers4,'\0',sizeof(in_addr) * DNS_MAX);
202 if (dns_aton4_s(dnsserver,&addr4) != NULL)
203 memcpy(&servers4[i4++],&addr4,sizeof(in_addr));
207 static int dns_send_requests(const s_header *h, const s_connection *s, const int l)
211 unsigned char payload[sizeof(s_header)];
213 dns_empty_header(payload,h,l);
218 /* otherwise send via standard ipv4 boringness */
219 memset(&addr4,0,sizeof(addr4));
220 memcpy(&addr4.sin_addr,&servers4[i],sizeof(addr4.sin_addr));
221 addr4.sin_family = AF_INET;
222 addr4.sin_port = htons(DNS_PORT);
223 if (sendto(s->fd, payload, l + 12, 0, (sockaddr *) &addr4, sizeof(addr4)) == -1)
231 static s_connection *dns_add_query(s_header *h) { /* build DNS query, add to list */
234 s = new s_connection;
236 /* set header flags */
237 h->id[0] = s->id[0] = rand() % 255; /* verified by dns_getresult_s() */
238 h->id[1] = s->id[1] = rand() % 255;
239 h->flags1 = 0 | FLAGS1_MASK_RD;
246 /* turn off want_list by default */
249 /* try to create ipv6 or ipv4 socket */
250 s->fd = socket(PF_INET, SOCK_DGRAM, 0);
252 if (fcntl(s->fd, F_SETFL, O_NONBLOCK) != 0) {
260 memset(&addr,0,sizeof(addr));
261 addr.sin_family = AF_INET;
263 addr.sin_addr.s_addr = INADDR_ANY;
264 if (bind(s->fd,(sockaddr *)&addr,sizeof(addr)) != 0) {
274 /* create new connection object, add to linked list */
275 s->next = connection_head;
278 if (wantclose == 1) {
279 shutdown(lastcreate,2);
287 static int dns_build_query_payload(const char * const name, const unsigned short rr, const unsigned short _class, unsigned char * const payload) {
289 const char * tempchr, * tempchr2;
295 /* split name up into labels, create query */
296 while ((tempchr = strchr(tempchr2,'.')) != NULL) {
297 l = tempchr - tempchr2;
298 if (payloadpos + l + 1 > 507)
300 payload[payloadpos++] = l;
301 memcpy(&payload[payloadpos],tempchr2,l);
303 tempchr2 = &tempchr[1];
305 l = strlen(tempchr2);
307 if (payloadpos + l + 2 > 507)
309 payload[payloadpos++] = l;
310 memcpy(&payload[payloadpos],tempchr2,l);
312 payload[payloadpos++] = '\0';
314 if (payloadpos > 508)
317 memcpy(&payload[payloadpos],&l,2);
319 memcpy(&payload[payloadpos + 2],&l,2);
320 return payloadpos + 4;
323 in_addr* DNS::dns_aton4(const char * const ipstring) { /* ascii to numeric: convert string to static 4part IP addr struct */
325 return dns_aton4_s(ipstring,&ip);
328 in_addr* DNS::dns_aton4_r(const char *ipstring) { /* ascii to numeric (reentrant): convert string to new 4part IP addr struct */
331 if(dns_aton4_s(ipstring,ip) == NULL) {
338 in_addr* DNS::dns_aton4_s(const char *ipstring, in_addr *ip) { /* ascii to numeric (buffered): convert string to given 4part IP addr struct */
339 inet_aton(ipstring,ip);
343 int DNS::dns_getip4(const char *name) { /* build, add and send A query; retrieve result with dns_getresult() */
351 l = dns_build_query_payload(name,DNS_QRY_A,1,(unsigned char *)&h.payload);
354 s = dns_add_query(&h);
359 if (dns_send_requests(&h,s,l) == -1)
365 int DNS::dns_getip4list(const char *name) { /* build, add and send A query; retrieve result with dns_getresult() */
373 l = dns_build_query_payload(name,DNS_QRY_A,1,(unsigned char *)&h.payload);
376 s = dns_add_query(&h);
382 if (dns_send_requests(&h,s,l) == -1)
388 int DNS::dns_getname4(const in_addr *ip) { /* build, add and send PTR query; retrieve result with dns_getresult() */
395 c = (unsigned char *)&ip->s_addr;
397 sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]);
399 l = dns_build_query_payload(query,DNS_QRY_PTR,1,(unsigned char *)&h.payload);
402 s = dns_add_query(&h);
406 s->type = DNS_QRY_PTR;
407 if (dns_send_requests(&h,s,l) == -1)
413 char* DNS::dns_ntoa4(const in_addr * const ip) { /* numeric to ascii: convert 4part IP addr struct to static string */
415 return dns_ntoa4_s(ip,r);
418 char* DNS::dns_ntoa4_s(const in_addr *ip, char *r) { /* numeric to ascii (buffered): convert 4part IP addr struct to given string */
420 m = (unsigned char *)&ip->s_addr;
421 sprintf(r,"%d.%d.%d.%d",m[0],m[1],m[2],m[3]);
425 char* DNS::dns_getresult(const int cfd) { /* retrieve result of DNS query */
426 log(DEBUG,"DNS: dns_getresult with cfd=%d",cfd);
427 return dns_getresult_s(cfd,this->localbuf);
430 char* DNS::dns_getresult_s(const int cfd, char *res) { /* retrieve result of DNS query (buffered) */
432 s_connection *c, *prev;
433 int l,i,q,curanswer,o;
435 unsigned char buffer[sizeof(s_header)];
445 while (c != NULL) { /* find query in list of open queries */
452 log(DEBUG,"DNS: got a response for a query we didnt send with fd=%d",cfd);
453 return NULL; /* query not found */
455 /* query found-- pull from list: */
457 prev->next = c->next;
459 connection_head = c->next;
461 l = recv(c->fd,buffer,sizeof(s_header),0);
467 dns_fill_header(&h,buffer,l - 12);
468 if (c->id[0] != h.id[0] || c->id[1] != h.id[1]) {
469 log(DEBUG,"DNS: id mismatch on query");
471 return NULL; /* ID mismatch */
473 if ((h.flags1 & FLAGS1_MASK_QR) == 0) {
474 log(DEBUG,"DNS: didnt get a query result");
478 if ((h.flags1 & FLAGS1_MASK_OPCODE) != 0) {
479 log(DEBUG,"DNS: got an OPCODE and didnt want one");
483 if ((h.flags2 & FLAGS2_MASK_RCODE) != 0) {
484 log(DEBUG,"DNS lookup failed due to SERVFAIL");
488 if (h.ancount < 1) { /* no sense going on if we don't have any answers */
489 log(DEBUG,"DNS: no answers!");
497 while ((unsigned)q < h.qdcount && i < l) {
498 if (h.payload[i] > 63) { /* pointer */
499 i += 6; /* skip pointer, _class and type */
502 if (h.payload[i] == 0) {
504 i += 5; /* skip nil, _class and type */
506 i += h.payload[i] + 1; /* skip length and label */
509 /* &h.payload[i] should now be the start of the first response */
511 while ((unsigned)curanswer < h.ancount) {
513 while (q == 0 && i < l) {
514 if (h.payload[i] > 63) { /* pointer */
515 i += 2; /* skip pointer */
518 if (h.payload[i] == 0) {
522 i += h.payload[i] + 1; /* skip length and label */
529 dns_fill_rr(&rr,&h.payload[i]);
531 if (rr.type != c->type) {
536 if (rr._class != c->_class) {
543 if ((unsigned)curanswer == h.ancount)
545 if ((unsigned)i + rr.rdlength > (unsigned)l)
547 if (rr.rdlength > 1023)
552 log(DEBUG,"DNS: got a result of type DNS_QRY_PTR");
555 while (q == 0 && i < l && o + 256 < 1023) {
556 if (h.payload[i] > 63) { /* pointer */
557 memcpy(&p,&h.payload[i],2);
558 i = ntohs(p) - DNS_POINTER_VALUE - 12;
560 if (h.payload[i] == 0)
566 memcpy(&res[o],&h.payload[i + 1],h.payload[i]);
568 i += h.payload[i] + 1;
575 log(DEBUG,"DNS: got a result of type DNS_QRY_A");
577 dns_ip4list *alist = (dns_ip4list *) res; /* we have to trust that this is aligned */
578 while ((char *)alist - (char *)res < 700) {
579 if (rr.type != DNS_QRY_A)
583 if (rr.rdlength != 4) {
587 memcpy(&alist->ip,&h.payload[i],4);
588 if ((unsigned)++curanswer >= h.ancount)
594 while (q == 0 && i < l) {
595 if (h.payload[i] > 63) { /* pointer */
596 i += 2; /* skip pointer */
599 if (h.payload[i] == 0) {
603 i += h.payload[i] + 1; /* skip length and label */
611 dns_fill_rr(&rr,&h.payload[i]);
613 alist->next = (dns_ip4list *) dns_align(((char *) alist) + sizeof(dns_ip4list));
624 log(DEBUG,"DNS: doing something with result 'default'");
625 memcpy(res,&h.payload[i],rr.rdlength);
626 res[rr.rdlength] = '\0';
636 log(DEBUG,"Create blank DNS");
639 DNS::DNS(std::string dnsserver)
641 dns_init_2(dnsserver.c_str());
642 log(DEBUG,"Create DNS");
645 void DNS::SetNS(std::string dnsserver)
647 dns_init_2(dnsserver.c_str());
655 bool DNS::ReverseLookup(std::string ip)
658 binip = dns_aton4(ip.c_str());
663 this->myfd = dns_getname4(binip);
664 if (this->myfd == -1)
668 log(DEBUG,"DNS: ReverseLookup, fd=%d",this->myfd);
670 SE->AddFd(this->myfd,true,X_ESTAB_DNS);
675 bool DNS::ForwardLookup(std::string host)
678 this->myfd = dns_getip4(host.c_str());
679 if (this->myfd == -1)
683 log(DEBUG,"DNS: ForwardLookup, fd=%d",this->myfd);
685 SE->AddFd(this->myfd,true,X_ESTAB_DNS);
690 bool DNS::HasResult(int fd)
692 return (fd == this->myfd);
695 /* Only the multithreaded dns uses this poll() based
696 * check now. As its in another thread we dont have
697 * to worry about its performance that much.
699 bool DNS::HasResult()
701 log(DEBUG,"DNS: HasResult, fd=%d",this->myfd);
703 polls.fd = this->myfd;
704 polls.events = POLLIN;
705 int ret = poll(&polls,1,1);
706 log(DEBUG,"DNS: Hasresult returning %d",ret);
715 std::string DNS::GetResult()
717 log(DEBUG,"DNS: GetResult()");
718 result = dns_getresult(this->myfd);
720 SE->DelFd(this->myfd);
723 stats->statsDnsGood++;
724 dns_close(this->myfd);
727 stats->statsDnsBad++;
728 if (this->myfd != -1)
730 dns_close(this->myfd);
736 std::string DNS::GetResultIP()
739 log(DEBUG,"DNS: GetResultIP()");
740 result = dns_getresult(this->myfd);
741 if (this->myfd != -1)
744 SE->DelFd(this->myfd);
746 dns_close(this->myfd);
750 stats->statsDnsGood++;
751 unsigned char a = (unsigned)result[0];
752 unsigned char b = (unsigned)result[1];
753 unsigned char c = (unsigned)result[2];
754 unsigned char d = (unsigned)result[3];
755 snprintf(r,1024,"%u.%u.%u.%u",a,b,c,d);
760 stats->statsDnsBad++;
761 log(DEBUG,"DANGER WILL ROBINSON! NXDOMAIN for forward lookup, but we got a reverse lookup!");