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