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.
22 static char *fileconf = "/etc/dnsd.conf";
23 #define LOCK_FILE "/var/run/dnsd.lock"
24 #define LOG_FILE "/var/log/dnsd.log"
26 // Must matct getopt32 call
27 #define OPT_daemon (option_mask32 & 0x10)
28 #define OPT_verbose (option_mask32 & 0x20)
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;
80 static int daemonmode;
81 static uint32_t ttl = DEFAULT_TTL;
84 * Convert host name from C-string to dns length/string.
86 static void convname(char *a, uint8_t *q)
88 int i = (q[0] == '.') ? 0 : 1;
89 for (; i < MAX_HOST_LEN-1 && *q; i++, q++)
96 * Insert length of substrings instead of dots
98 static void undot(uint8_t * rip)
103 for (--i; i >= 0; i--) {
112 * Append message to log file
114 static void log_message(char *filename, char *message)
119 logfile = fopen(filename, "a");
122 fprintf(logfile, "%s\n", message);
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.
135 static int getfileentry(FILE * fp, struct dns_entry *s)
137 unsigned int a,b,c,d;
141 r = xmalloc_fgets(fp);
144 while (*r == ' ' || *r == '\t') {
146 if (!*r || *r == '#' || *r == '\n')
147 goto restart; /* skipping empty/blank and commented lines */
150 while (*r != ' ' && *r != '\t')
153 if (sscanf(r, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
154 goto restart; /* skipping wrong lines */
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);
162 fprintf(stderr, "\tname:%s, ip:%s\n", &(s->name[1]),s->ip);
168 * Read hostname/IP records from file
170 static void dnsentryinit(void)
173 struct dns_entry *m, *prev;
174 prev = dnsentry = NULL;
176 fp = xfopen(fileconf, "r");
179 m = xmalloc(sizeof(struct dns_entry));
182 if (getfileentry(fp, m))
198 static int listen_socket(char *iface_addr, int listen_port)
200 struct sockaddr_in a;
203 s = xsocket(PF_INET, SOCK_DGRAM, 0);
204 if (setsockopt_reuseaddr(s) < 0)
205 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 xbind(s, (struct sockaddr *)&a, sizeof(a));
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, "\n%s: %d/%d p:%s q:%s %d",
234 __FUNCTION__, strlen(p), (int)(d->name[0]), p, q, strlen(q));
236 if (type == REQ_A) { /* search by host name */
237 for (i = 1; i <= (int)(d->name[0]); i++)
238 if (tolower(qs[i]) != d->name[i])
240 if (i > (int)(d->name[0])) {
242 fprintf(stderr, " OK");
244 strcpy((char *)as, d->ip);
246 fprintf(stderr, " as:%s\n", as);
251 if (type == REQ_PTR) { /* search by IP-address */
252 if (!strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
253 strcpy((char *)as, d->name);
264 * Decode message and generate answer
266 #define eret(s) do { fputs(s, stderr); return -1; } while (0)
267 static int process_packet(uint8_t * buf)
269 struct dns_head *head;
270 struct dns_prop *qprop;
271 struct dns_repl outr;
272 void *next, *from, *answb;
274 uint8_t answstr[MAX_NAME_LEN + 1];
275 int lookup_result, type, len, packet_len;
280 head = (struct dns_head *)buf;
281 if (head->nquer == 0)
282 eret("no queries\n");
284 if (head->flags & 0x8000)
285 eret("ignoring response packet\n");
287 from = (void *)&head[1]; // start of query string
288 next = answb = from + strlen((char *)from) + 1 + sizeof(struct dns_prop); // where to append answer block
290 outr.rlen = 0; // may change later
294 qprop = (struct dns_prop *)(answb - 4);
295 type = ntohs(qprop->type);
297 // only let REQ_A and REQ_PTR pass
298 if (!(type == REQ_A || type == REQ_PTR)) {
299 goto empty_packet; /* we can't handle the query type */
302 if (ntohs(qprop->class) != 1 /* class INET */ ) {
303 outr.flags = 4; /* not supported */
306 /* we only support standard queries */
308 if ((ntohs(head->flags) & 0x7800) != 0)
311 // We have a standard query
312 log_message(LOG_FILE, (char *)from);
313 lookup_result = table_lookup(type, answstr, (uint8_t*)from);
314 if (lookup_result != 0) {
315 outr.flags = 3 | 0x0400; //name do not exist and auth
318 if (type == REQ_A) { // return an address
320 if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
321 outr.flags = 1; /* Frmt err */
324 memcpy(answstr, &a.s_addr, 4); // save before a disappears
325 outr.rlen = 4; // uint32_t IP
328 outr.rlen = strlen((char *)answstr) + 1; // a host name
329 outr.r = answstr; // 32 bit ip or a host name
330 outr.flags |= 0x0400; /* authority-bit */
332 head->nansw = htons(1);
334 // copy query block to answer block
336 memcpy(answb, from, len);
339 // and append answer rr
340 *(uint32_t *) next = htonl(ttl);
342 *(uint16_t *) next = htons(outr.rlen);
344 memcpy(next, (void *)answstr, outr.rlen);
349 flags = ntohs(head->flags);
350 // clear rcode and RA, set responsebit and our new flags
351 flags |= (outr.flags & 0xff80) | 0x8000;
352 head->flags = htons(flags);
353 head->nauth = head->nadd = htons(0);
354 head->nquer = htons(1);
356 packet_len = next - (void *)buf;
363 static void interrupt(int x)
366 write(2, "interrupt exiting\n", 18);
370 int dnsd_main(int argc, char **argv)
374 uint8_t buf[MAX_PACK_LEN];
375 char *listen_interface = "0.0.0.0";
378 getopt32(argc, argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
379 //if (option_mask32 & 0x1) // -i
380 //if (option_mask32 & 0x2) // -c
381 if (option_mask32 & 0x4) // -t
382 if (!(ttl = atol(sttl)))
384 if (option_mask32 & 0x8) // -p
385 if (!(port = atol(sport)))
389 bb_info_msg("listen_interface: %s", listen_interface);
390 bb_info_msg("ttl: %d, port: %d", ttl, port);
391 bb_info_msg("fileconf: %s", fileconf);
396 /* reexec for vfork() do continue parent */
397 vfork_daemon_rexec(1, 0, argc, argv, "-d");
404 signal(SIGINT, interrupt);
405 signal(SIGPIPE, SIG_IGN);
406 signal(SIGHUP, SIG_IGN);
408 signal(SIGTSTP, SIG_IGN);
411 signal(SIGURG, SIG_IGN);
414 udps = listen_socket(listen_interface, port);
423 FD_SET(udps, &fdset);
424 // Block until a message arrives
425 r = select(udps + 1, &fdset, NULL, NULL, NULL);
427 bb_perror_msg_and_die("select error");
429 bb_perror_msg_and_die("select spurious return");
431 /* Can this test ever be false? - yes */
432 if (FD_ISSET(udps, &fdset)) {
433 struct sockaddr_in from;
434 int fromlen = sizeof(from);
435 r = recvfrom(udps, buf, sizeof(buf), 0,
436 (struct sockaddr *)&from,
439 fprintf(stderr, "\n--- Got UDP ");
440 log_message(LOG_FILE, "\n--- Got UDP ");
442 if (r < 12 || r > 512) {
443 bb_error_msg("invalid packet size");
447 r = process_packet(buf);
450 r, 0, (struct sockaddr *)&from,