dns.c 14 KB

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