dns.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. /**
  2. * @file
  3. * DNS - host name to IP address resolver.
  4. *
  5. */
  6. /**
  7. * This file implements a DNS host name to IP address resolver.
  8. * Port to lwIP from uIP
  9. * by Jim Pettinato April 2007
  10. * uIP version Copyright (c) 2002-2003, Adam Dunkels.
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or without
  14. * modification, are permitted provided that the following conditions
  15. * are met:
  16. * 1. Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. * 2. Redistributions in binary form must reproduce the above copyright
  19. * notice, this list of conditions and the following disclaimer in the
  20. * documentation and/or other materials provided with the distribution.
  21. * 3. The name of the author may not be used to endorse or promote
  22. * products derived from this software without specific prior
  23. * written permission.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  26. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  27. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  28. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  29. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  30. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  31. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  32. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  33. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  34. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  35. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. *
  37. *
  38. * DNS.C
  39. *
  40. * The lwIP DNS resolver functions are used to lookup a host name and
  41. * map it to a numerical IP address. It maintains a list of resolved
  42. * hostnames that can be queried with the dns_lookup() function.
  43. * New hostnames can be resolved using the dns_query() function.
  44. *
  45. * The lwIP version of the resolver also adds a non-blocking version of
  46. * gethostbyname() that will work with a raw API application. This function
  47. * checks for an IP address string first and converts it if it is valid.
  48. * gethostbyname() then does a dns_lookup() to see if the name is
  49. * already in the table. If so, the IP is returned. If not, a query is
  50. * issued and the function returns with a ERR_INPROGRESS status. The app
  51. * using the dns client must then go into a waiting state.
  52. *
  53. * Once a hostname has been resolved (or found to be non-existent),
  54. * the resolver code calls a specified callback function (which
  55. * must be implemented by the module that uses the resolver).
  56. */
  57. /*-----------------------------------------------------------------------------
  58. * RFC 1035 - Domain names - implementation and specification
  59. * RFC 2181 - Clarifications to the DNS Specification
  60. *----------------------------------------------------------------------------*/
  61. /** @todo: define good default values (rfc compliance) */
  62. /** @todo: improve answer parsing, more checkings... */
  63. /** @todo: check RFC1035 - 7.3. Processing responses */
  64. /*-----------------------------------------------------------------------------
  65. * Includes
  66. *----------------------------------------------------------------------------*/
  67. #include "lwip/opt.h"
  68. #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
  69. #include "lwip/udp.h"
  70. #include "lwip/mem.h"
  71. #include "lwip/memp.h"
  72. #include "lwip/dns.h"
  73. #include <string.h>
  74. #ifdef MEMLEAK_DEBUG
  75. static const char mem_debug_file[] ICACHE_RODATA_ATTR = __FILE__;
  76. #endif
  77. /** DNS server IP address */
  78. #ifndef DNS_SERVER_ADDRESS
  79. #define DNS_SERVER_ADDRESS(ipaddr) (ip4_addr_set_u32(ipaddr, 0xDEDE43D0)) /* resolver1.opendns.com(208.67.222.222) */
  80. #endif
  81. /** DNS server port address */
  82. #ifndef DNS_SERVER_PORT
  83. #define DNS_SERVER_PORT 53
  84. #endif
  85. /** DNS maximum number of retries when asking for a name, before "timeout". */
  86. #ifndef DNS_MAX_RETRIES
  87. #define DNS_MAX_RETRIES 4
  88. #endif
  89. /** DNS resource record max. TTL (one week as default) */
  90. #ifndef DNS_MAX_TTL
  91. #define DNS_MAX_TTL 604800
  92. #endif
  93. /* DNS protocol flags */
  94. #define DNS_FLAG1_RESPONSE 0x80
  95. #define DNS_FLAG1_OPCODE_STATUS 0x10
  96. #define DNS_FLAG1_OPCODE_INVERSE 0x08
  97. #define DNS_FLAG1_OPCODE_STANDARD 0x00
  98. #define DNS_FLAG1_AUTHORATIVE 0x04
  99. #define DNS_FLAG1_TRUNC 0x02
  100. #define DNS_FLAG1_RD 0x01
  101. #define DNS_FLAG2_RA 0x80
  102. #define DNS_FLAG2_ERR_MASK 0x0f
  103. #define DNS_FLAG2_ERR_NONE 0x00
  104. #define DNS_FLAG2_ERR_NAME 0x03
  105. /* DNS protocol states */
  106. #define DNS_STATE_UNUSED 0
  107. #define DNS_STATE_NEW 1
  108. #define DNS_STATE_ASKING 2
  109. #define DNS_STATE_DONE 3
  110. #ifdef PACK_STRUCT_USE_INCLUDES
  111. # include "arch/bpstruct.h"
  112. #endif
  113. PACK_STRUCT_BEGIN
  114. /** DNS message header */
  115. struct dns_hdr {
  116. PACK_STRUCT_FIELD(u16_t id);
  117. PACK_STRUCT_FIELD(u8_t flags1);
  118. PACK_STRUCT_FIELD(u8_t flags2);
  119. PACK_STRUCT_FIELD(u16_t numquestions);
  120. PACK_STRUCT_FIELD(u16_t numanswers);
  121. PACK_STRUCT_FIELD(u16_t numauthrr);
  122. PACK_STRUCT_FIELD(u16_t numextrarr);
  123. } PACK_STRUCT_STRUCT;
  124. PACK_STRUCT_END
  125. #ifdef PACK_STRUCT_USE_INCLUDES
  126. # include "arch/epstruct.h"
  127. #endif
  128. #define SIZEOF_DNS_HDR 12
  129. /** DNS query message structure.
  130. No packing needed: only used locally on the stack. */
  131. struct dns_query {
  132. /* DNS query record starts with either a domain name or a pointer
  133. to a name already present somewhere in the packet. */
  134. u16_t type;
  135. u16_t cls;
  136. };
  137. #define SIZEOF_DNS_QUERY 4
  138. /** DNS answer message structure.
  139. No packing needed: only used locally on the stack. */
  140. struct dns_answer {
  141. /* DNS answer record starts with either a domain name or a pointer
  142. to a name already present somewhere in the packet. */
  143. u16_t type;
  144. u16_t cls;
  145. u32_t ttl;
  146. u16_t len;
  147. };
  148. #define SIZEOF_DNS_ANSWER 10
  149. /** DNS table entry */
  150. struct dns_table_entry {
  151. u8_t state;
  152. u8_t numdns;
  153. u8_t tmr;
  154. u8_t retries;
  155. u8_t seqno;
  156. u8_t err;
  157. u32_t ttl;
  158. char name[DNS_MAX_NAME_LENGTH];
  159. ip_addr_t ipaddr;
  160. /* pointer to callback on DNS query done */
  161. dns_found_callback found;
  162. void *arg;
  163. };
  164. #if DNS_LOCAL_HOSTLIST
  165. #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
  166. /** Local host-list. For hostnames in this list, no
  167. * external name resolution is performed */
  168. static struct local_hostlist_entry *local_hostlist_dynamic;
  169. #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
  170. /** Defining this allows the local_hostlist_static to be placed in a different
  171. * linker section (e.g. FLASH) */
  172. #ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE
  173. #define DNS_LOCAL_HOSTLIST_STORAGE_PRE static
  174. #endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */
  175. /** Defining this allows the local_hostlist_static to be placed in a different
  176. * linker section (e.g. FLASH) */
  177. #ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST
  178. #define DNS_LOCAL_HOSTLIST_STORAGE_POST
  179. #endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */
  180. DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[]
  181. DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT;
  182. #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
  183. static void dns_init_local();
  184. #endif /* DNS_LOCAL_HOSTLIST */
  185. /* forward declarations */
  186. static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port);
  187. static void dns_check_entries(void);
  188. /*-----------------------------------------------------------------------------
  189. * Globales
  190. *----------------------------------------------------------------------------*/
  191. /* DNS variables */
  192. static struct udp_pcb *dns_pcb;
  193. static u8_t dns_seqno;
  194. static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
  195. static ip_addr_t dns_servers[DNS_MAX_SERVERS];
  196. /** Contiguous buffer for processing responses */
  197. //static u8_t dns_payload_buffer[LWIP_MEM_ALIGN_BUFFER(DNS_MSG_SIZE)];
  198. static u8_t* dns_payload;
  199. static u16_t dns_random;
  200. /**
  201. * Initialize the resolver: set up the UDP pcb and configure the default server
  202. * (DNS_SERVER_ADDRESS).
  203. */
  204. void ICACHE_FLASH_ATTR
  205. dns_init()
  206. {
  207. ip_addr_t dnsserver;
  208. // dns_payload = (u8_t *)LWIP_MEM_ALIGN(dns_payload_buffer);
  209. /* initialize default DNS server address */
  210. DNS_SERVER_ADDRESS(&dnsserver);
  211. LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
  212. /* if dns client not yet initialized... */
  213. if (dns_pcb == NULL) {
  214. dns_pcb = udp_new();
  215. if (dns_pcb != NULL) {
  216. /* initialize DNS table not needed (initialized to zero since it is a
  217. * global variable) */
  218. LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0",
  219. DNS_STATE_UNUSED == 0);
  220. /* initialize DNS client */
  221. udp_bind(dns_pcb, IP_ADDR_ANY, 0);
  222. udp_recv(dns_pcb, dns_recv, NULL);
  223. /* initialize default DNS primary server */
  224. dns_setserver(0, &dnsserver);
  225. }
  226. }
  227. #if DNS_LOCAL_HOSTLIST
  228. dns_init_local();
  229. #endif
  230. }
  231. /**
  232. * Initialize one of the DNS servers.
  233. *
  234. * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS
  235. * @param dnsserver IP address of the DNS server to set
  236. */
  237. void ICACHE_FLASH_ATTR
  238. dns_setserver(u8_t numdns, ip_addr_t *dnsserver)
  239. {
  240. if ((numdns < DNS_MAX_SERVERS) && (dns_pcb != NULL) &&
  241. (dnsserver != NULL) && !ip_addr_isany(dnsserver)) {
  242. dns_servers[numdns] = (*dnsserver);
  243. }
  244. }
  245. /**
  246. * Obtain one of the currently configured DNS server.
  247. *
  248. * @param numdns the index of the DNS server
  249. * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS
  250. * server has not been configured.
  251. */
  252. ip_addr_t ICACHE_FLASH_ATTR
  253. dns_getserver(u8_t numdns)
  254. {
  255. if (numdns < DNS_MAX_SERVERS) {
  256. return dns_servers[numdns];
  257. } else {
  258. return *IP_ADDR_ANY;
  259. }
  260. }
  261. /**
  262. * The DNS resolver client timer - handle retries and timeouts and should
  263. * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
  264. */
  265. void ICACHE_FLASH_ATTR
  266. dns_tmr(void)
  267. {
  268. if (dns_pcb != NULL) {
  269. LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
  270. dns_check_entries();
  271. }
  272. }
  273. #if DNS_LOCAL_HOSTLIST
  274. static void ICACHE_FLASH_ATTR
  275. dns_init_local()
  276. {
  277. #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
  278. int i;
  279. struct local_hostlist_entry *entry;
  280. /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */
  281. struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT;
  282. size_t namelen;
  283. for (i = 0; i < sizeof(local_hostlist_init) / sizeof(struct local_hostlist_entry); i++) {
  284. struct local_hostlist_entry *init_entry = &local_hostlist_init[i];
  285. LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL);
  286. namelen = os_strlen(init_entry->name);
  287. LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
  288. entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
  289. LWIP_ASSERT("mem-error in dns_init_local", entry != NULL);
  290. if (entry != NULL) {
  291. entry->name = (char*)entry + sizeof(struct local_hostlist_entry);
  292. MEMCPY((char*)entry->name, init_entry->name, namelen);
  293. ((char*)entry->name)[namelen] = 0;
  294. entry->addr = init_entry->addr;
  295. entry->next = local_hostlist_dynamic;
  296. local_hostlist_dynamic = entry;
  297. }
  298. }
  299. #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
  300. }
  301. /**
  302. * Scans the local host-list for a hostname.
  303. *
  304. * @param hostname Hostname to look for in the local host-list
  305. * @return The first IP address for the hostname in the local host-list or
  306. * IPADDR_NONE if not found.
  307. */
  308. static u32_t ICACHE_FLASH_ATTR
  309. dns_lookup_local(const char *hostname)
  310. {
  311. #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
  312. struct local_hostlist_entry *entry = local_hostlist_dynamic;
  313. while(entry != NULL) {
  314. if(strcmp(entry->name, hostname) == 0) {
  315. return ip4_addr_get_u32(&entry->addr);
  316. }
  317. entry = entry->next;
  318. }
  319. #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
  320. int i;
  321. for (i = 0; i < sizeof(local_hostlist_static) / sizeof(struct local_hostlist_entry); i++) {
  322. if(strcmp(local_hostlist_static[i].name, hostname) == 0) {
  323. return ip4_addr_get_u32(&local_hostlist_static[i].addr);
  324. }
  325. }
  326. #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
  327. return IPADDR_NONE;
  328. }
  329. #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
  330. /** Remove all entries from the local host-list for a specific hostname
  331. * and/or IP addess
  332. *
  333. * @param hostname hostname for which entries shall be removed from the local
  334. * host-list
  335. * @param addr address for which entries shall be removed from the local host-list
  336. * @return the number of removed entries
  337. */
  338. int ICACHE_FLASH_ATTR
  339. dns_local_removehost(const char *hostname, const ip_addr_t *addr)
  340. {
  341. int removed = 0;
  342. struct local_hostlist_entry *entry = local_hostlist_dynamic;
  343. struct local_hostlist_entry *last_entry = NULL;
  344. while (entry != NULL) {
  345. if (((hostname == NULL) || !strcmp(entry->name, hostname)) &&
  346. ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
  347. struct local_hostlist_entry *free_entry;
  348. if (last_entry != NULL) {
  349. last_entry->next = entry->next;
  350. } else {
  351. local_hostlist_dynamic = entry->next;
  352. }
  353. free_entry = entry;
  354. entry = entry->next;
  355. memp_free(MEMP_LOCALHOSTLIST, free_entry);
  356. removed++;
  357. } else {
  358. last_entry = entry;
  359. entry = entry->next;
  360. }
  361. }
  362. return removed;
  363. }
  364. /**
  365. * Add a hostname/IP address pair to the local host-list.
  366. * Duplicates are not checked.
  367. *
  368. * @param hostname hostname of the new entry
  369. * @param addr IP address of the new entry
  370. * @return ERR_OK if succeeded or ERR_MEM on memory error
  371. */
  372. err_t ICACHE_FLASH_ATTR
  373. dns_local_addhost(const char *hostname, const ip_addr_t *addr)
  374. {
  375. struct local_hostlist_entry *entry;
  376. size_t namelen;
  377. LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
  378. namelen = os_strlen(hostname);
  379. LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
  380. entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
  381. if (entry == NULL) {
  382. return ERR_MEM;
  383. }
  384. entry->name = (char*)entry + sizeof(struct local_hostlist_entry);
  385. MEMCPY((char*)entry->name, hostname, namelen);
  386. ((char*)entry->name)[namelen] = 0;
  387. ip_addr_copy(entry->addr, *addr);
  388. entry->next = local_hostlist_dynamic;
  389. local_hostlist_dynamic = entry;
  390. return ERR_OK;
  391. }
  392. #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
  393. #endif /* DNS_LOCAL_HOSTLIST */
  394. /**
  395. * Look up a hostname in the array of known hostnames.
  396. *
  397. * @note This function only looks in the internal array of known
  398. * hostnames, it does not send out a query for the hostname if none
  399. * was found. The function dns_enqueue() can be used to send a query
  400. * for a hostname.
  401. *
  402. * @param name the hostname to look up
  403. * @return the hostname's IP address, as u32_t (instead of ip_addr_t to
  404. * better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname
  405. * was not found in the cached dns_table.
  406. */
  407. static u32_t ICACHE_FLASH_ATTR
  408. dns_lookup(const char *name)
  409. {
  410. u8_t i;
  411. #if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN)
  412. u32_t addr;
  413. #endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */
  414. #if DNS_LOCAL_HOSTLIST
  415. if ((addr = dns_lookup_local(name)) != IPADDR_NONE) {
  416. return addr;
  417. }
  418. #endif /* DNS_LOCAL_HOSTLIST */
  419. #ifdef DNS_LOOKUP_LOCAL_EXTERN
  420. if((addr = DNS_LOOKUP_LOCAL_EXTERN(name)) != IPADDR_NONE) {
  421. return addr;
  422. }
  423. #endif /* DNS_LOOKUP_LOCAL_EXTERN */
  424. /* Walk through name list, return entry if found. If not, return NULL. */
  425. for (i = 0; i < DNS_TABLE_SIZE; ++i) {
  426. if ((dns_table[i].state == DNS_STATE_DONE) &&
  427. (strcmp(name, dns_table[i].name) == 0)) {
  428. LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
  429. ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
  430. LWIP_DEBUGF(DNS_DEBUG, ("\n"));
  431. return ip4_addr_get_u32(&dns_table[i].ipaddr);
  432. }
  433. }
  434. return IPADDR_NONE;
  435. }
  436. #if DNS_DOES_NAME_CHECK
  437. /**
  438. * Compare the "dotted" name "query" with the encoded name "response"
  439. * to make sure an answer from the DNS server matches the current dns_table
  440. * entry (otherwise, answers might arrive late for hostname not on the list
  441. * any more).
  442. *
  443. * @param query hostname (not encoded) from the dns_table
  444. * @param response encoded hostname in the DNS response
  445. * @return 0: names equal; 1: names differ
  446. */
  447. static u8_t ICACHE_FLASH_ATTR
  448. dns_compare_name(unsigned char *query, unsigned char *response)
  449. {
  450. unsigned char n;
  451. do {
  452. n = *response++;
  453. /** @see RFC 1035 - 4.1.4. Message compression */
  454. if ((n & 0xc0) == 0xc0) {
  455. /* Compressed name */
  456. break;
  457. } else {
  458. /* Not compressed name */
  459. while (n > 0) {
  460. if ((*query) != (*response)) {
  461. return 1;
  462. }
  463. ++response;
  464. ++query;
  465. --n;
  466. };
  467. ++query;
  468. }
  469. } while (*response != 0);
  470. return 0;
  471. }
  472. #endif /* DNS_DOES_NAME_CHECK */
  473. /**
  474. * Walk through a compact encoded DNS name and return the end of the name.
  475. *
  476. * @param query encoded DNS name in the DNS server response
  477. * @return end of the name
  478. */
  479. static unsigned char * ICACHE_FLASH_ATTR
  480. dns_parse_name(unsigned char *query)
  481. {
  482. unsigned char n;
  483. do {
  484. n = *query++;
  485. /** @see RFC 1035 - 4.1.4. Message compression */
  486. if ((n & 0xc0) == 0xc0) {
  487. /* Compressed name */
  488. break;
  489. } else {
  490. /* Not compressed name */
  491. while (n > 0) {
  492. ++query;
  493. --n;
  494. };
  495. }
  496. } while (*query != 0);
  497. return query + 1;
  498. }
  499. /**
  500. * Send a DNS query packet.
  501. *
  502. * @param numdns index of the DNS server in the dns_servers table
  503. * @param name hostname to query
  504. * @param id index of the hostname in dns_table, used as transaction ID in the
  505. * DNS query packet
  506. * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
  507. */
  508. static err_t ICACHE_FLASH_ATTR
  509. dns_send(u8_t numdns, const char* name, u8_t id)
  510. {
  511. err_t err;
  512. struct dns_hdr *hdr;
  513. struct dns_query qry;
  514. struct pbuf *p;
  515. char *query, *nptr;
  516. const char *pHostname;
  517. u8_t n;
  518. dns_random = (u16_t)os_random();
  519. LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
  520. (u16_t)(numdns), name));
  521. LWIP_ASSERT("dns server out of array", numdns < DNS_MAX_SERVERS);
  522. LWIP_ASSERT("dns server has no IP address set", !ip_addr_isany(&dns_servers[numdns]));
  523. /* if here, we have either a new query or a retry on a previous query to process */
  524. p = pbuf_alloc(PBUF_TRANSPORT, SIZEOF_DNS_HDR + DNS_MAX_NAME_LENGTH +
  525. SIZEOF_DNS_QUERY, PBUF_RAM);
  526. if (p != NULL) {
  527. LWIP_ASSERT("pbuf must be in one piece", p->next == NULL);
  528. /* fill dns header */
  529. hdr = (struct dns_hdr*)p->payload;
  530. os_memset(hdr, 0, SIZEOF_DNS_HDR);
  531. hdr->id = htons(id + dns_random);
  532. hdr->flags1 = DNS_FLAG1_RD;
  533. hdr->numquestions = PP_HTONS(1);
  534. query = (char*)hdr + SIZEOF_DNS_HDR;
  535. pHostname = name;
  536. --pHostname;
  537. /* convert hostname into suitable query format. */
  538. do {
  539. ++pHostname;
  540. nptr = query;
  541. ++query;
  542. for(n = 0; *pHostname != '.' && *pHostname != 0; ++pHostname) {
  543. *query = *pHostname;
  544. ++query;
  545. ++n;
  546. }
  547. *nptr = n;
  548. } while(*pHostname != 0);
  549. *query++='\0';
  550. /* fill dns query */
  551. qry.type = PP_HTONS(DNS_RRTYPE_A);
  552. qry.cls = PP_HTONS(DNS_RRCLASS_IN);
  553. SMEMCPY(query, &qry, SIZEOF_DNS_QUERY);
  554. /* resize pbuf to the exact dns query */
  555. pbuf_realloc(p, (u16_t)((query + SIZEOF_DNS_QUERY) - ((char*)(p->payload))));
  556. /* connect to the server for faster receiving */
  557. udp_connect(dns_pcb, &dns_servers[numdns], DNS_SERVER_PORT);
  558. /* send dns packet */
  559. err = udp_sendto(dns_pcb, p, &dns_servers[numdns], DNS_SERVER_PORT);
  560. /* free pbuf */
  561. pbuf_free(p);
  562. } else {
  563. err = ERR_MEM;
  564. }
  565. return err;
  566. }
  567. /**
  568. * dns_check_entry() - see if pEntry has not yet been queried and, if so, sends out a query.
  569. * Check an entry in the dns_table:
  570. * - send out query for new entries
  571. * - retry old pending entries on timeout (also with different servers)
  572. * - remove completed entries from the table if their TTL has expired
  573. *
  574. * @param i index of the dns_table entry to check
  575. */
  576. static void ICACHE_FLASH_ATTR
  577. dns_check_entry(u8_t i)
  578. {
  579. err_t err;
  580. struct dns_table_entry *pEntry = &dns_table[i];
  581. LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
  582. switch(pEntry->state) {
  583. case DNS_STATE_NEW: {
  584. /* initialize new entry */
  585. pEntry->state = DNS_STATE_ASKING;
  586. pEntry->numdns = 0;
  587. pEntry->tmr = 1;
  588. pEntry->retries = 0;
  589. /* send DNS packet for this entry */
  590. err = dns_send(pEntry->numdns, pEntry->name, i);
  591. if (err != ERR_OK) {
  592. LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
  593. ("dns_send returned error: %s\n", lwip_strerr(err)));
  594. }
  595. break;
  596. }
  597. case DNS_STATE_ASKING: {
  598. if (--pEntry->tmr == 0) {
  599. if (++pEntry->retries == DNS_MAX_RETRIES) {
  600. if ((pEntry->numdns+1<DNS_MAX_SERVERS) && !ip_addr_isany(&dns_servers[pEntry->numdns+1])) {
  601. /* change of server */
  602. pEntry->numdns++;
  603. pEntry->tmr = 1;
  604. pEntry->retries = 0;
  605. break;
  606. } else {
  607. LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", pEntry->name));
  608. /* call specified callback function if provided */
  609. if (pEntry->found)
  610. (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
  611. /* flush this entry */
  612. pEntry->state = DNS_STATE_UNUSED;
  613. pEntry->found = NULL;
  614. break;
  615. }
  616. }
  617. /* wait longer for the next retry */
  618. pEntry->tmr = pEntry->retries;
  619. /* send DNS packet for this entry */
  620. err = dns_send(pEntry->numdns, pEntry->name, i);
  621. if (err != ERR_OK) {
  622. LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
  623. ("dns_send returned error: %s\n", lwip_strerr(err)));
  624. }
  625. }
  626. break;
  627. }
  628. case DNS_STATE_DONE: {
  629. /* if the time to live is nul */
  630. if (--pEntry->ttl == 0) {
  631. LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", pEntry->name));
  632. /* flush this entry */
  633. pEntry->state = DNS_STATE_UNUSED;
  634. pEntry->found = NULL;
  635. }
  636. break;
  637. }
  638. case DNS_STATE_UNUSED:
  639. /* nothing to do */
  640. break;
  641. default:
  642. LWIP_ASSERT("unknown dns_table entry state:", 0);
  643. break;
  644. }
  645. }
  646. /**
  647. * Call dns_check_entry for each entry in dns_table - check all entries.
  648. */
  649. static void ICACHE_FLASH_ATTR
  650. dns_check_entries(void)
  651. {
  652. u8_t i;
  653. for (i = 0; i < DNS_TABLE_SIZE; ++i) {
  654. dns_check_entry(i);
  655. }
  656. }
  657. /**
  658. * Receive input function for DNS response packets arriving for the dns UDP pcb.
  659. *
  660. * @params see udp.h
  661. */
  662. static void ICACHE_FLASH_ATTR
  663. dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
  664. {
  665. u16_t i;
  666. char *pHostname;
  667. struct dns_hdr *hdr;
  668. struct dns_answer ans;
  669. struct dns_table_entry *pEntry;
  670. u16_t nquestions, nanswers;
  671. u8_t* dns_payload_buffer = (u8_t* )os_zalloc(LWIP_MEM_ALIGN_BUFFER(DNS_MSG_SIZE));
  672. dns_payload = (u8_t *)LWIP_MEM_ALIGN(dns_payload_buffer);
  673. LWIP_UNUSED_ARG(arg);
  674. LWIP_UNUSED_ARG(pcb);
  675. LWIP_UNUSED_ARG(addr);
  676. LWIP_UNUSED_ARG(port);
  677. /* is the dns message too big ? */
  678. if (p->tot_len > DNS_MSG_SIZE) {
  679. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too big\n"));
  680. /* free pbuf and return */
  681. goto memerr;
  682. }
  683. /* is the dns message big enough ? */
  684. if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY + SIZEOF_DNS_ANSWER)) {
  685. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
  686. /* free pbuf and return */
  687. goto memerr;
  688. }
  689. /* copy dns payload inside static buffer for processing */
  690. if (pbuf_copy_partial(p, dns_payload, p->tot_len, 0) == p->tot_len) {
  691. /* The ID in the DNS header should be our entry into the name table. */
  692. hdr = (struct dns_hdr*)dns_payload;
  693. i = htons(hdr->id);
  694. i = i - dns_random;
  695. if (i < DNS_TABLE_SIZE) {
  696. pEntry = &dns_table[i];
  697. if(pEntry->state == DNS_STATE_ASKING) {
  698. /* This entry is now completed. */
  699. pEntry->state = DNS_STATE_DONE;
  700. pEntry->err = hdr->flags2 & DNS_FLAG2_ERR_MASK;
  701. /* We only care about the question(s) and the answers. The authrr
  702. and the extrarr are simply discarded. */
  703. nquestions = htons(hdr->numquestions);
  704. nanswers = htons(hdr->numanswers);
  705. /* Check for error. If so, call callback to inform. */
  706. if (((hdr->flags1 & DNS_FLAG1_RESPONSE) == 0) || (pEntry->err != 0) || (nquestions != 1)) {
  707. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", pEntry->name));
  708. /* call callback to indicate error, clean up memory and return */
  709. goto responseerr;
  710. }
  711. #if DNS_DOES_NAME_CHECK
  712. /* Check if the name in the "question" part match with the name in the entry. */
  713. if (dns_compare_name((unsigned char *)(pEntry->name), (unsigned char *)dns_payload + SIZEOF_DNS_HDR) != 0) {
  714. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", pEntry->name));
  715. /* call callback to indicate error, clean up memory and return */
  716. goto responseerr;
  717. }
  718. #endif /* DNS_DOES_NAME_CHECK */
  719. /* Skip the name in the "question" part */
  720. pHostname = (char *) dns_parse_name((unsigned char *)dns_payload + SIZEOF_DNS_HDR) + SIZEOF_DNS_QUERY;
  721. while (nanswers > 0) {
  722. /* skip answer resource record's host name */
  723. pHostname = (char *) dns_parse_name((unsigned char *)pHostname);
  724. /* Check for IP address type and Internet class. Others are discarded. */
  725. SMEMCPY(&ans, pHostname, SIZEOF_DNS_ANSWER);
  726. if((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) &&
  727. (ans.len == PP_HTONS(sizeof(ip_addr_t))) ) {
  728. /* read the answer resource record's TTL, and maximize it if needed */
  729. pEntry->ttl = ntohl(ans.ttl);
  730. if (pEntry->ttl > DNS_MAX_TTL) {
  731. pEntry->ttl = DNS_MAX_TTL;
  732. }
  733. /* read the IP address after answer resource record's header */
  734. SMEMCPY(&(pEntry->ipaddr), (pHostname+SIZEOF_DNS_ANSWER), sizeof(ip_addr_t));
  735. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", pEntry->name));
  736. ip_addr_debug_print(DNS_DEBUG, (&(pEntry->ipaddr)));
  737. LWIP_DEBUGF(DNS_DEBUG, ("\n"));
  738. /* call specified callback function if provided */
  739. if (pEntry->found) {
  740. (*pEntry->found)(pEntry->name, &pEntry->ipaddr, pEntry->arg);
  741. }
  742. /* deallocate memory and return */
  743. goto memerr;
  744. } else {
  745. pHostname = pHostname + SIZEOF_DNS_ANSWER + htons(ans.len);
  746. }
  747. --nanswers;
  748. }
  749. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", pEntry->name));
  750. /* call callback to indicate error, clean up memory and return */
  751. goto responseerr;
  752. }
  753. }
  754. }
  755. /* deallocate memory and return */
  756. goto memerr;
  757. responseerr:
  758. /* ERROR: call specified callback function with NULL as name to indicate an error */
  759. if (pEntry->found) {
  760. (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
  761. }
  762. /* flush this entry */
  763. pEntry->state = DNS_STATE_UNUSED;
  764. pEntry->found = NULL;
  765. memerr:
  766. /* free pbuf */
  767. pbuf_free(p);
  768. os_free(dns_payload_buffer);
  769. return;
  770. }
  771. /**
  772. * Queues a new hostname to resolve and sends out a DNS query for that hostname
  773. *
  774. * @param name the hostname that is to be queried
  775. * @param found a callback founction to be called on success, failure or timeout
  776. * @param callback_arg argument to pass to the callback function
  777. * @return @return a err_t return code.
  778. */
  779. static err_t ICACHE_FLASH_ATTR
  780. dns_enqueue(const char *name, dns_found_callback found, void *callback_arg)
  781. {
  782. u8_t i;
  783. u8_t lseq, lseqi;
  784. struct dns_table_entry *pEntry = NULL;
  785. size_t namelen;
  786. /* search an unused entry, or the oldest one */
  787. lseq = lseqi = 0;
  788. for (i = 0; i < DNS_TABLE_SIZE; ++i) {
  789. pEntry = &dns_table[i];
  790. /* is it an unused entry ? */
  791. if (pEntry->state == DNS_STATE_UNUSED)
  792. break;
  793. /* check if this is the oldest completed entry */
  794. if (pEntry->state == DNS_STATE_DONE) {
  795. if ((dns_seqno - pEntry->seqno) > lseq) {
  796. lseq = dns_seqno - pEntry->seqno;
  797. lseqi = i;
  798. }
  799. }
  800. }
  801. /* if we don't have found an unused entry, use the oldest completed one */
  802. if (i == DNS_TABLE_SIZE) {
  803. if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
  804. /* no entry can't be used now, table is full */
  805. LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
  806. return ERR_MEM;
  807. } else {
  808. /* use the oldest completed one */
  809. i = lseqi;
  810. pEntry = &dns_table[i];
  811. }
  812. }
  813. /* use this entry */
  814. LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
  815. /* fill the entry */
  816. pEntry->state = DNS_STATE_NEW;
  817. pEntry->seqno = dns_seqno++;
  818. pEntry->found = found;
  819. pEntry->arg = callback_arg;
  820. namelen = LWIP_MIN(os_strlen(name), DNS_MAX_NAME_LENGTH-1);
  821. MEMCPY(pEntry->name, name, namelen);
  822. pEntry->name[namelen] = 0;
  823. /* force to send query without waiting timer */
  824. dns_check_entry(i);
  825. /* dns query is enqueued */
  826. return ERR_INPROGRESS;
  827. }
  828. /**
  829. * Resolve a hostname (string) into an IP address.
  830. * NON-BLOCKING callback version for use with raw API!!!
  831. *
  832. * Returns immediately with one of err_t return codes:
  833. * - ERR_OK if hostname is a valid IP address string or the host
  834. * name is already in the local names table.
  835. * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
  836. * for resolution if no errors are present.
  837. * - ERR_ARG: dns client not initialized or invalid hostname
  838. *
  839. * @param hostname the hostname that is to be queried
  840. * @param addr pointer to a ip_addr_t where to store the address if it is already
  841. * cached in the dns_table (only valid if ERR_OK is returned!)
  842. * @param found a callback function to be called on success, failure or timeout (only if
  843. * ERR_INPROGRESS is returned!)
  844. * @param callback_arg argument to pass to the callback function
  845. * @return a err_t return code.
  846. */
  847. err_t ICACHE_FLASH_ATTR
  848. dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found,
  849. void *callback_arg)
  850. {
  851. u32_t ipaddr;
  852. /* not initialized or no valid server yet, or invalid addr pointer
  853. * or invalid hostname or invalid hostname length */
  854. if ((dns_pcb == NULL) || (addr == NULL) ||
  855. (!hostname) || (!hostname[0]) ||
  856. (os_strlen(hostname) >= DNS_MAX_NAME_LENGTH)) {
  857. return ERR_ARG;
  858. }
  859. #if LWIP_HAVE_LOOPIF
  860. if (strcmp(hostname, "localhost")==0) {
  861. ip_addr_set_loopback(addr);
  862. return ERR_OK;
  863. }
  864. #endif /* LWIP_HAVE_LOOPIF */
  865. /* host name already in octet notation? set ip addr and return ERR_OK */
  866. ipaddr = ipaddr_addr(hostname);
  867. if (ipaddr == IPADDR_NONE) {
  868. /* already have this address cached? */
  869. // ipaddr = dns_lookup(hostname);
  870. }
  871. if (ipaddr != IPADDR_NONE) {
  872. ip4_addr_set_u32(addr, ipaddr);
  873. return ERR_OK;
  874. }
  875. /* queue query with specified callback */
  876. return dns_enqueue(hostname, found, callback_arg);
  877. }
  878. #endif /* LWIP_DNS */