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