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 source tree.
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.
20 //usage:#define dnsd_trivial_usage
21 //usage: "[-dvs] [-c CONFFILE] [-t TTL_SEC] [-p PORT] [-i ADDR]"
22 //usage:#define dnsd_full_usage "\n\n"
23 //usage: "Small static DNS server daemon\n"
25 //usage: "\n -c FILE Config file"
26 //usage: "\n -t SEC TTL"
27 //usage: "\n -p PORT Listen on PORT"
28 //usage: "\n -i ADDR Listen on ADDR"
29 //usage: "\n -d Daemonize"
30 //usage: "\n -v Verbose"
31 //usage: "\n -s Send successful replies only. Use this if you want"
32 //usage: "\n to use /etc/resolv.conf with two nameserver lines:"
33 //usage: "\n nameserver DNSD_SERVER"
34 //usage: "\n nameserver NORNAL_DNS_SERVER"
46 /* cannot get bigger packets than 512 per RFC1035. */
48 IP_STRING_LEN = sizeof(".xxx.xxx.xxx.xxx"),
49 MAX_NAME_LEN = IP_STRING_LEN - 1 + sizeof(".in-addr.arpa"),
54 /* the message from client and first part of response msg */
63 /* Structure used to access type and class fields.
64 * They are totally unaligned, but gcc 4.3.4 thinks that pointer of type uint16_t*
65 * is 16-bit aligned and replaces 16-bit memcpy (in move_from_unaligned16 macro)
66 * with aligned halfword access on arm920t!
67 * Oh well. Slapping PACKED everywhere seems to help: */
68 struct type_and_class {
70 uint16_t class PACKED;
72 /* element of known name, ip address and reversed ip address */
74 struct dns_entry *next;
76 char rip[IP_STRING_LEN]; /* length decimal reversed IP */
80 #define OPT_verbose (option_mask32 & 1)
81 #define OPT_silent (option_mask32 & 2)
85 * Insert length of substrings instead of dots
87 static void undot(char *rip)
94 for (--i; i >= 0; i--) {
105 * Read hostname/IP records from file
107 static struct dns_entry *parse_conf_file(const char *fileconf)
111 struct dns_entry *m, *conf_data;
112 struct dns_entry **nextp;
117 parser = config_open(fileconf);
118 while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
122 if (inet_aton(token[1], &ip) == 0) {
123 bb_error_msg("error at line %u, skipping", parser->lineno);
128 bb_error_msg("name:%s, ip:%s", token[0], token[1]);
130 /* sizeof(*m) includes 1 byte for m->name[0] */
131 m = xzalloc(sizeof(*m) + strlen(token[0]) + 1);
137 strcpy(m->name + 1, token[0]);
139 m->ip = ip.s_addr; /* in network order */
142 sprintf(m->rip, ".%u.%u.%u.%u",
145 (uint8_t)(v32 >> 16),
150 config_close(parser);
155 * Look query up in dns records and return answer if found.
157 static char *table_lookup(struct dns_entry *d,
162 unsigned len = d->name[0];
163 /* d->name[len] is the last (non NUL) char */
166 q = query_string + 1;
168 fprintf(stderr, "%d/%d p:%s q:%s %d\n",
173 if (type == htons(REQ_A)) {
174 /* search by host name */
175 if (len != 1 || d->name[1] != '*') {
176 /* we are lax, hope no name component is ever >64 so that length
177 * (which will be represented as 'A','B'...) matches a lowercase letter.
178 * Actually, I think false matches are hard to construct.
180 * [31] len is represented as '1', [65] as 'A', [65+32] as 'a'.
181 * [65] <65 same chars>[31]<31 same chars>NUL
182 * [65+32]<65 same chars>1 <31 same chars>NUL
183 * This example seems to be the minimal case when false match occurs.
185 if (strcasecmp(d->name, query_string) != 0)
188 return (char *)&d->ip;
190 fprintf(stderr, "Found IP:%x\n", (int)d->ip);
194 /* search by IP-address */
195 if ((len != 1 || d->name[1] != '*')
196 /* we assume (do not check) that query_string
197 * ends in ".in-addr.arpa" */
198 && strncmp(d->rip, query_string, strlen(d->rip)) == 0
201 fprintf(stderr, "Found name:%s\n", d->name);
213 * Decode message and generate answer
217 Whenever an octet represents a numeric quantity, the left most bit
218 in the diagram is the high order or most significant bit.
219 That is, the bit labeled 0 is the most significant bit.
222 4.1.1. Header section format
223 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
224 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
226 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
227 |QR| OPCODE |AA|TC|RD|RA| 0 0 0| RCODE |
228 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
230 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
232 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
234 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
236 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
237 ID 16 bit random identifier assigned by querying peer.
238 Used to match query/response.
239 QR message is a query (0), or a response (1).
240 OPCODE 0 standard query (QUERY)
241 1 inverse query (IQUERY)
242 2 server status request (STATUS)
243 AA Authoritative Answer - this bit is valid in responses.
244 Responding name server is an authority for the domain name
245 in question section. Answer section may have multiple owner names
246 because of aliases. The AA bit corresponds to the name which matches
247 the query name, or the first owner name in the answer section.
248 TC TrunCation - this message was truncated.
249 RD Recursion Desired - this bit may be set in a query and
250 is copied into the response. If RD is set, it directs
251 the name server to pursue the query recursively.
252 Recursive query support is optional.
253 RA Recursion Available - this be is set or cleared in a
254 response, and denotes whether recursive query support is
255 available in the name server.
259 2 Server failure - server was unable to process the query
260 due to a problem with the name server.
261 3 Name Error - meaningful only for responses from
262 an authoritative name server. The referenced domain name
266 QDCOUNT number of entries in the question section.
267 ANCOUNT number of records in the answer section.
268 NSCOUNT number of records in the authority records section.
269 ARCOUNT number of records in the additional records section.
271 4.1.2. Question section format
273 The section contains QDCOUNT (usually 1) entries, each of this format:
274 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
275 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
278 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
280 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
282 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
283 QNAME a domain name represented as a sequence of labels, where
284 each label consists of a length octet followed by that
285 number of octets. The domain name terminates with the
286 zero length octet for the null label of the root. Note
287 that this field may be an odd number of octets; no
289 QTYPE a two octet type of the query.
290 1 a host address [REQ_A const]
291 2 an authoritative name server
292 3 a mail destination (Obsolete - use MX)
293 4 a mail forwarder (Obsolete - use MX)
294 5 the canonical name for an alias
295 6 marks the start of a zone of authority
296 7 a mailbox domain name (EXPERIMENTAL)
297 8 a mail group member (EXPERIMENTAL)
298 9 a mail rename domain name (EXPERIMENTAL)
299 10 a null RR (EXPERIMENTAL)
300 11 a well known service description
301 12 a domain name pointer [REQ_PTR const]
303 14 mailbox or mail list information
307 252 a request for a transfer of an entire zone
308 253 a request for mailbox-related records (MB, MG or MR)
309 254 a request for mail agent RRs (Obsolete - see MX)
310 255 a request for all records
311 QCLASS a two octet code that specifies the class of the query.
313 (others are historic only)
316 4.1.3. Resource Record format
318 The answer, authority, and additional sections all share the same format:
319 a variable number of resource records, where the number of records
320 is specified in the corresponding count field in the header.
321 Each resource record has this format:
322 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
323 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
326 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
328 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
330 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
333 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
335 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
338 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
339 NAME a domain name to which this resource record pertains.
340 TYPE two octets containing one of the RR type codes. This
341 field specifies the meaning of the data in the RDATA field.
342 CLASS two octets which specify the class of the data in the RDATA field.
343 TTL a 32 bit unsigned integer that specifies the time interval
344 (in seconds) that the record may be cached.
345 RDLENGTH a 16 bit integer, length in octets of the RDATA field.
346 RDATA a variable length string of octets that describes the resource.
347 The format of this information varies according to the TYPE
348 and CLASS of the resource record.
349 If the TYPE is A and the CLASS is IN, it's a 4 octet IP address.
351 4.1.4. Message compression
353 In order to reduce the size of messages, domain names coan be compressed.
354 An entire domain name or a list of labels at the end of a domain name
355 is replaced with a pointer to a prior occurance of the same name.
357 The pointer takes the form of a two octet sequence:
358 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
360 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
361 The first two bits are ones. This allows a pointer to be distinguished
362 from a label, since the label must begin with two zero bits because
363 labels are restricted to 63 octets or less. The OFFSET field specifies
364 an offset from the start of the message (i.e., the first octet
365 of the ID field in the domain header).
366 A zero offset specifies the first byte of the ID field, etc.
367 Domain name in a message can be represented as either:
368 - a sequence of labels ending in a zero octet
370 - a sequence of labels ending with a pointer
372 static int process_packet(struct dns_entry *conf_data,
376 struct dns_head *head;
377 struct type_and_class *unaligned_type_class;
388 head = (struct dns_head *)buf;
389 if (head->nquer == 0) {
390 bb_error_msg("packet has 0 queries, ignored");
391 return 0; /* don't reply */
393 if (head->flags & htons(0x8000)) { /* QR bit */
394 bb_error_msg("response packet, ignored");
395 return 0; /* don't reply */
397 /* QR = 1 "response", RCODE = 4 "Not Implemented" */
398 outr_flags = htons(0x8000 | 4);
401 /* start of query string */
402 query_string = (void *)(head + 1);
403 /* caller guarantees strlen is <= MAX_PACK_LEN */
404 query_len = strlen(query_string) + 1;
405 /* may be unaligned! */
406 unaligned_type_class = (void *)(query_string + query_len);
407 query_len += sizeof(*unaligned_type_class);
408 /* where to append answer block */
409 answb = (void *)(unaligned_type_class + 1);
411 /* OPCODE != 0 "standard query"? */
412 if ((head->flags & htons(0x7800)) != 0) {
413 err_msg = "opcode != 0";
416 move_from_unaligned16(class, &unaligned_type_class->class);
417 if (class != htons(1)) { /* not class INET? */
418 err_msg = "class != 1";
421 move_from_unaligned16(type, &unaligned_type_class->type);
422 if (type != htons(REQ_A) && type != htons(REQ_PTR)) {
423 /* we can't handle this query type */
424 //TODO: happens all the time with REQ_AAAA (0x1c) requests - implement those?
425 err_msg = "type is !REQ_A and !REQ_PTR";
429 /* look up the name */
430 answstr = table_lookup(conf_data, type, query_string);
432 /* Shows lengths instead of dots, unusable for !DEBUG */
433 bb_error_msg("'%s'->'%s'", query_string, answstr);
436 if (answstr && type == htons(REQ_PTR)) {
437 /* returning a host name */
438 outr_rlen = strlen(answstr) + 1;
441 || (unsigned)(answb - buf) + query_len + 4 + 2 + outr_rlen > MAX_PACK_LEN
444 * AA = 1 "Authoritative Answer"
445 * RCODE = 3 "Name Error" */
446 err_msg = "name is not found";
447 outr_flags = htons(0x8000 | 0x0400 | 3);
451 /* Append answer Resource Record */
452 memcpy(answb, query_string, query_len); /* name, type, class */
454 move_to_unaligned32((uint32_t *)answb, htonl(conf_ttl));
456 move_to_unaligned16((uint16_t *)answb, htons(outr_rlen));
458 memcpy(answb, answstr, outr_rlen);
461 /* QR = 1 "response",
462 * AA = 1 "Authoritative Answer",
463 * TODO: need to set RA bit 0x80? One user says nslookup complains
464 * "Got recursion not available from SERVER, trying next server"
465 * "** server can't find HOSTNAME"
466 * RCODE = 0 "success"
469 bb_error_msg("returning positive reply");
470 outr_flags = htons(0x8000 | 0x0400 | 0);
471 /* we have one answer */
472 head->nansw = htons(1);
475 if ((outr_flags & htons(0xf)) != 0) { /* not a positive response */
477 bb_error_msg("%s, %s",
479 OPT_silent ? "dropping query" : "sending error reply"
485 head->flags |= outr_flags;
486 head->nauth = head->nadd = 0;
487 head->nquer = htons(1); // why???
492 int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
493 int dnsd_main(int argc UNUSED_PARAM, char **argv)
495 const char *listen_interface = "0.0.0.0";
496 const char *fileconf = "/etc/dnsd.conf";
497 struct dns_entry *conf_data;
498 uint32_t conf_ttl = DEFAULT_TTL;
500 len_and_sockaddr *lsa, *from, *to;
504 /* Ensure buf is 32bit aligned (we need 16bit, but 32bit can't hurt) */
505 uint8_t buf[MAX_PACK_LEN + 1] ALIGN4;
507 opts = getopt32(argv, "vsi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
508 //if (opts & (1 << 0)) // -v
509 //if (opts & (1 << 1)) // -s
510 //if (opts & (1 << 2)) // -i
511 //if (opts & (1 << 3)) // -c
512 if (opts & (1 << 4)) // -t
513 conf_ttl = xatou_range(sttl, 1, 0xffffffff);
514 if (opts & (1 << 5)) // -p
515 port = xatou_range(sport, 1, 0xffff);
516 if (opts & (1 << 6)) { // -d
517 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
518 openlog(applet_name, LOG_PID, LOG_DAEMON);
519 logmode = LOGMODE_SYSLOG;
522 conf_data = parse_conf_file(fileconf);
524 lsa = xdotted2sockaddr(listen_interface, port);
525 udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
526 xbind(udps, &lsa->u.sa, lsa->len);
527 socket_want_pktinfo(udps); /* needed for recv_from_to to work */
528 lsa_size = LSA_LEN_SIZE + lsa->len;
529 from = xzalloc(lsa_size);
530 to = xzalloc(lsa_size);
533 char *p = xmalloc_sockaddr2dotted(&lsa->u.sa);
534 bb_error_msg("accepting UDP packets on %s", p);
540 /* Try to get *DEST* address (to which of our addresses
541 * this query was directed), and reply from the same address.
542 * Or else we can exhibit usual UDP ugliness:
543 * [ip1.multihomed.ip2] <= query to ip1 <= peer
544 * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
545 memcpy(to, lsa, lsa_size);
546 r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
547 if (r < 12 || r > MAX_PACK_LEN) {
548 bb_error_msg("packet size %d, ignored", r);
552 bb_error_msg("got UDP packet");
553 buf[r] = '\0'; /* paranoia */
554 r = process_packet(conf_data, conf_ttl, buf);
557 send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);