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