]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/dns.cpp
c3d7cd786a270e769f25a197cb45ddf5c7ea517a
[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 void *dns_align(void *inp) {
99         char *p = (char*)inp;
100         int offby = ((char *)p - (char *)0) % DNS_ALIGN;
101         if (offby != 0)
102                 return p + (DNS_ALIGN - offby);
103         else
104                 return p;
105 }
106
107 /*
108  * These little hacks are here to avoid alignment and type sizing issues completely by doing manual copies
109  */
110 void dns_fill_rr(s_rr_middle* rr, const unsigned char *input) {
111         rr->type = input[0] * 256 + input[1];
112         rr->_class = input[2] * 256 + input[3];
113         rr->ttl = input[4] * 16777216 + input[5] * 65536 + input[6] * 256 + input[7];
114         rr->rdlength = input[8] * 256 + input[9];
115 }
116
117 void dns_fill_header(s_header *header, const unsigned char *input, const int l) {
118         header->id[0] = input[0];
119         header->id[1] = input[1];
120         header->flags1 = input[2];
121         header->flags2 = input[3];
122         header->qdcount = input[4] * 256 + input[5];
123         header->ancount = input[6] * 256 + input[7];
124         header->nscount = input[8] * 256 + input[9];
125         header->arcount = input[10] * 256 + input[11];
126         memcpy(header->payload,&input[12],l);
127 }
128
129 void dns_empty_header(unsigned char *output, const s_header *header, const int l) {
130         output[0] = header->id[0];
131         output[1] = header->id[1];
132         output[2] = header->flags1;
133         output[3] = header->flags2;
134         output[4] = header->qdcount / 256;
135         output[5] = header->qdcount % 256;
136         output[6] = header->ancount / 256;
137         output[7] = header->ancount % 256;
138         output[8] = header->nscount / 256;
139         output[9] = header->nscount % 256;
140         output[10] = header->arcount / 256;
141         output[11] = header->arcount % 256;
142         memcpy(&output[12],header->payload,l);
143 }
144
145 void dns_close(int fd) { /* close query */
146         if (fd == lastcreate) {
147                 wantclose = 1;
148                 return;
149         }
150         close(fd);
151         return;
152 }
153
154 void DNS::dns_init() { /* on first call only: populates servers4 struct with up to DNS_MAX nameserver IP addresses from /etc/resolv.conf */
155         FILE *f;
156         int i;
157         in_addr addr4;
158         char buf[1024];
159         if (initdone == 1)
160                 return;
161         i4 = 0;
162
163         initdone = 1;
164         srand((unsigned int) time(NULL));
165         memset(servers4,'\0',sizeof(in_addr) * DNS_MAX);
166         f = fopen(DNS_CONFIG_FBCK,"r");
167         if (f == NULL)
168                 return;
169         while (fgets(buf,1024,f) != NULL) {
170                 if (strncmp(buf,"nameserver",10) == 0) {
171                         i = 10;
172                         while (buf[i] == ' ' || buf[i] == '\t')
173                                 i++;
174                         if (i4 < DNS_MAX) {
175                                 if (dns_aton4_s(&buf[i],&addr4) != NULL)
176                                         memcpy(&servers4[i4++],&addr4,sizeof(in_addr));
177                         }
178                 }
179         }
180         fclose(f);
181
182 }
183
184 void DNS::dns_init_2(const char* dnsserver) { /* populates servers4 struct with address from the given parameter */
185         FILE *f;
186         int i;
187         in_addr addr4;
188         char buf[1024];
189         if (initdone == 1)
190                 return;
191         i4 = 0;
192
193         initdone = 1;
194         srand((unsigned int) time(NULL));
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) { /* send DNS query */
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         for (i = 0; i < i4; i++) {
210                 /* otherwise send via standard ipv4 boringness */
211                 memset(&addr4,0,sizeof(addr4));
212                 memcpy(&addr4.sin_addr,&servers4[i],sizeof(addr4.sin_addr));
213                 addr4.sin_family = AF_INET;
214                 addr4.sin_port = htons(DNS_PORT);
215                 if (sendto(s->fd, payload, l + 12, 0, (sockaddr *) &addr4, sizeof(addr4)) == -1)
216                 {
217                         return -1;
218                 }
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         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         unsigned char *myip;
330         int i,part = 0;
331         myip = (unsigned char *)ip;
332
333         memset(myip,'\0',4);
334         for (i = 0; i < 16; i++) {
335                 switch (ipstring[i]) {
336                         case '\0':
337                                 if (part != 3)
338                                         return NULL;
339                                 return ip;
340                                 break;
341                         case '0':
342                         case '1':
343                         case '2':
344                         case '3':
345                         case '4':
346                         case '5':
347                         case '6':
348                         case '7':
349                         case '8':
350                         case '9':
351                                 if (myip[part] > 25)
352                                         return NULL;
353                                 myip[part] *= 10;
354                                 if (myip[part] == 250 && ipstring[i] - '0' > 6)
355                                         return NULL;
356                                 myip[part] += ipstring[i] - '0';
357                                 break;
358                         case '.':
359                                 if (part == 3)
360                                         return ip;
361                                 else
362                                         part++;
363                                 break;
364                         default:
365                                 if (part == 3)
366                                         return ip;
367                                 else
368                                         return NULL;
369                                 break;
370                 }
371         }
372         if (part == 3)
373                 return ip;
374         else
375                 return NULL;
376 }
377
378 int DNS::dns_getip4(const char *name) { /* build, add and send A query; retrieve result with dns_getresult() */
379         s_header h;
380         s_connection *s;
381         int l;
382
383         dns_init();
384         
385
386         l = dns_build_query_payload(name,DNS_QRY_A,1,(unsigned char *)&h.payload);
387         if (l == -1)
388                 return -1;
389         s = dns_add_query(&h);
390         if (s == NULL)
391                 return -1;
392         s->_class = 1;
393         s->type = DNS_QRY_A;
394         if (dns_send_requests(&h,s,l) == -1)
395                 return -1;
396
397         return s->fd;
398 }
399
400 int DNS::dns_getip4list(const char *name) { /* build, add and send A query; retrieve result with dns_getresult() */
401         s_header h;
402         s_connection *s;
403         int l;
404
405         dns_init();
406         
407
408         l = dns_build_query_payload(name,DNS_QRY_A,1,(unsigned char *)&h.payload);
409         if (l == -1)
410                 return -1;
411         s = dns_add_query(&h);
412         if (s == NULL)
413                 return -1;
414         s->_class = 1;
415         s->type = DNS_QRY_A;
416         s->want_list = 1;
417         if (dns_send_requests(&h,s,l) == -1)
418                 return -1;
419
420         return s->fd;
421 }
422
423 int DNS::dns_getname4(const in_addr *ip) { /* build, add and send PTR query; retrieve result with dns_getresult() */
424         char query[512];
425         s_header h;
426         s_connection * s;
427         unsigned char *c;
428         int l;
429
430         dns_init();
431
432         c = (unsigned char *)&ip->s_addr;
433
434         sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]);
435
436         l = dns_build_query_payload(query,DNS_QRY_PTR,1,(unsigned char *)&h.payload);
437         if (l == -1)
438                 return -1;
439         s = dns_add_query(&h);
440         if (s == NULL)
441                 return -1;
442         s->_class = 1;
443         s->type = DNS_QRY_PTR;
444         if (dns_send_requests(&h,s,l) == -1)
445                 return -1;
446
447         return s->fd;
448 }
449
450 char* DNS::dns_ntoa4(const in_addr * const ip) { /* numeric to ascii: convert 4part IP addr struct to static string */
451         static char result[256];
452         return dns_ntoa4_s(ip,result);
453 }
454
455 char* DNS::dns_ntoa4_r(const in_addr *ip) { /* numeric to ascii (reentrant): convert 4part IP addr struct to new string */
456         char *result;
457         result = new char[256];
458         return dns_ntoa4_s(ip,result);
459 }
460
461 char* DNS::dns_ntoa4_s(const in_addr *ip, char *result) { /* numeric to ascii (buffered): convert 4part IP addr struct to given string */
462         unsigned char *m;
463         m = (unsigned char *)&ip->s_addr;
464         sprintf(result,"%d.%d.%d.%d",m[0],m[1],m[2],m[3]);
465         return result;
466 }
467
468 char* DNS::dns_getresult(const int fd) { /* retrieve result of DNS query */
469         static char result[RESULTSIZE];
470         return dns_getresult_s(fd,result);
471 }
472
473 char* DNS::dns_getresult_r(const int fd) { /* retrieve result of DNS query (reentrant) */
474         char *result;
475         result = new char[RESULTSIZE];
476         if(dns_getresult_s(fd,result) == NULL) {
477                 delete result;
478                 return NULL;
479         }
480         return result;
481 }
482
483 char* DNS::dns_getresult_s(const int fd, char *result) { /* retrieve result of DNS query (buffered) */
484         s_header h;
485         s_connection *c, *prev;
486         int l,i,q,curanswer,o;
487         s_rr_middle rr;
488         unsigned char buffer[sizeof(s_header)];
489         unsigned short p;
490
491         if (result)
492         {
493                 result[0] = 0;
494         }
495
496         prev = NULL;
497         c = connection_head;
498         while (c != NULL) { /* find query in list of open queries */
499                 if (c->fd == fd)
500                         break;
501                 prev = c;
502                 c = c->next;
503         }
504         if (c == NULL) {
505                 return NULL; /* query not found */
506         }
507         /* query found-- pull from list: */
508         if (prev != NULL)
509                 prev->next = c->next;
510         else
511                 connection_head = c->next;
512
513         l = recv(c->fd,buffer,sizeof(s_header),0);
514         dns_close(c->fd);
515         if (l < 12) {
516                 delete c;
517                 return NULL;
518         }
519         dns_fill_header(&h,buffer,l - 12);
520         if (c->id[0] != h.id[0] || c->id[1] != h.id[1]) {
521                 delete c;
522                 return NULL; /* ID mismatch */
523         }
524         if ((h.flags1 & FLAGS1_MASK_QR) == 0) {
525                 delete c;
526                 return NULL;
527         }
528         if ((h.flags1 & FLAGS1_MASK_OPCODE) != 0) {
529                 delete c;
530                 return NULL;
531         }
532         if ((h.flags2 & FLAGS2_MASK_RCODE) != 0) {
533                 delete c;
534                 return NULL;
535         }
536         if (h.ancount < 1)  { /* no sense going on if we don't have any answers */
537                 delete c;
538                 return NULL;
539         }
540         /* skip queries */
541         i = 0;
542         q = 0;
543         l -= 12;
544         while (q < h.qdcount && i < l) {
545                 if (h.payload[i] > 63) { /* pointer */
546                         i += 6; /* skip pointer, _class and type */
547                         q++;
548                 } else { /* label */
549                         if (h.payload[i] == 0) {
550                                 q++;
551                                 i += 5; /* skip nil, _class and type */
552                         } else
553                                 i += h.payload[i] + 1; /* skip length and label */
554                 }
555         }
556         /* &h.payload[i] should now be the start of the first response */
557         curanswer = 0;
558         while (curanswer < h.ancount) {
559                 q = 0;
560                 while (q == 0 && i < l) {
561                         if (h.payload[i] > 63) { /* pointer */
562                                 i += 2; /* skip pointer */
563                                 q = 1;
564                         } else { /* label */
565                                 if (h.payload[i] == 0) {
566                                         i++;
567                                         q = 1;
568                                 } else
569                                         i += h.payload[i] + 1; /* skip length and label */
570                         }
571                 }
572                 if (l - i < 10) {
573                         delete c;
574                         return NULL;
575                 }
576                 dns_fill_rr(&rr,&h.payload[i]);
577                 i += 10;
578                 if (rr.type != c->type) {
579                         curanswer++;
580                         i += rr.rdlength;
581                         continue;
582                 }
583                 if (rr._class != c->_class) {
584                         curanswer++;
585                         i += rr.rdlength;
586                         continue;
587                 }
588                 break;
589         }
590         if (curanswer == h.ancount)
591                 return NULL;
592         if (i + rr.rdlength > l)
593                 return NULL;
594         if (rr.rdlength > 1023)
595                 return NULL;
596
597         switch (rr.type) {
598                 case DNS_QRY_PTR:
599                         o = 0;
600                         q = 0;
601                         while (q == 0 && i < l && o + 256 < 1023) {
602                                 if (h.payload[i] > 63) { /* pointer */
603                                         memcpy(&p,&h.payload[i],2);
604                                         i = ntohs(p) - DNS_POINTER_VALUE - 12;
605                                 } else { /* label */
606                                         if (h.payload[i] == 0)
607                                                 q = 1;
608                                         else {
609                                                 result[o] = '\0';
610                                                 if (o != 0)
611                                                         result[o++] = '.';
612                                                 memcpy(&result[o],&h.payload[i + 1],h.payload[i]);
613                                                 o += h.payload[i];
614                                                 i += h.payload[i] + 1;
615                                         }
616                                 }
617                         }
618                         result[o] = '\0';
619                         break;
620                 case DNS_QRY_A:
621                         if (c->want_list) {
622                                 dns_ip4list *alist = (dns_ip4list *) result; /* we have to trust that this is aligned */
623                                 while ((char *)alist - (char *)result < 700) {
624                                         if (rr.type != DNS_QRY_A)
625                                                 break;
626                                         if (rr._class != 1)
627                                                 break;
628                                         if (rr.rdlength != 4) {
629                                                 delete c;
630                                                 return NULL;
631                                         }
632                                         memcpy(&alist->ip,&h.payload[i],4);
633                                         if (++curanswer >= h.ancount)
634                                                 break;
635                                         i += rr.rdlength;
636                                         {
637                                                 /* skip next name */
638                                                 q = 0;
639                                                 while (q == 0 && i < l) {
640                                                         if (h.payload[i] > 63) { /* pointer */
641                                                                 i += 2; /* skip pointer */
642                                                                 q = 1;
643                                                         } else { /* label */
644                                                                 if (h.payload[i] == 0) {
645                                                                         i++;
646                                                                         q = 1;
647                                                                 } else
648                                                                         i += h.payload[i] + 1; /* skip length and label */
649                                                         }
650                                                 }
651                                         }
652                                         if (l - i < 10) {
653                                                 delete c;
654                                                 return NULL;
655                                         }
656                                         dns_fill_rr(&rr,&h.payload[i]);
657                                         i += 10;
658                                         alist->next = (dns_ip4list *) dns_align(((char *) alist) + sizeof(dns_ip4list));
659                                         alist = alist->next;
660                                         alist->next = NULL;
661                                 }
662                                 alist->next = NULL;
663                                 break;
664                         }
665                         goto defaultcase;
666                         break;
667                 default:
668                 defaultcase:
669                         memcpy(result,&h.payload[i],rr.rdlength);
670                         result[rr.rdlength] = '\0';
671                         break;
672         }
673         delete c;
674         return result;
675 }
676
677 DNS::DNS()
678 {
679         dns_init();
680 }
681
682 DNS::DNS(std::string dnsserver)
683 {
684         dns_init_2(dnsserver.c_str());
685 }
686
687 DNS::~DNS()
688 {
689 }
690
691 bool DNS::ReverseLookup(std::string ip)
692 {
693         binip = dns_aton4(ip.c_str());
694         if (binip == NULL) {
695                 return false;
696         }
697         this->fd = dns_getname4(binip);
698         if (this->fd == -1)
699                 return false;
700         return true;
701 }
702
703 bool DNS::ForwardLookup(std::string host)
704 {
705 }
706
707 bool DNS::HasResult()
708 {
709         pollfd polls;
710         polls.fd = this->fd;
711         polls.events = POLLIN;
712         int ret = poll(&polls,1,1);
713         return (ret > 0);
714 }
715
716 int DNS::GetFD()
717 {
718         return this->fd;
719 }
720
721 std::string DNS::GetResult()
722 {
723         result = dns_getresult(this->fd);
724         if (result) {
725                 return result;
726         } else {
727                 return "";
728         }
729 }