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