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