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.577 2009/07/16 00:34:18 cheshire
58 <rdar://problem/6434656> Sleep Proxy: Put owner OPT records in multicast announcements to avoid conflicts
59 Additional refinement: If we didn't register with a Sleep Proxy when going to sleep,
60 we don't need to include our OWNER option in our packets when we re-awaken
62 Revision 1.576 2009/07/15 23:35:37 cheshire
63 <rdar://problem/6434656> Sleep Proxy: Put owner OPT records in multicast announcements to avoid conflicts
65 Revision 1.575 2009/07/11 01:57:00 cheshire
66 <rdar://problem/6613674> Sleep Proxy: Add support for using sleep proxy in local network interface hardware
67 Added declaration of ActivateLocalProxy
69 Revision 1.574 2009/07/10 23:03:17 cheshire
70 Made SecondLabel(X) more defensive, to guard against the case where the name doesn't have a second label
72 Revision 1.573 2009/06/30 18:17:45 herscher
73 Add to 64 bit macro check for 64 bit Windows OSes
75 Revision 1.572 2009/06/27 00:52:27 cheshire
76 <rdar://problem/6959273> mDNSResponder taking up 13% CPU with 400 KBps incoming bonjour requests
77 Removed overly-complicate and ineffective multi-packet known-answer snooping code
78 (Bracketed it with "#if ENABLE_MULTI_PACKET_QUERY_SNOOPING" for now; will delete actual code later)
80 Revision 1.571 2009/06/26 01:55:54 cheshire
81 <rdar://problem/6890712> mDNS: iChat's Buddy photo always appears as the "shadow person" over Bonjour
82 Additional refinements -- except for the case of explicit queries for record types we don't have (for names we own),
83 add additional NSEC records only when there's space to do that without having to generate an additional packet
85 Revision 1.570 2009/06/24 22:14:21 cheshire
86 <rdar://problem/6911445> Plugging and unplugging the power cable shouldn't cause a network change event
88 Revision 1.569 2009/06/03 23:07:12 cheshire
89 <rdar://problem/6890712> mDNS: iChat's Buddy photo always appears as the "shadow person" over Bonjour
90 Large records were not being added in cases where an NSEC record was also required
92 Revision 1.568 2009/05/19 22:37:04 cheshire
93 <rdar://problem/6903507> Sleep Proxy: Retransmission logic not working reliably on quiet networks
94 Added NextScheduledSPRetry field
96 Revision 1.567 2009/05/13 17:25:33 mkrochma
97 <rdar://problem/6879926> Should not schedule maintenance wake when machine has no advertised services
98 Sleep proxy client should only look for services being advertised via Multicast
100 Revision 1.566 2009/05/12 23:09:24 cheshire
101 <rdar://problem/6879926> Should not schedule maintenance wake when machine has no advertised services
102 Declare mDNSCoreHaveAdvertisedServices routine so it can be called from daemon.c
104 Revision 1.565 2009/05/09 00:10:58 jessic2
105 Change expected size of NetworkInterfaceInfo to fix build failure
107 Revision 1.564 2009/05/07 23:31:26 cheshire
108 <rdar://problem/6601427> Sleep Proxy: Retransmit and retry Sleep Proxy Server requests
109 Added NextSPSAttempt and NextSPSAttemptTime fields to NetworkInterfaceInfo_struct
111 Revision 1.563 2009/04/24 21:06:38 cheshire
112 Added comment about UDP length field (includes UDP header, so minimum value is 8 bytes)
114 Revision 1.562 2009/04/24 00:22:23 cheshire
115 <rdar://problem/3476350> Return negative answers when host knows authoritatively that no answer exists
116 Added definition of rdataNSEC
118 Revision 1.561 2009/04/23 22:06:29 cheshire
119 Added CacheRecord and InterfaceID parameters to MakeNegativeCacheRecord, in preparation for:
120 <rdar://problem/3476350> Return negative answers when host knows authoritatively that no answer exists
122 Revision 1.560 2009/04/23 21:54:50 cheshire
125 Revision 1.559 2009/04/22 00:37:38 cheshire
126 <rdar://problem/6814427> Remove unused kDNSType_MAC
128 Revision 1.558 2009/04/21 23:36:25 cheshire
129 <rdar://problem/6814427> Remove unused kDNSType_MAC
131 Revision 1.557 2009/04/15 20:42:51 mcguire
132 <rdar://problem/6768947> uDNS: Treat RCODE 5 (Refused) responses as failures
134 Revision 1.556 2009/04/11 00:19:43 jessic2
135 <rdar://problem/4426780> Daemon: Should be able to turn on LogOperation dynamically
137 Revision 1.555 2009/04/01 21:12:27 herscher
138 <rdar://problem/5925472> Current Bonjour code does not compile on Windows.
140 Revision 1.554 2009/04/01 17:50:11 mcguire
143 Revision 1.553 2009/03/26 03:59:00 jessic2
144 Changes for <rdar://problem/6492552&6492593&6492609&6492613&6492628&6492640&6492699>
146 Revision 1.552 2009/03/20 23:53:03 jessic2
147 <rdar://problem/6646228> SIGHUP should restart all in-progress queries
149 Revision 1.551 2009/03/18 20:41:04 cheshire
150 Added definition of the all-ones mDNSOpaque16 ID
152 Revision 1.550 2009/03/17 19:10:29 mcguire
153 Fix sizechecks for x86_64
155 Revision 1.549 2009/03/17 01:22:56 cheshire
156 <rdar://problem/6601427> Sleep Proxy: Retransmit and retry Sleep Proxy Server requests
157 Initial support for resolving up to three Sleep Proxies in parallel
159 Revision 1.548 2009/03/14 01:42:56 mcguire
160 <rdar://problem/5457116> BTMM: Fix issues with multiple .Mac accounts on the same machine
162 Revision 1.547 2009/03/10 01:14:30 cheshire
163 Sleep Proxies with invalid names need to be ignored (score 10000),
164 not treated as "Sleep Proxy of last resort" (score 9999)
166 Revision 1.546 2009/03/06 23:51:51 mcguire
167 Fix broken build by defining DiscardPort
169 Revision 1.545 2009/03/06 22:39:23 cheshire
170 <rdar://problem/6655850> Ignore prototype base stations when picking Sleep Proxy to register with
172 Revision 1.544 2009/03/04 01:33:30 cheshire
173 Add m->ProxyRecords counter
175 Revision 1.543 2009/03/03 23:04:43 cheshire
176 For clarity, renamed "MAC" field to "HMAC" (Host MAC, as opposed to Interface MAC)
178 Revision 1.542 2009/03/03 22:51:53 cheshire
179 <rdar://problem/6504236> Sleep Proxy: Waking on same network but different interface will cause conflicts
181 Revision 1.541 2009/03/03 00:45:19 cheshire
182 Added m->PrimaryMAC field
184 Revision 1.540 2009/02/27 02:56:57 cheshire
185 Moved struct SearchListElem definition from uDNS.c into mDNSEmbeddedAPI.h
187 Revision 1.539 2009/02/17 23:29:01 cheshire
188 Throttle logging to a slower rate when running on SnowLeopard
190 Revision 1.538 2009/02/11 02:31:57 cheshire
191 Moved SystemWakeOnLANEnabled from mDNSMacOSX.h, so it's accessible to mDNSCore routines
193 Revision 1.537 2009/02/07 02:51:48 cheshire
194 <rdar://problem/6084043> Sleep Proxy: Need to adopt IOPMConnection
195 Added new functions and timing variables
197 Revision 1.536 2009/01/30 23:50:31 cheshire
198 Added LastLabel() routine to get the last label of a domainname
200 Revision 1.535 2009/01/23 00:38:36 mcguire
201 <rdar://problem/5570906> BTMM: Doesn't work with Linksys WRT54GS firmware 4.71.1
203 Revision 1.534 2009/01/22 02:14:25 cheshire
204 <rdar://problem/6515626> Sleep Proxy: Set correct target MAC address, instead of all zeroes
206 Revision 1.533 2009/01/21 03:43:57 mcguire
207 <rdar://problem/6511765> BTMM: Add support for setting kDNSServiceErr_NATPortMappingDisabled in DynamicStore
209 Revision 1.532 2009/01/16 19:50:36 cheshire
210 Oops. Fixed definition of SleepProxyServiceType.
212 Revision 1.531 2009/01/16 19:48:09 cheshire
213 Added definition of SleepProxyServiceType
215 Revision 1.530 2009/01/15 00:22:49 mcguire
216 <rdar://problem/6437092> NAT-PMP: mDNSResponder needs to listen on 224.0.0.1:5350/UDP with REUSEPORT
218 Revision 1.529 2009/01/13 00:31:44 cheshire
219 Fixed off-by-one error in computing the implicit limit pointer in the "DomainNameLength(name)" macro
221 Revision 1.528 2009/01/10 01:43:52 cheshire
222 Changed misleading function name 'AnsweredLOQ' to more informative 'AnsweredLocalQ'
224 Revision 1.527 2008/12/12 01:23:19 cheshire
225 Added m->SPSProxyListChanged state variable to flag when we need to update our BPF filter program
227 Revision 1.526 2008/12/12 00:51:14 cheshire
228 Added structure definitions for IPv6Header, etc.
230 Revision 1.525 2008/12/10 02:18:31 cheshire
231 Increased MaxMsg to 160 for showing longer TXT records in SIGINFO output
233 Revision 1.524 2008/12/10 01:49:39 cheshire
234 Fixes for alignment issues on ARMv5
236 Revision 1.523 2008/12/05 02:35:24 mcguire
237 <rdar://problem/6107390> Write to the DynamicStore when a Sleep Proxy server is available on the network
239 Revision 1.522 2008/12/04 21:08:51 mcguire
240 <rdar://problem/6116863> mDNS: Provide mechanism to disable Multicast advertisements
242 Revision 1.521 2008/12/04 02:19:24 cheshire
245 Revision 1.520 2008/11/26 20:28:05 cheshire
246 Added new SSHPort constant
248 Revision 1.519 2008/11/25 22:46:30 cheshire
249 For ease of code searching, renamed ZoneData field of ServiceRecordSet_struct from "nta" to "srs_nta"
251 Revision 1.518 2008/11/25 05:07:15 cheshire
252 <rdar://problem/6374328> Advertise Sleep Proxy metrics in service name
254 Revision 1.517 2008/11/20 01:51:19 cheshire
255 Exported RecreateNATMappings so it's callable from other files
257 Revision 1.516 2008/11/16 16:49:25 cheshire
258 <rdar://problem/6375808> LLQs broken in mDNSResponder-184
259 DNSOpt_LLQData_Space was incorrectly defined to be 18 instead of 22
261 Revision 1.515 2008/11/14 20:59:41 cheshire
262 Added mDNSEthAddressIsZero(A) macro
264 Revision 1.514 2008/11/14 02:17:41 cheshire
265 Added NextScheduledSPS task scheduling variable
267 Revision 1.513 2008/11/14 00:47:19 cheshire
268 Added TimeRcvd and TimeExpire fields to AuthRecord_struct
270 Revision 1.512 2008/11/14 00:00:53 cheshire
271 After client machine wakes up, Sleep Proxy machine need to remove any records
272 it was temporarily holding as proxy for that client
274 Revision 1.511 2008/11/13 19:04:44 cheshire
275 Added definition of OwnerOptData
277 Revision 1.510 2008/11/06 23:48:32 cheshire
278 Changed SleepProxyServerType to mDNSu8
280 Revision 1.509 2008/11/04 23:06:50 cheshire
281 Split RDataBody union definition into RDataBody and RDataBody2, and removed
282 SOA from the normal RDataBody union definition, saving 270 bytes per AuthRecord
284 Revision 1.508 2008/11/04 22:21:43 cheshire
285 Changed zone field of AuthRecord_struct from domainname to pointer, saving 252 bytes per AuthRecord
287 Revision 1.507 2008/11/04 22:13:43 cheshire
288 Made RDataBody parameter to GetRRDisplayString_rdb "const"
290 Revision 1.506 2008/11/04 20:06:19 cheshire
291 <rdar://problem/6186231> Change MAX_DOMAIN_NAME to 256
293 Revision 1.505 2008/11/03 23:49:47 mkrochma
294 Increase NATMAP_DEFAULT_LEASE to 2 hours so we do maintenance wake less often
296 Revision 1.504 2008/10/31 22:55:04 cheshire
297 Initial support for structured SPS names
299 Revision 1.503 2008/10/24 23:58:47 cheshire
300 Ports should be mDNSIPPort, not mDNSOpaque16
302 Revision 1.502 2008/10/23 22:25:56 cheshire
303 Renamed field "id" to more descriptive "updateid"
305 Revision 1.501 2008/10/22 22:22:27 cheshire
306 Added packet structure definitions
308 Revision 1.500 2008/10/22 19:55:35 cheshire
309 Miscellaneous fixes; renamed FindFirstAnswerInCache to FindSPSInCache
311 Revision 1.499 2008/10/22 17:15:47 cheshire
312 Updated definitions of mDNSIPv4AddressIsZero/mDNSIPv4AddressIsOnes, etc.
314 Revision 1.498 2008/10/22 01:01:52 cheshire
315 Added onesEthAddr constant, used for sending ARP broadcasts
317 Revision 1.497 2008/10/21 00:51:11 cheshire
318 Added declaration of mDNSPlatformSetBPF(), used by uds_daemon.c to pass BPF fd to mDNSMacOSX.c
320 Revision 1.496 2008/10/16 22:38:52 cheshire
321 Added declaration of mDNSCoreReceiveRawPacket()
323 Revision 1.495 2008/10/15 22:53:51 cheshire
324 Removed unused "#define LocalReverseMapDomain"
326 Revision 1.494 2008/10/15 20:37:17 cheshire
327 Added "#define DNSOpt_Lease_Space 19"
329 Revision 1.493 2008/10/14 21:37:56 cheshire
330 Removed unnecessary m->BeSleepProxyServer variable
332 Revision 1.492 2008/10/14 20:26:36 cheshire
333 Added definition of a new kDNSType_MAC rdata type
335 Revision 1.491 2008/10/09 22:29:04 cheshire
336 Added "mDNSEthAddr MAC" to NetworkInterfaceInfo_struct
338 Revision 1.490 2008/10/09 21:39:20 cheshire
339 Update list of DNS types
341 Revision 1.489 2008/10/09 18:59:19 cheshire
342 Added NetWakeResolve code, removed unused m->SendDeregistrations and m->SendImmediateAnswers
344 Revision 1.488 2008/10/08 01:02:03 cheshire
345 Added mDNS_SetupQuestion() convenience function
347 Revision 1.487 2008/10/07 21:41:57 mcguire
348 Increase sizecheck limits to account for DNSQuestion added to NetworkInterfaceInfo_struct in 64bit builds
350 Revision 1.486 2008/10/07 15:56:24 cheshire
351 Increase sizecheck limits to account for DNSQuestion added to NetworkInterfaceInfo_struct
353 Revision 1.485 2008/10/04 00:48:37 cheshire
354 Added DNSQuestion to NetworkInterfaceInfo_struct, used for browsing for Sleep Proxy Servers
356 Revision 1.484 2008/10/04 00:01:45 cheshire
357 Move NetworkInterfaceInfo_struct further down in file (we'll need to add a DNSQuestion to it later)
359 Revision 1.483 2008/10/03 23:28:41 cheshire
360 Added declaration of mDNSPlatformSendRawPacket
362 Revision 1.482 2008/10/03 17:30:05 cheshire
363 Added declaration of mDNS_ConfigChanged(mDNS *const m);
365 Revision 1.481 2008/10/02 22:38:58 cheshire
366 Added SleepProxyServer fields, and mDNSCoreBeSleepProxyServer() call for turning SleepProxyServer on and off
368 Revision 1.480 2008/10/01 21:22:17 cheshire
369 Added NetWake field to NetworkInterfaceInfo structure, to signal when Wake-On-Magic-Packet is enabled for that interface
371 Revision 1.479 2008/09/29 20:12:37 cheshire
372 Rename 'AnswerLocalQuestions' to more descriptive 'AnswerLocalOnlyQuestions' and 'AnsweredLocalQ' to 'AnsweredLOQ'
374 Revision 1.478 2008/09/23 02:37:10 cheshire
375 Added FirstLabel/SecondLabel macros
377 Revision 1.477 2008/09/20 00:34:22 mcguire
378 <rdar://problem/6129039> BTMM: Add support for WANPPPConnection
380 Revision 1.476 2008/09/05 22:22:01 cheshire
381 Move "UDPSocket *LocalSocket" field to more logical place in DNSQuestion_struct
383 Revision 1.475 2008/07/25 22:34:11 mcguire
384 fix sizecheck issues for 64bit
386 Revision 1.474 2008/07/24 20:23:03 cheshire
387 <rdar://problem/3988320> Should use randomized source ports and transaction IDs to avoid DNS cache poisoning
389 Revision 1.473 2008/07/18 21:37:42 mcguire
390 <rdar://problem/5736845> BTMM: alternate SSDP queries between multicast & unicast
392 Revision 1.472 2008/07/01 01:39:59 mcguire
393 <rdar://problem/5823010> 64-bit fixes
395 Revision 1.471 2008/06/26 17:24:11 mkrochma
396 <rdar://problem/5450912> BTMM: Stop listening on UDP 5351 for NAT Status Announcements
398 Revision 1.470 2008/06/19 01:20:49 mcguire
399 <rdar://problem/4206534> Use all configured DNS servers
401 Revision 1.469 2008/03/07 18:56:02 cheshire
402 <rdar://problem/5777647> dnsbugtest query every three seconds when source IP address of response doesn't match
404 Revision 1.468 2008/03/06 02:48:34 mcguire
405 <rdar://problem/5321824> write status to the DS
407 Revision 1.467 2008/02/26 20:48:46 cheshire
408 Need parentheses around use of macro argument in mDNS_TimeNow_NoLock(m)
410 Revision 1.466 2008/02/21 21:36:32 cheshire
411 Updated comment about record type values (kDNSRecordTypePacketAns/Auth/Add)
413 Revision 1.465 2008/02/20 00:39:05 mcguire
414 <rdar://problem/5427102> Some device info XML blobs too large
416 Revision 1.464 2008/01/31 23:33:29 mcguire
417 <rdar://problem/5614450> changes to build using gcc 4.2 with -Werror
419 Revision 1.463 2007/12/17 23:53:25 cheshire
420 Added DNSDigest_SignMessageHostByteOrder, for signing messages not yet converted to network byte order
422 Revision 1.462 2007/12/17 23:48:29 cheshire
423 DNSDigest_SignMessage doesn't need to return a result -- it already updates the 'end' parameter
425 Revision 1.461 2007/12/15 00:18:51 cheshire
426 Renamed question->origLease to question->ReqLease
428 Revision 1.460 2007/12/14 23:55:28 cheshire
429 Moved "struct tcpInfo_t" definition from uDNS.c to mDNSEmbeddedAPI.h
431 Revision 1.459 2007/12/07 22:40:34 cheshire
432 Rename 'LocalAnswer' to more descriptive 'AnsweredLocalQ'
434 Revision 1.458 2007/12/07 00:45:58 cheshire
435 <rdar://problem/5526800> BTMM: Need to clean up registrations on shutdown
437 Revision 1.457 2007/12/06 00:22:27 mcguire
438 <rdar://problem/5604567> BTMM: Doesn't work with Linksys WAG300N 1.01.06 (sending from 1026/udp)
440 Revision 1.456 2007/12/05 01:45:35 cheshire
441 Renamed markedForDeletion -> MarkedForDeletion
443 Revision 1.455 2007/12/01 01:21:27 jgraessley
444 <rdar://problem/5623140> mDNSResponder unicast DNS improvements
446 Revision 1.454 2007/12/01 00:34:03 cheshire
447 Fixes from Bob Bradley for building on EFI
449 Revision 1.453 2007/10/29 23:51:22 cheshire
450 Added comment about NATTraversalInfo ExternalAddress field
452 Revision 1.452 2007/10/29 18:13:40 cheshire
453 Added Question_uDNS macro, analogous to AuthRecord_uDNS macro
455 Revision 1.451 2007/10/26 23:42:57 cheshire
456 Removed unused "mDNSs32 expire" field from ServiceRecordSet_struct
458 Revision 1.450 2007/10/26 22:24:08 cheshire
459 Added AuthRecord_uDNS() macro to determine when a given AuthRecord needs to be registered via unicast DNS
461 Revision 1.449 2007/10/25 20:48:47 cheshire
462 For naming consistency (with AuthRecord's UpdateServer) renamed 'ns' to 'SRSUpdateServer'
464 Revision 1.448 2007/10/22 22:19:44 cheshire
465 Tidied up code alignment
467 Revision 1.447 2007/10/22 19:40:30 cheshire
468 <rdar://problem/5519458> BTMM: Machines don't appear in the sidebar on wake from sleep
469 Made subroutine mDNSPlatformSourceAddrForDest(mDNSAddr *const src, const mDNSAddr *const dst)
471 Revision 1.446 2007/10/17 22:49:54 cheshire
472 <rdar://problem/5519458> BTMM: Machines don't appear in the sidebar on wake from sleep
474 Revision 1.445 2007/10/17 22:37:23 cheshire
475 <rdar://problem/5536979> BTMM: Need to create NAT port mapping for receiving LLQ events
477 Revision 1.444 2007/09/29 03:14:52 cheshire
478 <rdar://problem/5513168> BTMM: mDNSResponder memory corruption in GetAuthInfoForName_internal
479 Added AutoTunnelUnregistered macro to check state of DomainAuthInfo AuthRecords
481 Revision 1.443 2007/09/27 21:21:39 cheshire
482 Export CompleteDeregistration so it's callable from other files
484 Revision 1.442 2007/09/27 00:25:39 cheshire
485 Added ttl_seconds parameter to MakeNegativeCacheRecord in preparation for:
486 <rdar://problem/4947392> uDNS: Use SOA to determine TTL for negative answers
488 Revision 1.441 2007/09/26 23:17:49 cheshire
489 Get rid of unused kWideAreaTTL constant
491 Revision 1.440 2007/09/26 22:06:02 cheshire
492 <rdar://problem/5507399> BTMM: No immediate failure notifications for BTMM names
494 Revision 1.439 2007/09/21 21:12:36 cheshire
495 DNSDigest_SignMessage does not need separate "mDNSu16 *numAdditionals" parameter
497 Revision 1.438 2007/09/19 20:32:09 cheshire
498 Export GetAuthInfoForName so it's callable from other files
500 Revision 1.437 2007/09/18 21:42:29 cheshire
501 To reduce programming mistakes, renamed ExtPort to RequestedPort
503 Revision 1.436 2007/09/14 21:26:08 cheshire
504 <rdar://problem/5482627> BTMM: Need to manually avoid port conflicts when using UPnP gateways
506 Revision 1.435 2007/09/13 00:16:41 cheshire
507 <rdar://problem/5468706> Miscellaneous NAT Traversal improvements
509 Revision 1.434 2007/09/12 23:03:07 cheshire
510 <rdar://problem/5476978> DNSServiceNATPortMappingCreate callback not giving correct interface index
512 Revision 1.433 2007/09/12 22:19:28 cheshire
513 <rdar://problem/5476977> Need to listen for port 5350 NAT-PMP announcements
515 Revision 1.432 2007/09/12 19:22:19 cheshire
516 Variable renaming in preparation for upcoming fixes e.g. priv/pub renamed to intport/extport
517 Made NAT Traversal packet handlers take typed data instead of anonymous "mDNSu8 *" byte pointers
519 Revision 1.431 2007/09/11 19:19:16 cheshire
520 Correct capitalization of "uPNP" to "UPnP"
522 Revision 1.430 2007/09/10 22:06:50 cheshire
523 Rename uptime => upseconds and LastNATUptime => LastNATupseconds to make it clear these time values are in seconds
525 Revision 1.429 2007/09/07 21:16:58 cheshire
526 Add new symbol "NATPMPAnnouncementPort" (5350)
528 Revision 1.428 2007/09/05 21:48:01 cheshire
529 <rdar://problem/5385864> BTMM: mDNSResponder flushes wide-area Bonjour records after an hour for a zone.
530 Now that we're respecting the TTL of uDNS records in the cache, the LLQ maintenance code needs
531 to update the cache lifetimes of all relevant records every time it successfully renews an LLQ,
532 otherwise those records will expire and vanish from the cache.
534 Revision 1.427 2007/09/05 20:47:12 cheshire
535 Tidied up alignment of code layout
537 Revision 1.426 2007/09/04 20:37:06 cheshire
538 <rdar://problem/5457287> mDNSResponder taking up 100% CPU in ReissueBlockedQuestions
539 Reorder fields into more logical order, with AuthInfo before DuplicateOf
541 Revision 1.425 2007/08/31 19:53:14 cheshire
542 <rdar://problem/5431151> BTMM: IPv6 address lookup should not succeed if autotunnel cannot be setup
543 If AutoTunnel setup fails, the code now generates a fake NXDomain error saying that the requested AAAA record does not exist
545 Revision 1.424 2007/08/31 18:49:49 vazquez
546 <rdar://problem/5393719> BTMM: Need to properly deregister when stopping BTMM
548 Revision 1.423 2007/08/31 00:04:28 cheshire
549 Added comment explaining deltime in DomainAuthInfo structure
551 Revision 1.422 2007/08/28 23:58:42 cheshire
552 Rename HostTarget -> AutoTarget
554 Revision 1.421 2007/08/27 20:30:43 cheshire
555 Only include TunnelClients list when building for OS X
557 Revision 1.420 2007/08/23 21:47:09 vazquez
558 <rdar://problem/5427316> BTMM: mDNSResponder sends NAT-PMP packets on public network
559 make sure we clean up port mappings on base stations by sending a lease value of 0,
560 and only send NAT-PMP packets on private networks; also save some memory by
561 not using packet structs in NATTraversals.
563 Revision 1.419 2007/08/08 21:07:47 vazquez
564 <rdar://problem/5244687> BTMM: Need to advertise model information via wide-area bonjour
566 Revision 1.418 2007/08/01 16:09:13 cheshire
567 Removed unused NATTraversalInfo substructure from AuthRecord; reduced structure sizecheck values accordingly
569 Revision 1.417 2007/08/01 03:04:59 cheshire
570 Add NATTraversalInfo structures to HostnameInfo and DomainAuthInfo
572 Revision 1.416 2007/08/01 00:04:13 cheshire
573 <rdar://problem/5261696> Crash in tcpKQSocketCallback
574 Half-open TCP connections were not being cancelled properly
576 Revision 1.415 2007/07/31 02:28:35 vazquez
577 <rdar://problem/3734269> NAT-PMP: Detect public IP address changes and base station reboot
579 Revision 1.414 2007/07/30 23:34:19 cheshire
580 Remove unused "udpSock" from DNSQuestion
582 Revision 1.413 2007/07/28 01:25:56 cheshire
583 <rdar://problem/4780038> BTMM: Add explicit UDP event port to LLQ setup request, to fix LLQs not working behind NAT
585 Revision 1.412 2007/07/27 23:57:23 cheshire
586 Added compile-time structure size checks
588 Revision 1.411 2007/07/27 22:50:08 vazquez
589 Allocate memory for UPnP request and reply buffers instead of using arrays
591 Revision 1.410 2007/07/27 19:37:19 cheshire
592 Moved AutomaticBrowseDomainQ into main mDNS object
594 Revision 1.409 2007/07/27 19:30:39 cheshire
595 Changed mDNSQuestionCallback parameter from mDNSBool to QC_result,
596 to properly reflect tri-state nature of the possible responses
598 Revision 1.408 2007/07/27 18:44:01 cheshire
599 Rename "AnswerQuestionWithResourceRecord" to more informative "AnswerCurrentQuestionWithResourceRecord"
601 Revision 1.407 2007/07/26 21:19:26 vazquez
602 Retry port mapping with incremented port number (up to max) in order to handle
603 port mapping conflicts on UPnP gateways
605 Revision 1.406 2007/07/25 22:19:59 cheshire
606 ClientTunnel structure also needs a rmt_outer_port field
608 Revision 1.405 2007/07/25 03:05:02 vazquez
610 <rdar://problem/5338913> LegacyNATTraversal: UPnP heap overflow
611 <rdar://problem/5338933> LegacyNATTraversal: UPnP stack buffer overflow
612 and a myriad of other security problems
614 Revision 1.404 2007/07/24 20:22:07 cheshire
615 Add AutoTunnelHostAddrActive flag
617 Revision 1.403 2007/07/24 04:14:29 cheshire
618 <rdar://problem/5356281> LLQs not working in with NAT Traversal
620 Revision 1.402 2007/07/21 00:54:44 cheshire
621 <rdar://problem/5344576> Delay IPv6 address callback until AutoTunnel route and policy is configured
623 Revision 1.401 2007/07/20 20:01:38 cheshire
624 Rename "mDNS_DomainTypeBrowseLegacy" as "mDNS_DomainTypeBrowseAutomatic"
626 Revision 1.400 2007/07/20 00:54:18 cheshire
627 <rdar://problem/4641118> Need separate SCPreferences for per-user .Mac settings
629 Revision 1.399 2007/07/18 03:22:35 cheshire
630 SetupLocalAutoTunnelInterface_internal needs to be callable from uDNS.c
632 Revision 1.398 2007/07/18 02:26:56 cheshire
633 Don't need to declare UpdateTunnels here
635 Revision 1.397 2007/07/18 01:03:50 cheshire
636 <rdar://problem/5303834> Automatically configure IPSec policy when resolving services
637 Add list of client tunnels so we can automatically reconfigure when local address changes
639 Revision 1.396 2007/07/16 23:54:48 cheshire
640 <rdar://problem/5338850> Crash when removing or changing DNS keys
642 Revision 1.395 2007/07/16 20:12:33 vazquez
643 <rdar://problem/3867231> LegacyNATTraversal: Need complete rewrite
645 Revision 1.394 2007/07/12 02:51:27 cheshire
646 <rdar://problem/5303834> Automatically configure IPSec policy when resolving services
648 Revision 1.393 2007/07/11 23:43:42 cheshire
649 Rename PurgeCacheResourceRecord to mDNS_PurgeCacheResourceRecord
651 Revision 1.392 2007/07/11 22:44:40 cheshire
652 <rdar://problem/5328801> SIGHUP should purge the cache
654 Revision 1.391 2007/07/11 20:30:45 cheshire
655 <rdar://problem/5304766> Register IPSec tunnel with IPv4-only hostname and create NAT port mappings
656 Added AutoTunnelTarget and AutoTunnelService to DomainAuthInfo structure
658 Revision 1.390 2007/07/11 18:56:55 cheshire
659 Added comments about AutoTunnelHostAddr and AutoTunnelLabel
661 Revision 1.389 2007/07/11 02:44:03 cheshire
662 <rdar://problem/5303807> Register IPv6-only hostname and don't create port mappings for AutoTunnel services
663 Added AutoTunnel fields to structures
665 Revision 1.388 2007/07/10 01:53:18 cheshire
666 <rdar://problem/5196524> uDNS: mDNSresponder is leaking TCP connections to DNS server
667 AuthRecord, ServiceRecordSet, and DNSQuestion structures need tcpInfo_t pointers
668 so they can keep track of what TCP connections they open
670 Revision 1.387 2007/07/06 18:55:15 cheshire
671 Add explicit NextScheduledNATOp scheduling variable
673 Revision 1.386 2007/07/03 20:54:11 cheshire
674 Tidied up code layout of NATTraversalInfo_struct fields and comments
676 Revision 1.385 2007/07/03 00:40:23 vazquez
677 More changes for <rdar://problem/5301908> Clean up NAT state machine (necessary for 6 other fixes)
678 Safely deal with packet replies and client callbacks
680 Revision 1.384 2007/06/29 00:08:07 vazquez
681 <rdar://problem/5301908> Clean up NAT state machine (necessary for 6 other fixes)
683 Revision 1.383 2007/06/20 01:10:12 cheshire
684 <rdar://problem/5280520> Sync iPhone changes into main mDNSResponder code
686 Revision 1.382 2007/06/19 20:31:59 cheshire
687 Add DNSServer_Disabled state
688 Add mDNSInterfaceID for DNS servers reachable over specific interfaces
690 Revision 1.381 2007/06/15 18:11:16 cheshire
691 <rdar://problem/5174466> mDNSResponder crashed in memove() near end of MobileSafari stress test
692 Made AssignDomainName more defensive when source name is garbage
694 Revision 1.380 2007/05/25 00:04:51 cheshire
695 Added comment explaining rdlength
697 Revision 1.379 2007/05/21 18:04:40 cheshire
698 Updated comments -- port_mapping_create_reply renamed to port_mapping_reply
700 Revision 1.378 2007/05/17 19:11:46 cheshire
703 Revision 1.377 2007/05/15 00:43:33 cheshire
704 Remove unused regState_Cancelled
706 Revision 1.376 2007/05/14 23:51:49 cheshire
707 Added constants MAX_REVERSE_MAPPING_NAME_V4 and MAX_REVERSE_MAPPING_NAME_V6
709 Revision 1.375 2007/05/10 21:19:18 cheshire
710 Rate-limit DNS test queries to at most one per three seconds
711 (useful when we have a dozen active WAB queries, and then we join a new network)
713 Revision 1.374 2007/05/07 22:07:47 cheshire
714 <rdar://problem/4738025> Enhance GetLargeResourceRecord to decompress more record types
716 Revision 1.373 2007/05/07 20:43:45 cheshire
717 <rdar://problem/4241419> Reduce the number of queries and announcements
719 Revision 1.372 2007/05/04 22:15:29 cheshire
720 Get rid of unused q->RestartTime
722 Revision 1.371 2007/05/03 22:40:37 cheshire
723 <rdar://problem/4669229> mDNSResponder ignores bogus null target in SRV record
725 Revision 1.370 2007/05/02 22:18:09 cheshire
726 Renamed NATTraversalInfo_struct context to NATTraversalContext
728 Revision 1.369 2007/05/01 21:21:42 cheshire
729 Add missing parentheses in LEASE_OPT_RDLEN definition
731 Revision 1.368 2007/04/30 21:33:38 cheshire
732 Fix crash when a callback unregisters a service while the UpdateSRVRecords() loop
733 is iterating through the m->ServiceRegistrations list
735 Revision 1.367 2007/04/28 01:31:59 cheshire
736 Improve debugging support for catching memory corruption problems
738 Revision 1.366 2007/04/27 19:28:02 cheshire
739 Any code that calls StartGetZoneData needs to keep a handle to the structure, so
740 it can cancel it if necessary. (First noticed as a crash in Apple Remote Desktop
741 -- it would start a query and then quickly cancel it, and then when
742 StartGetZoneData completed, it had a dangling pointer and crashed.)
744 Revision 1.365 2007/04/26 00:35:15 cheshire
745 <rdar://problem/5140339> uDNS: Domain discovery not working over VPN
746 Fixes to make sure results update correctly when connectivity changes (e.g. a DNS server
747 inside the firewall may give answers where a public one gives none, and vice versa.)
749 Revision 1.364 2007/04/24 02:07:42 cheshire
750 <rdar://problem/4246187> Identical client queries should reference a single shared core query
751 Deleted some more redundant code
753 Revision 1.363 2007/04/24 00:09:47 cheshire
754 Remove MappedV4 field from mDNS_struct (not actually used anywhere)
756 Revision 1.362 2007/04/22 06:02:02 cheshire
757 <rdar://problem/4615977> Query should immediately return failure when no server
759 Revision 1.361 2007/04/21 19:43:33 cheshire
760 Code tidying: represent NAT opcodes as bitwise combinations rather than numerical additions
762 Revision 1.360 2007/04/20 21:17:24 cheshire
763 For naming consistency, kDNSRecordTypeNegative should be kDNSRecordTypePacketNegative
765 Revision 1.359 2007/04/19 22:50:53 cheshire
766 <rdar://problem/4246187> Identical client queries should reference a single shared core query
768 Revision 1.358 2007/04/19 20:06:41 cheshire
769 Rename field 'Private' (sounds like a boolean) to more informative 'AuthInfo' (it's a DomainAuthInfo pointer)
771 Revision 1.357 2007/04/19 18:14:51 cheshire
772 In mDNS_AddSearchDomain_CString check for NULL pointer before calling MakeDomainNameFromDNSNameString()
774 Revision 1.356 2007/04/18 20:56:46 cheshire
775 Added mDNS_AddSearchDomain_CString macro
777 Revision 1.355 2007/04/17 19:21:29 cheshire
778 <rdar://problem/5140339> Domain discovery not working over VPN
780 Revision 1.354 2007/04/05 22:55:34 cheshire
781 <rdar://problem/5077076> Records are ending up in Lighthouse without expiry information
783 Revision 1.353 2007/04/05 20:40:37 cheshire
784 Remove unused mDNSPlatformTCPGetFlags()
786 Revision 1.352 2007/04/04 21:48:52 cheshire
787 <rdar://problem/4720694> Combine unicast authoritative answer list with multicast list
789 Revision 1.351 2007/04/04 01:27:45 cheshire
792 Revision 1.350 2007/04/04 00:03:26 cheshire
793 <rdar://problem/5089862> DNSServiceQueryRecord is returning kDNSServiceErr_NoSuchRecord for empty rdata
795 Revision 1.349 2007/04/03 19:37:58 cheshire
796 Rename mDNSAddrIsv4Private() to more precise mDNSAddrIsRFC1918()
798 Revision 1.348 2007/04/03 19:13:39 cheshire
799 Added macros mDNSSameIPPort, mDNSSameOpaque16, mDNSIPPortIsZero, mDNSOpaque16IsZero
801 Revision 1.347 2007/03/28 20:59:26 cheshire
802 <rdar://problem/4743285> Remove inappropriate use of IsPrivateV4Addr()
804 Revision 1.346 2007/03/28 15:56:37 cheshire
805 <rdar://problem/5085774> Add listing of NAT port mapping and GetAddrInfo requests in SIGINFO output
807 Revision 1.345 2007/03/22 19:29:23 cheshire
808 Add comment and check to ensure StandardAuthRDSize is at least 256 bytes
810 Revision 1.344 2007/03/22 18:31:48 cheshire
811 Put dst parameter first in mDNSPlatformStrCopy/mDNSPlatformMemCopy, like conventional Posix strcpy/memcpy
813 Revision 1.343 2007/03/22 00:49:20 cheshire
814 <rdar://problem/4848295> Advertise model information via Bonjour
816 Revision 1.342 2007/03/21 23:06:00 cheshire
817 Rename uDNS_HostnameInfo to HostnameInfo; deleted some unused fields
819 Revision 1.341 2007/03/21 20:44:11 cheshire
820 Added mDNSAddressIsv4LinkLocal macro
822 Revision 1.340 2007/03/21 00:30:02 cheshire
823 <rdar://problem/4789455> Multiple errors in DNameList-related code
825 Revision 1.339 2007/03/20 17:07:15 cheshire
826 Rename "struct uDNS_TCPSocket_struct" to "TCPSocket", "struct uDNS_UDPSocket_struct" to "UDPSocket"
828 Revision 1.338 2007/03/10 02:28:28 cheshire
829 Added comment explaining NATResponseHndlr
831 Revision 1.337 2007/03/10 02:02:58 cheshire
832 <rdar://problem/4961667> uDNS: LLQ refresh response packet causes cached records to be removed from cache
833 Eliminate unnecessary "InternalResponseHndlr responseCallback" function pointer
835 Revision 1.336 2007/02/28 22:12:24 cheshire
836 Get rid of unused mDNSVal32 and mDNSOpaque32fromIntVal
838 Revision 1.335 2007/02/28 21:49:07 cheshire
839 Off-by-one error: SameDomainLabelCS (case-sensitive) was stopping one character short of
840 the end of the label, e.g. it would fail to detect that "chesh1" and "chesh2" are different.
842 Revision 1.334 2007/02/28 01:44:26 cheshire
843 <rdar://problem/5027863> Byte order bugs in uDNS.c, uds_daemon.c, dnssd_clientstub.c
845 Revision 1.333 2007/02/27 22:55:22 cheshire
846 Get rid of unused AllDNSLinkGroupv4 and AllDNSLinkGroupv6
848 Revision 1.332 2007/02/27 02:48:24 cheshire
849 Parameter to LNT_GetPublicIP function is IPv4 address, not anonymous "mDNSOpaque32" object
851 Revision 1.331 2007/02/14 03:16:39 cheshire
852 <rdar://problem/4789477> Eliminate unnecessary malloc/free in mDNSCore code
854 Revision 1.330 2007/02/08 21:12:28 cheshire
855 <rdar://problem/4386497> Stop reading /etc/mDNSResponder.conf on every sleep/wake
857 Revision 1.329 2007/02/07 01:19:36 cheshire
858 <rdar://problem/4849427> API: Reconcile conflicting error code values
860 Revision 1.328 2007/01/25 00:19:40 cheshire
861 Add CNAMEReferrals field to DNSQuestion_struct
863 Revision 1.327 2007/01/23 02:56:10 cheshire
864 Store negative results in the cache, instead of generating them out of pktResponseHndlr()
866 Revision 1.326 2007/01/20 01:30:49 cheshire
869 Revision 1.325 2007/01/19 18:39:11 cheshire
870 Fix a bunch of parameters that should have been declared "const"
872 Revision 1.324 2007/01/19 18:04:04 cheshire
873 For naming consistency, use capital letters for RR types: rdataOpt should be rdataOPT
875 Revision 1.323 2007/01/17 21:46:02 cheshire
876 Remove redundant duplicated "isPrivate" field from LLQ_Info
878 Revision 1.322 2007/01/10 22:51:56 cheshire
879 <rdar://problem/4917539> Add support for one-shot private queries as well as long-lived private queries
881 Revision 1.321 2007/01/09 22:37:18 cheshire
882 Provide ten-second grace period for deleted keys, to give mDNSResponder
883 time to delete host name before it gives up access to the required key.
885 Revision 1.320 2007/01/05 08:30:41 cheshire
886 Trim excessive "$Log" checkin history from before 2006
887 (checkin history still available via "cvs log ..." of course)
889 Revision 1.319 2007/01/04 23:11:11 cheshire
890 <rdar://problem/4720673> uDNS: Need to start caching unicast records
891 When an automatic browsing domain is removed, generate appropriate "remove" events for legacy queries
893 Revision 1.318 2007/01/04 20:57:48 cheshire
894 Rename ReturnCNAME to ReturnIntermed (for ReturnIntermediates)
896 Revision 1.317 2007/01/04 02:39:53 cheshire
897 <rdar://problem/4030599> Hostname passed into DNSServiceRegister ignored for Wide-Area service registrations
899 Revision 1.316 2006/12/22 20:59:49 cheshire
900 <rdar://problem/4742742> Read *all* DNS keys from keychain,
901 not just key for the system-wide default registration domain
903 Revision 1.315 2006/12/20 04:07:35 cheshire
904 Remove uDNS_info substructure from AuthRecord_struct
906 Revision 1.314 2006/12/19 22:49:23 cheshire
907 Remove uDNS_info substructure from ServiceRecordSet_struct
909 Revision 1.313 2006/12/19 02:38:20 cheshire
910 Get rid of unnecessary duplicate query ID field from DNSQuestion_struct
912 Revision 1.312 2006/12/19 02:18:48 cheshire
913 Get rid of unnecessary duplicate "void *context" field from DNSQuestion_struct
915 Revision 1.311 2006/12/16 01:58:31 cheshire
916 <rdar://problem/4720673> uDNS: Need to start caching unicast records
918 Revision 1.310 2006/12/15 19:09:56 cheshire
919 <rdar://problem/4769083> ValidateRData() should be stricter about malformed MX and SRV records
920 Made DomainNameLength() more defensive by adding a limit parameter, so it can be
921 safely used to inspect potentially malformed data received from external sources.
922 Without this, a domain name that starts off apparently valid, but extends beyond the end of
923 the received packet data, could have appeared valid if the random bytes are already in memory
924 beyond the end of the packet just happened to have reasonable values (e.g. all zeroes).
926 Revision 1.309 2006/12/14 03:02:37 cheshire
927 <rdar://problem/4838433> Tools: dns-sd -G 0 only returns IPv6 when you have a routable IPv6 address
929 Revision 1.308 2006/11/30 23:07:56 herscher
930 <rdar://problem/4765644> uDNS: Sync up with Lighthouse changes for Private DNS
932 Revision 1.307 2006/11/18 05:01:30 cheshire
933 Preliminary support for unifying the uDNS and mDNS code,
934 including caching of uDNS answers
936 Revision 1.306 2006/11/10 07:44:04 herscher
937 <rdar://problem/4825493> Fix Daemon locking failures while toggling BTMM
939 Revision 1.305 2006/11/10 00:54:15 cheshire
940 <rdar://problem/4816598> Changing case of Computer Name doesn't work
942 Revision 1.304 2006/10/20 05:35:05 herscher
943 <rdar://problem/4720713> uDNS: Merge unicast active question list with multicast list.
945 Revision 1.303 2006/10/04 21:37:33 herscher
946 Remove uDNS_info substructure from DNSQuestion_struct
948 Revision 1.302 2006/09/26 01:53:25 herscher
949 <rdar://problem/4245016> NAT Port Mapping API (for both NAT-PMP and UPnP Gateway Protocol)
951 Revision 1.301 2006/09/15 21:20:15 cheshire
952 Remove uDNS_info substructure from mDNS_struct
954 Revision 1.300 2006/08/14 23:24:23 cheshire
955 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
957 Revision 1.299 2006/07/15 02:01:28 cheshire
958 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
959 Fix broken "empty string" browsing
961 Revision 1.298 2006/07/05 22:55:03 cheshire
962 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
963 Need Private field in uDNS_RegInfo
965 Revision 1.297 2006/07/05 22:20:03 cheshire
966 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
968 Revision 1.296 2006/06/29 05:28:01 cheshire
969 Added comment about mDNSlocal and mDNSexport
971 Revision 1.295 2006/06/29 03:02:43 cheshire
972 <rdar://problem/4607042> mDNSResponder NXDOMAIN and CNAME support
974 Revision 1.294 2006/06/28 06:50:08 cheshire
975 In future we may want to change definition of mDNSs32 from "signed long" to "signed int"
976 I doubt anyone is building mDNSResponder on systems where int is 16-bits,
977 but lets add a compile-time assertion to make sure.
979 Revision 1.293 2006/06/12 18:00:43 cheshire
980 To make code a little more defensive, check _ILP64 before _LP64,
981 in case both are set by mistake on some platforms
983 Revision 1.292 2006/03/19 17:00:57 cheshire
984 Define symbol MaxMsg instead of using hard-coded constant value '80'
986 Revision 1.291 2006/03/19 02:00:07 cheshire
987 <rdar://problem/4073825> Improve logic for delaying packets after repeated interface transitions
989 Revision 1.290 2006/03/08 22:42:23 cheshire
990 Fix spelling mistake: LocalReverseMapomain -> LocalReverseMapDomain
992 Revision 1.289 2006/02/26 00:54:41 cheshire
993 Fixes to avoid code generation warning/error on FreeBSD 7
997 #ifndef __mDNSClientAPI_h
998 #define __mDNSClientAPI_h
1000 #if defined(EFI32) || defined(EFI64) || defined(EFIX64)
1001 // EFI doesn't have stdarg.h unless it's building with GCC.
1003 #if !defined(__GNUC__)
1004 #define va_list VA_LIST
1005 #define va_start(a, b) VA_START(a, b)
1006 #define va_end(a) VA_END(a)
1007 #define va_arg(a, b) VA_ARG(a, b)
1010 #include <stdarg.h> // stdarg.h is required for for va_list support for the mDNS_vsnprintf declaration
1013 #include "mDNSDebug.h"
1014 #if APPLE_OSX_mDNSResponder
1015 #include <uuid/uuid.h>
1022 // ***************************************************************************
1023 // Function scope indicators
1025 // If you see "mDNSlocal" before a function name in a C file, it means the function is not callable outside this file
1027 #define mDNSlocal static
1029 // If you see "mDNSexport" before a symbol in a C file, it means the symbol is exported for use by clients
1030 // For every "mDNSexport" in a C file, there needs to be a corresponding "extern" declaration in some header file
1031 // (When a C file #includes a header file, the "extern" declarations tell the compiler:
1032 // "This symbol exists -- but not necessarily in this C file.")
1037 // Explanation: These local/export markers are a little habit of mine for signaling the programmers' intentions.
1038 // When "mDNSlocal" is just a synonym for "static", and "mDNSexport" is a complete no-op, you could be
1039 // forgiven for asking what purpose they serve. The idea is that if you see "mDNSexport" in front of a
1040 // function definition it means the programmer intended it to be exported and callable from other files
1041 // in the project. If you see "mDNSlocal" in front of a function definition it means the programmer
1042 // intended it to be private to that file. If you see neither in front of a function definition it
1043 // means the programmer forgot (so you should work out which it is supposed to be, and fix it).
1044 // Using "mDNSlocal" instead of "static" makes it easier to do a textual searches for one or the other.
1045 // For example you can do a search for "static" to find if any functions declare any local variables as "static"
1046 // (generally a bad idea unless it's also "const", because static storage usually risks being non-thread-safe)
1047 // without the results being cluttered with hundreds of matches for functions declared static.
1048 // - Stuart Cheshire
1050 // ***************************************************************************
1051 // Structure packing macro
1053 // If we're not using GNUC, it's not fatal.
1054 // Most compilers naturally pack the on-the-wire structures correctly anyway, so a plain "struct" is usually fine.
1055 // In the event that structures are not packed correctly, mDNS_Init() will detect this and report an error, so the
1056 // developer will know what's wrong, and can investigate what needs to be done on that compiler to provide proper packing.
1057 #ifndef packedstruct
1058 #if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
1059 #define packedstruct struct __attribute__((__packed__))
1060 #define packedunion union __attribute__((__packed__))
1062 #define packedstruct struct
1063 #define packedunion union
1067 // ***************************************************************************
1069 #pragma mark - DNS Resource Record class and type constants
1072 typedef enum // From RFC 1035
1074 kDNSClass_IN
= 1, // Internet
1075 kDNSClass_CS
= 2, // CSNET
1076 kDNSClass_CH
= 3, // CHAOS
1077 kDNSClass_HS
= 4, // Hesiod
1078 kDNSClass_NONE
= 254, // Used in DNS UPDATE [RFC 2136]
1080 kDNSClass_Mask
= 0x7FFF,// Multicast DNS uses the bottom 15 bits to identify the record class...
1081 kDNSClass_UniqueRRSet
= 0x8000,// ... and the top bit indicates that all other cached records are now invalid
1083 kDNSQClass_ANY
= 255, // Not a DNS class, but a DNS query class, meaning "all classes"
1084 kDNSQClass_UnicastResponse
= 0x8000 // Top bit set in a question means "unicast response acceptable"
1087 typedef enum // From RFC 1035
1089 kDNSType_A
= 1, // 1 Address
1090 kDNSType_NS
, // 2 Name Server
1091 kDNSType_MD
, // 3 Mail Destination
1092 kDNSType_MF
, // 4 Mail Forwarder
1093 kDNSType_CNAME
, // 5 Canonical Name
1094 kDNSType_SOA
, // 6 Start of Authority
1095 kDNSType_MB
, // 7 Mailbox
1096 kDNSType_MG
, // 8 Mail Group
1097 kDNSType_MR
, // 9 Mail Rename
1098 kDNSType_NULL
, // 10 NULL RR
1099 kDNSType_WKS
, // 11 Well-known-service
1100 kDNSType_PTR
, // 12 Domain name pointer
1101 kDNSType_HINFO
, // 13 Host information
1102 kDNSType_MINFO
, // 14 Mailbox information
1103 kDNSType_MX
, // 15 Mail Exchanger
1104 kDNSType_TXT
, // 16 Arbitrary text string
1105 kDNSType_RP
, // 17 Responsible person
1106 kDNSType_AFSDB
, // 18 AFS cell database
1107 kDNSType_X25
, // 19 X_25 calling address
1108 kDNSType_ISDN
, // 20 ISDN calling address
1109 kDNSType_RT
, // 21 Router
1110 kDNSType_NSAP
, // 22 NSAP address
1111 kDNSType_NSAP_PTR
, // 23 Reverse NSAP lookup (deprecated)
1112 kDNSType_SIG
, // 24 Security signature
1113 kDNSType_KEY
, // 25 Security key
1114 kDNSType_PX
, // 26 X.400 mail mapping
1115 kDNSType_GPOS
, // 27 Geographical position (withdrawn)
1116 kDNSType_AAAA
, // 28 IPv6 Address
1117 kDNSType_LOC
, // 29 Location Information
1118 kDNSType_NXT
, // 30 Next domain (security)
1119 kDNSType_EID
, // 31 Endpoint identifier
1120 kDNSType_NIMLOC
, // 32 Nimrod Locator
1121 kDNSType_SRV
, // 33 Service record
1122 kDNSType_ATMA
, // 34 ATM Address
1123 kDNSType_NAPTR
, // 35 Naming Authority PoinTeR
1124 kDNSType_KX
, // 36 Key Exchange
1125 kDNSType_CERT
, // 37 Certification record
1126 kDNSType_A6
, // 38 IPv6 Address (deprecated)
1127 kDNSType_DNAME
, // 39 Non-terminal DNAME (for IPv6)
1128 kDNSType_SINK
, // 40 Kitchen sink (experimental)
1129 kDNSType_OPT
, // 41 EDNS0 option (meta-RR)
1130 kDNSType_APL
, // 42 Address Prefix List
1131 kDNSType_DS
, // 43 Delegation Signer
1132 kDNSType_SSHFP
, // 44 SSH Key Fingerprint
1133 kDNSType_IPSECKEY
, // 45 IPSECKEY
1134 kDNSType_RRSIG
, // 46 RRSIG
1135 kDNSType_NSEC
, // 47 Denial of Existence
1136 kDNSType_DNSKEY
, // 48 DNSKEY
1137 kDNSType_DHCID
, // 49 DHCP Client Identifier
1138 kDNSType_NSEC3
, // 50 Hashed Authenticated Denial of Existence
1139 kDNSType_NSEC3PARAM
, // 51 Hashed Authenticated Denial of Existence
1141 kDNSType_HIP
= 55, // 55 Host Identity Protocol
1143 kDNSType_SPF
= 99, // 99 Sender Policy Framework for E-Mail
1144 kDNSType_UINFO
, // 100 IANA-Reserved
1145 kDNSType_UID
, // 101 IANA-Reserved
1146 kDNSType_GID
, // 102 IANA-Reserved
1147 kDNSType_UNSPEC
, // 103 IANA-Reserved
1149 kDNSType_TKEY
= 249, // 249 Transaction key
1150 kDNSType_TSIG
, // 250 Transaction signature
1151 kDNSType_IXFR
, // 251 Incremental zone transfer
1152 kDNSType_AXFR
, // 252 Transfer zone of authority
1153 kDNSType_MAILB
, // 253 Transfer mailbox records
1154 kDNSType_MAILA
, // 254 Transfer mail agent records
1155 kDNSQType_ANY
// Not a DNS type, but a DNS query type, meaning "all types"
1158 // ***************************************************************************
1161 #pragma mark - Simple types
1164 // mDNS defines its own names for these common types to simplify portability across
1165 // multiple platforms that may each have their own (different) names for these types.
1166 typedef int mDNSBool
;
1167 typedef signed char mDNSs8
;
1168 typedef unsigned char mDNSu8
;
1169 typedef signed short mDNSs16
;
1170 typedef unsigned short mDNSu16
;
1172 // <http://gcc.gnu.org/onlinedocs/gcc-3.3.3/cpp/Common-Predefined-Macros.html> says
1174 // These macros are defined, with value 1, if (and only if) the compilation is
1175 // for a target where long int and pointer both use 64-bits and int uses 32-bit.
1176 // <http://www.intel.com/software/products/compilers/clin/docs/ug/lin1077.htm> says
1177 // Macro Name __LP64__ Value 1
1178 // A quick Google search for "defined(__LP64__)" OR "#ifdef __LP64__" gives 2590 hits and
1179 // a search for "#if __LP64__" gives only 12, so I think we'll go with the majority and use defined()
1180 #if defined(_ILP64) || defined(__ILP64__)
1181 typedef signed int32 mDNSs32
;
1182 typedef unsigned int32 mDNSu32
;
1183 #elif defined(_LP64) || defined(__LP64__)
1184 typedef signed int mDNSs32
;
1185 typedef unsigned int mDNSu32
;
1187 typedef signed long mDNSs32
;
1188 typedef unsigned long mDNSu32
;
1189 //typedef signed int mDNSs32;
1190 //typedef unsigned int mDNSu32;
1193 // To enforce useful type checking, we make mDNSInterfaceID be a pointer to a dummy struct
1194 // This way, mDNSInterfaceIDs can be assigned, and compared with each other, but not with other types
1195 // Declaring the type to be the typical generic "void *" would lack this type checking
1196 typedef struct mDNSInterfaceID_dummystruct
{ void *dummy
; } *mDNSInterfaceID
;
1198 // These types are for opaque two- and four-byte identifiers.
1199 // The "NotAnInteger" fields of the unions allow the value to be conveniently passed around in a
1200 // register for the sake of efficiency, and compared for equality or inequality, but don't forget --
1201 // just because it is in a register doesn't mean it is an integer. Operations like greater than,
1202 // less than, add, multiply, increment, decrement, etc., are undefined for opaque identifiers,
1203 // and if you make the mistake of trying to do those using the NotAnInteger field, then you'll
1204 // find you get code that doesn't work consistently on big-endian and little-endian machines.
1206 #pragma pack(push,2)
1208 typedef union { mDNSu8 b
[ 2]; mDNSu16 NotAnInteger
; } mDNSOpaque16
;
1209 typedef union { mDNSu8 b
[ 4]; mDNSu32 NotAnInteger
; } mDNSOpaque32
;
1210 typedef packedunion
{ mDNSu8 b
[ 6]; mDNSu16 w
[3]; mDNSu32 l
[1]; } mDNSOpaque48
;
1211 typedef union { mDNSu8 b
[ 8]; mDNSu16 w
[4]; mDNSu32 l
[2]; } mDNSOpaque64
;
1212 typedef union { mDNSu8 b
[16]; mDNSu16 w
[8]; mDNSu32 l
[4]; } mDNSOpaque128
;
1217 typedef mDNSOpaque16 mDNSIPPort
; // An IP port is a two-byte opaque identifier (not an integer)
1218 typedef mDNSOpaque32 mDNSv4Addr
; // An IP address is a four-byte opaque identifier (not an integer)
1219 typedef mDNSOpaque128 mDNSv6Addr
; // An IPv6 address is a 16-byte opaque identifier (not an integer)
1220 typedef mDNSOpaque48 mDNSEthAddr
; // An Ethernet address is a six-byte opaque identifier (not an integer)
1224 mDNSAddrType_None
= 0,
1225 mDNSAddrType_IPv4
= 4,
1226 mDNSAddrType_IPv6
= 6,
1227 mDNSAddrType_Unknown
= ~0 // Special marker value used in known answer list recording
1232 mDNSTransport_None
= 0,
1233 mDNSTransport_UDP
= 1,
1234 mDNSTransport_TCP
= 2
1240 union { mDNSv6Addr v6
; mDNSv4Addr v4
; } ip
;
1243 enum { mDNSfalse
= 0, mDNStrue
= 1 };
1249 mStatus_Waiting
= 1,
1250 mStatus_NoError
= 0,
1252 // mDNS return values are in the range FFFE FF00 (-65792) to FFFE FFFF (-65537)
1253 // The top end of the range (FFFE FFFF) is used for error codes;
1254 // the bottom end of the range (FFFE FF00) is used for non-error values;
1257 mStatus_UnknownErr
= -65537, // First value: 0xFFFE FFFF
1258 mStatus_NoSuchNameErr
= -65538,
1259 mStatus_NoMemoryErr
= -65539,
1260 mStatus_BadParamErr
= -65540,
1261 mStatus_BadReferenceErr
= -65541,
1262 mStatus_BadStateErr
= -65542,
1263 mStatus_BadFlagsErr
= -65543,
1264 mStatus_UnsupportedErr
= -65544,
1265 mStatus_NotInitializedErr
= -65545,
1266 mStatus_NoCache
= -65546,
1267 mStatus_AlreadyRegistered
= -65547,
1268 mStatus_NameConflict
= -65548,
1269 mStatus_Invalid
= -65549,
1270 mStatus_Firewall
= -65550,
1271 mStatus_Incompatible
= -65551,
1272 mStatus_BadInterfaceErr
= -65552,
1273 mStatus_Refused
= -65553,
1274 mStatus_NoSuchRecord
= -65554,
1275 mStatus_NoAuth
= -65555,
1276 mStatus_NoSuchKey
= -65556,
1277 mStatus_NATTraversal
= -65557,
1278 mStatus_DoubleNAT
= -65558,
1279 mStatus_BadTime
= -65559,
1280 mStatus_BadSig
= -65560, // while we define this per RFC 2845, BIND 9 returns Refused for bad/missing signatures
1281 mStatus_BadKey
= -65561,
1282 mStatus_TransientErr
= -65562, // transient failures, e.g. sending packets shortly after a network transition or wake from sleep
1283 mStatus_ServiceNotRunning
= -65563, // Background daemon not running
1284 mStatus_NATPortMappingUnsupported
= -65564, // NAT doesn't support NAT-PMP or UPnP
1285 mStatus_NATPortMappingDisabled
= -65565, // NAT supports NAT-PMP or UPnP but it's disabled by the administrator
1286 mStatus_NoRouter
= -65566,
1287 mStatus_PollingMode
= -65567,
1288 // -65568 to -65786 currently unused; available for allocation
1290 // tcp connection status
1291 mStatus_ConnPending
= -65787,
1292 mStatus_ConnFailed
= -65788,
1293 mStatus_ConnEstablished
= -65789,
1295 // Non-error values:
1296 mStatus_GrowCache
= -65790,
1297 mStatus_ConfigChanged
= -65791,
1298 mStatus_MemFree
= -65792 // Last value: 0xFFFE FF00
1299 // mStatus_MemFree is the last legal mDNS error code, at the end of the range allocated for mDNS
1302 typedef mDNSs32 mStatus
;
1304 // RFC 1034/1035 specify that a domain label consists of a length byte plus up to 63 characters
1305 #define MAX_DOMAIN_LABEL 63
1306 typedef struct { mDNSu8 c
[ 64]; } domainlabel
; // One label: length byte and up to 63 characters
1308 // RFC 1034/1035/2181 specify that a domain name, including length bytes, data bytes, and terminating zero, may be up to 256 bytes long
1309 #define MAX_DOMAIN_NAME 256
1310 typedef struct { mDNSu8 c
[256]; } domainname
; // Up to 256 bytes of length-prefixed domainlabels
1312 typedef struct { mDNSu8 c
[256]; } UTF8str255
; // Null-terminated C string
1314 // The longest legal textual form of a DNS name is 1009 bytes, including the C-string terminating NULL at the end.
1316 // When a native domainname object is converted to printable textual form using ConvertDomainNameToCString(),
1317 // non-printing characters are represented in the conventional DNS way, as '\ddd', where ddd is a three-digit decimal number.
1318 // The longest legal domain name is 256 bytes, in the form of four labels as shown below:
1319 // Length byte, 63 data bytes, length byte, 63 data bytes, length byte, 63 data bytes, length byte, 62 data bytes, zero byte.
1320 // Each label is encoded textually as characters followed by a trailing dot.
1321 // If every character has to be represented as a four-byte escape sequence, then this makes the maximum textual form four labels
1322 // plus the C-string terminating NULL as shown below:
1323 // 63*4+1 + 63*4+1 + 63*4+1 + 62*4+1 + 1 = 1009.
1324 // Note that MAX_ESCAPED_DOMAIN_LABEL is not normally used: If you're only decoding a single label, escaping is usually not required.
1325 // It is for domain names, where dots are used as label separators, that proper escaping is vital.
1326 #define MAX_ESCAPED_DOMAIN_LABEL 254
1327 #define MAX_ESCAPED_DOMAIN_NAME 1009
1329 // MAX_REVERSE_MAPPING_NAME
1330 // For IPv4: "123.123.123.123.in-addr.arpa." 30 bytes including terminating NUL
1331 // 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
1333 #define MAX_REVERSE_MAPPING_NAME_V4 30
1334 #define MAX_REVERSE_MAPPING_NAME_V6 74
1335 #define MAX_REVERSE_MAPPING_NAME 74
1337 // Most records have a TTL of 75 minutes, so that their 80% cache-renewal query occurs once per hour.
1338 // For records containing a hostname (in the name on the left, or in the rdata on the right),
1339 // like A, AAAA, reverse-mapping PTR, and SRV, we use a two-minute TTL by default, because we don't want
1340 // them to hang around for too long in the cache if the host in question crashes or otherwise goes away.
1342 #define kStandardTTL (3600UL * 100 / 80)
1343 #define kHostNameTTL 120UL
1345 #define DefaultTTLforRRType(X) (((X) == kDNSType_A || (X) == kDNSType_AAAA || (X) == kDNSType_SRV) ? kHostNameTTL : kStandardTTL)
1347 typedef struct AuthRecord_struct AuthRecord
;
1348 typedef struct ServiceRecordSet_struct ServiceRecordSet
;
1349 typedef struct CacheRecord_struct CacheRecord
;
1350 typedef struct CacheGroup_struct CacheGroup
;
1351 typedef struct DNSQuestion_struct DNSQuestion
;
1352 typedef struct ZoneData_struct ZoneData
;
1353 typedef struct mDNS_struct mDNS
;
1354 typedef struct mDNS_PlatformSupport_struct mDNS_PlatformSupport
;
1355 typedef struct NATTraversalInfo_struct NATTraversalInfo
;
1357 // Structure to abstract away the differences between TCP/SSL sockets, and one for UDP sockets
1358 // The actual definition of these structures appear in the appropriate platform support code
1359 typedef struct TCPSocket_struct TCPSocket
;
1360 typedef struct UDPSocket_struct UDPSocket
;
1362 // ***************************************************************************
1365 #pragma mark - DNS Message structures
1368 #define mDNS_numZones numQuestions
1369 #define mDNS_numPrereqs numAnswers
1370 #define mDNS_numUpdates numAuthorities
1372 typedef packedstruct
1376 mDNSu16 numQuestions
;
1378 mDNSu16 numAuthorities
;
1379 mDNSu16 numAdditionals
;
1382 // We can send and receive packets up to 9000 bytes (Ethernet Jumbo Frame size, if that ever becomes widely used)
1383 // However, in the normal case we try to limit packets to 1500 bytes so that we don't get IP fragmentation on standard Ethernet
1384 // 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
1385 #define AbsoluteMaxDNSMessageData 8940
1386 #define NormalMaxDNSMessageData 1440
1387 typedef packedstruct
1389 DNSMessageHeader h
; // Note: Size 12 bytes
1390 mDNSu8 data
[AbsoluteMaxDNSMessageData
]; // 40 (IPv6) + 8 (UDP) + 12 (DNS header) + 8940 (data) = 9000
1393 typedef struct tcpInfo_t
1399 DNSQuestion
*question
; // For queries
1400 ServiceRecordSet
*srs
; // For service record updates
1401 AuthRecord
*rr
; // For record updates
1406 unsigned long nread
;
1410 // ***************************************************************************
1413 #pragma mark - Other Packet Format Structures
1416 typedef packedstruct
1420 mDNSOpaque16 ethertype
;
1421 } EthernetHeader
; // 14 bytes
1423 typedef packedstruct
1434 } ARP_EthIP
; // 28 bytes
1436 typedef packedstruct
1442 mDNSOpaque16 flagsfrags
;
1448 } IPv4Header
; // 20 bytes
1450 typedef packedstruct
1452 mDNSu32 vcf
; // Version, Traffic Class, Flow Label
1453 mDNSu16 len
; // Payload Length
1454 mDNSu8 protocol
; // Type of next header: 0x06 = TCP, 0x11 = UDP, 0x3A = ICMPv6
1455 mDNSu8 ttl
; // Hop Limit
1458 } IPv6Header
; // 40 bytes
1460 typedef packedstruct
1462 mDNSu8 type
; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
1467 } IPv6ND
; // 24 bytes
1469 typedef packedstruct
1473 mDNSu16 len
; // Length including UDP header (ie. minimum value is 8 bytes)
1475 } UDPHeader
; // 8 bytes
1477 typedef packedstruct
1479 mDNSOpaque64 InitiatorCookie
;
1480 mDNSOpaque64 ResponderCookie
;
1483 mDNSu8 ExchangeType
;
1485 mDNSOpaque32 MessageID
;
1487 } IKEHeader
; // 28 bytes
1489 typedef packedstruct
1500 } TCPHeader
; // 20 bytes
1502 // ***************************************************************************
1505 #pragma mark - Resource Record structures
1508 // Authoritative Resource Records:
1509 // There are four basic types: Shared, Advisory, Unique, Known Unique
1511 // * Shared Resource Records do not have to be unique
1512 // -- Shared Resource Records are used for DNS-SD service PTRs
1513 // -- It is okay for several hosts to have RRs with the same name but different RDATA
1514 // -- We use a random delay on responses to reduce collisions when all the hosts respond to the same query
1515 // -- These RRs typically have moderately high TTLs (e.g. one hour)
1516 // -- These records are announced on startup and topology changes for the benefit of passive listeners
1517 // -- These records send a goodbye packet when deregistering
1519 // * Advisory Resource Records are like Shared Resource Records, except they don't send a goodbye packet
1521 // * Unique Resource Records should be unique among hosts within any given mDNS scope
1522 // -- The majority of Resource Records are of this type
1523 // -- If two entities on the network have RRs with the same name but different RDATA, this is a conflict
1524 // -- Responses may be sent immediately, because only one host should be responding to any particular query
1525 // -- These RRs typically have low TTLs (e.g. a few minutes)
1526 // -- On startup and after topology changes, a host issues queries to verify uniqueness
1528 // * Known Unique Resource Records are treated like Unique Resource Records, except that mDNS does
1529 // not have to verify their uniqueness because this is already known by other means (e.g. the RR name
1530 // is derived from the host's IP or Ethernet address, which is already known to be a unique identifier).
1532 // Summary of properties of different record types:
1533 // Probe? Does this record type send probes before announcing?
1534 // Conflict? Does this record type react if we observe an apparent conflict?
1535 // Goodbye? Does this record type send a goodbye packet on departure?
1537 // Probe? Conflict? Goodbye? Notes
1538 // Unregistered Should not appear in any list (sanity check value)
1539 // Shared No No Yes e.g. Service PTR record
1540 // Deregistering No No Yes Shared record about to announce its departure and leave the list
1541 // Advisory No No No
1542 // Unique Yes Yes No Record intended to be unique -- will probe to verify
1543 // Verified Yes Yes No Record has completed probing, and is verified unique
1544 // KnownUnique No Yes No Record is assumed by other means to be unique
1546 // Valid lifecycle of a record:
1547 // Unregistered -> Shared -> Deregistering -(goodbye)-> Unregistered
1548 // Unregistered -> Advisory -> Unregistered
1549 // Unregistered -> Unique -(probe)-> Verified -> Unregistered
1550 // Unregistered -> KnownUnique -> Unregistered
1552 // Each Authoritative kDNSRecordType has only one bit set. This makes it easy to quickly see if a record
1553 // is one of a particular set of types simply by performing the appropriate bitwise masking operation.
1555 // Cache Resource Records (received from the network):
1556 // There are four basic types: Answer, Unique Answer, Additional, Unique Additional
1557 // Bit 7 (the top bit) of kDNSRecordType is always set for Cache Resource Records; always clear for Authoritative Resource Records
1558 // Bit 6 (value 0x40) is set for answer records; clear for authority/additional records
1559 // Bit 5 (value 0x20) is set for records received with the kDNSClass_UniqueRRSet
1563 kDNSRecordTypeUnregistered
= 0x00, // Not currently in any list
1564 kDNSRecordTypeDeregistering
= 0x01, // Shared record about to announce its departure and leave the list
1566 kDNSRecordTypeUnique
= 0x02, // Will become a kDNSRecordTypeVerified when probing is complete
1568 kDNSRecordTypeAdvisory
= 0x04, // Like Shared, but no goodbye packet
1569 kDNSRecordTypeShared
= 0x08, // Shared means record name does not have to be unique -- use random delay on responses
1571 kDNSRecordTypeVerified
= 0x10, // Unique means mDNS should check that name is unique (and then send immediate responses)
1572 kDNSRecordTypeKnownUnique
= 0x20, // Known Unique means mDNS can assume name is unique without checking
1573 // For Dynamic Update records, Known Unique means the record must already exist on the server.
1574 kDNSRecordTypeUniqueMask
= (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
),
1575 kDNSRecordTypeActiveMask
= (kDNSRecordTypeAdvisory
| kDNSRecordTypeShared
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
),
1577 kDNSRecordTypePacketAdd
= 0x80, // Received in the Additional Section of a DNS Response
1578 kDNSRecordTypePacketAddUnique
= 0x90, // Received in the Additional Section of a DNS Response with kDNSClass_UniqueRRSet set
1579 kDNSRecordTypePacketAuth
= 0xA0, // Received in the Authorities Section of a DNS Response
1580 kDNSRecordTypePacketAuthUnique
= 0xB0, // Received in the Authorities Section of a DNS Response with kDNSClass_UniqueRRSet set
1581 kDNSRecordTypePacketAns
= 0xC0, // Received in the Answer Section of a DNS Response
1582 kDNSRecordTypePacketAnsUnique
= 0xD0, // Received in the Answer Section of a DNS Response with kDNSClass_UniqueRRSet set
1584 kDNSRecordTypePacketNegative
= 0xF0, // Pseudo-RR generated to cache non-existence results like NXDomain
1586 kDNSRecordTypePacketUniqueMask
= 0x10 // True for PacketAddUnique, PacketAnsUnique, PacketAuthUnique
1589 typedef packedstruct
{ mDNSu16 priority
; mDNSu16 weight
; mDNSIPPort port
; domainname target
; } rdataSRV
;
1590 typedef packedstruct
{ mDNSu16 preference
; domainname exchange
; } rdataMX
;
1591 typedef packedstruct
{ domainname mbox
; domainname txt
; } rdataRP
;
1592 typedef packedstruct
{ mDNSu16 preference
; domainname map822
; domainname mapx400
; } rdataPX
;
1594 typedef packedstruct
1598 mDNSs32 serial
; // Modular counter; increases when zone changes
1599 mDNSu32 refresh
; // Time in seconds that a slave waits after successful replication of the database before it attempts replication again
1600 mDNSu32 retry
; // Time in seconds that a slave waits after an unsuccessful replication attempt before it attempts replication again
1601 mDNSu32 expire
; // Time in seconds that a slave holds on to old data while replication attempts remain unsuccessful
1602 mDNSu32 min
; // Nominally the minimum record TTL for this zone, in seconds; also used for negative caching.
1605 // EDNS Option Code registrations are recorded in the "DNS EDNS0 Options" section of
1606 // <http://www.iana.org/assignments/dns-parameters>
1608 #define kDNSOpt_LLQ 1
1609 #define kDNSOpt_Lease 2
1610 #define kDNSOpt_NSID 3
1611 #define kDNSOpt_Owner 4
1617 mDNSu16 err
; // Or UDP reply port, in setup request
1618 // Note: In the in-memory form, there's typically a two-byte space here, so that the following 64-bit id is word-aligned
1625 mDNSu8 vers
; // Version number of this Owner OPT record
1626 mDNSs8 seq
; // Sleep/wake epoch
1627 mDNSEthAddr HMAC
; // Host's primary identifier (e.g. MAC of on-board Ethernet)
1628 mDNSEthAddr IMAC
; // Interface's MAC address (if different to primary MAC)
1629 mDNSOpaque48 password
; // Optional password
1632 // Note: rdataOPT format may be repeated an arbitrary number of times in a single resource record
1633 typedef packedstruct
1637 union { LLQOptData llq
; mDNSu32 updatelease
; OwnerOptData owner
; } u
;
1640 // Space needed to put OPT records into a packet:
1641 // Header 11 bytes (name 1, type 2, class 2, TTL 4, length 2)
1642 // LLQ rdata 18 bytes (opt 2, len 2, vers 2, op 2, err 2, id 8, lease 4)
1643 // Lease rdata 8 bytes (opt 2, len 2, lease 4)
1644 // Owner rdata 12-24 (opt 2, len 2, owner 8-20)
1646 #define DNSOpt_Header_Space 11
1647 #define DNSOpt_LLQData_Space (4 + 2 + 2 + 2 + 8 + 4)
1648 #define DNSOpt_LeaseData_Space (4 + 4)
1649 #define DNSOpt_OwnerData_ID_Space (4 + 2 + 6)
1650 #define DNSOpt_OwnerData_ID_Wake_Space (4 + 2 + 6 + 6)
1651 #define DNSOpt_OwnerData_ID_Wake_PW4_Space (4 + 2 + 6 + 6 + 4)
1652 #define DNSOpt_OwnerData_ID_Wake_PW6_Space (4 + 2 + 6 + 6 + 6)
1654 #define ValidOwnerLength(X) ( (X) == DNSOpt_OwnerData_ID_Space - 4 || \
1655 (X) == DNSOpt_OwnerData_ID_Wake_Space - 4 || \
1656 (X) == DNSOpt_OwnerData_ID_Wake_PW4_Space - 4 || \
1657 (X) == DNSOpt_OwnerData_ID_Wake_PW6_Space - 4 )
1659 #define ValidDNSOpt(O) (((O)->opt == kDNSOpt_LLQ && (O)->optlen == DNSOpt_LLQData_Space - 4) || \
1660 ((O)->opt == kDNSOpt_Lease && (O)->optlen == DNSOpt_LeaseData_Space - 4) || \
1661 ((O)->opt == kDNSOpt_Owner && ValidOwnerLength((O)->optlen) ) )
1663 #define DNSOpt_Owner_Space(A,B) (mDNSSameEthAddress((A),(B)) ? DNSOpt_OwnerData_ID_Space : DNSOpt_OwnerData_ID_Wake_Space)
1665 #define DNSOpt_Data_Space(O) ( \
1666 (O)->opt == kDNSOpt_LLQ ? DNSOpt_LLQData_Space : \
1667 (O)->opt == kDNSOpt_Lease ? DNSOpt_LeaseData_Space : \
1668 (O)->opt == kDNSOpt_Owner ? DNSOpt_Owner_Space(&(O)->u.owner.HMAC, &(O)->u.owner.IMAC) : 0x10000)
1670 // A maximal NSEC record is:
1671 // 256 bytes domainname 'nextname'
1672 // + 256 * 34 = 8704 bytes of bitmap data
1673 // = 8960 bytes total
1674 // For now we only support NSEC records encoding DNS types 0-255 and ignore the nextname (we always set it to be the same as the rrname),
1675 // which gives us a fixed in-memory size of 32 bytes (256 bits)
1681 // StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record (6 + 256 bytes)
1682 // MaximumRDSize is 8K the absolute maximum we support (at least for now)
1683 #define StandardAuthRDSize 264
1684 #define MaximumRDSize 8192
1686 // InlineCacheRDSize is 68
1687 // Records received from the network with rdata this size or less have their rdata stored right in the CacheRecord object
1688 // Records received from the network with rdata larger than this have additional storage allocated for the rdata
1689 // A quick unscientific sample from a busy network at Apple with lots of machines revealed this:
1690 // 1461 records in cache
1691 // 292 were one-byte TXT records
1692 // 136 were four-byte A records
1693 // 184 were sixteen-byte AAAA records
1694 // 780 were various PTR, TXT and SRV records from 12-64 bytes
1695 // Only 69 records had rdata bigger than 64 bytes
1696 // Note that since CacheRecord object and a CacheGroup object are allocated out of the same pool, it's sensible to
1697 // have them both be the same size. Making one smaller without making the other smaller won't actually save any memory.
1698 #define InlineCacheRDSize 68
1700 // On 64-bit, the pointers in a CacheRecord are bigger, and that creates 8 bytes more space for the name in a CacheGroup
1701 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
1702 #if defined(_ILP64) || defined(__ILP64__) || defined(_LP64) || defined(__LP64__) || defined(_WIN64)
1703 #define InlineCacheGroupNameSize 152
1705 #define InlineCacheGroupNameSize 144
1708 #if defined(_ILP64) || defined(__ILP64__) || defined(_LP64) || defined(__LP64__) || defined(_WIN64)
1709 #define InlineCacheGroupNameSize 136
1711 #define InlineCacheGroupNameSize 128
1715 // The RDataBody union defines the common rdata types that fit into our 264-byte limit
1718 mDNSu8 data
[StandardAuthRDSize
];
1719 mDNSv4Addr ipv4
; // For 'A' record
1720 domainname name
; // For PTR, NS, CNAME, DNAME
1723 mDNSv6Addr ipv6
; // For 'AAAA' record
1725 rdataOPT opt
[2]; // For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
1729 // The RDataBody2 union is the same as above, except it includes fields for the larger types like soa, rp, px
1732 mDNSu8 data
[StandardAuthRDSize
];
1733 mDNSv4Addr ipv4
; // For 'A' record
1734 domainname name
; // For PTR, NS, CNAME, DNAME
1735 rdataSOA soa
; // This is large; not included in the normal RDataBody definition
1738 rdataRP rp
; // This is large; not included in the normal RDataBody definition
1739 rdataPX px
; // This is large; not included in the normal RDataBody definition
1740 mDNSv6Addr ipv6
; // For 'AAAA' record
1742 rdataOPT opt
[2]; // For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
1748 mDNSu16 MaxRDLength
; // Amount of storage allocated for rdata (usually sizeof(RDataBody))
1749 mDNSu16 padding
; // So that RDataBody is aligned on 32-bit boundary
1753 // sizeofRDataHeader should be 4 bytes
1754 #define sizeofRDataHeader (sizeof(RData) - sizeof(RDataBody))
1756 // RData_small is a smaller version of the RData object, used for inline data storage embedded in a CacheRecord_struct
1759 mDNSu16 MaxRDLength
; // Storage allocated for data (may be greater than InlineCacheRDSize if additional storage follows this object)
1760 mDNSu16 padding
; // So that data is aligned on 32-bit boundary
1761 mDNSu8 data
[InlineCacheRDSize
];
1764 // Note: Within an mDNSRecordCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
1765 typedef void mDNSRecordCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
1768 // Restrictions: An mDNSRecordUpdateCallback may not make any mDNS API calls.
1769 // The intent of this callback is to allow the client to free memory, if necessary.
1770 // The internal data structures of the mDNS code may not be in a state where mDNS API calls may be made safely.
1771 typedef void mDNSRecordUpdateCallback(mDNS
*const m
, AuthRecord
*const rr
, RData
*OldRData
);
1773 // ***************************************************************************
1776 #pragma mark - NAT Traversal structures and constants
1779 #define NATMAP_MAX_RETRY_INTERVAL ((mDNSPlatformOneSecond * 60) * 15) // Max retry interval is 15 minutes
1780 #define NATMAP_MIN_RETRY_INTERVAL (mDNSPlatformOneSecond * 2) // Min retry interval is 2 seconds
1781 #define NATMAP_INIT_RETRY (mDNSPlatformOneSecond / 4) // start at 250ms w/ exponential decay
1782 #define NATMAP_DEFAULT_LEASE (60 * 60 * 2) // 2 hour lease life in seconds
1783 #define NATMAP_VERS 0
1787 NATOp_AddrRequest
= 0,
1791 NATOp_AddrResponse
= 0x80 | 0,
1792 NATOp_MapUDPResponse
= 0x80 | 1,
1793 NATOp_MapTCPResponse
= 0x80 | 2,
1806 typedef mDNSu16 NATErr_t
;
1808 typedef packedstruct
1814 typedef packedstruct
1819 mDNSu32 upseconds
; // Time since last NAT engine reboot, in seconds
1823 typedef packedstruct
1827 mDNSOpaque16 unused
;
1830 mDNSu32 NATReq_lease
;
1831 } NATPortMapRequest
;
1833 typedef packedstruct
1838 mDNSu32 upseconds
; // Time since last NAT engine reboot, in seconds
1841 mDNSu32 NATRep_lease
;
1847 LNTExternalAddrOp
= 2,
1849 LNTPortMapDeleteOp
= 4
1852 #define LNT_MAXBUFSIZE 8192
1853 typedef struct tcpLNTInfo_struct tcpLNTInfo
;
1854 struct tcpLNTInfo_struct
1858 NATTraversalInfo
*parentNATInfo
; // pointer back to the parent NATTraversalInfo
1860 LNTOp_t op
; // operation performed using this connection
1861 mDNSAddr Address
; // router address
1862 mDNSIPPort Port
; // router port
1863 mDNSs8
*Request
; // xml request to router
1865 mDNSs8
*Reply
; // xml reply from router
1867 unsigned long nread
; // number of bytes read so far
1868 int retries
; // number of times we've tried to do this port mapping
1871 typedef void (*NATTraversalClientCallback
)(mDNS
*m
, NATTraversalInfo
*n
);
1873 // if m->timenow < ExpiryTime then we have an active mapping, and we'll renew halfway to expiry
1874 // if m->timenow >= ExpiryTime then our mapping has expired, and we're trying to create one
1876 struct NATTraversalInfo_struct
1878 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1879 NATTraversalInfo
*next
;
1881 mDNSs32 ExpiryTime
; // Time this mapping expires, or zero if no mapping
1882 mDNSs32 retryInterval
; // Current interval, between last packet we sent and the next one
1883 mDNSs32 retryPortMap
; // If Protocol is nonzero, time to send our next mapping packet
1884 mStatus NewResult
; // New error code; will be copied to Result just prior to invoking callback
1886 #ifdef _LEGACY_NAT_TRAVERSAL_
1887 tcpLNTInfo tcpInfo
; // Legacy NAT traversal (UPnP) TCP connection
1890 // Result fields: When the callback is invoked these fields contain the answers the client is looking for
1891 // When the callback is invoked ExternalPort is *usually* set to be the same the same as RequestedPort, except:
1892 // (a) When we're behind a NAT gateway with port mapping disabled, ExternalPort is reported as zero to
1893 // indicate that we don't currently have a working mapping (but RequestedPort retains the external port
1894 // we'd like to get, the next time we meet an accomodating NAT gateway willing to give us one).
1895 // (b) When we have a routable non-RFC1918 address, we don't *need* a port mapping, so ExternalPort
1896 // is reported as the same as our InternalPort, since that is effectively our externally-visible port too.
1897 // Again, RequestedPort retains the external port we'd like to get the next time we find ourself behind a NAT gateway.
1898 // To improve stability of port mappings, RequestedPort is updated any time we get a successful
1899 // mapping response from the NAT-PMP or UPnP gateway. For example, if we ask for port 80, and
1900 // get assigned port 81, then thereafter we'll contine asking for port 81.
1901 mDNSInterfaceID InterfaceID
;
1902 mDNSv4Addr ExternalAddress
; // Initially set to onesIPv4Addr, until first callback
1903 mDNSIPPort ExternalPort
;
1907 // Client API fields: The client must set up these fields *before* making any NAT traversal API calls
1908 mDNSu8 Protocol
; // NATOp_MapUDP or NATOp_MapTCP, or zero if just requesting the external IP address
1909 mDNSIPPort IntPort
; // Client's internal port number (doesn't change)
1910 mDNSIPPort RequestedPort
; // Requested external port; may be updated with actual value assigned by gateway
1911 mDNSu32 NATLease
; // Requested lifetime in seconds (doesn't change)
1912 NATTraversalClientCallback clientCallback
;
1913 void *clientContext
;
1916 typedef struct // Size is 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit
1918 mDNSu8 RecordType
; // See enum above
1921 mDNSu32 rroriginalttl
; // In seconds
1922 mDNSu16 rdlength
; // Size of the raw rdata, in bytes, in the on-the-wire format
1923 // (In-memory storage may be larger, for structures containing 'holes', like SOA,
1924 // or smaller, for NSEC where we don't bother storing the nextname field)
1925 mDNSu16 rdestimate
; // Upper bound on on-the-wire size of rdata after name compression
1926 mDNSu32 namehash
; // Name-based (i.e. case-insensitive) hash of name
1927 mDNSu32 rdatahash
; // For rdata containing domain name (e.g. PTR, SRV, CNAME etc.), case-insensitive name hash
1928 // else, for all other rdata, 32-bit hash of the raw rdata
1929 // Note: This requirement is important. Various routines like AddAdditionalsToResponseList(),
1930 // ReconfirmAntecedents(), etc., use rdatahash as a pre-flight check to see
1931 // whether it's worth doing a full SameDomainName() call. If the rdatahash
1932 // is not a correct case-insensitive name hash, they'll get false negatives.
1934 // Grouping pointers together at the end of the structure improves the memory layout efficiency
1935 mDNSInterfaceID InterfaceID
; // Set if this RR is specific to one interface
1936 // For records received off the wire, InterfaceID is *always* set to the receiving interface
1937 // For our authoritative records, InterfaceID is usually zero, except for those few records
1938 // that are interface-specific (e.g. address records, especially linklocal addresses)
1939 const domainname
*name
;
1940 RData
*rdata
; // Pointer to storage for this rdata
1943 // Unless otherwise noted, states may apply to either independent record registrations or service registrations
1947 regState_FetchingZoneData
= 1, // getting info - update not sent
1948 regState_Pending
= 2, // update sent, reply not received
1949 regState_Registered
= 3, // update sent, reply received
1950 regState_DeregPending
= 4, // dereg sent, reply not received
1951 regState_DeregDeferred
= 5, // dereg requested while in Pending state - send dereg AFTER registration is confirmed
1952 regState_Unregistered
= 8, // not in any list
1953 regState_Refresh
= 9, // outstanding refresh (or target change) message
1954 regState_NATMap
= 10, // establishing NAT port mapping (service registrations only)
1955 regState_UpdatePending
= 11, // update in flight as result of mDNS_Update call
1956 regState_NoTarget
= 12, // service registration pending registration of hostname (ServiceRegistrations only)
1957 regState_ExtraQueued
= 13, // extra record to be registered upon completion of service registration (RecordRegistrations only)
1958 regState_NATError
= 14 // unable to complete NAT traversal
1964 Target_AutoHost
= 1,
1965 Target_AutoHostAndNATMAP
= 2
1968 struct AuthRecord_struct
1970 // For examples of how to set up this structure for use in mDNS_Register(),
1971 // see mDNS_AdvertiseInterface() or mDNS_RegisterService().
1972 // Basically, resrec and persistent metadata need to be set up before calling mDNS_Register().
1973 // mDNS_SetupResourceRecord() is avaliable as a helper routine to set up most fields to sensible default values for you
1975 AuthRecord
*next
; // Next in list; first element of structure for efficiency reasons
1976 // Field Group 1: Common ResourceRecord fields
1977 ResourceRecord resrec
; // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit
1979 // Field Group 2: Persistent metadata for Authoritative Records
1980 AuthRecord
*Additional1
; // Recommended additional record to include in response (e.g. SRV for PTR record)
1981 AuthRecord
*Additional2
; // Another additional (e.g. TXT for PTR record)
1982 AuthRecord
*DependentOn
; // This record depends on another for its uniqueness checking
1983 AuthRecord
*RRSet
; // This unique record is part of an RRSet
1984 mDNSRecordCallback
*RecordCallback
; // Callback function to call for state changes, and to free memory asynchronously on deregistration
1985 void *RecordContext
; // Context parameter for the callback function
1986 mDNSu8 AutoTarget
; // Set if the target of this record (PTR, CNAME, SRV, etc.) is our host name
1987 mDNSu8 AllowRemoteQuery
; // Set if we allow hosts not on the local link to query this record
1988 mDNSu8 ForceMCast
; // Set by client to advertise solely via multicast, even for apparently unicast names
1990 OwnerOptData WakeUp
; // Fpr Sleep Proxy records, MAC address of original owner (so we can wake it)
1991 mDNSAddr AddressProxy
; // For reverse-mapping Sleep Proxy PTR records, address in question
1992 mDNSs32 TimeRcvd
; // In platform time units
1993 mDNSs32 TimeExpire
; // In platform time units
1996 // Field Group 3: Transient state for Authoritative Records
1997 mDNSu8 Acknowledged
; // Set if we've given the success callback to the client
1998 mDNSu8 ProbeCount
; // Number of probes remaining before this record is valid (kDNSRecordTypeUnique)
1999 mDNSu8 AnnounceCount
; // Number of announcements remaining (kDNSRecordTypeShared)
2000 mDNSu8 RequireGoodbye
; // Set if this RR has been announced on the wire and will require a goodbye packet
2001 mDNSu8 AnsweredLocalQ
; // Set if this AuthRecord has been delivered to any local question (LocalOnly or mDNSInterface_Any)
2002 mDNSu8 IncludeInProbe
; // Set if this RR is being put into a probe right now
2003 mDNSu8 ImmedUnicast
; // Set if we may send our response directly via unicast to the requester
2004 mDNSInterfaceID SendNSECNow
; // Set if we need to generate associated NSEC data for this rrname
2005 mDNSInterfaceID ImmedAnswer
; // Someone on this interface issued a query we need to answer (all-ones for all interfaces)
2006 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
2007 mDNSs32 ImmedAnswerMarkTime
;
2009 mDNSInterfaceID ImmedAdditional
; // Hint that we might want to also send this record, just to be helpful
2010 mDNSInterfaceID SendRNow
; // The interface this query is being sent on right now
2011 mDNSv4Addr v4Requester
; // Recent v4 query for this record, or all-ones if more than one recent query
2012 mDNSv6Addr v6Requester
; // Recent v6 query for this record, or all-ones if more than one recent query
2013 AuthRecord
*NextResponse
; // Link to the next element in the chain of responses to generate
2014 const mDNSu8
*NR_AnswerTo
; // Set if this record was selected by virtue of being a direct answer to a question
2015 AuthRecord
*NR_AdditionalTo
; // Set if this record was selected by virtue of being additional to another
2016 mDNSs32 ThisAPInterval
; // In platform time units: Current interval for announce/probe
2017 mDNSs32 LastAPTime
; // In platform time units: Last time we sent announcement/probe
2018 mDNSs32 LastMCTime
; // Last time we multicast this record (used to guard against packet-storm attacks)
2019 mDNSInterfaceID LastMCInterface
; // Interface this record was multicast on at the time LastMCTime was recorded
2020 RData
*NewRData
; // Set if we are updating this record with new rdata
2021 mDNSu16 newrdlength
; // ... and the length of the new RData
2022 mDNSRecordUpdateCallback
*UpdateCallback
;
2023 mDNSu32 UpdateCredits
; // Token-bucket rate limiting of excessive updates
2024 mDNSs32 NextUpdateCredit
; // Time next token is added to bucket
2025 mDNSs32 UpdateBlocked
; // Set if update delaying is in effect
2027 // Field Group 4: Transient uDNS state for Authoritative Records
2028 regState_t state
; // Maybe combine this with resrec.RecordType state? Right now it's ambiguous and confusing.
2029 // e.g. rr->resrec.RecordType can be kDNSRecordTypeUnregistered,
2030 // and rr->state can be regState_Unregistered
2031 // What if we find one of those statements is true and the other false? What does that mean?
2032 mDNSBool uselease
; // dynamic update contains (should contain) lease option
2033 mDNSs32 expire
; // In platform time units: expiration of lease (-1 for static)
2034 mDNSBool Private
; // If zone is private, DNS updates may have to be encrypted to prevent eavesdropping
2035 mDNSOpaque16 updateid
; // Identifier to match update request and response -- also used when transferring records to Sleep Proxy
2036 const domainname
*zone
; // the zone that is updated
2037 mDNSAddr UpdateServer
; // DNS server that handles updates for this zone
2038 mDNSIPPort UpdatePort
; // port on which server accepts dynamic updates
2039 // !!!KRS not technically correct to cache longer than TTL
2040 // SDC Perhaps should keep a reference to the relevant SRV record in the cache?
2042 struct tcpInfo_t
*tcp
;
2044 // uDNS_UpdateRecord support fields
2045 // Do we really need all these in *addition* to NewRData and newrdlength above?
2046 mDNSu16 OrigRDLen
; // previously registered, being deleted
2047 mDNSu16 InFlightRDLen
; // currently being registered
2048 mDNSu16 QueuedRDLen
; // pending operation (re-transmitting if necessary) THEN register the queued update
2050 RData
*InFlightRData
;
2053 // Field Group 5: Large data objects go at the end
2054 domainname namestorage
;
2055 RData rdatastorage
; // Normally the storage is right here, except for oversized records
2056 // rdatastorage MUST be the last thing in the structure -- when using oversized AuthRecords, extra bytes
2057 // are appended after the end of the AuthRecord, logically augmenting the size of the rdatastorage
2058 // DO NOT ADD ANY MORE FIELDS HERE
2061 #define AuthRecord_uDNS(R) ((R)->resrec.InterfaceID == mDNSInterface_Any && !(R)->ForceMCast && !IsLocalDomain((R)->resrec.name))
2062 #define Question_uDNS(Q) ((Q)->InterfaceID == mDNSInterface_Any && !(Q)->ForceMCast && !IsLocalDomain(&(Q)->qname))
2064 // Wrapper struct for Auth Records for higher-level code that cannot use the AuthRecord's ->next pointer field
2065 typedef struct ARListElem
2067 struct ARListElem
*next
;
2068 AuthRecord ar
; // Note: Must be last element of structure, to accomodate oversized AuthRecords
2071 struct CacheGroup_struct
// Header object for a list of CacheRecords with the same name
2073 CacheGroup
*next
; // Next CacheGroup object in this hash table bucket
2074 mDNSu32 namehash
; // Name-based (i.e. case insensitive) hash of name
2075 CacheRecord
*members
; // List of CacheRecords with this same name
2076 CacheRecord
**rrcache_tail
; // Tail end of that list
2077 domainname
*name
; // Common name for all CacheRecords in this list
2078 // Size to here is 20 bytes when compiling 32-bit; 40 bytes when compiling 64-bit
2079 mDNSu8 namestorage
[InlineCacheGroupNameSize
];
2082 struct CacheRecord_struct
2084 CacheRecord
*next
; // Next in list; first element of structure for efficiency reasons
2085 ResourceRecord resrec
; // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit
2087 // Transient state for Cache Records
2088 CacheRecord
*NextInKAList
; // Link to the next element in the chain of known answers to send
2089 mDNSs32 TimeRcvd
; // In platform time units
2090 mDNSs32 DelayDelivery
; // Set if we want to defer delivery of this answer to local clients
2091 mDNSs32 NextRequiredQuery
; // In platform time units
2092 mDNSs32 LastUsed
; // In platform time units
2093 DNSQuestion
*CRActiveQuestion
; // Points to an active question referencing this answer
2094 mDNSu32 UnansweredQueries
; // Number of times we've issued a query for this record without getting an answer
2095 mDNSs32 LastUnansweredTime
; // In platform time units; last time we incremented UnansweredQueries
2096 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
2097 mDNSu32 MPUnansweredQ
; // Multi-packet query handling: Number of times we've seen a query for this record
2098 mDNSs32 MPLastUnansweredQT
; // Multi-packet query handling: Last time we incremented MPUnansweredQ
2099 mDNSu32 MPUnansweredKA
; // Multi-packet query handling: Number of times we've seen this record in a KA list
2100 mDNSBool MPExpectingKA
; // Multi-packet query handling: Set when we increment MPUnansweredQ; allows one KA
2102 CacheRecord
*NextInCFList
; // Set if this is in the list of records we just received with the cache flush bit set
2103 // Size to here is 76 bytes when compiling 32-bit; 104 bytes when compiling 64-bit
2104 RData_small smallrdatastorage
; // Storage for small records is right here (4 bytes header + 68 bytes data = 72 bytes)
2107 // Storage sufficient to hold either a CacheGroup header or a CacheRecord
2108 // -- for best efficiency (to avoid wasted unused storage) they should be the same size
2109 typedef union CacheEntity_union CacheEntity
;
2110 union CacheEntity_union
{ CacheEntity
*next
; CacheGroup cg
; CacheRecord cr
; };
2115 mDNSu8 _extradata
[MaximumRDSize
-InlineCacheRDSize
]; // Glue on the necessary number of extra bytes
2116 domainname namestorage
; // Needs to go *after* the extra rdata bytes
2119 typedef struct HostnameInfo
2121 struct HostnameInfo
*next
;
2122 NATTraversalInfo natinfo
;
2124 AuthRecord arv4
; // registered IPv4 address record
2125 AuthRecord arv6
; // registered IPv6 address record
2126 mDNSRecordCallback
*StatusCallback
; // callback to deliver success or error code to client layer
2127 const void *StatusContext
; // Client Context
2132 DNSServer_Untested
= 0,
2133 DNSServer_Passed
= 1,
2134 DNSServer_Failed
= 2,
2135 DNSServer_Disabled
= 3
2140 DNSServer_FlagDelete
= 1,
2141 DNSServer_FlagNew
= 2
2144 typedef struct DNSServer
2146 struct DNSServer
*next
;
2147 mDNSInterfaceID interface
; // For specialized uses; we can have DNS servers reachable over specific interfaces
2150 mDNSOpaque16 testid
;
2151 mDNSu32 flags
; // Set when we're planning to delete this from the list
2152 mDNSu32 teststate
; // Have we sent bug-detection query to this server?
2153 mDNSs32 lasttest
; // Time we sent last bug-detection query to this server
2154 domainname domain
; // name->server matching for "split dns"
2155 mDNSs32 penaltyTime
; // amount of time this server is penalized
2158 typedef struct ExtraResourceRecord_struct ExtraResourceRecord
;
2159 struct ExtraResourceRecord_struct
2161 ExtraResourceRecord
*next
;
2162 mDNSu32 ClientID
; // Opaque ID field to be used by client to map an AddRecord call to a set of Extra records
2164 // Note: Add any additional fields *before* the AuthRecord in this structure, not at the end.
2165 // In some cases clients can allocate larger chunks of memory and set r->rdata->MaxRDLength to indicate
2166 // that this extra memory is available, which would result in any fields after the AuthRecord getting smashed
2169 // Note: Within an mDNSServiceCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
2170 typedef void mDNSServiceCallback(mDNS
*const m
, ServiceRecordSet
*const sr
, mStatus result
);
2172 // A ServiceRecordSet is basically a convenience structure to group together
2173 // the PTR/SRV/TXT records that make up a standard service registration
2174 // It contains its own ServiceCallback+ServiceContext to report aggregate results up to the next layer of software above
2175 // It also contains:
2176 // * the "_services" PTR record for service enumeration
2177 // * the optional target host name (for proxy registrations)
2178 // * the optional list of SubType PTR records
2179 // * the optional list of additional records attached to the service set (e.g. iChat pictures)
2181 // ... and a bunch of stuff related to uDNS, some of which could be simplified or eliminated
2183 struct ServiceRecordSet_struct
2185 // These internal state fields are used internally by mDNSCore; the client layer needn't be concerned with them.
2186 // No fields need to be set up by the client prior to calling mDNS_RegisterService();
2187 // all required data is passed as parameters to that function.
2189 // Begin uDNS info ****************
2190 // All of these fields should be eliminated
2192 // Note: The current uDNS code keeps an explicit list of registered services, and handles them
2193 // differently to how individual records are treated (this is probably a mistake). What this means is
2194 // that ServiceRecordSets for uDNS are kept in a linked list, whereas ServiceRecordSets for mDNS exist
2195 // just as a convenient placeholder to group the component records together and are not kept on any list.
2196 ServiceRecordSet
*uDNS_next
;
2198 mDNSBool srs_uselease
; // dynamic update contains (should contain) lease option
2199 mDNSBool TestForSelfConflict
; // on name conflict, check if we're just seeing our own orphaned records
2200 mDNSBool Private
; // If zone is private, DNS updates may have to be encrypted to prevent eavesdropping
2203 domainname zone
; // the zone that is updated
2204 mDNSAddr SRSUpdateServer
; // primary name server for the record's zone !!!KRS not technically correct to cache longer than TTL
2205 mDNSIPPort SRSUpdatePort
; // port on which server accepts dynamic updates
2206 NATTraversalInfo NATinfo
;
2207 mDNSBool ClientCallbackDeferred
; // invoke client callback on completion of pending operation(s)
2208 mStatus DeferredStatus
; // status to deliver when above flag is set
2209 mDNSBool SRVUpdateDeferred
; // do we need to change target or port once current operation completes?
2210 mDNSBool SRVChanged
; // temporarily deregistered service because its SRV target or port changed
2211 struct tcpInfo_t
*tcp
;
2213 // End uDNS info ****************
2215 mDNSServiceCallback
*ServiceCallback
;
2216 void *ServiceContext
;
2217 mDNSBool Conflict
; // Set if this record set was forcibly deregistered because of a conflict
2219 ExtraResourceRecord
*Extras
; // Optional list of extra AuthRecords attached to this service registration
2220 mDNSu32 NumSubTypes
;
2221 AuthRecord
*SubTypes
;
2222 AuthRecord RR_ADV
; // e.g. _services._dns-sd._udp.local. PTR _printer._tcp.local.
2223 AuthRecord RR_PTR
; // e.g. _printer._tcp.local. PTR Name._printer._tcp.local.
2224 AuthRecord RR_SRV
; // e.g. Name._printer._tcp.local. SRV 0 0 port target
2225 AuthRecord RR_TXT
; // e.g. Name._printer._tcp.local. TXT PrintQueueName
2226 // Don't add any fields after AuthRecord RR_TXT.
2227 // This is where the implicit extra space goes if we allocate a ServiceRecordSet containing an oversized RR_TXT record
2230 // ***************************************************************************
2233 #pragma mark - Question structures
2236 // We record the last eight instances of each duplicate query
2237 // This gives us v4/v6 on each of Ethernet/AirPort and Firewire, and two free slots "for future expansion"
2238 // If the host has more active interfaces that this it is not fatal -- duplicate question suppression will degrade gracefully.
2239 // Since we will still remember the last eight, the busiest interfaces will still get the effective duplicate question suppression.
2240 #define DupSuppressInfoSize 8
2245 mDNSInterfaceID InterfaceID
;
2246 mDNSs32 Type
; // v4 or v6?
2251 LLQ_InitialRequest
= 1,
2252 LLQ_SecondaryRequest
= 2,
2253 LLQ_Established
= 3,
2259 #define kLLQ_DefLease 7200 // 2 hours
2260 #define kLLQ_MAX_TRIES 3 // retry an operation 3 times max
2261 #define kLLQ_INIT_RESEND 2 // resend an un-ack'd packet after 2 seconds, then double for each additional
2262 // LLQ Operation Codes
2263 #define kLLQOp_Setup 1
2264 #define kLLQOp_Refresh 2
2265 #define kLLQOp_Event 3
2271 LLQErr_ServFull
= 1,
2274 LLQErr_NoSuchLLQ
= 4,
2276 LLQErr_UnknownErr
= 6
2279 enum { NoAnswer_Normal
= 0, NoAnswer_Suspended
= 1, NoAnswer_Fail
= 2 };
2282 #define HMAC_IPAD 0x36
2283 #define HMAC_OPAD 0x5c
2286 #define AutoTunnelUnregistered(X) ( \
2287 (X)->AutoTunnelHostRecord.resrec.RecordType == kDNSRecordTypeUnregistered && \
2288 (X)->AutoTunnelDeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered && \
2289 (X)->AutoTunnelService. resrec.RecordType == kDNSRecordTypeUnregistered )
2291 // Internal data structure to maintain authentication information
2292 typedef struct DomainAuthInfo
2294 struct DomainAuthInfo
*next
;
2295 mDNSs32 deltime
; // If we're planning to delete this DomainAuthInfo, the time we want it deleted
2296 mDNSBool AutoTunnel
;
2297 AuthRecord AutoTunnelHostRecord
; // User-visible hostname; used as SRV target for AutoTunnel services
2298 AuthRecord AutoTunnelTarget
; // Opaque hostname of tunnel endpoint; used as SRV target for AutoTunnelService record
2299 AuthRecord AutoTunnelDeviceInfo
; // Device info of tunnel endpoint
2300 AuthRecord AutoTunnelService
; // Service record (possibly NAT-Mapped) of IKE daemon implementing tunnel endpoint
2301 NATTraversalInfo AutoTunnelNAT
;
2304 char b64keydata
[32];
2305 mDNSu8 keydata_ipad
[HMAC_LEN
]; // padded key for inner hash rounds
2306 mDNSu8 keydata_opad
[HMAC_LEN
]; // padded key for outer hash rounds
2309 // Note: Within an mDNSQuestionCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
2310 typedef enum { QC_rmv
= 0, QC_add
= 1, QC_addnocache
= 2 } QC_result
;
2311 typedef void mDNSQuestionCallback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
);
2312 struct DNSQuestion_struct
2314 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
2317 mDNSs32 DelayAnswering
; // Set if we want to defer answering this question until the cache settles
2318 mDNSs32 LastQTime
; // Last scheduled transmission of this Q on *all* applicable interfaces
2319 mDNSs32 ThisQInterval
; // LastQTime + ThisQInterval is the next scheduled transmission of this Q
2320 // ThisQInterval > 0 for an active question;
2321 // ThisQInterval = 0 for a suspended question that's still in the list
2322 // ThisQInterval = -1 for a cancelled question (should not still be in list)
2323 mDNSs32 ExpectUnicastResp
;// Set when we send a query with the kDNSQClass_UnicastResponse bit set
2324 mDNSs32 LastAnswerPktNum
; // The sequence number of the last response packet containing an answer to this Q
2325 mDNSu32 RecentAnswerPkts
; // Number of answers since the last time we sent this query
2326 mDNSu32 CurrentAnswers
; // Number of records currently in the cache that answer this question
2327 mDNSu32 LargeAnswers
; // Number of answers with rdata > 1024 bytes
2328 mDNSu32 UniqueAnswers
; // Number of answers received with kDNSClass_UniqueRRSet bit set
2329 mDNSInterfaceID FlappingInterface1
;// Set when an interface goes away, to flag if remove events are delivered for this Q
2330 mDNSInterfaceID FlappingInterface2
;// Set when an interface goes away, to flag if remove events are delivered for this Q
2331 DomainAuthInfo
*AuthInfo
; // Non-NULL if query is currently being done using Private DNS
2332 DNSQuestion
*DuplicateOf
;
2333 DNSQuestion
*NextInDQList
;
2334 DupSuppressInfo DupSuppress
[DupSuppressInfoSize
];
2335 mDNSInterfaceID SendQNow
; // The interface this query is being sent on right now
2336 mDNSBool SendOnAll
; // Set if we're sending this question on all active interfaces
2337 mDNSu32 RequestUnicast
; // Non-zero if we want to send query with kDNSQClass_UnicastResponse bit set
2338 mDNSs32 LastQTxTime
; // Last time this Q was sent on one (but not necessarily all) interfaces
2339 mDNSu32 CNAMEReferrals
; // Count of how many CNAME redirections we've done
2341 // Wide Area fields. These are used internally by the uDNS core
2342 UDPSocket
*LocalSocket
;
2343 DNSServer
*qDNSServer
; // Caching server for this query (in the absence of an SRV saying otherwise)
2344 mDNSu8 unansweredQueries
;// The number of unanswered queries to this server
2346 ZoneData
*nta
; // Used for getting zone data for private or LLQ query
2347 mDNSAddr servAddr
; // Address and port learned from _dns-llq, _dns-llq-tls or _dns-query-tls SRV query
2348 mDNSIPPort servPort
;
2349 struct tcpInfo_t
*tcp
;
2350 mDNSu8 NoAnswer
; // Set if we want to suppress answers until tunnel setup has completed
2352 // LLQ-specific fields. These fields are only meaningful when LongLived flag is set
2354 mDNSu32 ReqLease
; // seconds (relative)
2355 mDNSs32 expire
; // ticks (absolute)
2356 mDNSs16 ntries
; // for UDP: the number of packets sent for this LLQ state
2357 // for TCP: there is some ambiguity in the use of this variable, but in general, it is
2358 // the number of TCP/TLS connection attempts for this LLQ state, or
2359 // the number of packets sent for this TCP/TLS connection
2362 // Client API fields: The client must set up these fields *before* calling mDNS_StartQuery()
2363 mDNSInterfaceID InterfaceID
; // Non-zero if you want to issue queries only on a single specific IP interface
2364 mDNSAddr Target
; // Non-zero if you want to direct queries to a specific unicast target address
2365 mDNSIPPort TargetPort
; // Must be set if Target is set
2366 mDNSOpaque16 TargetQID
; // Must be set if Target is set
2370 mDNSBool LongLived
; // Set by client for calls to mDNS_StartQuery to indicate LLQs to unicast layer.
2371 mDNSBool ExpectUnique
; // Set by client if it's expecting unique RR(s) for this question, not shared RRs
2372 mDNSBool ForceMCast
; // Set by client to force mDNS query, even for apparently uDNS names
2373 mDNSBool ReturnIntermed
; // Set by client to request callbacks for intermediate CNAME/NXDOMAIN results
2374 mDNSQuestionCallback
*QuestionCallback
;
2375 void *QuestionContext
;
2380 // Client API fields: The client must set up name and InterfaceID *before* calling mDNS_StartResolveService()
2381 // When the callback is invoked, ip, port, TXTlen and TXTinfo will have been filled in with the results learned from the network.
2383 mDNSInterfaceID InterfaceID
; // ID of the interface the response was received on
2384 mDNSAddr ip
; // Remote (destination) IP address where this service can be accessed
2385 mDNSIPPort port
; // Port where this service can be accessed
2387 mDNSu8 TXTinfo
[2048]; // Additional demultiplexing information (e.g. LPR queue name)
2390 // Note: Within an mDNSServiceInfoQueryCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
2391 typedef struct ServiceInfoQuery_struct ServiceInfoQuery
;
2392 typedef void mDNSServiceInfoQueryCallback(mDNS
*const m
, ServiceInfoQuery
*query
);
2393 struct ServiceInfoQuery_struct
2395 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
2396 // No fields need to be set up by the client prior to calling mDNS_StartResolveService();
2397 // all required data is passed as parameters to that function.
2398 // The ServiceInfoQuery structure memory is working storage for mDNSCore to discover the requested information
2399 // and place it in the ServiceInfo structure. After the client has called mDNS_StopResolveService(), it may
2400 // dispose of the ServiceInfoQuery structure while retaining the results in the ServiceInfo structure.
2410 mDNSServiceInfoQueryCallback
*ServiceInfoQueryCallback
;
2411 void *ServiceInfoQueryContext
;
2414 typedef enum { ZoneServiceUpdate
, ZoneServiceQuery
, ZoneServiceLLQ
} ZoneService
;
2416 typedef void ZoneDataCallback(mDNS
*const m
, mStatus err
, const ZoneData
*result
);
2418 struct ZoneData_struct
2420 domainname ChildName
; // Name for which we're trying to find the responsible server
2421 ZoneService ZoneService
; // Which service we're seeking for this zone (update, query, or LLQ)
2422 domainname
*CurrentSOA
; // Points to somewhere within ChildName
2423 domainname ZoneName
; // Discovered result: Left-hand-side of SOA record
2424 mDNSu16 ZoneClass
; // Discovered result: DNS Class from SOA record
2425 domainname Host
; // Discovered result: Target host from SRV record
2426 mDNSIPPort Port
; // Discovered result: Update port, query port, or LLQ port from SRV record
2427 mDNSAddr Addr
; // Discovered result: Address of Target host from SRV record
2428 mDNSBool ZonePrivate
; // Discovered result: Does zone require encrypted queries?
2429 ZoneDataCallback
*ZoneDataCallback
; // Caller-specified function to be called upon completion
2430 void *ZoneDataContext
;
2431 DNSQuestion question
; // Storage for any active question
2434 extern ZoneData
*StartGetZoneData(mDNS
*const m
, const domainname
*const name
, const ZoneService target
, ZoneDataCallback callback
, void *callbackInfo
);
2435 extern void CancelGetZoneData(mDNS
*const m
, ZoneData
*nta
);
2437 typedef struct DNameListElem
2439 struct DNameListElem
*next
;
2444 #if APPLE_OSX_mDNSResponder
2445 typedef struct ClientTunnel
2447 struct ClientTunnel
*next
;
2449 mDNSBool MarkedForDeletion
;
2450 mDNSv6Addr loc_inner
;
2451 mDNSv4Addr loc_outer
;
2452 mDNSv6Addr rmt_inner
;
2453 mDNSv4Addr rmt_outer
;
2454 mDNSIPPort rmt_outer_port
;
2459 // ***************************************************************************
2462 #pragma mark - NetworkInterfaceInfo_struct
2465 typedef struct NetworkInterfaceInfo_struct NetworkInterfaceInfo
;
2467 // A NetworkInterfaceInfo_struct serves two purposes:
2468 // 1. It holds the address, PTR and HINFO records to advertise a given IP address on a given physical interface
2469 // 2. It tells mDNSCore which physical interfaces are available; each physical interface has its own unique InterfaceID.
2470 // Since there may be multiple IP addresses on a single physical interface,
2471 // there may be multiple NetworkInterfaceInfo_structs with the same InterfaceID.
2472 // In this case, to avoid sending the same packet n times, when there's more than one
2473 // struct with the same InterfaceID, mDNSCore picks one member of the set to be the
2474 // active representative of the set; all others have the 'InterfaceActive' flag unset.
2476 struct NetworkInterfaceInfo_struct
2478 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
2479 NetworkInterfaceInfo
*next
;
2481 mDNSu8 InterfaceActive
; // Set if interface is sending & receiving packets (see comment above)
2482 mDNSu8 IPv4Available
; // If InterfaceActive, set if v4 available on this InterfaceID
2483 mDNSu8 IPv6Available
; // If InterfaceActive, set if v6 available on this InterfaceID
2485 DNSQuestion NetWakeBrowse
;
2486 DNSQuestion NetWakeResolve
[3]; // For fault-tolerance, we try up to three Sleep Proxies
2487 mDNSAddr SPSAddr
[3];
2488 mDNSIPPort SPSPort
[3];
2489 mDNSs32 NextSPSAttempt
; // -1 if we're not currently attempting to register with any Sleep Proxy
2490 mDNSs32 NextSPSAttemptTime
;
2492 // Standard AuthRecords that every Responder host should have (one per active IP address)
2493 AuthRecord RR_A
; // 'A' or 'AAAA' (address) record for our ".local" name
2494 AuthRecord RR_PTR
; // PTR (reverse lookup) record
2495 AuthRecord RR_HINFO
;
2497 // Client API fields: The client must set up these fields *before* calling mDNS_RegisterInterface()
2498 mDNSInterfaceID InterfaceID
; // Identifies physical interface; MUST NOT be 0, -1, or -2
2499 mDNSAddr ip
; // The IPv4 or IPv6 address to advertise
2502 char ifname
[64]; // Windows uses a GUID string for the interface name, which doesn't fit in 16 bytes
2503 mDNSu8 Advertise
; // False if you are only searching on this interface
2504 mDNSu8 McastTxRx
; // Send/Receive multicast on this { InterfaceID, address family } ?
2505 mDNSu8 NetWake
; // Set if Wake-On-Magic-Packet is enabled on this interface
2508 typedef struct SearchListElem
2510 struct SearchListElem
*next
;
2512 int flag
; // -1 means delete, 0 means unchanged, +1 means newly added
2513 DNSQuestion BrowseQ
;
2514 DNSQuestion DefBrowseQ
;
2515 DNSQuestion AutomaticBrowseQ
;
2516 DNSQuestion RegisterQ
;
2517 DNSQuestion DefRegisterQ
;
2518 ARListElem
*AuthRecs
;
2521 // For domain enumeration and automatic browsing
2522 // This is the user's DNS search list.
2523 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
2524 // to discover recommended domains for domain enumeration (browse, default browse, registration,
2525 // default registration) and possibly one or more recommended automatic browsing domains.
2526 extern SearchListElem
*SearchList
; // This really ought to be part of mDNS_struct -- SC
2528 // ***************************************************************************
2531 #pragma mark - Main mDNS object, used to hold all the mDNS state
2534 typedef void mDNSCallback(mDNS
*const m
, mStatus result
);
2536 #define CACHE_HASH_SLOTS 499
2540 mDNS_KnownBug_PhantomInterfaces
= 1,
2541 mDNS_KnownBug_LossySyslog
= 2 // <rdar://problem/6561888>
2546 SleepState_Awake
= 0,
2547 SleepState_Transferring
= 1,
2548 SleepState_Sleeping
= 2
2553 // Internal state fields. These hold the main internal state of mDNSCore;
2554 // the client layer needn't be concerned with them.
2555 // No fields need to be set up by the client prior to calling mDNS_Init();
2556 // all required data is passed as parameters to that function.
2558 mDNS_PlatformSupport
*p
; // Pointer to platform-specific data of indeterminite size
2560 mDNSBool CanReceiveUnicastOn5353
;
2561 mDNSBool AdvertiseLocalAddresses
;
2562 mDNSBool DivertMulticastAdvertisements
; // from interfaces that do not advertise local addresses to local-only
2563 mStatus mDNSPlatformStatus
;
2564 mDNSIPPort UnicastPort4
;
2565 mDNSIPPort UnicastPort6
;
2566 mDNSEthAddr PrimaryMAC
; // Used as unique host ID
2567 mDNSCallback
*MainCallback
;
2570 // For debugging: To catch and report locking failures
2571 mDNSu32 mDNS_busy
; // Incremented between mDNS_Lock/mDNS_Unlock section
2572 mDNSu32 mDNS_reentrancy
; // Incremented when calling a client callback
2573 mDNSu8 lock_rrcache
; // For debugging: Set at times when these lists may not be modified
2574 mDNSu8 lock_Questions
;
2575 mDNSu8 lock_Records
;
2579 char MsgBuffer
[MaxMsg
]; // Temp storage used while building error log messages
2581 // Task Scheduling variables
2582 mDNSs32 timenow_adjust
; // Correction applied if we ever discover time went backwards
2583 mDNSs32 timenow
; // The time that this particular activation of the mDNS code started
2584 mDNSs32 timenow_last
; // The time the last time we ran
2585 mDNSs32 NextScheduledEvent
; // Derived from values below
2586 mDNSs32 ShutdownTime
; // Set when we're shutting down; allows us to skip some unnecessary steps
2587 mDNSs32 SuppressSending
; // Don't send *any* packets during this time
2588 mDNSs32 NextCacheCheck
; // Next time to refresh cache record before it expires
2589 mDNSs32 NextScheduledQuery
; // Next time to send query in its exponential backoff sequence
2590 mDNSs32 NextScheduledProbe
; // Next time to probe for new authoritative record
2591 mDNSs32 NextScheduledResponse
; // Next time to send authoritative record(s) in responses
2592 mDNSs32 NextScheduledNATOp
; // Next time to send NAT-traversal packets
2593 mDNSs32 NextScheduledSPS
; // Next time to purge expiring Sleep Proxy records
2594 mDNSs32 RandomQueryDelay
; // For de-synchronization of query packets on the wire
2595 mDNSu32 RandomReconfirmDelay
; // For de-synchronization of reconfirmation queries on the wire
2596 mDNSs32 PktNum
; // Unique sequence number assigned to each received packet
2597 mDNSu8 SleepState
; // Set if we're sleeping
2598 mDNSu8 SleepSeqNum
; // "Epoch number" of our current period of wakefulness
2599 mDNSu8 SystemWakeOnLANEnabled
; // Set if we want to register with a Sleep Proxy before going to sleep
2600 mDNSu8 SentSleepProxyRegistration
;// Set if we registered (or tried to register) with a Sleep Proxy
2601 mDNSs32 AnnounceOwner
; // After waking from sleep, include OWNER option in packets until this time
2602 mDNSs32 DelaySleep
; // To inhibit re-sleeping too quickly right after wake
2603 mDNSs32 SleepLimit
; // Time window to allow deregistrations, etc.,
2604 // during which underying platform layer should inhibit system sleep
2605 mDNSs32 NextScheduledSPRetry
; // Time next sleep proxy registration action is required.
2606 // Only valid if SleepLimit is nonzero and DelaySleep is zero.
2608 // These fields only required for mDNS Searcher...
2609 DNSQuestion
*Questions
; // List of all registered questions, active and inactive
2610 DNSQuestion
*NewQuestions
; // Fresh questions not yet answered from cache
2611 DNSQuestion
*CurrentQuestion
; // Next question about to be examined in AnswerLocalQuestions()
2612 DNSQuestion
*LocalOnlyQuestions
; // Questions with InterfaceID set to mDNSInterface_LocalOnly
2613 DNSQuestion
*NewLocalOnlyQuestions
; // Fresh local-only questions not yet answered
2614 mDNSu32 rrcache_size
; // Total number of available cache entries
2615 mDNSu32 rrcache_totalused
; // Number of cache entries currently occupied
2616 mDNSu32 rrcache_active
; // Number of cache entries currently occupied by records that answer active questions
2617 mDNSu32 rrcache_report
;
2618 CacheEntity
*rrcache_free
;
2619 CacheGroup
*rrcache_hash
[CACHE_HASH_SLOTS
];
2621 // Fields below only required for mDNS Responder...
2622 domainlabel nicelabel
; // Rich text label encoded using canonically precomposed UTF-8
2623 domainlabel hostlabel
; // Conforms to RFC 1034 "letter-digit-hyphen" ARPANET host name rules
2624 domainname MulticastHostname
; // Fully Qualified "dot-local" Host Name, e.g. "Foo.local."
2625 UTF8str255 HIHardware
;
2626 UTF8str255 HISoftware
;
2627 AuthRecord DeviceInfo
;
2628 AuthRecord
*ResourceRecords
;
2629 AuthRecord
*DuplicateRecords
; // Records currently 'on hold' because they are duplicates of existing records
2630 AuthRecord
*NewLocalRecords
; // Fresh local-only records not yet delivered to local-only questions
2631 AuthRecord
*CurrentRecord
; // Next AuthRecord about to be examined
2632 NetworkInterfaceInfo
*HostInterfaces
;
2633 mDNSs32 ProbeFailTime
;
2634 mDNSu32 NumFailedProbes
;
2635 mDNSs32 SuppressProbes
;
2637 // Unicast-specific data
2638 mDNSs32 NextuDNSEvent
; // uDNS next event
2639 mDNSs32 NextSRVUpdate
; // Time to perform delayed update
2640 mDNSs32 SuppressStdPort53Queries
; // Wait before allowing the next standard unicast query to the user's configured DNS server
2642 ServiceRecordSet
*ServiceRegistrations
;
2643 DNSServer
*DNSServers
; // list of DNS servers
2646 mDNSAddr AdvertisedV4
; // IPv4 address pointed to by hostname
2647 mDNSAddr AdvertisedV6
; // IPv6 address pointed to by hostname
2649 DomainAuthInfo
*AuthInfoList
; // list of domains requiring authentication for updates
2651 DNSQuestion ReverseMap
; // Reverse-map query to find static hostname for service target
2652 DNSQuestion AutomaticBrowseDomainQ
;
2653 domainname StaticHostname
; // Current answer to reverse-map query
2655 HostnameInfo
*Hostnames
; // List of registered hostnames + hostname metadata
2656 mDNSv6Addr AutoTunnelHostAddr
; // IPv6 address advertised for AutoTunnel services on this machine
2657 mDNSBool AutoTunnelHostAddrActive
;
2658 domainlabel AutoTunnelLabel
; // Used to construct hostname for *IPv4* address of tunnel endpoints
2660 mDNSBool RegisterSearchDomains
;
2662 // NAT-Traversal fields
2663 NATTraversalInfo LLQNAT
; // Single shared NAT Traversal to receive inbound LLQ notifications
2664 NATTraversalInfo
*NATTraversals
;
2665 NATTraversalInfo
*CurrentNATTraversal
;
2666 mDNSs32 retryIntervalGetAddr
; // delta between time sent and retry
2667 mDNSs32 retryGetAddr
; // absolute time when we retry
2668 mDNSv4Addr ExternalAddress
;
2670 UDPSocket
*NATMcastRecvskt
; // For receiving NAT-PMP AddrReply multicasts from router on port 5350
2671 mDNSu32 LastNATupseconds
; // NAT engine uptime in seconds, from most recent NAT packet
2672 mDNSs32 LastNATReplyLocalTime
; // Local time in ticks when most recent NAT packet was received
2673 mDNSu16 LastNATMapResultCode
; // Most recent error code for mappings
2675 tcpLNTInfo tcpAddrInfo
; // legacy NAT traversal TCP connection info for external address
2676 tcpLNTInfo tcpDeviceInfo
; // legacy NAT traversal TCP connection info for device info
2677 tcpLNTInfo
*tcpInfoUnmapList
; // list of pending unmap requests
2678 mDNSInterfaceID UPnPInterfaceID
;
2679 UDPSocket
*SSDPSocket
; // For SSDP request/response
2680 mDNSBool SSDPWANPPPConnection
; // whether we should send the SSDP query for WANIPConnection or WANPPPConnection
2681 mDNSIPPort UPnPRouterPort
; // port we send discovery messages to
2682 mDNSIPPort UPnPSOAPPort
; // port we send SOAP messages to
2683 mDNSu8
*UPnPRouterURL
; // router's URL string
2684 mDNSBool UPnPWANPPPConnection
; // whether we're using WANIPConnection or WANPPPConnection
2685 mDNSu8
*UPnPSOAPURL
; // router's SOAP control URL string
2686 mDNSu8
*UPnPRouterAddressString
; // holds both the router's address and port
2687 mDNSu8
*UPnPSOAPAddressString
; // holds both address and port for SOAP messages
2689 // Sleep Proxy Server fields
2690 mDNSu8 SPSType
; // 0 = off, 10-99 encodes desirability metric
2691 mDNSu8 SPSPortability
; // 10-99
2692 mDNSu8 SPSMarginalPower
; // 10-99
2693 mDNSu8 SPSTotalPower
; // 10-99
2694 mDNSu8 SPSState
; // 0 = off, 1 = running, 2 = shutting down, 3 = suspended during sleep
2695 mDNSInterfaceID SPSProxyListChanged
;
2696 UDPSocket
*SPSSocket
;
2697 ServiceRecordSet SPSRecords
;
2698 mDNSQuestionCallback
*SPSBrowseCallback
; // So the platform layer can do something useful with SPS browse results
2699 int ProxyRecords
; // Total number of records we're holding as proxy
2700 #define MAX_PROXY_RECORDS 10000 /* DOS protection: 400 machines at 25 records each */
2702 #if APPLE_OSX_mDNSResponder
2703 ClientTunnel
*TunnelClients
;
2704 uuid_t asl_uuid
; // uuid for ASL logging
2707 // Fixed storage, to avoid creating large objects on the stack
2708 // The imsg is declared as a union with a pointer type to enforce CPU-appropriate alignment
2709 union { DNSMessage m
; void *p
; } imsg
; // Incoming message received from wire
2710 DNSMessage omsg
; // Outgoing message we're building
2711 LargeCacheRecord rec
; // Resource Record extracted from received message
2714 #define FORALL_CACHERECORDS(SLOT,CG,CR) \
2715 for ((SLOT) = 0; (SLOT) < CACHE_HASH_SLOTS; (SLOT)++) \
2716 for ((CG)=m->rrcache_hash[(SLOT)]; (CG); (CG)=(CG)->next) \
2717 for ((CR) = (CG)->members; (CR); (CR)=(CR)->next)
2719 // ***************************************************************************
2722 #pragma mark - Useful Static Constants
2725 extern const mDNSIPPort zeroIPPort
;
2726 extern const mDNSv4Addr zerov4Addr
;
2727 extern const mDNSv6Addr zerov6Addr
;
2728 extern const mDNSEthAddr zeroEthAddr
;
2729 extern const mDNSv4Addr onesIPv4Addr
;
2730 extern const mDNSv6Addr onesIPv6Addr
;
2731 extern const mDNSEthAddr onesEthAddr
;
2732 extern const mDNSAddr zeroAddr
;
2734 extern const OwnerOptData zeroOwner
;
2736 extern const mDNSInterfaceID mDNSInterface_Any
; // Zero
2737 extern const mDNSInterfaceID mDNSInterface_LocalOnly
; // Special value
2738 extern const mDNSInterfaceID mDNSInterface_Unicast
; // Special value
2739 extern const mDNSInterfaceID mDNSInterfaceMark
; // Special value
2741 extern const mDNSIPPort DiscardPort
;
2742 extern const mDNSIPPort SSHPort
;
2743 extern const mDNSIPPort UnicastDNSPort
;
2744 extern const mDNSIPPort SSDPPort
;
2745 extern const mDNSIPPort IPSECPort
;
2746 extern const mDNSIPPort NSIPCPort
;
2747 extern const mDNSIPPort NATPMPAnnouncementPort
;
2748 extern const mDNSIPPort NATPMPPort
;
2749 extern const mDNSIPPort DNSEXTPort
;
2750 extern const mDNSIPPort MulticastDNSPort
;
2751 extern const mDNSIPPort LoopbackIPCPort
;
2752 extern const mDNSIPPort PrivateDNSPort
;
2754 extern const mDNSv4Addr AllDNSAdminGroup
;
2755 extern const mDNSv4Addr AllSystemsMcast
;
2756 extern const mDNSAddr AllDNSLinkGroup_v4
;
2757 extern const mDNSAddr AllDNSLinkGroup_v6
;
2759 extern const mDNSOpaque16 zeroID
;
2760 extern const mDNSOpaque16 onesID
;
2761 extern const mDNSOpaque16 QueryFlags
;
2762 extern const mDNSOpaque16 uQueryFlags
;
2763 extern const mDNSOpaque16 ResponseFlags
;
2764 extern const mDNSOpaque16 UpdateReqFlags
;
2765 extern const mDNSOpaque16 UpdateRespFlags
;
2767 extern const mDNSOpaque64 zeroOpaque64
;
2769 extern mDNSBool StrictUnicastOrdering
;
2771 #define localdomain (*(const domainname *)"\x5" "local")
2772 #define DeviceInfoName (*(const domainname *)"\xC" "_device-info" "\x4" "_tcp")
2773 #define SleepProxyServiceType (*(const domainname *)"\xC" "_sleep-proxy" "\x4" "_udp")
2775 // ***************************************************************************
2778 #pragma mark - Inline functions
2781 #if (defined(_MSC_VER))
2782 #define mDNSinline static __inline
2783 #elif ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
2784 #define mDNSinline static inline
2787 // If we're not doing inline functions, then this header needs to have the extern declarations
2788 #if !defined(mDNSinline)
2789 extern mDNSs32
NonZeroTime(mDNSs32 t
);
2790 extern mDNSu16
mDNSVal16(mDNSOpaque16 x
);
2791 extern mDNSOpaque16
mDNSOpaque16fromIntVal(mDNSu16 v
);
2794 // If we're compiling the particular C file that instantiates our inlines, then we
2795 // define "mDNSinline" (to empty string) so that we generate code in the following section
2796 #if (!defined(mDNSinline) && mDNS_InstantiateInlines)
2802 mDNSinline mDNSs32
NonZeroTime(mDNSs32 t
) { if (t
) return(t
); else return(1); }
2804 mDNSinline mDNSu16
mDNSVal16(mDNSOpaque16 x
) { return((mDNSu16
)((mDNSu16
)x
.b
[0] << 8 | (mDNSu16
)x
.b
[1])); }
2806 mDNSinline mDNSOpaque16
mDNSOpaque16fromIntVal(mDNSu16 v
)
2809 x
.b
[0] = (mDNSu8
)(v
>> 8);
2810 x
.b
[1] = (mDNSu8
)(v
& 0xFF);
2816 // ***************************************************************************
2819 #pragma mark - Main Client Functions
2822 // Every client should call mDNS_Init, passing in storage for the mDNS object and the mDNS_PlatformSupport object.
2824 // Clients that are only advertising services should use mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize.
2825 // Clients that plan to perform queries (mDNS_StartQuery, mDNS_StartBrowse, mDNS_StartResolveService, etc.)
2826 // need to provide storage for the resource record cache, or the query calls will return 'mStatus_NoCache'.
2827 // The rrcachestorage parameter is the address of memory for the resource record cache, and
2828 // the rrcachesize parameter is the number of entries in the CacheRecord array passed in.
2829 // (i.e. the size of the cache memory needs to be sizeof(CacheRecord) * rrcachesize).
2830 // OS X 10.3 Panther uses an initial cache size of 64 entries, and then mDNSCore sends an
2831 // mStatus_GrowCache message if it needs more.
2833 // Most clients should use mDNS_Init_AdvertiseLocalAddresses. This causes mDNSCore to automatically
2834 // create the correct address records for all the hosts interfaces. If you plan to advertise
2835 // services being offered by the local machine, this is almost always what you want.
2836 // There are two cases where you might use mDNS_Init_DontAdvertiseLocalAddresses:
2837 // 1. A client-only device, that browses for services but doesn't advertise any of its own.
2838 // 2. A proxy-registration service, that advertises services being offered by other machines, and takes
2839 // the appropriate steps to manually create the correct address records for those other machines.
2840 // In principle, a proxy-like registration service could manually create address records for its own machine too,
2841 // but this would be pointless extra effort when using mDNS_Init_AdvertiseLocalAddresses does that for you.
2843 // Note that a client-only device that wishes to prohibit multicast advertisements (e.g. from
2844 // higher-layer API calls) must also set DivertMulticastAdvertisements in the mDNS structure and
2845 // advertise local address(es) on a loopback interface.
2847 // When mDNS has finished setting up the client's callback is called
2848 // A client can also spin and poll the mDNSPlatformStatus field to see when it changes from mStatus_Waiting to mStatus_NoError
2850 // Call mDNS_StartExit to tidy up before exiting
2851 // Because exiting may be an asynchronous process (e.g. if unicast records need to be deregistered)
2852 // client layer may choose to wait until mDNS_ExitNow() returns true before calling mDNS_FinalExit().
2854 // Call mDNS_Register with a completed AuthRecord object to register a resource record
2855 // If the resource record type is kDNSRecordTypeUnique (or kDNSknownunique) then if a conflicting resource record is discovered,
2856 // the resource record's mDNSRecordCallback will be called with error code mStatus_NameConflict. The callback should deregister
2857 // the record, and may then try registering the record again after picking a new name (e.g. by automatically appending a number).
2858 // Following deregistration, the RecordCallback will be called with result mStatus_MemFree to signal that it is safe to deallocate
2859 // the record's storage (memory must be freed asynchronously to allow for goodbye packets and dynamic update deregistration).
2861 // Call mDNS_StartQuery to initiate a query. mDNS will proceed to issue Multicast DNS query packets, and any time a response
2862 // is received containing a record which matches the question, the DNSQuestion's mDNSAnswerCallback function will be called
2863 // Call mDNS_StopQuery when no more answers are required
2865 // Care should be taken on multi-threaded or interrupt-driven environments.
2866 // The main mDNS routines call mDNSPlatformLock() on entry and mDNSPlatformUnlock() on exit;
2867 // each platform layer needs to implement these appropriately for its respective platform.
2868 // For example, if the support code on a particular platform implements timer callbacks at interrupt time, then
2869 // mDNSPlatformLock/Unlock need to disable interrupts or do similar concurrency control to ensure that the mDNS
2870 // code is not entered by an interrupt-time timer callback while in the middle of processing a client call.
2872 extern mStatus
mDNS_Init (mDNS
*const m
, mDNS_PlatformSupport
*const p
,
2873 CacheEntity
*rrcachestorage
, mDNSu32 rrcachesize
,
2874 mDNSBool AdvertiseLocalAddresses
,
2875 mDNSCallback
*Callback
, void *Context
);
2876 // See notes above on use of NoCache/ZeroCacheSize
2877 #define mDNS_Init_NoCache mDNSNULL
2878 #define mDNS_Init_ZeroCacheSize 0
2879 // See notes above on use of Advertise/DontAdvertiseLocalAddresses
2880 #define mDNS_Init_AdvertiseLocalAddresses mDNStrue
2881 #define mDNS_Init_DontAdvertiseLocalAddresses mDNSfalse
2882 #define mDNS_Init_NoInitCallback mDNSNULL
2883 #define mDNS_Init_NoInitCallbackContext mDNSNULL
2885 extern void mDNS_ConfigChanged(mDNS
*const m
);
2886 extern void mDNS_GrowCache (mDNS
*const m
, CacheEntity
*storage
, mDNSu32 numrecords
);
2887 extern void mDNS_StartExit (mDNS
*const m
);
2888 extern void mDNS_FinalExit (mDNS
*const m
);
2889 #define mDNS_Close(m) do { mDNS_StartExit(m); mDNS_FinalExit(m); } while(0)
2890 #define mDNS_ExitNow(m, now) ((now) - (m)->ShutdownTime >= 0 || (!(m)->ResourceRecords && !(m)->ServiceRegistrations))
2892 extern mDNSs32
mDNS_Execute (mDNS
*const m
);
2894 extern mStatus
mDNS_Register (mDNS
*const m
, AuthRecord
*const rr
);
2895 extern mStatus
mDNS_Update (mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
2896 const mDNSu16 newrdlength
, RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
);
2897 extern mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
);
2899 extern mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
);
2900 extern mStatus
mDNS_StopQuery (mDNS
*const m
, DNSQuestion
*const question
);
2901 extern mStatus
mDNS_StopQueryWithRemoves(mDNS
*const m
, DNSQuestion
*const question
);
2902 extern mStatus
mDNS_Reconfirm (mDNS
*const m
, CacheRecord
*const cacherr
);
2903 extern mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
);
2904 extern void mDNS_PurgeCacheResourceRecord(mDNS
*const m
, CacheRecord
*rr
);
2905 extern mDNSs32
mDNS_TimeNow(const mDNS
*const m
);
2907 extern mStatus
mDNS_StartNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
);
2908 extern mStatus
mDNS_StopNATOperation(mDNS
*const m
, NATTraversalInfo
*traversal
);
2909 extern mStatus
mDNS_StopNATOperation_internal(mDNS
*m
, NATTraversalInfo
*traversal
);
2911 extern DomainAuthInfo
*GetAuthInfoForName(mDNS
*m
, const domainname
*const name
);
2913 // ***************************************************************************
2916 #pragma mark - Platform support functions that are accessible to the client layer too
2919 extern mDNSs32 mDNSPlatformOneSecond
;
2921 // ***************************************************************************
2924 #pragma mark - General utility and helper functions
2927 // mDNS_RegisterService is a single call to register the set of resource records associated with a given named service.
2929 // mDNS_StartResolveService is single call which is equivalent to multiple calls to mDNS_StartQuery,
2930 // to find the IP address, port number, and demultiplexing information for a given named service.
2931 // As with mDNS_StartQuery, it executes asynchronously, and calls the ServiceInfoQueryCallback when the answer is
2932 // found. After the service is resolved, the client should call mDNS_StopResolveService to complete the transaction.
2933 // The client can also call mDNS_StopResolveService at any time to abort the transaction.
2935 // mDNS_AddRecordToService adds an additional record to a Service Record Set. This record may be deregistered
2936 // via mDNS_RemoveRecordFromService, or by deregistering the service. mDNS_RemoveRecordFromService is passed a
2937 // callback to free the memory associated with the extra RR when it is safe to do so. The ExtraResourceRecord
2938 // object can be found in the record's context pointer.
2940 // mDNS_GetBrowseDomains is a special case of the mDNS_StartQuery call, where the resulting answers
2941 // are a list of PTR records indicating (in the rdata) domains that are recommended for browsing.
2942 // After getting the list of domains to browse, call mDNS_StopQuery to end the search.
2943 // mDNS_GetDefaultBrowseDomain returns the name of the domain that should be highlighted by default.
2945 // mDNS_GetRegistrationDomains and mDNS_GetDefaultRegistrationDomain are the equivalent calls to get the list
2946 // of one or more domains that should be offered to the user as choices for where they may register their service,
2947 // and the default domain in which to register in the case where the user has made no selection.
2949 extern void mDNS_SetupResourceRecord(AuthRecord
*rr
, RData
*RDataStorage
, mDNSInterfaceID InterfaceID
,
2950 mDNSu16 rrtype
, mDNSu32 ttl
, mDNSu8 RecordType
, mDNSRecordCallback Callback
, void *Context
);
2952 extern mStatus
mDNS_RegisterService (mDNS
*const m
, ServiceRecordSet
*sr
,
2953 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
2954 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
2955 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
2956 const mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
);
2957 extern mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
);
2958 extern mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
, mDNSRecordCallback MemFreeCallback
, void *Context
);
2959 extern mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
);
2960 extern mStatus
mDNS_DeregisterService(mDNS
*const m
, ServiceRecordSet
*sr
);
2962 extern mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
2963 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
2964 const domainname
*const host
,
2965 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
);
2966 #define mDNS_DeregisterNoSuchService mDNS_Deregister
2968 extern void mDNS_SetupQuestion(DNSQuestion
*const q
, const mDNSInterfaceID InterfaceID
, const domainname
*const name
,
2969 const mDNSu16 qtype
, mDNSQuestionCallback
*const callback
, void *const context
);
2971 extern mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
2972 const domainname
*const srv
, const domainname
*const domain
,
2973 const mDNSInterfaceID InterfaceID
, mDNSBool ForceMCast
, mDNSQuestionCallback
*Callback
, void *Context
);
2974 #define mDNS_StopBrowse mDNS_StopQuery
2976 extern mStatus
mDNS_StartResolveService(mDNS
*const m
, ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
);
2977 extern void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*query
);
2981 mDNS_DomainTypeBrowse
= 0,
2982 mDNS_DomainTypeBrowseDefault
= 1,
2983 mDNS_DomainTypeBrowseAutomatic
= 2,
2984 mDNS_DomainTypeRegistration
= 3,
2985 mDNS_DomainTypeRegistrationDefault
= 4,
2987 mDNS_DomainTypeMax
= 4
2990 extern const char *const mDNS_DomainTypeNames
[];
2992 extern mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
2993 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
);
2994 #define mDNS_StopGetDomains mDNS_StopQuery
2995 extern mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
, mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
);
2996 #define mDNS_StopAdvertiseDomains mDNS_Deregister
2998 extern mDNSOpaque16
mDNS_NewMessageID(mDNS
*const m
);
3000 extern DNSServer
*GetServerForName(mDNS
*m
, const domainname
*name
, DNSServer
*current
);
3002 // ***************************************************************************
3005 #pragma mark - DNS name utility functions
3008 // In order to expose the full capabilities of the DNS protocol (which allows any arbitrary eight-bit values
3009 // in domain name labels, including unlikely characters like ascii nulls and even dots) all the mDNS APIs
3010 // work with DNS's native length-prefixed strings. For convenience in C, the following utility functions
3011 // are provided for converting between C's null-terminated strings and DNS's length-prefixed strings.
3014 // A simple C structure assignment of a domainname can cause a protection fault by accessing unmapped memory,
3015 // because that object is defined to be 256 bytes long, but not all domainname objects are truly the full size.
3016 // This macro uses mDNSPlatformMemCopy() to make sure it only touches the actual bytes that are valid.
3017 #define AssignDomainName(DST, SRC) do { mDNSu16 len__ = DomainNameLength((SRC)); \
3018 if (len__ <= MAX_DOMAIN_NAME) mDNSPlatformMemCopy((DST)->c, (SRC)->c, len__); else (DST)->c[0] = 0; } while(0)
3020 // Comparison functions
3021 #define SameDomainLabelCS(A,B) ((A)[0] == (B)[0] && mDNSPlatformMemSame((A)+1, (B)+1, (A)[0]))
3022 extern mDNSBool
SameDomainLabel(const mDNSu8
*a
, const mDNSu8
*b
);
3023 extern mDNSBool
SameDomainName(const domainname
*const d1
, const domainname
*const d2
);
3024 extern mDNSBool
SameDomainNameCS(const domainname
*const d1
, const domainname
*const d2
);
3025 extern mDNSBool
IsLocalDomain(const domainname
*d
); // returns true for domains that by default should be looked up using link-local multicast
3027 #define StripFirstLabel(X) ((const domainname *)&(X)->c[(X)->c[0] ? 1 + (X)->c[0] : 0])
3029 #define FirstLabel(X) ((const domainlabel *)(X))
3030 #define SecondLabel(X) ((const domainlabel *)StripFirstLabel(X))
3031 #define ThirdLabel(X) ((const domainlabel *)StripFirstLabel(StripFirstLabel(X)))
3033 extern const mDNSu8
*LastLabel(const domainname
*d
);
3035 // Get total length of domain name, in native DNS format, including terminal root label
3036 // (e.g. length of "com." is 5 (length byte, three data bytes, final zero)
3037 extern mDNSu16
DomainNameLengthLimit(const domainname
*const name
, const mDNSu8
*limit
);
3038 #define DomainNameLength(name) DomainNameLengthLimit((name), (name)->c + MAX_DOMAIN_NAME)
3040 // Append functions to append one or more labels to an existing native format domain name:
3041 // AppendLiteralLabelString adds a single label from a literal C string, with no escape character interpretation.
3042 // AppendDNSNameString adds zero or more labels from a C string using conventional DNS dots-and-escaping interpretation
3043 // AppendDomainLabel adds a single label from a native format domainlabel
3044 // AppendDomainName adds zero or more labels from a native format domainname
3045 extern mDNSu8
*AppendLiteralLabelString(domainname
*const name
, const char *cstr
);
3046 extern mDNSu8
*AppendDNSNameString (domainname
*const name
, const char *cstr
);
3047 extern mDNSu8
*AppendDomainLabel (domainname
*const name
, const domainlabel
*const label
);
3048 extern mDNSu8
*AppendDomainName (domainname
*const name
, const domainname
*const append
);
3050 // Convert from null-terminated string to native DNS format:
3051 // The DomainLabel form makes a single label from a literal C string, with no escape character interpretation.
3052 // The DomainName form makes native format domain name from a C string using conventional DNS interpretation:
3053 // dots separate labels, and within each label, '\.' represents a literal dot, '\\' represents a literal
3054 // backslash and backslash with three decimal digits (e.g. \000) represents an arbitrary byte value.
3055 extern mDNSBool
MakeDomainLabelFromLiteralString(domainlabel
*const label
, const char *cstr
);
3056 extern mDNSu8
*MakeDomainNameFromDNSNameString (domainname
*const name
, const char *cstr
);
3058 // Convert native format domainlabel or domainname back to C string format
3060 // When using ConvertDomainLabelToCString, the target buffer must be MAX_ESCAPED_DOMAIN_LABEL (254) bytes long
3061 // to guarantee there will be no buffer overrun. It is only safe to use a buffer shorter than this in rare cases
3062 // where the label is known to be constrained somehow (for example, if the label is known to be either "_tcp" or "_udp").
3063 // Similarly, when using ConvertDomainNameToCString, the target buffer must be MAX_ESCAPED_DOMAIN_NAME (1009) bytes long.
3064 // See definitions of MAX_ESCAPED_DOMAIN_LABEL and MAX_ESCAPED_DOMAIN_NAME for more detailed explanation.
3065 extern char *ConvertDomainLabelToCString_withescape(const domainlabel
*const name
, char *cstr
, char esc
);
3066 #define ConvertDomainLabelToCString_unescaped(D,C) ConvertDomainLabelToCString_withescape((D), (C), 0)
3067 #define ConvertDomainLabelToCString(D,C) ConvertDomainLabelToCString_withescape((D), (C), '\\')
3068 extern char *ConvertDomainNameToCString_withescape(const domainname
*const name
, char *cstr
, char esc
);
3069 #define ConvertDomainNameToCString_unescaped(D,C) ConvertDomainNameToCString_withescape((D), (C), 0)
3070 #define ConvertDomainNameToCString(D,C) ConvertDomainNameToCString_withescape((D), (C), '\\')
3072 extern void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name
[], domainlabel
*const hostlabel
);
3074 extern mDNSu8
*ConstructServiceName(domainname
*const fqdn
, const domainlabel
*name
, const domainname
*type
, const domainname
*const domain
);
3075 extern mDNSBool
DeconstructServiceName(const domainname
*const fqdn
, domainlabel
*const name
, domainname
*const type
, domainname
*const domain
);
3077 // Note: Some old functions have been replaced by more sensibly-named versions.
3078 // You can uncomment the hash-defines below if you don't want to have to change your source code right away.
3079 // When updating your code, note that (unlike the old versions) *all* the new routines take the target object
3080 // as their first parameter.
3081 //#define ConvertCStringToDomainName(SRC,DST) MakeDomainNameFromDNSNameString((DST),(SRC))
3082 //#define ConvertCStringToDomainLabel(SRC,DST) MakeDomainLabelFromLiteralString((DST),(SRC))
3083 //#define AppendStringLabelToName(DST,SRC) AppendLiteralLabelString((DST),(SRC))
3084 //#define AppendStringNameToName(DST,SRC) AppendDNSNameString((DST),(SRC))
3085 //#define AppendDomainLabelToName(DST,SRC) AppendDomainLabel((DST),(SRC))
3086 //#define AppendDomainNameToName(DST,SRC) AppendDomainName((DST),(SRC))
3088 // ***************************************************************************
3091 #pragma mark - Other utility functions and macros
3094 // mDNS_vsnprintf/snprintf return the number of characters written, excluding the final terminating null.
3095 // The output is always null-terminated: for example, if the output turns out to be exactly buflen long,
3096 // then the output will be truncated by one character to allow space for the terminating null.
3097 // Unlike standard C vsnprintf/snprintf, they return the number of characters *actually* written,
3098 // not the number of characters that *would* have been printed were buflen unlimited.
3099 extern mDNSu32
mDNS_vsnprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, va_list arg
);
3100 extern mDNSu32
mDNS_snprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, ...) IS_A_PRINTF_STYLE_FUNCTION(3,4);
3101 extern mDNSu32
NumCacheRecordsForInterfaceID(const mDNS
*const m
, mDNSInterfaceID id
);
3102 extern char *DNSTypeName(mDNSu16 rrtype
);
3103 extern char *GetRRDisplayString_rdb(const ResourceRecord
*const rr
, const RDataBody
*const rd1
, char *const buffer
);
3104 #define RRDisplayString(m, rr) GetRRDisplayString_rdb(rr, &(rr)->rdata->u, (m)->MsgBuffer)
3105 #define ARDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
3106 #define CRDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
3107 extern mDNSBool
mDNSSameAddress(const mDNSAddr
*ip1
, const mDNSAddr
*ip2
);
3108 extern void IncrementLabelSuffix(domainlabel
*name
, mDNSBool RichText
);
3109 extern mDNSBool
mDNSv4AddrIsRFC1918(mDNSv4Addr
*addr
); // returns true for RFC1918 private addresses
3110 #define mDNSAddrIsRFC1918(X) ((X)->type == mDNSAddrType_IPv4 && mDNSv4AddrIsRFC1918(&(X)->ip.v4))
3112 #define mDNSSameIPPort(A,B) ((A).NotAnInteger == (B).NotAnInteger)
3113 #define mDNSSameOpaque16(A,B) ((A).NotAnInteger == (B).NotAnInteger)
3114 #define mDNSSameOpaque32(A,B) ((A).NotAnInteger == (B).NotAnInteger)
3115 #define mDNSSameOpaque64(A,B) ((A)->l[0] == (B)->l[0] && (A)->l[1] == (B)->l[1])
3117 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
3118 #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])
3119 #define mDNSSameEthAddress(A,B) ((A)->w[0] == (B)->w[0] && (A)->w[1] == (B)->w[1] && (A)->w[2] == (B)->w[2])
3121 #define mDNSIPPortIsZero(A) ((A).NotAnInteger == 0)
3122 #define mDNSOpaque16IsZero(A) ((A).NotAnInteger == 0)
3123 #define mDNSOpaque64IsZero(A) (((A)->l[0] | (A)->l[1] ) == 0)
3124 #define mDNSIPv4AddressIsZero(A) ((A).NotAnInteger == 0)
3125 #define mDNSIPv6AddressIsZero(A) (((A).l[0] | (A).l[1] | (A).l[2] | (A).l[3]) == 0)
3126 #define mDNSEthAddressIsZero(A) (((A).w[0] | (A).w[1] | (A).w[2] ) == 0)
3128 #define mDNSIPv4AddressIsOnes(A) ((A).NotAnInteger == 0xFFFFFFFF)
3129 #define mDNSIPv6AddressIsOnes(A) (((A).l[0] & (A).l[1] & (A).l[2] & (A).l[3]) == 0xFFFFFFFF)
3131 #define mDNSAddressIsAllDNSLinkGroup(X) ( \
3132 ((X)->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address((X)->ip.v4, AllDNSLinkGroup_v4.ip.v4)) || \
3133 ((X)->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address((X)->ip.v6, AllDNSLinkGroup_v6.ip.v6)) )
3135 #define mDNSAddressIsZero(X) ( \
3136 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4)) || \
3137 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6)) )
3139 #define mDNSAddressIsValidNonZero(X) ( \
3140 ((X)->type == mDNSAddrType_IPv4 && !mDNSIPv4AddressIsZero((X)->ip.v4)) || \
3141 ((X)->type == mDNSAddrType_IPv6 && !mDNSIPv6AddressIsZero((X)->ip.v6)) )
3143 #define mDNSAddressIsOnes(X) ( \
3144 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4)) || \
3145 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6)) )
3147 #define mDNSAddressIsValid(X) ( \
3148 ((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) : \
3149 ((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
3151 #define mDNSv4AddressIsLinkLocal(X) ((X)->b[0] == 169 && (X)->b[1] == 254)
3152 #define mDNSv6AddressIsLinkLocal(X) ((X)->b[0] == 0xFE && ((X)->b[1] & 0xC0) == 0x80)
3154 #define mDNSAddressIsLinkLocal(X) ( \
3155 ((X)->type == mDNSAddrType_IPv4) ? mDNSv4AddressIsLinkLocal(&(X)->ip.v4) : \
3156 ((X)->type == mDNSAddrType_IPv6) ? mDNSv6AddressIsLinkLocal(&(X)->ip.v6) : mDNSfalse)
3158 // ***************************************************************************
3161 #pragma mark - Authentication Support
3164 // Unicast DNS and Dynamic Update specific Client Calls
3166 // mDNS_SetSecretForDomain tells the core to authenticate (via TSIG with an HMAC_MD5 hash of the shared secret)
3167 // when dynamically updating a given zone (and its subdomains). The key used in authentication must be in
3168 // domain name format. The shared secret must be a null-terminated base64 encoded string. A minimum size of
3169 // 16 bytes (128 bits) is recommended for an MD5 hash as per RFC 2485.
3170 // Calling this routine multiple times for a zone replaces previously entered values. Call with a NULL key
3171 // to dissable authentication for the zone.
3173 extern mStatus
mDNS_SetSecretForDomain(mDNS
*m
, DomainAuthInfo
*info
,
3174 const domainname
*domain
, const domainname
*keyname
, const char *b64keydata
, mDNSBool AutoTunnel
);
3176 extern void RecreateNATMappings(mDNS
*const m
);
3178 // Hostname/Unicast Interface Configuration
3180 // All hostnames advertised point to one IPv4 address and/or one IPv6 address, set via SetPrimaryInterfaceInfo. Invoking this routine
3181 // updates all existing hostnames to point to the new address.
3183 // A hostname is added via AddDynDNSHostName, which points to the primary interface's v4 and/or v6 addresss
3185 // The status callback is invoked to convey success or failure codes - the callback should not modify the AuthRecord or free memory.
3186 // Added hostnames may be removed (deregistered) via mDNS_RemoveDynDNSHostName.
3188 // Host domains added prior to specification of the primary interface address and computer name will be deferred until
3189 // these values are initialized.
3191 // DNS servers used to resolve unicast queries are specified by mDNS_AddDNSServer.
3192 // For "split" DNS configurations, in which queries for different domains are sent to different servers (e.g. VPN and external),
3193 // a domain may be associated with a DNS server. For standard configurations, specify the root label (".") or NULL.
3195 extern void mDNS_AddDynDNSHostName(mDNS
*m
, const domainname
*fqdn
, mDNSRecordCallback
*StatusCallback
, const void *StatusContext
);
3196 extern void mDNS_RemoveDynDNSHostName(mDNS
*m
, const domainname
*fqdn
);
3197 extern void mDNS_SetPrimaryInterfaceInfo(mDNS
*m
, const mDNSAddr
*v4addr
, const mDNSAddr
*v6addr
, const mDNSAddr
*router
);
3198 extern DNSServer
*mDNS_AddDNSServer(mDNS
*const m
, const domainname
*d
, const mDNSInterfaceID interface
, const mDNSAddr
*addr
, const mDNSIPPort port
);
3199 extern void PenalizeDNSServer(mDNS
*const m
, DNSQuestion
*q
, mDNSBool QueryFail
);
3200 extern void mDNS_AddSearchDomain(const domainname
*const domain
);
3202 // We use ((void *)0) here instead of mDNSNULL to avoid compile warnings on gcc 4.2
3203 #define mDNS_AddSearchDomain_CString(X) \
3204 do { domainname d__; if (((X) != (void*)0) && MakeDomainNameFromDNSNameString(&d__, (X)) && d__.c[0]) mDNS_AddSearchDomain(&d__); } while(0)
3206 // Routines called by the core, exported by DNSDigest.c
3208 // Convert an arbitrary base64 encoded key key into an HMAC key (stored in AuthInfo struct)
3209 extern mDNSs32
DNSDigest_ConstructHMACKeyfromBase64(DomainAuthInfo
*info
, const char *b64key
);
3211 // sign a DNS message. The message must be complete, with all values in network byte order. end points to the end
3212 // of the message, and is modified by this routine. numAdditionals is a pointer to the number of additional
3213 // records in HOST byte order, which is incremented upon successful completion of this routine. The function returns
3214 // the new end pointer on success, and NULL on failure.
3215 extern void DNSDigest_SignMessage(DNSMessage
*msg
, mDNSu8
**end
, DomainAuthInfo
*info
, mDNSu16 tcode
);
3217 #define SwapDNSHeaderBytes(M) do { \
3218 (M)->h.numQuestions = (mDNSu16)((mDNSu8 *)&(M)->h.numQuestions )[0] << 8 | ((mDNSu8 *)&(M)->h.numQuestions )[1]; \
3219 (M)->h.numAnswers = (mDNSu16)((mDNSu8 *)&(M)->h.numAnswers )[0] << 8 | ((mDNSu8 *)&(M)->h.numAnswers )[1]; \
3220 (M)->h.numAuthorities = (mDNSu16)((mDNSu8 *)&(M)->h.numAuthorities)[0] << 8 | ((mDNSu8 *)&(M)->h.numAuthorities)[1]; \
3221 (M)->h.numAdditionals = (mDNSu16)((mDNSu8 *)&(M)->h.numAdditionals)[0] << 8 | ((mDNSu8 *)&(M)->h.numAdditionals)[1]; \
3224 #define DNSDigest_SignMessageHostByteOrder(M,E,INFO) \
3225 do { SwapDNSHeaderBytes(M); DNSDigest_SignMessage((M), (E), (INFO), 0); SwapDNSHeaderBytes(M); } while (0)
3227 // verify a DNS message. The message must be complete, with all values in network byte order. end points to the
3228 // end of the record. tsig is a pointer to the resource record that contains the TSIG OPT record. info is
3229 // the matching key to use for verifying the message. This function expects that the additionals member
3230 // of the DNS message header has already had one subtracted from it.
3231 extern mDNSBool
DNSDigest_VerifyMessage(DNSMessage
*msg
, mDNSu8
*end
, LargeCacheRecord
*tsig
, DomainAuthInfo
*info
, mDNSu16
*rcode
, mDNSu16
*tcode
);
3233 // ***************************************************************************
3236 #pragma mark - PlatformSupport interface
3239 // This section defines the interface to the Platform Support layer.
3240 // Normal client code should not use any of types defined here, or directly call any of the functions defined here.
3241 // The definitions are placed here because sometimes clients do use these calls indirectly, via other supported client operations.
3242 // For example, AssignDomainName is a macro defined using mDNSPlatformMemCopy()
3244 // Every platform support module must provide the following functions.
3245 // mDNSPlatformInit() typically opens a communication endpoint, and starts listening for mDNS packets.
3246 // When Setup is complete, the platform support layer calls mDNSCoreInitComplete().
3247 // mDNSPlatformSendUDP() sends one UDP packet
3248 // When a packet is received, the PlatformSupport code calls mDNSCoreReceive()
3249 // mDNSPlatformClose() tidies up on exit
3251 // Note: mDNSPlatformMemAllocate/mDNSPlatformMemFree are only required for handling oversized resource records and unicast DNS.
3252 // If your target platform has a well-defined specialized application, and you know that all the records it uses
3253 // are InlineCacheRDSize or less, then you can just make a simple mDNSPlatformMemAllocate() stub that always returns
3254 // NULL. InlineCacheRDSize is a compile-time constant, which is set by default to 68. If you need to handle records
3255 // a little larger than this and you don't want to have to implement run-time allocation and freeing, then you
3256 // can raise the value of this constant to a suitable value (at the expense of increased memory usage).
3258 // USE CAUTION WHEN CALLING mDNSPlatformRawTime: The m->timenow_adjust correction factor needs to be added
3259 // Generally speaking:
3260 // Code that's protected by the main mDNS lock should just use the m->timenow value
3261 // Code outside the main mDNS lock should use mDNS_TimeNow(m) to get properly adjusted time
3262 // In certain cases there may be reasons why it's necessary to get the time without taking the lock first
3263 // (e.g. inside the routines that are doing the locking and unlocking, where a call to get the lock would result in a
3264 // recursive loop); in these cases use mDNS_TimeNow_NoLock(m) to get mDNSPlatformRawTime with the proper correction factor added.
3266 // mDNSPlatformUTC returns the time, in seconds, since Jan 1st 1970 UTC and is required for generating TSIG records
3268 extern mStatus
mDNSPlatformInit (mDNS
*const m
);
3269 extern void mDNSPlatformClose (mDNS
*const m
);
3270 extern mStatus
mDNSPlatformSendUDP(const mDNS
*const m
, const void *const msg
, const mDNSu8
*const end
,
3271 mDNSInterfaceID InterfaceID
, UDPSocket
*src
, const mDNSAddr
*dst
, mDNSIPPort dstport
);
3273 extern void mDNSPlatformLock (const mDNS
*const m
);
3274 extern void mDNSPlatformUnlock (const mDNS
*const m
);
3276 extern void mDNSPlatformStrCopy ( void *dst
, const void *src
);
3277 extern mDNSu32
mDNSPlatformStrLen ( const void *src
);
3278 extern void mDNSPlatformMemCopy ( void *dst
, const void *src
, mDNSu32 len
);
3279 extern mDNSBool
mDNSPlatformMemSame (const void *dst
, const void *src
, mDNSu32 len
);
3280 extern void mDNSPlatformMemZero ( void *dst
, mDNSu32 len
);
3281 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
3282 #define mDNSPlatformMemAllocate(X) mallocL(#X, X)
3284 extern void * mDNSPlatformMemAllocate (mDNSu32 len
);
3286 extern void mDNSPlatformMemFree (void *mem
);
3288 // If the platform doesn't have a strong PRNG, we define a naive multiply-and-add based on a seed
3289 // from the platform layer. Long-term, we should embed an arc4 implementation, but the strength
3290 // will still depend on the randomness of the seed.
3291 #if !defined(_PLATFORM_HAS_STRONG_PRNG_) && (_BUILDING_XCODE_PROJECT_ || defined(_WIN32))
3292 #define _PLATFORM_HAS_STRONG_PRNG_ 1
3294 #if _PLATFORM_HAS_STRONG_PRNG_
3295 extern mDNSu32
mDNSPlatformRandomNumber(void);
3297 extern mDNSu32
mDNSPlatformRandomSeed (void);
3298 #endif // _PLATFORM_HAS_STRONG_PRNG_
3300 extern mStatus
mDNSPlatformTimeInit (void);
3301 extern mDNSs32
mDNSPlatformRawTime (void);
3302 extern mDNSs32
mDNSPlatformUTC (void);
3303 #define mDNS_TimeNow_NoLock(m) (mDNSPlatformRawTime() + (m)->timenow_adjust)
3306 extern void mDNSPlatformWriteDebugMsg(const char *msg
);
3308 extern void mDNSPlatformWriteLogMsg(const char *ident
, const char *msg
, mDNSLogLevel_t loglevel
);
3310 #if APPLE_OSX_mDNSResponder
3311 // Utility function for ASL logging
3312 mDNSexport
void mDNSASLLog(uuid_t
*uuid
, const char *subdomain
, const char *result
, const char *signature
, const char *fmt
, ...);
3315 // Platform support modules should provide the following functions to map between opaque interface IDs
3316 // and interface indexes in order to support the DNS-SD API. If your target platform does not support
3317 // multiple interfaces and/or does not support the DNS-SD API, these functions can be empty.
3318 extern mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS
*const m
, mDNSu32 ifindex
);
3319 extern mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(mDNS
*const m
, mDNSInterfaceID id
);
3321 // Every platform support module must provide the following functions if it is to support unicast DNS
3322 // and Dynamic Update.
3323 // All TCP socket operations implemented by the platform layer MUST NOT BLOCK.
3324 // mDNSPlatformTCPConnect initiates a TCP connection with a peer, adding the socket descriptor to the
3325 // main event loop. The return value indicates whether the connection succeeded, failed, or is pending
3326 // (i.e. the call would block.) On return, the descriptor parameter is set to point to the connected socket.
3327 // The TCPConnectionCallback is subsequently invoked when the connection
3328 // completes (in which case the ConnectionEstablished parameter is true), or data is available for
3329 // reading on the socket (indicated by the ConnectionEstablished parameter being false.) If the connection
3330 // asynchronously fails, the TCPConnectionCallback should be invoked as usual, with the error being
3331 // returned in subsequent calls to PlatformReadTCP or PlatformWriteTCP. (This allows for platforms
3332 // with limited asynchronous error detection capabilities.) PlatformReadTCP and PlatformWriteTCP must
3333 // return the number of bytes read/written, 0 if the call would block, and -1 if an error. PlatformReadTCP
3334 // should set the closed argument if the socket has been closed.
3335 // PlatformTCPCloseConnection must close the connection to the peer and remove the descriptor from the
3336 // event loop. CloseConnectin may be called at any time, including in a ConnectionCallback.
3340 kTCPSocketFlags_Zero
= 0,
3341 kTCPSocketFlags_UseTLS
= (1 << 0)
3344 typedef void (*TCPConnectionCallback
)(TCPSocket
*sock
, void *context
, mDNSBool ConnectionEstablished
, mStatus err
);
3345 extern TCPSocket
*mDNSPlatformTCPSocket(mDNS
*const m
, TCPSocketFlags flags
, mDNSIPPort
*port
); // creates a TCP socket
3346 extern TCPSocket
*mDNSPlatformTCPAccept(TCPSocketFlags flags
, int sd
);
3347 extern int mDNSPlatformTCPGetFD(TCPSocket
*sock
);
3348 extern mStatus
mDNSPlatformTCPConnect(TCPSocket
*sock
, const mDNSAddr
*dst
, mDNSOpaque16 dstport
, mDNSInterfaceID InterfaceID
,
3349 TCPConnectionCallback callback
, void *context
);
3350 extern void mDNSPlatformTCPCloseConnection(TCPSocket
*sock
);
3351 extern long mDNSPlatformReadTCP(TCPSocket
*sock
, void *buf
, unsigned long buflen
, mDNSBool
*closed
);
3352 extern long mDNSPlatformWriteTCP(TCPSocket
*sock
, const char *msg
, unsigned long len
);
3353 extern UDPSocket
*mDNSPlatformUDPSocket(mDNS
*const m
, const mDNSIPPort requestedport
);
3354 extern void mDNSPlatformUDPClose(UDPSocket
*sock
);
3355 extern void mDNSPlatformReceiveBPF_fd(mDNS
*const m
, int fd
);
3356 extern void mDNSPlatformUpdateProxyList(mDNS
*const m
, const mDNSInterfaceID InterfaceID
);
3357 extern void mDNSPlatformSendRawPacket(const void *const msg
, const mDNSu8
*const end
, mDNSInterfaceID InterfaceID
);
3358 extern void mDNSPlatformSetLocalARP(const mDNSv4Addr
*const tpa
, const mDNSEthAddr
*const tha
, mDNSInterfaceID InterfaceID
);
3359 extern void mDNSPlatformSourceAddrForDest(mDNSAddr
*const src
, const mDNSAddr
*const dst
);
3361 // mDNSPlatformTLSSetupCerts/mDNSPlatformTLSTearDownCerts used by dnsextd
3362 extern mStatus
mDNSPlatformTLSSetupCerts(void);
3363 extern void mDNSPlatformTLSTearDownCerts(void);
3365 // Platforms that support unicast browsing and dynamic update registration for clients who do not specify a domain
3366 // in browse/registration calls must implement these routines to get the "default" browse/registration list.
3368 extern void mDNSPlatformSetDNSConfig(mDNS
*const m
, mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
, DNameListElem
**BrowseDomains
);
3369 extern mStatus
mDNSPlatformGetPrimaryInterface(mDNS
*const m
, mDNSAddr
*v4
, mDNSAddr
*v6
, mDNSAddr
*router
);
3370 extern void mDNSPlatformDynDNSHostNameStatusChanged(const domainname
*const dname
, const mStatus status
);
3372 #ifdef _LEGACY_NAT_TRAVERSAL_
3373 // Support for legacy NAT traversal protocols, implemented by the platform layer and callable by the core.
3374 extern void LNT_SendDiscoveryMsg(mDNS
*m
);
3375 extern void LNT_ConfigureRouterInfo(mDNS
*m
, const mDNSInterfaceID InterfaceID
, mDNSu8
*data
, mDNSu16 len
);
3376 extern mStatus
LNT_GetExternalAddress(mDNS
*m
);
3377 extern mStatus
LNT_MapPort(mDNS
*m
, NATTraversalInfo
*n
);
3378 extern mStatus
LNT_UnmapPort(mDNS
*m
, NATTraversalInfo
*n
);
3379 extern void LNT_ClearState(mDNS
*const m
);
3380 #endif // _LEGACY_NAT_TRAVERSAL_
3382 // The core mDNS code provides these functions, for the platform support code to call at appropriate times
3384 // mDNS_SetFQDN() is called once on startup (typically from mDNSPlatformInit())
3385 // and then again on each subsequent change of the host name.
3387 // mDNS_RegisterInterface() is used by the platform support layer to inform mDNSCore of what
3388 // physical and/or logical interfaces are available for sending and receiving packets.
3389 // Typically it is called on startup for each available interface, but register/deregister may be
3390 // called again later, on multiple occasions, to inform the core of interface configuration changes.
3391 // If set->Advertise is set non-zero, then mDNS_RegisterInterface() also registers the standard
3392 // resource records that should be associated with every publicised IP address/interface:
3393 // -- Name-to-address records (A/AAAA)
3394 // -- Address-to-name records (PTR)
3395 // -- Host information (HINFO)
3396 // IMPORTANT: The specified mDNSInterfaceID MUST NOT be 0, -1, or -2; these values have special meaning
3397 // mDNS_RegisterInterface does not result in the registration of global hostnames via dynamic update -
3398 // see mDNS_SetPrimaryInterfaceInfo, mDNS_AddDynDNSHostName, etc. for this purpose.
3399 // Note that the set may be deallocated immediately after it is deregistered via mDNS_DeegisterInterface.
3401 // mDNS_RegisterDNS() is used by the platform support layer to provide the core with the addresses of
3402 // available domain name servers for unicast queries/updates. RegisterDNS() should be called once for
3403 // each name server, typically at startup, or when a new name server becomes available. DeregiterDNS()
3404 // must be called whenever a registered name server becomes unavailable. DeregisterDNSList deregisters
3405 // all registered servers. mDNS_DNSRegistered() returns true if one or more servers are registered in the core.
3407 // mDNSCoreInitComplete() is called when the platform support layer is finished.
3408 // Typically this is at the end of mDNSPlatformInit(), but may be later
3409 // (on platforms like OT that allow asynchronous initialization of the networking stack).
3411 // mDNSCoreReceive() is called when a UDP packet is received
3413 // mDNSCoreMachineSleep() is called when the machine sleeps or wakes
3414 // (This refers to heavyweight laptop-style sleep/wake that disables network access,
3415 // not lightweight second-by-second CPU power management modes.)
3417 extern void mDNS_SetFQDN(mDNS
*const m
);
3418 extern void mDNS_ActivateNetWake_internal (mDNS
*const m
, NetworkInterfaceInfo
*set
);
3419 extern void mDNS_DeactivateNetWake_internal(mDNS
*const m
, NetworkInterfaceInfo
*set
);
3420 extern mStatus
mDNS_RegisterInterface (mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
);
3421 extern void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
, mDNSBool flapping
);
3422 extern void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
);
3423 extern void mDNSCoreReceive(mDNS
*const m
, void *const msg
, const mDNSu8
*const end
,
3424 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
,
3425 const mDNSAddr
*const dstaddr
, const mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
);
3426 extern void mDNSCoreRestartQueries(mDNS
*const m
);
3427 extern mDNSBool
mDNSCoreHaveAdvertisedMulticastServices(mDNS
*const m
);
3428 extern void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool wake
);
3429 extern mDNSBool
mDNSCoreReadyForSleep(mDNS
*m
, mDNSs32 now
);
3430 extern mDNSs32
mDNSCoreIntervalToNextWake(mDNS
*const m
, mDNSs32 now
);
3432 extern void mDNSCoreBeSleepProxyServer(mDNS
*const m
, mDNSu8 sps
, mDNSu8 port
, mDNSu8 marginalpower
, mDNSu8 totpower
);
3433 extern void mDNSCoreReceiveRawPacket (mDNS
*const m
, const mDNSu8
*const p
, const mDNSu8
*const end
, const mDNSInterfaceID InterfaceID
);
3435 extern mDNSBool
mDNSAddrIsDNSMulticast(const mDNSAddr
*ip
);
3437 extern CacheRecord
*CreateNewCacheEntry(mDNS
*const m
, const mDNSu32 slot
, CacheGroup
*cg
);
3438 extern void GrantCacheExtensions(mDNS
*const m
, DNSQuestion
*q
, mDNSu32 lease
);
3439 extern void MakeNegativeCacheRecord(mDNS
*const m
, CacheRecord
*const cr
,
3440 const domainname
*const name
, const mDNSu32 namehash
, const mDNSu16 rrtype
, const mDNSu16 rrclass
, mDNSu32 ttl_seconds
, mDNSInterfaceID InterfaceID
);
3441 extern void CompleteDeregistration(mDNS
*const m
, AuthRecord
*rr
);
3442 extern void FindSPSInCache(mDNS
*const m
, const DNSQuestion
*const q
, const CacheRecord
*sps
[3]);
3443 #define PrototypeSPSName(X) ((X)[0] >= 11 && (X)[3] == '-' && (X)[ 4] == '9' && (X)[ 5] == '9' && \
3444 (X)[6] == '-' && (X)[ 7] == '9' && (X)[ 8] == '9' && \
3445 (X)[9] == '-' && (X)[10] == '9' && (X)[11] == '9' )
3446 #define ValidSPSName(X) ((X)[0] >= 5 && mDNSIsDigit((X)[1]) && mDNSIsDigit((X)[2]) && mDNSIsDigit((X)[4]) && mDNSIsDigit((X)[5]))
3447 #define SPSMetric(X) (!ValidSPSName(X) || PrototypeSPSName(X) ? 1000000 : \
3448 ((X)[1]-'0') * 100000 + ((X)[2]-'0') * 10000 + ((X)[4]-'0') * 1000 + ((X)[5]-'0') * 100 + ((X)[7]-'0') * 10 + ((X)[8]-'0'))
3449 extern void AnswerCurrentQuestionWithResourceRecord(mDNS
*const m
, CacheRecord
*const rr
, const QC_result AddRecord
);
3450 extern char *InterfaceNameForID(mDNS
*const m
, const mDNSInterfaceID InterfaceID
);
3452 // For now this AutoTunnel stuff is specific to Mac OS X.
3453 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
3454 #if APPLE_OSX_mDNSResponder
3455 extern void AutoTunnelCallback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
);
3456 extern void AddNewClientTunnel(mDNS
*const m
, DNSQuestion
*const q
);
3457 extern void SetupLocalAutoTunnelInterface_internal(mDNS
*const m
);
3458 extern void UpdateAutoTunnelDomainStatuses(const mDNS
*const m
);
3459 extern mStatus
ActivateLocalProxy(mDNS
*const m
, char *ifname
);
3462 // ***************************************************************************
3465 #pragma mark - Compile-Time assertion checks
3468 // Some C compiler cleverness. We can make the compiler check certain things for
3469 // us, and report compile-time errors if anything is wrong. The usual way to do
3470 // this would be to use a run-time "if" statement, but then you don't find out
3471 // what's wrong until you run the software. This way, if the assertion condition
3472 // is false, the array size is negative, and the complier complains immediately.
3474 struct CompileTimeAssertionChecks_mDNS
3476 // Check that the compiler generated our on-the-wire packet format structure definitions
3477 // properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
3478 char assert0
[(sizeof(rdataSRV
) == 262 ) ? 1 : -1];
3479 char assert1
[(sizeof(DNSMessageHeader
) == 12 ) ? 1 : -1];
3480 char assert2
[(sizeof(DNSMessage
) == 12+AbsoluteMaxDNSMessageData
) ? 1 : -1];
3481 char assert3
[(sizeof(mDNSs8
) == 1 ) ? 1 : -1];
3482 char assert4
[(sizeof(mDNSu8
) == 1 ) ? 1 : -1];
3483 char assert5
[(sizeof(mDNSs16
) == 2 ) ? 1 : -1];
3484 char assert6
[(sizeof(mDNSu16
) == 2 ) ? 1 : -1];
3485 char assert7
[(sizeof(mDNSs32
) == 4 ) ? 1 : -1];
3486 char assert8
[(sizeof(mDNSu32
) == 4 ) ? 1 : -1];
3487 char assert9
[(sizeof(mDNSOpaque16
) == 2 ) ? 1 : -1];
3488 char assertA
[(sizeof(mDNSOpaque32
) == 4 ) ? 1 : -1];
3489 char assertB
[(sizeof(mDNSOpaque128
) == 16 ) ? 1 : -1];
3490 char assertC
[(sizeof(CacheRecord
) == sizeof(CacheGroup
) ) ? 1 : -1];
3491 char assertD
[(sizeof(int) >= 4 ) ? 1 : -1];
3492 char assertE
[(StandardAuthRDSize
>= 256 ) ? 1 : -1];
3493 char assertF
[(sizeof(EthernetHeader
) == 14 ) ? 1 : -1];
3494 char assertG
[(sizeof(ARP_EthIP
) == 28 ) ? 1 : -1];
3495 char assertH
[(sizeof(IPv4Header
) == 20 ) ? 1 : -1];
3496 char assertI
[(sizeof(IPv6Header
) == 40 ) ? 1 : -1];
3497 char assertJ
[(sizeof(IPv6ND
) == 24 ) ? 1 : -1];
3498 char assertK
[(sizeof(UDPHeader
) == 8 ) ? 1 : -1];
3499 char assertL
[(sizeof(IKEHeader
) == 28 ) ? 1 : -1];
3500 char assertM
[(sizeof(TCPHeader
) == 20 ) ? 1 : -1];
3502 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
3503 // other overly-large structures instead of having a pointer to them, can inadvertently
3504 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
3505 char sizecheck_RDataBody
[(sizeof(RDataBody
) == 264) ? 1 : -1];
3506 char sizecheck_ResourceRecord
[(sizeof(ResourceRecord
) <= 56) ? 1 : -1];
3507 char sizecheck_AuthRecord
[(sizeof(AuthRecord
) <= 1000) ? 1 : -1];
3508 char sizecheck_CacheRecord
[(sizeof(CacheRecord
) <= 176) ? 1 : -1];
3509 char sizecheck_CacheGroup
[(sizeof(CacheGroup
) <= 176) ? 1 : -1];
3510 char sizecheck_DNSQuestion
[(sizeof(DNSQuestion
) <= 728) ? 1 : -1];
3511 char sizecheck_ZoneData
[(sizeof(ZoneData
) <= 1560) ? 1 : -1];
3512 char sizecheck_NATTraversalInfo
[(sizeof(NATTraversalInfo
) <= 192) ? 1 : -1];
3513 char sizecheck_HostnameInfo
[(sizeof(HostnameInfo
) <= 2800) ? 1 : -1];
3514 char sizecheck_DNSServer
[(sizeof(DNSServer
) <= 312) ? 1 : -1];
3515 char sizecheck_NetworkInterfaceInfo
[(sizeof(NetworkInterfaceInfo
) <= 5968) ? 1 : -1];
3516 char sizecheck_ServiceRecordSet
[(sizeof(ServiceRecordSet
) <= 5500) ? 1 : -1];
3517 char sizecheck_DomainAuthInfo
[(sizeof(DomainAuthInfo
) <= 5500) ? 1 : -1];
3518 char sizecheck_ServiceInfoQuery
[(sizeof(ServiceInfoQuery
) <= 2944) ? 1 : -1];
3519 #if APPLE_OSX_mDNSResponder
3520 char sizecheck_ClientTunnel
[(sizeof(ClientTunnel
) <= 1072) ? 1 : -1];
3524 // ***************************************************************************