dnsd.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 tarball for details.
  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 "busybox.h"
  20. static const char *fileconf = "/etc/dnsd.conf";
  21. #define LOCK_FILE "/var/run/dnsd.lock"
  22. // Must match getopt32 call
  23. #define OPT_daemon (option_mask32 & 0x10)
  24. #define OPT_verbose (option_mask32 & 0x20)
  25. //#define DEBUG 1
  26. #define DEBUG 0
  27. enum {
  28. MAX_HOST_LEN = 16, // longest host name allowed is 15
  29. IP_STRING_LEN = 18, // .xxx.xxx.xxx.xxx\0
  30. //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
  31. MAX_NAME_LEN = (IP_STRING_LEN + 13),
  32. /* Cannot get bigger packets than 512 per RFC1035
  33. In practice this can be set considerably smaller:
  34. Length of response packet is header (12B) + 2*type(4B) + 2*class(4B) +
  35. ttl(4B) + rlen(2B) + r (MAX_NAME_LEN =21B) +
  36. 2*querystring (2 MAX_NAME_LEN= 42B), all together 90 Byte
  37. */
  38. MAX_PACK_LEN = 512 + 1,
  39. DEFAULT_TTL = 30, // increase this when not testing?
  40. REQ_A = 1,
  41. REQ_PTR = 12
  42. };
  43. struct dns_repl { // resource record, add 0 or 1 to accepted dns_msg in resp
  44. uint16_t rlen;
  45. uint8_t *r; // resource
  46. uint16_t flags;
  47. };
  48. struct dns_head { // the message from client and first part of response mag
  49. uint16_t id;
  50. uint16_t flags;
  51. uint16_t nquer; // accepts 0
  52. uint16_t nansw; // 1 in response
  53. uint16_t nauth; // 0
  54. uint16_t nadd; // 0
  55. };
  56. struct dns_prop {
  57. uint16_t type;
  58. uint16_t class;
  59. };
  60. struct dns_entry { // element of known name, ip address and reversed ip address
  61. struct dns_entry *next;
  62. char ip[IP_STRING_LEN]; // dotted decimal IP
  63. char rip[IP_STRING_LEN]; // length decimal reversed IP
  64. char name[MAX_HOST_LEN];
  65. };
  66. static struct dns_entry *dnsentry = NULL;
  67. static uint32_t ttl = DEFAULT_TTL;
  68. /*
  69. * Convert host name from C-string to dns length/string.
  70. */
  71. static void convname(char *a, uint8_t *q)
  72. {
  73. int i = (q[0] == '.') ? 0 : 1;
  74. for (; i < MAX_HOST_LEN-1 && *q; i++, q++)
  75. a[i] = tolower(*q);
  76. a[0] = i - 1;
  77. a[i] = 0;
  78. }
  79. /*
  80. * Insert length of substrings instead of dots
  81. */
  82. static void undot(uint8_t * rip)
  83. {
  84. int i = 0, s = 0;
  85. while (rip[i])
  86. i++;
  87. for (--i; i >= 0; i--) {
  88. if (rip[i] == '.') {
  89. rip[i] = s;
  90. s = 0;
  91. } else s++;
  92. }
  93. }
  94. /*
  95. * Read one line of hostname/IP from file
  96. * Returns 0 for each valid entry read, -1 at EOF
  97. * Assumes all host names are lower case only
  98. * Hostnames with more than one label is not handled correctly.
  99. * Presently the dot is copied into name without
  100. * converting to a length/string substring for that label.
  101. */
  102. static int getfileentry(FILE * fp, struct dns_entry *s)
  103. {
  104. unsigned int a,b,c,d;
  105. char *r, *name;
  106. restart:
  107. r = xmalloc_fgets(fp);
  108. if (!r)
  109. return -1;
  110. while (*r == ' ' || *r == '\t') {
  111. r++;
  112. if (!*r || *r == '#' || *r == '\n')
  113. goto restart; /* skipping empty/blank and commented lines */
  114. }
  115. name = r;
  116. while (*r != ' ' && *r != '\t')
  117. r++;
  118. *r++ = 0;
  119. if (sscanf(r, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
  120. goto restart; /* skipping wrong lines */
  121. sprintf(s->ip, "%u.%u.%u.%u", a, b, c, d);
  122. sprintf(s->rip, ".%u.%u.%u.%u", d, c, b, a);
  123. undot((uint8_t*)s->rip);
  124. convname(s->name,(uint8_t*)name);
  125. if (OPT_verbose)
  126. fprintf(stderr, "\tname:%s, ip:%s\n", &(s->name[1]),s->ip);
  127. return 0;
  128. }
  129. /*
  130. * Read hostname/IP records from file
  131. */
  132. static void dnsentryinit(void)
  133. {
  134. FILE *fp;
  135. struct dns_entry *m, *prev;
  136. prev = dnsentry = NULL;
  137. fp = xfopen(fileconf, "r");
  138. while (1) {
  139. m = xmalloc(sizeof(struct dns_entry));
  140. m->next = NULL;
  141. if (getfileentry(fp, m))
  142. break;
  143. if (prev == NULL)
  144. dnsentry = m;
  145. else
  146. prev->next = m;
  147. prev = m;
  148. }
  149. fclose(fp);
  150. }
  151. /*
  152. * Look query up in dns records and return answer if found
  153. * qs is the query string, first byte the string length
  154. */
  155. static int table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
  156. {
  157. int i;
  158. struct dns_entry *d=dnsentry;
  159. do {
  160. #if DEBUG
  161. char *p,*q;
  162. q = (char *)&(qs[1]);
  163. p = &(d->name[1]);
  164. fprintf(stderr, "\n%s: %d/%d p:%s q:%s %d",
  165. __FUNCTION__, (int)strlen(p), (int)(d->name[0]),
  166. p, q, (int)strlen(q));
  167. #endif
  168. if (type == REQ_A) { /* search by host name */
  169. for (i = 1; i <= (int)(d->name[0]); i++)
  170. if (tolower(qs[i]) != d->name[i])
  171. break;
  172. if (i > (int)(d->name[0])) {
  173. #if DEBUG
  174. fprintf(stderr, " OK");
  175. #endif
  176. strcpy((char *)as, d->ip);
  177. #if DEBUG
  178. fprintf(stderr, " as:%s\n", as);
  179. #endif
  180. return 0;
  181. }
  182. } else
  183. if (type == REQ_PTR) { /* search by IP-address */
  184. if (!strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
  185. strcpy((char *)as, d->name);
  186. return 0;
  187. }
  188. }
  189. d = d->next;
  190. } while (d);
  191. return -1;
  192. }
  193. /*
  194. * Decode message and generate answer
  195. */
  196. #define eret(s) do { fputs(s, stderr); return -1; } while (0)
  197. static int process_packet(uint8_t * buf)
  198. {
  199. struct dns_head *head;
  200. struct dns_prop *qprop;
  201. struct dns_repl outr;
  202. void *next, *from, *answb;
  203. uint8_t answstr[MAX_NAME_LEN + 1];
  204. int lookup_result, type, len, packet_len;
  205. uint16_t flags;
  206. answstr[0] = '\0';
  207. head = (struct dns_head *)buf;
  208. if (head->nquer == 0)
  209. eret("no queries\n");
  210. if (head->flags & 0x8000)
  211. eret("ignoring response packet\n");
  212. from = (void *)&head[1]; // start of query string
  213. next = answb = from + strlen((char *)from) + 1 + sizeof(struct dns_prop); // where to append answer block
  214. outr.rlen = 0; // may change later
  215. outr.r = NULL;
  216. outr.flags = 0;
  217. qprop = (struct dns_prop *)(answb - 4);
  218. type = ntohs(qprop->type);
  219. // only let REQ_A and REQ_PTR pass
  220. if (!(type == REQ_A || type == REQ_PTR)) {
  221. goto empty_packet; /* we can't handle the query type */
  222. }
  223. if (ntohs(qprop->class) != 1 /* class INET */ ) {
  224. outr.flags = 4; /* not supported */
  225. goto empty_packet;
  226. }
  227. /* we only support standard queries */
  228. if ((ntohs(head->flags) & 0x7800) != 0)
  229. goto empty_packet;
  230. // We have a standard query
  231. bb_info_msg("%s", (char *)from);
  232. lookup_result = table_lookup(type, answstr, (uint8_t*)from);
  233. if (lookup_result != 0) {
  234. outr.flags = 3 | 0x0400; //name do not exist and auth
  235. goto empty_packet;
  236. }
  237. if (type == REQ_A) { // return an address
  238. struct in_addr a;
  239. if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
  240. outr.flags = 1; /* Frmt err */
  241. goto empty_packet;
  242. }
  243. memcpy(answstr, &a.s_addr, 4); // save before a disappears
  244. outr.rlen = 4; // uint32_t IP
  245. }
  246. else
  247. outr.rlen = strlen((char *)answstr) + 1; // a host name
  248. outr.r = answstr; // 32 bit ip or a host name
  249. outr.flags |= 0x0400; /* authority-bit */
  250. // we have an answer
  251. head->nansw = htons(1);
  252. // copy query block to answer block
  253. len = answb - from;
  254. memcpy(answb, from, len);
  255. next += len;
  256. // and append answer rr
  257. *(uint32_t *) next = htonl(ttl);
  258. next += 4;
  259. *(uint16_t *) next = htons(outr.rlen);
  260. next += 2;
  261. memcpy(next, (void *)answstr, outr.rlen);
  262. next += outr.rlen;
  263. empty_packet:
  264. flags = ntohs(head->flags);
  265. // clear rcode and RA, set responsebit and our new flags
  266. flags |= (outr.flags & 0xff80) | 0x8000;
  267. head->flags = htons(flags);
  268. head->nauth = head->nadd = htons(0);
  269. head->nquer = htons(1);
  270. packet_len = next - (void *)buf;
  271. return packet_len;
  272. }
  273. /*
  274. * Exit on signal
  275. */
  276. static void interrupt(int x)
  277. {
  278. unlink(LOCK_FILE);
  279. bb_error_msg("interrupt, exiting\n");
  280. exit(2);
  281. }
  282. int dnsd_main(int argc, char **argv)
  283. {
  284. char *listen_interface = NULL;
  285. char *sttl, *sport;
  286. len_and_sockaddr *lsa;
  287. int udps;
  288. uint16_t port = 53;
  289. uint8_t buf[MAX_PACK_LEN];
  290. getopt32(argc, argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
  291. //if (option_mask32 & 0x1) // -i
  292. //if (option_mask32 & 0x2) // -c
  293. if (option_mask32 & 0x4) // -t
  294. ttl = xatou_range(sttl, 1, 0xffffffff);
  295. if (option_mask32 & 0x8) // -p
  296. port = xatou_range(sttl, 1, 0xffff);
  297. if (OPT_verbose) {
  298. bb_info_msg("listen_interface: %s", listen_interface);
  299. bb_info_msg("ttl: %d, port: %d", ttl, port);
  300. bb_info_msg("fileconf: %s", fileconf);
  301. }
  302. if (OPT_daemon) {
  303. //FIXME: NOMMU will NOT set LOGMODE_SYSLOG!
  304. #ifdef BB_NOMMU
  305. /* reexec for vfork() do continue parent */
  306. vfork_daemon_rexec(1, 0, argc, argv, "-d");
  307. #else
  308. xdaemon(1, 0);
  309. #endif
  310. logmode = LOGMODE_SYSLOG;
  311. }
  312. dnsentryinit();
  313. signal(SIGINT, interrupt);
  314. signal(SIGPIPE, SIG_IGN);
  315. signal(SIGHUP, SIG_IGN);
  316. #ifdef SIGTSTP
  317. signal(SIGTSTP, SIG_IGN);
  318. #endif
  319. #ifdef SIGURG
  320. signal(SIGURG, SIG_IGN);
  321. #endif
  322. lsa = host2sockaddr(listen_interface, port);
  323. udps = xsocket(lsa->sa.sa_family, SOCK_DGRAM, 0);
  324. xbind(udps, &lsa->sa, lsa->len);
  325. // xlisten(udps, 50); - ?!! DGRAM sockets are never listened on I think?
  326. bb_info_msg("Accepting UDP packets on %s",
  327. xmalloc_sockaddr2dotted(&lsa->sa, lsa->len));
  328. while (1) {
  329. fd_set fdset;
  330. int r;
  331. FD_ZERO(&fdset);
  332. FD_SET(udps, &fdset);
  333. // Block until a message arrives
  334. // FIXME: Fantastic. select'ing on just one fd??
  335. // Why no just block on it doing recvfrom() ?
  336. r = select(udps + 1, &fdset, NULL, NULL, NULL);
  337. if (r < 0)
  338. bb_perror_msg_and_die("select error");
  339. if (r == 0)
  340. bb_perror_msg_and_die("select spurious return");
  341. /* Can this test ever be false? - yes */
  342. if (FD_ISSET(udps, &fdset)) {
  343. socklen_t fromlen = lsa->len;
  344. // FIXME: need to get *DEST* address (to which of our addresses
  345. // this query was directed), and reply from the same address.
  346. // Or else we can exhibit usual UDP ugliness:
  347. // [ip1.multihomed.ip2] <= query to ip1 <= peer
  348. // [ip1.multihomed.ip2] => reply from ip2 => peer (confused)
  349. r = recvfrom(udps, buf, sizeof(buf), 0, &lsa->sa, &fromlen);
  350. if (OPT_verbose)
  351. bb_info_msg("Got UDP packet");
  352. if (r < 12 || r > 512) {
  353. bb_error_msg("invalid packet size");
  354. continue;
  355. }
  356. if (r <= 0)
  357. continue;
  358. r = process_packet(buf);
  359. if (r <= 0)
  360. continue;
  361. sendto(udps, buf, r, 0, &lsa->sa, fromlen);
  362. }
  363. }
  364. }