Remove building with NOCRYPTO option
[minix3.git] / minix / lib / liblwip / dist / src / core / dns.c
blob4298889059f72495dd7c3ee2c5783582462ecb2d
1 /**
2 * @file
3 * DNS - host name to IP address resolver.
5 * @defgroup dns DNS
6 * @ingroup callbackstyle_api
8 * Implements a DNS host name to IP address resolver.
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.
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.
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).
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!
32 * All functions must be called from TCPIP thread.
34 * @see @ref netconn_common for thread-safe access.
38 * Port to lwIP from uIP
39 * by Jim Pettinato April 2007
41 * security fixes and more by Simon Goldschmidt
43 * uIP version Copyright (c) 2002-2003, Adam Dunkels.
44 * All rights reserved.
46 * Redistribution and use in source and binary forms, with or without
47 * modification, are permitted provided that the following conditions
48 * are met:
49 * 1. Redistributions of source code must retain the above copyright
50 * notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 * notice, this list of conditions and the following disclaimer in the
53 * documentation and/or other materials provided with the distribution.
54 * 3. The name of the author may not be used to endorse or promote
55 * products derived from this software without specific prior
56 * written permission.
58 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
59 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
60 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
62 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
64 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
65 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
66 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
67 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
68 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
71 /*-----------------------------------------------------------------------------
72 * RFC 1035 - Domain names - implementation and specification
73 * RFC 2181 - Clarifications to the DNS Specification
74 *----------------------------------------------------------------------------*/
76 /** @todo: define good default values (rfc compliance) */
77 /** @todo: improve answer parsing, more checkings... */
78 /** @todo: check RFC1035 - 7.3. Processing responses */
79 /** @todo: one-shot mDNS: dual-stack fallback to another IP version */
81 /*-----------------------------------------------------------------------------
82 * Includes
83 *----------------------------------------------------------------------------*/
85 #include "lwip/opt.h"
87 #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
89 #include "lwip/def.h"
90 #include "lwip/udp.h"
91 #include "lwip/mem.h"
92 #include "lwip/memp.h"
93 #include "lwip/dns.h"
94 #include "lwip/prot/dns.h"
96 #include <string.h>
98 /** Random generator function to create random TXIDs and source ports for queries */
99 #ifndef DNS_RAND_TXID
100 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_XID) != 0)
101 #define DNS_RAND_TXID LWIP_RAND
102 #else
103 static u16_t dns_txid;
104 #define DNS_RAND_TXID() (++dns_txid)
105 #endif
106 #endif
108 /** Limits the source port to be >= 1024 by default */
109 #ifndef DNS_PORT_ALLOWED
110 #define DNS_PORT_ALLOWED(port) ((port) >= 1024)
111 #endif
113 /** DNS maximum number of retries when asking for a name, before "timeout". */
114 #ifndef DNS_MAX_RETRIES
115 #define DNS_MAX_RETRIES 4
116 #endif
118 /** DNS resource record max. TTL (one week as default) */
119 #ifndef DNS_MAX_TTL
120 #define DNS_MAX_TTL 604800
121 #elif DNS_MAX_TTL > 0x7FFFFFFF
122 #error DNS_MAX_TTL must be a positive 32-bit value
123 #endif
125 #if DNS_TABLE_SIZE > 255
126 #error DNS_TABLE_SIZE must fit into an u8_t
127 #endif
128 #if DNS_MAX_SERVERS > 255
129 #error DNS_MAX_SERVERS must fit into an u8_t
130 #endif
132 /* The number of parallel requests (i.e. calls to dns_gethostbyname
133 * that cannot be answered from the DNS table.
134 * This is set to the table size by default.
136 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
137 #ifndef DNS_MAX_REQUESTS
138 #define DNS_MAX_REQUESTS DNS_TABLE_SIZE
139 #else
140 #if DNS_MAX_REQUESTS > 255
141 #error DNS_MAX_REQUESTS must fit into an u8_t
142 #endif
143 #endif
144 #else
145 /* In this configuration, both arrays have to have the same size and are used
146 * like one entry (used/free) */
147 #define DNS_MAX_REQUESTS DNS_TABLE_SIZE
148 #endif
150 /* The number of UDP source ports used in parallel */
151 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
152 #ifndef DNS_MAX_SOURCE_PORTS
153 #define DNS_MAX_SOURCE_PORTS DNS_MAX_REQUESTS
154 #else
155 #if DNS_MAX_SOURCE_PORTS > 255
156 #error DNS_MAX_SOURCE_PORTS must fit into an u8_t
157 #endif
158 #endif
159 #else
160 #ifdef DNS_MAX_SOURCE_PORTS
161 #undef DNS_MAX_SOURCE_PORTS
162 #endif
163 #define DNS_MAX_SOURCE_PORTS 1
164 #endif
166 #if LWIP_IPV4 && LWIP_IPV6
167 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) (((t) == LWIP_DNS_ADDRTYPE_IPV6_IPV4) || ((t) == LWIP_DNS_ADDRTYPE_IPV6))
168 #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)))
169 #define LWIP_DNS_ADDRTYPE_ARG(x) , x
170 #define LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(x) x
171 #define LWIP_DNS_SET_ADDRTYPE(x, y) do { x = y; } while(0)
172 #else
173 #if LWIP_IPV6
174 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) 1
175 #else
176 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) 0
177 #endif
178 #define LWIP_DNS_ADDRTYPE_MATCH_IP(t, ip) 1
179 #define LWIP_DNS_ADDRTYPE_ARG(x)
180 #define LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(x) 0
181 #define LWIP_DNS_SET_ADDRTYPE(x, y)
182 #endif /* LWIP_IPV4 && LWIP_IPV6 */
184 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
185 #define LWIP_DNS_ISMDNS_ARG(x) , x
186 #else
187 #define LWIP_DNS_ISMDNS_ARG(x)
188 #endif
190 /** DNS query message structure.
191 No packing needed: only used locally on the stack. */
192 struct dns_query {
193 /* DNS query record starts with either a domain name or a pointer
194 to a name already present somewhere in the packet. */
195 u16_t type;
196 u16_t cls;
198 #define SIZEOF_DNS_QUERY 4
200 /** DNS answer message structure.
201 No packing needed: only used locally on the stack. */
202 struct dns_answer {
203 /* DNS answer record starts with either a domain name or a pointer
204 to a name already present somewhere in the packet. */
205 u16_t type;
206 u16_t cls;
207 u32_t ttl;
208 u16_t len;
210 #define SIZEOF_DNS_ANSWER 10
211 /* maximum allowed size for the struct due to non-packed */
212 #define SIZEOF_DNS_ANSWER_ASSERT 12
214 /* DNS table entry states */
215 typedef enum {
216 DNS_STATE_UNUSED = 0,
217 DNS_STATE_NEW = 1,
218 DNS_STATE_ASKING = 2,
219 DNS_STATE_DONE = 3
220 } dns_state_enum_t;
222 /** DNS table entry */
223 struct dns_table_entry {
224 u32_t ttl;
225 ip_addr_t ipaddr;
226 u16_t txid;
227 u8_t state;
228 u8_t server_idx;
229 u8_t tmr;
230 u8_t retries;
231 u8_t seqno;
232 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
233 u8_t pcb_idx;
234 #endif
235 char name[DNS_MAX_NAME_LENGTH];
236 #if LWIP_IPV4 && LWIP_IPV6
237 u8_t reqaddrtype;
238 #endif /* LWIP_IPV4 && LWIP_IPV6 */
239 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
240 u8_t is_mdns;
241 #endif
244 /** DNS request table entry: used when dns_gehostbyname cannot answer the
245 * request from the DNS table */
246 struct dns_req_entry {
247 /* pointer to callback on DNS query done */
248 dns_found_callback found;
249 /* argument passed to the callback function */
250 void *arg;
251 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
252 u8_t dns_table_idx;
253 #endif
254 #if LWIP_IPV4 && LWIP_IPV6
255 u8_t reqaddrtype;
256 #endif /* LWIP_IPV4 && LWIP_IPV6 */
259 #if DNS_LOCAL_HOSTLIST
261 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
262 /** Local host-list. For hostnames in this list, no
263 * external name resolution is performed */
264 static struct local_hostlist_entry *local_hostlist_dynamic;
265 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
267 /** Defining this allows the local_hostlist_static to be placed in a different
268 * linker section (e.g. FLASH) */
269 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE
270 #define DNS_LOCAL_HOSTLIST_STORAGE_PRE static
271 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */
272 /** Defining this allows the local_hostlist_static to be placed in a different
273 * linker section (e.g. FLASH) */
274 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST
275 #define DNS_LOCAL_HOSTLIST_STORAGE_POST
276 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */
277 DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[]
278 DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT;
280 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
282 static void dns_init_local(void);
283 static err_t dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype));
284 #endif /* DNS_LOCAL_HOSTLIST */
287 /* forward declarations */
288 static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port);
289 static void dns_check_entries(void);
290 static void dns_call_found(u8_t idx, ip_addr_t* addr);
292 /*-----------------------------------------------------------------------------
293 * Globals
294 *----------------------------------------------------------------------------*/
296 /* DNS variables */
297 static struct udp_pcb *dns_pcbs[DNS_MAX_SOURCE_PORTS];
298 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
299 static u8_t dns_last_pcb_idx;
300 #endif
301 static u8_t dns_seqno;
302 static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
303 static struct dns_req_entry dns_requests[DNS_MAX_REQUESTS];
304 static ip_addr_t dns_servers[DNS_MAX_SERVERS];
306 #if LWIP_IPV4
307 const ip_addr_t dns_mquery_v4group = DNS_MQUERY_IPV4_GROUP_INIT;
308 #endif /* LWIP_IPV4 */
309 #if LWIP_IPV6
310 const ip_addr_t dns_mquery_v6group = DNS_MQUERY_IPV6_GROUP_INIT;
311 #endif /* LWIP_IPV6 */
314 * Initialize the resolver: set up the UDP pcb and configure the default server
315 * (if DNS_SERVER_ADDRESS is set).
317 void
318 dns_init(void)
320 #ifdef DNS_SERVER_ADDRESS
321 /* initialize default DNS server address */
322 ip_addr_t dnsserver;
323 DNS_SERVER_ADDRESS(&dnsserver);
324 dns_setserver(0, &dnsserver);
325 #endif /* DNS_SERVER_ADDRESS */
327 LWIP_ASSERT("sanity check SIZEOF_DNS_QUERY",
328 sizeof(struct dns_query) == SIZEOF_DNS_QUERY);
329 LWIP_ASSERT("sanity check SIZEOF_DNS_ANSWER",
330 sizeof(struct dns_answer) <= SIZEOF_DNS_ANSWER_ASSERT);
332 LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
334 /* if dns client not yet initialized... */
335 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
336 if (dns_pcbs[0] == NULL) {
337 dns_pcbs[0] = udp_new_ip_type(IPADDR_TYPE_ANY);
338 LWIP_ASSERT("dns_pcbs[0] != NULL", dns_pcbs[0] != NULL);
340 /* initialize DNS table not needed (initialized to zero since it is a
341 * global variable) */
342 LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0",
343 DNS_STATE_UNUSED == 0);
345 /* initialize DNS client */
346 udp_bind(dns_pcbs[0], IP_ANY_TYPE, 0);
347 udp_recv(dns_pcbs[0], dns_recv, NULL);
349 #endif
351 #if DNS_LOCAL_HOSTLIST
352 dns_init_local();
353 #endif
357 * @ingroup dns
358 * Initialize one of the DNS servers.
360 * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS
361 * @param dnsserver IP address of the DNS server to set
363 void
364 dns_setserver(u8_t numdns, const ip_addr_t *dnsserver)
366 if (numdns < DNS_MAX_SERVERS) {
367 if (dnsserver != NULL) {
368 dns_servers[numdns] = (*dnsserver);
369 } else {
370 dns_servers[numdns] = *IP_ADDR_ANY;
376 * @ingroup dns
377 * Obtain one of the currently configured DNS server.
379 * @param numdns the index of the DNS server
380 * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS
381 * server has not been configured.
383 const ip_addr_t*
384 dns_getserver(u8_t numdns)
386 if (numdns < DNS_MAX_SERVERS) {
387 return &dns_servers[numdns];
388 } else {
389 return IP_ADDR_ANY;
394 * The DNS resolver client timer - handle retries and timeouts and should
395 * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
397 void
398 dns_tmr(void)
400 LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
401 dns_check_entries();
404 #if DNS_LOCAL_HOSTLIST
405 static void
406 dns_init_local(void)
408 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
409 size_t i;
410 struct local_hostlist_entry *entry;
411 /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */
412 struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT;
413 size_t namelen;
414 for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_init); i++) {
415 struct local_hostlist_entry *init_entry = &local_hostlist_init[i];
416 LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL);
417 namelen = strlen(init_entry->name);
418 LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
419 entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
420 LWIP_ASSERT("mem-error in dns_init_local", entry != NULL);
421 if (entry != NULL) {
422 char* entry_name = (char*)entry + sizeof(struct local_hostlist_entry);
423 MEMCPY(entry_name, init_entry->name, namelen);
424 entry_name[namelen] = 0;
425 entry->name = entry_name;
426 entry->addr = init_entry->addr;
427 entry->next = local_hostlist_dynamic;
428 local_hostlist_dynamic = entry;
431 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
435 * @ingroup dns
436 * Iterate the local host-list for a hostname.
438 * @param iterator_fn a function that is called for every entry in the local host-list
439 * @param iterator_arg 3rd argument passed to iterator_fn
440 * @return the number of entries in the local host-list
442 size_t
443 dns_local_iterate(dns_found_callback iterator_fn, void *iterator_arg)
445 size_t i;
446 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
447 struct local_hostlist_entry *entry = local_hostlist_dynamic;
448 i = 0;
449 while (entry != NULL) {
450 if (iterator_fn != NULL) {
451 iterator_fn(entry->name, &entry->addr, iterator_arg);
453 i++;
454 entry = entry->next;
456 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
457 for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_static); i++) {
458 if (iterator_fn != NULL) {
459 iterator_fn(local_hostlist_static[i].name, &local_hostlist_static[i].addr, iterator_arg);
462 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
463 return i;
467 * @ingroup dns
468 * Scans the local host-list for a hostname.
470 * @param hostname Hostname to look for in the local host-list
471 * @param addr the first IP address for the hostname in the local host-list or
472 * IPADDR_NONE if not found.
473 * @param dns_addrtype - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 (ATTENTION: no fallback here!)
474 * - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 (ATTENTION: no fallback here!)
475 * - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
476 * - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
477 * @return ERR_OK if found, ERR_ARG if not found
479 err_t
480 dns_local_lookup(const char *hostname, ip_addr_t *addr, u8_t dns_addrtype)
482 LWIP_UNUSED_ARG(dns_addrtype);
483 return dns_lookup_local(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype));
486 /* Internal implementation for dns_local_lookup and dns_lookup */
487 static err_t
488 dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
490 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
491 struct local_hostlist_entry *entry = local_hostlist_dynamic;
492 while (entry != NULL) {
493 if ((lwip_stricmp(entry->name, hostname) == 0) &&
494 LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, entry->addr)) {
495 if (addr) {
496 ip_addr_copy(*addr, entry->addr);
498 return ERR_OK;
500 entry = entry->next;
502 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
503 size_t i;
504 for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_static); i++) {
505 if ((lwip_stricmp(local_hostlist_static[i].name, hostname) == 0) &&
506 LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, local_hostlist_static[i].addr)) {
507 if (addr) {
508 ip_addr_copy(*addr, local_hostlist_static[i].addr);
510 return ERR_OK;
513 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
514 return ERR_ARG;
517 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
519 * @ingroup dns
520 * Remove all entries from the local host-list for a specific hostname
521 * and/or IP address
523 * @param hostname hostname for which entries shall be removed from the local
524 * host-list
525 * @param addr address for which entries shall be removed from the local host-list
526 * @return the number of removed entries
529 dns_local_removehost(const char *hostname, const ip_addr_t *addr)
531 int removed = 0;
532 struct local_hostlist_entry *entry = local_hostlist_dynamic;
533 struct local_hostlist_entry *last_entry = NULL;
534 while (entry != NULL) {
535 if (((hostname == NULL) || !lwip_stricmp(entry->name, hostname)) &&
536 ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
537 struct local_hostlist_entry *free_entry;
538 if (last_entry != NULL) {
539 last_entry->next = entry->next;
540 } else {
541 local_hostlist_dynamic = entry->next;
543 free_entry = entry;
544 entry = entry->next;
545 memp_free(MEMP_LOCALHOSTLIST, free_entry);
546 removed++;
547 } else {
548 last_entry = entry;
549 entry = entry->next;
552 return removed;
556 * @ingroup dns
557 * Add a hostname/IP address pair to the local host-list.
558 * Duplicates are not checked.
560 * @param hostname hostname of the new entry
561 * @param addr IP address of the new entry
562 * @return ERR_OK if succeeded or ERR_MEM on memory error
564 err_t
565 dns_local_addhost(const char *hostname, const ip_addr_t *addr)
567 struct local_hostlist_entry *entry;
568 size_t namelen;
569 char* entry_name;
570 LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
571 namelen = strlen(hostname);
572 LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
573 entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
574 if (entry == NULL) {
575 return ERR_MEM;
577 entry_name = (char*)entry + sizeof(struct local_hostlist_entry);
578 MEMCPY(entry_name, hostname, namelen);
579 entry_name[namelen] = 0;
580 entry->name = entry_name;
581 ip_addr_copy(entry->addr, *addr);
582 entry->next = local_hostlist_dynamic;
583 local_hostlist_dynamic = entry;
584 return ERR_OK;
586 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
587 #endif /* DNS_LOCAL_HOSTLIST */
590 * @ingroup dns
591 * Look up a hostname in the array of known hostnames.
593 * @note This function only looks in the internal array of known
594 * hostnames, it does not send out a query for the hostname if none
595 * was found. The function dns_enqueue() can be used to send a query
596 * for a hostname.
598 * @param name the hostname to look up
599 * @param addr the hostname's IP address, as u32_t (instead of ip_addr_t to
600 * better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname
601 * was not found in the cached dns_table.
602 * @return ERR_OK if found, ERR_ARG if not found
604 static err_t
605 dns_lookup(const char *name, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
607 u8_t i;
608 #if DNS_LOCAL_HOSTLIST
609 if (dns_lookup_local(name, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
610 return ERR_OK;
612 #endif /* DNS_LOCAL_HOSTLIST */
613 #ifdef DNS_LOOKUP_LOCAL_EXTERN
614 if (DNS_LOOKUP_LOCAL_EXTERN(name, addr, LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(dns_addrtype)) == ERR_OK) {
615 return ERR_OK;
617 #endif /* DNS_LOOKUP_LOCAL_EXTERN */
619 /* Walk through name list, return entry if found. If not, return NULL. */
620 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
621 if ((dns_table[i].state == DNS_STATE_DONE) &&
622 (lwip_strnicmp(name, dns_table[i].name, sizeof(dns_table[i].name)) == 0) &&
623 LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, dns_table[i].ipaddr)) {
624 LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
625 ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
626 LWIP_DEBUGF(DNS_DEBUG, ("\n"));
627 if (addr) {
628 ip_addr_copy(*addr, dns_table[i].ipaddr);
630 return ERR_OK;
634 return ERR_ARG;
638 * Compare the "dotted" name "query" with the encoded name "response"
639 * to make sure an answer from the DNS server matches the current dns_table
640 * entry (otherwise, answers might arrive late for hostname not on the list
641 * any more).
643 * @param query hostname (not encoded) from the dns_table
644 * @param p pbuf containing the encoded hostname in the DNS response
645 * @param start_offset offset into p where the name starts
646 * @return 0xFFFF: names differ, other: names equal -> offset behind name
648 static u16_t
649 dns_compare_name(const char *query, struct pbuf* p, u16_t start_offset)
651 int n;
652 u16_t response_offset = start_offset;
654 do {
655 n = pbuf_try_get_at(p, response_offset++);
656 if (n < 0) {
657 return 0xFFFF;
659 /** @see RFC 1035 - 4.1.4. Message compression */
660 if ((n & 0xc0) == 0xc0) {
661 /* Compressed name: cannot be equal since we don't send them */
662 return 0xFFFF;
663 } else {
664 /* Not compressed name */
665 while (n > 0) {
666 int c = pbuf_try_get_at(p, response_offset);
667 if (c < 0) {
668 return 0xFFFF;
670 if ((*query) != (u8_t)c) {
671 return 0xFFFF;
673 ++response_offset;
674 ++query;
675 --n;
677 ++query;
679 n = pbuf_try_get_at(p, response_offset);
680 if (n < 0) {
681 return 0xFFFF;
683 } while (n != 0);
685 return response_offset + 1;
689 * Walk through a compact encoded DNS name and return the end of the name.
691 * @param p pbuf containing the name
692 * @param query_idx start index into p pointing to encoded DNS name in the DNS server response
693 * @return index to end of the name
695 static u16_t
696 dns_skip_name(struct pbuf* p, u16_t query_idx)
698 int n;
699 u16_t offset = query_idx;
701 do {
702 n = pbuf_try_get_at(p, offset++);
703 if (n < 0) {
704 return 0xFFFF;
706 /** @see RFC 1035 - 4.1.4. Message compression */
707 if ((n & 0xc0) == 0xc0) {
708 /* Compressed name: since we only want to skip it (not check it), stop here */
709 break;
710 } else {
711 /* Not compressed name */
712 if (offset + n >= p->tot_len) {
713 return 0xFFFF;
715 offset = (u16_t)(offset + n);
717 n = pbuf_try_get_at(p, offset);
718 if (n < 0) {
719 return 0xFFFF;
721 } while (n != 0);
723 return offset + 1;
727 * Send a DNS query packet.
729 * @param idx the DNS table entry index for which to send a request
730 * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
732 static err_t
733 dns_send(u8_t idx)
735 err_t err;
736 struct dns_hdr hdr;
737 struct dns_query qry;
738 struct pbuf *p;
739 u16_t query_idx, copy_len;
740 const char *hostname, *hostname_part;
741 u8_t n;
742 u8_t pcb_idx;
743 struct dns_table_entry* entry = &dns_table[idx];
745 LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
746 (u16_t)(entry->server_idx), entry->name));
747 LWIP_ASSERT("dns server out of array", entry->server_idx < DNS_MAX_SERVERS);
748 if (ip_addr_isany_val(dns_servers[entry->server_idx])
749 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
750 && !entry->is_mdns
751 #endif
753 /* DNS server not valid anymore, e.g. PPP netif has been shut down */
754 /* call specified callback function if provided */
755 dns_call_found(idx, NULL);
756 /* flush this entry */
757 entry->state = DNS_STATE_UNUSED;
758 return ERR_OK;
761 /* if here, we have either a new query or a retry on a previous query to process */
762 p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(SIZEOF_DNS_HDR + strlen(entry->name) + 2 +
763 SIZEOF_DNS_QUERY), PBUF_RAM);
764 if (p != NULL) {
765 const ip_addr_t* dst;
766 u16_t dst_port;
767 /* fill dns header */
768 memset(&hdr, 0, SIZEOF_DNS_HDR);
769 hdr.id = lwip_htons(entry->txid);
770 hdr.flags1 = DNS_FLAG1_RD;
771 hdr.numquestions = PP_HTONS(1);
772 pbuf_take(p, &hdr, SIZEOF_DNS_HDR);
773 hostname = entry->name;
774 --hostname;
776 /* convert hostname into suitable query format. */
777 query_idx = SIZEOF_DNS_HDR;
778 do {
779 ++hostname;
780 hostname_part = hostname;
781 for (n = 0; *hostname != '.' && *hostname != 0; ++hostname) {
782 ++n;
784 copy_len = (u16_t)(hostname - hostname_part);
785 pbuf_put_at(p, query_idx, n);
786 pbuf_take_at(p, hostname_part, copy_len, query_idx + 1);
787 query_idx += n + 1;
788 } while (*hostname != 0);
789 pbuf_put_at(p, query_idx, 0);
790 query_idx++;
792 /* fill dns query */
793 if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype)) {
794 qry.type = PP_HTONS(DNS_RRTYPE_AAAA);
795 } else {
796 qry.type = PP_HTONS(DNS_RRTYPE_A);
798 qry.cls = PP_HTONS(DNS_RRCLASS_IN);
799 pbuf_take_at(p, &qry, SIZEOF_DNS_QUERY, query_idx);
801 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
802 pcb_idx = entry->pcb_idx;
803 #else
804 pcb_idx = 0;
805 #endif
806 /* send dns packet */
807 LWIP_DEBUGF(DNS_DEBUG, ("sending DNS request ID %d for name \"%s\" to server %d\r\n",
808 entry->txid, entry->name, entry->server_idx));
809 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
810 if (entry->is_mdns) {
811 dst_port = DNS_MQUERY_PORT;
812 #if LWIP_IPV6
813 if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
815 dst = &dns_mquery_v6group;
817 #endif
818 #if LWIP_IPV4 && LWIP_IPV6
819 else
820 #endif
821 #if LWIP_IPV4
823 dst = &dns_mquery_v4group;
825 #endif
826 } else
827 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
829 dst_port = DNS_SERVER_PORT;
830 dst = &dns_servers[entry->server_idx];
832 err = udp_sendto(dns_pcbs[pcb_idx], p, dst, dst_port);
834 /* free pbuf */
835 pbuf_free(p);
836 } else {
837 err = ERR_MEM;
840 return err;
843 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
844 static struct udp_pcb*
845 dns_alloc_random_port(void)
847 err_t err;
848 struct udp_pcb* pcb;
850 pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
851 if (pcb == NULL) {
852 /* out of memory, have to reuse an existing pcb */
853 return NULL;
855 do {
856 u16_t port = (u16_t)DNS_RAND_TXID();
857 if (DNS_PORT_ALLOWED(port)) {
858 err = udp_bind(pcb, IP_ANY_TYPE, port);
859 } else {
860 /* this port is not allowed, try again */
861 err = ERR_USE;
863 } while (err == ERR_USE);
864 if (err != ERR_OK) {
865 udp_remove(pcb);
866 return NULL;
868 udp_recv(pcb, dns_recv, NULL);
869 return pcb;
873 * dns_alloc_pcb() - allocates a new pcb (or reuses an existing one) to be used
874 * for sending a request
876 * @return an index into dns_pcbs
878 static u8_t
879 dns_alloc_pcb(void)
881 u8_t i;
882 u8_t idx;
884 for (i = 0; i < DNS_MAX_SOURCE_PORTS; i++) {
885 if (dns_pcbs[i] == NULL) {
886 break;
889 if (i < DNS_MAX_SOURCE_PORTS) {
890 dns_pcbs[i] = dns_alloc_random_port();
891 if (dns_pcbs[i] != NULL) {
892 /* succeeded */
893 dns_last_pcb_idx = i;
894 return i;
897 /* if we come here, creating a new UDP pcb failed, so we have to use
898 an already existing one */
899 for (i = 0, idx = dns_last_pcb_idx + 1; i < DNS_MAX_SOURCE_PORTS; i++, idx++) {
900 if (idx >= DNS_MAX_SOURCE_PORTS) {
901 idx = 0;
903 if (dns_pcbs[idx] != NULL) {
904 dns_last_pcb_idx = idx;
905 return idx;
908 return DNS_MAX_SOURCE_PORTS;
910 #endif /* ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0) */
913 * dns_call_found() - call the found callback and check if there are duplicate
914 * entries for the given hostname. If there are any, their found callback will
915 * be called and they will be removed.
917 * @param idx dns table index of the entry that is resolved or removed
918 * @param addr IP address for the hostname (or NULL on error or memory shortage)
920 static void
921 dns_call_found(u8_t idx, ip_addr_t* addr)
923 #if ((LWIP_DNS_SECURE & (LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT)) != 0)
924 u8_t i;
925 #endif
927 #if LWIP_IPV4 && LWIP_IPV6
928 if (addr != NULL) {
929 /* check that address type matches the request and adapt the table entry */
930 if (IP_IS_V6_VAL(*addr)) {
931 LWIP_ASSERT("invalid response", LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
932 dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
933 } else {
934 LWIP_ASSERT("invalid response", !LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
935 dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
938 #endif /* LWIP_IPV4 && LWIP_IPV6 */
940 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
941 for (i = 0; i < DNS_MAX_REQUESTS; i++) {
942 if (dns_requests[i].found && (dns_requests[i].dns_table_idx == idx)) {
943 (*dns_requests[i].found)(dns_table[idx].name, addr, dns_requests[i].arg);
944 /* flush this entry */
945 dns_requests[i].found = NULL;
948 #else
949 if (dns_requests[idx].found) {
950 (*dns_requests[idx].found)(dns_table[idx].name, addr, dns_requests[idx].arg);
952 dns_requests[idx].found = NULL;
953 #endif
954 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
955 /* close the pcb used unless other request are using it */
956 for (i = 0; i < DNS_MAX_REQUESTS; i++) {
957 if (i == idx) {
958 continue; /* only check other requests */
960 if (dns_table[i].state == DNS_STATE_ASKING) {
961 if (dns_table[i].pcb_idx == dns_table[idx].pcb_idx) {
962 /* another request is still using the same pcb */
963 dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
964 break;
968 if (dns_table[idx].pcb_idx < DNS_MAX_SOURCE_PORTS) {
969 /* if we come here, the pcb is not used any more and can be removed */
970 udp_remove(dns_pcbs[dns_table[idx].pcb_idx]);
971 dns_pcbs[dns_table[idx].pcb_idx] = NULL;
972 dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
974 #endif
977 /* Create a query transmission ID that is unique for all outstanding queries */
978 static u16_t
979 dns_create_txid(void)
981 u16_t txid;
982 u8_t i;
984 again:
985 txid = (u16_t)DNS_RAND_TXID();
987 /* check whether the ID is unique */
988 for (i = 0; i < DNS_TABLE_SIZE; i++) {
989 if ((dns_table[i].state == DNS_STATE_ASKING) &&
990 (dns_table[i].txid == txid)) {
991 /* ID already used by another pending query */
992 goto again;
996 return txid;
1000 * dns_check_entry() - see if entry has not yet been queried and, if so, sends out a query.
1001 * Check an entry in the dns_table:
1002 * - send out query for new entries
1003 * - retry old pending entries on timeout (also with different servers)
1004 * - remove completed entries from the table if their TTL has expired
1006 * @param i index of the dns_table entry to check
1008 static void
1009 dns_check_entry(u8_t i)
1011 err_t err;
1012 struct dns_table_entry *entry = &dns_table[i];
1014 LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
1016 switch (entry->state) {
1017 case DNS_STATE_NEW:
1018 /* initialize new entry */
1019 entry->txid = dns_create_txid();
1020 entry->state = DNS_STATE_ASKING;
1021 entry->server_idx = 0;
1022 entry->tmr = 1;
1023 entry->retries = 0;
1025 /* send DNS packet for this entry */
1026 err = dns_send(i);
1027 if (err != ERR_OK) {
1028 LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
1029 ("dns_send returned error: %s\n", lwip_strerr(err)));
1031 break;
1032 case DNS_STATE_ASKING:
1033 if (--entry->tmr == 0) {
1034 if (++entry->retries == DNS_MAX_RETRIES) {
1035 if ((entry->server_idx + 1 < DNS_MAX_SERVERS) && !ip_addr_isany_val(dns_servers[entry->server_idx + 1])
1036 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1037 && !entry->is_mdns
1038 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
1040 /* change of server */
1041 entry->server_idx++;
1042 entry->tmr = 1;
1043 entry->retries = 0;
1044 } else {
1045 LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", entry->name));
1046 /* call specified callback function if provided */
1047 dns_call_found(i, NULL);
1048 /* flush this entry */
1049 entry->state = DNS_STATE_UNUSED;
1050 break;
1052 } else {
1053 /* wait longer for the next retry */
1054 entry->tmr = entry->retries;
1057 /* send DNS packet for this entry */
1058 err = dns_send(i);
1059 if (err != ERR_OK) {
1060 LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
1061 ("dns_send returned error: %s\n", lwip_strerr(err)));
1064 break;
1065 case DNS_STATE_DONE:
1066 /* if the time to live is nul */
1067 if ((entry->ttl == 0) || (--entry->ttl == 0)) {
1068 LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", entry->name));
1069 /* flush this entry, there cannot be any related pending entries in this state */
1070 entry->state = DNS_STATE_UNUSED;
1072 break;
1073 case DNS_STATE_UNUSED:
1074 /* nothing to do */
1075 break;
1076 default:
1077 LWIP_ASSERT("unknown dns_table entry state:", 0);
1078 break;
1083 * Call dns_check_entry for each entry in dns_table - check all entries.
1085 static void
1086 dns_check_entries(void)
1088 u8_t i;
1090 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
1091 dns_check_entry(i);
1096 * Save TTL and call dns_call_found for correct response.
1098 static void
1099 dns_correct_response(u8_t idx, u32_t ttl)
1101 struct dns_table_entry *entry = &dns_table[idx];
1103 entry->state = DNS_STATE_DONE;
1105 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", entry->name));
1106 ip_addr_debug_print(DNS_DEBUG, (&(entry->ipaddr)));
1107 LWIP_DEBUGF(DNS_DEBUG, ("\n"));
1109 /* read the answer resource record's TTL, and maximize it if needed */
1110 entry->ttl = ttl;
1111 if (entry->ttl > DNS_MAX_TTL) {
1112 entry->ttl = DNS_MAX_TTL;
1114 dns_call_found(idx, &entry->ipaddr);
1116 if (entry->ttl == 0) {
1117 /* RFC 883, page 29: "Zero values are
1118 interpreted to mean that the RR can only be used for the
1119 transaction in progress, and should not be cached."
1120 -> flush this entry now */
1121 /* entry reused during callback? */
1122 if (entry->state == DNS_STATE_DONE) {
1123 entry->state = DNS_STATE_UNUSED;
1128 * Receive input function for DNS response packets arriving for the dns UDP pcb.
1130 static void
1131 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
1133 u8_t i;
1134 u16_t txid;
1135 u16_t res_idx;
1136 struct dns_hdr hdr;
1137 struct dns_answer ans;
1138 struct dns_query qry;
1139 u16_t nquestions, nanswers;
1141 LWIP_UNUSED_ARG(arg);
1142 LWIP_UNUSED_ARG(pcb);
1143 LWIP_UNUSED_ARG(port);
1145 /* is the dns message big enough ? */
1146 if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY)) {
1147 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
1148 /* free pbuf and return */
1149 goto memerr;
1152 /* copy dns payload inside static buffer for processing */
1153 if (pbuf_copy_partial(p, &hdr, SIZEOF_DNS_HDR, 0) == SIZEOF_DNS_HDR) {
1154 /* Match the ID in the DNS header with the name table. */
1155 txid = lwip_htons(hdr.id);
1156 for (i = 0; i < DNS_TABLE_SIZE; i++) {
1157 const struct dns_table_entry *entry = &dns_table[i];
1158 if ((entry->state == DNS_STATE_ASKING) &&
1159 (entry->txid == txid)) {
1161 /* We only care about the question(s) and the answers. The authrr
1162 and the extrarr are simply discarded. */
1163 nquestions = lwip_htons(hdr.numquestions);
1164 nanswers = lwip_htons(hdr.numanswers);
1166 /* Check for correct response. */
1167 if ((hdr.flags1 & DNS_FLAG1_RESPONSE) == 0) {
1168 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": not a response\n", entry->name));
1169 goto memerr; /* ignore this packet */
1171 if (nquestions != 1) {
1172 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
1173 goto memerr; /* ignore this packet */
1176 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1177 if (!entry->is_mdns)
1178 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
1180 /* Check whether response comes from the same network address to which the
1181 question was sent. (RFC 5452) */
1182 if (!ip_addr_cmp(addr, &dns_servers[entry->server_idx])) {
1183 goto memerr; /* ignore this packet */
1187 /* Check if the name in the "question" part match with the name in the entry and
1188 skip it if equal. */
1189 res_idx = dns_compare_name(entry->name, p, SIZEOF_DNS_HDR);
1190 if (res_idx == 0xFFFF) {
1191 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
1192 goto memerr; /* ignore this packet */
1195 /* check if "question" part matches the request */
1196 if (pbuf_copy_partial(p, &qry, SIZEOF_DNS_QUERY, res_idx) != SIZEOF_DNS_QUERY) {
1197 goto memerr; /* ignore this packet */
1199 if ((qry.cls != PP_HTONS(DNS_RRCLASS_IN)) ||
1200 (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_AAAA))) ||
1201 (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_A)))) {
1202 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
1203 goto memerr; /* ignore this packet */
1205 /* skip the rest of the "question" part */
1206 res_idx += SIZEOF_DNS_QUERY;
1208 /* Check for error. If so, call callback to inform. */
1209 if (hdr.flags2 & DNS_FLAG2_ERR_MASK) {
1210 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", entry->name));
1211 } else {
1212 while ((nanswers > 0) && (res_idx < p->tot_len)) {
1213 /* skip answer resource record's host name */
1214 res_idx = dns_skip_name(p, res_idx);
1215 if (res_idx == 0xFFFF) {
1216 goto memerr; /* ignore this packet */
1219 /* Check for IP address type and Internet class. Others are discarded. */
1220 if (pbuf_copy_partial(p, &ans, SIZEOF_DNS_ANSWER, res_idx) != SIZEOF_DNS_ANSWER) {
1221 goto memerr; /* ignore this packet */
1223 res_idx += SIZEOF_DNS_ANSWER;
1225 if (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) {
1226 #if LWIP_IPV4
1227 if ((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.len == PP_HTONS(sizeof(ip4_addr_t)))) {
1228 #if LWIP_IPV4 && LWIP_IPV6
1229 if (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
1230 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1232 ip4_addr_t ip4addr;
1233 /* read the IP address after answer resource record's header */
1234 if (pbuf_copy_partial(p, &ip4addr, sizeof(ip4_addr_t), res_idx) != sizeof(ip4_addr_t)) {
1235 goto memerr; /* ignore this packet */
1237 ip_addr_copy_from_ip4(dns_table[i].ipaddr, ip4addr);
1238 pbuf_free(p);
1239 /* handle correct response */
1240 dns_correct_response(i, lwip_ntohl(ans.ttl));
1241 return;
1244 #endif /* LWIP_IPV4 */
1245 #if LWIP_IPV6
1246 if ((ans.type == PP_HTONS(DNS_RRTYPE_AAAA)) && (ans.len == PP_HTONS(sizeof(ip6_addr_t)))) {
1247 #if LWIP_IPV4 && LWIP_IPV6
1248 if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
1249 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1251 ip6_addr_t ip6addr;
1252 /* read the IP address after answer resource record's header */
1253 if (pbuf_copy_partial(p, &ip6addr, sizeof(ip6_addr_t), res_idx) != sizeof(ip6_addr_t)) {
1254 goto memerr; /* ignore this packet */
1256 ip_addr_copy_from_ip6(dns_table[i].ipaddr, ip6addr);
1257 pbuf_free(p);
1258 /* handle correct response */
1259 dns_correct_response(i, lwip_ntohl(ans.ttl));
1260 return;
1263 #endif /* LWIP_IPV6 */
1265 /* skip this answer */
1266 if ((int)(res_idx + lwip_htons(ans.len)) > 0xFFFF) {
1267 goto memerr; /* ignore this packet */
1269 res_idx += lwip_htons(ans.len);
1270 --nanswers;
1272 #if LWIP_IPV4 && LWIP_IPV6
1273 if ((entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) ||
1274 (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
1275 if (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
1276 /* IPv4 failed, try IPv6 */
1277 dns_table[i].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
1278 } else {
1279 /* IPv6 failed, try IPv4 */
1280 dns_table[i].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
1282 pbuf_free(p);
1283 dns_table[i].state = DNS_STATE_NEW;
1284 dns_check_entry(i);
1285 return;
1287 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1288 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", entry->name));
1290 /* call callback to indicate error, clean up memory and return */
1291 pbuf_free(p);
1292 dns_call_found(i, NULL);
1293 dns_table[i].state = DNS_STATE_UNUSED;
1294 return;
1299 memerr:
1300 /* deallocate memory and return */
1301 pbuf_free(p);
1302 return;
1306 * Queues a new hostname to resolve and sends out a DNS query for that hostname
1308 * @param name the hostname that is to be queried
1309 * @param hostnamelen length of the hostname
1310 * @param found a callback function to be called on success, failure or timeout
1311 * @param callback_arg argument to pass to the callback function
1312 * @return err_t return code.
1314 static err_t
1315 dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
1316 void *callback_arg LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype) LWIP_DNS_ISMDNS_ARG(u8_t is_mdns))
1318 u8_t i;
1319 u8_t lseq, lseqi;
1320 struct dns_table_entry *entry = NULL;
1321 size_t namelen;
1322 struct dns_req_entry* req;
1324 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
1325 u8_t r;
1326 /* check for duplicate entries */
1327 for (i = 0; i < DNS_TABLE_SIZE; i++) {
1328 if ((dns_table[i].state == DNS_STATE_ASKING) &&
1329 (lwip_strnicmp(name, dns_table[i].name, sizeof(dns_table[i].name)) == 0)) {
1330 #if LWIP_IPV4 && LWIP_IPV6
1331 if (dns_table[i].reqaddrtype != dns_addrtype) {
1332 /* requested address types don't match
1333 this can lead to 2 concurrent requests, but mixing the address types
1334 for the same host should not be that common */
1335 continue;
1337 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1338 /* this is a duplicate entry, find a free request entry */
1339 for (r = 0; r < DNS_MAX_REQUESTS; r++) {
1340 if (dns_requests[r].found == 0) {
1341 dns_requests[r].found = found;
1342 dns_requests[r].arg = callback_arg;
1343 dns_requests[r].dns_table_idx = i;
1344 LWIP_DNS_SET_ADDRTYPE(dns_requests[r].reqaddrtype, dns_addrtype);
1345 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": duplicate request\n", name));
1346 return ERR_INPROGRESS;
1351 /* no duplicate entries found */
1352 #endif
1354 /* search an unused entry, or the oldest one */
1355 lseq = 0;
1356 lseqi = DNS_TABLE_SIZE;
1357 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
1358 entry = &dns_table[i];
1359 /* is it an unused entry ? */
1360 if (entry->state == DNS_STATE_UNUSED) {
1361 break;
1363 /* check if this is the oldest completed entry */
1364 if (entry->state == DNS_STATE_DONE) {
1365 u8_t age = dns_seqno - entry->seqno;
1366 if (age > lseq) {
1367 lseq = age;
1368 lseqi = i;
1373 /* if we don't have found an unused entry, use the oldest completed one */
1374 if (i == DNS_TABLE_SIZE) {
1375 if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
1376 /* no entry can be used now, table is full */
1377 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
1378 return ERR_MEM;
1379 } else {
1380 /* use the oldest completed one */
1381 i = lseqi;
1382 entry = &dns_table[i];
1386 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
1387 /* find a free request entry */
1388 req = NULL;
1389 for (r = 0; r < DNS_MAX_REQUESTS; r++) {
1390 if (dns_requests[r].found == NULL) {
1391 req = &dns_requests[r];
1392 break;
1395 if (req == NULL) {
1396 /* no request entry can be used now, table is full */
1397 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS request entries table is full\n", name));
1398 return ERR_MEM;
1400 req->dns_table_idx = i;
1401 #else
1402 /* in this configuration, the entry index is the same as the request index */
1403 req = &dns_requests[i];
1404 #endif
1406 /* use this entry */
1407 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
1409 /* fill the entry */
1410 entry->state = DNS_STATE_NEW;
1411 entry->seqno = dns_seqno;
1412 LWIP_DNS_SET_ADDRTYPE(entry->reqaddrtype, dns_addrtype);
1413 LWIP_DNS_SET_ADDRTYPE(req->reqaddrtype, dns_addrtype);
1414 req->found = found;
1415 req->arg = callback_arg;
1416 namelen = LWIP_MIN(hostnamelen, DNS_MAX_NAME_LENGTH-1);
1417 MEMCPY(entry->name, name, namelen);
1418 entry->name[namelen] = 0;
1420 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
1421 entry->pcb_idx = dns_alloc_pcb();
1422 if (entry->pcb_idx >= DNS_MAX_SOURCE_PORTS) {
1423 /* failed to get a UDP pcb */
1424 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": failed to allocate a pcb\n", name));
1425 entry->state = DNS_STATE_UNUSED;
1426 req->found = NULL;
1427 return ERR_MEM;
1429 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS pcb %"U16_F"\n", name, (u16_t)(entry->pcb_idx)));
1430 #endif
1432 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1433 entry->is_mdns = is_mdns;
1434 #endif
1436 dns_seqno++;
1438 /* force to send query without waiting timer */
1439 dns_check_entry(i);
1441 /* dns query is enqueued */
1442 return ERR_INPROGRESS;
1446 * @ingroup dns
1447 * Resolve a hostname (string) into an IP address.
1448 * NON-BLOCKING callback version for use with raw API!!!
1450 * Returns immediately with one of err_t return codes:
1451 * - ERR_OK if hostname is a valid IP address string or the host
1452 * name is already in the local names table.
1453 * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
1454 * for resolution if no errors are present.
1455 * - ERR_ARG: dns client not initialized or invalid hostname
1457 * @param hostname the hostname that is to be queried
1458 * @param addr pointer to a ip_addr_t where to store the address if it is already
1459 * cached in the dns_table (only valid if ERR_OK is returned!)
1460 * @param found a callback function to be called on success, failure or timeout (only if
1461 * ERR_INPROGRESS is returned!)
1462 * @param callback_arg argument to pass to the callback function
1463 * @return a err_t return code.
1465 err_t
1466 dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found,
1467 void *callback_arg)
1469 return dns_gethostbyname_addrtype(hostname, addr, found, callback_arg, LWIP_DNS_ADDRTYPE_DEFAULT);
1473 * @ingroup dns
1474 * Like dns_gethostbyname, but returned address type can be controlled:
1475 * @param hostname the hostname that is to be queried
1476 * @param addr pointer to a ip_addr_t where to store the address if it is already
1477 * cached in the dns_table (only valid if ERR_OK is returned!)
1478 * @param found a callback function to be called on success, failure or timeout (only if
1479 * ERR_INPROGRESS is returned!)
1480 * @param callback_arg argument to pass to the callback function
1481 * @param dns_addrtype - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 first, try IPv6 if IPv4 fails only
1482 * - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 first, try IPv4 if IPv6 fails only
1483 * - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
1484 * - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
1486 err_t
1487 dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, dns_found_callback found,
1488 void *callback_arg, u8_t dns_addrtype)
1490 size_t hostnamelen;
1491 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1492 u8_t is_mdns;
1493 #endif
1494 /* not initialized or no valid server yet, or invalid addr pointer
1495 * or invalid hostname or invalid hostname length */
1496 if ((addr == NULL) ||
1497 (!hostname) || (!hostname[0])) {
1498 return ERR_ARG;
1500 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
1501 if (dns_pcbs[0] == NULL) {
1502 return ERR_ARG;
1504 #endif
1505 hostnamelen = strlen(hostname);
1506 if (hostnamelen >= DNS_MAX_NAME_LENGTH) {
1507 LWIP_DEBUGF(DNS_DEBUG, ("dns_gethostbyname: name too long to resolve"));
1508 return ERR_ARG;
1512 #if LWIP_HAVE_LOOPIF
1513 if (strcmp(hostname, "localhost") == 0) {
1514 ip_addr_set_loopback(LWIP_DNS_ADDRTYPE_IS_IPV6(dns_addrtype), addr);
1515 return ERR_OK;
1517 #endif /* LWIP_HAVE_LOOPIF */
1519 /* host name already in octet notation? set ip addr and return ERR_OK */
1520 if (ipaddr_aton(hostname, addr)) {
1521 #if LWIP_IPV4 && LWIP_IPV6
1522 if ((IP_IS_V6(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV4)) ||
1523 (IP_IS_V4(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV6)))
1524 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1526 return ERR_OK;
1529 /* already have this address cached? */
1530 if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
1531 return ERR_OK;
1533 #if LWIP_IPV4 && LWIP_IPV6
1534 if ((dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) || (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
1535 /* fallback to 2nd IP type and try again to lookup */
1536 u8_t fallback;
1537 if (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
1538 fallback = LWIP_DNS_ADDRTYPE_IPV6;
1539 } else {
1540 fallback = LWIP_DNS_ADDRTYPE_IPV4;
1542 if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(fallback)) == ERR_OK) {
1543 return ERR_OK;
1546 #else /* LWIP_IPV4 && LWIP_IPV6 */
1547 LWIP_UNUSED_ARG(dns_addrtype);
1548 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1550 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
1551 if (strstr(hostname, ".local") == &hostname[hostnamelen] - 6) {
1552 is_mdns = 1;
1553 } else {
1554 is_mdns = 0;
1557 if (!is_mdns)
1558 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
1560 /* prevent calling found callback if no server is set, return error instead */
1561 if (ip_addr_isany_val(dns_servers[0])) {
1562 return ERR_VAL;
1566 /* queue query with specified callback */
1567 return dns_enqueue(hostname, hostnamelen, found, callback_arg LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)
1568 LWIP_DNS_ISMDNS_ARG(is_mdns));
1571 #endif /* LWIP_DNS */