mdns_client.c
Go to the documentation of this file.
1 /**
2  * @file mdns_client.c
3  * @brief mDNS client (Multicast DNS)
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2020 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 1.9.8
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL MDNS_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "ipv6/ipv6.h"
37 #include "ipv6/ipv6_misc.h"
38 #include "mdns/mdns_client.h"
39 #include "mdns/mdns_responder.h"
40 #include "mdns/mdns_common.h"
41 #include "dns/dns_debug.h"
42 #include "debug.h"
43 
44 //Check TCP/IP stack configuration
45 #if (MDNS_CLIENT_SUPPORT == ENABLED)
46 
47 
48 /**
49  * @brief Resolve a host name using mDNS
50  * @param[in] interface Underlying network interface
51  * @param[in] name Name of the host to be resolved
52  * @param[in] type Host type (IPv4 or IPv6)
53  * @param[out] ipAddr IP address corresponding to the specified host name
54  **/
55 
58 {
59  error_t error;
60  DnsCacheEntry *entry;
61 
62 #if (NET_RTOS_SUPPORT == ENABLED)
63  systime_t delay;
64 
65  //Debug message
66  TRACE_INFO("Resolving host name %s (mDNS resolver)...\r\n", name);
67 #endif
68 
69  //Get exclusive access
71 
72  //Search the DNS cache for the specified host name
73  entry = dnsFindEntry(interface, name, type, HOST_NAME_RESOLVER_MDNS);
74 
75  //Check whether a matching entry has been found
76  if(entry)
77  {
78  //Host name already resolved?
79  if(entry->state == DNS_STATE_RESOLVED ||
80  entry->state == DNS_STATE_PERMANENT)
81  {
82  //Return the corresponding IP address
83  *ipAddr = entry->ipAddr;
84  //Successful host name resolution
85  error = NO_ERROR;
86  }
87  else
88  {
89  //Host name resolution is in progress...
90  error = ERROR_IN_PROGRESS;
91  }
92  }
93  else
94  {
95  //If no entry exists, then create a new one
96  entry = dnsCreateEntry();
97 
98  //Record the host name whose IP address is unknown
99  osStrcpy(entry->name, name);
100 
101  //Initialize DNS cache entry
102  entry->type = type;
104  entry->interface = interface;
105 
106  //Initialize retransmission counter
108  //Send mDNS query
109  error = mdnsClientSendQuery(entry);
110 
111  //mDNS message successfully sent?
112  if(!error)
113  {
114  //Save the time at which the query message was sent
115  entry->timestamp = osGetSystemTime();
116  //Set timeout value
119  //Decrement retransmission counter
120  entry->retransmitCount--;
121 
122  //Switch state
123  entry->state = DNS_STATE_IN_PROGRESS;
124  //Host name resolution is in progress
125  error = ERROR_IN_PROGRESS;
126  }
127  }
128 
129  //Release exclusive access
131 
132 #if (NET_RTOS_SUPPORT == ENABLED)
133  //Set default polling interval
135 
136  //Wait the host name resolution to complete
137  while(error == ERROR_IN_PROGRESS)
138  {
139  //Wait until the next polling period
140  osDelayTask(delay);
141 
142  //Get exclusive access
144 
145  //Search the DNS cache for the specified host name
146  entry = dnsFindEntry(interface, name, type, HOST_NAME_RESOLVER_MDNS);
147 
148  //Check whether a matching entry has been found
149  if(entry)
150  {
151  //Host name successfully resolved?
152  if(entry->state == DNS_STATE_RESOLVED)
153  {
154  //Return the corresponding IP address
155  *ipAddr = entry->ipAddr;
156  //Successful host name resolution
157  error = NO_ERROR;
158  }
159  }
160  else
161  {
162  //Host name resolution failed
163  error = ERROR_FAILURE;
164  }
165 
166  //Release exclusive access
168 
169  //Backoff support for less aggressive polling
170  delay = MIN(delay * 2, DNS_CACHE_MAX_POLLING_INTERVAL);
171  }
172 
173  //Check status code
174  if(error)
175  {
176  //Failed to resolve host name
177  TRACE_INFO("Host name resolution failed!\r\n");
178  }
179  else
180  {
181  //Successful host name resolution
182  TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
183  }
184 #endif
185 
186  //Return status code
187  return error;
188 }
189 
190 
191 /**
192  * @brief Send a mDNS query message
193  * @param[in] entry Pointer to a valid DNS cache entry
194  * @return Error code
195  **/
196 
198 {
199  error_t error;
200  DnsQuestion *dnsQuestion;
202 
203  //Create an empty mDNS query message
204  error = mdnsCreateMessage(&message, FALSE);
205  //Any error to report?
206  if(error)
207  return error;
208 
209  //Encode the host name using the DNS name notation
210  message.length += dnsEncodeName(entry->name, message.dnsHeader->questions);
211 
212  //Point to the corresponding question structure
213  dnsQuestion = DNS_GET_QUESTION(message.dnsHeader, message.length);
214 
215 #if (IPV4_SUPPORT == ENABLED)
216  //An IPv4 address is expected?
217  if(entry->type == HOST_TYPE_IPV4)
218  {
219  //Fill in question structure
220  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_A);
221  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
222  }
223 #endif
224 #if (IPV6_SUPPORT == ENABLED)
225  //An IPv6 address is expected?
226  if(entry->type == HOST_TYPE_IPV6)
227  {
228  //Fill in question structure
229  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_AAAA);
230  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
231  }
232 #endif
233 
234  //Update the length of the mDNS query message
235  message.length += sizeof(DnsQuestion);
236  //Number of questions in the Question Section
237  message.dnsHeader->qdcount = 1;
238 
239  //Send mDNS message
240  error = mdnsSendMessage(entry->interface, &message, NULL, MDNS_PORT);
241 
242  //Free previously allocated memory
244 
245  //Return status code
246  return error;
247 }
248 
249 
250 /**
251  * @brief Parse a resource record from the Answer Section
252  * @param[in] interface Underlying network interface
253  * @param[in] message Pointer to the mDNS message
254  * @param[in] offset Offset to first byte of the resource record
255  * @param[in] record Pointer to the resource record
256  **/
257 
259  const MdnsMessage *message, size_t offset, const DnsResourceRecord *record)
260 {
261  uint_t i;
262  uint16_t rclass;
263  DnsCacheEntry *entry;
264 
265  //Loop through DNS cache entries
266  for(i = 0; i < DNS_CACHE_SIZE; i++)
267  {
268  //Point to the current entry
269  entry = &dnsCache[i];
270 
271  //mDNS name resolution in progress?
272  if(entry->state == DNS_STATE_IN_PROGRESS &&
274  {
275  //Compare resource record name
276  if(!dnsCompareName(message->dnsHeader, message->length, offset, entry->name, 0))
277  {
278  //Convert the class to host byte order
279  rclass = ntohs(record->rclass);
280  //Discard Cache Flush flag
282 
283  //Check the class of the resource record
284  if(rclass == DNS_RR_CLASS_IN)
285  {
286 #if (IPV4_SUPPORT == ENABLED)
287  //IPv4 address expected?
288  if(entry->type == HOST_TYPE_IPV4)
289  {
290  //A resource record found?
291  if(ntohs(record->rtype) == DNS_RR_TYPE_A)
292  {
293  //Verify the length of the data field
294  if(ntohs(record->rdlength) == sizeof(Ipv4Addr))
295  {
296  //Copy the IPv4 address
297  entry->ipAddr.length = sizeof(Ipv4Addr);
298  ipv4CopyAddr(&entry->ipAddr.ipv4Addr, record->rdata);
299 
300  //Save current time
301  entry->timestamp = osGetSystemTime();
302  //Save TTL value
303  entry->timeout = ntohl(record->ttl) * 1000;
304  //Limit the lifetime of the mDNS cache entries
305  entry->timeout = MIN(entry->timeout, MDNS_MAX_LIFETIME);
306 
307  //Host name successfully resolved
308  entry->state = DNS_STATE_RESOLVED;
309  }
310  }
311  }
312 #endif
313 #if (IPV6_SUPPORT == ENABLED)
314  //IPv6 address expected?
315  if(entry->type == HOST_TYPE_IPV6)
316  {
317  //AAAA resource record found?
318  if(ntohs(record->rtype) == DNS_RR_TYPE_AAAA)
319  {
320  //Verify the length of the data field
321  if(ntohs(record->rdlength) == sizeof(Ipv6Addr))
322  {
323  //Copy the IPv6 address
324  entry->ipAddr.length = sizeof(Ipv6Addr);
325  ipv6CopyAddr(&entry->ipAddr.ipv6Addr, record->rdata);
326 
327  //Save current time
328  entry->timestamp = osGetSystemTime();
329  //Save TTL value
330  entry->timeout = ntohl(record->ttl) * 1000;
331  //Limit the lifetime of the mDNS cache entries
332  entry->timeout = MIN(entry->timeout, MDNS_MAX_LIFETIME);
333 
334  //Host name successfully resolved
335  entry->state = DNS_STATE_RESOLVED;
336  }
337  }
338  }
339 #endif
340  }
341  }
342  }
343  }
344 }
345 
346 #endif
void mdnsClientParseAnRecord(NetInterface *interface, const MdnsMessage *message, size_t offset, const DnsResourceRecord *record)
Parse a resource record from the Answer Section.
Definition: mdns_client.c:258
IPv6 (Internet Protocol Version 6)
HostType
Host types.
Definition: socket.h:172
HostType type
IPv4 or IPv6 host?
Definition: dns_cache.h:99
__start_packed struct @46 DnsResourceRecord
Resource record format.
#define MDNS_CLIENT_MAX_RETRIES
Definition: mdns_client.h:50
#define netMutex
Definition: net_legacy.h:266
IP network address.
Definition: ip.h:78
__start_packed struct @45 DnsQuestion
Question format.
systime_t timeout
Retransmission timeout.
Definition: dns_cache.h:108
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:727
uint16_t rclass
Definition: dns_common.h:204
HostnameResolver protocol
Name resolution protocol.
Definition: dns_cache.h:100
Internet.
Definition: dns_common.h:110
char_t name[]
IpAddr ipAddr
IP address.
Definition: dns_cache.h:106
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:239
Definitions common to mDNS client and mDNS responder.
#define MDNS_PORT
Definition: mdns_common.h:53
#define FALSE
Definition: os_port.h:46
char_t type
error_t
Error codes.
Definition: error.h:42
#define DNS_GET_QUESTION(message, offset)
Definition: dns_common.h:63
char_t name[DNS_MAX_NAME_LEN+1]
Domain name.
Definition: dns_cache.h:105
systime_t timestamp
Time stamp to manage entry lifetime.
Definition: dns_cache.h:107
Generic error code.
Definition: error.h:45
#define NetInterface
Definition: net.h:36
DNS cache entry.
Definition: dns_cache.h:96
Host address.
Definition: dns_common.h:123
#define MDNS_CLIENT_MAX_TIMEOUT
Definition: mdns_client.h:64
Helper functions for IPv6.
DnsCacheEntry * dnsCreateEntry(void)
Create a new entry in the DNS cache.
Definition: dns_cache.c:101
error_t mdnsCreateMessage(MdnsMessage *message, bool_t queryResponse)
Create an empty mDNS message.
Definition: mdns_common.c:358
mDNS client (Multicast DNS)
systime_t maxTimeout
Maximum retransmission timeout.
Definition: dns_cache.h:109
#define TRACE_INFO(...)
Definition: debug.h:95
#define MIN(a, b)
Definition: os_port.h:62
size_t length
Definition: ip.h:80
size_t dnsEncodeName(const char_t *src, uint8_t *dest)
Encode a domain name using the DNS name notation.
Definition: dns_common.c:56
#define DNS_CACHE_INIT_POLLING_INTERVAL
Definition: dns_cache.h:61
#define ntohs(value)
Definition: cpu_endian.h:421
mDNS message
Definition: mdns_common.h:77
char char_t
Definition: compiler_port.h:43
DnsCacheEntry * dnsFindEntry(NetInterface *interface, const char_t *name, HostType type, HostnameResolver protocol)
Search the DNS cache for a given domain name.
Definition: dns_cache.c:183
Ipv4Addr ipv4Addr
Definition: ip.h:84
#define ipv6CopyAddr(destIpAddr, srcIpAddr)
Definition: ipv6.h:117
#define MDNS_MAX_LIFETIME
Definition: mdns_client.h:71
void mdnsDeleteMessage(MdnsMessage *message)
release a mDNS message
Definition: mdns_common.c:434
#define HTONS(value)
Definition: cpu_endian.h:410
NetInterface * interface
Underlying network interface.
Definition: dns_cache.h:101
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
#define DNS_CACHE_SIZE
Definition: dns_cache.h:47
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
error_t mdnsClientResolve(NetInterface *interface, const char_t *name, HostType type, IpAddr *ipAddr)
Resolve a host name using mDNS.
Definition: mdns_client.c:56
uint8_t message[]
Definition: chap.h:152
error_t mdnsClientSendQuery(DnsCacheEntry *entry)
Send a mDNS query message.
Definition: mdns_client.c:197
__start_packed struct @77 Ipv6Addr
IPv6 network address.
#define ipv4CopyAddr(destIpAddr, srcIpAddr)
Definition: ipv4.h:142
void osDelayTask(systime_t delay)
Delay routine.
DnsCacheEntry dnsCache[DNS_CACHE_SIZE]
Definition: dns_cache.c:51
DnsState state
Entry state.
Definition: dns_cache.h:98
Ipv6Addr ipv6Addr
Definition: ip.h:87
uint_t retransmitCount
Retransmission counter.
Definition: dns_cache.h:110
unsigned int uint_t
Definition: compiler_port.h:45
TCP/IP stack core.
IPv6 address.
Definition: dns_common.h:133
Data logging functions for debugging purpose (DNS)
#define MDNS_CLIENT_INIT_TIMEOUT
Definition: mdns_client.h:57
int_t dnsCompareName(const DnsHeader *message, size_t length, size_t pos, const char_t *name, uint_t level)
Compare domain names.
Definition: dns_common.c:240
#define osStrcpy(s1, s2)
Definition: os_port.h:182
#define DNS_CACHE_MAX_POLLING_INTERVAL
Definition: dns_cache.h:68
uint32_t systime_t
Definition: compiler_port.h:46
uint8_t ipAddr[4]
Definition: mib_common.h:187
#define ntohl(value)
Definition: cpu_endian.h:422
Success.
Definition: error.h:44
Debugging facilities.
error_t mdnsSendMessage(NetInterface *interface, const MdnsMessage *message, const IpAddr *destIpAddr, uint_t destPort)
Send mDNS message.
Definition: mdns_common.c:458
mDNS responder (Multicast DNS)
#define MDNS_RCLASS_CACHE_FLUSH
Definition: mdns_common.h:62
systime_t osGetSystemTime(void)
Retrieve system time.