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