1 // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "mdns.h"
16 #include "mdns_private.h"
17 #include "mdns_networking.h"
18 #include "esp_log.h"
19 #include <string.h>
20 #include <sys/param.h>
21 
22 #ifdef MDNS_ENABLE_DEBUG
23 void mdns_debug_packet(const uint8_t * data, size_t len);
24 #endif
25 
26 // Internal size of IPv6 address is defined here as size of AAAA record in mdns packet
27 // since the ip6_addr_t is defined in lwip and depends on using IPv6 zones
28 #define _MDNS_SIZEOF_IP6_ADDR (MDNS_ANSWER_AAAA_SIZE)
29 
30 static const char * MDNS_DEFAULT_DOMAIN = "local";
31 static const char * MDNS_SUB_STR = "_sub";
32 
33 mdns_server_t * _mdns_server = NULL;
34 
35 static const char *TAG = "MDNS";
36 
37 static volatile TaskHandle_t _mdns_service_task_handle = NULL;
38 static SemaphoreHandle_t _mdns_service_semaphore = NULL;
39 
40 static void _mdns_search_finish_done(void);
41 static mdns_search_once_t * _mdns_search_find_from(mdns_search_once_t * search, mdns_name_t * name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol);
42 static void _mdns_search_result_add_ip(mdns_search_once_t * search, const char * hostname, esp_ip_addr_t * ip, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol);
43 static void _mdns_search_result_add_srv(mdns_search_once_t * search, const char * hostname, uint16_t port, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol);
44 static void _mdns_search_result_add_txt(mdns_search_once_t * search, mdns_txt_item_t * txt, size_t txt_count, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol);
45 static mdns_result_t * _mdns_search_result_add_ptr(mdns_search_once_t * search, const char * instance, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol);
46 
47 /*
48  * @brief  Internal collection of mdns supported interfaces
49  *
50  */
51 static esp_netif_t * s_esp_netifs[MDNS_IF_MAX] = {};
52 
53 /*
54  * @brief  Convert mdns if to esp-netif handle
55  */
_mdns_get_esp_netif(mdns_if_t tcpip_if)56 esp_netif_t *_mdns_get_esp_netif(mdns_if_t tcpip_if)
57 {
58     if (tcpip_if < MDNS_IF_MAX) {
59         if (s_esp_netifs[tcpip_if] == NULL) {
60             // if local netif copy is NULL, try to search for the default interface key
61             if (tcpip_if == MDNS_IF_STA) {
62                 s_esp_netifs[MDNS_IF_STA] = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
63             } else if (tcpip_if == MDNS_IF_AP) {
64                 s_esp_netifs[MDNS_IF_AP] = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
65 #if CONFIG_ETH_ENABLED
66             } else if (tcpip_if == MDNS_IF_ETH) {
67                 s_esp_netifs[MDNS_IF_ETH] = esp_netif_get_handle_from_ifkey("ETH_DEF");
68 #endif
69             }
70         }
71         return s_esp_netifs[tcpip_if];
72     }
73     return NULL;
74 }
75 
76 /*
77  * @brief  Convert esp-netif handle to mdns if
78  */
_mdns_get_if_from_esp_netif(esp_netif_t * interface)79 static mdns_if_t _mdns_get_if_from_esp_netif(esp_netif_t *interface)
80 {
81     for (int i=0; i<MDNS_IF_MAX; ++i) {
82         if (interface == s_esp_netifs[i])
83             return i;
84     }
85     return MDNS_IF_MAX;
86 }
87 
88 
89 
_str_null_or_empty(const char * str)90 static inline bool _str_null_or_empty(const char * str){
91     return (str == NULL || *str == 0);
92 }
93 
94 /*
95  * @brief  Appends/increments a number to name/instance in case of collision
96  * */
_mdns_mangle_name(char * in)97 static char * _mdns_mangle_name(char* in) {
98     char *p = strrchr(in, '-');
99     int suffix = 0;
100     if (p == NULL) {
101         //No - in ``in``
102         suffix = 2;
103     } else {
104         char *endp = NULL;
105         suffix = strtol(p + 1, &endp, 10);
106         if (*endp != 0) {
107             //suffix is not numerical
108             suffix = 2;
109             p = NULL; //so we append -suffix to the entire string
110         }
111     }
112     char *ret;
113     if (p == NULL) {
114         //need to add -2 to string
115         ret = malloc(strlen(in) + 3);
116         if (ret == NULL) {
117             HOOK_MALLOC_FAILED;
118             return NULL;
119         }
120         sprintf(ret, "%s-2", in);
121     } else {
122         ret = malloc(strlen(in) + 2); //one extra byte in case 9-10 or 99-100 etc
123         if (ret == NULL) {
124             HOOK_MALLOC_FAILED;
125             return NULL;
126         }
127         strcpy(ret, in);
128         int baseLen = p - in; //length of 'bla' in 'bla-123'
129         //overwrite suffix with new suffix
130         sprintf(ret + baseLen, "-%d", suffix + 1);
131     }
132     return ret;
133 }
134 
135 /**
136  * @brief  finds service from given service type
137  * @param  server       the server
138  * @param  service      service type to match
139  * @param  proto        proto to match
140  *
141  * @return the service item if found or NULL on error
142  */
_mdns_get_service_item(const char * service,const char * proto)143 static mdns_srv_item_t * _mdns_get_service_item(const char * service, const char * proto)
144 {
145     mdns_srv_item_t * s = _mdns_server->services;
146     while (s) {
147         if (!strcasecmp(s->service->service, service) && !strcasecmp(s->service->proto, proto)) {
148             return s;
149         }
150         s = s->next;
151     }
152     return NULL;
153 }
154 
_mdns_can_add_more_services(void)155 static bool _mdns_can_add_more_services(void)
156 {
157     mdns_srv_item_t * s = _mdns_server->services;
158     uint16_t service_num = 0;
159     while (s) {
160         service_num ++;
161         s = s->next;
162         if (service_num >= MDNS_MAX_SERVICES) {
163             return false;
164         }
165     }
166 
167     return true;
168 }
169 
_mdns_send_rx_action(mdns_rx_packet_t * packet)170 esp_err_t _mdns_send_rx_action(mdns_rx_packet_t * packet)
171 {
172     mdns_action_t * action = NULL;
173 
174     action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
175     if (!action) {
176         HOOK_MALLOC_FAILED;
177         return ESP_ERR_NO_MEM;
178     }
179 
180     action->type = ACTION_RX_HANDLE;
181     action->data.rx_handle.packet = packet;
182     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
183         free(action);
184         return ESP_ERR_NO_MEM;
185     }
186     return ESP_OK;
187 }
188 
189 /**
190  * @brief  Get the service name of a service
191  */
_mdns_get_service_instance_name(mdns_service_t * service)192 static const char * _mdns_get_service_instance_name(mdns_service_t * service)
193 {
194     if (service && !_str_null_or_empty(service->instance)) {
195         return service->instance;
196     }
197 
198     if (_mdns_server && !_str_null_or_empty(_mdns_server->instance)) {
199         return _mdns_server->instance;
200     }
201 
202     if (_mdns_server && !_str_null_or_empty(_mdns_server->hostname)) {
203         return _mdns_server->hostname;
204     }
205 
206     return NULL;
207 }
208 
209 /**
210  * @brief  reads MDNS FQDN into mdns_name_t structure
211  *         FQDN is in format: [hostname.|[instance.]_service._proto.]local.
212  *
213  * @param  packet       MDNS packet
214  * @param  start        Starting point of FQDN
215  * @param  name         mdns_name_t structure to populate
216  * @param  buf          temporary char buffer
217  *
218  * @return the address after the parsed FQDN in the packet or NULL on error
219  */
_mdns_read_fqdn(const uint8_t * packet,const uint8_t * start,mdns_name_t * name,char * buf)220 static const uint8_t * _mdns_read_fqdn(const uint8_t * packet, const uint8_t * start, mdns_name_t * name, char * buf)
221 {
222     size_t index = 0;
223     while (start[index]) {
224         if (name->parts == 4) {
225             name->invalid = true;
226         }
227         uint8_t len = start[index++];
228         if (len < 0xC0) {
229             if (len > 63) {
230                 //length can not be more than 63
231                 return NULL;
232             }
233             uint8_t i;
234             for (i=0; i<len; i++) {
235                 buf[i] = start[index++];
236             }
237             buf[len] = '\0';
238             if (name->parts == 1 && buf[0] != '_'
239                     && (strcasecmp(buf, MDNS_DEFAULT_DOMAIN) != 0)
240                     && (strcasecmp(buf, "ip6") != 0)
241                     && (strcasecmp(buf, "in-addr") != 0)) {
242                 strlcat(name->host, ".", sizeof(name->host));
243                 strlcat(name->host, buf, sizeof(name->host));
244             } else if (strcasecmp(buf, MDNS_SUB_STR) == 0) {
245                 name->sub = 1;
246             } else if (!name->invalid) {
247                 char* mdns_name_ptrs[]={name->host, name->service, name->proto, name->domain};
248                 memcpy(mdns_name_ptrs[name->parts++], buf, len+1);
249             }
250         } else {
251             size_t address = (((uint16_t)len & 0x3F) << 8) | start[index++];
252             if ((packet + address) >= start) {
253                 //reference address can not be after where we are
254                 return NULL;
255             }
256             if (_mdns_read_fqdn(packet, packet + address, name, buf)) {
257                 return start + index;
258             }
259             return NULL;
260         }
261     }
262     return start + index + 1;
263 }
264 
265 /**
266  * @brief  sets uint16_t value in a packet
267  *
268  * @param  packet       MDNS packet
269  * @param  index        offset of uint16_t value
270  * @param  value        the value to set
271  */
_mdns_set_u16(uint8_t * packet,uint16_t index,uint16_t value)272 static inline void _mdns_set_u16(uint8_t * packet, uint16_t index, uint16_t value)
273 {
274     if ((index + 1) >= MDNS_MAX_PACKET_SIZE) {
275         return;
276     }
277     packet[index] = (value >> 8) & 0xFF;
278     packet[index+1] = value & 0xFF;
279 }
280 
281 /**
282  * @brief  appends byte in a packet, incrementing the index
283  *
284  * @param  packet       MDNS packet
285  * @param  index        offset in the packet
286  * @param  value        the value to set
287  *
288  * @return length of added data: 0 on error or 1 on success
289  */
_mdns_append_u8(uint8_t * packet,uint16_t * index,uint8_t value)290 static inline uint8_t _mdns_append_u8(uint8_t * packet, uint16_t * index, uint8_t value)
291 {
292     if (*index >= MDNS_MAX_PACKET_SIZE) {
293         return 0;
294     }
295     packet[*index] = value;
296     *index += 1;
297     return 1;
298 }
299 
300 /**
301  * @brief  appends uint16_t in a packet, incrementing the index
302  *
303  * @param  packet       MDNS packet
304  * @param  index        offset in the packet
305  * @param  value        the value to set
306  *
307  * @return length of added data: 0 on error or 2 on success
308  */
_mdns_append_u16(uint8_t * packet,uint16_t * index,uint16_t value)309 static inline uint8_t _mdns_append_u16(uint8_t * packet, uint16_t * index, uint16_t value)
310 {
311     if ((*index + 1) >= MDNS_MAX_PACKET_SIZE) {
312         return 0;
313     }
314     _mdns_append_u8(packet, index, (value >> 8) & 0xFF);
315     _mdns_append_u8(packet, index, value & 0xFF);
316     return 2;
317 }
318 
319 /**
320  * @brief  appends uint32_t in a packet, incrementing the index
321  *
322  * @param  packet       MDNS packet
323  * @param  index        offset in the packet
324  * @param  value        the value to set
325  *
326  * @return length of added data: 0 on error or 4 on success
327  */
_mdns_append_u32(uint8_t * packet,uint16_t * index,uint32_t value)328 static inline uint8_t _mdns_append_u32(uint8_t * packet, uint16_t * index, uint32_t value)
329 {
330     if ((*index + 3) >= MDNS_MAX_PACKET_SIZE) {
331         return 0;
332     }
333     _mdns_append_u8(packet, index, (value >> 24) & 0xFF);
334     _mdns_append_u8(packet, index, (value >> 16) & 0xFF);
335     _mdns_append_u8(packet, index, (value >> 8) & 0xFF);
336     _mdns_append_u8(packet, index, value & 0xFF);
337     return 4;
338 }
339 
340 /**
341  * @brief  appends answer type, class, ttl and data length to a packet, incrementing the index
342  *
343  * @param  packet       MDNS packet
344  * @param  index        offset in the packet
345  * @param  type         answer type
346  * @param  ttl          answer ttl
347  *
348  * @return length of added data: 0 on error or 10 on success
349  */
_mdns_append_type(uint8_t * packet,uint16_t * index,uint8_t type,bool flush,uint32_t ttl)350 static inline uint8_t _mdns_append_type(uint8_t * packet, uint16_t * index, uint8_t type, bool flush, uint32_t ttl)
351 {
352     if ((*index + 10) >= MDNS_MAX_PACKET_SIZE) {
353         return 0;
354     }
355     uint16_t mdns_class = MDNS_CLASS_IN;
356     if (flush) {
357         mdns_class = MDNS_CLASS_IN_FLUSH_CACHE;
358     }
359     if (type == MDNS_ANSWER_PTR) {
360         _mdns_append_u16(packet, index, MDNS_TYPE_PTR);
361         _mdns_append_u16(packet, index, mdns_class);
362     } else if (type == MDNS_ANSWER_TXT) {
363         _mdns_append_u16(packet, index, MDNS_TYPE_TXT);
364         _mdns_append_u16(packet, index, mdns_class);
365     } else if (type == MDNS_ANSWER_SRV) {
366         _mdns_append_u16(packet, index, MDNS_TYPE_SRV);
367         _mdns_append_u16(packet, index, mdns_class);
368     } else if (type == MDNS_ANSWER_A) {
369         _mdns_append_u16(packet, index, MDNS_TYPE_A);
370         _mdns_append_u16(packet, index, mdns_class);
371     } else if (type == MDNS_ANSWER_AAAA) {
372         _mdns_append_u16(packet, index, MDNS_TYPE_AAAA);
373         _mdns_append_u16(packet, index, mdns_class);
374     } else {
375         return 0;
376     }
377     _mdns_append_u32(packet, index, ttl);
378     _mdns_append_u16(packet, index, 0);
379     return 10;
380 }
381 
382 /**
383  * @brief  appends single string to a packet, incrementing the index
384  *
385  * @param  packet       MDNS packet
386  * @param  index        offset in the packet
387  * @param  string       the string to append
388  *
389  * @return length of added data: 0 on error or length of the string + 1 on success
390  */
_mdns_append_string(uint8_t * packet,uint16_t * index,const char * string)391 static inline uint8_t _mdns_append_string(uint8_t * packet, uint16_t * index, const char * string)
392 {
393     uint8_t len = strlen(string);
394     if ((*index + len + 1) >= MDNS_MAX_PACKET_SIZE) {
395         return 0;
396     }
397     _mdns_append_u8(packet, index, len);
398     memcpy(packet + *index, string, len);
399     *index += len;
400     return len + 1;
401 }
402 
403 /**
404  * @brief  appends FQDN to a packet, incrementing the index and
405  *         compressing the output if previous occurrence of the string (or part of it) has been found
406  *
407  * @param  packet       MDNS packet
408  * @param  index        offset in the packet
409  * @param  strings      string array containing the parts of the FQDN
410  * @param  count        number of strings in the array
411  *
412  * @return length of added data: 0 on error or length on success
413  */
_mdns_append_fqdn(uint8_t * packet,uint16_t * index,const char * strings[],uint8_t count)414 static uint16_t _mdns_append_fqdn(uint8_t * packet, uint16_t * index, const char * strings[], uint8_t count)
415 {
416     if (!count) {
417         //empty string so terminate
418         return _mdns_append_u8(packet, index, 0);
419     }
420     mdns_name_t name;
421     static char buf[MDNS_NAME_BUF_LEN];
422     uint8_t len = strlen(strings[0]);
423     //try to find first the string length in the packet (if it exists)
424     uint8_t * len_location = (uint8_t *)memchr(packet, (char)len, *index);
425     while (len_location) {
426         //check if the string after len_location is the string that we are looking for
427         if (memcmp(len_location+1, strings[0], len)) { //not continuing with our string
428 search_next:
429             //try and find the length byte further in the packet
430             len_location = (uint8_t *)memchr(len_location+1, (char)len, *index - (len_location+1 - packet));
431             continue;
432         }
433         //seems that we might have found the string that we are looking for
434         //read the destination into name and compare
435         name.parts = 0;
436         name.sub = 0;
437         name.host[0] = 0;
438         name.service[0] = 0;
439         name.proto[0] = 0;
440         name.domain[0] = 0;
441         const uint8_t * content = _mdns_read_fqdn(packet, len_location, &name, buf);
442         if (!content) {
443             //not a readable fqdn?
444             return 0;
445         }
446         if (name.parts == count) {
447             uint8_t i;
448             for (i=0; i<count; i++) {
449                 if (strcasecmp(strings[i], (const char *)&name + (i * (MDNS_NAME_BUF_LEN)))) {
450                     //not our string! let's search more
451                     goto search_next;
452                 }
453             }
454             //we actually have found the string
455             break;
456         } else {
457             goto search_next;
458         }
459     }
460     //string is not yet in the packet, so let's add it
461     if (!len_location) {
462         uint8_t written = _mdns_append_string(packet, index, strings[0]);
463         if (!written) {
464             return 0;
465         }
466         //run the same for the other strings in the name
467         return written + _mdns_append_fqdn(packet, index, &strings[1], count - 1);
468     }
469 
470     //we have found the string so let's insert a pointer to it instead
471     uint16_t offset = len_location - packet;
472     offset |= MDNS_NAME_REF;
473     return _mdns_append_u16(packet, index, offset);
474 }
475 
476 /**
477  * @brief  appends PTR record for service to a packet, incrementing the index
478  *
479  * @param  packet       MDNS packet
480  * @param  index        offset in the packet
481  * @param  server       the server that is hosting the service
482  * @param  service      the service to add record for
483  *
484  * @return length of added data: 0 on error or length on success
485  */
_mdns_append_ptr_record(uint8_t * packet,uint16_t * index,const char * instance,const char * service,const char * proto,bool flush,bool bye)486 static uint16_t _mdns_append_ptr_record(uint8_t * packet, uint16_t * index, const char * instance, const char * service, const char * proto, bool flush, bool bye)
487 {
488     const char * str[4];
489     uint16_t record_length = 0;
490     uint8_t part_length;
491 
492     if (service == NULL) {
493         return 0;
494     }
495 
496     str[0] = instance;
497     str[1] = service;
498     str[2] = proto;
499     str[3] = MDNS_DEFAULT_DOMAIN;
500 
501     part_length = _mdns_append_fqdn(packet, index, str + 1, 3);
502     if (!part_length) {
503         return 0;
504     }
505     record_length += part_length;
506 
507     part_length = _mdns_append_type(packet, index, MDNS_ANSWER_PTR, false, bye?0:MDNS_ANSWER_PTR_TTL);
508     if (!part_length) {
509         return 0;
510     }
511     record_length += part_length;
512 
513     uint16_t data_len_location = *index - 2;
514     part_length = _mdns_append_fqdn(packet, index, str, 4);
515     if (!part_length) {
516         return 0;
517     }
518     _mdns_set_u16(packet, data_len_location, part_length);
519     record_length += part_length;
520     return record_length;
521 }
522 
523 /**
524  * @brief  appends DNS-SD PTR record for service to a packet, incrementing the index
525  *
526  * @param  packet       MDNS packet
527  * @param  index        offset in the packet
528  * @param  server       the server that is hosting the service
529  * @param  service      the service to add record for
530  *
531  * @return length of added data: 0 on error or length on success
532  */
_mdns_append_sdptr_record(uint8_t * packet,uint16_t * index,mdns_service_t * service,bool flush,bool bye)533 static uint16_t _mdns_append_sdptr_record(uint8_t * packet, uint16_t * index, mdns_service_t * service, bool flush, bool bye)
534 {
535     const char * str[3];
536     const char * sd_str[4];
537     uint16_t record_length = 0;
538     uint8_t part_length;
539 
540     if (service == NULL) {
541         return 0;
542     }
543 
544     sd_str[0] = (char*)"_services";
545     sd_str[1] = (char*)"_dns-sd";
546     sd_str[2] = (char*)"_udp";
547     sd_str[3] = MDNS_DEFAULT_DOMAIN;
548 
549     str[0] = service->service;
550     str[1] = service->proto;
551     str[2] = MDNS_DEFAULT_DOMAIN;
552 
553     part_length = _mdns_append_fqdn(packet, index, sd_str, 4);
554 
555     record_length += part_length;
556 
557     part_length = _mdns_append_type(packet, index, MDNS_ANSWER_PTR, flush, MDNS_ANSWER_PTR_TTL);
558     if (!part_length) {
559         return 0;
560     }
561     record_length += part_length;
562 
563     uint16_t data_len_location = *index - 2;
564     part_length = _mdns_append_fqdn(packet, index, str, 3);
565     if (!part_length) {
566         return 0;
567     }
568     _mdns_set_u16(packet, data_len_location, part_length);
569     record_length += part_length;
570     return record_length;
571 }
572 
573 /**
574  * @brief  appends TXT record for service to a packet, incrementing the index
575  *
576  * @param  packet       MDNS packet
577  * @param  index        offset in the packet
578  * @param  server       the server that is hosting the service
579  * @param  service      the service to add record for
580  *
581  * @return length of added data: 0 on error or length on success
582  */
_mdns_append_txt_record(uint8_t * packet,uint16_t * index,mdns_service_t * service,bool flush,bool bye)583 static uint16_t _mdns_append_txt_record(uint8_t * packet, uint16_t * index, mdns_service_t * service, bool flush, bool bye)
584 {
585     const char * str[4];
586     uint16_t record_length = 0;
587     uint8_t part_length;
588 
589     if (service == NULL) {
590         return 0;
591     }
592 
593     str[0] = _mdns_get_service_instance_name(service);
594     str[1] = service->service;
595     str[2] = service->proto;
596     str[3] = MDNS_DEFAULT_DOMAIN;
597 
598     if (!str[0]) {
599         return 0;
600     }
601 
602     part_length = _mdns_append_fqdn(packet, index, str, 4);
603     if (!part_length) {
604         return 0;
605     }
606     record_length += part_length;
607 
608     part_length = _mdns_append_type(packet, index, MDNS_ANSWER_TXT, flush, bye?0:MDNS_ANSWER_TXT_TTL);
609     if (!part_length) {
610         return 0;
611     }
612     record_length += part_length;
613 
614     uint16_t data_len_location = *index - 2;
615     uint16_t data_len = 0;
616 
617     char * tmp;
618     mdns_txt_linked_item_t * txt = service->txt;
619     while (txt) {
620         tmp = (char *)malloc(2 + strlen(txt->key) + strlen(txt->value));
621         if (tmp) {
622             sprintf(tmp, "%s=%s", txt->key, txt->value);
623             uint8_t l = _mdns_append_string(packet, index, tmp);
624             free(tmp);
625             if (!l) {
626                 return 0;
627             }
628             data_len += l;
629         } else {
630             HOOK_MALLOC_FAILED;
631             // continue
632         }
633         txt = txt->next;
634     }
635     if (!data_len) {
636         data_len = 1;
637         packet[*index] = 0;
638         *index = *index + 1;
639     }
640     _mdns_set_u16(packet, data_len_location, data_len);
641     record_length += data_len;
642     return record_length;
643 }
644 
645 /**
646  * @brief  appends SRV record for service to a packet, incrementing the index
647  *
648  * @param  packet       MDNS packet
649  * @param  index        offset in the packet
650  * @param  server       the server that is hosting the service
651  * @param  service      the service to add record for
652  *
653  * @return length of added data: 0 on error or length on success
654  */
_mdns_append_srv_record(uint8_t * packet,uint16_t * index,mdns_service_t * service,bool flush,bool bye)655 static uint16_t _mdns_append_srv_record(uint8_t * packet, uint16_t * index, mdns_service_t * service, bool flush, bool bye)
656 {
657     const char * str[4];
658     uint16_t record_length = 0;
659     uint8_t part_length;
660 
661     if (service == NULL) {
662         return 0;
663     }
664 
665     str[0] = _mdns_get_service_instance_name(service);
666     str[1] = service->service;
667     str[2] = service->proto;
668     str[3] = MDNS_DEFAULT_DOMAIN;
669 
670     if (!str[0]) {
671         return 0;
672     }
673 
674     part_length = _mdns_append_fqdn(packet, index, str, 4);
675     if (!part_length) {
676         return 0;
677     }
678     record_length += part_length;
679 
680     part_length = _mdns_append_type(packet, index, MDNS_ANSWER_SRV, flush, bye?0:MDNS_ANSWER_SRV_TTL);
681     if (!part_length) {
682         return 0;
683     }
684     record_length += part_length;
685 
686     uint16_t data_len_location = *index - 2;
687 
688     part_length = 0;
689     part_length += _mdns_append_u16(packet, index, service->priority);
690     part_length += _mdns_append_u16(packet, index, service->weight);
691     part_length += _mdns_append_u16(packet, index, service->port);
692     if (part_length != 6) {
693         return 0;
694     }
695 
696     str[0] = _mdns_server->hostname;
697     str[1] = MDNS_DEFAULT_DOMAIN;
698 
699     if (_str_null_or_empty(str[0])) {
700         return 0;
701     }
702 
703     part_length = _mdns_append_fqdn(packet, index, str, 2);
704     if (!part_length) {
705         return 0;
706     }
707     _mdns_set_u16(packet, data_len_location, part_length + 6);
708 
709     record_length += part_length + 6;
710     return record_length;
711 }
712 
713 /**
714  * @brief  appends A record to a packet, incrementing the index
715  *
716  * @param  packet       MDNS packet
717  * @param  index        offset in the packet
718  * @param  server       the server
719  * @param  ip           the IP address to add
720  *
721  * @return length of added data: 0 on error or length on success
722  */
_mdns_append_a_record(uint8_t * packet,uint16_t * index,uint32_t ip,bool flush,bool bye)723 static uint16_t _mdns_append_a_record(uint8_t * packet, uint16_t * index, uint32_t ip, bool flush, bool bye)
724 {
725     const char * str[2];
726     uint16_t record_length = 0;
727     uint8_t part_length;
728 
729     str[0] = _mdns_server->hostname;
730     str[1] = MDNS_DEFAULT_DOMAIN;
731 
732     if (_str_null_or_empty(str[0])) {
733         return 0;
734     }
735 
736 
737     part_length = _mdns_append_fqdn(packet, index, str, 2);
738     if (!part_length) {
739         return 0;
740     }
741     record_length += part_length;
742 
743     part_length = _mdns_append_type(packet, index, MDNS_ANSWER_A, flush, bye?0:MDNS_ANSWER_A_TTL);
744     if (!part_length) {
745         return 0;
746     }
747     record_length += part_length;
748 
749     uint16_t data_len_location = *index - 2;
750 
751     if ((*index + 3) >= MDNS_MAX_PACKET_SIZE) {
752         return 0;
753     }
754     _mdns_append_u8(packet, index, ip & 0xFF);
755     _mdns_append_u8(packet, index, (ip >> 8) & 0xFF);
756     _mdns_append_u8(packet, index, (ip >> 16) & 0xFF);
757     _mdns_append_u8(packet, index, (ip >> 24) & 0xFF);
758     _mdns_set_u16(packet, data_len_location, 4);
759 
760     record_length += 4;
761     return record_length;
762 }
763 
764 #if CONFIG_LWIP_IPV6
765 /**
766  * @brief  appends AAAA record to a packet, incrementing the index
767  *
768  * @param  packet       MDNS packet
769  * @param  index        offset in the packet
770  * @param  ipv6         the IPv6 address to add
771  *
772  * @return length of added data: 0 on error or length on success
773  */
_mdns_append_aaaa_record(uint8_t * packet,uint16_t * index,uint8_t * ipv6,bool flush,bool bye)774 static uint16_t _mdns_append_aaaa_record(uint8_t * packet, uint16_t * index, uint8_t * ipv6, bool flush, bool bye)
775 {
776     const char * str[2];
777     uint16_t record_length = 0;
778     uint8_t part_length;
779 
780     str[0] = _mdns_server->hostname;
781     str[1] = MDNS_DEFAULT_DOMAIN;
782 
783     if (_str_null_or_empty(str[0])) {
784         return 0;
785     }
786 
787 
788     part_length = _mdns_append_fqdn(packet, index, str, 2);
789     if (!part_length) {
790         return 0;
791     }
792     record_length += part_length;
793 
794     part_length = _mdns_append_type(packet, index, MDNS_ANSWER_AAAA, flush, bye?0:MDNS_ANSWER_AAAA_TTL);
795     if (!part_length) {
796         return 0;
797     }
798     record_length += part_length;
799 
800     uint16_t data_len_location = *index - 2;
801 
802     if ((*index + MDNS_ANSWER_AAAA_SIZE) > MDNS_MAX_PACKET_SIZE) {
803         return 0;
804     }
805 
806     part_length = MDNS_ANSWER_AAAA_SIZE;
807     memcpy(packet + *index, ipv6, part_length);
808     *index += part_length;
809     _mdns_set_u16(packet, data_len_location, part_length);
810     record_length += part_length;
811     return record_length;
812 }
813 #endif
814 
815 /**
816  * @brief  Append question to packet
817  */
_mdns_append_question(uint8_t * packet,uint16_t * index,mdns_out_question_t * q)818 static uint16_t _mdns_append_question(uint8_t * packet, uint16_t * index, mdns_out_question_t * q)
819 {
820     const char * str[4];
821     uint8_t str_index = 0;
822     uint8_t part_length;
823     if (q->host) {
824         str[str_index++] = q->host;
825     }
826     if (q->service) {
827         str[str_index++] = q->service;
828     }
829     if (q->proto) {
830         str[str_index++] = q->proto;
831     }
832     if (q->domain) {
833         str[str_index++] = q->domain;
834     }
835 
836     part_length = _mdns_append_fqdn(packet, index, str, str_index);
837     if (!part_length) {
838         return 0;
839     }
840 
841     part_length += _mdns_append_u16(packet, index, q->type);
842     part_length += _mdns_append_u16(packet, index, q->unicast?0x8001:0x0001);
843     return part_length;
844 }
845 
846 /**
847  * @brief  Helper to get either ETH or STA if the other is provided
848  *          Used when two interfaces are on the same subnet
849  */
_mdns_get_other_if(mdns_if_t tcpip_if)850 static mdns_if_t _mdns_get_other_if (mdns_if_t tcpip_if)
851 {
852     if (tcpip_if == MDNS_IF_STA) {
853         return MDNS_IF_ETH;
854     } else if (tcpip_if == MDNS_IF_ETH) {
855         return MDNS_IF_STA;
856     }
857     return MDNS_IF_MAX;
858 }
859 
860 /**
861  * @brief  Check if interface is duplicate (two interfaces on the same subnet)
862  */
_mdns_if_is_dup(mdns_if_t tcpip_if)863 static bool _mdns_if_is_dup(mdns_if_t tcpip_if)
864 {
865     mdns_if_t other_if = _mdns_get_other_if (tcpip_if);
866     if (other_if == MDNS_IF_MAX) {
867         return false;
868     }
869     if (_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V4].state == PCB_DUP
870         || _mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].state == PCB_DUP
871         || _mdns_server->interfaces[other_if].pcbs[MDNS_IP_PROTOCOL_V4].state == PCB_DUP
872         || _mdns_server->interfaces[other_if].pcbs[MDNS_IP_PROTOCOL_V6].state == PCB_DUP
873     ) {
874         return true;
875     }
876     return false;
877 }
878 
879 #if CONFIG_LWIP_IPV6
880 /**
881  * @brief  Check if IPv6 address is NULL
882  */
_ipv6_address_is_zero(esp_ip6_addr_t ip6)883 static bool _ipv6_address_is_zero(esp_ip6_addr_t ip6)
884 {
885     uint8_t i;
886     uint8_t * data = (uint8_t *)ip6.addr;
887     for (i=0; i<_MDNS_SIZEOF_IP6_ADDR; i++) {
888         if (data[i]) {
889             return false;
890         }
891     }
892     return true;
893 }
894 #endif
895 
896 /**
897  * @brief  Append answer to packet
898  *
899  *  @return number of answers added to the packet
900  */
_mdns_append_answer(uint8_t * packet,uint16_t * index,mdns_out_answer_t * answer,mdns_if_t tcpip_if)901 static uint8_t _mdns_append_answer(uint8_t * packet, uint16_t * index, mdns_out_answer_t * answer, mdns_if_t tcpip_if)
902 {
903     if (answer->type == MDNS_TYPE_PTR) {
904 
905         if (answer->service) {
906             return _mdns_append_ptr_record(packet, index,
907                 _mdns_get_service_instance_name(answer->service),
908                 answer->service->service, answer->service->proto,
909                 answer->flush, answer->bye) > 0;
910         } else {
911             return _mdns_append_ptr_record(packet, index,
912                 answer->custom_instance, answer->custom_service, answer->custom_proto,
913                 answer->flush, answer->bye) > 0;
914         }
915     } else if (answer->type == MDNS_TYPE_SRV) {
916         return _mdns_append_srv_record(packet, index, answer->service, answer->flush, answer->bye) > 0;
917     } else if (answer->type == MDNS_TYPE_TXT) {
918         return _mdns_append_txt_record(packet, index, answer->service, answer->flush, answer->bye) > 0;
919     } else if (answer->type == MDNS_TYPE_SDPTR) {
920         return _mdns_append_sdptr_record(packet, index, answer->service, answer->flush, answer->bye) > 0;
921     } else if (answer->type == MDNS_TYPE_A) {
922         esp_netif_ip_info_t if_ip_info;
923         if (!_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V4].pcb && _mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V4].state != PCB_DUP) {
924             return 0;
925         }
926         if (esp_netif_get_ip_info(_mdns_get_esp_netif(tcpip_if), &if_ip_info)) {
927             return 0;
928         }
929         if (_mdns_append_a_record(packet, index, if_ip_info.ip.addr, answer->flush, answer->bye) <= 0) {
930             return 0;
931         }
932         if (!_mdns_if_is_dup(tcpip_if)) {
933             return 1;
934         }
935         mdns_if_t other_if = _mdns_get_other_if (tcpip_if);
936         if (esp_netif_get_ip_info(_mdns_get_esp_netif(other_if), &if_ip_info)) {
937             return 1;
938         }
939         if (_mdns_append_a_record(packet, index, if_ip_info.ip.addr, answer->flush, answer->bye) > 0) {
940             return 2;
941         }
942         return 1;
943     }
944 #if CONFIG_LWIP_IPV6
945     else if (answer->type == MDNS_TYPE_AAAA) {
946         struct esp_ip6_addr if_ip6;
947         if (!_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].pcb && _mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].state != PCB_DUP) {
948             return 0;
949         }
950         if (esp_netif_get_ip6_linklocal(_mdns_get_esp_netif(tcpip_if), &if_ip6)) {
951             return 0;
952         }
953         if (_ipv6_address_is_zero(if_ip6)) {
954             return 0;
955         }
956         if (_mdns_append_aaaa_record(packet, index, (uint8_t*)if_ip6.addr, answer->flush, answer->bye) <= 0) {
957             return 0;
958         }
959         if (!_mdns_if_is_dup(tcpip_if)) {
960             return 1;
961         }
962         mdns_if_t other_if = _mdns_get_other_if (tcpip_if);
963         if (esp_netif_get_ip6_linklocal(_mdns_get_esp_netif(other_if), &if_ip6)) {
964             return 1;
965         }
966         if (_mdns_append_aaaa_record(packet, index, (uint8_t*)if_ip6.addr, answer->flush, answer->bye) > 0) {
967             return 2;
968         }
969         return 1;
970     }
971 #endif
972     return 0;
973 }
974 
975 /**
976  * @brief  sends a packet
977  *
978  * @param  p       the packet
979  */
_mdns_dispatch_tx_packet(mdns_tx_packet_t * p)980 static void _mdns_dispatch_tx_packet(mdns_tx_packet_t * p)
981 {
982     static uint8_t packet[MDNS_MAX_PACKET_SIZE];
983     uint16_t index = MDNS_HEAD_LEN;
984     memset(packet, 0, MDNS_HEAD_LEN);
985     mdns_out_question_t * q;
986     mdns_out_answer_t * a;
987     uint8_t count;
988 
989     _mdns_set_u16(packet, MDNS_HEAD_FLAGS_OFFSET, p->flags);
990     _mdns_set_u16(packet, MDNS_HEAD_ID_OFFSET, p->id);
991 
992     count = 0;
993     q = p->questions;
994     while (q) {
995         if (_mdns_append_question(packet, &index, q)) {
996             count++;
997         }
998         q = q->next;
999     }
1000     _mdns_set_u16(packet, MDNS_HEAD_QUESTIONS_OFFSET, count);
1001 
1002     count = 0;
1003     a = p->answers;
1004     while (a) {
1005         count += _mdns_append_answer(packet, &index, a, p->tcpip_if);
1006         a = a->next;
1007     }
1008     _mdns_set_u16(packet, MDNS_HEAD_ANSWERS_OFFSET, count);
1009 
1010     count = 0;
1011     a = p->servers;
1012     while (a) {
1013         count += _mdns_append_answer(packet, &index, a, p->tcpip_if);
1014         a = a->next;
1015     }
1016     _mdns_set_u16(packet, MDNS_HEAD_SERVERS_OFFSET, count);
1017 
1018     count = 0;
1019     a = p->additional;
1020     while (a) {
1021         count += _mdns_append_answer(packet, &index, a, p->tcpip_if);
1022         a = a->next;
1023     }
1024     _mdns_set_u16(packet, MDNS_HEAD_ADDITIONAL_OFFSET, count);
1025 
1026 #ifdef MDNS_ENABLE_DEBUG
1027     _mdns_dbg_printf("\nTX[%u][%u]: ", p->tcpip_if, p->ip_protocol);
1028     if (p->dst.type == IPADDR_TYPE_V4) {
1029         _mdns_dbg_printf("To: " IPSTR ":%u, ", IP2STR(&p->dst.u_addr.ip4), p->port);
1030     } else {
1031         _mdns_dbg_printf("To: " IPV6STR ":%u, ", IPV62STR(p->dst.u_addr.ip6), p->port);
1032     }
1033     mdns_debug_packet(packet, index);
1034 #endif
1035 
1036     _mdns_udp_pcb_write(p->tcpip_if, p->ip_protocol, &p->dst, p->port, packet, index);
1037 }
1038 
1039 /**
1040  * @brief  frees a packet
1041  *
1042  * @param  packet       the packet
1043  */
_mdns_free_tx_packet(mdns_tx_packet_t * packet)1044 static void _mdns_free_tx_packet(mdns_tx_packet_t * packet)
1045 {
1046     if (!packet) {
1047         return;
1048     }
1049     queueFree(mdns_out_question_t, packet->questions);
1050     queueFree(mdns_out_answer_t, packet->answers);
1051     queueFree(mdns_out_answer_t, packet->servers);
1052     queueFree(mdns_out_answer_t, packet->additional);
1053     free(packet);
1054 }
1055 
1056 /**
1057  * @brief  schedules a packet to be sent after given milliseconds
1058  *
1059  * @param  packet       the packet
1060  * @param  ms_after     number of milliseconds after which the packet should be dispatched
1061  */
_mdns_schedule_tx_packet(mdns_tx_packet_t * packet,uint32_t ms_after)1062 static void _mdns_schedule_tx_packet(mdns_tx_packet_t * packet, uint32_t ms_after)
1063 {
1064     if (!packet) {
1065         return;
1066     }
1067     packet->send_at = (xTaskGetTickCount() * portTICK_PERIOD_MS) + ms_after;
1068     packet->next = NULL;
1069     if (!_mdns_server->tx_queue_head || _mdns_server->tx_queue_head->send_at > packet->send_at) {
1070         packet->next = _mdns_server->tx_queue_head;
1071         _mdns_server->tx_queue_head = packet;
1072         return;
1073     }
1074     mdns_tx_packet_t * q = _mdns_server->tx_queue_head;
1075     while (q->next && q->next->send_at <= packet->send_at) {
1076         q = q->next;
1077     }
1078     packet->next = q->next;
1079     q->next = packet;
1080 }
1081 
1082 /**
1083  * @brief  free all packets scheduled for sending
1084  */
_mdns_clear_tx_queue_head(void)1085 static void _mdns_clear_tx_queue_head(void)
1086 {
1087     mdns_tx_packet_t * q;
1088     while (_mdns_server->tx_queue_head) {
1089         q = _mdns_server->tx_queue_head;
1090         _mdns_server->tx_queue_head = _mdns_server->tx_queue_head->next;
1091         _mdns_free_tx_packet(q);
1092     }
1093 }
1094 
1095 /**
1096  * @brief  clear packets scheduled for sending on a specific interface
1097  *
1098  * @param  tcpip_if     the interface
1099  * @param  ip_protocol     pcb type V4/V6
1100  */
_mdns_clear_pcb_tx_queue_head(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)1101 static void _mdns_clear_pcb_tx_queue_head(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
1102 {
1103     mdns_tx_packet_t * q, * p;
1104     while (_mdns_server->tx_queue_head && _mdns_server->tx_queue_head->tcpip_if == tcpip_if && _mdns_server->tx_queue_head->ip_protocol == ip_protocol) {
1105         q = _mdns_server->tx_queue_head;
1106         _mdns_server->tx_queue_head = _mdns_server->tx_queue_head->next;
1107         _mdns_free_tx_packet(q);
1108     }
1109     if (_mdns_server->tx_queue_head) {
1110         q = _mdns_server->tx_queue_head;
1111         while (q->next) {
1112             if (q->next->tcpip_if == tcpip_if && q->next->ip_protocol == ip_protocol) {
1113                 p = q->next;
1114                 q->next = p->next;
1115                 _mdns_free_tx_packet(p);
1116             } else {
1117                 q = q->next;
1118             }
1119         }
1120     }
1121 }
1122 
1123 /**
1124  * @brief  get the next packet scheduled for sending on a specific interface
1125  *
1126  * @param  tcpip_if     the interface
1127  * @param  ip_protocol     pcb type V4/V6
1128  */
_mdns_get_next_pcb_packet(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)1129 static mdns_tx_packet_t * _mdns_get_next_pcb_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
1130 {
1131     mdns_tx_packet_t * q = _mdns_server->tx_queue_head;
1132     while (q) {
1133         if (q->tcpip_if == tcpip_if && q->ip_protocol == ip_protocol) {
1134             return q;
1135         }
1136         q = q->next;
1137     }
1138     return NULL;
1139 }
1140 
1141 /**
1142  * @brief  Find, remove and free answer from the scheduled packets
1143  */
_mdns_remove_scheduled_answer(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol,uint16_t type,mdns_srv_item_t * service)1144 static void _mdns_remove_scheduled_answer(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, uint16_t type, mdns_srv_item_t * service)
1145 {
1146     mdns_srv_item_t s = {NULL, NULL};
1147     if (!service) {
1148         service = &s;
1149     }
1150     mdns_tx_packet_t * q = _mdns_server->tx_queue_head;
1151     while (q) {
1152         if (q->tcpip_if == tcpip_if && q->ip_protocol == ip_protocol && q->distributed) {
1153             mdns_out_answer_t * a = q->answers;
1154             if (a->type == type && a->service == service->service) {
1155                 q->answers = q->answers->next;
1156                 free(a);
1157             } else {
1158                 while (a->next) {
1159                     if (a->next->type == type && a->next->service == service->service) {
1160                         mdns_out_answer_t * b = a->next;
1161                         a->next = b->next;
1162                         free(b);
1163                         break;
1164                     }
1165                     a = a->next;
1166                 }
1167             }
1168         }
1169         q = q->next;
1170     }
1171 }
1172 
1173 /**
1174  * @brief  Remove and free answer from answer list (destination)
1175  */
_mdns_dealloc_answer(mdns_out_answer_t ** destination,uint16_t type,mdns_srv_item_t * service)1176 static void _mdns_dealloc_answer(mdns_out_answer_t ** destination, uint16_t type, mdns_srv_item_t * service)
1177 {
1178     mdns_out_answer_t * d = *destination;
1179     if (!d) {
1180         return;
1181     }
1182     mdns_srv_item_t s = {NULL, NULL};
1183     if (!service) {
1184         service = &s;
1185     }
1186     if (d->type == type && d->service == service->service) {
1187         *destination = d->next;
1188         free(d);
1189         return;
1190     }
1191     while (d->next) {
1192         mdns_out_answer_t * a = d->next;
1193         if (a->type == type && a->service == service->service) {
1194             d->next = a->next;
1195             free(a);
1196             return;
1197         }
1198         d = d->next;
1199     }
1200 }
1201 
1202 /**
1203  * @brief  Allocate new answer and add it to answer list (destination)
1204  */
_mdns_alloc_answer(mdns_out_answer_t ** destination,uint16_t type,mdns_service_t * service,bool flush,bool bye)1205 static bool _mdns_alloc_answer(mdns_out_answer_t ** destination, uint16_t type, mdns_service_t * service, bool flush, bool bye)
1206 {
1207     mdns_out_answer_t * d = *destination;
1208     while (d) {
1209         if (d->type == type && d->service == service) {
1210             return true;
1211         }
1212         d = d->next;
1213     }
1214 
1215     mdns_out_answer_t * a = (mdns_out_answer_t *)malloc(sizeof(mdns_out_answer_t));
1216     if (!a) {
1217         HOOK_MALLOC_FAILED;
1218         return false;
1219     }
1220     a->type = type;
1221     a->service = service;
1222     a->custom_service = NULL;
1223     a->bye = bye;
1224     a->flush = flush;
1225     a->next = NULL;
1226     queueToEnd(mdns_out_answer_t, *destination, a);
1227     return true;
1228 }
1229 
1230 /**
1231  * @brief  Allocate new packet for sending
1232  */
_mdns_alloc_packet_default(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)1233 static mdns_tx_packet_t * _mdns_alloc_packet_default(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
1234 {
1235     mdns_tx_packet_t * packet = (mdns_tx_packet_t*)malloc(sizeof(mdns_tx_packet_t));
1236     if (!packet) {
1237         HOOK_MALLOC_FAILED;
1238         return NULL;
1239     }
1240     memset((uint8_t*)packet, 0, sizeof(mdns_tx_packet_t));
1241     packet->tcpip_if = tcpip_if;
1242     packet->ip_protocol = ip_protocol;
1243     packet->port = MDNS_SERVICE_PORT;
1244     if (ip_protocol == MDNS_IP_PROTOCOL_V4) {
1245         IP4_ADDR(&packet->dst.u_addr.ip4, 224, 0, 0, 251);
1246     }
1247 #if CONFIG_LWIP_IPV6
1248     else {
1249         esp_ip_addr_t addr = IPADDR6_INIT(0x000002ff, 0, 0, 0xfb000000);
1250         memcpy(&packet->dst, &addr, sizeof(esp_ip_addr_t));
1251     }
1252 #endif
1253     return packet;
1254 }
1255 
1256 /**
1257  * @brief  Create answer packet to questions from parsed packet
1258  */
_mdns_create_answer_from_parsed_packet(mdns_parsed_packet_t * parsed_packet)1259 static void _mdns_create_answer_from_parsed_packet(mdns_parsed_packet_t * parsed_packet)
1260 {
1261     if (!parsed_packet->questions) {
1262         return;
1263     }
1264     bool send_flush = parsed_packet->src_port == MDNS_SERVICE_PORT;
1265     bool unicast = false;
1266     bool shared = false;
1267     mdns_tx_packet_t * packet = _mdns_alloc_packet_default(parsed_packet->tcpip_if, parsed_packet->ip_protocol);
1268     if (!packet) {
1269         return;
1270     }
1271     packet->flags = MDNS_FLAGS_AUTHORITATIVE;
1272     packet->distributed = parsed_packet->distributed;
1273     packet->id = parsed_packet->id;
1274 
1275     mdns_parsed_question_t * q = parsed_packet->questions;
1276     while (q) {
1277         mdns_srv_item_t * service = NULL;
1278         if (q->service && q->proto) {
1279             service = _mdns_get_service_item(q->service, q->proto);
1280             if (!service) {
1281                 continue;
1282             }
1283         }
1284         if (q->unicast) {
1285             unicast = true;
1286         }
1287         if (service) {
1288             if (q->type == MDNS_TYPE_PTR || q->type == MDNS_TYPE_ANY) {
1289                 if (q->type == MDNS_TYPE_PTR || !parsed_packet->probe) {
1290                     shared = true;
1291                 }
1292                 if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_PTR, service->service, false, false)
1293                         || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SRV, service->service, send_flush, false)
1294                         || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_TXT, service->service, send_flush, false)
1295                         || !_mdns_alloc_answer(shared?&packet->additional:&packet->answers, MDNS_TYPE_A, NULL, send_flush, false)
1296                         || !_mdns_alloc_answer(shared?&packet->additional:&packet->answers, MDNS_TYPE_AAAA, NULL, send_flush, false)) {
1297                     _mdns_free_tx_packet(packet);
1298                     return;
1299                 }
1300             } else if (q->type == MDNS_TYPE_SRV) {
1301                 if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SRV, service->service, send_flush, false)
1302                         || !_mdns_alloc_answer(&packet->additional, MDNS_TYPE_A, NULL, send_flush, false)
1303                         || !_mdns_alloc_answer(&packet->additional, MDNS_TYPE_AAAA, NULL, send_flush, false)) {
1304                     _mdns_free_tx_packet(packet);
1305                     return;
1306                 }
1307             } else if (q->type == MDNS_TYPE_TXT) {
1308                 if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_TXT, service->service, send_flush, false)) {
1309                     _mdns_free_tx_packet(packet);
1310                     return;
1311                 }
1312             } else if (q->type == MDNS_TYPE_SDPTR) {
1313                 shared = true;
1314                 if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SDPTR, service->service, false, false)) {
1315                     _mdns_free_tx_packet(packet);
1316                     return;
1317                 }
1318             }
1319         } else {
1320             if (q->type == MDNS_TYPE_ANY || q->type == MDNS_TYPE_A || q->type == MDNS_TYPE_AAAA) {
1321                 if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_A, NULL, send_flush, false)
1322                         || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_AAAA, NULL, send_flush, false)) {
1323                     _mdns_free_tx_packet(packet);
1324                     return;
1325                 }
1326 #ifdef MDNS_REPEAT_QUERY_IN_RESPONSE
1327                 mdns_out_question_t * out_question = malloc(sizeof(mdns_out_question_t));
1328                 if (out_question == NULL) {
1329                     HOOK_MALLOC_FAILED;
1330                     _mdns_free_tx_packet(packet);
1331                     return;
1332                 }
1333                 memcpy(out_question, q, sizeof(mdns_out_question_t));
1334                 out_question->next = NULL;
1335                 queueToEnd(mdns_out_question_t, packet->questions, out_question);
1336 #endif // MDNS_REPEAT_QUERY_IN_RESPONSE
1337             } else if (!_mdns_alloc_answer(&packet->answers, q->type, NULL, send_flush, false)) {
1338                 _mdns_free_tx_packet(packet);
1339                 return;
1340             }
1341         }
1342         q = q->next;
1343     }
1344     if (unicast || !send_flush) {
1345         memcpy(&packet->dst, &parsed_packet->src, sizeof(esp_ip_addr_t));
1346         packet->port = parsed_packet->src_port;
1347     }
1348 
1349     static uint8_t share_step = 0;
1350     if (shared) {
1351         _mdns_schedule_tx_packet(packet, 25 + (share_step * 25));
1352         share_step = (share_step + 1) & 0x03;
1353     } else {
1354         _mdns_dispatch_tx_packet(packet);
1355         _mdns_free_tx_packet(packet);
1356     }
1357 }
1358 
1359 /**
1360  * @brief  Check if question is already in the list
1361  */
_mdns_question_exists(mdns_out_question_t * needle,mdns_out_question_t * haystack)1362 static bool _mdns_question_exists(mdns_out_question_t * needle, mdns_out_question_t * haystack)
1363 {
1364     while (haystack) {
1365         if (haystack->type == needle->type
1366             && haystack->host == needle->host
1367             && haystack->service == needle->service
1368             && haystack->proto == needle->proto) {
1369             return true;
1370         }
1371         haystack = haystack->next;
1372     }
1373     return false;
1374 }
1375 
1376 /**
1377  * @brief  Create probe packet for particular services on particular PCB
1378  */
_mdns_create_probe_packet(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol,mdns_srv_item_t * services[],size_t len,bool first,bool include_ip)1379 static mdns_tx_packet_t * _mdns_create_probe_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t * services[], size_t len, bool first, bool include_ip)
1380 {
1381     mdns_tx_packet_t * packet = _mdns_alloc_packet_default(tcpip_if, ip_protocol);
1382     if (!packet) {
1383         return NULL;
1384     }
1385 
1386     size_t i;
1387     for (i=0; i<len; i++) {
1388         mdns_out_question_t * q = (mdns_out_question_t *)malloc(sizeof(mdns_out_question_t));
1389         if (!q) {
1390             HOOK_MALLOC_FAILED;
1391             _mdns_free_tx_packet(packet);
1392             return NULL;
1393         }
1394         q->next = NULL;
1395         q->unicast = first;
1396         q->type = MDNS_TYPE_ANY;
1397         q->host = _mdns_get_service_instance_name(services[i]->service);
1398         q->service = services[i]->service->service;
1399         q->proto = services[i]->service->proto;
1400         q->domain = MDNS_DEFAULT_DOMAIN;
1401         if (!q->host || _mdns_question_exists(q, packet->questions)) {
1402             free(q);
1403             continue;
1404         } else {
1405             queueToEnd(mdns_out_question_t, packet->questions, q);
1406         }
1407 
1408         if (!q->host || !_mdns_alloc_answer(&packet->servers, MDNS_TYPE_SRV, services[i]->service, false, false)) {
1409             _mdns_free_tx_packet(packet);
1410             return NULL;
1411         }
1412     }
1413 
1414     if (include_ip && !_str_null_or_empty(_mdns_server->hostname)) {
1415         mdns_out_question_t * q = (mdns_out_question_t *)malloc(sizeof(mdns_out_question_t));
1416         if (!q) {
1417             HOOK_MALLOC_FAILED;
1418             _mdns_free_tx_packet(packet);
1419             return NULL;
1420         }
1421         q->next = NULL;
1422         q->unicast = first;
1423         q->type = MDNS_TYPE_ANY;
1424         q->host = _mdns_server->hostname;
1425         q->service = NULL;
1426         q->proto = NULL;
1427         q->domain = MDNS_DEFAULT_DOMAIN;
1428         if (_mdns_question_exists(q, packet->questions)) {
1429             free(q);
1430         } else {
1431             queueToEnd(mdns_out_question_t, packet->questions, q);
1432         }
1433 
1434         if (_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V4].pcb) {
1435             if (!_mdns_alloc_answer(&packet->servers, MDNS_TYPE_A, NULL, false, false)) {
1436                 _mdns_free_tx_packet(packet);
1437                 return NULL;
1438             }
1439         }
1440 
1441         if (_mdns_server->interfaces[tcpip_if].pcbs[MDNS_IP_PROTOCOL_V6].pcb) {
1442             if (!_mdns_alloc_answer(&packet->servers, MDNS_TYPE_AAAA, NULL, false, false)) {
1443                 _mdns_free_tx_packet(packet);
1444                 return NULL;
1445             }
1446         }
1447     }
1448 
1449     return packet;
1450 }
1451 
1452 /**
1453  * @brief  Create announce packet for particular services on particular PCB
1454  */
_mdns_create_announce_packet(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol,mdns_srv_item_t * services[],size_t len,bool include_ip)1455 static mdns_tx_packet_t * _mdns_create_announce_packet(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t * services[], size_t len, bool include_ip)
1456 {
1457     mdns_tx_packet_t * packet = _mdns_alloc_packet_default(tcpip_if, ip_protocol);
1458     if (!packet) {
1459         return NULL;
1460     }
1461     packet->flags = MDNS_FLAGS_AUTHORITATIVE;
1462 
1463     uint8_t i;
1464     for (i=0; i<len; i++) {
1465         if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SDPTR, services[i]->service, false, false)
1466                 || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_PTR, services[i]->service, false, false)
1467                 || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SRV, services[i]->service, true, false)
1468                 || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_TXT, services[i]->service, true, false)) {
1469             _mdns_free_tx_packet(packet);
1470             return NULL;
1471         }
1472     }
1473     if (include_ip) {
1474         if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_A, NULL, true, false)
1475                 || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_AAAA, NULL, true, false)) {
1476             _mdns_free_tx_packet(packet);
1477             return NULL;
1478         }
1479     }
1480     return packet;
1481 }
1482 
1483 /**
1484  * @brief  Convert probe packet to announce
1485  */
_mdns_create_announce_from_probe(mdns_tx_packet_t * probe)1486 static mdns_tx_packet_t * _mdns_create_announce_from_probe(mdns_tx_packet_t * probe)
1487 {
1488 
1489     mdns_tx_packet_t * packet = _mdns_alloc_packet_default(probe->tcpip_if, probe->ip_protocol);
1490     if (!packet) {
1491         return NULL;
1492     }
1493     packet->flags = MDNS_FLAGS_AUTHORITATIVE;
1494 
1495     mdns_out_answer_t * s = probe->servers;
1496     while (s) {
1497         if (s->type == MDNS_TYPE_SRV) {
1498             if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SDPTR, s->service, false, false)
1499                     || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_PTR, s->service, false, false)
1500                     || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_SRV, s->service, true, false)
1501                     || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_TXT, s->service, true, false)) {
1502                 _mdns_free_tx_packet(packet);
1503                 return NULL;
1504             }
1505 
1506         } else if (s->type == MDNS_TYPE_A || s->type == MDNS_TYPE_AAAA) {
1507             if (!_mdns_alloc_answer(&packet->answers, s->type, NULL, true, false)) {
1508                 _mdns_free_tx_packet(packet);
1509                 return NULL;
1510             }
1511         }
1512 
1513         s = s->next;
1514     }
1515     return packet;
1516 }
1517 
1518 /**
1519  * @brief  Send by for particular services on particular PCB
1520  */
_mdns_pcb_send_bye(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol,mdns_srv_item_t ** services,size_t len,bool include_ip)1521 static void _mdns_pcb_send_bye(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t ** services, size_t len, bool include_ip)
1522 {
1523     mdns_tx_packet_t * packet = _mdns_alloc_packet_default(tcpip_if, ip_protocol);
1524     if (!packet) {
1525         return;
1526     }
1527     packet->flags = MDNS_FLAGS_AUTHORITATIVE;
1528     size_t i;
1529     for (i=0; i<len; i++) {
1530         if (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_PTR, services[i]->service, true, true)) {
1531             _mdns_free_tx_packet(packet);
1532             return;
1533         }
1534     }
1535     if (include_ip && (!_mdns_alloc_answer(&packet->answers, MDNS_TYPE_A, NULL, true, true) || !_mdns_alloc_answer(&packet->answers, MDNS_TYPE_AAAA, NULL, true, true))) {
1536         _mdns_free_tx_packet(packet);
1537         return;
1538     }
1539     _mdns_dispatch_tx_packet(packet);
1540     _mdns_free_tx_packet(packet);
1541 }
1542 
1543 /**
1544  * @brief  Send probe for additional services on particular PCB
1545  */
_mdns_init_pcb_probe_new_service(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol,mdns_srv_item_t ** services,size_t len,bool probe_ip)1546 static void _mdns_init_pcb_probe_new_service(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t ** services, size_t len, bool probe_ip)
1547 {
1548     mdns_pcb_t * pcb = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol];
1549     size_t services_final_len = len;
1550 
1551     if (PCB_STATE_IS_PROBING(pcb)) {
1552         services_final_len += pcb->probe_services_len;
1553     }
1554     mdns_srv_item_t ** _services = NULL;
1555     if (services_final_len) {
1556         _services = (mdns_srv_item_t **)malloc(sizeof(mdns_srv_item_t *) * services_final_len);
1557         if (!_services) {
1558             HOOK_MALLOC_FAILED;
1559             return;
1560         }
1561 
1562         size_t i;
1563         for (i=0; i<len; i++) {
1564             _services[i] = services[i];
1565         }
1566         if (pcb->probe_services) {
1567             for (i=0; i<pcb->probe_services_len; i++) {
1568                 _services[len+i] = pcb->probe_services[i];
1569             }
1570             free(pcb->probe_services);
1571         }
1572     }
1573 
1574     probe_ip = pcb->probe_ip || probe_ip;
1575 
1576     pcb->probe_ip = false;
1577     pcb->probe_services = NULL;
1578     pcb->probe_services_len = 0;
1579     pcb->probe_running = false;
1580 
1581     mdns_tx_packet_t * packet = _mdns_create_probe_packet(tcpip_if, ip_protocol, _services, services_final_len, true, probe_ip);
1582     if (!packet) {
1583         free(_services);
1584         return;
1585     }
1586 
1587     pcb->probe_ip = probe_ip;
1588     pcb->probe_services = _services;
1589     pcb->probe_services_len = services_final_len;
1590     pcb->probe_running = true;
1591     _mdns_schedule_tx_packet(packet, ((pcb->failed_probes > 5)?1000:120) + (esp_random() & 0x7F));
1592     pcb->state = PCB_PROBE_1;
1593 }
1594 
1595 /**
1596  * @brief  Send probe for particular services on particular PCB
1597  *
1598  * Tests possible duplication on probing service structure and probes only for new entries.
1599  * - If pcb probing then add only non-probing services and restarts probing
1600  * - If pcb not probing, run probing for all specified services
1601  */
_mdns_init_pcb_probe(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol,mdns_srv_item_t ** services,size_t len,bool probe_ip)1602 static void _mdns_init_pcb_probe(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t ** services, size_t len, bool probe_ip)
1603 {
1604     mdns_pcb_t * pcb = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol];
1605 
1606     _mdns_clear_pcb_tx_queue_head(tcpip_if, ip_protocol);
1607 
1608     if (_str_null_or_empty(_mdns_server->hostname)) {
1609         pcb->state = PCB_RUNNING;
1610         return;
1611     }
1612 
1613     if (PCB_STATE_IS_PROBING(pcb)) {
1614         // Looking for already probing services to resolve duplications
1615         mdns_srv_item_t * new_probe_services[len];
1616         int new_probe_service_len = 0;
1617         bool found;
1618         for (size_t j=0; j < len; ++j) {
1619             found = false;
1620             for (int i=0; i < pcb->probe_services_len; ++i) {
1621                 if (pcb->probe_services[i] == services[j]) {
1622                     found = true;
1623                     break;
1624                 }
1625             }
1626             if (!found) {
1627                 new_probe_services[new_probe_service_len++] = services[j];
1628             }
1629         }
1630         // init probing for newly added services
1631         _mdns_init_pcb_probe_new_service(tcpip_if, ip_protocol,
1632                                          new_probe_service_len?new_probe_services:NULL, new_probe_service_len, probe_ip);
1633     } else {
1634         // not probing, so init for all services
1635         _mdns_init_pcb_probe_new_service(tcpip_if, ip_protocol, services, len, probe_ip);
1636     }
1637 }
1638 
1639 /**
1640  * @brief  Restart the responder on particular PCB
1641  */
_mdns_restart_pcb(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)1642 static void _mdns_restart_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
1643 {
1644     size_t srv_count = 0;
1645     mdns_srv_item_t * a = _mdns_server->services;
1646     while (a) {
1647         srv_count++;
1648         a = a->next;
1649     }
1650     mdns_srv_item_t * services[srv_count];
1651     size_t i = 0;
1652     a = _mdns_server->services;
1653     while (a) {
1654         services[i++] = a;
1655         a = a->next;
1656     }
1657     _mdns_init_pcb_probe(tcpip_if, ip_protocol, services, srv_count, true);
1658 }
1659 
1660 /**
1661  * @brief  Send by for particular services
1662  */
_mdns_send_bye(mdns_srv_item_t ** services,size_t len,bool include_ip)1663 static void _mdns_send_bye(mdns_srv_item_t ** services, size_t len, bool include_ip)
1664 {
1665     uint8_t i, j;
1666     if (_str_null_or_empty(_mdns_server->hostname)) {
1667         return;
1668     }
1669 
1670     for (i=0; i<MDNS_IF_MAX; i++) {
1671         for (j=0; j<MDNS_IP_PROTOCOL_MAX; j++) {
1672             if (_mdns_server->interfaces[i].pcbs[j].pcb && _mdns_server->interfaces[i].pcbs[j].state == PCB_RUNNING) {
1673                 _mdns_pcb_send_bye((mdns_if_t)i, (mdns_ip_protocol_t)j, services, len, include_ip);
1674             }
1675         }
1676     }
1677 }
1678 
1679 /**
1680  * @brief  Send announcement on particular PCB
1681  */
_mdns_announce_pcb(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol,mdns_srv_item_t ** services,size_t len,bool include_ip)1682 static void _mdns_announce_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol, mdns_srv_item_t ** services, size_t len, bool include_ip)
1683 {
1684     mdns_pcb_t * _pcb = &_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol];
1685     size_t i;
1686     if (_pcb->pcb) {
1687         if (PCB_STATE_IS_PROBING(_pcb)) {
1688             _mdns_init_pcb_probe(tcpip_if, ip_protocol, services, len, include_ip);
1689         } else if (PCB_STATE_IS_ANNOUNCING(_pcb)) {
1690             mdns_tx_packet_t *  p = _mdns_get_next_pcb_packet(tcpip_if, ip_protocol);
1691             if (p) {
1692                 for (i=0; i<len; i++) {
1693                     if (!_mdns_alloc_answer(&p->answers, MDNS_TYPE_SDPTR, services[i]->service, false, false)
1694                             || !_mdns_alloc_answer(&p->answers, MDNS_TYPE_PTR, services[i]->service, false, false)
1695                             || !_mdns_alloc_answer(&p->answers, MDNS_TYPE_SRV, services[i]->service, true, false)
1696                             || !_mdns_alloc_answer(&p->answers, MDNS_TYPE_TXT, services[i]->service, true, false)) {
1697                         break;
1698                     }
1699                 }
1700                 if (include_ip) {
1701                     _mdns_dealloc_answer(&p->additional, MDNS_TYPE_A, NULL);
1702                     _mdns_dealloc_answer(&p->additional, MDNS_TYPE_AAAA, NULL);
1703                     _mdns_alloc_answer(&p->answers, MDNS_TYPE_A, NULL, true, false);
1704                     _mdns_alloc_answer(&p->answers, MDNS_TYPE_AAAA, NULL, true, false);
1705                 }
1706                 _pcb->state = PCB_ANNOUNCE_1;
1707             }
1708         } else if (_pcb->state == PCB_RUNNING) {
1709 
1710             if (_str_null_or_empty(_mdns_server->hostname)) {
1711                 return;
1712             }
1713 
1714             _pcb->state = PCB_ANNOUNCE_1;
1715             mdns_tx_packet_t *  p = _mdns_create_announce_packet(tcpip_if, ip_protocol, services, len, include_ip);
1716             if (p) {
1717                 _mdns_schedule_tx_packet(p, 0);
1718             }
1719         }
1720     }
1721 }
1722 
1723 /**
1724  * @brief  Send probe on all active PCBs
1725  */
_mdns_probe_all_pcbs(mdns_srv_item_t ** services,size_t len,bool probe_ip,bool clear_old_probe)1726 static void _mdns_probe_all_pcbs(mdns_srv_item_t ** services, size_t len, bool probe_ip, bool clear_old_probe)
1727 {
1728     uint8_t i, j;
1729     for (i=0; i<MDNS_IF_MAX; i++) {
1730         for (j=0; j<MDNS_IP_PROTOCOL_MAX; j++) {
1731             if (_mdns_server->interfaces[i].pcbs[j].pcb) {
1732                 mdns_pcb_t * _pcb = &_mdns_server->interfaces[i].pcbs[j];
1733                 if (clear_old_probe) {
1734                     free(_pcb->probe_services);
1735                     _pcb->probe_services = NULL;
1736                     _pcb->probe_services_len = 0;
1737                     _pcb->probe_running = false;
1738                 }
1739                 _mdns_init_pcb_probe((mdns_if_t)i, (mdns_ip_protocol_t)j, services, len, probe_ip);
1740             }
1741         }
1742     }
1743 }
1744 
1745 /**
1746  * @brief  Send announcement on all active PCBs
1747  */
_mdns_announce_all_pcbs(mdns_srv_item_t ** services,size_t len,bool include_ip)1748 static void _mdns_announce_all_pcbs(mdns_srv_item_t ** services, size_t len, bool include_ip)
1749 {
1750     uint8_t i, j;
1751     for (i=0; i<MDNS_IF_MAX; i++) {
1752         for (j=0; j<MDNS_IP_PROTOCOL_MAX; j++) {
1753             _mdns_announce_pcb((mdns_if_t)i, (mdns_ip_protocol_t)j, services, len, include_ip);
1754         }
1755     }
1756 }
1757 
1758 /**
1759  * @brief  Restart the responder on all active PCBs
1760  */
_mdns_send_final_bye(bool include_ip)1761 static void _mdns_send_final_bye(bool include_ip)
1762 {
1763     //collect all services and start probe
1764     size_t srv_count = 0;
1765     mdns_srv_item_t * a = _mdns_server->services;
1766     while (a) {
1767         srv_count++;
1768         a = a->next;
1769     }
1770     if (!srv_count) {
1771         return;
1772     }
1773     mdns_srv_item_t * services[srv_count];
1774     size_t i = 0;
1775     a = _mdns_server->services;
1776     while (a) {
1777         services[i++] = a;
1778         a = a->next;
1779     }
1780     _mdns_send_bye(services, srv_count, include_ip);
1781 }
1782 
1783 /**
1784  * @brief  Stop the responder on all services without instance
1785  */
_mdns_send_bye_all_pcbs_no_instance(bool include_ip)1786 static void _mdns_send_bye_all_pcbs_no_instance(bool include_ip)
1787 {
1788     size_t srv_count = 0;
1789     mdns_srv_item_t * a = _mdns_server->services;
1790     while (a) {
1791         if (!a->service->instance) {
1792             srv_count++;
1793         }
1794         a = a->next;
1795     }
1796     if (!srv_count) {
1797         return;
1798     }
1799     mdns_srv_item_t * services[srv_count];
1800     size_t i = 0;
1801     a = _mdns_server->services;
1802     while (a) {
1803         if (!a->service->instance) {
1804             services[i++] = a;
1805         }
1806         a = a->next;
1807     }
1808     _mdns_send_bye(services, srv_count, include_ip);
1809 }
1810 
1811 /**
1812  * @brief  Restart the responder on all services without instance
1813  */
_mdns_restart_all_pcbs_no_instance(void)1814 static void _mdns_restart_all_pcbs_no_instance(void)
1815 {
1816     size_t srv_count = 0;
1817     mdns_srv_item_t * a = _mdns_server->services;
1818     while (a) {
1819         if (!a->service->instance) {
1820             srv_count++;
1821         }
1822         a = a->next;
1823     }
1824     if (!srv_count) {
1825         return;
1826     }
1827     mdns_srv_item_t * services[srv_count];
1828     size_t i = 0;
1829     a = _mdns_server->services;
1830     while (a) {
1831         if (!a->service->instance) {
1832             services[i++] = a;
1833         }
1834         a = a->next;
1835     }
1836     _mdns_probe_all_pcbs(services, srv_count, false, true);
1837 }
1838 
1839 /**
1840  * @brief  Restart the responder on all active PCBs
1841  */
_mdns_restart_all_pcbs(void)1842 static void _mdns_restart_all_pcbs(void)
1843 {
1844     _mdns_clear_tx_queue_head();
1845     size_t srv_count = 0;
1846     mdns_srv_item_t * a = _mdns_server->services;
1847     while (a) {
1848         srv_count++;
1849         a = a->next;
1850     }
1851     mdns_srv_item_t * services[srv_count];
1852     size_t l = 0;
1853     a = _mdns_server->services;
1854     while (a) {
1855         services[l++] = a;
1856         a = a->next;
1857     }
1858 
1859     _mdns_probe_all_pcbs(services, srv_count, true, true);
1860 }
1861 
1862 
1863 
1864 /**
1865  * @brief  creates/allocates new text item list
1866  * @param  num_items     service number of txt items or 0
1867  * @param  txt           service txt items array or NULL
1868  *
1869  * @return pointer to the linked txt item list or NULL
1870  */
_mdns_allocate_txt(size_t num_items,mdns_txt_item_t txt[])1871 static mdns_txt_linked_item_t * _mdns_allocate_txt(size_t num_items, mdns_txt_item_t txt[])
1872 {
1873     mdns_txt_linked_item_t * new_txt = NULL;
1874     size_t i = 0;
1875     if (num_items) {
1876         for (i=0; i<num_items; i++) {
1877             mdns_txt_linked_item_t * new_item = (mdns_txt_linked_item_t *)malloc(sizeof(mdns_txt_linked_item_t));
1878             if (!new_item) {
1879                 HOOK_MALLOC_FAILED;
1880                 break;
1881             }
1882             new_item->key = strdup(txt[i].key);
1883             if (!new_item->key) {
1884                 free(new_item);
1885                 break;
1886             }
1887             new_item->value = strdup(txt[i].value);
1888             if (!new_item->value) {
1889                 free((char *)new_item->key);
1890                 free(new_item);
1891                 break;
1892             }
1893             new_item->next = new_txt;
1894             new_txt = new_item;
1895         }
1896     }
1897     return new_txt;
1898 }
_mdns_free_linked_txt(mdns_txt_linked_item_t * txt)1899 static void _mdns_free_linked_txt(mdns_txt_linked_item_t *txt)
1900 {
1901     mdns_txt_linked_item_t *t;
1902     while (txt) {
1903         t = txt;
1904         txt = txt->next;
1905         free((char *)t->value);
1906         free((char *)t->key);
1907         free(t);
1908     }
1909 }
1910 
1911 /**
1912  * @brief  creates/allocates new service
1913  * @param  service       service type
1914  * @param  proto         service proto
1915  * @param  port          service port
1916  * @param  instance      service instance
1917  * @param  num_items     service number of txt items or 0
1918  * @param  txt           service txt items array or NULL
1919  *
1920  * @return pointer to the service or NULL on error
1921  */
_mdns_create_service(const char * service,const char * proto,uint16_t port,const char * instance,size_t num_items,mdns_txt_item_t txt[])1922 static mdns_service_t * _mdns_create_service(const char * service, const char * proto, uint16_t port, const char * instance, size_t num_items, mdns_txt_item_t txt[])
1923 {
1924     mdns_service_t * s = (mdns_service_t *)malloc(sizeof(mdns_service_t));
1925     if (!s) {
1926         HOOK_MALLOC_FAILED;
1927         return NULL;
1928     }
1929 
1930     mdns_txt_linked_item_t * new_txt = _mdns_allocate_txt(num_items, txt);
1931     if (num_items && new_txt == NULL) {
1932         free(s);
1933         return NULL;
1934     }
1935 
1936     s->priority = 0;
1937     s->weight = 0;
1938     s->instance = instance?strndup(instance, MDNS_NAME_BUF_LEN - 1):NULL;
1939     s->txt = new_txt;
1940     s->port = port;
1941 
1942     s->service = strndup(service, MDNS_NAME_BUF_LEN - 1);
1943     if (!s->service) {
1944         free(s);
1945         return NULL;
1946     }
1947 
1948     s->proto = strndup(proto, MDNS_NAME_BUF_LEN - 1);
1949     if (!s->proto) {
1950         free((char *)s->service);
1951         free(s);
1952         return NULL;
1953     }
1954 
1955     return s;
1956 }
1957 
1958 /**
1959  * @brief  Remove and free service answer from answer list (destination)
1960  */
_mdns_dealloc_scheduled_service_answers(mdns_out_answer_t ** destination,mdns_service_t * service)1961 static void _mdns_dealloc_scheduled_service_answers(mdns_out_answer_t ** destination, mdns_service_t * service)
1962 {
1963     mdns_out_answer_t * d = *destination;
1964     if (!d) {
1965         return;
1966     }
1967     while (d && d->service == service) {
1968         *destination = d->next;
1969         free(d);
1970         d = *destination;
1971     }
1972     while (d && d->next) {
1973         mdns_out_answer_t * a = d->next;
1974         if (a->service == service) {
1975             d->next = a->next;
1976             free(a);
1977         } else {
1978             d = d->next;
1979         }
1980     }
1981 }
1982 
1983 /**
1984  * @brief  Find, remove and free answers and scheduled packets for service
1985  */
_mdns_remove_scheduled_service_packets(mdns_service_t * service)1986 static void _mdns_remove_scheduled_service_packets(mdns_service_t * service)
1987 {
1988     if (!service) {
1989         return;
1990     }
1991     mdns_tx_packet_t * p = NULL;
1992     mdns_tx_packet_t * q = _mdns_server->tx_queue_head;
1993     while (q) {
1994         bool had_answers = (q->answers != NULL);
1995 
1996         _mdns_dealloc_scheduled_service_answers(&(q->answers), service);
1997         _mdns_dealloc_scheduled_service_answers(&(q->additional), service);
1998         _mdns_dealloc_scheduled_service_answers(&(q->servers), service);
1999 
2000 
2001         mdns_pcb_t * _pcb = &_mdns_server->interfaces[q->tcpip_if].pcbs[q->ip_protocol];
2002         if(_pcb->pcb) {
2003             if (PCB_STATE_IS_PROBING(_pcb)) {
2004                 uint8_t i;
2005                 //check if we are probing this service
2006                 for (i=0; i<_pcb->probe_services_len; i++) {
2007                     mdns_srv_item_t * s = _pcb->probe_services[i];
2008                     if (s->service == service){
2009                         break;
2010                     }
2011                 }
2012                 if (i < _pcb->probe_services_len) {
2013                     if (_pcb->probe_services_len > 1) {
2014                         uint8_t n;
2015                         for (n=(i+1); n<_pcb->probe_services_len; n++) {
2016                             _pcb->probe_services[n-1] = _pcb->probe_services[n];
2017                         }
2018                         _pcb->probe_services_len--;
2019                     } else {
2020                         _pcb->probe_services_len = 0;
2021                         free(_pcb->probe_services);
2022                         _pcb->probe_services = NULL;
2023                         if (!_pcb->probe_ip) {
2024                             _pcb->probe_running = false;
2025                             _pcb->state = PCB_RUNNING;
2026                         }
2027                     }
2028 
2029                     if (q->questions) {
2030                         mdns_out_question_t * qsn = NULL;
2031                         mdns_out_question_t * qs = q->questions;
2032                         if (qs->type == MDNS_TYPE_ANY
2033                             && qs->service && strcmp(qs->service, service->service) == 0
2034                             && qs->proto && strcmp(qs->proto, service->proto) == 0)
2035                         {
2036                             q->questions = q->questions->next;
2037                             free(qs);
2038                         } else while (qs->next) {
2039                             qsn = qs->next;
2040                             if (qsn->type == MDNS_TYPE_ANY
2041                                 && qsn->service && strcmp(qsn->service, service->service) == 0
2042                                 && qsn->proto && strcmp(qsn->proto, service->proto) == 0)
2043                             {
2044                                 qs->next = qsn->next;
2045                                 free(qsn);
2046                                 break;
2047                             }
2048                             qs = qs->next;
2049                         }
2050                     }
2051                 }
2052             } else if (PCB_STATE_IS_ANNOUNCING(_pcb)) {
2053                 //if answers were cleared, set to running
2054                 if (had_answers && q->answers == NULL) {
2055                     _pcb->state = PCB_RUNNING;
2056                 }
2057             }
2058         }
2059 
2060         p = q;
2061         q = q->next;
2062         if(!p->questions && !p->answers && !p->additional && !p->servers){
2063             queueDetach(mdns_tx_packet_t, _mdns_server->tx_queue_head, p);
2064             _mdns_free_tx_packet(p);
2065         }
2066     }
2067 }
2068 
2069 /**
2070  * @brief  free service memory
2071  *
2072  * @param  service      the service
2073  */
_mdns_free_service(mdns_service_t * service)2074 static void _mdns_free_service(mdns_service_t * service)
2075 {
2076     if (!service) {
2077         return;
2078     }
2079     free((char *)service->instance);
2080     free((char *)service->service);
2081     free((char *)service->proto);
2082     while (service->txt) {
2083         mdns_txt_linked_item_t * s = service->txt;
2084         service->txt = service->txt->next;
2085         free((char *)s->key);
2086         free((char *)s->value);
2087         free(s);
2088     }
2089     free(service->txt);
2090     free(service);
2091 }
2092 
2093 
2094 /*
2095  * Received Packet Handling
2096  * */
2097 
2098 /**
2099  * @brief  Detect SRV collision
2100  */
_mdns_check_srv_collision(mdns_service_t * service,uint16_t priority,uint16_t weight,uint16_t port,const char * host,const char * domain)2101 static int _mdns_check_srv_collision(mdns_service_t * service, uint16_t priority, uint16_t weight, uint16_t port, const char * host, const char * domain)
2102 {
2103     if (_str_null_or_empty(_mdns_server->hostname)) {
2104         return 0;
2105     }
2106 
2107     size_t our_host_len = strlen(_mdns_server->hostname);
2108     size_t our_len = 14 + our_host_len;
2109 
2110     size_t their_host_len = strlen(host);
2111     size_t their_domain_len = strlen(domain);
2112     size_t their_len = 9 + their_host_len + their_domain_len;
2113 
2114     if (their_len > our_len) {
2115         return 1;//they win
2116     } else if (their_len < our_len) {
2117         return -1;//we win
2118     }
2119 
2120     uint16_t our_index = 0;
2121     uint8_t our_data[our_len];
2122     _mdns_append_u16(our_data, &our_index, service->priority);
2123     _mdns_append_u16(our_data, &our_index, service->weight);
2124     _mdns_append_u16(our_data, &our_index, service->port);
2125     our_data[our_index++] = our_host_len;
2126     memcpy(our_data + our_index, _mdns_server->hostname, our_host_len);
2127     our_index += our_host_len;
2128     our_data[our_index++] = 5;
2129     memcpy(our_data + our_index, MDNS_DEFAULT_DOMAIN, 5);
2130     our_index += 5;
2131     our_data[our_index++] = 0;
2132 
2133     uint16_t their_index = 0;
2134     uint8_t their_data[their_len];
2135     _mdns_append_u16(their_data, &their_index, priority);
2136     _mdns_append_u16(their_data, &their_index, weight);
2137     _mdns_append_u16(their_data, &their_index, port);
2138     their_data[their_index++] = their_host_len;
2139     memcpy(their_data + their_index, host, their_host_len);
2140     their_index += their_host_len;
2141     their_data[their_index++] = their_domain_len;
2142     memcpy(their_data + their_index, domain, their_domain_len);
2143     their_index += their_domain_len;
2144     their_data[their_index++] = 0;
2145 
2146     int ret = memcmp(our_data, their_data, our_len);
2147     if (ret > 0) {
2148         return -1;//we win
2149     } else if (ret < 0) {
2150         return 1;//they win
2151     }
2152     return 0;//same
2153 }
2154 
2155 /**
2156  * @brief  Detect TXT collision
2157  */
_mdns_check_txt_collision(mdns_service_t * service,const uint8_t * data,size_t len)2158 static int _mdns_check_txt_collision(mdns_service_t * service, const uint8_t * data, size_t len)
2159 {
2160     size_t data_len = 0;
2161     if (len == 1 && service->txt) {
2162         return -1;//we win
2163     } else if (len > 1 && !service->txt) {
2164         return 1;//they win
2165     } else if (len == 1 && !service->txt) {
2166         return 0;//same
2167     }
2168 
2169     mdns_txt_linked_item_t * txt = service->txt;
2170     while (txt) {
2171         data_len += 2 + strlen(txt->key) + strlen(txt->value);
2172         txt = txt->next;
2173     }
2174 
2175     if (len > data_len) {
2176         return 1;//they win
2177     } else if (len < data_len) {
2178         return -1;//we win
2179     }
2180 
2181     uint8_t ours[len];
2182     uint16_t index = 0;
2183     char * tmp;
2184 
2185     txt = service->txt;
2186     while (txt) {
2187         tmp = (char *)malloc(2 + strlen(txt->key) + strlen(txt->value));
2188         if (tmp) {
2189             sprintf(tmp, "%s=%s", txt->key, txt->value);
2190             _mdns_append_string(ours, &index, tmp);
2191             free(tmp);
2192         } else {
2193             HOOK_MALLOC_FAILED;
2194             // continue
2195         }
2196         txt = txt->next;
2197     }
2198 
2199     int ret = memcmp(ours, data, len);
2200     if (ret > 0) {
2201         return -1;//we win
2202     } else if (ret < 0) {
2203         return 1;//they win
2204     }
2205     return 0;//same
2206 }
2207 
2208 /**
2209  * @brief  Set interface as duplicate if another is found on the same subnet
2210  */
_mdns_dup_interface(mdns_if_t tcpip_if)2211 static void _mdns_dup_interface(mdns_if_t tcpip_if)
2212 {
2213     uint8_t i;
2214     mdns_if_t other_if = _mdns_get_other_if (tcpip_if);
2215     for (i=0; i<MDNS_IP_PROTOCOL_MAX; i++) {
2216         if (_mdns_server->interfaces[other_if].pcbs[i].pcb) {
2217             //stop this interface and mark as dup
2218             if (_mdns_server->interfaces[tcpip_if].pcbs[i].pcb) {
2219                 _mdns_clear_pcb_tx_queue_head(tcpip_if, i);
2220                 _mdns_pcb_deinit(tcpip_if, i);
2221             }
2222             _mdns_server->interfaces[tcpip_if].pcbs[i].state = PCB_DUP;
2223             _mdns_announce_pcb(other_if, i, NULL, 0, true);
2224         }
2225     }
2226 }
2227 
2228 /**
2229  * @brief  Detect IPv4 address collision
2230  */
_mdns_check_a_collision(esp_ip4_addr_t * ip,mdns_if_t tcpip_if)2231 static int _mdns_check_a_collision(esp_ip4_addr_t * ip, mdns_if_t tcpip_if)
2232 {
2233     esp_netif_ip_info_t if_ip_info;
2234     esp_netif_ip_info_t other_ip_info;
2235     if (!ip->addr) {
2236         return 1;//denial! they win
2237     }
2238     if (esp_netif_get_ip_info(_mdns_get_esp_netif(tcpip_if), &if_ip_info)) {
2239         return 1;//they win
2240     }
2241 
2242     int ret = memcmp((uint8_t*)&if_ip_info.ip.addr, (uint8_t*)&ip->addr, sizeof(esp_ip4_addr_t));
2243     if (ret > 0) {
2244         return -1;//we win
2245     } else if (ret < 0) {
2246         //is it the other interface?
2247         mdns_if_t other_if = _mdns_get_other_if (tcpip_if);
2248         if (other_if == MDNS_IF_MAX) {
2249             return 1;//AP interface! They win
2250         }
2251         if (esp_netif_get_ip_info(_mdns_get_esp_netif(other_if), &other_ip_info)) {
2252             return 1;//IPv4 not active! They win
2253         }
2254         if (ip->addr != other_ip_info.ip.addr) {
2255             return 1;//IPv4 not ours! They win
2256         }
2257         _mdns_dup_interface(tcpip_if);
2258         return 2;//they win
2259     }
2260     return 0;//same
2261 }
2262 
2263 #if CONFIG_LWIP_IPV6
2264 /**
2265  * @brief  Detect IPv6 address collision
2266  */
_mdns_check_aaaa_collision(esp_ip6_addr_t * ip,mdns_if_t tcpip_if)2267 static int _mdns_check_aaaa_collision(esp_ip6_addr_t * ip, mdns_if_t tcpip_if)
2268 {
2269     struct esp_ip6_addr if_ip6;
2270     struct esp_ip6_addr other_ip6;
2271     if (_ipv6_address_is_zero(*ip)) {
2272         return 1;//denial! they win
2273     }
2274     if (esp_netif_get_ip6_linklocal(_mdns_get_esp_netif(tcpip_if), &if_ip6)) {
2275         return 1;//they win
2276     }
2277     int ret = memcmp((uint8_t*)&if_ip6.addr, (uint8_t*)ip->addr, _MDNS_SIZEOF_IP6_ADDR);
2278     if (ret > 0) {
2279         return -1;//we win
2280     } else if (ret < 0) {
2281         //is it the other interface?
2282         mdns_if_t other_if = _mdns_get_other_if (tcpip_if);
2283         if (other_if == MDNS_IF_MAX) {
2284             return 1;//AP interface! They win
2285         }
2286         if (esp_netif_get_ip6_linklocal(_mdns_get_esp_netif(other_if), &other_ip6)) {
2287             return 1;//IPv6 not active! They win
2288         }
2289         if (memcmp((uint8_t*)&other_ip6.addr, (uint8_t*)ip->addr, _MDNS_SIZEOF_IP6_ADDR)) {
2290             return 1;//IPv6 not ours! They win
2291         }
2292         _mdns_dup_interface(tcpip_if);
2293         return 2;//they win
2294     }
2295     return 0;//same
2296 }
2297 #endif
2298 
2299 /**
2300  * @brief  Check if parsed name is discovery
2301  */
_mdns_name_is_discovery(mdns_name_t * name,uint16_t type)2302 static bool _mdns_name_is_discovery(mdns_name_t * name, uint16_t type)
2303 {
2304     return (
2305                (name->host && name->host[0] && !strcasecmp(name->host, "_services"))
2306                && (name->service && name->service[0] && !strcasecmp(name->service, "_dns-sd"))
2307                && (name->proto && name->proto[0] && !strcasecmp(name->proto, "_udp"))
2308                && (name->domain && name->domain[0] && !strcasecmp(name->domain, MDNS_DEFAULT_DOMAIN))
2309                && type == MDNS_TYPE_PTR
2310            );
2311 }
2312 
2313 /**
2314  * @brief  Check if the parsed name is ours (matches service or host name)
2315  */
_mdns_name_is_ours(mdns_name_t * name)2316 static bool _mdns_name_is_ours(mdns_name_t * name)
2317 {
2318     //domain have to be "local"
2319     if (_str_null_or_empty(name->domain) || strcasecmp(name->domain, MDNS_DEFAULT_DOMAIN)) {
2320         return false;
2321     }
2322 
2323     //if service and proto are empty, host must match out hostname
2324     if (_str_null_or_empty(name->service) && _str_null_or_empty(name->proto)) {
2325         if (!_str_null_or_empty(name->host)
2326           && !_str_null_or_empty(_mdns_server->hostname)
2327           && strcasecmp(name->host, _mdns_server->hostname) == 0)
2328         {
2329             return true;
2330         }
2331         return false;
2332     }
2333 
2334     //if service or proto is empty, name is invalid
2335     if (_str_null_or_empty(name->service) || _str_null_or_empty(name->proto)) {
2336         return false;
2337     }
2338 
2339     //find the service
2340     mdns_srv_item_t * service = _mdns_get_service_item(name->service, name->proto);
2341     if (!service) {
2342         return false;
2343     }
2344 
2345     //if host is empty and we have service, we have success
2346     if (_str_null_or_empty(name->host)) {
2347         return true;
2348     }
2349 
2350     //OK we have host in the name. find what is the instance of the service
2351     const char * instance = _mdns_get_service_instance_name(service->service);
2352     if (instance == NULL) {
2353         return false;
2354     }
2355 
2356     //compare the instance against the name
2357     if (strcasecmp(name->host, instance) == 0) {
2358         return true;
2359     }
2360 
2361     return false;
2362 }
2363 
2364 /**
2365  * @brief  read uint16_t from a packet
2366  * @param  packet       the packet
2367  * @param  index        index in the packet where the value starts
2368  *
2369  * @return the value
2370  */
_mdns_read_u16(const uint8_t * packet,uint16_t index)2371 static inline uint16_t _mdns_read_u16(const uint8_t * packet, uint16_t index)
2372 {
2373     return (uint16_t)(packet[index]) << 8 | packet[index+1];
2374 }
2375 
2376 /**
2377  * @brief  read uint32_t from a packet
2378  * @param  packet       the packet
2379  * @param  index        index in the packet where the value starts
2380  *
2381  * @return the value
2382  */
_mdns_read_u32(const uint8_t * packet,uint16_t index)2383 static inline uint32_t _mdns_read_u32(const uint8_t * packet, uint16_t index)
2384 {
2385     return (uint32_t)(packet[index]) << 24 | (uint32_t)(packet[index+1]) << 16 | (uint32_t)(packet[index+2]) << 8 | packet[index+3];
2386 }
2387 
2388 /**
2389  * @brief  reads and formats MDNS FQDN into mdns_name_t structure
2390  *
2391  * @param  packet       MDNS packet
2392  * @param  start        Starting point of FQDN
2393  * @param  name         mdns_name_t structure to populate
2394  *
2395  * @return the address after the parsed FQDN in the packet or NULL on error
2396  */
_mdns_parse_fqdn(const uint8_t * packet,const uint8_t * start,mdns_name_t * name)2397 static const uint8_t * _mdns_parse_fqdn(const uint8_t * packet, const uint8_t * start, mdns_name_t * name)
2398 {
2399     name->parts = 0;
2400     name->sub = 0;
2401     name->host[0] = 0;
2402     name->service[0] = 0;
2403     name->proto[0] = 0;
2404     name->domain[0] = 0;
2405     name->invalid = false;
2406 
2407     static char buf[MDNS_NAME_BUF_LEN];
2408 
2409     const uint8_t * next_data = (uint8_t*)_mdns_read_fqdn(packet, start, name, buf);
2410     if (!next_data) {
2411         return 0;
2412     }
2413     if (!name->parts || name->invalid) {
2414         return next_data;
2415     }
2416     if (name->parts == 3) {
2417         memmove((uint8_t*)name + (MDNS_NAME_BUF_LEN), (uint8_t*)name, 3*(MDNS_NAME_BUF_LEN));
2418         name->host[0] = 0;
2419     } else if (name->parts == 2) {
2420         memmove((uint8_t*)(name->domain), (uint8_t*)(name->service), (MDNS_NAME_BUF_LEN));
2421         name->service[0] = 0;
2422         name->proto[0] = 0;
2423     }
2424     if (strcasecmp(name->domain, MDNS_DEFAULT_DOMAIN) == 0 || strcasecmp(name->domain, "arpa") == 0) {
2425         return next_data;
2426     }
2427     return 0;
2428 }
2429 
2430 /**
2431  * @brief  Called from parser to check if question matches particular service
2432  */
_mdns_question_matches(mdns_parsed_question_t * question,uint16_t type,mdns_srv_item_t * service)2433 static bool _mdns_question_matches(mdns_parsed_question_t * question, uint16_t type, mdns_srv_item_t * service)
2434 {
2435     if (question->type != type) {
2436         return false;
2437     }
2438     if (type == MDNS_TYPE_A || type == MDNS_TYPE_AAAA) {
2439         return true;
2440     } else if (type == MDNS_TYPE_PTR || type == MDNS_TYPE_SDPTR) {
2441         if (!strcasecmp(service->service->service, question->service)
2442             && !strcasecmp(service->service->proto, question->proto)
2443             && !strcasecmp(MDNS_DEFAULT_DOMAIN, question->domain)) {
2444             return true;
2445         }
2446     } else if (type == MDNS_TYPE_SRV || type == MDNS_TYPE_TXT) {
2447         const char * name = _mdns_get_service_instance_name(service->service);
2448         if (name && question->host && !strcasecmp(name, question->host)
2449             && !strcasecmp(service->service->service, question->service)
2450             && !strcasecmp(service->service->proto, question->proto)
2451             && !strcasecmp(MDNS_DEFAULT_DOMAIN, question->domain)) {
2452             return true;
2453         }
2454     }
2455 
2456     return false;
2457 }
2458 
2459 /**
2460  * @brief  Removes saved question from parsed data
2461  */
_mdns_remove_parsed_question(mdns_parsed_packet_t * parsed_packet,uint16_t type,mdns_srv_item_t * service)2462 static void _mdns_remove_parsed_question(mdns_parsed_packet_t * parsed_packet, uint16_t type, mdns_srv_item_t * service)
2463 {
2464     mdns_parsed_question_t * q = parsed_packet->questions;
2465 
2466     if (_mdns_question_matches(q, type, service)) {
2467         parsed_packet->questions = q->next;
2468         free(q->host);
2469         free(q->service);
2470         free(q->proto);
2471         free(q->domain);
2472         free(q);
2473         return;
2474     }
2475 
2476     while (q->next) {
2477         mdns_parsed_question_t * p = q->next;
2478         if (_mdns_question_matches(p, type, service)) {
2479             q->next = p->next;
2480             free(p->host);
2481             free(p->service);
2482             free(p->proto);
2483             free(p->domain);
2484             free(p);
2485             return;
2486         }
2487         q = q->next;
2488     }
2489 }
2490 
2491 /**
2492  * @brief  Get number of items in TXT parsed data
2493  */
_mdns_txt_items_count_get(const uint8_t * data,size_t len)2494 static int _mdns_txt_items_count_get(const uint8_t * data, size_t len)
2495 {
2496     if (len == 1) {
2497         return 0;
2498     }
2499 
2500     int num_items = 0;
2501     uint16_t i=0;
2502     size_t partLen = 0;
2503 
2504     while (i < len) {
2505         partLen = data[i++];
2506         if (!partLen) {
2507             break;
2508         }
2509         if ((i+partLen) > len) {
2510             return -1;//error
2511         }
2512         i+=partLen;
2513         num_items++;
2514     }
2515     return num_items;
2516 }
2517 
2518 /**
2519  * @brief  Get the length of TXT item's key name
2520  */
_mdns_txt_item_name_get_len(const uint8_t * data,size_t len)2521 static int _mdns_txt_item_name_get_len(const uint8_t * data, size_t len)
2522 {
2523     if (*data == '=') {
2524         return -1;
2525     }
2526     for (size_t i = 0; i < len; i++) {
2527         if (data[i] == '=') {
2528             return i;
2529         }
2530     }
2531     return len;
2532 }
2533 
2534 /**
2535  * @brief  Create TXT result array from parsed TXT data
2536  */
_mdns_result_txt_create(const uint8_t * data,size_t len,mdns_txt_item_t ** out_txt,size_t * out_count)2537 static void _mdns_result_txt_create(const uint8_t * data, size_t len, mdns_txt_item_t ** out_txt, size_t * out_count)
2538 {
2539     *out_txt = NULL;
2540     *out_count = 0;
2541     uint16_t i=0, y;
2542     size_t partLen = 0;
2543     int num_items = _mdns_txt_items_count_get(data, len);
2544     if (num_items < 0) {
2545         return;//error
2546     }
2547 
2548     if (!num_items) {
2549         return;
2550     }
2551 
2552     mdns_txt_item_t * txt = (mdns_txt_item_t *)malloc(sizeof(mdns_txt_item_t) * num_items);
2553     if (!txt) {
2554         HOOK_MALLOC_FAILED;
2555         return;
2556     }
2557     memset(txt, 0, sizeof(mdns_txt_item_t) * num_items);
2558     size_t txt_num = 0;
2559 
2560     while (i < len) {
2561         partLen = data[i++];
2562         if (!partLen) {
2563             break;
2564         }
2565 
2566         if ((i+partLen) > len) {
2567             goto handle_error;//error
2568         }
2569 
2570         int name_len = _mdns_txt_item_name_get_len(data+i, partLen);
2571         if (name_len < 0) {//invalid item (no name)
2572             i += partLen;
2573             continue;
2574         }
2575         char * key = (char *)malloc(name_len + 1);
2576         if (!key) {
2577             HOOK_MALLOC_FAILED;
2578             goto handle_error;//error
2579         }
2580 
2581         mdns_txt_item_t * t = &txt[txt_num++];
2582 
2583         memcpy(key, data + i, name_len);
2584         key[name_len] = 0;
2585         i += name_len + 1;
2586         t->key = key;
2587 
2588         int value_len = partLen - name_len - 1;
2589         if (value_len > 0) {
2590             char * value = (char *)malloc(value_len + 1);
2591             if (!value) {
2592                 HOOK_MALLOC_FAILED;
2593                 goto handle_error;//error
2594             }
2595             memcpy(value, data + i, value_len);
2596             value[value_len] = 0;
2597             i += value_len;
2598             t->value = value;
2599         }
2600     }
2601 
2602     *out_txt = txt;
2603     *out_count = txt_num;
2604     return;
2605 
2606 handle_error :
2607     for (y=0; y<txt_num; y++) {
2608         mdns_txt_item_t * t = &txt[y];
2609         free((char *)t->key);
2610         free((char *)t->value);
2611     }
2612     free(txt);
2613 }
2614 
2615 /**
2616  * @brief  Duplicate string or return error
2617  */
_mdns_strdup_check(char ** out,char * in)2618 static esp_err_t _mdns_strdup_check(char ** out, char * in)
2619 {
2620     if (in && in[0]) {
2621         *out = strdup(in);
2622         if (!*out) {
2623             return ESP_FAIL;
2624         }
2625         return ESP_OK;
2626     }
2627     *out = NULL;
2628     return ESP_OK;
2629 }
2630 
2631 /**
2632  * @brief  main packet parser
2633  *
2634  * @param  packet       the packet
2635  */
mdns_parse_packet(mdns_rx_packet_t * packet)2636 void mdns_parse_packet(mdns_rx_packet_t * packet)
2637 {
2638     static mdns_name_t n;
2639     mdns_header_t header;
2640     const uint8_t * data = (const uint8_t*)packet->pb->payload;
2641     size_t len = packet->pb->len;
2642     const uint8_t * content = data + MDNS_HEAD_LEN;
2643     bool do_not_reply = false;
2644     mdns_search_once_t * search_result = NULL;
2645 
2646 #ifdef MDNS_ENABLE_DEBUG
2647     _mdns_dbg_printf("\nRX[%u][%u]: ", packet->tcpip_if, (uint32_t)packet->ip_protocol);
2648     if (packet->src.type == IPADDR_TYPE_V4) {
2649         _mdns_dbg_printf("From: " IPSTR ":%u, To: " IPSTR ", ", IP2STR(&packet->src.u_addr.ip4), packet->src_port, IP2STR(&packet->dest.u_addr.ip4));
2650     } else {
2651         _mdns_dbg_printf("From: " IPV6STR ":%u, To: " IPV6STR ", ", IPV62STR(packet->src.u_addr.ip6), packet->src_port, IPV62STR(packet->dest.u_addr.ip6));
2652     }
2653     mdns_debug_packet(data, len);
2654 #endif
2655 
2656     mdns_parsed_packet_t * parsed_packet = (mdns_parsed_packet_t *)malloc(sizeof(mdns_parsed_packet_t));
2657     if (!parsed_packet) {
2658         HOOK_MALLOC_FAILED;
2659         return;
2660     }
2661     memset(parsed_packet, 0, sizeof(mdns_parsed_packet_t));
2662 
2663     mdns_name_t * name = &n;
2664     memset(name, 0, sizeof(mdns_name_t));
2665 
2666     header.id = _mdns_read_u16(data, MDNS_HEAD_ID_OFFSET);
2667     header.flags.value = _mdns_read_u16(data, MDNS_HEAD_FLAGS_OFFSET);
2668     header.questions = _mdns_read_u16(data, MDNS_HEAD_QUESTIONS_OFFSET);
2669     header.answers = _mdns_read_u16(data, MDNS_HEAD_ANSWERS_OFFSET);
2670     header.servers = _mdns_read_u16(data, MDNS_HEAD_SERVERS_OFFSET);
2671     header.additional = _mdns_read_u16(data, MDNS_HEAD_ADDITIONAL_OFFSET);
2672 
2673     if (header.flags.value == MDNS_FLAGS_AUTHORITATIVE && packet->src_port != MDNS_SERVICE_PORT) {
2674         free(parsed_packet);
2675         return;
2676     }
2677 
2678     //if we have not set the hostname, we can not answer questions
2679     if (header.questions && !header.answers && _str_null_or_empty(_mdns_server->hostname)) {
2680         free(parsed_packet);
2681         return;
2682     }
2683 
2684     parsed_packet->tcpip_if = packet->tcpip_if;
2685     parsed_packet->ip_protocol = packet->ip_protocol;
2686     parsed_packet->multicast = packet->multicast;
2687     parsed_packet->authoritative = header.flags.value == MDNS_FLAGS_AUTHORITATIVE;
2688     parsed_packet->distributed = header.flags.value == MDNS_FLAGS_DISTRIBUTED;
2689     parsed_packet->id = header.id;
2690 #if CONFIG_LWIP_IPV6
2691     ip_addr_copy(parsed_packet->src, packet->src);
2692 #else
2693     ip4_addr_copy(parsed_packet->src.u_addr.ip4, packet->src.u_addr.ip4);
2694 #endif
2695 
2696     parsed_packet->src_port = packet->src_port;
2697 
2698     if (header.questions) {
2699         uint8_t qs = header.questions;
2700 
2701         while (qs--) {
2702             content = _mdns_parse_fqdn(data, content, name);
2703             if (!content) {
2704                 header.answers = 0;
2705                 header.additional = 0;
2706                 header.servers = 0;
2707                 goto clear_rx_packet;//error
2708             }
2709 
2710             uint16_t type = _mdns_read_u16(content, MDNS_TYPE_OFFSET);
2711             uint16_t mdns_class = _mdns_read_u16(content, MDNS_CLASS_OFFSET);
2712             bool unicast = !!(mdns_class & 0x8000);
2713             mdns_class &= 0x7FFF;
2714             content = content + 4;
2715 
2716             if (mdns_class != 0x0001 || name->invalid) {//bad class or invalid name for this question entry
2717                 continue;
2718             }
2719 
2720             if (_mdns_name_is_discovery(name, type)) {
2721                 //service discovery
2722                 parsed_packet->discovery = true;
2723                 mdns_srv_item_t * a = _mdns_server->services;
2724                 while (a) {
2725                     mdns_parsed_question_t * question = (mdns_parsed_question_t *)calloc(1, sizeof(mdns_parsed_question_t));
2726                     if (!question) {
2727                         HOOK_MALLOC_FAILED;
2728                         goto clear_rx_packet;
2729                     }
2730                     question->next = parsed_packet->questions;
2731                     parsed_packet->questions = question;
2732 
2733                     question->unicast = unicast;
2734                     question->type = MDNS_TYPE_SDPTR;
2735                     question->host = NULL;
2736                     question->service = strdup(a->service->service);
2737                     question->proto = strdup(a->service->proto);
2738                     question->domain = strdup(MDNS_DEFAULT_DOMAIN);
2739                     if (!question->service || !question->proto || !question->domain) {
2740                         goto clear_rx_packet;
2741                     }
2742                     a = a->next;
2743                 }
2744                 continue;
2745             } else if (name->sub || !_mdns_name_is_ours(name)) {
2746                 continue;
2747             }
2748 
2749             if (type == MDNS_TYPE_ANY && !_str_null_or_empty(name->host)) {
2750                 parsed_packet->probe = true;
2751             }
2752 
2753             mdns_parsed_question_t * question = (mdns_parsed_question_t *)calloc(1, sizeof(mdns_parsed_question_t));
2754             if (!question) {
2755                 HOOK_MALLOC_FAILED;
2756                 goto clear_rx_packet;
2757             }
2758             question->next = parsed_packet->questions;
2759             parsed_packet->questions = question;
2760 
2761             question->unicast = unicast;
2762             question->type = type;
2763             if (_mdns_strdup_check(&(question->host), name->host)
2764               || _mdns_strdup_check(&(question->service), name->service)
2765               || _mdns_strdup_check(&(question->proto), name->proto)
2766               || _mdns_strdup_check(&(question->domain), name->domain)) {
2767                 goto clear_rx_packet;
2768             }
2769         }
2770     }
2771 
2772     if (header.questions && !parsed_packet->questions && !parsed_packet->discovery && !header.answers) {
2773         goto clear_rx_packet;
2774     } else if (header.answers || header.servers || header.additional) {
2775         uint16_t recordIndex = 0;
2776 
2777         while (content < (data + len)) {
2778 
2779             content = _mdns_parse_fqdn(data, content, name);
2780             if (!content) {
2781                 goto clear_rx_packet;//error
2782             }
2783 
2784             uint16_t type = _mdns_read_u16(content, MDNS_TYPE_OFFSET);
2785             uint16_t mdns_class = _mdns_read_u16(content, MDNS_CLASS_OFFSET);
2786             uint32_t ttl = _mdns_read_u32(content, MDNS_TTL_OFFSET);
2787             uint16_t data_len = _mdns_read_u16(content, MDNS_LEN_OFFSET);
2788             const uint8_t * data_ptr = content + MDNS_DATA_OFFSET;
2789             mdns_class &= 0x7FFF;
2790 
2791             content = data_ptr + data_len;
2792             if (content > (data + len)) {
2793                 goto clear_rx_packet;
2794             }
2795 
2796             bool discovery = false;
2797             bool ours = false;
2798             mdns_srv_item_t * service = NULL;
2799             mdns_parsed_record_type_t record_type = MDNS_ANSWER;
2800 
2801             if (recordIndex >= (header.answers + header.servers)) {
2802                 record_type = MDNS_EXTRA;
2803             } else if (recordIndex >= (header.answers)) {
2804                 record_type = MDNS_NS;
2805             }
2806             recordIndex++;
2807 
2808             if (type == MDNS_TYPE_NSEC || type == MDNS_TYPE_OPT) {
2809                 //skip NSEC and OPT
2810                 continue;
2811             }
2812 
2813             if (parsed_packet->discovery && _mdns_name_is_discovery(name, type)) {
2814                 discovery = true;
2815             } else if (!name->sub && _mdns_name_is_ours(name)) {
2816                 ours = true;
2817                 if (name->service && name->service[0] && name->proto && name->proto[0]) {
2818                     service = _mdns_get_service_item(name->service, name->proto);
2819                 }
2820             } else {
2821                 if (!parsed_packet->authoritative || record_type == MDNS_NS) {
2822                     //skip this record
2823                     continue;
2824                 }
2825                 search_result = _mdns_search_find_from(_mdns_server->search_once, name, type, packet->tcpip_if, packet->ip_protocol);
2826             }
2827 
2828             if (type == MDNS_TYPE_PTR) {
2829                 if (!_mdns_parse_fqdn(data, data_ptr, name)) {
2830                     continue;//error
2831                 }
2832                 if (search_result) {
2833                     _mdns_search_result_add_ptr(search_result, name->host, packet->tcpip_if, packet->ip_protocol);
2834                 } else if ((discovery || ours) && !name->sub && _mdns_name_is_ours(name)) {
2835                     if (discovery) {
2836                         service = _mdns_get_service_item(name->service, name->proto);
2837                         _mdns_remove_parsed_question(parsed_packet, MDNS_TYPE_SDPTR, service);
2838                     } else if (parsed_packet->questions && !parsed_packet->probe) {
2839                         _mdns_remove_parsed_question(parsed_packet, type, service);
2840                     } else {
2841                         //check if TTL is more than half of the full TTL value (4500)
2842                         if (ttl > 2250) {
2843                             _mdns_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service);
2844                         }
2845                     }
2846                 }
2847             } else if (type == MDNS_TYPE_SRV) {
2848                 mdns_result_t * result = NULL;
2849                 if (search_result && search_result->type == MDNS_TYPE_PTR) {
2850                     result = search_result->result;
2851                     while (result) {
2852                         if (packet->tcpip_if == result->tcpip_if
2853                             && packet->ip_protocol == result->ip_protocol
2854                             && result->instance_name && !strcmp(name->host, result->instance_name)) {
2855                             break;
2856                         }
2857                         result = result->next;
2858                     }
2859                     if (!result) {
2860                         result = _mdns_search_result_add_ptr(search_result, name->host, packet->tcpip_if, packet->ip_protocol);
2861                         if (!result) {
2862                             continue;//error
2863                         }
2864                     }
2865                 }
2866 
2867                 if (!_mdns_parse_fqdn(data, data_ptr + MDNS_SRV_FQDN_OFFSET, name)) {
2868                     continue;//error
2869                 }
2870                 uint16_t priority = _mdns_read_u16(data_ptr, MDNS_SRV_PRIORITY_OFFSET);
2871                 uint16_t weight = _mdns_read_u16(data_ptr, MDNS_SRV_WEIGHT_OFFSET);
2872                 uint16_t port = _mdns_read_u16(data_ptr, MDNS_SRV_PORT_OFFSET);
2873 
2874                 if (search_result) {
2875                     if (search_result->type == MDNS_TYPE_PTR) {
2876                         if (!result->hostname) { // assign host/port for this entry only if not previously set
2877                             result->port = port;
2878                             result->hostname = strdup(name->host);
2879                         }
2880                     } else {
2881                         _mdns_search_result_add_srv(search_result, name->host, port, packet->tcpip_if, packet->ip_protocol);
2882                     }
2883                 } else if (ours) {
2884                     if (parsed_packet->questions && !parsed_packet->probe) {
2885                         _mdns_remove_parsed_question(parsed_packet, type, service);
2886                         continue;
2887                     } else if (parsed_packet->distributed) {
2888                         _mdns_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service);
2889                         continue;
2890                     }
2891                     //detect collision (-1=won, 0=none, 1=lost)
2892                     int col = 0;
2893                     if (mdns_class > 1) {
2894                         col = 1;
2895                     } else if (!mdns_class) {
2896                         col = -1;
2897                     } else if (service) { // only detect srv collision if service existed
2898                         col = _mdns_check_srv_collision(service->service, priority, weight, port, name->host, name->domain);
2899                     }
2900                     if (col && (parsed_packet->probe || parsed_packet->authoritative)) {
2901                         if (col > 0 || !port) {
2902                             do_not_reply = true;
2903                             if (_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) {
2904                                 _mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].failed_probes++;
2905                                 if (!_str_null_or_empty(service->service->instance)) {
2906                                     char * new_instance = _mdns_mangle_name((char *)service->service->instance);
2907                                     if (new_instance) {
2908                                         free((char *)service->service->instance);
2909                                         service->service->instance = new_instance;
2910                                     }
2911                                     _mdns_probe_all_pcbs(&service, 1, false, false);
2912                                 } else if (!_str_null_or_empty(_mdns_server->instance)) {
2913                                     char * new_instance = _mdns_mangle_name((char *)_mdns_server->instance);
2914                                     if (new_instance) {
2915                                         free((char *)_mdns_server->instance);
2916                                         _mdns_server->instance = new_instance;
2917                                     }
2918                                     _mdns_restart_all_pcbs_no_instance();
2919                                 } else {
2920                                     char * new_host = _mdns_mangle_name((char *)_mdns_server->hostname);
2921                                     if (new_host) {
2922                                         free((char *)_mdns_server->hostname);
2923                                         _mdns_server->hostname = new_host;
2924                                     }
2925                                     _mdns_restart_all_pcbs();
2926                                 }
2927                             } else {
2928                                 _mdns_pcb_send_bye(packet->tcpip_if, packet->ip_protocol, &service, 1, false);
2929                                 _mdns_init_pcb_probe(packet->tcpip_if, packet->ip_protocol, &service, 1, false);
2930                             }
2931                         }
2932                     } else if (ttl > 60 && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions) {
2933                         _mdns_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service);
2934                     }
2935                 }
2936             } else if (type == MDNS_TYPE_TXT) {
2937                 if (search_result) {
2938                     mdns_txt_item_t * txt = NULL;
2939                     size_t txt_count = 0;
2940 
2941                     mdns_result_t * result = NULL;
2942                     if (search_result->type == MDNS_TYPE_PTR) {
2943                         result = search_result->result;
2944                         while (result) {
2945                             if (packet->tcpip_if == result->tcpip_if
2946                                 && packet->ip_protocol == result->ip_protocol
2947                                 && result->instance_name && !strcmp(name->host, result->instance_name)) {
2948                                 break;
2949                             }
2950                             result = result->next;
2951                         }
2952                         if (!result) {
2953                             result = _mdns_search_result_add_ptr(search_result, name->host, packet->tcpip_if, packet->ip_protocol);
2954                             if (!result) {
2955                                 continue;//error
2956                             }
2957                         }
2958                         if (!result->txt) {
2959                             _mdns_result_txt_create(data_ptr, data_len, &txt, &txt_count);
2960                             if (txt_count) {
2961                                 result->txt = txt;
2962                                 result->txt_count = txt_count;
2963                             }
2964                         }
2965                     } else {
2966                         _mdns_result_txt_create(data_ptr, data_len, &txt, &txt_count);
2967                         if (txt_count) {
2968                             _mdns_search_result_add_txt(search_result, txt, txt_count, packet->tcpip_if, packet->ip_protocol);
2969                         }
2970                     }
2971                 } else if (ours) {
2972                     if (parsed_packet->questions && !parsed_packet->probe) {
2973                         _mdns_remove_parsed_question(parsed_packet, type, service);
2974                         continue;
2975                     }
2976                     //detect collision (-1=won, 0=none, 1=lost)
2977                     int col = 0;
2978                     if (mdns_class > 1) {
2979                         col = 1;
2980                     } else if (!mdns_class) {
2981                         col = -1;
2982                     } else if (service) { // only detect txt collision if service existed
2983                         col = _mdns_check_txt_collision(service->service, data_ptr, data_len);
2984                     }
2985                     if (col && !_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) {
2986                         do_not_reply = true;
2987                         _mdns_init_pcb_probe(packet->tcpip_if, packet->ip_protocol, &service, 1, true);
2988                     } else if (ttl > 2250 && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions && !_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) {
2989                         _mdns_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, service);
2990                     }
2991                 }
2992 
2993             }
2994 #if CONFIG_LWIP_IPV6
2995             else if (type == MDNS_TYPE_AAAA) {//ipv6
2996                 esp_ip_addr_t ip6;
2997                 ip6.type = IPADDR_TYPE_V6;
2998                 memcpy(ip6.u_addr.ip6.addr, data_ptr, MDNS_ANSWER_AAAA_SIZE);
2999                 if (search_result) {
3000                     //check for more applicable searches (PTR & A/AAAA at the same time)
3001                     while (search_result) {
3002                         _mdns_search_result_add_ip(search_result, name->host, &ip6, packet->tcpip_if, packet->ip_protocol);
3003                         search_result = _mdns_search_find_from(search_result->next, name, type, packet->tcpip_if, packet->ip_protocol);
3004                     }
3005                 } else if (ours) {
3006                     if (parsed_packet->questions && !parsed_packet->probe) {
3007                         _mdns_remove_parsed_question(parsed_packet, type, NULL);
3008                         continue;
3009                     }
3010                     //detect collision (-1=won, 0=none, 1=lost)
3011                     int col = 0;
3012                     if (mdns_class > 1) {
3013                         col = 1;
3014                     } else if (!mdns_class) {
3015                         col = -1;
3016                     } else {
3017                         col = _mdns_check_aaaa_collision(&(ip6.u_addr.ip6), packet->tcpip_if);
3018                     }
3019                     if (col == 2) {
3020                         goto clear_rx_packet;
3021                     } else if (col == 1) {
3022                         do_not_reply = true;
3023                         if (_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) {
3024                             if (col && (parsed_packet->probe || parsed_packet->authoritative)) {
3025                                 _mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].failed_probes++;
3026                                 char * new_host = _mdns_mangle_name((char *)_mdns_server->hostname);
3027                                 if (new_host) {
3028                                     free((char *)_mdns_server->hostname);
3029                                     _mdns_server->hostname = new_host;
3030                                 }
3031                                 _mdns_restart_all_pcbs();
3032                             }
3033                         } else {
3034                             _mdns_init_pcb_probe(packet->tcpip_if, packet->ip_protocol, NULL, 0, true);
3035                         }
3036                     } else if (ttl > 60 && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions && !_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) {
3037                         _mdns_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, NULL);
3038                     }
3039                 }
3040 
3041             }
3042 #endif
3043             else if (type == MDNS_TYPE_A) {
3044                 esp_ip_addr_t ip;
3045                 ip.type = IPADDR_TYPE_V4;
3046                 memcpy(&(ip.u_addr.ip4.addr), data_ptr, 4);
3047                 if (search_result) {
3048                     //check for more applicable searches (PTR & A/AAAA at the same time)
3049                     while (search_result) {
3050                         _mdns_search_result_add_ip(search_result, name->host, &ip, packet->tcpip_if, packet->ip_protocol);
3051                         search_result = _mdns_search_find_from(search_result->next, name, type, packet->tcpip_if, packet->ip_protocol);
3052                     }
3053                 } else if (ours) {
3054                     if (parsed_packet->questions && !parsed_packet->probe) {
3055                         _mdns_remove_parsed_question(parsed_packet, type, NULL);
3056                         continue;
3057                     }
3058                     //detect collision (-1=won, 0=none, 1=lost)
3059                     int col = 0;
3060                     if (mdns_class > 1) {
3061                         col = 1;
3062                     } else if (!mdns_class) {
3063                         col = -1;
3064                     } else {
3065                         col = _mdns_check_a_collision(&(ip.u_addr.ip4), packet->tcpip_if);
3066                     }
3067                     if (col == 2) {
3068                         goto clear_rx_packet;
3069                     } else if (col == 1) {
3070                         do_not_reply = true;
3071                         if (_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) {
3072                             if (col && (parsed_packet->probe || parsed_packet->authoritative)) {
3073                                 _mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].failed_probes++;
3074                                 char * new_host = _mdns_mangle_name((char *)_mdns_server->hostname);
3075                                 if (new_host) {
3076                                     free((char *)_mdns_server->hostname);
3077                                     _mdns_server->hostname = new_host;
3078                                 }
3079                                 _mdns_restart_all_pcbs();
3080                             }
3081                         } else {
3082                             _mdns_init_pcb_probe(packet->tcpip_if, packet->ip_protocol, NULL, 0, true);
3083                         }
3084                     } else if (ttl > 60 && !col && !parsed_packet->authoritative && !parsed_packet->probe && !parsed_packet->questions && !_mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].probe_running) {
3085                         _mdns_remove_scheduled_answer(packet->tcpip_if, packet->ip_protocol, type, NULL);
3086                     }
3087                 }
3088 
3089             }
3090         }
3091         //end while
3092         if (parsed_packet->authoritative) {
3093             _mdns_search_finish_done();
3094         }
3095     }
3096 
3097     if (!do_not_reply && _mdns_server->interfaces[packet->tcpip_if].pcbs[packet->ip_protocol].state > PCB_PROBE_3 && (parsed_packet->questions || parsed_packet->discovery)) {
3098         _mdns_create_answer_from_parsed_packet(parsed_packet);
3099     }
3100 
3101 
3102 clear_rx_packet:
3103     while (parsed_packet->questions) {
3104         mdns_parsed_question_t * question = parsed_packet->questions;
3105         parsed_packet->questions = parsed_packet->questions->next;
3106         free(question->host);
3107         free(question->service);
3108         free(question->proto);
3109         free(question->domain);
3110         free(question);
3111     }
3112     free(parsed_packet);
3113 }
3114 
3115 /**
3116  * @brief  Enable mDNS interface
3117  */
_mdns_enable_pcb(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3118 void _mdns_enable_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3119 {
3120     if (!_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb) {
3121         if (_mdns_pcb_init(tcpip_if, ip_protocol)) {
3122             return;
3123         }
3124     }
3125     _mdns_restart_pcb(tcpip_if, ip_protocol);
3126 }
3127 
3128 /**
3129  * @brief  Disable mDNS interface
3130  */
_mdns_disable_pcb(mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3131 void _mdns_disable_pcb(mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3132 {
3133     if (_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb) {
3134         _mdns_clear_pcb_tx_queue_head(tcpip_if, ip_protocol);
3135         _mdns_pcb_deinit(tcpip_if, ip_protocol);
3136         mdns_if_t other_if = _mdns_get_other_if (tcpip_if);
3137         if (other_if != MDNS_IF_MAX && _mdns_server->interfaces[other_if].pcbs[ip_protocol].state == PCB_DUP) {
3138             _mdns_server->interfaces[other_if].pcbs[ip_protocol].state = PCB_OFF;
3139             _mdns_enable_pcb(other_if, ip_protocol);
3140         }
3141     }
3142     _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].state = PCB_OFF;
3143 }
3144 
3145 /**
3146  * @brief  Dispatch interface changes based on system events
3147  */
_mdns_handle_system_event(esp_event_base_t event_base,int32_t event_id,esp_netif_t * interface)3148 static void _mdns_handle_system_event(esp_event_base_t event_base,
3149                                       int32_t event_id, esp_netif_t* interface)
3150 {
3151     if (!_mdns_server) {
3152         return;
3153     }
3154 
3155     esp_netif_dhcp_status_t dcst;
3156     if (event_base == WIFI_EVENT) {
3157         switch(event_id) {
3158             case WIFI_EVENT_STA_CONNECTED:
3159                 if (!esp_netif_dhcpc_get_status(_mdns_get_esp_netif(MDNS_IF_STA), &dcst)) {
3160                     if (dcst == ESP_NETIF_DHCP_STOPPED) {
3161                         _mdns_enable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4);
3162                     }
3163                 }
3164                 break;
3165             case WIFI_EVENT_STA_DISCONNECTED:
3166                 _mdns_disable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4);
3167                 _mdns_disable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V6);
3168                 break;
3169             case WIFI_EVENT_AP_START:
3170                 _mdns_enable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V4);
3171                 break;
3172             case WIFI_EVENT_AP_STOP:
3173                 _mdns_disable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V4);
3174                 _mdns_disable_pcb(MDNS_IF_AP, MDNS_IP_PROTOCOL_V6);
3175                 break;
3176             default:
3177                 break;
3178         }
3179     }
3180 #if CONFIG_ETH_ENABLED
3181     else if (event_base == ETH_EVENT) {
3182         switch (event_id) {
3183             case ETHERNET_EVENT_CONNECTED:
3184                 if (!esp_netif_dhcpc_get_status(_mdns_get_esp_netif(MDNS_IF_ETH), &dcst)) {
3185                     if (dcst == ESP_NETIF_DHCP_STOPPED) {
3186                         _mdns_enable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4);
3187                     }
3188                 }
3189                 break;
3190             case ETHERNET_EVENT_DISCONNECTED:
3191                 _mdns_disable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4);
3192                 _mdns_disable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V6);
3193                 break;
3194             default:
3195                 break;
3196         }
3197     }
3198 #endif
3199     else if (event_base == IP_EVENT) {
3200         switch (event_id) {
3201             case IP_EVENT_STA_GOT_IP:
3202                 _mdns_enable_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V4);
3203                 _mdns_announce_pcb(MDNS_IF_STA, MDNS_IP_PROTOCOL_V6, NULL, 0, true);
3204                 break;
3205 #if CONFIG_ETH_ENABLED
3206             case IP_EVENT_ETH_GOT_IP:
3207                 _mdns_enable_pcb(MDNS_IF_ETH, MDNS_IP_PROTOCOL_V4);
3208                 break;
3209 #endif
3210             case IP_EVENT_GOT_IP6:
3211             {
3212                 mdns_if_t mdns_if = _mdns_get_if_from_esp_netif(interface);
3213                 if (mdns_if != MDNS_IF_MAX) {
3214                     _mdns_enable_pcb(mdns_if, MDNS_IP_PROTOCOL_V6);
3215                     _mdns_announce_pcb(mdns_if, MDNS_IP_PROTOCOL_V4, NULL, 0, true);
3216                 }
3217 
3218             }
3219                 break;
3220             default:
3221                 break;
3222         }
3223     }
3224 }
3225 
3226 /*
3227  * MDNS Search
3228  * */
3229 
3230 /**
3231  * @brief  Free search structure (except the results)
3232  */
_mdns_search_free(mdns_search_once_t * search)3233 static void _mdns_search_free(mdns_search_once_t * search)
3234 {
3235     free(search->instance);
3236     free(search->service);
3237     free(search->proto);
3238     vSemaphoreDelete(search->done_semaphore);
3239     free(search);
3240 }
3241 
3242 /**
3243  * @brief  Allocate new search structure
3244  */
_mdns_search_init(const char * name,const char * service,const char * proto,uint16_t type,uint32_t timeout,uint8_t max_results)3245 static mdns_search_once_t * _mdns_search_init(const char * name, const char * service, const char * proto, uint16_t type, uint32_t timeout, uint8_t max_results)
3246 {
3247     mdns_search_once_t * search = (mdns_search_once_t *)malloc(sizeof(mdns_search_once_t));
3248     if (!search) {
3249         HOOK_MALLOC_FAILED;
3250         return NULL;
3251     }
3252     memset(search, 0, sizeof(mdns_search_once_t));
3253 
3254     search->done_semaphore = xSemaphoreCreateBinary();
3255     if (!search->done_semaphore) {
3256         free(search);
3257         return NULL;
3258     }
3259 
3260     if (!_str_null_or_empty(name)) {
3261         search->instance = strndup(name, MDNS_NAME_BUF_LEN-1);
3262         if (!search->instance) {
3263             _mdns_search_free(search);
3264             return NULL;
3265         }
3266     }
3267 
3268     if (!_str_null_or_empty(service)) {
3269         search->service = strndup(service, MDNS_NAME_BUF_LEN-1);
3270         if (!search->service) {
3271             _mdns_search_free(search);
3272             return NULL;
3273         }
3274     }
3275 
3276     if (!_str_null_or_empty(proto)) {
3277         search->proto = strndup(proto, MDNS_NAME_BUF_LEN-1);
3278         if (!search->proto) {
3279             _mdns_search_free(search);
3280             return NULL;
3281         }
3282     }
3283 
3284     search->type = type;
3285     search->timeout = timeout;
3286     search->num_results = 0;
3287     search->max_results = max_results;
3288     search->result = NULL;
3289     search->state = SEARCH_INIT;
3290     search->sent_at = 0;
3291     search->started_at = xTaskGetTickCount() * portTICK_PERIOD_MS;
3292     search->next = NULL;
3293 
3294     return search;
3295 }
3296 
3297 /**
3298  * @brief  Mark search as finished and remove it from search chain
3299  */
_mdns_search_finish(mdns_search_once_t * search)3300 static void _mdns_search_finish(mdns_search_once_t * search)
3301 {
3302     search->state = SEARCH_OFF;
3303     queueDetach(mdns_search_once_t, _mdns_server->search_once, search);
3304     xSemaphoreGive(search->done_semaphore);
3305 }
3306 
3307 /**
3308  * @brief  Add new search to the search chain
3309  */
_mdns_search_add(mdns_search_once_t * search)3310 static void _mdns_search_add(mdns_search_once_t * search)
3311 {
3312     search->next = _mdns_server->search_once;
3313     _mdns_server->search_once = search;
3314 }
3315 
3316 /**
3317  * @brief  Called from parser to finish any searches that have reached maximum results
3318  */
_mdns_search_finish_done(void)3319 static void _mdns_search_finish_done(void)
3320 {
3321     mdns_search_once_t * search = _mdns_server->search_once;
3322     mdns_search_once_t * s = NULL;
3323     while (search) {
3324         s = search;
3325         search = search->next;
3326         if (s->max_results && s->num_results >= s->max_results) {
3327             _mdns_search_finish(s);
3328         }
3329     }
3330 }
3331 
3332 /**
3333  * @brief  Create linked IP (copy) from parsed one
3334  */
_mdns_result_addr_create_ip(esp_ip_addr_t * ip)3335 static mdns_ip_addr_t * _mdns_result_addr_create_ip(esp_ip_addr_t * ip)
3336 {
3337     mdns_ip_addr_t * a = (mdns_ip_addr_t *)malloc(sizeof(mdns_ip_addr_t));
3338     if (!a) {
3339         HOOK_MALLOC_FAILED;
3340         return NULL;
3341     }
3342     memset(a, 0 , sizeof(mdns_ip_addr_t));
3343     a->addr.type = ip->type;
3344     if (ip->type == IPADDR_TYPE_V6) {
3345         memcpy(a->addr.u_addr.ip6.addr, ip->u_addr.ip6.addr, 16);
3346     } else {
3347         a->addr.u_addr.ip4.addr = ip->u_addr.ip4.addr;
3348     }
3349     return a;
3350 }
3351 
3352 /**
3353  * @brief  Chain new IP to search result
3354  */
_mdns_result_add_ip(mdns_result_t * r,esp_ip_addr_t * ip)3355 static void _mdns_result_add_ip(mdns_result_t * r, esp_ip_addr_t * ip)
3356 {
3357     mdns_ip_addr_t * a = r->addr;
3358     while (a) {
3359         if (a->addr.type == ip->type) {
3360             if (a->addr.type == IPADDR_TYPE_V4 && a->addr.u_addr.ip4.addr == ip->u_addr.ip4.addr) {
3361                 return;
3362             }
3363             if (a->addr.type == IPADDR_TYPE_V6 && !memcmp(a->addr.u_addr.ip6.addr, ip->u_addr.ip6.addr, 16)) {
3364                 return;
3365             }
3366         }
3367         a = a->next;
3368     }
3369     a = _mdns_result_addr_create_ip(ip);
3370     if (!a) {
3371         return;
3372     }
3373     a->next = r->addr;
3374     r->addr = a;
3375 }
3376 
3377 /**
3378  * @brief  Called from parser to add A/AAAA data to search result
3379  */
_mdns_search_result_add_ip(mdns_search_once_t * search,const char * hostname,esp_ip_addr_t * ip,mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3380 static void _mdns_search_result_add_ip(mdns_search_once_t * search, const char * hostname, esp_ip_addr_t * ip, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3381 {
3382     mdns_result_t * r = NULL;
3383     mdns_ip_addr_t * a = NULL;
3384 
3385     if ((search->type == MDNS_TYPE_A && ip->type == IPADDR_TYPE_V4)
3386       || (search->type == MDNS_TYPE_AAAA && ip->type == IPADDR_TYPE_V6)
3387       || search->type == MDNS_TYPE_ANY) {
3388         r = search->result;
3389         while (r) {
3390             if (r->tcpip_if == tcpip_if && r->ip_protocol == ip_protocol) {
3391                 _mdns_result_add_ip(r, ip);
3392                 return;
3393             }
3394             r = r->next;
3395         }
3396         if (!search->max_results || search->num_results < search->max_results) {
3397             r = (mdns_result_t *)malloc(sizeof(mdns_result_t));
3398             if (!r) {
3399                 HOOK_MALLOC_FAILED;
3400                 return;
3401             }
3402 
3403             memset(r, 0 , sizeof(mdns_result_t));
3404 
3405             a = _mdns_result_addr_create_ip(ip);
3406             if (!a) {
3407                 free(r);
3408                 return;
3409             }
3410             a->next = r->addr;
3411             r->addr = a;
3412             r->tcpip_if = tcpip_if;
3413             r->ip_protocol = ip_protocol;
3414             r->next = search->result;
3415             search->result = r;
3416             search->num_results++;
3417         }
3418     } else if (search->type == MDNS_TYPE_PTR) {
3419         r = search->result;
3420         while (r) {
3421             if (r->tcpip_if == tcpip_if && r->ip_protocol == ip_protocol && !_str_null_or_empty(r->hostname) && !strcasecmp(hostname, r->hostname)) {
3422                 _mdns_result_add_ip(r, ip);
3423                 break;
3424             }
3425             r = r->next;
3426         }
3427     }
3428 }
3429 
3430 /**
3431  * @brief  Called from parser to add PTR data to search result
3432  */
_mdns_search_result_add_ptr(mdns_search_once_t * search,const char * instance,mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3433 static mdns_result_t * _mdns_search_result_add_ptr(mdns_search_once_t * search, const char * instance, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3434 {
3435     mdns_result_t * r = search->result;
3436     while (r) {
3437         if (r->tcpip_if == tcpip_if && r->ip_protocol == ip_protocol && !_str_null_or_empty(r->instance_name) && !strcasecmp(instance, r->instance_name)) {
3438             return r;
3439         }
3440         r = r->next;
3441     }
3442     if (!search->max_results || search->num_results < search->max_results) {
3443         r = (mdns_result_t *)malloc(sizeof(mdns_result_t));
3444         if (!r) {
3445             HOOK_MALLOC_FAILED;
3446             return NULL;
3447         }
3448 
3449         memset(r, 0 , sizeof(mdns_result_t));
3450         r->instance_name = strdup(instance);
3451         if (!r->instance_name) {
3452             free(r);
3453             return NULL;
3454         }
3455 
3456         r->tcpip_if = tcpip_if;
3457         r->ip_protocol = ip_protocol;
3458         r->next = search->result;
3459         search->result = r;
3460         search->num_results++;
3461         return r;
3462     }
3463     return NULL;
3464 }
3465 
3466 /**
3467  * @brief  Called from parser to add SRV data to search result
3468  */
_mdns_search_result_add_srv(mdns_search_once_t * search,const char * hostname,uint16_t port,mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3469 static void _mdns_search_result_add_srv(mdns_search_once_t * search, const char * hostname, uint16_t port, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3470 {
3471     mdns_result_t * r = search->result;
3472     while (r) {
3473         if (r->tcpip_if == tcpip_if && r->ip_protocol == ip_protocol && !_str_null_or_empty(r->hostname) && !strcasecmp(hostname, r->hostname)) {
3474             return;
3475         }
3476         r = r->next;
3477     }
3478     if (!search->max_results || search->num_results < search->max_results) {
3479         r = (mdns_result_t *)malloc(sizeof(mdns_result_t));
3480         if (!r) {
3481             HOOK_MALLOC_FAILED;
3482             return;
3483         }
3484 
3485         memset(r, 0 , sizeof(mdns_result_t));
3486         r->hostname = strdup(hostname);
3487         if (!r->hostname) {
3488             free(r);
3489             return;
3490         }
3491         r->port = port;
3492         r->tcpip_if = tcpip_if;
3493         r->ip_protocol = ip_protocol;
3494         r->next = search->result;
3495         search->result = r;
3496         search->num_results++;
3497     }
3498 }
3499 
3500 /**
3501  * @brief  Called from parser to add TXT data to search result
3502  */
_mdns_search_result_add_txt(mdns_search_once_t * search,mdns_txt_item_t * txt,size_t txt_count,mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3503 static void _mdns_search_result_add_txt(mdns_search_once_t * search, mdns_txt_item_t * txt, size_t txt_count, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3504 {
3505     mdns_result_t * r = search->result;
3506     while (r) {
3507         if (r->tcpip_if == tcpip_if && r->ip_protocol == ip_protocol) {
3508             if (r->txt) {
3509                 goto free_txt;
3510             }
3511             r->txt = txt;
3512             r->txt_count = txt_count;
3513             return;
3514         }
3515         r = r->next;
3516     }
3517     if (!search->max_results || search->num_results < search->max_results) {
3518         r = (mdns_result_t *)malloc(sizeof(mdns_result_t));
3519         if (!r) {
3520             HOOK_MALLOC_FAILED;
3521             goto free_txt;
3522         }
3523 
3524         memset(r, 0 , sizeof(mdns_result_t));
3525         r->txt = txt;
3526         r->txt_count = txt_count;
3527         r->tcpip_if = tcpip_if;
3528         r->ip_protocol = ip_protocol;
3529         r->next = search->result;
3530         search->result = r;
3531         search->num_results++;
3532     }
3533     return;
3534 
3535 free_txt:
3536     for (size_t i=0; i<txt_count; i++) {
3537         free((char *)(txt[i].key));
3538         free((char *)(txt[i].value));
3539     }
3540     free(txt);
3541 }
3542 
3543 /**
3544  * @brief  Called from packet parser to find matching running search
3545  */
_mdns_search_find_from(mdns_search_once_t * s,mdns_name_t * name,uint16_t type,mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3546 static mdns_search_once_t * _mdns_search_find_from(mdns_search_once_t * s, mdns_name_t * name, uint16_t type, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3547 {
3548     mdns_result_t * r = NULL;
3549     while (s) {
3550         if (s->state == SEARCH_OFF) {
3551             s = s->next;
3552             continue;
3553         }
3554 
3555         if (type == MDNS_TYPE_A || type == MDNS_TYPE_AAAA) {
3556             if ((s->type == MDNS_TYPE_ANY && s->service != NULL)
3557                 || (s->type != MDNS_TYPE_ANY && s->type != type && s->type != MDNS_TYPE_PTR))
3558             {
3559                 s = s->next;
3560                 continue;
3561             }
3562             if (s->type != MDNS_TYPE_PTR) {
3563                 if (!strcasecmp(name->host, s->instance)) {
3564                     return s;
3565                 }
3566                 s = s->next;
3567                 continue;
3568             }
3569             r = s->result;
3570             while (r) {
3571                 if (r->tcpip_if == tcpip_if && r->ip_protocol == ip_protocol && !_str_null_or_empty(r->hostname) && !strcasecmp(name->host, r->hostname)) {
3572                     return s;
3573                 }
3574                 r = r->next;
3575             }
3576             s = s->next;
3577             continue;
3578         }
3579 
3580         if (type == MDNS_TYPE_SRV || type == MDNS_TYPE_TXT) {
3581             if ((s->type == MDNS_TYPE_ANY && s->service == NULL)
3582                 || (s->type != MDNS_TYPE_ANY && s->type != type && s->type != MDNS_TYPE_PTR))
3583             {
3584                 s = s->next;
3585                 continue;
3586             }
3587             if (strcasecmp(name->service, s->service)
3588                 || strcasecmp(name->proto, s->proto))
3589             {
3590                 s = s->next;
3591                 continue;
3592             }
3593             if (s->type != MDNS_TYPE_PTR) {
3594                 if (!strcasecmp(name->host, s->instance)) {
3595                     return s;
3596                 }
3597                 s = s->next;
3598                 continue;
3599             }
3600             return s;
3601         }
3602 
3603         if (type == MDNS_TYPE_PTR && type == s->type && !strcasecmp(name->service, s->service) && !strcasecmp(name->proto, s->proto)) {
3604             return s;
3605         }
3606 
3607         s = s->next;
3608     }
3609 
3610     return NULL;
3611 }
3612 
3613 /**
3614  * @brief  Create search packet for particular interface
3615  */
_mdns_create_search_packet(mdns_search_once_t * search,mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3616 static mdns_tx_packet_t * _mdns_create_search_packet(mdns_search_once_t * search, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3617 {
3618     mdns_result_t * r = NULL;
3619     mdns_tx_packet_t * packet = _mdns_alloc_packet_default(tcpip_if, ip_protocol);
3620     if (!packet) {
3621         return NULL;
3622     }
3623 
3624     mdns_out_question_t * q = (mdns_out_question_t *)malloc(sizeof(mdns_out_question_t));
3625     if (!q) {
3626         HOOK_MALLOC_FAILED;
3627         _mdns_free_tx_packet(packet);
3628         return NULL;
3629     }
3630     q->next = NULL;
3631     q->unicast = search->type != MDNS_TYPE_PTR;
3632     q->type = search->type;
3633     q->host = search->instance;
3634     q->service = search->service;
3635     q->proto = search->proto;
3636     q->domain = MDNS_DEFAULT_DOMAIN;
3637     queueToEnd(mdns_out_question_t, packet->questions, q);
3638 
3639     if (search->type == MDNS_TYPE_PTR) {
3640         r = search->result;
3641         while (r) {
3642             //full record on the same interface is available
3643             if (r->tcpip_if != tcpip_if || r->ip_protocol != ip_protocol || r->instance_name == NULL || r->hostname == NULL || r->addr == NULL) {
3644                 r = r->next;
3645                 continue;
3646             }
3647             mdns_out_answer_t * a = (mdns_out_answer_t *)malloc(sizeof(mdns_out_answer_t));
3648             if (!a) {
3649                 HOOK_MALLOC_FAILED;
3650                 _mdns_free_tx_packet(packet);
3651                 return NULL;
3652             }
3653             a->type = MDNS_TYPE_PTR;
3654             a->service = NULL;
3655             a->custom_instance = r->instance_name;
3656             a->custom_service = search->service;
3657             a->custom_proto = search->proto;
3658             a->bye = false;
3659             a->flush = false;
3660             a->next = NULL;
3661             queueToEnd(mdns_out_answer_t, packet->answers, a);
3662             r = r->next;
3663         }
3664     }
3665 
3666     return packet;
3667 }
3668 
3669 /**
3670  * @brief  Send search packet to particular interface
3671  */
_mdns_search_send_pcb(mdns_search_once_t * search,mdns_if_t tcpip_if,mdns_ip_protocol_t ip_protocol)3672 static void _mdns_search_send_pcb(mdns_search_once_t * search, mdns_if_t tcpip_if, mdns_ip_protocol_t ip_protocol)
3673 {
3674     mdns_tx_packet_t * packet = NULL;
3675     if (_mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].pcb && _mdns_server->interfaces[tcpip_if].pcbs[ip_protocol].state > PCB_INIT) {
3676         packet = _mdns_create_search_packet(search, tcpip_if, ip_protocol);
3677         if (!packet) {
3678             return;
3679         }
3680         _mdns_dispatch_tx_packet(packet);
3681         _mdns_free_tx_packet(packet);
3682     }
3683 }
3684 
3685 /**
3686  * @brief  Send search packet to all available interfaces
3687  */
_mdns_search_send(mdns_search_once_t * search)3688 static void _mdns_search_send(mdns_search_once_t * search)
3689 {
3690     mdns_search_once_t* queue = _mdns_server->search_once;
3691     bool found = false;
3692     // looking for this search in active searches
3693     while (queue) {
3694         if (queue == search) {
3695             found = true;
3696             break;
3697         }
3698         queue = queue->next;
3699     }
3700 
3701     if (!found) {
3702         // no longer active -> skip sending this search
3703         return;
3704     }
3705 
3706     uint8_t i, j;
3707     for (i=0; i<MDNS_IF_MAX; i++) {
3708         for (j=0; j<MDNS_IP_PROTOCOL_MAX; j++) {
3709             _mdns_search_send_pcb(search, (mdns_if_t)i, (mdns_ip_protocol_t)j);
3710         }
3711     }
3712 }
3713 
_mdns_tx_handle_packet(mdns_tx_packet_t * p)3714 static void _mdns_tx_handle_packet(mdns_tx_packet_t * p)
3715 {
3716     mdns_tx_packet_t * a = NULL;
3717     mdns_out_question_t * q = NULL;
3718     mdns_pcb_t * pcb = &_mdns_server->interfaces[p->tcpip_if].pcbs[p->ip_protocol];
3719     uint32_t send_after = 1000;
3720 
3721     if (pcb->state == PCB_OFF) {
3722         _mdns_free_tx_packet(p);
3723         return;
3724     }
3725     _mdns_dispatch_tx_packet(p);
3726 
3727     switch(pcb->state) {
3728     case PCB_PROBE_1:
3729         q = p->questions;
3730         while (q) {
3731             q->unicast = false;
3732             q = q->next;
3733         }
3734         //fallthrough
3735     case PCB_PROBE_2:
3736         _mdns_schedule_tx_packet(p, 250);
3737         pcb->state = (mdns_pcb_state_t)((uint8_t)(pcb->state) + 1);
3738         break;
3739     case PCB_PROBE_3:
3740         a = _mdns_create_announce_from_probe(p);
3741         if (!a) {
3742             _mdns_schedule_tx_packet(p, 250);
3743             break;
3744         }
3745         pcb->probe_running = false;
3746         pcb->probe_ip = false;
3747         pcb->probe_services_len = 0;
3748         pcb->failed_probes = 0;
3749         free(pcb->probe_services);
3750         pcb->probe_services = NULL;
3751         _mdns_free_tx_packet(p);
3752         p = a;
3753         send_after = 250;
3754         //fallthrough
3755     case PCB_ANNOUNCE_1:
3756         //fallthrough
3757     case PCB_ANNOUNCE_2:
3758         _mdns_schedule_tx_packet(p, send_after);
3759         pcb->state = (mdns_pcb_state_t)((uint8_t)(pcb->state) + 1);
3760         break;
3761     case PCB_ANNOUNCE_3:
3762         pcb->state = PCB_RUNNING;
3763         _mdns_free_tx_packet(p);
3764         break;
3765     default:
3766         _mdns_free_tx_packet(p);
3767         break;
3768     }
3769 }
3770 
3771 /**
3772  * @brief  Free action data
3773  */
_mdns_free_action(mdns_action_t * action)3774 static void _mdns_free_action(mdns_action_t * action)
3775 {
3776     switch(action->type) {
3777     case ACTION_HOSTNAME_SET:
3778         free(action->data.hostname);
3779         break;
3780     case ACTION_INSTANCE_SET:
3781         free(action->data.instance);
3782         break;
3783     case ACTION_SERVICE_ADD:
3784         _mdns_free_service(action->data.srv_add.service->service);
3785         free(action->data.srv_add.service);
3786         break;
3787     case ACTION_SERVICE_INSTANCE_SET:
3788         free(action->data.srv_instance.instance);
3789         break;
3790     case ACTION_SERVICE_TXT_REPLACE:
3791         _mdns_free_linked_txt(action->data.srv_txt_replace.txt);
3792         break;
3793     case ACTION_SERVICE_TXT_SET:
3794         free(action->data.srv_txt_set.key);
3795         free(action->data.srv_txt_set.value);
3796         break;
3797     case ACTION_SERVICE_TXT_DEL:
3798         free(action->data.srv_txt_del.key);
3799         break;
3800     case ACTION_SEARCH_ADD:
3801         //fallthrough
3802     case ACTION_SEARCH_SEND:
3803         //fallthrough
3804     case ACTION_SEARCH_END:
3805         _mdns_search_free(action->data.search_add.search);
3806         break;
3807     case ACTION_TX_HANDLE:
3808         _mdns_free_tx_packet(action->data.tx_handle.packet);
3809         break;
3810     case ACTION_RX_HANDLE:
3811         pbuf_free(action->data.rx_handle.packet->pb);
3812         free(action->data.rx_handle.packet);
3813         break;
3814     default:
3815         break;
3816     }
3817     free(action);
3818 }
3819 
3820 /**
3821  * @brief  Called from service thread to execute given action
3822  */
_mdns_execute_action(mdns_action_t * action)3823 static void _mdns_execute_action(mdns_action_t * action)
3824 {
3825     mdns_srv_item_t * a = NULL;
3826     mdns_service_t * service;
3827     char * key;
3828     char * value;
3829     mdns_txt_linked_item_t * txt, * t;
3830 
3831     switch(action->type) {
3832     case ACTION_SYSTEM_EVENT:
3833         _mdns_handle_system_event(action->data.sys_event.event_base,
3834             action->data.sys_event.event_id, action->data.sys_event.interface);
3835         break;
3836     case ACTION_HOSTNAME_SET:
3837         _mdns_send_bye_all_pcbs_no_instance(true);
3838         free((char*)_mdns_server->hostname);
3839         _mdns_server->hostname = action->data.hostname;
3840         _mdns_restart_all_pcbs();
3841 
3842         break;
3843     case ACTION_INSTANCE_SET:
3844         _mdns_send_bye_all_pcbs_no_instance(false);
3845         free((char*)_mdns_server->instance);
3846         _mdns_server->instance = action->data.instance;
3847         _mdns_restart_all_pcbs_no_instance();
3848 
3849         break;
3850     case ACTION_SERVICE_ADD:
3851         action->data.srv_add.service->next = _mdns_server->services;
3852         _mdns_server->services = action->data.srv_add.service;
3853         _mdns_probe_all_pcbs(&action->data.srv_add.service, 1, false, false);
3854 
3855         break;
3856     case ACTION_SERVICE_INSTANCE_SET:
3857         if (action->data.srv_instance.service->service->instance) {
3858             _mdns_send_bye(&action->data.srv_instance.service, 1, false);
3859             free((char*)action->data.srv_instance.service->service->instance);
3860         }
3861         action->data.srv_instance.service->service->instance = action->data.srv_instance.instance;
3862         _mdns_probe_all_pcbs(&action->data.srv_instance.service, 1, false, false);
3863 
3864         break;
3865     case ACTION_SERVICE_PORT_SET:
3866         action->data.srv_port.service->service->port = action->data.srv_port.port;
3867         _mdns_announce_all_pcbs(&action->data.srv_port.service, 1, true);
3868 
3869         break;
3870     case ACTION_SERVICE_TXT_REPLACE:
3871         service = action->data.srv_txt_replace.service->service;
3872         txt = service->txt;
3873         service->txt = NULL;
3874         _mdns_free_linked_txt(txt);
3875         service->txt = action->data.srv_txt_replace.txt;
3876         _mdns_announce_all_pcbs(&action->data.srv_txt_replace.service, 1, false);
3877 
3878         break;
3879     case ACTION_SERVICE_TXT_SET:
3880         service = action->data.srv_txt_set.service->service;
3881         key = action->data.srv_txt_set.key;
3882         value = action->data.srv_txt_set.value;
3883         txt = service->txt;
3884         while (txt) {
3885             if (strcmp(txt->key, key) == 0) {
3886                 free((char *)txt->value);
3887                 free(key);
3888                 txt->value = value;
3889                 break;
3890             }
3891             txt = txt->next;
3892         }
3893         if (!txt) {
3894             txt = (mdns_txt_linked_item_t *)malloc(sizeof(mdns_txt_linked_item_t));
3895             if (!txt) {
3896                 HOOK_MALLOC_FAILED;
3897                 _mdns_free_action(action);
3898                 return;
3899             }
3900             txt->key = key;
3901             txt->value = value;
3902             txt->next = service->txt;
3903             service->txt = txt;
3904         }
3905 
3906         _mdns_announce_all_pcbs(&action->data.srv_txt_set.service, 1, false);
3907 
3908         break;
3909     case ACTION_SERVICE_TXT_DEL:
3910         service = action->data.srv_txt_del.service->service;
3911         key = action->data.srv_txt_del.key;
3912         txt = service->txt;
3913         if (!txt) {
3914             break;
3915         }
3916         if (strcmp(txt->key, key) == 0) {
3917             service->txt = txt->next;
3918             free((char *)txt->key);
3919             free((char *)txt->value);
3920             free(txt);
3921         } else {
3922             while (txt->next) {
3923                 if (strcmp(txt->next->key, key) == 0) {
3924                     t = txt->next;
3925                     txt->next = t->next;
3926                     free((char *)t->key);
3927                     free((char *)t->value);
3928                     free(t);
3929                     break;
3930                 } else {
3931                     txt = txt->next;
3932                 }
3933             }
3934         }
3935         free(key);
3936 
3937         _mdns_announce_all_pcbs(&action->data.srv_txt_set.service, 1, false);
3938 
3939         break;
3940     case ACTION_SERVICE_DEL:
3941         a = _mdns_server->services;
3942         if (action->data.srv_del.service) {
3943             if (_mdns_server->services == action->data.srv_del.service) {
3944                 _mdns_server->services = a->next;
3945                 _mdns_send_bye(&a, 1, false);
3946                 _mdns_remove_scheduled_service_packets(a->service);
3947                 _mdns_free_service(a->service);
3948                 free(a);
3949             } else {
3950                 while (a->next && a->next != action->data.srv_del.service) {
3951                     a = a->next;
3952                 }
3953                 if (a->next == action->data.srv_del.service) {
3954                     mdns_srv_item_t * b = a->next;
3955                     a->next = a->next->next;
3956                     _mdns_send_bye(&b, 1, false);
3957                     _mdns_remove_scheduled_service_packets(b->service);
3958                     _mdns_free_service(b->service);
3959                     free(b);
3960                 }
3961             }
3962         }
3963 
3964         break;
3965     case ACTION_SERVICES_CLEAR:
3966         _mdns_send_final_bye(false);
3967         a = _mdns_server->services;
3968         _mdns_server->services = NULL;
3969         while (a) {
3970             mdns_srv_item_t * s = a;
3971             a = a->next;
3972             _mdns_remove_scheduled_service_packets(s->service);
3973             _mdns_free_service(s->service);
3974             free(s);
3975         }
3976 
3977         break;
3978     case ACTION_SEARCH_ADD:
3979         _mdns_search_add(action->data.search_add.search);
3980         break;
3981     case ACTION_SEARCH_SEND:
3982         _mdns_search_send(action->data.search_add.search);
3983         break;
3984     case ACTION_SEARCH_END:
3985         _mdns_search_finish(action->data.search_add.search);
3986         break;
3987     case ACTION_TX_HANDLE:
3988         {
3989             mdns_tx_packet_t * p = _mdns_server->tx_queue_head;
3990             // packet to be handled should be at tx head, but must be consistent with the one pushed to action queue
3991             if (p && p==action->data.tx_handle.packet && p->queued) {
3992                 p->queued = false; // clearing, as the packet might be reused (pushed and transmitted again)
3993                 _mdns_server->tx_queue_head = p->next;
3994                 _mdns_tx_handle_packet(p);
3995             } else {
3996                 ESP_LOGD(TAG, "Skipping transmit of an unexpected packet!");
3997             }
3998         }
3999         break;
4000     case ACTION_RX_HANDLE:
4001         mdns_parse_packet(action->data.rx_handle.packet);
4002         pbuf_free(action->data.rx_handle.packet->pb);
4003         free(action->data.rx_handle.packet);
4004         break;
4005     default:
4006         break;
4007     }
4008     free(action);
4009 }
4010 
4011 /**
4012  * @brief  Queue search action
4013  */
_mdns_send_search_action(mdns_action_type_t type,mdns_search_once_t * search)4014 static esp_err_t _mdns_send_search_action(mdns_action_type_t type, mdns_search_once_t * search)
4015 {
4016     mdns_action_t * action = NULL;
4017 
4018     action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4019     if (!action) {
4020         HOOK_MALLOC_FAILED;
4021         return ESP_ERR_NO_MEM;
4022     }
4023 
4024     action->type = type;
4025     action->data.search_add.search = search;
4026     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4027         free(action);
4028         return ESP_ERR_NO_MEM;
4029     }
4030     return ESP_OK;
4031 }
4032 
4033 /**
4034  * @brief  Called from timer task to run mDNS responder
4035  *
4036  * periodically checks first unqueued packet (from tx head).
4037  * if it is scheduled to be transmitted, then pushes the packet to action queue to be handled.
4038  *
4039  */
_mdns_scheduler_run(void)4040 static void _mdns_scheduler_run(void)
4041 {
4042     MDNS_SERVICE_LOCK();
4043     mdns_tx_packet_t * p = _mdns_server->tx_queue_head;
4044     mdns_action_t * action = NULL;
4045 
4046     // find first unqueued packet
4047     while (p && p->queued) {
4048         p = p->next;
4049     }
4050     if (!p) {
4051         MDNS_SERVICE_UNLOCK();
4052         return;
4053     }
4054     if ((int32_t)(p->send_at - (xTaskGetTickCount() * portTICK_PERIOD_MS)) < 0) {
4055         action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4056         if (action) {
4057             action->type = ACTION_TX_HANDLE;
4058             action->data.tx_handle.packet = p;
4059             p->queued = true;
4060             if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4061                 free(action);
4062                 p->queued = false;
4063             }
4064         } else {
4065             HOOK_MALLOC_FAILED;
4066             // continue
4067         }
4068     }
4069     MDNS_SERVICE_UNLOCK();
4070 }
4071 
4072 /**
4073  * @brief  Called from timer task to run active searches
4074  */
_mdns_search_run(void)4075 static void _mdns_search_run(void)
4076 {
4077     MDNS_SERVICE_LOCK();
4078     mdns_search_once_t * s = _mdns_server->search_once;
4079     uint32_t now = xTaskGetTickCount() * portTICK_PERIOD_MS;
4080     if (!s) {
4081         MDNS_SERVICE_UNLOCK();
4082         return;
4083     }
4084     while (s) {
4085         if (s->state != SEARCH_OFF) {
4086             if (now > (s->started_at + s->timeout)) {
4087                 s->state = SEARCH_OFF;
4088                 if (_mdns_send_search_action(ACTION_SEARCH_END, s) != ESP_OK) {
4089                     s->state = SEARCH_RUNNING;
4090                 }
4091             } else if (s->state == SEARCH_INIT || (now - s->sent_at) > 1000) {
4092                 s->state = SEARCH_RUNNING;
4093                 s->sent_at = now;
4094                 if (_mdns_send_search_action(ACTION_SEARCH_SEND, s) != ESP_OK) {
4095                     s->sent_at -= 1000;
4096                 }
4097             }
4098         }
4099         s = s->next;
4100     }
4101     MDNS_SERVICE_UNLOCK();
4102 }
4103 
4104 /**
4105  * @brief  the main MDNS service task. Packets are received and parsed here
4106  */
_mdns_service_task(void * pvParameters)4107 static void _mdns_service_task(void *pvParameters)
4108 {
4109     mdns_action_t * a = NULL;
4110     for (;;) {
4111         if (_mdns_server && _mdns_server->action_queue) {
4112             if (xQueueReceive(_mdns_server->action_queue, &a, portMAX_DELAY) == pdTRUE) {
4113                 if (a->type == ACTION_TASK_STOP) {
4114                     break;
4115                 }
4116                 MDNS_SERVICE_LOCK();
4117                 _mdns_execute_action(a);
4118                 MDNS_SERVICE_UNLOCK();
4119             }
4120         } else {
4121             vTaskDelay(500 * portTICK_PERIOD_MS);
4122         }
4123     }
4124     _mdns_service_task_handle = NULL;
4125     vTaskDelete(NULL);
4126 }
4127 
_mdns_timer_cb(void * arg)4128 static void _mdns_timer_cb(void * arg)
4129 {
4130     _mdns_scheduler_run();
4131     _mdns_search_run();
4132 }
4133 
_mdns_start_timer(void)4134 static esp_err_t _mdns_start_timer(void){
4135     esp_timer_create_args_t timer_conf = {
4136         .callback = _mdns_timer_cb,
4137         .arg = NULL,
4138         .dispatch_method = ESP_TIMER_TASK,
4139         .name = "mdns_timer"
4140     };
4141     esp_err_t err = esp_timer_create(&timer_conf, &(_mdns_server->timer_handle));
4142     if (err) {
4143         return err;
4144     }
4145     return esp_timer_start_periodic(_mdns_server->timer_handle, MDNS_TIMER_PERIOD_US);
4146 }
4147 
_mdns_stop_timer(void)4148 static esp_err_t _mdns_stop_timer(void){
4149     esp_err_t err = ESP_OK;
4150     if (_mdns_server->timer_handle) {
4151         err = esp_timer_stop(_mdns_server->timer_handle);
4152         if (err) {
4153             return err;
4154         }
4155         err = esp_timer_delete(_mdns_server->timer_handle);
4156     }
4157     return err;
4158 }
4159 
4160 /**
4161  * @brief  Start the service thread if not running
4162  *
4163  * @return
4164  *      - ESP_OK on success
4165  *      - ESP_FAIL on error
4166  */
_mdns_service_task_start(void)4167 static esp_err_t _mdns_service_task_start(void)
4168 {
4169     if (!_mdns_service_semaphore) {
4170         _mdns_service_semaphore = xSemaphoreCreateMutex();
4171         if (!_mdns_service_semaphore) {
4172             return ESP_FAIL;
4173         }
4174     }
4175     MDNS_SERVICE_LOCK();
4176     if (_mdns_start_timer()) {
4177         MDNS_SERVICE_UNLOCK();
4178         return ESP_FAIL;
4179     }
4180     if (!_mdns_service_task_handle) {
4181         xTaskCreatePinnedToCore(_mdns_service_task, "mdns", MDNS_SERVICE_STACK_DEPTH, NULL, MDNS_TASK_PRIORITY,
4182                                 (TaskHandle_t * const)(&_mdns_service_task_handle), MDNS_TASK_AFFINITY);
4183         if (!_mdns_service_task_handle) {
4184             _mdns_stop_timer();
4185             MDNS_SERVICE_UNLOCK();
4186             vSemaphoreDelete(_mdns_service_semaphore);
4187             _mdns_service_semaphore = NULL;
4188             return ESP_FAIL;
4189         }
4190     }
4191     MDNS_SERVICE_UNLOCK();
4192     return ESP_OK;
4193 }
4194 
4195 /**
4196  * @brief  Stop the service thread
4197  *
4198  * @return
4199  *      - ESP_OK
4200  */
_mdns_service_task_stop(void)4201 static esp_err_t _mdns_service_task_stop(void)
4202 {
4203     _mdns_stop_timer();
4204     if (_mdns_service_task_handle) {
4205         mdns_action_t action;
4206         mdns_action_t * a = &action;
4207         action.type = ACTION_TASK_STOP;
4208         if (xQueueSend(_mdns_server->action_queue, &a, (portTickType)0) != pdPASS) {
4209             vTaskDelete(_mdns_service_task_handle);
4210             _mdns_service_task_handle = NULL;
4211         }
4212         while (_mdns_service_task_handle) {
4213             vTaskDelay(10 / portTICK_PERIOD_MS);
4214         }
4215     }
4216     vSemaphoreDelete(_mdns_service_semaphore);
4217     _mdns_service_semaphore = NULL;
4218     return ESP_OK;
4219 }
4220 
4221 /*
4222  * Public Methods
4223  * */
4224 
mdns_handle_system_event(void * ctx,system_event_t * event)4225 esp_err_t mdns_handle_system_event(void *ctx, system_event_t *event)
4226 {
4227     /* no-op, kept for compatibility */
4228     return ESP_OK;
4229 }
4230 
event_handler(void * arg,esp_event_base_t event_base,int32_t event_id,void * event_data)4231 static void event_handler(void* arg, esp_event_base_t event_base,
4232                      int32_t event_id, void* event_data)
4233 {
4234     if (!_mdns_server) {
4235         return;
4236     }
4237 
4238     mdns_action_t * action = (mdns_action_t *)calloc(1, sizeof(mdns_action_t));
4239     if (!action) {
4240         HOOK_MALLOC_FAILED;
4241         return;
4242     }
4243     action->type = ACTION_SYSTEM_EVENT;
4244     action->data.sys_event.event_base = event_base;
4245     action->data.sys_event.event_id = event_id;
4246     if (event_base == IP_EVENT && event_id == IP_EVENT_GOT_IP6) {
4247         ip_event_got_ip6_t* event = (ip_event_got_ip6_t*) event_data;
4248         action->data.sys_event.interface = event->esp_netif;
4249     }
4250 
4251     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4252         free(action);
4253     }
4254 }
4255 
mdns_init(void)4256 esp_err_t mdns_init(void)
4257 {
4258     esp_err_t err = ESP_OK;
4259 
4260     if (_mdns_server) {
4261         return err;
4262     }
4263 
4264     _mdns_server = (mdns_server_t *)malloc(sizeof(mdns_server_t));
4265     if (!_mdns_server) {
4266         HOOK_MALLOC_FAILED;
4267         return ESP_ERR_NO_MEM;
4268     }
4269     memset((uint8_t*)_mdns_server, 0, sizeof(mdns_server_t));
4270     // zero-out local copy of netifs to initiate a fresh search by interface key whenever a netif ptr is needed
4271     memset(s_esp_netifs, 0, sizeof(s_esp_netifs));
4272 
4273     _mdns_server->lock = xSemaphoreCreateMutex();
4274     if (!_mdns_server->lock) {
4275         err = ESP_ERR_NO_MEM;
4276         goto free_server;
4277     }
4278 
4279     _mdns_server->action_queue = xQueueCreate(MDNS_ACTION_QUEUE_LEN, sizeof(mdns_action_t *));
4280     if (!_mdns_server->action_queue) {
4281         err = ESP_ERR_NO_MEM;
4282         goto free_lock;
4283     }
4284     if ((err = esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)) != ESP_OK) {
4285         goto free_event_handlers;
4286     }
4287     if ((err = esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)) != ESP_OK) {
4288         goto free_event_handlers;
4289     }
4290 #if CONFIG_ETH_ENABLED
4291     if ((err = esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)) != ESP_OK) {
4292         goto free_event_handlers;
4293     }
4294 #endif
4295     uint8_t i;
4296 #if CONFIG_LWIP_IPV6
4297     esp_ip6_addr_t tmp_addr6;
4298 #endif
4299     esp_netif_ip_info_t if_ip_info;
4300 
4301     for (i=0; i<MDNS_IF_MAX; i++) {
4302 #if CONFIG_LWIP_IPV6
4303         if (!esp_netif_get_ip6_linklocal(_mdns_get_esp_netif(i), &tmp_addr6) && !_ipv6_address_is_zero(tmp_addr6)) {
4304             _mdns_enable_pcb(i, MDNS_IP_PROTOCOL_V6);
4305         }
4306 #endif
4307         if (!esp_netif_get_ip_info(_mdns_get_esp_netif(i), &if_ip_info) && if_ip_info.ip.addr) {
4308             _mdns_enable_pcb(i, MDNS_IP_PROTOCOL_V4);
4309         }
4310     }
4311 
4312     if (_mdns_service_task_start()) {
4313         //service start failed!
4314         err = ESP_FAIL;
4315         goto free_all_and_disable_pcbs;
4316     }
4317 
4318     return ESP_OK;
4319 
4320 free_all_and_disable_pcbs:
4321     for (i=0; i<MDNS_IF_MAX; i++) {
4322         _mdns_disable_pcb(i, MDNS_IP_PROTOCOL_V6);
4323         _mdns_disable_pcb(i, MDNS_IP_PROTOCOL_V4);
4324     }
4325 free_event_handlers:
4326     esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler);
4327     esp_event_handler_unregister(IP_EVENT, ESP_EVENT_ANY_ID, &event_handler);
4328 #if CONFIG_ETH_ENABLED
4329     esp_event_handler_unregister(ETH_EVENT, ESP_EVENT_ANY_ID, &event_handler);
4330 #endif
4331     vQueueDelete(_mdns_server->action_queue);
4332 free_lock:
4333     vSemaphoreDelete(_mdns_server->lock);
4334 free_server:
4335     free(_mdns_server);
4336     _mdns_server = NULL;
4337     return err;
4338 }
4339 
mdns_free(void)4340 void mdns_free(void)
4341 {
4342     uint8_t i, j;
4343     if (!_mdns_server) {
4344         return;
4345     }
4346 
4347     // Unregister handlers before destroying the mdns internals to avoid receiving async events while deinit
4348     esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler);
4349     esp_event_handler_unregister(IP_EVENT, ESP_EVENT_ANY_ID, &event_handler);
4350 #if CONFIG_ETH_ENABLED
4351     esp_event_handler_unregister(ETH_EVENT, ESP_EVENT_ANY_ID, &event_handler);
4352 #endif
4353 
4354     mdns_service_remove_all();
4355     _mdns_service_task_stop();
4356     for (i=0; i<MDNS_IF_MAX; i++) {
4357         for (j=0; j<MDNS_IP_PROTOCOL_MAX; j++) {
4358             _mdns_pcb_deinit(i, j);
4359         }
4360     }
4361     free((char*)_mdns_server->hostname);
4362     free((char*)_mdns_server->instance);
4363     if (_mdns_server->action_queue) {
4364         mdns_action_t * c;
4365         while (xQueueReceive(_mdns_server->action_queue, &c, 0) == pdTRUE) {
4366             _mdns_free_action(c);
4367         }
4368         vQueueDelete(_mdns_server->action_queue);
4369     }
4370     _mdns_clear_tx_queue_head();
4371     while (_mdns_server->search_once) {
4372         mdns_search_once_t * h = _mdns_server->search_once;
4373         _mdns_server->search_once = h->next;
4374         free(h->instance);
4375         free(h->service);
4376         free(h->proto);
4377         vSemaphoreDelete(h->done_semaphore);
4378         if (h->result) {
4379             mdns_query_results_free(h->result);
4380         }
4381         free(h);
4382     }
4383     vSemaphoreDelete(_mdns_server->lock);
4384     free(_mdns_server);
4385     _mdns_server = NULL;
4386 }
4387 
mdns_hostname_set(const char * hostname)4388 esp_err_t mdns_hostname_set(const char * hostname)
4389 {
4390     if (!_mdns_server) {
4391         return ESP_ERR_INVALID_ARG;
4392     }
4393     if (_str_null_or_empty(hostname) || strlen(hostname) > (MDNS_NAME_BUF_LEN - 1)) {
4394         return ESP_ERR_INVALID_ARG;
4395     }
4396     char * new_hostname = strndup(hostname, MDNS_NAME_BUF_LEN - 1);
4397     if (!new_hostname) {
4398         return ESP_ERR_NO_MEM;
4399     }
4400 
4401     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4402     if (!action) {
4403         HOOK_MALLOC_FAILED;
4404         free(new_hostname);
4405         return ESP_ERR_NO_MEM;
4406     }
4407     action->type = ACTION_HOSTNAME_SET;
4408     action->data.hostname = new_hostname;
4409     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4410         free(new_hostname);
4411         free(action);
4412         return ESP_ERR_NO_MEM;
4413     }
4414     return ERR_OK;
4415 }
4416 
mdns_instance_name_set(const char * instance)4417 esp_err_t mdns_instance_name_set(const char * instance)
4418 {
4419     if (!_mdns_server) {
4420         return ESP_ERR_INVALID_ARG;
4421     }
4422     if (_str_null_or_empty(instance) || strlen(instance) > (MDNS_NAME_BUF_LEN - 1)) {
4423         return ESP_ERR_INVALID_ARG;
4424     }
4425     char * new_instance = strndup(instance, MDNS_NAME_BUF_LEN - 1);
4426     if (!new_instance) {
4427         return ESP_ERR_NO_MEM;
4428     }
4429 
4430     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4431     if (!action) {
4432         HOOK_MALLOC_FAILED;
4433         free(new_instance);
4434         return ESP_ERR_NO_MEM;
4435     }
4436     action->type = ACTION_INSTANCE_SET;
4437     action->data.instance = new_instance;
4438     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4439         free(new_instance);
4440         free(action);
4441         return ESP_ERR_NO_MEM;
4442     }
4443     return ERR_OK;
4444 }
4445 
4446 /*
4447  * MDNS SERVICES
4448  * */
4449 
mdns_service_add(const char * instance,const char * service,const char * proto,uint16_t port,mdns_txt_item_t txt[],size_t num_items)4450 esp_err_t mdns_service_add(const char * instance, const char * service, const char * proto, uint16_t port, mdns_txt_item_t txt[], size_t num_items)
4451 {
4452     if (!_mdns_server || _str_null_or_empty(service) || _str_null_or_empty(proto) || !port) {
4453         return ESP_ERR_INVALID_ARG;
4454     }
4455 
4456     if (!_mdns_can_add_more_services()) {
4457         return ESP_ERR_NO_MEM;
4458     }
4459 
4460     mdns_srv_item_t * item = _mdns_get_service_item(service, proto);
4461     if (item) {
4462         return ESP_ERR_INVALID_ARG;
4463     }
4464 
4465     mdns_service_t * s = _mdns_create_service(service, proto, port, instance, num_items, txt);
4466     if (!s) {
4467         return ESP_ERR_NO_MEM;
4468     }
4469 
4470     item = (mdns_srv_item_t *)malloc(sizeof(mdns_srv_item_t));
4471     if (!item) {
4472         HOOK_MALLOC_FAILED;
4473         _mdns_free_service(s);
4474         return ESP_ERR_NO_MEM;
4475     }
4476 
4477     item->service = s;
4478     item->next = NULL;
4479 
4480     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4481     if (!action) {
4482         HOOK_MALLOC_FAILED;
4483         _mdns_free_service(s);
4484         free(item);
4485         return ESP_ERR_NO_MEM;
4486     }
4487     action->type = ACTION_SERVICE_ADD;
4488     action->data.srv_add.service = item;
4489     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4490         _mdns_free_service(s);
4491         free(item);
4492         free(action);
4493         return ESP_ERR_NO_MEM;
4494     }
4495 
4496     size_t start = xTaskGetTickCount();
4497     size_t timeout_ticks = pdMS_TO_TICKS(MDNS_SERVICE_ADD_TIMEOUT_MS);
4498     while (_mdns_get_service_item(service, proto) == NULL)
4499     {
4500         uint32_t expired = xTaskGetTickCount() - start;
4501         if (expired >= timeout_ticks) {
4502             return ESP_FAIL; // Timeout
4503         }
4504         vTaskDelay(MIN(10 / portTICK_RATE_MS, timeout_ticks - expired));
4505     }
4506 
4507     return ESP_OK;
4508 }
4509 
mdns_service_port_set(const char * service,const char * proto,uint16_t port)4510 esp_err_t mdns_service_port_set(const char * service, const char * proto, uint16_t port)
4511 {
4512     if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || !port) {
4513         return ESP_ERR_INVALID_ARG;
4514     }
4515     mdns_srv_item_t * s = _mdns_get_service_item(service, proto);
4516     if (!s) {
4517         return ESP_ERR_NOT_FOUND;
4518     }
4519 
4520     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4521     if (!action) {
4522         HOOK_MALLOC_FAILED;
4523         return ESP_ERR_NO_MEM;
4524     }
4525     action->type = ACTION_SERVICE_PORT_SET;
4526     action->data.srv_port.service = s;
4527     action->data.srv_port.port = port;
4528     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4529         free(action);
4530         return ESP_ERR_NO_MEM;
4531     }
4532     return ESP_OK;
4533 }
4534 
mdns_service_txt_set(const char * service,const char * proto,mdns_txt_item_t txt[],uint8_t num_items)4535 esp_err_t mdns_service_txt_set(const char * service, const char * proto, mdns_txt_item_t txt[], uint8_t num_items)
4536 {
4537     if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || (num_items && txt == NULL)) {
4538         return ESP_ERR_INVALID_ARG;
4539     }
4540     mdns_srv_item_t * s = _mdns_get_service_item(service, proto);
4541     if (!s) {
4542         return ESP_ERR_NOT_FOUND;
4543     }
4544 
4545     mdns_txt_linked_item_t * new_txt = NULL;
4546     if (num_items){
4547         new_txt = _mdns_allocate_txt(num_items, txt);
4548         if (!new_txt) {
4549             return ESP_ERR_NO_MEM;
4550         }
4551     }
4552 
4553     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4554     if (!action) {
4555         HOOK_MALLOC_FAILED;
4556         _mdns_free_linked_txt(new_txt);
4557         return ESP_ERR_NO_MEM;
4558     }
4559     action->type = ACTION_SERVICE_TXT_REPLACE;
4560     action->data.srv_txt_replace.service = s;
4561     action->data.srv_txt_replace.txt = new_txt;
4562 
4563     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4564         _mdns_free_linked_txt(new_txt);
4565         free(action);
4566         return ESP_ERR_NO_MEM;
4567     }
4568     return ESP_OK;
4569 }
4570 
4571 
mdns_service_txt_item_set(const char * service,const char * proto,const char * key,const char * value)4572 esp_err_t mdns_service_txt_item_set(const char * service, const char * proto, const char * key, const char * value)
4573 {
4574     if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || _str_null_or_empty(key) || !value) {
4575         return ESP_ERR_INVALID_ARG;
4576     }
4577     mdns_srv_item_t * s = _mdns_get_service_item(service, proto);
4578     if (!s) {
4579         return ESP_ERR_NOT_FOUND;
4580     }
4581     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4582     if (!action) {
4583         HOOK_MALLOC_FAILED;
4584         return ESP_ERR_NO_MEM;
4585     }
4586 
4587     action->type = ACTION_SERVICE_TXT_SET;
4588     action->data.srv_txt_set.service = s;
4589     action->data.srv_txt_set.key = strdup(key);
4590     if (!action->data.srv_txt_set.key) {
4591         free(action);
4592         return ESP_ERR_NO_MEM;
4593     }
4594     action->data.srv_txt_set.value = strdup(value);
4595     if (!action->data.srv_txt_set.value) {
4596         free(action->data.srv_txt_set.key);
4597         free(action);
4598         return ESP_ERR_NO_MEM;
4599     }
4600     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4601         free(action->data.srv_txt_set.key);
4602         free(action->data.srv_txt_set.value);
4603         free(action);
4604         return ESP_ERR_NO_MEM;
4605     }
4606     return ESP_OK;
4607 }
4608 
mdns_service_txt_item_remove(const char * service,const char * proto,const char * key)4609 esp_err_t mdns_service_txt_item_remove(const char * service, const char * proto, const char * key)
4610 {
4611     if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto) || _str_null_or_empty(key)) {
4612         return ESP_ERR_INVALID_ARG;
4613     }
4614     mdns_srv_item_t * s = _mdns_get_service_item(service, proto);
4615     if (!s) {
4616         return ESP_ERR_NOT_FOUND;
4617     }
4618     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4619     if (!action) {
4620         HOOK_MALLOC_FAILED;
4621         return ESP_ERR_NO_MEM;
4622     }
4623 
4624     action->type = ACTION_SERVICE_TXT_DEL;
4625     action->data.srv_txt_del.service = s;
4626     action->data.srv_txt_del.key = strdup(key);
4627     if (!action->data.srv_txt_del.key) {
4628         free(action);
4629         return ESP_ERR_NO_MEM;
4630     }
4631     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4632         free(action->data.srv_txt_del.key);
4633         free(action);
4634         return ESP_ERR_NO_MEM;
4635     }
4636     return ESP_OK;
4637 }
4638 
mdns_service_instance_name_set(const char * service,const char * proto,const char * instance)4639 esp_err_t mdns_service_instance_name_set(const char * service, const char * proto, const char * instance)
4640 {
4641     if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto)) {
4642         return ESP_ERR_INVALID_ARG;
4643     }
4644     if (_str_null_or_empty(instance) || strlen(instance) > (MDNS_NAME_BUF_LEN - 1)) {
4645         return ESP_ERR_INVALID_ARG;
4646     }
4647     mdns_srv_item_t * s = _mdns_get_service_item(service, proto);
4648     if (!s) {
4649         return ESP_ERR_NOT_FOUND;
4650     }
4651     char * new_instance = strndup(instance, MDNS_NAME_BUF_LEN - 1);
4652     if (!new_instance) {
4653         return ESP_ERR_NO_MEM;
4654     }
4655 
4656     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4657     if (!action) {
4658         HOOK_MALLOC_FAILED;
4659         free(new_instance);
4660         return ESP_ERR_NO_MEM;
4661     }
4662     action->type = ACTION_SERVICE_INSTANCE_SET;
4663     action->data.srv_instance.service = s;
4664     action->data.srv_instance.instance = new_instance;
4665     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4666         free(new_instance);
4667         free(action);
4668         return ESP_ERR_NO_MEM;
4669     }
4670     return ESP_OK;
4671 }
4672 
mdns_service_remove(const char * service,const char * proto)4673 esp_err_t mdns_service_remove(const char * service, const char * proto)
4674 {
4675     if (!_mdns_server || !_mdns_server->services || _str_null_or_empty(service) || _str_null_or_empty(proto)) {
4676         return ESP_ERR_INVALID_ARG;
4677     }
4678     mdns_srv_item_t * s = _mdns_get_service_item(service, proto);
4679     if (!s) {
4680         return ESP_ERR_NOT_FOUND;
4681     }
4682 
4683     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4684     if (!action) {
4685         HOOK_MALLOC_FAILED;
4686         return ESP_ERR_NO_MEM;
4687     }
4688     action->type = ACTION_SERVICE_DEL;
4689     action->data.srv_del.service = s;
4690     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4691         free(action);
4692         return ESP_ERR_NO_MEM;
4693     }
4694     return ESP_OK;
4695 }
4696 
mdns_service_remove_all(void)4697 esp_err_t mdns_service_remove_all(void)
4698 {
4699     if (!_mdns_server) {
4700         return ESP_ERR_INVALID_ARG;
4701     }
4702     if (!_mdns_server->services) {
4703         return ESP_OK;
4704     }
4705 
4706     mdns_action_t * action = (mdns_action_t *)malloc(sizeof(mdns_action_t));
4707     if (!action) {
4708         HOOK_MALLOC_FAILED;
4709         return ESP_ERR_NO_MEM;
4710     }
4711     action->type = ACTION_SERVICES_CLEAR;
4712     if (xQueueSend(_mdns_server->action_queue, &action, (portTickType)0) != pdPASS) {
4713         free(action);
4714         return ESP_ERR_NO_MEM;
4715     }
4716     return ESP_OK;
4717 }
4718 
4719 /*
4720  * MDNS QUERY
4721  * */
4722 
mdns_query_results_free(mdns_result_t * results)4723 void mdns_query_results_free(mdns_result_t * results)
4724 {
4725     mdns_result_t * r;
4726     mdns_ip_addr_t * a;
4727 
4728     while (results) {
4729         r = results;
4730 
4731         free((char *)(r->hostname));
4732         free((char *)(r->instance_name));
4733 
4734         for (size_t i=0; i<r->txt_count; i++) {
4735             free((char *)(r->txt[i].key));
4736             free((char *)(r->txt[i].value));
4737         }
4738         free(r->txt);
4739 
4740         while (r->addr) {
4741             a = r->addr;
4742             r->addr = r->addr->next;
4743             free(a);
4744         }
4745 
4746         results = results->next;
4747         free(r);
4748     }
4749 }
4750 
mdns_query(const char * name,const char * service,const char * proto,uint16_t type,uint32_t timeout,size_t max_results,mdns_result_t ** results)4751 esp_err_t mdns_query(const char * name, const char * service, const char * proto, uint16_t type, uint32_t timeout, size_t max_results, mdns_result_t ** results)
4752 {
4753     mdns_search_once_t * search = NULL;
4754 
4755     *results = NULL;
4756 
4757     if (!_mdns_server) {
4758         return ESP_ERR_INVALID_STATE;
4759     }
4760 
4761     if (!timeout || _str_null_or_empty(service) != _str_null_or_empty(proto)) {
4762         return ESP_ERR_INVALID_ARG;
4763     }
4764 
4765     search = _mdns_search_init(name, service, proto, type, timeout, max_results);
4766     if (!search) {
4767         return ESP_ERR_NO_MEM;
4768     }
4769 
4770     if (_mdns_send_search_action(ACTION_SEARCH_ADD, search)) {
4771         _mdns_search_free(search);
4772         return ESP_ERR_NO_MEM;
4773     }
4774     xSemaphoreTake(search->done_semaphore, portMAX_DELAY);
4775 
4776     *results = search->result;
4777     _mdns_search_free(search);
4778 
4779     return ESP_OK;
4780 }
4781 
mdns_query_ptr(const char * service,const char * proto,uint32_t timeout,size_t max_results,mdns_result_t ** results)4782 esp_err_t mdns_query_ptr(const char * service, const char * proto, uint32_t timeout, size_t max_results, mdns_result_t ** results)
4783 {
4784     if (_str_null_or_empty(service) || _str_null_or_empty(proto)) {
4785         return ESP_ERR_INVALID_ARG;
4786     }
4787 
4788     return mdns_query(NULL, service, proto, MDNS_TYPE_PTR, timeout, max_results, results);
4789 }
4790 
mdns_query_srv(const char * instance,const char * service,const char * proto,uint32_t timeout,mdns_result_t ** result)4791 esp_err_t mdns_query_srv(const char * instance, const char * service, const char * proto, uint32_t timeout, mdns_result_t ** result)
4792 {
4793     if (_str_null_or_empty(instance) || _str_null_or_empty(service) || _str_null_or_empty(proto)) {
4794         return ESP_ERR_INVALID_ARG;
4795     }
4796 
4797     return mdns_query(instance, service, proto, MDNS_TYPE_SRV, timeout, 1, result);
4798 }
4799 
mdns_query_txt(const char * instance,const char * service,const char * proto,uint32_t timeout,mdns_result_t ** result)4800 esp_err_t mdns_query_txt(const char * instance, const char * service, const char * proto, uint32_t timeout, mdns_result_t ** result)
4801 {
4802     if (_str_null_or_empty(instance) || _str_null_or_empty(service) || _str_null_or_empty(proto)) {
4803         return ESP_ERR_INVALID_ARG;
4804     }
4805 
4806     return mdns_query(instance, service, proto, MDNS_TYPE_TXT, timeout, 1, result);
4807 }
4808 
mdns_query_a(const char * name,uint32_t timeout,esp_ip4_addr_t * addr)4809 esp_err_t mdns_query_a(const char * name, uint32_t timeout, esp_ip4_addr_t * addr)
4810 {
4811     mdns_result_t * result = NULL;
4812     esp_err_t err;
4813 
4814     if (_str_null_or_empty(name)) {
4815         return ESP_ERR_INVALID_ARG;
4816     }
4817 
4818     err = mdns_query(name, NULL, NULL, MDNS_TYPE_A, timeout, 1, &result);
4819 
4820     if (err) {
4821         return err;
4822     }
4823 
4824     if (!result) {
4825         return ESP_ERR_NOT_FOUND;
4826     }
4827 
4828     mdns_ip_addr_t * a = result->addr;
4829     while (a) {
4830         if (a->addr.type == IPADDR_TYPE_V4) {
4831             addr->addr = a->addr.u_addr.ip4.addr;
4832             mdns_query_results_free(result);
4833             return ESP_OK;
4834         }
4835         a = a->next;
4836     }
4837 
4838     mdns_query_results_free(result);
4839     return ESP_ERR_NOT_FOUND;
4840 }
4841 
4842 #if CONFIG_LWIP_IPV6
mdns_query_aaaa(const char * name,uint32_t timeout,esp_ip6_addr_t * addr)4843 esp_err_t mdns_query_aaaa(const char * name, uint32_t timeout, esp_ip6_addr_t * addr)
4844 {
4845     mdns_result_t * result = NULL;
4846     esp_err_t err;
4847 
4848     if (_str_null_or_empty(name)) {
4849         return ESP_ERR_INVALID_ARG;
4850     }
4851 
4852     err = mdns_query(name, NULL, NULL, MDNS_TYPE_AAAA, timeout, 1, &result);
4853 
4854     if (err) {
4855         return err;
4856     }
4857 
4858     if (!result) {
4859         return ESP_ERR_NOT_FOUND;
4860     }
4861 
4862     mdns_ip_addr_t * a = result->addr;
4863     while (a) {
4864         if (a->addr.type == IPADDR_TYPE_V6) {
4865             memcpy(addr->addr, a->addr.u_addr.ip6.addr, 16);
4866             mdns_query_results_free(result);
4867             return ESP_OK;
4868         }
4869         a = a->next;
4870     }
4871 
4872     mdns_query_results_free(result);
4873     return ESP_ERR_NOT_FOUND;
4874 }
4875 #endif
4876 
4877 #ifdef MDNS_ENABLE_DEBUG
4878 
mdns_debug_packet(const uint8_t * data,size_t len)4879 void mdns_debug_packet(const uint8_t * data, size_t len)
4880 {
4881     static mdns_name_t n;
4882     mdns_header_t header;
4883     const uint8_t * content = data + MDNS_HEAD_LEN;
4884     uint32_t t = xTaskGetTickCount() * portTICK_PERIOD_MS;
4885     mdns_name_t * name = &n;
4886     memset(name, 0, sizeof(mdns_name_t));
4887 
4888     _mdns_dbg_printf("Packet[%u]: ", t);
4889 
4890     header.id = _mdns_read_u16(data, MDNS_HEAD_ID_OFFSET);
4891     header.flags.value = _mdns_read_u16(data, MDNS_HEAD_FLAGS_OFFSET);
4892     header.questions = _mdns_read_u16(data, MDNS_HEAD_QUESTIONS_OFFSET);
4893     header.answers = _mdns_read_u16(data, MDNS_HEAD_ANSWERS_OFFSET);
4894     header.servers = _mdns_read_u16(data, MDNS_HEAD_SERVERS_OFFSET);
4895     header.additional = _mdns_read_u16(data, MDNS_HEAD_ADDITIONAL_OFFSET);
4896 
4897     _mdns_dbg_printf("%s",
4898         (header.flags.value == MDNS_FLAGS_AUTHORITATIVE)?"AUTHORITATIVE\n":
4899         (header.flags.value == MDNS_FLAGS_DISTRIBUTED)?"DISTRIBUTED\n":
4900         (header.flags.value == 0)?"\n":" "
4901     );
4902     if (header.flags.value && header.flags.value != MDNS_FLAGS_AUTHORITATIVE) {
4903         _mdns_dbg_printf("0x%04X\n", header.flags.value);
4904     }
4905 
4906     if (header.questions) {
4907         uint8_t qs = header.questions;
4908 
4909         while (qs--) {
4910             content = _mdns_parse_fqdn(data, content, name);
4911             if (!content) {
4912                 header.answers = 0;
4913                 header.additional = 0;
4914                 header.servers = 0;
4915                 _mdns_dbg_printf("ERROR: %s:%u\n", __FILE__, __LINE__);
4916                 break;
4917             }
4918 
4919             uint16_t type = _mdns_read_u16(content, MDNS_TYPE_OFFSET);
4920             uint16_t mdns_class = _mdns_read_u16(content, MDNS_CLASS_OFFSET);
4921             bool unicast = !!(mdns_class & 0x8000);
4922             mdns_class &= 0x7FFF;
4923             content = content + 4;
4924 
4925             _mdns_dbg_printf("    Q: ");
4926             if (unicast) {
4927                 _mdns_dbg_printf("*U* ");
4928             }
4929             if (type == MDNS_TYPE_PTR) {
4930                 _mdns_dbg_printf("%s.%s%s.%s.%s. PTR ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain);
4931             } else if (type == MDNS_TYPE_SRV) {
4932                 _mdns_dbg_printf("%s.%s%s.%s.%s. SRV ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain);
4933             } else if (type == MDNS_TYPE_TXT) {
4934                 _mdns_dbg_printf("%s.%s%s.%s.%s. TXT ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain);
4935             } else if (type == MDNS_TYPE_A) {
4936                 _mdns_dbg_printf("%s.%s. A ", name->host, name->domain);
4937             } else if (type == MDNS_TYPE_AAAA) {
4938                 _mdns_dbg_printf("%s.%s. AAAA ", name->host, name->domain);
4939             } else if (type == MDNS_TYPE_NSEC) {
4940                 _mdns_dbg_printf("%s.%s%s.%s.%s. NSEC ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain);
4941             } else if (type == MDNS_TYPE_ANY) {
4942                 _mdns_dbg_printf("%s.%s%s.%s.%s. ANY ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain);
4943             } else {
4944                 _mdns_dbg_printf("%s.%s%s.%s.%s. %04X ", name->host, name->sub?"_sub.":"", name->service, name->proto, name->domain, type);
4945             }
4946 
4947             if (mdns_class == 0x0001) {
4948                 _mdns_dbg_printf("IN");
4949             } else {
4950                 _mdns_dbg_printf("%04X", mdns_class);
4951             }
4952             _mdns_dbg_printf("\n");
4953         }
4954     }
4955 
4956     if (header.answers || header.servers || header.additional) {
4957         uint16_t recordIndex = 0;
4958 
4959         while (content < (data + len)) {
4960 
4961             content = _mdns_parse_fqdn(data, content, name);
4962             if (!content) {
4963                 _mdns_dbg_printf("ERROR: %s:%u\n", __FILE__, __LINE__);
4964                 break;
4965             }
4966 
4967             uint16_t type = _mdns_read_u16(content, MDNS_TYPE_OFFSET);
4968             uint16_t mdns_class = _mdns_read_u16(content, MDNS_CLASS_OFFSET);
4969             uint32_t ttl = _mdns_read_u32(content, MDNS_TTL_OFFSET);
4970             uint16_t data_len = _mdns_read_u16(content, MDNS_LEN_OFFSET);
4971             const uint8_t * data_ptr = content + MDNS_DATA_OFFSET;
4972             bool flush = !!(mdns_class & 0x8000);
4973             mdns_class &= 0x7FFF;
4974 
4975             content = data_ptr + data_len;
4976             if (content > (data + len)) {
4977                 _mdns_dbg_printf("ERROR: %s:%u\n", __FILE__, __LINE__);
4978                 break;
4979             }
4980 
4981             mdns_parsed_record_type_t record_type = MDNS_ANSWER;
4982 
4983             if (recordIndex >= (header.answers + header.servers)) {
4984                 record_type = MDNS_EXTRA;
4985             } else if (recordIndex >= (header.answers)) {
4986                 record_type = MDNS_NS;
4987             }
4988             recordIndex++;
4989 
4990             if (record_type == MDNS_EXTRA) {
4991                 _mdns_dbg_printf("    X");
4992             } else if (record_type == MDNS_NS) {
4993                 _mdns_dbg_printf("    S");
4994             } else {
4995                 _mdns_dbg_printf("    A");
4996             }
4997 
4998             if (type == MDNS_TYPE_PTR) {
4999                 _mdns_dbg_printf(": %s%s%s.%s.%s. PTR ", name->host, name->host[0]?".":"", name->service, name->proto, name->domain);
5000             } else if (type == MDNS_TYPE_SRV) {
5001                 _mdns_dbg_printf(": %s.%s.%s.%s. SRV ", name->host, name->service, name->proto, name->domain);
5002             } else if (type == MDNS_TYPE_TXT) {
5003                 _mdns_dbg_printf(": %s.%s.%s.%s. TXT ", name->host, name->service, name->proto, name->domain);
5004             } else if (type == MDNS_TYPE_A) {
5005                 _mdns_dbg_printf(": %s.%s. A ", name->host, name->domain);
5006             } else if (type == MDNS_TYPE_AAAA) {
5007                 _mdns_dbg_printf(": %s.%s. AAAA ", name->host, name->domain);
5008             } else if (type == MDNS_TYPE_NSEC) {
5009                 _mdns_dbg_printf(": %s.%s.%s.%s. NSEC ", name->host, name->service, name->proto, name->domain);
5010             } else if (type == MDNS_TYPE_ANY) {
5011                 _mdns_dbg_printf(": %s.%s.%s.%s. ANY ", name->host, name->service, name->proto, name->domain);
5012             } else if (type == MDNS_TYPE_OPT) {
5013                 _mdns_dbg_printf(": . OPT ");
5014             } else {
5015                 _mdns_dbg_printf(": %s.%s.%s.%s. %04X ", name->host, name->service, name->proto, name->domain, type);
5016             }
5017 
5018             if (mdns_class == 0x0001) {
5019                 _mdns_dbg_printf("IN ");
5020             } else {
5021                 _mdns_dbg_printf("%04X ", mdns_class);
5022             }
5023             if (flush) {
5024                 _mdns_dbg_printf("FLUSH ");
5025             }
5026             _mdns_dbg_printf("%u ", ttl);
5027             _mdns_dbg_printf("[%u] ", data_len);
5028             if (type == MDNS_TYPE_PTR) {
5029                 if (!_mdns_parse_fqdn(data, data_ptr, name)) {
5030                     _mdns_dbg_printf("ERROR: %s:%u\n", __FILE__, __LINE__);
5031                     continue;
5032                 }
5033                 _mdns_dbg_printf("%s.%s.%s.%s.\n", name->host, name->service, name->proto, name->domain);
5034             } else if (type == MDNS_TYPE_SRV) {
5035                 if (!_mdns_parse_fqdn(data, data_ptr + MDNS_SRV_FQDN_OFFSET, name)) {
5036                     _mdns_dbg_printf("ERROR: %s:%u\n", __FILE__, __LINE__);
5037                     continue;
5038                 }
5039                 uint16_t priority = _mdns_read_u16(data_ptr, MDNS_SRV_PRIORITY_OFFSET);
5040                 uint16_t weight = _mdns_read_u16(data_ptr, MDNS_SRV_WEIGHT_OFFSET);
5041                 uint16_t port = _mdns_read_u16(data_ptr, MDNS_SRV_PORT_OFFSET);
5042                 _mdns_dbg_printf("%u %u %u %s.%s.\n", priority, weight, port, name->host, name->domain);
5043             } else if (type == MDNS_TYPE_TXT) {
5044                 uint16_t i=0, y;
5045                 while (i < data_len) {
5046                     uint8_t partLen = data_ptr[i++];
5047                     if ((i+partLen) > data_len) {
5048                         _mdns_dbg_printf("ERROR: %s:%u\n", __FILE__, __LINE__);
5049                         break;
5050                     }
5051                     char txt[partLen+1];
5052                     for (y=0; y<partLen; y++) {
5053                         char d = data_ptr[i++];
5054                         txt[y] = d;
5055                     }
5056                     txt[partLen] = 0;
5057                     _mdns_dbg_printf("%s", txt);
5058                     if (i<data_len) {
5059                         _mdns_dbg_printf("; ");
5060                     }
5061                 }
5062                 _mdns_dbg_printf("\n");
5063             } else if (type == MDNS_TYPE_AAAA) {
5064                 esp_ip6_addr_t ip6;
5065                 memcpy(&ip6, data_ptr, sizeof(esp_ip6_addr_t));
5066                 _mdns_dbg_printf(IPV6STR "\n", IPV62STR(ip6));
5067             } else if (type == MDNS_TYPE_A) {
5068                 esp_ip4_addr_t ip;
5069                 memcpy(&ip, data_ptr, sizeof(esp_ip4_addr_t));
5070                 _mdns_dbg_printf(IPSTR "\n", IP2STR(&ip));
5071             } else if (type == MDNS_TYPE_NSEC) {
5072                 const uint8_t * old_ptr = data_ptr;
5073                 const uint8_t * new_ptr = _mdns_parse_fqdn(data, data_ptr, name);
5074                 if (new_ptr) {
5075                     _mdns_dbg_printf("%s.%s.%s.%s. ", name->host, name->service, name->proto, name->domain);
5076                     size_t diff = new_ptr - old_ptr;
5077                     data_len -= diff;
5078                     data_ptr = new_ptr;
5079                 }
5080                 size_t i;
5081                 for (i=0; i<data_len; i++) {
5082                     _mdns_dbg_printf(" %02x", data_ptr[i]);
5083                 }
5084                 _mdns_dbg_printf("\n");
5085             } else if (type == MDNS_TYPE_OPT) {
5086                 uint16_t opCode = _mdns_read_u16(data_ptr, 0);
5087                 uint16_t opLen = _mdns_read_u16(data_ptr, 2);
5088                 _mdns_dbg_printf(" Code: %04x Data[%u]:", opCode, opLen);
5089                 size_t i;
5090                 for (i=4; i<data_len; i++) {
5091                     _mdns_dbg_printf(" %02x", data_ptr[i]);
5092                 }
5093                 _mdns_dbg_printf("\n");
5094             } else {
5095                 size_t i;
5096                 for (i=0; i<data_len; i++) {
5097                     _mdns_dbg_printf(" %02x", data_ptr[i]);
5098                 }
5099                 _mdns_dbg_printf("\n");
5100             }
5101         }
5102     }
5103 }
5104 #endif
5105