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