]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/dns.cpp
Signed octets in dns forward lookup! GAH
[user/henk/code/inspircd.git] / src / dns.cpp
1 /*
2 dns.cpp - based on the firedns library Copyright (C) 2002 Ian Gulliver
3
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.
7
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.
12
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
16 */
17
18 #define _DNS_C
19
20 using namespace std;
21
22 #include <string>
23 #include <stdlib.h>
24 #include <time.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <stdio.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <poll.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include "dns.h"
39 #include "helperfuncs.h"
40
41 extern int statsAccept,statsRefused,statsUnknown,statsCollisions,statsDns,statsDnsGood,statsDnsBad,statsConnects,statsSent,statsRecv;
42
43 #define max(a,b) (a > b ? a : b)
44 #define DNS_MAX              8                    /* max number of nameservers used */
45 #define DNS_CONFIG_FBCK     "/etc/resolv.conf"    /* fallback config file */
46 #define DNS_PORT            53                    /* DNS well known port */
47 #define DNS_QRY_A            1                    /* name to IP address */
48 #define DNS_QRY_AAAA        28                    /* name to IP6 address */
49 #define DNS_QRY_PTR         12                    /* IP address to name */
50 #define DNS_QRY_MX          15                    /* name to MX */
51 #define DNS_QRY_TXT         16                    /* name to TXT */
52 #define DNS_QRY_CNAME       5
53
54 #define DNS_ALIGN (sizeof(void *) > sizeof(long) ? sizeof(void *) : sizeof(long))
55 #define DNS_TRIES 3
56 #define RESULTSIZE 1024
57 #define min(a,b) (a < b ? a : b)
58
59 static struct in_addr servers4[DNS_MAX]; /* up to DNS_MAX nameservers; populated by dns_init() */
60 static int i4; /* actual count of nameservers; set by dns_init() */
61
62 static int initdone = 0; /* to ensure dns_init() only runs once (on the first call) */
63 static int wantclose = 0;
64 static int lastcreate = -1;
65
66 struct s_connection { /* open DNS query */
67         struct s_connection *next; /* next in list */
68         unsigned char id[2];
69         unsigned int _class;
70         unsigned int type;
71         int want_list;
72         int fd; /* file descriptor returned from sockets */
73 };
74
75 struct s_rr_middle {
76         unsigned int type;
77         unsigned int _class;
78         unsigned long ttl;
79         unsigned int rdlength;
80 };
81
82 #define DNS_POINTER_VALUE 0xc000
83
84 static s_connection *connection_head = NULL; /* linked list of open DNS queries; populated by dns_add_query(), decimated by dns_getresult_s() */
85
86 struct s_header { /* DNS query header */
87         unsigned char id[2];
88         unsigned int flags1;
89 #define FLAGS1_MASK_QR 0x80
90 #define FLAGS1_MASK_OPCODE 0x78 /* bitshift right 3 */
91 #define FLAGS1_MASK_AA 0x04
92 #define FLAGS1_MASK_TC 0x02
93 #define FLAGS1_MASK_RD 0x01
94         unsigned int flags2;
95 #define FLAGS2_MASK_RA 0x80
96 #define FLAGS2_MASK_Z  0x70
97 #define FLAGS2_MASK_RCODE 0x0f
98         unsigned int qdcount;
99         unsigned int ancount;
100         unsigned int nscount;
101         unsigned int arcount;
102         unsigned char payload[512]; /* DNS question, populated by dns_build_query_payload() */
103 };
104
105 extern time_t TIME;
106
107 void *dns_align(void *inp) {
108         char *p = (char*)inp;
109         int offby = ((char *)p - (char *)0) % DNS_ALIGN;
110         if (offby != 0)
111                 return p + (DNS_ALIGN - offby);
112         else
113                 return p;
114 }
115
116 /*
117  * These little hacks are here to avoid alignment and type sizing issues completely by doing manual copies
118  */
119 void dns_fill_rr(s_rr_middle* rr, const unsigned char *input) {
120         rr->type = input[0] * 256 + input[1];
121         rr->_class = input[2] * 256 + input[3];
122         rr->ttl = input[4] * 16777216 + input[5] * 65536 + input[6] * 256 + input[7];
123         rr->rdlength = input[8] * 256 + input[9];
124 }
125
126 void dns_fill_header(s_header *header, const unsigned char *input, const int l) {
127         header->id[0] = input[0];
128         header->id[1] = input[1];
129         header->flags1 = input[2];
130         header->flags2 = input[3];
131         header->qdcount = input[4] * 256 + input[5];
132         header->ancount = input[6] * 256 + input[7];
133         header->nscount = input[8] * 256 + input[9];
134         header->arcount = input[10] * 256 + input[11];
135         memcpy(header->payload,&input[12],l);
136 }
137
138 void dns_empty_header(unsigned char *output, const s_header *header, const int l) {
139         output[0] = header->id[0];
140         output[1] = header->id[1];
141         output[2] = header->flags1;
142         output[3] = header->flags2;
143         output[4] = header->qdcount / 256;
144         output[5] = header->qdcount % 256;
145         output[6] = header->ancount / 256;
146         output[7] = header->ancount % 256;
147         output[8] = header->nscount / 256;
148         output[9] = header->nscount % 256;
149         output[10] = header->arcount / 256;
150         output[11] = header->arcount % 256;
151         memcpy(&output[12],header->payload,l);
152 }
153
154 void dns_close(int fd) { /* close query */
155         if (fd == lastcreate) {
156                 wantclose = 1;
157                 return;
158         }
159         close(fd);
160         return;
161 }
162
163 void DNS::dns_init() { /* on first call only: populates servers4 struct with up to DNS_MAX nameserver IP addresses from /etc/resolv.conf */
164         FILE *f;
165         int i;
166         in_addr addr4;
167         char buf[1024];
168         if (initdone == 1)
169                 return;
170         i4 = 0;
171
172         initdone = 1;
173         srand((unsigned int) TIME);
174         memset(servers4,'\0',sizeof(in_addr) * DNS_MAX);
175         f = fopen(DNS_CONFIG_FBCK,"r");
176         if (f == NULL)
177                 return;
178         while (fgets(buf,1024,f) != NULL) {
179                 if (strncmp(buf,"nameserver",10) == 0) {
180                         i = 10;
181                         while (buf[i] == ' ' || buf[i] == '\t')
182                                 i++;
183                         if (i4 < DNS_MAX) {
184                                 if (dns_aton4_s(&buf[i],&addr4) != NULL)
185                                         memcpy(&servers4[i4++],&addr4,sizeof(in_addr));
186                         }
187                 }
188         }
189         fclose(f);
190 }
191
192 void DNS::dns_init_2(const char* dnsserver)
193 {
194         in_addr addr4;
195         i4 = 0;
196         srand((unsigned int) TIME);
197         memset(servers4,'\0',sizeof(in_addr) * DNS_MAX);
198         if (dns_aton4_s(dnsserver,&addr4) != NULL)
199             memcpy(&servers4[i4++],&addr4,sizeof(in_addr));
200 }
201
202
203 static int dns_send_requests(const s_header *h, const s_connection *s, const int l)
204 {
205         int i;
206         sockaddr_in addr4;
207         unsigned char payload[sizeof(s_header)];
208
209         dns_empty_header(payload,h,l);
210
211
212         i = 0;
213
214         /* otherwise send via standard ipv4 boringness */
215         memset(&addr4,0,sizeof(addr4));
216         memcpy(&addr4.sin_addr,&servers4[i],sizeof(addr4.sin_addr));
217         addr4.sin_family = AF_INET;
218         addr4.sin_port = htons(DNS_PORT);
219         if (sendto(s->fd, payload, l + 12, 0, (sockaddr *) &addr4, sizeof(addr4)) == -1)
220         {
221                 return -1;
222         }
223
224         return 0;
225 }
226
227 static s_connection *dns_add_query(s_header *h) { /* build DNS query, add to list */
228         s_connection * s;
229
230         s = new s_connection;
231
232         /* set header flags */
233         h->id[0] = s->id[0] = rand() % 255; /* verified by dns_getresult_s() */
234         h->id[1] = s->id[1] = rand() % 255;
235         h->flags1 = 0 | FLAGS1_MASK_RD;
236         h->flags2 = 0;
237         h->qdcount = 1;
238         h->ancount = 0;
239         h->nscount = 0;
240         h->arcount = 0;
241
242         /* turn off want_list by default */
243         s->want_list = 0;
244
245         /* try to create ipv6 or ipv4 socket */
246                 s->fd = socket(PF_INET, SOCK_DGRAM, 0);
247                 if (s->fd != -1) {
248                         if (fcntl(s->fd, F_SETFL, O_NONBLOCK) != 0) {
249                                 close(s->fd);
250                                 s->fd = -1;
251                         }
252                 }
253                 if (s->fd != -1) {
254                         sockaddr_in addr;
255                         memset(&addr,0,sizeof(addr));
256                         addr.sin_family = AF_INET;
257                         addr.sin_port = 0;
258                         addr.sin_addr.s_addr = INADDR_ANY;
259                         if (bind(s->fd,(sockaddr *)&addr,sizeof(addr)) != 0) {
260                                 close(s->fd);
261                                 s->fd = -1;
262                         }
263                 }
264                 if (s->fd == -1) {
265                         delete s;
266                         return NULL;
267                 }
268         /* create new connection object, add to linked list */
269         s->next = connection_head;
270         connection_head = s;
271
272         if (wantclose == 1) {
273                 close(lastcreate);
274                 wantclose = 0;
275         }
276         lastcreate = s->fd;
277         return s;
278 }
279
280 static int dns_build_query_payload(const char * const name, const unsigned short rr, const unsigned short _class, unsigned char * const payload) { 
281         short payloadpos;
282         const char * tempchr, * tempchr2;
283         unsigned short l;
284         
285         payloadpos = 0;
286         tempchr2 = name;
287
288         /* split name up into labels, create query */
289         while ((tempchr = strchr(tempchr2,'.')) != NULL) {
290                 l = tempchr - tempchr2;
291                 if (payloadpos + l + 1 > 507)
292                         return -1;
293                 payload[payloadpos++] = l;
294                 memcpy(&payload[payloadpos],tempchr2,l);
295                 payloadpos += l;
296                 tempchr2 = &tempchr[1];
297         }
298         l = strlen(tempchr2);
299         if (l) {
300                 if (payloadpos + l + 2 > 507)
301                         return -1;
302                 payload[payloadpos++] = l;
303                 memcpy(&payload[payloadpos],tempchr2,l);
304                 payloadpos += l;
305                 payload[payloadpos++] = '\0';
306         }
307         if (payloadpos > 508)
308                 return -1;
309         l = htons(rr);
310         memcpy(&payload[payloadpos],&l,2);
311         l = htons(_class);
312         memcpy(&payload[payloadpos + 2],&l,2);
313         return payloadpos + 4;
314 }
315
316 in_addr* DNS::dns_aton4(const char * const ipstring) { /* ascii to numeric: convert string to static 4part IP addr struct */
317         static in_addr ip;
318         return dns_aton4_s(ipstring,&ip);
319 }
320
321 in_addr* DNS::dns_aton4_r(const char *ipstring) { /* ascii to numeric (reentrant): convert string to new 4part IP addr struct */
322         in_addr* ip;
323         ip = new in_addr;
324         if(dns_aton4_s(ipstring,ip) == NULL) {
325                 delete ip;
326                 return NULL;
327         }
328         return ip;
329 }
330
331 in_addr* DNS::dns_aton4_s(const char *ipstring, in_addr *ip) { /* ascii to numeric (buffered): convert string to given 4part IP addr struct */
332         inet_aton(ipstring,ip);
333         return ip;
334 }
335
336 int DNS::dns_getip4(const char *name) { /* build, add and send A query; retrieve result with dns_getresult() */
337         s_header h;
338         s_connection *s;
339         int l;
340
341         dns_init();
342         
343
344         l = dns_build_query_payload(name,DNS_QRY_A,1,(unsigned char *)&h.payload);
345         if (l == -1)
346                 return -1;
347         s = dns_add_query(&h);
348         if (s == NULL)
349                 return -1;
350         s->_class = 1;
351         s->type = DNS_QRY_A;
352         if (dns_send_requests(&h,s,l) == -1)
353                 return -1;
354
355         return s->fd;
356 }
357
358 int DNS::dns_getip4list(const char *name) { /* build, add and send A query; retrieve result with dns_getresult() */
359         s_header h;
360         s_connection *s;
361         int l;
362
363         dns_init();
364         
365
366         l = dns_build_query_payload(name,DNS_QRY_A,1,(unsigned char *)&h.payload);
367         if (l == -1)
368                 return -1;
369         s = dns_add_query(&h);
370         if (s == NULL)
371                 return -1;
372         s->_class = 1;
373         s->type = DNS_QRY_A;
374         s->want_list = 1;
375         if (dns_send_requests(&h,s,l) == -1)
376                 return -1;
377
378         return s->fd;
379 }
380
381 int DNS::dns_getname4(const in_addr *ip) { /* build, add and send PTR query; retrieve result with dns_getresult() */
382         char query[512];
383         s_header h;
384         s_connection * s;
385         unsigned char *c;
386         int l;
387
388         c = (unsigned char *)&ip->s_addr;
389
390         sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]);
391
392         l = dns_build_query_payload(query,DNS_QRY_PTR,1,(unsigned char *)&h.payload);
393         if (l == -1)
394                 return -1;
395         s = dns_add_query(&h);
396         if (s == NULL)
397                 return -1;
398         s->_class = 1;
399         s->type = DNS_QRY_PTR;
400         if (dns_send_requests(&h,s,l) == -1)
401                 return -1;
402
403         return s->fd;
404 }
405
406 char* DNS::dns_ntoa4(const in_addr * const ip) { /* numeric to ascii: convert 4part IP addr struct to static string */
407         static char r[256];
408         return dns_ntoa4_s(ip,r);
409 }
410
411 char* DNS::dns_ntoa4_r(const in_addr *ip) { /* numeric to ascii (reentrant): convert 4part IP addr struct to new string */
412         char *r;
413         r = new char[256];
414         return dns_ntoa4_s(ip,r);
415 }
416
417 char* DNS::dns_ntoa4_s(const in_addr *ip, char *r) { /* numeric to ascii (buffered): convert 4part IP addr struct to given string */
418         unsigned char *m;
419         m = (unsigned char *)&ip->s_addr;
420         sprintf(r,"%d.%d.%d.%d",m[0],m[1],m[2],m[3]);
421         return r;
422 }
423
424 char* DNS::dns_getresult(const int cfd) { /* retrieve result of DNS query */
425         static char r[RESULTSIZE];
426         return dns_getresult_s(cfd,r);
427 }
428
429 char* DNS::dns_getresult_r(const int cfd) { /* retrieve result of DNS query (reentrant) */
430         char *r;
431         r = new char[RESULTSIZE];
432         if(dns_getresult_s(cfd,r) == NULL) {
433                 delete r;
434                 return NULL;
435         }
436         return r;
437 }
438
439 char* DNS::dns_getresult_s(const int cfd, char *res) { /* retrieve result of DNS query (buffered) */
440         s_header h;
441         s_connection *c, *prev;
442         int l,i,q,curanswer,o;
443         s_rr_middle rr;
444         unsigned char buffer[sizeof(s_header)];
445         unsigned short p;
446
447         if (res)
448         {
449                 res[0] = 0;
450         }
451
452         prev = NULL;
453         c = connection_head;
454         while (c != NULL) { /* find query in list of open queries */
455                 if (c->fd == cfd)
456                         break;
457                 prev = c;
458                 c = c->next;
459         }
460         if (c == NULL) {
461                 return NULL; /* query not found */
462         }
463         /* query found-- pull from list: */
464         if (prev != NULL)
465                 prev->next = c->next;
466         else
467                 connection_head = c->next;
468
469         l = recv(c->fd,buffer,sizeof(s_header),0);
470         dns_close(c->fd);
471         if (l < 12) {
472                 delete c;
473                 return NULL;
474         }
475         dns_fill_header(&h,buffer,l - 12);
476         if (c->id[0] != h.id[0] || c->id[1] != h.id[1]) {
477                 delete c;
478                 return NULL; /* ID mismatch */
479         }
480         if ((h.flags1 & FLAGS1_MASK_QR) == 0) {
481                 delete c;
482                 return NULL;
483         }
484         if ((h.flags1 & FLAGS1_MASK_OPCODE) != 0) {
485                 delete c;
486                 return NULL;
487         }
488         if ((h.flags2 & FLAGS2_MASK_RCODE) != 0) {
489                 delete c;
490                 return NULL;
491         }
492         if (h.ancount < 1)  { /* no sense going on if we don't have any answers */
493                 delete c;
494                 return NULL;
495         }
496         /* skip queries */
497         i = 0;
498         q = 0;
499         l -= 12;
500         while ((unsigned)q < h.qdcount && i < l) {
501                 if (h.payload[i] > 63) { /* pointer */
502                         i += 6; /* skip pointer, _class and type */
503                         q++;
504                 } else { /* label */
505                         if (h.payload[i] == 0) {
506                                 q++;
507                                 i += 5; /* skip nil, _class and type */
508                         } else
509                                 i += h.payload[i] + 1; /* skip length and label */
510                 }
511         }
512         /* &h.payload[i] should now be the start of the first response */
513         curanswer = 0;
514         while ((unsigned)curanswer < h.ancount) {
515                 q = 0;
516                 while (q == 0 && i < l) {
517                         if (h.payload[i] > 63) { /* pointer */
518                                 i += 2; /* skip pointer */
519                                 q = 1;
520                         } else { /* label */
521                                 if (h.payload[i] == 0) {
522                                         i++;
523                                         q = 1;
524                                 } else
525                                         i += h.payload[i] + 1; /* skip length and label */
526                         }
527                 }
528                 if (l - i < 10) {
529                         delete c;
530                         return NULL;
531                 }
532                 dns_fill_rr(&rr,&h.payload[i]);
533                 i += 10;
534                 if (rr.type != c->type) {
535                         curanswer++;
536                         i += rr.rdlength;
537                         continue;
538                 }
539                 if (rr._class != c->_class) {
540                         curanswer++;
541                         i += rr.rdlength;
542                         continue;
543                 }
544                 break;
545         }
546         if ((unsigned)curanswer == h.ancount)
547                 return NULL;
548         if ((unsigned)i + rr.rdlength > (unsigned)l)
549                 return NULL;
550         if (rr.rdlength > 1023)
551                 return NULL;
552
553         switch (rr.type) {
554                 case DNS_QRY_PTR:
555                         o = 0;
556                         q = 0;
557                         while (q == 0 && i < l && o + 256 < 1023) {
558                                 if (h.payload[i] > 63) { /* pointer */
559                                         memcpy(&p,&h.payload[i],2);
560                                         i = ntohs(p) - DNS_POINTER_VALUE - 12;
561                                 } else { /* label */
562                                         if (h.payload[i] == 0)
563                                                 q = 1;
564                                         else {
565                                                 res[o] = '\0';
566                                                 if (o != 0)
567                                                         res[o++] = '.';
568                                                 memcpy(&res[o],&h.payload[i + 1],h.payload[i]);
569                                                 o += h.payload[i];
570                                                 i += h.payload[i] + 1;
571                                         }
572                                 }
573                         }
574                         res[o] = '\0';
575                         break;
576                 case DNS_QRY_A:
577                         if (c->want_list) {
578                                 dns_ip4list *alist = (dns_ip4list *) res; /* we have to trust that this is aligned */
579                                 while ((char *)alist - (char *)res < 700) {
580                                         if (rr.type != DNS_QRY_A)
581                                                 break;
582                                         if (rr._class != 1)
583                                                 break;
584                                         if (rr.rdlength != 4) {
585                                                 delete c;
586                                                 return NULL;
587                                         }
588                                         memcpy(&alist->ip,&h.payload[i],4);
589                                         if ((unsigned)++curanswer >= h.ancount)
590                                                 break;
591                                         i += rr.rdlength;
592                                         {
593                                                 /* skip next name */
594                                                 q = 0;
595                                                 while (q == 0 && i < l) {
596                                                         if (h.payload[i] > 63) { /* pointer */
597                                                                 i += 2; /* skip pointer */
598                                                                 q = 1;
599                                                         } else { /* label */
600                                                                 if (h.payload[i] == 0) {
601                                                                         i++;
602                                                                         q = 1;
603                                                                 } else
604                                                                         i += h.payload[i] + 1; /* skip length and label */
605                                                         }
606                                                 }
607                                         }
608                                         if (l - i < 10) {
609                                                 delete c;
610                                                 return NULL;
611                                         }
612                                         dns_fill_rr(&rr,&h.payload[i]);
613                                         i += 10;
614                                         alist->next = (dns_ip4list *) dns_align(((char *) alist) + sizeof(dns_ip4list));
615                                         alist = alist->next;
616                                         alist->next = NULL;
617                                 }
618                                 alist->next = NULL;
619                                 break;
620                         }
621                         goto defaultcase;
622                         break;
623                 default:
624                 defaultcase:
625                         memcpy(res,&h.payload[i],rr.rdlength);
626                         res[rr.rdlength] = '\0';
627                         break;
628         }
629         delete c;
630         return res;
631 }
632
633 DNS::DNS()
634 {
635         dns_init();
636 }
637
638 DNS::DNS(std::string dnsserver)
639 {
640         dns_init_2(dnsserver.c_str());
641 }
642
643 void DNS::SetNS(std::string dnsserver)
644 {
645         dns_init_2(dnsserver.c_str());
646 }
647
648 DNS::~DNS()
649 {
650 }
651
652 bool DNS::ReverseLookup(std::string ip)
653 {
654         statsDns++;
655         binip = dns_aton4(ip.c_str());
656         if (binip == NULL) {
657                 return false;
658         }
659
660         this->fd = dns_getname4(binip);
661         if (this->fd == -1)
662         {
663                 return false;
664         }
665         return true;
666 }
667
668 bool DNS::ForwardLookup(std::string host)
669 {
670         statsDns++;
671         this->fd = dns_getip4(host.c_str());
672         if (this->fd == -1)
673         {
674                 return false;
675         }
676         return true;
677 }
678
679 bool DNS::HasResult()
680 {
681         pollfd polls;
682         polls.fd = this->fd;
683         polls.events = POLLIN;
684         int ret = poll(&polls,1,1);
685         return (ret > 0);
686 }
687
688 int DNS::GetFD()
689 {
690         return this->fd;
691 }
692
693 std::string DNS::GetResult()
694 {
695         result = dns_getresult(this->fd);
696         if (result) {
697                 statsDnsGood++;
698                 dns_close(this->fd);
699                 return result;
700         } else {
701                 statsDnsBad++;
702                 if (this->fd != -1)
703                 {
704                         dns_close(this->fd);
705                 }
706                 return "";
707         }
708 }
709
710 std::string DNS::GetResultIP()
711 {
712         char r[1024];
713         result = dns_getresult(this->fd);
714         if (this->fd != -1)
715         {
716                 dns_close(this->fd);
717         }
718         if (result)
719         {
720                 sprintf(r,"%ld.%ld.%ld.%ld",result[0],result[1],result[2],result[3]);
721                 return r;
722         }
723         else
724         {
725                 log(DEBUG,"DANGER WILL ROBINSON! NXDOMAIN for forward lookup, but we got a reverse lookup!");
726                 return "";
727         }
728 }