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