3 * DNS - host name to IP address resolver.
9 * This file implements a DNS host name to IP address resolver.
11 * Port to lwIP from uIP
12 * by Jim Pettinato April 2007
14 * uIP version Copyright (c) 2002-2003, Adam Dunkels.
15 * All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 * 3. The name of the author may not be used to endorse or promote
26 * products derived from this software without specific prior
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
30 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
31 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
33 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
35 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
37 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
38 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
39 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 * The lwIP DNS resolver functions are used to lookup a host name and
45 * map it to a numerical IP address. It maintains a list of resolved
46 * hostnames that can be queried with the dns_lookup() function.
47 * New hostnames can be resolved using the dns_query() function.
49 * The lwIP version of the resolver also adds a non-blocking version of
50 * gethostbyname() that will work with a raw API application. This function
51 * checks for an IP address string first and converts it if it is valid.
52 * gethostbyname() then does a dns_lookup() to see if the name is
53 * already in the table. If so, the IP is returned. If not, a query is
54 * issued and the function returns with a ERR_INPROGRESS status. The app
55 * using the dns client must then go into a waiting state.
57 * Once a hostname has been resolved (or found to be non-existent),
58 * the resolver code calls a specified callback function (which
59 * must be implemented by the module that uses the resolver).
62 /*-----------------------------------------------------------------------------
63 * RFC 1035 - Domain names - implementation and specification
64 * RFC 2181 - Clarifications to the DNS Specification
65 *----------------------------------------------------------------------------*/
67 /** @todo: define good default values (rfc compliance) */
68 /** @todo: improve answer parsing, more checkings... */
69 /** @todo: check RFC1035 - 7.3. Processing responses */
71 /*-----------------------------------------------------------------------------
73 *----------------------------------------------------------------------------*/
77 #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
81 #include "lwip/memp.h"
86 /** DNS server IP address */
87 #ifndef DNS_SERVER_ADDRESS
88 #define DNS_SERVER_ADDRESS(ipaddr) (ip4_addr_set_u32(ipaddr, ipaddr_addr("208.67.222.222"))) /* resolver1.opendns.com */
91 /** DNS server port address */
92 #ifndef DNS_SERVER_PORT
93 #define DNS_SERVER_PORT 53
96 /** DNS maximum number of retries when asking for a name, before "timeout". */
97 #ifndef DNS_MAX_RETRIES
98 #define DNS_MAX_RETRIES 4
101 /** DNS resource record max. TTL (one week as default) */
103 #define DNS_MAX_TTL 604800
106 /* DNS protocol flags */
107 #define DNS_FLAG1_RESPONSE 0x80
108 #define DNS_FLAG1_OPCODE_STATUS 0x10
109 #define DNS_FLAG1_OPCODE_INVERSE 0x08
110 #define DNS_FLAG1_OPCODE_STANDARD 0x00
111 #define DNS_FLAG1_AUTHORATIVE 0x04
112 #define DNS_FLAG1_TRUNC 0x02
113 #define DNS_FLAG1_RD 0x01
114 #define DNS_FLAG2_RA 0x80
115 #define DNS_FLAG2_ERR_MASK 0x0f
116 #define DNS_FLAG2_ERR_NONE 0x00
117 #define DNS_FLAG2_ERR_NAME 0x03
119 /* DNS protocol states */
120 #define DNS_STATE_UNUSED 0
121 #define DNS_STATE_NEW 1
122 #define DNS_STATE_ASKING 2
123 #define DNS_STATE_DONE 3
125 #ifdef PACK_STRUCT_USE_INCLUDES
126 # include "arch/bpstruct.h"
129 /** DNS message header */
131 PACK_STRUCT_FIELD(u16_t id);
132 PACK_STRUCT_FIELD(u8_t flags1);
133 PACK_STRUCT_FIELD(u8_t flags2);
134 PACK_STRUCT_FIELD(u16_t numquestions);
135 PACK_STRUCT_FIELD(u16_t numanswers);
136 PACK_STRUCT_FIELD(u16_t numauthrr);
137 PACK_STRUCT_FIELD(u16_t numextrarr);
138 } PACK_STRUCT_STRUCT;
140 #ifdef PACK_STRUCT_USE_INCLUDES
141 # include "arch/epstruct.h"
143 #define SIZEOF_DNS_HDR 12
145 /** DNS query message structure.
146 No packing needed: only used locally on the stack. */
148 /* DNS query record starts with either a domain name or a pointer
149 to a name already present somewhere in the packet. */
153 #define SIZEOF_DNS_QUERY 4
155 /** DNS answer message structure.
156 No packing needed: only used locally on the stack. */
158 /* DNS answer record starts with either a domain name or a pointer
159 to a name already present somewhere in the packet. */
165 #define SIZEOF_DNS_ANSWER 10
167 /** DNS table entry */
168 struct dns_table_entry {
176 char name[DNS_MAX_NAME_LENGTH];
178 /* pointer to callback on DNS query done */
179 dns_found_callback found;
183 #if DNS_LOCAL_HOSTLIST
185 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
186 /** Local host-list. For hostnames in this list, no
187 * external name resolution is performed */
188 static struct local_hostlist_entry *local_hostlist_dynamic;
189 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
191 /** Defining this allows the local_hostlist_static to be placed in a different
192 * linker section (e.g. FLASH) */
193 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE
194 #define DNS_LOCAL_HOSTLIST_STORAGE_PRE static
195 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */
196 /** Defining this allows the local_hostlist_static to be placed in a different
197 * linker section (e.g. FLASH) */
198 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST
199 #define DNS_LOCAL_HOSTLIST_STORAGE_POST
200 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */
201 DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[]
202 DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT;
204 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
206 static void dns_init_local();
207 #endif /* DNS_LOCAL_HOSTLIST */
210 /* forward declarations */
211 static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port);
212 static void dns_check_entries(void);
214 /*-----------------------------------------------------------------------------
216 *----------------------------------------------------------------------------*/
219 static struct udp_pcb *dns_pcb;
220 static u8_t dns_seqno;
221 static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
222 static ip_addr_t dns_servers[DNS_MAX_SERVERS];
223 /** Contiguous buffer for processing responses */
224 static u8_t dns_payload_buffer[LWIP_MEM_ALIGN_BUFFER(DNS_MSG_SIZE)];
225 static u8_t* dns_payload;
228 * Initialize the resolver: set up the UDP pcb and configure the default server
229 * (DNS_SERVER_ADDRESS).
236 dns_payload = (u8_t *)LWIP_MEM_ALIGN(dns_payload_buffer);
238 /* initialize default DNS server address */
239 DNS_SERVER_ADDRESS(&dnsserver);
241 LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
243 /* if dns client not yet initialized... */
244 if (dns_pcb == NULL) {
247 if (dns_pcb != NULL) {
248 /* initialize DNS table not needed (initialized to zero since it is a
249 * global variable) */
250 LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0",
251 DNS_STATE_UNUSED == 0);
253 /* initialize DNS client */
254 udp_bind(dns_pcb, IP_ADDR_ANY, 0);
255 udp_recv(dns_pcb, dns_recv, NULL);
257 /* initialize default DNS primary server */
258 dns_setserver(0, &dnsserver);
261 #if DNS_LOCAL_HOSTLIST
267 * Initialize one of the DNS servers.
269 * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS
270 * @param dnsserver IP address of the DNS server to set
273 dns_setserver(u8_t numdns, ip_addr_t *dnsserver)
275 if ((numdns < DNS_MAX_SERVERS) && (dns_pcb != NULL) &&
276 (dnsserver != NULL) && !ip_addr_isany(dnsserver)) {
277 dns_servers[numdns] = (*dnsserver);
282 * Obtain one of the currently configured DNS server.
284 * @param numdns the index of the DNS server
285 * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS
286 * server has not been configured.
289 dns_getserver(u8_t numdns)
291 if (numdns < DNS_MAX_SERVERS) {
292 return dns_servers[numdns];
299 * The DNS resolver client timer - handle retries and timeouts and should
300 * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
305 if (dns_pcb != NULL) {
306 LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
311 #if DNS_LOCAL_HOSTLIST
315 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
317 struct local_hostlist_entry *entry;
318 /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */
319 struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT;
321 for (i = 0; i < sizeof(local_hostlist_init) / sizeof(struct local_hostlist_entry); i++) {
322 struct local_hostlist_entry *init_entry = &local_hostlist_init[i];
323 LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL);
324 namelen = strlen(init_entry->name);
325 LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
326 entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
327 LWIP_ASSERT("mem-error in dns_init_local", entry != NULL);
329 entry->name = (char*)entry + sizeof(struct local_hostlist_entry);
330 MEMCPY((char*)entry->name, init_entry->name, namelen);
331 ((char*)entry->name)[namelen] = 0;
332 entry->addr = init_entry->addr;
333 entry->next = local_hostlist_dynamic;
334 local_hostlist_dynamic = entry;
337 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
341 * Scans the local host-list for a hostname.
343 * @param hostname Hostname to look for in the local host-list
344 * @return The first IP address for the hostname in the local host-list or
345 * IPADDR_NONE if not found.
348 dns_lookup_local(const char *hostname)
350 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
351 struct local_hostlist_entry *entry = local_hostlist_dynamic;
352 while(entry != NULL) {
353 if(strcmp(entry->name, hostname) == 0) {
354 return ip4_addr_get_u32(&entry->addr);
358 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
360 for (i = 0; i < sizeof(local_hostlist_static) / sizeof(struct local_hostlist_entry); i++) {
361 if(strcmp(local_hostlist_static[i].name, hostname) == 0) {
362 return ip4_addr_get_u32(&local_hostlist_static[i].addr);
365 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
369 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
370 /** Remove all entries from the local host-list for a specific hostname
373 * @param hostname hostname for which entries shall be removed from the local
375 * @param addr address for which entries shall be removed from the local host-list
376 * @return the number of removed entries
379 dns_local_removehost(const char *hostname, const ip_addr_t *addr)
382 struct local_hostlist_entry *entry = local_hostlist_dynamic;
383 struct local_hostlist_entry *last_entry = NULL;
384 while (entry != NULL) {
385 if (((hostname == NULL) || !strcmp(entry->name, hostname)) &&
386 ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
387 struct local_hostlist_entry *free_entry;
388 if (last_entry != NULL) {
389 last_entry->next = entry->next;
391 local_hostlist_dynamic = entry->next;
395 memp_free(MEMP_LOCALHOSTLIST, free_entry);
406 * Add a hostname/IP address pair to the local host-list.
407 * Duplicates are not checked.
409 * @param hostname hostname of the new entry
410 * @param addr IP address of the new entry
411 * @return ERR_OK if succeeded or ERR_MEM on memory error
414 dns_local_addhost(const char *hostname, const ip_addr_t *addr)
416 struct local_hostlist_entry *entry;
418 LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
419 namelen = strlen(hostname);
420 LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
421 entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
425 entry->name = (char*)entry + sizeof(struct local_hostlist_entry);
426 MEMCPY((char*)entry->name, hostname, namelen);
427 ((char*)entry->name)[namelen] = 0;
428 ip_addr_copy(entry->addr, *addr);
429 entry->next = local_hostlist_dynamic;
430 local_hostlist_dynamic = entry;
433 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
434 #endif /* DNS_LOCAL_HOSTLIST */
437 * Look up a hostname in the array of known hostnames.
439 * @note This function only looks in the internal array of known
440 * hostnames, it does not send out a query for the hostname if none
441 * was found. The function dns_enqueue() can be used to send a query
444 * @param name the hostname to look up
445 * @return the hostname's IP address, as u32_t (instead of ip_addr_t to
446 * better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname
447 * was not found in the cached dns_table.
450 dns_lookup(const char *name)
453 #if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN)
455 #endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */
456 #if DNS_LOCAL_HOSTLIST
457 if ((addr = dns_lookup_local(name)) != IPADDR_NONE) {
460 #endif /* DNS_LOCAL_HOSTLIST */
461 #ifdef DNS_LOOKUP_LOCAL_EXTERN
462 if((addr = DNS_LOOKUP_LOCAL_EXTERN(name)) != IPADDR_NONE) {
465 #endif /* DNS_LOOKUP_LOCAL_EXTERN */
467 /* Walk through name list, return entry if found. If not, return NULL. */
468 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
469 if ((dns_table[i].state == DNS_STATE_DONE) &&
470 (strcmp(name, dns_table[i].name) == 0)) {
471 LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
472 ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
473 LWIP_DEBUGF(DNS_DEBUG, ("\n"));
474 return ip4_addr_get_u32(&dns_table[i].ipaddr);
481 #if DNS_DOES_NAME_CHECK
483 * Compare the "dotted" name "query" with the encoded name "response"
484 * to make sure an answer from the DNS server matches the current dns_table
485 * entry (otherwise, answers might arrive late for hostname not on the list
488 * @param query hostname (not encoded) from the dns_table
489 * @param response encoded hostname in the DNS response
490 * @return 0: names equal; 1: names differ
493 dns_compare_name(unsigned char *query, unsigned char *response)
499 /** @see RFC 1035 - 4.1.4. Message compression */
500 if ((n & 0xc0) == 0xc0) {
501 /* Compressed name */
504 /* Not compressed name */
506 if ((*query) != (*response)) {
515 } while (*response != 0);
519 #endif /* DNS_DOES_NAME_CHECK */
522 * Walk through a compact encoded DNS name and return the end of the name.
524 * @param query encoded DNS name in the DNS server response
525 * @return end of the name
527 static unsigned char *
528 dns_parse_name(unsigned char *query)
534 /** @see RFC 1035 - 4.1.4. Message compression */
535 if ((n & 0xc0) == 0xc0) {
536 /* Compressed name */
539 /* Not compressed name */
545 } while (*query != 0);
551 * Send a DNS query packet.
553 * @param numdns index of the DNS server in the dns_servers table
554 * @param name hostname to query
555 * @param id index of the hostname in dns_table, used as transaction ID in the
557 * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
560 dns_send(u8_t numdns, const char* name, u8_t id)
564 struct dns_query qry;
567 const char *pHostname;
570 LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
571 (u16_t)(numdns), name));
572 LWIP_ASSERT("dns server out of array", numdns < DNS_MAX_SERVERS);
573 LWIP_ASSERT("dns server has no IP address set", !ip_addr_isany(&dns_servers[numdns]));
575 /* if here, we have either a new query or a retry on a previous query to process */
576 p = pbuf_alloc(PBUF_TRANSPORT, SIZEOF_DNS_HDR + DNS_MAX_NAME_LENGTH +
577 SIZEOF_DNS_QUERY, PBUF_RAM);
579 LWIP_ASSERT("pbuf must be in one piece", p->next == NULL);
580 /* fill dns header */
581 hdr = (struct dns_hdr*)p->payload;
582 memset(hdr, 0, SIZEOF_DNS_HDR);
584 hdr->flags1 = DNS_FLAG1_RD;
585 hdr->numquestions = PP_HTONS(1);
586 query = (char*)hdr + SIZEOF_DNS_HDR;
590 /* convert hostname into suitable query format. */
595 for(n = 0; *pHostname != '.' && *pHostname != 0; ++pHostname) {
601 } while(*pHostname != 0);
605 qry.type = PP_HTONS(DNS_RRTYPE_A);
606 qry.cls = PP_HTONS(DNS_RRCLASS_IN);
607 SMEMCPY(query, &qry, SIZEOF_DNS_QUERY);
609 /* resize pbuf to the exact dns query */
610 pbuf_realloc(p, (u16_t)((query + SIZEOF_DNS_QUERY) - ((char*)(p->payload))));
612 /* connect to the server for faster receiving */
613 udp_connect(dns_pcb, &dns_servers[numdns], DNS_SERVER_PORT);
614 /* send dns packet */
615 err = udp_sendto(dns_pcb, p, &dns_servers[numdns], DNS_SERVER_PORT);
627 * dns_check_entry() - see if pEntry has not yet been queried and, if so, sends out a query.
628 * Check an entry in the dns_table:
629 * - send out query for new entries
630 * - retry old pending entries on timeout (also with different servers)
631 * - remove completed entries from the table if their TTL has expired
633 * @param i index of the dns_table entry to check
636 dns_check_entry(u8_t i)
639 struct dns_table_entry *pEntry = &dns_table[i];
641 LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
643 switch(pEntry->state) {
645 case DNS_STATE_NEW: {
646 /* initialize new entry */
647 pEntry->state = DNS_STATE_ASKING;
652 /* send DNS packet for this entry */
653 err = dns_send(pEntry->numdns, pEntry->name, i);
655 printf("Error in dns_send: %d\n", err);
659 case DNS_STATE_ASKING: {
660 if (--pEntry->tmr == 0) {
661 if (++pEntry->retries == DNS_MAX_RETRIES) {
662 if ((pEntry->numdns+1<DNS_MAX_SERVERS) && !ip_addr_isany(&dns_servers[pEntry->numdns+1])) {
663 /* change of server */
669 LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", pEntry->name));
670 /* call specified callback function if provided */
672 (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
673 /* flush this entry */
674 pEntry->state = DNS_STATE_UNUSED;
675 pEntry->found = NULL;
680 /* wait longer for the next retry */
681 pEntry->tmr = pEntry->retries;
683 /* send DNS packet for this entry */
684 err = dns_send(pEntry->numdns, pEntry->name, i);
686 printf("Error in dns_send: %d\n", err);
691 case DNS_STATE_DONE: {
692 /* if the time to live is nul */
693 if (--pEntry->ttl == 0) {
694 LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", pEntry->name));
695 /* flush this entry */
696 pEntry->state = DNS_STATE_UNUSED;
697 pEntry->found = NULL;
701 case DNS_STATE_UNUSED:
705 LWIP_ASSERT("unknown dns_table entry state:", 0);
711 * Call dns_check_entry for each entry in dns_table - check all entries.
714 dns_check_entries(void)
718 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
724 * Receive input function for DNS response packets arriving for the dns UDP pcb.
729 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
734 struct dns_answer ans;
735 struct dns_table_entry *pEntry;
736 u16_t nquestions, nanswers;
738 LWIP_UNUSED_ARG(arg);
739 LWIP_UNUSED_ARG(pcb);
740 LWIP_UNUSED_ARG(addr);
741 LWIP_UNUSED_ARG(port);
743 /* is the dns message too big ? */
744 if (p->tot_len > DNS_MSG_SIZE) {
745 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too big\n"));
746 /* free pbuf and return */
750 /* is the dns message big enough ? */
751 if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY + SIZEOF_DNS_ANSWER)) {
752 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
753 /* free pbuf and return */
757 /* copy dns payload inside static buffer for processing */
758 if (pbuf_copy_partial(p, dns_payload, p->tot_len, 0) == p->tot_len) {
759 /* The ID in the DNS header should be our entry into the name table. */
760 hdr = (struct dns_hdr*)dns_payload;
762 if (i < DNS_TABLE_SIZE) {
763 pEntry = &dns_table[i];
764 if(pEntry->state == DNS_STATE_ASKING) {
765 /* This entry is now completed. */
766 pEntry->state = DNS_STATE_DONE;
767 pEntry->err = hdr->flags2 & DNS_FLAG2_ERR_MASK;
769 /* We only care about the question(s) and the answers. The authrr
770 and the extrarr are simply discarded. */
771 nquestions = htons(hdr->numquestions);
772 nanswers = htons(hdr->numanswers);
774 /* Check for error. If so, call callback to inform. */
775 if (((hdr->flags1 & DNS_FLAG1_RESPONSE) == 0) || (pEntry->err != 0) || (nquestions != 1)) {
776 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", pEntry->name));
777 /* call callback to indicate error, clean up memory and return */
781 #if DNS_DOES_NAME_CHECK
782 /* Check if the name in the "question" part match with the name in the entry. */
783 if (dns_compare_name((unsigned char *)(pEntry->name), (unsigned char *)dns_payload + SIZEOF_DNS_HDR) != 0) {
784 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", pEntry->name));
785 /* call callback to indicate error, clean up memory and return */
788 #endif /* DNS_DOES_NAME_CHECK */
790 /* Skip the name in the "question" part */
791 pHostname = (char *) dns_parse_name((unsigned char *)dns_payload + SIZEOF_DNS_HDR) + SIZEOF_DNS_QUERY;
793 while (nanswers > 0) {
794 /* skip answer resource record's host name */
795 pHostname = (char *) dns_parse_name((unsigned char *)pHostname);
797 /* Check for IP address type and Internet class. Others are discarded. */
798 SMEMCPY(&ans, pHostname, SIZEOF_DNS_ANSWER);
799 if((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) &&
800 (ans.len == PP_HTONS(sizeof(ip_addr_t))) ) {
801 /* read the answer resource record's TTL, and maximize it if needed */
802 pEntry->ttl = ntohl(ans.ttl);
803 if (pEntry->ttl > DNS_MAX_TTL) {
804 pEntry->ttl = DNS_MAX_TTL;
806 /* read the IP address after answer resource record's header */
807 SMEMCPY(&(pEntry->ipaddr), (pHostname+SIZEOF_DNS_ANSWER), sizeof(ip_addr_t));
808 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", pEntry->name));
809 ip_addr_debug_print(DNS_DEBUG, (&(pEntry->ipaddr)));
810 LWIP_DEBUGF(DNS_DEBUG, ("\n"));
811 /* call specified callback function if provided */
813 (*pEntry->found)(pEntry->name, &pEntry->ipaddr, pEntry->arg);
815 /* deallocate memory and return */
818 pHostname = pHostname + SIZEOF_DNS_ANSWER + htons(ans.len);
822 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", pEntry->name));
823 /* call callback to indicate error, clean up memory and return */
829 /* deallocate memory and return */
833 /* ERROR: call specified callback function with NULL as name to indicate an error */
835 (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
837 /* flush this entry */
838 pEntry->state = DNS_STATE_UNUSED;
839 pEntry->found = NULL;
848 * Queues a new hostname to resolve and sends out a DNS query for that hostname
850 * @param name the hostname that is to be queried
851 * @param found a callback founction to be called on success, failure or timeout
852 * @param callback_arg argument to pass to the callback function
853 * @return @return a err_t return code.
856 dns_enqueue(const char *name, dns_found_callback found, void *callback_arg)
860 struct dns_table_entry *pEntry = NULL;
863 /* search an unused entry, or the oldest one */
865 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
866 pEntry = &dns_table[i];
867 /* is it an unused entry ? */
868 if (pEntry->state == DNS_STATE_UNUSED)
871 /* check if this is the oldest completed entry */
872 if (pEntry->state == DNS_STATE_DONE) {
873 if ((dns_seqno - pEntry->seqno) > lseq) {
874 lseq = dns_seqno - pEntry->seqno;
880 /* if we don't have found an unused entry, use the oldest completed one */
881 if (i == DNS_TABLE_SIZE) {
882 if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
883 /* no entry can't be used now, table is full */
884 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
887 /* use the oldest completed one */
889 pEntry = &dns_table[i];
894 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
897 pEntry->state = DNS_STATE_NEW;
898 pEntry->seqno = dns_seqno++;
899 pEntry->found = found;
900 pEntry->arg = callback_arg;
901 namelen = LWIP_MIN(strlen(name), DNS_MAX_NAME_LENGTH-1);
902 MEMCPY(pEntry->name, name, namelen);
903 pEntry->name[namelen] = 0;
905 /* force to send query without waiting timer */
908 /* dns query is enqueued */
909 return ERR_INPROGRESS;
913 * Resolve a hostname (string) into an IP address.
914 * NON-BLOCKING callback version for use with raw API!!!
916 * Returns immediately with one of err_t return codes:
917 * - ERR_OK if hostname is a valid IP address string or the host
918 * name is already in the local names table.
919 * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
920 * for resolution if no errors are present.
922 * @param hostname the hostname that is to be queried
923 * @param addr pointer to a ip_addr_t where to store the address if it is already
924 * cached in the dns_table (only valid if ERR_OK is returned!)
925 * @param found a callback function to be called on success, failure or timeout (only if
926 * ERR_INPROGRESS is returned!)
927 * @param callback_arg argument to pass to the callback function
928 * @return a err_t return code.
931 dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found,
935 /* not initialized or no valid server yet, or invalid addr pointer
936 * or invalid hostname or invalid hostname length */
937 if ((dns_pcb == NULL) || (addr == NULL) ||
938 (!hostname) || (!hostname[0]) ||
939 (strlen(hostname) >= DNS_MAX_NAME_LENGTH)) {
944 if (strcmp(hostname, "localhost")==0) {
945 ip_addr_set_loopback(addr);
948 #endif /* LWIP_HAVE_LOOPIF */
950 /* host name already in octet notation? set ip addr and return ERR_OK */
951 ipaddr = ipaddr_addr(hostname);
952 if (ipaddr == IPADDR_NONE) {
953 /* already have this address cached? */
954 ipaddr = dns_lookup(hostname);
956 if (ipaddr != IPADDR_NONE) {
957 ip4_addr_set_u32(addr, ipaddr);
961 /* queue query with specified callback */
962 return dns_enqueue(hostname, found, callback_arg);
965 #endif /* LWIP_DNS */