1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 If you're building an application that uses DNS Service Discovery
20 this is probably NOT the header file you're looking for.
21 In most cases you will want to use /usr/include/dns_sd.h instead.
23 This header file defines the lowest level raw interface to mDNSCore,
24 which is appropriate *only* on tiny embedded systems where everything
25 runs in a single address space and memory is extremely constrained.
26 All the APIs here are malloc-free, which means that the caller is
27 responsible for passing in a pointer to the relevant storage that
28 will be used in the execution of that call, and (when called with
29 correct parameters) all the calls are guaranteed to succeed. There
30 is never a case where a call can suffer intermittent failures because
31 the implementation calls malloc() and sometimes malloc() returns NULL
32 because memory is so limited that no more is available.
33 This is primarily for devices that need to have precisely known fixed
34 memory requirements, with absolutely no uncertainty or run-time variation,
35 but that certainty comes at a cost of more difficult programming.
37 For applications running on general-purpose desktop operating systems
38 (Mac OS, Linux, Solaris, Windows, etc.) the API you should use is
39 /usr/include/dns_sd.h, which defines the API by which multiple
40 independent client processes communicate their DNS Service Discovery
41 requests to a single "mdnsd" daemon running in the background.
43 Even on platforms that don't run multiple independent processes in
44 multiple independent address spaces, you can still use the preferred
45 dns_sd.h APIs by linking in "dnssd_clientshim.c", which implements
46 the standard "dns_sd.h" API calls, allocates any required storage
47 using malloc(), and then calls through to the low-level malloc-free
48 mDNSCore routines defined here. This has the benefit that even though
49 you're running on a small embedded system with a single address space,
50 you can still use the exact same client C code as you'd use on a
51 general-purpose desktop system.
54 Change History (most recent first):
56 $Log: mDNSEmbeddedAPI.h,v $
57 Revision 1.468 2008/03/06 02:48:34 mcguire
58 <rdar://problem/5321824> write status to the DS
60 Revision 1.467 2008/02/26 20:48:46 cheshire
61 Need parentheses around use of macro argument in mDNS_TimeNow_NoLock(m)
63 Revision 1.466 2008/02/21 21:36:32 cheshire
64 Updated comment about record type values (kDNSRecordTypePacketAns/Auth/Add)
66 Revision 1.465 2008/02/20 00:39:05 mcguire
67 <rdar://problem/5427102> Some device info XML blobs too large
69 Revision 1.464 2008/01/31 23:33:29 mcguire
70 <rdar://problem/5614450> changes to build using gcc 4.2 with -Werror
72 Revision 1.463 2007/12/17 23:53:25 cheshire
73 Added DNSDigest_SignMessageHostByteOrder, for signing messages not yet converted to network byte order
75 Revision 1.462 2007/12/17 23:48:29 cheshire
76 DNSDigest_SignMessage doesn't need to return a result -- it already updates the 'end' parameter
78 Revision 1.461 2007/12/15 00:18:51 cheshire
79 Renamed question->origLease to question->ReqLease
81 Revision 1.460 2007/12/14 23:55:28 cheshire
82 Moved "struct tcpInfo_t" definition from uDNS.c to mDNSEmbeddedAPI.h
84 Revision 1.459 2007/12/07 22:40:34 cheshire
85 Rename 'LocalAnswer' to more descriptive 'AnsweredLocalQ'
87 Revision 1.458 2007/12/07 00:45:58 cheshire
88 <rdar://problem/5526800> BTMM: Need to clean up registrations on shutdown
90 Revision 1.457 2007/12/06 00:22:27 mcguire
91 <rdar://problem/5604567> BTMM: Doesn't work with Linksys WAG300N 1.01.06 (sending from 1026/udp)
93 Revision 1.456 2007/12/05 01:45:35 cheshire
94 Renamed markedForDeletion -> MarkedForDeletion
96 Revision 1.455 2007/12/01 01:21:27 jgraessley
97 <rdar://problem/5623140> mDNSResponder unicast DNS improvements
99 Revision 1.454 2007/12/01 00:34:03 cheshire
100 Fixes from Bob Bradley for building on EFI
102 Revision 1.453 2007/10/29 23:51:22 cheshire
103 Added comment about NATTraversalInfo ExternalAddress field
105 Revision 1.452 2007/10/29 18:13:40 cheshire
106 Added Question_uDNS macro, analogous to AuthRecord_uDNS macro
108 Revision 1.451 2007/10/26 23:42:57 cheshire
109 Removed unused "mDNSs32 expire" field from ServiceRecordSet_struct
111 Revision 1.450 2007/10/26 22:24:08 cheshire
112 Added AuthRecord_uDNS() macro to determine when a given AuthRecord needs to be registered via unicast DNS
114 Revision 1.449 2007/10/25 20:48:47 cheshire
115 For naming consistency (with AuthRecord's UpdateServer) renamed 'ns' to 'SRSUpdateServer'
117 Revision 1.448 2007/10/22 22:19:44 cheshire
118 Tidied up code alignment
120 Revision 1.447 2007/10/22 19:40:30 cheshire
121 <rdar://problem/5519458> BTMM: Machines don't appear in the sidebar on wake from sleep
122 Made subroutine mDNSPlatformSourceAddrForDest(mDNSAddr *const src, const mDNSAddr *const dst)
124 Revision 1.446 2007/10/17 22:49:54 cheshire
125 <rdar://problem/5519458> BTMM: Machines don't appear in the sidebar on wake from sleep
127 Revision 1.445 2007/10/17 22:37:23 cheshire
128 <rdar://problem/5536979> BTMM: Need to create NAT port mapping for receiving LLQ events
130 Revision 1.444 2007/09/29 03:14:52 cheshire
131 <rdar://problem/5513168> BTMM: mDNSResponder memory corruption in GetAuthInfoForName_internal
132 Added AutoTunnelUnregistered macro to check state of DomainAuthInfo AuthRecords
134 Revision 1.443 2007/09/27 21:21:39 cheshire
135 Export CompleteDeregistration so it's callable from other files
137 Revision 1.442 2007/09/27 00:25:39 cheshire
138 Added ttl_seconds parameter to MakeNegativeCacheRecord in preparation for:
139 <rdar://problem/4947392> uDNS: Use SOA to determine TTL for negative answers
141 Revision 1.441 2007/09/26 23:17:49 cheshire
142 Get rid of unused kWideAreaTTL constant
144 Revision 1.440 2007/09/26 22:06:02 cheshire
145 <rdar://problem/5507399> BTMM: No immediate failure notifications for BTMM names
147 Revision 1.439 2007/09/21 21:12:36 cheshire
148 DNSDigest_SignMessage does not need separate "mDNSu16 *numAdditionals" parameter
150 Revision 1.438 2007/09/19 20:32:09 cheshire
151 Export GetAuthInfoForName so it's callable from other files
153 Revision 1.437 2007/09/18 21:42:29 cheshire
154 To reduce programming mistakes, renamed ExtPort to RequestedPort
156 Revision 1.436 2007/09/14 21:26:08 cheshire
157 <rdar://problem/5482627> BTMM: Need to manually avoid port conflicts when using UPnP gateways
159 Revision 1.435 2007/09/13 00:16:41 cheshire
160 <rdar://problem/5468706> Miscellaneous NAT Traversal improvements
162 Revision 1.434 2007/09/12 23:03:07 cheshire
163 <rdar://problem/5476978> DNSServiceNATPortMappingCreate callback not giving correct interface index
165 Revision 1.433 2007/09/12 22:19:28 cheshire
166 <rdar://problem/5476977> Need to listen for port 5350 NAT-PMP announcements
168 Revision 1.432 2007/09/12 19:22:19 cheshire
169 Variable renaming in preparation for upcoming fixes e.g. priv/pub renamed to intport/extport
170 Made NAT Traversal packet handlers take typed data instead of anonymous "mDNSu8 *" byte pointers
172 Revision 1.431 2007/09/11 19:19:16 cheshire
173 Correct capitalization of "uPNP" to "UPnP"
175 Revision 1.430 2007/09/10 22:06:50 cheshire
176 Rename uptime => upseconds and LastNATUptime => LastNATupseconds to make it clear these time values are in seconds
178 Revision 1.429 2007/09/07 21:16:58 cheshire
179 Add new symbol "NATPMPAnnouncementPort" (5350)
181 Revision 1.428 2007/09/05 21:48:01 cheshire
182 <rdar://problem/5385864> BTMM: mDNSResponder flushes wide-area Bonjour records after an hour for a zone.
183 Now that we're respecting the TTL of uDNS records in the cache, the LLQ maintenance cod needs
184 to update the cache lifetimes of all relevant records every time it successfully renews an LLQ,
185 otherwise those records will expire and vanish from the cache.
187 Revision 1.427 2007/09/05 20:47:12 cheshire
188 Tidied up alignment of code layout
190 Revision 1.426 2007/09/04 20:37:06 cheshire
191 <rdar://problem/5457287> mDNSResponder taking up 100% CPU in ReissueBlockedQuestions
192 Reorder fields into more logical order, with AuthInfo before DuplicateOf
194 Revision 1.425 2007/08/31 19:53:14 cheshire
195 <rdar://problem/5431151> BTMM: IPv6 address lookup should not succeed if autotunnel cannot be setup
196 If AutoTunnel setup fails, the code now generates a fake NXDomain error saying that the requested AAAA record does not exist
198 Revision 1.424 2007/08/31 18:49:49 vazquez
199 <rdar://problem/5393719> BTMM: Need to properly deregister when stopping BTMM
201 Revision 1.423 2007/08/31 00:04:28 cheshire
202 Added comment explaining deltime in DomainAuthInfo structure
204 Revision 1.422 2007/08/28 23:58:42 cheshire
205 Rename HostTarget -> AutoTarget
207 Revision 1.421 2007/08/27 20:30:43 cheshire
208 Only include TunnelClients list when building for OS X
210 Revision 1.420 2007/08/23 21:47:09 vazquez
211 <rdar://problem/5427316> BTMM: mDNSResponder sends NAT-PMP packets on public network
212 make sure we clean up port mappings on base stations by sending a lease value of 0,
213 and only send NAT-PMP packets on private networks; also save some memory by
214 not using packet structs in NATTraversals.
216 Revision 1.419 2007/08/08 21:07:47 vazquez
217 <rdar://problem/5244687> BTMM: Need to advertise model information via wide-area bonjour
219 Revision 1.418 2007/08/01 16:09:13 cheshire
220 Removed unused NATTraversalInfo substructure from AuthRecord; reduced structure sizecheck values accordingly
222 Revision 1.417 2007/08/01 03:04:59 cheshire
223 Add NATTraversalInfo structures to HostnameInfo and DomainAuthInfo
225 Revision 1.416 2007/08/01 00:04:13 cheshire
226 <rdar://problem/5261696> Crash in tcpKQSocketCallback
227 Half-open TCP connections were not being cancelled properly
229 Revision 1.415 2007/07/31 02:28:35 vazquez
230 <rdar://problem/3734269> NAT-PMP: Detect public IP address changes and base station reboot
232 Revision 1.414 2007/07/30 23:34:19 cheshire
233 Remove unused "udpSock" from DNSQuestion
235 Revision 1.413 2007/07/28 01:25:56 cheshire
236 <rdar://problem/4780038> BTMM: Add explicit UDP event port to LLQ setup request, to fix LLQs not working behind NAT
238 Revision 1.412 2007/07/27 23:57:23 cheshire
239 Added compile-time structure size checks
241 Revision 1.411 2007/07/27 22:50:08 vazquez
242 Allocate memory for UPnP request and reply buffers instead of using arrays
244 Revision 1.410 2007/07/27 19:37:19 cheshire
245 Moved AutomaticBrowseDomainQ into main mDNS object
247 Revision 1.409 2007/07/27 19:30:39 cheshire
248 Changed mDNSQuestionCallback parameter from mDNSBool to QC_result,
249 to properly reflect tri-state nature of the possible responses
251 Revision 1.408 2007/07/27 18:44:01 cheshire
252 Rename "AnswerQuestionWithResourceRecord" to more informative "AnswerCurrentQuestionWithResourceRecord"
254 Revision 1.407 2007/07/26 21:19:26 vazquez
255 Retry port mapping with incremented port number (up to max) in order to handle
256 port mapping conflicts on UPnP gateways
258 Revision 1.406 2007/07/25 22:19:59 cheshire
259 ClientTunnel structure also needs a rmt_outer_port field
261 Revision 1.405 2007/07/25 03:05:02 vazquez
263 <rdar://problem/5338913> LegacyNATTraversal: UPnP heap overflow
264 <rdar://problem/5338933> LegacyNATTraversal: UPnP stack buffer overflow
265 and a myriad of other security problems
267 Revision 1.404 2007/07/24 20:22:07 cheshire
268 Add AutoTunnelHostAddrActive flag
270 Revision 1.403 2007/07/24 04:14:29 cheshire
271 <rdar://problem/5356281> LLQs not working in with NAT Traversal
273 Revision 1.402 2007/07/21 00:54:44 cheshire
274 <rdar://problem/5344576> Delay IPv6 address callback until AutoTunnel route and policy is configured
276 Revision 1.401 2007/07/20 20:01:38 cheshire
277 Rename "mDNS_DomainTypeBrowseLegacy" as "mDNS_DomainTypeBrowseAutomatic"
279 Revision 1.400 2007/07/20 00:54:18 cheshire
280 <rdar://problem/4641118> Need separate SCPreferences for per-user .Mac settings
282 Revision 1.399 2007/07/18 03:22:35 cheshire
283 SetupLocalAutoTunnelInterface_internal needs to be callable from uDNS.c
285 Revision 1.398 2007/07/18 02:26:56 cheshire
286 Don't need to declare UpdateTunnels here
288 Revision 1.397 2007/07/18 01:03:50 cheshire
289 <rdar://problem/5303834> Automatically configure IPSec policy when resolving services
290 Add list of client tunnels so we can automatically reconfigure when local address changes
292 Revision 1.396 2007/07/16 23:54:48 cheshire
293 <rdar://problem/5338850> Crash when removing or changing DNS keys
295 Revision 1.395 2007/07/16 20:12:33 vazquez
296 <rdar://problem/3867231> LegacyNATTraversal: Need complete rewrite
298 Revision 1.394 2007/07/12 02:51:27 cheshire
299 <rdar://problem/5303834> Automatically configure IPSec policy when resolving services
301 Revision 1.393 2007/07/11 23:43:42 cheshire
302 Rename PurgeCacheResourceRecord to mDNS_PurgeCacheResourceRecord
304 Revision 1.392 2007/07/11 22:44:40 cheshire
305 <rdar://problem/5328801> SIGHUP should purge the cache
307 Revision 1.391 2007/07/11 20:30:45 cheshire
308 <rdar://problem/5304766> Register IPSec tunnel with IPv4-only hostname and create NAT port mappings
309 Added AutoTunnelTarget and AutoTunnelService to DomainAuthInfo structure
311 Revision 1.390 2007/07/11 18:56:55 cheshire
312 Added comments about AutoTunnelHostAddr and AutoTunnelLabel
314 Revision 1.389 2007/07/11 02:44:03 cheshire
315 <rdar://problem/5303807> Register IPv6-only hostname and don't create port mappings for AutoTunnel services
316 Added AutoTunnel fields to structures
318 Revision 1.388 2007/07/10 01:53:18 cheshire
319 <rdar://problem/5196524> uDNS: mDNSresponder is leaking TCP connections to DNS server
320 AuthRecord, ServiceRecordSet, and DNSQuestion structures need tcpInfo_t pointers
321 so they can keep track of what TCP connections they open
323 Revision 1.387 2007/07/06 18:55:15 cheshire
324 Add explicit NextScheduledNATOp scheduling variable
326 Revision 1.386 2007/07/03 20:54:11 cheshire
327 Tidied up code layout of NATTraversalInfo_struct fields and comments
329 Revision 1.385 2007/07/03 00:40:23 vazquez
330 More changes for <rdar://problem/5301908> Clean up NAT state machine (necessary for 6 other fixes)
331 Safely deal with packet replies and client callbacks
333 Revision 1.384 2007/06/29 00:08:07 vazquez
334 <rdar://problem/5301908> Clean up NAT state machine (necessary for 6 other fixes)
336 Revision 1.383 2007/06/20 01:10:12 cheshire
337 <rdar://problem/5280520> Sync iPhone changes into main mDNSResponder code
339 Revision 1.382 2007/06/19 20:31:59 cheshire
340 Add DNSServer_Disabled state
341 Add mDNSInterfaceID for DNS servers reachable over specific interfaces
343 Revision 1.381 2007/06/15 18:11:16 cheshire
344 <rdar://problem/5174466> mDNSResponder crashed in memove() near end of MobileSafari stress test
345 Made AssignDomainName more defensive when source name is garbage
347 Revision 1.380 2007/05/25 00:04:51 cheshire
348 Added comment explaining rdlength
350 Revision 1.379 2007/05/21 18:04:40 cheshire
351 Updated comments -- port_mapping_create_reply renamed to port_mapping_reply
353 Revision 1.378 2007/05/17 19:11:46 cheshire
356 Revision 1.377 2007/05/15 00:43:33 cheshire
357 Remove unused regState_Cancelled
359 Revision 1.376 2007/05/14 23:51:49 cheshire
360 Added constants MAX_REVERSE_MAPPING_NAME_V4 and MAX_REVERSE_MAPPING_NAME_V6
362 Revision 1.375 2007/05/10 21:19:18 cheshire
363 Rate-limit DNS test queries to at most one per three seconds
364 (useful when we have a dozen active WAB queries, and then we join a new network)
366 Revision 1.374 2007/05/07 22:07:47 cheshire
367 <rdar://problem/4738025> Enhance GetLargeResourceRecord to decompress more record types
369 Revision 1.373 2007/05/07 20:43:45 cheshire
370 <rdar://problem/4241419> Reduce the number of queries and announcements
372 Revision 1.372 2007/05/04 22:15:29 cheshire
373 Get rid of unused q->RestartTime
375 Revision 1.371 2007/05/03 22:40:37 cheshire
376 <rdar://problem/4669229> mDNSResponder ignores bogus null target in SRV record
378 Revision 1.370 2007/05/02 22:18:09 cheshire
379 Renamed NATTraversalInfo_struct context to NATTraversalContext
381 Revision 1.369 2007/05/01 21:21:42 cheshire
382 Add missing parentheses in LEASE_OPT_RDLEN definition
384 Revision 1.368 2007/04/30 21:33:38 cheshire
385 Fix crash when a callback unregisters a service while the UpdateSRVRecords() loop
386 is iterating through the m->ServiceRegistrations list
388 Revision 1.367 2007/04/28 01:31:59 cheshire
389 Improve debugging support for catching memory corruption problems
391 Revision 1.366 2007/04/27 19:28:02 cheshire
392 Any code that calls StartGetZoneData needs to keep a handle to the structure, so
393 it can cancel it if necessary. (First noticed as a crash in Apple Remote Desktop
394 -- it would start a query and then quickly cancel it, and then when
395 StartGetZoneData completed, it had a dangling pointer and crashed.)
397 Revision 1.365 2007/04/26 00:35:15 cheshire
398 <rdar://problem/5140339> uDNS: Domain discovery not working over VPN
399 Fixes to make sure results update correctly when connectivity changes (e.g. a DNS server
400 inside the firewall may give answers where a public one gives none, and vice versa.)
402 Revision 1.364 2007/04/24 02:07:42 cheshire
403 <rdar://problem/4246187> Identical client queries should reference a single shared core query
404 Deleted some more redundant code
406 Revision 1.363 2007/04/24 00:09:47 cheshire
407 Remove MappedV4 field from mDNS_struct (not actually used anywhere)
409 Revision 1.362 2007/04/22 06:02:02 cheshire
410 <rdar://problem/4615977> Query should immediately return failure when no server
412 Revision 1.361 2007/04/21 19:43:33 cheshire
413 Code tidying: represent NAT opcodes as bitwise combinations rather than numerical additions
415 Revision 1.360 2007/04/20 21:17:24 cheshire
416 For naming consistency, kDNSRecordTypeNegative should be kDNSRecordTypePacketNegative
418 Revision 1.359 2007/04/19 22:50:53 cheshire
419 <rdar://problem/4246187> Identical client queries should reference a single shared core query
421 Revision 1.358 2007/04/19 20:06:41 cheshire
422 Rename field 'Private' (sounds like a boolean) to more informative 'AuthInfo' (it's a DomainAuthInfo pointer)
424 Revision 1.357 2007/04/19 18:14:51 cheshire
425 In mDNS_AddSearchDomain_CString check for NULL pointer before calling MakeDomainNameFromDNSNameString()
427 Revision 1.356 2007/04/18 20:56:46 cheshire
428 Added mDNS_AddSearchDomain_CString macro
430 Revision 1.355 2007/04/17 19:21:29 cheshire
431 <rdar://problem/5140339> Domain discovery not working over VPN
433 Revision 1.354 2007/04/05 22:55:34 cheshire
434 <rdar://problem/5077076> Records are ending up in Lighthouse without expiry information
436 Revision 1.353 2007/04/05 20:40:37 cheshire
437 Remove unused mDNSPlatformTCPGetFlags()
439 Revision 1.352 2007/04/04 21:48:52 cheshire
440 <rdar://problem/4720694> Combine unicast authoritative answer list with multicast list
442 Revision 1.351 2007/04/04 01:27:45 cheshire
445 Revision 1.350 2007/04/04 00:03:26 cheshire
446 <rdar://problem/5089862> DNSServiceQueryRecord is returning kDNSServiceErr_NoSuchRecord for empty rdata
448 Revision 1.349 2007/04/03 19:37:58 cheshire
449 Rename mDNSAddrIsv4Private() to more precise mDNSAddrIsRFC1918()
451 Revision 1.348 2007/04/03 19:13:39 cheshire
452 Added macros mDNSSameIPPort, mDNSSameOpaque16, mDNSIPPortIsZero, mDNSOpaque16IsZero
454 Revision 1.347 2007/03/28 20:59:26 cheshire
455 <rdar://problem/4743285> Remove inappropriate use of IsPrivateV4Addr()
457 Revision 1.346 2007/03/28 15:56:37 cheshire
458 <rdar://problem/5085774> Add listing of NAT port mapping and GetAddrInfo requests in SIGINFO output
460 Revision 1.345 2007/03/22 19:29:23 cheshire
461 Add comment and check to ensure StandardAuthRDSize is at least 256 bytes
463 Revision 1.344 2007/03/22 18:31:48 cheshire
464 Put dst parameter first in mDNSPlatformStrCopy/mDNSPlatformMemCopy, like conventional Posix strcpy/memcpy
466 Revision 1.343 2007/03/22 00:49:20 cheshire
467 <rdar://problem/4848295> Advertise model information via Bonjour
469 Revision 1.342 2007/03/21 23:06:00 cheshire
470 Rename uDNS_HostnameInfo to HostnameInfo; deleted some unused fields
472 Revision 1.341 2007/03/21 20:44:11 cheshire
473 Added mDNSAddressIsv4LinkLocal macro
475 Revision 1.340 2007/03/21 00:30:02 cheshire
476 <rdar://problem/4789455> Multiple errors in DNameList-related code
478 Revision 1.339 2007/03/20 17:07:15 cheshire
479 Rename "struct uDNS_TCPSocket_struct" to "TCPSocket", "struct uDNS_UDPSocket_struct" to "UDPSocket"
481 Revision 1.338 2007/03/10 02:28:28 cheshire
482 Added comment explaining NATResponseHndlr
484 Revision 1.337 2007/03/10 02:02:58 cheshire
485 <rdar://problem/4961667> uDNS: LLQ refresh response packet causes cached records to be removed from cache
486 Eliminate unnecessary "InternalResponseHndlr responseCallback" function pointer
488 Revision 1.336 2007/02/28 22:12:24 cheshire
489 Get rid of unused mDNSVal32 and mDNSOpaque32fromIntVal
491 Revision 1.335 2007/02/28 21:49:07 cheshire
492 Off-by-one error: SameDomainLabelCS (case-sensitive) was stopping one character short of
493 the end of the label, e.g. it would fail to detect that "chesh1" and "chesh2" are different.
495 Revision 1.334 2007/02/28 01:44:26 cheshire
496 <rdar://problem/5027863> Byte order bugs in uDNS.c, uds_daemon.c, dnssd_clientstub.c
498 Revision 1.333 2007/02/27 22:55:22 cheshire
499 Get rid of unused AllDNSLinkGroupv4 and AllDNSLinkGroupv6
501 Revision 1.332 2007/02/27 02:48:24 cheshire
502 Parameter to LNT_GetPublicIP function is IPv4 address, not anonymous "mDNSOpaque32" object
504 Revision 1.331 2007/02/14 03:16:39 cheshire
505 <rdar://problem/4789477> Eliminate unnecessary malloc/free in mDNSCore code
507 Revision 1.330 2007/02/08 21:12:28 cheshire
508 <rdar://problem/4386497> Stop reading /etc/mDNSResponder.conf on every sleep/wake
510 Revision 1.329 2007/02/07 01:19:36 cheshire
511 <rdar://problem/4849427> API: Reconcile conflicting error code values
513 Revision 1.328 2007/01/25 00:19:40 cheshire
514 Add CNAMEReferrals field to DNSQuestion_struct
516 Revision 1.327 2007/01/23 02:56:10 cheshire
517 Store negative results in the cache, instead of generating them out of pktResponseHndlr()
519 Revision 1.326 2007/01/20 01:30:49 cheshire
522 Revision 1.325 2007/01/19 18:39:11 cheshire
523 Fix a bunch of parameters that should have been declared "const"
525 Revision 1.324 2007/01/19 18:04:04 cheshire
526 For naming consistency, use capital letters for RR types: rdataOpt should be rdataOPT
528 Revision 1.323 2007/01/17 21:46:02 cheshire
529 Remove redundant duplicated "isPrivate" field from LLQ_Info
531 Revision 1.322 2007/01/10 22:51:56 cheshire
532 <rdar://problem/4917539> Add support for one-shot private queries as well as long-lived private queries
534 Revision 1.321 2007/01/09 22:37:18 cheshire
535 Provide ten-second grace period for deleted keys, to give mDNSResponder
536 time to delete host name before it gives up access to the required key.
538 Revision 1.320 2007/01/05 08:30:41 cheshire
539 Trim excessive "$Log" checkin history from before 2006
540 (checkin history still available via "cvs log ..." of course)
542 Revision 1.319 2007/01/04 23:11:11 cheshire
543 <rdar://problem/4720673> uDNS: Need to start caching unicast records
544 When an automatic browsing domain is removed, generate appropriate "remove" events for legacy queries
546 Revision 1.318 2007/01/04 20:57:48 cheshire
547 Rename ReturnCNAME to ReturnIntermed (for ReturnIntermediates)
549 Revision 1.317 2007/01/04 02:39:53 cheshire
550 <rdar://problem/4030599> Hostname passed into DNSServiceRegister ignored for Wide-Area service registrations
552 Revision 1.316 2006/12/22 20:59:49 cheshire
553 <rdar://problem/4742742> Read *all* DNS keys from keychain,
554 not just key for the system-wide default registration domain
556 Revision 1.315 2006/12/20 04:07:35 cheshire
557 Remove uDNS_info substructure from AuthRecord_struct
559 Revision 1.314 2006/12/19 22:49:23 cheshire
560 Remove uDNS_info substructure from ServiceRecordSet_struct
562 Revision 1.313 2006/12/19 02:38:20 cheshire
563 Get rid of unnecessary duplicate query ID field from DNSQuestion_struct
565 Revision 1.312 2006/12/19 02:18:48 cheshire
566 Get rid of unnecessary duplicate "void *context" field from DNSQuestion_struct
568 Revision 1.311 2006/12/16 01:58:31 cheshire
569 <rdar://problem/4720673> uDNS: Need to start caching unicast records
571 Revision 1.310 2006/12/15 19:09:56 cheshire
572 <rdar://problem/4769083> ValidateRData() should be stricter about malformed MX and SRV records
573 Made DomainNameLength() more defensive by adding a limit parameter, so it can be
574 safely used to inspect potentially malformed data received from external sources.
575 Without this, a domain name that starts off apparently valid, but extends beyond the end of
576 the received packet data, could have appeared valid if the random bytes are already in memory
577 beyond the end of the packet just happened to have reasonable values (e.g. all zeroes).
579 Revision 1.309 2006/12/14 03:02:37 cheshire
580 <rdar://problem/4838433> Tools: dns-sd -G 0 only returns IPv6 when you have a routable IPv6 address
582 Revision 1.308 2006/11/30 23:07:56 herscher
583 <rdar://problem/4765644> uDNS: Sync up with Lighthouse changes for Private DNS
585 Revision 1.307 2006/11/18 05:01:30 cheshire
586 Preliminary support for unifying the uDNS and mDNS code,
587 including caching of uDNS answers
589 Revision 1.306 2006/11/10 07:44:04 herscher
590 <rdar://problem/4825493> Fix Daemon locking failures while toggling BTMM
592 Revision 1.305 2006/11/10 00:54:15 cheshire
593 <rdar://problem/4816598> Changing case of Computer Name doesn't work
595 Revision 1.304 2006/10/20 05:35:05 herscher
596 <rdar://problem/4720713> uDNS: Merge unicast active question list with multicast list.
598 Revision 1.303 2006/10/04 21:37:33 herscher
599 Remove uDNS_info substructure from DNSQuestion_struct
601 Revision 1.302 2006/09/26 01:53:25 herscher
602 <rdar://problem/4245016> NAT Port Mapping API (for both NAT-PMP and UPnP Gateway Protocol)
604 Revision 1.301 2006/09/15 21:20:15 cheshire
605 Remove uDNS_info substructure from mDNS_struct
607 Revision 1.300 2006/08/14 23:24:23 cheshire
608 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
610 Revision 1.299 2006/07/15 02:01:28 cheshire
611 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
612 Fix broken "empty string" browsing
614 Revision 1.298 2006/07/05 22:55:03 cheshire
615 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
616 Need Private field in uDNS_RegInfo
618 Revision 1.297 2006/07/05 22:20:03 cheshire
619 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
621 Revision 1.296 2006/06/29 05:28:01 cheshire
622 Added comment about mDNSlocal and mDNSexport
624 Revision 1.295 2006/06/29 03:02:43 cheshire
625 <rdar://problem/4607042> mDNSResponder NXDOMAIN and CNAME support
627 Revision 1.294 2006/06/28 06:50:08 cheshire
628 In future we may want to change definition of mDNSs32 from "signed long" to "signed int"
629 I doubt anyone is building mDNSResponder on systems where int is 16-bits,
630 but lets add a compile-time assertion to make sure.
632 Revision 1.293 2006/06/12 18:00:43 cheshire
633 To make code a little more defensive, check _ILP64 before _LP64,
634 in case both are set by mistake on some platforms
636 Revision 1.292 2006/03/19 17:00:57 cheshire
637 Define symbol MaxMsg instead of using hard-coded constant value '80'
639 Revision 1.291 2006/03/19 02:00:07 cheshire
640 <rdar://problem/4073825> Improve logic for delaying packets after repeated interface transitions
642 Revision 1.290 2006/03/08 22:42:23 cheshire
643 Fix spelling mistake: LocalReverseMapomain -> LocalReverseMapDomain
645 Revision 1.289 2006/02/26 00:54:41 cheshire
646 Fixes to avoid code generation warning/error on FreeBSD 7
650 #ifndef __mDNSClientAPI_h
651 #define __mDNSClientAPI_h
653 #if defined(EFI32) || defined(EFI64) || defined(EFIX64)
654 // EFI doesn't have stdarg.h unless it's building with GCC.
656 #if !defined(__GNUC__)
657 #define va_list VA_LIST
658 #define va_start(a, b) VA_START(a, b)
659 #define va_end(a) VA_END(a)
660 #define va_arg(a, b) VA_ARG(a, b)
663 #include <stdarg.h> // stdarg.h is required for for va_list support for the mDNS_vsnprintf declaration
666 #include "mDNSDebug.h"
672 // ***************************************************************************
673 // Function scope indicators
675 // If you see "mDNSlocal" before a function name in a C file, it means the function is not callable outside this file
677 #define mDNSlocal static
679 // If you see "mDNSexport" before a symbol in a C file, it means the symbol is exported for use by clients
680 // For every "mDNSexport" in a C file, there needs to be a corresponding "extern" declaration in some header file
681 // (When a C file #includes a header file, the "extern" declarations tell the compiler:
682 // "This symbol exists -- but not necessarily in this C file.")
687 // Explanation: These local/export markers are a little habit of mine for signaling the programmers' intentions.
688 // When "mDNSlocal" is just a synonym for "static", and "mDNSexport" is a complete no-op, you could be
689 // forgiven for asking what purpose they serve. The idea is that if you see "mDNSexport" in front of a
690 // function definition it means the programmer intended it to be exported and callable from other files
691 // in the project. If you see "mDNSlocal" in front of a function definition it means the programmer
692 // intended it to be private to that file. If you see neither in front of a function definition it
693 // means the programmer forgot (so you should work out which it is supposed to be, and fix it).
694 // Using "mDNSlocal" instead of "static" makes it easier to do a textual searches for one or the other.
695 // For example you can do a search for "static" to find if any functions declare any local variables as "static"
696 // (generally a bad idea unless it's also "const", because static storage usually risks being non-thread-safe)
697 // without the results being cluttered with hundreds of matches for functions declared static.
700 // ***************************************************************************
701 // Structure packing macro
703 // If we're not using GNUC, it's not fatal.
704 // Most compilers naturally pack the on-the-wire structures correctly anyway, so a plain "struct" is usually fine.
705 // In the event that structures are not packed correctly, mDNS_Init() will detect this and report an error, so the
706 // developer will know what's wrong, and can investigate what needs to be done on that compiler to provide proper packing.
708 #if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
709 #define packedstruct struct __attribute__((__packed__))
710 #define packedunion union __attribute__((__packed__))
712 #define packedstruct struct
713 #define packedunion union
717 // ***************************************************************************
719 #pragma mark - DNS Resource Record class and type constants
722 typedef enum // From RFC 1035
724 kDNSClass_IN
= 1, // Internet
725 kDNSClass_CS
= 2, // CSNET
726 kDNSClass_CH
= 3, // CHAOS
727 kDNSClass_HS
= 4, // Hesiod
728 kDNSClass_NONE
= 254, // Used in DNS UPDATE [RFC 2136]
730 kDNSClass_Mask
= 0x7FFF,// Multicast DNS uses the bottom 15 bits to identify the record class...
731 kDNSClass_UniqueRRSet
= 0x8000,// ... and the top bit indicates that all other cached records are now invalid
733 kDNSQClass_ANY
= 255, // Not a DNS class, but a DNS query class, meaning "all classes"
734 kDNSQClass_UnicastResponse
= 0x8000 // Top bit set in a question means "unicast response acceptable"
737 typedef enum // From RFC 1035
739 kDNSType_A
= 1, // 1 Address
740 kDNSType_NS
, // 2 Name Server
741 kDNSType_MD
, // 3 Mail Destination
742 kDNSType_MF
, // 4 Mail Forwarder
743 kDNSType_CNAME
, // 5 Canonical Name
744 kDNSType_SOA
, // 6 Start of Authority
745 kDNSType_MB
, // 7 Mailbox
746 kDNSType_MG
, // 8 Mail Group
747 kDNSType_MR
, // 9 Mail Rename
748 kDNSType_NULL
, // 10 NULL RR
749 kDNSType_WKS
, // 11 Well-known-service
750 kDNSType_PTR
, // 12 Domain name pointer
751 kDNSType_HINFO
, // 13 Host information
752 kDNSType_MINFO
, // 14 Mailbox information
753 kDNSType_MX
, // 15 Mail Exchanger
754 kDNSType_TXT
, // 16 Arbitrary text string
755 kDNSType_RP
, // 17 Responsible person.
756 kDNSType_AFSDB
, // 18 AFS cell database.
757 kDNSType_X25
, // 19 X_25 calling address.
758 kDNSType_ISDN
, // 20 ISDN calling address.
759 kDNSType_RT
, // 21 Router.
760 kDNSType_NSAP
, // 22 NSAP address.
761 kDNSType_NSAP_PTR
, // 23 Reverse NSAP lookup (deprecated).
762 kDNSType_SIG
, // 24 Security signature.
763 kDNSType_KEY
, // 25 Security key.
764 kDNSType_PX
, // 26 X.400 mail mapping.
765 kDNSType_GPOS
, // 27 Geographical position (withdrawn).
766 kDNSType_AAAA
, // 28 IPv6 Address.
767 kDNSType_LOC
, // 29 Location Information.
768 kDNSType_NXT
, // 30 Next domain (security).
769 kDNSType_EID
, // 31 Endpoint identifier.
770 kDNSType_NIMLOC
, // 32 Nimrod Locator.
771 kDNSType_SRV
, // 33 Service record.
772 kDNSType_ATMA
, // 34 ATM Address
773 kDNSType_NAPTR
, // 35 Naming Authority PoinTeR
774 kDNSType_KX
, // 36 Key Exchange
775 kDNSType_CERT
, // 37 Certification record
776 kDNSType_A6
, // 38 IPv6 Address (deprecated)
777 kDNSType_DNAME
, // 39 Non-terminal DNAME (for IPv6)
778 kDNSType_SINK
, // 40 Kitchen sink (experimentatl)
779 kDNSType_OPT
, // 41 EDNS0 option (meta-RR)
780 kDNSType_APL
, // 42 Address Prefix List
781 kDNSType_DS
, // 43 Delegation Signer
782 kDNSType_SSHFP
, // 44 SSH Key Fingerprint
783 kDNSType_IPSECKEY
, // 45 IPSECKEY
784 kDNSType_RRSIG
, // 46 RRSIG
785 kDNSType_NSEC
, // 47 NSEC
786 kDNSType_DNSKEY
, // 48 DNSKEY
787 kDNSType_DHCID
, // 49 DHCID
789 kDNSType_TKEY
= 249, // 249 Transaction key
790 kDNSType_TSIG
, // 250 Transaction signature.
791 kDNSType_IXFR
, // 251 Incremental zone transfer.
792 kDNSType_AXFR
, // 252 Transfer zone of authority.
793 kDNSType_MAILB
, // 253 Transfer mailbox records.
794 kDNSType_MAILA
, // 254 Transfer mail agent records.
795 kDNSQType_ANY
// Not a DNS type, but a DNS query type, meaning "all types"
798 // ***************************************************************************
800 #pragma mark - Simple types
803 // mDNS defines its own names for these common types to simplify portability across
804 // multiple platforms that may each have their own (different) names for these types.
805 typedef int mDNSBool
;
806 typedef signed char mDNSs8
;
807 typedef unsigned char mDNSu8
;
808 typedef signed short mDNSs16
;
809 typedef unsigned short mDNSu16
;
811 // <http://gcc.gnu.org/onlinedocs/gcc-3.3.3/cpp/Common-Predefined-Macros.html> says
813 // These macros are defined, with value 1, if (and only if) the compilation is
814 // for a target where long int and pointer both use 64-bits and int uses 32-bit.
815 // <http://www.intel.com/software/products/compilers/clin/docs/ug/lin1077.htm> says
816 // Macro Name __LP64__ Value 1
817 // A quick Google search for "defined(__LP64__)" OR "#ifdef __LP64__" gives 2590 hits and
818 // a search for "#if __LP64__" gives only 12, so I think we'll go with the majority and use defined()
819 #if defined(_ILP64) || defined(__ILP64__)
820 typedef signed int32 mDNSs32
;
821 typedef unsigned int32 mDNSu32
;
822 #elif defined(_LP64) || defined(__LP64__)
823 typedef signed int mDNSs32
;
824 typedef unsigned int mDNSu32
;
826 typedef signed long mDNSs32
;
827 typedef unsigned long mDNSu32
;
828 //typedef signed int mDNSs32;
829 //typedef unsigned int mDNSu32;
832 // To enforce useful type checking, we make mDNSInterfaceID be a pointer to a dummy struct
833 // This way, mDNSInterfaceIDs can be assigned, and compared with each other, but not with other types
834 // Declaring the type to be the typical generic "void *" would lack this type checking
835 typedef struct mDNSInterfaceID_dummystruct
{ void *dummy
; } *mDNSInterfaceID
;
837 // These types are for opaque two- and four-byte identifiers.
838 // The "NotAnInteger" fields of the unions allow the value to be conveniently passed around in a
839 // register for the sake of efficiency, and compared for equality or inequality, but don't forget --
840 // just because it is in a register doesn't mean it is an integer. Operations like greater than,
841 // less than, add, multiply, increment, decrement, etc., are undefined for opaque identifiers,
842 // and if you make the mistake of trying to do those using the NotAnInteger field, then you'll
843 // find you get code that doesn't work consistently on big-endian and little-endian machines.
844 typedef packedunion
{ mDNSu8 b
[ 2]; mDNSu16 NotAnInteger
; } mDNSOpaque16
;
845 typedef packedunion
{ mDNSu8 b
[ 4]; mDNSu32 NotAnInteger
; } mDNSOpaque32
;
846 typedef packedunion
{ mDNSu8 b
[ 6]; mDNSu16 w
[3]; mDNSu32 l
[1]; } mDNSOpaque48
;
847 typedef packedunion
{ mDNSu8 b
[ 8]; mDNSu16 w
[4]; mDNSu32 l
[2]; } mDNSOpaque64
;
848 typedef packedunion
{ mDNSu8 b
[16]; mDNSu16 w
[8]; mDNSu32 l
[4]; } mDNSOpaque128
;
850 typedef mDNSOpaque16 mDNSIPPort
; // An IP port is a two-byte opaque identifier (not an integer)
851 typedef mDNSOpaque32 mDNSv4Addr
; // An IP address is a four-byte opaque identifier (not an integer)
852 typedef mDNSOpaque128 mDNSv6Addr
; // An IPv6 address is a 16-byte opaque identifier (not an integer)
853 typedef mDNSOpaque48 mDNSEthAddr
; // An Ethernet address is a six-byte opaque identifier (not an integer)
857 mDNSAddrType_None
= 0,
858 mDNSAddrType_IPv4
= 4,
859 mDNSAddrType_IPv6
= 6,
860 mDNSAddrType_Unknown
= ~0 // Special marker value used in known answer list recording
866 union { mDNSv6Addr v6
; mDNSv4Addr v4
; } ip
;
869 enum { mDNSfalse
= 0, mDNStrue
= 1 };
878 // mDNS return values are in the range FFFE FF00 (-65792) to FFFE FFFF (-65537)
879 // The top end of the range (FFFE FFFF) is used for error codes;
880 // the bottom end of the range (FFFE FF00) is used for non-error values;
883 mStatus_UnknownErr
= -65537, // First value: 0xFFFE FFFF
884 mStatus_NoSuchNameErr
= -65538,
885 mStatus_NoMemoryErr
= -65539,
886 mStatus_BadParamErr
= -65540,
887 mStatus_BadReferenceErr
= -65541,
888 mStatus_BadStateErr
= -65542,
889 mStatus_BadFlagsErr
= -65543,
890 mStatus_UnsupportedErr
= -65544,
891 mStatus_NotInitializedErr
= -65545,
892 mStatus_NoCache
= -65546,
893 mStatus_AlreadyRegistered
= -65547,
894 mStatus_NameConflict
= -65548,
895 mStatus_Invalid
= -65549,
896 mStatus_Firewall
= -65550,
897 mStatus_Incompatible
= -65551,
898 mStatus_BadInterfaceErr
= -65552,
899 mStatus_Refused
= -65553,
900 mStatus_NoSuchRecord
= -65554,
901 mStatus_NoAuth
= -65555,
902 mStatus_NoSuchKey
= -65556,
903 mStatus_NATTraversal
= -65557,
904 mStatus_DoubleNAT
= -65558,
905 mStatus_BadTime
= -65559,
906 mStatus_BadSig
= -65560, // while we define this per RFC 2845, BIND 9 returns Refused for bad/missing signatures
907 mStatus_BadKey
= -65561,
908 mStatus_TransientErr
= -65562, // transient failures, e.g. sending packets shortly after a network transition or wake from sleep
909 mStatus_ServiceNotRunning
= -65563, // Background daemon not running
910 mStatus_NATPortMappingUnsupported
= -65564, // NAT doesn't support NAT-PMP or UPnP
911 mStatus_NATPortMappingDisabled
= -65565, // NAT supports NAT-PMP or UPnP but it's disabled by the administrator
912 mStatus_NoRouter
= -65566,
913 mStatus_PollingMode
= -65567,
914 // -65568 to -65786 currently unused; available for allocation
916 // tcp connection status
917 mStatus_ConnPending
= -65787,
918 mStatus_ConnFailed
= -65788,
919 mStatus_ConnEstablished
= -65789,
922 mStatus_GrowCache
= -65790,
923 mStatus_ConfigChanged
= -65791,
924 mStatus_MemFree
= -65792 // Last value: 0xFFFE FF00
925 // mStatus_MemFree is the last legal mDNS error code, at the end of the range allocated for mDNS
928 typedef mDNSs32 mStatus
;
930 // RFC 1034/1035 specify that a domain label consists of a length byte plus up to 63 characters
931 #define MAX_DOMAIN_LABEL 63
932 typedef struct { mDNSu8 c
[ 64]; } domainlabel
; // One label: length byte and up to 63 characters
934 // RFC 1034/1035 specify that a domain name, including length bytes, data bytes, and terminating zero, may be up to 255 bytes long
935 #define MAX_DOMAIN_NAME 255
936 typedef struct { mDNSu8 c
[256]; } domainname
; // Up to 255 bytes of length-prefixed domainlabels
938 typedef struct { mDNSu8 c
[256]; } UTF8str255
; // Null-terminated C string
940 // The longest legal textual form of a DNS name is 1005 bytes, including the C-string terminating NULL at the end.
942 // When a native domainname object is converted to printable textual form using ConvertDomainNameToCString(),
943 // non-printing characters are represented in the conventional DNS way, as '\ddd', where ddd is a three-digit decimal number.
944 // The longest legal domain name is 255 bytes, in the form of four labels as shown below:
945 // Length byte, 63 data bytes, length byte, 63 data bytes, length byte, 63 data bytes, length byte, 61 data bytes, zero byte.
946 // Each label is encoded textually as characters followed by a trailing dot.
947 // If every character has to be represented as a four-byte escape sequence, then this makes the maximum textual form four labels
948 // plus the C-string terminating NULL as shown below:
949 // 63*4+1 + 63*4+1 + 63*4+1 + 61*4+1 + 1 = 1005.
950 // Note that MAX_ESCAPED_DOMAIN_LABEL is not normally used: If you're only decoding a single label, escaping is usually not required.
951 // It is for domain names, where dots are used as label separators, that proper escaping is vital.
952 #define MAX_ESCAPED_DOMAIN_LABEL 254
953 #define MAX_ESCAPED_DOMAIN_NAME 1005
955 // MAX_REVERSE_MAPPING_NAME
956 // For IPv4: "123.123.123.123.in-addr.arpa." 30 bytes including terminating NUL
957 // 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
959 #define MAX_REVERSE_MAPPING_NAME_V4 30
960 #define MAX_REVERSE_MAPPING_NAME_V6 74
961 #define MAX_REVERSE_MAPPING_NAME 74
963 // Most records have a TTL of 75 minutes, so that their 80% cache-renewal query occurs once per hour.
964 // For records containing a hostname (in the name on the left, or in the rdata on the right),
965 // like A, AAAA, reverse-mapping PTR, and SRV, we use a two-minute TTL by default, because we don't want
966 // them to hang around for too long in the cache if the host in question crashes or otherwise goes away.
968 #define kStandardTTL (3600UL * 100 / 80)
969 #define kHostNameTTL 120UL
971 #define DefaultTTLforRRType(X) (((X) == kDNSType_A || (X) == kDNSType_AAAA || (X) == kDNSType_SRV) ? kHostNameTTL : kStandardTTL)
973 typedef struct AuthRecord_struct AuthRecord
;
974 typedef struct ServiceRecordSet_struct ServiceRecordSet
;
975 typedef struct CacheRecord_struct CacheRecord
;
976 typedef struct CacheGroup_struct CacheGroup
;
977 typedef struct DNSQuestion_struct DNSQuestion
;
978 typedef struct ZoneData_struct ZoneData
;
979 typedef struct mDNS_struct mDNS
;
980 typedef struct mDNS_PlatformSupport_struct mDNS_PlatformSupport
;
981 typedef struct NATTraversalInfo_struct NATTraversalInfo
;
983 // Structure to abstract away the differences between TCP/SSL sockets, and one for UDP sockets
984 // The actual definition of these structures in the in the appropriate platform support code
985 typedef struct TCPSocket_struct TCPSocket
;
986 typedef struct UDPSocket_struct UDPSocket
;
988 // ***************************************************************************
990 #pragma mark - DNS Message structures
993 #define mDNS_numZones numQuestions
994 #define mDNS_numPrereqs numAnswers
995 #define mDNS_numUpdates numAuthorities
1001 mDNSu16 numQuestions
;
1003 mDNSu16 numAuthorities
;
1004 mDNSu16 numAdditionals
;
1007 // We can send and receive packets up to 9000 bytes (Ethernet Jumbo Frame size, if that ever becomes widely used)
1008 // However, in the normal case we try to limit packets to 1500 bytes so that we don't get IP fragmentation on standard Ethernet
1009 // 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
1010 #define AbsoluteMaxDNSMessageData 8940
1011 #define NormalMaxDNSMessageData 1440
1012 typedef packedstruct
1014 DNSMessageHeader h
; // Note: Size 12 bytes
1015 mDNSu8 data
[AbsoluteMaxDNSMessageData
]; // 40 (IPv6) + 8 (UDP) + 12 (DNS header) + 8940 (data) = 9000
1018 typedef struct tcpInfo_t
1024 DNSQuestion
*question
; // For queries
1025 ServiceRecordSet
*srs
; // For service record updates
1026 AuthRecord
*rr
; // For record updates
1031 unsigned long nread
;
1035 // ***************************************************************************
1037 #pragma mark - Resource Record structures
1040 // Authoritative Resource Records:
1041 // There are four basic types: Shared, Advisory, Unique, Known Unique
1043 // * Shared Resource Records do not have to be unique
1044 // -- Shared Resource Records are used for DNS-SD service PTRs
1045 // -- It is okay for several hosts to have RRs with the same name but different RDATA
1046 // -- We use a random delay on responses to reduce collisions when all the hosts respond to the same query
1047 // -- These RRs typically have moderately high TTLs (e.g. one hour)
1048 // -- These records are announced on startup and topology changes for the benefit of passive listeners
1049 // -- These records send a goodbye packet when deregistering
1051 // * Advisory Resource Records are like Shared Resource Records, except they don't send a goodbye packet
1053 // * Unique Resource Records should be unique among hosts within any given mDNS scope
1054 // -- The majority of Resource Records are of this type
1055 // -- If two entities on the network have RRs with the same name but different RDATA, this is a conflict
1056 // -- Responses may be sent immediately, because only one host should be responding to any particular query
1057 // -- These RRs typically have low TTLs (e.g. a few minutes)
1058 // -- On startup and after topology changes, a host issues queries to verify uniqueness
1060 // * Known Unique Resource Records are treated like Unique Resource Records, except that mDNS does
1061 // not have to verify their uniqueness because this is already known by other means (e.g. the RR name
1062 // is derived from the host's IP or Ethernet address, which is already known to be a unique identifier).
1064 // Summary of properties of different record types:
1065 // Probe? Does this record type send probes before announcing?
1066 // Conflict? Does this record type react if we observe an apparent conflict?
1067 // Goodbye? Does this record type send a goodbye packet on departure?
1069 // Probe? Conflict? Goodbye? Notes
1070 // Unregistered Should not appear in any list (sanity check value)
1071 // Shared No No Yes e.g. Service PTR record
1072 // Deregistering No No Yes Shared record about to announce its departure and leave the list
1073 // Advisory No No No
1074 // Unique Yes Yes No Record intended to be unique -- will probe to verify
1075 // Verified Yes Yes No Record has completed probing, and is verified unique
1076 // KnownUnique No Yes No Record is assumed by other means to be unique
1078 // Valid lifecycle of a record:
1079 // Unregistered -> Shared -> Deregistering -(goodbye)-> Unregistered
1080 // Unregistered -> Advisory -> Unregistered
1081 // Unregistered -> Unique -(probe)-> Verified -> Unregistered
1082 // Unregistered -> KnownUnique -> Unregistered
1084 // Each Authoritative kDNSRecordType has only one bit set. This makes it easy to quickly see if a record
1085 // is one of a particular set of types simply by performing the appropriate bitwise masking operation.
1087 // Cache Resource Records (received from the network):
1088 // There are four basic types: Answer, Unique Answer, Additional, Unique Additional
1089 // Bit 7 (the top bit) of kDNSRecordType is always set for Cache Resource Records; always clear for Authoritative Resource Records
1090 // Bit 6 (value 0x40) is set for answer records; clear for authority/additional records
1091 // Bit 5 (value 0x20) is set for records received with the kDNSClass_UniqueRRSet
1095 kDNSRecordTypeUnregistered
= 0x00, // Not currently in any list
1096 kDNSRecordTypeDeregistering
= 0x01, // Shared record about to announce its departure and leave the list
1098 kDNSRecordTypeUnique
= 0x02, // Will become a kDNSRecordTypeVerified when probing is complete
1100 kDNSRecordTypeAdvisory
= 0x04, // Like Shared, but no goodbye packet
1101 kDNSRecordTypeShared
= 0x08, // Shared means record name does not have to be unique -- use random delay on responses
1103 kDNSRecordTypeVerified
= 0x10, // Unique means mDNS should check that name is unique (and then send immediate responses)
1104 kDNSRecordTypeKnownUnique
= 0x20, // Known Unique means mDNS can assume name is unique without checking
1105 // For Dynamic Update records, Known Unique means the record must already exist on the server.
1106 kDNSRecordTypeUniqueMask
= (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
),
1107 kDNSRecordTypeActiveMask
= (kDNSRecordTypeAdvisory
| kDNSRecordTypeShared
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
),
1109 kDNSRecordTypePacketAdd
= 0x80, // Received in the Additional Section of a DNS Response
1110 kDNSRecordTypePacketAddUnique
= 0x90, // Received in the Additional Section of a DNS Response with kDNSClass_UniqueRRSet set
1111 kDNSRecordTypePacketAuth
= 0xA0, // Received in the Authorities Section of a DNS Response
1112 kDNSRecordTypePacketAuthUnique
= 0xB0, // Received in the Authorities Section of a DNS Response with kDNSClass_UniqueRRSet set
1113 kDNSRecordTypePacketAns
= 0xC0, // Received in the Answer Section of a DNS Response
1114 kDNSRecordTypePacketAnsUnique
= 0xD0, // Received in the Answer Section of a DNS Response with kDNSClass_UniqueRRSet set
1116 kDNSRecordTypePacketNegative
= 0xF0, // Pseudo-RR generated to cache non-existence results like NXDomain
1118 kDNSRecordTypePacketUniqueMask
= 0x10 // True for PacketAddUnique, PacketAnsUnique, PacketAuthUnique
1121 typedef packedstruct
{ mDNSu16 priority
; mDNSu16 weight
; mDNSIPPort port
; domainname target
; } rdataSRV
;
1122 typedef packedstruct
{ mDNSu16 preference
; domainname exchange
; } rdataMX
;
1123 typedef packedstruct
{ domainname mbox
; domainname txt
; } rdataRP
;
1124 typedef packedstruct
{ mDNSu16 preference
; domainname map822
; domainname mapx400
; } rdataPX
;
1126 typedef packedstruct
1130 mDNSs32 serial
; // Modular counter; increases when zone changes
1131 mDNSu32 refresh
; // Time in seconds that a slave waits after successful replication of the database before it attempts replication again
1132 mDNSu32 retry
; // Time in seconds that a slave waits after an unsuccessful replication attempt before it attempts replication again
1133 mDNSu32 expire
; // Time in seconds that a slave holds on to old data while replication attempts remain unsuccessful
1134 mDNSu32 min
; // Nominally the minimum record TTL for this zone, in seconds; also used for negative caching.
1137 typedef packedstruct
1141 mDNSu16 err
; // Or UDP reply port, in setup request
1146 // Windows adds pad bytes to sizeof(LLQOptData).
1147 // Use this macro when setting length fields or validating option rdata from off the wire.
1148 // Use sizeof(LLQOptData) when dealing with structures (e.g. memcpy).
1149 // Never memcpy between on-the-wire representation and a structure.
1151 #define LLQ_OPTLEN ((3 * sizeof(mDNSu16)) + 8 + sizeof(mDNSu32))
1153 // NOTE: rdataOPT format may be repeated an arbitrary number of times in a single resource record
1154 typedef packedstruct
1158 union { LLQOptData llq
; mDNSu32 updatelease
; } OptData
;
1161 // StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record (6 + 256 bytes)
1162 // MaximumRDSize is 8K the absolute maximum we support (at least for now)
1163 #define StandardAuthRDSize 264
1164 #define MaximumRDSize 8192
1166 // InlineCacheRDSize is 68
1167 // Records received from the network with rdata this size or less have their rdata stored right in the CacheRecord object
1168 // Records received from the network with rdata larger than this have additional storage allocated for the rdata
1169 // A quick unscientific sample from a busy network at Apple with lots of machines revealed this:
1170 // 1461 records in cache
1171 // 292 were one-byte TXT records
1172 // 136 were four-byte A records
1173 // 184 were sixteen-byte AAAA records
1174 // 780 were various PTR, TXT and SRV records from 12-64 bytes
1175 // Only 69 records had rdata bigger than 64 bytes
1176 // Note that since CacheRecord object and a CacheGroup object are allocated out of the same pool, it's sensible to
1177 // have them both be the same size. Making one smaller without making the other smaller won't actually save any memory.
1178 #define InlineCacheRDSize 68
1180 #define InlineCacheGroupNameSize 144
1184 mDNSu8 data
[StandardAuthRDSize
];
1185 mDNSv4Addr ipv4
; // For 'A' record
1186 domainname name
; // For PTR, NS, CNAME, DNAME
1192 mDNSv6Addr ipv6
; // For 'AAAA' record
1194 rdataOPT opt
; // For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
1199 mDNSu16 MaxRDLength
; // Amount of storage allocated for rdata (usually sizeof(RDataBody))
1202 #define sizeofRDataHeader (sizeof(RData) - sizeof(RDataBody))
1204 // Note: Within an mDNSRecordCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
1205 typedef void mDNSRecordCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
1208 // Restrictions: An mDNSRecordUpdateCallback may not make any mDNS API calls.
1209 // The intent of this callback is to allow the client to free memory, if necessary.
1210 // The internal data structures of the mDNS code may not be in a state where mDNS API calls may be made safely.
1211 typedef void mDNSRecordUpdateCallback(mDNS
*const m
, AuthRecord
*const rr
, RData
*OldRData
);
1213 // ***************************************************************************
1215 #pragma mark - NAT Traversal structures and constants
1218 #define NATMAP_MAX_RETRY_INTERVAL ((mDNSPlatformOneSecond * 60) * 15) // Max retry interval is 15 minutes
1219 #define NATMAP_MIN_RETRY_INTERVAL (mDNSPlatformOneSecond * 2) // Min retry interval is 2 seconds
1220 #define NATMAP_INIT_RETRY (mDNSPlatformOneSecond / 4) // start at 250ms w/ exponential decay
1221 #define NATMAP_DEFAULT_LEASE (60 * 60) // lease life in seconds
1222 #define NATMAP_VERS 0
1226 NATOp_AddrRequest
= 0,
1230 NATOp_AddrResponse
= 0x80 | 0,
1231 NATOp_MapUDPResponse
= 0x80 | 1,
1232 NATOp_MapTCPResponse
= 0x80 | 2,
1245 typedef mDNSu16 NATErr_t
;
1247 typedef packedstruct
1253 typedef packedstruct
1258 mDNSu32 upseconds
; // Time since last NAT engine reboot, in seconds
1262 typedef packedstruct
1266 mDNSOpaque16 unused
;
1269 mDNSu32 NATReq_lease
;
1270 } NATPortMapRequest
;
1272 typedef packedstruct
1277 mDNSu32 upseconds
; // Time since last NAT engine reboot, in seconds
1280 mDNSu32 NATRep_lease
;
1286 LNTExternalAddrOp
= 2,
1288 LNTPortMapDeleteOp
= 4
1291 #define LNT_MAXBUFSIZE 8192
1292 typedef struct tcpLNTInfo_struct tcpLNTInfo
;
1293 struct tcpLNTInfo_struct
1297 NATTraversalInfo
*parentNATInfo
; // pointer back to the parent NATTraversalInfo
1299 LNTOp_t op
; // operation performed using this connection
1300 mDNSAddr Address
; // router address
1301 mDNSIPPort Port
; // router port
1302 mDNSs8
*Request
; // xml request to router
1304 mDNSs8
*Reply
; // xml reply from router
1306 unsigned long nread
; // number of bytes read so far
1307 int retries
; // number of times we've tried to do this port mapping
1310 typedef void (*NATTraversalClientCallback
)(mDNS
*m
, NATTraversalInfo
*n
);
1312 // if m->timenow < ExpiryTime then we have an active mapping, and we'll renew halfway to expiry
1313 // if m->timenow >= ExpiryTime then our mapping has expired, and we're trying to create one
1315 struct NATTraversalInfo_struct
1317 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1318 NATTraversalInfo
*next
;
1320 mDNSs32 ExpiryTime
; // Time this mapping expires, or zero if no mapping
1321 mDNSs32 retryInterval
; // Current interval, between last packet we sent and the next one
1322 mDNSs32 retryPortMap
; // If Protocol is nonzero, time to send our next mapping packet
1323 mStatus NewResult
; // New error code; will be copied to Result just prior to invoking callback
1325 #ifdef _LEGACY_NAT_TRAVERSAL_
1326 tcpLNTInfo tcpInfo
; // Legacy NAT traversal (UPnP) TCP connection
1329 // Result fields: When the callback is invoked these fields contain the answers the client is looking for
1330 // When the callback is invoked ExternalPort is *usually* set to be the same the same as RequestedPort, except:
1331 // (a) When we're behind a NAT gateway with port mapping disabled, ExternalPort is reported as zero to
1332 // indicate that we don't currently have a working mapping (but RequestedPort retains the external port
1333 // we'd like to get, the next time we meet an accomodating NAT gateway willing to give us one).
1334 // (b) When we have a routable non-RFC1918 address, we don't *need* a port mapping, so ExternalPort
1335 // is reported as the same as our InternalPort, since that is effectively our externally-visible port too.
1336 // Again, RequestedPort retains the external port we'd like to get the next time we find ourself behind a NAT gateway.
1337 // To improve stability of port mappings, RequestedPort is updated any time we get a successful
1338 // mapping response from the NAT-PMP or UPnP gateway. For example, if we ask for port 80, and
1339 // get assigned port 81, then thereafter we'll contine asking for port 81.
1340 mDNSInterfaceID InterfaceID
;
1341 mDNSv4Addr ExternalAddress
; // Initially set to onesIPv4Addr, until first callback
1342 mDNSIPPort ExternalPort
;
1346 // Client API fields: The client must set up these fields *before* making any NAT traversal API calls
1347 mDNSu8 Protocol
; // NATOp_MapUDP or NATOp_MapTCP, or zero if just requesting the external IP address
1348 mDNSIPPort IntPort
; // Client's internal port number (doesn't change)
1349 mDNSIPPort RequestedPort
; // Requested public port mapping; may be updated with actual value assigned by gateway
1350 mDNSu32 NATLease
; // Requested lifetime in seconds (doesn't change)
1351 NATTraversalClientCallback clientCallback
;
1352 void *clientContext
;
1357 mDNSu8 RecordType
; // See enum above
1358 mDNSInterfaceID InterfaceID
; // Set if this RR is specific to one interface
1359 // For records received off the wire, InterfaceID is *always* set to the receiving interface
1360 // For our authoritative records, InterfaceID is usually zero, except for those few records
1361 // that are interface-specific (e.g. address records, especially linklocal addresses)
1362 const domainname
*name
;
1365 mDNSu32 rroriginalttl
; // In seconds
1366 mDNSu16 rdlength
; // Size of the raw rdata, in bytes, in the on-the-wire format
1367 // (in-memory storage may be larger, for structures containing 'holes', like SOA)
1368 mDNSu16 rdestimate
; // Upper bound on size of rdata after name compression
1369 mDNSu32 namehash
; // Name-based (i.e. case-insensitive) hash of name
1370 mDNSu32 rdatahash
; // For rdata containing domain name (e.g. PTR, SRV, CNAME etc.), case-insensitive name hash
1371 // else, for all other rdata, 32-bit hash of the raw rdata
1372 // Note: This requirement is important. Various routines like AddAdditionalsToResponseList(),
1373 // ReconfirmAntecedents(), etc., use rdatahash as a pre-flight check to see
1374 // whether it's worth doing a full SameDomainName() call. If the rdatahash
1375 // is not a correct case-insensitive name hash, they'll get false negatives.
1376 RData
*rdata
; // Pointer to storage for this rdata
1379 // Unless otherwise noted, states may apply to either independent record registrations or service registrations
1383 regState_FetchingZoneData
= 1, // getting info - update not sent
1384 regState_Pending
= 2, // update sent, reply not received
1385 regState_Registered
= 3, // update sent, reply received
1386 regState_DeregPending
= 4, // dereg sent, reply not received
1387 regState_DeregDeferred
= 5, // dereg requested while in Pending state - send dereg AFTER registration is confirmed
1388 regState_Unregistered
= 8, // not in any list
1389 regState_Refresh
= 9, // outstanding refresh (or target change) message
1390 regState_NATMap
= 10, // establishing NAT port mapping (service registrations only)
1391 regState_UpdatePending
= 11, // update in flight as result of mDNS_Update call
1392 regState_NoTarget
= 12, // service registration pending registration of hostname (ServiceRegistrations only)
1393 regState_ExtraQueued
= 13, // extra record to be registered upon completion of service registration (RecordRegistrations only)
1394 regState_NATError
= 14 // unable to complete NAT traversal
1400 Target_AutoHost
= 1,
1401 Target_AutoHostAndNATMAP
= 2
1404 struct AuthRecord_struct
1406 // For examples of how to set up this structure for use in mDNS_Register(),
1407 // see mDNS_AdvertiseInterface() or mDNS_RegisterService().
1408 // Basically, resrec and persistent metadata need to be set up before calling mDNS_Register().
1409 // mDNS_SetupResourceRecord() is avaliable as a helper routine to set up most fields to sensible default values for you
1411 AuthRecord
*next
; // Next in list; first element of structure for efficiency reasons
1412 // Field Group 1: Common ResourceRecord fields
1413 ResourceRecord resrec
;
1415 // Field Group 2: Persistent metadata for Authoritative Records
1416 AuthRecord
*Additional1
; // Recommended additional record to include in response (e.g. SRV for PTR record)
1417 AuthRecord
*Additional2
; // Another additional (e.g. TXT for record)
1418 AuthRecord
*DependentOn
; // This record depends on another for its uniqueness checking
1419 AuthRecord
*RRSet
; // This unique record is part of an RRSet
1420 mDNSRecordCallback
*RecordCallback
; // Callback function to call for state changes, and to free memory asynchronously on deregistration
1421 void *RecordContext
; // Context parameter for the callback function
1422 mDNSu8 AutoTarget
; // Set if the target of this record (PTR, CNAME, SRV, etc.) is our host name
1423 mDNSu8 AllowRemoteQuery
; // Set if we allow hosts not on the local link to query this record
1424 mDNSu8 ForceMCast
; // Set by client to advertise solely via multicast, even for apparently unicast names
1426 // Field Group 3: Transient state for Authoritative Records
1427 mDNSu8 Acknowledged
; // Set if we've given the success callback to the client
1428 mDNSu8 ProbeCount
; // Number of probes remaining before this record is valid (kDNSRecordTypeUnique)
1429 mDNSu8 AnnounceCount
; // Number of announcements remaining (kDNSRecordTypeShared)
1430 mDNSu8 RequireGoodbye
; // Set if this RR has been announced on the wire and will require a goodbye packet
1431 mDNSu8 AnsweredLocalQ
; // Set if this RR has been delivered to LocalOnly questions
1432 mDNSu8 IncludeInProbe
; // Set if this RR is being put into a probe right now
1433 mDNSInterfaceID ImmedAnswer
; // Someone on this interface issued a query we need to answer (all-ones for all interfaces)
1434 mDNSu8 ImmedUnicast
; // Set if we may send our response directly via unicast to the requester
1435 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
1436 mDNSs32 ImmedAnswerMarkTime
;
1438 mDNSInterfaceID ImmedAdditional
; // Hint that we might want to also send this record, just to be helpful
1439 mDNSInterfaceID SendRNow
; // The interface this query is being sent on right now
1440 mDNSv4Addr v4Requester
; // Recent v4 query for this record, or all-ones if more than one recent query
1441 mDNSv6Addr v6Requester
; // Recent v6 query for this record, or all-ones if more than one recent query
1442 AuthRecord
*NextResponse
; // Link to the next element in the chain of responses to generate
1443 const mDNSu8
*NR_AnswerTo
; // Set if this record was selected by virtue of being a direct answer to a question
1444 AuthRecord
*NR_AdditionalTo
; // Set if this record was selected by virtue of being additional to another
1445 mDNSs32 ThisAPInterval
; // In platform time units: Current interval for announce/probe
1446 mDNSs32 LastAPTime
; // In platform time units: Last time we sent announcement/probe
1447 mDNSs32 LastMCTime
; // Last time we multicast this record (used to guard against packet-storm attacks)
1448 mDNSInterfaceID LastMCInterface
; // Interface this record was multicast on at the time LastMCTime was recorded
1449 RData
*NewRData
; // Set if we are updating this record with new rdata
1450 mDNSu16 newrdlength
; // ... and the length of the new RData
1451 mDNSRecordUpdateCallback
*UpdateCallback
;
1452 mDNSu32 UpdateCredits
; // Token-bucket rate limiting of excessive updates
1453 mDNSs32 NextUpdateCredit
; // Time next token is added to bucket
1454 mDNSs32 UpdateBlocked
; // Set if update delaying is in effect
1456 // Field Group 4: Transient uDNS state for Authoritative Records
1457 regState_t state
; // Maybe combine this with resrec.RecordType state? Right now it's ambiguous and confusing.
1458 // e.g. rr->resrec.RecordType can be kDNSRecordTypeUnregistered,
1459 // and rr->state can be regState_Unregistered
1460 // What if we find one of those statements is true and the other false? What does that mean?
1461 mDNSBool uselease
; // dynamic update contains (should contain) lease option
1462 mDNSs32 expire
; // expiration of lease (-1 for static)
1463 mDNSBool Private
; // If zone is private, DNS updates may have to be encrypted to prevent eavesdropping
1464 mDNSOpaque16 id
; // identifier to match update request and response
1465 domainname zone
; // the zone that is updated
1466 mDNSAddr UpdateServer
; // DNS server that handles updates for this zone
1467 mDNSIPPort UpdatePort
; // port on which server accepts dynamic updates
1468 // !!!KRS not technically correct to cache longer than TTL
1469 // SDC Perhaps should keep a reference to the relevant SRV record in the cache?
1471 struct tcpInfo_t
*tcp
;
1473 // uDNS_UpdateRecord support fields
1474 // Do we really need all these in *addition* to NewRData and newrdlength above?
1476 mDNSu16 OrigRDLen
; // previously registered, being deleted
1477 RData
*InFlightRData
;
1478 mDNSu16 InFlightRDLen
; // currently being registered
1479 RData
*QueuedRData
; // if the client call Update while an update is in flight, we must finish the
1480 mDNSu16 QueuedRDLen
; // pending operation (re-transmitting if necessary) THEN register the queued update
1482 // Field Group 5: Large data objects go at the end
1483 domainname namestorage
;
1484 RData rdatastorage
; // Normally the storage is right here, except for oversized records
1485 // rdatastorage MUST be the last thing in the structure -- when using oversized AuthRecords, extra bytes
1486 // are appended after the end of the AuthRecord, logically augmenting the size of the rdatastorage
1487 // DO NOT ADD ANY MORE FIELDS HERE
1490 #define AuthRecord_uDNS(R) ((R)->resrec.InterfaceID == mDNSInterface_Any && !(R)->ForceMCast && !IsLocalDomain((R)->resrec.name))
1491 #define Question_uDNS(Q) ((Q)->InterfaceID == mDNSInterface_Any && !(Q)->ForceMCast && !IsLocalDomain(&(Q)->qname))
1493 // Wrapper struct for Auth Records for higher-level code that cannot use the AuthRecord's ->next pointer field
1494 typedef struct ARListElem
1496 struct ARListElem
*next
;
1497 AuthRecord ar
; // Note: Must be last element of structure, to accomodate oversized AuthRecords
1500 struct CacheGroup_struct
// Header object for a list of CacheRecords with the same name
1502 CacheGroup
*next
; // Next CacheGroup object in this hash table bucket
1503 mDNSu32 namehash
; // Name-based (i.e. case insensitive) hash of name
1504 CacheRecord
*members
; // List of CacheRecords with this same name
1505 CacheRecord
**rrcache_tail
; // Tail end of that list
1506 domainname
*name
; // Common name for all CacheRecords in this list
1507 mDNSu8 namestorage
[InlineCacheGroupNameSize
];
1510 struct CacheRecord_struct
1512 CacheRecord
*next
; // Next in list; first element of structure for efficiency reasons
1513 ResourceRecord resrec
;
1515 // Transient state for Cache Records
1516 CacheRecord
*NextInKAList
; // Link to the next element in the chain of known answers to send
1517 mDNSs32 TimeRcvd
; // In platform time units
1518 mDNSs32 DelayDelivery
; // Set if we want to defer delivery of this answer to local clients
1519 mDNSs32 NextRequiredQuery
; // In platform time units
1520 mDNSs32 LastUsed
; // In platform time units
1521 DNSQuestion
*CRActiveQuestion
; // Points to an active question referencing this answer
1522 mDNSu32 UnansweredQueries
; // Number of times we've issued a query for this record without getting an answer
1523 mDNSs32 LastUnansweredTime
; // In platform time units; last time we incremented UnansweredQueries
1524 mDNSu32 MPUnansweredQ
; // Multi-packet query handling: Number of times we've seen a query for this record
1525 mDNSs32 MPLastUnansweredQT
; // Multi-packet query handling: Last time we incremented MPUnansweredQ
1526 mDNSu32 MPUnansweredKA
; // Multi-packet query handling: Number of times we've seen this record in a KA list
1527 mDNSBool MPExpectingKA
; // Multi-packet query handling: Set when we increment MPUnansweredQ; allows one KA
1528 CacheRecord
*NextInCFList
; // Set if this is in the list of records we just received with the cache flush bit set
1530 struct { mDNSu16 MaxRDLength
; mDNSu8 data
[InlineCacheRDSize
]; } rdatastorage
; // Storage for small records is right here
1533 // Storage sufficient to hold either a CacheGroup header or a CacheRecord
1534 typedef union CacheEntity_union CacheEntity
;
1535 union CacheEntity_union
{ CacheEntity
*next
; CacheGroup cg
; CacheRecord cr
; };
1540 mDNSu8 _extradata
[MaximumRDSize
-InlineCacheRDSize
]; // Glue on the necessary number of extra bytes
1541 domainname namestorage
; // Needs to go *after* the extra rdata bytes
1544 typedef struct HostnameInfo
1546 struct HostnameInfo
*next
;
1547 NATTraversalInfo natinfo
;
1549 AuthRecord arv4
; // registered IPv4 address record
1550 AuthRecord arv6
; // registered IPv6 address record
1551 mDNSRecordCallback
*StatusCallback
; // callback to deliver success or error code to client layer
1552 const void *StatusContext
; // Client Context
1557 DNSServer_Untested
= 0,
1558 DNSServer_Passed
= 1,
1559 DNSServer_Failed
= 2,
1560 DNSServer_Disabled
= 3
1565 DNSServer_FlagDelete
= 1,
1566 DNSServer_FlagNew
= 2
1569 typedef struct DNSServer
1571 struct DNSServer
*next
;
1572 mDNSInterfaceID interface
; // For specialized uses; we can have DNS servers reachable over specific interfaces
1575 mDNSu32 flags
; // Set when we're planning to delete this from the list
1576 mDNSu32 teststate
; // Have we sent bug-detection query to this server?
1577 mDNSs32 lasttest
; // Time we sent last bug-detection query to this server
1578 domainname domain
; // name->server matching for "split dns"
1581 typedef struct NetworkInterfaceInfo_struct NetworkInterfaceInfo
;
1583 // A NetworkInterfaceInfo_struct serves two purposes:
1584 // 1. It holds the address, PTR and HINFO records to advertise a given IP address on a given physical interface
1585 // 2. It tells mDNSCore which physical interfaces are available; each physical interface has its own unique InterfaceID.
1586 // Since there may be multiple IP addresses on a single physical interface,
1587 // there may be multiple NetworkInterfaceInfo_structs with the same InterfaceID.
1588 // In this case, to avoid sending the same packet n times, when there's more than one
1589 // struct with the same InterfaceID, mDNSCore picks one member of the set to be the
1590 // active representative of the set; all others have the 'InterfaceActive' flag unset.
1592 struct NetworkInterfaceInfo_struct
1594 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1595 NetworkInterfaceInfo
*next
;
1597 mDNSBool InterfaceActive
; // Set if interface is sending & receiving packets (see comment above)
1598 mDNSBool IPv4Available
; // If InterfaceActive, set if v4 available on this InterfaceID
1599 mDNSBool IPv6Available
; // If InterfaceActive, set if v6 available on this InterfaceID
1601 // Standard AuthRecords that every Responder host should have (one per active IP address)
1602 AuthRecord RR_A
; // 'A' or 'AAAA' (address) record for our ".local" name
1603 AuthRecord RR_PTR
; // PTR (reverse lookup) record
1604 AuthRecord RR_HINFO
;
1606 // Client API fields: The client must set up these fields *before* calling mDNS_RegisterInterface()
1607 mDNSInterfaceID InterfaceID
; // Identifies physical interface; MUST NOT be 0, -1, or -2
1608 mDNSAddr ip
; // The IPv4 or IPv6 address to advertise
1610 char ifname
[64]; // Windows uses a GUID string for the interface name, which doesn't fit in 16 bytes
1611 mDNSBool Advertise
; // False if you are only searching on this interface
1612 mDNSBool McastTxRx
; // Send/Receive multicast on this { InterfaceID, address family } ?
1615 typedef struct ExtraResourceRecord_struct ExtraResourceRecord
;
1616 struct ExtraResourceRecord_struct
1618 ExtraResourceRecord
*next
;
1619 mDNSu32 ClientID
; // Opaque ID field to be used by client to map an AddRecord call to a set of Extra records
1621 // Note: Add any additional fields *before* the AuthRecord in this structure, not at the end.
1622 // In some cases clients can allocate larger chunks of memory and set r->rdata->MaxRDLength to indicate
1623 // that this extra memory is available, which would result in any fields after the AuthRecord getting smashed
1626 // Note: Within an mDNSServiceCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
1627 typedef void mDNSServiceCallback(mDNS
*const m
, ServiceRecordSet
*const sr
, mStatus result
);
1629 // A ServiceRecordSet is basically a convenience structure to group together
1630 // the PTR/SRV/TXT records that make up a standard service registration
1631 // It contains its own ServiceCallback+ServiceContext to report aggregate results up to the next layer of software above
1632 // It also contains:
1633 // * the "_services" PTR record for service enumeration
1634 // * the optional target host name (for proxy registrations)
1635 // * the optional list of SubType PTR records
1636 // * the optional list of additional records attached to the service set (e.g. iChat pictures)
1638 // ... and a bunch of stuff related to uDNS, some of which could be simplified or eliminated
1640 struct ServiceRecordSet_struct
1642 // These internal state fields are used internally by mDNSCore; the client layer needn't be concerned with them.
1643 // No fields need to be set up by the client prior to calling mDNS_RegisterService();
1644 // all required data is passed as parameters to that function.
1646 // Begin uDNS info ****************
1647 // Hopefully much of this stuff can be simplified or eliminated
1649 // NOTE: The current uDNS code keeps an explicit list of registered services, and handles them
1650 // differently to how individual records are treated (this is probably a mistake). What this means is
1651 // that ServiceRecordSets for uDNS are kept in a linked list, whereas ServiceRecordSets for mDNS exist
1652 // just as a convenient placeholder to group the component records together and are not kept on any list.
1653 ServiceRecordSet
*uDNS_next
;
1655 mDNSBool srs_uselease
; // dynamic update contains (should contain) lease option
1656 mDNSBool TestForSelfConflict
; // on name conflict, check if we're just seeing our own orphaned records
1657 mDNSBool Private
; // If zone is private, DNS updates may have to be encrypted to prevent eavesdropping
1660 domainname zone
; // the zone that is updated
1661 mDNSAddr SRSUpdateServer
; // primary name server for the record's zone !!!KRS not technically correct to cache longer than TTL
1662 mDNSIPPort SRSUpdatePort
; // port on which server accepts dynamic updates
1663 NATTraversalInfo NATinfo
;
1664 mDNSBool ClientCallbackDeferred
; // invoke client callback on completion of pending operation(s)
1665 mStatus DeferredStatus
; // status to deliver when above flag is set
1666 mDNSBool SRVUpdateDeferred
; // do we need to change target or port once current operation completes?
1667 mDNSBool SRVChanged
; // temporarily deregistered service because its SRV target or port changed
1668 struct tcpInfo_t
*tcp
;
1670 // End uDNS info ****************
1672 mDNSServiceCallback
*ServiceCallback
;
1673 void *ServiceContext
;
1674 mDNSBool Conflict
; // Set if this record set was forcibly deregistered because of a conflict
1676 ExtraResourceRecord
*Extras
; // Optional list of extra AuthRecords attached to this service registration
1677 mDNSu32 NumSubTypes
;
1678 AuthRecord
*SubTypes
;
1679 AuthRecord RR_ADV
; // e.g. _services._dns-sd._udp.local. PTR _printer._tcp.local.
1680 AuthRecord RR_PTR
; // e.g. _printer._tcp.local. PTR Name._printer._tcp.local.
1681 AuthRecord RR_SRV
; // e.g. Name._printer._tcp.local. SRV 0 0 port target
1682 AuthRecord RR_TXT
; // e.g. Name._printer._tcp.local. TXT PrintQueueName
1683 // Don't add any fields after AuthRecord RR_TXT.
1684 // This is where the implicit extra space goes if we allocate a ServiceRecordSet containing an oversized RR_TXT record
1687 // ***************************************************************************
1689 #pragma mark - Question structures
1692 // We record the last eight instances of each duplicate query
1693 // This gives us v4/v6 on each of Ethernet/AirPort and Firewire, and two free slots "for future expansion"
1694 // If the host has more active interfaces that this it is not fatal -- duplicate question suppression will degrade gracefully.
1695 // Since we will still remember the last eight, the busiest interfaces will still get the effective duplicate question suppression.
1696 #define DupSuppressInfoSize 8
1701 mDNSInterfaceID InterfaceID
;
1702 mDNSs32 Type
; // v4 or v6?
1707 LLQ_InitialRequest
= 1,
1708 LLQ_SecondaryRequest
= 2,
1709 LLQ_Established
= 3,
1714 #define kDNSOpt_LLQ 1
1715 #define kDNSOpt_Lease 2
1717 #define kLLQ_DefLease 7200 // 2 hours
1718 #define kLLQ_MAX_TRIES 3 // retry an operation 3 times max
1719 #define kLLQ_INIT_RESEND 2 // resend an un-ack'd packet after 2 seconds, then double for each additional
1720 // LLQ Operation Codes
1721 #define kLLQOp_Setup 1
1722 #define kLLQOp_Refresh 2
1723 #define kLLQOp_Event 3
1725 #define LLQ_OPT_RDLEN ((2 * sizeof(mDNSu16)) + LLQ_OPTLEN )
1726 #define LEASE_OPT_RDLEN ((2 * sizeof(mDNSu16)) + sizeof(mDNSs32))
1732 LLQErr_ServFull
= 1,
1735 LLQErr_NoSuchLLQ
= 4,
1737 LLQErr_UnknownErr
= 6
1740 enum { NoAnswer_Normal
= 0, NoAnswer_Suspended
= 1, NoAnswer_Fail
= 2 };
1743 #define HMAC_IPAD 0x36
1744 #define HMAC_OPAD 0x5c
1747 #define AutoTunnelUnregistered(X) ( \
1748 (X)->AutoTunnelHostRecord.resrec.RecordType == kDNSRecordTypeUnregistered && \
1749 (X)->AutoTunnelDeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered && \
1750 (X)->AutoTunnelService. resrec.RecordType == kDNSRecordTypeUnregistered )
1752 // Internal data structure to maintain authentication information
1753 typedef struct DomainAuthInfo
1755 struct DomainAuthInfo
*next
;
1756 mDNSs32 deltime
; // If we're planning to delete this DomainAuthInfo, the time we want it deleted
1757 mDNSBool AutoTunnel
;
1758 AuthRecord AutoTunnelHostRecord
; // User-visible hostname; used as SRV target for AutoTunnel services
1759 AuthRecord AutoTunnelTarget
; // Opaque hostname of tunnel endpoint; used as SRV target for AutoTunnelService record
1760 AuthRecord AutoTunnelDeviceInfo
; // Device info of tunnel endpoint
1761 AuthRecord AutoTunnelService
; // Service record (possibly NAT-Mapped) of IKE daemon implementing tunnel endpoint
1762 NATTraversalInfo AutoTunnelNAT
;
1765 char b64keydata
[32];
1766 mDNSu8 keydata_ipad
[HMAC_LEN
]; // padded key for inner hash rounds
1767 mDNSu8 keydata_opad
[HMAC_LEN
]; // padded key for outer hash rounds
1770 // Note: Within an mDNSQuestionCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
1771 typedef enum { QC_rmv
= 0, QC_add
= 1, QC_addnocache
= 2 } QC_result
;
1772 typedef void mDNSQuestionCallback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
);
1773 struct DNSQuestion_struct
1775 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1778 mDNSs32 DelayAnswering
; // Set if we want to defer answering this question until the cache settles
1779 mDNSs32 LastQTime
; // Last scheduled transmission of this Q on *all* applicable interfaces
1780 mDNSs32 ThisQInterval
; // LastQTime + ThisQInterval is the next scheduled transmission of this Q
1781 // ThisQInterval > 0 for an active question;
1782 // ThisQInterval = 0 for a suspended question that's still in the list
1783 // ThisQInterval = -1 for a cancelled question (should not still be in list)
1784 mDNSs32 ExpectUnicastResp
;// Set when we send a query with the kDNSQClass_UnicastResponse bit set
1785 mDNSs32 LastAnswerPktNum
; // The sequence number of the last response packet containing an answer to this Q
1786 mDNSu32 RecentAnswerPkts
; // Number of answers since the last time we sent this query
1787 mDNSu32 CurrentAnswers
; // Number of records currently in the cache that answer this question
1788 mDNSu32 LargeAnswers
; // Number of answers with rdata > 1024 bytes
1789 mDNSu32 UniqueAnswers
; // Number of answers received with kDNSClass_UniqueRRSet bit set
1790 mDNSInterfaceID FlappingInterface1
;// Set when an interface goes away, to flag if remove events are delivered for this Q
1791 mDNSInterfaceID FlappingInterface2
;// Set when an interface goes away, to flag if remove events are delivered for this Q
1792 DomainAuthInfo
*AuthInfo
; // Non-NULL if query is currently being done using Private DNS
1793 DNSQuestion
*DuplicateOf
;
1794 DNSQuestion
*NextInDQList
;
1795 DupSuppressInfo DupSuppress
[DupSuppressInfoSize
];
1796 mDNSInterfaceID SendQNow
; // The interface this query is being sent on right now
1797 mDNSBool SendOnAll
; // Set if we're sending this question on all active interfaces
1798 mDNSu32 RequestUnicast
; // Non-zero if we want to send query with kDNSQClass_UnicastResponse bit set
1799 mDNSs32 LastQTxTime
; // Last time this Q was sent on one (but not necessarily all) interfaces
1800 mDNSu32 CNAMEReferrals
; // Count of how many CNAME redirections we've done
1802 // Wide Area fields. These are used internally by the uDNS core
1803 DNSServer
*qDNSServer
; // Caching server for this query (in the absence of an SRV saying otherwise)
1805 ZoneData
*nta
; // Used for getting zone data for private or LLQ query
1806 mDNSAddr servAddr
; // Address and port learned from _dns-llq, _dns-llq-tls or _dns-query-tls SRV query
1807 mDNSIPPort servPort
;
1808 struct tcpInfo_t
*tcp
;
1809 mDNSu8 NoAnswer
; // Set if we want to suppress answers until tunnel setup has completed
1811 // LLQ-specific fields. These fields are only meaningful when LongLived flag is set
1813 mDNSu32 ReqLease
; // seconds (relative)
1814 mDNSs32 expire
; // ticks (absolute)
1818 // Client API fields: The client must set up these fields *before* calling mDNS_StartQuery()
1819 mDNSInterfaceID InterfaceID
; // Non-zero if you want to issue queries only on a single specific IP interface
1820 mDNSAddr Target
; // Non-zero if you want to direct queries to a specific unicast target address
1821 mDNSIPPort TargetPort
; // Must be set if Target is set
1822 mDNSOpaque16 TargetQID
; // Must be set if Target is set
1826 mDNSBool LongLived
; // Set by client for calls to mDNS_StartQuery to indicate LLQs to unicast layer.
1827 mDNSBool ExpectUnique
; // Set by client if it's expecting unique RR(s) for this question, not shared RRs
1828 mDNSBool ForceMCast
; // Set by client to force mDNS query, even for apparently uDNS names
1829 mDNSBool ReturnIntermed
; // Set by client to request callbacks for intermediate CNAME/NXDOMAIN results
1830 mDNSQuestionCallback
*QuestionCallback
;
1831 void *QuestionContext
;
1836 // Client API fields: The client must set up name and InterfaceID *before* calling mDNS_StartResolveService()
1837 // When the callback is invoked, ip, port, TXTlen and TXTinfo will have been filled in with the results learned from the network.
1839 mDNSInterfaceID InterfaceID
; // ID of the interface the response was received on
1840 mDNSAddr ip
; // Remote (destination) IP address where this service can be accessed
1841 mDNSIPPort port
; // Port where this service can be accessed
1843 mDNSu8 TXTinfo
[2048]; // Additional demultiplexing information (e.g. LPR queue name)
1846 // Note: Within an mDNSServiceInfoQueryCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
1847 typedef struct ServiceInfoQuery_struct ServiceInfoQuery
;
1848 typedef void mDNSServiceInfoQueryCallback(mDNS
*const m
, ServiceInfoQuery
*query
);
1849 struct ServiceInfoQuery_struct
1851 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1852 // No fields need to be set up by the client prior to calling mDNS_StartResolveService();
1853 // all required data is passed as parameters to that function.
1854 // The ServiceInfoQuery structure memory is working storage for mDNSCore to discover the requested information
1855 // and place it in the ServiceInfo structure. After the client has called mDNS_StopResolveService(), it may
1856 // dispose of the ServiceInfoQuery structure while retaining the results in the ServiceInfo structure.
1866 mDNSServiceInfoQueryCallback
*ServiceInfoQueryCallback
;
1867 void *ServiceInfoQueryContext
;
1870 typedef enum { ZoneServiceUpdate
, ZoneServiceQuery
, ZoneServiceLLQ
} ZoneService
;
1872 typedef void ZoneDataCallback(mDNS
*const m
, mStatus err
, const ZoneData
*result
);
1874 struct ZoneData_struct
1876 domainname ChildName
; // Name for which we're trying to find the responsible server
1877 ZoneService ZoneService
; // Which service we're seeking for this zone (update, query, or LLQ)
1878 domainname
*CurrentSOA
; // Points to somewhere within ChildName
1879 domainname ZoneName
; // Discovered result: Left-hand-side of SOA record
1880 mDNSu16 ZoneClass
; // Discovered result: DNS Class from SOA record
1881 domainname Host
; // Discovered result: Target host from SRV record
1882 mDNSIPPort Port
; // Discovered result: Update port, query port, or LLQ port from SRV record
1883 mDNSAddr Addr
; // Discovered result: Address of Target host from SRV record
1884 mDNSBool ZonePrivate
; // Discovered result: Does zone require encrypted queries?
1885 ZoneDataCallback
*ZoneDataCallback
; // Caller-specified function to be called upon completion
1886 void *ZoneDataContext
;
1887 DNSQuestion question
; // Storage for any active question
1890 extern ZoneData
*StartGetZoneData(mDNS
*const m
, const domainname
*const name
, const ZoneService target
, ZoneDataCallback callback
, void *callbackInfo
);
1891 extern void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
);
1893 typedef struct DNameListElem
1895 struct DNameListElem
*next
;
1900 #if APPLE_OSX_mDNSResponder
1901 typedef struct ClientTunnel
1903 struct ClientTunnel
*next
;
1905 mDNSBool MarkedForDeletion
;
1906 mDNSv6Addr loc_inner
;
1907 mDNSv4Addr loc_outer
;
1908 mDNSv6Addr rmt_inner
;
1909 mDNSv4Addr rmt_outer
;
1910 mDNSIPPort rmt_outer_port
;
1911 char b64keydata
[32];
1916 // ***************************************************************************
1918 #pragma mark - Main mDNS object, used to hold all the mDNS state
1921 typedef void mDNSCallback(mDNS
*const m
, mStatus result
);
1923 #define CACHE_HASH_SLOTS 499
1927 mDNS_KnownBug_PhantomInterfaces
= 1
1932 // Internal state fields. These hold the main internal state of mDNSCore;
1933 // the client layer needn't be concerned with them.
1934 // No fields need to be set up by the client prior to calling mDNS_Init();
1935 // all required data is passed as parameters to that function.
1937 mDNS_PlatformSupport
*p
; // Pointer to platform-specific data of indeterminite size
1939 mDNSBool CanReceiveUnicastOn5353
;
1940 mDNSBool AdvertiseLocalAddresses
;
1941 mStatus mDNSPlatformStatus
;
1942 mDNSIPPort UnicastPort4
;
1943 mDNSIPPort UnicastPort6
;
1944 mDNSCallback
*MainCallback
;
1947 // For debugging: To catch and report locking failures
1948 mDNSu32 mDNS_busy
; // Incremented between mDNS_Lock/mDNS_Unlock section
1949 mDNSu32 mDNS_reentrancy
; // Incremented when calling a client callback
1950 mDNSu8 lock_rrcache
; // For debugging: Set at times when these lists may not be modified
1951 mDNSu8 lock_Questions
;
1952 mDNSu8 lock_Records
;
1954 char MsgBuffer
[MaxMsg
]; // Temp storage used while building error log messages
1956 // Task Scheduling variables
1957 mDNSs32 timenow_adjust
; // Correction applied if we ever discover time went backwards
1958 mDNSs32 timenow
; // The time that this particular activation of the mDNS code started
1959 mDNSs32 timenow_last
; // The time the last time we ran
1960 mDNSs32 NextScheduledEvent
; // Derived from values below
1961 mDNSs32 ShutdownTime
; // Set when we're shutting down, allows us to skip some unnecessary steps
1962 mDNSs32 SuppressSending
; // Don't send *any* packets during this time
1963 mDNSs32 NextCacheCheck
; // Next time to refresh cache record before it expires
1964 mDNSs32 NextScheduledQuery
; // Next time to send query in its exponential backoff sequence
1965 mDNSs32 NextScheduledProbe
; // Next time to probe for new authoritative record
1966 mDNSs32 NextScheduledResponse
; // Next time to send authoritative record(s) in responses
1967 mDNSs32 NextScheduledNATOp
; // Next time to send NAT-traversal packets
1968 mDNSs32 RandomQueryDelay
; // For de-synchronization of query packets on the wire
1969 mDNSu32 RandomReconfirmDelay
; // For de-synchronization of reconfirmation queries on the wire
1970 mDNSs32 PktNum
; // Unique sequence number assigned to each received packet
1971 mDNSBool SendDeregistrations
; // Set if we need to send deregistrations (immediately)
1972 mDNSBool SendImmediateAnswers
; // Set if we need to send answers (immediately -- or as soon as SuppressSending clears)
1973 mDNSBool SleepState
; // Set if we're sleeping (send no more packets)
1975 // These fields only required for mDNS Searcher...
1976 DNSQuestion
*Questions
; // List of all registered questions, active and inactive
1977 DNSQuestion
*NewQuestions
; // Fresh questions not yet answered from cache
1978 DNSQuestion
*CurrentQuestion
; // Next question about to be examined in AnswerLocalQuestions()
1979 DNSQuestion
*LocalOnlyQuestions
; // Questions with InterfaceID set to mDNSInterface_LocalOnly
1980 DNSQuestion
*NewLocalOnlyQuestions
; // Fresh local-only questions not yet answered
1981 mDNSu32 rrcache_size
; // Total number of available cache entries
1982 mDNSu32 rrcache_totalused
; // Number of cache entries currently occupied
1983 mDNSu32 rrcache_active
; // Number of cache entries currently occupied by records that answer active questions
1984 mDNSu32 rrcache_report
;
1985 CacheEntity
*rrcache_free
;
1986 CacheGroup
*rrcache_hash
[CACHE_HASH_SLOTS
];
1988 // Fields below only required for mDNS Responder...
1989 domainlabel nicelabel
; // Rich text label encoded using canonically precomposed UTF-8
1990 domainlabel hostlabel
; // Conforms to RFC 1034 "letter-digit-hyphen" ARPANET host name rules
1991 domainname MulticastHostname
; // Fully Qualified "dot-local" Host Name, e.g. "Foo.local."
1992 UTF8str255 HIHardware
;
1993 UTF8str255 HISoftware
;
1994 AuthRecord DeviceInfo
;
1995 AuthRecord
*ResourceRecords
;
1996 AuthRecord
*DuplicateRecords
; // Records currently 'on hold' because they are duplicates of existing records
1997 AuthRecord
*NewLocalRecords
; // Fresh local-only records not yet delivered to local-only questions
1998 AuthRecord
*CurrentRecord
; // Next AuthRecord about to be examined
1999 NetworkInterfaceInfo
*HostInterfaces
;
2000 mDNSs32 ProbeFailTime
;
2001 mDNSu32 NumFailedProbes
;
2002 mDNSs32 SuppressProbes
;
2004 // unicast-specific data
2005 mDNSs32 NextuDNSEvent
; // uDNS next event
2006 mDNSs32 NextSRVUpdate
; // Time to perform delayed update
2007 mDNSs32 SuppressStdPort53Queries
; // Wait before allowing the next standard unicast query to the user's configured DNS server
2009 ServiceRecordSet
*ServiceRegistrations
;
2010 mDNSu16 NextMessageID
;
2011 DNSServer
*DNSServers
; // list of DNS servers
2014 mDNSAddr AdvertisedV4
; // IPv4 address pointed to by hostname
2015 mDNSAddr AdvertisedV6
; // IPv6 address pointed to by hostname
2017 DomainAuthInfo
*AuthInfoList
; // list of domains requiring authentication for updates
2019 DNSQuestion ReverseMap
; // Reverse-map query to find static hostname for service target
2020 DNSQuestion AutomaticBrowseDomainQ
;
2021 domainname StaticHostname
; // Current answer to reverse-map query
2023 HostnameInfo
*Hostnames
; // List of registered hostnames + hostname metadata
2024 mDNSv6Addr AutoTunnelHostAddr
; // IPv6 address advertised for AutoTunnel services on this machine
2025 mDNSBool AutoTunnelHostAddrActive
;
2026 domainlabel AutoTunnelLabel
; // Used to construct hostname for *IPv4* address of tunnel endpoints
2028 mDNSBool RegisterSearchDomains
;
2030 // NAT traversal fields
2031 NATTraversalInfo LLQNAT
; // Single shared NAT Traversal to receive inbound LLQ notifications
2032 NATTraversalInfo
*NATTraversals
;
2033 NATTraversalInfo
*CurrentNATTraversal
;
2034 mDNSs32 retryIntervalGetAddr
; // delta between time sent and retry
2035 mDNSs32 retryGetAddr
; // absolute time when we retry
2036 mDNSv4Addr ExternalAddress
;
2038 UDPSocket
*NATMcastRecvskt
; // For receiving NAT-PMP AddrReply multicasts from router on port 5350
2039 UDPSocket
*NATMcastRecvsk2
; // For backwards compatibility, same as above but listening on port 5351
2040 mDNSu32 LastNATupseconds
; // NAT engine uptime in seconds, from most recent NAT packet
2041 mDNSs32 LastNATReplyLocalTime
; // Local time in ticks when most recent NAT packet was received
2043 tcpLNTInfo tcpAddrInfo
; // legacy NAT traversal TCP connection info for external address
2044 tcpLNTInfo tcpDeviceInfo
; // legacy NAT traversal TCP connection info for device info
2045 tcpLNTInfo
*tcpInfoUnmapList
; // list of pending unmap requests
2046 mDNSInterfaceID UPnPInterfaceID
;
2047 UDPSocket
*SSDPSocket
; // For SSDP request/response
2048 mDNSIPPort UPnPRouterPort
; // port we send discovery messages to
2049 mDNSIPPort UPnPSOAPPort
; // port we send SOAP messages to
2050 mDNSu8
*UPnPRouterURL
; // router's URL string
2051 mDNSu8
*UPnPSOAPURL
; // router's SOAP control URL string
2052 mDNSu8
*UPnPRouterAddressString
; // holds both the router's address and port
2053 mDNSu8
*UPnPSOAPAddressString
; // holds both address and port for SOAP messages
2055 #if APPLE_OSX_mDNSResponder
2056 ClientTunnel
*TunnelClients
;
2059 // Fixed storage, to avoid creating large objects on the stack
2060 DNSMessage imsg
; // Incoming message received from wire
2061 DNSMessage omsg
; // Outgoing message we're building
2062 LargeCacheRecord rec
; // Resource Record extracted from received message
2065 #define FORALL_CACHERECORDS(SLOT,CG,CR) \
2066 for ((SLOT) = 0; (SLOT) < CACHE_HASH_SLOTS; (SLOT)++) \
2067 for ((CG)=m->rrcache_hash[(SLOT)]; (CG); (CG)=(CG)->next) \
2068 for ((CR) = (CG)->members; (CR); (CR)=(CR)->next)
2070 // ***************************************************************************
2072 #pragma mark - Useful Static Constants
2075 extern const mDNSIPPort zeroIPPort
;
2076 extern const mDNSv4Addr zerov4Addr
;
2077 extern const mDNSv6Addr zerov6Addr
;
2078 extern const mDNSEthAddr zeroEthAddr
;
2079 extern const mDNSv4Addr onesIPv4Addr
;
2080 extern const mDNSv6Addr onesIPv6Addr
;
2081 extern const mDNSAddr zeroAddr
;
2083 extern const mDNSInterfaceID mDNSInterface_Any
; // Zero
2084 extern const mDNSInterfaceID mDNSInterface_LocalOnly
; // Special value
2085 extern const mDNSInterfaceID mDNSInterface_Unicast
; // Special value
2087 extern const mDNSIPPort SSDPPort
;
2089 extern const mDNSIPPort UnicastDNSPort
;
2090 extern const mDNSIPPort NATPMPAnnouncementPort
;
2091 extern const mDNSIPPort NATPMPPort
;
2092 extern const mDNSIPPort DNSEXTPort
;
2093 extern const mDNSIPPort MulticastDNSPort
;
2094 extern const mDNSIPPort LoopbackIPCPort
;
2096 extern const mDNSIPPort NSIPCPort
;
2097 extern const mDNSIPPort PrivateDNSPort
;
2099 extern const mDNSv4Addr AllDNSAdminGroup
;
2100 extern const mDNSAddr AllDNSLinkGroup_v4
;
2101 extern const mDNSAddr AllDNSLinkGroup_v6
;
2103 extern const mDNSOpaque16 zeroID
;
2104 extern const mDNSOpaque16 QueryFlags
;
2105 extern const mDNSOpaque16 uQueryFlags
;
2106 extern const mDNSOpaque16 ResponseFlags
;
2107 extern const mDNSOpaque16 UpdateReqFlags
;
2108 extern const mDNSOpaque16 UpdateRespFlags
;
2110 extern const mDNSOpaque64 zeroOpaque64
;
2112 #define localdomain (*(const domainname *)"\x5" "local")
2113 #define LocalReverseMapDomain (*(const domainname *)"\x3" "254" "\x3" "169" "\x7" "in-addr" "\x4" "arpa")
2114 #define DeviceInfoName (*(const domainname *)"\xC" "_device-info" "\x4" "_tcp")
2116 // ***************************************************************************
2118 #pragma mark - Inline functions
2121 #if (defined(_MSC_VER))
2122 #define mDNSinline static __inline
2123 #elif ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
2124 #define mDNSinline static inline
2127 // If we're not doing inline functions, then this header needs to have the extern declarations
2128 #if !defined(mDNSinline)
2129 extern mDNSs32
NonZeroTime(mDNSs32 t
);
2130 extern mDNSu16
mDNSVal16(mDNSOpaque16 x
);
2131 extern mDNSOpaque16
mDNSOpaque16fromIntVal(mDNSu16 v
);
2134 // If we're compiling the particular C file that instantiates our inlines, then we
2135 // define "mDNSinline" (to empty string) so that we generate code in the following section
2136 #if (!defined(mDNSinline) && mDNS_InstantiateInlines)
2142 mDNSinline mDNSs32
NonZeroTime(mDNSs32 t
) { if (t
) return(t
); else return(1); }
2144 mDNSinline mDNSu16
mDNSVal16(mDNSOpaque16 x
) { return((mDNSu16
)((mDNSu16
)x
.b
[0] << 8 | (mDNSu16
)x
.b
[1])); }
2146 mDNSinline mDNSOpaque16
mDNSOpaque16fromIntVal(mDNSu16 v
)
2149 x
.b
[0] = (mDNSu8
)(v
>> 8);
2150 x
.b
[1] = (mDNSu8
)(v
& 0xFF);
2156 // ***************************************************************************
2158 #pragma mark - Main Client Functions
2161 // Every client should call mDNS_Init, passing in storage for the mDNS object and the mDNS_PlatformSupport object.
2163 // Clients that are only advertising services should use mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize.
2164 // Clients that plan to perform queries (mDNS_StartQuery, mDNS_StartBrowse, mDNS_StartResolveService, etc.)
2165 // need to provide storage for the resource record cache, or the query calls will return 'mStatus_NoCache'.
2166 // The rrcachestorage parameter is the address of memory for the resource record cache, and
2167 // the rrcachesize parameter is the number of entries in the CacheRecord array passed in.
2168 // (i.e. the size of the cache memory needs to be sizeof(CacheRecord) * rrcachesize).
2169 // OS X 10.3 Panther uses an initial cache size of 64 entries, and then mDNSCore sends an
2170 // mStatus_GrowCache message if it needs more.
2172 // Most clients should use mDNS_Init_AdvertiseLocalAddresses. This causes mDNSCore to automatically
2173 // create the correct address records for all the hosts interfaces. If you plan to advertise
2174 // services being offered by the local machine, this is almost always what you want.
2175 // There are two cases where you might use mDNS_Init_DontAdvertiseLocalAddresses:
2176 // 1. A client-only device, that browses for services but doesn't advertise any of its own.
2177 // 2. A proxy-registration service, that advertises services being offered by other machines, and takes
2178 // the appropriate steps to manually create the correct address records for those other machines.
2179 // In principle, a proxy-like registration service could manually create address records for its own machine too,
2180 // but this would be pointless extra effort when using mDNS_Init_AdvertiseLocalAddresses does that for you.
2182 // When mDNS has finished setting up the client's callback is called
2183 // A client can also spin and poll the mDNSPlatformStatus field to see when it changes from mStatus_Waiting to mStatus_NoError
2185 // Call mDNS_StartExit to tidy up before exiting
2186 // Because exiting may be an asynchronous process (e.g. if unicast records need to be deregistered)
2187 // client layer may choose to wait until mDNS_ExitNow() returns true before calling mDNS_FinalExit().
2189 // Call mDNS_Register with a completed AuthRecord object to register a resource record
2190 // If the resource record type is kDNSRecordTypeUnique (or kDNSknownunique) then if a conflicting resource record is discovered,
2191 // the resource record's mDNSRecordCallback will be called with error code mStatus_NameConflict. The callback should deregister
2192 // the record, and may then try registering the record again after picking a new name (e.g. by automatically appending a number).
2193 // Following deregistration, the RecordCallback will be called with result mStatus_MemFree to signal that it is safe to deallocate
2194 // the record's storage (memory must be freed asynchronously to allow for goodbye packets and dynamic update deregistration).
2196 // Call mDNS_StartQuery to initiate a query. mDNS will proceed to issue Multicast DNS query packets, and any time a response
2197 // is received containing a record which matches the question, the DNSQuestion's mDNSAnswerCallback function will be called
2198 // Call mDNS_StopQuery when no more answers are required
2200 // Care should be taken on multi-threaded or interrupt-driven environments.
2201 // The main mDNS routines call mDNSPlatformLock() on entry and mDNSPlatformUnlock() on exit;
2202 // each platform layer needs to implement these appropriately for its respective platform.
2203 // For example, if the support code on a particular platform implements timer callbacks at interrupt time, then
2204 // mDNSPlatformLock/Unlock need to disable interrupts or do similar concurrency control to ensure that the mDNS
2205 // code is not entered by an interrupt-time timer callback while in the middle of processing a client call.
2207 extern mStatus
mDNS_Init (mDNS
*const m
, mDNS_PlatformSupport
*const p
,
2208 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
2209 mDNSBool AdvertiseLocalAddresses
,
2210 mDNSCallback
*Callback
, void *Context
);
2211 // See notes above on use of NoCache/ZeroCacheSize
2212 #define mDNS_Init_NoCache mDNSNULL
2213 #define mDNS_Init_ZeroCacheSize 0
2214 // See notes above on use of Advertise/DontAdvertiseLocalAddresses
2215 #define mDNS_Init_AdvertiseLocalAddresses mDNStrue
2216 #define mDNS_Init_DontAdvertiseLocalAddresses mDNSfalse
2217 #define mDNS_Init_NoInitCallback mDNSNULL
2218 #define mDNS_Init_NoInitCallbackContext mDNSNULL
2220 extern void mDNS_GrowCache (mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
);
2221 extern void mDNS_StartExit (mDNS
*const m
);
2222 extern void mDNS_FinalExit (mDNS
*const m
);
2223 #define mDNS_Close(m) do { mDNS_StartExit(m); mDNS_FinalExit(m); } while(0)
2224 #define mDNS_ExitNow(m, now) ((now) - (m)->ShutdownTime >= 0 || (!(m)->ResourceRecords && !(m)->ServiceRegistrations))
2226 extern mDNSs32
mDNS_Execute (mDNS
*const m
);
2228 extern mStatus
mDNS_Register (mDNS
*const m
, AuthRecord
*const rr
);
2229 extern mStatus
mDNS_Update (mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
2230 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
);
2231 extern mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
);
2233 extern mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
);
2234 extern mStatus
mDNS_StopQuery (mDNS
*const m
, DNSQuestion
*const question
);
2235 extern mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
);
2236 extern mStatus
mDNS_Reconfirm (mDNS
*const m
, CacheRecord
*const cacherr
);
2237 extern mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
);
2238 extern void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
);
2239 extern mDNSs32
mDNS_TimeNow(const mDNS
*const m
);
2241 extern mStatus
mDNS_StartNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
);
2242 extern mStatus
mDNS_StopNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
);
2243 extern mStatus
mDNS_StopNATOperation_internal(mDNS
*m
, NATTraversalInfo
*traversal
);
2245 extern DomainAuthInfo
*GetAuthInfoForName(mDNS
*m
, const domainname
*const name
);
2247 // ***************************************************************************
2249 #pragma mark - Platform support functions that are accessible to the client layer too
2252 extern mDNSs32 mDNSPlatformOneSecond
;
2254 // ***************************************************************************
2256 #pragma mark - General utility and helper functions
2259 // mDNS_RegisterService is a single call to register the set of resource records associated with a given named service.
2261 // mDNS_StartResolveService is single call which is equivalent to multiple calls to mDNS_StartQuery,
2262 // to find the IP address, port number, and demultiplexing information for a given named service.
2263 // As with mDNS_StartQuery, it executes asynchronously, and calls the ServiceInfoQueryCallback when the answer is
2264 // found. After the service is resolved, the client should call mDNS_StopResolveService to complete the transaction.
2265 // The client can also call mDNS_StopResolveService at any time to abort the transaction.
2267 // mDNS_AddRecordToService adds an additional record to a Service Record Set. This record may be deregistered
2268 // via mDNS_RemoveRecordFromService, or by deregistering the service. mDNS_RemoveRecordFromService is passed a
2269 // callback to free the memory associated with the extra RR when it is safe to do so. The ExtraResourceRecord
2270 // object can be found in the record's context pointer.
2272 // mDNS_GetBrowseDomains is a special case of the mDNS_StartQuery call, where the resulting answers
2273 // are a list of PTR records indicating (in the rdata) domains that are recommended for browsing.
2274 // After getting the list of domains to browse, call mDNS_StopQuery to end the search.
2275 // mDNS_GetDefaultBrowseDomain returns the name of the domain that should be highlighted by default.
2277 // mDNS_GetRegistrationDomains and mDNS_GetDefaultRegistrationDomain are the equivalent calls to get the list
2278 // of one or more domains that should be offered to the user as choices for where they may register their service,
2279 // and the default domain in which to register in the case where the user has made no selection.
2281 extern void mDNS_SetupResourceRecord(AuthRecord
*rr
, RData
*RDataStorage
, mDNSInterfaceID InterfaceID
,
2282 mDNSu16 rrtype
, mDNSu32 ttl
, mDNSu8 RecordType
, mDNSRecordCallback Callback
, void *Context
);
2284 extern mStatus
mDNS_RegisterService (mDNS
*const m
, ServiceRecordSet
*sr
,
2285 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
2286 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
2287 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
2288 const mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
);
2289 extern mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
);
2290 extern mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
, mDNSRecordCallback MemFreeCallback
, void *Context
);
2291 extern mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
);
2292 extern mStatus
mDNS_DeregisterService(mDNS
*const m
, ServiceRecordSet
*sr
);
2294 extern mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
2295 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
2296 const domainname
*const host
,
2297 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
);
2298 #define mDNS_DeregisterNoSuchService mDNS_Deregister
2300 extern mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
2301 const domainname
*const srv
, const domainname
*const domain
,
2302 const mDNSInterfaceID InterfaceID
, mDNSBool ForceMCast
, mDNSQuestionCallback
*Callback
, void *Context
);
2303 #define mDNS_StopBrowse mDNS_StopQuery
2305 extern mStatus
mDNS_StartResolveService(mDNS
*const m
, ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
);
2306 extern void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*query
);
2310 mDNS_DomainTypeBrowse
= 0,
2311 mDNS_DomainTypeBrowseDefault
= 1,
2312 mDNS_DomainTypeBrowseAutomatic
= 2,
2313 mDNS_DomainTypeRegistration
= 3,
2314 mDNS_DomainTypeRegistrationDefault
= 4,
2316 mDNS_DomainTypeMax
= 4
2319 extern const char *const mDNS_DomainTypeNames
[];
2321 extern mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
2322 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
);
2323 #define mDNS_StopGetDomains mDNS_StopQuery
2324 extern mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
, mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
);
2325 #define mDNS_StopAdvertiseDomains mDNS_Deregister
2327 extern mDNSOpaque16
mDNS_NewMessageID(mDNS
*const m
);
2329 // ***************************************************************************
2331 #pragma mark - DNS name utility functions
2334 // In order to expose the full capabilities of the DNS protocol (which allows any arbitrary eight-bit values
2335 // in domain name labels, including unlikely characters like ascii nulls and even dots) all the mDNS APIs
2336 // work with DNS's native length-prefixed strings. For convenience in C, the following utility functions
2337 // are provided for converting between C's null-terminated strings and DNS's length-prefixed strings.
2340 // A simple C structure assignment of a domainname can cause a protection fault by accessing unmapped memory,
2341 // because that object is defined to be 256 bytes long, but not all domainname objects are truly the full size.
2342 // This macro uses mDNSPlatformMemCopy() to make sure it only touches the actual bytes that are valid.
2343 #define AssignDomainName(DST, SRC) do { mDNSu16 len__ = DomainNameLength((SRC)); \
2344 if (len__ <= MAX_DOMAIN_NAME) mDNSPlatformMemCopy((DST)->c, (SRC)->c, len__); else (DST)->c[0] = 0; } while(0)
2346 // Comparison functions
2347 #define SameDomainLabelCS(A,B) ((A)[0] == (B)[0] && mDNSPlatformMemSame((A)+1, (B)+1, (A)[0]))
2348 extern mDNSBool
SameDomainLabel(const mDNSu8
*a
, const mDNSu8
*b
);
2349 extern mDNSBool
SameDomainName(const domainname
*const d1
, const domainname
*const d2
);
2350 extern mDNSBool
SameDomainNameCS(const domainname
*const d1
, const domainname
*const d2
);
2351 extern mDNSBool
IsLocalDomain(const domainname
*d
); // returns true for domains that by default should be looked up using link-local multicast
2353 // Get total length of domain name, in native DNS format, including terminal root label
2354 // (e.g. length of "com." is 5 (length byte, three data bytes, final zero)
2355 extern mDNSu16
DomainNameLengthLimit(const domainname
*const name
, const mDNSu8
*limit
);
2356 #define DomainNameLength(name) DomainNameLengthLimit((name), (name)->c + MAX_DOMAIN_NAME + 1)
2358 // Append functions to append one or more labels to an existing native format domain name:
2359 // AppendLiteralLabelString adds a single label from a literal C string, with no escape character interpretation.
2360 // AppendDNSNameString adds zero or more labels from a C string using conventional DNS dots-and-escaping interpretation
2361 // AppendDomainLabel adds a single label from a native format domainlabel
2362 // AppendDomainName adds zero or more labels from a native format domainname
2363 extern mDNSu8
*AppendLiteralLabelString(domainname
*const name
, const char *cstr
);
2364 extern mDNSu8
*AppendDNSNameString (domainname
*const name
, const char *cstr
);
2365 extern mDNSu8
*AppendDomainLabel (domainname
*const name
, const domainlabel
*const label
);
2366 extern mDNSu8
*AppendDomainName (domainname
*const name
, const domainname
*const append
);
2368 // Convert from null-terminated string to native DNS format:
2369 // The DomainLabel form makes a single label from a literal C string, with no escape character interpretation.
2370 // The DomainName form makes native format domain name from a C string using conventional DNS interpretation:
2371 // dots separate labels, and within each label, '\.' represents a literal dot, '\\' represents a literal
2372 // backslash and backslash with three decimal digits (e.g. \000) represents an arbitrary byte value.
2373 extern mDNSBool
MakeDomainLabelFromLiteralString(domainlabel
*const label
, const char *cstr
);
2374 extern mDNSu8
*MakeDomainNameFromDNSNameString (domainname
*const name
, const char *cstr
);
2376 // Convert native format domainlabel or domainname back to C string format
2378 // When using ConvertDomainLabelToCString, the target buffer must be MAX_ESCAPED_DOMAIN_LABEL (254) bytes long
2379 // to guarantee there will be no buffer overrun. It is only safe to use a buffer shorter than this in rare cases
2380 // where the label is known to be constrained somehow (for example, if the label is known to be either "_tcp" or "_udp").
2381 // Similarly, when using ConvertDomainNameToCString, the target buffer must be MAX_ESCAPED_DOMAIN_NAME (1005) bytes long.
2382 // See definitions of MAX_ESCAPED_DOMAIN_LABEL and MAX_ESCAPED_DOMAIN_NAME for more detailed explanation.
2383 extern char *ConvertDomainLabelToCString_withescape(const domainlabel
*const name
, char *cstr
, char esc
);
2384 #define ConvertDomainLabelToCString_unescaped(D,C) ConvertDomainLabelToCString_withescape((D), (C), 0)
2385 #define ConvertDomainLabelToCString(D,C) ConvertDomainLabelToCString_withescape((D), (C), '\\')
2386 extern char *ConvertDomainNameToCString_withescape(const domainname
*const name
, char *cstr
, char esc
);
2387 #define ConvertDomainNameToCString_unescaped(D,C) ConvertDomainNameToCString_withescape((D), (C), 0)
2388 #define ConvertDomainNameToCString(D,C) ConvertDomainNameToCString_withescape((D), (C), '\\')
2390 extern void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name
[], domainlabel
*const hostlabel
);
2392 extern mDNSu8
*ConstructServiceName(domainname
*const fqdn
, const domainlabel
*name
, const domainname
*type
, const domainname
*const domain
);
2393 extern mDNSBool
DeconstructServiceName(const domainname
*const fqdn
, domainlabel
*const name
, domainname
*const type
, domainname
*const domain
);
2395 // Note: Some old functions have been replaced by more sensibly-named versions.
2396 // You can uncomment the hash-defines below if you don't want to have to change your source code right away.
2397 // When updating your code, note that (unlike the old versions) *all* the new routines take the target object
2398 // as their first parameter.
2399 //#define ConvertCStringToDomainName(SRC,DST) MakeDomainNameFromDNSNameString((DST),(SRC))
2400 //#define ConvertCStringToDomainLabel(SRC,DST) MakeDomainLabelFromLiteralString((DST),(SRC))
2401 //#define AppendStringLabelToName(DST,SRC) AppendLiteralLabelString((DST),(SRC))
2402 //#define AppendStringNameToName(DST,SRC) AppendDNSNameString((DST),(SRC))
2403 //#define AppendDomainLabelToName(DST,SRC) AppendDomainLabel((DST),(SRC))
2404 //#define AppendDomainNameToName(DST,SRC) AppendDomainName((DST),(SRC))
2406 // ***************************************************************************
2408 #pragma mark - Other utility functions and macros
2411 // mDNS_vsnprintf/snprintf return the number of characters written, excluding the final terminating null.
2412 // The output is always null-terminated: for example, if the output turns out to be exactly buflen long,
2413 // then the output will be truncated by one character to allow space for the terminating null.
2414 // Unlike standard C vsnprintf/snprintf, they return the number of characters *actually* written,
2415 // not the number of characters that *would* have been printed were buflen unlimited.
2416 extern mDNSu32
mDNS_vsnprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, va_list arg
);
2417 extern mDNSu32
mDNS_snprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, ...) IS_A_PRINTF_STYLE_FUNCTION(3,4);
2418 extern mDNSu32
NumCacheRecordsForInterfaceID(const mDNS
*const m
, mDNSInterfaceID id
);
2419 extern char *DNSTypeName(mDNSu16 rrtype
);
2420 extern char *GetRRDisplayString_rdb(const ResourceRecord
*rr
, RDataBody
*rd
, char *buffer
);
2421 #define RRDisplayString(m, rr) GetRRDisplayString_rdb(rr, &(rr)->rdata->u, (m)->MsgBuffer)
2422 #define ARDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
2423 #define CRDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
2424 extern mDNSBool
mDNSSameAddress(const mDNSAddr
*ip1
, const mDNSAddr
*ip2
);
2425 extern void IncrementLabelSuffix(domainlabel
*name
, mDNSBool RichText
);
2426 extern mDNSBool
mDNSv4AddrIsRFC1918(mDNSv4Addr
*addr
); // returns true for RFC1918 private addresses
2427 #define mDNSAddrIsRFC1918(X) ((X)->type == mDNSAddrType_IPv4 && mDNSv4AddrIsRFC1918(&(X)->ip.v4))
2429 #define mDNSSameIPPort(A,B) ((A).NotAnInteger == (B).NotAnInteger)
2430 #define mDNSSameOpaque16(A,B) ((A).NotAnInteger == (B).NotAnInteger)
2431 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
2432 #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])
2433 #define mDNSSameEthAddress(A,B) ((A)->w[0] == (B)->w[0] && (A)->w[1] == (B)->w[1] && (A)->w[2] == (B)->w[2])
2435 #define mDNSSameOpaque64(A,B) ((A)->l[0] == (B)->l[0] && (A)->l[1] == (B)->l[1])
2436 #define mDNSOpaque64IsZero(A) ((A)->l[0] == 0 && (A)->l[1] == 0)
2438 #define mDNSIPPortIsZero(A) mDNSSameIPPort((A), zeroIPPort)
2439 #define mDNSOpaque16IsZero(A) mDNSSameOpaque16((A), zeroIPPort)
2440 #define mDNSIPv4AddressIsZero(A) mDNSSameIPv4Address((A), zerov4Addr)
2441 #define mDNSIPv6AddressIsZero(A) mDNSSameIPv6Address((A), zerov6Addr)
2443 #define mDNSIPv4AddressIsOnes(A) mDNSSameIPv4Address((A), onesIPv4Addr)
2444 #define mDNSIPv6AddressIsOnes(A) mDNSSameIPv6Address((A), onesIPv6Addr)
2446 #define mDNSAddressIsAllDNSLinkGroup(X) ( \
2447 ((X)->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address((X)->ip.v4, AllDNSLinkGroup_v4.ip.v4)) || \
2448 ((X)->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address((X)->ip.v6, AllDNSLinkGroup_v6.ip.v6)) )
2450 #define mDNSAddressIsZero(X) ( \
2451 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4)) || \
2452 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6)) )
2454 #define mDNSAddressIsValidNonZero(X) ( \
2455 ((X)->type == mDNSAddrType_IPv4 && !mDNSIPv4AddressIsZero((X)->ip.v4)) || \
2456 ((X)->type == mDNSAddrType_IPv6 && !mDNSIPv6AddressIsZero((X)->ip.v6)) )
2458 #define mDNSAddressIsOnes(X) ( \
2459 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4)) || \
2460 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6)) )
2462 #define mDNSAddressIsValid(X) ( \
2463 ((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) : \
2464 ((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
2466 #define mDNSv4AddressIsLinkLocal(X) ((X)->b[0] == 169 && (X)->b[1] == 254)
2467 #define mDNSv6AddressIsLinkLocal(X) ((X)->b[0] == 0xFE && ((X)->b[1] & 0xC0) == 0x80)
2469 #define mDNSAddressIsLinkLocal(X) ( \
2470 ((X)->type == mDNSAddrType_IPv4) ? mDNSv4AddressIsLinkLocal(&(X)->ip.v4) : \
2471 ((X)->type == mDNSAddrType_IPv6) ? mDNSv6AddressIsLinkLocal(&(X)->ip.v6) : mDNSfalse)
2473 // ***************************************************************************
2475 #pragma mark - Authentication Support
2478 // Unicast DNS and Dynamic Update specific Client Calls
2480 // mDNS_SetSecretForDomain tells the core to authenticate (via TSIG with an HMAC_MD5 hash of the shared secret)
2481 // when dynamically updating a given zone (and its subdomains). The key used in authentication must be in
2482 // domain name format. The shared secret must be a null-terminated base64 encoded string. A minimum size of
2483 // 16 bytes (128 bits) is recommended for an MD5 hash as per RFC 2485.
2484 // Calling this routine multiple times for a zone replaces previously entered values. Call with a NULL key
2485 // to dissable authentication for the zone.
2487 extern mStatus
mDNS_SetSecretForDomain(mDNS
*m
, DomainAuthInfo
*info
,
2488 const domainname
*domain
, const domainname
*keyname
, const char *b64keydata
, mDNSBool AutoTunnel
);
2490 // Hostname/Unicast Interface Configuration
2492 // All hostnames advertised point to one IPv4 address and/or one IPv6 address, set via SetPrimaryInterfaceInfo. Invoking this routine
2493 // updates all existing hostnames to point to the new address.
2495 // A hostname is added via AddDynDNSHostName, which points to the primary interface's v4 and/or v6 addresss
2497 // The status callback is invoked to convey success or failure codes - the callback should not modify the AuthRecord or free memory.
2498 // Added hostnames may be removed (deregistered) via mDNS_RemoveDynDNSHostName.
2500 // Host domains added prior to specification of the primary interface address and computer name will be deferred until
2501 // these values are initialized.
2503 // DNS servers used to resolve unicast queries are specified by mDNS_AddDNSServer.
2504 // For "split" DNS configurations, in which queries for different domains are sent to different servers (e.g. VPN and external),
2505 // a domain may be associated with a DNS server. For standard configurations, specify the root label (".") or NULL.
2507 extern void mDNS_AddDynDNSHostName(mDNS
*m
, const domainname
*fqdn
, mDNSRecordCallback
*StatusCallback
, const void *StatusContext
);
2508 extern void mDNS_RemoveDynDNSHostName(mDNS
*m
, const domainname
*fqdn
);
2509 extern void mDNS_SetPrimaryInterfaceInfo(mDNS
*m
, const mDNSAddr
*v4addr
, const mDNSAddr
*v6addr
, const mDNSAddr
*router
);
2510 extern DNSServer
*mDNS_AddDNSServer(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, const mDNSAddr
*addr
, const mDNSIPPort port
);
2511 extern void mDNS_AddSearchDomain(const domainname
*const domain
);
2513 // We use ((void *)0) here instead of mDNSNULL to avoid compile warnings on gcc 4.2
2514 #define mDNS_AddSearchDomain_CString(X) \
2515 do { domainname d__; if (((X) != (void*)0) && MakeDomainNameFromDNSNameString(&d__, (X)) && d__.c[0]) mDNS_AddSearchDomain(&d__); } while(0)
2517 // Routines called by the core, exported by DNSDigest.c
2519 // Convert an arbitrary base64 encoded key key into an HMAC key (stored in AuthInfo struct)
2520 extern mDNSs32
DNSDigest_ConstructHMACKeyfromBase64(DomainAuthInfo
*info
, const char *b64key
);
2522 // sign a DNS message. The message must be complete, with all values in network byte order. end points to the end
2523 // of the message, and is modified by this routine. numAdditionals is a pointer to the number of additional
2524 // records in HOST byte order, which is incremented upon successful completion of this routine. The function returns
2525 // the new end pointer on success, and NULL on failure.
2526 extern void DNSDigest_SignMessage(DNSMessage
*msg
, mDNSu8
**end
, DomainAuthInfo
*info
, mDNSu16 tcode
);
2528 #define SwapDNSHeaderBytes(M) do { \
2529 (M)->h.numQuestions = (mDNSu16)((mDNSu8 *)&(M)->h.numQuestions )[0] << 8 | ((mDNSu8 *)&(M)->h.numQuestions )[1]; \
2530 (M)->h.numAnswers = (mDNSu16)((mDNSu8 *)&(M)->h.numAnswers )[0] << 8 | ((mDNSu8 *)&(M)->h.numAnswers )[1]; \
2531 (M)->h.numAuthorities = (mDNSu16)((mDNSu8 *)&(M)->h.numAuthorities)[0] << 8 | ((mDNSu8 *)&(M)->h.numAuthorities)[1]; \
2532 (M)->h.numAdditionals = (mDNSu16)((mDNSu8 *)&(M)->h.numAdditionals)[0] << 8 | ((mDNSu8 *)&(M)->h.numAdditionals)[1]; \
2535 #define DNSDigest_SignMessageHostByteOrder(M,E,INFO) \
2536 do { SwapDNSHeaderBytes(M); DNSDigest_SignMessage((M), (E), (INFO), 0); SwapDNSHeaderBytes(M); } while (0)
2538 // verify a DNS message. The message must be complete, with all values in network byte order. end points to the
2539 // end of the record. tsig is a pointer to the resource record that contains the TSIG OPT record. info is
2540 // the matching key to use for verifying the message. This function expects that the additionals member
2541 // of the DNS message header has already had one subtracted from it.
2542 extern mDNSBool
DNSDigest_VerifyMessage(DNSMessage
*msg
, mDNSu8
*end
, LargeCacheRecord
*tsig
, DomainAuthInfo
*info
, mDNSu16
*rcode
, mDNSu16
*tcode
);
2544 // ***************************************************************************
2546 #pragma mark - PlatformSupport interface
2549 // This section defines the interface to the Platform Support layer.
2550 // Normal client code should not use any of types defined here, or directly call any of the functions defined here.
2551 // The definitions are placed here because sometimes clients do use these calls indirectly, via other supported client operations.
2552 // For example, AssignDomainName is a macro defined using mDNSPlatformMemCopy()
2554 // Every platform support module must provide the following functions.
2555 // mDNSPlatformInit() typically opens a communication endpoint, and starts listening for mDNS packets.
2556 // When Setup is complete, the platform support layer calls mDNSCoreInitComplete().
2557 // mDNSPlatformSendUDP() sends one UDP packet
2558 // When a packet is received, the PlatformSupport code calls mDNSCoreReceive()
2559 // mDNSPlatformClose() tidies up on exit
2561 // Note: mDNSPlatformMemAllocate/mDNSPlatformMemFree are only required for handling oversized resource records and unicast DNS.
2562 // If your target platform has a well-defined specialized application, and you know that all the records it uses
2563 // are InlineCacheRDSize or less, then you can just make a simple mDNSPlatformMemAllocate() stub that always returns
2564 // NULL. InlineCacheRDSize is a compile-time constant, which is set by default to 64. If you need to handle records
2565 // a little larger than this and you don't want to have to implement run-time allocation and freeing, then you
2566 // can raise the value of this constant to a suitable value (at the expense of increased memory usage).
2568 // USE CAUTION WHEN CALLING mDNSPlatformRawTime: The m->timenow_adjust correction factor needs to be added
2569 // Generally speaking:
2570 // Code that's protected by the main mDNS lock should just use the m->timenow value
2571 // Code outside the main mDNS lock should use mDNS_TimeNow(m) to get properly adjusted time
2572 // In certain cases there may be reasons why it's necessary to get the time without taking the lock first
2573 // (e.g. inside the routines that are doing the locking and unlocking, where a call to get the lock would result in a
2574 // recursive loop); in these cases use mDNS_TimeNow_NoLock(m) to get mDNSPlatformRawTime with the proper correction factor added.
2576 // mDNSPlatformUTC returns the time, in seconds, since Jan 1st 1970 UTC and is required for generating TSIG records
2578 extern mStatus
mDNSPlatformInit (mDNS
*const m
);
2579 extern void mDNSPlatformClose (mDNS
*const m
);
2580 extern mStatus
mDNSPlatformSendUDP(const mDNS
*const m
, const void *const msg
, const mDNSu8
*const end
,
2581 mDNSInterfaceID InterfaceID
, const mDNSAddr
*dst
, mDNSIPPort dstport
);
2583 extern void mDNSPlatformLock (const mDNS
*const m
);
2584 extern void mDNSPlatformUnlock (const mDNS
*const m
);
2586 extern void mDNSPlatformStrCopy ( void *dst
, const void *src
);
2587 extern mDNSu32
mDNSPlatformStrLen ( const void *src
);
2588 extern void mDNSPlatformMemCopy ( void *dst
, const void *src
, mDNSu32 len
);
2589 extern mDNSBool
mDNSPlatformMemSame (const void *dst
, const void *src
, mDNSu32 len
);
2590 extern void mDNSPlatformMemZero ( void *dst
, mDNSu32 len
);
2591 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
2592 #define mDNSPlatformMemAllocate(X) mallocL(#X, X)
2594 extern void * mDNSPlatformMemAllocate (mDNSu32 len
);
2596 extern void mDNSPlatformMemFree (void *mem
);
2597 extern mDNSu32
mDNSPlatformRandomSeed (void);
2598 extern mStatus
mDNSPlatformTimeInit (void);
2599 extern mDNSs32
mDNSPlatformRawTime (void);
2600 extern mDNSs32
mDNSPlatformUTC (void);
2601 #define mDNS_TimeNow_NoLock(m) (mDNSPlatformRawTime() + (m)->timenow_adjust)
2604 extern void mDNSPlatformWriteDebugMsg(const char *msg
);
2606 extern void mDNSPlatformWriteLogMsg(const char *ident
, const char *msg
, int flags
);
2608 // Platform support modules should provide the following functions to map between opaque interface IDs
2609 // and interface indexes in order to support the DNS-SD API. If your target platform does not support
2610 // multiple interfaces and/or does not support the DNS-SD API, these functions can be empty.
2611 extern mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS
*const m
, mDNSu32 ifindex
);
2612 extern mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(mDNS
*const m
, mDNSInterfaceID id
);
2614 // Every platform support module must provide the following functions if it is to support unicast DNS
2615 // and Dynamic Update.
2616 // All TCP socket operations implemented by the platform layer MUST NOT BLOCK.
2617 // mDNSPlatformTCPConnect initiates a TCP connection with a peer, adding the socket descriptor to the
2618 // main event loop. The return value indicates whether the connection succeeded, failed, or is pending
2619 // (i.e. the call would block.) On return, the descriptor parameter is set to point to the connected socket.
2620 // The TCPConnectionCallback is subsequently invoked when the connection
2621 // completes (in which case the ConnectionEstablished parameter is true), or data is available for
2622 // reading on the socket (indicated by the ConnectionEstablished parameter being false.) If the connection
2623 // asynchronously fails, the TCPConnectionCallback should be invoked as usual, with the error being
2624 // returned in subsequent calls to PlatformReadTCP or PlatformWriteTCP. (This allows for platforms
2625 // with limited asynchronous error detection capabilities.) PlatformReadTCP and PlatformWriteTCP must
2626 // return the number of bytes read/written, 0 if the call would block, and -1 if an error. PlatformReadTCP
2627 // should set the closed argument if the socket has been closed.
2628 // PlatformTCPCloseConnection must close the connection to the peer and remove the descriptor from the
2629 // event loop. CloseConnectin may be called at any time, including in a ConnectionCallback.
2633 kTCPSocketFlags_Zero
= 0,
2634 kTCPSocketFlags_UseTLS
= (1 << 0)
2637 typedef void (*TCPConnectionCallback
)(TCPSocket
*sock
, void *context
, mDNSBool ConnectionEstablished
, mStatus err
);
2638 extern TCPSocket
*mDNSPlatformTCPSocket(mDNS
*const m
, TCPSocketFlags flags
, mDNSIPPort
*port
); // creates a TCP socket
2639 extern TCPSocket
*mDNSPlatformTCPAccept(TCPSocketFlags flags
, int sd
);
2640 extern int mDNSPlatformTCPGetFD(TCPSocket
*sock
);
2641 extern mStatus
mDNSPlatformTCPConnect(TCPSocket
*sock
, const mDNSAddr
*dst
, mDNSOpaque16 dstport
, mDNSInterfaceID InterfaceID
,
2642 TCPConnectionCallback callback
, void *context
);
2643 extern void mDNSPlatformTCPCloseConnection(TCPSocket
*sock
);
2644 extern long mDNSPlatformReadTCP(TCPSocket
*sock
, void *buf
, unsigned long buflen
, mDNSBool
*closed
);
2645 extern long mDNSPlatformWriteTCP(TCPSocket
*sock
, const char *msg
, unsigned long len
);
2646 extern UDPSocket
*mDNSPlatformUDPSocket(mDNS
*const m
, mDNSIPPort port
);
2647 extern void mDNSPlatformUDPClose(UDPSocket
*sock
);
2648 extern void mDNSPlatformSourceAddrForDest(mDNSAddr
*const src
, const mDNSAddr
*const dst
);
2650 // mDNSPlatformTLSSetupCerts/mDNSPlatformTLSTearDownCerts used by dnsextd
2651 extern mStatus
mDNSPlatformTLSSetupCerts(void);
2652 extern void mDNSPlatformTLSTearDownCerts(void);
2654 // Platforms that support unicast browsing and dynamic update registration for clients who do not specify a domain
2655 // in browse/registration calls must implement these routines to get the "default" browse/registration list.
2657 extern void mDNSPlatformSetDNSConfig(mDNS
*const m
, mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
, DNameListElem
**BrowseDomains
);
2658 extern mStatus
mDNSPlatformGetPrimaryInterface(mDNS
*const m
, mDNSAddr
*v4
, mDNSAddr
*v6
, mDNSAddr
*router
);
2659 extern void mDNSPlatformDynDNSHostNameStatusChanged(const domainname
*const dname
, const mStatus status
);
2661 #ifdef _LEGACY_NAT_TRAVERSAL_
2662 // Support for legacy NAT traversal protocols, implemented by the platform layer and callable by the core.
2663 extern void LNT_SendDiscoveryMsg(mDNS
*m
);
2664 extern void LNT_ConfigureRouterInfo(mDNS
*m
, const mDNSInterfaceID InterfaceID
, mDNSu8
*data
, mDNSu16 len
);
2665 extern mStatus
LNT_GetExternalAddress(mDNS
*m
);
2666 extern mStatus
LNT_MapPort(mDNS
*m
, NATTraversalInfo
*n
);
2667 extern mStatus
LNT_UnmapPort(mDNS
*m
, NATTraversalInfo
*n
);
2668 #endif // _LEGACY_NAT_TRAVERSAL_
2670 // The core mDNS code provides these functions, for the platform support code to call at appropriate times
2672 // mDNS_SetFQDN() is called once on startup (typically from mDNSPlatformInit())
2673 // and then again on each subsequent change of the host name.
2675 // mDNS_RegisterInterface() is used by the platform support layer to inform mDNSCore of what
2676 // physical and/or logical interfaces are available for sending and receiving packets.
2677 // Typically it is called on startup for each available interface, but register/deregister may be
2678 // called again later, on multiple occasions, to inform the core of interface configuration changes.
2679 // If set->Advertise is set non-zero, then mDNS_RegisterInterface() also registers the standard
2680 // resource records that should be associated with every publicised IP address/interface:
2681 // -- Name-to-address records (A/AAAA)
2682 // -- Address-to-name records (PTR)
2683 // -- Host information (HINFO)
2684 // IMPORTANT: The specified mDNSInterfaceID MUST NOT be 0, -1, or -2; these values have special meaning
2685 // mDNS_RegisterInterface does not result in the registration of global hostnames via dynamic update -
2686 // see mDNS_SetPrimaryInterfaceInfo, mDNS_AddDynDNSHostName, etc. for this purpose.
2687 // Note that the set may be deallocated immediately after it is deregistered via mDNS_DeegisterInterface.
2689 // mDNS_RegisterDNS() is used by the platform support layer to provide the core with the addresses of
2690 // available domain name servers for unicast queries/updates. RegisterDNS() should be called once for
2691 // each name server, typically at startup, or when a new name server becomes available. DeregiterDNS()
2692 // must be called whenever a registered name server becomes unavailable. DeregisterDNSList deregisters
2693 // all registered servers. mDNS_DNSRegistered() returns true if one or more servers are registered in the core.
2695 // mDNSCoreInitComplete() is called when the platform support layer is finished.
2696 // Typically this is at the end of mDNSPlatformInit(), but may be later
2697 // (on platforms like OT that allow asynchronous initialization of the networking stack).
2699 // mDNSCoreReceive() is called when a UDP packet is received
2701 // mDNSCoreMachineSleep() is called when the machine sleeps or wakes
2702 // (This refers to heavyweight laptop-style sleep/wake that disables network access,
2703 // not lightweight second-by-second CPU power management modes.)
2705 extern void mDNS_SetFQDN(mDNS
*const m
);
2706 extern mStatus
mDNS_RegisterInterface (mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
);
2707 extern void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
);
2708 extern void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
);
2709 extern void mDNSCoreReceive(mDNS
*const m
, void *const msg
, const mDNSu8
*const end
,
2710 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
,
2711 const mDNSAddr
*const dstaddr
, const mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
);
2712 extern void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool wake
);
2714 extern mDNSBool
mDNSAddrIsDNSMulticast(const mDNSAddr
*ip
);
2716 extern CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
);
2717 extern void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
);
2718 extern void MakeNegativeCacheRecord(mDNS
*const m
, const domainname
*const name
, const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
);
2719 extern void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
);
2720 extern void AnswerCurrentQuestionWithResourceRecord(mDNS
*const m
, CacheRecord
*const rr
, const QC_result AddRecord
);
2722 // For now this AutoTunnel stuff is specific to Mac OS X.
2723 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
2724 #if APPLE_OSX_mDNSResponder
2725 extern void AutoTunnelCallback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
);
2726 extern void AddNewClientTunnel(mDNS
*const m
, DNSQuestion
*const q
);
2727 extern void SetupLocalAutoTunnelInterface_internal(mDNS
*const m
);
2728 extern void UpdateAutoTunnelDomainStatuses(const mDNS
*const m
);
2731 // ***************************************************************************
2733 #pragma mark - Compile-Time assertion checks
2736 // Some C compiler cleverness. We can make the compiler check certain things for
2737 // us, and report compile-time errors if anything is wrong. The usual way to do
2738 // this would be to use a run-time "if" statement, but then you don't find out
2739 // what's wrong until you run the software. This way, if the assertion condition
2740 // is false, the array size is negative, and the complier complains immediately.
2742 struct CompileTimeAssertionChecks_mDNS
2744 // Check that the compiler generated our on-the-wire packet format structure definitions
2745 // properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
2746 char assert0
[(sizeof(rdataSRV
) == 262 ) ? 1 : -1];
2747 char assert1
[(sizeof(DNSMessageHeader
) == 12 ) ? 1 : -1];
2748 char assert2
[(sizeof(DNSMessage
) == 12+AbsoluteMaxDNSMessageData
) ? 1 : -1];
2749 char assert3
[(sizeof(mDNSs8
) == 1 ) ? 1 : -1];
2750 char assert4
[(sizeof(mDNSu8
) == 1 ) ? 1 : -1];
2751 char assert5
[(sizeof(mDNSs16
) == 2 ) ? 1 : -1];
2752 char assert6
[(sizeof(mDNSu16
) == 2 ) ? 1 : -1];
2753 char assert7
[(sizeof(mDNSs32
) == 4 ) ? 1 : -1];
2754 char assert8
[(sizeof(mDNSu32
) == 4 ) ? 1 : -1];
2755 char assert9
[(sizeof(mDNSOpaque16
) == 2 ) ? 1 : -1];
2756 char assertA
[(sizeof(mDNSOpaque32
) == 4 ) ? 1 : -1];
2757 char assertB
[(sizeof(mDNSOpaque128
) == 16 ) ? 1 : -1];
2758 char assertC
[(sizeof(CacheRecord
) >= sizeof(CacheGroup
) ) ? 1 : -1];
2759 char assertD
[(sizeof(int) >= 4 ) ? 1 : -1];
2760 char assertE
[(StandardAuthRDSize
>= 256 ) ? 1 : -1];
2762 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
2763 // other overly-large structures instead of having a pointer to them, can inadvertently
2764 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
2765 char sizecheck_ResourceRecord
[(sizeof(ResourceRecord
) <= 40) ? 1 : -1];
2766 char sizecheck_AuthRecord
[(sizeof(AuthRecord
) <= 1290) ? 1 : -1];
2767 char sizecheck_CacheRecord
[(sizeof(CacheRecord
) <= 170) ? 1 : -1];
2768 char sizecheck_CacheGroup
[(sizeof(CacheGroup
) <= 170) ? 1 : -1];
2769 char sizecheck_DNSQuestion
[(sizeof(DNSQuestion
) <= 560) ? 1 : -1];
2770 char sizecheck_ZoneData
[(sizeof(ZoneData
) <= 1600) ? 1 : -1];
2771 char sizecheck_NATTraversalInfo
[(sizeof(NATTraversalInfo
) <= 140) ? 1 : -1];
2772 char sizecheck_HostnameInfo
[(sizeof(HostnameInfo
) <= 3000) ? 1 : -1];
2773 char sizecheck_DNSServer
[(sizeof(DNSServer
) <= 300) ? 1 : -1];
2774 char sizecheck_NetworkInterfaceInfo
[(sizeof(NetworkInterfaceInfo
) <= 4000) ? 1 : -1];
2775 char sizecheck_ServiceRecordSet
[(sizeof(ServiceRecordSet
) <= 5700) ? 1 : -1];
2776 char sizecheck_DomainAuthInfo
[(sizeof(DomainAuthInfo
) <= 6000) ? 1 : -1];
2777 char sizecheck_ServiceInfoQuery
[(sizeof(ServiceInfoQuery
) <= 2900) ? 1 : -1];
2778 #if APPLE_OSX_mDNSResponder
2779 char sizecheck_ClientTunnel
[(sizeof(ClientTunnel
) <= 1040) ? 1 : -1];
2783 // ***************************************************************************