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