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.
30 /* cannot get bigger packets than 512 per RFC1035. */
32 IP_STRING_LEN = sizeof(".xxx.xxx.xxx.xxx"),
33 MAX_NAME_LEN = IP_STRING_LEN - 1 + sizeof(".in-addr.arpa"),
38 /* the message from client and first part of response msg */
47 struct type_and_class {
51 /* element of known name, ip address and reversed ip address */
53 struct dns_entry *next;
55 char rip[IP_STRING_LEN]; /* length decimal reversed IP */
59 #define OPT_verbose (option_mask32)
63 * Insert length of substrings instead of dots
65 static void undot(char *rip)
72 for (--i; i >= 0; i--) {
83 * Read hostname/IP records from file
85 static struct dns_entry *parse_conf_file(const char *fileconf)
89 struct dns_entry *m, *conf_data;
90 struct dns_entry **nextp;
95 parser = config_open(fileconf);
96 while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
100 if (inet_aton(token[1], &ip) == 0) {
101 bb_error_msg("error at line %u, skipping", parser->lineno);
106 bb_error_msg("name:%s, ip:%s", token[0], token[1]);
108 /* sizeof(*m) includes 1 byte for m->name[0] */
109 m = xzalloc(sizeof(*m) + strlen(token[0]) + 1);
115 strcpy(m->name + 1, token[0]);
117 m->ip = ip.s_addr; /* in network order */
120 sprintf(m->rip, ".%u.%u.%u.%u",
123 (uint8_t)(v32 >> 16),
128 config_close(parser);
133 * Look query up in dns records and return answer if found.
135 static char *table_lookup(struct dns_entry *d,
140 unsigned len = d->name[0];
141 /* d->name[len] is the last (non NUL) char */
144 q = query_string + 1;
146 fprintf(stderr, "%d/%d p:%s q:%s %d\n",
151 if (type == htons(REQ_A)) {
152 /* search by host name */
153 if (len != 1 || d->name[1] != '*') {
154 /* we are lax, hope no name component is ever >64 so that length
155 * (which will be represented as 'A','B'...) matches a lowercase letter.
156 * Actually, I think false matches are hard to construct.
158 * [31] len is represented as '1', [65] as 'A', [65+32] as 'a'.
159 * [65] <65 same chars>[31]<31 same chars>NUL
160 * [65+32]<65 same chars>1 <31 same chars>NUL
161 * This example seems to be the minimal case when false match occurs.
163 if (strcasecmp(d->name, query_string) != 0)
166 return (char *)&d->ip;
168 fprintf(stderr, "Found IP:%x\n", (int)d->ip);
172 /* search by IP-address */
173 if ((len != 1 || d->name[1] != '*')
174 /* we assume (do not check) that query_string
175 * ends in ".in-addr.arpa" */
176 && strncmp(d->rip, query_string, strlen(d->rip)) == 0
179 fprintf(stderr, "Found name:%s\n", d->name);
191 * Decode message and generate answer
195 Whenever an octet represents a numeric quantity, the left most bit
196 in the diagram is the high order or most significant bit.
197 That is, the bit labeled 0 is the most significant bit.
200 4.1.1. Header section format
201 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
202 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
204 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
205 |QR| OPCODE |AA|TC|RD|RA| 0 0 0| RCODE |
206 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
208 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
210 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
212 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
214 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
215 ID 16 bit random identifier assigned by querying peer.
216 Used to match query/response.
217 QR message is a query (0), or a response (1).
218 OPCODE 0 standard query (QUERY)
219 1 inverse query (IQUERY)
220 2 server status request (STATUS)
221 AA Authoritative Answer - this bit is valid in responses.
222 Responding name server is an authority for the domain name
223 in question section. Answer section may have multiple owner names
224 because of aliases. The AA bit corresponds to the name which matches
225 the query name, or the first owner name in the answer section.
226 TC TrunCation - this message was truncated.
227 RD Recursion Desired - this bit may be set in a query and
228 is copied into the response. If RD is set, it directs
229 the name server to pursue the query recursively.
230 Recursive query support is optional.
231 RA Recursion Available - this be is set or cleared in a
232 response, and denotes whether recursive query support is
233 available in the name server.
237 2 Server failure - server was unable to process the query
238 due to a problem with the name server.
239 3 Name Error - meaningful only for responses from
240 an authoritative name server. The referenced domain name
244 QDCOUNT number of entries in the question section.
245 ANCOUNT number of records in the answer section.
246 NSCOUNT number of records in the authority records section.
247 ARCOUNT number of records in the additional records section.
249 4.1.2. Question section format
251 The section contains QDCOUNT (usually 1) entries, each of this format:
252 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
253 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
256 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
258 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
260 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
261 QNAME a domain name represented as a sequence of labels, where
262 each label consists of a length octet followed by that
263 number of octets. The domain name terminates with the
264 zero length octet for the null label of the root. Note
265 that this field may be an odd number of octets; no
267 QTYPE a two octet type of the query.
268 1 a host address [REQ_A const]
269 2 an authoritative name server
270 3 a mail destination (Obsolete - use MX)
271 4 a mail forwarder (Obsolete - use MX)
272 5 the canonical name for an alias
273 6 marks the start of a zone of authority
274 7 a mailbox domain name (EXPERIMENTAL)
275 8 a mail group member (EXPERIMENTAL)
276 9 a mail rename domain name (EXPERIMENTAL)
277 10 a null RR (EXPERIMENTAL)
278 11 a well known service description
279 12 a domain name pointer [REQ_PTR const]
281 14 mailbox or mail list information
285 252 a request for a transfer of an entire zone
286 253 a request for mailbox-related records (MB, MG or MR)
287 254 a request for mail agent RRs (Obsolete - see MX)
288 255 a request for all records
289 QCLASS a two octet code that specifies the class of the query.
291 (others are historic only)
294 4.1.3. Resource Record format
296 The answer, authority, and additional sections all share the same format:
297 a variable number of resource records, where the number of records
298 is specified in the corresponding count field in the header.
299 Each resource record has this format:
300 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
301 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
304 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
306 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
308 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
311 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
313 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
316 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
317 NAME a domain name to which this resource record pertains.
318 TYPE two octets containing one of the RR type codes. This
319 field specifies the meaning of the data in the RDATA field.
320 CLASS two octets which specify the class of the data in the RDATA field.
321 TTL a 32 bit unsigned integer that specifies the time interval
322 (in seconds) that the record may be cached.
323 RDLENGTH a 16 bit integer, length in octets of the RDATA field.
324 RDATA a variable length string of octets that describes the resource.
325 The format of this information varies according to the TYPE
326 and CLASS of the resource record.
327 If the TYPE is A and the CLASS is IN, it's a 4 octet IP address.
329 4.1.4. Message compression
331 In order to reduce the size of messages, domain names coan be compressed.
332 An entire domain name or a list of labels at the end of a domain name
333 is replaced with a pointer to a prior occurance of the same name.
335 The pointer takes the form of a two octet sequence:
336 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
338 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
339 The first two bits are ones. This allows a pointer to be distinguished
340 from a label, since the label must begin with two zero bits because
341 labels are restricted to 63 octets or less. The OFFSET field specifies
342 an offset from the start of the message (i.e., the first octet
343 of the ID field in the domain header).
344 A zero offset specifies the first byte of the ID field, etc.
345 Domain name in a message can be represented as either:
346 - a sequence of labels ending in a zero octet
348 - a sequence of labels ending with a pointer
350 static int process_packet(struct dns_entry *conf_data,
355 struct dns_head *head;
356 struct type_and_class *unaligned_type_class;
365 head = (struct dns_head *)buf;
366 if (head->nquer == 0) {
367 bb_error_msg("packet has 0 queries, ignored");
371 if (head->flags & htons(0x8000)) { /* QR bit */
372 bb_error_msg("response packet, ignored");
376 /* start of query string */
377 query_string = (void *)(head + 1);
378 /* caller guarantees strlen is <= MAX_PACK_LEN */
379 query_len = strlen(query_string) + 1;
380 /* may be unaligned! */
381 unaligned_type_class = (void *)(query_string + query_len);
382 query_len += sizeof(unaligned_type_class);
383 /* where to append answer block */
384 answb = (void *)(unaligned_type_class + 1);
386 /* QR = 1 "response", RCODE = 4 "Not Implemented" */
387 outr_flags = htons(0x8000 | 4);
389 move_from_unaligned16(type, &unaligned_type_class->type);
390 if (type != htons(REQ_A) && type != htons(REQ_PTR)) {
391 /* we can't handle the query type */
394 move_from_unaligned16(class, &unaligned_type_class->class);
395 if (class != htons(1)) { /* not class INET? */
398 /* OPCODE != 0 "standard query" ? */
399 if ((head->flags & htons(0x7800)) != 0) {
403 /* look up the name */
405 /* need to convert lengths to dots before we can use it in non-debug */
406 bb_info_msg("%s", query_string);
408 answstr = table_lookup(conf_data, type, query_string);
410 if (answstr && type == htons(REQ_PTR)) {
411 /* returning a host name */
412 outr_rlen = strlen(answstr) + 1;
415 || (unsigned)(answb - buf) + query_len + 4 + 2 + outr_rlen > MAX_PACK_LEN
418 * AA = 1 "Authoritative Answer"
419 * RCODE = 3 "Name Error" */
420 outr_flags = htons(0x8000 | 0x0400 | 3);
424 /* Append answer Resource Record */
425 memcpy(answb, query_string, query_len); /* name, type, class */
427 move_to_unaligned32((uint32_t *)answb, htonl(conf_ttl));
429 move_to_unaligned16((uint16_t *)answb, htons(outr_rlen));
431 memcpy(answb, answstr, outr_rlen);
434 /* QR = 1 "response",
435 * AA = 1 "Authoritative Answer",
436 * TODO: need to set RA bit 0x80? One user says nslookup complains
437 * "Got recursion not available from SERVER, trying next server"
438 * "** server can't find HOSTNAME"
439 * RCODE = 0 "success"
441 outr_flags = htons(0x8000 | 0x0400 | 0);
442 /* we have one answer */
443 head->nansw = htons(1);
446 head->flags |= outr_flags;
447 head->nauth = head->nadd = 0;
448 head->nquer = htons(1); // why???
453 int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
454 int dnsd_main(int argc UNUSED_PARAM, char **argv)
456 const char *listen_interface = "0.0.0.0";
457 const char *fileconf = "/etc/dnsd.conf";
458 struct dns_entry *conf_data;
459 uint32_t conf_ttl = DEFAULT_TTL;
461 len_and_sockaddr *lsa, *from, *to;
465 uint8_t buf[MAX_PACK_LEN + 1];
467 opts = getopt32(argv, "vi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
468 //if (opts & 0x1) // -v
469 //if (opts & 0x2) // -i
470 //if (opts & 0x4) // -c
471 if (opts & 0x8) // -t
472 conf_ttl = xatou_range(sttl, 1, 0xffffffff);
473 if (opts & 0x10) // -p
474 port = xatou_range(sport, 1, 0xffff);
475 if (opts & 0x20) { // -d
476 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
477 openlog(applet_name, LOG_PID, LOG_DAEMON);
478 logmode = LOGMODE_SYSLOG;
480 /* Clear all except "verbose" bit */
483 conf_data = parse_conf_file(fileconf);
485 lsa = xdotted2sockaddr(listen_interface, port);
486 udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
487 xbind(udps, &lsa->u.sa, lsa->len);
488 socket_want_pktinfo(udps); /* needed for recv_from_to to work */
489 lsa_size = LSA_LEN_SIZE + lsa->len;
490 from = xzalloc(lsa_size);
491 to = xzalloc(lsa_size);
494 char *p = xmalloc_sockaddr2dotted(&lsa->u.sa);
495 bb_info_msg("Accepting UDP packets on %s", p);
501 /* Try to get *DEST* address (to which of our addresses
502 * this query was directed), and reply from the same address.
503 * Or else we can exhibit usual UDP ugliness:
504 * [ip1.multihomed.ip2] <= query to ip1 <= peer
505 * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
506 memcpy(to, lsa, lsa_size);
507 r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
508 if (r < 12 || r > MAX_PACK_LEN) {
509 bb_error_msg("packet size %d, ignored", r);
513 bb_info_msg("Got UDP packet");
514 buf[r] = '\0'; /* paranoia */
515 r = process_packet(conf_data, conf_ttl, buf);
518 send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);