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
8 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10 * Odd Arild Olsen started out with the sheerdns [1] of Paul Sheer and rewrote
11 * it into a shape which I believe is both easier to understand and maintain.
12 * I also reused the input buffer for output and removed services he did not
13 * need. [1] http://threading.2038bug.com/sheerdns/
15 * Some bugfix and minor changes was applied by Roberto A. Foglietta who made
16 * the first porting of oao' scdns to busybox also.
22 #include <arpa/inet.h>
23 #include <sys/socket.h>
27 static char *fileconf = "/etc/dnsd.conf";
28 #define LOCK_FILE "/var/run/dnsd.lock"
29 #define LOG_FILE "/var/log/dnsd.log"
32 MAX_HOST_LEN = 16, // longest host name allowed is 15
33 IP_STRING_LEN = 18, // .xxx.xxx.xxx.xxx\0
35 //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
36 MAX_NAME_LEN = (IP_STRING_LEN + 13),
38 /* Cannot get bigger packets than 512 per RFC1035
39 In practice this can be set considerably smaller:
40 Length of response packet is header (12B) + 2*type(4B) + 2*class(4B) +
41 ttl(4B) + rlen(2B) + r (MAX_NAME_LEN =21B) +
42 2*querystring (2 MAX_NAME_LEN= 42B), all together 90 Byte
44 MAX_PACK_LEN = 512 + 1,
46 DEFAULT_TTL = 30, // increase this when not testing?
52 struct dns_repl { // resource record, add 0 or 1 to accepted dns_msg in resp
54 uint8_t *r; // resource
58 struct dns_head { // the message from client and first part of response mag
61 uint16_t nquer; // accepts 0
62 uint16_t nansw; // 1 in response
70 struct dns_entry { // element of known name, ip address and reversed ip address
71 struct dns_entry *next;
72 char ip[IP_STRING_LEN]; // dotted decimal IP
73 char rip[IP_STRING_LEN]; // length decimal reversed IP
74 char name[MAX_HOST_LEN];
77 static struct dns_entry *dnsentry = NULL;
78 static int daemonmode = 0;
79 static uint32_t ttl = DEFAULT_TTL;
82 * Convert host name from C-string to dns length/string.
85 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 insetad of dots
102 for(--i; i >= 0; i--) {
111 * Append message to log file
114 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.
136 getfileentry(FILE * fp, struct dns_entry *s, int verb)
138 unsigned int a,b,c,d;
142 if(!(r = bb_get_line_from_file(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);
164 return 0; /* warningkiller */
168 * Read hostname/IP records from file
171 dnsentryinit(int verb)
174 struct dns_entry *m, *prev;
175 prev = dnsentry = NULL;
177 if(!(fp = fopen(fileconf, "r")))
178 bb_perror_msg_and_die("open %s",fileconf);
181 if(!(m = (struct dns_entry *)malloc(sizeof(struct dns_entry))))
182 bb_perror_msg_and_die("malloc dns_entry");
185 if (getfileentry(fp, m, verb))
202 listen_socket(char *iface_addr, int listen_port)
204 struct sockaddr_in a;
208 s = bb_xsocket(PF_INET, SOCK_DGRAM, 0);
210 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes)) < 0)
211 bb_perror_msg_and_die("setsockopt() failed");
213 memset(&a, 0, sizeof(a));
214 a.sin_port = htons(listen_port);
215 a.sin_family = AF_INET;
216 if (!inet_aton(iface_addr, &a.sin_addr))
217 bb_perror_msg_and_die("bad iface address");
218 if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0)
219 bb_perror_msg_and_die("bind() failed");
221 sprintf(msg, "accepting UDP packets on addr:port %s:%d\n",
222 iface_addr, (int)listen_port);
223 log_message(LOG_FILE, msg);
228 * Look query up in dns records and return answer if found
229 * qs is the query string, first byte the string length
232 table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
235 struct dns_entry *d=dnsentry;
240 q = (char *)&(qs[1]);
242 fprintf(stderr, "\ntest: %d <%s> <%s> %d", strlen(p), p, q, strlen(q));
244 if (type == REQ_A) { /* search by host name */
245 for(i = 1; i <= (int)(d->name[0]); i++)
246 if(tolower(qs[i]) != d->name[i])
249 fprintf(stderr, " OK");
251 strcpy((char *)as, d->ip);
253 fprintf(stderr, " %s ", as);
257 else if (type == REQ_PTR) { /* search by IP-address */
258 if (!strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
259 strcpy((char *)as, d->name);
263 } while ((d = d->next) != NULL);
269 * Decode message and generate answer
271 #define eret(s) do { fprintf (stderr, "%s\n", s); return -1; } while (0)
273 process_packet(uint8_t * buf)
275 struct dns_head *head;
276 struct dns_prop *qprop;
277 struct dns_repl outr;
278 void *next, *from, *answb;
280 uint8_t answstr[MAX_NAME_LEN + 1];
281 int lookup_result, type, len, packet_len;
286 head = (struct dns_head *)buf;
287 if (head->nquer == 0)
290 if ((head->flags & 0x8000))
291 eret("ignoring response packet");
293 from = (void *)&head[1]; // start of query string
294 next = answb = from + strlen((char *)&head[1]) + 1 + sizeof(struct dns_prop); // where to append answer block
296 outr.rlen = 0; // may change later
300 qprop = (struct dns_prop *)(answb - 4);
301 type = ntohs(qprop->type);
303 // only let REQ_A and REQ_PTR pass
304 if (!(type == REQ_A || type == REQ_PTR)) {
305 goto empty_packet; /* we can't handle the query type */
308 if (ntohs(qprop->class) != 1 /* class INET */ ) {
309 outr.flags = 4; /* not supported */
312 /* we only support standard queries */
314 if ((ntohs(head->flags) & 0x7800) != 0)
317 // We have a standard query
319 log_message(LOG_FILE, (char *)head);
320 lookup_result = table_lookup(type, answstr, (uint8_t*)(&head[1]));
321 if (lookup_result != 0) {
322 outr.flags = 3 | 0x0400; //name do not exist and auth
325 if (type == REQ_A) { // return an address
327 if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
328 outr.flags = 1; /* Frmt err */
331 memcpy(answstr, &a.s_addr, 4); // save before a disappears
332 outr.rlen = 4; // uint32_t IP
335 outr.rlen = strlen((char *)answstr) + 1; // a host name
336 outr.r = answstr; // 32 bit ip or a host name
337 outr.flags |= 0x0400; /* authority-bit */
339 head->nansw = htons(1);
341 // copy query block to answer block
343 memcpy(answb, from, len);
346 // and append answer rr
347 *(uint32_t *) next = htonl(ttl);
349 *(uint16_t *) next = htons(outr.rlen);
351 memcpy(next, (void *)answstr, outr.rlen);
356 flags = ntohs(head->flags);
357 // clear rcode and RA, set responsebit and our new flags
358 flags |= (outr.flags & 0xff80) | 0x8000;
359 head->flags = htons(flags);
360 head->nauth = head->nadd = htons(0);
361 head->nquer = htons(1);
363 packet_len = next - (void *)buf;
374 write(2, "interrupt exiting\n", 18);
378 #define is_daemon() (flags&16)
379 #define is_verbose() (flags&32)
382 int dnsd_main(int argc, char **argv)
386 uint8_t buf[MAX_PACK_LEN];
387 unsigned long flags = 0;
388 char *listen_interface = "0.0.0.0";
389 char *sttl=NULL, *sport=NULL;
392 flags = bb_getopt_ulflags(argc, argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
394 if(!(ttl = atol(sttl)))
397 if(!(port = atol(sport)))
401 fprintf(stderr,"listen_interface: %s\n", listen_interface);
402 fprintf(stderr,"ttl: %d, port: %d\n", ttl, port);
403 fprintf(stderr,"fileconf: %s\n", fileconf);
407 #if defined(__uClinux__)
408 /* reexec for vfork() do continue parent */
409 vfork_daemon_rexec(1, 0, argc, argv, "-d");
411 if (daemon(1, 0) < 0) {
412 bb_perror_msg_and_die("daemon");
414 #endif /* uClinuvx */
416 dnsentryinit(is_verbose());
418 signal(SIGINT, interrupt);
419 signal(SIGPIPE, SIG_IGN);
420 signal(SIGHUP, SIG_IGN);
422 signal(SIGTSTP, SIG_IGN);
425 signal(SIGURG, SIG_IGN);
428 udps = listen_socket(listen_interface, port);
437 FD_SET(udps, &fdset);
438 // Block until a message arrives
439 if((r = select(udps + 1, &fdset, NULL, NULL, NULL)) < 0)
440 bb_perror_msg_and_die("select error");
443 bb_perror_msg_and_die("select spurious return");
445 /* Can this test ever be false? */
446 if (FD_ISSET(udps, &fdset)) {
447 struct sockaddr_in from;
448 int fromlen = sizeof(from);
449 r = recvfrom(udps, buf, sizeof(buf), 0,
450 (struct sockaddr *)&from,
453 fprintf(stderr, "\n--- Got UDP ");
454 log_message(LOG_FILE, "\n--- Got UDP ");
456 if (r < 12 || r > 512) {
457 bb_error_msg("invalid packet size");
461 r = process_packet(buf);
464 r, 0, (struct sockaddr *)&from,