dns_sd.c
Go to the documentation of this file.
1 /**
2  * @file dns_sd.c
3  * @brief DNS-SD (DNS-Based Service Discovery)
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  * @section Description
28  *
29  * DNS-SD allows clients to discover a list of named instances of that
30  * desired service, using standard DNS queries. Refer to the following
31  * RFCs for complete details:
32  * - RFC 6763: DNS-Based Service Discovery
33  * - RFC 2782: A DNS RR for specifying the location of services (DNS SRV)
34  *
35  * @author Oryx Embedded SARL (www.oryx-embedded.com)
36  * @version 2.4.0
37  **/
38 
39 //Switch to the appropriate trace level
40 #define TRACE_LEVEL DNS_SD_TRACE_LEVEL
41 
42 //Dependencies
43 #include <stdlib.h>
44 #include "core/net.h"
45 #include "mdns/mdns_responder.h"
46 #include "dns_sd/dns_sd.h"
47 #include "dns_sd/dns_sd_misc.h"
48 #include "debug.h"
49 
50 //Check TCP/IP stack configuration
51 #if (DNS_SD_SUPPORT == ENABLED)
52 
53 //Tick counter to handle periodic operations
55 
56 
57 /**
58  * @brief Initialize settings with default values
59  * @param[out] settings Structure that contains DNS-SD settings
60  **/
61 
63 {
64  //Use default interface
65  settings->interface = netGetDefaultInterface();
66 
67  //Number of announcement packets
69  //TTL resource record
70  settings->ttl = DNS_SD_DEFAULT_RR_TTL;
71  //FSM state change event
72  settings->stateChangeEvent = NULL;
73 }
74 
75 
76 /**
77  * @brief DNS-DS initialization
78  * @param[in] context Pointer to the DNS-SD context
79  * @param[in] settings DNS-SD specific settings
80  * @return Error code
81  **/
82 
83 error_t dnsSdInit(DnsSdContext *context, const DnsSdSettings *settings)
84 {
85  NetInterface *interface;
86 
87  //Debug message
88  TRACE_INFO("Initializing DNS-SD...\r\n");
89 
90  //Ensure the parameters are valid
91  if(context == NULL || settings == NULL)
93 
94  //Invalid network interface?
95  if(settings->interface == NULL)
97 
98  //Point to the underlying network interface
99  interface = settings->interface;
100 
101  //Clear the DNS-SD context
102  osMemset(context, 0, sizeof(DnsSdContext));
103  //Save user settings
104  context->settings = *settings;
105 
106  //DNS-SD is currently suspended
107  context->running = FALSE;
108  //Initialize state machine
109  context->state = MDNS_STATE_INIT;
110 
111  //Attach the DNS-SD context to the network interface
112  interface->dnsSdContext = context;
113 
114  //Successful initialization
115  return NO_ERROR;
116 }
117 
118 
119 /**
120  * @brief Start mDNS responder
121  * @param[in] context Pointer to the DNS-SD context
122  * @return Error code
123  **/
124 
126 {
127  //Make sure the DNS-SD context is valid
128  if(context == NULL)
130 
131  //Debug message
132  TRACE_INFO("Starting DNS-SD...\r\n");
133 
134  //Get exclusive access
136 
137  //Start DNS-SD
138  context->running = TRUE;
139  //Initialize state machine
140  context->state = MDNS_STATE_INIT;
141 
142  //Release exclusive access
144 
145  //Successful processing
146  return NO_ERROR;
147 }
148 
149 
150 /**
151  * @brief Stop mDNS responder
152  * @param[in] context Pointer to the DNS-SD context
153  * @return Error code
154  **/
155 
157 {
158  //Make sure the DNS-SD context is valid
159  if(context == NULL)
161 
162  //Debug message
163  TRACE_INFO("Stopping DNS-SD...\r\n");
164 
165  //Get exclusive access
167 
168  //Suspend DNS-SD
169  context->running = FALSE;
170  //Reinitialize state machine
171  context->state = MDNS_STATE_INIT;
172 
173  //Release exclusive access
175 
176  //Successful processing
177  return NO_ERROR;
178 }
179 
180 
181 /**
182  * @brief Retrieve current state
183  * @param[in] context Pointer to the DNS-SD context
184  * @return Current DNS-SD state
185  **/
186 
188 {
189  MdnsState state;
190 
191  //Get exclusive access
193  //Get current state
194  state = context->state;
195  //Release exclusive access
197 
198  //Return current state
199  return state;
200 }
201 
202 
203 /**
204  * @brief Set service instance name
205  * @param[in] context Pointer to the DNS-SD context
206  * @param[in] instanceName NULL-terminated string that contains the service
207  * instance name
208  * @return Error code
209  **/
210 
211 error_t dnsSdSetInstanceName(DnsSdContext *context, const char_t *instanceName)
212 {
213  NetInterface *interface;
214 
215  //Check parameters
216  if(context == NULL || instanceName == NULL)
218 
219  //Make sure the length of the instance name is acceptable
220  if(osStrlen(instanceName) > DNS_SD_MAX_INSTANCE_NAME_LEN)
221  return ERROR_INVALID_LENGTH;
222 
223  //Get exclusive access
225 
226  //Point to the underlying network interface
227  interface = context->settings.interface;
228 
229  //Any registered services?
230  if(dnsSdGetNumServices(context) > 0)
231  {
232  //Check whether the link is up
233  if(interface->linkState)
234  {
235  //Send a goodbye packet
236  dnsSdSendGoodbye(context, NULL);
237  }
238  }
239 
240  //Set instance name
241  osStrcpy(context->instanceName, instanceName);
242 
243  //Restart probing process
244  dnsSdStartProbing(context);
245 
246  //Release exclusive access
248 
249  //Successful processing
250  return NO_ERROR;
251 }
252 
253 
254 /**
255  * @brief Register a DNS-SD service
256  * @param[in] context Pointer to the DNS-SD context
257  * @param[in] serviceName NULL-terminated string that contains the name of the
258  * service to be registered
259  * @param[in] priority Priority field
260  * @param[in] weight Weight field
261  * @param[in] port Port number
262  * @param[in] metadata NULL-terminated string that contains the discovery-time
263  * metadata (TXT record)
264  * @return Error code
265  **/
266 
267 error_t dnsSdRegisterService(DnsSdContext *context, const char_t *serviceName,
268  uint16_t priority, uint16_t weight, uint16_t port, const char_t *metadata)
269 {
270  error_t error;
271  size_t i;
272  size_t j;
273  size_t k;
274  size_t n;
275  DnsSdService *entry;
276  DnsSdService *firstFreeEntry;
277 
278  //Check parameters
279  if(context == NULL || serviceName == NULL || metadata == NULL)
281 
282  //Make sure the length of the service name is acceptable
283  if(osStrlen(serviceName) > DNS_SD_MAX_SERVICE_NAME_LEN)
284  return ERROR_INVALID_LENGTH;
285 
286  //Get exclusive access
288 
289  //Keep track of the first free entry
290  firstFreeEntry = NULL;
291 
292  //Loop through the list of registered services
293  for(i = 0; i < DNS_SD_SERVICE_LIST_SIZE; i++)
294  {
295  //Point to the current entry
296  entry = &context->serviceList[i];
297 
298  //Check if the entry is currently in use
299  if(entry->name[0] != '\0')
300  {
301  //Check whether the specified service is already registered
302  if(!osStrcasecmp(entry->name, serviceName))
303  break;
304  }
305  else
306  {
307  //Keep track of the first free entry
308  if(firstFreeEntry == NULL)
309  {
310  firstFreeEntry = entry;
311  }
312  }
313  }
314 
315  //If the specified service is not yet registered, then a new
316  //entry should be created
317  if(i >= DNS_SD_SERVICE_LIST_SIZE)
318  entry = firstFreeEntry;
319 
320  //Check whether the service list runs out of space
321  if(entry != NULL)
322  {
323  //Service name
324  osStrcpy(entry->name, serviceName);
325 
326  //Priority field
327  entry->priority = priority;
328  //Weight field
329  entry->weight = weight;
330  //Port number
331  entry->port = port;
332 
333  //Clear TXT record
334  entry->metadataLength = 0;
335 
336  //Point to the beginning of the information string
337  i = 0;
338  j = 0;
339 
340  //Point to the beginning of the resulting TXT record data
341  k = 0;
342 
343  //Format TXT record
344  while(1)
345  {
346  //End of text data?
347  if(metadata[i] == '\0' || metadata[i] == ';')
348  {
349  //Calculate the length of the text data
350  n = MIN(i - j, UINT8_MAX);
351 
352  //Check the length of the resulting TXT record
353  if((entry->metadataLength + n + 1) > DNS_SD_MAX_METADATA_LEN)
354  break;
355 
356  //Write length field
357  entry->metadata[k] = n;
358  //Write text data
359  osMemcpy(entry->metadata + k + 1, metadata + j, n);
360 
361  //Jump to the next text data
362  j = i + 1;
363  //Advance write index
364  k += n + 1;
365 
366  //Update the length of the TXT record
367  entry->metadataLength += n + 1;
368 
369  //End of string detected?
370  if(metadata[i] == '\0')
371  break;
372  }
373 
374  //Advance read index
375  i++;
376  }
377 
378  //Empty TXT record?
379  if(!entry->metadataLength)
380  {
381  //An empty TXT record shall contain a single zero byte
382  entry->metadata[0] = 0;
383  entry->metadataLength = 1;
384  }
385 
386  //Restart probing process
387  dnsSdStartProbing(context);
388 
389  //Successful processing
390  error = NO_ERROR;
391  }
392  else
393  {
394  //The service list is full
395  error = ERROR_FAILURE;
396  }
397 
398  //Release exclusive access
400 
401  //Return error code
402  return error;
403 }
404 
405 
406 /**
407  * @brief Unregister a DNS-SD service
408  * @param[in] context Pointer to the DNS-SD context
409  * @param[in] serviceName NULL-terminated string that contains the name of the
410  * service to be unregistered
411  * @return Error code
412  **/
413 
414 error_t dnsSdUnregisterService(DnsSdContext *context, const char_t *serviceName)
415 {
416  uint_t i;
417  DnsSdService *entry;
418 
419  //Check parameters
420  if(context == NULL || serviceName == NULL)
422 
423  //Get exclusive access
425 
426  //Loop through the list of registered services
427  for(i = 0; i < DNS_SD_SERVICE_LIST_SIZE; i++)
428  {
429  //Point to the current entry
430  entry = &context->serviceList[i];
431 
432  //Service name found?
433  if(!osStrcasecmp(entry->name, serviceName))
434  {
435  //Send a goodbye packet
436  dnsSdSendGoodbye(context, entry);
437  //Remove the service from the list
438  entry->name[0] = '\0';
439  }
440  }
441 
442  //Release exclusive access
444 
445  //Successful processing
446  return NO_ERROR;
447 }
448 
449 
450 /**
451  * @brief Get the number of registered services
452  * @param[in] context Pointer to the DNS-SD context
453  * @return Number of registered services
454  **/
455 
457 {
458  uint_t i;
459  uint_t n;
460 
461  //Number of registered services
462  n = 0;
463 
464  //Check parameter
465  if(context != NULL)
466  {
467  //Valid instance name?
468  if(context->instanceName[0] != '\0')
469  {
470  //Loop through the list of registered services
471  for(i = 0; i < DNS_SD_SERVICE_LIST_SIZE; i++)
472  {
473  //Check if the entry is currently in use
474  if(context->serviceList[i].name[0] != '\0')
475  n++;
476  }
477  }
478  }
479 
480  //Return the number of registered services
481  return n;
482 }
483 
484 
485 /**
486  * @brief Restart probing process
487  * @param[in] context Pointer to the DNS-SD context
488  * @return Error code
489  **/
490 
492 {
493  //Check parameter
494  if(context == NULL)
496 
497  //Force DNS-SD to start probing again
498  context->state = MDNS_STATE_INIT;
499 
500  //Successful processing
501  return NO_ERROR;
502 }
503 
504 
505 /**
506  * @brief DNS-SD responder timer handler
507  *
508  * This routine must be periodically called by the TCP/IP stack to
509  * manage DNS-SD operation
510  *
511  * @param[in] context Pointer to the DNS-SD context
512  **/
513 
514 void dnsSdTick(DnsSdContext *context)
515 {
516  systime_t time;
517  systime_t delay;
518  NetInterface *interface;
519 
520  //Make sure DNS-SD has been properly instantiated
521  if(context == NULL)
522  return;
523 
524  //Point to the underlying network interface
525  interface = context->settings.interface;
526 
527  //Get current time
528  time = osGetSystemTime();
529 
530  //Check current state
531  if(context->state == MDNS_STATE_INIT)
532  {
533  //Ensure the mDNS and DNS-SD services are running
534  if(context->running && interface->mdnsResponderContext != NULL)
535  {
536  //Wait for mDNS probing to complete
537  if(interface->mdnsResponderContext->state == MDNS_STATE_IDLE)
538  {
539  //Any registered services?
540  if(dnsSdGetNumServices(context) > 0)
541  {
542  //Initial random delay
545 
546  //Perform probing
547  dnsSdChangeState(context, MDNS_STATE_PROBING, delay);
548  }
549  }
550  }
551  }
552  else if(context->state == MDNS_STATE_PROBING)
553  {
554  //Probing failed?
555  if(context->conflict && context->retransmitCount > 0)
556  {
557  //Programmatically change the service instance name
558  dnsSdChangeInstanceName(context);
559  //Probe again, and repeat as necessary until a unique name is found
561  }
562  //Tie-break lost?
563  else if(context->tieBreakLost && context->retransmitCount > 0)
564  {
565  //The host defers to the winning host by waiting one second, and
566  //then begins probing for this record again
568  }
569  else
570  {
571  //Check current time
572  if(timeCompare(time, context->timestamp + context->timeout) >= 0)
573  {
574  //Probing is on-going?
575  if(context->retransmitCount < MDNS_PROBE_NUM)
576  {
577  //First probe?
578  if(context->retransmitCount == 0)
579  {
580  //Apparently conflicting mDNS responses received before the
581  //first probe packet is sent must be silently ignored
582  context->conflict = FALSE;
583  context->tieBreakLost = FALSE;
584  }
585 
586  //Send probe packet
587  dnsSdSendProbe(context);
588 
589  //Save the time at which the packet was sent
590  context->timestamp = time;
591  //Time interval between subsequent probe packets
592  context->timeout = MDNS_PROBE_DELAY;
593  //Increment retransmission counter
594  context->retransmitCount++;
595  }
596  //Probing is complete?
597  else
598  {
599  //The mDNS responder must send unsolicited mDNS responses
600  //containing all of its newly registered resource records
601  if(context->settings.numAnnouncements > 0)
602  {
604  }
605  else
606  {
607  dnsSdChangeState(context, MDNS_STATE_IDLE, 0);
608  }
609  }
610  }
611  }
612  }
613  else if(context->state == MDNS_STATE_ANNOUNCING)
614  {
615  //Whenever a mDNS responder receives any mDNS response (solicited or
616  //otherwise) containing a conflicting resource record, the conflict
617  //must be resolved
618  if(context->conflict)
619  {
620  //Probe again, and repeat as necessary until a unique name is found
622  }
623  else
624  {
625  //Check current time
626  if(timeCompare(time, context->timestamp + context->timeout) >= 0)
627  {
628  //Send announcement packet
629  dnsSdSendAnnouncement(context);
630 
631  //Save the time at which the packet was sent
632  context->timestamp = time;
633  //Increment retransmission counter
634  context->retransmitCount++;
635 
636  //First announcement packet?
637  if(context->retransmitCount == 1)
638  {
639  //The mDNS responder must send at least two unsolicited
640  //responses, one second apart
641  context->timeout = MDNS_ANNOUNCE_DELAY;
642  }
643  else
644  {
645  //To provide increased robustness against packet loss, a mDNS
646  //responder may send up to eight unsolicited responses, provided
647  //that the interval between unsolicited responses increases by
648  //at least a factor of two with every response sent
649  context->timeout *= 2;
650  }
651 
652  //Last announcement packet?
653  if(context->retransmitCount >= context->settings.numAnnouncements)
654  {
655  //A mDNS responder must not send regular periodic announcements
656  dnsSdChangeState(context, MDNS_STATE_IDLE, 0);
657  }
658  }
659  }
660  }
661  else if(context->state == MDNS_STATE_IDLE)
662  {
663  //Whenever a mDNS responder receives any mDNS response (solicited or
664  //otherwise) containing a conflicting resource record, the conflict
665  //must be resolved
666  if(context->conflict)
667  {
668  //Probe again, and repeat as necessary until a unique name is found
670  }
671  }
672 }
673 
674 
675 /**
676  * @brief Callback function for link change event
677  * @param[in] context Pointer to the DNS-SD context
678  **/
679 
681 {
682  //Make sure DNS-SD has been properly instantiated
683  if(context == NULL)
684  return;
685 
686  //Whenever a mDNS responder receives an indication of a link
687  //change event, it must perform probing and announcing
688  dnsSdChangeState(context, MDNS_STATE_INIT, 0);
689 }
690 
691 #endif
unsigned int uint_t
Definition: compiler_port.h:50
char char_t
Definition: compiler_port.h:48
Debugging facilities.
#define TRACE_INFO(...)
Definition: debug.h:95
uint8_t n
uint32_t time
uint16_t priority
Definition: dns_common.h:265
uint16_t weight
Definition: dns_common.h:266
uint16_t port
Definition: dns_common.h:267
error_t dnsSdStartProbing(DnsSdContext *context)
Restart probing process.
Definition: dns_sd.c:491
error_t dnsSdUnregisterService(DnsSdContext *context, const char_t *serviceName)
Unregister a DNS-SD service.
Definition: dns_sd.c:414
error_t dnsSdStop(DnsSdContext *context)
Stop mDNS responder.
Definition: dns_sd.c:156
uint_t dnsSdGetNumServices(DnsSdContext *context)
Get the number of registered services.
Definition: dns_sd.c:456
void dnsSdGetDefaultSettings(DnsSdSettings *settings)
Initialize settings with default values.
Definition: dns_sd.c:62
void dnsSdLinkChangeEvent(DnsSdContext *context)
Callback function for link change event.
Definition: dns_sd.c:680
error_t dnsSdSetInstanceName(DnsSdContext *context, const char_t *instanceName)
Set service instance name.
Definition: dns_sd.c:211
error_t dnsSdRegisterService(DnsSdContext *context, const char_t *serviceName, uint16_t priority, uint16_t weight, uint16_t port, const char_t *metadata)
Register a DNS-SD service.
Definition: dns_sd.c:267
MdnsState dnsSdGetState(DnsSdContext *context)
Retrieve current state.
Definition: dns_sd.c:187
error_t dnsSdStart(DnsSdContext *context)
Start mDNS responder.
Definition: dns_sd.c:125
void dnsSdTick(DnsSdContext *context)
DNS-SD responder timer handler.
Definition: dns_sd.c:514
error_t dnsSdInit(DnsSdContext *context, const DnsSdSettings *settings)
DNS-DS initialization.
Definition: dns_sd.c:83
systime_t dnsSdTickCounter
Definition: dns_sd.c:54
DNS-SD (DNS-Based Service Discovery)
#define DNS_SD_MAX_SERVICE_NAME_LEN
Definition: dns_sd.h:62
#define DNS_SD_SERVICE_LIST_SIZE
Definition: dns_sd.h:55
#define DnsSdContext
Definition: dns_sd.h:90
#define DNS_SD_MAX_METADATA_LEN
Definition: dns_sd.h:76
#define DNS_SD_DEFAULT_RR_TTL
Definition: dns_sd.h:83
#define DNS_SD_MAX_INSTANCE_NAME_LEN
Definition: dns_sd.h:69
void dnsSdChangeInstanceName(DnsSdContext *context)
Programmatically change the service instance name.
Definition: dns_sd_misc.c:88
void dnsSdChangeState(DnsSdContext *context, MdnsState newState, systime_t delay)
Update FSM state.
Definition: dns_sd_misc.c:53
error_t dnsSdSendGoodbye(DnsSdContext *context, const DnsSdService *service)
Send goodbye packet.
Definition: dns_sd_misc.c:368
error_t dnsSdSendAnnouncement(DnsSdContext *context)
Send announcement packet.
Definition: dns_sd_misc.c:279
error_t dnsSdSendProbe(DnsSdContext *context)
Send probe packet.
Definition: dns_sd_misc.c:163
Helper functions for DNS-SD.
error_t
Error codes.
Definition: error.h:43
@ NO_ERROR
Success.
Definition: error.h:44
@ ERROR_INVALID_LENGTH
Definition: error.h:111
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
mDNS responder (Multicast DNS)
#define MDNS_PROBE_DELAY
#define MDNS_ANNOUNCE_NUM
#define MDNS_ANNOUNCE_DELAY
#define MDNS_PROBE_DEFER_DELAY
#define MDNS_RAND_DELAY_MIN
#define MDNS_PROBE_NUM
#define MDNS_RAND_DELAY_MAX
MdnsState
mDNS responder states
@ MDNS_STATE_INIT
@ MDNS_STATE_ANNOUNCING
@ MDNS_STATE_IDLE
@ MDNS_STATE_PROBING
#define MDNS_PROBE_CONFLICT_DELAY
NetInterface * netGetDefaultInterface(void)
Get default network interface.
Definition: net.c:470
TCP/IP stack core.
#define NetInterface
Definition: net.h:36
#define netMutex
Definition: net_legacy.h:195
uint32_t netGenerateRandRange(uint32_t min, uint32_t max)
Generate a random value in the specified range.
Definition: net_misc.c:914
#define osMemset(p, value, length)
Definition: os_port.h:135
#define osMemcpy(dest, src, length)
Definition: os_port.h:141
#define timeCompare(t1, t2)
Definition: os_port.h:40
#define osStrcasecmp(s1, s2)
Definition: os_port.h:183
#define MIN(a, b)
Definition: os_port.h:63
#define osStrlen(s)
Definition: os_port.h:165
#define TRUE
Definition: os_port.h:50
#define FALSE
Definition: os_port.h:46
#define osStrcpy(s1, s2)
Definition: os_port.h:207
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
systime_t osGetSystemTime(void)
Retrieve system time.
uint32_t systime_t
System time.
DNS-SD service descriptor.
Definition: dns_sd.h:124
uint16_t priority
Priority of the target host.
Definition: dns_sd.h:126
uint16_t weight
Server selection mechanism.
Definition: dns_sd.h:127
uint8_t metadata[DNS_SD_MAX_METADATA_LEN]
Discovery-time metadata (TXT record)
Definition: dns_sd.h:129
size_t metadataLength
Length of the metadata.
Definition: dns_sd.h:130
uint16_t port
Port on the target host of this service.
Definition: dns_sd.h:128
char_t name[DNS_SD_MAX_SERVICE_NAME_LEN+1]
Service name.
Definition: dns_sd.h:125
DNS-SD settings.
Definition: dns_sd.h:111
DnsSdStateChangeCallback stateChangeEvent
FSM state change event.
Definition: dns_sd.h:115
uint32_t ttl
TTL resource record.
Definition: dns_sd.h:114
uint_t numAnnouncements
Number of announcement packets.
Definition: dns_sd.h:113
NetInterface * interface
Underlying network interface.
Definition: dns_sd.h:112