]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lwip.git/blob - src/core/dns.c
cb3d0a6834a04c54cbfce079619ee328da8a0f74
[pes-rpp/rpp-lwip.git] / src / core / dns.c
1 /**
2  * @file
3  * DNS - host name to IP address resolver.
4  *
5  */
6
7 /**
8
9  * This file implements a DNS host name to IP address resolver.
10
11  * Port to lwIP from uIP
12  * by Jim Pettinato April 2007
13
14  * uIP version Copyright (c) 2002-2003, Adam Dunkels.
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
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
27  *    written permission.
28  *
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.
40  *
41  *
42  * DNS.C
43  *
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.
48  *
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.
56  *
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).
60  */
61
62 /*-----------------------------------------------------------------------------
63  * RFC 1035 - Domain names - implementation and specification
64  * RFC 2181 - Clarifications to the DNS Specification
65  *----------------------------------------------------------------------------*/
66
67 /** @todo: define good default values (rfc compliance) */
68 /** @todo: improve answer parsing, more checkings... */
69 /** @todo: check RFC1035 - 7.3. Processing responses */
70
71 /*-----------------------------------------------------------------------------
72  * Includes
73  *----------------------------------------------------------------------------*/
74
75 #include "lwip/opt.h"
76
77 #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
78
79 #include "lwip/udp.h"
80 #include "lwip/mem.h"
81 #include "lwip/dns.h"
82
83 #include <string.h>
84
85 /** DNS server IP address */
86 #ifndef DNS_SERVER_ADDRESS
87 #define DNS_SERVER_ADDRESS        inet_addr("208.67.222.222") /* resolver1.opendns.com */
88 #endif
89
90 /** DNS server port address */
91 #ifndef DNS_SERVER_PORT
92 #define DNS_SERVER_PORT           53
93 #endif
94
95 /** DNS maximum number of retries when asking for a name, before "timeout". */
96 #ifndef DNS_MAX_RETRIES
97 #define DNS_MAX_RETRIES           4
98 #endif
99
100 /** DNS resource record max. TTL (one week as default) */
101 #ifndef DNS_MAX_TTL
102 #define DNS_MAX_TTL               604800
103 #endif
104
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
117
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
123
124 #ifdef PACK_STRUCT_USE_INCLUDES
125 #  include "arch/bpstruct.h"
126 #endif
127 PACK_STRUCT_BEGIN
128 /** DNS message header */
129 struct dns_hdr {
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;
138 PACK_STRUCT_END
139 #ifdef PACK_STRUCT_USE_INCLUDES
140 #  include "arch/epstruct.h"
141 #endif
142 #define SIZEOF_DNS_HDR 12
143
144 #ifdef PACK_STRUCT_USE_INCLUDES
145 #  include "arch/bpstruct.h"
146 #endif
147 PACK_STRUCT_BEGIN
148 /** DNS query message structure */
149 struct dns_query {
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;
155 PACK_STRUCT_END
156 #ifdef PACK_STRUCT_USE_INCLUDES
157 #  include "arch/epstruct.h"
158 #endif
159 #define SIZEOF_DNS_QUERY 4
160
161 #ifdef PACK_STRUCT_USE_INCLUDES
162 #  include "arch/bpstruct.h"
163 #endif
164 PACK_STRUCT_BEGIN
165 /** DNS answer message structure */
166 struct dns_answer {
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;
174 PACK_STRUCT_END
175 #ifdef PACK_STRUCT_USE_INCLUDES
176 #  include "arch/epstruct.h"
177 #endif
178 #define SIZEOF_DNS_ANSWER 10
179
180 /** DNS table entry */
181 struct dns_table_entry {
182   u8_t  state;
183   u8_t  numdns;
184   u8_t  tmr;
185   u8_t  retries;
186   u8_t  seqno;
187   u8_t  err;
188   u32_t ttl;
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;
193   void *arg;
194 };
195
196 #if DNS_LOCAL_HOSTLIST
197 /** struct used for local host-list */
198 struct local_hostlist_entry {
199   /** static hostname */
200   const char *name;
201   /** static host address in network byteorder */
202   u32_t addr;
203   struct local_hostlist_entry *next;
204 };
205
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 */
211
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;
224
225 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
226
227 static void dns_init_local();
228 #endif /* DNS_LOCAL_HOSTLIST */
229
230
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);
234
235 /*-----------------------------------------------------------------------------
236  * Globales
237  *----------------------------------------------------------------------------*/
238
239 /* DNS variables */
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];
244
245 #if (DNS_USES_STATIC_BUF == 1)
246 static u8_t                   dns_payload[DNS_MSG_SIZE];
247 #endif /* (DNS_USES_STATIC_BUF == 1) */
248
249 /**
250  * Initialize the resolver: set up the UDP pcb and configure the default server
251  * (DNS_SERVER_ADDRESS).
252  */
253 void
254 dns_init()
255 {
256   struct ip_addr dnsserver;
257   
258   /* initialize default DNS server address */
259   dnsserver.addr = DNS_SERVER_ADDRESS;
260
261   LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
262
263   /* if dns client not yet initialized... */
264   if (dns_pcb == NULL) {
265     dns_pcb = udp_new();
266
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);
272
273       /* initialize DNS client */
274       udp_bind(dns_pcb, IP_ADDR_ANY, 0);
275       udp_recv(dns_pcb, dns_recv, NULL);
276
277       /* initialize default DNS primary server */
278       dns_setserver(0, &dnsserver);
279     }
280   }
281 #if DNS_LOCAL_HOSTLIST
282   dns_init_local();
283 #endif
284 }
285
286 /**
287  * Initialize one of the DNS servers.
288  *
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
291  */
292 void
293 dns_setserver(u8_t numdns, struct ip_addr *dnsserver)
294 {
295   if ((numdns < DNS_MAX_SERVERS) && (dns_pcb != NULL) &&
296       (dnsserver != NULL) && (dnsserver->addr !=0 )) {
297     dns_servers[numdns] = (*dnsserver);
298   }
299 }
300
301 /**
302  * Obtain one of the currently configured DNS server.
303  *
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.
307  */
308 struct ip_addr
309 dns_getserver(u8_t numdns)
310 {
311   if (numdns < DNS_MAX_SERVERS) {
312     return dns_servers[numdns];
313   } else {
314     return *IP_ADDR_ANY;
315   }
316 }
317
318 /**
319  * The DNS resolver client timer - handle retries and timeouts and should
320  * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
321  */
322 void
323 dns_tmr(void)
324 {
325   if (dns_pcb != NULL) {
326     LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
327     dns_check_entries();
328   }
329 }
330
331 #if DNS_LOCAL_HOSTLIST
332 static void
333 dns_init_local()
334 {
335 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
336   int i;
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;
340   size_t namelen;
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);
347     if (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;
354     }
355   }
356 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
357 }
358
359 /**
360  * Scans the local host-list for a hostname.
361  *
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.
365  */
366 static u32_t
367 dns_lookup_local(const char *hostname)
368 {
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) {
373       return entry->addr;
374     }
375     entry = entry->next;
376   }
377 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
378   int i;
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;
382     }
383   }
384 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
385   return INADDR_NONE;
386 }
387
388 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
389 /** Remove all entries from the local host-list for a specific hostname
390  * and/or IP addess
391  *
392  * @param hostname hostname for which entries shall be removed from the local
393  *                 host-list
394  * @param addr address for which entries shall be removed from the local host-list
395  * @return the number of removed entries
396  */
397 int
398 dns_local_removehost(const char *hostname, const struct ip_addr *addr)
399 {
400   int removed = 0;
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;
409       } else {
410         local_hostlist_dynamic = entry->next;
411       }
412       free_entry = entry;
413       entry = entry->next;
414       mem_free(free_entry);
415       removed++;
416     } else {
417       last_entry = entry;
418       entry = entry->next;
419     }
420   }
421   return removed;
422 }
423
424 /**
425  * Add a hostname/IP address pair to the local host-list.
426  * Duplicates are not checked.
427  *
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
431  */
432 err_t
433 dns_local_addhost(const char *hostname, const struct ip_addr *addr)
434 {
435   struct local_hostlist_entry *entry;
436   size_t namelen;
437   LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
438   namelen = strlen(hostname);
439   entry = mem_malloc(sizeof(struct local_hostlist_entry) + namelen + 1);
440   if (entry == NULL) {
441     return ERR_MEM;
442   }
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;
449   return ERR_OK;
450 }
451 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
452 #endif /* DNS_LOCAL_HOSTLIST */
453
454 /**
455  * Look up a hostname in the array of known hostnames.
456  *
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
460  * for a hostname.
461  *
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.
466  */
467 static u32_t
468 dns_lookup(const char *name)
469 {
470   u8_t i;
471 #if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN)
472   u32_t addr;
473 #endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */
474 #if DNS_LOCAL_HOSTLIST
475   if ((addr = dns_lookup_local(name)) != INADDR_NONE) {
476     return addr;
477   }
478 #endif /* DNS_LOCAL_HOSTLIST */
479 #ifdef DNS_LOOKUP_LOCAL_EXTERN
480   if((addr = DNS_LOOKUP_LOCAL_EXTERN(name)) != INADDR_NONE) {
481     return addr;
482   }
483 #endif /* DNS_LOOKUP_LOCAL_EXTERN */
484
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;
493     }
494   }
495
496   return INADDR_NONE;
497 }
498
499 #if DNS_DOES_NAME_CHECK
500 /**
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
504  * any more).
505  *
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
509  */
510 static u8_t
511 dns_compare_name(unsigned char *query, unsigned char *response)
512 {
513   unsigned char n;
514
515   do {
516     n = *response++;
517     /** @see RFC 1035 - 4.1.4. Message compression */
518     if ((n & 0xc0) == 0xc0) {
519       /* Compressed name */
520       break;
521     } else {
522       /* Not compressed name */
523       while (n > 0) {
524         if ((*query) != (*response)) {
525           return 1;
526         }
527         ++response;
528         ++query;
529         --n;
530       };
531       ++query;
532     }
533   } while (*response != 0);
534
535   return 0;
536 }
537 #endif /* DNS_DOES_NAME_CHECK */
538
539 /**
540  * Walk through a compact encoded DNS name and return the end of the name.
541  *
542  * @param query encoded DNS name in the DNS server response
543  * @return end of the name
544  */
545 static unsigned char *
546 dns_parse_name(unsigned char *query)
547 {
548   unsigned char n;
549
550   do {
551     n = *query++;
552     /** @see RFC 1035 - 4.1.4. Message compression */
553     if ((n & 0xc0) == 0xc0) {
554       /* Compressed name */
555       break;
556     } else {
557       /* Not compressed name */
558       while (n > 0) {
559         ++query;
560         --n;
561       };
562     }
563   } while (*query != 0);
564
565   return query + 1;
566 }
567
568 /**
569  * Send a DNS query packet.
570  *
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
574  *        DNS query packet
575  * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
576  */
577 static err_t
578 dns_send(u8_t numdns, const char* name, u8_t id)
579 {
580   err_t err;
581   struct dns_hdr *hdr;
582   struct dns_query qry;
583   struct pbuf *p;
584   char *query, *nptr;
585   const char *pHostname;
586   u8_t n;
587
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);
592
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);
596   if (p != NULL) {
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);
601     hdr->id = htons(id);
602     hdr->flags1 = DNS_FLAG1_RD;
603     hdr->numquestions = htons(1);
604     query = (char*)hdr + SIZEOF_DNS_HDR;
605     pHostname = name;
606     --pHostname;
607
608     /* convert hostname into suitable query format. */
609     do {
610       ++pHostname;
611       nptr = query;
612       ++query;
613       for(n = 0; *pHostname != '.' && *pHostname != 0; ++pHostname) {
614         *query = *pHostname;
615         ++query;
616         ++n;
617       }
618       *nptr = n;
619     } while(*pHostname != 0);
620     *query++='\0';
621
622     /* fill dns query */
623     qry.type  = htons(DNS_RRTYPE_A);
624     qry.class = htons(DNS_RRCLASS_IN);
625     MEMCPY( query, &qry, SIZEOF_DNS_QUERY);
626
627     /* resize pbuf to the exact dns query */
628     pbuf_realloc(p, (query + SIZEOF_DNS_QUERY) - ((char*)(p->payload)));
629
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);
634
635     /* free pbuf */
636     pbuf_free(p);
637   } else {
638     err = ERR_MEM;
639   }
640
641   return err;
642 }
643
644 /**
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
650  *
651  * @param i index of the dns_table entry to check
652  */
653 static void
654 dns_check_entry(u8_t i)
655 {
656   struct dns_table_entry *pEntry = &dns_table[i];
657
658   LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
659
660   switch(pEntry->state) {
661
662     case DNS_STATE_NEW: {
663       /* initialize new entry */
664       pEntry->state   = DNS_STATE_ASKING;
665       pEntry->numdns  = 0;
666       pEntry->tmr     = 1;
667       pEntry->retries = 0;
668       
669       /* send DNS packet for this entry */
670       dns_send(pEntry->numdns, pEntry->name, i);
671       break;
672     }
673
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 */
679             pEntry->numdns++;
680             pEntry->tmr     = 1;
681             pEntry->retries = 0;
682             break;
683           } else {
684             LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", pEntry->name));
685             /* call specified callback function if provided */
686             if (pEntry->found)
687               (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
688             /* flush this entry */
689             pEntry->state   = DNS_STATE_UNUSED;
690             pEntry->found   = NULL;
691             break;
692           }
693         }
694
695         /* wait longer for the next retry */
696         pEntry->tmr = pEntry->retries;
697
698         /* send DNS packet for this entry */
699         dns_send(pEntry->numdns, pEntry->name, i);
700       }
701       break;
702     }
703
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;
711       }
712       break;
713     }
714     case DNS_STATE_UNUSED:
715       /* nothing to do */
716       break;
717     default:
718       LWIP_ASSERT("unknown dns_table entry state:", 0);
719       break;
720   }
721 }
722
723 /**
724  * Call dns_check_entry for each entry in dns_table - check all entries.
725  */
726 static void
727 dns_check_entries(void)
728 {
729   u8_t i;
730
731   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
732     dns_check_entry(i);
733   }
734 }
735
736 /**
737  * Receive input function for DNS response packets arriving for the dns UDP pcb.
738  *
739  * @params see udp.h
740  */
741 static void
742 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, u16_t port)
743 {
744   u8_t i;
745   char *pHostname;
746   struct dns_hdr *hdr;
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)
754   u8_t* dns_payload;
755 #endif /* (DNS_USES_STATIC_BUF == 2) */
756
757   LWIP_UNUSED_ARG(arg);
758   LWIP_UNUSED_ARG(pcb);
759   LWIP_UNUSED_ARG(addr);
760   LWIP_UNUSED_ARG(port);
761
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 */
766     goto memerr1;
767   }
768
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 */
773     goto memerr1;
774   }
775
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 */
781     goto memerr1;
782   }
783 #endif /* (DNS_USES_STATIC_BUF == 2) */
784
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;
789     i = htons(hdr->id);
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;
796
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);
801
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 */
806           goto responseerr;
807         }
808
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 */
814           goto responseerr;
815         }
816 #endif /* DNS_DOES_NAME_CHECK */
817
818         /* Skip the name in the "question" part */
819         pHostname = (char *) dns_parse_name((unsigned char *)dns_payload + SIZEOF_DNS_HDR) + SIZEOF_DNS_QUERY;
820
821         while(nanswers > 0) {
822           /* skip answer resource record's host name */
823           pHostname = (char *) dns_parse_name((unsigned char *)pHostname);
824
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;
832             }
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 */
839             if (pEntry->found) {
840               (*pEntry->found)(pEntry->name, &pEntry->ipaddr, pEntry->arg);
841             }
842             /* deallocate memory and return */
843             goto memerr2;
844           } else {
845             pHostname = pHostname + SIZEOF_DNS_ANSWER + htons(ans.len);
846           }
847           --nanswers;
848         }
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 */
851         goto responseerr;
852       }
853     }
854   }
855
856   /* deallocate memory and return */
857   goto memerr2;
858
859 responseerr:
860   /* ERROR: call specified callback function with NULL as name to indicate an error */
861   if (pEntry->found) {
862     (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
863   }
864   /* flush this entry */
865   pEntry->state = DNS_STATE_UNUSED;
866   pEntry->found = NULL;
867
868 memerr2:
869 #if (DNS_USES_STATIC_BUF == 2)
870   /* free dns buffer */
871   mem_free(dns_payload);
872 #endif /* (DNS_USES_STATIC_BUF == 2) */
873
874 memerr1:
875   /* free pbuf */
876   pbuf_free(p);
877   return;
878 }
879
880 /**
881  * Queues a new hostname to resolve and sends out a DNS query for that hostname
882  *
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.
887  */
888 static err_t
889 dns_enqueue(const char *name, dns_found_callback found, void *callback_arg)
890 {
891   u8_t i;
892   u8_t lseq, lseqi;
893   struct dns_table_entry *pEntry = NULL;
894
895   /* search an unused entry, or the oldest one */
896   lseq = lseqi = 0;
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)
901       break;
902
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;
907         lseqi = i;
908       }
909     }
910   }
911
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));
917       return ERR_MEM;
918     } else {
919       /* use the oldest completed one */
920       i = lseqi;
921       pEntry = &dns_table[i];
922     }
923   }
924
925   /* use this entry */
926   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
927
928   /* fill the entry */
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);
934
935   /* force to send query without waiting timer */
936   dns_check_entry(i);
937
938   /* dns query is enqueued */
939   return ERR_INPROGRESS;
940 }
941
942 /**
943  * Resolve a hostname (string) into an IP address.
944  * NON-BLOCKING callback version for use with raw API!!!
945  *
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.
951  *
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.
959  */
960 err_t
961 dns_gethostbyname(const char *hostname, struct ip_addr *addr, dns_found_callback found,
962                   void *callback_arg)
963 {
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)) {
969     return ERR_VAL;
970   }
971
972 #if LWIP_HAVE_LOOPIF
973   if (strcmp(hostname,"localhost")==0) {
974     addr->addr = htonl(INADDR_LOOPBACK);
975     return ERR_OK;
976   }
977 #endif /* LWIP_HAVE_LOOPIF */
978
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)) {
983     return ERR_OK;
984   }
985
986   /* queue query with specified callback */
987   return dns_enqueue(hostname, found, callback_arg);
988 }
989
990 #endif /* LWIP_DNS */