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