xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSCore/mDNSEmbeddedAPI.h (revision d48be21240dfd051b689384ce2b23479d757f2d8)
1 /*
2  * Copyright (c) 2002-2020 Apple Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15 
16    NOTE:
17    If you're building an application that uses DNS Service Discovery
18    this is probably NOT the header file you're looking for.
19    In most cases you will want to use /usr/include/dns_sd.h instead.
20 
21    This header file defines the lowest level raw interface to mDNSCore,
22    which is appropriate *only* on tiny embedded systems where everything
23    runs in a single address space and memory is extremely constrained.
24    All the APIs here are malloc-free, which means that the caller is
25    responsible for passing in a pointer to the relevant storage that
26    will be used in the execution of that call, and (when called with
27    correct parameters) all the calls are guaranteed to succeed. There
28    is never a case where a call can suffer intermittent failures because
29    the implementation calls malloc() and sometimes malloc() returns NULL
30    because memory is so limited that no more is available.
31    This is primarily for devices that need to have precisely known fixed
32    memory requirements, with absolutely no uncertainty or run-time variation,
33    but that certainty comes at a cost of more difficult programming.
34 
35    For applications running on general-purpose desktop operating systems
36    (Mac OS, Linux, Solaris, Windows, etc.) the API you should use is
37    /usr/include/dns_sd.h, which defines the API by which multiple
38    independent client processes communicate their DNS Service Discovery
39    requests to a single "mdnsd" daemon running in the background.
40 
41    Even on platforms that don't run multiple independent processes in
42    multiple independent address spaces, you can still use the preferred
43    dns_sd.h APIs by linking in "dnssd_clientshim.c", which implements
44    the standard "dns_sd.h" API calls, allocates any required storage
45    using malloc(), and then calls through to the low-level malloc-free
46    mDNSCore routines defined here. This has the benefit that even though
47    you're running on a small embedded system with a single address space,
48    you can still use the exact same client C code as you'd use on a
49    general-purpose desktop system.
50 
51  */
52 
53 #ifndef __mDNSEmbeddedAPI_h
54 #define __mDNSEmbeddedAPI_h
55 
56 #if defined(EFI32) || defined(EFI64) || defined(EFIX64)
57 // EFI doesn't have stdarg.h unless it's building with GCC.
58 #include "Tiano.h"
59 #if !defined(__GNUC__)
60 #define va_list         VA_LIST
61 #define va_start(a, b)  VA_START(a, b)
62 #define va_end(a)       VA_END(a)
63 #define va_arg(a, b)    VA_ARG(a, b)
64 #endif
65 #else
66 #include <stdarg.h>     // stdarg.h is required for for va_list support for the mDNS_vsnprintf declaration
67 #endif
68 
69 #if APPLE_OSX_mDNSResponder
70 #include <uuid/uuid.h>
71 #endif
72 
73 #include "mDNSFeatures.h"
74 #include "mDNSDebug.h"
75 
76 // ***************************************************************************
77 // Feature removal compile options & limited resource targets
78 
79 // The following compile options are responsible for removing certain features from mDNSCore to reduce the
80 // memory footprint for use in embedded systems with limited resources.
81 
82 // UNICAST_DISABLED - disables unicast DNS functionality, including Wide Area Bonjour
83 // SPC_DISABLED - disables Bonjour Sleep Proxy client
84 // IDLESLEEPCONTROL_DISABLED - disables sleep control for Bonjour Sleep Proxy clients
85 
86 // In order to disable the above features pass the option to your compiler, e.g. -D UNICAST_DISABLED
87 
88 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
89 #include <WebFilterDNS/WebFilterDNS.h>
90 #endif
91 
92 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
93 #include "dnssec_v2_embedded.h"
94 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
95 
96 // Additionally, the LIMITED_RESOURCES_TARGET compile option will reduce the maximum DNS message sizes.
97 
98 #ifdef LIMITED_RESOURCES_TARGET
99 // Don't support jumbo frames
100 // 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
101 #define AbsoluteMaxDNSMessageData   1440
102 // StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record (6 + 256 bytes)
103 #define MaximumRDSize               264
104 #endif
105 
106 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
107 #include "mdns_private.h"
108 #endif
109 
110 #ifdef __cplusplus
111 extern "C" {
112 #endif
113 
114 // ***************************************************************************
115 // Function scope indicators
116 
117 // If you see "mDNSlocal" before a function name in a C file, it means the function is not callable outside this file
118 #ifndef mDNSlocal
119 #define mDNSlocal static
120 #endif
121 // If you see "mDNSexport" before a symbol in a C file, it means the symbol is exported for use by clients
122 // For every "mDNSexport" in a C file, there needs to be a corresponding "extern" declaration in some header file
123 // (When a C file #includes a header file, the "extern" declarations tell the compiler:
124 // "This symbol exists -- but not necessarily in this C file.")
125 #ifndef mDNSexport
126 #define mDNSexport
127 #endif
128 
129 // Explanation: These local/export markers are a little habit of mine for signaling the programmers' intentions.
130 // When "mDNSlocal" is just a synonym for "static", and "mDNSexport" is a complete no-op, you could be
131 // forgiven for asking what purpose they serve. The idea is that if you see "mDNSexport" in front of a
132 // function definition it means the programmer intended it to be exported and callable from other files
133 // in the project. If you see "mDNSlocal" in front of a function definition it means the programmer
134 // intended it to be private to that file. If you see neither in front of a function definition it
135 // means the programmer forgot (so you should work out which it is supposed to be, and fix it).
136 // Using "mDNSlocal" instead of "static" makes it easier to do a textual searches for one or the other.
137 // For example you can do a search for "static" to find if any functions declare any local variables as "static"
138 // (generally a bad idea unless it's also "const", because static storage usually risks being non-thread-safe)
139 // without the results being cluttered with hundreds of matches for functions declared static.
140 // - Stuart Cheshire
141 
142 // ***************************************************************************
143 // Structure packing macro
144 
145 // If we're not using GNUC, it's not fatal.
146 // Most compilers naturally pack the on-the-wire structures correctly anyway, so a plain "struct" is usually fine.
147 // In the event that structures are not packed correctly, mDNS_Init() will detect this and report an error, so the
148 // developer will know what's wrong, and can investigate what needs to be done on that compiler to provide proper packing.
149 #ifndef packedstruct
150  #if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
151   #define packedstruct struct __attribute__((__packed__))
152   #define packedunion  union  __attribute__((__packed__))
153  #else
154   #define packedstruct struct
155   #define packedunion  union
156  #endif
157 #endif
158 
159 #ifndef fallthrough
160  #if __clang__
161   #if __has_c_attribute(fallthrough)
162    #define fallthrough() [[fallthrough]]
163   #else
164    #define fallthrough()
165   #endif
166  #elif __GNUC__
167   #define fallthrough() __attribute__((fallthrough))
168  #else
169   #define fallthrough()
170  #endif // __GNUC__
171 #endif // fallthrough
172 
173 // ***************************************************************************
174 #if 0
175 #pragma mark - DNS Resource Record class and type constants
176 #endif
177 
178 typedef enum                            // From RFC 1035
179 {
180     kDNSClass_IN               = 1,     // Internet
181     kDNSClass_CS               = 2,     // CSNET
182     kDNSClass_CH               = 3,     // CHAOS
183     kDNSClass_HS               = 4,     // Hesiod
184     kDNSClass_NONE             = 254,   // Used in DNS UPDATE [RFC 2136]
185 
186     kDNSClass_Mask             = 0x7FFF, // Multicast DNS uses the bottom 15 bits to identify the record class...
187     kDNSClass_UniqueRRSet      = 0x8000, // ... and the top bit indicates that all other cached records are now invalid
188 
189     kDNSQClass_ANY             = 255,   // Not a DNS class, but a DNS query class, meaning "all classes"
190     kDNSQClass_UnicastResponse = 0x8000 // Top bit set in a question means "unicast response acceptable"
191 } DNS_ClassValues;
192 
193 typedef enum                // From RFC 1035
194 {
195     kDNSType_A = 1,         //  1 Address
196     kDNSType_NS,            //  2 Name Server
197     kDNSType_MD,            //  3 Mail Destination
198     kDNSType_MF,            //  4 Mail Forwarder
199     kDNSType_CNAME,         //  5 Canonical Name
200     kDNSType_SOA,           //  6 Start of Authority
201     kDNSType_MB,            //  7 Mailbox
202     kDNSType_MG,            //  8 Mail Group
203     kDNSType_MR,            //  9 Mail Rename
204     kDNSType_NULL,          // 10 NULL RR
205     kDNSType_WKS,           // 11 Well-known-service
206     kDNSType_PTR,           // 12 Domain name pointer
207     kDNSType_HINFO,         // 13 Host information
208     kDNSType_MINFO,         // 14 Mailbox information
209     kDNSType_MX,            // 15 Mail Exchanger
210     kDNSType_TXT,           // 16 Arbitrary text string
211     kDNSType_RP,            // 17 Responsible person
212     kDNSType_AFSDB,         // 18 AFS cell database
213     kDNSType_X25,           // 19 X_25 calling address
214     kDNSType_ISDN,          // 20 ISDN calling address
215     kDNSType_RT,            // 21 Router
216     kDNSType_NSAP,          // 22 NSAP address
217     kDNSType_NSAP_PTR,      // 23 Reverse NSAP lookup (deprecated)
218     kDNSType_SIG,           // 24 Security signature
219     kDNSType_KEY,           // 25 Security key
220     kDNSType_PX,            // 26 X.400 mail mapping
221     kDNSType_GPOS,          // 27 Geographical position (withdrawn)
222     kDNSType_AAAA,          // 28 IPv6 Address
223     kDNSType_LOC,           // 29 Location Information
224     kDNSType_NXT,           // 30 Next domain (security)
225     kDNSType_EID,           // 31 Endpoint identifier
226     kDNSType_NIMLOC,        // 32 Nimrod Locator
227     kDNSType_SRV,           // 33 Service record
228     kDNSType_ATMA,          // 34 ATM Address
229     kDNSType_NAPTR,         // 35 Naming Authority PoinTeR
230     kDNSType_KX,            // 36 Key Exchange
231     kDNSType_CERT,          // 37 Certification record
232     kDNSType_A6,            // 38 IPv6 Address (deprecated)
233     kDNSType_DNAME,         // 39 Non-terminal DNAME (for IPv6)
234     kDNSType_SINK,          // 40 Kitchen sink (experimental)
235     kDNSType_OPT,           // 41 EDNS0 option (meta-RR)
236     kDNSType_APL,           // 42 Address Prefix List
237     kDNSType_DS,            // 43 Delegation Signer
238     kDNSType_SSHFP,         // 44 SSH Key Fingerprint
239     kDNSType_IPSECKEY,      // 45 IPSECKEY
240     kDNSType_RRSIG,         // 46 RRSIG
241     kDNSType_NSEC,          // 47 Denial of Existence
242     kDNSType_DNSKEY,        // 48 DNSKEY
243     kDNSType_DHCID,         // 49 DHCP Client Identifier
244     kDNSType_NSEC3,         // 50 Hashed Authenticated Denial of Existence
245     kDNSType_NSEC3PARAM,    // 51 Hashed Authenticated Denial of Existence
246 
247     kDNSType_HIP = 55,      // 55 Host Identity Protocol
248 
249     kDNSType_SVCB = 64,     // 64 Service Binding
250     kDNSType_HTTPS,         // 65 HTTPS Service Binding
251 
252     kDNSType_SPF = 99,      // 99 Sender Policy Framework for E-Mail
253     kDNSType_UINFO,         // 100 IANA-Reserved
254     kDNSType_UID,           // 101 IANA-Reserved
255     kDNSType_GID,           // 102 IANA-Reserved
256     kDNSType_UNSPEC,        // 103 IANA-Reserved
257 
258     kDNSType_TKEY = 249,    // 249 Transaction key
259     kDNSType_TSIG,          // 250 Transaction signature
260     kDNSType_IXFR,          // 251 Incremental zone transfer
261     kDNSType_AXFR,          // 252 Transfer zone of authority
262     kDNSType_MAILB,         // 253 Transfer mailbox records
263     kDNSType_MAILA,         // 254 Transfer mail agent records
264     kDNSQType_ANY          // Not a DNS type, but a DNS query type, meaning "all types"
265 } DNS_TypeValues;
266 
267 // ***************************************************************************
268 #if 0
269 #pragma mark -
270 #pragma mark - Simple types
271 #endif
272 
273 // mDNS defines its own names for these common types to simplify portability across
274 // multiple platforms that may each have their own (different) names for these types.
275 typedef unsigned char mDNSBool;
276 typedef   signed char mDNSs8;
277 typedef unsigned char mDNSu8;
278 typedef   signed short mDNSs16;
279 typedef unsigned short mDNSu16;
280 
281 // Source: http://www.unix.org/version2/whatsnew/lp64_wp.html
282 // http://software.intel.com/sites/products/documentation/hpc/mkl/lin/MKL_UG_structure/Support_for_ILP64_Programming.htm
283 // It can be safely assumed that int is 32bits on the platform
284 #if defined(_ILP64) || defined(__ILP64__)
285 typedef   signed int32 mDNSs32;
286 typedef unsigned int32 mDNSu32;
287 #else
288 typedef   signed int mDNSs32;
289 typedef unsigned int mDNSu32;
290 #endif
291 
292 // To enforce useful type checking, we make mDNSInterfaceID be a pointer to a dummy struct
293 // This way, mDNSInterfaceIDs can be assigned, and compared with each other, but not with other types
294 // Declaring the type to be the typical generic "void *" would lack this type checking
295 typedef const struct mDNSInterfaceID_dummystruct { void *dummy; } *mDNSInterfaceID;
296 
297 // Use when printing interface IDs; the interface ID is actually a pointer, but we're only using
298 // the pointer as a unique identifier, and in special cases it's actually a small number.   So there's
299 // little point in printing all 64 bits--the upper 32 bits in particular will not add information.
300 #define IIDPrintable(x) ((uint32_t)(uintptr_t)(x))
301 
302 // These types are for opaque two- and four-byte identifiers.
303 // The "NotAnInteger" fields of the unions allow the value to be conveniently passed around in a
304 // register for the sake of efficiency, and compared for equality or inequality, but don't forget --
305 // just because it is in a register doesn't mean it is an integer. Operations like greater than,
306 // less than, add, multiply, increment, decrement, etc., are undefined for opaque identifiers,
307 // and if you make the mistake of trying to do those using the NotAnInteger field, then you'll
308 // find you get code that doesn't work consistently on big-endian and little-endian machines.
309 #if defined(_WIN32)
310  #pragma pack(push,2)
311 #elif !defined(__GNUC__)
312  #pragma pack(1)
313 #endif
314 typedef       union { mDNSu8 b[ 2]; mDNSu16 NotAnInteger; } mDNSOpaque16;
315 typedef       union { mDNSu8 b[ 4]; mDNSu32 NotAnInteger; } mDNSOpaque32;
316 typedef packedunion { mDNSu8 b[ 6]; mDNSu16 w[3]; mDNSu32 l[1]; } mDNSOpaque48;
317 typedef       union { mDNSu8 b[ 8]; mDNSu16 w[4]; mDNSu32 l[2]; } mDNSOpaque64;
318 typedef       union { mDNSu8 b[16]; mDNSu16 w[8]; mDNSu32 l[4]; } mDNSOpaque128;
319 #if defined(_WIN32)
320  #pragma pack(pop)
321 #elif !defined(__GNUC__)
322  #pragma pack()
323 #endif
324 
325 typedef mDNSOpaque16 mDNSIPPort;        // An IP port is a two-byte opaque identifier (not an integer)
326 typedef mDNSOpaque32 mDNSv4Addr;        // An IP address is a four-byte opaque identifier (not an integer)
327 typedef mDNSOpaque128 mDNSv6Addr;       // An IPv6 address is a 16-byte opaque identifier (not an integer)
328 typedef mDNSOpaque48 mDNSEthAddr;       // An Ethernet address is a six-byte opaque identifier (not an integer)
329 
330 // Bit operations for opaque 64 bit quantity. Uses the 32 bit quantity(l[2]) to set and clear bits
331 #define mDNSNBBY 8
332 #define bit_set_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] |= (1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
333 #define bit_clr_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] &= ~(1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
334 #define bit_get_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] & (1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
335 
336 // Bit operations for opaque 128 bit quantity. Uses the 32 bit quantity(l[4]) to set and clear bits
337 #define bit_set_opaque128(op128, index) (op128.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] |= (1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
338 #define bit_clr_opaque128(op128, index) (op128.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] &= ~(1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
339 #define bit_get_opaque128(op128, index) (op128.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] & (1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
340 
341 typedef enum
342 {
343     mDNSAddrType_None    = 0,
344     mDNSAddrType_IPv4    = 4,
345     mDNSAddrType_IPv6    = 6,
346     mDNSAddrType_Unknown = ~0   // Special marker value used in known answer list recording
347 } mDNSAddr_Type;
348 
349 typedef enum
350 {
351     mDNSTransport_None = 0,
352     mDNSTransport_UDP  = 1,
353     mDNSTransport_TCP  = 2
354 } mDNSTransport_Type;
355 
356 typedef struct
357 {
358     mDNSs32 type;
359     union { mDNSv6Addr v6; mDNSv4Addr v4; } ip;
360 } mDNSAddr;
361 
362 enum { mDNSfalse = 0, mDNStrue = 1 };
363 
364 #define mDNSNULL 0L
365 
366 enum
367 {
368     mStatus_Waiting           = 1,
369     mStatus_NoError           = 0,
370 
371     // mDNS return values are in the range FFFE FF00 (-65792) to FFFE FFFF (-65537)
372     // The top end of the range (FFFE FFFF) is used for error codes;
373     // the bottom end of the range (FFFE FF00) is used for non-error values;
374 
375     // Error codes:
376     mStatus_UnknownErr                = -65537,     // First value: 0xFFFE FFFF
377     mStatus_NoSuchNameErr             = -65538,
378     mStatus_NoMemoryErr               = -65539,
379     mStatus_BadParamErr               = -65540,
380     mStatus_BadReferenceErr           = -65541,
381     mStatus_BadStateErr               = -65542,
382     mStatus_BadFlagsErr               = -65543,
383     mStatus_UnsupportedErr            = -65544,
384     mStatus_NotInitializedErr         = -65545,
385     mStatus_NoCache                   = -65546,
386     mStatus_AlreadyRegistered         = -65547,
387     mStatus_NameConflict              = -65548,
388     mStatus_Invalid                   = -65549,
389     mStatus_Firewall                  = -65550,
390     mStatus_Incompatible              = -65551,
391     mStatus_BadInterfaceErr           = -65552,
392     mStatus_Refused                   = -65553,
393     mStatus_NoSuchRecord              = -65554,
394     mStatus_NoAuth                    = -65555,
395     mStatus_NoSuchKey                 = -65556,
396     mStatus_NATTraversal              = -65557,
397     mStatus_DoubleNAT                 = -65558,
398     mStatus_BadTime                   = -65559,
399     mStatus_BadSig                    = -65560,     // while we define this per RFC 2845, BIND 9 returns Refused for bad/missing signatures
400     mStatus_BadKey                    = -65561,
401     mStatus_TransientErr              = -65562,     // transient failures, e.g. sending packets shortly after a network transition or wake from sleep
402     mStatus_ServiceNotRunning         = -65563,     // Background daemon not running
403     mStatus_NATPortMappingUnsupported = -65564,     // NAT doesn't support PCP, NAT-PMP or UPnP
404     mStatus_NATPortMappingDisabled    = -65565,     // NAT supports PCP, NAT-PMP or UPnP, but it's disabled by the administrator
405     mStatus_NoRouter                  = -65566,
406     mStatus_PollingMode               = -65567,
407     mStatus_Timeout                   = -65568,
408     mStatus_DefunctConnection         = -65569,
409     mStatus_PolicyDenied              = -65570,
410     // -65571 to -65785 currently unused; available for allocation
411 
412     // udp connection status
413     mStatus_HostUnreachErr    = -65786,
414 
415     // tcp connection status
416     mStatus_ConnPending       = -65787,
417     mStatus_ConnFailed        = -65788,
418     mStatus_ConnEstablished   = -65789,
419 
420     // Non-error values:
421     mStatus_GrowCache         = -65790,
422     mStatus_ConfigChanged     = -65791,
423     mStatus_MemFree           = -65792      // Last value: 0xFFFE FF00
424 
425     // mStatus_MemFree is the last legal mDNS error code, at the end of the range allocated for mDNS
426 };
427 
428 typedef mDNSs32 mStatus;
429 
430 #define MaxIp 5 // Needs to be consistent with MaxInputIf in dns_services.h
431 
432 typedef enum { q_stop = 0, q_start } q_state;
433 typedef enum { reg_stop = 0, reg_start } reg_state;
434 
435 // RFC 1034/1035 specify that a domain label consists of a length byte plus up to 63 characters
436 #define MAX_DOMAIN_LABEL 63
437 typedef struct { mDNSu8 c[ 64]; } domainlabel;      // One label: length byte and up to 63 characters
438 
439 // RFC 1034/1035/2181 specify that a domain name (length bytes and data bytes) may be up to 255 bytes long,
440 // plus the terminating zero at the end makes 256 bytes total in the on-the-wire format.
441 #define MAX_DOMAIN_NAME 256
442 typedef struct { mDNSu8 c[256]; } domainname;       // Up to 256 bytes of length-prefixed domainlabels
443 
444 typedef struct { mDNSu8 c[256]; } UTF8str255;       // Null-terminated C string
445 
446 // The longest legal textual form of a DNS name is 1009 bytes, including the C-string terminating NULL at the end.
447 // Explanation:
448 // When a native domainname object is converted to printable textual form using ConvertDomainNameToCString(),
449 // non-printing characters are represented in the conventional DNS way, as '\ddd', where ddd is a three-digit decimal number.
450 // The longest legal domain name is 256 bytes, in the form of four labels as shown below:
451 // Length byte, 63 data bytes, length byte, 63 data bytes, length byte, 63 data bytes, length byte, 62 data bytes, zero byte.
452 // Each label is encoded textually as characters followed by a trailing dot.
453 // If every character has to be represented as a four-byte escape sequence, then this makes the maximum textual form four labels
454 // plus the C-string terminating NULL as shown below:
455 // 63*4+1 + 63*4+1 + 63*4+1 + 62*4+1 + 1 = 1009.
456 // Note that MAX_ESCAPED_DOMAIN_LABEL is not normally used: If you're only decoding a single label, escaping is usually not required.
457 // It is for domain names, where dots are used as label separators, that proper escaping is vital.
458 #define MAX_ESCAPED_DOMAIN_LABEL 254
459 #define MAX_ESCAPED_DOMAIN_NAME 1009
460 
461 // MAX_REVERSE_MAPPING_NAME
462 // For IPv4: "123.123.123.123.in-addr.arpa."  30 bytes including terminating NUL
463 // For IPv6: "x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.ip6.arpa."  74 bytes including terminating NUL
464 
465 #define MAX_REVERSE_MAPPING_NAME_V4 30
466 #define MAX_REVERSE_MAPPING_NAME_V6 74
467 #define MAX_REVERSE_MAPPING_NAME    74
468 
469 // Most records have a TTL of 75 minutes, so that their 80% cache-renewal query occurs once per hour.
470 // For records containing a hostname (in the name on the left, or in the rdata on the right),
471 // like A, AAAA, reverse-mapping PTR, and SRV, we use a two-minute TTL by default, because we don't want
472 // them to hang around for too long in the cache if the host in question crashes or otherwise goes away.
473 
474 #define kStandardTTL (3600UL * 100 / 80)
475 #define kHostNameTTL 120UL
476 
477 // Multicast DNS uses announcements (gratuitous responses) to update peer caches.
478 // This means it is feasible to use relatively larger TTL values than we might otherwise
479 // use, because we have a cache coherency protocol to keep the peer caches up to date.
480 // With Unicast DNS, once an authoritative server gives a record with a certain TTL value to a client
481 // or caching server, that client or caching server is entitled to hold onto the record until its TTL
482 // expires, and has no obligation to contact the authoritative server again until that time arrives.
483 // This means that whereas Multicast DNS can use announcements to pre-emptively update stale data
484 // before it would otherwise have expired, standard Unicast DNS (not using LLQs) has no equivalent
485 // mechanism, and TTL expiry is the *only* mechanism by which stale data gets deleted. Because of this,
486 // we currently limit the TTL to ten seconds in such cases where no dynamic cache updating is possible.
487 #define kStaticCacheTTL 10
488 
489 #define DefaultTTLforRRType(X) (((X) == kDNSType_A || (X) == kDNSType_AAAA || (X) == kDNSType_SRV) ? kHostNameTTL : kStandardTTL)
490 #define mDNS_KeepaliveRecord(rr) ((rr)->rrtype == kDNSType_NULL && SameDomainLabel(SecondLabel((rr)->name)->c, (mDNSu8 *)"\x0A_keepalive"))
491 
492 // Number of times keepalives are sent if no ACK is received before waking up the system
493 // this is analogous to net.inet.tcp.keepcnt
494 #define kKeepaliveRetryCount    10
495 // The frequency at which keepalives are retried if no ACK is received
496 #define kKeepaliveRetryInterval 30
497 
498 typedef struct AuthRecord_struct AuthRecord;
499 typedef struct ServiceRecordSet_struct ServiceRecordSet;
500 typedef struct CacheRecord_struct CacheRecord;
501 typedef struct CacheGroup_struct CacheGroup;
502 typedef struct AuthGroup_struct AuthGroup;
503 typedef struct DNSQuestion_struct DNSQuestion;
504 typedef struct ZoneData_struct ZoneData;
505 typedef struct mDNS_struct mDNS;
506 typedef struct mDNS_PlatformSupport_struct mDNS_PlatformSupport;
507 typedef struct NATTraversalInfo_struct NATTraversalInfo;
508 typedef struct ResourceRecord_struct ResourceRecord;
509 
510 // Structure to abstract away the differences between TCP/SSL sockets, and one for UDP sockets
511 // The actual definition of these structures appear in the appropriate platform support code
512 typedef struct TCPListener_struct TCPListener;
513 typedef struct TCPSocket_struct TCPSocket;
514 typedef struct UDPSocket_struct UDPSocket;
515 
516 // ***************************************************************************
517 #if 0
518 #pragma mark -
519 #pragma mark - DNS Message structures
520 #endif
521 
522 #define mDNS_numZones   numQuestions
523 #define mDNS_numPrereqs numAnswers
524 #define mDNS_numUpdates numAuthorities
525 
526 typedef struct
527 {
528     mDNSOpaque16 id;
529     mDNSOpaque16 flags;
530     mDNSu16 numQuestions;
531     mDNSu16 numAnswers;
532     mDNSu16 numAuthorities;
533     mDNSu16 numAdditionals;
534 } DNSMessageHeader;
535 
536 // We can send and receive packets up to 9000 bytes (Ethernet Jumbo Frame size, if that ever becomes widely used)
537 // However, in the normal case we try to limit packets to 1500 bytes so that we don't get IP fragmentation on standard Ethernet
538 // 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
539 #ifndef AbsoluteMaxDNSMessageData
540 #define AbsoluteMaxDNSMessageData 8940
541 #endif
542 #define NormalMaxDNSMessageData 1440
543 typedef struct
544 {
545     DNSMessageHeader h;                     // Note: Size 12 bytes
546     mDNSu8 data[AbsoluteMaxDNSMessageData]; // 40 (IPv6) + 8 (UDP) + 12 (DNS header) + 8940 (data) = 9000
547 } DNSMessage;
548 
549 typedef struct tcpInfo_t
550 {
551     mDNS             *m;
552     TCPSocket        *sock;
553     DNSMessage request;
554     int requestLen;
555     DNSQuestion      *question;   // For queries
556     AuthRecord       *rr;         // For record updates
557     mDNSAddr Addr;
558     mDNSIPPort Port;
559     mDNSIPPort SrcPort;
560     DNSMessage       *reply;
561     mDNSu16 replylen;
562     unsigned long nread;
563     int numReplies;
564 } tcpInfo_t;
565 
566 // ***************************************************************************
567 #if 0
568 #pragma mark -
569 #pragma mark - Other Packet Format Structures
570 #endif
571 
572 typedef packedstruct
573 {
574     mDNSEthAddr dst;
575     mDNSEthAddr src;
576     mDNSOpaque16 ethertype;
577 } EthernetHeader;           // 14 bytes
578 
579 typedef packedstruct
580 {
581     mDNSOpaque16 hrd;
582     mDNSOpaque16 pro;
583     mDNSu8 hln;
584     mDNSu8 pln;
585     mDNSOpaque16 op;
586     mDNSEthAddr sha;
587     mDNSv4Addr spa;
588     mDNSEthAddr tha;
589     mDNSv4Addr tpa;
590 } ARP_EthIP;                // 28 bytes
591 
592 typedef packedstruct
593 {
594     mDNSu8 vlen;
595     mDNSu8 tos;
596     mDNSOpaque16 totlen;
597     mDNSOpaque16 id;
598     mDNSOpaque16 flagsfrags;
599     mDNSu8 ttl;
600     mDNSu8 protocol;        // Payload type: 0x06 = TCP, 0x11 = UDP
601     mDNSu16 checksum;
602     mDNSv4Addr src;
603     mDNSv4Addr dst;
604 } IPv4Header;               // 20 bytes
605 
606 typedef packedstruct
607 {
608     mDNSu32 vcf;            // Version, Traffic Class, Flow Label
609     mDNSu16 len;            // Payload Length
610     mDNSu8 pro;             // Type of next header: 0x06 = TCP, 0x11 = UDP, 0x3A = ICMPv6
611     mDNSu8 ttl;             // Hop Limit
612     mDNSv6Addr src;
613     mDNSv6Addr dst;
614 } IPv6Header;               // 40 bytes
615 
616 typedef packedstruct
617 {
618     mDNSv6Addr src;
619     mDNSv6Addr dst;
620     mDNSOpaque32 len;
621     mDNSOpaque32 pro;
622 } IPv6PseudoHeader;         // 40 bytes
623 
624 typedef union
625 {
626     mDNSu8 bytes[20];
627     ARP_EthIP arp;
628     IPv4Header v4;
629     IPv6Header v6;
630 } NetworkLayerPacket;
631 
632 typedef packedstruct
633 {
634     mDNSIPPort src;
635     mDNSIPPort dst;
636     mDNSu32 seq;
637     mDNSu32 ack;
638     mDNSu8 offset;
639     mDNSu8 flags;
640     mDNSu16 window;
641     mDNSu16 checksum;
642     mDNSu16 urgent;
643 } TCPHeader;                // 20 bytes; IP protocol type 0x06
644 
645 typedef struct
646 {
647     mDNSInterfaceID IntfId;
648     mDNSu32 seq;
649     mDNSu32 ack;
650     mDNSu16 window;
651 } mDNSTCPInfo;
652 
653 typedef packedstruct
654 {
655     mDNSIPPort src;
656     mDNSIPPort dst;
657     mDNSu16 len;            // Length including UDP header (i.e. minimum value is 8 bytes)
658     mDNSu16 checksum;
659 } UDPHeader;                // 8 bytes; IP protocol type 0x11
660 
661 typedef struct
662 {
663     mDNSu8 type;            // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
664     mDNSu8 code;
665     mDNSu16 checksum;
666     mDNSu32 flags_res;      // R/S/O flags and reserved bits
667     mDNSv6Addr target;
668     // Typically 8 bytes of options are also present
669 } IPv6NDP;                  // 24 bytes or more; IP protocol type 0x3A
670 
671 typedef struct
672 {
673     mDNSAddr    ipaddr;
674     char        ethaddr[18];
675 } IPAddressMACMapping;
676 
677 #define NDP_Sol 0x87
678 #define NDP_Adv 0x88
679 
680 #define NDP_Router    0x80
681 #define NDP_Solicited 0x40
682 #define NDP_Override  0x20
683 
684 #define NDP_SrcLL 1
685 #define NDP_TgtLL 2
686 
687 typedef union
688 {
689     mDNSu8 bytes[20];
690     TCPHeader tcp;
691     UDPHeader udp;
692     IPv6NDP ndp;
693 } TransportLayerPacket;
694 
695 typedef packedstruct
696 {
697     mDNSOpaque64 InitiatorCookie;
698     mDNSOpaque64 ResponderCookie;
699     mDNSu8 NextPayload;
700     mDNSu8 Version;
701     mDNSu8 ExchangeType;
702     mDNSu8 Flags;
703     mDNSOpaque32 MessageID;
704     mDNSu32 Length;
705 } IKEHeader;                // 28 bytes
706 
707 // ***************************************************************************
708 #if 0
709 #pragma mark -
710 #pragma mark - Resource Record structures
711 #endif
712 
713 // Authoritative Resource Records:
714 // There are four basic types: Shared, Advisory, Unique, Known Unique
715 
716 // * Shared Resource Records do not have to be unique
717 // -- Shared Resource Records are used for DNS-SD service PTRs
718 // -- It is okay for several hosts to have RRs with the same name but different RDATA
719 // -- We use a random delay on responses to reduce collisions when all the hosts respond to the same query
720 // -- These RRs typically have moderately high TTLs (e.g. one hour)
721 // -- These records are announced on startup and topology changes for the benefit of passive listeners
722 // -- These records send a goodbye packet when deregistering
723 //
724 // * Advisory Resource Records are like Shared Resource Records, except they don't send a goodbye packet
725 //
726 // * Unique Resource Records should be unique among hosts within any given mDNS scope
727 // -- The majority of Resource Records are of this type
728 // -- If two entities on the network have RRs with the same name but different RDATA, this is a conflict
729 // -- Responses may be sent immediately, because only one host should be responding to any particular query
730 // -- These RRs typically have low TTLs (e.g. a few minutes)
731 // -- On startup and after topology changes, a host issues queries to verify uniqueness
732 
733 // * Known Unique Resource Records are treated like Unique Resource Records, except that mDNS does
734 // not have to verify their uniqueness because this is already known by other means (e.g. the RR name
735 // is derived from the host's IP or Ethernet address, which is already known to be a unique identifier).
736 
737 // Summary of properties of different record types:
738 // Probe?    Does this record type send probes before announcing?
739 // Conflict? Does this record type react if we observe an apparent conflict?
740 // Goodbye?  Does this record type send a goodbye packet on departure?
741 //
742 //               Probe? Conflict? Goodbye? Notes
743 // Unregistered                            Should not appear in any list (sanity check value)
744 // Shared         No      No       Yes     e.g. Service PTR record
745 // Deregistering  No      No       Yes     Shared record about to announce its departure and leave the list
746 // Advisory       No      No       No
747 // Unique         Yes     Yes      No      Record intended to be unique -- will probe to verify
748 // Verified       Yes     Yes      No      Record has completed probing, and is verified unique
749 // KnownUnique    No      Yes      No      Record is assumed by other means to be unique
750 
751 // Valid lifecycle of a record:
752 // Unregistered ->                   Shared      -> Deregistering -(goodbye)-> Unregistered
753 // Unregistered ->                   Advisory                               -> Unregistered
754 // Unregistered -> Unique -(probe)-> Verified                               -> Unregistered
755 // Unregistered ->                   KnownUnique                            -> Unregistered
756 
757 // Each Authoritative kDNSRecordType has only one bit set. This makes it easy to quickly see if a record
758 // is one of a particular set of types simply by performing the appropriate bitwise masking operation.
759 
760 // Cache Resource Records (received from the network):
761 // There are four basic types: Answer, Unique Answer, Additional, Unique Additional
762 // Bit 7 (the top bit) of kDNSRecordType is always set for Cache Resource Records; always clear for Authoritative Resource Records
763 // Bit 6 (value 0x40) is set for answer records; clear for authority/additional records
764 // Bit 5 (value 0x20) is set for records received with the kDNSClass_UniqueRRSet
765 
766 typedef enum
767 {
768     kDNSRecordTypeUnregistered     = 0x00,  // Not currently in any list
769     kDNSRecordTypeDeregistering    = 0x01,  // Shared record about to announce its departure and leave the list
770 
771     kDNSRecordTypeUnique           = 0x02,  // Will become a kDNSRecordTypeVerified when probing is complete
772 
773     kDNSRecordTypeAdvisory         = 0x04,  // Like Shared, but no goodbye packet
774     kDNSRecordTypeShared           = 0x08,  // Shared means record name does not have to be unique -- use random delay on responses
775 
776     kDNSRecordTypeVerified         = 0x10,  // Unique means mDNS should check that name is unique (and then send immediate responses)
777     kDNSRecordTypeKnownUnique      = 0x20,  // Known Unique means mDNS can assume name is unique without checking
778                                             // For Dynamic Update records, Known Unique means the record must already exist on the server.
779     kDNSRecordTypeUniqueMask       = (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique),
780     kDNSRecordTypeActiveSharedMask = (kDNSRecordTypeAdvisory         | kDNSRecordTypeShared),
781     kDNSRecordTypeActiveUniqueMask = (kDNSRecordTypeVerified         | kDNSRecordTypeKnownUnique),
782     kDNSRecordTypeActiveMask       = (kDNSRecordTypeActiveSharedMask | kDNSRecordTypeActiveUniqueMask),
783 
784     kDNSRecordTypePacketAdd        = 0x80,  // Received in the Additional  Section of a DNS Response
785     kDNSRecordTypePacketAddUnique  = 0x90,  // Received in the Additional  Section of a DNS Response with kDNSClass_UniqueRRSet set
786     kDNSRecordTypePacketAuth       = 0xA0,  // Received in the Authorities Section of a DNS Response
787     kDNSRecordTypePacketAuthUnique = 0xB0,  // Received in the Authorities Section of a DNS Response with kDNSClass_UniqueRRSet set
788     kDNSRecordTypePacketAns        = 0xC0,  // Received in the Answer      Section of a DNS Response
789     kDNSRecordTypePacketAnsUnique  = 0xD0,  // Received in the Answer      Section of a DNS Response with kDNSClass_UniqueRRSet set
790 
791     kDNSRecordTypePacketNegative   = 0xF0,  // Pseudo-RR generated to cache non-existence results like NXDomain
792 
793     kDNSRecordTypePacketUniqueMask = 0x10   // True for PacketAddUnique, PacketAnsUnique, PacketAuthUnique, kDNSRecordTypePacketNegative
794 } kDNSRecordTypes;
795 
796 typedef packedstruct { mDNSu16 priority; mDNSu16 weight; mDNSIPPort port; domainname target;   } rdataSRV;
797 typedef packedstruct { mDNSu16 preference;                                domainname exchange; } rdataMX;
798 typedef packedstruct { domainname mbox; domainname txt;                                        } rdataRP;
799 typedef packedstruct { mDNSu16 preference; domainname map822; domainname mapx400;              } rdataPX;
800 
801 typedef packedstruct
802 {
803     domainname mname;
804     domainname rname;
805     mDNSs32 serial;     // Modular counter; increases when zone changes
806     mDNSu32 refresh;    // Time in seconds that a slave waits after successful replication of the database before it attempts replication again
807     mDNSu32 retry;      // Time in seconds that a slave waits after an unsuccessful replication attempt before it attempts replication again
808     mDNSu32 expire;     // Time in seconds that a slave holds on to old data while replication attempts remain unsuccessful
809     mDNSu32 min;        // Nominally the minimum record TTL for this zone, in seconds; also used for negative caching.
810 } rdataSOA;
811 
812 typedef enum
813 {
814     platform_OSX = 1,   // OSX Platform
815     platform_iOS,       // iOS Platform
816     platform_Atv,       // Atv Platform
817     platform_NonApple   // Non-Apple (Windows, POSIX) Platform
818 } Platform_t;
819 
820 // EDNS Option Code registrations are recorded in the "DNS EDNS0 Options" section of
821 // <http://www.iana.org/assignments/dns-parameters>
822 
823 #define kDNSOpt_LLQ   1
824 #define kDNSOpt_Lease 2
825 #define kDNSOpt_NSID  3
826 #define kDNSOpt_Owner 4
827 #define kDNSOpt_Trace 65001  // 65001-65534 Reserved for Local/Experimental Use
828 
829 typedef struct
830 {
831     mDNSu16 vers;
832     mDNSu16 llqOp;
833     mDNSu16 err;        // Or UDP reply port, in setup request
834     // Note: In the in-memory form, there's typically a two-byte space here, so that the following 64-bit id is word-aligned
835     mDNSOpaque64 id;
836     mDNSu32 llqlease;
837 } LLQOptData;
838 
839 typedef struct
840 {
841     mDNSu8 vers;            // Version number of this Owner OPT record
842     mDNSs8 seq;             // Sleep/wake epoch
843     mDNSEthAddr HMAC;       // Host's primary identifier (e.g. MAC of on-board Ethernet)
844     mDNSEthAddr IMAC;       // Interface's MAC address (if different to primary MAC)
845     mDNSOpaque48 password;  // Optional password
846 } OwnerOptData;
847 
848 typedef struct
849 {
850     mDNSu8    platf;      // Running platform (see enum Platform_t)
851     mDNSu32   mDNSv;      // mDNSResponder Version (DNS_SD_H defined in dns_sd.h)
852 } TracerOptData;
853 
854 // Note: rdataOPT format may be repeated an arbitrary number of times in a single resource record
855 typedef struct
856 {
857     mDNSu16 opt;
858     mDNSu16 optlen;
859     union { LLQOptData llq; mDNSu32 updatelease; OwnerOptData owner; TracerOptData tracer; } u;
860 } rdataOPT;
861 
862 // Space needed to put OPT records into a packet:
863 // Header         11  bytes (name 1, type 2, class 2, TTL 4, length 2)
864 // LLQ   rdata    18  bytes (opt 2, len 2, vers 2, op 2, err 2, id 8, lease 4)
865 // Lease rdata     8  bytes (opt 2, len 2, lease 4)
866 // Owner rdata 12-24  bytes (opt 2, len 2, owner 8-20)
867 // Trace rdata     9  bytes (opt 2, len 2, platf 1, mDNSv 4)
868 
869 
870 #define DNSOpt_Header_Space                 11
871 #define DNSOpt_LLQData_Space               (4 + 2 + 2 + 2 + 8 + 4)
872 #define DNSOpt_LeaseData_Space             (4 + 4)
873 #define DNSOpt_OwnerData_ID_Space          (4 + 2 + 6)
874 #define DNSOpt_OwnerData_ID_Wake_Space     (4 + 2 + 6 + 6)
875 #define DNSOpt_OwnerData_ID_Wake_PW4_Space (4 + 2 + 6 + 6 + 4)
876 #define DNSOpt_OwnerData_ID_Wake_PW6_Space (4 + 2 + 6 + 6 + 6)
877 #define DNSOpt_TraceData_Space             (4 + 1 + 4)
878 
879 #define ValidOwnerLength(X) (   (X) == DNSOpt_OwnerData_ID_Space          - 4 || \
880                                 (X) == DNSOpt_OwnerData_ID_Wake_Space     - 4 || \
881                                 (X) == DNSOpt_OwnerData_ID_Wake_PW4_Space - 4 || \
882                                 (X) == DNSOpt_OwnerData_ID_Wake_PW6_Space - 4    )
883 
884 #define DNSOpt_Owner_Space(A,B) (mDNSSameEthAddress((A),(B)) ? DNSOpt_OwnerData_ID_Space : DNSOpt_OwnerData_ID_Wake_Space)
885 
886 #define DNSOpt_Data_Space(O) (                                  \
887         (O)->opt == kDNSOpt_LLQ   ? DNSOpt_LLQData_Space   :        \
888         (O)->opt == kDNSOpt_Lease ? DNSOpt_LeaseData_Space :        \
889         (O)->opt == kDNSOpt_Trace ? DNSOpt_TraceData_Space :        \
890         (O)->opt == kDNSOpt_Owner ? DNSOpt_Owner_Space(&(O)->u.owner.HMAC, &(O)->u.owner.IMAC) : 0x10000)
891 
892 // NSEC record is defined in RFC 4034.
893 // 16 bit RRTYPE space is split into 256 windows and each window has 256 bits (32 bytes).
894 // If we create a structure for NSEC, it's size would be:
895 //
896 //   256 bytes domainname 'nextname'
897 // + 256 * 34 = 8704 bytes of bitmap data
898 // = 8960 bytes total
899 //
900 // This would be a waste, as types about 256 are not very common. But it would be odd, if we receive
901 // a type above 256 (.US zone had TYPE65534 when this code was written) and not able to handle it.
902 // Hence, we handle any size by not fixing a strucure in place. The following is just a placeholder
903 // and never used anywhere.
904 //
905 #define NSEC_MCAST_WINDOW_SIZE 32
906 typedef struct
907 {
908     domainname *next; //placeholders are uncommented because C89 in Windows requires that a struct has at least a member.
909     char bitmap[32];
910 } rdataNSEC;
911 
912 // StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record (6 + 256 bytes)
913 // MaximumRDSize is 8K the absolute maximum we support (at least for now)
914 #define StandardAuthRDSize 264
915 #ifndef MaximumRDSize
916 #define MaximumRDSize 8192
917 #endif
918 
919 // InlineCacheRDSize is 68
920 // Records received from the network with rdata this size or less have their rdata stored right in the CacheRecord object
921 // Records received from the network with rdata larger than this have additional storage allocated for the rdata
922 // A quick unscientific sample from a busy network at Apple with lots of machines revealed this:
923 // 1461 records in cache
924 // 292 were one-byte TXT records
925 // 136 were four-byte A records
926 // 184 were sixteen-byte AAAA records
927 // 780 were various PTR, TXT and SRV records from 12-64 bytes
928 // Only 69 records had rdata bigger than 64 bytes
929 // Note that since CacheRecord object and a CacheGroup object are allocated out of the same pool, it's sensible to
930 // have them both be the same size. Making one smaller without making the other smaller won't actually save any memory.
931 #define InlineCacheRDSize 68
932 
933 // The RDataBody union defines the common rdata types that fit into our 264-byte limit
934 typedef union
935 {
936     mDNSu8 data[StandardAuthRDSize];
937     mDNSv4Addr ipv4;        // For 'A' record
938     domainname name;        // For PTR, NS, CNAME, DNAME
939     UTF8str255 txt;
940     rdataMX mx;
941     mDNSv6Addr ipv6;        // For 'AAAA' record
942     rdataSRV srv;
943     rdataOPT opt[2];        // For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
944 } RDataBody;
945 
946 // The RDataBody2 union is the same as above, except it includes fields for the larger types like soa, rp, px
947 typedef union
948 {
949     mDNSu8 data[StandardAuthRDSize];
950     mDNSv4Addr ipv4;        // For 'A' record
951     domainname name;        // For PTR, NS, CNAME, DNAME
952     rdataSOA soa;           // This is large; not included in the normal RDataBody definition
953     UTF8str255 txt;
954     rdataMX mx;
955     rdataRP rp;             // This is large; not included in the normal RDataBody definition
956     rdataPX px;             // This is large; not included in the normal RDataBody definition
957     mDNSv6Addr ipv6;        // For 'AAAA' record
958     rdataSRV srv;
959     rdataOPT opt[2];        // For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
960 } RDataBody2;
961 
962 typedef struct
963 {
964     mDNSu16 MaxRDLength;    // Amount of storage allocated for rdata (usually sizeof(RDataBody))
965     mDNSu16 padding;        // So that RDataBody is aligned on 32-bit boundary
966     RDataBody u;
967 } RData;
968 
969 // sizeofRDataHeader should be 4 bytes
970 #define sizeofRDataHeader (sizeof(RData) - sizeof(RDataBody))
971 
972 // RData_small is a smaller version of the RData object, used for inline data storage embedded in a CacheRecord_struct
973 typedef struct
974 {
975     mDNSu16 MaxRDLength;    // Storage allocated for data (may be greater than InlineCacheRDSize if additional storage follows this object)
976     mDNSu16 padding;        // So that data is aligned on 32-bit boundary
977     mDNSu8 data[InlineCacheRDSize];
978 } RData_small;
979 
980 // Note: Within an mDNSRecordCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
981 typedef void mDNSRecordCallback (mDNS *const m, AuthRecord *const rr, mStatus result);
982 
983 // Note:
984 // Restrictions: An mDNSRecordUpdateCallback may not make any mDNS API calls.
985 // The intent of this callback is to allow the client to free memory, if necessary.
986 // The internal data structures of the mDNS code may not be in a state where mDNS API calls may be made safely.
987 typedef void mDNSRecordUpdateCallback (mDNS *const m, AuthRecord *const rr, RData *OldRData, mDNSu16 OldRDLen);
988 
989 // ***************************************************************************
990 #if 0
991 #pragma mark -
992 #pragma mark - NAT Traversal structures and constants
993 #endif
994 
995 #define NATMAP_MAX_RETRY_INTERVAL    ((mDNSPlatformOneSecond * 60) * 15)    // Max retry interval is 15 minutes
996 #define NATMAP_MIN_RETRY_INTERVAL     (mDNSPlatformOneSecond * 2)           // Min retry interval is 2 seconds
997 #define NATMAP_INIT_RETRY             (mDNSPlatformOneSecond / 4)           // start at 250ms w/ exponential decay
998 #define NATMAP_DEFAULT_LEASE          (60 * 60 * 2)                         // 2 hour lease life in seconds
999 #define NATMAP_VERS 0
1000 
1001 typedef enum
1002 {
1003     NATOp_AddrRequest    = 0,
1004     NATOp_MapUDP         = 1,
1005     NATOp_MapTCP         = 2,
1006 
1007     NATOp_AddrResponse   = 0x80 | 0,
1008     NATOp_MapUDPResponse = 0x80 | 1,
1009     NATOp_MapTCPResponse = 0x80 | 2,
1010 } NATOp_t;
1011 
1012 enum
1013 {
1014     NATErr_None    = 0,
1015     NATErr_Vers    = 1,
1016     NATErr_Refused = 2,
1017     NATErr_NetFail = 3,
1018     NATErr_Res     = 4,
1019     NATErr_Opcode  = 5
1020 };
1021 
1022 typedef mDNSu16 NATErr_t;
1023 
1024 typedef packedstruct
1025 {
1026     mDNSu8 vers;
1027     mDNSu8 opcode;
1028 } NATAddrRequest;
1029 
1030 typedef packedstruct
1031 {
1032     mDNSu8 vers;
1033     mDNSu8 opcode;
1034     mDNSu16 err;
1035     mDNSu32 upseconds;          // Time since last NAT engine reboot, in seconds
1036     mDNSv4Addr ExtAddr;
1037 } NATAddrReply;
1038 
1039 typedef packedstruct
1040 {
1041     mDNSu8 vers;
1042     mDNSu8 opcode;
1043     mDNSOpaque16 unused;
1044     mDNSIPPort intport;
1045     mDNSIPPort extport;
1046     mDNSu32 NATReq_lease;
1047 } NATPortMapRequest;
1048 
1049 typedef packedstruct
1050 {
1051     mDNSu8 vers;
1052     mDNSu8 opcode;
1053     mDNSu16 err;
1054     mDNSu32 upseconds;          // Time since last NAT engine reboot, in seconds
1055     mDNSIPPort intport;
1056     mDNSIPPort extport;
1057     mDNSu32 NATRep_lease;
1058 } NATPortMapReply;
1059 
1060 // PCP Support for IPv4 mappings
1061 
1062 #define PCP_VERS 0x02
1063 #define PCP_WAITSECS_AFTER_EPOCH_INVALID 5
1064 
1065 typedef enum
1066 {
1067     PCPOp_Announce = 0,
1068     PCPOp_Map      = 1
1069 } PCPOp_t;
1070 
1071 typedef enum
1072 {
1073     PCPProto_All = 0,
1074     PCPProto_TCP = 6,
1075     PCPProto_UDP = 17
1076 } PCPProto_t;
1077 
1078 typedef enum
1079 {
1080     PCPResult_Success         = 0,
1081     PCPResult_UnsuppVersion   = 1,
1082     PCPResult_NotAuthorized   = 2,
1083     PCPResult_MalformedReq    = 3,
1084     PCPResult_UnsuppOpcode    = 4,
1085     PCPResult_UnsuppOption    = 5,
1086     PCPResult_MalformedOption = 6,
1087     PCPResult_NetworkFailure  = 7,
1088     PCPResult_NoResources     = 8,
1089     PCPResult_UnsuppProtocol  = 9,
1090     PCPResult_UserExQuota     = 10,
1091     PCPResult_CantProvideExt  = 11,
1092     PCPResult_AddrMismatch    = 12,
1093     PCPResult_ExcesRemotePeer = 13
1094 } PCPResult_t;
1095 
1096 typedef struct
1097 {
1098     mDNSu8       version;
1099     mDNSu8       opCode;
1100     mDNSOpaque16 reserved;
1101     mDNSu32      lifetime;
1102     mDNSv6Addr   clientAddr;
1103     mDNSu32      nonce[3];
1104     mDNSu8       protocol;
1105     mDNSu8       reservedMapOp[3];
1106     mDNSIPPort   intPort;
1107     mDNSIPPort   extPort;
1108     mDNSv6Addr   extAddress;
1109 } PCPMapRequest;
1110 
1111 typedef struct
1112 {
1113     mDNSu8     version;
1114     mDNSu8     opCode;
1115     mDNSu8     reserved;
1116     mDNSu8     result;
1117     mDNSu32    lifetime;
1118     mDNSu32    epoch;
1119     mDNSu32    clientAddrParts[3];
1120     mDNSu32    nonce[3];
1121     mDNSu8     protocol;
1122     mDNSu8     reservedMapOp[3];
1123     mDNSIPPort intPort;
1124     mDNSIPPort extPort;
1125     mDNSv6Addr extAddress;
1126 } PCPMapReply;
1127 
1128 // LNT Support
1129 
1130 typedef enum
1131 {
1132     LNTDiscoveryOp      = 1,
1133     LNTExternalAddrOp   = 2,
1134     LNTPortMapOp        = 3,
1135     LNTPortMapDeleteOp  = 4
1136 } LNTOp_t;
1137 
1138 #define LNT_MAXBUFSIZE 8192
1139 typedef struct tcpLNTInfo_struct tcpLNTInfo;
1140 struct tcpLNTInfo_struct
1141 {
1142     tcpLNTInfo       *next;
1143     mDNS             *m;
1144     NATTraversalInfo *parentNATInfo;    // pointer back to the parent NATTraversalInfo
1145     TCPSocket        *sock;
1146     LNTOp_t op;                         // operation performed using this connection
1147     mDNSAddr Address;                   // router address
1148     mDNSIPPort Port;                    // router port
1149     mDNSu8           *Request;          // xml request to router
1150     int requestLen;
1151     mDNSu8           *Reply;            // xml reply from router
1152     int replyLen;
1153     unsigned long nread;                // number of bytes read so far
1154     int retries;                        // number of times we've tried to do this port mapping
1155 };
1156 
1157 typedef void (*NATTraversalClientCallback)(mDNS *m, NATTraversalInfo *n);
1158 
1159 // if m->timenow <  ExpiryTime then we have an active mapping, and we'll renew halfway to expiry
1160 // if m->timenow >= ExpiryTime then our mapping has expired, and we're trying to create one
1161 
1162 typedef enum
1163 {
1164     NATTProtocolNone    = 0,
1165     NATTProtocolNATPMP  = 1,
1166     NATTProtocolUPNPIGD = 2,
1167     NATTProtocolPCP     = 3,
1168 } NATTProtocol;
1169 
1170 struct NATTraversalInfo_struct
1171 {
1172     // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1173     NATTraversalInfo           *next;
1174 
1175     mDNSs32 ExpiryTime;                             // Time this mapping expires, or zero if no mapping
1176     mDNSs32 retryInterval;                          // Current interval, between last packet we sent and the next one
1177     mDNSs32 retryPortMap;                           // If Protocol is nonzero, time to send our next mapping packet
1178     mStatus NewResult;                              // New error code; will be copied to Result just prior to invoking callback
1179     NATTProtocol lastSuccessfulProtocol;            // To send correct deletion request & update non-PCP external address operations
1180     mDNSBool sentNATPMP;                            // Whether we just sent a NAT-PMP packet, so we won't send another if
1181                                                     //    we receive another NAT-PMP "Unsupported Version" packet
1182 
1183 #ifdef _LEGACY_NAT_TRAVERSAL_
1184     tcpLNTInfo tcpInfo;                             // Legacy NAT traversal (UPnP) TCP connection
1185 #endif
1186 
1187     // Result fields: When the callback is invoked these fields contain the answers the client is looking for
1188     // When the callback is invoked ExternalPort is *usually* set to be the same the same as RequestedPort, except:
1189     // (a) When we're behind a NAT gateway with port mapping disabled, ExternalPort is reported as zero to
1190     //     indicate that we don't currently have a working mapping (but RequestedPort retains the external port
1191     //     we'd like to get, the next time we meet an accomodating NAT gateway willing to give us one).
1192     // (b) When we have a routable non-RFC1918 address, we don't *need* a port mapping, so ExternalPort
1193     //     is reported as the same as our InternalPort, since that is effectively our externally-visible port too.
1194     //     Again, RequestedPort retains the external port we'd like to get the next time we find ourself behind a NAT gateway.
1195     // To improve stability of port mappings, RequestedPort is updated any time we get a successful
1196     // mapping response from the PCP, NAT-PMP or UPnP gateway. For example, if we ask for port 80, and
1197     // get assigned port 81, then thereafter we'll contine asking for port 81.
1198     mDNSInterfaceID InterfaceID;
1199     mDNSv4Addr ExternalAddress;                     // Initially set to onesIPv4Addr, until first callback
1200     mDNSv4Addr NewAddress;                          // May be updated with actual value assigned by gateway
1201     mDNSIPPort ExternalPort;
1202     mDNSu32 Lifetime;
1203     mStatus Result;
1204 
1205     // Client API fields: The client must set up these fields *before* making any NAT traversal API calls
1206     mDNSu8 Protocol;                                // NATOp_MapUDP or NATOp_MapTCP, or zero if just requesting the external IP address
1207     mDNSIPPort IntPort;                             // Client's internal port number (doesn't change)
1208     mDNSIPPort RequestedPort;                       // Requested external port; may be updated with actual value assigned by gateway
1209     mDNSu32 NATLease;                               // Requested lifetime in seconds (doesn't change)
1210     NATTraversalClientCallback clientCallback;
1211     void                       *clientContext;
1212 };
1213 
1214 // ***************************************************************************
1215 #if 0
1216 #pragma mark -
1217 #pragma mark - DNSServer & McastResolver structures and constants
1218 #endif
1219 
1220 enum
1221 {
1222     McastResolver_FlagDelete = 1,
1223     McastResolver_FlagNew    = 2
1224 };
1225 
1226 typedef struct McastResolver
1227 {
1228     struct McastResolver *next;
1229     mDNSInterfaceID interface;
1230     mDNSu32 flags;              // Set when we're planning to delete this from the list
1231     domainname domain;
1232     mDNSu32 timeout;            // timeout value for questions
1233 } McastResolver;
1234 
1235 enum {
1236     Mortality_Mortal      = 0,          // This cache record can expire and get purged
1237     Mortality_Immortal    = 1,          // Allow this record to remain in the cache indefinitely
1238     Mortality_Ghost       = 2           // An immortal record that has expired and can linger in the cache
1239 };
1240 typedef mDNSu8 MortalityState;
1241 
1242 // ScopeType values for DNSServer matching
1243 typedef enum
1244 {
1245     kScopeNone         = 0,        // DNS server used by unscoped questions
1246     kScopeInterfaceID  = 1,        // Scoped DNS server used only by scoped questions
1247     kScopeServiceID    = 2         // Service specific DNS server used only by questions
1248                                    // have a matching serviceID
1249 } ScopeType;
1250 
1251 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
1252 typedef mDNSu32 DNSServerFlags;
1253 #define DNSServerFlag_Delete        (1U << 0)
1254 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
1255 #define DNSServerFlag_Unreachable   (1U << 1)
1256 #endif
1257 
1258 typedef struct DNSServer
1259 {
1260     struct DNSServer *next;
1261     mDNSInterfaceID interface;  // DNS requests should be sent on this interface
1262     mDNSs32 serviceID;          // ServiceID from DNS configuration.
1263     mDNSAddr addr;              // DNS server's IP address.
1264     DNSServerFlags flags;       // Set when we're planning to delete this from the list.
1265     mDNSs32 penaltyTime;        // amount of time this server is penalized
1266     ScopeType scopeType;        // See the ScopeType enum above
1267     mDNSu32 timeout;            // timeout value for questions
1268     mDNSu32 resGroupID;         // ID of the resolver group that contains this DNSServer
1269     mDNSIPPort port;            // DNS server's port number.
1270     mDNSBool usableA;           // True if A query results are usable over the interface, i.e., interface has IPv4.
1271     mDNSBool usableAAAA;        // True if AAAA query results are usable over the interface, i.e., interface has IPv6.
1272     mDNSBool isCell;            // True if the interface to this server is cellular.
1273     mDNSBool isExpensive;       // True if the interface to this server is expensive.
1274     mDNSBool isConstrained;     // True if the interface to this server is constrained.
1275     mDNSBool isCLAT46;          // True if the interface to this server supports CLAT46.
1276     domainname domain;          // name->server matching for "split dns"
1277 } DNSServer;
1278 #endif
1279 
1280 #define kNegativeRecordType_Unspecified 0 // Initializer of ResourceRecord didn't specify why the record is negative.
1281 #define kNegativeRecordType_NoData      1 // The record's name exists, but there are no records of this type.
1282 
1283 struct ResourceRecord_struct
1284 {
1285     mDNSu8 RecordType;                  // See kDNSRecordTypes enum.
1286     mDNSu8 negativeRecordType;          // If RecordType is kDNSRecordTypePacketNegative, specifies type of negative record.
1287     MortalityState mortality;           // Mortality of this resource record (See MortalityState enum)
1288     mDNSu16 rrtype;                     // See DNS_TypeValues enum.
1289     mDNSu16 rrclass;                    // See DNS_ClassValues enum.
1290     mDNSu32 rroriginalttl;              // In seconds
1291     mDNSu16 rdlength;                   // Size of the raw rdata, in bytes, in the on-the-wire format
1292                                         // (In-memory storage may be larger, for structures containing 'holes', like SOA)
1293     mDNSu16 rdestimate;                 // Upper bound on on-the-wire size of rdata after name compression
1294     mDNSu32 namehash;                   // Name-based (i.e. case-insensitive) hash of name
1295     mDNSu32 rdatahash;                  // For rdata containing domain name (e.g. PTR, SRV, CNAME etc.), case-insensitive name hash
1296                                         // else, for all other rdata, 32-bit hash of the raw rdata
1297                                         // Note: This requirement is important. Various routines like AddAdditionalsToResponseList(),
1298                                         // ReconfirmAntecedents(), etc., use rdatahash as a pre-flight check to see
1299                                         // whether it's worth doing a full SameDomainName() call. If the rdatahash
1300                                         // is not a correct case-insensitive name hash, they'll get false negatives.
1301     // Grouping pointers together at the end of the structure improves the memory layout efficiency
1302     mDNSInterfaceID InterfaceID;        // Set if this RR is specific to one interface
1303                                         // For records received off the wire, InterfaceID is *always* set to the receiving interface
1304                                         // For our authoritative records, InterfaceID is usually zero, except for those few records
1305                                         // that are interface-specific (e.g. address records, especially linklocal addresses)
1306     const domainname *name;
1307     RData           *rdata;             // Pointer to storage for this rdata
1308 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
1309 	mdns_dns_service_t dnsservice;
1310 	mdns_resolver_type_t protocol;
1311 #else
1312     DNSServer       *rDNSServer;        // Unicast DNS server authoritative for this entry; null for multicast
1313 #endif
1314 
1315 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
1316     dnssec_result_t dnssec_result;      // DNSSEC validation result of the current resource record.
1317                                         // For all DNSSEC-disabled queries, the result would always be dnssec_indeterminate.
1318                                         // For DNSSEC-enabled queries, the result would be dnssec_indeterminate,
1319                                         // dnssec_secure, dnssec_insecure, or dnssec_bogus, see
1320                                         // <https://tools.ietf.org/html/rfc4033#section-5> for the detailed meaning of
1321                                         // each state.
1322 #endif
1323 };
1324 
1325 
1326 // Unless otherwise noted, states may apply to either independent record registrations or service registrations
1327 typedef enum
1328 {
1329     regState_Zero              = 0,
1330     regState_Pending           = 1,     // update sent, reply not received
1331     regState_Registered        = 2,     // update sent, reply received
1332     regState_DeregPending      = 3,     // dereg sent, reply not received
1333     regState_Unregistered      = 4,     // not in any list
1334     regState_Refresh           = 5,     // outstanding refresh (or target change) message
1335     regState_NATMap            = 6,     // establishing NAT port mapping
1336     regState_UpdatePending     = 7,     // update in flight as result of mDNS_Update call
1337     regState_NoTarget          = 8,     // SRV Record registration pending registration of hostname
1338     regState_NATError          = 9     // unable to complete NAT traversal
1339 } regState_t;
1340 
1341 enum
1342 {
1343     Target_Manual = 0,
1344     Target_AutoHost = 1,
1345     Target_AutoHostAndNATMAP = 2
1346 };
1347 
1348 typedef enum
1349 {
1350     mergeState_Zero = 0,
1351     mergeState_DontMerge = 1  // Set on fatal error conditions to disable merging
1352 } mergeState_t;
1353 
1354 #define AUTH_GROUP_NAME_SIZE    128
1355 struct AuthGroup_struct             // Header object for a list of AuthRecords with the same name
1356 {
1357     AuthGroup      *next;               // Next AuthGroup object in this hash table bucket
1358     mDNSu32 namehash;                   // Name-based (i.e. case insensitive) hash of name
1359     AuthRecord     *members;            // List of CacheRecords with this same name
1360     AuthRecord    **rrauth_tail;        // Tail end of that list
1361     domainname     *name;               // Common name for all AuthRecords in this list
1362     AuthRecord     *NewLocalOnlyRecords;
1363     mDNSu8 namestorage[AUTH_GROUP_NAME_SIZE];
1364 };
1365 
1366 #ifndef AUTH_HASH_SLOTS
1367 #define AUTH_HASH_SLOTS 499
1368 #endif
1369 #define FORALL_AUTHRECORDS(SLOT,AG,AR)                              \
1370     for ((SLOT) = 0; (SLOT) < AUTH_HASH_SLOTS; (SLOT)++)                                                                     \
1371         for ((AG)=m->rrauth.rrauth_hash[(SLOT)]; (AG); (AG)=(AG)->next)                                                                         \
1372             for ((AR) = (AG)->members; (AR); (AR)=(AR)->next)
1373 
1374 typedef union AuthEntity_union AuthEntity;
1375 union AuthEntity_union { AuthEntity *next; AuthGroup ag; };
1376 typedef struct {
1377     mDNSu32 rrauth_size;                // Total number of available auth entries
1378     mDNSu32 rrauth_totalused;           // Number of auth entries currently occupied
1379     mDNSu32 rrauth_report;
1380     mDNSu8 rrauth_lock;                 // For debugging: Set at times when these lists may not be modified
1381     AuthEntity *rrauth_free;
1382     AuthGroup *rrauth_hash[AUTH_HASH_SLOTS];
1383 }AuthHash;
1384 
1385 // AuthRecordAny includes mDNSInterface_Any and interface specific auth records.
1386 typedef enum
1387 {
1388     AuthRecordAny,              // registered for *Any, NOT including P2P interfaces
1389     AuthRecordAnyIncludeP2P,    // registered for *Any, including P2P interfaces
1390     AuthRecordAnyIncludeAWDL,   // registered for *Any, including AWDL interface
1391     AuthRecordAnyIncludeAWDLandP2P, // registered for *Any, including AWDL and P2P interfaces
1392     AuthRecordLocalOnly,
1393     AuthRecordP2P,              // discovered over D2D/P2P framework
1394 } AuthRecType;
1395 
1396 #define AuthRecordIncludesAWDL(AR) \
1397     (((AR)->ARType == AuthRecordAnyIncludeAWDL) || ((AR)->ARType == AuthRecordAnyIncludeAWDLandP2P))
1398 
1399 typedef enum
1400 {
1401     AuthFlagsWakeOnly = 0x1     // WakeOnly service
1402 } AuthRecordFlags;
1403 
1404 struct AuthRecord_struct
1405 {
1406     // For examples of how to set up this structure for use in mDNS_Register(),
1407     // see mDNS_AdvertiseInterface() or mDNS_RegisterService().
1408     // Basically, resrec and persistent metadata need to be set up before calling mDNS_Register().
1409     // mDNS_SetupResourceRecord() is avaliable as a helper routine to set up most fields to sensible default values for you
1410 
1411     AuthRecord     *next;               // Next in list; first element of structure for efficiency reasons
1412     // Field Group 1: Common ResourceRecord fields
1413     ResourceRecord resrec;              // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit (now 44/64)
1414 
1415     // Field Group 2: Persistent metadata for Authoritative Records
1416     AuthRecord     *Additional1;        // Recommended additional record to include in response (e.g. SRV for PTR record)
1417     AuthRecord     *Additional2;        // Another additional (e.g. TXT for PTR record)
1418     AuthRecord     *DependentOn;        // This record depends on another for its uniqueness checking
1419     AuthRecord     *RRSet;              // This unique record is part of an RRSet
1420     mDNSRecordCallback *RecordCallback; // Callback function to call for state changes, and to free memory asynchronously on deregistration
1421     void           *RecordContext;      // Context parameter for the callback function
1422     mDNSu8 AutoTarget;                  // Set if the target of this record (PTR, CNAME, SRV, etc.) is our host name
1423     mDNSu8 AllowRemoteQuery;            // Set if we allow hosts not on the local link to query this record
1424     mDNSu8 ForceMCast;                  // Set by client to advertise solely via multicast, even for apparently unicast names
1425     mDNSu8 AuthFlags;
1426 
1427     OwnerOptData WakeUp;                // WakeUp.HMAC.l[0] nonzero indicates that this is a Sleep Proxy record
1428     mDNSAddr AddressProxy;              // For reverse-mapping Sleep Proxy PTR records, address in question
1429     mDNSs32 TimeRcvd;                   // In platform time units
1430     mDNSs32 TimeExpire;                 // In platform time units
1431     AuthRecType ARType;                 // LocalOnly, P2P or Normal ?
1432     mDNSs32 KATimeExpire;               // In platform time units: time to send keepalive packet for the proxy record
1433 
1434     // Field Group 3: Transient state for Authoritative Records
1435     mDNSs32 ProbingConflictCount;       // Number of conflicting records observed during probing.
1436     mDNSs32 LastConflictPktNum;         // Number of the last received packet that caused a probing conflict.
1437     mDNSu8 Acknowledged;                // Set if we've given the success callback to the client
1438     mDNSu8 ProbeRestartCount;           // Number of times we have restarted probing
1439     mDNSu8 ProbeCount;                  // Number of probes remaining before this record is valid (kDNSRecordTypeUnique)
1440     mDNSu8 AnnounceCount;               // Number of announcements remaining (kDNSRecordTypeShared)
1441     mDNSu8 RequireGoodbye;              // Set if this RR has been announced on the wire and will require a goodbye packet
1442     mDNSu8 AnsweredLocalQ;              // Set if this AuthRecord has been delivered to any local question (LocalOnly or mDNSInterface_Any)
1443     mDNSu8 IncludeInProbe;              // Set if this RR is being put into a probe right now
1444     mDNSu8 ImmedUnicast;                // Set if we may send our response directly via unicast to the requester
1445     mDNSInterfaceID SendNSECNow;        // Set if we need to generate associated NSEC data for this rrname
1446     mDNSInterfaceID ImmedAnswer;        // Someone on this interface issued a query we need to answer (all-ones for all interfaces)
1447 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
1448     mDNSs32 ImmedAnswerMarkTime;
1449 #endif
1450     mDNSInterfaceID ImmedAdditional;    // Hint that we might want to also send this record, just to be helpful
1451     mDNSInterfaceID SendRNow;           // The interface this query is being sent on right now
1452     mDNSv4Addr v4Requester;             // Recent v4 query for this record, or all-ones if more than one recent query
1453     mDNSv6Addr v6Requester;             // Recent v6 query for this record, or all-ones if more than one recent query
1454     AuthRecord     *NextResponse;       // Link to the next element in the chain of responses to generate
1455     const mDNSu8   *NR_AnswerTo;        // Set if this record was selected by virtue of being a direct answer to a question
1456     AuthRecord     *NR_AdditionalTo;    // Set if this record was selected by virtue of being additional to another
1457     mDNSs32 ThisAPInterval;             // In platform time units: Current interval for announce/probe
1458     mDNSs32 LastAPTime;                 // In platform time units: Last time we sent announcement/probe
1459     mDNSs32 LastMCTime;                 // Last time we multicast this record (used to guard against packet-storm attacks)
1460     mDNSInterfaceID LastMCInterface;    // Interface this record was multicast on at the time LastMCTime was recorded
1461     RData          *NewRData;           // Set if we are updating this record with new rdata
1462     mDNSu16 newrdlength;                // ... and the length of the new RData
1463     mDNSRecordUpdateCallback *UpdateCallback;
1464     mDNSu32 UpdateCredits;              // Token-bucket rate limiting of excessive updates
1465     mDNSs32 NextUpdateCredit;           // Time next token is added to bucket
1466     mDNSs32 UpdateBlocked;              // Set if update delaying is in effect
1467 
1468     // Field Group 4: Transient uDNS state for Authoritative Records
1469     regState_t state;           // Maybe combine this with resrec.RecordType state? Right now it's ambiguous and confusing.
1470                                 // e.g. rr->resrec.RecordType can be kDNSRecordTypeUnregistered,
1471                                 // and rr->state can be regState_Unregistered
1472                                 // What if we find one of those statements is true and the other false? What does that mean?
1473     mDNSBool uselease;          // dynamic update contains (should contain) lease option
1474     mDNSs32 expire;             // In platform time units: expiration of lease (-1 for static)
1475     mDNSBool Private;           // If zone is private, DNS updates may have to be encrypted to prevent eavesdropping
1476     mDNSOpaque16 updateid;      // Identifier to match update request and response -- also used when transferring records to Sleep Proxy
1477     mDNSOpaque64 updateIntID;   // Interface IDs (one bit per interface index)to which updates have been sent
1478     const domainname *zone;     // the zone that is updated
1479     ZoneData  *nta;
1480     struct tcpInfo_t *tcp;
1481     NATTraversalInfo NATinfo;
1482     mDNSBool SRVChanged;       // temporarily deregistered service because its SRV target or port changed
1483     mergeState_t mState;       // Unicast Record Registrations merge state
1484     mDNSu8 refreshCount;        // Number of refreshes to the server
1485     mStatus updateError;        // Record update resulted in Error ?
1486 
1487     // uDNS_UpdateRecord support fields
1488     // Do we really need all these in *addition* to NewRData and newrdlength above?
1489     void *UpdateContext;    // Context parameter for the update callback function
1490     mDNSu16 OrigRDLen;      // previously registered, being deleted
1491     mDNSu16 InFlightRDLen;  // currently being registered
1492     mDNSu16 QueuedRDLen;    // pending operation (re-transmitting if necessary) THEN register the queued update
1493     RData *OrigRData;
1494     RData *InFlightRData;
1495     RData *QueuedRData;
1496 
1497     // Field Group 5: Large data objects go at the end
1498     domainname namestorage;
1499     RData rdatastorage;                 // Normally the storage is right here, except for oversized records
1500     // rdatastorage MUST be the last thing in the structure -- when using oversized AuthRecords, extra bytes
1501     // are appended after the end of the AuthRecord, logically augmenting the size of the rdatastorage
1502     // DO NOT ADD ANY MORE FIELDS HERE
1503 };
1504 
1505 // IsLocalDomain alone is not sufficient to determine that a record is mDNS or uDNS. By default domain names within
1506 // the "local" pseudo-TLD (and within the IPv4 and IPv6 link-local reverse mapping domains) are automatically treated
1507 // as mDNS records, but it is also possible to force any record (even those not within one of the inherently local
1508 // domains) to be handled as an mDNS record by setting the ForceMCast flag, or by setting a non-zero InterfaceID.
1509 // For example, the reverse-mapping PTR record created in AdvertiseInterface sets the ForceMCast flag, since it points to
1510 // a dot-local hostname, and therefore it would make no sense to register this record with a wide-area Unicast DNS server.
1511 // The same applies to Sleep Proxy records, which we will answer for when queried via mDNS, but we never want to try
1512 // to register them with a wide-area Unicast DNS server -- and we probably don't have the required credentials anyway.
1513 // Currently we have no concept of a wide-area uDNS record scoped to a particular interface, so if the InterfaceID is
1514 // nonzero we treat this the same as ForceMCast.
1515 // Note: Question_uDNS(Q) is used in *only* one place -- on entry to mDNS_StartQuery_internal, to decide whether to set TargetQID.
1516 // Everywhere else in the code, the determination of whether a question is unicast is made by checking to see if TargetQID is nonzero.
1517 #define AuthRecord_uDNS(R) ((R)->resrec.InterfaceID == mDNSInterface_Any && !(R)->ForceMCast && !IsLocalDomain((R)->resrec.name))
1518 #define Question_uDNS(Q)   ((Q)->IsUnicastDotLocal || (Q)->ProxyQuestion || \
1519                             ((Q)->InterfaceID != mDNSInterface_LocalOnly && (Q)->InterfaceID != mDNSInterface_P2P && (Q)->InterfaceID != mDNSInterface_BLE && !(Q)->ForceMCast && !IsLocalDomain(&(Q)->qname)))
1520 
1521 // AuthRecordLocalOnly records are registered using mDNSInterface_LocalOnly and
1522 // AuthRecordP2P records are created by D2DServiceFound events.  Both record types are kept on the same list.
1523 #define RRLocalOnly(rr) ((rr)->ARType == AuthRecordLocalOnly || (rr)->ARType == AuthRecordP2P)
1524 
1525 // All other auth records, not including those defined as RRLocalOnly().
1526 #define RRAny(rr) ((rr)->ARType == AuthRecordAny || (rr)->ARType == AuthRecordAnyIncludeP2P || (rr)->ARType == AuthRecordAnyIncludeAWDL || (rr)->ARType == AuthRecordAnyIncludeAWDLandP2P)
1527 
1528 // Normally we always lookup the cache and /etc/hosts before sending the query on the wire. For single label
1529 // queries (A and AAAA) that are unqualified (indicated by AppendSearchDomains), we want to append search
1530 // domains before we try them as such
1531 #define ApplySearchDomainsFirst(q) ((q)->AppendSearchDomains && (CountLabels(&((q)->qname))) == 1)
1532 
1533 // Wrapper struct for Auth Records for higher-level code that cannot use the AuthRecord's ->next pointer field
1534 typedef struct ARListElem
1535 {
1536     struct ARListElem *next;
1537     AuthRecord ar;          // Note: Must be last element of structure, to accomodate oversized AuthRecords
1538 } ARListElem;
1539 
1540 struct CacheRecord_struct
1541 {
1542     CacheRecord    *next;               // Next in list; first element of structure for efficiency reasons
1543     ResourceRecord resrec;              // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit (now 44/64)
1544 
1545     // Transient state for Cache Records
1546     CacheRecord    *NextInKAList;       // Link to the next element in the chain of known answers to send
1547     mDNSs32 TimeRcvd;                   // In platform time units
1548     mDNSs32 DelayDelivery;              // Set if we want to defer delivery of this answer to local clients
1549     mDNSs32 NextRequiredQuery;          // In platform time units
1550 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
1551     mDNSs32 LastCachedAnswerTime;       // Last time this record was used as an answer from the cache (before a query)
1552                                         // In platform time units
1553 #else
1554     // Extra four bytes here (on 64bit)
1555 #endif
1556     DNSQuestion    *CRActiveQuestion;   // Points to an active question referencing this answer. Can never point to a NewQuestion.
1557     mDNSs32 LastUnansweredTime;         // In platform time units; last time we incremented UnansweredQueries
1558     mDNSu8  UnansweredQueries;          // Number of times we've issued a query for this record without getting an answer
1559     mDNSOpaque16 responseFlags;         // Second 16 bit in the DNS response
1560     CacheRecord    *NextInCFList;       // Set if this is in the list of records we just received with the cache flush bit set
1561     CacheRecord    *soa;                // SOA record to return for proxy questions
1562 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
1563     void *denial_of_existence_records;  // denial_of_existence_records_t
1564 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
1565 
1566     mDNSAddr sourceAddress;             // node from which we received this record
1567     // Size to here is 76 bytes when compiling 32-bit; 104 bytes when compiling 64-bit (now 160 bytes for 64-bit)
1568     RData_small smallrdatastorage;      // Storage for small records is right here (4 bytes header + 68 bytes data = 72 bytes)
1569 };
1570 
1571 // Should match the CacheGroup_struct members, except namestorage[].  Only used to calculate
1572 // the size of the namestorage array in CacheGroup_struct so that sizeof(CacheGroup) == sizeof(CacheRecord)
1573 struct CacheGroup_base
1574 {
1575     CacheGroup     *next;
1576     mDNSu32         namehash;
1577     CacheRecord    *members;
1578     CacheRecord   **rrcache_tail;
1579     domainname     *name;
1580 };
1581 
1582 struct CacheGroup_struct                // Header object for a list of CacheRecords with the same name
1583 {
1584     CacheGroup     *next;               // Next CacheGroup object in this hash table bucket
1585     mDNSu32         namehash;           // Name-based (i.e. case insensitive) hash of name
1586     CacheRecord    *members;            // List of CacheRecords with this same name
1587     CacheRecord   **rrcache_tail;       // Tail end of that list
1588     domainname     *name;               // Common name for all CacheRecords in this list
1589     mDNSu8 namestorage[sizeof(CacheRecord) - sizeof(struct CacheGroup_base)];  // match sizeof(CacheRecord)
1590 };
1591 
1592 // Storage sufficient to hold either a CacheGroup header or a CacheRecord
1593 // -- for best efficiency (to avoid wasted unused storage) they should be the same size
1594 typedef union CacheEntity_union CacheEntity;
1595 union CacheEntity_union { CacheEntity *next; CacheGroup cg; CacheRecord cr; };
1596 
1597 typedef struct
1598 {
1599     CacheRecord r;
1600     mDNSu8 _extradata[MaximumRDSize-InlineCacheRDSize];     // Glue on the necessary number of extra bytes
1601     domainname namestorage;                                 // Needs to go *after* the extra rdata bytes
1602 } LargeCacheRecord;
1603 
1604 typedef struct HostnameInfo
1605 {
1606     struct HostnameInfo *next;
1607     NATTraversalInfo natinfo;
1608     domainname fqdn;
1609     AuthRecord arv4;                          // registered IPv4 address record
1610     AuthRecord arv6;                          // registered IPv6 address record
1611     mDNSRecordCallback *StatusCallback;       // callback to deliver success or error code to client layer
1612     const void *StatusContext;                // Client Context
1613 } HostnameInfo;
1614 
1615 typedef struct ExtraResourceRecord_struct ExtraResourceRecord;
1616 struct ExtraResourceRecord_struct
1617 {
1618     ExtraResourceRecord *next;
1619     mDNSu32 ClientID;  // Opaque ID field to be used by client to map an AddRecord call to a set of Extra records
1620     AuthRecord r;
1621     // Note: Add any additional fields *before* the AuthRecord in this structure, not at the end.
1622     // In some cases clients can allocate larger chunks of memory and set r->rdata->MaxRDLength to indicate
1623     // that this extra memory is available, which would result in any fields after the AuthRecord getting smashed
1624 };
1625 
1626 // Note: Within an mDNSServiceCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
1627 typedef void mDNSServiceCallback (mDNS *const m, ServiceRecordSet *const sr, mStatus result);
1628 
1629 // A ServiceRecordSet has no special meaning to the core code of the Multicast DNS protocol engine;
1630 // it is just a convenience structure to group together the records that make up a standard service
1631 // registration so that they can be allocted and deallocted together as a single memory object.
1632 // It contains its own ServiceCallback+ServiceContext to report aggregate results up to the next layer of software above.
1633 // It also contains:
1634 //  * the basic PTR/SRV/TXT triplet used to represent any DNS-SD service
1635 //  * the "_services" PTR record for service enumeration
1636 //  * the optional list of SubType PTR records
1637 //  * the optional list of additional records attached to the service set (e.g. iChat pictures)
1638 
1639 struct ServiceRecordSet_struct
1640 {
1641     // These internal state fields are used internally by mDNSCore; the client layer needn't be concerned with them.
1642     // No fields need to be set up by the client prior to calling mDNS_RegisterService();
1643     // all required data is passed as parameters to that function.
1644     mDNSServiceCallback *ServiceCallback;
1645     void                *ServiceContext;
1646     mDNSBool Conflict;              // Set if this record set was forcibly deregistered because of a conflict
1647 
1648     ExtraResourceRecord *Extras;    // Optional list of extra AuthRecords attached to this service registration
1649     mDNSu32 NumSubTypes;
1650     AuthRecord          *SubTypes;
1651     mDNSu32             flags;      // saved for subsequent calls to mDNS_RegisterService() if records
1652                                     // need to be re-registered.
1653     AuthRecord RR_ADV;              // e.g. _services._dns-sd._udp.local. PTR _printer._tcp.local.
1654     AuthRecord RR_PTR;              // e.g. _printer._tcp.local.        PTR Name._printer._tcp.local.
1655     AuthRecord RR_SRV;              // e.g. Name._printer._tcp.local.   SRV 0 0 port target
1656     AuthRecord RR_TXT;              // e.g. Name._printer._tcp.local.   TXT PrintQueueName
1657     // Don't add any fields after AuthRecord RR_TXT.
1658     // This is where the implicit extra space goes if we allocate a ServiceRecordSet containing an oversized RR_TXT record
1659 };
1660 
1661 // ***************************************************************************
1662 #if 0
1663 #pragma mark -
1664 #pragma mark - Question structures
1665 #endif
1666 
1667 // We record the last eight instances of each duplicate query
1668 // This gives us v4/v6 on each of Ethernet, AirPort and Firewire, and two free slots "for future expansion"
1669 // If the host has more active interfaces that this it is not fatal -- duplicate question suppression will degrade gracefully.
1670 // Since we will still remember the last eight, the busiest interfaces will still get the effective duplicate question suppression.
1671 #define DupSuppressInfoSize 8
1672 
1673 typedef struct
1674 {
1675     mDNSs32 Time;
1676     mDNSInterfaceID InterfaceID;
1677     mDNSs32 Type;                           // v4 or v6?
1678 } DupSuppressInfo;
1679 
1680 typedef enum
1681 {
1682     // This is the initial state.
1683     LLQ_Init = 1,
1684 
1685     // All of these states indicate that we are doing DNS Push, and haven't given up yet.
1686 	LLQ_DNSPush_ServerDiscovery = 100,
1687 	LLQ_DNSPush_Connecting      = 101,
1688 	LLQ_DNSPush_Established     = 102,
1689 
1690     // All of these states indicate that we are doing LLQ and haven't given up yet.
1691     LLQ_InitialRequest   = 200,
1692     LLQ_SecondaryRequest = 201,
1693     LLQ_Established      = 202,
1694 
1695     // If we get here, it means DNS Push isn't available, so we're polling.
1696     LLQ_Poll                    = 300
1697 } LLQ_State;
1698 
1699 // LLQ constants
1700 #define kLLQ_Vers      1
1701 #define kLLQ_DefLease  7200 // 2 hours
1702 #define kLLQ_MAX_TRIES 3    // retry an operation 3 times max
1703 #define kLLQ_INIT_RESEND 2 // resend an un-ack'd packet after 2 seconds, then double for each additional
1704 // LLQ Operation Codes
1705 #define kLLQOp_Setup     1
1706 #define kLLQOp_Refresh   2
1707 #define kLLQOp_Event     3
1708 
1709 // LLQ Errror Codes
1710 enum
1711 {
1712     LLQErr_NoError    = 0,
1713     LLQErr_ServFull   = 1,
1714     LLQErr_Static     = 2,
1715     LLQErr_FormErr    = 3,
1716     LLQErr_NoSuchLLQ  = 4,
1717     LLQErr_BadVers    = 5,
1718     LLQErr_UnknownErr = 6
1719 };
1720 
1721 enum { NoAnswer_Normal = 0, NoAnswer_Suspended = 1, NoAnswer_Fail = 2 };
1722 
1723 typedef enum {
1724     DNSPushServerDisconnected,
1725 	DNSPushServerConnectFailed,
1726 	DNSPushServerConnectionInProgress,
1727 	DNSPushServerConnected,
1728 	DNSPushServerSessionEstablished,
1729 	DNSPushServerNoDNSPush
1730 } DNSPushServer_ConnectState;
1731 
1732 enum {
1733     AllowExpired_None = 0,                  // Don't allow expired answers or mark answers immortal (behave normally)
1734     AllowExpired_MakeAnswersImmortal = 1,   // Any answers to this question get marked as immortal
1735     AllowExpired_AllowExpiredAnswers = 2    // Allow already expired answers from the cache
1736 };
1737 typedef mDNSu8 AllowExpiredState;
1738 
1739 #define HMAC_LEN    64
1740 #define HMAC_IPAD   0x36
1741 #define HMAC_OPAD   0x5c
1742 #define MD5_LEN     16
1743 
1744 // Internal data structure to maintain authentication information
1745 typedef struct DomainAuthInfo
1746 {
1747     struct DomainAuthInfo *next;
1748     mDNSs32 deltime;                        // If we're planning to delete this DomainAuthInfo, the time we want it deleted
1749     domainname domain;
1750     domainname keyname;
1751     domainname hostname;
1752     mDNSIPPort port;
1753     char b64keydata[32];
1754     mDNSu8 keydata_ipad[HMAC_LEN];              // padded key for inner hash rounds
1755     mDNSu8 keydata_opad[HMAC_LEN];              // padded key for outer hash rounds
1756 } DomainAuthInfo;
1757 
1758 // Note: Within an mDNSQuestionCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
1759 // Note: Any value other than QC_rmv i.e., any non-zero value will result in kDNSServiceFlagsAdd to the application
1760 // layer. These values are used within mDNSResponder and not sent across to the application. QC_addnocache is for
1761 // delivering a response without adding to the cache. QC_forceresponse is superset of QC_addnocache where in
1762 // addition to not entering in the cache, it also forces the negative response through.
1763 typedef enum { QC_rmv = 0, QC_add, QC_addnocache, QC_forceresponse, QC_suppressed } QC_result;
1764 typedef void mDNSQuestionCallback (mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord);
1765 typedef void (*mDNSQuestionResetHandler)(DNSQuestion *question);
1766 typedef void AsyncDispatchFunc(mDNS *const m, void *context);
1767 extern void mDNSPlatformDispatchAsync(mDNS *const m, void *context, AsyncDispatchFunc func);
1768 
1769 #define NextQSendTime(Q)  ((Q)->LastQTime + (Q)->ThisQInterval)
1770 #define ActiveQuestion(Q) ((Q)->ThisQInterval > 0 && !(Q)->DuplicateOf)
1771 #define TimeToSendThisQuestion(Q,time) (ActiveQuestion(Q) && (time) - NextQSendTime(Q) >= 0)
1772 
1773 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
1774 #define FollowCNAMEOptionDNSSEC(Q)      !(Q)->DNSSECStatus.enable_dnssec
1775 #else // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
1776 #define FollowCNAMEOptionDNSSEC(Q)      mDNStrue
1777 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
1778 
1779 // Given the resource record and the question, should we follow the CNAME ?
1780 #define FollowCNAME(q, rr, AddRecord)   (AddRecord && (q)->qtype != kDNSType_CNAME && \
1781                                          (rr)->RecordType != kDNSRecordTypePacketNegative && \
1782                                          (rr)->rrtype == kDNSType_CNAME \
1783                                          && FollowCNAMEOptionDNSSEC(q))
1784 
1785 // RFC 4122 defines it to be 16 bytes
1786 #define UUID_SIZE       16
1787 
1788 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
1789 enum
1790 {
1791     ExpiredAnswer_None = 0,                  // No expired answers used
1792     ExpiredAnswer_Allowed = 1,               // An expired answer is allowed by this request
1793     ExpiredAnswer_AnsweredWithCache = 2,     // Question was answered with a cached answer
1794     ExpiredAnswer_AnsweredWithExpired = 3,   // Question was answered with an expired answer
1795     ExpiredAnswer_ExpiredAnswerChanged = 4,  // Expired answer changed on refresh
1796 
1797     ExpiredAnswer_EnumCount
1798 };
1799 typedef mDNSu8 ExpiredAnswerMetric;
1800 
1801 enum
1802 {
1803     DNSOverTCP_None = 0,                     // DNS Over TCP not used
1804     DNSOverTCP_Truncated = 1,                // DNS Over TCP used because UDP reply was truncated
1805     DNSOverTCP_Suspicious = 2,               // DNS Over TCP used because we received a suspicious reply
1806     DNSOverTCP_SuspiciousDefense = 3,        // DNS Over TCP used because we were within the timeframe of a previous suspicious response
1807 
1808     DNSOverTCP_EnumCount
1809 };
1810 typedef mDNSu8 DNSOverTCPMetric;
1811 
1812 typedef struct
1813 {
1814     domainname *        originalQName;          // Name of original A/AAAA record if this question is for a CNAME record.
1815     mDNSu32             querySendCount;         // Number of queries that have been sent to DNS servers so far.
1816     mDNSs32             firstQueryTime;         // The time when the first query was sent to a DNS server.
1817     mDNSBool            answered;               // Has this question been answered?
1818     ExpiredAnswerMetric expiredAnswerState;     // Expired answer state (see ExpiredAnswerMetric above)
1819     DNSOverTCPMetric    dnsOverTCPState;        // DNS Over TCP state (see DNSOverTCPMetric above)
1820 
1821 }   uDNSMetrics;
1822 #endif
1823 
1824 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
1825 extern mDNSu32 curr_num_regservices; // tracks the current number of services registered
1826 extern mDNSu32 max_num_regservices;  // tracks the max number of simultaneous services registered by the device
1827 #endif
1828 
1829 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
1830 #include "DNS64State.h"
1831 #endif
1832 
1833 typedef struct mDNS_DNSPushNotificationServer DNSPushNotificationServer;
1834 typedef struct mDNS_DNSPushNotificationZone   DNSPushNotificationZone;
1835 
1836 struct DNSQuestion_struct
1837 {
1838     // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1839     DNSQuestion          *next;
1840     mDNSu32 qnamehash;
1841     mDNSs32 DelayAnswering;                 // Set if we want to defer answering this question until the cache settles
1842     mDNSs32 LastQTime;                      // Last scheduled transmission of this Q on *all* applicable interfaces
1843     mDNSs32 ThisQInterval;                  // LastQTime + ThisQInterval is the next scheduled transmission of this Q
1844                                             // ThisQInterval > 0 for an active question;
1845                                             // ThisQInterval = 0 for a suspended question that's still in the list
1846                                             // ThisQInterval = -1 for a cancelled question (should not still be in list)
1847     mDNSs32 ExpectUnicastResp;              // Set when we send a query with the kDNSQClass_UnicastResponse bit set
1848     mDNSs32 LastAnswerPktNum;               // The sequence number of the last response packet containing an answer to this Q
1849     mDNSu32 RecentAnswerPkts;               // Number of answers since the last time we sent this query
1850     mDNSu32 CurrentAnswers;                 // Number of records currently in the cache that answer this question
1851     mDNSu32 BrowseThreshold;                // If we have received at least this number of answers,
1852                                             // set the next question interval to MaxQuestionInterval
1853     mDNSu32 LargeAnswers;                   // Number of answers with rdata > 1024 bytes
1854     mDNSu32 UniqueAnswers;                  // Number of answers received with kDNSClass_UniqueRRSet bit set
1855     mDNSInterfaceID FlappingInterface1;     // Set when an interface goes away, to flag if remove events are delivered for this Q
1856     mDNSInterfaceID FlappingInterface2;     // Set when an interface goes away, to flag if remove events are delivered for this Q
1857     DomainAuthInfo       *AuthInfo;         // Non-NULL if query is currently being done using Private DNS
1858     DNSQuestion          *DuplicateOf;
1859     DNSQuestion          *NextInDQList;
1860     DupSuppressInfo DupSuppress[DupSuppressInfoSize];
1861     mDNSInterfaceID SendQNow;               // The interface this query is being sent on right now
1862     mDNSBool SendOnAll;                     // Set if we're sending this question on all active interfaces
1863     mDNSBool CachedAnswerNeedsUpdate;       // See SendQueries().  Set if we're sending this question
1864                                             // because a cached answer needs to be refreshed.
1865     mDNSu32 RequestUnicast;                 // Non-zero if we want to send query with kDNSQClass_UnicastResponse bit set
1866     mDNSs32 LastQTxTime;                    // Last time this Q was sent on one (but not necessarily all) interfaces
1867     mDNSu32 CNAMEReferrals;                 // Count of how many CNAME redirections we've done
1868     mDNSBool Suppressed;                    // This query should be suppressed, i.e., not sent on the wire.
1869     mDNSu8 LOAddressAnswers;                // Number of answers from the local only auth records that are
1870                                             // answering A, AAAA, CNAME, or PTR (/etc/hosts)
1871     mDNSu8 WakeOnResolveCount;              // Number of wakes that should be sent on resolve
1872     mDNSBool InitialCacheMiss;              // True after the question cannot be answered from the cache
1873     mDNSs32 StopTime;                       // Time this question should be stopped by giving them a negative answer
1874 
1875     // Wide Area fields. These are used internally by the uDNS core (Unicast)
1876     UDPSocket            *LocalSocket;
1877 
1878     // |-> DNS Configuration related fields used in uDNS (Subset of Wide Area/Unicast fields)
1879 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
1880     mdns_dns_service_t    dnsservice;       // The current DNS service.
1881     mdns_dns_service_id_t lastDNSServiceID; // The ID of the previous DNS service before a CNAME restart.
1882     mdns_querier_t        querier;          // The current querier.
1883 #else
1884     DNSServer            *qDNSServer;       // Caching server for this query (in the absence of an SRV saying otherwise)
1885     mDNSOpaque128 validDNSServers;          // Valid DNSServers for this question
1886     mDNSu16 noServerResponse;               // At least one server did not respond.
1887     mDNSBool triedAllServersOnce;           // True if all DNS servers have been tried once.
1888     mDNSu8 unansweredQueries;               // The number of unanswered queries to this server
1889 #endif
1890     AllowExpiredState allowExpired;         // Allow expired answers state (see enum AllowExpired_None, etc. above)
1891 
1892     ZoneData             *nta;              // Used for getting zone data for private or LLQ query
1893     mDNSAddr servAddr;                      // Address and port learned from _dns-llq, _dns-llq-tls or _dns-query-tls SRV query
1894     mDNSIPPort servPort;
1895     struct tcpInfo_t *tcp;
1896     mDNSIPPort tcpSrcPort;                  // Local Port TCP packet received on;need this as tcp struct is disposed
1897                                             // by tcpCallback before calling into mDNSCoreReceive
1898     mDNSu8 NoAnswer;                        // Set if we want to suppress answers until tunnel setup has completed
1899 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
1900     mDNSBool Restart;                       // This question should be restarted soon.
1901 #endif
1902 
1903     // LLQ-specific fields. These fields are only meaningful when LongLived flag is set
1904     LLQ_State state;
1905     mDNSu32 ReqLease;                       // seconds (relative)
1906     mDNSs32 expire;                         // ticks (absolute)
1907     mDNSs16 ntries;                         // for UDP: the number of packets sent for this LLQ state
1908                                             // for TCP: there is some ambiguity in the use of this variable, but in general, it is
1909                                             //          the number of TCP/TLS connection attempts for this LLQ state, or
1910                                             //          the number of packets sent for this TCP/TLS connection
1911 
1912     // DNS Push Notification fields. These fields are only meaningful when LongLived flag is set
1913     DNSPushNotificationServer *dnsPushServer;
1914 
1915     mDNSOpaque64 id;
1916 
1917     // DNS Proxy fields
1918     mDNSOpaque16 responseFlags;             // Temporary place holder for the error we get back from the DNS server
1919                                             // till we populate in the cache
1920     mDNSBool     BlockedByPolicy;           // True if the question is blocked by policy rule evaluation.
1921     mDNSs32      ServiceID;                 // Service identifier to match against the DNS server
1922 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
1923     mDNSu8       ResolverUUID[UUID_SIZE];   // Resolver UUID to match against the DNS server
1924     mdns_dns_service_id_t CustomID;
1925 #endif
1926 
1927     // Client API fields: The client must set up these fields *before* calling mDNS_StartQuery()
1928     mDNSInterfaceID InterfaceID;            // Non-zero if you want to issue queries only on a single specific IP interface
1929     mDNSu32  flags;                         // flags from original DNSService*() API request.
1930     mDNSOpaque16 TargetQID;                 // DNS or mDNS message ID.
1931     domainname qname;
1932     domainname firstExpiredQname;           // first expired qname in request chain
1933     mDNSu16 qtype;
1934     mDNSu16 qclass;
1935     mDNSBool LongLived;                     // Set by client for calls to mDNS_StartQuery to indicate LLQs to unicast layer.
1936     mDNSBool ExpectUnique;                  // Set by client if it's expecting unique RR(s) for this question, not shared RRs
1937     mDNSBool ForceMCast;                    // Set by client to force mDNS query, even for apparently uDNS names
1938     mDNSBool ReturnIntermed;                // Set by client to request callbacks for intermediate CNAME/NXDOMAIN results
1939     mDNSBool SuppressUnusable;              // Set by client to suppress unusable queries to be sent on the wire
1940     mDNSBool TimeoutQuestion;               // Timeout this question if there is no reply in configured time
1941     mDNSBool IsUnicastDotLocal;             // True if this is a dot-local query that should be answered via unicast DNS.
1942     mDNSBool WakeOnResolve;                 // Send wakeup on resolve
1943     mDNSBool UseBackgroundTraffic;          // Set by client to use background traffic class for request
1944     mDNSBool AppendSearchDomains;           // Search domains can be appended for this query
1945     mDNSBool ForcePathEval;                 // Perform a path evaluation even if kDNSServiceFlagsPathEvaluationDone is set.
1946 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
1947     mDNSBool RequireEncryption;             // Set by client to require encrypted queries
1948 #endif
1949 #if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
1950     mDNSBool inAppBrowserRequest;           // Is request associated with an in-app-browser
1951     audit_token_t  peerAuditToken;          // audit token of the peer requesting the question
1952     audit_token_t  delegateAuditToken;      // audit token of the delegated client the question is for
1953 #endif
1954     mDNSu8 ProxyQuestion;                   // Proxy Question
1955     mDNSs32 pid;                            // Process ID of the client that is requesting the question
1956     mDNSu8  uuid[UUID_SIZE];                // Unique ID of the client that is requesting the question (valid only if pid is zero)
1957     mDNSu32 euid;                           // Effective User Id of the client that is requesting the question
1958     mDNSu32 request_id;                     // The ID of request that generates the current question
1959     mDNSQuestionCallback *QuestionCallback;
1960     mDNSQuestionResetHandler ResetHandler;
1961     void                 *QuestionContext;
1962 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
1963     uDNSMetrics metrics;                    // Data used for collecting unicast DNS query metrics.
1964 #endif
1965 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
1966     DNS64 dns64;                            // DNS64 state for performing IPv6 address synthesis on networks with NAT64.
1967 #endif
1968 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
1969     dnssec_status_t DNSSECStatus;           // DNSSEC state for fectching DNSSEC records and doing validation
1970 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
1971 };
1972 
1973 typedef enum { ZoneServiceUpdate, ZoneServiceQuery, ZoneServiceLLQ, ZoneServiceDNSPush } ZoneService;
1974 
1975 typedef void ZoneDataCallback (mDNS *const m, mStatus err, const ZoneData *result);
1976 
1977 struct ZoneData_struct
1978 {
1979     domainname ChildName;               // Name for which we're trying to find the responsible server
1980     ZoneService ZoneService;            // Which service we're seeking for this zone (update, query, or LLQ)
1981     domainname       *CurrentSOA;       // Points to somewhere within ChildName
1982     domainname ZoneName;                // Discovered result: Left-hand-side of SOA record
1983     mDNSu16 ZoneClass;                  // Discovered result: DNS Class from SOA record
1984     domainname Host;                    // Discovered result: Target host from SRV record
1985     mDNSIPPort Port;                    // Discovered result: Update port, query port, or LLQ port from SRV record
1986     mDNSAddr Addr;                      // Discovered result: Address of Target host from SRV record
1987     mDNSBool ZonePrivate;               // Discovered result: Does zone require encrypted queries?
1988     ZoneDataCallback *ZoneDataCallback; // Caller-specified function to be called upon completion
1989     void             *ZoneDataContext;
1990     DNSQuestion question;               // Storage for any active question
1991 };
1992 
1993 extern ZoneData *StartGetZoneData(mDNS *const m, const domainname *const name, const ZoneService target, ZoneDataCallback callback, void *callbackInfo);
1994 extern void CancelGetZoneData(mDNS *const m, ZoneData *nta);
1995 extern mDNSBool IsGetZoneDataQuestion(DNSQuestion *q);
1996 
1997 typedef struct DNameListElem
1998 {
1999     struct DNameListElem *next;
2000     mDNSu32 uid;
2001     domainname name;
2002 } DNameListElem;
2003 
2004 #if APPLE_OSX_mDNSResponder
2005 // Different states that we go through locating the peer
2006 #define TC_STATE_AAAA_PEER          0x000000001     /* Peer's BTMM IPv6 address */
2007 #define TC_STATE_AAAA_PEER_RELAY    0x000000002     /* Peer's IPv6 Relay address */
2008 #define TC_STATE_SRV_PEER           0x000000003     /* Peer's SRV Record corresponding to IPv4 address */
2009 #define TC_STATE_ADDR_PEER          0x000000004     /* Peer's IPv4 address */
2010 
2011 typedef struct ClientTunnel
2012 {
2013     struct ClientTunnel *next;
2014     domainname dstname;
2015     mDNSBool MarkedForDeletion;
2016     mDNSv6Addr loc_inner;
2017     mDNSv4Addr loc_outer;
2018     mDNSv6Addr loc_outer6;
2019     mDNSv6Addr rmt_inner;
2020     mDNSv4Addr rmt_outer;
2021     mDNSv6Addr rmt_outer6;
2022     mDNSIPPort rmt_outer_port;
2023     mDNSu16 tc_state;
2024     DNSQuestion q;
2025 } ClientTunnel;
2026 #endif
2027 
2028 // ***************************************************************************
2029 #if 0
2030 #pragma mark -
2031 #pragma mark - NetworkInterfaceInfo_struct
2032 #endif
2033 
2034 typedef struct NetworkInterfaceInfo_struct NetworkInterfaceInfo;
2035 
2036 // A NetworkInterfaceInfo_struct serves two purposes:
2037 // 1. It holds the address, PTR and HINFO records to advertise a given IP address on a given physical interface
2038 // 2. It tells mDNSCore which physical interfaces are available; each physical interface has its own unique InterfaceID.
2039 //    Since there may be multiple IP addresses on a single physical interface,
2040 //    there may be multiple NetworkInterfaceInfo_structs with the same InterfaceID.
2041 //    In this case, to avoid sending the same packet n times, when there's more than one
2042 //    struct with the same InterfaceID, mDNSCore picks one member of the set to be the
2043 //    active representative of the set; all others have the 'InterfaceActive' flag unset.
2044 
2045 struct NetworkInterfaceInfo_struct
2046 {
2047     // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
2048     NetworkInterfaceInfo *next;
2049 
2050     mDNSu8 InterfaceActive;             // Set if interface is sending & receiving packets (see comment above)
2051     mDNSu8 IPv4Available;               // If InterfaceActive, set if v4 available on this InterfaceID
2052     mDNSu8 IPv6Available;               // If InterfaceActive, set if v6 available on this InterfaceID
2053 
2054     DNSQuestion NetWakeBrowse;
2055     DNSQuestion NetWakeResolve[3];      // For fault-tolerance, we try up to three Sleep Proxies
2056     mDNSAddr SPSAddr[3];
2057     mDNSIPPort SPSPort[3];
2058     mDNSs32 NextSPSAttempt;             // -1 if we're not currently attempting to register with any Sleep Proxy
2059     mDNSs32 NextSPSAttemptTime;
2060 
2061     // Standard AuthRecords that every Responder host should have (one per active IP address)
2062     AuthRecord RR_A;                    // 'A' or 'AAAA' (address) record for our ".local" name
2063     AuthRecord RR_PTR;                  // PTR (reverse lookup) record
2064 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
2065     AuthRecord RR_AddrRand;             // For non-AWDL interfaces, this is the A or AAAA record of the randomized hostname.
2066 #endif
2067 
2068     // Client API fields: The client must set up these fields *before* calling mDNS_RegisterInterface()
2069     mDNSInterfaceID InterfaceID;        // Identifies physical interface; MUST NOT be 0, -1, or -2
2070     mDNSAddr ip;                        // The IPv4 or IPv6 address to advertise
2071     mDNSAddr mask;
2072     mDNSEthAddr MAC;
2073     char ifname[64];                    // Windows uses a GUID string for the interface name, which doesn't fit in 16 bytes
2074     mDNSu8 Advertise;                   // False if you are only searching on this interface
2075     mDNSu8 McastTxRx;                   // Send/Receive multicast on this { InterfaceID, address family } ?
2076     mDNSu8 NetWake;                     // Set if Wake-On-Magic-Packet is enabled on this interface
2077     mDNSu8 Loopback;                    // Set if this is the loopback interface
2078     mDNSu8 IgnoreIPv4LL;                // Set if IPv4 Link-Local addresses have to be ignored.
2079     mDNSu8 SendGoodbyes;                // Send goodbyes on this interface while sleeping
2080     mDNSBool DirectLink;                // a direct link, indicating we can skip the probe for
2081                                         // address records
2082     mDNSBool SupportsUnicastMDNSResponse;  // Indicates that the interface supports unicast responses
2083                                         // to Bonjour queries.  Generally true for an interface.
2084 };
2085 
2086 #define SLE_DELETE                      0x00000001
2087 #define SLE_WAB_BROWSE_QUERY_STARTED    0x00000002
2088 #define SLE_WAB_LBROWSE_QUERY_STARTED   0x00000004
2089 #define SLE_WAB_REG_QUERY_STARTED       0x00000008
2090 
2091 typedef struct SearchListElem
2092 {
2093     struct SearchListElem *next;
2094     domainname domain;
2095     int flag;
2096     mDNSInterfaceID InterfaceID;
2097     DNSQuestion BrowseQ;
2098     DNSQuestion DefBrowseQ;
2099     DNSQuestion AutomaticBrowseQ;
2100     DNSQuestion RegisterQ;
2101     DNSQuestion DefRegisterQ;
2102     int numCfAnswers;
2103     ARListElem *AuthRecs;
2104 } SearchListElem;
2105 
2106 // For domain enumeration and automatic browsing
2107 // This is the user's DNS search list.
2108 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
2109 // to discover recommended domains for domain enumeration (browse, default browse, registration,
2110 // default registration) and possibly one or more recommended automatic browsing domains.
2111 extern SearchListElem *SearchList;      // This really ought to be part of mDNS_struct -- SC
2112 
2113 // ***************************************************************************
2114 #if 0
2115 #pragma mark -
2116 #pragma mark - Main mDNS object, used to hold all the mDNS state
2117 #endif
2118 
2119 typedef void mDNSCallback (mDNS *const m, mStatus result);
2120 
2121 #ifndef CACHE_HASH_SLOTS
2122 #define CACHE_HASH_SLOTS 499
2123 #endif
2124 
2125 enum
2126 {
2127     SleepState_Awake = 0,
2128     SleepState_Transferring = 1,
2129     SleepState_Sleeping = 2
2130 };
2131 
2132 typedef struct
2133 {
2134     mDNSu32 NameConflicts;                  // Normal Name conflicts
2135     mDNSu32 KnownUniqueNameConflicts;       // Name Conflicts for KnownUnique Records
2136     mDNSu32 DupQuerySuppressions;           // Duplicate query suppressions
2137     mDNSu32 KnownAnswerSuppressions;        // Known Answer suppressions
2138     mDNSu32 KnownAnswerMultiplePkts;        // Known Answer in queries spannign multiple packets
2139     mDNSu32 PoofCacheDeletions;             // Number of times the cache was deleted due to POOF
2140     mDNSu32 UnicastBitInQueries;            // Queries with QU bit set
2141     mDNSu32 NormalQueries;                  // Queries with QU bit not set
2142     mDNSu32 MatchingAnswersForQueries;      // Queries for which we had a response
2143     mDNSu32 UnicastResponses;               // Unicast responses to queries
2144     mDNSu32 MulticastResponses;             // Multicast responses to queries
2145     mDNSu32 UnicastDemotedToMulticast;      // Number of times unicast demoted to multicast
2146     mDNSu32 Sleeps;                         // Total sleeps
2147     mDNSu32 Wakes;                          // Total wakes
2148     mDNSu32 InterfaceUp;                    // Total Interface UP events
2149     mDNSu32 InterfaceUpFlap;                // Total Interface UP events with flaps
2150     mDNSu32 InterfaceDown;                  // Total Interface Down events
2151     mDNSu32 InterfaceDownFlap;              // Total Interface Down events with flaps
2152     mDNSu32 CacheRefreshQueries;            // Number of queries that we sent for refreshing cache
2153     mDNSu32 CacheRefreshed;                 // Number of times the cache was refreshed due to a response
2154     mDNSu32 WakeOnResolves;                 // Number of times we did a wake on resolve
2155 } mDNSStatistics;
2156 
2157 extern void LogMDNSStatisticsToFD(int fd, mDNS *const m);
2158 
2159 // Time constant (~= 260 hours ~= 10 days and 21 hours) used to set
2160 // various time values to a point well into the future.
2161 #define FutureTime   0x38000000
2162 
2163 struct mDNS_struct
2164 {
2165     // Internal state fields. These hold the main internal state of mDNSCore;
2166     // the client layer needn't be concerned with them.
2167     // No fields need to be set up by the client prior to calling mDNS_Init();
2168     // all required data is passed as parameters to that function.
2169 
2170     mDNS_PlatformSupport *p;            // Pointer to platform-specific data of indeterminite size
2171     mDNSs32 NetworkChanged;
2172     mDNSBool CanReceiveUnicastOn5353;
2173     mDNSBool AdvertiseLocalAddresses;
2174     mDNSBool DivertMulticastAdvertisements; // from interfaces that do not advertise local addresses to local-only
2175     mStatus mDNSPlatformStatus;
2176     mDNSIPPort UnicastPort4;
2177     mDNSIPPort UnicastPort6;
2178     mDNSEthAddr PrimaryMAC;             // Used as unique host ID
2179     mDNSCallback *MainCallback;
2180     void         *MainContext;
2181 
2182     // For debugging: To catch and report locking failures
2183     mDNSu32 mDNS_busy;                  // Incremented between mDNS_Lock/mDNS_Unlock section
2184     mDNSu32 mDNS_reentrancy;            // Incremented when calling a client callback
2185     mDNSu8 lock_rrcache;                // For debugging: Set at times when these lists may not be modified
2186     mDNSu8 lock_Questions;
2187     mDNSu8 lock_Records;
2188 
2189     // Task Scheduling variables
2190     mDNSs32 timenow_adjust;             // Correction applied if we ever discover time went backwards
2191     mDNSs32 timenow;                    // The time that this particular activation of the mDNS code started
2192     mDNSs32 timenow_last;               // The time the last time we ran
2193     mDNSs32 NextScheduledEvent;         // Derived from values below
2194     mDNSs32 ShutdownTime;               // Set when we're shutting down; allows us to skip some unnecessary steps
2195     mDNSs32 SuppressSending;            // Don't send local-link mDNS packets during this time
2196     mDNSs32 NextCacheCheck;             // Next time to refresh cache record before it expires
2197     mDNSs32 NextScheduledQuery;         // Next time to send query in its exponential backoff sequence
2198     mDNSs32 NextScheduledProbe;         // Next time to probe for new authoritative record
2199     mDNSs32 NextScheduledResponse;      // Next time to send authoritative record(s) in responses
2200     mDNSs32 NextScheduledNATOp;         // Next time to send NAT-traversal packets
2201     mDNSs32 NextScheduledSPS;           // Next time to purge expiring Sleep Proxy records
2202     mDNSs32 NextScheduledKA;            // Next time to send Keepalive packets (SPS)
2203 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
2204     mDNSs32 NextBonjourDisableTime;     // Next time to leave multicast group if Bonjour on Demand is enabled
2205     mDNSu8 BonjourEnabled;              // Non zero if Bonjour is currently enabled by the Bonjour on Demand logic
2206 #endif
2207     mDNSs32 RandomQueryDelay;           // For de-synchronization of query packets on the wire
2208     mDNSu32 RandomReconfirmDelay;       // For de-synchronization of reconfirmation queries on the wire
2209     mDNSs32 PktNum;                     // Unique sequence number assigned to each received packet
2210     mDNSs32 MPktNum;                    // Unique sequence number assigned to each received Multicast packet
2211     mDNSu8 LocalRemoveEvents;           // Set if we may need to deliver remove events for local-only questions and/or local-only records
2212     mDNSu8 SleepState;                  // Set if we're sleeping
2213     mDNSu8 SleepSeqNum;                 // "Epoch number" of our current period of wakefulness
2214     mDNSu8 SystemWakeOnLANEnabled;      // Set if we want to register with a Sleep Proxy before going to sleep
2215     mDNSu8 SentSleepProxyRegistration;  // Set if we registered (or tried to register) with a Sleep Proxy
2216     mDNSu8 SystemSleepOnlyIfWakeOnLAN;  // Set if we may only sleep if we managed to register with a Sleep Proxy
2217     mDNSs32 AnnounceOwner;              // After waking from sleep, include OWNER option in packets until this time
2218     mDNSs32 DelaySleep;                 // To inhibit re-sleeping too quickly right after wake
2219     mDNSs32 SleepLimit;                 // Time window to allow deregistrations, etc.,
2220                                         // during which underying platform layer should inhibit system sleep
2221     mDNSs32 TimeSlept;                  // Time we went to sleep.
2222 
2223     mDNSs32 UnicastPacketsSent;         // Number of unicast packets sent.
2224     mDNSs32 MulticastPacketsSent;       // Number of multicast packets sent.
2225     mDNSs32 RemoteSubnet;               // Multicast packets received from outside our subnet.
2226 
2227     mDNSs32 NextScheduledSPRetry;       // Time next sleep proxy registration action is required.
2228                                         // Only valid if SleepLimit is nonzero and DelaySleep is zero.
2229 
2230     mDNSs32 NextScheduledStopTime;      // Next time to stop a question
2231 
2232     mDNSs32 NextBLEServiceTime;         // Next time to call the BLE discovery management layer.  Non zero when active.
2233 
2234     // These fields only required for mDNS Searcher...
2235     DNSQuestion *Questions;             // List of all registered questions, active and inactive
2236     DNSQuestion *NewQuestions;          // Fresh questions not yet answered from cache
2237     DNSQuestion *CurrentQuestion;       // Next question about to be examined in AnswerLocalQuestions()
2238     DNSQuestion *LocalOnlyQuestions;    // Questions with InterfaceID set to mDNSInterface_LocalOnly or mDNSInterface_P2P
2239     DNSQuestion *NewLocalOnlyQuestions; // Fresh local-only or P2P questions not yet answered
2240     DNSQuestion *RestartQuestion;       // Questions that are being restarted (stop followed by start)
2241     mDNSu32 rrcache_size;               // Total number of available cache entries
2242     mDNSu32 rrcache_totalused;          // Number of cache entries currently occupied
2243     mDNSu32 rrcache_totalused_unicast;  // Number of cache entries currently occupied by unicast
2244     mDNSu32 rrcache_active;             // Number of cache entries currently occupied by records that answer active questions
2245     mDNSu32 rrcache_report;
2246     CacheEntity *rrcache_free;
2247     CacheGroup *rrcache_hash[CACHE_HASH_SLOTS];
2248     mDNSs32 rrcache_nextcheck[CACHE_HASH_SLOTS];
2249 
2250     AuthHash rrauth;
2251 
2252     // Fields below only required for mDNS Responder...
2253     domainlabel nicelabel;              // Rich text label encoded using canonically precomposed UTF-8
2254     domainlabel hostlabel;              // Conforms to RFC 1034 "letter-digit-hyphen" ARPANET host name rules
2255     domainname MulticastHostname;       // Fully Qualified "dot-local" Host Name, e.g. "Foo.local."
2256 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
2257     domainname RandomizedHostname;      // Randomized hostname to use for services involving AWDL interfaces. This is to
2258                                         // avoid using a hostname derived from the device's name, which may contain the
2259                                         // owner's real name, (e.g., "Steve's iPhone" -> "Steves-iPhone.local"), which is a
2260                                         // privacy concern.
2261     mDNSu32 AutoTargetAWDLIncludedCount;// Number of registered AWDL-included auto-target records.
2262     mDNSu32 AutoTargetAWDLOnlyCount;    // Number of registered AWDL-only auto-target records.
2263 #endif
2264     UTF8str255 HIHardware;
2265     UTF8str255 HISoftware;
2266     AuthRecord DeviceInfo;
2267     AuthRecord *ResourceRecords;
2268     AuthRecord *DuplicateRecords;       // Records currently 'on hold' because they are duplicates of existing records
2269     AuthRecord *NewLocalRecords;        // Fresh AuthRecords (public) not yet delivered to our local-only questions
2270     AuthRecord *CurrentRecord;          // Next AuthRecord about to be examined
2271     mDNSBool NewLocalOnlyRecords;       // Fresh AuthRecords (local only) not yet delivered to our local questions
2272     NetworkInterfaceInfo *HostInterfaces;
2273     mDNSs32 ProbeFailTime;
2274     mDNSu32 NumFailedProbes;
2275     mDNSs32 SuppressProbes;
2276     Platform_t mDNS_plat;               // Why is this here in the “only required for mDNS Responder” section? -- SC
2277 
2278     // Unicast-specific data
2279     mDNSs32 NextuDNSEvent;                  // uDNS next event
2280     mDNSs32 NextSRVUpdate;                  // Time to perform delayed update
2281 
2282 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
2283     DNSServer        *DNSServers;           // list of DNS servers
2284 #endif
2285     McastResolver    *McastResolvers;       // list of Mcast Resolvers
2286 
2287     mDNSAddr Router;
2288     mDNSAddr AdvertisedV4;                  // IPv4 address pointed to by hostname
2289     mDNSAddr AdvertisedV6;                  // IPv6 address pointed to by hostname
2290 
2291     DomainAuthInfo   *AuthInfoList;         // list of domains requiring authentication for updates
2292 
2293     DNSQuestion ReverseMap;                 // Reverse-map query to find static hostname for service target
2294     DNSQuestion AutomaticBrowseDomainQ;
2295     domainname StaticHostname;              // Current answer to reverse-map query
2296     domainname FQDN;
2297     HostnameInfo     *Hostnames;            // List of registered hostnames + hostname metadata
2298 
2299     mDNSu32 WABBrowseQueriesCount;          // Number of WAB Browse domain enumeration queries (b, db) callers
2300     mDNSu32 WABLBrowseQueriesCount;         // Number of legacy WAB Browse domain enumeration queries (lb) callers
2301     mDNSu32 WABRegQueriesCount;             // Number of WAB Registration domain enumeration queries (r, dr) callers
2302     mDNSu8 SearchDomainsHash[MD5_LEN];
2303 
2304     // NAT-Traversal fields
2305     NATTraversalInfo LLQNAT;                    // Single shared NAT Traversal to receive inbound LLQ notifications
2306     NATTraversalInfo *NATTraversals;
2307     NATTraversalInfo *CurrentNATTraversal;
2308     mDNSs32 retryIntervalGetAddr;               // delta between time sent and retry for NAT-PMP & UPnP/IGD external address request
2309     mDNSs32 retryGetAddr;                       // absolute time when we retry for NAT-PMP & UPnP/IGD external address request
2310     mDNSv4Addr ExtAddress;                      // the external address discovered via NAT-PMP or UPnP/IGD
2311     mDNSu32 PCPNonce[3];                        // the nonce if using PCP
2312 
2313     UDPSocket        *NATMcastRecvskt;          // For receiving PCP & NAT-PMP announcement multicasts from router on port 5350
2314     mDNSu32 LastNATupseconds;                   // NAT engine uptime in seconds, from most recent NAT packet
2315     mDNSs32 LastNATReplyLocalTime;              // Local time in ticks when most recent NAT packet was received
2316     mDNSu16 LastNATMapResultCode;               // Most recent error code for mappings
2317 
2318     tcpLNTInfo tcpAddrInfo;                     // legacy NAT traversal TCP connection info for external address
2319     tcpLNTInfo tcpDeviceInfo;                   // legacy NAT traversal TCP connection info for device info
2320     tcpLNTInfo       *tcpInfoUnmapList;         // list of pending unmap requests
2321     mDNSInterfaceID UPnPInterfaceID;
2322     UDPSocket        *SSDPSocket;               // For SSDP request/response
2323     mDNSBool SSDPWANPPPConnection;              // whether we should send the SSDP query for WANIPConnection or WANPPPConnection
2324     mDNSIPPort UPnPRouterPort;                  // port we send discovery messages to
2325     mDNSIPPort UPnPSOAPPort;                    // port we send SOAP messages to
2326     char             *UPnPRouterURL;            // router's URL string
2327     mDNSBool UPnPWANPPPConnection;              // whether we're using WANIPConnection or WANPPPConnection
2328     char             *UPnPSOAPURL;              // router's SOAP control URL string
2329     char             *UPnPRouterAddressString;  // holds both the router's address and port
2330     char             *UPnPSOAPAddressString;    // holds both address and port for SOAP messages
2331 
2332     // DNS Push Notification fields
2333     DNSPushNotificationServer *DNSPushServers;  // DNS Push Notification Servers
2334     DNSPushNotificationZone   *DNSPushZones;
2335 
2336     // Sleep Proxy client fields
2337     AuthRecord *SPSRRSet;                       // To help the client keep track of the records registered with the sleep proxy
2338 
2339     // Sleep Proxy Server fields
2340     mDNSu8 SPSType;                             // 0 = off, 10-99 encodes desirability metric
2341     mDNSu8 SPSPortability;                      // 10-99
2342     mDNSu8 SPSMarginalPower;                    // 10-99
2343     mDNSu8 SPSTotalPower;                       // 10-99
2344     mDNSu8 SPSFeatureFlags;                     // Features supported. Currently 1 = TCP KeepAlive supported.
2345     mDNSu8 SPSState;                            // 0 = off, 1 = running, 2 = shutting down, 3 = suspended during sleep
2346     mDNSInterfaceID SPSProxyListChanged;
2347     UDPSocket        *SPSSocket;
2348 #ifndef SPC_DISABLED
2349     ServiceRecordSet SPSRecords;
2350 #endif
2351     mDNSQuestionCallback *SPSBrowseCallback;    // So the platform layer can do something useful with SPS browse results
2352     int ProxyRecords;                           // Total number of records we're holding as proxy
2353     #define           MAX_PROXY_RECORDS 10000   /* DOS protection: 400 machines at 25 records each */
2354 
2355 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
2356     WCFConnection    *WCF;
2357 #endif
2358     // DNS Proxy fields
2359     mDNSu32 dp_ipintf[MaxIp];                   // input interface index list from the DNS Proxy Client
2360     mDNSu32 dp_opintf;                          // output interface index from the DNS Proxy Client
2361 
2362     int             notifyToken;
2363     int             uds_listener_skt;           // Listening socket for incoming UDS clients. This should not be here -- it's private to uds_daemon.c and nothing to do with mDNSCore -- SC
2364     mDNSu32         AutoTargetServices;         // # of services that have AutoTarget set
2365 
2366 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
2367     // Counters used in Bonjour on Demand logic.
2368     mDNSu32         NumAllInterfaceRecords;     // Right now we count *all* multicast records here. Later we may want to change to count interface-specific records separately. (This count includes records on the DuplicateRecords list too.)
2369     mDNSu32         NumAllInterfaceQuestions;   // Right now we count *all* multicast questions here. Later we may want to change to count interface-specific questions separately.
2370 #endif
2371 
2372     mDNSStatistics   mDNSStats;
2373 
2374     // Fixed storage, to avoid creating large objects on the stack
2375     // The imsg is declared as a union with a pointer type to enforce CPU-appropriate alignment
2376     union { DNSMessage m; void *p; } imsg;  // Incoming message received from wire
2377     DNSMessage omsg;                        // Outgoing message we're building
2378     LargeCacheRecord rec;                   // Resource Record extracted from received message
2379 
2380 #ifndef MaxMsg
2381     #define MaxMsg 512
2382 #endif
2383     char MsgBuffer[MaxMsg];                 // Temp storage used while building error log messages (keep at end of struct)
2384 };
2385 
2386 #define FORALL_CACHERECORDS(SLOT,CG,CR)                           \
2387     for ((SLOT) = 0; (SLOT) < CACHE_HASH_SLOTS; (SLOT)++)         \
2388         for ((CG)=m->rrcache_hash[(SLOT)]; (CG); (CG)=(CG)->next) \
2389             for ((CR) = (CG)->members; (CR); (CR)=(CR)->next)
2390 
2391 // ***************************************************************************
2392 #if 0
2393 #pragma mark -
2394 #pragma mark - Useful Static Constants
2395 #endif
2396 
2397 extern const mDNSInterfaceID mDNSInterface_Any;             // Zero
2398 extern const mDNSInterfaceID mDNSInterface_LocalOnly;       // Special value
2399 extern const mDNSInterfaceID mDNSInterfaceMark;             // Special value
2400 extern const mDNSInterfaceID mDNSInterface_P2P;             // Special value
2401 extern const mDNSInterfaceID uDNSInterfaceMark;             // Special value
2402 extern const mDNSInterfaceID mDNSInterface_BLE;             // Special value
2403 
2404 #define LocalOnlyOrP2PInterface(INTERFACE)  (((INTERFACE) == mDNSInterface_LocalOnly) || ((INTERFACE) == mDNSInterface_P2P) || ((INTERFACE) == mDNSInterface_BLE))
2405 
2406 extern const mDNSIPPort DiscardPort;
2407 extern const mDNSIPPort SSHPort;
2408 extern const mDNSIPPort UnicastDNSPort;
2409 extern const mDNSIPPort SSDPPort;
2410 extern const mDNSIPPort IPSECPort;
2411 extern const mDNSIPPort NSIPCPort;
2412 extern const mDNSIPPort NATPMPAnnouncementPort;
2413 extern const mDNSIPPort NATPMPPort;
2414 extern const mDNSIPPort DNSEXTPort;
2415 extern const mDNSIPPort MulticastDNSPort;
2416 extern const mDNSIPPort LoopbackIPCPort;
2417 extern const mDNSIPPort PrivateDNSPort;
2418 
2419 extern const OwnerOptData zeroOwner;
2420 
2421 extern const mDNSIPPort zeroIPPort;
2422 extern const mDNSv4Addr zerov4Addr;
2423 extern const mDNSv6Addr zerov6Addr;
2424 extern const mDNSEthAddr zeroEthAddr;
2425 extern const mDNSv4Addr onesIPv4Addr;
2426 extern const mDNSv6Addr onesIPv6Addr;
2427 extern const mDNSEthAddr onesEthAddr;
2428 extern const mDNSAddr zeroAddr;
2429 
2430 extern const mDNSv4Addr AllDNSAdminGroup;
2431 extern const mDNSv4Addr AllHosts_v4;
2432 extern const mDNSv6Addr AllHosts_v6;
2433 extern const mDNSv6Addr NDP_prefix;
2434 extern const mDNSEthAddr AllHosts_v6_Eth;
2435 extern const mDNSAddr AllDNSLinkGroup_v4;
2436 extern const mDNSAddr AllDNSLinkGroup_v6;
2437 
2438 extern const mDNSOpaque16 zeroID;
2439 extern const mDNSOpaque16 onesID;
2440 extern const mDNSOpaque16 QueryFlags;
2441 extern const mDNSOpaque16 uQueryFlags;
2442 extern const mDNSOpaque16 ResponseFlags;
2443 extern const mDNSOpaque16 UpdateReqFlags;
2444 extern const mDNSOpaque16 UpdateRespFlags;
2445 extern const mDNSOpaque16 SubscribeFlags;
2446 extern const mDNSOpaque16 UnSubscribeFlags;
2447 extern const mDNSOpaque16 uDNSSecQueryFlags;
2448 
2449 extern const mDNSOpaque64 zeroOpaque64;
2450 extern const mDNSOpaque128 zeroOpaque128;
2451 
2452 extern mDNSBool StrictUnicastOrdering;
2453 
2454 #define localdomain           (*(const domainname *)"\x5" "local")
2455 #define DeviceInfoName        (*(const domainname *)"\xC" "_device-info" "\x4" "_tcp")
2456 #define LocalDeviceInfoName   (*(const domainname *)"\xC" "_device-info" "\x4" "_tcp" "\x5" "local")
2457 #define SleepProxyServiceType (*(const domainname *)"\xC" "_sleep-proxy" "\x4" "_udp")
2458 
2459 // ***************************************************************************
2460 #if 0
2461 #pragma mark -
2462 #pragma mark - Inline functions
2463 #endif
2464 
2465 #if (defined(_MSC_VER))
2466     #define mDNSinline static __inline
2467 #elif ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
2468     #define mDNSinline static inline
2469 #else
2470     #define mDNSinline static inline
2471 #endif
2472 
2473 // If we're not doing inline functions, then this header needs to have the extern declarations
2474 #if !defined(mDNSinline)
2475 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
2476 extern int          CountOfUnicastDNSServers(mDNS *const m);
2477 #endif
2478 extern mDNSs32      NonZeroTime(mDNSs32 t);
2479 extern mDNSu16      mDNSVal16(mDNSOpaque16 x);
2480 extern mDNSOpaque16 mDNSOpaque16fromIntVal(mDNSu16 v);
2481 #endif
2482 
2483 // If we're compiling the particular C file that instantiates our inlines, then we
2484 // define "mDNSinline" (to empty string) so that we generate code in the following section
2485 #if (!defined(mDNSinline) && mDNS_InstantiateInlines)
2486 #define mDNSinline
2487 #endif
2488 
2489 #ifdef mDNSinline
2490 
2491 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
2492 mDNSinline int CountOfUnicastDNSServers(mDNS *const m)
2493 {
2494     int count = 0;
2495     DNSServer *ptr = m->DNSServers;
2496     while(ptr) { if(!(ptr->flags & DNSServerFlag_Delete)) count++; ptr = ptr->next; }
2497     return (count);
2498 }
2499 #endif
2500 
2501 mDNSinline mDNSs32 NonZeroTime(mDNSs32 t) { if (t) return(t);else return(1);}
2502 
2503 mDNSinline mDNSu16 mDNSVal16(mDNSOpaque16 x) { return((mDNSu16)((mDNSu16)x.b[0] <<  8 | (mDNSu16)x.b[1])); }
2504 
2505 mDNSinline mDNSOpaque16 mDNSOpaque16fromIntVal(mDNSu16 v)
2506 {
2507     mDNSOpaque16 x;
2508     x.b[0] = (mDNSu8)(v >> 8);
2509     x.b[1] = (mDNSu8)(v & 0xFF);
2510     return(x);
2511 }
2512 
2513 #endif
2514 
2515 // ***************************************************************************
2516 #if 0
2517 #pragma mark -
2518 #pragma mark - Main Client Functions
2519 #endif
2520 
2521 // Every client should call mDNS_Init, passing in storage for the mDNS object and the mDNS_PlatformSupport object.
2522 //
2523 // Clients that are only advertising services should use mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize.
2524 // Clients that plan to perform queries (mDNS_StartQuery, mDNS_StartBrowse, etc.)
2525 // need to provide storage for the resource record cache, or the query calls will return 'mStatus_NoCache'.
2526 // The rrcachestorage parameter is the address of memory for the resource record cache, and
2527 // the rrcachesize parameter is the number of entries in the CacheRecord array passed in.
2528 // (i.e. the size of the cache memory needs to be sizeof(CacheRecord) * rrcachesize).
2529 // OS X 10.3 Panther uses an initial cache size of 64 entries, and then mDNSCore sends an
2530 // mStatus_GrowCache message if it needs more.
2531 //
2532 // Most clients should use mDNS_Init_AdvertiseLocalAddresses. This causes mDNSCore to automatically
2533 // create the correct address records for all the hosts interfaces. If you plan to advertise
2534 // services being offered by the local machine, this is almost always what you want.
2535 // There are two cases where you might use mDNS_Init_DontAdvertiseLocalAddresses:
2536 // 1. A client-only device, that browses for services but doesn't advertise any of its own.
2537 // 2. A proxy-registration service, that advertises services being offered by other machines, and takes
2538 //    the appropriate steps to manually create the correct address records for those other machines.
2539 // In principle, a proxy-like registration service could manually create address records for its own machine too,
2540 // but this would be pointless extra effort when using mDNS_Init_AdvertiseLocalAddresses does that for you.
2541 //
2542 // Note that a client-only device that wishes to prohibit multicast advertisements (e.g. from
2543 // higher-layer API calls) must also set DivertMulticastAdvertisements in the mDNS structure and
2544 // advertise local address(es) on a loopback interface.
2545 //
2546 // When mDNS has finished setting up the client's callback is called
2547 // A client can also spin and poll the mDNSPlatformStatus field to see when it changes from mStatus_Waiting to mStatus_NoError
2548 //
2549 // Call mDNS_StartExit to tidy up before exiting
2550 // Because exiting may be an asynchronous process (e.g. if unicast records need to be deregistered)
2551 // client layer may choose to wait until mDNS_ExitNow() returns true before calling mDNS_FinalExit().
2552 //
2553 // Call mDNS_Register with a completed AuthRecord object to register a resource record
2554 // If the resource record type is kDNSRecordTypeUnique (or kDNSknownunique) then if a conflicting resource record is discovered,
2555 // the resource record's mDNSRecordCallback will be called with error code mStatus_NameConflict. The callback should deregister
2556 // the record, and may then try registering the record again after picking a new name (e.g. by automatically appending a number).
2557 // Following deregistration, the RecordCallback will be called with result mStatus_MemFree to signal that it is safe to deallocate
2558 // the record's storage (memory must be freed asynchronously to allow for goodbye packets and dynamic update deregistration).
2559 //
2560 // Call mDNS_StartQuery to initiate a query. mDNS will proceed to issue Multicast DNS query packets, and any time a response
2561 // is received containing a record which matches the question, the DNSQuestion's mDNSAnswerCallback function will be called
2562 // Call mDNS_StopQuery when no more answers are required
2563 //
2564 // Care should be taken on multi-threaded or interrupt-driven environments.
2565 // The main mDNS routines call mDNSPlatformLock() on entry and mDNSPlatformUnlock() on exit;
2566 // each platform layer needs to implement these appropriately for its respective platform.
2567 // For example, if the support code on a particular platform implements timer callbacks at interrupt time, then
2568 // mDNSPlatformLock/Unlock need to disable interrupts or do similar concurrency control to ensure that the mDNS
2569 // code is not entered by an interrupt-time timer callback while in the middle of processing a client call.
2570 
2571 extern mStatus mDNS_Init      (mDNS *const m, mDNS_PlatformSupport *const p,
2572                                CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
2573                                mDNSBool AdvertiseLocalAddresses,
2574                                mDNSCallback *Callback, void *Context);
2575 // See notes above on use of NoCache/ZeroCacheSize
2576 #define mDNS_Init_NoCache                     mDNSNULL
2577 #define mDNS_Init_ZeroCacheSize               0
2578 // See notes above on use of Advertise/DontAdvertiseLocalAddresses
2579 #define mDNS_Init_AdvertiseLocalAddresses     mDNStrue
2580 #define mDNS_Init_DontAdvertiseLocalAddresses mDNSfalse
2581 #define mDNS_Init_NoInitCallback              mDNSNULL
2582 #define mDNS_Init_NoInitCallbackContext       mDNSNULL
2583 
2584 extern void    mDNS_ConfigChanged(mDNS *const m);
2585 extern void    mDNS_GrowCache (mDNS *const m, CacheEntity *storage, mDNSu32 numrecords);
2586 extern void    mDNS_StartExit (mDNS *const m);
2587 extern void    mDNS_FinalExit (mDNS *const m);
2588 #define mDNS_Close(m) do { mDNS_StartExit(m); mDNS_FinalExit(m); } while(0)
2589 #define mDNS_ExitNow(m, now) ((now) - (m)->ShutdownTime >= 0 || (!(m)->ResourceRecords))
2590 
2591 extern mDNSs32 mDNS_Execute   (mDNS *const m);
2592 
2593 extern mStatus mDNS_Register  (mDNS *const m, AuthRecord *const rr);
2594 extern mStatus mDNS_Update    (mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
2595                                const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback);
2596 extern mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr);
2597 
2598 extern mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question);
2599 extern mStatus mDNS_StopQuery (mDNS *const m, DNSQuestion *const question);
2600 extern mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question);
2601 extern mStatus mDNS_Reconfirm (mDNS *const m, CacheRecord *const cacherr);
2602 extern mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval);
2603 extern mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr);
2604 extern void    mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr);
2605 extern mDNSs32 mDNS_TimeNow(const mDNS *const m);
2606 
2607 extern mStatus mDNS_StartNATOperation(mDNS *const m, NATTraversalInfo *traversal);
2608 extern mStatus mDNS_StopNATOperation(mDNS *const m, NATTraversalInfo *traversal);
2609 extern mStatus mDNS_StopNATOperation_internal(mDNS *m, NATTraversalInfo *traversal);
2610 
2611 extern DomainAuthInfo *GetAuthInfoForName(mDNS *m, const domainname *const name);
2612 
2613 extern void    mDNS_UpdateAllowSleep(mDNS *const m);
2614 
2615 // ***************************************************************************
2616 #if 0
2617 #pragma mark -
2618 #pragma mark - Platform support functions that are accessible to the client layer too
2619 #endif
2620 
2621 extern mDNSs32 mDNSPlatformOneSecond;
2622 
2623 // ***************************************************************************
2624 #if 0
2625 #pragma mark -
2626 #pragma mark - General utility and helper functions
2627 #endif
2628 
2629 // mDNS_Dereg_normal is used for most calls to mDNS_Deregister_internal
2630 // mDNS_Dereg_rapid is used to send one goodbye instead of three, when we want the memory available for reuse sooner
2631 // mDNS_Dereg_conflict is used to indicate that this record is being forcibly deregistered because of a conflict
2632 // mDNS_Dereg_repeat is used when cleaning up, for records that may have already been forcibly deregistered
2633 typedef enum { mDNS_Dereg_normal, mDNS_Dereg_rapid, mDNS_Dereg_conflict, mDNS_Dereg_repeat } mDNS_Dereg_type;
2634 
2635 // mDNS_RegisterService is a single call to register the set of resource records associated with a given named service.
2636 //
2637 //
2638 // mDNS_AddRecordToService adds an additional record to a Service Record Set.  This record may be deregistered
2639 // via mDNS_RemoveRecordFromService, or by deregistering the service.  mDNS_RemoveRecordFromService is passed a
2640 // callback to free the memory associated with the extra RR when it is safe to do so.  The ExtraResourceRecord
2641 // object can be found in the record's context pointer.
2642 
2643 // mDNS_GetBrowseDomains is a special case of the mDNS_StartQuery call, where the resulting answers
2644 // are a list of PTR records indicating (in the rdata) domains that are recommended for browsing.
2645 // After getting the list of domains to browse, call mDNS_StopQuery to end the search.
2646 // mDNS_GetDefaultBrowseDomain returns the name of the domain that should be highlighted by default.
2647 //
2648 // mDNS_GetRegistrationDomains and mDNS_GetDefaultRegistrationDomain are the equivalent calls to get the list
2649 // of one or more domains that should be offered to the user as choices for where they may register their service,
2650 // and the default domain in which to register in the case where the user has made no selection.
2651 
2652 extern void    mDNS_SetupResourceRecord(AuthRecord *rr, RData *RDataStorage, mDNSInterfaceID InterfaceID,
2653                                         mDNSu16 rrtype, mDNSu32 ttl, mDNSu8 RecordType, AuthRecType artype, mDNSRecordCallback Callback, void *Context);
2654 
2655 extern mStatus mDNS_RegisterService  (mDNS *const m, ServiceRecordSet *sr,
2656                                       const domainlabel *const name, const domainname *const type, const domainname *const domain,
2657                                       const domainname *const host, mDNSIPPort port, RData *txtrdata, const mDNSu8 txtinfo[], mDNSu16 txtlen,
2658                                       AuthRecord *SubTypes, mDNSu32 NumSubTypes,
2659                                       mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags);
2660 extern mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl,  mDNSu32 flags);
2661 extern mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, mDNSRecordCallback MemFreeCallback, void *Context);
2662 extern mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname);
2663 extern mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt);
2664 #define mDNS_DeregisterService(M,S) mDNS_DeregisterService_drt((M), (S), mDNS_Dereg_normal)
2665 
2666 extern mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
2667                                           const domainlabel *const name, const domainname *const type, const domainname *const domain,
2668                                           const domainname *const host,
2669                                           const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags);
2670 #define        mDNS_DeregisterNoSuchService mDNS_Deregister
2671 
2672 extern void mDNS_SetupQuestion(DNSQuestion *const q, const mDNSInterfaceID InterfaceID, const domainname *const name,
2673                                const mDNSu16 qtype, mDNSQuestionCallback *const callback, void *const context);
2674 
2675 extern mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
2676                                 const domainname *const srv, const domainname *const domain,
2677                                 const mDNSInterfaceID InterfaceID, mDNSu32 flags,
2678                                 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
2679                                 mDNSQuestionCallback *Callback, void *Context);
2680 #define        mDNS_StopBrowse mDNS_StopQuery
2681 
2682 
2683 typedef enum
2684 {
2685     mDNS_DomainTypeBrowse              = 0,
2686     mDNS_DomainTypeBrowseDefault       = 1,
2687     mDNS_DomainTypeBrowseAutomatic     = 2,
2688     mDNS_DomainTypeRegistration        = 3,
2689     mDNS_DomainTypeRegistrationDefault = 4,
2690 
2691     mDNS_DomainTypeMax = 4
2692 } mDNS_DomainType;
2693 
2694 extern const char *const mDNS_DomainTypeNames[];
2695 
2696 extern mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
2697                                const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context);
2698 #define        mDNS_StopGetDomains mDNS_StopQuery
2699 extern mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr, mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname);
2700 #define        mDNS_StopAdvertiseDomains mDNS_Deregister
2701 
2702 extern mDNSOpaque16 mDNS_NewMessageID(mDNS *const m);
2703 extern mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr);
2704 
2705 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
2706 extern DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question);
2707 #endif
2708 extern mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question);
2709 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
2710 extern mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *q, mdns_dns_service_t dnsservice);
2711 extern mDNSBool LocalRecordRmvEventsForQuestion(mDNS *m, DNSQuestion *q);
2712 #endif
2713 
2714 // ***************************************************************************
2715 #if 0
2716 #pragma mark -
2717 #pragma mark - DNS name utility functions
2718 #endif
2719 
2720 // In order to expose the full capabilities of the DNS protocol (which allows any arbitrary eight-bit values
2721 // in domain name labels, including unlikely characters like ascii nulls and even dots) all the mDNS APIs
2722 // work with DNS's native length-prefixed strings. For convenience in C, the following utility functions
2723 // are provided for converting between C's null-terminated strings and DNS's length-prefixed strings.
2724 
2725 // Assignment
2726 // A simple C structure assignment of a domainname can cause a protection fault by accessing unmapped memory,
2727 // because that object is defined to be 256 bytes long, but not all domainname objects are truly the full size.
2728 // This macro uses mDNSPlatformMemCopy() to make sure it only touches the actual bytes that are valid.
2729 #define AssignDomainName(DST, SRC) do { mDNSu16 len__ = DomainNameLength((SRC)); \
2730     if (len__ <= MAX_DOMAIN_NAME) mDNSPlatformMemCopy((DST)->c, (SRC)->c, len__); else (DST)->c[0] = 0; } while(0)
2731 #define AssignConstStringDomainName(DST, SRC) do { \
2732     mDNSu16 len__ = DomainNameLengthLimit((domainname *)(SRC), (mDNSu8 *)(SRC) + sizeof (SRC)); \
2733     if (len__ <= MAX_DOMAIN_NAME) \
2734         mDNSPlatformMemCopy((DST)->c, (SRC), len__); else (DST)->c[0] = 0; } while(0)
2735 
2736 // Comparison functions
2737 #define SameDomainLabelCS(A,B) ((A)[0] == (B)[0] && mDNSPlatformMemSame((A)+1, (B)+1, (A)[0]))
2738 extern mDNSBool SameDomainLabel(const mDNSu8 *a, const mDNSu8 *b);
2739 extern mDNSBool SameDomainName(const domainname *const d1, const domainname *const d2);
2740 extern mDNSBool SameDomainNameCS(const domainname *const d1, const domainname *const d2);
2741 typedef mDNSBool DomainNameComparisonFn (const domainname *const d1, const domainname *const d2);
2742 extern mDNSBool IsLocalDomain(const domainname *d);     // returns true for domains that by default should be looked up using link-local multicast
2743 
2744 #define StripFirstLabel(X) ((const domainname *)& (X)->c[(X)->c[0] ? 1 + (X)->c[0] : 0])
2745 
2746 #define FirstLabel(X)  ((const domainlabel *)(X))
2747 #define SecondLabel(X) ((const domainlabel *)StripFirstLabel(X))
2748 #define ThirdLabel(X)  ((const domainlabel *)StripFirstLabel(StripFirstLabel(X)))
2749 
2750 extern const mDNSu8 *LastLabel(const domainname *d);
2751 
2752 // Get total length of domain name, in native DNS format, including terminal root label
2753 //   (e.g. length of "com." is 5 (length byte, three data bytes, final zero)
2754 extern mDNSu16  DomainNameLengthLimit(const domainname *const name, const mDNSu8 *limit);
2755 #define DomainNameLength(name) DomainNameLengthLimit((name), (name)->c + MAX_DOMAIN_NAME)
2756 
2757 // Append functions to append one or more labels to an existing native format domain name:
2758 //   AppendLiteralLabelString adds a single label from a literal C string, with no escape character interpretation.
2759 //   AppendDNSNameString      adds zero or more labels from a C string using conventional DNS dots-and-escaping interpretation
2760 //   AppendDomainLabel        adds a single label from a native format domainlabel
2761 //   AppendDomainName         adds zero or more labels from a native format domainname
2762 extern mDNSu8  *AppendLiteralLabelString(domainname *const name, const char *cstr);
2763 extern mDNSu8  *AppendDNSNameString     (domainname *const name, const char *cstr);
2764 extern mDNSu8  *AppendDomainLabel       (domainname *const name, const domainlabel *const label);
2765 extern mDNSu8  *AppendDomainName        (domainname *const name, const domainname *const append);
2766 
2767 // Convert from null-terminated string to native DNS format:
2768 //   The DomainLabel form makes a single label from a literal C string, with no escape character interpretation.
2769 //   The DomainName form makes native format domain name from a C string using conventional DNS interpretation:
2770 //     dots separate labels, and within each label, '\.' represents a literal dot, '\\' represents a literal
2771 //     backslash and backslash with three decimal digits (e.g. \000) represents an arbitrary byte value.
2772 extern mDNSBool MakeDomainLabelFromLiteralString(domainlabel *const label, const char *cstr);
2773 extern mDNSu8  *MakeDomainNameFromDNSNameString (domainname  *const name,  const char *cstr);
2774 
2775 // Convert native format domainlabel or domainname back to C string format
2776 // IMPORTANT:
2777 // When using ConvertDomainLabelToCString, the target buffer must be MAX_ESCAPED_DOMAIN_LABEL (254) bytes long
2778 // to guarantee there will be no buffer overrun. It is only safe to use a buffer shorter than this in rare cases
2779 // where the label is known to be constrained somehow (for example, if the label is known to be either "_tcp" or "_udp").
2780 // Similarly, when using ConvertDomainNameToCString, the target buffer must be MAX_ESCAPED_DOMAIN_NAME (1009) bytes long.
2781 // See definitions of MAX_ESCAPED_DOMAIN_LABEL and MAX_ESCAPED_DOMAIN_NAME for more detailed explanation.
2782 extern char    *ConvertDomainLabelToCString_withescape(const domainlabel *const name, char *cstr, char esc);
2783 #define         ConvertDomainLabelToCString_unescaped(D,C) ConvertDomainLabelToCString_withescape((D), (C), 0)
2784 #define         ConvertDomainLabelToCString(D,C)           ConvertDomainLabelToCString_withescape((D), (C), '\\')
2785 extern char    *ConvertDomainNameToCString_withescape(const domainname *const name, char *cstr, char esc);
2786 #define         ConvertDomainNameToCString_unescaped(D,C) ConvertDomainNameToCString_withescape((D), (C), 0)
2787 #define         ConvertDomainNameToCString(D,C)           ConvertDomainNameToCString_withescape((D), (C), '\\')
2788 
2789 extern void     ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name[], domainlabel *const hostlabel);
2790 
2791 #define ValidTransportProtocol(X) ( (X)[0] == 4 && (X)[1] == '_' && \
2792                                     ((((X)[2] | 0x20) == 'u' && ((X)[3] | 0x20) == 'd') || (((X)[2] | 0x20) == 't' && ((X)[3] | 0x20) == 'c')) && \
2793                                     ((X)[4] | 0x20) == 'p')
2794 
2795 extern mDNSu8  *ConstructServiceName(domainname *const fqdn, const domainlabel *name, const domainname *type, const domainname *const domain);
2796 extern mDNSBool DeconstructServiceName(const domainname *const fqdn, domainlabel *const name, domainname *const type, domainname *const domain);
2797 
2798 // Note: Some old functions have been replaced by more sensibly-named versions.
2799 // You can uncomment the hash-defines below if you don't want to have to change your source code right away.
2800 // When updating your code, note that (unlike the old versions) *all* the new routines take the target object
2801 // as their first parameter.
2802 //#define ConvertCStringToDomainName(SRC,DST)  MakeDomainNameFromDNSNameString((DST),(SRC))
2803 //#define ConvertCStringToDomainLabel(SRC,DST) MakeDomainLabelFromLiteralString((DST),(SRC))
2804 //#define AppendStringLabelToName(DST,SRC)     AppendLiteralLabelString((DST),(SRC))
2805 //#define AppendStringNameToName(DST,SRC)      AppendDNSNameString((DST),(SRC))
2806 //#define AppendDomainLabelToName(DST,SRC)     AppendDomainLabel((DST),(SRC))
2807 //#define AppendDomainNameToName(DST,SRC)      AppendDomainName((DST),(SRC))
2808 
2809 // ***************************************************************************
2810 #if 0
2811 #pragma mark -
2812 #pragma mark - Other utility functions and macros
2813 #endif
2814 
2815 // mDNS_vsnprintf/snprintf return the number of characters written, excluding the final terminating null.
2816 // The output is always null-terminated: for example, if the output turns out to be exactly buflen long,
2817 // then the output will be truncated by one character to allow space for the terminating null.
2818 // Unlike standard C vsnprintf/snprintf, they return the number of characters *actually* written,
2819 // not the number of characters that *would* have been printed were buflen unlimited.
2820 extern mDNSu32 mDNS_vsnprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, va_list arg) IS_A_PRINTF_STYLE_FUNCTION(3,0);
2821 extern mDNSu32 mDNS_snprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, ...) IS_A_PRINTF_STYLE_FUNCTION(3,4);
2822 extern void mDNS_snprintf_add(char **dst, const char *lim, const char *fmt, ...) IS_A_PRINTF_STYLE_FUNCTION(3,4);
2823 extern mDNSu32 NumCacheRecordsForInterfaceID(const mDNS *const m, mDNSInterfaceID id);
2824 extern char *DNSTypeName(mDNSu16 rrtype);
2825 extern const char *mStatusDescription(mStatus error);
2826 extern char *GetRRDisplayString_rdb(const ResourceRecord *const rr, const RDataBody *const rd1, char *const buffer);
2827 #define RRDisplayString(m, rr) GetRRDisplayString_rdb(rr, &(rr)->rdata->u, (m)->MsgBuffer)
2828 #define ARDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
2829 #define CRDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
2830 #define MortalityDisplayString(M) (M == Mortality_Mortal ? "mortal" : (M == Mortality_Immortal ? "immortal" : "ghost"))
2831 extern mDNSBool mDNSSameAddress(const mDNSAddr *ip1, const mDNSAddr *ip2);
2832 extern void IncrementLabelSuffix(domainlabel *name, mDNSBool RichText);
2833 extern mDNSBool mDNSv4AddrIsRFC1918(const mDNSv4Addr * const addr);  // returns true for RFC1918 private addresses
2834 #define mDNSAddrIsRFC1918(X) ((X)->type == mDNSAddrType_IPv4 && mDNSv4AddrIsRFC1918(&(X)->ip.v4))
2835 extern const char *DNSScopeToString(mDNSu32 scope);
2836 
2837 // For PCP
2838 extern void mDNSAddrMapIPv4toIPv6(mDNSv4Addr* in, mDNSv6Addr* out);
2839 extern mDNSBool mDNSAddrIPv4FromMappedIPv6(mDNSv6Addr *in, mDNSv4Addr *out);
2840 
2841 #define mDNSSameIPPort(A,B)      ((A).NotAnInteger == (B).NotAnInteger)
2842 #define mDNSSameOpaque16(A,B)    ((A).NotAnInteger == (B).NotAnInteger)
2843 #define mDNSSameOpaque32(A,B)    ((A).NotAnInteger == (B).NotAnInteger)
2844 #define mDNSSameOpaque64(A,B)    ((A)->l[0] == (B)->l[0] && (A)->l[1] == (B)->l[1])
2845 
2846 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
2847 #define mDNSSameIPv6Address(A,B) ((A).l[0] == (B).l[0] && (A).l[1] == (B).l[1] && (A).l[2] == (B).l[2] && (A).l[3] == (B).l[3])
2848 #define mDNSSameIPv6NetworkPart(A,B) ((A).l[0] == (B).l[0] && (A).l[1] == (B).l[1])
2849 #define mDNSSameEthAddress(A,B)  ((A)->w[0] == (B)->w[0] && (A)->w[1] == (B)->w[1] && (A)->w[2] == (B)->w[2])
2850 
2851 #define mDNSIPPortIsZero(A)      ((A).NotAnInteger                            == 0)
2852 #define mDNSOpaque16IsZero(A)    ((A).NotAnInteger                            == 0)
2853 #define mDNSOpaque64IsZero(A)    (((A)->l[0] | (A)->l[1]                    ) == 0)
2854 #define mDNSOpaque128IsZero(A)   (((A)->l[0] | (A)->l[1] | (A)->l[2] | (A)->l[3]) == 0)
2855 #define mDNSIPv4AddressIsZero(A) ((A).NotAnInteger                            == 0)
2856 #define mDNSIPv6AddressIsZero(A) (((A).l[0] | (A).l[1] | (A).l[2] | (A).l[3]) == 0)
2857 #define mDNSEthAddressIsZero(A)  (((A).w[0] | (A).w[1] | (A).w[2]           ) == 0)
2858 
2859 #define mDNSIPv4AddressIsOnes(A) ((A).NotAnInteger == 0xFFFFFFFF)
2860 #define mDNSIPv6AddressIsOnes(A) (((A).l[0] & (A).l[1] & (A).l[2] & (A).l[3]) == 0xFFFFFFFF)
2861 
2862 #define mDNSAddressIsAllDNSLinkGroup(X) (                                                            \
2863         ((X)->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address((X)->ip.v4, AllDNSLinkGroup_v4.ip.v4)) || \
2864         ((X)->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address((X)->ip.v6, AllDNSLinkGroup_v6.ip.v6))    )
2865 
2866 #define mDNSAddressIsZero(X) (                                                \
2867         ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4))  || \
2868         ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6))     )
2869 
2870 #define mDNSAddressIsValidNonZero(X) (                                        \
2871         ((X)->type == mDNSAddrType_IPv4 && !mDNSIPv4AddressIsZero((X)->ip.v4)) || \
2872         ((X)->type == mDNSAddrType_IPv6 && !mDNSIPv6AddressIsZero((X)->ip.v6))    )
2873 
2874 #define mDNSAddressIsOnes(X) (                                                \
2875         ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4))  || \
2876         ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6))     )
2877 
2878 #define mDNSAddressIsValid(X) (                                                                                             \
2879         ((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) :          \
2880         ((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
2881 
2882 #define mDNSv4AddressIsLinkLocal(X) ((X)->b[0] ==  169 &&  (X)->b[1]         ==  254)
2883 #define mDNSv6AddressIsLinkLocal(X) ((X)->b[0] == 0xFE && ((X)->b[1] & 0xC0) == 0x80)
2884 
2885 #define mDNSAddressIsLinkLocal(X)  (                                                    \
2886         ((X)->type == mDNSAddrType_IPv4) ? mDNSv4AddressIsLinkLocal(&(X)->ip.v4) :          \
2887         ((X)->type == mDNSAddrType_IPv6) ? mDNSv6AddressIsLinkLocal(&(X)->ip.v6) : mDNSfalse)
2888 
2889 
2890 // ***************************************************************************
2891 #if 0
2892 #pragma mark -
2893 #pragma mark - Authentication Support
2894 #endif
2895 
2896 // Unicast DNS and Dynamic Update specific Client Calls
2897 //
2898 // mDNS_SetSecretForDomain tells the core to authenticate (via TSIG with an HMAC_MD5 hash of the shared secret)
2899 // when dynamically updating a given zone (and its subdomains).  The key used in authentication must be in
2900 // domain name format.  The shared secret must be a null-terminated base64 encoded string.  A minimum size of
2901 // 16 bytes (128 bits) is recommended for an MD5 hash as per RFC 2485.
2902 // Calling this routine multiple times for a zone replaces previously entered values.  Call with a NULL key
2903 // to disable authentication for the zone.  A non-NULL autoTunnelPrefix means this is an AutoTunnel domain,
2904 // and the value is prepended to the IPSec identifier (used for key lookup)
2905 
2906 extern mStatus mDNS_SetSecretForDomain(mDNS *m, DomainAuthInfo *info,
2907                                        const domainname *domain, const domainname *keyname, const char *b64keydata, const domainname *hostname, mDNSIPPort *port);
2908 
2909 extern void RecreateNATMappings(mDNS *const m, const mDNSu32 waitTicks);
2910 
2911 // Hostname/Unicast Interface Configuration
2912 
2913 // All hostnames advertised point to one IPv4 address and/or one IPv6 address, set via SetPrimaryInterfaceInfo.  Invoking this routine
2914 // updates all existing hostnames to point to the new address.
2915 
2916 // A hostname is added via AddDynDNSHostName, which points to the primary interface's v4 and/or v6 addresss
2917 
2918 // The status callback is invoked to convey success or failure codes - the callback should not modify the AuthRecord or free memory.
2919 // Added hostnames may be removed (deregistered) via mDNS_RemoveDynDNSHostName.
2920 
2921 // Host domains added prior to specification of the primary interface address and computer name will be deferred until
2922 // these values are initialized.
2923 
2924 // DNS servers used to resolve unicast queries are specified by mDNS_AddDNSServer.
2925 // For "split" DNS configurations, in which queries for different domains are sent to different servers (e.g. VPN and external),
2926 // a domain may be associated with a DNS server.  For standard configurations, specify the root label (".") or NULL.
2927 
2928 extern void mDNS_AddDynDNSHostName(mDNS *m, const domainname *fqdn, mDNSRecordCallback *StatusCallback, const void *StatusContext);
2929 extern void mDNS_RemoveDynDNSHostName(mDNS *m, const domainname *fqdn);
2930 extern void mDNS_SetPrimaryInterfaceInfo(mDNS *m, const mDNSAddr *v4addr,  const mDNSAddr *v6addr, const mDNSAddr *router);
2931 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
2932 extern DNSServer *mDNS_AddDNSServer(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSs32 serviceID, const mDNSAddr *addr,
2933                                     const mDNSIPPort port, ScopeType scopeType, mDNSu32 timeout, mDNSBool cellIntf, mDNSBool isExpensive, mDNSBool isConstrained, mDNSBool isCLAT46,
2934                                     mDNSu32 resGroupID, mDNSBool reqA, mDNSBool reqAAAA, mDNSBool reqDO);
2935 extern void PenalizeDNSServer(mDNS *const m, DNSQuestion *q, mDNSOpaque16 responseFlags);
2936 #endif
2937 extern void mDNS_AddSearchDomain(const domainname *const domain, mDNSInterfaceID InterfaceID);
2938 
2939 extern McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout);
2940 
2941 // We use ((void *)0) here instead of mDNSNULL to avoid compile warnings on gcc 4.2
2942 #define mDNS_AddSearchDomain_CString(X, I) \
2943     do { domainname d__; if (((X) != (void*)0) && MakeDomainNameFromDNSNameString(&d__, (X)) && d__.c[0]) mDNS_AddSearchDomain(&d__, I);} while(0)
2944 
2945 // Routines called by the core, exported by DNSDigest.c
2946 
2947 // Convert an arbitrary base64 encoded key key into an HMAC key (stored in AuthInfo struct)
2948 extern mDNSs32 DNSDigest_ConstructHMACKeyfromBase64(DomainAuthInfo *info, const char *b64key);
2949 
2950 // sign a DNS message.  The message must be complete, with all values in network byte order.  end points to the end
2951 // of the message, and is modified by this routine.  numAdditionals is a pointer to the number of additional
2952 // records in HOST byte order, which is incremented upon successful completion of this routine.  The function returns
2953 // the new end pointer on success, and NULL on failure.
2954 extern void DNSDigest_SignMessage(DNSMessage *msg, mDNSu8 **end, DomainAuthInfo *info, mDNSu16 tcode);
2955 
2956 #define SwapDNSHeaderBytes(M) do { \
2957     (M)->h.numQuestions   = (mDNSu16)((mDNSu8 *)&(M)->h.numQuestions  )[0] << 8 | ((mDNSu8 *)&(M)->h.numQuestions  )[1]; \
2958     (M)->h.numAnswers     = (mDNSu16)((mDNSu8 *)&(M)->h.numAnswers    )[0] << 8 | ((mDNSu8 *)&(M)->h.numAnswers    )[1]; \
2959     (M)->h.numAuthorities = (mDNSu16)((mDNSu8 *)&(M)->h.numAuthorities)[0] << 8 | ((mDNSu8 *)&(M)->h.numAuthorities)[1]; \
2960     (M)->h.numAdditionals = (mDNSu16)((mDNSu8 *)&(M)->h.numAdditionals)[0] << 8 | ((mDNSu8 *)&(M)->h.numAdditionals)[1]; \
2961 } while (0)
2962 
2963 // verify a DNS message.  The message must be complete, with all values in network byte order.  end points to the
2964 // end of the record.  tsig is a pointer to the resource record that contains the TSIG OPT record.  info is
2965 // the matching key to use for verifying the message.  This function expects that the additionals member
2966 // of the DNS message header has already had one subtracted from it.
2967 extern mDNSBool DNSDigest_VerifyMessage(DNSMessage *msg, mDNSu8 *end, LargeCacheRecord *tsig, DomainAuthInfo *info, mDNSu16 *rcode, mDNSu16 *tcode);
2968 
2969 // ***************************************************************************
2970 #if 0
2971 #pragma mark -
2972 #pragma mark - PlatformSupport interface
2973 #endif
2974 
2975 // This section defines the interface to the Platform Support layer.
2976 // Normal client code should not use any of types defined here, or directly call any of the functions defined here.
2977 // The definitions are placed here because sometimes clients do use these calls indirectly, via other supported client operations.
2978 // For example, AssignDomainName is a macro defined using mDNSPlatformMemCopy()
2979 
2980 // Every platform support module must provide the following functions.
2981 // mDNSPlatformInit() typically opens a communication endpoint, and starts listening for mDNS packets.
2982 // When Setup is complete, the platform support layer calls mDNSCoreInitComplete().
2983 // mDNSPlatformSendUDP() sends one UDP packet
2984 // When a packet is received, the PlatformSupport code calls mDNSCoreReceive()
2985 // mDNSPlatformClose() tidies up on exit
2986 //
2987 // Note: mDNSPlatformMemAllocate/mDNSPlatformMemFree are only required for handling oversized resource records and unicast DNS.
2988 // If your target platform has a well-defined specialized application, and you know that all the records it uses
2989 // are InlineCacheRDSize or less, then you can just make a simple mDNSPlatformMemAllocate() stub that always returns
2990 // NULL. InlineCacheRDSize is a compile-time constant, which is set by default to 68. If you need to handle records
2991 // a little larger than this and you don't want to have to implement run-time allocation and freeing, then you
2992 // can raise the value of this constant to a suitable value (at the expense of increased memory usage).
2993 //
2994 // USE CAUTION WHEN CALLING mDNSPlatformRawTime: The m->timenow_adjust correction factor needs to be added
2995 // Generally speaking:
2996 // Code that's protected by the main mDNS lock should just use the m->timenow value
2997 // Code outside the main mDNS lock should use mDNS_TimeNow(m) to get properly adjusted time
2998 // In certain cases there may be reasons why it's necessary to get the time without taking the lock first
2999 // (e.g. inside the routines that are doing the locking and unlocking, where a call to get the lock would result in a
3000 // recursive loop); in these cases use mDNS_TimeNow_NoLock(m) to get mDNSPlatformRawTime with the proper correction factor added.
3001 //
3002 // mDNSPlatformUTC returns the time, in seconds, since Jan 1st 1970 UTC and is required for generating TSIG records
3003 
3004 #ifdef MDNS_MALLOC_DEBUGGING
3005 typedef void mDNSListValidationFunction(void *);
3006 typedef struct listValidator mDNSListValidator;
3007 struct listValidator {
3008     struct listValidator *next;
3009     const char *validationFunctionName;
3010     mDNSListValidationFunction *validator;
3011     void *context;
3012 };
3013 #endif // MDNS_MALLOC_DEBUGGING
3014 
3015 extern mStatus  mDNSPlatformInit        (mDNS *const m);
3016 extern void     mDNSPlatformClose       (mDNS *const m);
3017 extern mStatus  mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
3018                                     mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
3019                                     mDNSIPPort dstport, mDNSBool useBackgroundTrafficClass);
3020 
3021 extern void     mDNSPlatformLock        (const mDNS *const m);
3022 extern void     mDNSPlatformUnlock      (const mDNS *const m);
3023 
3024 extern mDNSu32  mDNSPlatformStrLCopy    (      void *dst, const void *src, mDNSu32 len);
3025 extern mDNSu32  mDNSPlatformStrLen      (                 const void *src);
3026 extern void     mDNSPlatformMemCopy     (      void *dst, const void *src, mDNSu32 len);
3027 extern mDNSBool mDNSPlatformMemSame     (const void *dst, const void *src, mDNSu32 len);
3028 extern int      mDNSPlatformMemCmp      (const void *dst, const void *src, mDNSu32 len);
3029 extern void     mDNSPlatformMemZero     (      void *dst,                  mDNSu32 len);
3030 extern void mDNSPlatformQsort       (void *base, int nel, int width, int (*compar)(const void *, const void *));
3031 #if MDNS_MALLOC_DEBUGGING
3032 #define         mDNSPlatformMemAllocate(X)      mallocL(# X, X)
3033 #define         mDNSPlatformMemAllocateClear(X)	callocL(# X, X)
3034 #define         mDNSPlatformMemFree(X)          freeL(# X, X)
3035 extern void     mDNSPlatformValidateLists (void);
3036 extern void     mDNSPlatformAddListValidator(mDNSListValidator *validator,
3037                                              mDNSListValidationFunction *vf, const char *vfName, void *context);
3038 #else
3039 extern void *   mDNSPlatformMemAllocate(mDNSu32 len);
3040 extern void *   mDNSPlatformMemAllocateClear(mDNSu32 len);
3041 extern void     mDNSPlatformMemFree(void *mem);
3042 #endif // MDNS_MALLOC_DEBUGGING
3043 
3044 // If the platform doesn't have a strong PRNG, we define a naive multiply-and-add based on a seed
3045 // from the platform layer.  Long-term, we should embed an arc4 implementation, but the strength
3046 // will still depend on the randomness of the seed.
3047 #if !defined(_PLATFORM_HAS_STRONG_PRNG_) && (_BUILDING_XCODE_PROJECT_ || defined(_WIN32))
3048 #define _PLATFORM_HAS_STRONG_PRNG_ 1
3049 #endif
3050 #if _PLATFORM_HAS_STRONG_PRNG_
3051 extern mDNSu32  mDNSPlatformRandomNumber(void);
3052 #else
3053 extern mDNSu32  mDNSPlatformRandomSeed  (void);
3054 #endif // _PLATFORM_HAS_STRONG_PRNG_
3055 
3056 extern mStatus  mDNSPlatformTimeInit    (void);
3057 extern mDNSs32  mDNSPlatformRawTime     (void);
3058 extern mDNSs32  mDNSPlatformUTC         (void);
3059 #define mDNS_TimeNow_NoLock(m) (mDNSPlatformRawTime() + (m)->timenow_adjust)
3060 
3061 #if MDNS_DEBUGMSGS
3062 extern void mDNSPlatformWriteDebugMsg(const char *msg);
3063 #endif
3064 extern void mDNSPlatformWriteLogMsg(const char *ident, const char *msg, mDNSLogLevel_t loglevel);
3065 
3066 // Platform support modules should provide the following functions to map between opaque interface IDs
3067 // and interface indexes in order to support the DNS-SD API. If your target platform does not support
3068 // multiple interfaces and/or does not support the DNS-SD API, these functions can be empty.
3069 extern mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 ifindex);
3070 extern mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange);
3071 
3072 // Every platform support module must provide the following functions if it is to support unicast DNS
3073 // and Dynamic Update.
3074 // All TCP socket operations implemented by the platform layer MUST NOT BLOCK.
3075 // mDNSPlatformTCPConnect initiates a TCP connection with a peer, adding the socket descriptor to the
3076 // main event loop.  The return value indicates whether the connection succeeded, failed, or is pending
3077 // (i.e. the call would block.)  On return, the descriptor parameter is set to point to the connected socket.
3078 // The TCPConnectionCallback is subsequently invoked when the connection
3079 // completes (in which case the ConnectionEstablished parameter is true), or data is available for
3080 // reading on the socket (indicated by the ConnectionEstablished parameter being false.)  If the connection
3081 // asynchronously fails, the TCPConnectionCallback should be invoked as usual, with the error being
3082 // returned in subsequent calls to PlatformReadTCP or PlatformWriteTCP.  (This allows for platforms
3083 // with limited asynchronous error detection capabilities.)  PlatformReadTCP and PlatformWriteTCP must
3084 // return the number of bytes read/written, 0 if the call would block, and -1 if an error.  PlatformReadTCP
3085 // should set the closed argument if the socket has been closed.
3086 // PlatformTCPCloseConnection must close the connection to the peer and remove the descriptor from the
3087 // event loop.  CloseConnectin may be called at any time, including in a ConnectionCallback.
3088 
3089 typedef enum
3090 {
3091     kTCPSocketFlags_Zero   = 0,
3092     kTCPSocketFlags_UseTLS = (1 << 0)
3093 } TCPSocketFlags;
3094 
3095 typedef void (*TCPConnectionCallback)(TCPSocket *sock, void *context, mDNSBool ConnectionEstablished, mStatus err);
3096 typedef void (*TCPAcceptedCallback)(TCPSocket *sock, mDNSAddr *addr, mDNSIPPort *port,
3097 									const char *remoteName, void *context);
3098 extern TCPSocket *mDNSPlatformTCPSocket(TCPSocketFlags flags, mDNSAddr_Type addrtype, mDNSIPPort *port, domainname *hostname, mDNSBool useBackgroundTrafficClass); // creates a TCP socket
3099 extern TCPListener *mDNSPlatformTCPListen(mDNSAddr_Type addrtype, mDNSIPPort *port, mDNSAddr *addr,
3100 										  TCPSocketFlags socketFlags, mDNSBool reuseAddr, int queueLength,
3101 										  TCPAcceptedCallback callback, void *context); // Listen on a port
3102 extern mStatus mDNSPlatformTCPSocketSetCallback(TCPSocket *sock, TCPConnectionCallback callback, void *context);
3103 extern TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int sd);
3104 extern int        mDNSPlatformTCPGetFD(TCPSocket *sock);
3105 extern mDNSBool   mDNSPlatformTCPWritable(TCPSocket *sock);
3106 extern mStatus    mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport,
3107                                          mDNSInterfaceID InterfaceID, TCPConnectionCallback callback, void *context);
3108 extern void       mDNSPlatformTCPCloseConnection(TCPSocket *sock);
3109 extern long       mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool *closed);
3110 extern long       mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len);
3111 extern UDPSocket *mDNSPlatformUDPSocket(const mDNSIPPort requestedport);
3112 extern mDNSu16    mDNSPlatformGetUDPPort(UDPSocket *sock);
3113 extern void       mDNSPlatformUDPClose(UDPSocket *sock);
3114 extern mDNSBool   mDNSPlatformUDPSocketEncounteredEOF(const UDPSocket *sock);
3115 extern void       mDNSPlatformReceiveBPF_fd(int fd);
3116 extern void       mDNSPlatformUpdateProxyList(const mDNSInterfaceID InterfaceID);
3117 extern void       mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID);
3118 extern void       mDNSPlatformSetLocalAddressCacheEntry(const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID);
3119 extern void       mDNSPlatformSourceAddrForDest(mDNSAddr *const src, const mDNSAddr *const dst);
3120 extern void       mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win);
3121 extern mStatus    mDNSPlatformRetrieveTCPInfo(mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr,  mDNSIPPort *rport, mDNSTCPInfo *mti);
3122 extern mStatus    mDNSPlatformGetRemoteMacAddr(mDNSAddr *raddr);
3123 extern mStatus    mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname);
3124 extern mStatus    mDNSPlatformClearSPSData(void);
3125 extern mStatus    mDNSPlatformStoreOwnerOptRecord(char *ifname, DNSMessage *msg, int length);
3126 
3127 // mDNSPlatformTLSSetupCerts/mDNSPlatformTLSTearDownCerts used by dnsextd
3128 extern mStatus    mDNSPlatformTLSSetupCerts(void);
3129 extern void       mDNSPlatformTLSTearDownCerts(void);
3130 
3131 // Platforms that support unicast browsing and dynamic update registration for clients who do not specify a domain
3132 // in browse/registration calls must implement these routines to get the "default" browse/registration list.
3133 
3134 extern mDNSBool   mDNSPlatformSetDNSConfig(mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
3135                                            DNameListElem **BrowseDomains, mDNSBool ackConfig);
3136 extern mStatus    mDNSPlatformGetPrimaryInterface(mDNSAddr *v4, mDNSAddr *v6, mDNSAddr *router);
3137 extern void       mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status);
3138 
3139 extern void       mDNSPlatformSetAllowSleep(mDNSBool allowSleep, const char *reason);
3140 extern void       mDNSPlatformPreventSleep(mDNSu32 timeout, const char *reason);
3141 extern void       mDNSPlatformSendWakeupPacket(mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration);
3142 
3143 extern mDNSBool   mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID);
3144 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
3145 extern mDNSBool   mDNSPlatformInterfaceIsAWDL(mDNSInterfaceID interfaceID);
3146 #endif
3147 extern mDNSBool   mDNSPlatformValidRecordForQuestion(const ResourceRecord *const rr, const DNSQuestion *const q);
3148 extern mDNSBool   mDNSPlatformValidRecordForInterface(const AuthRecord *rr, mDNSInterfaceID InterfaceID);
3149 extern mDNSBool   mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf);
3150 
3151 extern void mDNSPlatformFormatTime(unsigned long t, mDNSu8 *buf, int bufsize);
3152 
3153 // Platform event API
3154 
3155 #ifdef _LEGACY_NAT_TRAVERSAL_
3156 // Support for legacy NAT traversal protocols, implemented by the platform layer and callable by the core.
3157 extern void     LNT_SendDiscoveryMsg(mDNS *m);
3158 extern void     LNT_ConfigureRouterInfo(mDNS *m, const mDNSInterfaceID InterfaceID, const mDNSu8 *const data, const mDNSu16 len);
3159 extern mStatus  LNT_GetExternalAddress(mDNS *m);
3160 extern mStatus  LNT_MapPort(mDNS *m, NATTraversalInfo *const n);
3161 extern mStatus  LNT_UnmapPort(mDNS *m, NATTraversalInfo *const n);
3162 extern void     LNT_ClearState(mDNS *const m);
3163 #endif // _LEGACY_NAT_TRAVERSAL_
3164 
3165 // The core mDNS code provides these functions, for the platform support code to call at appropriate times
3166 //
3167 // mDNS_SetFQDN() is called once on startup (typically from mDNSPlatformInit())
3168 // and then again on each subsequent change of the host name.
3169 //
3170 // mDNS_RegisterInterface() is used by the platform support layer to inform mDNSCore of what
3171 // physical and/or logical interfaces are available for sending and receiving packets.
3172 // Typically it is called on startup for each available interface, but register/deregister may be
3173 // called again later, on multiple occasions, to inform the core of interface configuration changes.
3174 // If set->Advertise is set non-zero, then mDNS_RegisterInterface() also registers the standard
3175 // resource records that should be associated with every publicised IP address/interface:
3176 // -- Name-to-address records (A/AAAA)
3177 // -- Address-to-name records (PTR)
3178 // -- Host information (HINFO)
3179 // IMPORTANT: The specified mDNSInterfaceID MUST NOT be 0, -1, or -2; these values have special meaning
3180 // mDNS_RegisterInterface does not result in the registration of global hostnames via dynamic update -
3181 // see mDNS_SetPrimaryInterfaceInfo, mDNS_AddDynDNSHostName, etc. for this purpose.
3182 // Note that the set may be deallocated immediately after it is deregistered via mDNS_DeegisterInterface.
3183 //
3184 // mDNS_RegisterDNS() is used by the platform support layer to provide the core with the addresses of
3185 // available domain name servers for unicast queries/updates.  RegisterDNS() should be called once for
3186 // each name server, typically at startup, or when a new name server becomes available.  DeregiterDNS()
3187 // must be called whenever a registered name server becomes unavailable.  DeregisterDNSList deregisters
3188 // all registered servers.  mDNS_DNSRegistered() returns true if one or more servers are registered in the core.
3189 //
3190 // mDNSCoreInitComplete() is called when the platform support layer is finished.
3191 // Typically this is at the end of mDNSPlatformInit(), but may be later
3192 // (on platforms like OT that allow asynchronous initialization of the networking stack).
3193 //
3194 // mDNSCoreReceive() is called when a UDP packet is received
3195 //
3196 // mDNSCoreMachineSleep() is called when the machine sleeps or wakes
3197 // (This refers to heavyweight laptop-style sleep/wake that disables network access,
3198 // not lightweight second-by-second CPU power management modes.)
3199 
3200 extern void     mDNS_SetFQDN(mDNS *const m);
3201 extern void     mDNS_ActivateNetWake_internal  (mDNS *const m, NetworkInterfaceInfo *set);
3202 extern void     mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set);
3203 
3204 // Attributes that controls the Bonjour operation initiation and response speed for an interface.
3205 typedef enum
3206 {
3207     FastActivation,     // For p2p* and DirectLink type interfaces
3208     NormalActivation,   // For standard interface timing
3209     SlowActivation      // For flapping interfaces
3210 } InterfaceActivationSpeed;
3211 
3212 extern mStatus  mDNS_RegisterInterface  (mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed probeDelay);
3213 extern void     mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed probeDelay);
3214 extern void     mDNSCoreInitComplete(mDNS *const m, mStatus result);
3215 extern void     mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
3216                                 const mDNSAddr *const srcaddr, const mDNSIPPort srcport,
3217                                 const mDNSAddr *dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID);
3218 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
3219 extern void     mDNSCoreReceiveForQuerier(mDNS *m, DNSMessage *msg, const mDNSu8 *end, mdns_querier_t querier, mdns_dns_service_t service);
3220 #endif
3221 extern CacheRecord *mDNSCheckCacheFlushRecords(mDNS *m, CacheRecord *CacheFlushRecords, mDNSBool id_is_zero, int numAnswers,
3222 											   DNSQuestion *unicastQuestion, CacheRecord *NSECCachePtr, CacheRecord *NSECRecords,
3223 											   mDNSu8 rcode);
3224 extern void     mDNSCoreRestartQueries(mDNS *const m);
3225 extern void     mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q);
3226 extern void     mDNSCoreRestartRegistration(mDNS *const m, AuthRecord  *rr, int announceCount);
3227 typedef void (*FlushCache)(mDNS *const m);
3228 typedef void (*CallbackBeforeStartQuery)(mDNS *const m, void *context);
3229 extern void     mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
3230                                               CallbackBeforeStartQuery beforeQueryStart, void *context);
3231 extern mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m);
3232 extern void     mDNSCoreMachineSleep(mDNS *const m, mDNSBool wake);
3233 extern mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now);
3234 
3235 typedef enum
3236 {
3237     mDNSNextWakeReason_Null                        = 0,
3238     mDNSNextWakeReason_NATPortMappingRenewal       = 1,
3239     mDNSNextWakeReason_RecordRegistrationRenewal   = 2,
3240     mDNSNextWakeReason_UpkeepWake                  = 3,
3241     mDNSNextWakeReason_DHCPLeaseRenewal            = 4,
3242     mDNSNextWakeReason_SleepProxyRegistrationRetry = 5
3243 } mDNSNextWakeReason;
3244 
3245 extern mDNSs32  mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now, mDNSNextWakeReason *outReason);
3246 
3247 extern void     mDNSCoreReceiveRawPacket  (mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID);
3248 
3249 extern mDNSBool mDNSAddrIsDNSMulticast(const mDNSAddr *ip);
3250 
3251 extern CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress);
3252 extern CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 namehash, const domainname *const name);
3253 extern void ReleaseCacheRecord(mDNS *const m, CacheRecord *r);
3254 extern void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event);
3255 extern void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr);
3256 extern void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease);
3257 extern void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr, const domainname *const name,
3258     const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID,
3259 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
3260     mdns_dns_service_t service);
3261 #else
3262     DNSServer *dnsserver);
3263 #endif
3264 extern void CompleteDeregistration(mDNS *const m, AuthRecord *rr);
3265 extern void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord);
3266 extern void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr);
3267 extern char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID);
3268 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
3269 extern void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *newServer);
3270 #endif
3271 extern void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr);
3272 extern void CheckSuppressUnusableQuestions(mDNS *const m);
3273 extern void RetrySearchDomainQuestions(mDNS *const m);
3274 extern mDNSBool DomainEnumQuery(const domainname *qname);
3275 extern mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr);
3276 extern void  UpdateKeepaliveRMACAsync(mDNS *const m, void *context);
3277 extern void UpdateRMAC(mDNS *const m, void *context);
3278 
3279 // Used only in logging to restrict the number of /etc/hosts entries printed
3280 extern void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result);
3281 // exported for using the hash for /etc/hosts AuthRecords
3282 extern AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 namehash, const domainname *const name);
3283 extern AuthGroup *AuthGroupForRecord(AuthHash *r, const ResourceRecord *const rr);
3284 extern AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr);
3285 extern AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr);
3286 
3287 #if APPLE_OSX_mDNSResponder
3288 // For now this LocalSleepProxy stuff is specific to Mac OS X.
3289 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
3290 extern mStatus ActivateLocalProxy(NetworkInterfaceInfo *const intf, mDNSBool offloadKeepAlivesOnly, mDNSBool *keepaliveOnly);
3291 extern mDNSBool SupportsInNICProxy(NetworkInterfaceInfo *const intf);
3292 #endif
3293 
3294 typedef void ProxyCallback (void *socket, DNSMessage *const msg, const mDNSu8 *const end, const mDNSAddr *const srcaddr,
3295     const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, void *context);
3296 extern void mDNSPlatformInitDNSProxySkts(ProxyCallback *UDPCallback, ProxyCallback *TCPCallback);
3297 extern void mDNSPlatformCloseDNSProxySkts(mDNS *const m);
3298 extern void mDNSPlatformDisposeProxyContext(void *context);
3299 extern mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *start, mDNSu8 *limit);
3300 
3301 #if APPLE_OSX_mDNSResponder
3302 extern void mDNSPlatformGetDNSRoutePolicy(DNSQuestion *q);
3303 #endif
3304 extern void mDNSPlatformSetSocktOpt(void *sock, mDNSTransport_Type transType, mDNSAddr_Type addrType, const DNSQuestion *q);
3305 extern mDNSs32 mDNSPlatformGetPID(void);
3306 extern mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr);
3307 extern mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
3308 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
3309 extern void GetRandomUUIDLabel(domainlabel *label);
3310 extern void GetRandomUUIDLocalHostname(domainname *hostname);
3311 #endif
3312 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
3313 extern void uDNSMetricsClear(uDNSMetrics *metrics);
3314 #endif
3315 
3316 // ***************************************************************************
3317 #if 0
3318 #pragma mark -
3319 #pragma mark - Sleep Proxy
3320 #endif
3321 
3322 // Sleep Proxy Server Property Encoding
3323 //
3324 // Sleep Proxy Servers are advertised using a structured service name, consisting of four
3325 // metrics followed by a human-readable name. The metrics assist clients in deciding which
3326 // Sleep Proxy Server(s) to use when multiple are available on the network. Each metric
3327 // is a two-digit decimal number in the range 10-99. Lower metrics are generally better.
3328 //
3329 //   AA-BB-CC-DD.FF Name
3330 //
3331 // Metrics:
3332 //
3333 // AA = Intent
3334 // BB = Portability
3335 // CC = Marginal Power
3336 // DD = Total Power
3337 // FF = Features Supported (Currently TCP Keepalive only)
3338 //
3339 //
3340 // ** Intent Metric **
3341 //
3342 // 20 = Dedicated Sleep Proxy Server -- a device, permanently powered on,
3343 //      installed for the express purpose of providing Sleep Proxy Service.
3344 //
3345 // 30 = Primary Network Infrastructure Hardware -- a router, DHCP server, NAT gateway,
3346 //      or similar permanently installed device which is permanently powered on.
3347 //      This is hardware designed for the express purpose of being network
3348 //      infrastructure, and for most home users is typically a single point
3349 //      of failure for the local network -- e.g. most home users only have
3350 //      a single NAT gateway / DHCP server. Even though in principle the
3351 //      hardware might technically be capable of running different software,
3352 //      a typical user is unlikely to do that. e.g. AirPort base station.
3353 //
3354 // 40 = Primary Network Infrastructure Software -- a general-purpose computer
3355 //      (e.g. Mac, Windows, Linux, etc.) which is currently running DHCP server
3356 //      or NAT gateway software, but the user could choose to turn that off
3357 //      fairly easily. e.g. iMac running Internet Sharing
3358 //
3359 // 50 = Secondary Network Infrastructure Hardware -- like primary infrastructure
3360 //      hardware, except not a single point of failure for the entire local network.
3361 //      For example, an AirPort base station in bridge mode. This may have clients
3362 //      associated with it, and if it goes away those clients will be inconvenienced,
3363 //      but unlike the NAT gateway / DHCP server, the entire local network is not
3364 //      dependent on it.
3365 //
3366 // 60 = Secondary Network Infrastructure Software -- like 50, but in a general-
3367 //      purpose CPU.
3368 //
3369 // 70 = Incidentally Available Hardware -- a device which has no power switch
3370 //      and is generally left powered on all the time. Even though it is not a
3371 //      part of what we conventionally consider network infrastructure (router,
3372 //      DHCP, NAT, DNS, etc.), and the rest of the network can operate fine
3373 //      without it, since it's available and unlikely to be turned off, it is a
3374 //      reasonable candidate for providing Sleep Proxy Service e.g. Apple TV,
3375 //      or an AirPort base station in client mode, associated with an existing
3376 //      wireless network (e.g. AirPort Express connected to a music system, or
3377 //      being used to share a USB printer).
3378 //
3379 // 80 = Incidentally Available Software -- a general-purpose computer which
3380 //      happens at this time to be set to "never sleep", and as such could be
3381 //      useful as a Sleep Proxy Server, but has not been intentionally provided
3382 //      for this purpose. Of all the Intent Metric categories this is the
3383 //      one most likely to be shut down or put to sleep without warning.
3384 //      However, if nothing else is availalable, it may be better than nothing.
3385 //      e.g. Office computer in the workplace which has been set to "never sleep"
3386 //
3387 //
3388 // ** Portability Metric **
3389 //
3390 // Inversely related to mass of device, on the basis that, all other things
3391 // being equal, heavier devices are less likely to be moved than lighter devices.
3392 // E.g. A MacBook running Internet Sharing is probably more likely to be
3393 // put to sleep and taken away than a Mac Pro running Internet Sharing.
3394 // The Portability Metric is a logarithmic decibel scale, computed by taking the
3395 // (approximate) mass of the device in milligrammes, taking the base 10 logarithm
3396 // of that, multiplying by 10, and subtracting the result from 100:
3397 //
3398 //   Portability Metric = 100 - (log10(mg) * 10)
3399 //
3400 // The Portability Metric is not necessarily computed literally from the actual
3401 // mass of the device; the intent is just that lower numbers indicate more
3402 // permanent devices, and higher numbers indicate devices more likely to be
3403 // removed from the network, e.g., in order of increasing portability:
3404 //
3405 // Mac Pro < iMac < Laptop < iPhone
3406 //
3407 // Example values:
3408 //
3409 // 10 = 1 metric tonne
3410 // 40 = 1kg
3411 // 70 = 1g
3412 // 90 = 10mg
3413 //
3414 //
3415 // ** Marginal Power and Total Power Metrics **
3416 //
3417 // The Marginal Power Metric is the power difference between sleeping and staying awake
3418 // to be a Sleep Proxy Server.
3419 //
3420 // The Total Power Metric is the total power consumption when being Sleep Proxy Server.
3421 //
3422 // The Power Metrics use a logarithmic decibel scale, computed as ten times the
3423 // base 10 logarithm of the (approximate) power in microwatts:
3424 //
3425 //   Power Metric = log10(uW) * 10
3426 //
3427 // Higher values indicate higher power consumption. Example values:
3428 //
3429 // 10 =  10 uW
3430 // 20 = 100 uW
3431 // 30 =   1 mW
3432 // 60 =   1 W
3433 // 90 =   1 kW
3434 
3435 typedef enum
3436 {
3437     mDNSSleepProxyMetric_Dedicated          = 20,
3438     mDNSSleepProxyMetric_PrimaryHardware    = 30,
3439     mDNSSleepProxyMetric_PrimarySoftware    = 40,
3440     mDNSSleepProxyMetric_SecondaryHardware  = 50,
3441     mDNSSleepProxyMetric_SecondarySoftware  = 60,
3442     mDNSSleepProxyMetric_IncidentalHardware = 70,
3443     mDNSSleepProxyMetric_IncidentalSoftware = 80
3444 } mDNSSleepProxyMetric;
3445 
3446 typedef enum
3447 {
3448     mDNS_NoWake        = 0, // System does not support Wake on LAN
3449     mDNS_WakeOnAC      = 1, // System supports Wake on LAN when connected to AC power only
3450     mDNS_WakeOnBattery = 2  // System supports Wake on LAN on battery
3451 } mDNSWakeForNetworkAccess;
3452 
3453 extern void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features);
3454 #define mDNSCoreBeSleepProxyServer(M,S,P,MP,TP,F)                       \
3455     do { mDNS_Lock(m); mDNSCoreBeSleepProxyServer_internal((M),(S),(P),(MP),(TP),(F)); mDNS_Unlock(m); } while(0)
3456 
3457 extern void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3]);
3458 #define PrototypeSPSName(X) ((X)[0] >= 11 && (X)[3] == '-' && (X)[ 4] == '9' && (X)[ 5] == '9' && \
3459                              (X)[6] == '-' && (X)[ 7] == '9' && (X)[ 8] == '9' && \
3460                              (X)[9] == '-' && (X)[10] == '9' && (X)[11] == '9'    )
3461 #define ValidSPSName(X) ((X)[0] >= 5 && mDNSIsDigit((X)[1]) && mDNSIsDigit((X)[2]) && mDNSIsDigit((X)[4]) && mDNSIsDigit((X)[5]))
3462 #define SPSMetric(X) (!ValidSPSName(X) || PrototypeSPSName(X) ? 1000000 : \
3463                       ((X)[1]-'0') * 100000 + ((X)[2]-'0') * 10000 + ((X)[4]-'0') * 1000 + ((X)[5]-'0') * 100 + ((X)[7]-'0') * 10 + ((X)[8]-'0'))
3464 #define LocalSPSMetric(X) ( (X)->SPSType * 10000 + (X)->SPSPortability * 100 + (X)->SPSMarginalPower)
3465 #define SPSFeatures(X) ((X)[0] >= 13 && (X)[12] =='.' ? ((X)[13]-'0') : 0 )
3466 
3467 #define MD5_DIGEST_LENGTH   16          /* digest length in bytes */
3468 #define MD5_BLOCK_BYTES     64          /* block size in bytes */
3469 #define MD5_BLOCK_LONG       (MD5_BLOCK_BYTES / sizeof(mDNSu32))
3470 
3471 typedef struct MD5state_st
3472 {
3473     mDNSu32 A,B,C,D;
3474     mDNSu32 Nl,Nh;
3475     mDNSu32 data[MD5_BLOCK_LONG];
3476     mDNSu32 num;
3477 } MD5_CTX;
3478 
3479 extern int MD5_Init(MD5_CTX *c);
3480 extern int MD5_Update(MD5_CTX *c, const void *data, unsigned long len);
3481 extern int MD5_Final(unsigned char *md, MD5_CTX *c);
3482 
3483 // ***************************************************************************
3484 #if 0
3485 #pragma mark -
3486 #pragma mark - Compile-Time assertion checks
3487 #endif
3488 
3489 // Some C compiler cleverness. We can make the compiler check certain things for
3490 // us, and report compile-time errors if anything is wrong. The usual way to do
3491 // this would be to use a run-time "if" statement, but then you don't find out
3492 // what's wrong until you run the software. This way, if the assertion condition
3493 // is false, the array size is negative, and the complier complains immediately.
3494 
3495 struct CompileTimeAssertionChecks_mDNS
3496 {
3497     // Check that the compiler generated our on-the-wire packet format structure definitions
3498     // properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
3499     char assert0[(sizeof(rdataSRV)         == 262                          ) ? 1 : -1];
3500     char assert1[(sizeof(DNSMessageHeader) ==  12                          ) ? 1 : -1];
3501     char assert2[(sizeof(DNSMessage)       ==  12+AbsoluteMaxDNSMessageData) ? 1 : -1];
3502     char assert3[(sizeof(mDNSs8)           ==   1                          ) ? 1 : -1];
3503     char assert4[(sizeof(mDNSu8)           ==   1                          ) ? 1 : -1];
3504     char assert5[(sizeof(mDNSs16)          ==   2                          ) ? 1 : -1];
3505     char assert6[(sizeof(mDNSu16)          ==   2                          ) ? 1 : -1];
3506     char assert7[(sizeof(mDNSs32)          ==   4                          ) ? 1 : -1];
3507     char assert8[(sizeof(mDNSu32)          ==   4                          ) ? 1 : -1];
3508     char assert9[(sizeof(mDNSOpaque16)     ==   2                          ) ? 1 : -1];
3509     char assertA[(sizeof(mDNSOpaque32)     ==   4                          ) ? 1 : -1];
3510     char assertB[(sizeof(mDNSOpaque128)    ==  16                          ) ? 1 : -1];
3511     char assertC[(sizeof(CacheRecord  )    ==  sizeof(CacheGroup)          ) ? 1 : -1];
3512     char assertD[(sizeof(int)              >=  4                           ) ? 1 : -1];
3513     char assertE[(StandardAuthRDSize       >=  256                         ) ? 1 : -1];
3514     char assertF[(sizeof(EthernetHeader)   ==   14                         ) ? 1 : -1];
3515     char assertG[(sizeof(ARP_EthIP     )   ==   28                         ) ? 1 : -1];
3516     char assertH[(sizeof(IPv4Header    )   ==   20                         ) ? 1 : -1];
3517     char assertI[(sizeof(IPv6Header    )   ==   40                         ) ? 1 : -1];
3518     char assertJ[(sizeof(IPv6NDP       )   ==   24                         ) ? 1 : -1];
3519     char assertK[(sizeof(UDPHeader     )   ==    8                         ) ? 1 : -1];
3520     char assertL[(sizeof(IKEHeader     )   ==   28                         ) ? 1 : -1];
3521     char assertM[(sizeof(TCPHeader     )   ==   20                         ) ? 1 : -1];
3522 	char assertN[(sizeof(rdataOPT)		   ==   24                         ) ? 1 : -1];
3523 	char assertP[(sizeof(PCPMapRequest)    ==   60                         ) ? 1 : -1];
3524 	char assertQ[(sizeof(PCPMapReply)      ==   60                         ) ? 1 : -1];
3525 
3526 
3527     // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
3528     // other overly-large structures instead of having a pointer to them, can inadvertently
3529     // cause structure sizes (and therefore memory usage) to balloon unreasonably.
3530     char sizecheck_RDataBody           [(sizeof(RDataBody)            ==   264) ? 1 : -1];
3531     char sizecheck_ResourceRecord      [(sizeof(ResourceRecord)       <=    72) ? 1 : -1];
3532     char sizecheck_AuthRecord          [(sizeof(AuthRecord)           <=  1176) ? 1 : -1];
3533     char sizecheck_CacheRecord         [(sizeof(CacheRecord)          <=   232) ? 1 : -1];
3534     char sizecheck_CacheGroup          [(sizeof(CacheGroup)           <=   232) ? 1 : -1];
3535     char sizecheck_DNSQuestion         [(sizeof(DNSQuestion)          <=  1216) ? 1 : -1];
3536     char sizecheck_ZoneData            [(sizeof(ZoneData)             <=  2048) ? 1 : -1];
3537     char sizecheck_NATTraversalInfo    [(sizeof(NATTraversalInfo)     <=   200) ? 1 : -1];
3538     char sizecheck_HostnameInfo        [(sizeof(HostnameInfo)         <=  3050) ? 1 : -1];
3539 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
3540     char sizecheck_DNSServer           [(sizeof(DNSServer)            <=   328) ? 1 : -1];
3541 #endif
3542     char sizecheck_NetworkInterfaceInfo[(sizeof(NetworkInterfaceInfo) <=  9000) ? 1 : -1];
3543     char sizecheck_ServiceRecordSet    [(sizeof(ServiceRecordSet)     <=  4760) ? 1 : -1];
3544     char sizecheck_DomainAuthInfo      [(sizeof(DomainAuthInfo)       <=   944) ? 1 : -1];
3545 #if APPLE_OSX_mDNSResponder
3546     char sizecheck_ClientTunnel        [(sizeof(ClientTunnel)         <=  1560) ? 1 : -1];
3547 #endif
3548 #if MDNSRESPONDER_SUPPORTS(APPLE, OS_LOG)
3549     // structure size is assumed by LogRedact routine.
3550     char sizecheck_mDNSAddr            [(sizeof(mDNSAddr)             ==    20) ? 1 : -1];
3551     char sizecheck_mDNSv4Addr          [(sizeof(mDNSv4Addr)           ==     4) ? 1 : -1];
3552     char sizecheck_mDNSv6Addr          [(sizeof(mDNSv6Addr)           ==    16) ? 1 : -1];
3553 #endif
3554 };
3555 
3556 // Routine to initialize device-info TXT record contents
3557 mDNSu32 initializeDeviceInfoTXT(mDNS *m, mDNSu8 *ptr);
3558 
3559 // ***************************************************************************
3560 
3561 #ifdef __cplusplus
3562 }
3563 #endif
3564 
3565 #endif
3566