dns.c 31 KB

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