1 /* vi: set sw=4 ts=4: */
3 * Mini DNS server implementation for busybox
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
9 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
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/
16 * Some bugfix and minor changes was applied by Roberto A. Foglietta who made
17 * the first porting of oao' scdns to busybox also.
23 #include <arpa/inet.h>
24 #include <sys/socket.h>
28 static char *fileconf = "/etc/dnsd.conf";
29 #define LOCK_FILE "/var/run/dnsd.lock"
30 #define LOG_FILE "/var/log/dnsd.log"
33 MAX_HOST_LEN = 16, // longest host name allowed is 15
34 IP_STRING_LEN = 18, // .xxx.xxx.xxx.xxx\0
36 //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
37 MAX_NAME_LEN = (IP_STRING_LEN + 13),
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
45 MAX_PACK_LEN = 512 + 1,
47 DEFAULT_TTL = 30, // increase this when not testing?
53 struct dns_repl { // resource record, add 0 or 1 to accepted dns_msg in resp
55 uint8_t *r; // resource
59 struct dns_head { // the message from client and first part of response mag
62 uint16_t nquer; // accepts 0
63 uint16_t nansw; // 1 in response
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];
78 static struct dns_entry *dnsentry = NULL;
79 static int daemonmode = 0;
80 static uint32_t ttl = DEFAULT_TTL;
83 * Convert host name from C-string to dns length/string.
85 static void convname(char *a, uint8_t *q)
87 int i = (q[0] == '.') ? 0 : 1;
88 for(; i < MAX_HOST_LEN-1 && *q; i++, q++)
95 * Insert length of substrings instead of dots
97 static void undot(uint8_t * rip)
101 for(--i; i >= 0; i--) {
110 * Append message to log file
112 static void log_message(char *filename, char *message)
117 logfile = fopen(filename, "a");
120 fprintf(logfile, "%s\n", message);
125 * Read one line of hostname/IP from file
126 * Returns 0 for each valid entry read, -1 at EOF
127 * Assumes all host names are lower case only
128 * Hostnames with more than one label is not handled correctly.
129 * Presently the dot is copied into name without
130 * converting to a length/string substring for that label.
133 static int getfileentry(FILE * fp, struct dns_entry *s, int verb)
135 unsigned int a,b,c,d;
139 if(!(r = bb_get_line_from_file(fp)))
141 while(*r == ' ' || *r == '\t') {
143 if(!*r || *r == '#' || *r == '\n')
144 goto restart; /* skipping empty/blank and commented lines */
147 while(*r != ' ' && *r != '\t')
150 if(sscanf(r,"%u.%u.%u.%u",&a,&b,&c,&d) != 4)
151 goto restart; /* skipping wrong lines */
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);
159 fprintf(stderr,"\tname:%s, ip:%s\n",&(s->name[1]),s->ip);
161 return 0; /* warningkiller */
165 * Read hostname/IP records from file
167 static void dnsentryinit(int verb)
170 struct dns_entry *m, *prev;
171 prev = dnsentry = NULL;
173 fp = bb_xfopen(fileconf, "r");
176 m = xmalloc(sizeof(struct dns_entry));
179 if (getfileentry(fp, m, verb))
195 static int listen_socket(char *iface_addr, int listen_port)
197 struct sockaddr_in a;
201 s = bb_xsocket(PF_INET, SOCK_DGRAM, 0);
203 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes)) < 0)
204 bb_perror_msg_and_die("setsockopt() failed");
206 memset(&a, 0, sizeof(a));
207 a.sin_port = htons(listen_port);
208 a.sin_family = AF_INET;
209 if (!inet_aton(iface_addr, &a.sin_addr))
210 bb_perror_msg_and_die("bad iface address");
211 bb_xbind(s, (struct sockaddr *)&a, sizeof(a));
212 listen(s, 50); /* bb_xlisten? */
213 sprintf(msg, "accepting UDP packets on addr:port %s:%d\n",
214 iface_addr, (int)listen_port);
215 log_message(LOG_FILE, msg);
220 * Look query up in dns records and return answer if found
221 * qs is the query string, first byte the string length
223 static int table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
226 struct dns_entry *d=dnsentry;
231 q = (char *)&(qs[1]);
233 fprintf(stderr, "\ntest: %d <%s> <%s> %d", strlen(p), p, q, strlen(q));
235 if (type == REQ_A) { /* search by host name */
236 for(i = 1; i <= (int)(d->name[0]); i++)
237 if(tolower(qs[i]) != d->name[i])
240 fprintf(stderr, " OK");
242 strcpy((char *)as, d->ip);
244 fprintf(stderr, " %s ", as);
248 else if (type == REQ_PTR) { /* search by IP-address */
249 if (!strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
250 strcpy((char *)as, d->name);
254 } while ((d = d->next) != NULL);
260 * Decode message and generate answer
262 #define eret(s) do { fprintf (stderr, "%s\n", s); return -1; } while (0)
263 static int process_packet(uint8_t * buf)
265 struct dns_head *head;
266 struct dns_prop *qprop;
267 struct dns_repl outr;
268 void *next, *from, *answb;
270 uint8_t answstr[MAX_NAME_LEN + 1];
271 int lookup_result, type, len, packet_len;
276 head = (struct dns_head *)buf;
277 if (head->nquer == 0)
280 if ((head->flags & 0x8000))
281 eret("ignoring response packet");
283 from = (void *)&head[1]; // start of query string
284 next = answb = from + strlen((char *)&head[1]) + 1 + sizeof(struct dns_prop); // where to append answer block
286 outr.rlen = 0; // may change later
290 qprop = (struct dns_prop *)(answb - 4);
291 type = ntohs(qprop->type);
293 // only let REQ_A and REQ_PTR pass
294 if (!(type == REQ_A || type == REQ_PTR)) {
295 goto empty_packet; /* we can't handle the query type */
298 if (ntohs(qprop->class) != 1 /* class INET */ ) {
299 outr.flags = 4; /* not supported */
302 /* we only support standard queries */
304 if ((ntohs(head->flags) & 0x7800) != 0)
307 // We have a standard query
309 log_message(LOG_FILE, (char *)head);
310 lookup_result = table_lookup(type, answstr, (uint8_t*)(&head[1]));
311 if (lookup_result != 0) {
312 outr.flags = 3 | 0x0400; //name do not exist and auth
315 if (type == REQ_A) { // return an address
317 if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
318 outr.flags = 1; /* Frmt err */
321 memcpy(answstr, &a.s_addr, 4); // save before a disappears
322 outr.rlen = 4; // uint32_t IP
325 outr.rlen = strlen((char *)answstr) + 1; // a host name
326 outr.r = answstr; // 32 bit ip or a host name
327 outr.flags |= 0x0400; /* authority-bit */
329 head->nansw = htons(1);
331 // copy query block to answer block
333 memcpy(answb, from, len);
336 // and append answer rr
337 *(uint32_t *) next = htonl(ttl);
339 *(uint16_t *) next = htons(outr.rlen);
341 memcpy(next, (void *)answstr, outr.rlen);
346 flags = ntohs(head->flags);
347 // clear rcode and RA, set responsebit and our new flags
348 flags |= (outr.flags & 0xff80) | 0x8000;
349 head->flags = htons(flags);
350 head->nauth = head->nadd = htons(0);
351 head->nquer = htons(1);
353 packet_len = next - (void *)buf;
360 static void interrupt(int x)
363 write(2, "interrupt exiting\n", 18);
367 #define is_daemon() (flags&16)
368 #define is_verbose() (flags&32)
371 int dnsd_main(int argc, char **argv)
375 uint8_t buf[MAX_PACK_LEN];
376 unsigned long flags = 0;
377 char *listen_interface = "0.0.0.0";
378 char *sttl=NULL, *sport=NULL;
381 flags = bb_getopt_ulflags(argc, argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
383 if(!(ttl = atol(sttl)))
386 if(!(port = atol(sport)))
390 fprintf(stderr,"listen_interface: %s\n", listen_interface);
391 fprintf(stderr,"ttl: %d, port: %d\n", ttl, port);
392 fprintf(stderr,"fileconf: %s\n", fileconf);
397 /* reexec for vfork() do continue parent */
398 vfork_daemon_rexec(1, 0, argc, argv, "-d");
403 dnsentryinit(is_verbose());
405 signal(SIGINT, interrupt);
406 signal(SIGPIPE, SIG_IGN);
407 signal(SIGHUP, SIG_IGN);
409 signal(SIGTSTP, SIG_IGN);
412 signal(SIGURG, SIG_IGN);
415 udps = listen_socket(listen_interface, port);
424 FD_SET(udps, &fdset);
425 // Block until a message arrives
426 if((r = select(udps + 1, &fdset, NULL, NULL, NULL)) < 0)
427 bb_perror_msg_and_die("select error");
430 bb_perror_msg_and_die("select spurious return");
432 /* Can this test ever be false? */
433 if (FD_ISSET(udps, &fdset)) {
434 struct sockaddr_in from;
435 int fromlen = sizeof(from);
436 r = recvfrom(udps, buf, sizeof(buf), 0,
437 (struct sockaddr *)&from,
440 fprintf(stderr, "\n--- Got UDP ");
441 log_message(LOG_FILE, "\n--- Got UDP ");
443 if (r < 12 || r > 512) {
444 bb_error_msg("invalid packet size");
448 r = process_packet(buf);
451 r, 0, (struct sockaddr *)&from,