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