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