3
0

dnsd.c 18 KB

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