2 * Mini DNS server implementation for busybox
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.
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/
14 * Some bugfix and minor changes was applied by Roberto A. Foglietta who made
15 * the first porting of oao' scdns to busybox also.
21 #include <arpa/inet.h>
25 static char *fileconf = "/etc/dnsd.conf";
26 #define LOCK_FILE "/var/run/dnsd.lock"
27 #define LOG_FILE "/var/log/dnsd.log"
29 #define MAX_HOST_LEN 16 // longest host name allowed is 15
30 #define IP_STRING_LEN 18 // .xxx.xxx.xxx.xxx\0
32 //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
33 static const int MAX_NAME_LEN = (IP_STRING_LEN + 13);
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
41 static const int MAX_PACK_LEN = 512 + 1;
43 #define DEFAULT_TTL 30; // increase this when not testing?
45 static const int REQ_A = 1;
46 static const int REQ_PTR = 12;
48 struct dns_repl { // resource record, add 0 or 1 to accepted dns_msg in resp
50 uint8_t *r; // resource
54 struct dns_head { // the message from client and first part of response mag
57 uint16_t nquer; // accepts 0
58 uint16_t nansw; // 1 in response
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];
73 static struct dns_entry *dnsentry = NULL;
74 static int daemonmode = 0;
75 static uint32_t ttl = DEFAULT_TTL;
78 * Convert host name from C-string to dns length/string.
81 convname(char *a, uint8_t *q)
83 int i = (q[0] == '.')?0:1;
84 for(; i < MAX_HOST_LEN-1 && *q; i++, q++)
91 * Insert length of substrings insetad of dots
98 for(--i; i >= 0; i--) {
107 * Append message to log file
110 log_message(char *filename, char *message)
115 logfile = fopen(filename, "a");
118 fprintf(logfile, "%s\n", message);
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.
132 getfileentry(FILE * fp, struct dns_entry *s, int verb)
134 unsigned int a,b,c,d;
138 if(!(r = bb_get_line_from_file(fp)))
140 while(*r == ' ' || *r == '\t') {
142 if(!*r || *r == '#' || *r == '\n')
143 goto restart; /* skipping empty/blank and commented lines */
146 while(*r != ' ' && *r != '\t')
149 if(sscanf(r,"%u.%u.%u.%u",&a,&b,&c,&d) != 4)
150 goto restart; /* skipping wrong lines */
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);
158 fprintf(stderr,"\tname:%s, ip:%s\n",&(s->name[1]),s->ip);
160 return 0; /* warningkiller */
164 * Read hostname/IP records from file
167 dnsentryinit(int verb)
170 struct dns_entry *m, *prev;
171 prev = dnsentry = NULL;
173 if(!(fp = fopen(fileconf, "r")))
174 bb_perror_msg_and_die("open %s",fileconf);
177 if(!(m = (struct dns_entry *)malloc(sizeof(struct dns_entry))))
178 bb_perror_msg_and_die("malloc dns_entry");
181 if (getfileentry(fp, m, verb))
198 listen_socket(char *iface_addr, int listen_port)
200 struct sockaddr_in a;
204 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
205 bb_perror_msg_and_die("socket() failed");
207 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes)) < 0)
208 bb_perror_msg_and_die("setsockopt() failed");
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");
218 sprintf(msg, "accepting UDP packets on addr:port %s:%d\n",
219 iface_addr, (int)listen_port);
220 log_message(LOG_FILE, msg);
225 * Look query up in dns records and return answer if found
226 * qs is the query string, first byte the string length
229 table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
232 struct dns_entry *d=dnsentry;
237 q = (char *)&(qs[1]);
239 fprintf(stderr, "\ntest: %d <%s> <%s> %d", strlen(p), p, q, strlen(q));
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])
246 fprintf(stderr, " OK");
248 strcpy((char *)as, d->ip);
250 fprintf(stderr, " %s ", as);
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);
260 } while ((d = d->next) != NULL);
266 * Decode message and generate answer
268 #define eret(s) do { fprintf (stderr, "%s\n", s); return -1; } while (0)
270 process_packet(uint8_t * buf)
272 struct dns_head *head;
273 struct dns_prop *qprop;
274 struct dns_repl outr;
275 void *next, *from, *answb;
277 uint8_t answstr[MAX_NAME_LEN + 1];
278 int lookup_result, type, len, packet_len;
283 head = (struct dns_head *)buf;
284 if (head->nquer == 0)
287 if ((head->flags & 0x8000))
288 eret("ignoring response packet");
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
293 outr.rlen = 0; // may change later
297 qprop = (struct dns_prop *)(answb - 4);
298 type = ntohs(qprop->type);
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 */
305 if (ntohs(qprop->class) != 1 /* class INET */ ) {
306 outr.flags = 4; /* not supported */
309 /* we only support standard queries */
311 if ((ntohs(head->flags) & 0x7800) != 0)
314 // We have a standard query
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
322 if (type == REQ_A) { // return an address
324 if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
325 outr.flags = 1; /* Frmt err */
328 memcpy(answstr, &a.s_addr, 4); // save before a disappears
329 outr.rlen = 4; // uint32_t IP
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 */
336 head->nansw = htons(1);
338 // copy query block to answer block
340 memcpy(answb, from, len);
343 // and append answer rr
344 *(uint32_t *) next = htonl(ttl);
346 *(uint16_t *) next = htons(outr.rlen);
348 memcpy(next, (void *)answstr, outr.rlen);
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);
360 packet_len = next - (void *)buf;
371 write(2, "interrupt exiting\n", 18);
375 #define is_daemon() (flags&16)
376 #define is_verbose() (flags&32)
379 int dnsd_main(int argc, char **argv)
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;
389 flags = bb_getopt_ulflags(argc, argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
391 if(!(ttl = atol(sttl)))
394 if(!(port = atol(sport)))
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);
404 #if defined(__uClinux__)
405 /* reexec for vfork() do continue parent */
406 vfork_daemon_rexec(1, 0, argc, argv, "-d");
408 if (daemon(1, 0) < 0) {
409 bb_perror_msg_and_die("daemon");
411 #endif /* uClinuvx */
413 dnsentryinit(is_verbose());
415 signal(SIGINT, interrupt);
416 signal(SIGPIPE, SIG_IGN);
417 signal(SIGHUP, SIG_IGN);
419 signal(SIGTSTP, SIG_IGN);
422 signal(SIGURG, SIG_IGN);
425 udps = listen_socket(listen_interface, port);
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");
440 bb_perror_msg_and_die("select spurious return");
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,
450 fprintf(stderr, "\n--- Got UDP ");
451 log_message(LOG_FILE, "\n--- Got UDP ");
453 if (r < 12 || r > 512) {
454 bb_error_msg("invalid packet size");
458 r = process_packet(buf);
461 r, 0, (struct sockaddr *)&from,