dns.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  1. /**
  2. * @file
  3. * DNS - host name to IP address resolver.
  4. *
  5. */
  6. /**
  7. * This file implements a DNS host name to IP address resolver.
  8. * Port to lwIP from uIP
  9. * by Jim Pettinato April 2007
  10. * security fixes and more by Simon Goldschmidt
  11. * uIP version Copyright (c) 2002-2003, Adam Dunkels.
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or without
  15. * modification, are permitted provided that the following conditions
  16. * are met:
  17. * 1. Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. * 2. Redistributions in binary form must reproduce the above copyright
  20. * notice, this list of conditions and the following disclaimer in the
  21. * documentation and/or other materials provided with the distribution.
  22. * 3. The name of the author may not be used to endorse or promote
  23. * products derived from this software without specific prior
  24. * written permission.
  25. *
  26. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  27. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  28. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  29. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  30. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  31. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  32. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  33. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  34. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  35. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  36. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  37. *
  38. *
  39. * DNS.C
  40. *
  41. * The lwIP DNS resolver functions are used to lookup a host name and
  42. * map it to a numerical IP address. It maintains a list of resolved
  43. * hostnames that can be queried with the dns_lookup() function.
  44. * New hostnames can be resolved using the dns_query() function.
  45. *
  46. * The lwIP version of the resolver also adds a non-blocking version of
  47. * gethostbyname() that will work with a raw API application. This function
  48. * checks for an IP address string first and converts it if it is valid.
  49. * gethostbyname() then does a dns_lookup() to see if the name is
  50. * already in the table. If so, the IP is returned. If not, a query is
  51. * issued and the function returns with a ERR_INPROGRESS status. The app
  52. * using the dns client must then go into a waiting state.
  53. *
  54. * Once a hostname has been resolved (or found to be non-existent),
  55. * the resolver code calls a specified callback function (which
  56. * must be implemented by the module that uses the resolver).
  57. */
  58. /*-----------------------------------------------------------------------------
  59. * RFC 1035 - Domain names - implementation and specification
  60. * RFC 2181 - Clarifications to the DNS Specification
  61. *----------------------------------------------------------------------------*/
  62. /** @todo: define good default values (rfc compliance) */
  63. /** @todo: improve answer parsing, more checkings... */
  64. /** @todo: check RFC1035 - 7.3. Processing responses */
  65. /*-----------------------------------------------------------------------------
  66. * Includes
  67. *----------------------------------------------------------------------------*/
  68. #include "lwip/opt.h"
  69. #if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
  70. #include "lwip/udp.h"
  71. #include "lwip/mem.h"
  72. #include "lwip/memp.h"
  73. #include "lwip/dns.h"
  74. #include <string.h>
  75. /** Random generator function to create random TXIDs and source ports for queries */
  76. #ifndef DNS_RAND_TXID
  77. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_XID) != 0)
  78. #define DNS_RAND_TXID LWIP_RAND
  79. #else
  80. static u16_t dns_txid;
  81. #define DNS_RAND_TXID() (++dns_txid)
  82. #endif
  83. #endif
  84. /** Limits the source port to be >= 1024 by default */
  85. #ifndef DNS_PORT_ALLOWED
  86. #define DNS_PORT_ALLOWED(port) ((port) >= 1024)
  87. #endif
  88. /** DNS server port address */
  89. #ifndef DNS_SERVER_PORT
  90. #define DNS_SERVER_PORT 53
  91. #endif
  92. /** DNS maximum number of retries when asking for a name, before "timeout". */
  93. #ifndef DNS_MAX_RETRIES
  94. #define DNS_MAX_RETRIES 4
  95. #endif
  96. /** DNS resource record max. TTL (one week as default) */
  97. #ifndef DNS_MAX_TTL
  98. #define DNS_MAX_TTL 604800
  99. #endif
  100. /* The number of parallel requests (i.e. calls to dns_gethostbyname
  101. * that cannot be answered from the DNS table.
  102. * This is set to the table size by default.
  103. */
  104. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
  105. #ifndef DNS_MAX_REQUESTS
  106. #define DNS_MAX_REQUESTS DNS_TABLE_SIZE
  107. #endif
  108. #else
  109. /* In this configuration, both arrays have to have the same size and are used
  110. * like one entry (used/free) */
  111. #define DNS_MAX_REQUESTS DNS_TABLE_SIZE
  112. #endif
  113. /* The number of UDP source ports used in parallel */
  114. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
  115. #ifndef DNS_MAX_SOURCE_PORTS
  116. #define DNS_MAX_SOURCE_PORTS DNS_MAX_REQUESTS
  117. #endif
  118. #else
  119. #ifdef DNS_MAX_SOURCE_PORTS
  120. #undef DNS_MAX_SOURCE_PORTS
  121. #endif
  122. #define DNS_MAX_SOURCE_PORTS 1
  123. #endif
  124. #if LWIP_IPV4 && LWIP_IPV6
  125. #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) (((t) == LWIP_DNS_ADDRTYPE_IPV6_IPV4) || ((t) == LWIP_DNS_ADDRTYPE_IPV6))
  126. #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)))
  127. #define LWIP_DNS_ADDRTYPE_ARG(x) , x
  128. #define LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(x) x
  129. #define LWIP_DNS_SET_ADDRTYPE(x, y) do { x = y; } while(0)
  130. #else
  131. #if LWIP_IPV6
  132. #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) 1
  133. #else
  134. #define LWIP_DNS_ADDRTYPE_IS_IPV6(t) 0
  135. #endif
  136. #define LWIP_DNS_ADDRTYPE_MATCH_IP(t, ip) 1
  137. #define LWIP_DNS_ADDRTYPE_ARG(x)
  138. #define LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(x) 0
  139. #define LWIP_DNS_SET_ADDRTYPE(x, y)
  140. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  141. /** DNS field TYPE used for "Resource Records" */
  142. #define DNS_RRTYPE_A 1 /* a host address */
  143. #define DNS_RRTYPE_NS 2 /* an authoritative name server */
  144. #define DNS_RRTYPE_MD 3 /* a mail destination (Obsolete - use MX) */
  145. #define DNS_RRTYPE_MF 4 /* a mail forwarder (Obsolete - use MX) */
  146. #define DNS_RRTYPE_CNAME 5 /* the canonical name for an alias */
  147. #define DNS_RRTYPE_SOA 6 /* marks the start of a zone of authority */
  148. #define DNS_RRTYPE_MB 7 /* a mailbox domain name (EXPERIMENTAL) */
  149. #define DNS_RRTYPE_MG 8 /* a mail group member (EXPERIMENTAL) */
  150. #define DNS_RRTYPE_MR 9 /* a mail rename domain name (EXPERIMENTAL) */
  151. #define DNS_RRTYPE_NULL 10 /* a null RR (EXPERIMENTAL) */
  152. #define DNS_RRTYPE_WKS 11 /* a well known service description */
  153. #define DNS_RRTYPE_PTR 12 /* a domain name pointer */
  154. #define DNS_RRTYPE_HINFO 13 /* host information */
  155. #define DNS_RRTYPE_MINFO 14 /* mailbox or mail list information */
  156. #define DNS_RRTYPE_MX 15 /* mail exchange */
  157. #define DNS_RRTYPE_TXT 16 /* text strings */
  158. #define DNS_RRTYPE_AAAA 28 /* IPv6 address */
  159. /** DNS field CLASS used for "Resource Records" */
  160. #define DNS_RRCLASS_IN 1 /* the Internet */
  161. #define DNS_RRCLASS_CS 2 /* the CSNET class (Obsolete - used only for examples in some obsolete RFCs) */
  162. #define DNS_RRCLASS_CH 3 /* the CHAOS class */
  163. #define DNS_RRCLASS_HS 4 /* Hesiod [Dyer 87] */
  164. #define DNS_RRCLASS_FLUSH 0x800 /* Flush bit */
  165. /* DNS protocol flags */
  166. #define DNS_FLAG1_RESPONSE 0x80
  167. #define DNS_FLAG1_OPCODE_STATUS 0x10
  168. #define DNS_FLAG1_OPCODE_INVERSE 0x08
  169. #define DNS_FLAG1_OPCODE_STANDARD 0x00
  170. #define DNS_FLAG1_AUTHORATIVE 0x04
  171. #define DNS_FLAG1_TRUNC 0x02
  172. #define DNS_FLAG1_RD 0x01
  173. #define DNS_FLAG2_RA 0x80
  174. #define DNS_FLAG2_ERR_MASK 0x0f
  175. #define DNS_FLAG2_ERR_NONE 0x00
  176. #define DNS_FLAG2_ERR_NAME 0x03
  177. /* DNS protocol states */
  178. #define DNS_STATE_UNUSED 0
  179. #define DNS_STATE_NEW 1
  180. #define DNS_STATE_ASKING 2
  181. #define DNS_STATE_DONE 3
  182. #ifdef PACK_STRUCT_USE_INCLUDES
  183. # include "arch/bpstruct.h"
  184. #endif
  185. PACK_STRUCT_BEGIN
  186. /** DNS message header */
  187. struct dns_hdr {
  188. PACK_STRUCT_FIELD(u16_t id);
  189. PACK_STRUCT_FLD_8(u8_t flags1);
  190. PACK_STRUCT_FLD_8(u8_t flags2);
  191. PACK_STRUCT_FIELD(u16_t numquestions);
  192. PACK_STRUCT_FIELD(u16_t numanswers);
  193. PACK_STRUCT_FIELD(u16_t numauthrr);
  194. PACK_STRUCT_FIELD(u16_t numextrarr);
  195. } PACK_STRUCT_STRUCT;
  196. PACK_STRUCT_END
  197. #ifdef PACK_STRUCT_USE_INCLUDES
  198. # include "arch/epstruct.h"
  199. #endif
  200. #define SIZEOF_DNS_HDR 12
  201. /** DNS query message structure.
  202. No packing needed: only used locally on the stack. */
  203. struct dns_query {
  204. /* DNS query record starts with either a domain name or a pointer
  205. to a name already present somewhere in the packet. */
  206. u16_t type;
  207. u16_t cls;
  208. };
  209. #define SIZEOF_DNS_QUERY 4
  210. /** DNS answer message structure.
  211. No packing needed: only used locally on the stack. */
  212. struct dns_answer {
  213. /* DNS answer record starts with either a domain name or a pointer
  214. to a name already present somewhere in the packet. */
  215. u16_t type;
  216. u16_t cls;
  217. u32_t ttl;
  218. u16_t len;
  219. };
  220. #define SIZEOF_DNS_ANSWER 10
  221. /* maximum allowed size for the struct due to non-packed */
  222. #define SIZEOF_DNS_ANSWER_ASSERT 12
  223. /** DNS table entry */
  224. struct dns_table_entry {
  225. u32_t ttl;
  226. ip_addr_t ipaddr;
  227. u16_t txid;
  228. u8_t state;
  229. u8_t server_idx;
  230. u8_t tmr;
  231. u8_t retries;
  232. u8_t seqno;
  233. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
  234. u8_t pcb_idx;
  235. #endif
  236. char name[DNS_MAX_NAME_LENGTH];
  237. #if LWIP_IPV4 && LWIP_IPV6
  238. u8_t reqaddrtype;
  239. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  240. };
  241. /** DNS request table entry: used when dns_gehostbyname cannot answer the
  242. * request from the DNS table */
  243. struct dns_req_entry {
  244. /* pointer to callback on DNS query done */
  245. dns_found_callback found;
  246. /* argument passed to the callback function */
  247. void *arg;
  248. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
  249. u8_t dns_table_idx;
  250. #endif
  251. #if LWIP_IPV4 && LWIP_IPV6
  252. u8_t reqaddrtype;
  253. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  254. };
  255. #if DNS_LOCAL_HOSTLIST
  256. #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
  257. /** Local host-list. For hostnames in this list, no
  258. * external name resolution is performed */
  259. static struct local_hostlist_entry *local_hostlist_dynamic;
  260. #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
  261. /** Defining this allows the local_hostlist_static to be placed in a different
  262. * linker section (e.g. FLASH) */
  263. #ifndef DNS_LOCAL_HOSTLIST_STORAGE_PRE
  264. #define DNS_LOCAL_HOSTLIST_STORAGE_PRE static
  265. #endif /* DNS_LOCAL_HOSTLIST_STORAGE_PRE */
  266. /** Defining this allows the local_hostlist_static to be placed in a different
  267. * linker section (e.g. FLASH) */
  268. #ifndef DNS_LOCAL_HOSTLIST_STORAGE_POST
  269. #define DNS_LOCAL_HOSTLIST_STORAGE_POST
  270. #endif /* DNS_LOCAL_HOSTLIST_STORAGE_POST */
  271. DNS_LOCAL_HOSTLIST_STORAGE_PRE struct local_hostlist_entry local_hostlist_static[]
  272. DNS_LOCAL_HOSTLIST_STORAGE_POST = DNS_LOCAL_HOSTLIST_INIT;
  273. #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
  274. static void dns_init_local(void);
  275. #endif /* DNS_LOCAL_HOSTLIST */
  276. /* forward declarations */
  277. static void dns_recv(void *s, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port);
  278. static void dns_check_entries(void);
  279. static void dns_call_found(u8_t idx, ip_addr_t* addr);
  280. /*-----------------------------------------------------------------------------
  281. * Globals
  282. *----------------------------------------------------------------------------*/
  283. /* DNS variables */
  284. static struct udp_pcb *dns_pcbs[DNS_MAX_SOURCE_PORTS];
  285. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
  286. static u8_t dns_last_pcb_idx;
  287. #endif
  288. static u8_t dns_seqno;
  289. static struct dns_table_entry dns_table[DNS_TABLE_SIZE];
  290. static struct dns_req_entry dns_requests[DNS_MAX_REQUESTS];
  291. static ip_addr_t dns_servers[DNS_MAX_SERVERS];
  292. #ifndef LWIP_DNS_STRICMP
  293. #define LWIP_DNS_STRICMP(str1, str2) dns_stricmp(str1, str2)
  294. /**
  295. * A small but sufficient implementation for case insensitive strcmp.
  296. * This can be defined to e.g. stricmp for windows or strcasecmp for linux. */
  297. static int
  298. dns_stricmp(const char* str1, const char* str2)
  299. {
  300. char c1, c2;
  301. do {
  302. c1 = *str1++;
  303. c2 = *str2++;
  304. if (c1 != c2) {
  305. char c1_upc = c1 | 0x20;
  306. if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
  307. /* characters are not equal an one is in the alphabet range:
  308. downcase both chars and check again */
  309. char c2_upc = c2 | 0x20;
  310. if (c1_upc != c2_upc) {
  311. /* still not equal */
  312. /* don't care for < or > */
  313. return 1;
  314. }
  315. } else {
  316. /* characters are not equal but none is in the alphabet range */
  317. return 1;
  318. }
  319. }
  320. } while (c1 != 0);
  321. return 0;
  322. }
  323. #endif /* LWIP_DNS_STRICMP */
  324. /**
  325. * Initialize the resolver: set up the UDP pcb and configure the default server
  326. * (if DNS_SERVER_ADDRESS is set).
  327. */
  328. void
  329. dns_init(void)
  330. {
  331. #ifdef DNS_SERVER_ADDRESS
  332. /* initialize default DNS server address */
  333. ip_addr_t dnsserver;
  334. DNS_SERVER_ADDRESS(&dnsserver);
  335. dns_setserver(0, &dnsserver);
  336. #endif /* DNS_SERVER_ADDRESS */
  337. LWIP_ASSERT("sanity check SIZEOF_DNS_QUERY",
  338. sizeof(struct dns_query) == SIZEOF_DNS_QUERY);
  339. LWIP_ASSERT("sanity check SIZEOF_DNS_ANSWER",
  340. sizeof(struct dns_answer) <= SIZEOF_DNS_ANSWER_ASSERT);
  341. LWIP_DEBUGF(DNS_DEBUG, ("dns_init: initializing\n"));
  342. /* if dns client not yet initialized... */
  343. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
  344. if (dns_pcbs[0] == NULL) {
  345. dns_pcbs[0] = udp_new_ip_type(IPADDR_TYPE_ANY);
  346. LWIP_ASSERT("dns_pcbs[0] != NULL", dns_pcbs[0] != NULL);
  347. /* initialize DNS table not needed (initialized to zero since it is a
  348. * global variable) */
  349. LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0",
  350. DNS_STATE_UNUSED == 0);
  351. /* initialize DNS client */
  352. udp_bind(dns_pcbs[0], IP_ANY_TYPE, 0);
  353. udp_recv(dns_pcbs[0], dns_recv, NULL);
  354. }
  355. #endif
  356. #if DNS_LOCAL_HOSTLIST
  357. dns_init_local();
  358. #endif
  359. }
  360. /**
  361. * Initialize one of the DNS servers.
  362. *
  363. * @param numdns the index of the DNS server to set must be < DNS_MAX_SERVERS
  364. * @param dnsserver IP address of the DNS server to set
  365. */
  366. void
  367. dns_setserver(u8_t numdns, const ip_addr_t *dnsserver)
  368. {
  369. if (numdns < DNS_MAX_SERVERS) {
  370. if (dnsserver != NULL) {
  371. dns_servers[numdns] = (*dnsserver);
  372. } else {
  373. dns_servers[numdns] = *IP_ADDR_ANY;
  374. }
  375. }
  376. }
  377. /**
  378. * Obtain one of the currently configured DNS server.
  379. *
  380. * @param numdns the index of the DNS server
  381. * @return IP address of the indexed DNS server or "ip_addr_any" if the DNS
  382. * server has not been configured.
  383. */
  384. ip_addr_t
  385. dns_getserver(u8_t numdns)
  386. {
  387. if (numdns < DNS_MAX_SERVERS) {
  388. return dns_servers[numdns];
  389. } else {
  390. return *IP_ADDR_ANY;
  391. }
  392. }
  393. /**
  394. * The DNS resolver client timer - handle retries and timeouts and should
  395. * be called every DNS_TMR_INTERVAL milliseconds (every second by default).
  396. */
  397. void
  398. dns_tmr(void)
  399. {
  400. LWIP_DEBUGF(DNS_DEBUG, ("dns_tmr: dns_check_entries\n"));
  401. dns_check_entries();
  402. }
  403. #if DNS_LOCAL_HOSTLIST
  404. static void
  405. dns_init_local(void)
  406. {
  407. #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT)
  408. size_t i;
  409. struct local_hostlist_entry *entry;
  410. /* Dynamic: copy entries from DNS_LOCAL_HOSTLIST_INIT to list */
  411. struct local_hostlist_entry local_hostlist_init[] = DNS_LOCAL_HOSTLIST_INIT;
  412. size_t namelen;
  413. for (i = 0; i < sizeof(local_hostlist_init) / sizeof(struct local_hostlist_entry); i++) {
  414. struct local_hostlist_entry *init_entry = &local_hostlist_init[i];
  415. LWIP_ASSERT("invalid host name (NULL)", init_entry->name != NULL);
  416. namelen = strlen(init_entry->name);
  417. LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
  418. entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
  419. LWIP_ASSERT("mem-error in dns_init_local", entry != NULL);
  420. if (entry != NULL) {
  421. char* entry_name = (char*)entry + sizeof(struct local_hostlist_entry);
  422. MEMCPY(entry_name, init_entry->name, namelen);
  423. entry_name[namelen] = 0;
  424. entry->name = entry_name;
  425. entry->addr = init_entry->addr;
  426. entry->next = local_hostlist_dynamic;
  427. local_hostlist_dynamic = entry;
  428. }
  429. }
  430. #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC && defined(DNS_LOCAL_HOSTLIST_INIT) */
  431. }
  432. /**
  433. * Scans the local host-list for a hostname.
  434. *
  435. * @param hostname Hostname to look for in the local host-list
  436. * @param addr the first IP address for the hostname in the local host-list or
  437. * IPADDR_NONE if not found.
  438. * @return ERR_OK if found, ERR_ARG if not found
  439. */
  440. static err_t
  441. dns_lookup_local(const char *hostname, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
  442. {
  443. #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
  444. struct local_hostlist_entry *entry = local_hostlist_dynamic;
  445. while (entry != NULL) {
  446. if ((LWIP_DNS_STRICMP(entry->name, hostname) == 0) &&
  447. LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, entry->addr)) {
  448. if (addr) {
  449. ip_addr_copy(*addr, entry->addr);
  450. }
  451. return ERR_OK;
  452. }
  453. entry = entry->next;
  454. }
  455. #else /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
  456. size_t i;
  457. for (i = 0; i < sizeof(local_hostlist_static) / sizeof(struct local_hostlist_entry); i++) {
  458. if ((LWIP_DNS_STRICMP(local_hostlist_static[i].name, hostname) == 0) &&
  459. LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, local_hostlist_static[i].addr)) {
  460. if (addr) {
  461. ip_addr_copy(*addr, local_hostlist_static[i].addr);
  462. }
  463. return ERR_OK;
  464. }
  465. }
  466. #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */
  467. return ERR_ARG;
  468. }
  469. #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC
  470. /** Remove all entries from the local host-list for a specific hostname
  471. * and/or IP address
  472. *
  473. * @param hostname hostname for which entries shall be removed from the local
  474. * host-list
  475. * @param addr address for which entries shall be removed from the local host-list
  476. * @return the number of removed entries
  477. */
  478. int
  479. dns_local_removehost(const char *hostname, const ip_addr_t *addr)
  480. {
  481. int removed = 0;
  482. struct local_hostlist_entry *entry = local_hostlist_dynamic;
  483. struct local_hostlist_entry *last_entry = NULL;
  484. while (entry != NULL) {
  485. if (((hostname == NULL) || !LWIP_DNS_STRICMP(entry->name, hostname)) &&
  486. ((addr == NULL) || ip_addr_cmp(&entry->addr, addr))) {
  487. struct local_hostlist_entry *free_entry;
  488. if (last_entry != NULL) {
  489. last_entry->next = entry->next;
  490. } else {
  491. local_hostlist_dynamic = entry->next;
  492. }
  493. free_entry = entry;
  494. entry = entry->next;
  495. memp_free(MEMP_LOCALHOSTLIST, free_entry);
  496. removed++;
  497. } else {
  498. last_entry = entry;
  499. entry = entry->next;
  500. }
  501. }
  502. return removed;
  503. }
  504. /**
  505. * Add a hostname/IP address pair to the local host-list.
  506. * Duplicates are not checked.
  507. *
  508. * @param hostname hostname of the new entry
  509. * @param addr IP address of the new entry
  510. * @return ERR_OK if succeeded or ERR_MEM on memory error
  511. */
  512. err_t
  513. dns_local_addhost(const char *hostname, const ip_addr_t *addr)
  514. {
  515. struct local_hostlist_entry *entry;
  516. size_t namelen;
  517. char* entry_name;
  518. LWIP_ASSERT("invalid host name (NULL)", hostname != NULL);
  519. namelen = strlen(hostname);
  520. LWIP_ASSERT("namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN", namelen <= DNS_LOCAL_HOSTLIST_MAX_NAMELEN);
  521. entry = (struct local_hostlist_entry *)memp_malloc(MEMP_LOCALHOSTLIST);
  522. if (entry == NULL) {
  523. return ERR_MEM;
  524. }
  525. entry_name = (char*)entry + sizeof(struct local_hostlist_entry);
  526. MEMCPY(entry_name, hostname, namelen);
  527. entry_name[namelen] = 0;
  528. entry->name = entry_name;
  529. ip_addr_copy(entry->addr, *addr);
  530. entry->next = local_hostlist_dynamic;
  531. local_hostlist_dynamic = entry;
  532. return ERR_OK;
  533. }
  534. #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC*/
  535. #endif /* DNS_LOCAL_HOSTLIST */
  536. /**
  537. * Look up a hostname in the array of known hostnames.
  538. *
  539. * @note This function only looks in the internal array of known
  540. * hostnames, it does not send out a query for the hostname if none
  541. * was found. The function dns_enqueue() can be used to send a query
  542. * for a hostname.
  543. *
  544. * @param name the hostname to look up
  545. * @param addr the hostname's IP address, as u32_t (instead of ip_addr_t to
  546. * better check for failure: != IPADDR_NONE) or IPADDR_NONE if the hostname
  547. * was not found in the cached dns_table.
  548. * @return ERR_OK if found, ERR_ARG if not found
  549. */
  550. static err_t
  551. dns_lookup(const char *name, ip_addr_t *addr LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
  552. {
  553. u8_t i;
  554. #if DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN)
  555. #endif /* DNS_LOCAL_HOSTLIST || defined(DNS_LOOKUP_LOCAL_EXTERN) */
  556. #if DNS_LOCAL_HOSTLIST
  557. if (dns_lookup_local(name, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
  558. return ERR_OK;
  559. }
  560. #endif /* DNS_LOCAL_HOSTLIST */
  561. #ifdef DNS_LOOKUP_LOCAL_EXTERN
  562. if (DNS_LOOKUP_LOCAL_EXTERN(name, addr, LWIP_DNS_ADDRTYPE_ARG_OR_ZERO(dns_addrtype))) {
  563. return ERR_OK;
  564. }
  565. #endif /* DNS_LOOKUP_LOCAL_EXTERN */
  566. /* Walk through name list, return entry if found. If not, return NULL. */
  567. for (i = 0; i < DNS_TABLE_SIZE; ++i) {
  568. if ((dns_table[i].state == DNS_STATE_DONE) &&
  569. (LWIP_DNS_STRICMP(name, dns_table[i].name) == 0) &&
  570. LWIP_DNS_ADDRTYPE_MATCH_IP(dns_addrtype, dns_table[i].ipaddr)) {
  571. LWIP_DEBUGF(DNS_DEBUG, ("dns_lookup: \"%s\": found = ", name));
  572. ip_addr_debug_print(DNS_DEBUG, &(dns_table[i].ipaddr));
  573. LWIP_DEBUGF(DNS_DEBUG, ("\n"));
  574. if (addr) {
  575. ip_addr_copy(*addr, dns_table[i].ipaddr);
  576. }
  577. return ERR_OK;
  578. }
  579. }
  580. return ERR_ARG;
  581. }
  582. /**
  583. * Compare the "dotted" name "query" with the encoded name "response"
  584. * to make sure an answer from the DNS server matches the current dns_table
  585. * entry (otherwise, answers might arrive late for hostname not on the list
  586. * any more).
  587. *
  588. * @param query hostname (not encoded) from the dns_table
  589. * @param p pbuf containing the encoded hostname in the DNS response
  590. * @param start_offset offset into p where the name starts
  591. * @return 0xFFFF: names differ, other: names equal -> offset behind name
  592. */
  593. static u16_t
  594. dns_compare_name(char *query, struct pbuf* p, u16_t start_offset)
  595. {
  596. unsigned char n;
  597. u16_t response_offset = start_offset;
  598. do {
  599. n = pbuf_get_at(p, response_offset++);
  600. /** @see RFC 1035 - 4.1.4. Message compression */
  601. if ((n & 0xc0) == 0xc0) {
  602. /* Compressed name: cannot be equal since we don't send them */
  603. return 0xFFFF;
  604. } else {
  605. /* Not compressed name */
  606. while (n > 0) {
  607. if ((*query) != pbuf_get_at(p, response_offset)) {
  608. return 0xFFFF;
  609. }
  610. ++response_offset;
  611. ++query;
  612. --n;
  613. }
  614. ++query;
  615. }
  616. } while (pbuf_get_at(p, response_offset) != 0);
  617. return response_offset + 1;
  618. }
  619. /**
  620. * Walk through a compact encoded DNS name and return the end of the name.
  621. *
  622. * @param p pbuf containing the name
  623. * @param query_idx start index into p pointing to encoded DNS name in the DNS server response
  624. * @return index to end of the name
  625. */
  626. static u16_t
  627. dns_parse_name(struct pbuf* p, u16_t query_idx)
  628. {
  629. unsigned char n;
  630. do {
  631. n = pbuf_get_at(p, query_idx++);
  632. /** @see RFC 1035 - 4.1.4. Message compression */
  633. if ((n & 0xc0) == 0xc0) {
  634. /* Compressed name */
  635. break;
  636. } else {
  637. /* Not compressed name */
  638. while (n > 0) {
  639. ++query_idx;
  640. --n;
  641. }
  642. }
  643. } while (pbuf_get_at(p, query_idx) != 0);
  644. return query_idx + 1;
  645. }
  646. /**
  647. * Send a DNS query packet.
  648. *
  649. * @param idx the DNS table entry index for which to send a request
  650. * @return ERR_OK if packet is sent; an err_t indicating the problem otherwise
  651. */
  652. static err_t
  653. dns_send(u8_t idx)
  654. {
  655. err_t err;
  656. struct dns_hdr hdr;
  657. struct dns_query qry;
  658. struct pbuf *p;
  659. u16_t query_idx, copy_len;
  660. const char *hostname, *hostname_part;
  661. u8_t n;
  662. u8_t pcb_idx;
  663. struct dns_table_entry* entry = &dns_table[idx];
  664. LWIP_DEBUGF(DNS_DEBUG, ("dns_send: dns_servers[%"U16_F"] \"%s\": request\n",
  665. (u16_t)(entry->server_idx), entry->name));
  666. LWIP_ASSERT("dns server out of array", entry->server_idx < DNS_MAX_SERVERS);
  667. if (ip_addr_isany_val(dns_servers[entry->server_idx])) {
  668. /* DNS server not valid anymore, e.g. PPP netif has been shut down */
  669. /* call specified callback function if provided */
  670. dns_call_found(idx, NULL);
  671. /* flush this entry */
  672. entry->state = DNS_STATE_UNUSED;
  673. return ERR_OK;
  674. }
  675. /* if here, we have either a new query or a retry on a previous query to process */
  676. p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(SIZEOF_DNS_HDR + strlen(entry->name) + 2 +
  677. SIZEOF_DNS_QUERY), PBUF_RAM);
  678. if (p != NULL) {
  679. /* fill dns header */
  680. memset(&hdr, 0, SIZEOF_DNS_HDR);
  681. hdr.id = htons(entry->txid);
  682. hdr.flags1 = DNS_FLAG1_RD;
  683. hdr.numquestions = PP_HTONS(1);
  684. pbuf_take(p, &hdr, SIZEOF_DNS_HDR);
  685. hostname = entry->name;
  686. --hostname;
  687. /* convert hostname into suitable query format. */
  688. query_idx = SIZEOF_DNS_HDR;
  689. do {
  690. ++hostname;
  691. hostname_part = hostname;
  692. for (n = 0; *hostname != '.' && *hostname != 0; ++hostname) {
  693. ++n;
  694. }
  695. copy_len = (u16_t)(hostname - hostname_part);
  696. pbuf_put_at(p, query_idx, n);
  697. pbuf_take_at(p, hostname_part, copy_len, query_idx + 1);
  698. query_idx += n + 1;
  699. } while (*hostname != 0);
  700. pbuf_put_at(p, query_idx, 0);
  701. query_idx++;
  702. /* fill dns query */
  703. if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype)) {
  704. qry.type = PP_HTONS(DNS_RRTYPE_AAAA);
  705. } else {
  706. qry.type = PP_HTONS(DNS_RRTYPE_A);
  707. }
  708. qry.cls = PP_HTONS(DNS_RRCLASS_IN);
  709. pbuf_take_at(p, &qry, SIZEOF_DNS_QUERY, query_idx);
  710. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
  711. pcb_idx = entry->pcb_idx;
  712. #else
  713. pcb_idx = 0;
  714. #endif
  715. /* send dns packet */
  716. LWIP_DEBUGF(DNS_DEBUG, ("sending DNS request ID %d for name \"%s\" to server %d\r\n",
  717. entry->txid, entry->name, entry->server_idx));
  718. err = udp_sendto(dns_pcbs[pcb_idx], p, &dns_servers[entry->server_idx], DNS_SERVER_PORT);
  719. /* free pbuf */
  720. pbuf_free(p);
  721. } else {
  722. err = ERR_MEM;
  723. }
  724. return err;
  725. }
  726. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
  727. static struct udp_pcb*
  728. dns_alloc_random_port(void)
  729. {
  730. err_t err;
  731. struct udp_pcb* ret;
  732. ret = udp_new_ip_type(IPADDR_TYPE_ANY);
  733. if (ret == NULL) {
  734. /* out of memory, have to reuse an existing pcb */
  735. return NULL;
  736. }
  737. do {
  738. u16_t port = (u16_t)DNS_RAND_TXID();
  739. if (!DNS_PORT_ALLOWED(port)) {
  740. /* this port is not allowed, try again */
  741. err = ERR_USE;
  742. continue;
  743. }
  744. err = udp_bind(ret, IP_ANY_TYPE, port);
  745. } while (err == ERR_USE);
  746. if (err != ERR_OK) {
  747. udp_remove(ret);
  748. return NULL;
  749. }
  750. udp_recv(ret, dns_recv, NULL);
  751. return ret;
  752. }
  753. /**
  754. * dns_alloc_pcb() - allocates a new pcb (or reuses an existing one) to be used
  755. * for sending a request
  756. *
  757. * @return an index into dns_pcbs
  758. */
  759. static u8_t
  760. dns_alloc_pcb(void)
  761. {
  762. u8_t i;
  763. u8_t idx;
  764. for (i = 0; i < DNS_MAX_SOURCE_PORTS; i++) {
  765. if (dns_pcbs[i] == NULL) {
  766. break;
  767. }
  768. }
  769. if (i < DNS_MAX_SOURCE_PORTS) {
  770. dns_pcbs[i] = dns_alloc_random_port();
  771. if (dns_pcbs[i] != NULL) {
  772. /* succeeded */
  773. dns_last_pcb_idx = i;
  774. return i;
  775. }
  776. }
  777. /* if we come here, creating a new UDP pcb failed, so we have to use
  778. an already existing one */
  779. for (i = 0, idx = dns_last_pcb_idx + 1; i < DNS_MAX_SOURCE_PORTS; i++, idx++) {
  780. if (idx >= DNS_MAX_SOURCE_PORTS) {
  781. idx = 0;
  782. }
  783. if (dns_pcbs[idx] != NULL) {
  784. dns_last_pcb_idx = idx;
  785. return idx;
  786. }
  787. }
  788. return DNS_MAX_SOURCE_PORTS;
  789. }
  790. #endif /* ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0) */
  791. /**
  792. * dns_call_found() - call the found callback and check if there are duplicate
  793. * entries for the given hostname. If there are any, their found callback will
  794. * be called and they will be removed.
  795. *
  796. * @param idx dns table index of the entry that is resolved or removed
  797. * @param addr IP address for the hostname (or NULL on error or memory shortage)
  798. */
  799. static void
  800. dns_call_found(u8_t idx, ip_addr_t* addr)
  801. {
  802. #if ((LWIP_DNS_SECURE & (LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT)) != 0)
  803. u8_t i;
  804. #endif
  805. #if LWIP_IPV4 && LWIP_IPV6
  806. if (addr != NULL) {
  807. /* check that address type matches the request and adapt the table entry */
  808. if (IP_IS_V6_VAL(*addr)) {
  809. LWIP_ASSERT("invalid response", LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
  810. dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
  811. } else {
  812. LWIP_ASSERT("invalid response", !LWIP_DNS_ADDRTYPE_IS_IPV6(dns_table[idx].reqaddrtype));
  813. dns_table[idx].reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
  814. }
  815. }
  816. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  817. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
  818. for (i = 0; i < DNS_MAX_REQUESTS; i++) {
  819. if (dns_requests[i].found && (dns_requests[i].dns_table_idx == idx)) {
  820. (*dns_requests[i].found)(dns_table[idx].name, addr, dns_requests[i].arg);
  821. /* flush this entry */
  822. dns_requests[i].found = NULL;
  823. }
  824. }
  825. #else
  826. if (dns_requests[idx].found) {
  827. (*dns_requests[idx].found)(dns_table[idx].name, addr, dns_requests[idx].arg);
  828. }
  829. dns_requests[idx].found = NULL;
  830. #endif
  831. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
  832. /* close the pcb used unless other request are using it */
  833. for (i = 0; i < DNS_MAX_REQUESTS; i++) {
  834. if (i == idx) {
  835. continue; /* only check other requests */
  836. }
  837. if (dns_table[i].state == DNS_STATE_ASKING) {
  838. if (dns_table[i].pcb_idx == dns_table[idx].pcb_idx) {
  839. /* another request is still using the same pcb */
  840. dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
  841. break;
  842. }
  843. }
  844. }
  845. if (dns_table[idx].pcb_idx < DNS_MAX_SOURCE_PORTS) {
  846. /* if we come here, the pcb is not used any more and can be removed */
  847. udp_remove(dns_pcbs[dns_table[idx].pcb_idx]);
  848. dns_pcbs[dns_table[idx].pcb_idx] = NULL;
  849. dns_table[idx].pcb_idx = DNS_MAX_SOURCE_PORTS;
  850. }
  851. #endif
  852. }
  853. /* Create a query transmission ID that is unique for all outstanding queries */
  854. static u16_t
  855. dns_create_txid(void)
  856. {
  857. u16_t txid;
  858. u8_t i;
  859. again:
  860. txid = (u16_t)DNS_RAND_TXID();
  861. /* check whether the ID is unique */
  862. for (i = 0; i < DNS_TABLE_SIZE; i++) {
  863. if ((dns_table[i].state == DNS_STATE_ASKING) &&
  864. (dns_table[i].txid == txid)) {
  865. /* ID already used by another pending query */
  866. goto again;
  867. }
  868. }
  869. return txid;
  870. }
  871. /**
  872. * dns_check_entry() - see if entry has not yet been queried and, if so, sends out a query.
  873. * Check an entry in the dns_table:
  874. * - send out query for new entries
  875. * - retry old pending entries on timeout (also with different servers)
  876. * - remove completed entries from the table if their TTL has expired
  877. *
  878. * @param i index of the dns_table entry to check
  879. */
  880. static void
  881. dns_check_entry(u8_t i)
  882. {
  883. err_t err;
  884. struct dns_table_entry *entry = &dns_table[i];
  885. LWIP_ASSERT("array index out of bounds", i < DNS_TABLE_SIZE);
  886. switch (entry->state) {
  887. case DNS_STATE_NEW: {
  888. u16_t txid;
  889. /* initialize new entry */
  890. txid = dns_create_txid();
  891. entry->txid = txid;
  892. entry->state = DNS_STATE_ASKING;
  893. entry->server_idx = 0;
  894. entry->tmr = 1;
  895. entry->retries = 0;
  896. /* send DNS packet for this entry */
  897. err = dns_send(i);
  898. if (err != ERR_OK) {
  899. LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
  900. ("dns_send returned error: %s\n", lwip_strerr(err)));
  901. }
  902. break;
  903. }
  904. case DNS_STATE_ASKING:
  905. if (--entry->tmr == 0) {
  906. if (++entry->retries == DNS_MAX_RETRIES) {
  907. if ((entry->server_idx + 1 < DNS_MAX_SERVERS) && !ip_addr_isany_val(dns_servers[entry->server_idx + 1])) {
  908. /* change of server */
  909. entry->server_idx++;
  910. entry->tmr = 1;
  911. entry->retries = 0;
  912. } else {
  913. LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": timeout\n", entry->name));
  914. /* call specified callback function if provided */
  915. dns_call_found(i, NULL);
  916. /* flush this entry */
  917. entry->state = DNS_STATE_UNUSED;
  918. break;
  919. }
  920. } else {
  921. /* wait longer for the next retry */
  922. entry->tmr = entry->retries;
  923. }
  924. /* send DNS packet for this entry */
  925. err = dns_send(i);
  926. if (err != ERR_OK) {
  927. LWIP_DEBUGF(DNS_DEBUG | LWIP_DBG_LEVEL_WARNING,
  928. ("dns_send returned error: %s\n", lwip_strerr(err)));
  929. }
  930. }
  931. break;
  932. case DNS_STATE_DONE:
  933. /* if the time to live is nul */
  934. if ((entry->ttl == 0) || (--entry->ttl == 0)) {
  935. LWIP_DEBUGF(DNS_DEBUG, ("dns_check_entry: \"%s\": flush\n", entry->name));
  936. /* flush this entry, there cannot be any related pending entries in this state */
  937. entry->state = DNS_STATE_UNUSED;
  938. }
  939. break;
  940. case DNS_STATE_UNUSED:
  941. /* nothing to do */
  942. break;
  943. default:
  944. LWIP_ASSERT("unknown dns_table entry state:", 0);
  945. break;
  946. }
  947. }
  948. /**
  949. * Call dns_check_entry for each entry in dns_table - check all entries.
  950. */
  951. static void
  952. dns_check_entries(void)
  953. {
  954. u8_t i;
  955. for (i = 0; i < DNS_TABLE_SIZE; ++i) {
  956. dns_check_entry(i);
  957. }
  958. }
  959. /**
  960. * Receive input function for DNS response packets arriving for the dns UDP pcb.
  961. *
  962. * @params see udp.h
  963. */
  964. static void
  965. dns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
  966. {
  967. u8_t i, entry_idx = DNS_TABLE_SIZE;
  968. u16_t txid;
  969. u16_t res_idx;
  970. struct dns_hdr hdr;
  971. struct dns_answer ans;
  972. struct dns_query qry;
  973. u16_t nquestions, nanswers;
  974. LWIP_UNUSED_ARG(arg);
  975. LWIP_UNUSED_ARG(pcb);
  976. LWIP_UNUSED_ARG(port);
  977. /* is the dns message big enough ? */
  978. if (p->tot_len < (SIZEOF_DNS_HDR + SIZEOF_DNS_QUERY)) {
  979. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: pbuf too small\n"));
  980. /* free pbuf and return */
  981. goto memerr;
  982. }
  983. /* copy dns payload inside static buffer for processing */
  984. if (pbuf_copy_partial(p, &hdr, SIZEOF_DNS_HDR, 0) == SIZEOF_DNS_HDR) {
  985. /* Match the ID in the DNS header with the name table. */
  986. txid = htons(hdr.id);
  987. for (i = 0; i < DNS_TABLE_SIZE; i++) {
  988. struct dns_table_entry *entry = &dns_table[i];
  989. entry_idx = i;
  990. if ((entry->state == DNS_STATE_ASKING) &&
  991. (entry->txid == txid)) {
  992. u8_t dns_err;
  993. /* This entry is now completed. */
  994. #if ! ESP_DNS
  995. entry->state = DNS_STATE_DONE;
  996. #endif
  997. dns_err = hdr.flags2 & DNS_FLAG2_ERR_MASK;
  998. /* We only care about the question(s) and the answers. The authrr
  999. and the extrarr are simply discarded. */
  1000. nquestions = htons(hdr.numquestions);
  1001. nanswers = htons(hdr.numanswers);
  1002. /* Check for error. If so, call callback to inform. */
  1003. if (((hdr.flags1 & DNS_FLAG1_RESPONSE) == 0) || (dns_err != 0) || (nquestions != 1)) {
  1004. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in flags\n", entry->name));
  1005. /* call callback to indicate error, clean up memory and return */
  1006. #if ! ESP_DNS
  1007. goto responseerr;
  1008. }
  1009. #else
  1010. goto memerr;
  1011. }
  1012. entry->state = DNS_STATE_DONE;
  1013. #endif
  1014. /* Check whether response comes from the same network address to which the
  1015. question was sent. (RFC 5452) */
  1016. if (!ip_addr_cmp(addr, &dns_servers[entry->server_idx])) {
  1017. /* call callback to indicate error, clean up memory and return */
  1018. goto responseerr;
  1019. }
  1020. /* Check if the name in the "question" part match with the name in the entry and
  1021. skip it if equal. */
  1022. res_idx = dns_compare_name(entry->name, p, SIZEOF_DNS_HDR);
  1023. if (res_idx == 0xFFFF) {
  1024. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
  1025. /* call callback to indicate error, clean up memory and return */
  1026. goto responseerr;
  1027. }
  1028. /* check if "question" part matches the request */
  1029. pbuf_copy_partial(p, &qry, SIZEOF_DNS_QUERY, res_idx);
  1030. if ((qry.cls != PP_HTONS(DNS_RRCLASS_IN)) ||
  1031. (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_AAAA))) ||
  1032. (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype) && (qry.type != PP_HTONS(DNS_RRTYPE_A)))) {
  1033. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response not match to query\n", entry->name));
  1034. /* call callback to indicate error, clean up memory and return */
  1035. goto responseerr;
  1036. }
  1037. /* skip the rest of the "question" part */
  1038. res_idx += SIZEOF_DNS_QUERY;
  1039. while ((nanswers > 0) && (res_idx < p->tot_len)) {
  1040. /* skip answer resource record's host name */
  1041. res_idx = dns_parse_name(p, res_idx);
  1042. /* Check for IP address type and Internet class. Others are discarded. */
  1043. pbuf_copy_partial(p, &ans, SIZEOF_DNS_ANSWER, res_idx);
  1044. if (ans.cls == PP_HTONS(DNS_RRCLASS_IN)) {
  1045. #if LWIP_IPV4
  1046. if ((ans.type == PP_HTONS(DNS_RRTYPE_A)) && (ans.len == PP_HTONS(sizeof(ip4_addr_t)))) {
  1047. #if LWIP_IPV4 && LWIP_IPV6
  1048. if (!LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
  1049. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  1050. {
  1051. ip4_addr_t ip4addr;
  1052. res_idx += SIZEOF_DNS_ANSWER;
  1053. /* read the answer resource record's TTL, and maximize it if needed */
  1054. entry->ttl = ntohl(ans.ttl);
  1055. if (entry->ttl > DNS_MAX_TTL) {
  1056. entry->ttl = DNS_MAX_TTL;
  1057. }
  1058. /* read the IP address after answer resource record's header */
  1059. pbuf_copy_partial(p, &ip4addr, sizeof(ip4_addr_t), res_idx);
  1060. ip_addr_copy_from_ip4(entry->ipaddr, ip4addr);
  1061. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", entry->name));
  1062. ip_addr_debug_print(DNS_DEBUG, (&(entry->ipaddr)));
  1063. LWIP_DEBUGF(DNS_DEBUG, ("\n"));
  1064. /* call specified callback function if provided */
  1065. dns_call_found(entry_idx, &entry->ipaddr);
  1066. if (entry->ttl == 0) {
  1067. /* RFC 883, page 29: "Zero values are
  1068. interpreted to mean that the RR can only be used for the
  1069. transaction in progress, and should not be cached."
  1070. -> flush this entry now */
  1071. goto flushentry;
  1072. }
  1073. /* deallocate memory and return */
  1074. goto memerr;
  1075. }
  1076. }
  1077. #endif /* LWIP_IPV4 */
  1078. #if LWIP_IPV6
  1079. if ((ans.type == PP_HTONS(DNS_RRTYPE_AAAA)) && (ans.len == PP_HTONS(sizeof(ip6_addr_t)))) {
  1080. #if LWIP_IPV4 && LWIP_IPV6
  1081. if (LWIP_DNS_ADDRTYPE_IS_IPV6(entry->reqaddrtype))
  1082. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  1083. {
  1084. ip6_addr_t ip6addr;
  1085. res_idx += SIZEOF_DNS_ANSWER;
  1086. /* read the answer resource record's TTL, and maximize it if needed */
  1087. entry->ttl = ntohl(ans.ttl);
  1088. if (entry->ttl > DNS_MAX_TTL) {
  1089. entry->ttl = DNS_MAX_TTL;
  1090. }
  1091. /* read the IP address after answer resource record's header */
  1092. pbuf_copy_partial(p, &ip6addr, sizeof(ip6_addr_t), res_idx);
  1093. ip_addr_copy_from_ip6(entry->ipaddr, ip6addr);
  1094. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": response = ", entry->name));
  1095. ip_addr_debug_print(DNS_DEBUG, (&(entry->ipaddr)));
  1096. LWIP_DEBUGF(DNS_DEBUG, (" AAAA\n"));
  1097. /* call specified callback function if provided */
  1098. dns_call_found(entry_idx, &entry->ipaddr);
  1099. if (entry->ttl == 0) {
  1100. /* RFC 883, page 29: "Zero values are
  1101. interpreted to mean that the RR can only be used for the
  1102. transaction in progress, and should not be cached."
  1103. -> flush this entry now */
  1104. goto flushentry;
  1105. }
  1106. /* deallocate memory and return */
  1107. goto memerr;
  1108. }
  1109. }
  1110. #endif /* LWIP_IPV6 */
  1111. }
  1112. /* skip this answer */
  1113. res_idx += SIZEOF_DNS_ANSWER + htons(ans.len);
  1114. --nanswers;
  1115. }
  1116. #if LWIP_IPV4 && LWIP_IPV6
  1117. if ((entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) ||
  1118. (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
  1119. if (entry->reqaddrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
  1120. /* IPv4 failed, try IPv6 */
  1121. entry->reqaddrtype = LWIP_DNS_ADDRTYPE_IPV6;
  1122. } else {
  1123. /* IPv6 failed, try IPv4 */
  1124. entry->reqaddrtype = LWIP_DNS_ADDRTYPE_IPV4;
  1125. }
  1126. pbuf_free(p);
  1127. entry->state = DNS_STATE_NEW;
  1128. dns_check_entry(entry_idx);
  1129. return;
  1130. }
  1131. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  1132. LWIP_DEBUGF(DNS_DEBUG, ("dns_recv: \"%s\": error in response\n", entry->name));
  1133. /* call callback to indicate error, clean up memory and return */
  1134. goto responseerr;
  1135. }
  1136. }
  1137. }
  1138. /* deallocate memory and return */
  1139. goto memerr;
  1140. responseerr:
  1141. /* ERROR: call specified callback function with NULL as name to indicate an error */
  1142. dns_call_found(entry_idx, NULL);
  1143. flushentry:
  1144. /* flush this entry */
  1145. dns_table[entry_idx].state = DNS_STATE_UNUSED;
  1146. memerr:
  1147. /* free pbuf */
  1148. pbuf_free(p);
  1149. return;
  1150. }
  1151. /**
  1152. * Queues a new hostname to resolve and sends out a DNS query for that hostname
  1153. *
  1154. * @param name the hostname that is to be queried
  1155. * @param hostnamelen length of the hostname
  1156. * @param found a callback function to be called on success, failure or timeout
  1157. * @param callback_arg argument to pass to the callback function
  1158. * @return @return a err_t return code.
  1159. */
  1160. static err_t
  1161. dns_enqueue(const char *name, size_t hostnamelen, dns_found_callback found,
  1162. void *callback_arg LWIP_DNS_ADDRTYPE_ARG(u8_t dns_addrtype))
  1163. {
  1164. u8_t i;
  1165. u8_t lseq, lseqi;
  1166. struct dns_table_entry *entry = NULL;
  1167. size_t namelen;
  1168. struct dns_req_entry* req;
  1169. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
  1170. u8_t r;
  1171. /* check for duplicate entries */
  1172. for (i = 0; i < DNS_TABLE_SIZE; i++) {
  1173. if ((dns_table[i].state == DNS_STATE_ASKING) &&
  1174. (LWIP_DNS_STRICMP(name, dns_table[i].name) == 0)) {
  1175. #if LWIP_IPV4 && LWIP_IPV6
  1176. if (dns_table[i].reqaddrtype != dns_addrtype) {
  1177. /* requested address types don't match
  1178. this can lead to 2 concurrent requests, but mixing the address types
  1179. for the same host should not be that common */
  1180. continue;
  1181. }
  1182. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  1183. /* this is a duplicate entry, find a free request entry */
  1184. for (r = 0; r < DNS_MAX_REQUESTS; r++) {
  1185. if (dns_requests[r].found == 0) {
  1186. dns_requests[r].found = found;
  1187. dns_requests[r].arg = callback_arg;
  1188. dns_requests[r].dns_table_idx = i;
  1189. LWIP_DNS_SET_ADDRTYPE(dns_requests[r].reqaddrtype, dns_addrtype);
  1190. LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": duplicate request\n", name));
  1191. return ERR_INPROGRESS;
  1192. }
  1193. }
  1194. }
  1195. }
  1196. /* no duplicate entries found */
  1197. #endif
  1198. /* search an unused entry, or the oldest one */
  1199. lseq = 0;
  1200. lseqi = DNS_TABLE_SIZE;
  1201. for (i = 0; i < DNS_TABLE_SIZE; ++i) {
  1202. entry = &dns_table[i];
  1203. /* is it an unused entry ? */
  1204. if (entry->state == DNS_STATE_UNUSED) {
  1205. break;
  1206. }
  1207. /* check if this is the oldest completed entry */
  1208. if (entry->state == DNS_STATE_DONE) {
  1209. if ((u8_t)(dns_seqno - entry->seqno) > lseq) {
  1210. lseq = dns_seqno - entry->seqno;
  1211. lseqi = i;
  1212. }
  1213. }
  1214. }
  1215. /* if we don't have found an unused entry, use the oldest completed one */
  1216. if (i == DNS_TABLE_SIZE) {
  1217. if ((lseqi >= DNS_TABLE_SIZE) || (dns_table[lseqi].state != DNS_STATE_DONE)) {
  1218. /* no entry can be used now, table is full */
  1219. LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS entries table is full\n", name));
  1220. return ERR_MEM;
  1221. } else {
  1222. /* use the oldest completed one */
  1223. i = lseqi;
  1224. entry = &dns_table[i];
  1225. }
  1226. }
  1227. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING) != 0)
  1228. /* find a free request entry */
  1229. req = NULL;
  1230. for (r = 0; r < DNS_MAX_REQUESTS; r++) {
  1231. if (dns_requests[r].found == NULL) {
  1232. req = &dns_requests[r];
  1233. break;
  1234. }
  1235. }
  1236. if (req == NULL) {
  1237. /* no request entry can be used now, table is full */
  1238. LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": DNS request entries table is full\n", name));
  1239. return ERR_MEM;
  1240. }
  1241. req->dns_table_idx = i;
  1242. #else
  1243. /* in this configuration, the entry index is the same as the request index */
  1244. req = &dns_requests[i];
  1245. #endif
  1246. /* use this entry */
  1247. LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS entry %"U16_F"\n", name, (u16_t)(i)));
  1248. /* fill the entry */
  1249. entry->state = DNS_STATE_NEW;
  1250. entry->seqno = dns_seqno;
  1251. LWIP_DNS_SET_ADDRTYPE(entry->reqaddrtype, dns_addrtype);
  1252. LWIP_DNS_SET_ADDRTYPE(req->reqaddrtype, dns_addrtype);
  1253. req->found = found;
  1254. req->arg = callback_arg;
  1255. namelen = LWIP_MIN(hostnamelen, DNS_MAX_NAME_LENGTH-1);
  1256. MEMCPY(entry->name, name, namelen);
  1257. entry->name[namelen] = 0;
  1258. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0)
  1259. entry->pcb_idx = dns_alloc_pcb();
  1260. if (entry->pcb_idx >= DNS_MAX_SOURCE_PORTS) {
  1261. /* failed to get a UDP pcb */
  1262. LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": failed to allocate a pcb\n", name));
  1263. entry->state = DNS_STATE_UNUSED;
  1264. req->found = NULL;
  1265. return ERR_MEM;
  1266. }
  1267. LWIP_DEBUGF(DNS_DEBUG, ("dns_enqueue: \"%s\": use DNS pcb %"U16_F"\n", name, (u16_t)(entry->pcb_idx)));
  1268. #endif
  1269. dns_seqno++;
  1270. /* force to send query without waiting timer */
  1271. dns_check_entry(i);
  1272. /* dns query is enqueued */
  1273. return ERR_INPROGRESS;
  1274. }
  1275. /**
  1276. * Resolve a hostname (string) into an IP address.
  1277. * NON-BLOCKING callback version for use with raw API!!!
  1278. *
  1279. * Returns immediately with one of err_t return codes:
  1280. * - ERR_OK if hostname is a valid IP address string or the host
  1281. * name is already in the local names table.
  1282. * - ERR_INPROGRESS enqueue a request to be sent to the DNS server
  1283. * for resolution if no errors are present.
  1284. * - ERR_ARG: dns client not initialized or invalid hostname
  1285. *
  1286. * @param hostname the hostname that is to be queried
  1287. * @param addr pointer to a ip_addr_t where to store the address if it is already
  1288. * cached in the dns_table (only valid if ERR_OK is returned!)
  1289. * @param found a callback function to be called on success, failure or timeout (only if
  1290. * ERR_INPROGRESS is returned!)
  1291. * @param callback_arg argument to pass to the callback function
  1292. * @return a err_t return code.
  1293. */
  1294. err_t
  1295. dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found,
  1296. void *callback_arg)
  1297. {
  1298. return dns_gethostbyname_addrtype(hostname, addr, found, callback_arg, LWIP_DNS_ADDRTYPE_DEFAULT);
  1299. }
  1300. /** Like dns_gethostbyname, but returned address type can be controlled:
  1301. * @param dns_addrtype: - LWIP_DNS_ADDRTYPE_IPV4_IPV6: try to resolve IPv4 first, try IPv6 if IPv4 fails only
  1302. * - LWIP_DNS_ADDRTYPE_IPV6_IPV4: try to resolve IPv6 first, try IPv4 if IPv6 fails only
  1303. * - LWIP_DNS_ADDRTYPE_IPV4: try to resolve IPv4 only
  1304. * - LWIP_DNS_ADDRTYPE_IPV6: try to resolve IPv6 only
  1305. */
  1306. err_t
  1307. dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, dns_found_callback found,
  1308. void *callback_arg, u8_t dns_addrtype)
  1309. {
  1310. size_t hostnamelen;
  1311. /* not initialized or no valid server yet, or invalid addr pointer
  1312. * or invalid hostname or invalid hostname length */
  1313. if ((addr == NULL) ||
  1314. (!hostname) || (!hostname[0])) {
  1315. return ERR_ARG;
  1316. }
  1317. #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) == 0)
  1318. if (dns_pcbs[0] == NULL) {
  1319. return ERR_ARG;
  1320. }
  1321. #endif
  1322. hostnamelen = strlen(hostname);
  1323. if (hostnamelen >= DNS_MAX_NAME_LENGTH) {
  1324. LWIP_DEBUGF(DNS_DEBUG, ("dns_gethostbyname: name too long to resolve"));
  1325. return ERR_ARG;
  1326. }
  1327. #if LWIP_HAVE_LOOPIF
  1328. if (strcmp(hostname, "localhost") == 0) {
  1329. ip_addr_set_loopback(LWIP_DNS_ADDRTYPE_IS_IPV6(dns_addrtype), addr);
  1330. return ERR_OK;
  1331. }
  1332. #endif /* LWIP_HAVE_LOOPIF */
  1333. /* host name already in octet notation? set ip addr and return ERR_OK */
  1334. if (ipaddr_aton(hostname, addr)) {
  1335. #if LWIP_IPV4 && LWIP_IPV6
  1336. if ((IP_IS_V6(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV4)) ||
  1337. (!IP_IS_V6(addr) && (dns_addrtype != LWIP_DNS_ADDRTYPE_IPV6)))
  1338. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  1339. {
  1340. return ERR_OK;
  1341. }
  1342. }
  1343. /* already have this address cached? */
  1344. if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(dns_addrtype)) == ERR_OK) {
  1345. return ERR_OK;
  1346. }
  1347. #if LWIP_IPV4 && LWIP_IPV6
  1348. if ((dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) || (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV6_IPV4)) {
  1349. /* fallback to 2nd IP type and try again to lookup */
  1350. u8_t fallback;
  1351. if (dns_addrtype == LWIP_DNS_ADDRTYPE_IPV4_IPV6) {
  1352. fallback = LWIP_DNS_ADDRTYPE_IPV6;
  1353. } else {
  1354. fallback = LWIP_DNS_ADDRTYPE_IPV4;
  1355. }
  1356. if (dns_lookup(hostname, addr LWIP_DNS_ADDRTYPE_ARG(fallback)) == ERR_OK) {
  1357. return ERR_OK;
  1358. }
  1359. }
  1360. #else /* LWIP_IPV4 && LWIP_IPV6 */
  1361. LWIP_UNUSED_ARG(dns_addrtype);
  1362. #endif /* LWIP_IPV4 && LWIP_IPV6 */
  1363. /* prevent calling found callback if no server is set, return error instead */
  1364. if (ip_addr_isany_val(dns_servers[0])) {
  1365. return ERR_VAL;
  1366. }
  1367. /* queue query with specified callback */
  1368. return dns_enqueue(hostname, hostnamelen, found, callback_arg LWIP_DNS_ADDRTYPE_ARG(dns_addrtype));
  1369. }
  1370. #endif /* LWIP_DNS */