dnsd.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini DNS server implementation for busybox
  4. *
  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. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  10. *
  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/
  15. *
  16. * Some bugfix and minor changes was applied by Roberto A. Foglietta who made
  17. * the first porting of oao' scdns to busybox also.
  18. */
  19. //usage:#define dnsd_trivial_usage
  20. //usage: "[-dvs] [-c CONFFILE] [-t TTL_SEC] [-p PORT] [-i ADDR]"
  21. //usage:#define dnsd_full_usage "\n\n"
  22. //usage: "Small static DNS server daemon\n"
  23. //usage: "\n -c FILE Config file"
  24. //usage: "\n -t SEC TTL"
  25. //usage: "\n -p PORT Listen on PORT"
  26. //usage: "\n -i ADDR Listen on ADDR"
  27. //usage: "\n -d Daemonize"
  28. //usage: "\n -v Verbose"
  29. //usage: "\n -s Send successful replies only. Use this if you want"
  30. //usage: "\n to use /etc/resolv.conf with two nameserver lines:"
  31. //usage: "\n nameserver DNSD_SERVER"
  32. //usage: "\n nameserver NORMAL_DNS_SERVER"
  33. #include "libbb.h"
  34. #include <syslog.h>
  35. //#define DEBUG 1
  36. #define DEBUG 0
  37. enum {
  38. /* can tweak this */
  39. DEFAULT_TTL = 120,
  40. /* cannot get bigger packets than 512 per RFC1035. */
  41. MAX_PACK_LEN = 512,
  42. IP_STRING_LEN = sizeof(".xxx.xxx.xxx.xxx"),
  43. MAX_NAME_LEN = IP_STRING_LEN - 1 + sizeof(".in-addr.arpa"),
  44. REQ_A = 1,
  45. REQ_PTR = 12,
  46. };
  47. /* the message from client and first part of response msg */
  48. struct dns_head {
  49. uint16_t id;
  50. uint16_t flags;
  51. uint16_t nquer;
  52. uint16_t nansw;
  53. uint16_t nauth;
  54. uint16_t nadd;
  55. };
  56. /* Structure used to access type and class fields.
  57. * They are totally unaligned, but gcc 4.3.4 thinks that pointer of type uint16_t*
  58. * is 16-bit aligned and replaces 16-bit memcpy (in move_from_unaligned16 macro)
  59. * with aligned halfword access on arm920t!
  60. * Oh well. Slapping PACKED everywhere seems to help: */
  61. struct type_and_class {
  62. uint16_t type PACKED;
  63. uint16_t class PACKED;
  64. } PACKED;
  65. /* element of known name, ip address and reversed ip address */
  66. struct dns_entry {
  67. struct dns_entry *next;
  68. uint32_t ip;
  69. char rip[IP_STRING_LEN]; /* length decimal reversed IP */
  70. char name[1];
  71. };
  72. #define OPT_verbose (option_mask32 & 1)
  73. #define OPT_silent (option_mask32 & 2)
  74. /*
  75. * Insert length of substrings instead of dots
  76. */
  77. static void undot(char *rip)
  78. {
  79. int i = 0;
  80. int s = 0;
  81. while (rip[i])
  82. i++;
  83. for (--i; i >= 0; i--) {
  84. if (rip[i] == '.') {
  85. rip[i] = s;
  86. s = 0;
  87. } else {
  88. s++;
  89. }
  90. }
  91. }
  92. /*
  93. * Read hostname/IP records from file
  94. */
  95. static struct dns_entry *parse_conf_file(const char *fileconf)
  96. {
  97. char *token[2];
  98. parser_t *parser;
  99. struct dns_entry *m, *conf_data;
  100. struct dns_entry **nextp;
  101. conf_data = NULL;
  102. nextp = &conf_data;
  103. parser = config_open(fileconf);
  104. while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
  105. struct in_addr ip;
  106. uint32_t v32;
  107. if (inet_aton(token[1], &ip) == 0) {
  108. bb_error_msg("error at line %u, skipping", parser->lineno);
  109. continue;
  110. }
  111. if (OPT_verbose)
  112. 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);
  115. /*m->next = NULL;*/
  116. *nextp = m;
  117. nextp = &m->next;
  118. m->name[0] = '.';
  119. strcpy(m->name + 1, token[0]);
  120. undot(m->name);
  121. m->ip = ip.s_addr; /* in network order */
  122. v32 = ntohl(m->ip);
  123. /* inverted order */
  124. sprintf(m->rip, ".%u.%u.%u.%u",
  125. (uint8_t)(v32),
  126. (uint8_t)(v32 >> 8),
  127. (uint8_t)(v32 >> 16),
  128. (v32 >> 24)
  129. );
  130. undot(m->rip);
  131. }
  132. config_close(parser);
  133. return conf_data;
  134. }
  135. /*
  136. * Look query up in dns records and return answer if found.
  137. */
  138. static char *table_lookup(struct dns_entry *d,
  139. uint16_t type,
  140. char* query_string)
  141. {
  142. while (d) {
  143. unsigned len = d->name[0];
  144. /* d->name[len] is the last (non NUL) char */
  145. #if DEBUG
  146. char *p, *q;
  147. q = query_string + 1;
  148. p = d->name + 1;
  149. fprintf(stderr, "%d/%d p:%s q:%s %d\n",
  150. (int)strlen(p), len,
  151. p, q, (int)strlen(q)
  152. );
  153. #endif
  154. if (type == htons(REQ_A)) {
  155. /* search by host name */
  156. if (len != 1 || d->name[1] != '*') {
  157. /* we are lax, hope no name component is ever >64 so that length
  158. * (which will be represented as 'A','B'...) matches a lowercase letter.
  159. * Actually, I think false matches are hard to construct.
  160. * Example.
  161. * [31] len is represented as '1', [65] as 'A', [65+32] as 'a'.
  162. * [65] <65 same chars>[31]<31 same chars>NUL
  163. * [65+32]<65 same chars>1 <31 same chars>NUL
  164. * This example seems to be the minimal case when false match occurs.
  165. */
  166. if (strcasecmp(d->name, query_string) != 0)
  167. goto next;
  168. }
  169. return (char *)&d->ip;
  170. #if DEBUG
  171. fprintf(stderr, "Found IP:%x\n", (int)d->ip);
  172. #endif
  173. return 0;
  174. }
  175. /* search by IP-address */
  176. if ((len != 1 || d->name[1] != '*')
  177. /* we assume (do not check) that query_string
  178. * ends in ".in-addr.arpa" */
  179. && strncmp(d->rip, query_string, strlen(d->rip)) == 0
  180. ) {
  181. #if DEBUG
  182. fprintf(stderr, "Found name:%s\n", d->name);
  183. #endif
  184. return d->name;
  185. }
  186. next:
  187. d = d->next;
  188. }
  189. return NULL;
  190. }
  191. /*
  192. * Decode message and generate answer
  193. */
  194. /* RFC 1035
  195. ...
  196. Whenever an octet represents a numeric quantity, the left most bit
  197. in the diagram is the high order or most significant bit.
  198. That is, the bit labeled 0 is the most significant bit.
  199. ...
  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. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  203. | ID |
  204. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  205. |QR| OPCODE |AA|TC|RD|RA| 0 0 0| RCODE |
  206. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  207. | QDCOUNT |
  208. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  209. | ANCOUNT |
  210. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  211. | NSCOUNT |
  212. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  213. | ARCOUNT |
  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.
  234. RCODE Response code.
  235. 0 No error condition
  236. 1 Format error
  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
  241. does not exist.
  242. 4 Not Implemented.
  243. 5 Refused.
  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.
  248. 4.1.2. Question section format
  249. The section contains QDCOUNT (usually 1) entries, each of this format:
  250. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  251. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  252. / QNAME /
  253. / /
  254. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  255. | QTYPE |
  256. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  257. | QCLASS |
  258. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  259. QNAME a domain name represented as a sequence of labels, where
  260. each label consists of a length octet followed by that
  261. number of octets. The domain name terminates with the
  262. zero length octet for the null label of the root. Note
  263. that this field may be an odd number of octets; no
  264. padding is used.
  265. QTYPE a two octet type of the query.
  266. 1 a host address [REQ_A const]
  267. 2 an authoritative name server
  268. 3 a mail destination (Obsolete - use MX)
  269. 4 a mail forwarder (Obsolete - use MX)
  270. 5 the canonical name for an alias
  271. 6 marks the start of a zone of authority
  272. 7 a mailbox domain name (EXPERIMENTAL)
  273. 8 a mail group member (EXPERIMENTAL)
  274. 9 a mail rename domain name (EXPERIMENTAL)
  275. 10 a null RR (EXPERIMENTAL)
  276. 11 a well known service description
  277. 12 a domain name pointer [REQ_PTR const]
  278. 13 host information
  279. 14 mailbox or mail list information
  280. 15 mail exchange
  281. 16 text strings
  282. 0x1c IPv6?
  283. 252 a request for a transfer of an entire zone
  284. 253 a request for mailbox-related records (MB, MG or MR)
  285. 254 a request for mail agent RRs (Obsolete - see MX)
  286. 255 a request for all records
  287. QCLASS a two octet code that specifies the class of the query.
  288. 1 the Internet
  289. (others are historic only)
  290. 255 any class
  291. 4.1.3. Resource Record format
  292. The answer, authority, and additional sections all share the same format:
  293. a variable number of resource records, where the number of records
  294. is specified in the corresponding count field in the header.
  295. Each resource record has this format:
  296. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  297. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  298. / /
  299. / NAME /
  300. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  301. | TYPE |
  302. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  303. | CLASS |
  304. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  305. | TTL |
  306. | |
  307. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  308. | RDLENGTH |
  309. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
  310. / RDATA /
  311. / /
  312. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  313. NAME a domain name to which this resource record pertains.
  314. TYPE two octets containing one of the RR type codes. This
  315. field specifies the meaning of the data in the RDATA field.
  316. CLASS two octets which specify the class of the data in the RDATA field.
  317. TTL a 32 bit unsigned integer that specifies the time interval
  318. (in seconds) that the record may be cached.
  319. RDLENGTH a 16 bit integer, length in octets of the RDATA field.
  320. RDATA a variable length string of octets that describes the resource.
  321. The format of this information varies according to the TYPE
  322. and CLASS of the resource record.
  323. If the TYPE is A and the CLASS is IN, it's a 4 octet IP address.
  324. 4.1.4. Message compression
  325. In order to reduce the size of messages, domain names coan be compressed.
  326. An entire domain name or a list of labels at the end of a domain name
  327. is replaced with a pointer to a prior occurance of the same name.
  328. The pointer takes the form of a two octet sequence:
  329. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  330. | 1 1| OFFSET |
  331. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  332. The first two bits are ones. This allows a pointer to be distinguished
  333. from a label, since the label must begin with two zero bits because
  334. labels are restricted to 63 octets or less. The OFFSET field specifies
  335. an offset from the start of the message (i.e., the first octet
  336. of the ID field in the domain header).
  337. A zero offset specifies the first byte of the ID field, etc.
  338. Domain name in a message can be represented as either:
  339. - a sequence of labels ending in a zero octet
  340. - a pointer
  341. - a sequence of labels ending with a pointer
  342. */
  343. static int process_packet(struct dns_entry *conf_data,
  344. uint32_t conf_ttl,
  345. uint8_t *buf)
  346. {
  347. struct dns_head *head;
  348. struct type_and_class *unaligned_type_class;
  349. const char *err_msg;
  350. char *query_string;
  351. char *answstr;
  352. uint8_t *answb;
  353. uint16_t outr_rlen;
  354. uint16_t outr_flags;
  355. uint16_t type;
  356. uint16_t class;
  357. int query_len;
  358. head = (struct dns_head *)buf;
  359. if (head->nquer == 0) {
  360. bb_error_msg("packet has 0 queries, ignored");
  361. return 0; /* don't reply */
  362. }
  363. if (head->flags & htons(0x8000)) { /* QR bit */
  364. bb_error_msg("response packet, ignored");
  365. return 0; /* don't reply */
  366. }
  367. /* QR = 1 "response", RCODE = 4 "Not Implemented" */
  368. outr_flags = htons(0x8000 | 4);
  369. err_msg = NULL;
  370. /* start of query string */
  371. query_string = (void *)(head + 1);
  372. /* caller guarantees strlen is <= MAX_PACK_LEN */
  373. query_len = strlen(query_string) + 1;
  374. /* may be unaligned! */
  375. unaligned_type_class = (void *)(query_string + query_len);
  376. query_len += sizeof(*unaligned_type_class);
  377. /* where to append answer block */
  378. answb = (void *)(unaligned_type_class + 1);
  379. /* OPCODE != 0 "standard query"? */
  380. if ((head->flags & htons(0x7800)) != 0) {
  381. err_msg = "opcode != 0";
  382. goto empty_packet;
  383. }
  384. move_from_unaligned16(class, &unaligned_type_class->class);
  385. if (class != htons(1)) { /* not class INET? */
  386. err_msg = "class != 1";
  387. goto empty_packet;
  388. }
  389. move_from_unaligned16(type, &unaligned_type_class->type);
  390. if (type != htons(REQ_A) && type != htons(REQ_PTR)) {
  391. /* we can't handle this query type */
  392. //TODO: happens all the time with REQ_AAAA (0x1c) requests - implement those?
  393. err_msg = "type is !REQ_A and !REQ_PTR";
  394. goto empty_packet;
  395. }
  396. /* look up the name */
  397. answstr = table_lookup(conf_data, type, query_string);
  398. #if DEBUG
  399. /* Shows lengths instead of dots, unusable for !DEBUG */
  400. bb_error_msg("'%s'->'%s'", query_string, answstr);
  401. #endif
  402. outr_rlen = 4;
  403. if (answstr && type == htons(REQ_PTR)) {
  404. /* returning a host name */
  405. outr_rlen = strlen(answstr) + 1;
  406. }
  407. if (!answstr
  408. || (unsigned)(answb - buf) + query_len + 4 + 2 + outr_rlen > MAX_PACK_LEN
  409. ) {
  410. /* QR = 1 "response"
  411. * AA = 1 "Authoritative Answer"
  412. * RCODE = 3 "Name Error" */
  413. err_msg = "name is not found";
  414. outr_flags = htons(0x8000 | 0x0400 | 3);
  415. goto empty_packet;
  416. }
  417. /* Append answer Resource Record */
  418. memcpy(answb, query_string, query_len); /* name, type, class */
  419. answb += query_len;
  420. move_to_unaligned32((uint32_t *)answb, htonl(conf_ttl));
  421. answb += 4;
  422. move_to_unaligned16((uint16_t *)answb, htons(outr_rlen));
  423. answb += 2;
  424. memcpy(answb, answstr, outr_rlen);
  425. answb += outr_rlen;
  426. /* QR = 1 "response",
  427. * AA = 1 "Authoritative Answer",
  428. * TODO: need to set RA bit 0x80? One user says nslookup complains
  429. * "Got recursion not available from SERVER, trying next server"
  430. * "** server can't find HOSTNAME"
  431. * RCODE = 0 "success"
  432. */
  433. if (OPT_verbose)
  434. bb_error_msg("returning positive reply");
  435. outr_flags = htons(0x8000 | 0x0400 | 0);
  436. /* we have one answer */
  437. head->nansw = htons(1);
  438. empty_packet:
  439. if ((outr_flags & htons(0xf)) != 0) { /* not a positive response */
  440. if (OPT_verbose) {
  441. bb_error_msg("%s, %s",
  442. err_msg,
  443. OPT_silent ? "dropping query" : "sending error reply"
  444. );
  445. }
  446. if (OPT_silent)
  447. return 0;
  448. }
  449. head->flags |= outr_flags;
  450. head->nauth = head->nadd = 0;
  451. head->nquer = htons(1); // why???
  452. return answb - buf;
  453. }
  454. int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  455. int dnsd_main(int argc UNUSED_PARAM, char **argv)
  456. {
  457. const char *listen_interface = "0.0.0.0";
  458. const char *fileconf = "/etc/dnsd.conf";
  459. struct dns_entry *conf_data;
  460. uint32_t conf_ttl = DEFAULT_TTL;
  461. char *sttl, *sport;
  462. len_and_sockaddr *lsa, *from, *to;
  463. unsigned lsa_size;
  464. int udps, opts;
  465. uint16_t port = 53;
  466. /* Ensure buf is 32bit aligned (we need 16bit, but 32bit can't hurt) */
  467. uint8_t buf[MAX_PACK_LEN + 1] ALIGN4;
  468. opts = getopt32(argv, "vsi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
  469. //if (opts & (1 << 0)) // -v
  470. //if (opts & (1 << 1)) // -s
  471. //if (opts & (1 << 2)) // -i
  472. //if (opts & (1 << 3)) // -c
  473. if (opts & (1 << 4)) // -t
  474. conf_ttl = xatou_range(sttl, 1, 0xffffffff);
  475. if (opts & (1 << 5)) // -p
  476. port = xatou_range(sport, 1, 0xffff);
  477. if (opts & (1 << 6)) { // -d
  478. bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
  479. openlog(applet_name, LOG_PID, LOG_DAEMON);
  480. logmode = LOGMODE_SYSLOG;
  481. }
  482. conf_data = parse_conf_file(fileconf);
  483. lsa = xdotted2sockaddr(listen_interface, port);
  484. udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
  485. xbind(udps, &lsa->u.sa, lsa->len);
  486. socket_want_pktinfo(udps); /* needed for recv_from_to to work */
  487. lsa_size = LSA_LEN_SIZE + lsa->len;
  488. from = xzalloc(lsa_size);
  489. to = xzalloc(lsa_size);
  490. {
  491. char *p = xmalloc_sockaddr2dotted(&lsa->u.sa);
  492. bb_error_msg("accepting UDP packets on %s", p);
  493. free(p);
  494. }
  495. while (1) {
  496. int r;
  497. /* Try to get *DEST* address (to which of our addresses
  498. * this query was directed), and reply from the same address.
  499. * Or else we can exhibit usual UDP ugliness:
  500. * [ip1.multihomed.ip2] <= query to ip1 <= peer
  501. * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
  502. memcpy(to, lsa, lsa_size);
  503. r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
  504. if (r < 12 || r > MAX_PACK_LEN) {
  505. bb_error_msg("packet size %d, ignored", r);
  506. continue;
  507. }
  508. if (OPT_verbose)
  509. bb_error_msg("got UDP packet");
  510. buf[r] = '\0'; /* paranoia */
  511. r = process_packet(conf_data, conf_ttl, buf);
  512. if (r <= 0)
  513. continue;
  514. send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);
  515. }
  516. return 0;
  517. }