dns.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /* Minimal DNS resolver: an A-record query over UDP (RFC 1035).
  2. *
  3. * One question, up to four answers, three sends one second apart. Name
  4. * compression is handled when skipping over the answer section; the reply's
  5. * checksum is not validated, matching the rest of the stack (net_udp_send()
  6. * sends with the UDP checksum disabled too).
  7. *
  8. * Polled like every other net command: the caller owns the NIC
  9. * (netdev_acquire) while dns_resolve() runs. */
  10. #include "io.h"
  11. #include "timer.h"
  12. #include "netcore.h"
  13. #include "netdev.h"
  14. #include "net.h"
  15. #include "process.h"
  16. #include "dns.h"
  17. #define DNS_PORT 53
  18. #define DNS_MAX_ANSWERS 4
  19. #define DNS_RETRY_MS 1000
  20. #define DNS_RETRIES 3
  21. #define DNS_WAIT_MS 15000
  22. #define DNS_CACHE_MAX 8
  23. #define DNS_CACHE_TTL_MS 300000
  24. #define DNS_CACHE_NAME 96
  25. /* Query buffer: 12-byte header + a 255-byte name + qtype/qclass. */
  26. static unsigned char query_buf[12 + 260 + 4];
  27. /* One query may be pending at a time. Stack-mode resolvers hand received
  28. * frames to dns_input() through net_pump(); a raw owner keeps its direct
  29. * polling path because it consumes every frame itself. */
  30. static int dns_busy;
  31. static unsigned int dns_owner;
  32. static unsigned short dns_pending_id;
  33. static unsigned char dns_pending_server[4];
  34. static unsigned char dns_pending_ip[4];
  35. static unsigned char dns_pending_extra[DNS_MAX_ANSWERS][4];
  36. static unsigned int dns_pending_count;
  37. static int dns_pending_result; /* 0 none, 1 answer, -1 failure */
  38. /* Small A-record cache so parallel browser workers that ask for the same
  39. * host do not queue a separate query each. */
  40. struct dns_cache_entry {
  41. char name[DNS_CACHE_NAME];
  42. unsigned char ip[4];
  43. unsigned int age_ms;
  44. int used;
  45. };
  46. static struct dns_cache_entry dns_cache[DNS_CACHE_MAX];
  47. static void put_dec(unsigned int v)
  48. {
  49. char b[12];
  50. int i = 0;
  51. if (v == 0) {
  52. io_putchar('0');
  53. return;
  54. }
  55. while (v) {
  56. b[i++] = (char)('0' + (v % 10));
  57. v /= 10;
  58. }
  59. while (i)
  60. io_putchar(b[--i]);
  61. }
  62. static void put_ip(const unsigned char *ip)
  63. {
  64. unsigned int i;
  65. for (i = 0; i < 4; i++) {
  66. if (i)
  67. io_putchar('.');
  68. put_dec(ip[i]);
  69. }
  70. }
  71. static int ip_eq(const unsigned char *a, const unsigned char *b)
  72. {
  73. return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3];
  74. }
  75. /* Encode a dotted name as DNS labels (no trailing dot needed); 0 on error. */
  76. static int dns_encode_name(const char *name, unsigned char *out,
  77. unsigned int max)
  78. {
  79. const char *p = name;
  80. unsigned int o = 0;
  81. if (!*name)
  82. return -1;
  83. for (;;) {
  84. const char *q = p;
  85. unsigned int n = 0;
  86. while (*q && *q != '.') {
  87. q++;
  88. n++;
  89. }
  90. if (n == 0 || n > 63)
  91. return -1;
  92. /* length byte + label + a possible terminator must fit */
  93. if (o + 1 + n + 1 > max || o + 1 + n > 254)
  94. return -1;
  95. out[o++] = (unsigned char)n;
  96. while (p < q)
  97. out[o++] = (unsigned char)*p++;
  98. if (!*p)
  99. break;
  100. p++; /* skip the '.' */
  101. if (!*p) /* trailing dot */
  102. break;
  103. }
  104. out[o++] = 0;
  105. return (int)o;
  106. }
  107. /* Skip one (possibly compressed) name; 0, or -1 when malformed. */
  108. static int dns_skip_name(const unsigned char *p, unsigned int plen,
  109. unsigned int *pos)
  110. {
  111. while (*pos < plen) {
  112. unsigned char b = p[*pos];
  113. if (b == 0) {
  114. (*pos)++;
  115. return 0;
  116. }
  117. if ((b & 0xC0) == 0xC0) {
  118. if (*pos + 2 > plen)
  119. return -1;
  120. *pos += 2; /* pointer: nothing else to skip */
  121. return 0;
  122. }
  123. if (b & 0xC0)
  124. return -1;
  125. if (*pos + 1 + b > plen)
  126. return -1;
  127. *pos += 1 + b;
  128. }
  129. return -1;
  130. }
  131. /* Check one frame as a reply to our query. Returns:
  132. * 1 = at least one A record (ip and extras filled),
  133. * 0 = not our reply (keep waiting),
  134. * -1 = our reply but a DNS-level failure (already reported). */
  135. static int dns_parse(const unsigned char *frame, unsigned int len,
  136. unsigned short id, const unsigned char *server,
  137. unsigned char ip[4], unsigned char extra[DNS_MAX_ANSWERS][4],
  138. unsigned int *count)
  139. {
  140. unsigned char s_ip[4], d_ip[4];
  141. const unsigned char *p;
  142. unsigned int sport, dport, plen, pos, qd, an, i;
  143. if (!net_udp_parse(frame, len, s_ip, d_ip, &sport, &dport, &p, &plen))
  144. return 0;
  145. if (sport != DNS_PORT || !ip_eq(s_ip, server))
  146. return 0;
  147. if (plen < 12)
  148. return 0;
  149. if ((((unsigned int)p[0] << 8) | p[1]) != id)
  150. return 0;
  151. if (!(p[2] & 0x80)) /* QR: must be a reply */
  152. return 0;
  153. if (p[2] & 0x02) { /* TC: truncated */
  154. io_putstr("dns: reply truncated (TC)\n");
  155. return -1;
  156. }
  157. switch (p[3] & 0x0F) {
  158. case 0:
  159. break;
  160. case 3:
  161. io_putstr("dns: no such name (NXDOMAIN)\n");
  162. return -1;
  163. case 2:
  164. io_putstr("dns: server failure (SERVFAIL)\n");
  165. return -1;
  166. default:
  167. io_putstr("dns: rcode ");
  168. put_dec(p[3] & 0x0F);
  169. io_putchar('\n');
  170. return -1;
  171. }
  172. qd = ((unsigned int)p[4] << 8) | p[5];
  173. an = ((unsigned int)p[6] << 8) | p[7];
  174. pos = 12;
  175. for (i = 0; i < qd; i++) {
  176. if (dns_skip_name(p, plen, &pos) != 0 || pos + 4 > plen)
  177. return 0;
  178. pos += 4; /* qtype + qclass */
  179. }
  180. *count = 0;
  181. for (i = 0; i < an; i++) {
  182. unsigned int type, class_, rdlen;
  183. if (dns_skip_name(p, plen, &pos) != 0 || pos + 10 > plen)
  184. return 0;
  185. type = ((unsigned int)p[pos] << 8) | p[pos + 1];
  186. class_ = ((unsigned int)p[pos + 2] << 8) | p[pos + 3];
  187. rdlen = ((unsigned int)p[pos + 8] << 8) | p[pos + 9];
  188. pos += 10;
  189. if (pos + rdlen > plen)
  190. return 0;
  191. if (type == 1 && class_ == 1 && rdlen == 4) {
  192. unsigned int k;
  193. if (*count == 0) {
  194. for (k = 0; k < 4; k++)
  195. ip[k] = p[pos + k];
  196. } else if (*count < DNS_MAX_ANSWERS) {
  197. for (k = 0; k < 4; k++)
  198. extra[*count - 1][k] = p[pos + k];
  199. }
  200. (*count)++;
  201. }
  202. pos += rdlen;
  203. }
  204. return *count > 0 ? 1 : 0;
  205. }
  206. /* Feed one frame to a pending stack-mode query. Returns 1 when it was a
  207. * reply to the pending query (consumed), 0 otherwise. */
  208. int dns_input(const unsigned char *frame, unsigned int len)
  209. {
  210. int r;
  211. if (!dns_busy || dns_pending_result)
  212. return 0;
  213. r = dns_parse(frame, len, dns_pending_id, dns_pending_server,
  214. dns_pending_ip, dns_pending_extra,
  215. &dns_pending_count);
  216. if (r == 0)
  217. return 0;
  218. dns_pending_result = r > 0 ? 1 : -1;
  219. return 1;
  220. }
  221. void dns_reap(unsigned int pid)
  222. {
  223. if (dns_busy && dns_owner == pid) {
  224. dns_busy = 0;
  225. dns_owner = 0;
  226. dns_pending_result = 0;
  227. }
  228. }
  229. static void dns_print_answer(const char *name, const unsigned char *ip,
  230. const unsigned char extra[DNS_MAX_ANSWERS][4],
  231. unsigned int count)
  232. {
  233. unsigned int i;
  234. io_putstr("dns: ");
  235. io_putstr(name);
  236. io_putstr(" -> ");
  237. put_ip(ip);
  238. for (i = 1; i < count && i < DNS_MAX_ANSWERS; i++) {
  239. io_putstr(", ");
  240. put_ip(extra[i - 1]);
  241. }
  242. io_putchar('\n');
  243. }
  244. static void dns_print_cached(const char *name, const unsigned char *ip)
  245. {
  246. io_putstr("dns: ");
  247. io_putstr(name);
  248. io_putstr(" -> ");
  249. put_ip(ip);
  250. io_putchar('\n');
  251. }
  252. static int dns_name_eq(const char *a, const char *b)
  253. {
  254. while (*a && *b && *a == *b)
  255. a++, b++;
  256. return *a == *b;
  257. }
  258. static int dns_cache_lookup(const char *name, unsigned char ip[4])
  259. {
  260. unsigned int i, now = get_ticks_ms();
  261. for (i = 0; i < DNS_CACHE_MAX; i++) {
  262. if (!dns_cache[i].used ||
  263. !dns_name_eq(dns_cache[i].name, name))
  264. continue;
  265. if (now - dns_cache[i].age_ms > DNS_CACHE_TTL_MS) {
  266. dns_cache[i].used = 0;
  267. return 0;
  268. }
  269. ip[0] = dns_cache[i].ip[0];
  270. ip[1] = dns_cache[i].ip[1];
  271. ip[2] = dns_cache[i].ip[2];
  272. ip[3] = dns_cache[i].ip[3];
  273. return 1;
  274. }
  275. return 0;
  276. }
  277. static void dns_cache_put(const char *name, const unsigned char ip[4])
  278. {
  279. unsigned int i, n = 0, slot = 0;
  280. while (name[n] && n + 1 < DNS_CACHE_NAME)
  281. n++;
  282. if (name[n]) /* too long: do not truncate */
  283. return;
  284. for (i = 0; i < DNS_CACHE_MAX; i++) {
  285. if (dns_cache[i].used && dns_name_eq(dns_cache[i].name, name)) {
  286. slot = i;
  287. goto store;
  288. }
  289. }
  290. for (i = 0; i < DNS_CACHE_MAX; i++) {
  291. if (!dns_cache[i].used) {
  292. slot = i;
  293. goto store;
  294. }
  295. if (dns_cache[i].age_ms < dns_cache[slot].age_ms)
  296. slot = i;
  297. }
  298. store:
  299. for (i = 0; i < n; i++)
  300. dns_cache[slot].name[i] = name[i];
  301. dns_cache[slot].name[n] = '\0';
  302. dns_cache[slot].ip[0] = ip[0];
  303. dns_cache[slot].ip[1] = ip[1];
  304. dns_cache[slot].ip[2] = ip[2];
  305. dns_cache[slot].ip[3] = ip[3];
  306. dns_cache[slot].age_ms = get_ticks_ms();
  307. dns_cache[slot].used = 1;
  308. }
  309. int dns_resolve(const char *name, unsigned char ip[4])
  310. {
  311. unsigned char server[4], hop[4], server_mac[6];
  312. unsigned char extra[DNS_MAX_ANSWERS][4];
  313. const struct netdev *nd = netdev_active();
  314. unsigned short id;
  315. unsigned int sport, qlen, tries, count = 0, i;
  316. unsigned int pid = current_proc() ? current_proc()->pid : 0;
  317. unsigned int wait_start;
  318. int raw, r = -1;
  319. if (!nd) {
  320. io_putstr("dns: no NIC found\n");
  321. return -1;
  322. }
  323. if (dns_cache_lookup(name, ip)) {
  324. dns_print_cached(name, ip);
  325. return 0;
  326. }
  327. raw = pid && netdev_owner() == pid;
  328. if (!raw)
  329. net_stack_enter();
  330. /* One query in flight. A second stack-mode resolver waits (and keeps
  331. * pumping TCP frames) until the first one finishes. */
  332. wait_start = get_ticks_ms();
  333. while (dns_busy && dns_owner != pid) {
  334. if (raw ||
  335. (int)(get_ticks_ms() - (wait_start + DNS_WAIT_MS)) >= 0) {
  336. if (!raw)
  337. net_stack_leave();
  338. return -1;
  339. }
  340. net_pump_burst(64);
  341. process_sleep_ms(1);
  342. }
  343. dns_busy = 1;
  344. dns_owner = pid;
  345. dns_pending_result = 0;
  346. dns_pending_count = 0;
  347. /* The waiter we just queued behind may have filled the cache. */
  348. if (dns_cache_lookup(name, ip)) {
  349. dns_print_cached(name, ip);
  350. goto out;
  351. }
  352. net_get_dns(server);
  353. if (!(server[0] || server[1] || server[2] || server[3])) {
  354. /* Home routers usually proxy DNS for their clients. */
  355. net_get_gateway(server);
  356. if (!(server[0] || server[1] || server[2] || server[3])) {
  357. io_putstr("dns: no resolver (run netdns <a.b.c.d>)\n");
  358. goto out;
  359. }
  360. }
  361. for (i = 0; i < 12; i++)
  362. query_buf[i] = 0;
  363. id = (unsigned short)(get_ticks_ms() ^
  364. ((unsigned int)(unsigned char)name[0] << 8) ^
  365. 0x4E42);
  366. query_buf[0] = (unsigned char)(id >> 8);
  367. query_buf[1] = (unsigned char)id;
  368. query_buf[2] = 0x01; /* RD=1: recursion desired */
  369. query_buf[5] = 1; /* QDCOUNT=1 */
  370. qlen = 12;
  371. {
  372. int n = dns_encode_name(name, query_buf + 12,
  373. sizeof(query_buf) - 12 - 4);
  374. if (n <= 0) {
  375. io_putstr("dns: bad name\n");
  376. goto out;
  377. }
  378. qlen += (unsigned int)n;
  379. }
  380. query_buf[qlen++] = 0; /* QTYPE A */
  381. query_buf[qlen++] = 1;
  382. query_buf[qlen++] = 0; /* QCLASS IN */
  383. query_buf[qlen++] = 1;
  384. sport = 45000 + (id & 0x0FFF);
  385. for (i = 0; i < 4; i++)
  386. dns_pending_server[i] = server[i];
  387. dns_pending_id = id;
  388. net_next_hop(server, hop);
  389. if (net_arp_resolve(hop, server_mac) != 0) {
  390. io_putstr("dns: no ARP reply from ");
  391. put_ip(hop);
  392. io_putchar('\n');
  393. goto out;
  394. }
  395. for (tries = 0; tries < DNS_RETRIES; tries++) {
  396. unsigned int deadline = get_ticks_ms() + DNS_RETRY_MS;
  397. unsigned int flags;
  398. int tx;
  399. flags = net_irq_enter();
  400. tx = net_udp_send(server_mac, server, sport, DNS_PORT,
  401. query_buf, qlen);
  402. net_irq_exit(flags);
  403. if (tx != 0) {
  404. io_putstr("dns: send failed\n");
  405. goto out;
  406. }
  407. while ((int)(get_ticks_ms() - deadline) < 0) {
  408. if (raw) {
  409. int len = nd->rx(netdev_rx_scratch(),
  410. NETDEV_FRAME_MAX);
  411. if (len < 0)
  412. continue;
  413. r = dns_parse(netdev_rx_scratch(),
  414. (unsigned int)len, id, server,
  415. ip, extra, &count);
  416. if (r < 0)
  417. goto out;
  418. if (r == 0)
  419. continue;
  420. dns_cache_put(name, ip);
  421. dns_print_answer(name, ip, extra, count);
  422. r = 0;
  423. goto out;
  424. }
  425. net_pump_burst(64);
  426. if (dns_pending_result > 0) {
  427. for (i = 0; i < 4; i++)
  428. ip[i] = dns_pending_ip[i];
  429. for (i = 0; i < DNS_MAX_ANSWERS; i++) {
  430. unsigned int j;
  431. for (j = 0; j < 4; j++)
  432. extra[i][j] =
  433. dns_pending_extra[i][j];
  434. }
  435. count = dns_pending_count;
  436. dns_cache_put(name, ip);
  437. dns_print_answer(name, ip, extra, count);
  438. r = 0;
  439. goto out;
  440. }
  441. if (dns_pending_result < 0)
  442. goto out;
  443. process_sleep_ms(1);
  444. }
  445. }
  446. io_putstr("dns: no reply from ");
  447. put_ip(server);
  448. io_putchar('\n');
  449. out:
  450. dns_busy = 0;
  451. dns_owner = 0;
  452. dns_pending_result = 0;
  453. if (!raw)
  454. net_stack_leave();
  455. return r;
  456. }