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>
22 #include <sys/socket.h>
26 static char *fileconf = "/etc/dnsd.conf";
27 #define LOCK_FILE "/var/run/dnsd.lock"
28 #define LOG_FILE "/var/log/dnsd.log"
30 #define MAX_HOST_LEN 16 // longest host name allowed is 15
31 #define IP_STRING_LEN 18 // .xxx.xxx.xxx.xxx\0
33 //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
34 static const int MAX_NAME_LEN = (IP_STRING_LEN + 13);
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
42 static const int MAX_PACK_LEN = 512 + 1;
44 #define DEFAULT_TTL 30; // increase this when not testing?
46 static const int REQ_A = 1;
47 static const int REQ_PTR = 12;
49 struct dns_repl { // resource record, add 0 or 1 to accepted dns_msg in resp
51 uint8_t *r; // resource
55 struct dns_head { // the message from client and first part of response mag
58 uint16_t nquer; // accepts 0
59 uint16_t nansw; // 1 in response
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];
74 static struct dns_entry *dnsentry = NULL;
75 static int daemonmode = 0;
76 static uint32_t ttl = DEFAULT_TTL;
79 * Convert host name from C-string to dns length/string.
82 convname(char *a, uint8_t *q)
84 int i = (q[0] == '.') ? 0 : 1;
85 for(; i < MAX_HOST_LEN-1 && *q; i++, q++)
92 * Insert length of substrings insetad of dots
99 for(--i; i >= 0; i--) {
108 * Append message to log file
111 log_message(char *filename, char *message)
116 logfile = fopen(filename, "a");
119 fprintf(logfile, "%s\n", message);
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.
133 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
168 dnsentryinit(int verb)
171 struct dns_entry *m, *prev;
172 prev = dnsentry = NULL;
174 if(!(fp = fopen(fileconf, "r")))
175 bb_perror_msg_and_die("open %s",fileconf);
178 if(!(m = (struct dns_entry *)malloc(sizeof(struct dns_entry))))
179 bb_perror_msg_and_die("malloc dns_entry");
182 if (getfileentry(fp, m, verb))
199 listen_socket(char *iface_addr, int listen_port)
201 struct sockaddr_in a;
205 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
206 bb_perror_msg_and_die("socket() failed");
208 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes)) < 0)
209 bb_perror_msg_and_die("setsockopt() failed");
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");
219 sprintf(msg, "accepting UDP packets on addr:port %s:%d\n",
220 iface_addr, (int)listen_port);
221 log_message(LOG_FILE, msg);
226 * Look query up in dns records and return answer if found
227 * qs is the query string, first byte the string length
230 table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
233 struct dns_entry *d=dnsentry;
238 q = (char *)&(qs[1]);
240 fprintf(stderr, "\ntest: %d <%s> <%s> %d", strlen(p), p, q, strlen(q));
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])
247 fprintf(stderr, " OK");
249 strcpy((char *)as, d->ip);
251 fprintf(stderr, " %s ", as);
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);
261 } while ((d = d->next) != NULL);
267 * Decode message and generate answer
269 #define eret(s) do { fprintf (stderr, "%s\n", s); return -1; } while (0)
271 process_packet(uint8_t * buf)
273 struct dns_head *head;
274 struct dns_prop *qprop;
275 struct dns_repl outr;
276 void *next, *from, *answb;
278 uint8_t answstr[MAX_NAME_LEN + 1];
279 int lookup_result, type, len, packet_len;
284 head = (struct dns_head *)buf;
285 if (head->nquer == 0)
288 if ((head->flags & 0x8000))
289 eret("ignoring response packet");
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
294 outr.rlen = 0; // may change later
298 qprop = (struct dns_prop *)(answb - 4);
299 type = ntohs(qprop->type);
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 */
306 if (ntohs(qprop->class) != 1 /* class INET */ ) {
307 outr.flags = 4; /* not supported */
310 /* we only support standard queries */
312 if ((ntohs(head->flags) & 0x7800) != 0)
315 // We have a standard query
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
323 if (type == REQ_A) { // return an address
325 if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
326 outr.flags = 1; /* Frmt err */
329 memcpy(answstr, &a.s_addr, 4); // save before a disappears
330 outr.rlen = 4; // uint32_t IP
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 */
337 head->nansw = htons(1);
339 // copy query block to answer block
341 memcpy(answb, from, len);
344 // and append answer rr
345 *(uint32_t *) next = htonl(ttl);
347 *(uint16_t *) next = htons(outr.rlen);
349 memcpy(next, (void *)answstr, outr.rlen);
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);
361 packet_len = next - (void *)buf;
372 write(2, "interrupt exiting\n", 18);
376 #define is_daemon() (flags&16)
377 #define is_verbose() (flags&32)
380 int dnsd_main(int argc, char **argv)
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;
390 flags = bb_getopt_ulflags(argc, argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
392 if(!(ttl = atol(sttl)))
395 if(!(port = atol(sport)))
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);
405 #if defined(__uClinux__)
406 /* reexec for vfork() do continue parent */
407 vfork_daemon_rexec(1, 0, argc, argv, "-d");
409 if (daemon(1, 0) < 0) {
410 bb_perror_msg_and_die("daemon");
412 #endif /* uClinuvx */
414 dnsentryinit(is_verbose());
416 signal(SIGINT, interrupt);
417 signal(SIGPIPE, SIG_IGN);
418 signal(SIGHUP, SIG_IGN);
420 signal(SIGTSTP, SIG_IGN);
423 signal(SIGURG, SIG_IGN);
426 udps = listen_socket(listen_interface, port);
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");
441 bb_perror_msg_and_die("select spurious return");
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,
451 fprintf(stderr, "\n--- Got UDP ");
452 log_message(LOG_FILE, "\n--- Got UDP ");
454 if (r < 12 || r > 512) {
455 bb_error_msg("invalid packet size");
459 r = process_packet(buf);
462 r, 0, (struct sockaddr *)&from,