]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/ankh/lib/lwip/contrib/src/core/dns.c
c3f356cfceace02605bcf27e4e660605b42d7cb5
[l4.git] / l4 / pkg / ankh / lib / lwip / contrib / 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/memp.h"
82 #include "lwip/dns.h"
83
84 #include <string.h>
85
86 /** DNS server IP address */
87 #ifndef DNS_SERVER_ADDRESS
88 #define DNS_SERVER_ADDRESS(ipaddr)        (ip4_addr_set_u32(ipaddr, ipaddr_addr("208.67.222.222"))) /* resolver1.opendns.com */
89 #endif
90
91 /** DNS server port address */
92 #ifndef DNS_SERVER_PORT
93 #define DNS_SERVER_PORT           53
94 #endif
95
96 /** DNS maximum number of retries when asking for a name, before "timeout". */
97 #ifndef DNS_MAX_RETRIES
98 #define DNS_MAX_RETRIES           4
99 #endif
100
101 /** DNS resource record max. TTL (one week as default) */
102 #ifndef DNS_MAX_TTL
103 #define DNS_MAX_TTL               604800
104 #endif
105
106 /* DNS protocol flags */
107 #define DNS_FLAG1_RESPONSE        0x80
108 #define DNS_FLAG1_OPCODE_STATUS   0x10
109 #define DNS_FLAG1_OPCODE_INVERSE  0x08
110 #define DNS_FLAG1_OPCODE_STANDARD 0x00
111 #define DNS_FLAG1_AUTHORATIVE     0x04
112 #define DNS_FLAG1_TRUNC           0x02
113 #define DNS_FLAG1_RD              0x01
114 #define DNS_FLAG2_RA              0x80
115 #define DNS_FLAG2_ERR_MASK        0x0f
116 #define DNS_FLAG2_ERR_NONE        0x00
117 #define DNS_FLAG2_ERR_NAME        0x03
118
119 /* DNS protocol states */
120 #define DNS_STATE_UNUSED          0
121 #define DNS_STATE_NEW             1
122 #define DNS_STATE_ASKING          2
123 #define DNS_STATE_DONE            3
124
125 #ifdef PACK_STRUCT_USE_INCLUDES
126 #  include "arch/bpstruct.h"
127 #endif
128 PACK_STRUCT_BEGIN
129 /** DNS message header */
130 struct dns_hdr {
131   PACK_STRUCT_FIELD(u16_t id);
132   PACK_STRUCT_FIELD(u8_t flags1);
133   PACK_STRUCT_FIELD(u8_t flags2);
134   PACK_STRUCT_FIELD(u16_t numquestions);
135   PACK_STRUCT_FIELD(u16_t numanswers);
136   PACK_STRUCT_FIELD(u16_t numauthrr);
137   PACK_STRUCT_FIELD(u16_t numextrarr);
138 } PACK_STRUCT_STRUCT;
139 PACK_STRUCT_END
140 #ifdef PACK_STRUCT_USE_INCLUDES
141 #  include "arch/epstruct.h"
142 #endif
143 #define SIZEOF_DNS_HDR 12
144
145 /** DNS query message structure.
146     No packing needed: only used locally on the stack. */
147 struct dns_query {
148   /* DNS query record starts with either a domain name or a pointer
149      to a name already present somewhere in the packet. */
150   u16_t type;
151   u16_t cls;
152 };
153 #define SIZEOF_DNS_QUERY 4
154
155 /** DNS answer message structure.
156     No packing needed: only used locally on the stack. */
157 struct dns_answer {
158   /* DNS answer record starts with either a domain name or a pointer
159      to a name already present somewhere in the packet. */
160   u16_t type;
161   u16_t cls;
162   u32_t ttl;
163   u16_t len;
164 };
165 #define SIZEOF_DNS_ANSWER 10
166
167 /** DNS table entry */
168 struct dns_table_entry {
169   u8_t  state;
170   u8_t  numdns;
171   u8_t  tmr;
172   u8_t  retries;
173   u8_t  seqno;
174   u8_t  err;
175   u32_t ttl;
176   char name[DNS_MAX_NAME_LENGTH];
177   ip_addr_t ipaddr;
178   /* pointer to callback on DNS query done */
179   dns_found_callback found;
180   void *arg;
181 };
182
183 #if DNS_LOCAL_HOSTLIST
184
185 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
186 /** Local host-list. For hostnames in this list, no
187  *  external name resolution is performed */
188 static struct local_hostlist_entry *local_hostlist_dynamic;
189 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
190
191 /** Defining this allows the local_hostlist_static to be placed in a different
192  * linker section (e.g. FLASH) */
193 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE
194 #define DNS_LOCAL_HOSTLIST_STORAGE_PRE static
195 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */
196 /** Defining this allows the local_hostlist_static to be placed in a different
197  * linker section (e.g. FLASH) */
198 #ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST
199 #define DNS_LOCAL_HOSTLIST_STORAGE_POST
200 #endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */
201 DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[]
202   DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT;
203
204 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
205
206 static void dns_init_local();
207 #endif /* DNS_LOCAL_HOSTLIST */
208
209
210 /* forward declarations */
211 static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port);
212 static void dns_check_entries(void);
213
214 /*-----------------------------------------------------------------------------
215  * Globales
216  *----------------------------------------------------------------------------*/
217
218 /* DNS variables */
219 static struct udp_pcb        *dns_pcb;
220 static u8_t                   dns_seqno;
221 static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
222 static ip_addr_t              dns_servers[DNS_MAX_SERVERS];
223 /** Contiguous buffer for processing responses */
224 static u8_t                   dns_payload_buffer[LWIP_MEM_ALIGN_BUFFER(DNS_MSG_SIZE)];
225 static u8_t*                  dns_payload;
226
227 /**
228  * Initialize the resolver: set up the UDP pcb and configure the default server
229  * (DNS_SERVER_ADDRESS).
230  */
231 void
232 dns_init()
233 {
234   ip_addr_t dnsserver;
235
236   dns_payload = (u8_t *)LWIP_MEM_ALIGN(dns_payload_buffer);
237   
238   /* initialize default DNS server address */
239   DNS_SERVER_ADDRESS(&dnsserver);
240
241   LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
242
243   /* if dns client not yet initialized... */
244   if (dns_pcb == NULL) {
245     dns_pcb = udp_new();
246
247     if (dns_pcb != NULL) {
248       /* initialize DNS table not needed (initialized to zero since it is a
249        * global variable) */
250       LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0",
251         DNS_STATE_UNUSED == 0);
252
253       /* initialize DNS client */
254       udp_bind(dns_pcb, IP_ADDR_ANY, 0);
255       udp_recv(dns_pcb, dns_recv, NULL);
256
257       /* initialize default DNS primary server */
258       dns_setserver(0, &dnsserver);
259     }
260   }
261 #if DNS_LOCAL_HOSTLIST
262   dns_init_local();
263 #endif
264 }
265
266 /**
267  * Initialize one of the DNS servers.
268  *
269  * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS
270  * @param dnsserver IP address of the DNS server to set
271  */
272 void
273 dns_setserver(u8_t numdns, ip_addr_t *dnsserver)
274 {
275   if ((numdns < DNS_MAX_SERVERS) && (dns_pcb != NULL) &&
276       (dnsserver != NULL) && !ip_addr_isany(dnsserver)) {
277     dns_servers[numdns] = (*dnsserver);
278   }
279 }
280
281 /**
282  * Obtain one of the currently configured DNS server.
283  *
284  * @param numdns the index of the DNS server
285  * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS
286  *         server has not been configured.
287  */
288 ip_addr_t
289 dns_getserver(u8_t numdns)
290 {
291   if (numdns < DNS_MAX_SERVERS) {
292     return dns_servers[numdns];
293   } else {
294     return *IP_ADDR_ANY;
295   }
296 }
297
298 /**
299  * The DNS resolver client timer - handle retries and timeouts and should
300  * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
301  */
302 void
303 dns_tmr(void)
304 {
305   if (dns_pcb != NULL) {
306     LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
307     dns_check_entries();
308   }
309 }
310
311 #if DNS_LOCAL_HOSTLIST
312 static void
313 dns_init_local()
314 {
315 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
316   int i;
317   struct local_hostlist_entry *entry;
318   /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */
319   struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT;
320   size_t namelen;
321   for (i = 0; i < sizeof(local_hostlist_init) / sizeof(struct local_hostlist_entry); i++) {
322     struct local_hostlist_entry *init_entry = &local_hostlist_init[i];
323     LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL);
324     namelen = strlen(init_entry->name);
325     LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
326     entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
327     LWIP_ASSERT("mem-error in dns_init_local", entry != NULL);
328     if (entry != NULL) {
329       entry->name = (char*)entry + sizeof(struct local_hostlist_entry);
330       MEMCPY((char*)entry->name, init_entry->name, namelen);
331       ((char*)entry->name)[namelen] = 0;
332       entry->addr = init_entry->addr;
333       entry->next = local_hostlist_dynamic;
334       local_hostlist_dynamic = entry;
335     }
336   }
337 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
338 }
339
340 /**
341  * Scans the local host-list for a hostname.
342  *
343  * @param hostname Hostname to look for in the local host-list
344  * @return The first IP address for the hostname in the local host-list or
345  *         IPADDR_NONE if not found.
346  */
347 static u32_t
348 dns_lookup_local(const char *hostname)
349 {
350 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
351   struct local_hostlist_entry *entry = local_hostlist_dynamic;
352   while(entry != NULL) {
353     if(strcmp(entry->name, hostname) == 0) {
354       return ip4_addr_get_u32(&entry->addr);
355     }
356     entry = entry->next;
357   }
358 #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
359   int i;
360   for (i = 0; i < sizeof(local_hostlist_static) / sizeof(struct local_hostlist_entry); i++) {
361     if(strcmp(local_hostlist_static[i].name, hostname) == 0) {
362       return ip4_addr_get_u32(&local_hostlist_static[i].addr);
363     }
364   }
365 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
366   return IPADDR_NONE;
367 }
368
369 #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
370 /** Remove all entries from the local host-list for a specific hostname
371  * and/or IP addess
372  *
373  * @param hostname hostname for which entries shall be removed from the local
374  *                 host-list
375  * @param addr address for which entries shall be removed from the local host-list
376  * @return the number of removed entries
377  */
378 int
379 dns_local_removehost(const char *hostname, const ip_addr_t *addr)
380 {
381   int removed = 0;
382   struct local_hostlist_entry *entry = local_hostlist_dynamic;
383   struct local_hostlist_entry *last_entry = NULL;
384   while (entry != NULL) {
385     if (((hostname == NULL) || !strcmp(entry->name, hostname)) &&
386         ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
387       struct local_hostlist_entry *free_entry;
388       if (last_entry != NULL) {
389         last_entry->next = entry->next;
390       } else {
391         local_hostlist_dynamic = entry->next;
392       }
393       free_entry = entry;
394       entry = entry->next;
395       memp_free(MEMP_LOCALHOSTLIST, free_entry);
396       removed++;
397     } else {
398       last_entry = entry;
399       entry = entry->next;
400     }
401   }
402   return removed;
403 }
404
405 /**
406  * Add a hostname/IP address pair to the local host-list.
407  * Duplicates are not checked.
408  *
409  * @param hostname hostname of the new entry
410  * @param addr IP address of the new entry
411  * @return ERR_OK if succeeded or ERR_MEM on memory error
412  */
413 err_t
414 dns_local_addhost(const char *hostname, const ip_addr_t *addr)
415 {
416   struct local_hostlist_entry *entry;
417   size_t namelen;
418   LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
419   namelen = strlen(hostname);
420   LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
421   entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
422   if (entry == NULL) {
423     return ERR_MEM;
424   }
425   entry->name = (char*)entry + sizeof(struct local_hostlist_entry);
426   MEMCPY((char*)entry->name, hostname, namelen);
427   ((char*)entry->name)[namelen] = 0;
428   ip_addr_copy(entry->addr, *addr);
429   entry->next = local_hostlist_dynamic;
430   local_hostlist_dynamic = entry;
431   return ERR_OK;
432 }
433 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
434 #endif /* DNS_LOCAL_HOSTLIST */
435
436 /**
437  * Look up a hostname in the array of known hostnames.
438  *
439  * @note This function only looks in the internal array of known
440  * hostnames, it does not send out a query for the hostname if none
441  * was found. The function dns_enqueue() can be used to send a query
442  * for a hostname.
443  *
444  * @param name the hostname to look up
445  * @return the hostname's IP address, as u32_t (instead of ip_addr_t to
446  *         better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname
447  *         was not found in the cached dns_table.
448  */
449 static u32_t
450 dns_lookup(const char *name)
451 {
452   u8_t i;
453 #if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN)
454   u32_t addr;
455 #endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */
456 #if DNS_LOCAL_HOSTLIST
457   if ((addr = dns_lookup_local(name)) != IPADDR_NONE) {
458     return addr;
459   }
460 #endif /* DNS_LOCAL_HOSTLIST */
461 #ifdef DNS_LOOKUP_LOCAL_EXTERN
462   if((addr = DNS_LOOKUP_LOCAL_EXTERN(name)) != IPADDR_NONE) {
463     return addr;
464   }
465 #endif /* DNS_LOOKUP_LOCAL_EXTERN */
466
467   /* Walk through name list, return entry if found. If not, return NULL. */
468   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
469     if ((dns_table[i].state == DNS_STATE_DONE) &&
470         (strcmp(name, dns_table[i].name) == 0)) {
471       LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
472       ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
473       LWIP_DEBUGF(DNS_DEBUG, ("\n"));
474       return ip4_addr_get_u32(&dns_table[i].ipaddr);
475     }
476   }
477
478   return IPADDR_NONE;
479 }
480
481 #if DNS_DOES_NAME_CHECK
482 /**
483  * Compare the "dotted" name "query" with the encoded name "response"
484  * to make sure an answer from the DNS server matches the current dns_table
485  * entry (otherwise, answers might arrive late for hostname not on the list
486  * any more).
487  *
488  * @param query hostname (not encoded) from the dns_table
489  * @param response encoded hostname in the DNS response
490  * @return 0: names equal; 1: names differ
491  */
492 static u8_t
493 dns_compare_name(unsigned char *query, unsigned char *response)
494 {
495   unsigned char n;
496
497   do {
498     n = *response++;
499     /** @see RFC 1035 - 4.1.4. Message compression */
500     if ((n & 0xc0) == 0xc0) {
501       /* Compressed name */
502       break;
503     } else {
504       /* Not compressed name */
505       while (n > 0) {
506         if ((*query) != (*response)) {
507           return 1;
508         }
509         ++response;
510         ++query;
511         --n;
512       };
513       ++query;
514     }
515   } while (*response != 0);
516
517   return 0;
518 }
519 #endif /* DNS_DOES_NAME_CHECK */
520
521 /**
522  * Walk through a compact encoded DNS name and return the end of the name.
523  *
524  * @param query encoded DNS name in the DNS server response
525  * @return end of the name
526  */
527 static unsigned char *
528 dns_parse_name(unsigned char *query)
529 {
530   unsigned char n;
531
532   do {
533     n = *query++;
534     /** @see RFC 1035 - 4.1.4. Message compression */
535     if ((n & 0xc0) == 0xc0) {
536       /* Compressed name */
537       break;
538     } else {
539       /* Not compressed name */
540       while (n > 0) {
541         ++query;
542         --n;
543       };
544     }
545   } while (*query != 0);
546
547   return query + 1;
548 }
549
550 /**
551  * Send a DNS query packet.
552  *
553  * @param numdns index of the DNS server in the dns_servers table
554  * @param name hostname to query
555  * @param id index of the hostname in dns_table, used as transaction ID in the
556  *        DNS query packet
557  * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
558  */
559 static err_t
560 dns_send(u8_t numdns, const char* name, u8_t id)
561 {
562   err_t err;
563   struct dns_hdr *hdr;
564   struct dns_query qry;
565   struct pbuf *p;
566   char *query, *nptr;
567   const char *pHostname;
568   u8_t n;
569
570   LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
571               (u16_t)(numdns), name));
572   LWIP_ASSERT("dns server out of array", numdns < DNS_MAX_SERVERS);
573   LWIP_ASSERT("dns server has no IP address set", !ip_addr_isany(&dns_servers[numdns]));
574
575   /* if here, we have either a new query or a retry on a previous query to process */
576   p = pbuf_alloc(PBUF_TRANSPORT, SIZEOF_DNS_HDR + DNS_MAX_NAME_LENGTH +
577                  SIZEOF_DNS_QUERY, PBUF_RAM);
578   if (p != NULL) {
579     LWIP_ASSERT("pbuf must be in one piece", p->next == NULL);
580     /* fill dns header */
581     hdr = (struct dns_hdr*)p->payload;
582     memset(hdr, 0, SIZEOF_DNS_HDR);
583     hdr->id = htons(id);
584     hdr->flags1 = DNS_FLAG1_RD;
585     hdr->numquestions = PP_HTONS(1);
586     query = (char*)hdr + SIZEOF_DNS_HDR;
587     pHostname = name;
588     --pHostname;
589
590     /* convert hostname into suitable query format. */
591     do {
592       ++pHostname;
593       nptr = query;
594       ++query;
595       for(n = 0; *pHostname != '.' && *pHostname != 0; ++pHostname) {
596         *query = *pHostname;
597         ++query;
598         ++n;
599       }
600       *nptr = n;
601     } while(*pHostname != 0);
602     *query++='\0';
603
604     /* fill dns query */
605     qry.type = PP_HTONS(DNS_RRTYPE_A);
606     qry.cls = PP_HTONS(DNS_RRCLASS_IN);
607     SMEMCPY(query, &qry, SIZEOF_DNS_QUERY);
608
609     /* resize pbuf to the exact dns query */
610     pbuf_realloc(p, (u16_t)((query + SIZEOF_DNS_QUERY) - ((char*)(p->payload))));
611
612     /* connect to the server for faster receiving */
613     udp_connect(dns_pcb, &dns_servers[numdns], DNS_SERVER_PORT);
614     /* send dns packet */
615     err = udp_sendto(dns_pcb, p, &dns_servers[numdns], DNS_SERVER_PORT);
616
617     /* free pbuf */
618     pbuf_free(p);
619   } else {
620     err = ERR_MEM;
621   }
622
623   return err;
624 }
625
626 /**
627  * dns_check_entry() - see if pEntry has not yet been queried and, if so, sends out a query.
628  * Check an entry in the dns_table:
629  * - send out query for new entries
630  * - retry old pending entries on timeout (also with different servers)
631  * - remove completed entries from the table if their TTL has expired
632  *
633  * @param i index of the dns_table entry to check
634  */
635 static void
636 dns_check_entry(u8_t i)
637 {
638   int err;
639   struct dns_table_entry *pEntry = &dns_table[i];
640
641   LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
642
643   switch(pEntry->state) {
644
645     case DNS_STATE_NEW: {
646       /* initialize new entry */
647       pEntry->state   = DNS_STATE_ASKING;
648       pEntry->numdns  = 0;
649       pEntry->tmr     = 1;
650       pEntry->retries = 0;
651
652       /* send DNS packet for this entry */
653       err = dns_send(pEntry->numdns, pEntry->name, i);
654       if (err)
655         printf("Error in dns_send: %d\n", err);
656       break;
657     }
658
659     case DNS_STATE_ASKING: {
660       if (--pEntry->tmr == 0) {
661         if (++pEntry->retries == DNS_MAX_RETRIES) {
662           if ((pEntry->numdns+1<DNS_MAX_SERVERS) && !ip_addr_isany(&dns_servers[pEntry->numdns+1])) {
663             /* change of server */
664             pEntry->numdns++;
665             pEntry->tmr     = 1;
666             pEntry->retries = 0;
667             break;
668           } else {
669             LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", pEntry->name));
670             /* call specified callback function if provided */
671             if (pEntry->found)
672               (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
673             /* flush this entry */
674             pEntry->state   = DNS_STATE_UNUSED;
675             pEntry->found   = NULL;
676             break;
677           }
678         }
679
680         /* wait longer for the next retry */
681         pEntry->tmr = pEntry->retries;
682
683         /* send DNS packet for this entry */
684         err = dns_send(pEntry->numdns, pEntry->name, i);
685         if (err)
686           printf("Error in dns_send: %d\n", err);
687       }
688       break;
689     }
690
691     case DNS_STATE_DONE: {
692       /* if the time to live is nul */
693       if (--pEntry->ttl == 0) {
694         LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", pEntry->name));
695         /* flush this entry */
696         pEntry->state = DNS_STATE_UNUSED;
697         pEntry->found = NULL;
698       }
699       break;
700     }
701     case DNS_STATE_UNUSED:
702       /* nothing to do */
703       break;
704     default:
705       LWIP_ASSERT("unknown dns_table entry state:", 0);
706       break;
707   }
708 }
709
710 /**
711  * Call dns_check_entry for each entry in dns_table - check all entries.
712  */
713 static void
714 dns_check_entries(void)
715 {
716   u8_t i;
717
718   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
719     dns_check_entry(i);
720   }
721 }
722
723 /**
724  * Receive input function for DNS response packets arriving for the dns UDP pcb.
725  *
726  * @params see udp.h
727  */
728 static void
729 dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
730 {
731   u16_t i;
732   char *pHostname;
733   struct dns_hdr *hdr;
734   struct dns_answer ans;
735   struct dns_table_entry *pEntry;
736   u16_t nquestions, nanswers;
737
738   LWIP_UNUSED_ARG(arg);
739   LWIP_UNUSED_ARG(pcb);
740   LWIP_UNUSED_ARG(addr);
741   LWIP_UNUSED_ARG(port);
742
743   /* is the dns message too big ? */
744   if (p->tot_len > DNS_MSG_SIZE) {
745     LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too big\n"));
746     /* free pbuf and return */
747     goto memerr;
748   }
749
750   /* is the dns message big enough ? */
751   if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY + SIZEOF_DNS_ANSWER)) {
752     LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
753     /* free pbuf and return */
754     goto memerr;
755   }
756
757   /* copy dns payload inside static buffer for processing */ 
758   if (pbuf_copy_partial(p, dns_payload, p->tot_len, 0) == p->tot_len) {
759     /* The ID in the DNS header should be our entry into the name table. */
760     hdr = (struct dns_hdr*)dns_payload;
761     i = htons(hdr->id);
762     if (i < DNS_TABLE_SIZE) {
763       pEntry = &dns_table[i];
764       if(pEntry->state == DNS_STATE_ASKING) {
765         /* This entry is now completed. */
766         pEntry->state = DNS_STATE_DONE;
767         pEntry->err   = hdr->flags2 & DNS_FLAG2_ERR_MASK;
768
769         /* We only care about the question(s) and the answers. The authrr
770            and the extrarr are simply discarded. */
771         nquestions = htons(hdr->numquestions);
772         nanswers   = htons(hdr->numanswers);
773
774         /* Check for error. If so, call callback to inform. */
775         if (((hdr->flags1 & DNS_FLAG1_RESPONSE) == 0) || (pEntry->err != 0) || (nquestions != 1)) {
776           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", pEntry->name));
777           /* call callback to indicate error, clean up memory and return */
778           goto responseerr;
779         }
780
781 #if DNS_DOES_NAME_CHECK
782         /* Check if the name in the "question" part match with the name in the entry. */
783         if (dns_compare_name((unsigned char *)(pEntry->name), (unsigned char *)dns_payload + SIZEOF_DNS_HDR) != 0) {
784           LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", pEntry->name));
785           /* call callback to indicate error, clean up memory and return */
786           goto responseerr;
787         }
788 #endif /* DNS_DOES_NAME_CHECK */
789
790         /* Skip the name in the "question" part */
791         pHostname = (char *) dns_parse_name((unsigned char *)dns_payload + SIZEOF_DNS_HDR) + SIZEOF_DNS_QUERY;
792
793         while (nanswers > 0) {
794           /* skip answer resource record's host name */
795           pHostname = (char *) dns_parse_name((unsigned char *)pHostname);
796
797           /* Check for IP address type and Internet class. Others are discarded. */
798           SMEMCPY(&ans, pHostname, SIZEOF_DNS_ANSWER);
799           if((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) &&
800              (ans.len == PP_HTONS(sizeof(ip_addr_t))) ) {
801             /* read the answer resource record's TTL, and maximize it if needed */
802             pEntry->ttl = ntohl(ans.ttl);
803             if (pEntry->ttl > DNS_MAX_TTL) {
804               pEntry->ttl = DNS_MAX_TTL;
805             }
806             /* read the IP address after answer resource record's header */
807             SMEMCPY(&(pEntry->ipaddr), (pHostname+SIZEOF_DNS_ANSWER), sizeof(ip_addr_t));
808             LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", pEntry->name));
809             ip_addr_debug_print(DNS_DEBUG, (&(pEntry->ipaddr)));
810             LWIP_DEBUGF(DNS_DEBUG, ("\n"));
811             /* call specified callback function if provided */
812             if (pEntry->found) {
813               (*pEntry->found)(pEntry->name, &pEntry->ipaddr, pEntry->arg);
814             }
815             /* deallocate memory and return */
816             goto memerr;
817           } else {
818             pHostname = pHostname + SIZEOF_DNS_ANSWER + htons(ans.len);
819           }
820           --nanswers;
821         }
822         LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", pEntry->name));
823         /* call callback to indicate error, clean up memory and return */
824         goto responseerr;
825       }
826     }
827   }
828
829   /* deallocate memory and return */
830   goto memerr;
831
832 responseerr:
833   /* ERROR: call specified callback function with NULL as name to indicate an error */
834   if (pEntry->found) {
835     (*pEntry->found)(pEntry->name, NULL, pEntry->arg);
836   }
837   /* flush this entry */
838   pEntry->state = DNS_STATE_UNUSED;
839   pEntry->found = NULL;
840
841 memerr:
842   /* free pbuf */
843   pbuf_free(p);
844   return;
845 }
846
847 /**
848  * Queues a new hostname to resolve and sends out a DNS query for that hostname
849  *
850  * @param name the hostname that is to be queried
851  * @param found a callback founction to be called on success, failure or timeout
852  * @param callback_arg argument to pass to the callback function
853  * @return @return a err_t return code.
854  */
855 static err_t
856 dns_enqueue(const char *name, dns_found_callback found, void *callback_arg)
857 {
858   u8_t i;
859   u8_t lseq, lseqi;
860   struct dns_table_entry *pEntry = NULL;
861   size_t namelen;
862
863   /* search an unused entry, or the oldest one */
864   lseq = lseqi = 0;
865   for (i = 0; i < DNS_TABLE_SIZE; ++i) {
866     pEntry = &dns_table[i];
867     /* is it an unused entry ? */
868     if (pEntry->state == DNS_STATE_UNUSED)
869       break;
870
871     /* check if this is the oldest completed entry */
872     if (pEntry->state == DNS_STATE_DONE) {
873       if ((dns_seqno - pEntry->seqno) > lseq) {
874         lseq = dns_seqno - pEntry->seqno;
875         lseqi = i;
876       }
877     }
878   }
879
880   /* if we don't have found an unused entry, use the oldest completed one */
881   if (i == DNS_TABLE_SIZE) {
882     if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
883       /* no entry can't be used now, table is full */
884       LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
885       return ERR_MEM;
886     } else {
887       /* use the oldest completed one */
888       i = lseqi;
889       pEntry = &dns_table[i];
890     }
891   }
892
893   /* use this entry */
894   LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
895
896   /* fill the entry */
897   pEntry->state = DNS_STATE_NEW;
898   pEntry->seqno = dns_seqno++;
899   pEntry->found = found;
900   pEntry->arg   = callback_arg;
901   namelen = LWIP_MIN(strlen(name), DNS_MAX_NAME_LENGTH-1);
902   MEMCPY(pEntry->name, name, namelen);
903   pEntry->name[namelen] = 0;
904
905   /* force to send query without waiting timer */
906   dns_check_entry(i);
907
908   /* dns query is enqueued */
909   return ERR_INPROGRESS;
910 }
911
912 /**
913  * Resolve a hostname (string) into an IP address.
914  * NON-BLOCKING callback version for use with raw API!!!
915  *
916  * Returns immediately with one of err_t return codes:
917  * - ERR_OK if hostname is a valid IP address string or the host
918  *   name is already in the local names table.
919  * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
920  *   for resolution if no errors are present.
921  *
922  * @param hostname the hostname that is to be queried
923  * @param addr pointer to a ip_addr_t where to store the address if it is already
924  *             cached in the dns_table (only valid if ERR_OK is returned!)
925  * @param found a callback function to be called on success, failure or timeout (only if
926  *              ERR_INPROGRESS is returned!)
927  * @param callback_arg argument to pass to the callback function
928  * @return a err_t return code.
929  */
930 err_t
931 dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found,
932                   void *callback_arg)
933 {
934   u32_t ipaddr;
935   /* not initialized or no valid server yet, or invalid addr pointer
936    * or invalid hostname or invalid hostname length */
937   if ((dns_pcb == NULL) || (addr == NULL) ||
938       (!hostname) || (!hostname[0]) ||
939       (strlen(hostname) >= DNS_MAX_NAME_LENGTH)) {
940     return ERR_VAL;
941   }
942
943 #if LWIP_HAVE_LOOPIF
944   if (strcmp(hostname, "localhost")==0) {
945     ip_addr_set_loopback(addr);
946     return ERR_OK;
947   }
948 #endif /* LWIP_HAVE_LOOPIF */
949
950   /* host name already in octet notation? set ip addr and return ERR_OK */
951   ipaddr = ipaddr_addr(hostname);
952   if (ipaddr == IPADDR_NONE) {
953     /* already have this address cached? */
954     ipaddr = dns_lookup(hostname);
955   }
956   if (ipaddr != IPADDR_NONE) {
957     ip4_addr_set_u32(addr, ipaddr);
958     return ERR_OK;
959   }
960
961   /* queue query with specified callback */
962   return dns_enqueue(hostname, found, callback_arg);
963 }
964
965 #endif /* LWIP_DNS */