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"
24 //usage: "\n -c FILE Config file"
25 //usage: "\n -t SEC TTL"
26 //usage: "\n -p PORT Listen on PORT"
27 //usage: "\n -i ADDR Listen on ADDR"
28 //usage: "\n -d Daemonize"
29 //usage: "\n -v Verbose"
30 //usage: "\n -s Send successful replies only. Use this if you want"
31 //usage: "\n to use /etc/resolv.conf with two nameserver lines:"
32 //usage: "\n nameserver DNSD_SERVER"
33 //usage: "\n nameserver NORMAL_DNS_SERVER"
45 /* cannot get bigger packets than 512 per RFC1035. */
47 IP_STRING_LEN = sizeof(".xxx.xxx.xxx.xxx"),
48 MAX_NAME_LEN = IP_STRING_LEN - 1 + sizeof(".in-addr.arpa"),
53 /* the message from client and first part of response msg */
62 /* Structure used to access type and class fields.
63 * They are totally unaligned, but gcc 4.3.4 thinks that pointer of type uint16_t*
64 * is 16-bit aligned and replaces 16-bit memcpy (in move_from_unaligned16 macro)
65 * with aligned halfword access on arm920t!
66 * Oh well. Slapping PACKED everywhere seems to help: */
67 struct type_and_class {
69 uint16_t class PACKED;
71 /* element of known name, ip address and reversed ip address */
73 struct dns_entry *next;
75 char rip[IP_STRING_LEN]; /* length decimal reversed IP */
79 #define OPT_verbose (option_mask32 & 1)
80 #define OPT_silent (option_mask32 & 2)
84 * Insert length of substrings instead of dots
86 static void undot(char *rip)
93 for (--i; i >= 0; i--) {
104 * Read hostname/IP records from file
106 static struct dns_entry *parse_conf_file(const char *fileconf)
110 struct dns_entry *m, *conf_data;
111 struct dns_entry **nextp;
116 parser = config_open(fileconf);
117 while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
121 if (inet_aton(token[1], &ip) == 0) {
122 bb_error_msg("error at line %u, skipping", parser->lineno);
127 bb_error_msg("name:%s, ip:%s", token[0], token[1]);
129 /* sizeof(*m) includes 1 byte for m->name[0] */
130 m = xzalloc(sizeof(*m) + strlen(token[0]) + 1);
136 strcpy(m->name + 1, token[0]);
138 m->ip = ip.s_addr; /* in network order */
141 sprintf(m->rip, ".%u.%u.%u.%u",
144 (uint8_t)(v32 >> 16),
149 config_close(parser);
154 * Look query up in dns records and return answer if found.
156 static char *table_lookup(struct dns_entry *d,
161 unsigned len = d->name[0];
162 /* d->name[len] is the last (non NUL) char */
165 q = query_string + 1;
167 fprintf(stderr, "%d/%d p:%s q:%s %d\n",
172 if (type == htons(REQ_A)) {
173 /* search by host name */
174 if (len != 1 || d->name[1] != '*') {
175 /* we are lax, hope no name component is ever >64 so that length
176 * (which will be represented as 'A','B'...) matches a lowercase letter.
177 * Actually, I think false matches are hard to construct.
179 * [31] len is represented as '1', [65] as 'A', [65+32] as 'a'.
180 * [65] <65 same chars>[31]<31 same chars>NUL
181 * [65+32]<65 same chars>1 <31 same chars>NUL
182 * This example seems to be the minimal case when false match occurs.
184 if (strcasecmp(d->name, query_string) != 0)
187 return (char *)&d->ip;
189 fprintf(stderr, "Found IP:%x\n", (int)d->ip);
193 /* search by IP-address */
194 if ((len != 1 || d->name[1] != '*')
195 /* we assume (do not check) that query_string
196 * ends in ".in-addr.arpa" */
197 && strncmp(d->rip, query_string, strlen(d->rip)) == 0
200 fprintf(stderr, "Found name:%s\n", d->name);
212 * Decode message and generate answer
216 Whenever an octet represents a numeric quantity, the left most bit
217 in the diagram is the high order or most significant bit.
218 That is, the bit labeled 0 is the most significant bit.
221 4.1.1. Header section format
222 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
223 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
225 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
226 |QR| OPCODE |AA|TC|RD|RA| 0 0 0| RCODE |
227 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
229 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
231 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
233 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
235 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
236 ID 16 bit random identifier assigned by querying peer.
237 Used to match query/response.
238 QR message is a query (0), or a response (1).
239 OPCODE 0 standard query (QUERY)
240 1 inverse query (IQUERY)
241 2 server status request (STATUS)
242 AA Authoritative Answer - this bit is valid in responses.
243 Responding name server is an authority for the domain name
244 in question section. Answer section may have multiple owner names
245 because of aliases. The AA bit corresponds to the name which matches
246 the query name, or the first owner name in the answer section.
247 TC TrunCation - this message was truncated.
248 RD Recursion Desired - this bit may be set in a query and
249 is copied into the response. If RD is set, it directs
250 the name server to pursue the query recursively.
251 Recursive query support is optional.
252 RA Recursion Available - this be is set or cleared in a
253 response, and denotes whether recursive query support is
254 available in the name server.
258 2 Server failure - server was unable to process the query
259 due to a problem with the name server.
260 3 Name Error - meaningful only for responses from
261 an authoritative name server. The referenced domain name
265 QDCOUNT number of entries in the question section.
266 ANCOUNT number of records in the answer section.
267 NSCOUNT number of records in the authority records section.
268 ARCOUNT number of records in the additional records section.
270 4.1.2. Question section format
272 The section contains QDCOUNT (usually 1) entries, each of this format:
273 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
274 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
277 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
279 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
281 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
282 QNAME a domain name represented as a sequence of labels, where
283 each label consists of a length octet followed by that
284 number of octets. The domain name terminates with the
285 zero length octet for the null label of the root. Note
286 that this field may be an odd number of octets; no
288 QTYPE a two octet type of the query.
289 1 a host address [REQ_A const]
290 2 an authoritative name server
291 3 a mail destination (Obsolete - use MX)
292 4 a mail forwarder (Obsolete - use MX)
293 5 the canonical name for an alias
294 6 marks the start of a zone of authority
295 7 a mailbox domain name (EXPERIMENTAL)
296 8 a mail group member (EXPERIMENTAL)
297 9 a mail rename domain name (EXPERIMENTAL)
298 10 a null RR (EXPERIMENTAL)
299 11 a well known service description
300 12 a domain name pointer [REQ_PTR const]
302 14 mailbox or mail list information
306 252 a request for a transfer of an entire zone
307 253 a request for mailbox-related records (MB, MG or MR)
308 254 a request for mail agent RRs (Obsolete - see MX)
309 255 a request for all records
310 QCLASS a two octet code that specifies the class of the query.
312 (others are historic only)
315 4.1.3. Resource Record format
317 The answer, authority, and additional sections all share the same format:
318 a variable number of resource records, where the number of records
319 is specified in the corresponding count field in the header.
320 Each resource record has this format:
321 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
322 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
325 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
327 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
329 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
332 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
334 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
337 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
338 NAME a domain name to which this resource record pertains.
339 TYPE two octets containing one of the RR type codes. This
340 field specifies the meaning of the data in the RDATA field.
341 CLASS two octets which specify the class of the data in the RDATA field.
342 TTL a 32 bit unsigned integer that specifies the time interval
343 (in seconds) that the record may be cached.
344 RDLENGTH a 16 bit integer, length in octets of the RDATA field.
345 RDATA a variable length string of octets that describes the resource.
346 The format of this information varies according to the TYPE
347 and CLASS of the resource record.
348 If the TYPE is A and the CLASS is IN, it's a 4 octet IP address.
350 4.1.4. Message compression
352 In order to reduce the size of messages, domain names coan be compressed.
353 An entire domain name or a list of labels at the end of a domain name
354 is replaced with a pointer to a prior occurance of the same name.
356 The pointer takes the form of a two octet sequence:
357 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
359 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
360 The first two bits are ones. This allows a pointer to be distinguished
361 from a label, since the label must begin with two zero bits because
362 labels are restricted to 63 octets or less. The OFFSET field specifies
363 an offset from the start of the message (i.e., the first octet
364 of the ID field in the domain header).
365 A zero offset specifies the first byte of the ID field, etc.
366 Domain name in a message can be represented as either:
367 - a sequence of labels ending in a zero octet
369 - a sequence of labels ending with a pointer
371 static int process_packet(struct dns_entry *conf_data,
375 struct dns_head *head;
376 struct type_and_class *unaligned_type_class;
387 head = (struct dns_head *)buf;
388 if (head->nquer == 0) {
389 bb_error_msg("packet has 0 queries, ignored");
390 return 0; /* don't reply */
392 if (head->flags & htons(0x8000)) { /* QR bit */
393 bb_error_msg("response packet, ignored");
394 return 0; /* don't reply */
396 /* QR = 1 "response", RCODE = 4 "Not Implemented" */
397 outr_flags = htons(0x8000 | 4);
400 /* start of query string */
401 query_string = (void *)(head + 1);
402 /* caller guarantees strlen is <= MAX_PACK_LEN */
403 query_len = strlen(query_string) + 1;
404 /* may be unaligned! */
405 unaligned_type_class = (void *)(query_string + query_len);
406 query_len += sizeof(*unaligned_type_class);
407 /* where to append answer block */
408 answb = (void *)(unaligned_type_class + 1);
410 /* OPCODE != 0 "standard query"? */
411 if ((head->flags & htons(0x7800)) != 0) {
412 err_msg = "opcode != 0";
415 move_from_unaligned16(class, &unaligned_type_class->class);
416 if (class != htons(1)) { /* not class INET? */
417 err_msg = "class != 1";
420 move_from_unaligned16(type, &unaligned_type_class->type);
421 if (type != htons(REQ_A) && type != htons(REQ_PTR)) {
422 /* we can't handle this query type */
423 //TODO: happens all the time with REQ_AAAA (0x1c) requests - implement those?
424 err_msg = "type is !REQ_A and !REQ_PTR";
428 /* look up the name */
429 answstr = table_lookup(conf_data, type, query_string);
431 /* Shows lengths instead of dots, unusable for !DEBUG */
432 bb_error_msg("'%s'->'%s'", query_string, answstr);
435 if (answstr && type == htons(REQ_PTR)) {
436 /* returning a host name */
437 outr_rlen = strlen(answstr) + 1;
440 || (unsigned)(answb - buf) + query_len + 4 + 2 + outr_rlen > MAX_PACK_LEN
443 * AA = 1 "Authoritative Answer"
444 * RCODE = 3 "Name Error" */
445 err_msg = "name is not found";
446 outr_flags = htons(0x8000 | 0x0400 | 3);
450 /* Append answer Resource Record */
451 memcpy(answb, query_string, query_len); /* name, type, class */
453 move_to_unaligned32((uint32_t *)answb, htonl(conf_ttl));
455 move_to_unaligned16((uint16_t *)answb, htons(outr_rlen));
457 memcpy(answb, answstr, outr_rlen);
460 /* QR = 1 "response",
461 * AA = 1 "Authoritative Answer",
462 * TODO: need to set RA bit 0x80? One user says nslookup complains
463 * "Got recursion not available from SERVER, trying next server"
464 * "** server can't find HOSTNAME"
465 * RCODE = 0 "success"
468 bb_error_msg("returning positive reply");
469 outr_flags = htons(0x8000 | 0x0400 | 0);
470 /* we have one answer */
471 head->nansw = htons(1);
474 if ((outr_flags & htons(0xf)) != 0) { /* not a positive response */
476 bb_error_msg("%s, %s",
478 OPT_silent ? "dropping query" : "sending error reply"
484 head->flags |= outr_flags;
485 head->nauth = head->nadd = 0;
486 head->nquer = htons(1); // why???
491 int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
492 int dnsd_main(int argc UNUSED_PARAM, char **argv)
494 const char *listen_interface = "0.0.0.0";
495 const char *fileconf = "/etc/dnsd.conf";
496 struct dns_entry *conf_data;
497 uint32_t conf_ttl = DEFAULT_TTL;
499 len_and_sockaddr *lsa, *from, *to;
503 /* Ensure buf is 32bit aligned (we need 16bit, but 32bit can't hurt) */
504 uint8_t buf[MAX_PACK_LEN + 1] ALIGN4;
506 opts = getopt32(argv, "vsi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
507 //if (opts & (1 << 0)) // -v
508 //if (opts & (1 << 1)) // -s
509 //if (opts & (1 << 2)) // -i
510 //if (opts & (1 << 3)) // -c
511 if (opts & (1 << 4)) // -t
512 conf_ttl = xatou_range(sttl, 1, 0xffffffff);
513 if (opts & (1 << 5)) // -p
514 port = xatou_range(sport, 1, 0xffff);
515 if (opts & (1 << 6)) { // -d
516 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
517 openlog(applet_name, LOG_PID, LOG_DAEMON);
518 logmode = LOGMODE_SYSLOG;
521 conf_data = parse_conf_file(fileconf);
523 lsa = xdotted2sockaddr(listen_interface, port);
524 udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
525 xbind(udps, &lsa->u.sa, lsa->len);
526 socket_want_pktinfo(udps); /* needed for recv_from_to to work */
527 lsa_size = LSA_LEN_SIZE + lsa->len;
528 from = xzalloc(lsa_size);
529 to = xzalloc(lsa_size);
532 char *p = xmalloc_sockaddr2dotted(&lsa->u.sa);
533 bb_error_msg("accepting UDP packets on %s", p);
539 /* Try to get *DEST* address (to which of our addresses
540 * this query was directed), and reply from the same address.
541 * Or else we can exhibit usual UDP ugliness:
542 * [ip1.multihomed.ip2] <= query to ip1 <= peer
543 * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
544 memcpy(to, lsa, lsa_size);
545 r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
546 if (r < 12 || r > MAX_PACK_LEN) {
547 bb_error_msg("packet size %d, ignored", r);
551 bb_error_msg("got UDP packet");
552 buf[r] = '\0'; /* paranoia */
553 r = process_packet(conf_data, conf_ttl, buf);
556 send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);