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.
31 * In practice this can be set considerably smaller:
32 * Length of response packet is header (12B) + 2*type(4B) + 2*class(4B) +
33 * ttl(4B) + rlen(2B) + r (MAX_NAME_LEN = 21B) +
34 * 2*querystring (2 MAX_NAME_LEN = 42B), all together 90 Bytes
37 IP_STRING_LEN = sizeof(".xxx.xxx.xxx.xxx"),
38 MAX_NAME_LEN = IP_STRING_LEN - 1 + sizeof(".in-addr.arpa"),
43 /* the message from client and first part of response msg */
56 /* element of known name, ip address and reversed ip address */
58 struct dns_entry *next;
60 char rip[IP_STRING_LEN]; /* length decimal reversed IP */
64 #define OPT_verbose (option_mask32)
68 * Insert length of substrings instead of dots
70 static void undot(char *rip)
77 for (--i; i >= 0; i--) {
88 * Read hostname/IP records from file
90 static struct dns_entry *parse_conf_file(const char *fileconf)
94 struct dns_entry *m, *conf_data;
95 struct dns_entry **nextp;
100 parser = config_open(fileconf);
101 while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
105 if (inet_aton(token[1], &ip) == 0) {
106 bb_error_msg("error at line %u, skipping", parser->lineno);
111 bb_error_msg("name:%s, ip:%s", token[0], token[1]);
113 /* sizeof(*m) includes 1 byte for m->name[0] */
114 m = xzalloc(sizeof(*m) + strlen(token[0]) + 1);
120 strcpy(m->name + 1, token[0]);
122 m->ip = ip.s_addr; /* in network order */
125 sprintf(m->rip, ".%u.%u.%u.%u",
128 (uint8_t)(v32 >> 16),
133 config_close(parser);
138 * Look query up in dns records and return answer if found.
140 static char *table_lookup(struct dns_entry *d,
145 unsigned len = d->name[0];
146 /* d->name[len] is the last (non NUL) char */
149 q = query_string + 1;
151 fprintf(stderr, "%d/%d p:%s q:%s %d\n",
156 if (type == htons(REQ_A)) {
157 /* search by host name */
158 if (len != 1 || d->name[1] != '*') {
159 /* we are lax, hope no name component is ever >64 so that length
160 * (which will be represented as 'A','B'...) matches a lowercase letter.
161 * Actually, I think false matches are hard to construct.
163 * [31] len is represented as '1', [65] as 'A', [65+32] as 'a'.
164 * [65] <65 same chars>[31]<31 same chars>NUL
165 * [65+32]<65 same chars>1 <31 same chars>NUL
166 * This example seems to be the minimal case when false match occurs.
168 if (strcasecmp(d->name, query_string) != 0)
171 return (char *)&d->ip;
173 fprintf(stderr, "Found IP:%x\n", (int)d->ip);
177 /* search by IP-address */
178 if ((len != 1 || d->name[1] != '*')
179 /* we assume (do not check) that query_string
180 * ends in ".in-addr.arpa" */
181 && strncmp(d->rip, query_string, strlen(d->rip)) == 0
184 fprintf(stderr, "Found name:%s\n", d->name);
196 * Decode message and generate answer
200 Whenever an octet represents a numeric quantity, the left most bit
201 in the diagram is the high order or most significant bit.
202 That is, the bit labeled 0 is the most significant bit.
205 4.1.1. Header section format
206 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
207 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
209 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
210 |QR| OPCODE |AA|TC|RD|RA| 0 0 0| RCODE |
211 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
213 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
215 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
217 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
219 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
220 ID 16 bit random identifier assigned by querying peer.
221 Used to match query/response.
222 QR message is a query (0), or a response (1).
223 OPCODE 0 standard query (QUERY)
224 1 inverse query (IQUERY)
225 2 server status request (STATUS)
226 AA Authoritative Answer - this bit is valid in responses.
227 Responding name server is an authority for the domain name
228 in question section. Answer section may have multiple owner names
229 because of aliases. The AA bit corresponds to the name which matches
230 the query name, or the first owner name in the answer section.
231 TC TrunCation - this message was truncated.
232 RD Recursion Desired - this bit may be set in a query and
233 is copied into the response. If RD is set, it directs
234 the name server to pursue the query recursively.
235 Recursive query support is optional.
236 RA Recursion Available - this be is set or cleared in a
237 response, and denotes whether recursive query support is
238 available in the name server.
242 2 Server failure - server was unable to process the query
243 due to a problem with the name server.
244 3 Name Error - meaningful only for responses from
245 an authoritative name server. The referenced domain name
249 QDCOUNT number of entries in the question section.
250 ANCOUNT number of records in the answer section.
251 NSCOUNT number of records in the authority records section.
252 ARCOUNT number of records in the additional records section.
254 4.1.2. Question section format
256 The section contains QDCOUNT (usually 1) entries, each of this format:
257 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
258 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
261 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
263 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
265 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
266 QNAME a domain name represented as a sequence of labels, where
267 each label consists of a length octet followed by that
268 number of octets. The domain name terminates with the
269 zero length octet for the null label of the root. Note
270 that this field may be an odd number of octets; no
272 QTYPE a two octet type of the query.
273 1 a host address [REQ_A const]
274 2 an authoritative name server
275 3 a mail destination (Obsolete - use MX)
276 4 a mail forwarder (Obsolete - use MX)
277 5 the canonical name for an alias
278 6 marks the start of a zone of authority
279 7 a mailbox domain name (EXPERIMENTAL)
280 8 a mail group member (EXPERIMENTAL)
281 9 a mail rename domain name (EXPERIMENTAL)
282 10 a null RR (EXPERIMENTAL)
283 11 a well known service description
284 12 a domain name pointer [REQ_PTR const]
286 14 mailbox or mail list information
290 252 a request for a transfer of an entire zone
291 253 a request for mailbox-related records (MB, MG or MR)
292 254 a request for mail agent RRs (Obsolete - see MX)
293 255 a request for all records
294 QCLASS a two octet code that specifies the class of the query.
296 (others are historic only)
299 4.1.3. Resource record format
301 The answer, authority, and additional sections all share the same format:
302 a variable number of resource records, where the number of records
303 is specified in the corresponding count field in the header.
304 Each resource record has this format:
305 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
306 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
309 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
311 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
313 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
316 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
318 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
321 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
322 NAME a domain name to which this resource record pertains.
323 TYPE two octets containing one of the RR type codes. This
324 field specifies the meaning of the data in the RDATA field.
325 CLASS two octets which specify the class of the data in the RDATA field.
326 TTL a 32 bit unsigned integer that specifies the time interval
327 (in seconds) that the record may be cached.
328 RDLENGTH a 16 bit integer, length in octets of the RDATA field.
329 RDATA a variable length string of octets that describes the resource.
330 The format of this information varies according to the TYPE
331 and CLASS of the resource record.
332 If the TYPE is A and the CLASS is IN, it's a 4 octet IP address.
334 4.1.4. Message compression
336 In order to reduce the size of messages, domain names coan be compressed.
337 An entire domain name or a list of labels at the end of a domain name
338 is replaced with a pointer to a prior occurance of the same name.
340 The pointer takes the form of a two octet sequence:
341 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
343 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
344 The first two bits are ones. This allows a pointer to be distinguished
345 from a label, since the label must begin with two zero bits because
346 labels are restricted to 63 octets or less. The OFFSET field specifies
347 an offset from the start of the message (i.e., the first octet
348 of the ID field in the domain header).
349 A zero offset specifies the first byte of the ID field, etc.
350 Domain name in a message can be represented as either:
351 - a sequence of labels ending in a zero octet
353 - a sequence of labels ending with a pointer
355 static int process_packet(struct dns_entry *conf_data,
360 struct dns_head *head;
361 struct dns_prop *unaligned_qprop;
370 head = (struct dns_head *)buf;
371 if (head->nquer == 0) {
372 bb_error_msg("packet has 0 queries, ignored");
376 if (head->flags & htons(0x8000)) { /* QR bit */
377 bb_error_msg("response packet, ignored");
381 /* start of query string */
382 query_string = (void *)(head + 1);
383 /* caller guarantees strlen is <= MAX_PACK_LEN */
384 querystr_len = strlen(query_string) + 1;
385 /* may be unaligned! */
386 unaligned_qprop = (void *)(query_string + querystr_len);
387 querystr_len += sizeof(unaligned_qprop);
388 /* where to append answer block */
389 answb = (void *)(unaligned_qprop + 1);
391 /* QR = 1 "response", RCODE = 4 "Not Implemented" */
392 outr_flags = htons(0x8000 | 4);
394 move_from_unaligned16(type, &unaligned_qprop->type);
395 if (type != htons(REQ_A) && type != htons(REQ_PTR)) {
396 /* we can't handle the query type */
399 move_from_unaligned16(class, &unaligned_qprop->class);
400 if (class != htons(1)) { /* not class INET? */
403 /* OPCODE != 0 "standard query" ? */
404 if ((head->flags & htons(0x7800)) != 0) {
408 /* look up the name */
410 /* need to convert lengths to dots before we can use it in non-debug */
411 bb_info_msg("%s", query_string);
413 answstr = table_lookup(conf_data, type, query_string);
415 if (answstr && type == htons(REQ_PTR)) {
416 /* return a host name */
417 outr_rlen = strlen(answstr) + 1;
420 || (unsigned)(answb - buf) + querystr_len + 4 + 2 + outr_rlen > MAX_PACK_LEN
423 * AA = 1 "Authoritative Answer"
424 * RCODE = 3 "Name Error" */
425 outr_flags = htons(0x8000 | 0x0400 | 3);
429 /* copy query block to answer block */
430 memcpy(answb, query_string, querystr_len);
431 answb += querystr_len;
432 /* append answer Resource Record */
433 move_to_unaligned32((uint32_t *)answb, htonl(conf_ttl));
435 move_to_unaligned32((uint16_t *)answb, htons(outr_rlen));
437 memcpy(answb, answstr, outr_rlen);
440 /* QR = 1 "response",
441 * AA = 1 "Authoritative Answer",
442 * RCODE = 0 "success" */
443 outr_flags = htons(0x8000 | 0x0400 | 0);
444 /* we have one answer */
445 head->nansw = htons(1);
448 head->flags |= outr_flags;
449 head->nauth = head->nadd = 0;
450 head->nquer = htons(1); // why???
455 int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
456 int dnsd_main(int argc UNUSED_PARAM, char **argv)
458 const char *listen_interface = "0.0.0.0";
459 const char *fileconf = "/etc/dnsd.conf";
460 struct dns_entry *conf_data;
461 uint32_t conf_ttl = DEFAULT_TTL;
463 len_and_sockaddr *lsa, *from, *to;
467 /* Paranoid sizing: querystring x2 + ttl + outr_rlen + answstr */
468 /* I'd rather see process_packet() fixed instead... */
469 uint8_t buf[MAX_PACK_LEN * 2 + 4 + 2 + (MAX_NAME_LEN+1)];
471 opts = getopt32(argv, "vi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
472 //if (opts & 0x1) // -v
473 //if (opts & 0x2) // -i
474 //if (opts & 0x4) // -c
475 if (opts & 0x8) // -t
476 conf_ttl = xatou_range(sttl, 1, 0xffffffff);
477 if (opts & 0x10) // -p
478 port = xatou_range(sport, 1, 0xffff);
479 if (opts & 0x20) { // -d
480 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
481 openlog(applet_name, LOG_PID, LOG_DAEMON);
482 logmode = LOGMODE_SYSLOG;
484 /* Clear all except "verbose" bit */
487 conf_data = parse_conf_file(fileconf);
489 lsa = xdotted2sockaddr(listen_interface, port);
490 udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
491 xbind(udps, &lsa->u.sa, lsa->len);
492 socket_want_pktinfo(udps); /* needed for recv_from_to to work */
493 lsa_size = LSA_LEN_SIZE + lsa->len;
494 from = xzalloc(lsa_size);
495 to = xzalloc(lsa_size);
498 char *p = xmalloc_sockaddr2dotted(&lsa->u.sa);
499 bb_info_msg("Accepting UDP packets on %s", p);
505 /* Try to get *DEST* address (to which of our addresses
506 * this query was directed), and reply from the same address.
507 * Or else we can exhibit usual UDP ugliness:
508 * [ip1.multihomed.ip2] <= query to ip1 <= peer
509 * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
510 memcpy(to, lsa, lsa_size);
511 r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
512 if (r < 12 || r > MAX_PACK_LEN) {
513 bb_error_msg("packet size %d, ignored", r);
517 bb_info_msg("Got UDP packet");
518 buf[r] = '\0'; /* paranoia */
519 r = process_packet(conf_data, conf_ttl, buf);
522 send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);