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