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