Knight KE / Mbed OS Game_Master
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers lwip_dns.c Source File

lwip_dns.c

Go to the documentation of this file.
00001 /**
00002  * @file
00003  * DNS - host name to IP address resolver.
00004  *
00005  * @defgroup dns DNS
00006  * @ingroup callbackstyle_api
00007  *
00008  * Implements a DNS host name to IP address resolver.
00009  *
00010  * The lwIP DNS resolver functions are used to lookup a host name and
00011  * map it to a numerical IP address. It maintains a list of resolved
00012  * hostnames that can be queried with the dns_lookup() function.
00013  * New hostnames can be resolved using the dns_query() function.
00014  *
00015  * The lwIP version of the resolver also adds a non-blocking version of
00016  * gethostbyname() that will work with a raw API application. This function
00017  * checks for an IP address string first and converts it if it is valid.
00018  * gethostbyname() then does a dns_lookup() to see if the name is
00019  * already in the table. If so, the IP is returned. If not, a query is
00020  * issued and the function returns with a ERR_INPROGRESS status. The app
00021  * using the dns client must then go into a waiting state.
00022  *
00023  * Once a hostname has been resolved (or found to be non-existent),
00024  * the resolver code calls a specified callback function (which
00025  * must be implemented by the module that uses the resolver).
00026  * 
00027  * Multicast DNS queries are supported for names ending on ".local".
00028  * However, only "One-Shot Multicast DNS Queries" are supported (RFC 6762
00029  * chapter 5.1), this is not a fully compliant implementation of continuous
00030  * mDNS querying!
00031  *
00032  * All functions must be called from TCPIP thread.
00033  * 
00034  * @see @ref netconn_common for thread-safe access.
00035  */
00036 
00037 /*
00038  * Port to lwIP from uIP
00039  * by Jim Pettinato April 2007
00040  *
00041  * security fixes and more by Simon Goldschmidt
00042  *
00043  * uIP version Copyright (c) 2002-2003, Adam Dunkels.
00044  * All rights reserved.
00045  *
00046  * Redistribution and use in source and binary forms, with or without
00047  * modification, are permitted provided that the following conditions
00048  * are met:
00049  * 1. Redistributions of source code must retain the above copyright
00050  *    notice, this list of conditions and the following disclaimer.
00051  * 2. Redistributions in binary form must reproduce the above copyright
00052  *    notice, this list of conditions and the following disclaimer in the
00053  *    documentation and/or other materials provided with the distribution.
00054  * 3. The name of the author may not be used to endorse or promote
00055  *    products derived from this software without specific prior
00056  *    written permission.
00057  *
00058  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
00059  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
00060  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00061  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
00062  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00063  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
00064  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00065  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
00066  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
00067  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
00068  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00069  */
00070 
00071 /*-----------------------------------------------------------------------------
00072  * RFC 1035 - Domain names - implementation and specification
00073  * RFC 2181 - Clarifications to the DNS Specification
00074  *----------------------------------------------------------------------------*/
00075 
00076 /** @todo: define good default values (rfc compliance) */
00077 /** @todo: improve answer parsing, more checkings... */
00078 /** @todo: check RFC1035 - 7.3. Processing responses */
00079 /** @todo: one-shot mDNS: dual-stack fallback to another IP version */
00080 
00081 /*-----------------------------------------------------------------------------
00082  * Includes
00083  *----------------------------------------------------------------------------*/
00084 
00085 #include "lwip/opt.h"
00086 
00087 #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
00088 
00089 #include "lwip/def.h"
00090 #include "lwip/udp.h"
00091 #include "lwip/mem.h"
00092 #include "lwip/memp.h"
00093 #include "lwip/dns.h"
00094 #include "lwip/prot/dns.h"
00095 
00096 #include <string.h>
00097 
00098 /** Random generator function to create random TXIDs and source ports for queries */
00099 #ifndef DNS_RAND_TXID
00100 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_XID) != 0)
00101 #define DNS_RAND_TXID LWIP_RAND
00102 #else
00103 static u16_t dns_txid;
00104 #define DNS_RAND_TXID() (++dns_txid)
00105 #endif
00106 #endif
00107 
00108 /** Limits the source port to be >= 1024 by default */
00109 #ifndef DNS_PORT_ALLOWED
00110 #define DNS_PORT_ALLOWED(port) ((port) >= 1024)
00111 #endif
00112 
00113 /** DNS maximum number of retries when asking for a name, before "timeout". */
00114 #ifndef DNS_MAX_RETRIES
00115 #define DNS_MAX_RETRIES           4
00116 #endif
00117 
00118 /** DNS resource record max. TTL (one week as default) */
00119 #ifndef DNS_MAX_TTL
00120 #define DNS_MAX_TTL               604800
00121 #elif DNS_MAX_TTL > 0x7FFFFFFF
00122 #error DNS_MAX_TTL must be a positive 32-bit value
00123 #endif
00124 
00125 #if DNS_TABLE_SIZE > 255
00126 #error DNS_TABLE_SIZE must fit into an u8_t
00127 #endif
00128 #if DNS_MAX_SERVERS > 255
00129 #error DNS_MAX_SERVERS must fit into an u8_t
00130 #endif
00131 
00132 /* The number of parallel requests (i.e. calls to dns_gethostbyname
00133  * that cannot be answered from the DNS table.
00134  * This is set to the table size by default.
00135  */
00136 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
00137 #ifndef DNS_MAX_REQUESTS
00138 #define DNS_MAX_REQUESTS          DNS_TABLE_SIZE
00139 #else
00140 #if DNS_MAX_REQUESTS > 255
00141 #error DNS_MAX_REQUESTS must fit into an u8_t
00142 #endif
00143 #endif
00144 #else
00145 /* In this configuration, both arrays have to have the same size and are used
00146  * like one entry (used/free) */
00147 #define DNS_MAX_REQUESTS          DNS_TABLE_SIZE
00148 #endif
00149 
00150 /* The number of UDP source ports used in parallel */
00151 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
00152 #ifndef DNS_MAX_SOURCE_PORTS
00153 #define DNS_MAX_SOURCE_PORTS      DNS_MAX_REQUESTS
00154 #else
00155 #if DNS_MAX_SOURCE_PORTS > 255
00156 #error DNS_MAX_SOURCE_PORTS must fit into an u8_t
00157 #endif
00158 #endif
00159 #else
00160 #ifdef DNS_MAX_SOURCE_PORTS
00161 #undef DNS_MAX_SOURCE_PORTS
00162 #endif
00163 #define DNS_MAX_SOURCE_PORTS      1
00164 #endif
00165 
00166 #if LWIP_IPV4 && LWIP_IPV6
00167 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) (((t) == LWIP_DNS_ADDRTYPE_IPV6_IPV4) || ((t) == LWIP_DNS_ADDRTYPE_IPV6))
00168 #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)))
00169 #define LWIP_DNS_ADDRTYPE_ARG(x) , x
00170 #define LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(x) x
00171 #define LWIP_DNS_SET_ADDRTYPE(x, y) do { x = y; } while(0)
00172 #else
00173 #if LWIP_IPV6
00174 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) 1
00175 #else
00176 #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) 0
00177 #endif
00178 #define LWIP_DNS_ADDRTYPE_MATCH_IP(t, ip) 1
00179 #define LWIP_DNS_ADDRTYPE_ARG(x)
00180 #define LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(x) 0
00181 #define LWIP_DNS_SET_ADDRTYPE(x, y)
00182 #endif /* LWIP_IPV4 && LWIP_IPV6 */
00183 
00184 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
00185 #define LWIP_DNS_ISMDNS_ARG(x) , x
00186 #else
00187 #define LWIP_DNS_ISMDNS_ARG(x)
00188 #endif
00189 
00190 /** DNS query message structure.
00191     No packing needed: only used locally on the stack. */
00192 struct dns_query {
00193   /* DNS query record starts with either a domain name or a pointer
00194      to a name already present somewhere in the packet. */
00195   u16_t type;
00196   u16_t cls;
00197 };
00198 #define SIZEOF_DNS_QUERY 4
00199 
00200 /** DNS answer message structure.
00201     No packing needed: only used locally on the stack. */
00202 struct dns_answer {
00203   /* DNS answer record starts with either a domain name or a pointer
00204      to a name already present somewhere in the packet. */
00205   u16_t type;
00206   u16_t cls;
00207   u32_t ttl;
00208   u16_t len;
00209 };
00210 #define SIZEOF_DNS_ANSWER 10
00211 /* maximum allowed size for the struct due to non-packed */
00212 #define SIZEOF_DNS_ANSWER_ASSERT 12
00213 
00214 /* DNS table entry states */
00215 typedef enum {
00216   DNS_STATE_UNUSED           = 0,
00217   DNS_STATE_NEW              = 1,
00218   DNS_STATE_ASKING           = 2,
00219   DNS_STATE_DONE             = 3
00220 } dns_state_enum_t;
00221 
00222 /** DNS table entry */
00223 struct dns_table_entry {
00224   u32_t ttl;
00225   ip_addr_t ipaddr;
00226   u16_t txid;
00227   u8_t  state;
00228   u8_t  server_idx;
00229   u8_t  tmr;
00230   u8_t  retries;
00231   u8_t  seqno;
00232 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
00233   u8_t pcb_idx;
00234 #endif
00235   char name[DNS_MAX_NAME_LENGTH];
00236 #if LWIP_IPV4 && LWIP_IPV6
00237   u8_t reqaddrtype;
00238 #endif /* LWIP_IPV4 && LWIP_IPV6 */
00239 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
00240   u8_t is_mdns;
00241 #endif
00242 };
00243 
00244 /** DNS request table entry: used when dns_gehostbyname cannot answer the
00245  * request from the DNS table */
00246 struct dns_req_entry {
00247   /* pointer to callback on DNS query done */
00248   dns_found_callback found;
00249   /* argument passed to the callback function */
00250   void *arg;
00251 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
00252   u8_t dns_table_idx;
00253 #endif
00254 #if LWIP_IPV4 && LWIP_IPV6
00255   u8_t reqaddrtype;
00256 #endif /* LWIP_IPV4 && LWIP_IPV6 */
00257 };
00258 
00259 #if DNS_LOCAL_HOSTLIST
00260 
00261 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
00262 /** Local host-list. For hostnames in this list, no
00263  *  external name resolution is performed */
00264 static struct local_hostlist_entry *local_hostlist_dynamic;
00265 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
00266 
00267 /** Defining this allows the local_hostlist_static to be placed in a different
00268  * linker section (e.g. FLASH) */
00269 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE
00270 #define DNS_LOCAL_HOSTLIST_STORAGE_PRE static
00271 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */
00272 /** Defining this allows the local_hostlist_static to be placed in a different
00273  * linker section (e.g. FLASH) */
00274 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST
00275 #define DNS_LOCAL_HOSTLIST_STORAGE_POST
00276 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */
00277 DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[]
00278   DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT;
00279 
00280 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
00281 
00282 static void dns_init_local(void);
00283 static err_t dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype));
00284 #endif /* DNS_LOCAL_HOSTLIST */
00285 
00286 #if LWIP_FULL_DNS
00287 /* forward declarations */
00288 static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port);
00289 static void dns_check_entries(void);
00290 static void dns_call_found(u8_t idx, ip_addr_t* addr);
00291 #endif
00292 
00293 /*-----------------------------------------------------------------------------
00294  * Globals
00295  *----------------------------------------------------------------------------*/
00296 
00297 #if LWIP_FULL_DNS
00298 /* DNS variables */
00299 static struct udp_pcb        *dns_pcbs[DNS_MAX_SOURCE_PORTS];
00300 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
00301 static u8_t                   dns_last_pcb_idx;
00302 #endif
00303 static u8_t                   dns_seqno;
00304 static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
00305 static struct dns_req_entry   dns_requests[DNS_MAX_REQUESTS];
00306 #endif
00307 static ip_addr_t              dns_servers[DNS_MAX_SERVERS];
00308 
00309 #if LWIP_IPV4
00310 const ip_addr_t dns_mquery_v4group = DNS_MQUERY_IPV4_GROUP_INIT;
00311 #endif /* LWIP_IPV4 */
00312 #if LWIP_IPV6
00313 const ip_addr_t dns_mquery_v6group = DNS_MQUERY_IPV6_GROUP_INIT;
00314 #endif /* LWIP_IPV6 */
00315 
00316 /**
00317  * Initialize the resolver: set up the UDP pcb and configure the default server
00318  * (if DNS_SERVER_ADDRESS is set).
00319  */
00320 void
00321 dns_init(void)
00322 {
00323 #ifdef DNS_SERVER_ADDRESS
00324   /* initialize default DNS server address */
00325   ip_addr_t dnsserver;
00326   DNS_SERVER_ADDRESS(&dnsserver);
00327   dns_setserver(0, &dnsserver);
00328 #endif /* DNS_SERVER_ADDRESS */
00329 
00330 #if LWIP_FULL_DNS
00331   LWIP_ASSERT("sanity check SIZEOF_DNS_QUERY",
00332     sizeof(struct dns_query) == SIZEOF_DNS_QUERY);
00333   LWIP_ASSERT("sanity check SIZEOF_DNS_ANSWER",
00334     sizeof(struct dns_answer) <= SIZEOF_DNS_ANSWER_ASSERT);
00335 
00336   LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
00337 
00338   /* if dns client not yet initialized... */
00339 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
00340   if (dns_pcbs[0] == NULL) {
00341     dns_pcbs[0] = udp_new_ip_type(IPADDR_TYPE_ANY);
00342     LWIP_ASSERT("dns_pcbs[0] != NULL", dns_pcbs[0] != NULL);
00343 
00344     /* initialize DNS table not needed (initialized to zero since it is a
00345      * global variable) */
00346     LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0",
00347       DNS_STATE_UNUSED == 0);
00348 
00349     /* initialize DNS client */
00350     udp_bind(dns_pcbs[0], IP_ANY_TYPE, 0);
00351     udp_recv(dns_pcbs[0], dns_recv, NULL);
00352   }
00353 #endif
00354 
00355 #if DNS_LOCAL_HOSTLIST
00356   dns_init_local();
00357 #endif
00358 #endif /* LWIP_FULL_DNS */
00359 }
00360 
00361 /**
00362  * @ingroup dns
00363  * Initialize one of the DNS servers.
00364  *
00365  * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS
00366  * @param dnsserver IP address of the DNS server to set
00367  */
00368 void
00369 dns_setserver(u8_t numdns, const ip_addr_t *dnsserver)
00370 {
00371   if (numdns < DNS_MAX_SERVERS) {
00372     if (dnsserver != NULL) {
00373       dns_servers[numdns] = (*dnsserver);
00374     } else {
00375       dns_servers[numdns] = *IP_ADDR_ANY;
00376     }
00377   }
00378 }
00379 
00380 /**
00381  * @ingroup dns
00382  * Obtain one of the currently configured DNS server.
00383  *
00384  * @param numdns the index of the DNS server
00385  * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS
00386  *         server has not been configured.
00387  */
00388 const ip_addr_t*
00389 dns_getserver(u8_t numdns)
00390 {
00391   if (numdns < DNS_MAX_SERVERS) {
00392     return &dns_servers[numdns];
00393   } else {
00394     return IP_ADDR_ANY;
00395   }
00396 }
00397 
00398 /**
00399  * The DNS resolver client timer - handle retries and timeouts and should
00400  * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
00401  */
00402 void
00403 dns_tmr(void)
00404 {
00405 #if LWIP_FULL_DNS
00406   LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
00407   dns_check_entries();
00408 #endif
00409 }
00410 
00411 #if LWIP_FULL_DNS
00412 
00413 #if DNS_LOCAL_HOSTLIST
00414 static void
00415 dns_init_local(void)
00416 {
00417 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
00418   size_t i;
00419   struct local_hostlist_entry *entry;
00420   /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */
00421   struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT;
00422   size_t namelen;
00423   for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_init); i++) {
00424     struct local_hostlist_entry *init_entry = &local_hostlist_init[i];
00425     LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL);
00426     namelen = strlen(init_entry->name);
00427     LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
00428     entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
00429     LWIP_ASSERT("mem-error in dns_init_local", entry != NULL);
00430     if (entry != NULL) {
00431       char* entry_name = (char*)entry + sizeof(struct local_hostlist_entry);
00432       MEMCPY(entry_name, init_entry->name, namelen);
00433       entry_name[namelen] = 0;
00434       entry->name = entry_name;
00435       entry->addr = init_entry->addr;
00436       entry->next = local_hostlist_dynamic;
00437       local_hostlist_dynamic = entry;
00438     }
00439   }
00440 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
00441 }
00442 
00443 /**
00444  * @ingroup dns
00445  * Iterate the local host-list for a hostname.
00446  *
00447  * @param iterator_fn a function that is called for every entry in the local host-list
00448  * @param iterator_arg 3rd argument passed to iterator_fn
00449  * @return the number of entries in the local host-list
00450  */
00451 size_t
00452 dns_local_iterate(dns_found_callback iterator_fn, void *iterator_arg)
00453 {
00454   size_t i;
00455 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
00456   struct local_hostlist_entry *entry = local_hostlist_dynamic;
00457   i = 0;
00458   while (entry != NULL) {
00459     if (iterator_fn != NULL) {
00460       iterator_fn(entry->name, &entry->addr, iterator_arg);
00461     }
00462     i++;
00463     entry = entry->next;
00464   }
00465 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
00466   for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_static); i++) {
00467     if (iterator_fn != NULL) {
00468       iterator_fn(local_hostlist_static[i].name, &local_hostlist_static[i].addr, iterator_arg);
00469     }
00470   }
00471 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
00472   return i;
00473 }
00474 
00475 /**
00476  * @ingroup dns
00477  * Scans the local host-list for a hostname.
00478  *
00479  * @param hostname Hostname to look for in the local host-list
00480  * @param addr the first IP address for the hostname in the local host-list or
00481  *         IPADDR_NONE if not found.
00482  * @param dns_addrtype - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 (ATTENTION: no fallback here!)
00483  *                     - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 (ATTENTION: no fallback here!)
00484  *                     - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
00485  *                     - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
00486  * @return ERR_OK if found, ERR_ARG if not found
00487  */
00488 err_t
00489 dns_local_lookup(const char *hostname, ip_addr_t *addr, u8_t dns_addrtype)
00490 {
00491   LWIP_UNUSED_ARG(dns_addrtype);
00492   return dns_lookup_local(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype));
00493 }
00494 
00495 /* Internal implementation for dns_local_lookup and dns_lookup */
00496 static err_t
00497 dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
00498 {
00499 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
00500   struct local_hostlist_entry *entry = local_hostlist_dynamic;
00501   while (entry != NULL) {
00502     if ((lwip_stricmp(entry->name, hostname) == 0) &&
00503         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, entry->addr)) {
00504       if (addr) {
00505         ip_addr_copy(*addr, entry->addr);
00506       }
00507       return ERR_OK;
00508     }
00509     entry = entry->next;
00510   }
00511 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
00512   size_t i;
00513   for (i = 0; i < LWIP_ARRAYSIZE(local_hostlist_static); i++) {
00514     if ((lwip_stricmp(local_hostlist_static[i].name, hostname) == 0) &&
00515         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, local_hostlist_static[i].addr)) {
00516       if (addr) {
00517         ip_addr_copy(*addr, local_hostlist_static[i].addr);
00518       }
00519       return ERR_OK;
00520     }
00521   }
00522 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
00523   return ERR_ARG;
00524 }
00525 
00526 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
00527 /**
00528  * @ingroup dns
00529  * Remove all entries from the local host-list for a specific hostname
00530  * and/or IP address
00531  *
00532  * @param hostname hostname for which entries shall be removed from the local
00533  *                 host-list
00534  * @param addr address for which entries shall be removed from the local host-list
00535  * @return the number of removed entries
00536  */
00537 int
00538 dns_local_removehost(const char *hostname, const ip_addr_t *addr)
00539 {
00540   int removed = 0;
00541   struct local_hostlist_entry *entry = local_hostlist_dynamic;
00542   struct local_hostlist_entry *last_entry = NULL;
00543   while (entry != NULL) {
00544     if (((hostname == NULL) || !lwip_stricmp(entry->name, hostname)) &&
00545         ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
00546       struct local_hostlist_entry *free_entry;
00547       if (last_entry != NULL) {
00548         last_entry->next = entry->next;
00549       } else {
00550         local_hostlist_dynamic = entry->next;
00551       }
00552       free_entry = entry;
00553       entry = entry->next;
00554       memp_free(MEMP_LOCALHOSTLIST, free_entry);
00555       removed++;
00556     } else {
00557       last_entry = entry;
00558       entry = entry->next;
00559     }
00560   }
00561   return removed;
00562 }
00563 
00564 /**
00565  * @ingroup dns
00566  * Add a hostname/IP address pair to the local host-list.
00567  * Duplicates are not checked.
00568  *
00569  * @param hostname hostname of the new entry
00570  * @param addr IP address of the new entry
00571  * @return ERR_OK if succeeded or ERR_MEM on memory error
00572  */
00573 err_t
00574 dns_local_addhost(const char *hostname, const ip_addr_t *addr)
00575 {
00576   struct local_hostlist_entry *entry;
00577   size_t namelen;
00578   char* entry_name;
00579   LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
00580   namelen = strlen(hostname);
00581   LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
00582   entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
00583   if (entry == NULL) {
00584     return ERR_MEM;
00585   }
00586   entry_name = (char*)entry + sizeof(struct local_hostlist_entry);
00587   MEMCPY(entry_name, hostname, namelen);
00588   entry_name[namelen] = 0;
00589   entry->name = entry_name;
00590   ip_addr_copy(entry->addr, *addr);
00591   entry->next = local_hostlist_dynamic;
00592   local_hostlist_dynamic = entry;
00593   return ERR_OK;
00594 }
00595 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
00596 #endif /* DNS_LOCAL_HOSTLIST */
00597 
00598 /**
00599  * @ingroup dns
00600  * Look up a hostname in the array of known hostnames.
00601  *
00602  * @note This function only looks in the internal array of known
00603  * hostnames, it does not send out a query for the hostname if none
00604  * was found. The function dns_enqueue() can be used to send a query
00605  * for a hostname.
00606  *
00607  * @param name the hostname to look up
00608  * @param addr the hostname's IP address, as u32_t (instead of ip_addr_t to
00609  *         better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname
00610  *         was not found in the cached dns_table.
00611  * @return ERR_OK if found, ERR_ARG if not found
00612  */
00613 static err_t
00614 dns_lookup(const char *name, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
00615 {
00616   u8_t i;
00617 #if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN)
00618 #endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */
00619 #if DNS_LOCAL_HOSTLIST
00620   if (dns_lookup_local(name, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
00621     return ERR_OK;
00622   }
00623 #endif /* DNS_LOCAL_HOSTLIST */
00624 #ifdef DNS_LOOKUP_LOCAL_EXTERN
00625   if (DNS_LOOKUP_LOCAL_EXTERN(name, addr, LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(dns_addrtype)) == ERR_OK) {
00626     return ERR_OK;
00627   }
00628 #endif /* DNS_LOOKUP_LOCAL_EXTERN */
00629 
00630   /* Walk through name list, return entry if found. If not, return NULL. */
00631   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
00632     if ((dns_table[i].state == DNS_STATE_DONE) &&
00633         (lwip_strnicmp(name, dns_table[i].name, sizeof(dns_table[i].name)) == 0) &&
00634         LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, dns_table[i].ipaddr)) {
00635       LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
00636       ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
00637       LWIP_DEBUGF(DNS_DEBUG, ("\n"));
00638       if (addr) {
00639         ip_addr_copy(*addr, dns_table[i].ipaddr);
00640       }
00641       return ERR_OK;
00642     }
00643   }
00644 
00645   return ERR_ARG;
00646 }
00647 
00648 /**
00649  * Compare the "dotted" name "query" with the encoded name "response"
00650  * to make sure an answer from the DNS server matches the current dns_table
00651  * entry (otherwise, answers might arrive late for hostname not on the list
00652  * any more).
00653  *
00654  * @param query hostname (not encoded) from the dns_table
00655  * @param p pbuf containing the encoded hostname in the DNS response
00656  * @param start_offset offset into p where the name starts
00657  * @return 0xFFFF: names differ, other: names equal -> offset behind name
00658  */
00659 static u16_t
00660 dns_compare_name(const char *query, struct pbuf* p, u16_t start_offset)
00661 {
00662   int n;
00663   u16_t response_offset = start_offset;
00664 
00665   do {
00666     n = pbuf_try_get_at(p, response_offset++);
00667     if (n < 0) {
00668       return 0xFFFF;
00669     }
00670     /** @see RFC 1035 - 4.1.4. Message compression */
00671     if ((n & 0xc0) == 0xc0) {
00672       /* Compressed name: cannot be equal since we don't send them */
00673       return 0xFFFF;
00674     } else {
00675       /* Not compressed name */
00676       while (n > 0) {
00677         int c = pbuf_try_get_at(p, response_offset);
00678         if (c < 0) {
00679           return 0xFFFF;
00680         }
00681         if ((*query) != (u8_t)c) {
00682           return 0xFFFF;
00683         }
00684         ++response_offset;
00685         ++query;
00686         --n;
00687       }
00688       ++query;
00689     }
00690     n = pbuf_try_get_at(p, response_offset);
00691     if (n < 0) {
00692       return 0xFFFF;
00693     }
00694   } while (n != 0);
00695 
00696   return response_offset + 1;
00697 }
00698 
00699 /**
00700  * Walk through a compact encoded DNS name and return the end of the name.
00701  *
00702  * @param p pbuf containing the name
00703  * @param query_idx start index into p pointing to encoded DNS name in the DNS server response
00704  * @return index to end of the name
00705  */
00706 static u16_t
00707 dns_skip_name(struct pbuf* p, u16_t query_idx)
00708 {
00709   int n;
00710   u16_t offset = query_idx;
00711 
00712   do {
00713     n = pbuf_try_get_at(p, offset++);
00714     if (n < 0) {
00715       return 0xFFFF;
00716     }
00717     /** @see RFC 1035 - 4.1.4. Message compression */
00718     if ((n & 0xc0) == 0xc0) {
00719       /* Compressed name: since we only want to skip it (not check it), stop here */
00720       break;
00721     } else {
00722       /* Not compressed name */
00723       if (offset + n >= p->tot_len) {
00724         return 0xFFFF;
00725       }
00726       offset = (u16_t)(offset + n);
00727     }
00728     n = pbuf_try_get_at(p, offset);
00729     if (n < 0) {
00730       return 0xFFFF;
00731     }
00732   } while (n != 0);
00733 
00734   return offset + 1;
00735 }
00736 
00737 /**
00738  * Send a DNS query packet.
00739  *
00740  * @param idx the DNS table entry index for which to send a request
00741  * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
00742  */
00743 static err_t
00744 dns_send(u8_t idx)
00745 {
00746   err_t err;
00747   struct dns_hdr hdr;
00748   struct dns_query qry;
00749   struct pbuf *p;
00750   u16_t query_idx, copy_len;
00751   const char *hostname, *hostname_part;
00752   u8_t n;
00753   u8_t pcb_idx;
00754   struct dns_table_entry* entry = &dns_table[idx];
00755 
00756   LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
00757               (u16_t)(entry->server_idx), entry->name));
00758   LWIP_ASSERT("dns server out of array", entry->server_idx < DNS_MAX_SERVERS);
00759   if (ip_addr_isany_val(dns_servers[entry->server_idx])
00760 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
00761       && !entry->is_mdns
00762 #endif
00763     ) {
00764     /* DNS server not valid anymore, e.g. PPP netif has been shut down */
00765     /* call specified callback function if provided */
00766     dns_call_found(idx, NULL);
00767     /* flush this entry */
00768     entry->state = DNS_STATE_UNUSED;
00769     return ERR_OK;
00770   }
00771 
00772   /* if here, we have either a new query or a retry on a previous query to process */
00773   p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(SIZEOF_DNS_HDR + strlen(entry->name) + 2 +
00774                  SIZEOF_DNS_QUERY), PBUF_RAM);
00775   if (p != NULL) {
00776     const ip_addr_t* dst;
00777     u16_t dst_port;
00778     /* fill dns header */
00779     memset(&hdr, 0, SIZEOF_DNS_HDR);
00780     hdr.id = lwip_htons(entry->txid);
00781     hdr.flags1 = DNS_FLAG1_RD;
00782     hdr.numquestions = PP_HTONS(1);
00783     pbuf_take(p, &hdr, SIZEOF_DNS_HDR);
00784     hostname = entry->name;
00785     --hostname;
00786 
00787     /* convert hostname into suitable query format. */
00788     query_idx = SIZEOF_DNS_HDR;
00789     do {
00790       ++hostname;
00791       hostname_part = hostname;
00792       for (n = 0; *hostname != '.' && *hostname != 0; ++hostname) {
00793         ++n;
00794       }
00795       copy_len = (u16_t)(hostname - hostname_part);
00796       pbuf_put_at(p, query_idx, n);
00797       pbuf_take_at(p, hostname_part, copy_len, query_idx + 1);
00798       query_idx += n + 1;
00799     } while (*hostname != 0);
00800     pbuf_put_at(p, query_idx, 0);
00801     query_idx++;
00802 
00803     /* fill dns query */
00804     if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype)) {
00805       qry.type = PP_HTONS(DNS_RRTYPE_AAAA);
00806     } else {
00807       qry.type = PP_HTONS(DNS_RRTYPE_A);
00808     }
00809     qry.cls = PP_HTONS(DNS_RRCLASS_IN);
00810     pbuf_take_at(p, &qry, SIZEOF_DNS_QUERY, query_idx);
00811 
00812 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
00813     pcb_idx = entry->pcb_idx;
00814 #else
00815     pcb_idx = 0;
00816 #endif
00817     /* send dns packet */
00818     LWIP_DEBUGF(DNS_DEBUG, ("sending DNS request ID %d for name \"%s\" to server %d\r\n",
00819       entry->txid, entry->name, entry->server_idx));
00820 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
00821     if (entry->is_mdns) {
00822       dst_port = DNS_MQUERY_PORT;
00823 #if LWIP_IPV6
00824       if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
00825       {
00826         dst = &dns_mquery_v6group;
00827       }
00828 #endif
00829 #if LWIP_IPV4 && LWIP_IPV6
00830       else
00831 #endif
00832 #if LWIP_IPV4
00833       {
00834         dst = &dns_mquery_v4group;
00835       }
00836 #endif
00837     } else
00838 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
00839     {
00840       dst_port = DNS_SERVER_PORT;
00841       dst = &dns_servers[entry->server_idx];
00842     }
00843     err = udp_sendto(dns_pcbs[pcb_idx], p, dst, dst_port);
00844 
00845     /* free pbuf */
00846     pbuf_free(p);
00847   } else {
00848     err = ERR_MEM;
00849   }
00850 
00851   return err;
00852 }
00853 
00854 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
00855 static struct udp_pcb*
00856 dns_alloc_random_port(void)
00857 {
00858   err_t err;
00859   struct udp_pcb* ret;
00860 
00861   ret = udp_new_ip_type(IPADDR_TYPE_ANY);
00862   if (ret == NULL) {
00863     /* out of memory, have to reuse an existing pcb */
00864     return NULL;
00865   }
00866   do {
00867     u16_t port = (u16_t)DNS_RAND_TXID();
00868     if (!DNS_PORT_ALLOWED(port)) {
00869       /* this port is not allowed, try again */
00870       err = ERR_USE;
00871       continue;
00872     }
00873     err = udp_bind(ret, IP_ANY_TYPE, port);
00874   } while (err == ERR_USE);
00875   if (err != ERR_OK) {
00876     udp_remove(ret);
00877     return NULL;
00878   }
00879   udp_recv(ret, dns_recv, NULL);
00880   return ret;
00881 }
00882 
00883 /**
00884  * dns_alloc_pcb() - allocates a new pcb (or reuses an existing one) to be used
00885  * for sending a request
00886  *
00887  * @return an index into dns_pcbs
00888  */
00889 static u8_t
00890 dns_alloc_pcb(void)
00891 {
00892   u8_t i;
00893   u8_t idx;
00894 
00895   for (i = 0; i < DNS_MAX_SOURCE_PORTS; i++) {
00896     if (dns_pcbs[i] == NULL) {
00897       break;
00898     }
00899   }
00900   if (i < DNS_MAX_SOURCE_PORTS) {
00901     dns_pcbs[i] = dns_alloc_random_port();
00902     if (dns_pcbs[i] != NULL) {
00903       /* succeeded */
00904       dns_last_pcb_idx = i;
00905       return i;
00906     }
00907   }
00908   /* if we come here, creating a new UDP pcb failed, so we have to use
00909      an already existing one */
00910   for (i = 0, idx = dns_last_pcb_idx + 1; i < DNS_MAX_SOURCE_PORTS; i++, idx++) {
00911     if (idx >= DNS_MAX_SOURCE_PORTS) {
00912       idx = 0;
00913     }
00914     if (dns_pcbs[idx] != NULL) {
00915       dns_last_pcb_idx = idx;
00916       return idx;
00917     }
00918   }
00919   return DNS_MAX_SOURCE_PORTS;
00920 }
00921 #endif /* ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0) */
00922 
00923 /**
00924  * dns_call_found() - call the found callback and check if there are duplicate
00925  * entries for the given hostname. If there are any, their found callback will
00926  * be called and they will be removed.
00927  *
00928  * @param idx dns table index of the entry that is resolved or removed
00929  * @param addr IP address for the hostname (or NULL on error or memory shortage)
00930  */
00931 static void
00932 dns_call_found(u8_t idx, ip_addr_t* addr)
00933 {
00934 #if ((LWIP_DNS_SECURE & (LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT)) != 0)
00935   u8_t i;
00936 #endif
00937 
00938 #if LWIP_IPV4 && LWIP_IPV6
00939   if (addr != NULL) {
00940     /* check that address type matches the request and adapt the table entry */
00941     if (IP_IS_V6_VAL(*addr)) {
00942       LWIP_ASSERT("invalid response", LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
00943       dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
00944     } else {
00945       LWIP_ASSERT("invalid response", !LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
00946       dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
00947     }
00948   }
00949 #endif /* LWIP_IPV4 && LWIP_IPV6 */
00950 
00951 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
00952   for (i = 0; i < DNS_MAX_REQUESTS; i++) {
00953     if (dns_requests[i].found && (dns_requests[i].dns_table_idx == idx)) {
00954       (*dns_requests[i].found)(dns_table[idx].name, addr, dns_requests[i].arg);
00955       /* flush this entry */
00956       dns_requests[i].found = NULL;
00957     }
00958   }
00959 #else
00960   if (dns_requests[idx].found) {
00961     (*dns_requests[idx].found)(dns_table[idx].name, addr, dns_requests[idx].arg);
00962   }
00963   dns_requests[idx].found = NULL;
00964 #endif
00965 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
00966   /* close the pcb used unless other request are using it */
00967   for (i = 0; i < DNS_MAX_REQUESTS; i++) {
00968     if (i == idx) {
00969       continue; /* only check other requests */
00970     }
00971     if (dns_table[i].state == DNS_STATE_ASKING) {
00972       if (dns_table[i].pcb_idx == dns_table[idx].pcb_idx) {
00973         /* another request is still using the same pcb */
00974         dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
00975         break;
00976       }
00977     }
00978   }
00979   if (dns_table[idx].pcb_idx < DNS_MAX_SOURCE_PORTS) {
00980     /* if we come here, the pcb is not used any more and can be removed */
00981     udp_remove(dns_pcbs[dns_table[idx].pcb_idx]);
00982     dns_pcbs[dns_table[idx].pcb_idx] = NULL;
00983     dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
00984   }
00985 #endif
00986 }
00987 
00988 /* Create a query transmission ID that is unique for all outstanding queries */
00989 static u16_t
00990 dns_create_txid(void)
00991 {
00992   u16_t txid;
00993   u8_t i;
00994 
00995 again:
00996   txid = (u16_t)DNS_RAND_TXID();
00997 
00998   /* check whether the ID is unique */
00999   for (i = 0; i < DNS_TABLE_SIZE; i++) {
01000     if ((dns_table[i].state == DNS_STATE_ASKING) &&
01001         (dns_table[i].txid == txid)) {
01002       /* ID already used by another pending query */
01003       goto again;
01004     }
01005   }
01006 
01007   return txid;
01008 }
01009 
01010 /**
01011  * dns_check_entry() - see if entry has not yet been queried and, if so, sends out a query.
01012  * Check an entry in the dns_table:
01013  * - send out query for new entries
01014  * - retry old pending entries on timeout (also with different servers)
01015  * - remove completed entries from the table if their TTL has expired
01016  *
01017  * @param i index of the dns_table entry to check
01018  */
01019 static void
01020 dns_check_entry(u8_t i)
01021 {
01022   err_t err;
01023   struct dns_table_entry *entry = &dns_table[i];
01024 
01025   LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
01026 
01027   switch (entry->state) {
01028     case DNS_STATE_NEW:
01029       /* initialize new entry */
01030       entry->txid = dns_create_txid();
01031       entry->state = DNS_STATE_ASKING;
01032       entry->server_idx = 0;
01033       entry->tmr = 1;
01034       entry->retries = 0;
01035 
01036       /* send DNS packet for this entry */
01037       err = dns_send(i);
01038       if (err != ERR_OK) {
01039         LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
01040                     ("dns_send returned error: %s\n", lwip_strerr(err)));
01041       }
01042       break;
01043     case DNS_STATE_ASKING:
01044       if (--entry->tmr == 0) {
01045         if (++entry->retries == DNS_MAX_RETRIES) {
01046           if ((entry->server_idx + 1 < DNS_MAX_SERVERS) && !ip_addr_isany_val(dns_servers[entry->server_idx + 1])
01047 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
01048             && !entry->is_mdns
01049 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
01050             ) {
01051             /* change of server */
01052             entry->server_idx++;
01053             entry->tmr = 1;
01054             entry->retries = 0;
01055           } else {
01056             LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", entry->name));
01057             /* call specified callback function if provided */
01058             dns_call_found(i, NULL);
01059             /* flush this entry */
01060             entry->state = DNS_STATE_UNUSED;
01061             break;
01062           }
01063         } else {
01064           /* wait longer for the next retry */
01065           entry->tmr = entry->retries;
01066         }
01067 
01068         /* send DNS packet for this entry */
01069         err = dns_send(i);
01070         if (err != ERR_OK) {
01071           LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
01072                       ("dns_send returned error: %s\n", lwip_strerr(err)));
01073         }
01074       }
01075       break;
01076     case DNS_STATE_DONE:
01077       /* if the time to live is nul */
01078       if ((entry->ttl == 0) || (--entry->ttl == 0)) {
01079         LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", entry->name));
01080         /* flush this entry, there cannot be any related pending entries in this state */
01081         entry->state = DNS_STATE_UNUSED;
01082       }
01083       break;
01084     case DNS_STATE_UNUSED:
01085       /* nothing to do */
01086       break;
01087     default:
01088       LWIP_ASSERT("unknown dns_table entry state:", 0);
01089       break;
01090   }
01091 }
01092 
01093 /**
01094  * Call dns_check_entry for each entry in dns_table - check all entries.
01095  */
01096 static void
01097 dns_check_entries(void)
01098 {
01099   u8_t i;
01100 
01101   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
01102     dns_check_entry(i);
01103   }
01104 }
01105 
01106 /**
01107  * Save TTL and call dns_call_found for correct response.
01108  */
01109 static void
01110 dns_correct_response(u8_t idx, u32_t ttl)
01111 {
01112   struct dns_table_entry *entry = &dns_table[idx];
01113 
01114   entry->state = DNS_STATE_DONE;
01115 
01116   LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", entry->name));
01117   ip_addr_debug_print(DNS_DEBUG, (&(entry->ipaddr)));
01118   LWIP_DEBUGF(DNS_DEBUG, ("\n"));
01119 
01120   /* read the answer resource record's TTL, and maximize it if needed */
01121   entry->ttl = ttl;
01122   if (entry->ttl > DNS_MAX_TTL) {
01123     entry->ttl = DNS_MAX_TTL;
01124   }
01125   dns_call_found(idx, &entry->ipaddr);
01126 
01127   if (entry->ttl == 0) {
01128     /* RFC 883, page 29: "Zero values are
01129        interpreted to mean that the RR can only be used for the
01130        transaction in progress, and should not be cached."
01131        -> flush this entry now */
01132     /* entry reused during callback? */
01133     if (entry->state == DNS_STATE_DONE) {
01134       entry->state = DNS_STATE_UNUSED;
01135     }
01136   }
01137 }
01138 /**
01139  * Receive input function for DNS response packets arriving for the dns UDP pcb.
01140  */
01141 static void
01142 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
01143 {
01144   u8_t i;
01145   u16_t txid;
01146   u16_t res_idx;
01147   struct dns_hdr hdr;
01148   struct dns_answer ans;
01149   struct dns_query qry;
01150   u16_t nquestions, nanswers;
01151 
01152   LWIP_UNUSED_ARG(arg);
01153   LWIP_UNUSED_ARG(pcb);
01154   LWIP_UNUSED_ARG(port);
01155 
01156   /* is the dns message big enough ? */
01157   if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY)) {
01158     LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
01159     /* free pbuf and return */
01160     goto memerr;
01161   }
01162 
01163   /* copy dns payload inside static buffer for processing */
01164   if (pbuf_copy_partial(p, &hdr, SIZEOF_DNS_HDR, 0) == SIZEOF_DNS_HDR) {
01165     /* Match the ID in the DNS header with the name table. */
01166     txid = lwip_htons(hdr.id);
01167     for (i = 0; i < DNS_TABLE_SIZE; i++) {
01168       const struct dns_table_entry *entry = &dns_table[i];
01169       if ((entry->state == DNS_STATE_ASKING) &&
01170           (entry->txid == txid)) {
01171 
01172         /* We only care about the question(s) and the answers. The authrr
01173            and the extrarr are simply discarded. */
01174         nquestions = lwip_htons(hdr.numquestions);
01175         nanswers   = lwip_htons(hdr.numanswers);
01176 
01177         /* Check for correct response. */
01178         if ((hdr.flags1 & DNS_FLAG1_RESPONSE) == 0) {
01179           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": not a response\n", entry->name));
01180           goto memerr; /* ignore this packet */
01181         }
01182         if (nquestions != 1) {
01183           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
01184           goto memerr; /* ignore this packet */
01185         }
01186 
01187 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
01188         if (!entry->is_mdns)
01189 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
01190         {
01191           /* Check whether response comes from the same network address to which the
01192              question was sent. (RFC 5452) */
01193           if (!ip_addr_cmp(addr, &dns_servers[entry->server_idx])) {
01194             goto memerr; /* ignore this packet */
01195           }
01196         }
01197 
01198         /* Check if the name in the "question" part match with the name in the entry and
01199            skip it if equal. */
01200         res_idx = dns_compare_name(entry->name, p, SIZEOF_DNS_HDR);
01201         if (res_idx == 0xFFFF) {
01202           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
01203           goto memerr; /* ignore this packet */
01204         }
01205 
01206         /* check if "question" part matches the request */
01207         if (pbuf_copy_partial(p, &qry, SIZEOF_DNS_QUERY, res_idx) != SIZEOF_DNS_QUERY) {
01208           goto memerr; /* ignore this packet */
01209         }
01210         if ((qry.cls != PP_HTONS(DNS_RRCLASS_IN)) ||
01211           (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_AAAA))) ||
01212           (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_A)))) {
01213           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
01214           goto memerr; /* ignore this packet */
01215         }
01216         /* skip the rest of the "question" part */
01217         res_idx += SIZEOF_DNS_QUERY;
01218 
01219         /* Check for error. If so, call callback to inform. */
01220         if (hdr.flags2 & DNS_FLAG2_ERR_MASK) {
01221           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", entry->name));
01222         } else {
01223           while ((nanswers > 0) && (res_idx < p->tot_len)) {
01224             /* skip answer resource record's host name */
01225             res_idx = dns_skip_name(p, res_idx);
01226             if (res_idx == 0xFFFF) {
01227               goto memerr; /* ignore this packet */
01228             }
01229 
01230             /* Check for IP address type and Internet class. Others are discarded. */
01231             if (pbuf_copy_partial(p, &ans, SIZEOF_DNS_ANSWER, res_idx) != SIZEOF_DNS_ANSWER) {
01232               goto memerr; /* ignore this packet */
01233             }
01234             res_idx += SIZEOF_DNS_ANSWER;
01235 
01236             if (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) {
01237 #if LWIP_IPV4
01238               if ((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.len == PP_HTONS(sizeof(ip4_addr_t)))) {
01239 #if LWIP_IPV4 && LWIP_IPV6
01240                 if (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
01241 #endif /* LWIP_IPV4 && LWIP_IPV6 */
01242                 {
01243                   ip4_addr_t ip4addr;
01244                   /* read the IP address after answer resource record's header */
01245                   if (pbuf_copy_partial(p, &ip4addr, sizeof(ip4_addr_t), res_idx) != sizeof(ip4_addr_t)) {
01246                     goto memerr; /* ignore this packet */
01247                   }
01248                   ip_addr_copy_from_ip4(dns_table[i].ipaddr, ip4addr);
01249                   pbuf_free(p);
01250                   /* handle correct response */
01251                   dns_correct_response(i, lwip_ntohl(ans.ttl));
01252                   return;
01253                 }
01254               }
01255 #endif /* LWIP_IPV4 */
01256 #if LWIP_IPV6
01257               if ((ans.type == PP_HTONS(DNS_RRTYPE_AAAA)) && (ans.len == PP_HTONS(sizeof(ip6_addr_t)))) {
01258 #if LWIP_IPV4 && LWIP_IPV6
01259                 if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
01260 #endif /* LWIP_IPV4 && LWIP_IPV6 */
01261                 {
01262                   ip6_addr_t ip6addr;
01263                   /* read the IP address after answer resource record's header */
01264                   if (pbuf_copy_partial(p, &ip6addr, sizeof(ip6_addr_t), res_idx) != sizeof(ip6_addr_t)) {
01265                     goto memerr; /* ignore this packet */
01266                   }
01267                   ip_addr_copy_from_ip6(dns_table[i].ipaddr, ip6addr);
01268                   pbuf_free(p);
01269                   /* handle correct response */
01270                   dns_correct_response(i, lwip_ntohl(ans.ttl));
01271                   return;
01272                 }
01273               }
01274 #endif /* LWIP_IPV6 */
01275             }
01276             /* skip this answer */
01277             if ((int)(res_idx + lwip_htons(ans.len)) > 0xFFFF) {
01278               goto memerr; /* ignore this packet */
01279             }
01280             res_idx += lwip_htons(ans.len);
01281             --nanswers;
01282           }
01283 #if LWIP_IPV4 && LWIP_IPV6
01284           if ((entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) ||
01285               (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
01286             if (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
01287               /* IPv4 failed, try IPv6 */
01288               dns_table[i].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
01289             } else {
01290               /* IPv6 failed, try IPv4 */
01291               dns_table[i].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
01292             }
01293             pbuf_free(p);
01294             dns_table[i].state = DNS_STATE_NEW;
01295             dns_check_entry(i);
01296             return;
01297           }
01298 #endif /* LWIP_IPV4 && LWIP_IPV6 */
01299           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", entry->name));
01300         }
01301         /* call callback to indicate error, clean up memory and return */
01302         pbuf_free(p);
01303         dns_call_found(i, NULL);
01304         dns_table[i].state = DNS_STATE_UNUSED;
01305         return;
01306       }
01307     }
01308   }
01309 
01310 memerr:
01311   /* deallocate memory and return */
01312   pbuf_free(p);
01313   return;
01314 }
01315 
01316 /**
01317  * Queues a new hostname to resolve and sends out a DNS query for that hostname
01318  *
01319  * @param name the hostname that is to be queried
01320  * @param hostnamelen length of the hostname
01321  * @param found a callback function to be called on success, failure or timeout
01322  * @param callback_arg argument to pass to the callback function
01323  * @return err_t return code.
01324  */
01325 static err_t
01326 dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
01327             void *callback_arg LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype) LWIP_DNS_ISMDNS_ARG(u8_t is_mdns))
01328 {
01329   u8_t i;
01330   u8_t lseq, lseqi;
01331   struct dns_table_entry *entry = NULL;
01332   size_t namelen;
01333   struct dns_req_entry* req;
01334 
01335 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
01336   u8_t r;
01337   /* check for duplicate entries */
01338   for (i = 0; i < DNS_TABLE_SIZE; i++) {
01339     if ((dns_table[i].state == DNS_STATE_ASKING) &&
01340         (lwip_strnicmp(name, dns_table[i].name, sizeof(dns_table[i].name)) == 0)) {
01341 #if LWIP_IPV4 && LWIP_IPV6
01342       if (dns_table[i].reqaddrtype != dns_addrtype) {
01343         /* requested address types don't match
01344            this can lead to 2 concurrent requests, but mixing the address types
01345            for the same host should not be that common */
01346         continue;
01347       }
01348 #endif /* LWIP_IPV4 && LWIP_IPV6 */
01349       /* this is a duplicate entry, find a free request entry */
01350       for (r = 0; r < DNS_MAX_REQUESTS; r++) {
01351         if (dns_requests[r].found == 0) {
01352           dns_requests[r].found = found;
01353           dns_requests[r].arg = callback_arg;
01354           dns_requests[r].dns_table_idx = i;
01355           LWIP_DNS_SET_ADDRTYPE(dns_requests[r].reqaddrtype, dns_addrtype);
01356           LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": duplicate request\n", name));
01357           return ERR_INPROGRESS;
01358         }
01359       }
01360     }
01361   }
01362   /* no duplicate entries found */
01363 #endif
01364 
01365   /* search an unused entry, or the oldest one */
01366   lseq = 0;
01367   lseqi = DNS_TABLE_SIZE;
01368   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
01369     entry = &dns_table[i];
01370     /* is it an unused entry ? */
01371     if (entry->state == DNS_STATE_UNUSED) {
01372       break;
01373     }
01374     /* check if this is the oldest completed entry */
01375     if (entry->state == DNS_STATE_DONE) {
01376       u8_t age = dns_seqno - entry->seqno;
01377       if (age > lseq) {
01378         lseq = age;
01379         lseqi = i;
01380       }
01381     }
01382   }
01383 
01384   /* if we don't have found an unused entry, use the oldest completed one */
01385   if (i == DNS_TABLE_SIZE) {
01386     if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
01387       /* no entry can be used now, table is full */
01388       LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
01389       return ERR_MEM;
01390     } else {
01391       /* use the oldest completed one */
01392       i = lseqi;
01393       entry = &dns_table[i];
01394     }
01395   }
01396 
01397 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
01398   /* find a free request entry */
01399   req = NULL;
01400   for (r = 0; r < DNS_MAX_REQUESTS; r++) {
01401     if (dns_requests[r].found == NULL) {
01402       req = &dns_requests[r];
01403       break;
01404     }
01405   }
01406   if (req == NULL) {
01407     /* no request entry can be used now, table is full */
01408     LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS request entries table is full\n", name));
01409     return ERR_MEM;
01410   }
01411   req->dns_table_idx = i;
01412 #else
01413   /* in this configuration, the entry index is the same as the request index */
01414   req = &dns_requests[i];
01415 #endif
01416 
01417   /* use this entry */
01418   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
01419 
01420   /* fill the entry */
01421   entry->state = DNS_STATE_NEW;
01422   entry->seqno = dns_seqno;
01423   LWIP_DNS_SET_ADDRTYPE(entry->reqaddrtype, dns_addrtype);
01424   LWIP_DNS_SET_ADDRTYPE(req->reqaddrtype, dns_addrtype);
01425   req->found = found;
01426   req->arg   = callback_arg;
01427   namelen = LWIP_MIN(hostnamelen, DNS_MAX_NAME_LENGTH-1);
01428   MEMCPY(entry->name, name, namelen);
01429   entry->name[namelen] = 0;
01430 
01431 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
01432   entry->pcb_idx = dns_alloc_pcb();
01433   if (entry->pcb_idx >= DNS_MAX_SOURCE_PORTS) {
01434     /* failed to get a UDP pcb */
01435     LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": failed to allocate a pcb\n", name));
01436     entry->state = DNS_STATE_UNUSED;
01437     req->found = NULL;
01438     return ERR_MEM;
01439   }
01440   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS pcb %"U16_F"\n", name, (u16_t)(entry->pcb_idx)));
01441 #endif
01442 
01443 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
01444   entry->is_mdns = is_mdns;
01445 #endif
01446 
01447   dns_seqno++;
01448 
01449   /* force to send query without waiting timer */
01450   dns_check_entry(i);
01451 
01452   /* dns query is enqueued */
01453   return ERR_INPROGRESS;
01454 }
01455 
01456 /**
01457  * @ingroup dns
01458  * Resolve a hostname (string) into an IP address.
01459  * NON-BLOCKING callback version for use with raw API!!!
01460  *
01461  * Returns immediately with one of err_t return codes:
01462  * - ERR_OK if hostname is a valid IP address string or the host
01463  *   name is already in the local names table.
01464  * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
01465  *   for resolution if no errors are present.
01466  * - ERR_ARG: dns client not initialized or invalid hostname
01467  *
01468  * @param hostname the hostname that is to be queried
01469  * @param addr pointer to a ip_addr_t where to store the address if it is already
01470  *             cached in the dns_table (only valid if ERR_OK is returned!)
01471  * @param found a callback function to be called on success, failure or timeout (only if
01472  *              ERR_INPROGRESS is returned!)
01473  * @param callback_arg argument to pass to the callback function
01474  * @return a err_t return code.
01475  */
01476 err_t
01477 dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found,
01478                   void *callback_arg)
01479 {
01480   return dns_gethostbyname_addrtype(hostname, addr, found, callback_arg, LWIP_DNS_ADDRTYPE_DEFAULT);
01481 }
01482 
01483 /**
01484  * @ingroup dns
01485  * Like dns_gethostbyname, but returned address type can be controlled:
01486  * @param hostname the hostname that is to be queried
01487  * @param addr pointer to a ip_addr_t where to store the address if it is already
01488  *             cached in the dns_table (only valid if ERR_OK is returned!)
01489  * @param found a callback function to be called on success, failure or timeout (only if
01490  *              ERR_INPROGRESS is returned!)
01491  * @param callback_arg argument to pass to the callback function
01492  * @param dns_addrtype - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 first, try IPv6 if IPv4 fails only
01493  *                     - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 first, try IPv4 if IPv6 fails only
01494  *                     - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
01495  *                     - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
01496  */
01497 err_t
01498 dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, dns_found_callback found,
01499                            void *callback_arg, u8_t dns_addrtype)
01500 {
01501   size_t hostnamelen;
01502 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
01503   u8_t is_mdns;
01504 #endif
01505   /* not initialized or no valid server yet, or invalid addr pointer
01506    * or invalid hostname or invalid hostname length */
01507   if ((addr == NULL) ||
01508       (!hostname) || (!hostname[0])) {
01509     return ERR_ARG;
01510   }
01511 #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
01512   if (dns_pcbs[0] == NULL) {
01513     return ERR_ARG;
01514   }
01515 #endif
01516   hostnamelen = strlen(hostname);
01517   if (hostnamelen >= DNS_MAX_NAME_LENGTH) {
01518     LWIP_DEBUGF(DNS_DEBUG, ("dns_gethostbyname: name too long to resolve"));
01519     return ERR_ARG;
01520   }
01521 
01522 
01523 #if LWIP_HAVE_LOOPIF
01524   if (strcmp(hostname, "localhost") == 0) {
01525     ip_addr_set_loopback(LWIP_DNS_ADDRTYPE_IS_IPV6(dns_addrtype), addr);
01526     return ERR_OK;
01527   }
01528 #endif /* LWIP_HAVE_LOOPIF */
01529 
01530   /* host name already in octet notation? set ip addr and return ERR_OK */
01531   if (ipaddr_aton(hostname, addr)) {
01532 #if LWIP_IPV4 && LWIP_IPV6
01533     if ((IP_IS_V6(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV4)) ||
01534         (IP_IS_V4(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV6)))
01535 #endif /* LWIP_IPV4 && LWIP_IPV6 */
01536     {
01537       return ERR_OK;
01538     }
01539   }
01540   /* already have this address cached? */
01541   if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
01542     return ERR_OK;
01543   }
01544 #if LWIP_IPV4 && LWIP_IPV6
01545   if ((dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) || (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
01546     /* fallback to 2nd IP type and try again to lookup */
01547     u8_t fallback;
01548     if (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
01549       fallback = LWIP_DNS_ADDRTYPE_IPV6;
01550     } else {
01551       fallback = LWIP_DNS_ADDRTYPE_IPV4;
01552     }
01553     if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(fallback)) == ERR_OK) {
01554       return ERR_OK;
01555     }
01556   }
01557 #else /* LWIP_IPV4 && LWIP_IPV6 */
01558   LWIP_UNUSED_ARG(dns_addrtype);
01559 #endif /* LWIP_IPV4 && LWIP_IPV6 */
01560 
01561 #if LWIP_DNS_SUPPORT_MDNS_QUERIES
01562   if (strstr(hostname, ".local") == &hostname[hostnamelen] - 6) {
01563     is_mdns = 1;
01564   } else {
01565     is_mdns = 0;
01566   }
01567 
01568   if (!is_mdns)
01569 #endif /* LWIP_DNS_SUPPORT_MDNS_QUERIES */
01570   {
01571     /* prevent calling found callback if no server is set, return error instead */
01572     if (ip_addr_isany_val(dns_servers[0])) {
01573       return ERR_VAL;
01574     }
01575   }
01576 
01577   /* queue query with specified callback */
01578   return dns_enqueue(hostname, hostnamelen, found, callback_arg LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)
01579      LWIP_DNS_ISMDNS_ARG(is_mdns));
01580 }
01581 
01582 #endif /* LWIP_FULL_DNS */
01583 
01584 #endif /* LWIP_DNS */