• 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, 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
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   LWIP_UNUSED_ARG(dns_addrtype);
514   return dns_lookup_local(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype));
515 }
516 
517 /* Internal implementation for dns_local_lookup and dns_lookup */
518 static err_t
dns_lookup_local(const char * hostname,ip_addr_t * addr LWIP_DNS_ADDRTYPE_ARG (u8_t dns_addrtype))519 dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
520 {
521 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
522   struct local_hostlist_entry *entry = local_hostlist_dynamic;
523   while (entry != NULL) {
524     if ((lwip_stricmp(entry->name, hostname) == 0) &&
525         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, entry->addr)) {
526       if (addr) {
527         ip_addr_copy(*addr, entry->addr);
528       }
529       return ERR_OK;
530     }
531     entry = entry->next;
532   }
533 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
534   size_t i;
535   for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_static); i++) {
536     if ((lwip_stricmp(local_hostlist_static[i].name, hostname) == 0) &&
537         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, local_hostlist_static[i].addr)) {
538       if (addr) {
539         ip_addr_copy(*addr, local_hostlist_static[i].addr);
540       }
541       return ERR_OK;
542     }
543   }
544 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
545   return ERR_ARG;
546 }
547 
548 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
549 /**
550  * @ingroup dns
551  * Remove all entries from the local host-list for a specific hostname
552  * and/or IP address
553  *
554  * @param hostname hostname for which entries shall be removed from the local
555  *                 host-list
556  * @param addr address for which entries shall be removed from the local host-list
557  * @return the number of removed entries
558  */
559 int
dns_local_removehost(const char * hostname,const ip_addr_t * addr)560 dns_local_removehost(const char *hostname, const ip_addr_t *addr)
561 {
562   int removed = 0;
563   struct local_hostlist_entry *entry = local_hostlist_dynamic;
564   struct local_hostlist_entry *last_entry = NULL;
565   while (entry != NULL) {
566     if (((hostname == NULL) || !lwip_stricmp(entry->name, hostname)) &&
567         ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
568       struct local_hostlist_entry *free_entry;
569       if (last_entry != NULL) {
570         last_entry->next = entry->next;
571       } else {
572         local_hostlist_dynamic = entry->next;
573       }
574       free_entry = entry;
575       entry = entry->next;
576       memp_free(MEMP_LOCALHOSTLIST, free_entry);
577       removed++;
578     } else {
579       last_entry = entry;
580       entry = entry->next;
581     }
582   }
583   return removed;
584 }
585 
586 /**
587  * @ingroup dns
588  * Add a hostname/IP address pair to the local host-list.
589  * Duplicates are not checked.
590  *
591  * @param hostname hostname of the new entry
592  * @param addr IP address of the new entry
593  * @return ERR_OK if succeeded or ERR_MEM on memory error
594  */
595 err_t
dns_local_addhost(const char * hostname,const ip_addr_t * addr)596 dns_local_addhost(const char *hostname, const ip_addr_t *addr)
597 {
598   struct local_hostlist_entry *entry;
599   size_t namelen;
600   char *entry_name;
601   LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
602   namelen = strlen(hostname);
603   LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
604   entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
605   if (entry == NULL) {
606     return ERR_MEM;
607   }
608   entry_name = (char *)entry + sizeof(struct local_hostlist_entry);
609   MEMCPY(entry_name, hostname, namelen);
610   entry_name[namelen] = 0;
611   entry->name = entry_name;
612   ip_addr_copy(entry->addr, *addr);
613   entry->next = local_hostlist_dynamic;
614   local_hostlist_dynamic = entry;
615   return ERR_OK;
616 }
617 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
618 #endif /* DNS_LOCAL_HOSTLIST */
619 
620 /**
621  * @ingroup dns
622  * Look up a hostname in the array of known hostnames.
623  *
624  * @note This function only looks in the internal array of known
625  * hostnames, it does not send out a query for the hostname if none
626  * was found. The function dns_enqueue() can be used to send a query
627  * for a hostname.
628  *
629  * @param name the hostname to look up
630  * @param addr the hostname's IP address, as u32_t (instead of ip_addr_t to
631  *         better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname
632  *         was not found in the cached dns_table.
633  * @return ERR_OK if found, ERR_ARG if not found
634  */
635 static err_t
dns_lookup(const char * name,ip_addr_t * addr LWIP_DNS_ADDRTYPE_ARG (u8_t dns_addrtype))636 dns_lookup(const char *name, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
637 {
638   u8_t i;
639 #if DNS_LOCAL_HOSTLIST
640   if (dns_lookup_local(name, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
641     return ERR_OK;
642   }
643 #endif /* DNS_LOCAL_HOSTLIST */
644 #ifdef DNS_LOOKUP_LOCAL_EXTERN
645   if (DNS_LOOKUP_LOCAL_EXTERN(name, addr, LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(dns_addrtype)) == ERR_OK) {
646     return ERR_OK;
647   }
648 #endif /* DNS_LOOKUP_LOCAL_EXTERN */
649 
650   /* Walk through name list, return entry if found. If not, return NULL. */
651   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
652     if ((dns_table[i].state == DNS_STATE_DONE) &&
653         (lwip_strnicmp(name, dns_table[i].name, sizeof(dns_table[i].name)) == 0) &&
654         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, dns_table[i].ipaddr)) {
655       LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
656       ip_addr_debug_print_val(DNS_DEBUG, dns_table[i].ipaddr);
657       LWIP_DEBUGF(DNS_DEBUG, ("\n"));
658       if (addr) {
659         ip_addr_copy(*addr, dns_table[i].ipaddr);
660       }
661       return ERR_OK;
662     }
663   }
664 
665   return ERR_ARG;
666 }
667 
668 /**
669  * Compare the "dotted" name "query" with the encoded name "response"
670  * to make sure an answer from the DNS server matches the current dns_table
671  * entry (otherwise, answers might arrive late for hostname not on the list
672  * any more).
673  *
674  * For now, this function compares case-insensitive to cope with all kinds of
675  * servers. This also means that "dns 0x20 bit encoding" must be checked
676  * externally, if we want to implement it.
677  * Currently, the request is sent exactly as passed in by he user request.
678  *
679  * @param query hostname (not encoded) from the dns_table
680  * @param p pbuf containing the encoded hostname in the DNS response
681  * @param start_offset offset into p where the name starts
682  * @return 0xFFFF: names differ, other: names equal -> offset behind name
683  */
684 static u16_t
dns_compare_name(const char * query,struct pbuf * p,u16_t start_offset)685 dns_compare_name(const char *query, struct pbuf *p, u16_t start_offset)
686 {
687   int n;
688   u16_t response_offset = start_offset;
689 
690   do {
691     n = pbuf_try_get_at(p, response_offset);
692     if ((n < 0) || (response_offset == 0xFFFF)) {
693       /* error or overflow */
694       return 0xFFFF;
695     }
696     response_offset++;
697     /** @see RFC 1035 - 4.1.4. Message compression */
698     if ((n & 0xc0) == 0xc0) {
699       /* Compressed name: cannot be equal since we don't send them */
700       return 0xFFFF;
701     } else {
702       /* Not compressed name */
703       while (n > 0) {
704         int c = pbuf_try_get_at(p, response_offset);
705         if (c < 0) {
706           return 0xFFFF;
707         }
708         if (lwip_tolower((*query)) != lwip_tolower((u8_t)c)) {
709           return 0xFFFF;
710         }
711         if (response_offset == 0xFFFF) {
712           /* would overflow */
713           return 0xFFFF;
714         }
715         response_offset++;
716         ++query;
717         --n;
718       }
719       ++query;
720     }
721     n = pbuf_try_get_at(p, response_offset);
722     if (n < 0) {
723       return 0xFFFF;
724     }
725   } while (n != 0);
726 
727   if (response_offset == 0xFFFF) {
728     /* would overflow */
729     return 0xFFFF;
730   }
731   return (u16_t)(response_offset + 1);
732 }
733 
734 /**
735  * Walk through a compact encoded DNS name and return the end of the name.
736  *
737  * @param p pbuf containing the name
738  * @param query_idx start index into p pointing to encoded DNS name in the DNS server response
739  * @return index to end of the name
740  */
741 static u16_t
dns_skip_name(struct pbuf * p,u16_t query_idx)742 dns_skip_name(struct pbuf *p, u16_t query_idx)
743 {
744   int n;
745   u16_t offset = query_idx;
746 
747   do {
748     n = pbuf_try_get_at(p, offset++);
749     if ((n < 0) || (offset == 0)) {
750       return 0xFFFF;
751     }
752     /** @see RFC 1035 - 4.1.4. Message compression */
753     if ((n & 0xc0) == 0xc0) {
754       /* Compressed name: since we only want to skip it (not check it), stop here */
755       break;
756     } else {
757       /* Not compressed name */
758       if (offset + n >= p->tot_len) {
759         return 0xFFFF;
760       }
761       offset = (u16_t)(offset + n);
762     }
763     n = pbuf_try_get_at(p, offset);
764     if (n < 0) {
765       return 0xFFFF;
766     }
767   } while (n != 0);
768 
769   if (offset == 0xFFFF) {
770     return 0xFFFF;
771   }
772   return (u16_t)(offset + 1);
773 }
774 
775 /**
776  * Send a DNS query packet.
777  *
778  * @param idx the DNS table entry index for which to send a request
779  * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
780  */
781 static err_t
dns_send(u8_t idx)782 dns_send(u8_t idx)
783 {
784   err_t err;
785   struct dns_hdr hdr;
786   struct dns_query qry;
787   struct pbuf *p;
788   u16_t query_idx, copy_len;
789   const char *hostname, *hostname_part;
790   u8_t n;
791   u8_t pcb_idx;
792   struct dns_table_entry *entry = &dns_table[idx];
793 
794   LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
795                           (u16_t)(entry->server_idx), entry->name));
796   LWIP_ASSERT("dns server out of array", entry->server_idx < DNS_MAX_SERVERS);
797   if (ip_addr_isany_val(dns_servers[entry->server_idx])
798 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
799       && !entry->is_mdns
800 #endif
801      ) {
802     /* DNS server not valid anymore, e.g. PPP netif has been shut down */
803     /* call specified callback function if provided */
804     dns_call_found(idx, NULL);
805     /* flush this entry */
806     entry->state = DNS_STATE_UNUSED;
807     return ERR_OK;
808   }
809 
810   /* if here, we have either a new query or a retry on a previous query to process */
811 #if LWIP_ENABLE_DISTRIBUTED_NET && !LWIP_USE_GET_HOST_BY_NAME_EXTERNAL
812   if (is_distributed_net_enabled()) {
813     p = pbuf_alloc(PBUF_TRANSPORT,
814                    (u16_t)(sizeof(udp_data) + SIZEOF_DNS_HDR + strlen(entry->name) + 2 + SIZEOF_DNS_QUERY), PBUF_RAM);
815   } else {
816     p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(SIZEOF_DNS_HDR + strlen(entry->name) + 2 + SIZEOF_DNS_QUERY), PBUF_RAM);
817   }
818 #else
819   p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(SIZEOF_DNS_HDR + strlen(entry->name) + 2 +
820                                          SIZEOF_DNS_QUERY), PBUF_RAM);
821 #endif
822 
823   if (p != NULL) {
824     const ip_addr_t *dst;
825     u16_t dst_port;
826     /* fill dns header */
827     memset(&hdr, 0, SIZEOF_DNS_HDR);
828     hdr.id = lwip_htons(entry->txid);
829     hdr.flags1 = DNS_FLAG1_RD;
830     hdr.numquestions = PP_HTONS(1);
831 #if LWIP_ENABLE_DISTRIBUTED_NET && !LWIP_USE_GET_HOST_BY_NAME_EXTERNAL
832     if (is_distributed_net_enabled()) {
833       udp_data udp_data_hdr = {0};
834       (void)memset_s(&udp_data_hdr, sizeof(udp_data_hdr), 0, sizeof(udp_data_hdr));
835       dst = &dns_servers[entry->server_idx];
836 
837 #if LWIP_IPV6
838       (void)strcpy_s(udp_data_hdr.dest_addr, sizeof(udp_data_hdr.dest_addr), ip4addr_ntoa(&dst->u_addr.ip4));
839 #else
840       (void)strcpy_s(udp_data_hdr.dest_addr, sizeof(udp_data_hdr.dest_addr), ip4addr_ntoa(dst));
841 #endif
842 
843       udp_data_hdr.dest_port = DNS_SERVER_PORT;
844 
845       pbuf_take(p, &udp_data_hdr, sizeof(udp_data_hdr));
846       pbuf_take_at(p, &hdr, SIZEOF_DNS_HDR, sizeof(udp_data_hdr));
847     } else {
848       pbuf_take(p, &hdr, SIZEOF_DNS_HDR);
849     }
850 #else
851     pbuf_take(p, &hdr, SIZEOF_DNS_HDR);
852 #endif
853     hostname = entry->name;
854     --hostname;
855 
856     /* convert hostname into suitable query format. */
857 #if LWIP_ENABLE_DISTRIBUTED_NET && !LWIP_USE_GET_HOST_BY_NAME_EXTERNAL
858     if (is_distributed_net_enabled()) {
859       query_idx = sizeof(udp_data) + SIZEOF_DNS_HDR;
860     } else {
861       query_idx = SIZEOF_DNS_HDR;
862     }
863 #else
864     query_idx = SIZEOF_DNS_HDR;
865 #endif
866     do {
867       ++hostname;
868       hostname_part = hostname;
869       for (n = 0; *hostname != '.' && *hostname != 0; ++hostname) {
870         ++n;
871       }
872       copy_len = (u16_t)(hostname - hostname_part);
873       if (query_idx + n + 1 > 0xFFFF) {
874         /* u16_t overflow */
875         goto overflow_return;
876       }
877       pbuf_put_at(p, query_idx, n);
878       pbuf_take_at(p, hostname_part, copy_len, (u16_t)(query_idx + 1));
879       query_idx = (u16_t)(query_idx + n + 1);
880     } while (*hostname != 0);
881     pbuf_put_at(p, query_idx, 0);
882     query_idx++;
883 
884     /* fill dns query */
885     if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype)) {
886       qry.type = PP_HTONS(DNS_RRTYPE_AAAA);
887     } else {
888       qry.type = PP_HTONS(DNS_RRTYPE_A);
889     }
890     qry.cls = PP_HTONS(DNS_RRCLASS_IN);
891     pbuf_take_at(p, &qry, SIZEOF_DNS_QUERY, query_idx);
892 
893 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
894     pcb_idx = entry->pcb_idx;
895 #else
896     pcb_idx = 0;
897 #endif
898     /* send dns packet */
899     LWIP_DEBUGF(DNS_DEBUG, ("sending DNS request ID %d for name \"%s\" to server %d\r\n",
900                             entry->txid, entry->name, entry->server_idx));
901 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
902     if (entry->is_mdns) {
903       dst_port = DNS_MQUERY_PORT;
904 #if LWIP_IPV6
905       if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype)) {
906         dst = &dns_mquery_v6group;
907       }
908 #endif
909 #if LWIP_IPV4 && LWIP_IPV6
910       else
911 #endif
912 #if LWIP_IPV4
913       {
914         dst = &dns_mquery_v4group;
915       }
916 #endif
917     } else
918 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
919     {
920       dst_port = DNS_SERVER_PORT;
921       dst = &dns_servers[entry->server_idx];
922     }
923 #if LWIP_ENABLE_DISTRIBUTED_NET && !LWIP_USE_GET_HOST_BY_NAME_EXTERNAL
924     if (is_distributed_net_enabled()) {
925       ip_addr_t local_addr = {0};
926       dst_port = get_local_udp_server_port();
927 
928 #if LWIP_IPV6
929       local_addr.u_addr.ip4.addr = ipaddr_addr(LOCAL_SERVER_IP);
930       local_addr.type = IPADDR_TYPE_V4;
931 #else
932       local_addr.addr = ipaddr_addr(LOCAL_SERVER_IP);
933 #endif
934 #if (defined(EMUI_WEB_CLIENT))
935       DISTRIBUTED_NET_START_UDP_SERVER();
936 #endif
937       err = udp_sendto(dns_pcbs[pcb_idx], p, &local_addr, dst_port);
938     } else {
939       err = udp_sendto(dns_pcbs[pcb_idx], p, dst, dst_port);
940     }
941 #else
942     err = udp_sendto(dns_pcbs[pcb_idx], p, dst, dst_port);
943 #endif
944 
945     /* free pbuf */
946     pbuf_free(p);
947   } else {
948     err = ERR_MEM;
949   }
950 
951   return err;
952 overflow_return:
953   pbuf_free(p);
954   return ERR_VAL;
955 }
956 
957 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
958 static struct udp_pcb *
dns_alloc_random_port(void)959 dns_alloc_random_port(void)
960 {
961   err_t err;
962   struct udp_pcb *pcb;
963 
964   pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
965   if (pcb == NULL) {
966     /* out of memory, have to reuse an existing pcb */
967     return NULL;
968   }
969   do {
970     u16_t port = (u16_t)DNS_RAND_TXID();
971     if (DNS_PORT_ALLOWED(port)) {
972       err = udp_bind(pcb, IP_ANY_TYPE, port);
973     } else {
974       /* this port is not allowed, try again */
975       err = ERR_USE;
976     }
977   } while (err == ERR_USE);
978   if (err != ERR_OK) {
979     udp_remove(pcb);
980     return NULL;
981   }
982   udp_recv(pcb, dns_recv, NULL);
983   return pcb;
984 }
985 
986 /**
987  * dns_alloc_pcb() - allocates a new pcb (or reuses an existing one) to be used
988  * for sending a request
989  *
990  * @return an index into dns_pcbs
991  */
992 static u8_t
dns_alloc_pcb(void)993 dns_alloc_pcb(void)
994 {
995   u8_t i;
996   u8_t idx;
997 
998   for (i = 0; i < DNS_MAX_SOURCE_PORTS; i++) {
999     if (dns_pcbs[i] == NULL) {
1000       break;
1001     }
1002   }
1003   if (i < DNS_MAX_SOURCE_PORTS) {
1004     dns_pcbs[i] = dns_alloc_random_port();
1005     if (dns_pcbs[i] != NULL) {
1006       /* succeeded */
1007       dns_last_pcb_idx = i;
1008       return i;
1009     }
1010   }
1011   /* if we come here, creating a new UDP pcb failed, so we have to use
1012      an already existing one (so overflow is no issue) */
1013   for (i = 0, idx = (u8_t)(dns_last_pcb_idx + 1); i < DNS_MAX_SOURCE_PORTS; i++, idx++) {
1014     if (idx >= DNS_MAX_SOURCE_PORTS) {
1015       idx = 0;
1016     }
1017     if (dns_pcbs[idx] != NULL) {
1018       dns_last_pcb_idx = idx;
1019       return idx;
1020     }
1021   }
1022   return DNS_MAX_SOURCE_PORTS;
1023 }
1024 #endif /* ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0) */
1025 
1026 /**
1027  * dns_call_found() - call the found callback and check if there are duplicate
1028  * entries for the given hostname. If there are any, their found callback will
1029  * be called and they will be removed.
1030  *
1031  * @param idx dns table index of the entry that is resolved or removed
1032  * @param addr IP address for the hostname (or NULL on error or memory shortage)
1033  */
1034 static void
dns_call_found(u8_t idx,ip_addr_t * addr)1035 dns_call_found(u8_t idx, ip_addr_t *addr)
1036 {
1037 #if ((LWIP_DNS_SECURE & (LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT)) != 0)
1038   u8_t i;
1039 #endif
1040 
1041 #if LWIP_IPV4 && LWIP_IPV6
1042   if (addr != NULL) {
1043     /* check that address type matches the request and adapt the table entry */
1044     if (IP_IS_V6_VAL(*addr)) {
1045       LWIP_ASSERT("invalid response", LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
1046       dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
1047     } else {
1048       LWIP_ASSERT("invalid response", !LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
1049       dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
1050     }
1051   }
1052 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1053 
1054 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
1055   for (i = 0; i < DNS_MAX_REQUESTS; i++) {
1056     if (dns_requests[i].found && (dns_requests[i].dns_table_idx == idx)) {
1057       (*dns_requests[i].found)(dns_table[idx].name, addr, dns_requests[i].arg);
1058       /* flush this entry */
1059       dns_requests[i].found = NULL;
1060     }
1061   }
1062 #else
1063   if (dns_requests[idx].found) {
1064     (*dns_requests[idx].found)(dns_table[idx].name, addr, dns_requests[idx].arg);
1065   }
1066   dns_requests[idx].found = NULL;
1067 #endif
1068 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
1069   /* close the pcb used unless other request are using it */
1070   for (i = 0; i < DNS_MAX_REQUESTS; i++) {
1071     if (i == idx) {
1072       continue; /* only check other requests */
1073     }
1074     if (dns_table[i].state == DNS_STATE_ASKING) {
1075       if (dns_table[i].pcb_idx == dns_table[idx].pcb_idx) {
1076         /* another request is still using the same pcb */
1077         dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
1078         break;
1079       }
1080     }
1081   }
1082   if (dns_table[idx].pcb_idx < DNS_MAX_SOURCE_PORTS) {
1083     /* if we come here, the pcb is not used any more and can be removed */
1084     udp_remove(dns_pcbs[dns_table[idx].pcb_idx]);
1085     dns_pcbs[dns_table[idx].pcb_idx] = NULL;
1086     dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
1087   }
1088 #endif
1089 }
1090 
1091 /* Create a query transmission ID that is unique for all outstanding queries */
1092 static u16_t
dns_create_txid(void)1093 dns_create_txid(void)
1094 {
1095   u16_t txid;
1096   u8_t i;
1097 
1098 again:
1099   txid = (u16_t)DNS_RAND_TXID();
1100 
1101   /* check whether the ID is unique */
1102   for (i = 0; i < DNS_TABLE_SIZE; i++) {
1103     if ((dns_table[i].state == DNS_STATE_ASKING) &&
1104         (dns_table[i].txid == txid)) {
1105       /* ID already used by another pending query */
1106       goto again;
1107     }
1108   }
1109 
1110   return txid;
1111 }
1112 
1113 /**
1114  * Check whether there are other backup DNS servers available to try
1115  */
1116 static u8_t
dns_backupserver_available(struct dns_table_entry * pentry)1117 dns_backupserver_available(struct dns_table_entry *pentry)
1118 {
1119   u8_t ret = 0;
1120 
1121   if (pentry) {
1122     if ((pentry->server_idx + 1 < DNS_MAX_SERVERS) && !ip_addr_isany_val(dns_servers[pentry->server_idx + 1])) {
1123       ret = 1;
1124     }
1125   }
1126 
1127   return ret;
1128 }
1129 
1130 /**
1131  * dns_check_entry() - see if entry has not yet been queried and, if so, sends out a query.
1132  * Check an entry in the dns_table:
1133  * - send out query for new entries
1134  * - retry old pending entries on timeout (also with different servers)
1135  * - remove completed entries from the table if their TTL has expired
1136  *
1137  * @param i index of the dns_table entry to check
1138  */
1139 static void
dns_check_entry(u8_t i)1140 dns_check_entry(u8_t i)
1141 {
1142   err_t err;
1143   struct dns_table_entry *entry = &dns_table[i];
1144 
1145   LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
1146 
1147   switch (entry->state) {
1148     case DNS_STATE_NEW:
1149       /* initialize new entry */
1150       entry->txid = dns_create_txid();
1151       entry->state = DNS_STATE_ASKING;
1152       entry->server_idx = 0;
1153       entry->tmr = 1;
1154       entry->retries = 0;
1155 
1156       /* send DNS packet for this entry */
1157       err = dns_send(i);
1158       if (err != ERR_OK) {
1159         LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
1160                     ("dns_send returned error: %s\n", lwip_strerr(err)));
1161       }
1162       break;
1163     case DNS_STATE_ASKING:
1164       if (--entry->tmr == 0) {
1165         if (++entry->retries == DNS_MAX_RETRIES) {
1166           if (dns_backupserver_available(entry)
1167 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1168               && !entry->is_mdns
1169 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
1170              ) {
1171             /* change of server */
1172             entry->server_idx++;
1173             entry->tmr = 1;
1174             entry->retries = 0;
1175           } else {
1176             LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", entry->name));
1177             /* call specified callback function if provided */
1178             dns_call_found(i, NULL);
1179             /* flush this entry */
1180             entry->state = DNS_STATE_UNUSED;
1181             break;
1182           }
1183         } else {
1184           /* wait longer for the next retry */
1185           entry->tmr = entry->retries;
1186         }
1187 
1188         /* send DNS packet for this entry */
1189         err = dns_send(i);
1190         if (err != ERR_OK) {
1191           LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
1192                       ("dns_send returned error: %s\n", lwip_strerr(err)));
1193         }
1194       }
1195       break;
1196     case DNS_STATE_DONE:
1197       /* if the time to live is nul */
1198       if ((entry->ttl == 0) || (--entry->ttl == 0)) {
1199         LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", entry->name));
1200         /* flush this entry, there cannot be any related pending entries in this state */
1201         entry->state = DNS_STATE_UNUSED;
1202       }
1203       break;
1204     case DNS_STATE_UNUSED:
1205       /* nothing to do */
1206       break;
1207     default:
1208       LWIP_ASSERT("unknown dns_table entry state:", 0);
1209       break;
1210   }
1211 }
1212 
1213 /**
1214  * Call dns_check_entry for each entry in dns_table - check all entries.
1215  */
1216 static void
dns_check_entries(void)1217 dns_check_entries(void)
1218 {
1219   u8_t i;
1220 
1221   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
1222     dns_check_entry(i);
1223   }
1224 }
1225 
1226 /**
1227  * Save TTL and call dns_call_found for correct response.
1228  */
1229 static void
dns_correct_response(u8_t idx,u32_t ttl)1230 dns_correct_response(u8_t idx, u32_t ttl)
1231 {
1232   struct dns_table_entry *entry = &dns_table[idx];
1233 
1234   entry->state = DNS_STATE_DONE;
1235 
1236   LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", entry->name));
1237   ip_addr_debug_print_val(DNS_DEBUG, entry->ipaddr);
1238   LWIP_DEBUGF(DNS_DEBUG, ("\n"));
1239 
1240   /* read the answer resource record's TTL, and maximize it if needed */
1241   entry->ttl = ttl;
1242   if (entry->ttl > DNS_MAX_TTL) {
1243     entry->ttl = DNS_MAX_TTL;
1244   }
1245   dns_call_found(idx, &entry->ipaddr);
1246 
1247   if (entry->ttl == 0) {
1248     /* RFC 883, page 29: "Zero values are
1249        interpreted to mean that the RR can only be used for the
1250        transaction in progress, and should not be cached."
1251        -> flush this entry now */
1252     /* entry reused during callback? */
1253     if (entry->state == DNS_STATE_DONE) {
1254       entry->state = DNS_STATE_UNUSED;
1255     }
1256   }
1257 }
1258 
1259 /**
1260  * Receive input function for DNS response packets arriving for the dns UDP pcb.
1261  */
1262 static void
dns_recv(void * arg,struct udp_pcb * pcb,struct pbuf * p,const ip_addr_t * addr,u16_t port)1263 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
1264 {
1265   u8_t i;
1266   u16_t txid;
1267   u16_t res_idx;
1268   struct dns_hdr hdr;
1269   struct dns_answer ans;
1270   struct dns_query qry;
1271   u16_t nquestions, nanswers;
1272 
1273   LWIP_UNUSED_ARG(arg);
1274   LWIP_UNUSED_ARG(pcb);
1275   LWIP_UNUSED_ARG(port);
1276 
1277   /* is the dns message big enough ? */
1278   if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY)) {
1279     LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
1280     /* free pbuf and return */
1281     goto ignore_packet;
1282   }
1283 
1284   /* copy dns payload inside static buffer for processing */
1285   if (pbuf_copy_partial(p, &hdr, SIZEOF_DNS_HDR, 0) == SIZEOF_DNS_HDR) {
1286     /* Match the ID in the DNS header with the name table. */
1287     txid = lwip_htons(hdr.id);
1288     for (i = 0; i < DNS_TABLE_SIZE; i++) {
1289       struct dns_table_entry *entry = &dns_table[i];
1290       if ((entry->state == DNS_STATE_ASKING) &&
1291           (entry->txid == txid)) {
1292 
1293         /* We only care about the question(s) and the answers. The authrr
1294            and the extrarr are simply discarded. */
1295         nquestions = lwip_htons(hdr.numquestions);
1296         nanswers   = lwip_htons(hdr.numanswers);
1297 
1298         /* Check for correct response. */
1299         if ((hdr.flags1 & DNS_FLAG1_RESPONSE) == 0) {
1300           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": not a response\n", entry->name));
1301           goto ignore_packet; /* ignore this packet */
1302         }
1303         if (nquestions != 1) {
1304           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
1305           goto ignore_packet; /* ignore this packet */
1306         }
1307 
1308 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1309         if (!entry->is_mdns)
1310 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
1311         {
1312           /* Check whether response comes from the same network address to which the
1313              question was sent. (RFC 5452) */
1314 #if LWIP_ENABLE_DISTRIBUTED_NET && !LWIP_USE_GET_HOST_BY_NAME_EXTERNAL
1315           if (is_distributed_net_enabled()) {
1316 #if LWIP_IPV6
1317             if (addr->type != IPADDR_TYPE_V4 || addr->u_addr.ip4.addr != ipaddr_addr(LOCAL_SERVER_IP) ||
1318                 port != get_local_udp_server_port()) {
1319               goto ignore_packet; /* ignore this packet */
1320             }
1321 #else
1322             if (addr->addr != ipaddr_addr(LOCAL_SERVER_IP) || port != get_local_udp_server_port()) {
1323               goto ignore_packet; /* ignore this packet */
1324             }
1325 #endif
1326           } else {
1327             if (!ip_addr_cmp(addr, &dns_servers[entry->server_idx])) {
1328               goto ignore_packet; /* ignore this packet */
1329             }
1330           }
1331 #else
1332           if (!ip_addr_cmp(addr, &dns_servers[entry->server_idx])) {
1333             goto ignore_packet; /* ignore this packet */
1334           }
1335 #endif
1336         }
1337 
1338         /* Check if the name in the "question" part match with the name in the entry and
1339            skip it if equal. */
1340         res_idx = dns_compare_name(entry->name, p, SIZEOF_DNS_HDR);
1341         if (res_idx == 0xFFFF) {
1342           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
1343           goto ignore_packet; /* ignore this packet */
1344         }
1345 
1346         /* check if "question" part matches the request */
1347         if (pbuf_copy_partial(p, &qry, SIZEOF_DNS_QUERY, res_idx) != SIZEOF_DNS_QUERY) {
1348           goto ignore_packet; /* ignore this packet */
1349         }
1350         if ((qry.cls != PP_HTONS(DNS_RRCLASS_IN)) ||
1351             (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_AAAA))) ||
1352             (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_A)))) {
1353           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
1354           goto ignore_packet; /* ignore this packet */
1355         }
1356         /* skip the rest of the "question" part */
1357         if (res_idx + SIZEOF_DNS_QUERY > 0xFFFF) {
1358           goto ignore_packet;
1359         }
1360         res_idx = (u16_t)(res_idx + SIZEOF_DNS_QUERY);
1361 
1362         /* Check for error. If so, call callback to inform. */
1363         if (hdr.flags2 & DNS_FLAG2_ERR_MASK) {
1364           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", entry->name));
1365 
1366           /* if there is another backup DNS server to try
1367            * then don't stop the DNS request
1368            */
1369           if (dns_backupserver_available(entry)) {
1370             /* avoid retrying the same server */
1371             entry->retries = DNS_MAX_RETRIES-1;
1372             entry->tmr     = 1;
1373 
1374             /* contact next available server for this entry */
1375             dns_check_entry(i);
1376 
1377             goto ignore_packet;
1378           }
1379         } else {
1380           while ((nanswers > 0) && (res_idx < p->tot_len)) {
1381             /* skip answer resource record's host name */
1382             res_idx = dns_skip_name(p, res_idx);
1383             if (res_idx == 0xFFFF) {
1384               goto ignore_packet; /* ignore this packet */
1385             }
1386 
1387             /* Check for IP address type and Internet class. Others are discarded. */
1388             if (pbuf_copy_partial(p, &ans, SIZEOF_DNS_ANSWER, res_idx) != SIZEOF_DNS_ANSWER) {
1389               goto ignore_packet; /* ignore this packet */
1390             }
1391             if (res_idx + SIZEOF_DNS_ANSWER > 0xFFFF) {
1392               goto ignore_packet;
1393             }
1394             res_idx = (u16_t)(res_idx + SIZEOF_DNS_ANSWER);
1395 
1396             if (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) {
1397 #if LWIP_IPV4
1398               if ((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.len == PP_HTONS(sizeof(ip4_addr_t)))) {
1399 #if LWIP_IPV4 && LWIP_IPV6
1400                 if (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
1401 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1402                 {
1403                   ip4_addr_t ip4addr;
1404                   /* read the IP address after answer resource record's header */
1405                   if (pbuf_copy_partial(p, &ip4addr, sizeof(ip4_addr_t), res_idx) != sizeof(ip4_addr_t)) {
1406                     goto ignore_packet; /* ignore this packet */
1407                   }
1408                   ip_addr_copy_from_ip4(dns_table[i].ipaddr, ip4addr);
1409                   pbuf_free(p);
1410                   /* handle correct response */
1411                   dns_correct_response(i, lwip_ntohl(ans.ttl));
1412                   return;
1413                 }
1414               }
1415 #endif /* LWIP_IPV4 */
1416 #if LWIP_IPV6
1417               if ((ans.type == PP_HTONS(DNS_RRTYPE_AAAA)) && (ans.len == PP_HTONS(sizeof(ip6_addr_p_t)))) {
1418 #if LWIP_IPV4 && LWIP_IPV6
1419                 if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
1420 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1421                 {
1422                   ip6_addr_p_t ip6addr;
1423                   /* read the IP address after answer resource record's header */
1424                   if (pbuf_copy_partial(p, &ip6addr, sizeof(ip6_addr_p_t), res_idx) != sizeof(ip6_addr_p_t)) {
1425                     goto ignore_packet; /* ignore this packet */
1426                   }
1427                   /* @todo: scope ip6addr? Might be required for link-local addresses at least? */
1428                   ip_addr_copy_from_ip6_packed(dns_table[i].ipaddr, ip6addr);
1429                   pbuf_free(p);
1430                   /* handle correct response */
1431                   dns_correct_response(i, lwip_ntohl(ans.ttl));
1432                   return;
1433                 }
1434               }
1435 #endif /* LWIP_IPV6 */
1436             }
1437             /* skip this answer */
1438             if ((int)(res_idx + lwip_htons(ans.len)) > 0xFFFF) {
1439               goto ignore_packet; /* ignore this packet */
1440             }
1441             res_idx = (u16_t)(res_idx + lwip_htons(ans.len));
1442             --nanswers;
1443           }
1444 #if LWIP_IPV4 && LWIP_IPV6
1445           if ((entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) ||
1446               (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
1447             if (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
1448               /* IPv4 failed, try IPv6 */
1449               dns_table[i].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
1450             } else {
1451               /* IPv6 failed, try IPv4 */
1452               dns_table[i].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
1453             }
1454             pbuf_free(p);
1455             dns_table[i].state = DNS_STATE_NEW;
1456             dns_check_entry(i);
1457             return;
1458           }
1459 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1460           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", entry->name));
1461         }
1462         /* call callback to indicate error, clean up memory and return */
1463         pbuf_free(p);
1464         dns_call_found(i, NULL);
1465         dns_table[i].state = DNS_STATE_UNUSED;
1466         return;
1467       }
1468     }
1469   }
1470 
1471 ignore_packet:
1472   /* deallocate memory and return */
1473   pbuf_free(p);
1474   return;
1475 }
1476 
1477 /**
1478  * Queues a new hostname to resolve and sends out a DNS query for that hostname
1479  *
1480  * @param name the hostname that is to be queried
1481  * @param hostnamelen length of the hostname
1482  * @param found a callback function to be called on success, failure or timeout
1483  * @param callback_arg argument to pass to the callback function
1484  * @return err_t return code.
1485  */
1486 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))1487 dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
1488             void *callback_arg LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype) LWIP_DNS_ISMDNS_ARG(u8_t is_mdns))
1489 {
1490   u8_t i;
1491   u8_t lseq, lseqi;
1492   struct dns_table_entry *entry = NULL;
1493   size_t namelen;
1494   struct dns_req_entry *req;
1495 
1496 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
1497   u8_t r;
1498   /* check for duplicate entries */
1499   for (i = 0; i < DNS_TABLE_SIZE; i++) {
1500     if ((dns_table[i].state == DNS_STATE_ASKING) &&
1501         (lwip_strnicmp(name, dns_table[i].name, sizeof(dns_table[i].name)) == 0)) {
1502 #if LWIP_IPV4 && LWIP_IPV6
1503       if (dns_table[i].reqaddrtype != dns_addrtype) {
1504         /* requested address types don't match
1505            this can lead to 2 concurrent requests, but mixing the address types
1506            for the same host should not be that common */
1507         continue;
1508       }
1509 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1510       /* this is a duplicate entry, find a free request entry */
1511       for (r = 0; r < DNS_MAX_REQUESTS; r++) {
1512         if (dns_requests[r].found == 0) {
1513           dns_requests[r].found = found;
1514           dns_requests[r].arg = callback_arg;
1515           dns_requests[r].dns_table_idx = i;
1516           LWIP_DNS_SET_ADDRTYPE(dns_requests[r].reqaddrtype, dns_addrtype);
1517           LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": duplicate request\n", name));
1518           return ERR_INPROGRESS;
1519         }
1520       }
1521     }
1522   }
1523   /* no duplicate entries found */
1524 #endif
1525 
1526   /* search an unused entry, or the oldest one */
1527   lseq = 0;
1528   lseqi = DNS_TABLE_SIZE;
1529   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
1530     entry = &dns_table[i];
1531     /* is it an unused entry ? */
1532     if (entry->state == DNS_STATE_UNUSED) {
1533       break;
1534     }
1535     /* check if this is the oldest completed entry */
1536     if (entry->state == DNS_STATE_DONE) {
1537       u8_t age = (u8_t)(dns_seqno - entry->seqno);
1538       if (age > lseq) {
1539         lseq = age;
1540         lseqi = i;
1541       }
1542     }
1543   }
1544 
1545   /* if we don't have found an unused entry, use the oldest completed one */
1546   if (i == DNS_TABLE_SIZE) {
1547     if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
1548       /* no entry can be used now, table is full */
1549       LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
1550       return ERR_MEM;
1551     } else {
1552       /* use the oldest completed one */
1553       i = lseqi;
1554       entry = &dns_table[i];
1555     }
1556   }
1557 
1558 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
1559   /* find a free request entry */
1560   req = NULL;
1561   for (r = 0; r < DNS_MAX_REQUESTS; r++) {
1562     if (dns_requests[r].found == NULL) {
1563       req = &dns_requests[r];
1564       break;
1565     }
1566   }
1567   if (req == NULL) {
1568     /* no request entry can be used now, table is full */
1569     LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS request entries table is full\n", name));
1570     return ERR_MEM;
1571   }
1572   req->dns_table_idx = i;
1573 #else
1574   /* in this configuration, the entry index is the same as the request index */
1575   req = &dns_requests[i];
1576 #endif
1577 
1578   /* use this entry */
1579   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
1580 
1581   /* fill the entry */
1582   entry->state = DNS_STATE_NEW;
1583   entry->seqno = dns_seqno;
1584   LWIP_DNS_SET_ADDRTYPE(entry->reqaddrtype, dns_addrtype);
1585   LWIP_DNS_SET_ADDRTYPE(req->reqaddrtype, dns_addrtype);
1586   req->found = found;
1587   req->arg   = callback_arg;
1588   namelen = LWIP_MIN(hostnamelen, DNS_MAX_NAME_LENGTH - 1);
1589   MEMCPY(entry->name, name, namelen);
1590   entry->name[namelen] = 0;
1591 
1592 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
1593   entry->pcb_idx = dns_alloc_pcb();
1594   if (entry->pcb_idx >= DNS_MAX_SOURCE_PORTS) {
1595     /* failed to get a UDP pcb */
1596     LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": failed to allocate a pcb\n", name));
1597     entry->state = DNS_STATE_UNUSED;
1598     req->found = NULL;
1599     return ERR_MEM;
1600   }
1601   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS pcb %"U16_F"\n", name, (u16_t)(entry->pcb_idx)));
1602 #endif
1603 
1604 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1605   entry->is_mdns = is_mdns;
1606 #endif
1607 
1608   dns_seqno++;
1609 
1610   /* force to send query without waiting timer */
1611   dns_check_entry(i);
1612 
1613   /* dns query is enqueued */
1614   return ERR_INPROGRESS;
1615 }
1616 
1617 /**
1618  * @ingroup dns
1619  * Resolve a hostname (string) into an IP address.
1620  * NON-BLOCKING callback version for use with raw API!!!
1621  *
1622  * Returns immediately with one of err_t return codes:
1623  * - ERR_OK if hostname is a valid IP address string or the host
1624  *   name is already in the local names table.
1625  * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
1626  *   for resolution if no errors are present.
1627  * - ERR_ARG: dns client not initialized or invalid hostname
1628  *
1629  * @param hostname the hostname that is to be queried
1630  * @param addr pointer to a ip_addr_t where to store the address if it is already
1631  *             cached in the dns_table (only valid if ERR_OK is returned!)
1632  * @param found a callback function to be called on success, failure or timeout (only if
1633  *              ERR_INPROGRESS is returned!)
1634  * @param callback_arg argument to pass to the callback function
1635  * @return a err_t return code.
1636  */
1637 err_t
dns_gethostbyname(const char * hostname,ip_addr_t * addr,dns_found_callback found,void * callback_arg)1638 dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found,
1639                   void *callback_arg)
1640 {
1641   return dns_gethostbyname_addrtype(hostname, addr, found, callback_arg, LWIP_DNS_ADDRTYPE_DEFAULT);
1642 }
1643 
1644 /**
1645  * @ingroup dns
1646  * Like dns_gethostbyname, but returned address type can be controlled:
1647  * @param hostname the hostname that is to be queried
1648  * @param addr pointer to a ip_addr_t where to store the address if it is already
1649  *             cached in the dns_table (only valid if ERR_OK is returned!)
1650  * @param found a callback function to be called on success, failure or timeout (only if
1651  *              ERR_INPROGRESS is returned!)
1652  * @param callback_arg argument to pass to the callback function
1653  * @param dns_addrtype - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 first, try IPv6 if IPv4 fails only
1654  *                     - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 first, try IPv4 if IPv6 fails only
1655  *                     - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
1656  *                     - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
1657  */
1658 err_t
dns_gethostbyname_addrtype(const char * hostname,ip_addr_t * addr,dns_found_callback found,void * callback_arg,u8_t dns_addrtype)1659 dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, dns_found_callback found,
1660                            void *callback_arg, u8_t dns_addrtype)
1661 {
1662   size_t hostnamelen;
1663 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1664   u8_t is_mdns;
1665 #endif
1666   /* not initialized or no valid server yet, or invalid addr pointer
1667    * or invalid hostname or invalid hostname length */
1668   if ((addr == NULL) ||
1669       (!hostname) || (!hostname[0])) {
1670     return ERR_ARG;
1671   }
1672 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
1673   if (dns_pcbs[0] == NULL) {
1674     return ERR_ARG;
1675   }
1676 #endif
1677   hostnamelen = strlen(hostname);
1678   if (hostnamelen >= DNS_MAX_NAME_LENGTH) {
1679     LWIP_DEBUGF(DNS_DEBUG, ("dns_gethostbyname: name too long to resolve"));
1680     return ERR_ARG;
1681   }
1682 
1683 
1684 #if LWIP_HAVE_LOOPIF
1685   if (strcmp(hostname, "localhost") == 0) {
1686     ip_addr_set_loopback(LWIP_DNS_ADDRTYPE_IS_IPV6(dns_addrtype), addr);
1687     return ERR_OK;
1688   }
1689 #endif /* LWIP_HAVE_LOOPIF */
1690 
1691   /* host name already in octet notation? set ip addr and return ERR_OK */
1692   if (ipaddr_aton(hostname, addr)) {
1693 #if LWIP_IPV4 && LWIP_IPV6
1694     if ((IP_IS_V6(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV4)) ||
1695         (IP_IS_V4(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV6)))
1696 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1697     {
1698       return ERR_OK;
1699     }
1700   }
1701   /* already have this address cached? */
1702   if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
1703     return ERR_OK;
1704   }
1705 #if LWIP_IPV4 && LWIP_IPV6
1706   if ((dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) || (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
1707     /* fallback to 2nd IP type and try again to lookup */
1708     u8_t fallback;
1709     if (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
1710       fallback = LWIP_DNS_ADDRTYPE_IPV6;
1711     } else {
1712       fallback = LWIP_DNS_ADDRTYPE_IPV4;
1713     }
1714     if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(fallback)) == ERR_OK) {
1715       return ERR_OK;
1716     }
1717   }
1718 #else /* LWIP_IPV4 && LWIP_IPV6 */
1719   LWIP_UNUSED_ARG(dns_addrtype);
1720 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1721 
1722 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1723   if (strstr(hostname, ".local") == &hostname[hostnamelen] - 6) {
1724     is_mdns = 1;
1725   } else {
1726     is_mdns = 0;
1727   }
1728 
1729   if (!is_mdns)
1730 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
1731   {
1732     /* prevent calling found callback if no server is set, return error instead */
1733     if (ip_addr_isany_val(dns_servers[0])) {
1734       return ERR_VAL;
1735     }
1736   }
1737 
1738   /* queue query with specified callback */
1739   return dns_enqueue(hostname, hostnamelen, found, callback_arg LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)
1740                      LWIP_DNS_ISMDNS_ARG(is_mdns));
1741 }
1742 
1743 #endif /* LWIP_DNS */
1744