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 */
85 /** DNS server IP address */
86 #ifndef DNS_SERVER_ADDRESS
87 #define DNS_SERVER_ADDRESS inet_addr("208.67.222.222") /* resolver1.opendns.com */
90 /** DNS server port address */
91 #ifndef DNS_SERVER_PORT
92 #define DNS_SERVER_PORT 53
95 /** DNS maximum number of retries when asking for a name, before "timeout". */
96 #ifndef DNS_MAX_RETRIES
97 #define DNS_MAX_RETRIES 4
100 /** DNS resource record max. TTL (one week as default) */
102 #define DNS_MAX_TTL 604800
105 /* DNS protocol flags */
106 #define DNS_FLAG1_RESPONSE 0x80
107 #define DNS_FLAG1_OPCODE_STATUS 0x10
108 #define DNS_FLAG1_OPCODE_INVERSE 0x08
109 #define DNS_FLAG1_OPCODE_STANDARD 0x00
110 #define DNS_FLAG1_AUTHORATIVE 0x04
111 #define DNS_FLAG1_TRUNC 0x02
112 #define DNS_FLAG1_RD 0x01
113 #define DNS_FLAG2_RA 0x80
114 #define DNS_FLAG2_ERR_MASK 0x0f
115 #define DNS_FLAG2_ERR_NONE 0x00
116 #define DNS_FLAG2_ERR_NAME 0x03
118 /* DNS protocol states */
119 #define DNS_STATE_UNUSED 0
120 #define DNS_STATE_NEW 1
121 #define DNS_STATE_ASKING 2
122 #define DNS_STATE_DONE 3
124 #ifdef PACK_STRUCT_USE_INCLUDES
125 # include "arch/bpstruct.h"
128 /** DNS message header */
130 PACK_STRUCT_FIELD(u16_t id);
131 PACK_STRUCT_FIELD(u8_t flags1);
132 PACK_STRUCT_FIELD(u8_t flags2);
133 PACK_STRUCT_FIELD(u16_t numquestions);
134 PACK_STRUCT_FIELD(u16_t numanswers);
135 PACK_STRUCT_FIELD(u16_t numauthrr);
136 PACK_STRUCT_FIELD(u16_t numextrarr);
137 } PACK_STRUCT_STRUCT;
139 #ifdef PACK_STRUCT_USE_INCLUDES
140 # include "arch/epstruct.h"
142 #define SIZEOF_DNS_HDR 12
144 #ifdef PACK_STRUCT_USE_INCLUDES
145 # include "arch/bpstruct.h"
148 /** DNS query message structure */
150 /* DNS query record starts with either a domain name or a pointer
151 to a name already present somewhere in the packet. */
152 PACK_STRUCT_FIELD(u16_t type);
153 PACK_STRUCT_FIELD(u16_t class);
154 } PACK_STRUCT_STRUCT;
156 #ifdef PACK_STRUCT_USE_INCLUDES
157 # include "arch/epstruct.h"
159 #define SIZEOF_DNS_QUERY 4
161 #ifdef PACK_STRUCT_USE_INCLUDES
162 # include "arch/bpstruct.h"
165 /** DNS answer message structure */
167 /* DNS answer record starts with either a domain name or a pointer
168 to a name already present somewhere in the packet. */
169 PACK_STRUCT_FIELD(u16_t type);
170 PACK_STRUCT_FIELD(u16_t class);
171 PACK_STRUCT_FIELD(u32_t ttl);
172 PACK_STRUCT_FIELD(u16_t len);
173 } PACK_STRUCT_STRUCT;
175 #ifdef PACK_STRUCT_USE_INCLUDES
176 # include "arch/epstruct.h"
178 #define SIZEOF_DNS_ANSWER 10
180 /** DNS table entry */
181 struct dns_table_entry {
189 char name[DNS_MAX_NAME_LENGTH];
190 struct ip_addr ipaddr;
191 /* pointer to callback on DNS query done */
192 dns_found_callback found;
196 #if DNS_LOCAL_HOSTLIST
197 /** struct used for local host-list */
198 struct local_hostlist_entry {
199 /** static hostname */
201 /** static host address in network byteorder */
203 struct local_hostlist_entry *next;
206 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
207 /** Local host-list. For hostnames in this list, no
208 * external name resolution is performed */
209 static struct local_hostlist_entry *local_hostlist_dynamic;
210 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
212 /** Defining this allows the local_hostlist_static to be placed in a different
213 * linker section (e.g. FLASH) */
214 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE
215 #define DNS_LOCAL_HOSTLIST_STORAGE_PRE static
216 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */
217 /** Defining this allows the local_hostlist_static to be placed in a different
218 * linker section (e.g. FLASH) */
219 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST
220 #define DNS_LOCAL_HOSTLIST_STORAGE_POST
221 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */
222 DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[]
223 DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT;
225 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
227 static void dns_init_local();
228 #endif /* DNS_LOCAL_HOSTLIST */
231 /* forward declarations */
232 static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, u16_t port);
233 static void dns_check_entries(void);
235 /*-----------------------------------------------------------------------------
237 *----------------------------------------------------------------------------*/
240 static struct udp_pcb *dns_pcb;
241 static u8_t dns_seqno;
242 static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
243 static struct ip_addr dns_servers[DNS_MAX_SERVERS];
245 #if (DNS_USES_STATIC_BUF == 1)
246 static u8_t dns_payload[DNS_MSG_SIZE];
247 #endif /* (DNS_USES_STATIC_BUF == 1) */
250 * Initialize the resolver: set up the UDP pcb and configure the default server
251 * (DNS_SERVER_ADDRESS).
256 struct ip_addr dnsserver;
258 /* initialize default DNS server address */
259 dnsserver.addr = DNS_SERVER_ADDRESS;
261 LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
263 /* if dns client not yet initialized... */
264 if (dns_pcb == NULL) {
267 if (dns_pcb != NULL) {
268 /* initialize DNS table not needed (initialized to zero since it is a
269 * global variable) */
270 LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0",
271 DNS_STATE_UNUSED == 0);
273 /* initialize DNS client */
274 udp_bind(dns_pcb, IP_ADDR_ANY, 0);
275 udp_recv(dns_pcb, dns_recv, NULL);
277 /* initialize default DNS primary server */
278 dns_setserver(0, &dnsserver);
281 #if DNS_LOCAL_HOSTLIST
287 * Initialize one of the DNS servers.
289 * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS
290 * @param dnsserver IP address of the DNS server to set
293 dns_setserver(u8_t numdns, struct ip_addr *dnsserver)
295 if ((numdns < DNS_MAX_SERVERS) && (dns_pcb != NULL) &&
296 (dnsserver != NULL) && (dnsserver->addr !=0 )) {
297 dns_servers[numdns] = (*dnsserver);
302 * Obtain one of the currently configured DNS server.
304 * @param numdns the index of the DNS server
305 * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS
306 * server has not been configured.
309 dns_getserver(u8_t numdns)
311 if (numdns < DNS_MAX_SERVERS) {
312 return dns_servers[numdns];
319 * The DNS resolver client timer - handle retries and timeouts and should
320 * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
325 if (dns_pcb != NULL) {
326 LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
331 #if DNS_LOCAL_HOSTLIST
335 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
337 struct local_hostlist_entry *entry;
338 /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */
339 struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT;
341 for (i = 0; i < sizeof(local_hostlist_init) / sizeof(struct local_hostlist_entry); i++) {
342 struct local_hostlist_entry *init_entry = &local_hostlist_init[i];
343 LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL);
344 namelen = strlen(init_entry->name);
345 entry = mem_malloc(sizeof(struct local_hostlist_entry) + namelen + 1);
346 LWIP_ASSERT("mem-error in dns_init_local", entry != NULL);
348 entry->name = (char*)entry + sizeof(struct local_hostlist_entry);
349 MEMCPY((char*)entry->name, init_entry->name, namelen);
350 ((char*)entry->name)[namelen] = 0;
351 entry->addr = init_entry->addr;
352 entry->next = local_hostlist_dynamic;
353 local_hostlist_dynamic = entry;
356 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
360 * Scans the local host-list for a hostname.
362 * @param hostname Hostname to look for in the local host-list
363 * @return The first IP address for the hostname in the local host-list or
364 * INADDR_NONE if not found.
367 dns_lookup_local(const char *hostname)
369 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
370 struct local_hostlist_entry *entry = local_hostlist_dynamic;
371 while(entry != NULL) {
372 if(strcmp(entry->name, hostname) == 0) {
377 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
379 for (i = 0; i < sizeof(local_hostlist_static) / sizeof(struct local_hostlist_entry); i++) {
380 if(strcmp(local_hostlist_static[i].name, hostname) == 0) {
381 return local_hostlist_static[i].addr;
384 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
388 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
389 /** Remove all entries from the local host-list for a specific hostname
392 * @param hostname hostname for which entries shall be removed from the local
394 * @param addr address for which entries shall be removed from the local host-list
395 * @return the number of removed entries
398 dns_local_removehost(const char *hostname, const struct ip_addr *addr)
401 struct local_hostlist_entry *entry = local_hostlist_dynamic;
402 struct local_hostlist_entry *last_entry = NULL;
403 while (entry != NULL) {
404 if (((hostname == NULL) || !strcmp(entry->name, hostname)) &&
405 ((addr == NULL) || (entry->addr == addr->addr))) {
406 struct local_hostlist_entry *free_entry;
407 if (last_entry != NULL) {
408 last_entry->next = entry->next;
410 local_hostlist_dynamic = entry->next;
414 mem_free(free_entry);
425 * Add a hostname/IP address pair to the local host-list.
426 * Duplicates are not checked.
428 * @param hostname hostname of the new entry
429 * @param addr IP address of the new entry
430 * @return ERR_OK if succeeded or ERR_MEM on memory error
433 dns_local_addhost(const char *hostname, const struct ip_addr *addr)
435 struct local_hostlist_entry *entry;
437 LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
438 namelen = strlen(hostname);
439 entry = mem_malloc(sizeof(struct local_hostlist_entry) + namelen + 1);
443 entry->name = (char*)entry + sizeof(struct local_hostlist_entry);
444 MEMCPY((char*)entry->name, hostname, namelen);
445 ((char*)entry->name)[namelen] = 0;
446 entry->addr = addr->addr;
447 entry->next = local_hostlist_dynamic;
448 local_hostlist_dynamic = entry;
451 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
452 #endif /* DNS_LOCAL_HOSTLIST */
455 * Look up a hostname in the array of known hostnames.
457 * @note This function only looks in the internal array of known
458 * hostnames, it does not send out a query for the hostname if none
459 * was found. The function dns_enqueue() can be used to send a query
462 * @param name the hostname to look up
463 * @return the hostname's IP address, as u32_t (instead of struct ip_addr to
464 * better check for failure: != INADDR_NONE) or INADDR_NONE if the hostname
465 * was not found in the cached dns_table.
468 dns_lookup(const char *name)
471 #if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN)
473 #endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */
474 #if DNS_LOCAL_HOSTLIST
475 if ((addr = dns_lookup_local(name)) != INADDR_NONE) {
478 #endif /* DNS_LOCAL_HOSTLIST */
479 #ifdef DNS_LOOKUP_LOCAL_EXTERN
480 if((addr = DNS_LOOKUP_LOCAL_EXTERN(name)) != INADDR_NONE) {
483 #endif /* DNS_LOOKUP_LOCAL_EXTERN */
485 /* Walk through name list, return entry if found. If not, return NULL. */
486 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
487 if ((dns_table[i].state == DNS_STATE_DONE) &&
488 (strcmp(name, dns_table[i].name) == 0)) {
489 LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
490 ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
491 LWIP_DEBUGF(DNS_DEBUG, ("\n"));
492 return dns_table[i].ipaddr.addr;
499 #if DNS_DOES_NAME_CHECK
501 * Compare the "dotted" name "query" with the encoded name "response"
502 * to make sure an answer from the DNS server matches the current dns_table
503 * entry (otherwise, answers might arrive late for hostname not on the list
506 * @param query hostname (not encoded) from the dns_table
507 * @param response encoded hostname in the DNS response
508 * @return 0: names equal; 1: names differ
511 dns_compare_name(unsigned char *query, unsigned char *response)
517 /** @see RFC 1035 - 4.1.4. Message compression */
518 if ((n & 0xc0) == 0xc0) {
519 /* Compressed name */
522 /* Not compressed name */
524 if ((*query) != (*response)) {
533 } while (*response != 0);
537 #endif /* DNS_DOES_NAME_CHECK */
540 * Walk through a compact encoded DNS name and return the end of the name.
542 * @param query encoded DNS name in the DNS server response
543 * @return end of the name
545 static unsigned char *
546 dns_parse_name(unsigned char *query)
552 /** @see RFC 1035 - 4.1.4. Message compression */
553 if ((n & 0xc0) == 0xc0) {
554 /* Compressed name */
557 /* Not compressed name */
563 } while (*query != 0);
569 * Send a DNS query packet.
571 * @param numdns index of the DNS server in the dns_servers table
572 * @param name hostname to query
573 * @param id index of the hostname in dns_table, used as transaction ID in the
575 * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
578 dns_send(u8_t numdns, const char* name, u8_t id)
582 struct dns_query qry;
585 const char *pHostname;
588 LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
589 (u16_t)(numdns), name));
590 LWIP_ASSERT("dns server out of array", numdns < DNS_MAX_SERVERS);
591 LWIP_ASSERT("dns server has no IP address set", dns_servers[numdns].addr != 0);
593 /* if here, we have either a new query or a retry on a previous query to process */
594 p = pbuf_alloc(PBUF_TRANSPORT, SIZEOF_DNS_HDR + DNS_MAX_NAME_LENGTH +
595 SIZEOF_DNS_QUERY, PBUF_RAM);
597 LWIP_ASSERT("pbuf must be in one piece", p->next == NULL);
598 /* fill dns header */
599 hdr = (struct dns_hdr*)p->payload;
600 memset(hdr, 0, SIZEOF_DNS_HDR);
602 hdr->flags1 = DNS_FLAG1_RD;
603 hdr->numquestions = htons(1);
604 query = (char*)hdr + SIZEOF_DNS_HDR;
608 /* convert hostname into suitable query format. */
613 for(n = 0; *pHostname != '.' && *pHostname != 0; ++pHostname) {
619 } while(*pHostname != 0);
623 qry.type = htons(DNS_RRTYPE_A);
624 qry.class = htons(DNS_RRCLASS_IN);
625 MEMCPY( query, &qry, SIZEOF_DNS_QUERY);
627 /* resize pbuf to the exact dns query */
628 pbuf_realloc(p, (query + SIZEOF_DNS_QUERY) - ((char*)(p->payload)));
630 /* connect to the server for faster receiving */
631 udp_connect(dns_pcb, &dns_servers[numdns], DNS_SERVER_PORT);
632 /* send dns packet */
633 err = udp_sendto(dns_pcb, p, &dns_servers[numdns], DNS_SERVER_PORT);
645 * dns_check_entry() - see if pEntry has not yet been queried and, if so, sends out a query.
646 * Check an entry in the dns_table:
647 * - send out query for new entries
648 * - retry old pending entries on timeout (also with different servers)
649 * - remove completed entries from the table if their TTL has expired
651 * @param i index of the dns_table entry to check
654 dns_check_entry(u8_t i)
656 struct dns_table_entry *pEntry = &dns_table[i];
658 LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
660 switch(pEntry->state) {
662 case DNS_STATE_NEW: {
663 /* initialize new entry */
664 pEntry->state = DNS_STATE_ASKING;
669 /* send DNS packet for this entry */
670 dns_send(pEntry->numdns, pEntry->name, i);
674 case DNS_STATE_ASKING: {
675 if (--pEntry->tmr == 0) {
676 if (++pEntry->retries == DNS_MAX_RETRIES) {
677 if ((pEntry->numdns+1<DNS_MAX_SERVERS) && (dns_servers[pEntry->numdns+1].addr!=0)) {
678 /* change of server */
684 LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", pEntry->name));
685 /* call specified callback function if provided */
687 (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
688 /* flush this entry */
689 pEntry->state = DNS_STATE_UNUSED;
690 pEntry->found = NULL;
695 /* wait longer for the next retry */
696 pEntry->tmr = pEntry->retries;
698 /* send DNS packet for this entry */
699 dns_send(pEntry->numdns, pEntry->name, i);
704 case DNS_STATE_DONE: {
705 /* if the time to live is nul */
706 if (--pEntry->ttl == 0) {
707 LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", pEntry->name));
708 /* flush this entry */
709 pEntry->state = DNS_STATE_UNUSED;
710 pEntry->found = NULL;
714 case DNS_STATE_UNUSED:
718 LWIP_ASSERT("unknown dns_table entry state:", 0);
724 * Call dns_check_entry for each entry in dns_table - check all entries.
727 dns_check_entries(void)
731 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
737 * Receive input function for DNS response packets arriving for the dns UDP pcb.
742 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, u16_t port)
747 struct dns_answer ans;
748 struct dns_table_entry *pEntry;
749 u8_t nquestions, nanswers;
750 #if (DNS_USES_STATIC_BUF == 0)
751 u8_t dns_payload[DNS_MSG_SIZE];
752 #endif /* (DNS_USES_STATIC_BUF == 0) */
753 #if (DNS_USES_STATIC_BUF == 2)
755 #endif /* (DNS_USES_STATIC_BUF == 2) */
757 LWIP_UNUSED_ARG(arg);
758 LWIP_UNUSED_ARG(pcb);
759 LWIP_UNUSED_ARG(addr);
760 LWIP_UNUSED_ARG(port);
762 /* is the dns message too big ? */
763 if (p->tot_len > DNS_MSG_SIZE) {
764 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too big\n"));
765 /* free pbuf and return */
769 /* is the dns message big enough ? */
770 if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY + SIZEOF_DNS_ANSWER)) {
771 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
772 /* free pbuf and return */
776 #if (DNS_USES_STATIC_BUF == 2)
777 dns_payload = mem_malloc(p->tot_len);
778 if (dns_payload == NULL) {
779 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: mem_malloc error\n"));
780 /* free pbuf and return */
783 #endif /* (DNS_USES_STATIC_BUF == 2) */
785 /* copy dns payload inside static buffer for processing */
786 if (pbuf_copy_partial(p, dns_payload, p->tot_len, 0) == p->tot_len) {
787 /* The ID in the DNS header should be our entry into the name table. */
788 hdr = (struct dns_hdr*)dns_payload;
790 if (i < DNS_TABLE_SIZE) {
791 pEntry = &dns_table[i];
792 if(pEntry->state == DNS_STATE_ASKING) {
793 /* This entry is now completed. */
794 pEntry->state = DNS_STATE_DONE;
795 pEntry->err = hdr->flags2 & DNS_FLAG2_ERR_MASK;
797 /* We only care about the question(s) and the answers. The authrr
798 and the extrarr are simply discarded. */
799 nquestions = htons(hdr->numquestions);
800 nanswers = htons(hdr->numanswers);
802 /* Check for error. If so, call callback to inform. */
803 if (((hdr->flags1 & DNS_FLAG1_RESPONSE) == 0) || (pEntry->err != 0) || (nquestions != 1)) {
804 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", pEntry->name));
805 /* call callback to indicate error, clean up memory and return */
809 #if DNS_DOES_NAME_CHECK
810 /* Check if the name in the "question" part match with the name in the entry. */
811 if (dns_compare_name((unsigned char *)(pEntry->name), (unsigned char *)dns_payload + SIZEOF_DNS_HDR) != 0) {
812 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", pEntry->name));
813 /* call callback to indicate error, clean up memory and return */
816 #endif /* DNS_DOES_NAME_CHECK */
818 /* Skip the name in the "question" part */
819 pHostname = (char *) dns_parse_name((unsigned char *)dns_payload + SIZEOF_DNS_HDR) + SIZEOF_DNS_QUERY;
821 while(nanswers > 0) {
822 /* skip answer resource record's host name */
823 pHostname = (char *) dns_parse_name((unsigned char *)pHostname);
825 /* Check for IP address type and Internet class. Others are discarded. */
826 MEMCPY(&ans, pHostname, SIZEOF_DNS_ANSWER);
827 if((ntohs(ans.type) == DNS_RRTYPE_A) && (ntohs(ans.class) == DNS_RRCLASS_IN) && (ntohs(ans.len) == sizeof(struct ip_addr)) ) {
828 /* read the answer resource record's TTL, and maximize it if needed */
829 pEntry->ttl = ntohl(ans.ttl);
830 if (pEntry->ttl > DNS_MAX_TTL) {
831 pEntry->ttl = DNS_MAX_TTL;
833 /* read the IP address after answer resource record's header */
834 MEMCPY( &(pEntry->ipaddr), (pHostname+SIZEOF_DNS_ANSWER), sizeof(struct ip_addr));
835 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", pEntry->name));
836 ip_addr_debug_print(DNS_DEBUG, (&(pEntry->ipaddr)));
837 LWIP_DEBUGF(DNS_DEBUG, ("\n"));
838 /* call specified callback function if provided */
840 (*pEntry->found)(pEntry->name, &pEntry->ipaddr, pEntry->arg);
842 /* deallocate memory and return */
845 pHostname = pHostname + SIZEOF_DNS_ANSWER + htons(ans.len);
849 LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", pEntry->name));
850 /* call callback to indicate error, clean up memory and return */
856 /* deallocate memory and return */
860 /* ERROR: call specified callback function with NULL as name to indicate an error */
862 (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
864 /* flush this entry */
865 pEntry->state = DNS_STATE_UNUSED;
866 pEntry->found = NULL;
869 #if (DNS_USES_STATIC_BUF == 2)
870 /* free dns buffer */
871 mem_free(dns_payload);
872 #endif /* (DNS_USES_STATIC_BUF == 2) */
881 * Queues a new hostname to resolve and sends out a DNS query for that hostname
883 * @param name the hostname that is to be queried
884 * @param found a callback founction to be called on success, failure or timeout
885 * @param callback_arg argument to pass to the callback function
886 * @return @return a err_t return code.
889 dns_enqueue(const char *name, dns_found_callback found, void *callback_arg)
893 struct dns_table_entry *pEntry = NULL;
895 /* search an unused entry, or the oldest one */
897 for (i = 0; i < DNS_TABLE_SIZE; ++i) {
898 pEntry = &dns_table[i];
899 /* is it an unused entry ? */
900 if (pEntry->state == DNS_STATE_UNUSED)
903 /* check if this is the oldest completed entry */
904 if (pEntry->state == DNS_STATE_DONE) {
905 if ((dns_seqno - pEntry->seqno) > lseq) {
906 lseq = dns_seqno - pEntry->seqno;
912 /* if we don't have found an unused entry, use the oldest completed one */
913 if (i == DNS_TABLE_SIZE) {
914 if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
915 /* no entry can't be used now, table is full */
916 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
919 /* use the oldest completed one */
921 pEntry = &dns_table[i];
926 LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
929 pEntry->state = DNS_STATE_NEW;
930 pEntry->seqno = dns_seqno++;
931 pEntry->found = found;
932 pEntry->arg = callback_arg;
933 strcpy(pEntry->name, name);
935 /* force to send query without waiting timer */
938 /* dns query is enqueued */
939 return ERR_INPROGRESS;
943 * Resolve a hostname (string) into an IP address.
944 * NON-BLOCKING callback version for use with raw API!!!
946 * Returns immediately with one of err_t return codes:
947 * - ERR_OK if hostname is a valid IP address string or the host
948 * name is already in the local names table.
949 * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
950 * for resolution if no errors are present.
952 * @param hostname the hostname that is to be queried
953 * @param addr pointer to a struct ip_addr where to store the address if it is already
954 * cached in the dns_table (only valid if ERR_OK is returned!)
955 * @param found a callback function to be called on success, failure or timeout (only if
956 * ERR_INPROGRESS is returned!)
957 * @param callback_arg argument to pass to the callback function
958 * @return a err_t return code.
961 dns_gethostbyname(const char *hostname, struct ip_addr *addr, dns_found_callback found,
964 /* not initialized or no valid server yet, or invalid addr pointer
965 * or invalid hostname or invalid hostname length */
966 if ((dns_pcb == NULL) || (addr == NULL) ||
967 (!hostname) || (!hostname[0]) ||
968 (strlen(hostname) >= DNS_MAX_NAME_LENGTH)) {
973 if (strcmp(hostname,"localhost")==0) {
974 addr->addr = htonl(INADDR_LOOPBACK);
977 #endif /* LWIP_HAVE_LOOPIF */
979 /* host name already in octet notation? set ip addr and return ERR_OK
980 * already have this address cached? */
981 if (((addr->addr = inet_addr(hostname)) != INADDR_NONE) ||
982 ((addr->addr = dns_lookup(hostname)) != INADDR_NONE)) {
986 /* queue query with specified callback */
987 return dns_enqueue(hostname, found, callback_arg);
990 #endif /* LWIP_DNS */