]> granicus.if.org Git - esp-idf/blob - components/lwip/core/dns.c
tcpip_adapter/lwip: make dhcp domain name server option configurable
[esp-idf] / components / lwip / core / dns.c
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  * security fixes and more by Simon Goldschmidt
15
16  * uIP version Copyright (c) 2002-2003, Adam Dunkels.
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  * 3. The name of the author may not be used to endorse or promote
28  *    products derived from this software without specific prior
29  *    written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
32  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
33  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
35  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
37  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
39  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
40  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
41  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  *
44  * DNS.C
45  *
46  * The lwIP DNS resolver functions are used to lookup a host name and
47  * map it to a numerical IP address. It maintains a list of resolved
48  * hostnames that can be queried with the dns_lookup() function.
49  * New hostnames can be resolved using the dns_query() function.
50  *
51  * The lwIP version of the resolver also adds a non-blocking version of
52  * gethostbyname() that will work with a raw API application. This function
53  * checks for an IP address string first and converts it if it is valid.
54  * gethostbyname() then does a dns_lookup() to see if the name is
55  * already in the table. If so, the IP is returned. If not, a query is
56  * issued and the function returns with a ERR_INPROGRESS status. The app
57  * using the dns client must then go into a waiting state.
58  *
59  * Once a hostname has been resolved (or found to be non-existent),
60  * the resolver code calls a specified callback function (which
61  * must be implemented by the module that uses the resolver).
62  */
63
64 /*-----------------------------------------------------------------------------
65  * RFC 1035 - Domain names - implementation and specification
66  * RFC 2181 - Clarifications to the DNS Specification
67  *----------------------------------------------------------------------------*/
68
69 /** @todo: define good default values (rfc compliance) */
70 /** @todo: improve answer parsing, more checkings... */
71 /** @todo: check RFC1035 - 7.3. Processing responses */
72
73 /*-----------------------------------------------------------------------------
74  * Includes
75  *----------------------------------------------------------------------------*/
76
77 #include "lwip/opt.h"
78
79 #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
80
81 #include "lwip/udp.h"
82 #include "lwip/mem.h"
83 #include "lwip/memp.h"
84 #include "lwip/dns.h"
85
86 #include <string.h>
87
88 /** Random generator function to create random TXIDs and source ports for queries */
89 #ifndef DNS_RAND_TXID
90 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_XID) != 0)
91 #define DNS_RAND_TXID LWIP_RAND
92 #else
93 static u16_t dns_txid;
94 #define DNS_RAND_TXID() (++dns_txid)
95 #endif
96 #endif
97
98 /** Limits the source port to be >= 1024 by default */
99 #ifndef DNS_PORT_ALLOWED
100 #define DNS_PORT_ALLOWED(port) ((port) >= 1024)
101 #endif
102
103 /** DNS server port address */
104 #ifndef DNS_SERVER_PORT
105 #define DNS_SERVER_PORT           53
106 #endif
107
108 /** DNS maximum number of retries when asking for a name, before "timeout". */
109 #ifndef DNS_MAX_RETRIES
110 #define DNS_MAX_RETRIES           4
111 #endif
112
113 /** DNS resource record max. TTL (one week as default) */
114 #ifndef DNS_MAX_TTL
115 #define DNS_MAX_TTL               604800
116 #endif
117
118 /* The number of parallel requests (i.e. calls to dns_gethostbyname
119  * that cannot be answered from the DNS table.
120  * This is set to the table size by default.
121  */
122 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
123 #ifndef DNS_MAX_REQUESTS
124 #define DNS_MAX_REQUESTS          DNS_TABLE_SIZE
125 #endif
126 #else
127 /* In this configuration, both arrays have to have the same size and are used
128  * like one entry (used/free) */
129 #define DNS_MAX_REQUESTS          DNS_TABLE_SIZE
130 #endif
131
132 /* The number of UDP source ports used in parallel */
133 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
134 #ifndef DNS_MAX_SOURCE_PORTS
135 #define DNS_MAX_SOURCE_PORTS      DNS_MAX_REQUESTS
136 #endif
137 #else
138 #ifdef DNS_MAX_SOURCE_PORTS
139 #undef DNS_MAX_SOURCE_PORTS
140 #endif
141 #define DNS_MAX_SOURCE_PORTS      1
142 #endif
143
144 #if LWIP_IPV4 && LWIP_IPV6
145 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) (((t) == LWIP_DNS_ADDRTYPE_IPV6_IPV4) || ((t) == LWIP_DNS_ADDRTYPE_IPV6))
146 #define LWIP_DNS_ADDRTYPE_MATCH_IP(t, ip) (IP_IS_V6_VAL(ip) ? LWIP_DNS_ADDRTYPE_IS_IPV6(t) : (!LWIP_DNS_ADDRTYPE_IS_IPV6(t)))
147 #define LWIP_DNS_ADDRTYPE_ARG(x) , x
148 #define LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(x) x
149 #define LWIP_DNS_SET_ADDRTYPE(x, y) do { x = y; } while(0)
150 #else
151 #if LWIP_IPV6
152 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) 1
153 #else
154 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) 0
155 #endif
156 #define LWIP_DNS_ADDRTYPE_MATCH_IP(t, ip) 1
157 #define LWIP_DNS_ADDRTYPE_ARG(x)
158 #define LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(x) 0
159 #define LWIP_DNS_SET_ADDRTYPE(x, y)
160 #endif /* LWIP_IPV4 && LWIP_IPV6 */
161
162 /** DNS field TYPE used for "Resource Records" */
163 #define DNS_RRTYPE_A              1     /* a host address */
164 #define DNS_RRTYPE_NS             2     /* an authoritative name server */
165 #define DNS_RRTYPE_MD             3     /* a mail destination (Obsolete - use MX) */
166 #define DNS_RRTYPE_MF             4     /* a mail forwarder (Obsolete - use MX) */
167 #define DNS_RRTYPE_CNAME          5     /* the canonical name for an alias */
168 #define DNS_RRTYPE_SOA            6     /* marks the start of a zone of authority */
169 #define DNS_RRTYPE_MB             7     /* a mailbox domain name (EXPERIMENTAL) */
170 #define DNS_RRTYPE_MG             8     /* a mail group member (EXPERIMENTAL) */
171 #define DNS_RRTYPE_MR             9     /* a mail rename domain name (EXPERIMENTAL) */
172 #define DNS_RRTYPE_NULL           10    /* a null RR (EXPERIMENTAL) */
173 #define DNS_RRTYPE_WKS            11    /* a well known service description */
174 #define DNS_RRTYPE_PTR            12    /* a domain name pointer */
175 #define DNS_RRTYPE_HINFO          13    /* host information */
176 #define DNS_RRTYPE_MINFO          14    /* mailbox or mail list information */
177 #define DNS_RRTYPE_MX             15    /* mail exchange */
178 #define DNS_RRTYPE_TXT            16    /* text strings */
179 #define DNS_RRTYPE_AAAA           28    /* IPv6 address */
180
181 /** DNS field CLASS used for "Resource Records" */
182 #define DNS_RRCLASS_IN            1     /* the Internet */
183 #define DNS_RRCLASS_CS            2     /* the CSNET class (Obsolete - used only for examples in some obsolete RFCs) */
184 #define DNS_RRCLASS_CH            3     /* the CHAOS class */
185 #define DNS_RRCLASS_HS            4     /* Hesiod [Dyer 87] */
186 #define DNS_RRCLASS_FLUSH         0x800 /* Flush bit */
187
188 /* DNS protocol flags */
189 #define DNS_FLAG1_RESPONSE        0x80
190 #define DNS_FLAG1_OPCODE_STATUS   0x10
191 #define DNS_FLAG1_OPCODE_INVERSE  0x08
192 #define DNS_FLAG1_OPCODE_STANDARD 0x00
193 #define DNS_FLAG1_AUTHORATIVE     0x04
194 #define DNS_FLAG1_TRUNC           0x02
195 #define DNS_FLAG1_RD              0x01
196 #define DNS_FLAG2_RA              0x80
197 #define DNS_FLAG2_ERR_MASK        0x0f
198 #define DNS_FLAG2_ERR_NONE        0x00
199 #define DNS_FLAG2_ERR_NAME        0x03
200
201 /* DNS protocol states */
202 #define DNS_STATE_UNUSED            0
203 #define DNS_STATE_NEW               1
204 #define DNS_STATE_ASKING            2
205 #define DNS_STATE_DONE              3
206
207 #ifdef PACK_STRUCT_USE_INCLUDES
208 #  include "arch/bpstruct.h"
209 #endif
210 PACK_STRUCT_BEGIN
211 /** DNS message header */
212 struct dns_hdr {
213   PACK_STRUCT_FIELD(u16_t id);
214   PACK_STRUCT_FLD_8(u8_t flags1);
215   PACK_STRUCT_FLD_8(u8_t flags2);
216   PACK_STRUCT_FIELD(u16_t numquestions);
217   PACK_STRUCT_FIELD(u16_t numanswers);
218   PACK_STRUCT_FIELD(u16_t numauthrr);
219   PACK_STRUCT_FIELD(u16_t numextrarr);
220 } PACK_STRUCT_STRUCT;
221 PACK_STRUCT_END
222 #ifdef PACK_STRUCT_USE_INCLUDES
223 #  include "arch/epstruct.h"
224 #endif
225 #define SIZEOF_DNS_HDR 12
226
227 /** DNS query message structure.
228     No packing needed: only used locally on the stack. */
229 struct dns_query {
230   /* DNS query record starts with either a domain name or a pointer
231      to a name already present somewhere in the packet. */
232   u16_t type;
233   u16_t cls;
234 };
235 #define SIZEOF_DNS_QUERY 4
236
237 /** DNS answer message structure.
238     No packing needed: only used locally on the stack. */
239 struct dns_answer {
240   /* DNS answer record starts with either a domain name or a pointer
241      to a name already present somewhere in the packet. */
242   u16_t type;
243   u16_t cls;
244   u32_t ttl;
245   u16_t len;
246 };
247 #define SIZEOF_DNS_ANSWER 10
248 /* maximum allowed size for the struct due to non-packed */
249 #define SIZEOF_DNS_ANSWER_ASSERT 12
250
251 /** DNS table entry */
252 struct dns_table_entry {
253   u32_t ttl;
254   ip_addr_t ipaddr;
255   u16_t txid;
256   u8_t  state;
257   u8_t  server_idx;
258   u8_t  tmr;
259   u8_t  retries;
260   u8_t  seqno;
261 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
262   u8_t pcb_idx;
263 #endif
264   char name[DNS_MAX_NAME_LENGTH];
265 #if LWIP_IPV4 && LWIP_IPV6
266   u8_t reqaddrtype;
267 #endif /* LWIP_IPV4 && LWIP_IPV6 */
268 };
269
270 /** DNS request table entry: used when dns_gehostbyname cannot answer the
271  * request from the DNS table */
272 struct dns_req_entry {
273   /* pointer to callback on DNS query done */
274   dns_found_callback found;
275   /* argument passed to the callback function */
276   void *arg;
277 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
278   u8_t dns_table_idx;
279 #endif
280 #if LWIP_IPV4 && LWIP_IPV6
281   u8_t reqaddrtype;
282 #endif /* LWIP_IPV4 && LWIP_IPV6 */
283 };
284
285 #if DNS_LOCAL_HOSTLIST
286
287 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
288 /** Local host-list. For hostnames in this list, no
289  *  external name resolution is performed */
290 static struct local_hostlist_entry *local_hostlist_dynamic;
291 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
292
293 /** Defining this allows the local_hostlist_static to be placed in a different
294  * linker section (e.g. FLASH) */
295 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE
296 #define DNS_LOCAL_HOSTLIST_STORAGE_PRE static
297 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */
298 /** Defining this allows the local_hostlist_static to be placed in a different
299  * linker section (e.g. FLASH) */
300 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST
301 #define DNS_LOCAL_HOSTLIST_STORAGE_POST
302 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */
303 DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[]
304   DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT;
305
306 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
307
308 static void dns_init_local(void);
309 #endif /* DNS_LOCAL_HOSTLIST */
310
311
312 /* forward declarations */
313 static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port);
314 static void dns_check_entries(void);
315 static void dns_call_found(u8_t idx, ip_addr_t* addr);
316
317 /*-----------------------------------------------------------------------------
318  * Globals
319  *----------------------------------------------------------------------------*/
320
321 /* DNS variables */
322 static struct udp_pcb        *dns_pcbs[DNS_MAX_SOURCE_PORTS];
323 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
324 static u8_t                   dns_last_pcb_idx;
325 #endif
326 static u8_t                   dns_seqno;
327 static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
328 static struct dns_req_entry   dns_requests[DNS_MAX_REQUESTS];
329 static ip_addr_t              dns_servers[DNS_MAX_SERVERS];
330
331 #ifndef LWIP_DNS_STRICMP
332 #define LWIP_DNS_STRICMP(str1, str2) dns_stricmp(str1, str2)
333 /**
334  * A small but sufficient implementation for case insensitive strcmp.
335  * This can be defined to e.g. stricmp for windows or strcasecmp for linux. */
336 static int
337 dns_stricmp(const char* str1, const char* str2)
338 {
339   char c1, c2;
340
341   do {
342     c1 = *str1++;
343     c2 = *str2++;
344     if (c1 != c2) {
345       char c1_upc = c1 | 0x20;
346       if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
347         /* characters are not equal an one is in the alphabet range:
348         downcase both chars and check again */
349         char c2_upc = c2 | 0x20;
350         if (c1_upc != c2_upc) {
351           /* still not equal */
352           /* don't care for < or > */
353           return 1;
354         }
355       } else {
356         /* characters are not equal but none is in the alphabet range */
357         return 1;
358       }
359     }
360   } while (c1 != 0);
361   return 0;
362 }
363 #endif /* LWIP_DNS_STRICMP */
364
365 /**
366  * Initialize the resolver: set up the UDP pcb and configure the fallback dns server
367  * (if FALLBACK_DNS_SERVER_ADDRESS is set).
368  */
369 void
370 dns_init(void)
371 {
372 #ifdef FALLBACK_DNS_SERVER_ADDRESS
373   /* initialize default DNS server address */
374   ip_addr_t dnsserver;
375   FALLBACK_DNS_SERVER_ADDRESS(&dnsserver);
376   dnsserver.type = IPADDR_TYPE_V4;
377   dns_setserver(DNS_FALLBACK_SERVER_INDEX, &dnsserver);
378 #endif /* FALLBACK_DNS_SERVER_ADDRESS */
379
380   LWIP_ASSERT("sanity check SIZEOF_DNS_QUERY",
381     sizeof(struct dns_query) == SIZEOF_DNS_QUERY);
382   LWIP_ASSERT("sanity check SIZEOF_DNS_ANSWER",
383     sizeof(struct dns_answer) <= SIZEOF_DNS_ANSWER_ASSERT);
384
385   LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
386
387   /* if dns client not yet initialized... */
388 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
389   if (dns_pcbs[0] == NULL) {
390     dns_pcbs[0] = udp_new_ip_type(IPADDR_TYPE_ANY);
391     LWIP_ASSERT("dns_pcbs[0] != NULL", dns_pcbs[0] != NULL);
392
393     /* initialize DNS table not needed (initialized to zero since it is a
394      * global variable) */
395     LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0",
396       DNS_STATE_UNUSED == 0);
397
398     /* initialize DNS client */
399     udp_bind(dns_pcbs[0], IP_ANY_TYPE, 0);
400     udp_recv(dns_pcbs[0], dns_recv, NULL);
401   }
402 #endif
403
404 #if DNS_LOCAL_HOSTLIST
405   dns_init_local();
406 #endif
407 }
408
409 /**
410  * Initialize one of the DNS servers.
411  *
412  * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS
413  * @param dnsserver IP address of the DNS server to set
414  */
415 void
416 dns_setserver(u8_t numdns, const ip_addr_t *dnsserver)
417 {
418   if (numdns < DNS_MAX_SERVERS) {
419     if (dnsserver != NULL) {
420       dns_servers[numdns] = (*dnsserver);
421     } else {
422       dns_servers[numdns] = *IP_ADDR_ANY;
423     }
424   }
425 }
426
427 void 
428 dns_clear_servers(bool keep_fallback)
429 {
430   u8_t numdns = 0; 
431   
432   for (numdns = 0; numdns < DNS_MAX_SERVERS; numdns ++) {
433     if (keep_fallback && numdns == DNS_FALLBACK_SERVER_INDEX) {
434       continue;
435     }
436
437     dns_setserver(numdns, NULL);
438   }
439 }
440
441
442 /**
443  * Obtain one of the currently configured DNS server.
444  *
445  * @param numdns the index of the DNS server
446  * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS
447  *         server has not been configured.
448  */
449 ip_addr_t
450 dns_getserver(u8_t numdns)
451 {
452   if (numdns < DNS_MAX_SERVERS) {
453     return dns_servers[numdns];
454   } else {
455     return *IP_ADDR_ANY;
456   }
457 }
458
459 /**
460  * The DNS resolver client timer - handle retries and timeouts and should
461  * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
462  */
463 void
464 dns_tmr(void)
465 {
466   LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
467   dns_check_entries();
468 }
469
470 #if DNS_LOCAL_HOSTLIST
471 static void
472 dns_init_local(void)
473 {
474 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
475   size_t i;
476   struct local_hostlist_entry *entry;
477   /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */
478   struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT;
479   size_t namelen;
480   for (i = 0; i < sizeof(local_hostlist_init) / sizeof(struct local_hostlist_entry); i++) {
481     struct local_hostlist_entry *init_entry = &local_hostlist_init[i];
482     LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL);
483     namelen = strlen(init_entry->name);
484     LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
485     entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
486     LWIP_ASSERT("mem-error in dns_init_local", entry != NULL);
487     if (entry != NULL) {
488       char* entry_name = (char*)entry + sizeof(struct local_hostlist_entry);
489       MEMCPY(entry_name, init_entry->name, namelen);
490       entry_name[namelen] = 0;
491       entry->name = entry_name;
492       entry->addr = init_entry->addr;
493       entry->next = local_hostlist_dynamic;
494       local_hostlist_dynamic = entry;
495     }
496   }
497 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
498 }
499
500 /**
501  * Scans the local host-list for a hostname.
502  *
503  * @param hostname Hostname to look for in the local host-list
504  * @param addr the first IP address for the hostname in the local host-list or
505  *         IPADDR_NONE if not found.
506  * @return ERR_OK if found, ERR_ARG if not found
507  */
508 static err_t
509 dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
510 {
511 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
512   struct local_hostlist_entry *entry = local_hostlist_dynamic;
513   while (entry != NULL) {
514     if ((LWIP_DNS_STRICMP(entry->name, hostname) == 0) &&
515         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, entry->addr)) {
516       if (addr) {
517         ip_addr_copy(*addr, entry->addr);
518       }
519       return ERR_OK;
520     }
521     entry = entry->next;
522   }
523 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
524   size_t i;
525   for (i = 0; i < sizeof(local_hostlist_static) / sizeof(struct local_hostlist_entry); i++) {
526     if ((LWIP_DNS_STRICMP(local_hostlist_static[i].name, hostname) == 0) &&
527         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, local_hostlist_static[i].addr)) {
528       if (addr) {
529         ip_addr_copy(*addr, local_hostlist_static[i].addr);
530       }
531       return ERR_OK;
532     }
533   }
534 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
535   return ERR_ARG;
536 }
537
538 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
539 /** Remove all entries from the local host-list for a specific hostname
540  * and/or IP address
541  *
542  * @param hostname hostname for which entries shall be removed from the local
543  *                 host-list
544  * @param addr address for which entries shall be removed from the local host-list
545  * @return the number of removed entries
546  */
547 int
548 dns_local_removehost(const char *hostname, const ip_addr_t *addr)
549 {
550   int removed = 0;
551   struct local_hostlist_entry *entry = local_hostlist_dynamic;
552   struct local_hostlist_entry *last_entry = NULL;
553   while (entry != NULL) {
554     if (((hostname == NULL) || !LWIP_DNS_STRICMP(entry->name, hostname)) &&
555         ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
556       struct local_hostlist_entry *free_entry;
557       if (last_entry != NULL) {
558         last_entry->next = entry->next;
559       } else {
560         local_hostlist_dynamic = entry->next;
561       }
562       free_entry = entry;
563       entry = entry->next;
564       memp_free(MEMP_LOCALHOSTLIST, free_entry);
565       removed++;
566     } else {
567       last_entry = entry;
568       entry = entry->next;
569     }
570   }
571   return removed;
572 }
573
574 /**
575  * Add a hostname/IP address pair to the local host-list.
576  * Duplicates are not checked.
577  *
578  * @param hostname hostname of the new entry
579  * @param addr IP address of the new entry
580  * @return ERR_OK if succeeded or ERR_MEM on memory error
581  */
582 err_t
583 dns_local_addhost(const char *hostname, const ip_addr_t *addr)
584 {
585   struct local_hostlist_entry *entry;
586   size_t namelen;
587   char* entry_name;
588   LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
589   namelen = strlen(hostname);
590   LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
591   entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
592   if (entry == NULL) {
593     return ERR_MEM;
594   }
595   entry_name = (char*)entry + sizeof(struct local_hostlist_entry);
596   MEMCPY(entry_name, hostname, namelen);
597   entry_name[namelen] = 0;
598   entry->name = entry_name;
599   ip_addr_copy(entry->addr, *addr);
600   entry->next = local_hostlist_dynamic;
601   local_hostlist_dynamic = entry;
602   return ERR_OK;
603 }
604 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
605 #endif /* DNS_LOCAL_HOSTLIST */
606
607 /**
608  * Look up a hostname in the array of known hostnames.
609  *
610  * @note This function only looks in the internal array of known
611  * hostnames, it does not send out a query for the hostname if none
612  * was found. The function dns_enqueue() can be used to send a query
613  * for a hostname.
614  *
615  * @param name the hostname to look up
616  * @param addr the hostname's IP address, as u32_t (instead of ip_addr_t to
617  *         better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname
618  *         was not found in the cached dns_table.
619  * @return ERR_OK if found, ERR_ARG if not found
620  */
621 static err_t
622 dns_lookup(const char *name, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
623 {
624   u8_t i;
625 #if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN)
626 #endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */
627 #if DNS_LOCAL_HOSTLIST
628   if (dns_lookup_local(name, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
629     return ERR_OK;
630   }
631 #endif /* DNS_LOCAL_HOSTLIST */
632 #ifdef DNS_LOOKUP_LOCAL_EXTERN
633   if (DNS_LOOKUP_LOCAL_EXTERN(name, addr, LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(dns_addrtype))) {
634     return ERR_OK;
635   }
636 #endif /* DNS_LOOKUP_LOCAL_EXTERN */
637
638   /* Walk through name list, return entry if found. If not, return NULL. */
639   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
640     if ((dns_table[i].state == DNS_STATE_DONE) &&
641         (LWIP_DNS_STRICMP(name, dns_table[i].name) == 0) &&
642         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, dns_table[i].ipaddr)) {
643       LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
644       ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
645       LWIP_DEBUGF(DNS_DEBUG, ("\n"));
646       if (addr) {
647         ip_addr_copy(*addr, dns_table[i].ipaddr);
648       }
649       return ERR_OK;
650     }
651   }
652
653   return ERR_ARG;
654 }
655
656 /**
657  * Compare the "dotted" name "query" with the encoded name "response"
658  * to make sure an answer from the DNS server matches the current dns_table
659  * entry (otherwise, answers might arrive late for hostname not on the list
660  * any more).
661  *
662  * @param query hostname (not encoded) from the dns_table
663  * @param p pbuf containing the encoded hostname in the DNS response
664  * @param start_offset offset into p where the name starts
665  * @return 0xFFFF: names differ, other: names equal -> offset behind name
666  */
667 static u16_t
668 dns_compare_name(char *query, struct pbuf* p, u16_t start_offset)
669 {
670   unsigned char n;
671   u16_t response_offset = start_offset;
672
673   do {
674     n = pbuf_get_at(p, response_offset++);
675     /** @see RFC 1035 - 4.1.4. Message compression */
676     if ((n & 0xc0) == 0xc0) {
677       /* Compressed name: cannot be equal since we don't send them */
678       return 0xFFFF;
679     } else {
680       /* Not compressed name */
681       while (n > 0) {
682         if ((*query) != pbuf_get_at(p, response_offset)) {
683           return 0xFFFF;
684         }
685         ++response_offset;
686         ++query;
687         --n;
688       }
689       ++query;
690     }
691   } while (pbuf_get_at(p, response_offset) != 0);
692
693   return response_offset + 1;
694 }
695
696 /**
697  * Walk through a compact encoded DNS name and return the end of the name.
698  *
699  * @param p pbuf containing the name
700  * @param query_idx start index into p pointing to encoded DNS name in the DNS server response
701  * @return index to end of the name
702  */
703 static u16_t
704 dns_parse_name(struct pbuf* p, u16_t query_idx)
705 {
706   unsigned char n;
707
708   do {
709     n = pbuf_get_at(p, query_idx++);
710     /** @see RFC 1035 - 4.1.4. Message compression */
711     if ((n & 0xc0) == 0xc0) {
712       /* Compressed name */
713       break;
714     } else {
715       /* Not compressed name */
716       while (n > 0) {
717         ++query_idx;
718         --n;
719       }
720     }
721   } while (pbuf_get_at(p, query_idx) != 0);
722
723   return query_idx + 1;
724 }
725
726 /**
727  * Send a DNS query packet.
728  *
729  * @param idx the DNS table entry index for which to send a request
730  * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
731  */
732 static err_t
733 dns_send(u8_t idx)
734 {
735   err_t err;
736   struct dns_hdr hdr;
737   struct dns_query qry;
738   struct pbuf *p;
739   u16_t query_idx, copy_len;
740   const char *hostname, *hostname_part;
741   u8_t n;
742   u8_t pcb_idx;
743   struct dns_table_entry* entry = &dns_table[idx];
744
745   LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
746               (u16_t)(entry->server_idx), entry->name));
747   LWIP_ASSERT("dns server out of array", entry->server_idx < DNS_MAX_SERVERS);
748   if (ip_addr_isany_val(dns_servers[entry->server_idx])) {
749     return ERR_OK;
750   }
751
752   /* if here, we have either a new query or a retry on a previous query to process */
753   p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(SIZEOF_DNS_HDR + strlen(entry->name) + 2 +
754                  SIZEOF_DNS_QUERY), PBUF_RAM);
755   if (p != NULL) {
756     /* fill dns header */
757     memset(&hdr, 0, SIZEOF_DNS_HDR);
758     hdr.id = htons(entry->txid);
759     hdr.flags1 = DNS_FLAG1_RD;
760     hdr.numquestions = PP_HTONS(1);
761     pbuf_take(p, &hdr, SIZEOF_DNS_HDR);
762     hostname = entry->name;
763     --hostname;
764
765     /* convert hostname into suitable query format. */
766     query_idx = SIZEOF_DNS_HDR;
767     do {
768       ++hostname;
769       hostname_part = hostname;
770       for (n = 0; *hostname != '.' && *hostname != 0; ++hostname) {
771         ++n;
772       }
773       copy_len = (u16_t)(hostname - hostname_part);
774       pbuf_put_at(p, query_idx, n);
775       pbuf_take_at(p, hostname_part, copy_len, query_idx + 1);
776       query_idx += n + 1;
777     } while (*hostname != 0);
778     pbuf_put_at(p, query_idx, 0);
779     query_idx++;
780
781     /* fill dns query */
782     if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype)) {
783       qry.type = PP_HTONS(DNS_RRTYPE_AAAA);
784     } else {
785       qry.type = PP_HTONS(DNS_RRTYPE_A);
786     }
787     qry.cls = PP_HTONS(DNS_RRCLASS_IN);
788     pbuf_take_at(p, &qry, SIZEOF_DNS_QUERY, query_idx);
789
790 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
791     pcb_idx = entry->pcb_idx;
792 #else
793     pcb_idx = 0;
794 #endif
795     /* send dns packet */
796     LWIP_DEBUGF(DNS_DEBUG, ("sending DNS request ID %d for name \"%s\" to server %d\r\n",
797       entry->txid, entry->name, entry->server_idx));
798     err = udp_sendto(dns_pcbs[pcb_idx], p, &dns_servers[entry->server_idx], DNS_SERVER_PORT);
799
800     /* free pbuf */
801     pbuf_free(p);
802   } else {
803     err = ERR_MEM;
804   }
805
806   return err;
807 }
808
809 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
810 static struct udp_pcb*
811 dns_alloc_random_port(void)
812 {
813   err_t err;
814   struct udp_pcb* ret;
815
816   ret = udp_new_ip_type(IPADDR_TYPE_ANY);
817   if (ret == NULL) {
818     /* out of memory, have to reuse an existing pcb */
819     return NULL;
820   }
821   do {
822     u16_t port = (u16_t)DNS_RAND_TXID();
823     if (!DNS_PORT_ALLOWED(port)) {
824       /* this port is not allowed, try again */
825       err = ERR_USE;
826       continue;
827     }
828     err = udp_bind(ret, IP_ANY_TYPE, port);
829   } while (err == ERR_USE);
830   if (err != ERR_OK) {
831     udp_remove(ret);
832     return NULL;
833   }
834   udp_recv(ret, dns_recv, NULL);
835   return ret;
836 }
837
838 /**
839  * dns_alloc_pcb() - allocates a new pcb (or reuses an existing one) to be used
840  * for sending a request
841  *
842  * @return an index into dns_pcbs
843  */
844 static u8_t
845 dns_alloc_pcb(void)
846 {
847   u8_t i;
848   u8_t idx;
849
850   for (i = 0; i < DNS_MAX_SOURCE_PORTS; i++) {
851     if (dns_pcbs[i] == NULL) {
852       break;
853     }
854   }
855   if (i < DNS_MAX_SOURCE_PORTS) {
856     dns_pcbs[i] = dns_alloc_random_port();
857     if (dns_pcbs[i] != NULL) {
858       /* succeeded */
859       dns_last_pcb_idx = i;
860       return i;
861     }
862   }
863   /* if we come here, creating a new UDP pcb failed, so we have to use
864      an already existing one */
865   for (i = 0, idx = dns_last_pcb_idx + 1; i < DNS_MAX_SOURCE_PORTS; i++, idx++) {
866     if (idx >= DNS_MAX_SOURCE_PORTS) {
867       idx = 0;
868     }
869     if (dns_pcbs[idx] != NULL) {
870       dns_last_pcb_idx = idx;
871       return idx;
872     }
873   }
874   return DNS_MAX_SOURCE_PORTS;
875 }
876 #endif /* ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0) */
877
878 /**
879  * dns_call_found() - call the found callback and check if there are duplicate
880  * entries for the given hostname. If there are any, their found callback will
881  * be called and they will be removed.
882  *
883  * @param idx dns table index of the entry that is resolved or removed
884  * @param addr IP address for the hostname (or NULL on error or memory shortage)
885  */
886 static void
887 dns_call_found(u8_t idx, ip_addr_t* addr)
888 {
889 #if ((LWIP_DNS_SECURE & (LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT)) != 0)
890   u8_t i;
891 #endif
892
893 #if LWIP_IPV4 && LWIP_IPV6
894   if (addr != NULL) {
895     /* check that address type matches the request and adapt the table entry */
896     if (IP_IS_V6_VAL(*addr)) {
897       LWIP_ASSERT("invalid response", LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
898       dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
899     } else {
900       LWIP_ASSERT("invalid response", !LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
901       dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
902     }
903   }
904 #endif /* LWIP_IPV4 && LWIP_IPV6 */
905
906 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
907   for (i = 0; i < DNS_MAX_REQUESTS; i++) {
908     if (dns_requests[i].found && (dns_requests[i].dns_table_idx == idx)) {
909       (*dns_requests[i].found)(dns_table[idx].name, addr, dns_requests[i].arg);
910       /* flush this entry */
911       dns_requests[i].found = NULL;
912     }
913   }
914 #else
915   if (dns_requests[idx].found) {
916     (*dns_requests[idx].found)(dns_table[idx].name, addr, dns_requests[idx].arg);
917   }
918   dns_requests[idx].found = NULL;
919 #endif
920 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
921   /* close the pcb used unless other request are using it */
922   for (i = 0; i < DNS_MAX_REQUESTS; i++) {
923     if (i == idx) {
924       continue; /* only check other requests */
925     }
926     if (dns_table[i].state == DNS_STATE_ASKING) {
927       if (dns_table[i].pcb_idx == dns_table[idx].pcb_idx) {
928         /* another request is still using the same pcb */
929         dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
930         break;
931       }
932     }
933   }
934   if (dns_table[idx].pcb_idx < DNS_MAX_SOURCE_PORTS) {
935     /* if we come here, the pcb is not used any more and can be removed */
936     udp_remove(dns_pcbs[dns_table[idx].pcb_idx]);
937     dns_pcbs[dns_table[idx].pcb_idx] = NULL;
938     dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
939   }
940 #endif
941 }
942
943 /* Create a query transmission ID that is unique for all outstanding queries */
944 static u16_t
945 dns_create_txid(void)
946 {
947   u16_t txid;
948   u8_t i;
949
950 again:
951   txid = (u16_t)DNS_RAND_TXID();
952
953   /* check whether the ID is unique */
954   for (i = 0; i < DNS_TABLE_SIZE; i++) {
955     if ((dns_table[i].state == DNS_STATE_ASKING) &&
956         (dns_table[i].txid == txid)) {
957       /* ID already used by another pending query */
958       goto again;
959     }
960   }
961
962   return txid;
963 }
964
965 /**
966  * dns_check_entry() - see if entry has not yet been queried and, if so, sends out a query.
967  * Check an entry in the dns_table:
968  * - send out query for new entries
969  * - retry old pending entries on timeout (also with different servers)
970  * - remove completed entries from the table if their TTL has expired
971  *
972  * @param i index of the dns_table entry to check
973  */
974 static void
975 dns_check_entry(u8_t i)
976 {
977   err_t err;
978   struct dns_table_entry *entry = &dns_table[i];
979
980   LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
981
982   switch (entry->state) {
983
984     case DNS_STATE_NEW: {
985       u16_t txid;
986       /* initialize new entry */
987       txid = dns_create_txid();
988       entry->txid = txid;
989       entry->state = DNS_STATE_ASKING;
990       entry->server_idx = 0;
991       entry->tmr = 1;
992       entry->retries = 0;
993
994       /* send DNS packet for this entry */
995       err = dns_send(i);
996       if (err != ERR_OK) {
997         LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
998                     ("dns_send returned error: %s\n", lwip_strerr(err)));
999       }
1000       break;
1001     }
1002
1003     case DNS_STATE_ASKING:
1004       if (--entry->tmr == 0) {
1005         if (++entry->retries == DNS_MAX_RETRIES) {
1006           /* skip DNS servers with zero address */
1007           while ((entry->server_idx + 1 < DNS_MAX_SERVERS) && ip_addr_isany_val(dns_servers[entry->server_idx + 1])) {
1008             entry->server_idx++;
1009           }
1010
1011           if ((entry->server_idx + 1 < DNS_MAX_SERVERS) && !ip_addr_isany_val(dns_servers[entry->server_idx + 1])) {
1012             /* change of server */
1013             entry->server_idx++;
1014             entry->tmr = 1;
1015             entry->retries = 0;
1016           } else {
1017             LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", entry->name));
1018             /* call specified callback function if provided */
1019             dns_call_found(i, NULL);
1020             /* flush this entry */
1021             entry->state = DNS_STATE_UNUSED;
1022             break;
1023           }
1024         } else {
1025           /* wait longer for the next retry */
1026           entry->tmr = entry->retries;
1027         }
1028
1029         /* send DNS packet for this entry */
1030         err = dns_send(i);
1031         if (err != ERR_OK) {
1032           LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
1033                       ("dns_send returned error: %s\n", lwip_strerr(err)));
1034         }
1035       }
1036       break;
1037     case DNS_STATE_DONE:
1038       /* if the time to live is nul */
1039       if ((entry->ttl == 0) || (--entry->ttl == 0)) {
1040         LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", entry->name));
1041         /* flush this entry, there cannot be any related pending entries in this state */
1042         entry->state = DNS_STATE_UNUSED;
1043       }
1044       break;
1045     case DNS_STATE_UNUSED:
1046       /* nothing to do */
1047       break;
1048     default:
1049       LWIP_ASSERT("unknown dns_table entry state:", 0);
1050       break;
1051   }
1052 }
1053
1054 /**
1055  * Call dns_check_entry for each entry in dns_table - check all entries.
1056  */
1057 static void
1058 dns_check_entries(void)
1059 {
1060   u8_t i;
1061
1062   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
1063     dns_check_entry(i);
1064   }
1065 }
1066
1067 /**
1068  * Receive input function for DNS response packets arriving for the dns UDP pcb.
1069  *
1070  * @params see udp.h
1071  */
1072 static void
1073 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
1074 {
1075   u8_t i, entry_idx = DNS_TABLE_SIZE;
1076   u16_t txid;
1077   u16_t res_idx;
1078   struct dns_hdr hdr;
1079   struct dns_answer ans;
1080   struct dns_query qry;
1081   u16_t nquestions, nanswers;
1082
1083   LWIP_UNUSED_ARG(arg);
1084   LWIP_UNUSED_ARG(pcb);
1085   LWIP_UNUSED_ARG(port);
1086
1087   /* is the dns message big enough ? */
1088   if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY)) {
1089     LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
1090     /* free pbuf and return */
1091     goto memerr;
1092   }
1093
1094   /* copy dns payload inside static buffer for processing */
1095   if (pbuf_copy_partial(p, &hdr, SIZEOF_DNS_HDR, 0) == SIZEOF_DNS_HDR) {
1096     /* Match the ID in the DNS header with the name table. */
1097     txid = htons(hdr.id);
1098     for (i = 0; i < DNS_TABLE_SIZE; i++) {
1099       struct dns_table_entry *entry = &dns_table[i];
1100       entry_idx = i;
1101       if ((entry->state == DNS_STATE_ASKING) &&
1102           (entry->txid == txid)) {
1103         u8_t dns_err;
1104         /* This entry is now completed. */
1105         
1106 #if ! ESP_DNS
1107         entry->state = DNS_STATE_DONE;
1108 #endif
1109         dns_err = hdr.flags2 & DNS_FLAG2_ERR_MASK;
1110
1111         /* We only care about the question(s) and the answers. The authrr
1112            and the extrarr are simply discarded. */
1113         nquestions = htons(hdr.numquestions);
1114         nanswers   = htons(hdr.numanswers);
1115
1116         /* Check for error. If so, call callback to inform. */
1117         if (((hdr.flags1 & DNS_FLAG1_RESPONSE) == 0) || (dns_err != 0) || (nquestions != 1)) {
1118           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", entry->name));
1119           /* call callback to indicate error, clean up memory and return */
1120 #if ! ESP_DNS
1121                 goto responseerr;
1122         }
1123 #else
1124                 goto memerr;
1125         }
1126         entry->state = DNS_STATE_DONE;
1127 #endif
1128         
1129
1130         /* Check whether response comes from the same network address to which the
1131            question was sent. (RFC 5452) */
1132         if (!ip_addr_cmp(addr, &dns_servers[entry->server_idx])) {
1133           /* call callback to indicate error, clean up memory and return */
1134           goto responseerr;
1135         }
1136
1137         /* Check if the name in the "question" part match with the name in the entry and
1138            skip it if equal. */
1139         res_idx = dns_compare_name(entry->name, p, SIZEOF_DNS_HDR);
1140         if (res_idx == 0xFFFF) {
1141           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
1142           /* call callback to indicate error, clean up memory and return */
1143           goto responseerr;
1144         }
1145
1146         /* check if "question" part matches the request */
1147         pbuf_copy_partial(p, &qry, SIZEOF_DNS_QUERY, res_idx);
1148         if ((qry.cls != PP_HTONS(DNS_RRCLASS_IN)) ||
1149           (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_AAAA))) ||
1150           (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_A)))) {
1151           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
1152           /* call callback to indicate error, clean up memory and return */
1153           goto responseerr;
1154         }
1155         /* skip the rest of the "question" part */
1156         res_idx += SIZEOF_DNS_QUERY;
1157
1158         while ((nanswers > 0) && (res_idx < p->tot_len)) {
1159           /* skip answer resource record's host name */
1160           res_idx = dns_parse_name(p, res_idx);
1161
1162           /* Check for IP address type and Internet class. Others are discarded. */
1163           pbuf_copy_partial(p, &ans, SIZEOF_DNS_ANSWER, res_idx);
1164           if (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) {
1165 #if LWIP_IPV4
1166             if ((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.len == PP_HTONS(sizeof(ip4_addr_t)))) {
1167 #if LWIP_IPV4 && LWIP_IPV6
1168               if (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
1169 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1170               {
1171                 ip4_addr_t ip4addr;
1172                 res_idx += SIZEOF_DNS_ANSWER;
1173                 /* read the answer resource record's TTL, and maximize it if needed */
1174                 entry->ttl = ntohl(ans.ttl);
1175                 if (entry->ttl > DNS_MAX_TTL) {
1176                   entry->ttl = DNS_MAX_TTL;
1177                 }
1178                 /* read the IP address after answer resource record's header */
1179                 pbuf_copy_partial(p, &ip4addr, sizeof(ip4_addr_t), res_idx);
1180                 ip_addr_copy_from_ip4(entry->ipaddr, ip4addr);
1181                 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", entry->name));
1182                 ip_addr_debug_print(DNS_DEBUG, (&(entry->ipaddr)));
1183                 LWIP_DEBUGF(DNS_DEBUG, ("\n"));
1184                 /* call specified callback function if provided */
1185                 dns_call_found(entry_idx, &entry->ipaddr);
1186                 if (entry->ttl == 0) {
1187                   /* RFC 883, page 29: "Zero values are
1188                      interpreted to mean that the RR can only be used for the
1189                      transaction in progress, and should not be cached."
1190                      -> flush this entry now */
1191                   goto flushentry;
1192                 }
1193                 /* deallocate memory and return */
1194                 goto memerr;
1195               }
1196             }
1197 #endif /* LWIP_IPV4 */
1198 #if LWIP_IPV6
1199             if ((ans.type == PP_HTONS(DNS_RRTYPE_AAAA)) && (ans.len == PP_HTONS(sizeof(ip6_addr_t)))) {
1200 #if LWIP_IPV4 && LWIP_IPV6
1201               if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
1202 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1203               {
1204                 ip6_addr_t ip6addr;
1205                 res_idx += SIZEOF_DNS_ANSWER;
1206                 /* read the answer resource record's TTL, and maximize it if needed */
1207                 entry->ttl = ntohl(ans.ttl);
1208                 if (entry->ttl > DNS_MAX_TTL) {
1209                   entry->ttl = DNS_MAX_TTL;
1210                 }
1211                 /* read the IP address after answer resource record's header */
1212                 pbuf_copy_partial(p, &ip6addr, sizeof(ip6_addr_t), res_idx);
1213                 ip_addr_copy_from_ip6(entry->ipaddr, ip6addr);
1214                 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", entry->name));
1215                 ip_addr_debug_print(DNS_DEBUG, (&(entry->ipaddr)));
1216                 LWIP_DEBUGF(DNS_DEBUG, (" AAAA\n"));
1217                 /* call specified callback function if provided */
1218                 dns_call_found(entry_idx, &entry->ipaddr);
1219                 if (entry->ttl == 0) {
1220                   /* RFC 883, page 29: "Zero values are
1221                      interpreted to mean that the RR can only be used for the
1222                      transaction in progress, and should not be cached."
1223                      -> flush this entry now */
1224                   goto flushentry;
1225                 }
1226                 /* deallocate memory and return */
1227                 goto memerr;
1228               }
1229             }
1230 #endif /* LWIP_IPV6 */
1231           }
1232           /* skip this answer */
1233           res_idx += SIZEOF_DNS_ANSWER + htons(ans.len);
1234           --nanswers;
1235         }
1236 #if LWIP_IPV4 && LWIP_IPV6
1237         if ((entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) ||
1238             (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
1239           if (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
1240             /* IPv4 failed, try IPv6 */
1241             entry->reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
1242           } else {
1243             /* IPv6 failed, try IPv4 */
1244             entry->reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
1245           }
1246           pbuf_free(p);
1247           entry->state = DNS_STATE_NEW;
1248           dns_check_entry(entry_idx);
1249           return;
1250         }
1251 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1252         LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", entry->name));
1253         /* call callback to indicate error, clean up memory and return */
1254         goto responseerr;
1255       }
1256     }
1257   }
1258
1259   /* deallocate memory and return */
1260   goto memerr;
1261
1262 responseerr:
1263   /* ERROR: call specified callback function with NULL as name to indicate an error */
1264   dns_call_found(entry_idx, NULL);
1265 flushentry:
1266   /* flush this entry */
1267   dns_table[entry_idx].state = DNS_STATE_UNUSED;
1268
1269 memerr:
1270   /* free pbuf */
1271   pbuf_free(p);
1272   return;
1273 }
1274
1275 /**
1276  * Queues a new hostname to resolve and sends out a DNS query for that hostname
1277  *
1278  * @param name the hostname that is to be queried
1279  * @param hostnamelen length of the hostname
1280  * @param found a callback function to be called on success, failure or timeout
1281  * @param callback_arg argument to pass to the callback function
1282  * @return @return a err_t return code.
1283  */
1284 static err_t
1285 dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
1286             void *callback_arg LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
1287 {
1288   u8_t i;
1289   u8_t lseq, lseqi;
1290   struct dns_table_entry *entry = NULL;
1291   size_t namelen;
1292   struct dns_req_entry* req;
1293
1294 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
1295   u8_t r;
1296   /* check for duplicate entries */
1297   for (i = 0; i < DNS_TABLE_SIZE; i++) {
1298     if ((dns_table[i].state == DNS_STATE_ASKING) &&
1299         (LWIP_DNS_STRICMP(name, dns_table[i].name) == 0)) {
1300 #if LWIP_IPV4 && LWIP_IPV6
1301       if (dns_table[i].reqaddrtype != dns_addrtype) {
1302         /* requested address types don't match
1303            this can lead to 2 concurrent requests, but mixing the address types
1304            for the same host should not be that common */
1305         continue;
1306       }
1307 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1308       /* this is a duplicate entry, find a free request entry */
1309       for (r = 0; r < DNS_MAX_REQUESTS; r++) {
1310         if (dns_requests[r].found == 0) {
1311           dns_requests[r].found = found;
1312           dns_requests[r].arg = callback_arg;
1313           dns_requests[r].dns_table_idx = i;
1314           LWIP_DNS_SET_ADDRTYPE(dns_requests[r].reqaddrtype, dns_addrtype);
1315           LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": duplicate request\n", name));
1316           return ERR_INPROGRESS;
1317         }
1318       }
1319     }
1320   }
1321   /* no duplicate entries found */
1322 #endif
1323
1324   /* search an unused entry, or the oldest one */
1325   lseq = 0;
1326   lseqi = DNS_TABLE_SIZE;
1327   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
1328     entry = &dns_table[i];
1329     /* is it an unused entry ? */
1330     if (entry->state == DNS_STATE_UNUSED) {
1331       break;
1332     }
1333     /* check if this is the oldest completed entry */
1334     if (entry->state == DNS_STATE_DONE) {
1335       if ((u8_t)(dns_seqno - entry->seqno) > lseq) {
1336         lseq = dns_seqno - entry->seqno;
1337         lseqi = i;
1338       }
1339     }
1340   }
1341
1342   /* if we don't have found an unused entry, use the oldest completed one */
1343   if (i == DNS_TABLE_SIZE) {
1344     if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
1345       /* no entry can be used now, table is full */
1346       LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
1347       return ERR_MEM;
1348     } else {
1349       /* use the oldest completed one */
1350       i = lseqi;
1351       entry = &dns_table[i];
1352     }
1353   }
1354
1355 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
1356   /* find a free request entry */
1357   req = NULL;
1358   for (r = 0; r < DNS_MAX_REQUESTS; r++) {
1359     if (dns_requests[r].found == NULL) {
1360       req = &dns_requests[r];
1361       break;
1362     }
1363   }
1364   if (req == NULL) {
1365     /* no request entry can be used now, table is full */
1366     LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS request entries table is full\n", name));
1367     return ERR_MEM;
1368   }
1369   req->dns_table_idx = i;
1370 #else
1371   /* in this configuration, the entry index is the same as the request index */
1372   req = &dns_requests[i];
1373 #endif
1374
1375   /* use this entry */
1376   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
1377
1378   /* fill the entry */
1379   entry->state = DNS_STATE_NEW;
1380   entry->seqno = dns_seqno;
1381   LWIP_DNS_SET_ADDRTYPE(entry->reqaddrtype, dns_addrtype);
1382   LWIP_DNS_SET_ADDRTYPE(req->reqaddrtype, dns_addrtype);
1383   req->found = found;
1384   req->arg   = callback_arg;
1385   namelen = LWIP_MIN(hostnamelen, DNS_MAX_NAME_LENGTH-1);
1386   MEMCPY(entry->name, name, namelen);
1387   entry->name[namelen] = 0;
1388
1389 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
1390   entry->pcb_idx = dns_alloc_pcb();
1391   if (entry->pcb_idx >= DNS_MAX_SOURCE_PORTS) {
1392     /* failed to get a UDP pcb */
1393     LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": failed to allocate a pcb\n", name));
1394     entry->state = DNS_STATE_UNUSED;
1395     req->found = NULL;
1396     return ERR_MEM;
1397   }
1398   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS pcb %"U16_F"\n", name, (u16_t)(entry->pcb_idx)));
1399 #endif
1400
1401   dns_seqno++;
1402
1403   /* force to send query without waiting timer */
1404   dns_check_entry(i);
1405
1406   /* dns query is enqueued */
1407   return ERR_INPROGRESS;
1408 }
1409
1410 /**
1411  * Resolve a hostname (string) into an IP address.
1412  * NON-BLOCKING callback version for use with raw API!!!
1413  *
1414  * Returns immediately with one of err_t return codes:
1415  * - ERR_OK if hostname is a valid IP address string or the host
1416  *   name is already in the local names table.
1417  * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
1418  *   for resolution if no errors are present.
1419  * - ERR_ARG: dns client not initialized or invalid hostname
1420  *
1421  * @param hostname the hostname that is to be queried
1422  * @param addr pointer to a ip_addr_t where to store the address if it is already
1423  *             cached in the dns_table (only valid if ERR_OK is returned!)
1424  * @param found a callback function to be called on success, failure or timeout (only if
1425  *              ERR_INPROGRESS is returned!)
1426  * @param callback_arg argument to pass to the callback function
1427  * @return a err_t return code.
1428  */
1429 err_t
1430 dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found,
1431                   void *callback_arg)
1432 {
1433   return dns_gethostbyname_addrtype(hostname, addr, found, callback_arg, LWIP_DNS_ADDRTYPE_DEFAULT);
1434 }
1435
1436 static bool dns_server_is_set (void)
1437 {
1438   int i = 0;
1439   for (i = 0;i < DNS_MAX_SERVERS; i++) {
1440     if (!ip_addr_isany_val(dns_servers[i])) {
1441       return true;
1442     }
1443   }
1444   return false;
1445 }
1446
1447 /** Like dns_gethostbyname, but returned address type can be controlled:
1448  * @param dns_addrtype: - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 first, try IPv6 if IPv4 fails only
1449  *                      - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 first, try IPv4 if IPv6 fails only
1450  *                      - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
1451  *                      - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
1452  */
1453 err_t
1454 dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, dns_found_callback found,
1455                            void *callback_arg, u8_t dns_addrtype)
1456 {
1457   size_t hostnamelen;
1458   /* not initialized or no valid server yet, or invalid addr pointer
1459    * or invalid hostname or invalid hostname length */
1460   if ((addr == NULL) ||
1461       (!hostname) || (!hostname[0])) {
1462     return ERR_ARG;
1463   }
1464 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
1465   if (dns_pcbs[0] == NULL) {
1466     return ERR_ARG;
1467   }
1468 #endif
1469   hostnamelen = strlen(hostname);
1470   if (hostnamelen >= DNS_MAX_NAME_LENGTH) {
1471     LWIP_DEBUGF(DNS_DEBUG, ("dns_gethostbyname: name too long to resolve"));
1472     return ERR_ARG;
1473   }
1474
1475
1476 #if LWIP_HAVE_LOOPIF
1477   if (strcmp(hostname, "localhost") == 0) {
1478     ip_addr_set_loopback(LWIP_DNS_ADDRTYPE_IS_IPV6(dns_addrtype), addr);
1479     return ERR_OK;
1480   }
1481 #endif /* LWIP_HAVE_LOOPIF */
1482
1483   /* host name already in octet notation? set ip addr and return ERR_OK */
1484   if (ipaddr_aton(hostname, addr)) {
1485 #if LWIP_IPV4 && LWIP_IPV6
1486     if ((IP_IS_V6(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV4)) ||
1487         (!IP_IS_V6(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV6)))
1488 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1489     {
1490       return ERR_OK;
1491     }
1492   }
1493   /* already have this address cached? */
1494   if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
1495     return ERR_OK;
1496   }
1497 #if LWIP_IPV4 && LWIP_IPV6
1498   if ((dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) || (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
1499     /* fallback to 2nd IP type and try again to lookup */
1500     u8_t fallback;
1501     if (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
1502       fallback = LWIP_DNS_ADDRTYPE_IPV6;
1503     } else {
1504       fallback = LWIP_DNS_ADDRTYPE_IPV4;
1505     }
1506     if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(fallback)) == ERR_OK) {
1507       return ERR_OK;
1508     }
1509   }
1510 #else /* LWIP_IPV4 && LWIP_IPV6 */
1511   LWIP_UNUSED_ARG(dns_addrtype);
1512 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1513
1514   /* prevent calling found callback if no server is set, return error instead */
1515   
1516   if (dns_server_is_set() == false) {
1517     return ERR_VAL;
1518   }
1519
1520   /* queue query with specified callback */
1521   return dns_enqueue(hostname, hostnamelen, found, callback_arg LWIP_DNS_ADDRTYPE_ARG(dns_addrtype));
1522 }
1523
1524 #endif /* LWIP_DNS */