77d37d996e096e849cbdb6aba458420770e0df9a
[oweals/busybox.git] / networking / dnsd.c
1 /*
2  * Mini DNS server implementation for busybox
3  *
4  * Copyright (C) 2005 Roberto A. Foglietta (me@roberto.foglietta.name)
5  * Copyright (C) 2005 Odd Arild Olsen (oao at fibula dot no)
6  * Copyright (C) 2003 Paul Sheer
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  *
9  * Odd Arild Olsen started out with the sheerdns [1] of Paul Sheer and rewrote
10  * it into a shape which I believe is both easier to understand and maintain. 
11  * I also reused the input buffer for output and removed services he did not 
12  * need.  [1] http://threading.2038bug.com/sheerdns/
13  * 
14  * Some bugfix and minor changes was applied by Roberto A. Foglietta who made
15  * the first porting of oao' scdns to busybox also.
16  */
17
18 #include <unistd.h>
19 #include <string.h>
20 #include <signal.h>
21 #include <arpa/inet.h>
22 #include <ctype.h>
23 #include "libbb.h"
24
25 static char *fileconf = "/etc/dnsd.conf";
26 #define LOCK_FILE       "/var/run/dnsd.lock"
27 #define LOG_FILE        "/var/log/dnsd.log"
28
29 #define  MAX_HOST_LEN 16        // longest host name allowed is 15
30 #define IP_STRING_LEN 18        // .xxx.xxx.xxx.xxx\0
31
32 //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
33 static const int MAX_NAME_LEN = (IP_STRING_LEN + 13);
34
35 /* Cannot get bigger packets than 512 per RFC1035
36    In practice this can be set considerably smaller:
37    Length of response packet is  header (12B) + 2*type(4B) + 2*class(4B) + 
38    ttl(4B) + rlen(2B) + r (MAX_NAME_LEN =21B) + 
39    2*querystring (2 MAX_NAME_LEN= 42B), all together 90 Byte
40 */
41 static const int MAX_PACK_LEN = 512 + 1;
42
43 #define  DEFAULT_TTL 30;        // increase this when not testing?
44
45 static const int REQ_A = 1;
46 static const int REQ_PTR = 12;
47
48 struct dns_repl {               // resource record, add 0 or 1 to accepted dns_msg in resp
49         uint16_t rlen;
50         uint8_t *r;             // resource
51         uint16_t flags;
52 };
53
54 struct dns_head {               // the message from client and first part of response mag
55         uint16_t id;
56         uint16_t flags;
57         uint16_t nquer;         // accepts 0
58         uint16_t nansw;         // 1 in response
59         uint16_t nauth;         // 0 
60         uint16_t nadd;          // 0
61 };
62 struct dns_prop {
63         uint16_t type;
64         uint16_t class;
65 };
66 struct dns_entry {              // element of known name, ip address and reversed ip address
67         struct dns_entry *next;
68         char ip[IP_STRING_LEN];         // dotted decimal IP
69         char rip[IP_STRING_LEN];        // length decimal reversed IP 
70         char name[MAX_HOST_LEN];
71 };
72
73 static struct dns_entry *dnsentry = NULL;
74 static int daemonmode = 0;
75 static uint32_t ttl = DEFAULT_TTL;
76
77 /*
78  * Convert host name from C-string to dns length/string. 
79  */
80 static void
81 convname(char *a, uint8_t *q)
82 {
83         int i = (q[0] == '.')?0:1;
84         for(; i < MAX_HOST_LEN-1 && *q; i++, q++)
85                 a[i] = tolower(*q);
86         a[0] = i - 1;
87         a[i] = 0;
88 }
89
90 /*
91  * Insert length of substrings insetad of dots
92  */
93 static void
94 undot(uint8_t * rip)
95 {
96         int i=0, s=0;
97         while(rip[i]) i++;
98         for(--i; i >= 0; i--) {
99                 if(rip[i] == '.') {
100                         rip[i] = s;
101                         s = 0;
102                 } else s++;
103         }
104 }
105
106 /* 
107  * Append message to log file
108  */
109 static void
110 log_message(char *filename, char *message)
111 {
112         FILE *logfile;
113         if (!daemonmode)
114                 return;
115         logfile = fopen(filename, "a");
116         if (!logfile)
117                 return;
118         fprintf(logfile, "%s\n", message);
119         fclose(logfile);
120 }
121
122 /* 
123  * Read one line of hostname/IP from file
124  * Returns 0 for each valid entry read, -1 at EOF
125  * Assumes all host names are lower case only
126  * Hostnames with more than one label is not handled correctly.
127  * Presently the dot is copied into name without
128  * converting to a length/string substring for that label.
129  */
130
131 static int
132 getfileentry(FILE * fp, struct dns_entry *s, int verb)
133 {
134         unsigned int a,b,c,d;
135         char *r, *name;
136
137 restart:
138         if(!(r = bb_get_line_from_file(fp)))
139                 return -1;
140         while(*r == ' ' || *r == '\t') {
141                 r++;
142                 if(!*r || *r == '#' || *r == '\n') 
143                         goto restart; /* skipping empty/blank and commented lines  */
144         }
145         name = r;
146         while(*r != ' ' && *r != '\t')
147                 r++;
148         *r++ = 0;
149         if(sscanf(r,"%u.%u.%u.%u",&a,&b,&c,&d) != 4)
150                         goto restart; /* skipping wrong lines */
151
152         sprintf(s->ip,"%u.%u.%u.%u",a,b,c,d);
153         sprintf(s->rip,".%u.%u.%u.%u",d,c,b,a);
154         undot((uint8_t*)s->rip);
155         convname(s->name,(uint8_t*)name);
156         
157         if(verb) 
158                 fprintf(stderr,"\tname:%s, ip:%s\n",&(s->name[1]),s->ip);
159
160         return 0; /* warningkiller */
161 }
162
163 /*
164  * Read hostname/IP records from file
165  */
166 static void
167 dnsentryinit(int verb)
168 {
169         FILE *fp;
170         struct dns_entry *m, *prev;
171         prev = dnsentry = NULL;
172
173         if(!(fp = fopen(fileconf, "r")))
174                 bb_perror_msg_and_die("open %s",fileconf);
175
176         while (1) {
177                 if(!(m = (struct dns_entry *)malloc(sizeof(struct dns_entry))))
178                         bb_perror_msg_and_die("malloc dns_entry");
179
180                 m->next = NULL;
181                 if (getfileentry(fp, m, verb))
182                         break;
183
184                 if (prev == NULL)
185                         dnsentry = m;
186                 else
187                         prev->next = m;
188                 prev = m;
189         }
190         fclose(fp);
191 }
192
193
194 /*
195  * Set up UDP socket
196  */
197 static int
198 listen_socket(char *iface_addr, int listen_port)
199 {
200         struct sockaddr_in a;
201         char msg[100];
202         int s;
203         int yes = 1;
204         if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0) 
205                 bb_perror_msg_and_die("socket() failed");
206 #ifdef SO_REUSEADDR
207         if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes)) < 0) 
208                 bb_perror_msg_and_die("setsockopt() failed");
209 #endif
210         memset(&a, 0, sizeof(a));
211         a.sin_port = htons(listen_port);
212         a.sin_family = AF_INET;
213         if (!inet_aton(iface_addr, &a.sin_addr)) 
214                 bb_perror_msg_and_die("bad iface address");
215         if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0)
216                 bb_perror_msg_and_die("bind() failed");
217         listen(s, 50);
218         sprintf(msg, "accepting UDP packets on addr:port %s:%d\n",
219                 iface_addr, (int)listen_port);
220         log_message(LOG_FILE, msg);
221         return s;
222 }
223
224 /*
225  * Look query up in dns records and return answer if found 
226  * qs is the query string, first byte the string length
227  */ 
228 static int
229 table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
230 {
231         int i;
232         struct dns_entry *d=dnsentry;
233
234         do {
235 #ifdef DEBUG
236                 char *p,*q;
237                 q = (char *)&(qs[1]);
238                 p = &(d->name[1]);
239                 fprintf(stderr, "\ntest: %d <%s> <%s> %d", strlen(p), p, q, strlen(q));
240 #endif
241                 if (type == REQ_A) { /* search by host name */
242                         for(i = 1; i <= (int)(d->name[0]); i++)
243                                 if(tolower(qs[i]) != d->name[i])
244                                         continue;
245 #ifdef DEBUG
246                         fprintf(stderr, " OK");
247 #endif
248                         strcpy((char *)as, d->ip);
249 #ifdef DEBUG
250                         fprintf(stderr, " %s ", as);
251 #endif
252                                         return 0;
253                                 }       
254                 else if (type == REQ_PTR) { /* search by IP-address */
255                         if (!strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
256                                 strcpy((char *)as, d->name);
257                                 return 0;
258                         }
259                 }
260         } while ((d = d->next) != NULL);
261         return -1;
262 }
263
264
265 /* 
266  * Decode message and generate answer
267  */
268 #define eret(s) do { fprintf (stderr, "%s\n", s); return -1; } while (0)
269 static int
270 process_packet(uint8_t * buf)
271 {
272         struct dns_head *head;
273         struct dns_prop *qprop;
274         struct dns_repl outr;
275         void *next, *from, *answb;
276
277         uint8_t answstr[MAX_NAME_LEN + 1];
278         int lookup_result, type, len, packet_len;
279         uint16_t flags;
280
281         answstr[0] = '\0';
282
283         head = (struct dns_head *)buf;
284         if (head->nquer == 0)
285                 eret("no queries");
286
287         if ((head->flags & 0x8000))
288                 eret("ignoring response packet");
289
290         from = (void *)&head[1];        //  start of query string
291         next = answb = from + strlen((char *)&head[1]) + 1 + sizeof(struct dns_prop);   // where to append answer block
292
293         outr.rlen = 0;          // may change later
294         outr.r = NULL;
295         outr.flags = 0;
296
297         qprop = (struct dns_prop *)(answb - 4);
298         type = ntohs(qprop->type);
299
300         // only let REQ_A and REQ_PTR pass
301         if (!(type == REQ_A || type == REQ_PTR)) {
302                 goto empty_packet;      /* we can't handle the query type */
303         }
304
305         if (ntohs(qprop->class) != 1 /* class INET */ ) {
306                 outr.flags = 4; /* not supported */
307                 goto empty_packet;
308         }
309         /* we only support standard queries */
310
311         if ((ntohs(head->flags) & 0x7800) != 0)
312                 goto empty_packet;
313
314         // We have a standard query
315
316         log_message(LOG_FILE, (char *)head);
317         lookup_result = table_lookup(type, answstr, (uint8_t*)(&head[1]));
318         if (lookup_result != 0) {
319                 outr.flags = 3 | 0x0400;        //name do not exist and auth
320                 goto empty_packet;
321         }
322         if (type == REQ_A) {    // return an address
323                 struct in_addr a;
324                 if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
325                         outr.flags = 1; /* Frmt err */
326                         goto empty_packet;
327                 }
328                 memcpy(answstr, &a.s_addr, 4);  // save before a disappears
329                 outr.rlen = 4;  // uint32_t IP
330         }
331         else
332                 outr.rlen = strlen((char *)answstr) + 1;    // a host name
333         outr.r = answstr;       // 32 bit ip or a host name
334         outr.flags |= 0x0400;   /* authority-bit */
335         // we have an answer
336         head->nansw = htons(1);
337
338         // copy query block to answer block 
339         len = answb - from;
340         memcpy(answb, from, len);
341         next += len;
342
343         // and append answer rr
344         *(uint32_t *) next = htonl(ttl);
345         next += 4;
346         *(uint16_t *) next = htons(outr.rlen);
347         next += 2;
348         memcpy(next, (void *)answstr, outr.rlen);
349         next += outr.rlen;
350
351       empty_packet:
352
353         flags = ntohs(head->flags);
354         // clear rcode and RA, set responsebit and our new flags
355         flags |= (outr.flags & 0xff80) | 0x8000;
356         head->flags = htons(flags);
357         head->nauth = head->nadd = htons(0);
358         head->nquer = htons(1);
359
360         packet_len = next - (void *)buf;
361         return packet_len;
362 }
363
364 /* 
365  * Exit on signal
366  */
367 static void
368 interrupt(int x)
369 {
370         unlink(LOCK_FILE);
371         write(2, "interrupt exiting\n", 18);
372         exit(2);
373 }
374
375 #define is_daemon()  (flags&16)
376 #define is_verbose() (flags&32)
377 //#define DEBUG 1
378
379 int dnsd_main(int argc, char **argv)
380 {
381         int i, udps;
382         uint16_t port = 53;
383         uint8_t buf[MAX_PACK_LEN];
384         unsigned long flags = 0;
385         char *listen_interface = "0.0.0.0";
386         char *sttl=NULL, *sport=NULL;
387
388         if(argc > 1)
389                 flags = bb_getopt_ulflags(argc, argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
390         if(sttl)
391                 if(!(ttl = atol(sttl)))
392                         bb_show_usage();
393         if(sport)
394                 if(!(port = atol(sport)))
395                         bb_show_usage();
396                 
397         if(is_verbose()) {
398                 fprintf(stderr,"listen_interface: %s\n", listen_interface);
399                 fprintf(stderr,"ttl: %d, port: %d\n", ttl, port);
400                 fprintf(stderr,"fileconf: %s\n", fileconf);
401         }
402         
403         if(is_daemon()) 
404 #if defined(__uClinux__)
405                 /* reexec for vfork() do continue parent */
406                 vfork_daemon_rexec(1, 0, argc, argv, "-d");
407 #else                                                   /* uClinux */
408                 if (daemon(1, 0) < 0) {
409                         bb_perror_msg_and_die("daemon");
410                 }
411 #endif                                                  /* uClinuvx */
412                         
413         dnsentryinit(is_verbose());
414
415         signal(SIGINT, interrupt);
416         signal(SIGPIPE, SIG_IGN);
417         signal(SIGHUP, SIG_IGN);
418 #ifdef SIGTSTP
419         signal(SIGTSTP, SIG_IGN);
420 #endif
421 #ifdef SIGURG
422         signal(SIGURG, SIG_IGN);
423 #endif
424
425         udps = listen_socket(listen_interface, port);
426         if (udps < 0)
427                 exit(1);
428
429         while (1) {
430                 fd_set fdset;
431                 int r;
432
433                 FD_ZERO(&fdset);
434                 FD_SET(udps, &fdset);
435                 // Block until a message arrives
436                 if((r = select(udps + 1, &fdset, NULL, NULL, NULL)) < 0)
437                         bb_perror_msg_and_die("select error");
438                 else 
439                 if(r == 0) 
440                         bb_perror_msg_and_die("select spurious return");
441
442                 /* Can this test ever be false? */
443                 if (FD_ISSET(udps, &fdset)) {
444                         struct sockaddr_in from;
445                         int fromlen = sizeof(from);
446                         r = recvfrom(udps, buf, sizeof(buf), 0,
447                                      (struct sockaddr *)&from,
448                                      (void *)&fromlen);
449                         if(is_verbose()) 
450                                 fprintf(stderr, "\n--- Got UDP  ");
451                         log_message(LOG_FILE, "\n--- Got UDP  ");
452
453                         if (r < 12 || r > 512) {
454                                 bb_error_msg("invalid packet size");
455                                 continue;
456                         }
457                         if (r > 0) {
458                                 r = process_packet(buf);
459                                 if (r > 0)
460                                         sendto(udps, buf,
461                                                r, 0, (struct sockaddr *)&from,
462                                                fromlen);
463                         }
464                 }               // end if
465         }                       // end while
466         return 0;
467 }
468
469