dns.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. //*****************************************************************************
  2. //
  3. //! \file dns.c
  4. //! \brief DNS APIs Implement file.
  5. //! \details Send DNS query & Receive DNS reponse. \n
  6. //! It depends on stdlib.h & string.h in ansi-c library
  7. //! \version 1.1.0
  8. //! \date 2013/11/18
  9. //! \par Revision history
  10. //! <2013/10/21> 1st Release
  11. //! <2013/12/20> V1.1.0
  12. //! 1. Remove secondary DNS server in DNS_run
  13. //! If 1st DNS_run failed, call DNS_run with 2nd DNS again
  14. //! 2. DNS_timerHandler -> DNS_time_handler
  15. //! 3. Remove the unused define
  16. //! 4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c
  17. //! <2013/12/20> V1.1.0
  18. //!
  19. //! \author Eric Jung & MidnightCow
  20. //! \copyright
  21. //!
  22. //! Copyright (c) 2013, WIZnet Co., LTD.
  23. //! All rights reserved.
  24. //!
  25. //! Redistribution and use in source and binary forms, with or without
  26. //! modification, are permitted provided that the following conditions
  27. //! are met:
  28. //!
  29. //! * Redistributions of source code must retain the above copyright
  30. //! notice, this list of conditions and the following disclaimer.
  31. //! * Redistributions in binary form must reproduce the above copyright
  32. //! notice, this list of conditions and the following disclaimer in the
  33. //! documentation and/or other materials provided with the distribution.
  34. //! * Neither the name of the <ORGANIZATION> nor the names of its
  35. //! contributors may be used to endorse or promote products derived
  36. //! from this software without specific prior written permission.
  37. //!
  38. //! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  39. //! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  40. //! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  41. //! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  42. //! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  43. //! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  44. //! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  45. //! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  46. //! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  47. //! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  48. //! THE POSSIBILITY OF SUCH DAMAGE.
  49. //
  50. //*****************************************************************************
  51. #include <RTL.h>
  52. #include <string.h>
  53. #include <stdlib.h>
  54. #include "Ethernet/socket.h"
  55. #include "Internet/dns.h"
  56. #ifdef _DNS_DEBUG_
  57. #include <stdio.h>
  58. #endif
  59. #define INITRTT 2000L /* Initial smoothed response time */
  60. #define MAXCNAME (MAX_DOMAIN_NAME + (MAX_DOMAIN_NAME>>1)) /* Maximum amount of cname recursion */
  61. #define TYPE_A 1 /* Host address */
  62. #define TYPE_NS 2 /* Name server */
  63. #define TYPE_MD 3 /* Mail destination (obsolete) */
  64. #define TYPE_MF 4 /* Mail forwarder (obsolete) */
  65. #define TYPE_CNAME 5 /* Canonical name */
  66. #define TYPE_SOA 6 /* Start of Authority */
  67. #define TYPE_MB 7 /* Mailbox name (experimental) */
  68. #define TYPE_MG 8 /* Mail group member (experimental) */
  69. #define TYPE_MR 9 /* Mail rename name (experimental) */
  70. #define TYPE_NULL 10 /* Null (experimental) */
  71. #define TYPE_WKS 11 /* Well-known sockets */
  72. #define TYPE_PTR 12 /* Pointer record */
  73. #define TYPE_HINFO 13 /* Host information */
  74. #define TYPE_MINFO 14 /* Mailbox information (experimental)*/
  75. #define TYPE_MX 15 /* Mail exchanger */
  76. #define TYPE_TXT 16 /* Text strings */
  77. #define TYPE_ANY 255 /* Matches any type */
  78. #define CLASS_IN 1 /* The ARPA Internet */
  79. /* Round trip timing parameters */
  80. #define AGAIN 8 /* Average RTT gain = 1/8 */
  81. #define LAGAIN 3 /* Log2(AGAIN) */
  82. #define DGAIN 4 /* Mean deviation gain = 1/4 */
  83. #define LDGAIN 2 /* log2(DGAIN) */
  84. /* Header for all domain messages */
  85. struct dhdr
  86. {
  87. uint16_t id; /* Identification */
  88. uint8_t qr; /* Query/Response */
  89. #define QUERY 0
  90. #define RESPONSE 1
  91. uint8_t opcode;
  92. #define IQUERY 1
  93. uint8_t aa; /* Authoratative answer */
  94. uint8_t tc; /* Truncation */
  95. uint8_t rd; /* Recursion desired */
  96. uint8_t ra; /* Recursion available */
  97. uint8_t rcode; /* Response code */
  98. #define NO_ERROR 0
  99. #define FORMAT_ERROR 1
  100. #define SERVER_FAIL 2
  101. #define NAME_ERROR 3
  102. #define NOT_IMPL 4
  103. #define REFUSED 5
  104. uint16_t qdcount; /* Question count */
  105. uint16_t ancount; /* Answer count */
  106. uint16_t nscount; /* Authority (name server) count */
  107. uint16_t arcount; /* Additional record count */
  108. };
  109. uint8_t* pDNSMSG; // DNS message buffer
  110. uint8_t DNS_SOCKET; // SOCKET number for DNS
  111. uint16_t DNS_MSGID; // DNS message ID
  112. uint32_t dns_1s_tick; // for timout of DNS processing
  113. /* converts uint16_t from network buffer to a host byte order integer. */
  114. uint16_t get16(uint8_t * s)
  115. {
  116. uint16_t i;
  117. i = *s++ << 8;
  118. i = i + *s;
  119. return i;
  120. }
  121. /* copies uint16_t to the network buffer with network byte order. */
  122. uint8_t * put16(uint8_t * s, uint16_t i)
  123. {
  124. *s++ = i >> 8;
  125. *s++ = i;
  126. return s;
  127. }
  128. /*
  129. * CONVERT A DOMAIN NAME TO THE HUMAN-READABLE FORM
  130. *
  131. * Description : This function converts a compressed domain name to the human-readable form
  132. * Arguments : msg - is a pointer to the reply message
  133. * compressed - is a pointer to the domain name in reply message.
  134. * buf - is a pointer to the buffer for the human-readable form name.
  135. * len - is the MAX. size of buffer.
  136. * Returns : the length of compressed message
  137. */
  138. int parse_name(uint8_t * msg, uint8_t * compressed, char * buf, int16_t len)
  139. {
  140. uint16_t slen; /* Length of current segment */
  141. uint8_t * cp;
  142. int clen = 0; /* Total length of compressed name */
  143. int indirect = 0; /* Set if indirection encountered */
  144. int nseg = 0; /* Total number of segments in name */
  145. cp = compressed;
  146. for (;;)
  147. {
  148. slen = *cp++; /* Length of this segment */
  149. if (!indirect) clen++;
  150. if ((slen & 0xc0) == 0xc0)
  151. {
  152. if (!indirect)
  153. clen++;
  154. indirect = 1;
  155. /* Follow indirection */
  156. cp = &msg[((slen & 0x3f)<<8) + *cp];
  157. slen = *cp++;
  158. }
  159. if (slen == 0) /* zero length == all done */
  160. break;
  161. len -= slen + 1;
  162. if (len < 0) return -1;
  163. if (!indirect) clen += slen;
  164. while (slen-- != 0) *buf++ = (char)*cp++;
  165. *buf++ = '.';
  166. nseg++;
  167. }
  168. if (nseg == 0)
  169. {
  170. /* Root name; represent as single dot */
  171. *buf++ = '.';
  172. len--;
  173. }
  174. *buf++ = '\0';
  175. len--;
  176. return clen; /* Length of compressed message */
  177. }
  178. /*
  179. * PARSE QUESTION SECTION
  180. *
  181. * Description : This function parses the qeustion record of the reply message.
  182. * Arguments : msg - is a pointer to the reply message
  183. * cp - is a pointer to the qeustion record.
  184. * Returns : a pointer the to next record.
  185. */
  186. uint8_t * dns_question(uint8_t * msg, uint8_t * cp)
  187. {
  188. int len;
  189. char name[MAXCNAME];
  190. len = parse_name(msg, cp, name, MAXCNAME);
  191. if (len == -1) return 0;
  192. cp += len;
  193. cp += 2; /* type */
  194. cp += 2; /* class */
  195. return cp;
  196. }
  197. /*
  198. * PARSE ANSER SECTION
  199. *
  200. * Description : This function parses the answer record of the reply message.
  201. * Arguments : msg - is a pointer to the reply message
  202. * cp - is a pointer to the answer record.
  203. * Returns : a pointer the to next record.
  204. */
  205. uint8_t * dns_answer(uint8_t * msg, uint8_t * cp, uint8_t * ip_from_dns)
  206. {
  207. int len, type;
  208. char name[MAXCNAME];
  209. len = parse_name(msg, cp, name, MAXCNAME);
  210. if (len == -1) return 0;
  211. cp += len;
  212. type = get16(cp);
  213. cp += 2; /* type */
  214. cp += 2; /* class */
  215. cp += 4; /* ttl */
  216. cp += 2; /* len */
  217. switch (type)
  218. {
  219. case TYPE_A:
  220. /* Just read the address directly into the structure */
  221. ip_from_dns[0] = *cp++;
  222. ip_from_dns[1] = *cp++;
  223. ip_from_dns[2] = *cp++;
  224. ip_from_dns[3] = *cp++;
  225. break;
  226. case TYPE_CNAME:
  227. case TYPE_MB:
  228. case TYPE_MG:
  229. case TYPE_MR:
  230. case TYPE_NS:
  231. case TYPE_PTR:
  232. /* These types all consist of a single domain name */
  233. /* convert it to ascii format */
  234. len = parse_name(msg, cp, name, MAXCNAME);
  235. if (len == -1) return 0;
  236. cp += len;
  237. break;
  238. case TYPE_HINFO:
  239. len = *cp++;
  240. cp += len;
  241. len = *cp++;
  242. cp += len;
  243. break;
  244. case TYPE_MX:
  245. cp += 2;
  246. /* Get domain name of exchanger */
  247. len = parse_name(msg, cp, name, MAXCNAME);
  248. if (len == -1) return 0;
  249. cp += len;
  250. break;
  251. case TYPE_SOA:
  252. /* Get domain name of name server */
  253. len = parse_name(msg, cp, name, MAXCNAME);
  254. if (len == -1) return 0;
  255. cp += len;
  256. /* Get domain name of responsible person */
  257. len = parse_name(msg, cp, name, MAXCNAME);
  258. if (len == -1) return 0;
  259. cp += len;
  260. cp += 4;
  261. cp += 4;
  262. cp += 4;
  263. cp += 4;
  264. cp += 4;
  265. break;
  266. case TYPE_TXT:
  267. /* Just stash */
  268. break;
  269. default:
  270. /* Ignore */
  271. break;
  272. }
  273. return cp;
  274. }
  275. /*
  276. * PARSE THE DNS REPLY
  277. *
  278. * Description : This function parses the reply message from DNS server.
  279. * Arguments : dhdr - is a pointer to the header for DNS message
  280. * buf - is a pointer to the reply message.
  281. * len - is the size of reply message.
  282. * Returns : -1 - Domain name lenght is too big
  283. * 0 - Fail (Timout or parse error)
  284. * 1 - Success,
  285. */
  286. int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns)
  287. {
  288. uint16_t tmp;
  289. uint16_t i;
  290. uint8_t * msg;
  291. uint8_t * cp;
  292. msg = pbuf;
  293. memset(pdhdr, 0, sizeof(pdhdr));
  294. pdhdr->id = get16(&msg[0]);
  295. tmp = get16(&msg[2]);
  296. if (tmp & 0x8000) pdhdr->qr = 1;
  297. pdhdr->opcode = (tmp >> 11) & 0xf;
  298. if (tmp & 0x0400) pdhdr->aa = 1;
  299. if (tmp & 0x0200) pdhdr->tc = 1;
  300. if (tmp & 0x0100) pdhdr->rd = 1;
  301. if (tmp & 0x0080) pdhdr->ra = 1;
  302. pdhdr->rcode = tmp & 0xf;
  303. pdhdr->qdcount = get16(&msg[4]);
  304. pdhdr->ancount = get16(&msg[6]);
  305. pdhdr->nscount = get16(&msg[8]);
  306. pdhdr->arcount = get16(&msg[10]);
  307. /* Now parse the variable length sections */
  308. cp = &msg[12];
  309. /* Question section */
  310. for (i = 0; i < pdhdr->qdcount; i++)
  311. {
  312. cp = dns_question(msg, cp);
  313. #ifdef _DNS_DEUBG_
  314. printf("MAX_DOMAIN_NAME is too small, it should be redfine in dns.h"
  315. #endif
  316. if(!cp) return -1;
  317. }
  318. /* Answer section */
  319. for (i = 0; i < pdhdr->ancount; i++)
  320. {
  321. cp = dns_answer(msg, cp, ip_from_dns);
  322. #ifdef _DNS_DEUBG_
  323. printf("MAX_DOMAIN_NAME is too small, it should be redfine in dns.h"
  324. #endif
  325. if(!cp) return -1;
  326. }
  327. /* Name server (authority) section */
  328. for (i = 0; i < pdhdr->nscount; i++)
  329. {
  330. ;
  331. }
  332. /* Additional section */
  333. for (i = 0; i < pdhdr->arcount; i++)
  334. {
  335. ;
  336. }
  337. if(pdhdr->rcode == 0) return 1; // No error
  338. else return 0;
  339. }
  340. /*
  341. * MAKE DNS QUERY MESSAGE
  342. *
  343. * Description : This function makes DNS query message.
  344. * Arguments : op - Recursion desired
  345. * name - is a pointer to the domain name.
  346. * buf - is a pointer to the buffer for DNS message.
  347. * len - is the MAX. size of buffer.
  348. * Returns : the pointer to the DNS message.
  349. */
  350. int16_t dns_makequery(uint16_t op, char * name, uint8_t * buf, uint16_t len)
  351. {
  352. uint8_t *cp;
  353. char *cp1;
  354. char sname[MAXCNAME];
  355. char *dname;
  356. uint16_t p;
  357. uint16_t dlen;
  358. cp = buf;
  359. DNS_MSGID++;
  360. cp = put16(cp, DNS_MSGID);
  361. p = (op << 11) | 0x0100; /* Recursion desired */
  362. cp = put16(cp, p);
  363. cp = put16(cp, 1);
  364. cp = put16(cp, 0);
  365. cp = put16(cp, 0);
  366. cp = put16(cp, 0);
  367. strcpy(sname, name);
  368. dname = sname;
  369. dlen = strlen(dname);
  370. for (;;)
  371. {
  372. /* Look for next dot */
  373. cp1 = strchr(dname, '.');
  374. if (cp1 != NULL) len = cp1 - dname; /* More to come */
  375. else len = dlen; /* Last component */
  376. *cp++ = len; /* Write length of component */
  377. if (len == 0) break;
  378. /* Copy component up to (but not including) dot */
  379. strncpy((char *)cp, dname, len);
  380. cp += len;
  381. if (cp1 == NULL)
  382. {
  383. *cp++ = 0; /* Last one; write null and finish */
  384. break;
  385. }
  386. dname += len+1;
  387. dlen -= len+1;
  388. }
  389. cp = put16(cp, 0x0001); /* type */
  390. cp = put16(cp, 0x0001); /* class */
  391. return ((int16_t)((uint32_t)(cp) - (uint32_t)(buf)));
  392. }
  393. /*
  394. * CHECK DNS TIMEOUT
  395. *
  396. * Description : This function check the DNS timeout
  397. * Arguments : None.
  398. * Returns : -1 - timeout occurred, 0 - timer over, but no timeout, 1 - no timer over, no timeout occur
  399. * Note : timeout : retry count and timer both over.
  400. */
  401. int8_t check_DNS_timeout(void)
  402. {
  403. static uint8_t retry_count;
  404. if(dns_1s_tick >= DNS_WAIT_TIME)
  405. {
  406. dns_1s_tick = 0;
  407. if(retry_count >= MAX_DNS_RETRY) {
  408. retry_count = 0;
  409. return -1; // timeout occurred
  410. }
  411. retry_count++;
  412. return 0; // timer over, but no timeout
  413. }
  414. return 1; // no timer over, no timeout occur
  415. }
  416. /* DNS CLIENT INIT */
  417. void DNS_init(uint8_t s, uint8_t * buf)
  418. {
  419. DNS_SOCKET = s; // SOCK_DNS
  420. pDNSMSG = buf; // User's shared buffer
  421. DNS_MSGID = DNS_MSG_ID;
  422. }
  423. /* DNS CLIENT RUN */
  424. int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns)
  425. {
  426. int8_t ret;
  427. struct dhdr dhp;
  428. uint8_t ip[4];
  429. uint16_t len, port;
  430. int8_t ret_check_timeout;
  431. // Socket open
  432. socket(DNS_SOCKET, Sn_MR_UDP, 0, 0);
  433. #ifdef _DNS_DEBUG_
  434. printf("> DNS Query to DNS Server : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]);
  435. #endif
  436. len = dns_makequery(0, (char *)name, pDNSMSG, MAX_DNS_BUF_SIZE);
  437. sendto(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN);
  438. while (1)
  439. {
  440. if ((len = getSn_RX_RSR(DNS_SOCKET)) > 0)
  441. {
  442. if (len > MAX_DNS_BUF_SIZE) len = MAX_DNS_BUF_SIZE;
  443. len = recvfrom(DNS_SOCKET, pDNSMSG, len, ip, &port);
  444. #ifdef _DNS_DEBUG_
  445. printf("> Receive DNS message from %d.%d.%d.%d(%d). len = %d\r\n", ip[0], ip[1], ip[2], ip[3],port,len);
  446. #endif
  447. ret = parseDNSMSG(&dhp, pDNSMSG, ip_from_dns);
  448. break;
  449. }
  450. // Check Timeout
  451. ret_check_timeout = check_DNS_timeout();
  452. if (ret_check_timeout < 0) {
  453. #ifdef _DNS_DEBUG_
  454. printf("> DNS Server is not responding : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]);
  455. #endif
  456. return 0; // timeout occurred
  457. }
  458. else if (ret_check_timeout == 0) {
  459. #ifdef _DNS_DEBUG_
  460. printf("> DNS Timeout\r\n");
  461. #endif
  462. sendto(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN);
  463. }
  464. }
  465. close(DNS_SOCKET);
  466. // Return value
  467. // 0 > : failed / 1 - success
  468. return ret;
  469. }
  470. /* DNS TIMER HANDLER */
  471. void DNS_time_handler(void)
  472. {
  473. dns_1s_tick++;
  474. }