2 dns.cpp - based on the dns 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
23 #include <sys/types.h>
24 #include <sys/socket.h>
34 extern int statsAccept,statsRefused,statsUnknown,statsCollisions,statsDns,statsDnsGood,statsDnsBad,statsConnects,statsSent,statsRecv;
36 #define max(a,b) (a > b ? a : b)
37 #define DNS_MAX 8 /* max number of nameservers used */
38 #define DNS_CONFIG_FBCK "/etc/resolv.conf" /* fallback config file */
39 #define DNS_PORT 53 /* DNS well known port */
40 #define DNS_QRY_A 1 /* name to IP address */
41 #define DNS_QRY_AAAA 28 /* name to IP6 address */
42 #define DNS_QRY_PTR 12 /* IP address to name */
43 #define DNS_QRY_MX 15 /* name to MX */
44 #define DNS_QRY_TXT 16 /* name to TXT */
45 #define DNS_QRY_CNAME 5
47 #define DNS_ALIGN (sizeof(void *) > sizeof(long) ? sizeof(void *) : sizeof(long))
49 #define RESULTSIZE 1024
50 #define min(a,b) (a < b ? a : b)
52 static struct in_addr servers4[DNS_MAX]; /* up to DNS_MAX nameservers; populated by dns_init() */
53 static int i4; /* actual count of nameservers; set by dns_init() */
55 static int initdone = 0; /* to ensure dns_init() only runs once (on the first call) */
56 static int wantclose = 0;
57 static int lastcreate = -1;
59 struct s_connection { /* open DNS query */
60 struct s_connection *next; /* next in list */
65 int fd; /* file descriptor returned from sockets */
72 unsigned int rdlength;
75 #define DNS_POINTER_VALUE 0xc000
77 static s_connection *connection_head = NULL; /* linked list of open DNS queries; populated by dns_add_query(), decimated by dns_getresult_s() */
79 struct s_header { /* DNS query header */
82 #define FLAGS1_MASK_QR 0x80
83 #define FLAGS1_MASK_OPCODE 0x78 /* bitshift right 3 */
84 #define FLAGS1_MASK_AA 0x04
85 #define FLAGS1_MASK_TC 0x02
86 #define FLAGS1_MASK_RD 0x01
88 #define FLAGS2_MASK_RA 0x80
89 #define FLAGS2_MASK_Z 0x70
90 #define FLAGS2_MASK_RCODE 0x0f
95 unsigned char payload[512]; /* DNS question, populated by dns_build_query_payload() */
100 void *dns_align(void *inp) {
101 char *p = (char*)inp;
102 int offby = ((char *)p - (char *)0) % DNS_ALIGN;
104 return p + (DNS_ALIGN - offby);
110 * These little hacks are here to avoid alignment and type sizing issues completely by doing manual copies
112 void dns_fill_rr(s_rr_middle* rr, const unsigned char *input) {
113 rr->type = input[0] * 256 + input[1];
114 rr->_class = input[2] * 256 + input[3];
115 rr->ttl = input[4] * 16777216 + input[5] * 65536 + input[6] * 256 + input[7];
116 rr->rdlength = input[8] * 256 + input[9];
119 void dns_fill_header(s_header *header, const unsigned char *input, const int l) {
120 header->id[0] = input[0];
121 header->id[1] = input[1];
122 header->flags1 = input[2];
123 header->flags2 = input[3];
124 header->qdcount = input[4] * 256 + input[5];
125 header->ancount = input[6] * 256 + input[7];
126 header->nscount = input[8] * 256 + input[9];
127 header->arcount = input[10] * 256 + input[11];
128 memcpy(header->payload,&input[12],l);
131 void dns_empty_header(unsigned char *output, const s_header *header, const int l) {
132 output[0] = header->id[0];
133 output[1] = header->id[1];
134 output[2] = header->flags1;
135 output[3] = header->flags2;
136 output[4] = header->qdcount / 256;
137 output[5] = header->qdcount % 256;
138 output[6] = header->ancount / 256;
139 output[7] = header->ancount % 256;
140 output[8] = header->nscount / 256;
141 output[9] = header->nscount % 256;
142 output[10] = header->arcount / 256;
143 output[11] = header->arcount % 256;
144 memcpy(&output[12],header->payload,l);
147 void dns_close(int fd) { /* close query */
148 if (fd == lastcreate) {
156 void DNS::dns_init() { /* on first call only: populates servers4 struct with up to DNS_MAX nameserver IP addresses from /etc/resolv.conf */
166 srand((unsigned int) TIME);
167 memset(servers4,'\0',sizeof(in_addr) * DNS_MAX);
168 f = fopen(DNS_CONFIG_FBCK,"r");
171 while (fgets(buf,1024,f) != NULL) {
172 if (strncmp(buf,"nameserver",10) == 0) {
174 while (buf[i] == ' ' || buf[i] == '\t')
177 if (dns_aton4_s(&buf[i],&addr4) != NULL)
178 memcpy(&servers4[i4++],&addr4,sizeof(in_addr));
185 void DNS::dns_init_2(const char* dnsserver)
189 srand((unsigned int) TIME);
190 memset(servers4,'\0',sizeof(in_addr) * DNS_MAX);
191 if (dns_aton4_s(dnsserver,&addr4) != NULL)
192 memcpy(&servers4[i4++],&addr4,sizeof(in_addr));
196 static int dns_send_requests(const s_header *h, const s_connection *s, const int l)
200 unsigned char payload[sizeof(s_header)];
202 dns_empty_header(payload,h,l);
205 for (i = 0; i < i4; i++) {
206 /* otherwise send via standard ipv4 boringness */
207 memset(&addr4,0,sizeof(addr4));
208 memcpy(&addr4.sin_addr,&servers4[i],sizeof(addr4.sin_addr));
209 addr4.sin_family = AF_INET;
210 addr4.sin_port = htons(DNS_PORT);
211 if (sendto(s->fd, payload, l + 12, 0, (sockaddr *) &addr4, sizeof(addr4)) == -1)
220 static s_connection *dns_add_query(s_header *h) { /* build DNS query, add to list */
223 s = new s_connection;
225 /* set header flags */
226 h->id[0] = s->id[0] = rand() % 255; /* verified by dns_getresult_s() */
227 h->id[1] = s->id[1] = rand() % 255;
228 h->flags1 = 0 | FLAGS1_MASK_RD;
235 /* turn off want_list by default */
238 /* try to create ipv6 or ipv4 socket */
239 s->fd = socket(PF_INET, SOCK_DGRAM, 0);
241 if (fcntl(s->fd, F_SETFL, O_NONBLOCK) != 0) {
248 memset(&addr,0,sizeof(addr));
249 addr.sin_family = AF_INET;
251 addr.sin_addr.s_addr = INADDR_ANY;
252 if (bind(s->fd,(sockaddr *)&addr,sizeof(addr)) != 0) {
261 /* create new connection object, add to linked list */
262 s->next = connection_head;
265 if (wantclose == 1) {
273 static int dns_build_query_payload(const char * const name, const unsigned short rr, const unsigned short _class, unsigned char * const payload) {
275 const char * tempchr, * tempchr2;
281 /* split name up into labels, create query */
282 while ((tempchr = strchr(tempchr2,'.')) != NULL) {
283 l = tempchr - tempchr2;
284 if (payloadpos + l + 1 > 507)
286 payload[payloadpos++] = l;
287 memcpy(&payload[payloadpos],tempchr2,l);
289 tempchr2 = &tempchr[1];
291 l = strlen(tempchr2);
293 if (payloadpos + l + 2 > 507)
295 payload[payloadpos++] = l;
296 memcpy(&payload[payloadpos],tempchr2,l);
298 payload[payloadpos++] = '\0';
300 if (payloadpos > 508)
303 memcpy(&payload[payloadpos],&l,2);
305 memcpy(&payload[payloadpos + 2],&l,2);
306 return payloadpos + 4;
309 in_addr* DNS::dns_aton4(const char * const ipstring) { /* ascii to numeric: convert string to static 4part IP addr struct */
311 return dns_aton4_s(ipstring,&ip);
314 in_addr* DNS::dns_aton4_r(const char *ipstring) { /* ascii to numeric (reentrant): convert string to new 4part IP addr struct */
317 if(dns_aton4_s(ipstring,ip) == NULL) {
324 in_addr* DNS::dns_aton4_s(const char *ipstring, in_addr *ip) { /* ascii to numeric (buffered): convert string to given 4part IP addr struct */
327 myip = (unsigned char *)ip;
330 for (i = 0; i < 16; i++) {
331 switch (ipstring[i]) {
350 if (myip[part] == 250 && ipstring[i] - '0' > 6)
352 myip[part] += ipstring[i] - '0';
374 int DNS::dns_getip4(const char *name) { /* build, add and send A query; retrieve result with dns_getresult() */
382 l = dns_build_query_payload(name,DNS_QRY_A,1,(unsigned char *)&h.payload);
385 s = dns_add_query(&h);
390 if (dns_send_requests(&h,s,l) == -1)
396 int DNS::dns_getip4list(const char *name) { /* build, add and send A query; retrieve result with dns_getresult() */
404 l = dns_build_query_payload(name,DNS_QRY_A,1,(unsigned char *)&h.payload);
407 s = dns_add_query(&h);
413 if (dns_send_requests(&h,s,l) == -1)
419 int DNS::dns_getname4(const in_addr *ip) { /* build, add and send PTR query; retrieve result with dns_getresult() */
428 c = (unsigned char *)&ip->s_addr;
430 sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]);
432 l = dns_build_query_payload(query,DNS_QRY_PTR,1,(unsigned char *)&h.payload);
435 s = dns_add_query(&h);
439 s->type = DNS_QRY_PTR;
440 if (dns_send_requests(&h,s,l) == -1)
446 char* DNS::dns_ntoa4(const in_addr * const ip) { /* numeric to ascii: convert 4part IP addr struct to static string */
448 return dns_ntoa4_s(ip,r);
451 char* DNS::dns_ntoa4_r(const in_addr *ip) { /* numeric to ascii (reentrant): convert 4part IP addr struct to new string */
454 return dns_ntoa4_s(ip,r);
457 char* DNS::dns_ntoa4_s(const in_addr *ip, char *r) { /* numeric to ascii (buffered): convert 4part IP addr struct to given string */
459 m = (unsigned char *)&ip->s_addr;
460 sprintf(r,"%d.%d.%d.%d",m[0],m[1],m[2],m[3]);
464 char* DNS::dns_getresult(const int cfd) { /* retrieve result of DNS query */
465 static char r[RESULTSIZE];
466 return dns_getresult_s(cfd,r);
469 char* DNS::dns_getresult_r(const int cfd) { /* retrieve result of DNS query (reentrant) */
471 r = new char[RESULTSIZE];
472 if(dns_getresult_s(cfd,r) == NULL) {
479 char* DNS::dns_getresult_s(const int cfd, char *res) { /* retrieve result of DNS query (buffered) */
481 s_connection *c, *prev;
482 int l,i,q,curanswer,o;
484 unsigned char buffer[sizeof(s_header)];
494 while (c != NULL) { /* find query in list of open queries */
501 return NULL; /* query not found */
503 /* query found-- pull from list: */
505 prev->next = c->next;
507 connection_head = c->next;
509 l = recv(c->fd,buffer,sizeof(s_header),0);
515 dns_fill_header(&h,buffer,l - 12);
516 if (c->id[0] != h.id[0] || c->id[1] != h.id[1]) {
518 return NULL; /* ID mismatch */
520 if ((h.flags1 & FLAGS1_MASK_QR) == 0) {
524 if ((h.flags1 & FLAGS1_MASK_OPCODE) != 0) {
528 if ((h.flags2 & FLAGS2_MASK_RCODE) != 0) {
532 if (h.ancount < 1) { /* no sense going on if we don't have any answers */
540 while (q < h.qdcount && i < l) {
541 if (h.payload[i] > 63) { /* pointer */
542 i += 6; /* skip pointer, _class and type */
545 if (h.payload[i] == 0) {
547 i += 5; /* skip nil, _class and type */
549 i += h.payload[i] + 1; /* skip length and label */
552 /* &h.payload[i] should now be the start of the first response */
554 while (curanswer < h.ancount) {
556 while (q == 0 && i < l) {
557 if (h.payload[i] > 63) { /* pointer */
558 i += 2; /* skip pointer */
561 if (h.payload[i] == 0) {
565 i += h.payload[i] + 1; /* skip length and label */
572 dns_fill_rr(&rr,&h.payload[i]);
574 if (rr.type != c->type) {
579 if (rr._class != c->_class) {
586 if (curanswer == h.ancount)
588 if (i + rr.rdlength > l)
590 if (rr.rdlength > 1023)
597 while (q == 0 && i < l && o + 256 < 1023) {
598 if (h.payload[i] > 63) { /* pointer */
599 memcpy(&p,&h.payload[i],2);
600 i = ntohs(p) - DNS_POINTER_VALUE - 12;
602 if (h.payload[i] == 0)
608 memcpy(&res[o],&h.payload[i + 1],h.payload[i]);
610 i += h.payload[i] + 1;
618 dns_ip4list *alist = (dns_ip4list *) res; /* we have to trust that this is aligned */
619 while ((char *)alist - (char *)res < 700) {
620 if (rr.type != DNS_QRY_A)
624 if (rr.rdlength != 4) {
628 memcpy(&alist->ip,&h.payload[i],4);
629 if (++curanswer >= h.ancount)
635 while (q == 0 && i < l) {
636 if (h.payload[i] > 63) { /* pointer */
637 i += 2; /* skip pointer */
640 if (h.payload[i] == 0) {
644 i += h.payload[i] + 1; /* skip length and label */
652 dns_fill_rr(&rr,&h.payload[i]);
654 alist->next = (dns_ip4list *) dns_align(((char *) alist) + sizeof(dns_ip4list));
665 memcpy(res,&h.payload[i],rr.rdlength);
666 res[rr.rdlength] = '\0';
678 DNS::DNS(std::string dnsserver)
680 dns_init_2(dnsserver.c_str());
683 void DNS::SetNS(std::string dnsserver)
685 dns_init_2(dnsserver.c_str());
692 bool DNS::ReverseLookup(std::string ip)
695 binip = dns_aton4(ip.c_str());
699 this->fd = dns_getname4(binip);
705 bool DNS::ForwardLookup(std::string host)
709 bool DNS::HasResult()
713 polls.events = POLLIN;
714 int ret = poll(&polls,1,1);
723 std::string DNS::GetResult()
725 result = dns_getresult(this->fd);