dns_sd_responder.c
Go to the documentation of this file.
1 /**
2  * @file dns_sd_responder.c
3  * @brief DNS-SD responder (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.4
37  **/
38 
39 //Switch to the appropriate trace level
40 #define TRACE_LEVEL DNS_SD_TRACE_LEVEL
41 
42 //Dependencies
43 #include "core/net.h"
44 #include "mdns/mdns_responder.h"
47 #include "debug.h"
48 
49 //Check TCP/IP stack configuration
50 #if (DNS_SD_RESPONDER_SUPPORT == ENABLED)
51 
52 //Tick counter to handle periodic operations
54 
55 
56 /**
57  * @brief Initialize settings with default values
58  * @param[out] settings Structure that contains DNS-SD responder settings
59  **/
60 
62 {
63  //Use default interface
64  settings->interface = netGetDefaultInterface();
65 
66  //DNS-SD services
67  settings->numServices = 0;
68  settings->services = NULL;
69 
70  //Number of announcement packets
72  //TTL resource record
73  settings->ttl = DNS_SD_DEFAULT_RR_TTL;
74  //FSM state change event
75  settings->stateChangeEvent = NULL;
76 }
77 
78 
79 /**
80  * @brief DNS-DS initialization
81  * @param[in] context Pointer to the DNS-SD responder context
82  * @param[in] settings DNS-SD specific settings
83  * @return Error code
84  **/
85 
87  const DnsSdResponderSettings *settings)
88 {
89  uint_t i;
90  NetInterface *interface;
91  DnsSdResponderService *service;
92 
93  //Debug message
94  TRACE_INFO("Initializing DNS-SD...\r\n");
95 
96  //Ensure the parameters are valid
97  if(context == NULL || settings == NULL)
99 
100  //Check settings
101  if(settings->interface == NULL || settings->services == NULL ||
102  settings->numServices < 1)
103  {
105  }
106 
107  //Point to the underlying network interface
108  interface = settings->interface;
109 
110  //Clear the DNS-SD responder context
111  osMemset(context, 0, sizeof(DnsSdResponderContext));
112 
113  //Initialize DNS-SD responder context
114  context->interface = settings->interface;
115  context->numServices = settings->numServices;
116  context->services = settings->services;
117  context->numAnnouncements = settings->numAnnouncements;
118  context->ttl = settings->ttl;
119  context->stateChangeEvent = settings->stateChangeEvent;
120 
121  //DNS-SD responder is currently suspended
122  context->running = FALSE;
123 
124  //Loop through the list of registered services
125  for(i = 0; i < context->numServices; i++)
126  {
127  //Point to the current entry
128  service = &context->services[i];
129 
130  //Clear entry
131  osMemset(service, 0, sizeof(DnsSdResponderService));
132 
133  //Attach DNS-SD responder context
134  service->context = context;
135  //Initialize state machine
136  service->state = MDNS_STATE_INIT;
137  }
138 
139  //Attach the DNS-SD responder context to the network interface
140  interface->dnsSdResponderContext = context;
141 
142  //Successful initialization
143  return NO_ERROR;
144 }
145 
146 
147 /**
148  * @brief Start DNS-SD responder
149  * @param[in] context Pointer to the DNS-SD responder context
150  * @return Error code
151  **/
152 
154 {
155  uint_t i;
156 
157  //Make sure the DNS-SD responder context is valid
158  if(context == NULL)
160 
161  //Debug message
162  TRACE_INFO("Starting DNS-SD...\r\n");
163 
164  //Get exclusive access
166 
167  //Start DNS-SD responder
168  context->running = TRUE;
169 
170  //Loop through the list of registered services
171  for(i = 0; i < context->numServices; i++)
172  {
173  //Initialize state machine
174  context->services[i].state = MDNS_STATE_INIT;
175  }
176 
177  //Release exclusive access
179 
180  //Successful processing
181  return NO_ERROR;
182 }
183 
184 
185 /**
186  * @brief Stop DNS-SD responder
187  * @param[in] context Pointer to the DNS-SD responder context
188  * @return Error code
189  **/
190 
192 {
193  uint_t i;
194 
195  //Make sure the DNS-SD responder context is valid
196  if(context == NULL)
198 
199  //Debug message
200  TRACE_INFO("Stopping DNS-SD...\r\n");
201 
202  //Get exclusive access
204 
205  //Suspend DNS-SD responder
206  context->running = FALSE;
207 
208  //Loop through the list of registered services
209  for(i = 0; i < context->numServices; i++)
210  {
211  //Initialize state machine
212  context->services[i].state = MDNS_STATE_INIT;
213  }
214 
215  //Release exclusive access
217 
218  //Successful processing
219  return NO_ERROR;
220 }
221 
222 
223 /**
224  * @brief Register a DNS-SD service
225  * @param[in] context Pointer to the DNS-SD responder context
226  * @param[in] index Zero-based index identifying a slot
227  * @param[in] instanceName NULL-terminated string that contains the service
228  * instance name
229  * @param[in] serviceName NULL-terminated string that contains the name of the
230  * service to be registered
231  * @param[in] priority Priority field
232  * @param[in] weight Weight field
233  * @param[in] port Port number
234  * @param[in] metadata NULL-terminated string that contains the discovery-time
235  * metadata (TXT record)
236  * @return Error code
237  **/
238 
240  uint_t index, const char_t *instanceName, const char_t *serviceName,
241  uint16_t priority, uint16_t weight, uint16_t port, const char_t *metadata)
242 {
243  size_t i;
244  size_t j;
245  size_t k;
246  size_t n;
247  DnsSdResponderService *service;
248 
249  //Check parameters
250  if(context == NULL || instanceName == NULL || serviceName == NULL ||
251  metadata == NULL)
252  {
254  }
255 
256  //The implementation limits the number of services that can be advertised
257  if(index >= context->numServices)
259 
260  //Make sure the length of the instance name is acceptable
261  if(osStrlen(instanceName) > DNS_SD_MAX_INSTANCE_NAME_LEN)
262  return ERROR_INVALID_LENGTH;
263 
264  //Make sure the length of the service name is acceptable
265  if(osStrlen(serviceName) > DNS_SD_MAX_SERVICE_NAME_LEN)
266  return ERROR_INVALID_LENGTH;
267 
268  //Get exclusive access
270 
271  //Point to the specified entry
272  service = &context->services[index];
273 
274  //Valid service?
275  if(service->instanceName[0] != '\0' &&
276  service->serviceName[0] != '\0')
277  {
278  //Send a goodbye packet
279  dnsSdResponderSendGoodbye(service);
280  }
281 
282  //Instance name
283  osStrcpy(service->instanceName, instanceName);
284  //Service name
285  osStrcpy(service->serviceName, serviceName);
286 
287  //Priority field
288  service->priority = priority;
289  //Weight field
290  service->weight = weight;
291  //Port number
292  service->port = port;
293 
294  //Clear TXT record
295  service->metadataLen = 0;
296 
297  //Point to the beginning of the information string
298  i = 0;
299  j = 0;
300 
301  //Point to the beginning of the resulting TXT record data
302  k = 0;
303 
304  //Format TXT record
305  while(1)
306  {
307  //End of text data?
308  if(metadata[i] == '\0' || metadata[i] == ';')
309  {
310  //Calculate the length of the text data
311  n = MIN(i - j, UINT8_MAX);
312 
313  //Check the length of the resulting TXT record
314  if((service->metadataLen + n + 1) > DNS_SD_MAX_METADATA_LEN)
315  break;
316 
317  //Write length field
318  service->metadata[k] = n;
319  //Write text data
320  osMemcpy(service->metadata + k + 1, metadata + j, n);
321 
322  //Jump to the next text data
323  j = i + 1;
324  //Advance write index
325  k += n + 1;
326 
327  //Update the length of the TXT record
328  service->metadataLen += n + 1;
329 
330  //End of string detected?
331  if(metadata[i] == '\0')
332  break;
333  }
334 
335  //Advance read index
336  i++;
337  }
338 
339  //Empty TXT record?
340  if(service->metadataLen == 0)
341  {
342  //An empty TXT record shall contain a single zero byte
343  service->metadata[0] = 0;
344  service->metadataLen = 1;
345  }
346 
347  //Restart probing process
349 
350  //Release exclusive access
352 
353  //Successful processing
354  return NO_ERROR;
355 }
356 
357 
358 /**
359  * @brief Unregister a DNS-SD service
360  * @param[in] context Pointer to the DNS-SD responder context
361  * @param[in] index Zero-based index identifying the service to be unregistered
362  * @return Error code
363  **/
364 
366  uint_t index)
367 {
368  DnsSdResponderService *service;
369 
370  //Check parameters
371  if(context == NULL)
373 
374  //The implementation limits the number of services that can be advertised
375  if(index >= context->numServices)
377 
378  //Get exclusive access
380 
381  //Point to the specified entry
382  service = &context->services[index];
383 
384  //Valid service?
385  if(service->instanceName[0] != '\0' &&
386  service->serviceName[0] != '\0')
387  {
388  //Send a goodbye packet
389  dnsSdResponderSendGoodbye(service);
390  }
391 
392  //Remove the service from the list
393  service->instanceName[0] = '\0';
394  service->serviceName[0] = '\0';
395 
396  //Release exclusive access
398 
399  //Successful processing
400  return NO_ERROR;
401 }
402 
403 
404 /**
405  * @brief Restart probing process
406  * @param[in] context Pointer to the DNS-SD responder context
407  * @return Error code
408  **/
409 
411 {
412  uint_t i;
413 
414  //Check parameter
415  if(context == NULL)
417 
418  //Loop through the list of registered services
419  for(i = 0; i < context->numServices; i++)
420  {
421  //Force DNS-SD to start probing again
422  context->services[i].state = MDNS_STATE_INIT;
423  }
424 
425  //Successful processing
426  return NO_ERROR;
427 }
428 
429 
430 /**
431  * @brief DNS-SD responder timer handler
432  *
433  * This routine must be periodically called by the TCP/IP stack to
434  * manage DNS-SD operation
435  *
436  * @param[in] context Pointer to the DNS-SD responder context
437  **/
438 
440 {
441  uint_t i;
442  systime_t time;
443  systime_t delay;
444  NetInterface *interface;
445  DnsSdResponderService *service;
446 
447  //Make sure the DNS-SD responder has been properly instantiated
448  if(context == NULL)
449  return;
450 
451  //Point to the underlying network interface
452  interface = context->interface;
453 
454  //Get current time
455  time = osGetSystemTime();
456 
457  //Loop through the list of registered services
458  for(i = 0; i < context->numServices; i++)
459  {
460  //Point to the current entry
461  service = &context->services[i];
462 
463  //Valid service?
464  if(service->instanceName[0] != '\0' &&
465  service->serviceName[0] != '\0')
466  {
467  //Check current state
468  if(service->state == MDNS_STATE_INIT)
469  {
470  //Ensure the mDNS and DNS-SD services are running
471  if(context->running && interface->mdnsResponderContext != NULL)
472  {
473  //Wait for mDNS probing to complete
474  if(interface->mdnsResponderContext->state == MDNS_STATE_IDLE)
475  {
476  //Initial random delay
479 
480  //Perform probing
482  }
483  }
484  }
485  else if(service->state == MDNS_STATE_PROBING)
486  {
487  //Probing failed?
488  if(service->conflict && service->retransmitCount > 0)
489  {
490  //Programmatically change the service instance name
492 
493  //Probe again, and repeat as necessary until a unique name is found
496  }
497  //Tie-break lost?
498  else if(service->tieBreakLost && service->retransmitCount > 0)
499  {
500  //The host defers to the winning host by waiting one second, and
501  //then begins probing for this record again
504  }
505  else
506  {
507  //Check current time
508  if(timeCompare(time, service->timestamp + service->timeout) >= 0)
509  {
510  //Probing is on-going?
511  if(service->retransmitCount < MDNS_PROBE_NUM)
512  {
513  //First probe?
514  if(service->retransmitCount == 0)
515  {
516  //Apparently conflicting mDNS responses received before
517  //the first probe packet is sent must be silently ignored
518  service->conflict = FALSE;
519  service->tieBreakLost = FALSE;
520  }
521 
522  //Send probe packet
523  dnsSdResponderSendProbe(service);
524 
525  //Save the time at which the packet was sent
526  service->timestamp = time;
527  //Time interval between subsequent probe packets
528  service->timeout = MDNS_PROBE_DELAY;
529  //Increment retransmission counter
530  service->retransmitCount++;
531  }
532  //Probing is complete?
533  else
534  {
535  //The mDNS responder must send unsolicited mDNS responses
536  //containing all of its newly registered resource records
537  if(context->numAnnouncements > 0)
538  {
540  }
541  else
542  {
544  }
545  }
546  }
547  }
548  }
549  else if(service->state == MDNS_STATE_ANNOUNCING)
550  {
551  //Whenever a mDNS responder receives any mDNS response (solicited or
552  //otherwise) containing a conflicting resource record, the conflict
553  //must be resolved
554  if(service->conflict)
555  {
556  //Probe again, and repeat as necessary until a unique name is
557  //found
559  }
560  else
561  {
562  //Check current time
563  if(timeCompare(time, service->timestamp + service->timeout) >= 0)
564  {
565  //Send announcement packet
567 
568  //Save the time at which the packet was sent
569  service->timestamp = time;
570  //Increment retransmission counter
571  service->retransmitCount++;
572 
573  //First announcement packet?
574  if(service->retransmitCount == 1)
575  {
576  //The mDNS responder must send at least two unsolicited
577  //responses, one second apart
578  service->timeout = MDNS_ANNOUNCE_DELAY;
579  }
580  else
581  {
582  //To provide increased robustness against packet loss, a
583  //mDNS responder may send up to eight unsolicited responses,
584  //provided that the interval between unsolicited responses
585  //increases by at least a factor of two with every response
586  //sent
587  service->timeout *= 2;
588  }
589 
590  //Last announcement packet?
591  if(service->retransmitCount >= context->numAnnouncements)
592  {
593  //A mDNS responder must not send regular periodic
594  //announcements
596  }
597  }
598  }
599  }
600  else if(service->state == MDNS_STATE_IDLE)
601  {
602  //Whenever a mDNS responder receives any mDNS response (solicited or
603  //otherwise) containing a conflicting resource record, the conflict
604  //must be resolved
605  if(service->conflict)
606  {
607  //Probe again, and repeat as necessary until a unique name is
608  //found
610  }
611  }
612  }
613  }
614 }
615 
616 
617 /**
618  * @brief Callback function for link change event
619  * @param[in] context Pointer to the DNS-SD responder context
620  **/
621 
623 {
624  uint_t i;
625 
626  //Make sure the DNS-SD responder has been properly instantiated
627  if(context == NULL)
628  return;
629 
630  //Loop through the list of registered services
631  for(i = 0; i < context->numServices; i++)
632  {
633  //Whenever a mDNS responder receives an indication of a link change
634  //event, it must perform probing and announcing
635  context->services[i].state = MDNS_STATE_INIT;
636  }
637 }
638 
639 #endif
error_t dnsSdResponderSendGoodbye(DnsSdResponderService *service)
Send goodbye packet.
error_t dnsSdResponderStop(DnsSdResponderContext *context)
Stop DNS-SD responder.
NetInterface * interface
Underlying network interface.
#define MDNS_PROBE_NUM
#define netMutex
Definition: net_legacy.h:195
error_t dnsSdResponderInit(DnsSdResponderContext *context, const DnsSdResponderSettings *settings)
DNS-DS initialization.
uint16_t weight
Definition: dns_common.h:266
#define DNS_SD_MAX_METADATA_LEN
#define TRUE
Definition: os_port.h:50
#define DNS_SD_DEFAULT_RR_TTL
systime_t dnsSdResponderTickCounter
error_t dnsSdResponderSendAnnouncement(DnsSdResponderService *service)
Send announcement packet.
DnsSdStateChangeCallback stateChangeEvent
FSM state change event.
#define MDNS_PROBE_DEFER_DELAY
uint32_t ttl
TTL resource record.
error_t dnsSdResponderStart(DnsSdResponderContext *context)
Start DNS-SD responder.
@ MDNS_STATE_IDLE
#define osStrlen(s)
Definition: os_port.h:165
uint_t numServices
Maximum number of DNS-SD services that can be registered.
#define timeCompare(t1, t2)
Definition: os_port.h:40
error_t dnsSdResponderStartProbing(DnsSdResponderContext *context)
Restart probing process.
#define MDNS_RAND_DELAY_MIN
void dnsSdResponderTick(DnsSdResponderContext *context)
DNS-SD responder timer handler.
#define FALSE
Definition: os_port.h:46
#define MDNS_RAND_DELAY_MAX
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
#define osMemcpy(dest, src, length)
Definition: os_port.h:141
uint32_t netGenerateRandRange(uint32_t min, uint32_t max)
Generate a random value in the specified range.
Definition: net_misc.c:948
error_t
Error codes.
Definition: error.h:43
void dnsSdResponderChangeInstanceName(DnsSdResponderService *service)
Programmatically change the service instance name.
DNS-SD responder (DNS-Based Service Discovery)
@ MDNS_STATE_PROBING
#define NetInterface
Definition: net.h:36
@ ERROR_INVALID_LENGTH
Definition: error.h:111
NetInterface * netGetDefaultInterface(void)
Get default network interface.
Definition: net.c:467
#define DnsSdResponderContext
#define MDNS_PROBE_DELAY
#define DnsSdResponderService
#define TRACE_INFO(...)
Definition: debug.h:95
#define DNS_SD_MAX_INSTANCE_NAME_LEN
#define MIN(a, b)
Definition: os_port.h:63
@ MDNS_STATE_INIT
error_t dnsSdResponderSendProbe(DnsSdResponderService *service)
Send probe packet.
DNS-SD responder settings.
uint32_t systime_t
System time.
uint16_t port
Definition: dns_common.h:267
char char_t
Definition: compiler_port.h:48
void dnsSdResponderChangeState(DnsSdResponderService *service, MdnsState newState, systime_t delay)
Update FSM state.
uint32_t time
Helper functions for DNS-SD responder.
@ MDNS_STATE_ANNOUNCING
uint8_t n
void osAcquireMutex(OsMutex *mutex)
Acquire ownership of the specified mutex object.
void osReleaseMutex(OsMutex *mutex)
Release ownership of the specified mutex object.
#define MDNS_PROBE_CONFLICT_DELAY
#define MDNS_ANNOUNCE_DELAY
uint_t numAnnouncements
Number of announcement packets.
error_t dnsSdResponderRegisterService(DnsSdResponderContext *context, uint_t index, const char_t *instanceName, const char_t *serviceName, uint16_t priority, uint16_t weight, uint16_t port, const char_t *metadata)
Register a DNS-SD service.
error_t dnsSdResponderUnregisterService(DnsSdResponderContext *context, uint_t index)
Unregister a DNS-SD service.
unsigned int uint_t
Definition: compiler_port.h:50
#define DNS_SD_MAX_SERVICE_NAME_LEN
#define osMemset(p, value, length)
Definition: os_port.h:135
TCP/IP stack core.
DnsSdResponderService * services
DNS-SD services.
uint16_t priority
Definition: dns_common.h:265
#define osStrcpy(s1, s2)
Definition: os_port.h:207
#define MDNS_ANNOUNCE_NUM
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
void dnsSdResponderGetDefaultSettings(DnsSdResponderSettings *settings)
Initialize settings with default values.
void dnsSdResponderLinkChangeEvent(DnsSdResponderContext *context)
Callback function for link change event.
mDNS responder (Multicast DNS)
systime_t osGetSystemTime(void)
Retrieve system time.