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-2024 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 2.4.4
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 "dns/dns_debug.h"
41 #include "debug.h"
42 
43 //Check TCP/IP stack configuration
44 #if (MDNS_CLIENT_SUPPORT == ENABLED)
45 
46 
47 /**
48  * @brief Resolve a host name using mDNS
49  * @param[in] interface Underlying network interface
50  * @param[in] name Name of the host to be resolved
51  * @param[in] type Host type (IPv4 or IPv6)
52  * @param[out] ipAddr IP address corresponding to the specified host name
53  **/
54 
57 {
58  error_t error;
59  DnsCacheEntry *entry;
60 
61 #if (NET_RTOS_SUPPORT == ENABLED)
62  systime_t delay;
63 
64  //Debug message
65  TRACE_INFO("Resolving host name %s (mDNS resolver)...\r\n", name);
66 #endif
67 
68  //Get exclusive access
70 
71  //Search the DNS cache for the specified host name
72  entry = dnsFindEntry(interface, name, type, HOST_NAME_RESOLVER_MDNS);
73 
74  //Check whether a matching entry has been found
75  if(entry != NULL)
76  {
77  //Host name already resolved?
78  if(entry->state == DNS_STATE_RESOLVED ||
79  entry->state == DNS_STATE_PERMANENT)
80  {
81  //Return the corresponding IP address
82  *ipAddr = entry->ipAddr;
83  //Successful host name resolution
84  error = NO_ERROR;
85  }
86  else
87  {
88  //Host name resolution is in progress
89  error = ERROR_IN_PROGRESS;
90  }
91  }
92  else
93  {
94  //If no entry exists, then create a new one
95  entry = dnsCreateEntry();
96 
97  //Record the host name whose IP address is unknown
98  osStrcpy(entry->name, name);
99 
100  //Initialize DNS cache entry
101  entry->type = type;
103  entry->interface = interface;
104 
105  //Initialize retransmission counter
107  //Send mDNS query
108  error = mdnsClientSendQuery(entry);
109 
110  //mDNS message successfully sent?
111  if(!error)
112  {
113  //Save the time at which the query message was sent
114  entry->timestamp = osGetSystemTime();
115  //Set timeout value
118  //Decrement retransmission counter
119  entry->retransmitCount--;
120 
121  //Switch state
122  entry->state = DNS_STATE_IN_PROGRESS;
123  //Host name resolution is in progress
124  error = ERROR_IN_PROGRESS;
125  }
126  }
127 
128  //Release exclusive access
130 
131 #if (NET_RTOS_SUPPORT == ENABLED)
132  //Set default polling interval
134 
135  //Wait the host name resolution to complete
136  while(error == ERROR_IN_PROGRESS)
137  {
138  //Wait until the next polling period
139  osDelayTask(delay);
140 
141  //Get exclusive access
143 
144  //Search the DNS cache for the specified host name
145  entry = dnsFindEntry(interface, name, type, HOST_NAME_RESOLVER_MDNS);
146 
147  //Check whether a matching entry has been found
148  if(entry != NULL)
149  {
150  //Host name successfully resolved?
151  if(entry->state == DNS_STATE_RESOLVED)
152  {
153  //Return the corresponding IP address
154  *ipAddr = entry->ipAddr;
155  //Successful host name resolution
156  error = NO_ERROR;
157  }
158  }
159  else
160  {
161  //Host name resolution failed
162  error = ERROR_FAILURE;
163  }
164 
165  //Release exclusive access
167 
168  //Backoff support for less aggressive polling
169  delay = MIN(delay * 2, DNS_CACHE_MAX_POLLING_INTERVAL);
170  }
171 
172  //Check status code
173  if(error)
174  {
175  //Failed to resolve host name
176  TRACE_INFO("Host name resolution failed!\r\n");
177  }
178  else
179  {
180  //Successful host name resolution
181  TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
182  }
183 #endif
184 
185  //Return status code
186  return error;
187 }
188 
189 
190 /**
191  * @brief Send a mDNS query message
192  * @param[in] entry Pointer to a valid DNS cache entry
193  * @return Error code
194  **/
195 
197 {
198  error_t error;
199  DnsQuestion *dnsQuestion;
201 
202  //Create an empty mDNS query message
203  error = mdnsCreateMessage(&message, FALSE);
204  //Any error to report?
205  if(error)
206  return error;
207 
208  //Encode the host name using the DNS name notation
209  message.length += dnsEncodeName(entry->name, message.dnsHeader->questions);
210 
211  //Point to the corresponding question structure
212  dnsQuestion = DNS_GET_QUESTION(message.dnsHeader, message.length);
213 
214 #if (IPV4_SUPPORT == ENABLED)
215  //An IPv4 address is expected?
216  if(entry->type == HOST_TYPE_IPV4)
217  {
218  //Fill in question structure
219  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_A);
220  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
221  }
222 #endif
223 #if (IPV6_SUPPORT == ENABLED)
224  //An IPv6 address is expected?
225  if(entry->type == HOST_TYPE_IPV6)
226  {
227  //Fill in question structure
228  dnsQuestion->qtype = HTONS(DNS_RR_TYPE_AAAA);
229  dnsQuestion->qclass = HTONS(DNS_RR_CLASS_IN);
230  }
231 #endif
232 
233  //Update the length of the mDNS query message
234  message.length += sizeof(DnsQuestion);
235  //Number of questions in the Question Section
236  message.dnsHeader->qdcount = 1;
237 
238  //Send mDNS message
239  error = mdnsSendMessage(entry->interface, &message, NULL, MDNS_PORT);
240 
241  //Free previously allocated memory
243 
244  //Return status code
245  return error;
246 }
247 
248 
249 /**
250  * @brief Parse a resource record from the Answer Section
251  * @param[in] interface Underlying network interface
252  * @param[in] message Pointer to the mDNS message
253  * @param[in] offset Offset to first byte of the resource record
254  * @param[in] record Pointer to the resource record
255  **/
256 
258  const MdnsMessage *message, size_t offset, const DnsResourceRecord *record)
259 {
260  uint_t i;
261  uint16_t rclass;
262  DnsCacheEntry *entry;
263 
264  //Loop through DNS cache entries
265  for(i = 0; i < DNS_CACHE_SIZE; i++)
266  {
267  //Point to the current entry
268  entry = &dnsCache[i];
269 
270  //mDNS name resolution in progress?
271  if(entry->state == DNS_STATE_IN_PROGRESS &&
273  {
274  //Compare resource record name
275  if(!dnsCompareName(message->dnsHeader, message->length, offset, entry->name, 0))
276  {
277  //Convert the class to host byte order
278  rclass = ntohs(record->rclass);
279  //Discard Cache Flush flag
281 
282  //Check the class of the resource record
283  if(rclass == DNS_RR_CLASS_IN)
284  {
285 #if (IPV4_SUPPORT == ENABLED)
286  //IPv4 address expected?
287  if(entry->type == HOST_TYPE_IPV4)
288  {
289  //A resource record found?
290  if(ntohs(record->rtype) == DNS_RR_TYPE_A)
291  {
292  //Verify the length of the data field
293  if(ntohs(record->rdlength) == sizeof(Ipv4Addr))
294  {
295  //Copy the IPv4 address
296  entry->ipAddr.length = sizeof(Ipv4Addr);
297  ipv4CopyAddr(&entry->ipAddr.ipv4Addr, record->rdata);
298 
299  //Save current time
300  entry->timestamp = osGetSystemTime();
301  //Save TTL value
302  entry->timeout = ntohl(record->ttl) * 1000;
303  //Limit the lifetime of the mDNS cache entries
304  entry->timeout = MIN(entry->timeout, MDNS_MAX_LIFETIME);
305 
306  //Host name successfully resolved
307  entry->state = DNS_STATE_RESOLVED;
308  }
309  }
310  }
311 #endif
312 #if (IPV6_SUPPORT == ENABLED)
313  //IPv6 address expected?
314  if(entry->type == HOST_TYPE_IPV6)
315  {
316  //AAAA resource record found?
317  if(ntohs(record->rtype) == DNS_RR_TYPE_AAAA)
318  {
319  //Verify the length of the data field
320  if(ntohs(record->rdlength) == sizeof(Ipv6Addr))
321  {
322  //Copy the IPv6 address
323  entry->ipAddr.length = sizeof(Ipv6Addr);
324  ipv6CopyAddr(&entry->ipAddr.ipv6Addr, record->rdata);
325 
326  //Save current time
327  entry->timestamp = osGetSystemTime();
328  //Save TTL value
329  entry->timeout = ntohl(record->ttl) * 1000;
330  //Limit the lifetime of the mDNS cache entries
331  entry->timeout = MIN(entry->timeout, MDNS_MAX_LIFETIME);
332 
333  //Host name successfully resolved
334  entry->state = DNS_STATE_RESOLVED;
335  }
336  }
337  }
338 #endif
339  }
340  }
341  }
342  }
343 }
344 
345 #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:257
IPv6 (Internet Protocol Version 6)
HostType
Host types.
Definition: socket.h:215
@ DNS_STATE_PERMANENT
Definition: dns_cache.h:88
HostType type
IPv4 or IPv6 host?
Definition: dns_cache.h:99
#define MDNS_CLIENT_MAX_RETRIES
Definition: mdns_client.h:50
#define netMutex
Definition: net_legacy.h:195
IP network address.
Definition: ip.h:90
uint8_t message[]
Definition: chap.h:154
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:805
Ipv6Addr
Definition: ipv6.h:260
uint8_t type
Definition: coap_common.h:176
uint16_t rclass
Definition: dns_common.h:220
HostnameResolver protocol
Name resolution protocol.
Definition: dns_cache.h:100
@ DNS_RR_CLASS_IN
Internet.
Definition: dns_common.h:124
char_t name[]
IpAddr ipAddr
IP address.
Definition: dns_cache.h:106
uint32_t Ipv4Addr
IPv4 network address.
Definition: ipv4.h:297
@ HOST_TYPE_IPV6
Definition: socket.h:218
#define MDNS_PORT
Definition: mdns_common.h:53
@ ERROR_IN_PROGRESS
Definition: error.h:213
#define FALSE
Definition: os_port.h:46
error_t
Error codes.
Definition: error.h:43
#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
@ HOST_NAME_RESOLVER_MDNS
Definition: socket.h:230
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
#define NetInterface
Definition: net.h:36
DNS cache entry.
Definition: dns_cache.h:97
@ DNS_RR_TYPE_A
Host address.
Definition: dns_common.h:137
#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:103
error_t mdnsCreateMessage(MdnsMessage *message, bool_t queryResponse)
Create an empty mDNS message.
Definition: mdns_common.c:357
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:63
size_t length
Definition: ip.h:91
@ HOST_TYPE_IPV4
Definition: socket.h:217
size_t dnsEncodeName(const char_t *src, uint8_t *dest)
Encode a domain name using the DNS name notation.
Definition: dns_common.c:58
#define DNS_CACHE_INIT_POLLING_INTERVAL
Definition: dns_cache.h:61
uint32_t systime_t
System time.
#define ntohs(value)
Definition: cpu_endian.h:421
mDNS message
Definition: mdns_common.h:78
char char_t
Definition: compiler_port.h:48
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:186
Ipv4Addr ipv4Addr
Definition: ip.h:95
#define ipv6CopyAddr(destIpAddr, srcIpAddr)
Definition: ipv6.h:123
#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
@ DNS_STATE_IN_PROGRESS
Definition: dns_cache.h:86
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.
@ DNS_STATE_RESOLVED
Definition: dns_cache.h:87
error_t mdnsClientResolve(NetInterface *interface, const char_t *name, HostType type, IpAddr *ipAddr)
Resolve a host name using mDNS.
Definition: mdns_client.c:55
DnsQuestion
Definition: dns_common.h:210
error_t mdnsClientSendQuery(DnsCacheEntry *entry)
Send a mDNS query message.
Definition: mdns_client.c:196
#define ipv4CopyAddr(destIpAddr, srcIpAddr)
Definition: ipv4.h:155
void osDelayTask(systime_t delay)
Delay routine.
Ipv4Addr ipAddr
Definition: ipcp.h:105
DnsCacheEntry dnsCache[DNS_CACHE_SIZE]
Definition: dns_cache.c:51
DnsState state
Entry state.
Definition: dns_cache.h:98
Ipv6Addr ipv6Addr
Definition: ip.h:98
uint_t retransmitCount
Retransmission counter.
Definition: dns_cache.h:110
unsigned int uint_t
Definition: compiler_port.h:50
TCP/IP stack core.
DnsResourceRecord
Definition: dns_common.h:224
@ DNS_RR_TYPE_AAAA
IPv6 address.
Definition: dns_common.h:147
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:242
#define osStrcpy(s1, s2)
Definition: os_port.h:207
#define DNS_CACHE_MAX_POLLING_INTERVAL
Definition: dns_cache.h:68
#define ntohl(value)
Definition: cpu_endian.h:422
@ NO_ERROR
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.