xref: /minix/minix/lib/liblwip/dist/src/apps/mdns/mdns.c (revision e4dbab1e)
1 /**
2  * @file
3  * MDNS responder implementation
4  *
5  * @defgroup mdns MDNS
6  * @ingroup apps
7  *
8  * RFC 6762 - Multicast DNS\n
9  * RFC 6763 - DNS-Based Service Discovery\n
10  *
11  * @verbinclude mdns.txt
12  *
13  * Things left to implement:
14  * -------------------------
15  *
16  * - Probing/conflict resolution
17  * - Sending goodbye messages (zero ttl) - shutdown, DHCP lease about to expire, DHCP turned off...
18  * - Checking that source address of unicast requests are on the same network
19  * - Limiting multicast responses to 1 per second per resource record
20  * - Fragmenting replies if required
21  * - Handling multi-packet known answers
22  * - Individual known answer detection for all local IPv6 addresses
23  * - Dynamic size of outgoing packet
24  */
25 
26 /*
27  * Copyright (c) 2015 Verisure Innovation AB
28  * All rights reserved.
29  *
30  * Redistribution and use in source and binary forms, with or without modification,
31  * are permitted provided that the following conditions are met:
32  *
33  * 1. Redistributions of source code must retain the above copyright notice,
34  *    this list of conditions and the following disclaimer.
35  * 2. Redistributions in binary form must reproduce the above copyright notice,
36  *    this list of conditions and the following disclaimer in the documentation
37  *    and/or other materials provided with the distribution.
38  * 3. The name of the author may not be used to endorse or promote products
39  *    derived from this software without specific prior written permission.
40  *
41  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
42  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
43  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
44  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
46  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
47  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
48  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
49  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
50  * OF SUCH DAMAGE.
51  *
52  * This file is part of the lwIP TCP/IP stack.
53  *
54  * Author: Erik Ekman <erik@kryo.se>
55  *
56  */
57 
58 #include "lwip/apps/mdns.h"
59 #include "lwip/apps/mdns_priv.h"
60 #include "lwip/netif.h"
61 #include "lwip/udp.h"
62 #include "lwip/ip_addr.h"
63 #include "lwip/mem.h"
64 #include "lwip/prot/dns.h"
65 
66 #include <string.h>
67 
68 #if LWIP_MDNS_RESPONDER
69 
70 #if (LWIP_IPV4 && !LWIP_IGMP)
71   #error "If you want to use MDNS with IPv4, you have to define LWIP_IGMP=1 in your lwipopts.h"
72 #endif
73 #if (LWIP_IPV6 && !LWIP_IPV6_MLD)
74 #error "If you want to use MDNS with IPv6, you have to define LWIP_IPV6_MLD=1 in your lwipopts.h"
75 #endif
76 #if (!LWIP_UDP)
77   #error "If you want to use MDNS, you have to define LWIP_UDP=1 in your lwipopts.h"
78 #endif
79 
80 #if LWIP_IPV4
81 #include "lwip/igmp.h"
82 /* IPv4 multicast group 224.0.0.251 */
83 static const ip_addr_t v4group = DNS_MQUERY_IPV4_GROUP_INIT;
84 #endif
85 
86 #if LWIP_IPV6
87 #include "lwip/mld6.h"
88 /* IPv6 multicast group FF02::FB */
89 static const ip_addr_t v6group = DNS_MQUERY_IPV6_GROUP_INIT;
90 #endif
91 
92 #define MDNS_PORT 5353
93 #define MDNS_TTL  255
94 
95 /* Stored offsets to beginning of domain names
96  * Used for compression.
97  */
98 #define NUM_DOMAIN_OFFSETS 10
99 #define DOMAIN_JUMP_SIZE 2
100 #define DOMAIN_JUMP 0xc000
101 
102 static u8_t mdns_netif_client_id;
103 static struct udp_pcb *mdns_pcb;
104 NETIF_DECLARE_EXT_CALLBACK(netif_callback)
105 
106 #define NETIF_TO_HOST(netif) (struct mdns_host*)(netif_get_client_data(netif, mdns_netif_client_id))
107 
108 #define TOPDOMAIN_LOCAL "local"
109 
110 #define REVERSE_PTR_TOPDOMAIN "arpa"
111 #define REVERSE_PTR_V4_DOMAIN "in-addr"
112 #define REVERSE_PTR_V6_DOMAIN "ip6"
113 
114 #define SRV_PRIORITY 0
115 #define SRV_WEIGHT   0
116 
117 /* Payload size allocated for each outgoing UDP packet */
118 #define OUTPACKET_SIZE 500
119 
120 /* Lookup from hostname -> IPv4 */
121 #define REPLY_HOST_A            0x01
122 /* Lookup from IPv4/v6 -> hostname */
123 #define REPLY_HOST_PTR_V4       0x02
124 /* Lookup from hostname -> IPv6 */
125 #define REPLY_HOST_AAAA         0x04
126 /* Lookup from hostname -> IPv6 */
127 #define REPLY_HOST_PTR_V6       0x08
128 
129 /* Lookup for service types */
130 #define REPLY_SERVICE_TYPE_PTR  0x10
131 /* Lookup for instances of service */
132 #define REPLY_SERVICE_NAME_PTR  0x20
133 /* Lookup for location of service instance */
134 #define REPLY_SERVICE_SRV       0x40
135 /* Lookup for text info on service instance */
136 #define REPLY_SERVICE_TXT       0x80
137 
138 static const char *dnssd_protos[] = {
139     "_udp", /* DNSSD_PROTO_UDP */
140     "_tcp", /* DNSSD_PROTO_TCP */
141 };
142 
143 /** Description of a service */
144 struct mdns_service {
145   /** TXT record to answer with */
146   struct mdns_domain txtdata;
147   /** Name of service, like 'myweb' */
148   char name[MDNS_LABEL_MAXLEN + 1];
149   /** Type of service, like '_http' */
150   char service[MDNS_LABEL_MAXLEN + 1];
151   /** Callback function and userdata
152    * to update txtdata buffer */
153   service_get_txt_fn_t txt_fn;
154   void *txt_userdata;
155   /** TTL in seconds of SRV/TXT replies */
156   u32_t dns_ttl;
157   /** Protocol, TCP or UDP */
158   u16_t proto;
159   /** Port of the service */
160   u16_t port;
161 };
162 
163 /** Description of a host/netif */
164 struct mdns_host {
165   /** Hostname */
166   char name[MDNS_LABEL_MAXLEN + 1];
167   /** Pointer to services */
168   struct mdns_service *services[MDNS_MAX_SERVICES];
169   /** TTL in seconds of A/AAAA/PTR replies */
170   u32_t dns_ttl;
171 };
172 
173 /** Information about received packet */
174 struct mdns_packet {
175   /** Sender IP/port */
176   ip_addr_t source_addr;
177   u16_t source_port;
178   /** If packet was received unicast */
179   u16_t recv_unicast;
180   /** Netif that received the packet */
181   struct netif *netif;
182   /** Packet data */
183   struct pbuf *pbuf;
184   /** Current parsing offset in packet */
185   u16_t parse_offset;
186   /** Identifier. Used in legacy queries */
187   u16_t tx_id;
188   /** Number of questions in packet,
189    *  read from packet header */
190   u16_t questions;
191   /** Number of unparsed questions */
192   u16_t questions_left;
193   /** Number of answers in packet,
194    *  (sum of normal, authorative and additional answers)
195    *  read from packet header */
196   u16_t answers;
197   /** Number of unparsed answers */
198   u16_t answers_left;
199 };
200 
201 /** Information about outgoing packet */
202 struct mdns_outpacket {
203   /** Netif to send the packet on */
204   struct netif *netif;
205   /** Packet data */
206   struct pbuf *pbuf;
207   /** Current write offset in packet */
208   u16_t write_offset;
209   /** Identifier. Used in legacy queries */
210   u16_t tx_id;
211   /** Destination IP/port if sent unicast */
212   ip_addr_t dest_addr;
213   u16_t dest_port;
214   /** Number of questions written */
215   u16_t questions;
216   /** Number of normal answers written */
217   u16_t answers;
218   /** Number of additional answers written */
219   u16_t additional;
220   /** Offsets for written domain names in packet.
221    *  Used for compression */
222   u16_t domain_offsets[NUM_DOMAIN_OFFSETS];
223   /** If all answers in packet should set cache_flush bit */
224   u8_t cache_flush;
225   /** If reply should be sent unicast */
226   u8_t unicast_reply;
227   /** If legacy query. (tx_id needed, and write
228    *  question again in reply before answer) */
229   u8_t legacy_query;
230   /* Reply bitmask for host information */
231   u8_t host_replies;
232   /* Bitmask for which reverse IPv6 hosts to answer */
233   u8_t host_reverse_v6_replies;
234   /* Reply bitmask per service */
235   u8_t serv_replies[MDNS_MAX_SERVICES];
236 };
237 
238 /** Domain, type and class.
239  *  Shared between questions and answers */
240 struct mdns_rr_info {
241   struct mdns_domain domain;
242   u16_t type;
243   u16_t klass;
244 };
245 
246 struct mdns_question {
247   struct mdns_rr_info info;
248   /** unicast reply requested */
249   u16_t unicast;
250 };
251 
252 struct mdns_answer {
253   struct mdns_rr_info info;
254   /** cache flush command bit */
255   u16_t cache_flush;
256   /* Validity time in seconds */
257   u32_t ttl;
258   /** Length of variable answer */
259   u16_t rd_length;
260   /** Offset of start of variable answer in packet */
261   u16_t rd_offset;
262 };
263 
264 /**
265  * Add a label part to a domain
266  * @param domain The domain to add a label to
267  * @param label The label to add, like &lt;hostname&gt;, 'local', 'com' or ''
268  * @param len The length of the label
269  * @return ERR_OK on success, an err_t otherwise if label too long
270  */
271 err_t
272 mdns_domain_add_label(struct mdns_domain *domain, const char *label, u8_t len)
273 {
274   if (len > MDNS_LABEL_MAXLEN) {
275     return ERR_VAL;
276   }
277   if (len > 0 && (1 + len + domain->length >= MDNS_DOMAIN_MAXLEN)) {
278     return ERR_VAL;
279   }
280   /* Allow only zero marker on last byte */
281   if (len == 0 && (1 + domain->length > MDNS_DOMAIN_MAXLEN)) {
282     return ERR_VAL;
283   }
284   domain->name[domain->length] = len;
285   domain->length++;
286   if (len) {
287     MEMCPY(&domain->name[domain->length], label, len);
288     domain->length += len;
289   }
290   return ERR_OK;
291 }
292 
293 /**
294  * Internal readname function with max 6 levels of recursion following jumps
295  * while decompressing name
296  */
297 static u16_t
298 mdns_readname_loop(struct pbuf *p, u16_t offset, struct mdns_domain *domain, unsigned depth)
299 {
300   u8_t c;
301 
302   do {
303     if (depth > 5) {
304       /* Too many jumps */
305       return MDNS_READNAME_ERROR;
306     }
307 
308     c = pbuf_get_at(p, offset);
309     offset++;
310 
311     /* is this a compressed label? */
312     if((c & 0xc0) == 0xc0) {
313       u16_t jumpaddr;
314       if (offset >= p->tot_len) {
315         /* Make sure both jump bytes fit in the packet */
316         return MDNS_READNAME_ERROR;
317       }
318       jumpaddr = (((c & 0x3f) << 8) | (pbuf_get_at(p, offset) & 0xff));
319       offset++;
320       if (jumpaddr >= SIZEOF_DNS_HDR && jumpaddr < p->tot_len) {
321         u16_t res;
322       /* Recursive call, maximum depth will be checked */
323         res = mdns_readname_loop(p, jumpaddr, domain, depth + 1);
324         /* Dont return offset since new bytes were not read (jumped to somewhere in packet) */
325         if (res == MDNS_READNAME_ERROR) {
326           return res;
327         }
328       } else {
329         return MDNS_READNAME_ERROR;
330       }
331       break;
332     }
333 
334     /* normal label */
335     if (c <= MDNS_LABEL_MAXLEN) {
336       u8_t label[MDNS_LABEL_MAXLEN];
337       err_t res;
338 
339       if (c + domain->length >= MDNS_DOMAIN_MAXLEN) {
340         return MDNS_READNAME_ERROR;
341       }
342       if (c != 0) {
343         if (pbuf_copy_partial(p, label, c, offset) != c) {
344           return MDNS_READNAME_ERROR;
345         }
346         offset += c;
347       }
348       res = mdns_domain_add_label(domain, (char *) label, c);
349       if (res != ERR_OK) {
350         return MDNS_READNAME_ERROR;
351       }
352     } else {
353       /* bad length byte */
354       return MDNS_READNAME_ERROR;
355     }
356   } while (c != 0);
357 
358   return offset;
359 }
360 
361 /**
362  * Read possibly compressed domain name from packet buffer
363  * @param p The packet
364  * @param offset start position of domain name in packet
365  * @param domain The domain name destination
366  * @return The new offset after the domain, or MDNS_READNAME_ERROR
367  *         if reading failed
368  */
369 u16_t
370 mdns_readname(struct pbuf *p, u16_t offset, struct mdns_domain *domain)
371 {
372   memset(domain, 0, sizeof(struct mdns_domain));
373   return mdns_readname_loop(p, offset, domain, 0);
374 }
375 
376 /**
377  * Print domain name to debug output
378  * @param domain The domain name
379  */
380 static void
381 mdns_domain_debug_print(struct mdns_domain *domain)
382 {
383   u8_t *src = domain->name;
384   u8_t i;
385 
386   while (*src) {
387     u8_t label_len = *src;
388     src++;
389     for (i = 0; i < label_len; i++) {
390       LWIP_DEBUGF(MDNS_DEBUG, ("%c", src[i]));
391     }
392     src += label_len;
393     LWIP_DEBUGF(MDNS_DEBUG, ("."));
394   }
395 }
396 
397 /**
398  * Return 1 if contents of domains match (case-insensitive)
399  * @param a Domain name to compare 1
400  * @param b Domain name to compare 2
401  * @return 1 if domains are equal ignoring case, 0 otherwise
402  */
403 int
404 mdns_domain_eq(struct mdns_domain *a, struct mdns_domain *b)
405 {
406   u8_t *ptra, *ptrb;
407   u8_t len;
408   int res;
409 
410   if (a->length != b->length) {
411     return 0;
412   }
413 
414   ptra = a->name;
415   ptrb = b->name;
416   while (*ptra && *ptrb && ptra < &a->name[a->length]) {
417     if (*ptra != *ptrb) {
418       return 0;
419     }
420     len = *ptra;
421     ptra++;
422     ptrb++;
423     res = lwip_strnicmp((char *) ptra, (char *) ptrb, len);
424     if (res != 0) {
425       return 0;
426     }
427     ptra += len;
428     ptrb += len;
429   }
430   if (*ptra != *ptrb && ptra < &a->name[a->length]) {
431     return 0;
432   }
433   return 1;
434 }
435 
436 /**
437  * Call user supplied function to setup TXT data
438  * @param service The service to build TXT record for
439  */
440 static void
441 mdns_prepare_txtdata(struct mdns_service *service)
442 {
443   memset(&service->txtdata, 0, sizeof(struct mdns_domain));
444   if (service->txt_fn) {
445     service->txt_fn(service, service->txt_userdata);
446   }
447 }
448 
449 #if LWIP_IPV4
450 /**
451  * Build domain for reverse lookup of IPv4 address
452  * like 12.0.168.192.in-addr.arpa. for 192.168.0.12
453  * @param domain Where to write the domain name
454  * @param addr Pointer to an IPv4 address to encode
455  * @return ERR_OK if domain was written, an err_t otherwise
456  */
457 static err_t
458 mdns_build_reverse_v4_domain(struct mdns_domain *domain, const ip4_addr_t *addr)
459 {
460   int i;
461   err_t res;
462   const u8_t *ptr;
463   if (!domain || !addr) {
464     return ERR_ARG;
465   }
466   memset(domain, 0, sizeof(struct mdns_domain));
467   ptr = (const u8_t *) addr;
468   for (i = sizeof(ip4_addr_t) - 1; i >= 0; i--) {
469     char buf[4];
470     u8_t val = ptr[i];
471 
472     lwip_itoa(buf, sizeof(buf), val);
473     res = mdns_domain_add_label(domain, buf, (u8_t)strlen(buf));
474     LWIP_ERROR("mdns_build_reverse_v4_domain: Failed to add label", (res == ERR_OK), return res);
475   }
476   res = mdns_domain_add_label(domain, REVERSE_PTR_V4_DOMAIN, (u8_t)(sizeof(REVERSE_PTR_V4_DOMAIN)-1));
477   LWIP_ERROR("mdns_build_reverse_v4_domain: Failed to add label", (res == ERR_OK), return res);
478   res = mdns_domain_add_label(domain, REVERSE_PTR_TOPDOMAIN, (u8_t)(sizeof(REVERSE_PTR_TOPDOMAIN)-1));
479   LWIP_ERROR("mdns_build_reverse_v4_domain: Failed to add label", (res == ERR_OK), return res);
480   res = mdns_domain_add_label(domain, NULL, 0);
481   LWIP_ERROR("mdns_build_reverse_v4_domain: Failed to add label", (res == ERR_OK), return res);
482 
483   return ERR_OK;
484 }
485 #endif
486 
487 #if LWIP_IPV6
488 /**
489  * Build domain for reverse lookup of IP address
490  * like b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. for 2001:db8::567:89ab
491  * @param domain Where to write the domain name
492  * @param addr Pointer to an IPv6 address to encode
493  * @return ERR_OK if domain was written, an err_t otherwise
494  */
495 static err_t
496 mdns_build_reverse_v6_domain(struct mdns_domain *domain, const ip6_addr_t *addr)
497 {
498   int i;
499   err_t res;
500   const u8_t *ptr;
501   if (!domain || !addr) {
502     return ERR_ARG;
503   }
504   memset(domain, 0, sizeof(struct mdns_domain));
505   ptr = (const u8_t *) addr;
506   for (i = sizeof(ip6_addr_t) - 1; i >= 0; i--) {
507     char buf;
508     u8_t byte = ptr[i];
509     int j;
510     for (j = 0; j < 2; j++) {
511       if ((byte & 0x0F) < 0xA) {
512         buf = '0' + (byte & 0x0F);
513       } else {
514         buf = 'a' + (byte & 0x0F) - 0xA;
515       }
516       res = mdns_domain_add_label(domain, &buf, sizeof(buf));
517       LWIP_ERROR("mdns_build_reverse_v6_domain: Failed to add label", (res == ERR_OK), return res);
518       byte >>= 4;
519     }
520   }
521   res = mdns_domain_add_label(domain, REVERSE_PTR_V6_DOMAIN, (u8_t)(sizeof(REVERSE_PTR_V6_DOMAIN)-1));
522   LWIP_ERROR("mdns_build_reverse_v6_domain: Failed to add label", (res == ERR_OK), return res);
523   res = mdns_domain_add_label(domain, REVERSE_PTR_TOPDOMAIN, (u8_t)(sizeof(REVERSE_PTR_TOPDOMAIN)-1));
524   LWIP_ERROR("mdns_build_reverse_v6_domain: Failed to add label", (res == ERR_OK), return res);
525   res = mdns_domain_add_label(domain, NULL, 0);
526   LWIP_ERROR("mdns_build_reverse_v6_domain: Failed to add label", (res == ERR_OK), return res);
527 
528   return ERR_OK;
529 }
530 #endif
531 
532 /* Add .local. to domain */
533 static err_t
534 mdns_add_dotlocal(struct mdns_domain *domain)
535 {
536   err_t res = mdns_domain_add_label(domain, TOPDOMAIN_LOCAL, (u8_t)(sizeof(TOPDOMAIN_LOCAL)-1));
537   LWIP_ERROR("mdns_add_dotlocal: Failed to add label", (res == ERR_OK), return res);
538   return mdns_domain_add_label(domain, NULL, 0);
539 }
540 
541 /**
542  * Build the <hostname>.local. domain name
543  * @param domain Where to write the domain name
544  * @param mdns TMDNS netif descriptor.
545  * @return ERR_OK if domain <hostname>.local. was written, an err_t otherwise
546  */
547 static err_t
548 mdns_build_host_domain(struct mdns_domain *domain, struct mdns_host *mdns)
549 {
550   err_t res;
551   memset(domain, 0, sizeof(struct mdns_domain));
552   LWIP_ERROR("mdns_build_host_domain: mdns != NULL", (mdns != NULL), return ERR_VAL);
553   res = mdns_domain_add_label(domain, mdns->name, (u8_t)strlen(mdns->name));
554   LWIP_ERROR("mdns_build_host_domain: Failed to add label", (res == ERR_OK), return res);
555   return mdns_add_dotlocal(domain);
556 }
557 
558 /**
559  * Build the lookup-all-services special DNS-SD domain name
560  * @param domain Where to write the domain name
561  * @return ERR_OK if domain _services._dns-sd._udp.local. was written, an err_t otherwise
562  */
563 static err_t
564 mdns_build_dnssd_domain(struct mdns_domain *domain)
565 {
566   err_t res;
567   memset(domain, 0, sizeof(struct mdns_domain));
568   res = mdns_domain_add_label(domain, "_services", (u8_t)(sizeof("_services")-1));
569   LWIP_ERROR("mdns_build_dnssd_domain: Failed to add label", (res == ERR_OK), return res);
570   res = mdns_domain_add_label(domain, "_dns-sd", (u8_t)(sizeof("_dns-sd")-1));
571   LWIP_ERROR("mdns_build_dnssd_domain: Failed to add label", (res == ERR_OK), return res);
572   res = mdns_domain_add_label(domain, dnssd_protos[DNSSD_PROTO_UDP], (u8_t)strlen(dnssd_protos[DNSSD_PROTO_UDP]));
573   LWIP_ERROR("mdns_build_dnssd_domain: Failed to add label", (res == ERR_OK), return res);
574   return mdns_add_dotlocal(domain);
575 }
576 
577 /**
578  * Build domain name for a service
579  * @param domain Where to write the domain name
580  * @param service The service struct, containing service name, type and protocol
581  * @param include_name Whether to include the service name in the domain
582  * @return ERR_OK if domain was written. If service name is included,
583  *         <name>.<type>.<proto>.local. will be written, otherwise <type>.<proto>.local.
584  *         An err_t is returned on error.
585  */
586 static err_t
587 mdns_build_service_domain(struct mdns_domain *domain, struct mdns_service *service, int include_name)
588 {
589   err_t res;
590   memset(domain, 0, sizeof(struct mdns_domain));
591   if (include_name) {
592     res = mdns_domain_add_label(domain, service->name, (u8_t)strlen(service->name));
593     LWIP_ERROR("mdns_build_service_domain: Failed to add label", (res == ERR_OK), return res);
594   }
595   res = mdns_domain_add_label(domain, service->service, (u8_t)strlen(service->service));
596   LWIP_ERROR("mdns_build_service_domain: Failed to add label", (res == ERR_OK), return res);
597   res = mdns_domain_add_label(domain, dnssd_protos[service->proto], (u8_t)strlen(dnssd_protos[service->proto]));
598   LWIP_ERROR("mdns_build_service_domain: Failed to add label", (res == ERR_OK), return res);
599   return mdns_add_dotlocal(domain);
600 }
601 
602 /**
603  * Check which replies we should send for a host/netif based on question
604  * @param netif The network interface that received the question
605  * @param rr Domain/type/class from a question
606  * @param reverse_v6_reply Bitmask of which IPv6 addresses to send reverse PTRs for
607  *                         if reply bit has REPLY_HOST_PTR_V6 set
608  * @return Bitmask of which replies to send
609  */
610 static int
611 check_host(struct netif *netif, struct mdns_rr_info *rr, u8_t *reverse_v6_reply)
612 {
613   err_t res;
614   int replies = 0;
615   struct mdns_domain mydomain;
616 
617   LWIP_UNUSED_ARG(reverse_v6_reply); /* if ipv6 is disabled */
618 
619   if (rr->klass != DNS_RRCLASS_IN && rr->klass != DNS_RRCLASS_ANY) {
620     /* Invalid class */
621     return replies;
622   }
623 
624   /* Handle PTR for our addresses */
625   if (rr->type == DNS_RRTYPE_PTR || rr->type == DNS_RRTYPE_ANY) {
626 #if LWIP_IPV6
627     int i;
628     for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
629       if (ip6_addr_isvalid(netif_ip6_addr_state(netif, i))) {
630         res = mdns_build_reverse_v6_domain(&mydomain, netif_ip6_addr(netif, i));
631         if (res == ERR_OK && mdns_domain_eq(&rr->domain, &mydomain)) {
632           replies |= REPLY_HOST_PTR_V6;
633           /* Mark which addresses where requested */
634           if (reverse_v6_reply) {
635             *reverse_v6_reply |= (1 << i);
636           }
637         }
638       }
639     }
640 #endif
641 #if LWIP_IPV4
642     if (!ip4_addr_isany_val(*netif_ip4_addr(netif))) {
643       res = mdns_build_reverse_v4_domain(&mydomain, netif_ip4_addr(netif));
644       if (res == ERR_OK && mdns_domain_eq(&rr->domain, &mydomain)) {
645         replies |= REPLY_HOST_PTR_V4;
646       }
647     }
648 #endif
649   }
650 
651   res = mdns_build_host_domain(&mydomain, NETIF_TO_HOST(netif));
652   /* Handle requests for our hostname */
653   if (res == ERR_OK && mdns_domain_eq(&rr->domain, &mydomain)) {
654     /* TODO return NSEC if unsupported protocol requested */
655 #if LWIP_IPV4
656     if (!ip4_addr_isany_val(*netif_ip4_addr(netif))
657         && (rr->type == DNS_RRTYPE_A || rr->type == DNS_RRTYPE_ANY)) {
658       replies |= REPLY_HOST_A;
659     }
660 #endif
661 #if LWIP_IPV6
662     if (rr->type == DNS_RRTYPE_AAAA || rr->type == DNS_RRTYPE_ANY) {
663       replies |= REPLY_HOST_AAAA;
664     }
665 #endif
666   }
667 
668   return replies;
669 }
670 
671 /**
672  * Check which replies we should send for a service based on question
673  * @param service A registered MDNS service
674  * @param rr Domain/type/class from a question
675  * @return Bitmask of which replies to send
676  */
677 static int
678 check_service(struct mdns_service *service, struct mdns_rr_info *rr)
679 {
680   err_t res;
681   int replies = 0;
682   struct mdns_domain mydomain;
683 
684   if (rr->klass != DNS_RRCLASS_IN && rr->klass != DNS_RRCLASS_ANY) {
685     /* Invalid class */
686     return 0;
687   }
688 
689   res = mdns_build_dnssd_domain(&mydomain);
690   if (res == ERR_OK && mdns_domain_eq(&rr->domain, &mydomain) &&
691       (rr->type == DNS_RRTYPE_PTR || rr->type == DNS_RRTYPE_ANY)) {
692     /* Request for all service types */
693     replies |= REPLY_SERVICE_TYPE_PTR;
694   }
695 
696   res = mdns_build_service_domain(&mydomain, service, 0);
697   if (res == ERR_OK && mdns_domain_eq(&rr->domain, &mydomain) &&
698       (rr->type == DNS_RRTYPE_PTR || rr->type == DNS_RRTYPE_ANY)) {
699     /* Request for the instance of my service */
700     replies |= REPLY_SERVICE_NAME_PTR;
701   }
702 
703   res = mdns_build_service_domain(&mydomain, service, 1);
704   if (res == ERR_OK && mdns_domain_eq(&rr->domain, &mydomain)) {
705     /* Request for info about my service */
706     if (rr->type == DNS_RRTYPE_SRV || rr->type == DNS_RRTYPE_ANY) {
707       replies |= REPLY_SERVICE_SRV;
708     }
709     if (rr->type == DNS_RRTYPE_TXT || rr->type == DNS_RRTYPE_ANY) {
710       replies |= REPLY_SERVICE_TXT;
711     }
712   }
713 
714   return replies;
715 }
716 
717 /**
718  * Return bytes needed to write before jump for best result of compressing supplied domain
719  * against domain in outpacket starting at specified offset.
720  * If a match is found, offset is updated to where to jump to
721  * @param pbuf Pointer to pbuf with the partially constructed DNS packet
722  * @param offset Start position of a domain written earlier. If this location is suitable
723  *               for compression, the pointer is updated to where in the domain to jump to.
724  * @param domain The domain to write
725  * @return Number of bytes to write of the new domain before writing a jump to the offset.
726  *         If compression can not be done against this previous domain name, the full new
727  *         domain length is returned.
728  */
729 u16_t
730 mdns_compress_domain(struct pbuf *pbuf, u16_t *offset, struct mdns_domain *domain)
731 {
732   struct mdns_domain target;
733   u16_t target_end;
734   u8_t target_len;
735   u8_t writelen = 0;
736   u8_t *ptr;
737   if (pbuf == NULL) {
738     return domain->length;
739   }
740   target_end = mdns_readname(pbuf, *offset, &target);
741   if (target_end == MDNS_READNAME_ERROR) {
742     return domain->length;
743   }
744   target_len = (u8_t)(target_end - *offset);
745   ptr = domain->name;
746   while (writelen < domain->length) {
747     u8_t domainlen = (u8_t)(domain->length - writelen);
748     u8_t labellen;
749     if (domainlen <= target.length && domainlen > DOMAIN_JUMP_SIZE) {
750       /* Compare domains if target is long enough, and we have enough left of the domain */
751       u8_t targetpos = (u8_t)(target.length - domainlen);
752       if ((targetpos + DOMAIN_JUMP_SIZE) >= target_len) {
753         /* We are checking at or beyond a jump in the original, stop looking */
754         break;
755       }
756       if (target.length >= domainlen &&
757           memcmp(&domain->name[writelen], &target.name[targetpos], domainlen) == 0) {
758         *offset += targetpos;
759         return writelen;
760       }
761     }
762     /* Skip to next label in domain */
763     labellen = *ptr;
764     writelen += 1 + labellen;
765     ptr += 1 + labellen;
766   }
767   /* Nothing found */
768   return domain->length;
769 }
770 
771 /**
772  * Write domain to outpacket. Compression will be attempted,
773  * unless domain->skip_compression is set.
774  * @param outpkt The outpacket to write to
775  * @param domain The domain name to write
776  * @return ERR_OK on success, an err_t otherwise
777  */
778 static err_t
779 mdns_write_domain(struct mdns_outpacket *outpkt, struct mdns_domain *domain)
780 {
781   int i;
782   err_t res;
783   u16_t writelen = domain->length;
784   u16_t jump_offset = 0;
785   u16_t jump;
786 
787   if (!domain->skip_compression) {
788     for (i = 0; i < NUM_DOMAIN_OFFSETS; ++i) {
789       u16_t offset = outpkt->domain_offsets[i];
790       if (offset) {
791         u16_t len = mdns_compress_domain(outpkt->pbuf, &offset, domain);
792         if (len < writelen) {
793           writelen = len;
794           jump_offset = offset;
795         }
796       }
797     }
798   }
799 
800   if (writelen) {
801     /* Write uncompressed part of name */
802     res = pbuf_take_at(outpkt->pbuf, domain->name, writelen, outpkt->write_offset);
803     if (res != ERR_OK) {
804       return res;
805     }
806 
807     /* Store offset of this new domain */
808     for (i = 0; i < NUM_DOMAIN_OFFSETS; ++i) {
809       if (outpkt->domain_offsets[i] == 0) {
810         outpkt->domain_offsets[i] = outpkt->write_offset;
811         break;
812       }
813     }
814 
815     outpkt->write_offset += writelen;
816   }
817   if (jump_offset) {
818     /* Write jump */
819     jump = lwip_htons(DOMAIN_JUMP | jump_offset);
820     res = pbuf_take_at(outpkt->pbuf, &jump, DOMAIN_JUMP_SIZE, outpkt->write_offset);
821     if (res != ERR_OK) {
822       return res;
823     }
824     outpkt->write_offset += DOMAIN_JUMP_SIZE;
825   }
826   return ERR_OK;
827 }
828 
829 /**
830  * Write a question to an outpacket
831  * A question contains domain, type and class. Since an answer also starts with these fields this function is also
832  * called from mdns_add_answer().
833  * @param outpkt The outpacket to write to
834  * @param domain The domain name the answer is for
835  * @param type The DNS type of the answer (like 'AAAA', 'SRV')
836  * @param klass The DNS type of the answer (like 'IN')
837  * @param unicast If highest bit in class should be set, to instruct the responder to
838  *                reply with a unicast packet
839  * @return ERR_OK on success, an err_t otherwise
840  */
841 static err_t
842 mdns_add_question(struct mdns_outpacket *outpkt, struct mdns_domain *domain, u16_t type, u16_t klass, u16_t unicast)
843 {
844   u16_t question_len;
845   u16_t field16;
846   err_t res;
847 
848   if (!outpkt->pbuf) {
849     /* If no pbuf is active, allocate one */
850     outpkt->pbuf = pbuf_alloc(PBUF_TRANSPORT, OUTPACKET_SIZE, PBUF_RAM);
851     if (!outpkt->pbuf) {
852       return ERR_MEM;
853     }
854     outpkt->write_offset = SIZEOF_DNS_HDR;
855   }
856 
857   /* Worst case calculation. Domain string might be compressed */
858   question_len = domain->length + sizeof(type) + sizeof(klass);
859   if (outpkt->write_offset + question_len > outpkt->pbuf->tot_len) {
860     /* No space */
861     return ERR_MEM;
862   }
863 
864   /* Write name */
865   res = mdns_write_domain(outpkt, domain);
866   if (res != ERR_OK) {
867     return res;
868   }
869 
870   /* Write type */
871   field16 = lwip_htons(type);
872   res = pbuf_take_at(outpkt->pbuf, &field16, sizeof(field16), outpkt->write_offset);
873   if (res != ERR_OK) {
874     return res;
875   }
876   outpkt->write_offset += sizeof(field16);
877 
878   /* Write class */
879   if (unicast) {
880     klass |= 0x8000;
881   }
882   field16 = lwip_htons(klass);
883   res = pbuf_take_at(outpkt->pbuf, &field16, sizeof(field16), outpkt->write_offset);
884   if (res != ERR_OK) {
885     return res;
886   }
887   outpkt->write_offset += sizeof(field16);
888 
889   return ERR_OK;
890 }
891 
892 /**
893  * Write answer to reply packet.
894  * buf or answer_domain can be null. The rd_length written will be buf_length +
895  * size of (compressed) domain. Most uses will need either buf or answer_domain,
896  * special case is SRV that starts with 3 u16 and then a domain name.
897  * @param reply The outpacket to write to
898  * @param domain The domain name the answer is for
899  * @param type The DNS type of the answer (like 'AAAA', 'SRV')
900  * @param klass The DNS type of the answer (like 'IN')
901  * @param cache_flush If highest bit in class should be set, to instruct receiver that
902  *                    this reply replaces any earlier answer for this domain/type/class
903  * @param ttl Validity time in seconds to send out for IP address data in DNS replies
904  * @param buf Pointer to buffer of answer data
905  * @param buf_length Length of variable data
906  * @param answer_domain A domain to write after any buffer data as answer
907  * @return ERR_OK on success, an err_t otherwise
908  */
909 static err_t
910 mdns_add_answer(struct mdns_outpacket *reply, struct mdns_domain *domain, u16_t type, u16_t klass, u16_t cache_flush,
911                 u32_t ttl, const u8_t *buf, size_t buf_length, struct mdns_domain *answer_domain)
912 {
913   u16_t answer_len;
914   u16_t field16;
915   u16_t rdlen_offset;
916   u16_t answer_offset;
917   u32_t field32;
918   err_t res;
919 
920   if (!reply->pbuf) {
921     /* If no pbuf is active, allocate one */
922     reply->pbuf = pbuf_alloc(PBUF_TRANSPORT, OUTPACKET_SIZE, PBUF_RAM);
923     if (!reply->pbuf) {
924       return ERR_MEM;
925     }
926     reply->write_offset = SIZEOF_DNS_HDR;
927   }
928 
929   /* Worst case calculation. Domain strings might be compressed */
930   answer_len = domain->length + sizeof(type) + sizeof(klass) + sizeof(ttl) + sizeof(field16)/*rd_length*/;
931   if (buf) {
932     answer_len += (u16_t)buf_length;
933   }
934   if (answer_domain) {
935     answer_len += answer_domain->length;
936   }
937   if (reply->write_offset + answer_len > reply->pbuf->tot_len) {
938     /* No space */
939     return ERR_MEM;
940   }
941 
942   /* Answer starts with same data as question, then more fields */
943   mdns_add_question(reply, domain, type, klass, cache_flush);
944 
945   /* Write TTL */
946   field32 = lwip_htonl(ttl);
947   res = pbuf_take_at(reply->pbuf, &field32, sizeof(field32), reply->write_offset);
948   if (res != ERR_OK) {
949     return res;
950   }
951   reply->write_offset += sizeof(field32);
952 
953   /* Store offsets and skip forward to the data */
954   rdlen_offset = reply->write_offset;
955   reply->write_offset += sizeof(field16);
956   answer_offset = reply->write_offset;
957 
958   if (buf) {
959     /* Write static data */
960     res = pbuf_take_at(reply->pbuf, buf, (u16_t)buf_length, reply->write_offset);
961     if (res != ERR_OK) {
962       return res;
963     }
964     reply->write_offset += (u16_t)buf_length;
965   }
966 
967   if (answer_domain) {
968     /* Write name answer (compressed if possible) */
969     res = mdns_write_domain(reply, answer_domain);
970     if (res != ERR_OK) {
971       return res;
972     }
973   }
974 
975   /* Write rd_length after when we know the answer size */
976   field16 = lwip_htons(reply->write_offset - answer_offset);
977   res = pbuf_take_at(reply->pbuf, &field16, sizeof(field16), rdlen_offset);
978 
979   return res;
980 }
981 
982 /**
983  * Helper function for mdns_read_question/mdns_read_answer
984  * Reads a domain, type and class from the packet
985  * @param pkt The MDNS packet to read from. The parse_offset field will be
986  *            incremented to point to the next unparsed byte.
987  * @param info The struct to fill with domain, type and class
988  * @return ERR_OK on success, an err_t otherwise
989  */
990 static err_t
991 mdns_read_rr_info(struct mdns_packet *pkt, struct mdns_rr_info *info)
992 {
993   u16_t field16, copied;
994   pkt->parse_offset = mdns_readname(pkt->pbuf, pkt->parse_offset, &info->domain);
995   if (pkt->parse_offset == MDNS_READNAME_ERROR) {
996     return ERR_VAL;
997   }
998 
999   copied = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), pkt->parse_offset);
1000   if (copied != sizeof(field16)) {
1001     return ERR_VAL;
1002   }
1003   pkt->parse_offset += copied;
1004   info->type = lwip_ntohs(field16);
1005 
1006   copied = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), pkt->parse_offset);
1007   if (copied != sizeof(field16)) {
1008     return ERR_VAL;
1009   }
1010   pkt->parse_offset += copied;
1011   info->klass = lwip_ntohs(field16);
1012 
1013   return ERR_OK;
1014 }
1015 
1016 /**
1017  * Read a question from the packet.
1018  * All questions have to be read before the answers.
1019  * @param pkt The MDNS packet to read from. The questions_left field will be decremented
1020  *            and the parse_offset will be updated.
1021  * @param question The struct to fill with question data
1022  * @return ERR_OK on success, an err_t otherwise
1023  */
1024 static err_t
1025 mdns_read_question(struct mdns_packet *pkt, struct mdns_question *question)
1026 {
1027   /* Safety check */
1028   if (pkt->pbuf->tot_len < pkt->parse_offset) {
1029     return ERR_VAL;
1030   }
1031 
1032   if (pkt->questions_left) {
1033     err_t res;
1034     pkt->questions_left--;
1035 
1036     memset(question, 0, sizeof(struct mdns_question));
1037     res = mdns_read_rr_info(pkt, &question->info);
1038     if (res != ERR_OK) {
1039       return res;
1040     }
1041 
1042     /* Extract unicast flag from class field */
1043     question->unicast = question->info.klass & 0x8000;
1044     question->info.klass &= 0x7FFF;
1045 
1046     return ERR_OK;
1047   }
1048   return ERR_VAL;
1049 }
1050 
1051 /**
1052  * Read an answer from the packet
1053  * The variable length reply is not copied, its pbuf offset and length is stored instead.
1054  * @param pkt The MDNS packet to read. The answers_left field will be decremented and
1055  *            the parse_offset will be updated.
1056  * @param answer The struct to fill with answer data
1057  * @return ERR_OK on success, an err_t otherwise
1058  */
1059 static err_t
1060 mdns_read_answer(struct mdns_packet *pkt, struct mdns_answer *answer)
1061 {
1062   /* Read questions first */
1063   if (pkt->questions_left) {
1064     return ERR_VAL;
1065   }
1066 
1067   /* Safety check */
1068   if (pkt->pbuf->tot_len < pkt->parse_offset) {
1069     return ERR_VAL;
1070   }
1071 
1072   if (pkt->answers_left) {
1073     u16_t copied, field16;
1074     u32_t ttl;
1075     err_t res;
1076     pkt->answers_left--;
1077 
1078     memset(answer, 0, sizeof(struct mdns_answer));
1079     res = mdns_read_rr_info(pkt, &answer->info);
1080     if (res != ERR_OK) {
1081       return res;
1082     }
1083 
1084     /* Extract cache_flush flag from class field */
1085     answer->cache_flush = answer->info.klass & 0x8000;
1086     answer->info.klass &= 0x7FFF;
1087 
1088     copied = pbuf_copy_partial(pkt->pbuf, &ttl, sizeof(ttl), pkt->parse_offset);
1089     if (copied != sizeof(ttl)) {
1090       return ERR_VAL;
1091     }
1092     pkt->parse_offset += copied;
1093     answer->ttl = lwip_ntohl(ttl);
1094 
1095     copied = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), pkt->parse_offset);
1096     if (copied != sizeof(field16)) {
1097       return ERR_VAL;
1098     }
1099     pkt->parse_offset += copied;
1100     answer->rd_length = lwip_ntohs(field16);
1101 
1102     answer->rd_offset = pkt->parse_offset;
1103     pkt->parse_offset += answer->rd_length;
1104 
1105     return ERR_OK;
1106   }
1107   return ERR_VAL;
1108 }
1109 
1110 #if LWIP_IPV4
1111 /** Write an IPv4 address (A) RR to outpacket */
1112 static err_t
1113 mdns_add_a_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct netif *netif)
1114 {
1115   struct mdns_domain host;
1116   mdns_build_host_domain(&host, NETIF_TO_HOST(netif));
1117   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with A record\n"));
1118   return mdns_add_answer(reply, &host, DNS_RRTYPE_A, DNS_RRCLASS_IN, cache_flush, (NETIF_TO_HOST(netif))->dns_ttl, (const u8_t *) netif_ip4_addr(netif), sizeof(ip4_addr_t), NULL);
1119 }
1120 
1121 /** Write a 4.3.2.1.in-addr.arpa -> hostname.local PTR RR to outpacket */
1122 static err_t
1123 mdns_add_hostv4_ptr_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct netif *netif)
1124 {
1125   struct mdns_domain host, revhost;
1126   mdns_build_host_domain(&host, NETIF_TO_HOST(netif));
1127   mdns_build_reverse_v4_domain(&revhost, netif_ip4_addr(netif));
1128   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with v4 PTR record\n"));
1129   return mdns_add_answer(reply, &revhost, DNS_RRTYPE_PTR, DNS_RRCLASS_IN, cache_flush, (NETIF_TO_HOST(netif))->dns_ttl, NULL, 0, &host);
1130 }
1131 #endif
1132 
1133 #if LWIP_IPV6
1134 /** Write an IPv6 address (AAAA) RR to outpacket */
1135 static err_t
1136 mdns_add_aaaa_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct netif *netif, int addrindex)
1137 {
1138   struct mdns_domain host;
1139   mdns_build_host_domain(&host, NETIF_TO_HOST(netif));
1140   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with AAAA record\n"));
1141   return mdns_add_answer(reply, &host, DNS_RRTYPE_AAAA, DNS_RRCLASS_IN, cache_flush, (NETIF_TO_HOST(netif))->dns_ttl, (const u8_t *) netif_ip6_addr(netif, addrindex), sizeof(ip6_addr_t), NULL);
1142 }
1143 
1144 /** Write a x.y.z.ip6.arpa -> hostname.local PTR RR to outpacket */
1145 static err_t
1146 mdns_add_hostv6_ptr_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct netif *netif, int addrindex)
1147 {
1148   struct mdns_domain host, revhost;
1149   mdns_build_host_domain(&host, NETIF_TO_HOST(netif));
1150   mdns_build_reverse_v6_domain(&revhost, netif_ip6_addr(netif, addrindex));
1151   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with v6 PTR record\n"));
1152   return mdns_add_answer(reply, &revhost, DNS_RRTYPE_PTR, DNS_RRCLASS_IN, cache_flush, (NETIF_TO_HOST(netif))->dns_ttl, NULL, 0, &host);
1153 }
1154 #endif
1155 
1156 /** Write an all-services -> servicetype PTR RR to outpacket */
1157 static err_t
1158 mdns_add_servicetype_ptr_answer(struct mdns_outpacket *reply, struct mdns_service *service)
1159 {
1160   struct mdns_domain service_type, service_dnssd;
1161   mdns_build_service_domain(&service_type, service, 0);
1162   mdns_build_dnssd_domain(&service_dnssd);
1163   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with service type PTR record\n"));
1164   return mdns_add_answer(reply, &service_dnssd, DNS_RRTYPE_PTR, DNS_RRCLASS_IN, 0, service->dns_ttl, NULL, 0, &service_type);
1165 }
1166 
1167 /** Write a servicetype -> servicename PTR RR to outpacket */
1168 static err_t
1169 mdns_add_servicename_ptr_answer(struct mdns_outpacket *reply, struct mdns_service *service)
1170 {
1171   struct mdns_domain service_type, service_instance;
1172   mdns_build_service_domain(&service_type, service, 0);
1173   mdns_build_service_domain(&service_instance, service, 1);
1174   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with service name PTR record\n"));
1175   return mdns_add_answer(reply, &service_type, DNS_RRTYPE_PTR, DNS_RRCLASS_IN, 0, service->dns_ttl, NULL, 0, &service_instance);
1176 }
1177 
1178 /** Write a SRV RR to outpacket */
1179 static err_t
1180 mdns_add_srv_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct mdns_host *mdns, struct mdns_service *service)
1181 {
1182   struct mdns_domain service_instance, srvhost;
1183   u16_t srvdata[3];
1184   mdns_build_service_domain(&service_instance, service, 1);
1185   mdns_build_host_domain(&srvhost, mdns);
1186   if (reply->legacy_query) {
1187     /* RFC 6762 section 18.14:
1188      * In legacy unicast responses generated to answer legacy queries,
1189      * name compression MUST NOT be performed on SRV records.
1190      */
1191     srvhost.skip_compression = 1;
1192   }
1193   srvdata[0] = lwip_htons(SRV_PRIORITY);
1194   srvdata[1] = lwip_htons(SRV_WEIGHT);
1195   srvdata[2] = lwip_htons(service->port);
1196   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with SRV record\n"));
1197   return mdns_add_answer(reply, &service_instance, DNS_RRTYPE_SRV, DNS_RRCLASS_IN, cache_flush, service->dns_ttl,
1198                          (const u8_t *) &srvdata, sizeof(srvdata), &srvhost);
1199 }
1200 
1201 /** Write a TXT RR to outpacket */
1202 static err_t
1203 mdns_add_txt_answer(struct mdns_outpacket *reply, u16_t cache_flush, struct mdns_service *service)
1204 {
1205   struct mdns_domain service_instance;
1206   mdns_build_service_domain(&service_instance, service, 1);
1207   mdns_prepare_txtdata(service);
1208   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Responding with TXT record\n"));
1209   return mdns_add_answer(reply, &service_instance, DNS_RRTYPE_TXT, DNS_RRCLASS_IN, cache_flush, service->dns_ttl,
1210                          (u8_t *) &service->txtdata.name, service->txtdata.length, NULL);
1211 }
1212 
1213 /**
1214  * Setup outpacket as a reply to the incoming packet
1215  */
1216 static void
1217 mdns_init_outpacket(struct mdns_outpacket *out, struct mdns_packet *in)
1218 {
1219   memset(out, 0, sizeof(struct mdns_outpacket));
1220   out->cache_flush = 1;
1221   out->netif = in->netif;
1222 
1223   /* Copy source IP/port to use when responding unicast, or to choose
1224    * which pcb to use for multicast (IPv4/IPv6)
1225    */
1226   SMEMCPY(&out->dest_addr, &in->source_addr, sizeof(ip_addr_t));
1227   out->dest_port = in->source_port;
1228 
1229   if (in->source_port != MDNS_PORT) {
1230     out->unicast_reply = 1;
1231     out->cache_flush = 0;
1232     if (in->questions == 1) {
1233       out->legacy_query = 1;
1234       out->tx_id = in->tx_id;
1235     }
1236   }
1237 
1238   if (in->recv_unicast) {
1239     out->unicast_reply = 1;
1240   }
1241 }
1242 
1243 /**
1244  * Send chosen answers as a reply
1245  *
1246  * Add all selected answers (first write will allocate pbuf)
1247  * Add additional answers based on the selected answers
1248  * Send the packet
1249  */
1250 static void
1251 mdns_send_outpacket(struct mdns_outpacket *outpkt)
1252 {
1253   struct mdns_service *service;
1254   err_t res;
1255   int i;
1256   struct mdns_host* mdns = NETIF_TO_HOST(outpkt->netif);
1257 
1258   /* Write answers to host questions */
1259 #if LWIP_IPV4
1260   if (outpkt->host_replies & REPLY_HOST_A) {
1261     res = mdns_add_a_answer(outpkt, outpkt->cache_flush, outpkt->netif);
1262     if (res != ERR_OK) {
1263       goto cleanup;
1264     }
1265     outpkt->answers++;
1266   }
1267   if (outpkt->host_replies & REPLY_HOST_PTR_V4) {
1268     res = mdns_add_hostv4_ptr_answer(outpkt, outpkt->cache_flush, outpkt->netif);
1269     if (res != ERR_OK) {
1270       goto cleanup;
1271     }
1272     outpkt->answers++;
1273   }
1274 #endif
1275 #if LWIP_IPV6
1276   if (outpkt->host_replies & REPLY_HOST_AAAA) {
1277     int addrindex;
1278     for (addrindex = 0; addrindex < LWIP_IPV6_NUM_ADDRESSES; ++addrindex) {
1279       if (ip6_addr_isvalid(netif_ip6_addr_state(outpkt->netif, addrindex))) {
1280         res = mdns_add_aaaa_answer(outpkt, outpkt->cache_flush, outpkt->netif, addrindex);
1281         if (res != ERR_OK) {
1282           goto cleanup;
1283         }
1284         outpkt->answers++;
1285       }
1286     }
1287   }
1288   if (outpkt->host_replies & REPLY_HOST_PTR_V6) {
1289     u8_t rev_addrs = outpkt->host_reverse_v6_replies;
1290     int addrindex = 0;
1291     while (rev_addrs) {
1292       if (rev_addrs & 1) {
1293         res = mdns_add_hostv6_ptr_answer(outpkt, outpkt->cache_flush, outpkt->netif, addrindex);
1294         if (res != ERR_OK) {
1295           goto cleanup;
1296         }
1297         outpkt->answers++;
1298       }
1299       addrindex++;
1300       rev_addrs >>= 1;
1301     }
1302   }
1303 #endif
1304 
1305   /* Write answers to service questions */
1306   for (i = 0; i < MDNS_MAX_SERVICES; ++i) {
1307     service = mdns->services[i];
1308     if (!service) {
1309       continue;
1310     }
1311 
1312     if (outpkt->serv_replies[i] & REPLY_SERVICE_TYPE_PTR) {
1313       res = mdns_add_servicetype_ptr_answer(outpkt, service);
1314       if (res != ERR_OK) {
1315         goto cleanup;
1316       }
1317       outpkt->answers++;
1318     }
1319 
1320     if (outpkt->serv_replies[i] & REPLY_SERVICE_NAME_PTR) {
1321       res = mdns_add_servicename_ptr_answer(outpkt, service);
1322       if (res != ERR_OK) {
1323         goto cleanup;
1324       }
1325       outpkt->answers++;
1326     }
1327 
1328     if (outpkt->serv_replies[i] & REPLY_SERVICE_SRV) {
1329       res = mdns_add_srv_answer(outpkt, outpkt->cache_flush, mdns, service);
1330       if (res != ERR_OK) {
1331         goto cleanup;
1332       }
1333       outpkt->answers++;
1334     }
1335 
1336     if (outpkt->serv_replies[i] & REPLY_SERVICE_TXT) {
1337       res = mdns_add_txt_answer(outpkt, outpkt->cache_flush, service);
1338       if (res != ERR_OK) {
1339         goto cleanup;
1340       }
1341       outpkt->answers++;
1342     }
1343   }
1344 
1345   /* All answers written, add additional RRs */
1346   for (i = 0; i < MDNS_MAX_SERVICES; ++i) {
1347     service = mdns->services[i];
1348     if (!service) {
1349       continue;
1350     }
1351 
1352     if (outpkt->serv_replies[i] & REPLY_SERVICE_NAME_PTR) {
1353       /* Our service instance requested, include SRV & TXT
1354        * if they are already not requested. */
1355       if (!(outpkt->serv_replies[i] & REPLY_SERVICE_SRV)) {
1356         res = mdns_add_srv_answer(outpkt, outpkt->cache_flush, mdns, service);
1357         if (res != ERR_OK) {
1358           goto cleanup;
1359         }
1360         outpkt->additional++;
1361       }
1362 
1363       if (!(outpkt->serv_replies[i] & REPLY_SERVICE_TXT)) {
1364         res = mdns_add_txt_answer(outpkt, outpkt->cache_flush, service);
1365         if (res != ERR_OK) {
1366           goto cleanup;
1367         }
1368         outpkt->additional++;
1369       }
1370     }
1371 
1372     /* If service instance, SRV, record or an IP address is requested,
1373      * supply all addresses for the host
1374      */
1375     if ((outpkt->serv_replies[i] & (REPLY_SERVICE_NAME_PTR | REPLY_SERVICE_SRV)) ||
1376         (outpkt->host_replies & (REPLY_HOST_A | REPLY_HOST_AAAA))) {
1377 #if LWIP_IPV6
1378       if (!(outpkt->host_replies & REPLY_HOST_AAAA)) {
1379         int addrindex;
1380         for (addrindex = 0; addrindex < LWIP_IPV6_NUM_ADDRESSES; ++addrindex) {
1381           if (ip6_addr_isvalid(netif_ip6_addr_state(outpkt->netif, addrindex))) {
1382             res = mdns_add_aaaa_answer(outpkt, outpkt->cache_flush, outpkt->netif, addrindex);
1383             if (res != ERR_OK) {
1384               goto cleanup;
1385             }
1386             outpkt->additional++;
1387           }
1388         }
1389       }
1390 #endif
1391 #if LWIP_IPV4
1392       if (!(outpkt->host_replies & REPLY_HOST_A)) {
1393         res = mdns_add_a_answer(outpkt, outpkt->cache_flush, outpkt->netif);
1394         if (res != ERR_OK) {
1395           goto cleanup;
1396         }
1397         outpkt->additional++;
1398       }
1399 #endif
1400     }
1401   }
1402 
1403   if (outpkt->pbuf) {
1404     const ip_addr_t *mcast_destaddr;
1405     struct dns_hdr hdr;
1406 
1407     /* Write header */
1408     memset(&hdr, 0, sizeof(hdr));
1409     hdr.flags1 = DNS_FLAG1_RESPONSE | DNS_FLAG1_AUTHORATIVE;
1410     hdr.numanswers = lwip_htons(outpkt->answers);
1411     hdr.numextrarr = lwip_htons(outpkt->additional);
1412     if (outpkt->legacy_query) {
1413       hdr.numquestions = lwip_htons(1);
1414       hdr.id = lwip_htons(outpkt->tx_id);
1415     }
1416     pbuf_take(outpkt->pbuf, &hdr, sizeof(hdr));
1417 
1418     /* Shrink packet */
1419     pbuf_realloc(outpkt->pbuf, outpkt->write_offset);
1420 
1421     if (IP_IS_V6_VAL(outpkt->dest_addr)) {
1422 #if LWIP_IPV6
1423       mcast_destaddr = &v6group;
1424 #endif
1425     } else {
1426 #if LWIP_IPV4
1427       mcast_destaddr = &v4group;
1428 #endif
1429     }
1430     /* Send created packet */
1431     LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Sending packet, len=%d, unicast=%d\n", outpkt->write_offset, outpkt->unicast_reply));
1432     if (outpkt->unicast_reply) {
1433       udp_sendto_if(mdns_pcb, outpkt->pbuf, &outpkt->dest_addr, outpkt->dest_port, outpkt->netif);
1434     } else {
1435       udp_sendto_if(mdns_pcb, outpkt->pbuf, mcast_destaddr, MDNS_PORT, outpkt->netif);
1436     }
1437   }
1438 
1439 cleanup:
1440   if (outpkt->pbuf) {
1441     pbuf_free(outpkt->pbuf);
1442     outpkt->pbuf = NULL;
1443   }
1444 }
1445 
1446 /**
1447  * Send unsolicited answer containing all our known data
1448  * @param netif The network interface to send on
1449  * @param destination The target address to send to (usually multicast address)
1450  */
1451 static void
1452 mdns_announce(struct netif *netif, const ip_addr_t *destination)
1453 {
1454   struct mdns_outpacket announce;
1455   int i;
1456   struct mdns_host* mdns = NETIF_TO_HOST(netif);
1457 
1458   memset(&announce, 0, sizeof(announce));
1459   announce.netif = netif;
1460   announce.cache_flush = 1;
1461 #if LWIP_IPV4
1462   if (!ip4_addr_isany_val(*netif_ip4_addr(netif)))
1463     announce.host_replies = REPLY_HOST_A | REPLY_HOST_PTR_V4;
1464 #endif
1465 #if LWIP_IPV6
1466   for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; ++i) {
1467     if (ip6_addr_isvalid(netif_ip6_addr_state(netif, i))) {
1468       announce.host_replies |= REPLY_HOST_AAAA | REPLY_HOST_PTR_V6;
1469       announce.host_reverse_v6_replies |= (1 << i);
1470     }
1471   }
1472 #endif
1473 
1474   for (i = 0; i < MDNS_MAX_SERVICES; i++) {
1475     struct mdns_service *serv = mdns->services[i];
1476     if (serv) {
1477       announce.serv_replies[i] = REPLY_SERVICE_TYPE_PTR | REPLY_SERVICE_NAME_PTR |
1478           REPLY_SERVICE_SRV | REPLY_SERVICE_TXT;
1479     }
1480   }
1481 
1482   announce.dest_port = MDNS_PORT;
1483   SMEMCPY(&announce.dest_addr, destination, sizeof(announce.dest_addr));
1484   mdns_send_outpacket(&announce);
1485 }
1486 
1487 /**
1488  * Handle question MDNS packet
1489  * 1. Parse all questions and set bits what answers to send
1490  * 2. Clear pending answers if known answers are supplied
1491  * 3. Put chosen answers in new packet and send as reply
1492  */
1493 static void
1494 mdns_handle_question(struct mdns_packet *pkt)
1495 {
1496   struct mdns_service *service;
1497   struct mdns_outpacket reply;
1498   int replies = 0;
1499   int i;
1500   err_t res;
1501   struct mdns_host* mdns = NETIF_TO_HOST(pkt->netif);
1502 
1503   mdns_init_outpacket(&reply, pkt);
1504 
1505   while (pkt->questions_left) {
1506     struct mdns_question q;
1507 
1508     res = mdns_read_question(pkt, &q);
1509     if (res != ERR_OK) {
1510       LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Failed to parse question, skipping query packet\n"));
1511       return;
1512     }
1513 
1514     LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Query for domain "));
1515     mdns_domain_debug_print(&q.info.domain);
1516     LWIP_DEBUGF(MDNS_DEBUG, (" type %d class %d\n", q.info.type, q.info.klass));
1517 
1518     if (q.unicast) {
1519       /* Reply unicast if any question is unicast */
1520       reply.unicast_reply = 1;
1521     }
1522 
1523     reply.host_replies |= check_host(pkt->netif, &q.info, &reply.host_reverse_v6_replies);
1524     replies |= reply.host_replies;
1525 
1526     for (i = 0; i < MDNS_MAX_SERVICES; ++i) {
1527       service = mdns->services[i];
1528       if (!service) {
1529         continue;
1530       }
1531       reply.serv_replies[i] |= check_service(service, &q.info);
1532       replies |= reply.serv_replies[i];
1533     }
1534 
1535     if (replies && reply.legacy_query) {
1536       /* Add question to reply packet (legacy packet only has 1 question) */
1537       res = mdns_add_question(&reply, &q.info.domain, q.info.type, q.info.klass, 0);
1538       if (res != ERR_OK) {
1539         goto cleanup;
1540       }
1541     }
1542   }
1543 
1544   /* Handle known answers */
1545   while (pkt->answers_left) {
1546     struct mdns_answer ans;
1547     u8_t rev_v6;
1548     int match;
1549 
1550     res = mdns_read_answer(pkt, &ans);
1551     if (res != ERR_OK) {
1552       LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Failed to parse answer, skipping query packet\n"));
1553       goto cleanup;
1554     }
1555 
1556     LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Known answer for domain "));
1557     mdns_domain_debug_print(&ans.info.domain);
1558     LWIP_DEBUGF(MDNS_DEBUG, (" type %d class %d\n", ans.info.type, ans.info.klass));
1559 
1560 
1561     if (ans.info.type == DNS_RRTYPE_ANY || ans.info.klass == DNS_RRCLASS_ANY) {
1562       /* Skip known answers for ANY type & class */
1563       continue;
1564     }
1565 
1566     rev_v6 = 0;
1567     match = reply.host_replies & check_host(pkt->netif, &ans.info, &rev_v6);
1568     if (match && (ans.ttl > (mdns->dns_ttl / 2))) {
1569       /* The RR in the known answer matches an RR we are planning to send,
1570        * and the TTL is less than half gone.
1571        * If the payload matches we should not send that answer.
1572        */
1573       if (ans.info.type == DNS_RRTYPE_PTR) {
1574         /* Read domain and compare */
1575         struct mdns_domain known_ans, my_ans;
1576         u16_t len;
1577         len = mdns_readname(pkt->pbuf, ans.rd_offset, &known_ans);
1578         res = mdns_build_host_domain(&my_ans, mdns);
1579         if (len != MDNS_READNAME_ERROR && res == ERR_OK && mdns_domain_eq(&known_ans, &my_ans)) {
1580 #if LWIP_IPV4
1581           if (match & REPLY_HOST_PTR_V4) {
1582               LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Skipping known answer: v4 PTR\n"));
1583               reply.host_replies &= ~REPLY_HOST_PTR_V4;
1584           }
1585 #endif
1586 #if LWIP_IPV6
1587           if (match & REPLY_HOST_PTR_V6) {
1588               LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Skipping known answer: v6 PTR\n"));
1589               reply.host_reverse_v6_replies &= ~rev_v6;
1590               if (reply.host_reverse_v6_replies == 0) {
1591                 reply.host_replies &= ~REPLY_HOST_PTR_V6;
1592               }
1593           }
1594 #endif
1595         }
1596       } else if (match & REPLY_HOST_A) {
1597 #if LWIP_IPV4
1598         if (ans.rd_length == sizeof(ip4_addr_t) &&
1599             pbuf_memcmp(pkt->pbuf, ans.rd_offset, netif_ip4_addr(pkt->netif), ans.rd_length) == 0) {
1600           LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Skipping known answer: A\n"));
1601           reply.host_replies &= ~REPLY_HOST_A;
1602         }
1603 #endif
1604       } else if (match & REPLY_HOST_AAAA) {
1605 #if LWIP_IPV6
1606         if (ans.rd_length == sizeof(ip6_addr_t) &&
1607             /* TODO this clears all AAAA responses if first addr is set as known */
1608             pbuf_memcmp(pkt->pbuf, ans.rd_offset, netif_ip6_addr(pkt->netif, 0), ans.rd_length) == 0) {
1609           LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Skipping known answer: AAAA\n"));
1610           reply.host_replies &= ~REPLY_HOST_AAAA;
1611         }
1612 #endif
1613       }
1614     }
1615 
1616     for (i = 0; i < MDNS_MAX_SERVICES; ++i) {
1617       service = mdns->services[i];
1618       if (!service) {
1619         continue;
1620       }
1621       match = reply.serv_replies[i] & check_service(service, &ans.info);
1622       if (match && (ans.ttl > (service->dns_ttl / 2))) {
1623         /* The RR in the known answer matches an RR we are planning to send,
1624          * and the TTL is less than half gone.
1625          * If the payload matches we should not send that answer.
1626          */
1627         if (ans.info.type == DNS_RRTYPE_PTR) {
1628           /* Read domain and compare */
1629           struct mdns_domain known_ans, my_ans;
1630           u16_t len;
1631           len = mdns_readname(pkt->pbuf, ans.rd_offset, &known_ans);
1632           if (len != MDNS_READNAME_ERROR) {
1633             if (match & REPLY_SERVICE_TYPE_PTR) {
1634               res = mdns_build_service_domain(&my_ans, service, 0);
1635               if (res == ERR_OK && mdns_domain_eq(&known_ans, &my_ans)) {
1636                 LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Skipping known answer: service type PTR\n"));
1637                 reply.serv_replies[i] &= ~REPLY_SERVICE_TYPE_PTR;
1638               }
1639             }
1640             if (match & REPLY_SERVICE_NAME_PTR) {
1641               res = mdns_build_service_domain(&my_ans, service, 1);
1642               if (res == ERR_OK && mdns_domain_eq(&known_ans, &my_ans)) {
1643                 LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Skipping known answer: service name PTR\n"));
1644                 reply.serv_replies[i] &= ~REPLY_SERVICE_NAME_PTR;
1645               }
1646             }
1647           }
1648         } else if (match & REPLY_SERVICE_SRV) {
1649           /* Read and compare to my SRV record */
1650           u16_t field16, len, read_pos;
1651           struct mdns_domain known_ans, my_ans;
1652           read_pos = ans.rd_offset;
1653           do {
1654             /* Check priority field */
1655             len = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), read_pos);
1656             if (len != sizeof(field16) || lwip_ntohs(field16) != SRV_PRIORITY) {
1657               break;
1658             }
1659             read_pos += len;
1660             /* Check weight field */
1661             len = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), read_pos);
1662             if (len != sizeof(field16) || lwip_ntohs(field16) != SRV_WEIGHT) {
1663               break;
1664             }
1665             read_pos += len;
1666             /* Check port field */
1667             len = pbuf_copy_partial(pkt->pbuf, &field16, sizeof(field16), read_pos);
1668             if (len != sizeof(field16) || lwip_ntohs(field16) != service->port) {
1669               break;
1670             }
1671             read_pos += len;
1672             /* Check host field */
1673             len = mdns_readname(pkt->pbuf, read_pos, &known_ans);
1674             mdns_build_host_domain(&my_ans, mdns);
1675             if (len == MDNS_READNAME_ERROR || !mdns_domain_eq(&known_ans, &my_ans)) {
1676               break;
1677             }
1678             LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Skipping known answer: SRV\n"));
1679             reply.serv_replies[i] &= ~REPLY_SERVICE_SRV;
1680           } while (0);
1681         } else if (match & REPLY_SERVICE_TXT) {
1682           mdns_prepare_txtdata(service);
1683           if (service->txtdata.length == ans.rd_length &&
1684               pbuf_memcmp(pkt->pbuf, ans.rd_offset, service->txtdata.name, ans.rd_length) == 0) {
1685             LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Skipping known answer: TXT\n"));
1686             reply.serv_replies[i] &= ~REPLY_SERVICE_TXT;
1687           }
1688         }
1689       }
1690     }
1691   }
1692 
1693   mdns_send_outpacket(&reply);
1694 
1695 cleanup:
1696   if (reply.pbuf) {
1697     /* This should only happen if we fail to alloc/write question for legacy query */
1698     pbuf_free(reply.pbuf);
1699     reply.pbuf = NULL;
1700   }
1701 }
1702 
1703 /**
1704  * Handle response MDNS packet
1705  * Only prints debug for now. Will need more code to do conflict resolution.
1706  */
1707 static void
1708 mdns_handle_response(struct mdns_packet *pkt)
1709 {
1710   /* Ignore all questions */
1711   while (pkt->questions_left) {
1712     struct mdns_question q;
1713     err_t res;
1714 
1715     res = mdns_read_question(pkt, &q);
1716     if (res != ERR_OK) {
1717       LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Failed to parse question, skipping response packet\n"));
1718       return;
1719     }
1720   }
1721 
1722   while (pkt->answers_left) {
1723     struct mdns_answer ans;
1724     err_t res;
1725 
1726     res = mdns_read_answer(pkt, &ans);
1727     if (res != ERR_OK) {
1728       LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Failed to parse answer, skipping response packet\n"));
1729       return;
1730     }
1731 
1732     LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Answer for domain "));
1733     mdns_domain_debug_print(&ans.info.domain);
1734     LWIP_DEBUGF(MDNS_DEBUG, (" type %d class %d\n", ans.info.type, ans.info.klass));
1735   }
1736 }
1737 
1738 /**
1739  * Receive input function for MDNS packets.
1740  * Handles both IPv4 and IPv6 UDP pcbs.
1741  */
1742 static void
1743 mdns_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
1744 {
1745   struct dns_hdr hdr;
1746   struct mdns_packet packet;
1747   struct netif *recv_netif = ip_current_input_netif();
1748   u16_t offset = 0;
1749 
1750   LWIP_UNUSED_ARG(arg);
1751   LWIP_UNUSED_ARG(pcb);
1752 
1753   LWIP_DEBUGF(MDNS_DEBUG, ("MDNS: Received IPv%d MDNS packet, len %d\n", IP_IS_V6(addr)? 6 : 4, p->tot_len));
1754 
1755   if (NETIF_TO_HOST(recv_netif) == NULL) {
1756     /* From netif not configured for MDNS */
1757     goto dealloc;
1758   }
1759 
1760   if (pbuf_copy_partial(p, &hdr, SIZEOF_DNS_HDR, offset) < SIZEOF_DNS_HDR) {
1761     /* Too small */
1762     goto dealloc;
1763   }
1764   offset += SIZEOF_DNS_HDR;
1765 
1766   if (DNS_HDR_GET_OPCODE(&hdr)) {
1767     /* Ignore non-standard queries in multicast packets (RFC 6762, section 18.3) */
1768     goto dealloc;
1769   }
1770 
1771   memset(&packet, 0, sizeof(packet));
1772   SMEMCPY(&packet.source_addr, addr, sizeof(packet.source_addr));
1773   packet.source_port = port;
1774   packet.netif = recv_netif;
1775   packet.pbuf = p;
1776   packet.parse_offset = offset;
1777   packet.tx_id = lwip_ntohs(hdr.id);
1778   packet.questions = packet.questions_left = lwip_ntohs(hdr.numquestions);
1779   packet.answers = packet.answers_left = lwip_ntohs(hdr.numanswers) + lwip_ntohs(hdr.numauthrr) + lwip_ntohs(hdr.numextrarr);
1780 
1781 #if LWIP_IPV6
1782   if (IP_IS_V6(ip_current_dest_addr())) {
1783     if (!ip_addr_cmp(ip_current_dest_addr(), &v6group)) {
1784       packet.recv_unicast = 1;
1785     }
1786   }
1787 #endif
1788 #if LWIP_IPV4
1789   if (!IP_IS_V6(ip_current_dest_addr())) {
1790     if (!ip_addr_cmp(ip_current_dest_addr(), &v4group)) {
1791       packet.recv_unicast = 1;
1792     }
1793   }
1794 #endif
1795 
1796   if (hdr.flags1 & DNS_FLAG1_RESPONSE) {
1797     mdns_handle_response(&packet);
1798   } else {
1799     mdns_handle_question(&packet);
1800   }
1801 
1802 dealloc:
1803   pbuf_free(p);
1804 }
1805 
1806 /**
1807  * @ingroup mdns
1808  * Announce IP settings have changed on netif.
1809  * Call this in your callback registered by netif_set_status_callback().
1810  * No need to call this function when LWIP_NETIF_EXT_STATUS_CALLBACK==1,
1811  * this handled automatically for you.
1812  * @param netif The network interface where settings have changed.
1813  */
1814 void
1815 mdns_resp_netif_settings_changed(struct netif *netif)
1816 {
1817   LWIP_ERROR("mdns_resp_netif_ip_changed: netif != NULL", (netif != NULL), return);
1818 
1819   if (NETIF_TO_HOST(netif) == NULL) {
1820     return;
1821   }
1822 
1823   /* Announce on IPv6 and IPv4 */
1824 #if LWIP_IPV6
1825   mdns_announce(netif, IP6_ADDR_ANY);
1826 #endif
1827 #if LWIP_IPV4
1828   mdns_announce(netif, IP4_ADDR_ANY);
1829 #endif
1830 }
1831 
1832 #if LWIP_NETIF_EXT_STATUS_CALLBACK
1833 static void
1834 mdns_netif_ext_status_callback(struct netif* netif, netif_nsc_reason_t reason, const netif_ext_callback_args_t* args)
1835 {
1836   LWIP_UNUSED_ARG(args);
1837 
1838   /* MDNS enabled on netif? */
1839   if (NETIF_TO_HOST(netif) == NULL) {
1840     return;
1841   }
1842 
1843   switch (reason)
1844   {
1845   case LWIP_NSC_STATUS_CHANGED:
1846     if (args->status_changed.state != 0) {
1847       mdns_resp_netif_settings_changed(netif);
1848     }
1849     /* TODO: send goodbye message */
1850     break;
1851   case LWIP_NSC_LINK_CHANGED:
1852     if (args->link_changed.state != 0) {
1853       mdns_resp_netif_settings_changed(netif);
1854     }
1855     break;
1856   case LWIP_NSC_IPV4_ADDRESS_CHANGED:  /* fall through */
1857   case LWIP_NSC_IPV4_GATEWAY_CHANGED:  /* fall through */
1858   case LWIP_NSC_IPV4_NETMASK_CHANGED:  /* fall through */
1859   case LWIP_NSC_IPV4_SETTINGS_CHANGED: /* fall through */
1860   case LWIP_NSC_IPV6_SET:              /* fall through */
1861   case LWIP_NSC_IPV6_ADDR_STATE_CHANGED:
1862     mdns_resp_netif_settings_changed(netif);
1863     break;
1864   default:
1865     break;
1866   }
1867 }
1868 #endif
1869 
1870 /**
1871  * @ingroup mdns
1872  * Activate MDNS responder for a network interface and send announce packets.
1873  * @param netif The network interface to activate.
1874  * @param hostname Name to use. Queries for &lt;hostname&gt;.local will be answered
1875  *                 with the IP addresses of the netif. The hostname will be copied, the
1876  *                 given pointer can be on the stack.
1877  * @param dns_ttl Validity time in seconds to send out for IP address data in DNS replies
1878  * @return ERR_OK if netif was added, an err_t otherwise
1879  */
1880 err_t
1881 mdns_resp_add_netif(struct netif *netif, const char *hostname, u32_t dns_ttl)
1882 {
1883   err_t res;
1884   struct mdns_host* mdns;
1885 
1886   LWIP_ERROR("mdns_resp_add_netif: netif != NULL", (netif != NULL), return ERR_VAL);
1887   LWIP_ERROR("mdns_resp_add_netif: Hostname too long", (strlen(hostname) <= MDNS_LABEL_MAXLEN), return ERR_VAL);
1888 
1889   LWIP_ASSERT("mdns_resp_add_netif: Double add", NETIF_TO_HOST(netif) == NULL);
1890   mdns = (struct mdns_host *) mem_malloc(sizeof(struct mdns_host));
1891   LWIP_ERROR("mdns_resp_add_netif: Alloc failed", (mdns != NULL), return ERR_MEM);
1892 
1893   netif_set_client_data(netif, mdns_netif_client_id, mdns);
1894 
1895   memset(mdns, 0, sizeof(struct mdns_host));
1896   MEMCPY(&mdns->name, hostname, LWIP_MIN(MDNS_LABEL_MAXLEN, strlen(hostname)));
1897   mdns->dns_ttl = dns_ttl;
1898 
1899   /* Join multicast groups */
1900 #if LWIP_IPV4
1901   res = igmp_joingroup_netif(netif, ip_2_ip4(&v4group));
1902   if (res != ERR_OK) {
1903     goto cleanup;
1904   }
1905 #endif
1906 #if LWIP_IPV6
1907   res = mld6_joingroup_netif(netif, ip_2_ip6(&v6group));
1908   if (res != ERR_OK) {
1909     goto cleanup;
1910   }
1911 #endif
1912 
1913   mdns_resp_netif_settings_changed(netif);
1914   return ERR_OK;
1915 
1916 cleanup:
1917   mem_free(mdns);
1918   netif_set_client_data(netif, mdns_netif_client_id, NULL);
1919   return res;
1920 }
1921 
1922 /**
1923  * @ingroup mdns
1924  * Stop responding to MDNS queries on this interface, leave multicast groups,
1925  * and free the helper structure and any of its services.
1926  * @param netif The network interface to remove.
1927  * @return ERR_OK if netif was removed, an err_t otherwise
1928  */
1929 err_t
1930 mdns_resp_remove_netif(struct netif *netif)
1931 {
1932   int i;
1933   struct mdns_host* mdns;
1934 
1935   LWIP_ASSERT("mdns_resp_remove_netif: Null pointer", netif);
1936   mdns = NETIF_TO_HOST(netif);
1937   LWIP_ERROR("mdns_resp_remove_netif: Not an active netif", (mdns != NULL), return ERR_VAL);
1938 
1939   for (i = 0; i < MDNS_MAX_SERVICES; i++) {
1940     struct mdns_service *service = mdns->services[i];
1941     if (service) {
1942       mem_free(service);
1943     }
1944   }
1945 
1946   /* Leave multicast groups */
1947 #if LWIP_IPV4
1948   igmp_leavegroup_netif(netif, ip_2_ip4(&v4group));
1949 #endif
1950 #if LWIP_IPV6
1951   mld6_leavegroup_netif(netif, ip_2_ip6(&v6group));
1952 #endif
1953 
1954   mem_free(mdns);
1955   netif_set_client_data(netif, mdns_netif_client_id, NULL);
1956   return ERR_OK;
1957 }
1958 
1959 /**
1960  * @ingroup mdns
1961  * Add a service to the selected network interface.
1962  * @param netif The network interface to publish this service on
1963  * @param name The name of the service
1964  * @param service The service type, like "_http"
1965  * @param proto The service protocol, DNSSD_PROTO_TCP for TCP ("_tcp") and DNSSD_PROTO_UDP
1966  *              for others ("_udp")
1967  * @param port The port the service listens to
1968  * @param dns_ttl Validity time in seconds to send out for service data in DNS replies
1969  * @param txt_fn Callback to get TXT data. Will be called each time a TXT reply is created to
1970  *               allow dynamic replies.
1971  * @param txt_data Userdata pointer for txt_fn
1972  * @return ERR_OK if the service was added to the netif, an err_t otherwise
1973  */
1974 err_t
1975 mdns_resp_add_service(struct netif *netif, const char *name, const char *service, enum mdns_sd_proto proto, u16_t port, u32_t dns_ttl, service_get_txt_fn_t txt_fn, void *txt_data)
1976 {
1977   int i;
1978   int slot = -1;
1979   struct mdns_service *srv;
1980   struct mdns_host* mdns;
1981 
1982   LWIP_ASSERT("mdns_resp_add_service: netif != NULL", netif);
1983   mdns = NETIF_TO_HOST(netif);
1984   LWIP_ERROR("mdns_resp_add_service: Not an mdns netif", (mdns != NULL), return ERR_VAL);
1985 
1986   LWIP_ERROR("mdns_resp_add_service: Name too long", (strlen(name) <= MDNS_LABEL_MAXLEN), return ERR_VAL);
1987   LWIP_ERROR("mdns_resp_add_service: Service too long", (strlen(service) <= MDNS_LABEL_MAXLEN), return ERR_VAL);
1988   LWIP_ERROR("mdns_resp_add_service: Bad proto (need TCP or UDP)", (proto == DNSSD_PROTO_TCP || proto == DNSSD_PROTO_UDP), return ERR_VAL);
1989 
1990   for (i = 0; i < MDNS_MAX_SERVICES; i++) {
1991     if (mdns->services[i] == NULL) {
1992       slot = i;
1993       break;
1994     }
1995   }
1996   LWIP_ERROR("mdns_resp_add_service: Service list full (increase MDNS_MAX_SERVICES)", (slot >= 0), return ERR_MEM);
1997 
1998   srv = (struct mdns_service*)mem_malloc(sizeof(struct mdns_service));
1999   LWIP_ERROR("mdns_resp_add_service: Alloc failed", (srv != NULL), return ERR_MEM);
2000 
2001   memset(srv, 0, sizeof(struct mdns_service));
2002 
2003   MEMCPY(&srv->name, name, LWIP_MIN(MDNS_LABEL_MAXLEN, strlen(name)));
2004   MEMCPY(&srv->service, service, LWIP_MIN(MDNS_LABEL_MAXLEN, strlen(service)));
2005   srv->txt_fn = txt_fn;
2006   srv->txt_userdata = txt_data;
2007   srv->proto = (u16_t)proto;
2008   srv->port = port;
2009   srv->dns_ttl = dns_ttl;
2010 
2011   mdns->services[slot] = srv;
2012 
2013   /* Announce on IPv6 and IPv4 */
2014 #if LWIP_IPV6
2015   mdns_announce(netif, IP6_ADDR_ANY);
2016 #endif
2017 #if LWIP_IPV4
2018   mdns_announce(netif, IP4_ADDR_ANY);
2019 #endif
2020 
2021   return ERR_OK;
2022 }
2023 
2024 /**
2025  * @ingroup mdns
2026  * Call this function from inside the service_get_txt_fn_t callback to add text data.
2027  * Buffer for TXT data is 256 bytes, and each field is prefixed with a length byte.
2028  * @param service The service provided to the get_txt callback
2029  * @param txt String to add to the TXT field.
2030  * @param txt_len Length of string
2031  * @return ERR_OK if the string was added to the reply, an err_t otherwise
2032  */
2033 err_t
2034 mdns_resp_add_service_txtitem(struct mdns_service *service, const char *txt, u8_t txt_len)
2035 {
2036   LWIP_ASSERT("mdns_resp_add_service_txtitem: service != NULL", service);
2037 
2038   /* Use a mdns_domain struct to store txt chunks since it is the same encoding */
2039   return mdns_domain_add_label(&service->txtdata, txt, txt_len);
2040 }
2041 
2042 /**
2043  * @ingroup mdns
2044  * Initiate MDNS responder. Will open UDP sockets on port 5353
2045  */
2046 void
2047 mdns_resp_init(void)
2048 {
2049   err_t res;
2050 
2051   mdns_pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
2052   LWIP_ASSERT("Failed to allocate pcb", mdns_pcb != NULL);
2053 #if LWIP_MULTICAST_TX_OPTIONS
2054   udp_set_multicast_ttl(mdns_pcb, MDNS_TTL);
2055 #else
2056   mdns_pcb->ttl = MDNS_TTL;
2057 #endif
2058   res = udp_bind(mdns_pcb, IP_ANY_TYPE, MDNS_PORT);
2059   LWIP_UNUSED_ARG(res); /* in case of LWIP_NOASSERT */
2060   LWIP_ASSERT("Failed to bind pcb", res == ERR_OK);
2061   udp_recv(mdns_pcb, mdns_recv, NULL);
2062 
2063   mdns_netif_client_id = netif_alloc_client_data_id();
2064 
2065   /* register for netif events when started on first netif */
2066   netif_add_ext_callback(&netif_callback, mdns_netif_ext_status_callback);
2067 }
2068 
2069 #endif /* LWIP_MDNS_RESPONDER */
2070