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