2 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
23 * @APPLE_LICENSE_HEADER_END@
25 Change History (most recent first):
27 $Log: mDNSClientAPI.h,v $
28 Revision 1.177 2004/06/05 00:04:26 cheshire
29 <rdar://problem/3668639>: wide-area domains should be returned in reg. domain enumeration
31 Revision 1.176 2004/06/04 08:58:29 ksekar
32 <rdar://problem/3668624>: Keychain integration for secure dynamic update
34 Revision 1.175 2004/06/04 00:15:06 cheshire
35 Move misplaced brackets
37 Revision 1.174 2004/06/03 23:30:16 cheshire
38 Remove extraneous blank lines and white space
40 Revision 1.173 2004/06/03 03:09:58 ksekar
41 <rdar://problem/3668626>: Garbage Collection for Dynamic Updates
43 Revision 1.172 2004/06/01 23:46:50 ksekar
44 <rdar://problem/3675149>: DynDNS: dynamically look up LLQ/Update ports
46 Revision 1.171 2004/05/28 23:42:37 ksekar
47 <rdar://problem/3258021>: Feature: DNS server->client notification on record changes (#7805)
49 Revision 1.170 2004/05/18 23:51:25 cheshire
50 Tidy up all checkin comments to use consistent "<rdar://problem/xxxxxxx>" format for bug numbers
52 Revision 1.169 2004/05/13 04:54:20 ksekar
53 Unified list copy/free code. Added symetric list for
55 Revision 1.168 2004/05/12 22:03:09 ksekar
56 Made GetSearchDomainList a true platform-layer call (declaration moved
57 from mDNSMacOSX.h to mDNSClientAPI.h), impelemted to return "local"
58 only on non-OSX platforms. Changed call to return a copy of the list
59 to avoid shared memory issues. Added a routine to free the list.
61 Revision 1.167 2004/04/22 04:07:01 cheshire
62 Fix from Bob Bradley: Don't try to do inline functions on compilers that don't support it
64 Revision 1.166 2004/04/22 03:15:56 cheshire
65 Fix use of "struct __attribute__((__packed__))" so it only applies on GCC >= 2.9
67 Revision 1.165 2004/04/22 03:05:28 cheshire
68 kDNSClass_ANY should be kDNSQClass_ANY
70 Revision 1.164 2004/04/21 02:55:03 cheshire
71 Update comments describing 'InterfaceActive' field
73 Revision 1.163 2004/04/21 02:49:11 cheshire
74 To reduce future confusion, renamed 'TxAndRx' to 'McastTxRx'
76 Revision 1.162 2004/04/15 00:51:28 bradley
77 Minor tweaks for Windows and C++ builds. Added casts for signed/unsigned integers and 64-bit pointers.
78 Prefix some functions with mDNS to avoid conflicts. Disable benign warnings on Microsoft compilers.
80 Revision 1.161 2004/04/14 23:09:28 ksekar
81 Support for TSIG signed dynamic updates.
83 Revision 1.160 2004/04/09 17:40:26 cheshire
84 Remove unnecessary "Multicast" field -- it duplicates the semantics of the existing McastTxRx field
86 Revision 1.159 2004/04/09 16:37:15 cheshire
87 Suggestion from Bob Bradley:
88 Move NumCacheRecordsForInterfaceID() to DNSCommon.c so it's available to all platform layers
90 Revision 1.158 2004/04/02 19:38:33 cheshire
91 Update comment about typical RR TTLs
93 Revision 1.157 2004/04/02 19:35:53 cheshire
94 Add clarifying comments about legal mDNSInterfaceID values
96 Revision 1.156 2004/04/02 19:19:48 cheshire
97 Add code to do optional logging of multi-packet KA list time intervals
99 Revision 1.155 2004/03/24 00:29:45 ksekar
100 Make it safe to call StopQuery in a unicast question callback
102 Revision 1.154 2004/03/20 01:05:49 cheshire
103 Test __LP64__ and __ILP64__ to compile properly on a wider range of 64-bit architectures
105 Revision 1.153 2004/03/13 01:57:33 ksekar
106 <rdar://problem/3192546>: DynDNS: Dynamic update of service records
108 Revision 1.152 2004/03/09 02:27:16 cheshire
109 Remove erroneous underscore in 'packed_struct' (makes no difference now, but might in future)
111 Revision 1.151 2004/03/02 03:21:56 cheshire
112 <rdar://problem/3549576> Properly support "_services._dns-sd._udp" meta-queries
114 Revision 1.150 2004/02/21 02:06:24 cheshire
115 Can't use anonymous unions -- they're non-standard and don't work on all compilers
117 Revision 1.149 2004/02/06 23:04:19 ksekar
118 Basic Dynamic Update support via mDNS_Register (dissabled via
119 UNICAST_REGISTRATION #define)
121 Revision 1.148 2004/02/03 19:47:36 ksekar
122 Added an asyncronous state machine mechanism to uDNS.c, including
123 calls to find the parent zone for a domain name. Changes include code
124 in repository previously dissabled via "#if 0 //incomplete". Codepath
125 is currently unused, and will be called to create update records, etc.
127 Revision 1.147 2004/02/03 18:57:35 cheshire
128 Update comment for "IsLocalDomain()"
130 Revision 1.146 2004/01/30 02:20:24 bradley
131 Map inline to __inline when building with Microsoft C compilers since they do not support C99 inline.
133 Revision 1.145 2004/01/29 02:59:17 ksekar
134 Unicast DNS: Changed from a resource record oriented question/response
135 matching to packet based matching. New callback architecture allows
136 collections of records in a response to be processed differently
137 depending on the nature of the request, and allows the same structure
138 to be used for internal and client-driven queries with different processing needs.
140 Revision 1.144 2004/01/28 20:20:45 ksekar
141 Unified ActiveQueries and ActiveInternalQueries lists, using a flag to
142 demux them. Check-in includes work-in-progress code, #ifdef'd out.
144 Revision 1.143 2004/01/28 03:41:00 cheshire
145 <rdar://problem/3541946>: Need ability to do targeted queries as well as multicast queries
147 Revision 1.142 2004/01/28 02:30:07 ksekar
148 Added default Search Domains to unicast browsing, controlled via
149 Networking sharing prefs pane. Stopped sending unicast messages on
150 every interface. Fixed unicast resolving via mach-port API.
152 Revision 1.141 2004/01/27 20:15:22 cheshire
153 <rdar://problem/3541288>: Time to prune obsolete code for listening on port 53
155 Revision 1.140 2004/01/24 23:37:08 cheshire
156 At Kiren's suggestion, made functions to convert mDNSOpaque16s to/from integer values
158 Revision 1.139 2004/01/24 08:46:26 bradley
159 Added InterfaceID<->Index platform interfaces since they are now used by all platforms for the DNS-SD APIs.
161 Revision 1.138 2004/01/24 04:59:15 cheshire
162 Fixes so that Posix/Linux, OS9, Windows, and VxWorks targets build again
164 Revision 1.137 2004/01/24 03:40:56 cheshire
165 Move mDNSAddrIsDNSMulticast() from DNSCommon.h to mDNSClientAPI.h so clients can use it
167 Revision 1.136 2004/01/24 03:38:27 cheshire
168 Fix minor syntactic error: Headers should use "extern" declarations, not "mDNSexport"
170 Revision 1.135 2004/01/23 23:23:15 ksekar
171 Added TCP support for truncated unicast messages.
173 Revision 1.134 2004/01/22 03:54:11 cheshire
174 Create special meta-interface 'mDNSInterface_ForceMCast' (-2),
175 which means "do this query via multicast, even if it's apparently a unicast domain"
177 Revision 1.133 2004/01/22 03:48:41 cheshire
178 Make sure uDNS client doesn't accidentally use query ID zero
180 Revision 1.132 2004/01/22 03:43:08 cheshire
181 Export constants like mDNSInterface_LocalOnly so that the client layers can use them
183 Revision 1.131 2004/01/21 21:53:18 cheshire
184 <rdar://problem/3448144>: Don't try to receive unicast responses if we're not the first to bind to the UDP port
186 Revision 1.130 2003/12/14 05:05:29 cheshire
187 Add comments explaining mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize
189 Revision 1.129 2003/12/13 03:05:27 ksekar
190 <rdar://problem/3192548>: DynDNS: Unicast query of service records
192 Revision 1.128 2003/12/01 21:44:23 cheshire
193 Add mStatus_BadInterfaceErr = -65552 for consistency with dns_sd.h
195 Revision 1.127 2003/12/01 18:26:37 cheshire
196 Also pack the OpaqueXX union types. Otherwise, on some systems, mDNSOpaque16 is four bytes!
198 Revision 1.126 2003/12/01 18:23:48 cheshire
199 <rdar://problem/3464646>: Scalar size problem in mDNS code on some 64-bit architectures
201 Revision 1.125 2003/11/22 00:18:27 cheshire
202 Add compile-time asserts to verify correct sizes of mDNSu32, mDNSOpaque16, etc.
204 Revision 1.124 2003/11/20 22:59:54 cheshire
205 Changed runtime checks in mDNS.c to be compile-time checks in mDNSClientAPI.h
206 Thanks to Bob Bradley for suggesting the ingenious compiler trick to make this work.
208 Revision 1.123 2003/11/20 22:53:01 cheshire
209 Add comment about MAX_ESCAPED_DOMAIN_LABEL
211 Revision 1.122 2003/11/20 20:49:53 cheshire
212 Another fix from HP: Use packedstruct macro to ensure proper packing for on-the-wire packet structures
214 Revision 1.121 2003/11/20 05:01:38 cheshire
215 Update comments; add explanation of Advertise/DontAdvertiseLocalAddresses
217 Revision 1.120 2003/11/14 20:59:08 cheshire
218 Clients can't use AssignDomainName macro because mDNSPlatformMemCopy is defined in mDNSPlatformFunctions.h.
219 Best solution is just to combine mDNSClientAPI.h and mDNSPlatformFunctions.h into a single file.
221 Revision 1.119 2003/11/14 19:47:52 cheshire
222 Define symbol MAX_ESCAPED_DOMAIN_NAME to indicate recommended buffer size for ConvertDomainNameToCString
224 Revision 1.118 2003/11/14 19:18:34 cheshire
225 Move AssignDomainName macro to mDNSClientAPI.h to that client layers can use it too
227 Revision 1.117 2003/11/08 23:32:24 cheshire
228 Gave name to anonymous struct, to avoid errors on certain compilers.
229 (Thanks to ramaprasad.kr@hp.com for reporting this.)
231 Revision 1.116 2003/11/07 03:32:56 cheshire
232 <rdar://problem/3472153> mDNSResponder delivers answers in inconsistent order
233 This is the real fix. Checkin 1.312 was overly simplistic; Calling GetFreeCacheRR() can sometimes
234 purge records from the cache, causing tail pointer *rp to be stale on return. The correct fix is
235 to maintain a system-wide tail pointer for each cache slot, and then if neccesary GetFreeCacheRR()
236 can update this pointer, so that mDNSCoreReceiveResponse() appends records in the right place.
238 Revision 1.115 2003/09/23 00:53:54 cheshire
239 NumFailedProbes should be unsigned
241 Revision 1.114 2003/08/29 19:44:15 cheshire
242 <rdar://problem/3400967> Traffic reduction: Eliminate synchronized QUs when a new service appears
243 1. Use m->RandomQueryDelay to impose a random delay in the range 0-500ms on queries
244 that already have at least one unique answer in the cache
245 2. For these queries, go straight to QM, skipping QU
247 Revision 1.113 2003/08/21 19:31:58 cheshire
248 Cosmetic: Swap order of fields
250 Revision 1.112 2003/08/21 19:27:36 cheshire
251 <rdar://problem/3387878> Traffic reduction: No need to announce record for longer than TTL
253 Revision 1.111 2003/08/21 02:21:50 cheshire
254 <rdar://problem/3386473> Efficiency: Reduce repeated queries
256 Revision 1.110 2003/08/20 23:39:31 cheshire
257 <rdar://problem/3344098> Review syslog messages, and remove as appropriate
259 Revision 1.109 2003/08/19 22:24:10 cheshire
262 Revision 1.108 2003/08/19 22:20:00 cheshire
263 <rdar://problem/3376721> Don't use IPv6 on interfaces that have a routable IPv4 address configured
264 More minor refinements
266 Revision 1.107 2003/08/19 06:48:25 cheshire
267 <rdar://problem/3376552> Guard against excessive record updates
268 Each record starts with 10 UpdateCredits.
269 Every update consumes one UpdateCredit.
270 UpdateCredits are replenished at a rate of one one per minute, up to a maximum of 10.
271 As the number of UpdateCredits declines, the number of announcements is similarly scaled back.
272 When fewer than 5 UpdateCredits remain, the first announcement is also delayed by an increasing amount.
274 Revision 1.106 2003/08/19 04:49:28 cheshire
275 <rdar://problem/3368159> Interaction between v4, v6 and dual-stack hosts not working quite right
276 1. A dual-stack host should only suppress its own query if it sees the same query from other hosts on BOTH IPv4 and IPv6.
277 2. When we see the first v4 (or first v6) member of a group, we re-trigger questions and probes on that interface.
278 3. When we see the last v4 (or v6) member of a group go away, we revalidate all the records received on that interface.
280 Revision 1.105 2003/08/19 02:33:37 cheshire
283 Revision 1.104 2003/08/19 02:31:11 cheshire
284 <rdar://problem/3378386> mDNSResponder overenthusiastic with final expiration queries
285 Final expiration queries now only mark the question for sending on the particular interface
286 pertaining to the record that's expiring.
288 Revision 1.103 2003/08/18 19:05:44 cheshire
289 <rdar://problem/3382423> UpdateRecord not working right
290 Added "newrdlength" field to hold new length of updated rdata
292 Revision 1.102 2003/08/16 03:39:00 cheshire
293 <rdar://problem/3338440> InterfaceID -1 indicates "local only"
295 Revision 1.101 2003/08/15 20:16:02 cheshire
296 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
297 We want to avoid touching the rdata pages, so we don't page them in.
298 1. RDLength was stored with the rdata, which meant touching the page just to find the length.
299 Moved this from the RData to the ResourceRecord object.
300 2. To avoid unnecessarily touching the rdata just to compare it,
301 compute a hash of the rdata and store the hash in the ResourceRecord object.
303 Revision 1.100 2003/08/14 19:29:04 cheshire
304 <rdar://problem/3378473> Include cache records in SIGINFO output
305 Moved declarations of DNSTypeName() and GetRRDisplayString to mDNSClientAPI.h so daemon.c can use them
307 Revision 1.99 2003/08/14 02:17:05 cheshire
308 <rdar://problem/3375491> Split generic ResourceRecord type into two separate types: AuthRecord and CacheRecord
310 Revision 1.98 2003/08/12 19:56:23 cheshire
313 Revision 1.97 2003/08/12 14:59:27 cheshire
314 <rdar://problem/3374490> Rate-limiting blocks some legitimate responses
315 When setting LastMCTime also record LastMCInterface. When checking LastMCTime to determine
316 whether to suppress the response, also check LastMCInterface to see if it matches.
318 Revision 1.96 2003/08/12 13:57:04 cheshire
319 <rdar://problem/3323817> Improve cache performance
320 Changed the number of hash table slots from 37 to 499
322 Revision 1.95 2003/08/09 00:55:02 cheshire
323 <rdar://problem/3366553> mDNSResponder is taking 20-30% of the CPU
324 Don't scan the whole cache after every packet.
326 Revision 1.94 2003/08/09 00:35:29 cheshire
328 Revision 1.93 2003/08/08 18:55:48 cheshire
329 <rdar://problem/3370365> Guard against time going backwards
331 Revision 1.92 2003/08/08 18:36:04 cheshire
332 <rdar://problem/3344154> Only need to revalidate on interface removal on platforms that have the PhantomInterfaces bug
334 Revision 1.91 2003/08/06 21:33:39 cheshire
335 Fix compiler warnings on PocketPC 2003 (Windows CE)
337 Revision 1.90 2003/08/06 20:30:17 cheshire
338 Add structure definition for rdataMX (not currently used, but good to have it for completeness)
340 Revision 1.89 2003/08/06 18:58:19 cheshire
343 Revision 1.88 2003/07/24 23:45:44 cheshire
344 To eliminate compiler warnings, changed definition of mDNSBool from
345 "unsigned char" to "int", since "int" is in fact truly the type that C uses
346 for the result of comparison operators (a<b) and logical operators (a||b)
348 Revision 1.87 2003/07/22 23:57:20 cheshire
349 Move platform-layer function prototypes from mDNSClientAPI.h to mDNSPlatformFunctions.h where they belong
351 Revision 1.86 2003/07/20 03:52:02 ksekar
352 <rdar://problem/3320722>: Feature: New Rendezvous APIs (#7875) (mDNSResponder component)
353 Added error type for incompatibility between daemon and client versions
355 Revision 1.85 2003/07/19 03:23:13 cheshire
356 <rdar://problem/2986147> mDNSResponder needs to receive and cache larger records
358 Revision 1.84 2003/07/18 23:52:12 cheshire
359 To improve consistency of field naming, global search-and-replace:
360 NextProbeTime -> NextScheduledProbe
361 NextResponseTime -> NextScheduledResponse
363 Revision 1.83 2003/07/18 00:29:59 cheshire
364 <rdar://problem/3268878> Remove mDNSResponder version from packet header and use HINFO record instead
366 Revision 1.82 2003/07/17 17:35:04 cheshire
367 <rdar://problem/3325583> Rate-limit responses, to guard against packet flooding
369 Revision 1.81 2003/07/16 05:01:36 cheshire
370 Add fields 'LargeAnswers' and 'ExpectUnicastResponse' in preparation for
371 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
373 Revision 1.80 2003/07/15 01:55:12 cheshire
374 <rdar://problem/3315777> Need to implement service registration with subtypes
376 Revision 1.79 2003/07/13 02:28:00 cheshire
377 <rdar://problem/3325166> SendResponses didn't all its responses
378 Delete all references to RRInterfaceActive -- it's now superfluous
380 Revision 1.78 2003/07/13 01:47:53 cheshire
381 Fix one error and one warning in the Windows build
383 Revision 1.77 2003/07/11 01:32:38 cheshire
384 Syntactic cleanup (no change to funcationality): Now that we only have one host name,
385 rename field "hostname1" to "hostname", and field "RR_A1" to "RR_A".
387 Revision 1.76 2003/07/11 01:28:00 cheshire
388 <rdar://problem/3161289> No more local.arpa
390 Revision 1.75 2003/07/02 21:19:45 cheshire
391 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
393 Revision 1.74 2003/07/02 02:41:23 cheshire
394 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
396 Revision 1.73 2003/06/10 04:24:39 cheshire
397 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
398 Some additional refinements:
399 Don't try to do this for unicast-response queries
400 better tracking of Qs and KAs in multi-packet KA lists
402 Revision 1.72 2003/06/10 01:46:27 cheshire
403 Add better comments explaining how these data structures are intended to be used from the client layer
405 Revision 1.71 2003/06/07 06:45:05 cheshire
406 <rdar://problem/3283666> No need for multiple machines to all be sending the same queries
408 Revision 1.70 2003/06/07 04:50:53 cheshire
409 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
411 Revision 1.69 2003/06/07 04:22:17 cheshire
412 Add MsgBuffer for error log and debug messages
414 Revision 1.68 2003/06/07 01:46:38 cheshire
415 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
417 Revision 1.67 2003/06/07 01:22:14 cheshire
418 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
420 Revision 1.66 2003/06/07 00:59:43 cheshire
421 <rdar://problem/3283454> Need some randomness to spread queries on the network
423 Revision 1.65 2003/06/06 21:41:11 cheshire
424 For consistency, mDNS_StopQuery() should return an mStatus result, just like all the other mDNSCore routines
426 Revision 1.64 2003/06/06 21:38:55 cheshire
427 Renamed 'NewData' as 'FreshData' (The data may not be new data, just a refresh of data that we
428 already had in our cache. This refreshes our TTL on the data, but the data itself stays the same.)
430 Revision 1.63 2003/06/06 17:20:14 cheshire
431 For clarity, rename question fields name/rrtype/rrclass as qname/qtype/qclass
432 (Global search-and-replace; no functional change to code execution.)
434 Revision 1.62 2003/06/04 01:25:33 cheshire
435 <rdar://problem/3274950> Cannot perform multi-packet known-answer suppression messages
436 Display time interval between first and subsequent queries
438 Revision 1.61 2003/06/03 05:02:16 cheshire
439 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
441 Revision 1.60 2003/05/31 00:09:49 cheshire
442 <rdar://problem/3274862> Add ability to discover what services are on a network
444 Revision 1.59 2003/05/29 06:11:35 cheshire
445 <rdar://problem/3272214>: Report if there appear to be too many "Resolve" callbacks
447 Revision 1.58 2003/05/29 05:48:06 cheshire
448 Minor fix for when generating printf warnings: mDNS_snprintf arguments are now 3,4
450 Revision 1.57 2003/05/26 03:21:27 cheshire
451 Tidy up address structure naming:
452 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
453 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
454 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
456 Revision 1.56 2003/05/26 03:01:27 cheshire
457 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
459 Revision 1.55 2003/05/26 00:47:30 cheshire
460 Comment clarification
462 Revision 1.54 2003/05/24 16:39:48 cheshire
463 <rdar://problem/3268631> SendResponses also needs to handle multihoming better
465 Revision 1.53 2003/05/23 02:15:37 cheshire
466 Fixed misleading use of the term "duplicate suppression" where it should have
467 said "known answer suppression". (Duplicate answer suppression is something
468 different, and duplicate question suppression is yet another thing, so the use
469 of the completely vague term "duplicate suppression" was particularly bad.)
471 Revision 1.52 2003/05/22 02:29:22 cheshire
472 <rdar://problem/2984918> SendQueries needs to handle multihoming better
473 Complete rewrite of SendQueries. Works much better now :-)
475 Revision 1.51 2003/05/21 20:14:55 cheshire
476 Fix comments and warnings
478 Revision 1.50 2003/05/14 07:08:36 cheshire
479 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
480 Previously, when there was any network configuration change, mDNSResponder
481 would tear down the entire list of active interfaces and start again.
482 That was very disruptive, and caused the entire cache to be flushed,
483 and caused lots of extra network traffic. Now it only removes interfaces
484 that have really gone, and only adds new ones that weren't there before.
486 Revision 1.49 2003/05/07 01:49:36 cheshire
487 Remove "const" in ConstructServiceName prototype
489 Revision 1.48 2003/05/07 00:18:44 cheshire
490 Fix typo: "kDNSQClass_Mask" should be "kDNSClass_Mask"
492 Revision 1.47 2003/05/06 00:00:46 cheshire
493 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
495 Revision 1.46 2003/04/30 20:39:09 cheshire
498 Revision 1.45 2003/04/29 00:40:50 cheshire
499 Fix compiler warnings
501 Revision 1.44 2003/04/26 02:41:56 cheshire
502 <rdar://problem/3241281> Change timenow from a local variable to a structure member
504 Revision 1.43 2003/04/25 01:45:56 cheshire
505 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
507 Revision 1.42 2003/04/15 20:58:31 jgraessl
509 <rdar://problem/3229014> Added a hash to lookup records in the cache.
511 Revision 1.41 2003/04/15 18:09:13 jgraessl
513 <rdar://problem/3228892>
514 Reviewed by: Stuart Cheshire
515 Added code to keep track of when the next cache item will expire so we can
516 call TidyRRCache only when necessary.
518 Revision 1.40 2003/03/29 01:55:19 cheshire
519 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
520 Solution: Major cleanup of packet timing and conflict handling rules
522 Revision 1.39 2003/03/27 03:30:55 cheshire
523 <rdar://problem/3210018> Name conflicts not handled properly, resulting in memory corruption, and eventual crash
524 Problem was that HostNameCallback() was calling mDNS_DeregisterInterface(), which is not safe in a callback
526 1. Make mDNS_DeregisterInterface() safe to call from a callback
527 2. Make HostNameCallback() use mDNS_DeadvertiseInterface() instead
528 (it never really needed to deregister the interface at all)
530 Revision 1.38 2003/03/15 04:40:36 cheshire
531 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
533 Revision 1.37 2003/03/14 21:34:11 cheshire
534 <rdar://problem/3176950> Can't setup and print to Lexmark PS printers via Airport Extreme
535 Increase size of cache rdata from 512 to 768
537 Revision 1.36 2003/03/05 03:38:35 cheshire
538 <rdar://problem/3185731> Bogus error message in console: died or deallocated, but no record of client can be found!
539 Fixed by leaving client in list after conflict, until client explicitly deallocates
541 Revision 1.35 2003/02/21 02:47:54 cheshire
542 <rdar://problem/3099194> mDNSResponder needs performance improvements
543 Several places in the code were calling CacheRRActive(), which searched the entire
544 question list every time, to see if this cache resource record answers any question.
545 Instead, we now have a field "CRActiveQuestion" in the resource record structure
547 Revision 1.34 2003/02/21 01:54:08 cheshire
548 <rdar://problem/3099194> mDNSResponder needs performance improvements
549 Switched to using new "mDNS_Execute" model (see "Implementer Notes.txt")
551 Revision 1.33 2003/02/20 06:48:32 cheshire
552 <rdar://problem/3169535> Xserve RAID needs to do interface-specific registrations
553 Reviewed by: Josh Graessley, Bob Bradley
555 Revision 1.32 2003/01/31 03:35:59 cheshire
556 <rdar://problem/3147097> mDNSResponder sometimes fails to find the correct results
557 When there were *two* active questions in the list, they were incorrectly
558 finding *each other* and *both* being marked as duplicates of another question
560 Revision 1.31 2003/01/29 02:46:37 cheshire
562 A physical interface is identified solely by its InterfaceID (not by IP and type).
563 On a given InterfaceID, mDNSCore may send both v4 and v6 multicasts.
564 In cases where the requested outbound protocol (v4 or v6) is not supported on
565 that InterfaceID, the platform support layer should simply discard that packet.
567 Revision 1.30 2003/01/29 01:47:08 cheshire
568 Rename 'Active' to 'CRActive' or 'InterfaceActive' for improved clarity
570 Revision 1.29 2003/01/28 05:23:43 cheshire
571 <rdar://problem/3147097> mDNSResponder sometimes fails to find the correct results
572 Add 'Active' flag for interfaces
574 Revision 1.28 2003/01/28 01:35:56 cheshire
575 Revise comment about ThisQInterval to reflect new semantics
577 Revision 1.27 2003/01/13 23:49:42 jgraessl
578 Merged changes for the following fixes in to top of tree:
579 <rdar://problem/3086540> computer name changes not handled properly
580 <rdar://problem/3124348> service name changes are not properly handled
581 <rdar://problem/3124352> announcements sent in pairs, failing chattiness test
583 Revision 1.26 2002/12/23 22:13:28 jgraessl
585 Reviewed by: Stuart Cheshire
586 Initial IPv6 support for mDNSResponder.
588 Revision 1.25 2002/09/21 20:44:49 zarzycki
591 Revision 1.24 2002/09/19 23:47:35 cheshire
592 Added mDNS_RegisterNoSuchService() function for assertion of non-existance
593 of a particular named service
595 Revision 1.23 2002/09/19 21:25:34 cheshire
596 mDNS_snprintf() doesn't need to be in a separate file
598 Revision 1.22 2002/09/19 04:20:43 cheshire
599 Remove high-ascii characters that confuse some systems
601 Revision 1.21 2002/09/17 01:06:35 cheshire
602 Change mDNS_AdvertiseLocalAddresses to be a parameter to mDNS_Init()
604 Revision 1.20 2002/09/16 18:41:41 cheshire
605 Merge in license terms from Quinn's copy, in preparation for Darwin release
609 #ifndef __mDNSClientAPI_h
610 #define __mDNSClientAPI_h
612 #include <stdarg.h> // stdarg.h is required for for va_list support for the mDNS_vsnprintf declaration
613 #include "mDNSDebug.h"
619 // ***************************************************************************
620 // Function scope indicators
622 // If you see "mDNSlocal" before a function name in a C file, it means the function is not callable outside this file
624 #define mDNSlocal static
626 // If you see "mDNSexport" before a symbol in a C file, it means the symbol is exported for use by clients
627 // For every "mDNSexport" in a C file, there needs to be a corresponding "extern" declaration in some header file
628 // (When a C file #includes a header file, the "extern" declarations tell the compiler:
629 // "This symbol exists -- but not necessarily in this C file.")
634 // ***************************************************************************
635 // Structure packing macro
637 // If we're not using GNUC, it's not fatal.
638 // Most compilers naturally pack the on-the-wire structures correctly anyway, so a plain "struct" is usually fine.
639 // In the event that structures are not packed correctly, mDNS_Init() will detect this and report an error, so the
640 // developer will know what's wrong, and can investigate what needs to be done on that compiler to provide proper packing.
642 #if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
643 #define packedstruct struct __attribute__((__packed__))
644 #define packedunion union __attribute__((__packed__))
646 #define packedstruct struct
647 #define packedunion union
651 // ***************************************************************************
653 #pragma mark - DNS Resource Record class and type constants
656 typedef enum // From RFC 1035
658 kDNSClass_IN
= 1, // Internet
659 kDNSClass_CS
= 2, // CSNET
660 kDNSClass_CH
= 3, // CHAOS
661 kDNSClass_HS
= 4, // Hesiod
662 kDNSClass_NONE
= 254, // Used in DNS UPDATE [RFC 2136]
664 kDNSClass_Mask
= 0x7FFF,// Multicast DNS uses the bottom 15 bits to identify the record class...
665 kDNSClass_UniqueRRSet
= 0x8000,// ... and the top bit indicates that all other cached records are now invalid
667 kDNSQClass_ANY
= 255, // Not a DNS class, but a DNS query class, meaning "all classes"
668 kDNSQClass_UnicastResponse
= 0x8000 // Top bit set in a question means "unicast response acceptable"
671 typedef enum // From RFC 1035
673 kDNSType_A
= 1, // 1 Address
674 kDNSType_NS
, // 2 Name Server
675 kDNSType_MD
, // 3 Mail Destination
676 kDNSType_MF
, // 4 Mail Forwarder
677 kDNSType_CNAME
, // 5 Canonical Name
678 kDNSType_SOA
, // 6 Start of Authority
679 kDNSType_MB
, // 7 Mailbox
680 kDNSType_MG
, // 8 Mail Group
681 kDNSType_MR
, // 9 Mail Rename
682 kDNSType_NULL
, // 10 NULL RR
683 kDNSType_WKS
, // 11 Well-known-service
684 kDNSType_PTR
, // 12 Domain name pointer
685 kDNSType_HINFO
, // 13 Host information
686 kDNSType_MINFO
, // 14 Mailbox information
687 kDNSType_MX
, // 15 Mail Exchanger
688 kDNSType_TXT
, // 16 Arbitrary text string
690 kDNSType_AAAA
= 28, // 28 IPv6 address
691 kDNSType_SRV
= 33, // 33 Service record
692 kDNSType_OPT
= 41, // EDNS0 OPT record
693 kDNSType_TSIG
= 250, // 250 Transaction Signature
695 kDNSQType_ANY
= 255 // Not a DNS type, but a DNS query type, meaning "all types"
698 // ***************************************************************************
700 #pragma mark - Simple types
703 // mDNS defines its own names for these common types to simplify portability across
704 // multiple platforms that may each have their own (different) names for these types.
705 typedef int mDNSBool
;
706 typedef signed char mDNSs8
;
707 typedef unsigned char mDNSu8
;
708 typedef signed short mDNSs16
;
709 typedef unsigned short mDNSu16
;
711 // <http://gcc.gnu.org/onlinedocs/gcc-3.3.3/cpp/Common-Predefined-Macros.html> says
713 // These macros are defined, with value 1, if (and only if) the compilation is
714 // for a target where long int and pointer both use 64-bits and int uses 32-bit.
715 // <http://www.intel.com/software/products/compilers/clin/docs/ug/lin1077.htm> says
716 // Macro Name __LP64__ Value 1
717 // A quick Google search for "defined(__LP64__)" OR "#ifdef __LP64__" gives 2590 hits and
718 // a search for "#if __LP64__" gives only 12, so I think we'll go with the majority and use defined()
719 #if defined(_LP64) || defined(__LP64__)
720 typedef signed int mDNSs32
;
721 typedef unsigned int mDNSu32
;
722 #elif defined(_ILP64) || defined(__ILP64__)
723 typedef signed int32 mDNSs32
;
724 typedef unsigned int32 mDNSu32
;
726 typedef signed long mDNSs32
;
727 typedef unsigned long mDNSu32
;
730 // To enforce useful type checking, we make mDNSInterfaceID be a pointer to a dummy struct
731 // This way, mDNSInterfaceIDs can be assigned, and compared with each other, but not with other types
732 // Declaring the type to be the typical generic "void *" would lack this type checking
733 typedef struct mDNSInterfaceID_dummystruct
{ void *dummy
; } *mDNSInterfaceID
;
735 // These types are for opaque two- and four-byte identifiers.
736 // The "NotAnInteger" fields of the unions allow the value to be conveniently passed around in a
737 // register for the sake of efficiency, and compared for equality or inequality, but don't forget --
738 // just because it is in a register doesn't mean it is an integer. Operations like greater than,
739 // less than, add, multiply, increment, decrement, etc., are undefined for opaque identifiers,
740 // and if you make the mistake of trying to do those using the NotAnInteger field, then you'll
741 // find you get code that doesn't work consistently on big-endian and little-endian machines.
742 typedef packedunion
{ mDNSu8 b
[2]; mDNSu16 NotAnInteger
; } mDNSOpaque16
;
743 typedef packedunion
{ mDNSu8 b
[4]; mDNSu32 NotAnInteger
; } mDNSOpaque32
;
744 typedef packedunion
{ mDNSu8 b
[16]; mDNSu16 w
[8]; mDNSu32 l
[4]; } mDNSOpaque128
;
746 typedef mDNSOpaque16 mDNSIPPort
; // An IP port is a two-byte opaque identifier (not an integer)
747 typedef mDNSOpaque32 mDNSv4Addr
; // An IP address is a four-byte opaque identifier (not an integer)
748 typedef mDNSOpaque128 mDNSv6Addr
; // An IPv6 address is a 16-byte opaque identifier (not an integer)
752 mDNSAddrType_None
= 0,
753 mDNSAddrType_IPv4
= 4,
754 mDNSAddrType_IPv6
= 6,
755 mDNSAddrType_Unknown
= ~0 // Special marker value used in known answer list recording
761 union { mDNSv6Addr v6
; mDNSv4Addr v4
; } ip
;
764 enum { mDNSfalse
= 0, mDNStrue
= 1 };
773 // mDNS return values are in the range FFFE FF00 (-65792) to FFFE FFFF (-65537)
774 // The top end of the range (FFFE FFFF) is used for error codes;
775 // the bottom end of the range (FFFE FF00) is used for non-error values;
778 mStatus_UnknownErr
= -65537, // 0xFFFE FFFF
779 mStatus_NoSuchNameErr
= -65538,
780 mStatus_NoMemoryErr
= -65539,
781 mStatus_BadParamErr
= -65540,
782 mStatus_BadReferenceErr
= -65541,
783 mStatus_BadStateErr
= -65542,
784 mStatus_BadFlagsErr
= -65543,
785 mStatus_UnsupportedErr
= -65544,
786 mStatus_NotInitializedErr
= -65545,
787 mStatus_NoCache
= -65546,
788 mStatus_AlreadyRegistered
= -65547,
789 mStatus_NameConflict
= -65548,
790 mStatus_Invalid
= -65549,
792 mStatus_Incompatible
= -65551,
793 mStatus_BadInterfaceErr
= -65552,
794 mStatus_Refused
= -65553,
795 mStatus_NoSuchRecord
= -65554,
796 mStatus_NoAuth
= -65555,
797 // -65556 - -65789 currently unused
800 mStatus_GrowCache
= -65790,
801 mStatus_ConfigChanged
= -65791,
802 mStatus_MemFree
= -65792, // 0xFFFE FF00
804 // tcp connection status
805 mStatus_ConnectionPending
= -65793,
806 mStatus_ConnectionFailed
= -65794,
807 mStatus_ConnectionEstablished
= -65795
810 typedef mDNSs32 mStatus
;
812 // RFC 1034/1035 specify that a domain label consists of a length byte plus up to 63 characters
813 #define MAX_DOMAIN_LABEL 63
814 typedef struct { mDNSu8 c
[ 64]; } domainlabel
; // One label: length byte and up to 63 characters
816 // RFC 1034/1035 specify that a domain name, including length bytes, data bytes, and terminating zero, may be up to 255 bytes long
817 #define MAX_DOMAIN_NAME 255
818 typedef struct { mDNSu8 c
[256]; } domainname
; // Up to 255 bytes of length-prefixed domainlabels
820 typedef struct { mDNSu8 c
[256]; } UTF8str255
; // Null-terminated C string
822 // The longest legal textual form of a DNS name is 1005 bytes, including the C-string terminating NULL at the end.
824 // When a native domainname object is converted to printable textual form using ConvertDomainNameToCString(),
825 // non-printing characters are represented in the conventional DNS way, as '\ddd', where ddd is a three-digit decimal number.
826 // The longest legal domain name is 255 bytes, in the form of four labels as shown below:
827 // Length byte, 63 data bytes, length byte, 63 data bytes, length byte, 63 data bytes, length byte, 61 data bytes, zero byte.
828 // Each label is encoded textually as characters followed by a trailing dot.
829 // If every character has to be represented as a four-byte escape sequence, then this makes the maximum textual form four labels
830 // plus the C-string terminating NULL as shown below:
831 // 63*4+1 + 63*4+1 + 63*4+1 + 61*4+1 + 1 = 1005.
832 // Note that MAX_ESCAPED_DOMAIN_LABEL is not normally used: If you're only decoding a single label, escaping is usually not required.
833 // It is for domain names, where dots are used as label separators, that proper escaping is vital.
834 #define MAX_ESCAPED_DOMAIN_LABEL 254
835 #define MAX_ESCAPED_DOMAIN_NAME 1005
837 // ***************************************************************************
839 #pragma mark - DNS Message structures
842 #define mDNS_numZones numQuestions
843 #define mDNS_numPrereqs numAnswers
844 #define mDNS_numUpdates numAuthorities
850 mDNSu16 numQuestions
;
852 mDNSu16 numAuthorities
;
853 mDNSu16 numAdditionals
;
856 // We can send and receive packets up to 9000 bytes (Ethernet Jumbo Frame size, if that ever becomes widely used)
857 // However, in the normal case we try to limit packets to 1500 bytes so that we don't get IP fragmentation on standard Ethernet
858 // 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
859 #define AbsoluteMaxDNSMessageData 8940
860 #define NormalMaxDNSMessageData 1440
863 DNSMessageHeader h
; // Note: Size 12 bytes
864 mDNSu8 data
[AbsoluteMaxDNSMessageData
]; // 40 (IPv6) + 8 (UDP) + 12 (DNS header) + 8940 (data) = 9000
867 // ***************************************************************************
869 #pragma mark - Resource Record structures
872 // Authoritative Resource Records:
873 // There are four basic types: Shared, Advisory, Unique, Known Unique
875 // * Shared Resource Records do not have to be unique
876 // -- Shared Resource Records are used for DNS-SD service PTRs
877 // -- It is okay for several hosts to have RRs with the same name but different RDATA
878 // -- We use a random delay on responses to reduce collisions when all the hosts respond to the same query
879 // -- These RRs typically have moderately high TTLs (e.g. one hour)
880 // -- These records are announced on startup and topology changes for the benefit of passive listeners
881 // -- These records send a goodbye packet when deregistering
883 // * Advisory Resource Records are like Shared Resource Records, except they don't send a goodbye packet
885 // * Unique Resource Records should be unique among hosts within any given mDNS scope
886 // -- The majority of Resource Records are of this type
887 // -- If two entities on the network have RRs with the same name but different RDATA, this is a conflict
888 // -- Responses may be sent immediately, because only one host should be responding to any particular query
889 // -- These RRs typically have low TTLs (e.g. a few minutes)
890 // -- On startup and after topology changes, a host issues queries to verify uniqueness
892 // * Known Unique Resource Records are treated like Unique Resource Records, except that mDNS does
893 // not have to verify their uniqueness because this is already known by other means (e.g. the RR name
894 // is derived from the host's IP or Ethernet address, which is already known to be a unique identifier).
896 // Summary of properties of different record types:
897 // Probe? Does this record type send probes before announcing?
898 // Conflict? Does this record type react if we observe an apparent conflict?
899 // Goodbye? Does this record type send a goodbye packet on departure?
901 // Probe? Conflict? Goodbye? Notes
902 // Unregistered Should not appear in any list (sanity check value)
903 // Shared No No Yes e.g. Service PTR record
904 // Deregistering No No Yes Shared record about to announce its departure and leave the list
906 // Unique Yes Yes No Record intended to be unique -- will probe to verify
907 // Verified Yes Yes No Record has completed probing, and is verified unique
908 // KnownUnique No Yes No Record is assumed by other means to be unique
910 // Valid lifecycle of a record:
911 // Unregistered -> Shared -> Deregistering -(goodbye)-> Unregistered
912 // Unregistered -> Advisory -> Unregistered
913 // Unregistered -> Unique -(probe)-> Verified -> Unregistered
914 // Unregistered -> KnownUnique -> Unregistered
916 // Each Authoritative kDNSRecordType has only one bit set. This makes it easy to quickly see if a record
917 // is one of a particular set of types simply by performing the appropriate bitwise masking operation.
919 // Cache Resource Records (received from the network):
920 // There are four basic types: Answer, Unique Answer, Additional, Unique Additional
921 // Bit 7 (the top bit) of kDNSRecordType is always set for Cache Resource Records; always clear for Authoritative Resource Records
922 // Bit 6 (value 0x40) is set for answer records; clear for additional records
923 // Bit 5 (value 0x20) is set for records received with the kDNSClass_UniqueRRSet
927 kDNSRecordTypeUnregistered
= 0x00, // Not currently in any list
928 kDNSRecordTypeDeregistering
= 0x01, // Shared record about to announce its departure and leave the list
930 kDNSRecordTypeUnique
= 0x02, // Will become a kDNSRecordTypeVerified when probing is complete
932 kDNSRecordTypeAdvisory
= 0x04, // Like Shared, but no goodbye packet
933 kDNSRecordTypeShared
= 0x08, // Shared means record name does not have to be unique -- use random delay on responses
935 kDNSRecordTypeVerified
= 0x10, // Unique means mDNS should check that name is unique (and then send immediate responses)
936 kDNSRecordTypeKnownUnique
= 0x20, // Known Unique means mDNS can assume name is unique without checking
937 // For Dynamic Update records, Known Unique means the record must already exist on the server.
938 kDNSRecordTypeUniqueMask
= (kDNSRecordTypeUnique
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
),
939 kDNSRecordTypeActiveMask
= (kDNSRecordTypeAdvisory
| kDNSRecordTypeShared
| kDNSRecordTypeVerified
| kDNSRecordTypeKnownUnique
),
941 kDNSRecordTypePacketAdd
= 0x80, // Received in the Additional Section of a DNS Response
942 kDNSRecordTypePacketAddUnique
= 0xA0, // Received in the Additional Section of a DNS Response with kDNSClass_UniqueRRSet set
943 kDNSRecordTypePacketAns
= 0xC0, // Received in the Answer Section of a DNS Response
944 kDNSRecordTypePacketAnsUnique
= 0xE0, // Received in the Answer Section of a DNS Response with kDNSClass_UniqueRRSet set
946 kDNSRecordTypePacketAnsMask
= 0x40, // True for PacketAns and PacketAnsUnique
947 kDNSRecordTypePacketUniqueMask
= 0x20 // True for PacketAddUnique and PacketAnsUnique
950 typedef packedstruct
{ mDNSu16 priority
; mDNSu16 weight
; mDNSIPPort port
; domainname target
; } rdataSRV
;
951 typedef packedstruct
{ mDNSu16 preference
; domainname exchange
; } rdataMX
;
952 typedef packedstruct
{ domainname mname
; domainname rname
; mDNSOpaque32 serial
; mDNSOpaque32 refresh
;
953 mDNSOpaque32 retry
; mDNSOpaque32 expire
; mDNSOpaque32 min
; } rdataSOA
;
964 // NOTE: rdataOpt format may be repeated an arbitrary number of times in a single resource record
969 union { LLQOptData llq
; mDNSu32 lease
; } OptData
;
972 // StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record
973 // MaximumRDSize is 8K the absolute maximum we support (at least for now)
974 #define StandardAuthRDSize 264
975 #define MaximumRDSize 8192
977 // InlineCacheRDSize is 64
978 // Records received from the network with rdata this size or less have their rdata stored right in the CacheRecord object
979 // Records received from the network with rdata larger than this have additional storage allocated for the rdata
980 // A quick unscientific sample from a busy network at Apple with lots of machines revealed this:
981 // 1461 records in cache
982 // 292 were one-byte TXT records
983 // 136 were four-byte A records
984 // 184 were sixteen-byte AAAA records
985 // 780 were various PTR, TXT and SRV records from 12-64 bytes
986 // Only 69 records had rdata bigger than 64 bytes
987 #define InlineCacheRDSize 64
991 mDNSu8 data
[StandardAuthRDSize
];
992 mDNSv4Addr ip
; // For 'A' record
993 mDNSv6Addr ipv6
; // For 'AAAA' record
994 domainname name
; // For PTR, NS, and CNAME records
995 UTF8str255 txt
; // For TXT record
996 rdataSRV srv
; // For SRV record
997 rdataMX mx
; // For MX record
998 rdataSOA soa
; // For SOA record
999 rdataOpt opt
; // For eDNS0 opt record
1004 mDNSu16 MaxRDLength
; // Amount of storage allocated for rdata (usually sizeof(RDataBody))
1007 #define sizeofRDataHeader (sizeof(RData) - sizeof(RDataBody))
1009 typedef struct AuthRecord_struct AuthRecord
;
1010 typedef struct CacheRecord_struct CacheRecord
;
1011 typedef struct ResourceRecord_struct ResourceRecord
;
1012 typedef struct DNSQuestion_struct DNSQuestion
;
1013 typedef struct mDNS_struct mDNS
;
1014 typedef struct mDNS_PlatformSupport_struct mDNS_PlatformSupport
;
1016 // Note: Within an mDNSRecordCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Close(), mDNS_Execute()
1017 typedef void mDNSRecordCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
);
1020 // Restrictions: An mDNSRecordUpdateCallback may not make any mDNS API calls.
1021 // The intent of this callback is to allow the client to free memory, if necessary.
1022 // The internal data structures of the mDNS code may not be in a state where mDNS API calls may be made safely.
1023 typedef void mDNSRecordUpdateCallback(mDNS
*const m
, AuthRecord
*const rr
, RData
*OldRData
);
1025 struct ResourceRecord_struct
1027 mDNSu8 RecordType
; // See enum above
1028 mDNSInterfaceID InterfaceID
; // Set if this RR is specific to one interface
1029 // For records received off the wire, InterfaceID is *always* set to the receiving interface
1030 // For our authoritative records, InterfaceID is usually zero, except for those few records
1031 // that are interface-specific (e.g. address records, especially linklocal addresses)
1035 mDNSu32 rroriginalttl
; // In seconds
1036 mDNSu16 rdlength
; // Size of the raw rdata, in bytes
1037 mDNSu16 rdestimate
; // Upper bound on size of rdata after name compression
1038 mDNSu32 namehash
; // Name-based (i.e. case insensitive) hash of name
1039 mDNSu32 rdatahash
; // 32-bit hash of the raw rdata
1040 mDNSu32 rdnamehash
; // Set if this rdata contains a domain name (e.g. PTR, SRV, CNAME etc.)
1041 RData
*rdata
; // Pointer to storage for this rdata
1046 regState_FetchingZoneData
= 1, // getting info - update not sent
1047 regState_Pending
= 2, // update sent, reply not received
1048 regState_Registered
= 3, // update sent, reply received
1049 regState_DeregPending
= 4, // dereg sent, reply not received
1050 regState_DeregDeferred
= 5, // dereg requested while in Pending state - send dereg AFTER registration is confirmed
1051 regState_Cancelled
= 6, // update not sent, reg. cancelled by client
1052 regState_TargetChange
= 7, // host name change update pending
1053 regState_Unregistered
= 8, // not in any list
1054 regState_Refresh
= 9 // outstanding refresh message
1057 typedef mDNSu16 regState_t
;
1063 domainname zone
; // the zone that is updated
1064 mDNSAddr ns
; // primary name server for the record's zone !!!KRS not technically correct to cache longer than TTL
1065 mDNSIPPort port
; // port on which server accepts dynamic updates
1066 mDNSBool add
; // !!!KRS this should really be an enumerated state
1067 struct uDNS_AuthInfo
*AuthInfo
; // authentication info (may be null)
1068 mDNSBool lease
; // dynamic update contains (should contain) lease option
1069 mDNSs32 expire
; // expiration of lease (-1 for static)
1072 struct AuthRecord_struct
1074 // For examples of how to set up this structure for use in mDNS_Register(),
1075 // see mDNS_AdvertiseInterface() or mDNS_RegisterService().
1076 // Basically, resrec and persistent metadata need to be set up before calling mDNS_Register().
1077 // mDNS_SetupResourceRecord() is avaliable as a helper routine to set up most fields to sensible default values for you
1079 AuthRecord
*next
; // Next in list; first element of structure for efficiency reasons
1080 ResourceRecord resrec
;
1081 uDNS_RegInfo uDNS_info
;
1083 // Persistent metadata for Authoritative Records
1084 AuthRecord
*Additional1
; // Recommended additional record to include in response
1085 AuthRecord
*Additional2
; // Another additional
1086 AuthRecord
*DependentOn
; // This record depends on another for its uniqueness checking
1087 AuthRecord
*RRSet
; // This unique record is part of an RRSet
1088 mDNSRecordCallback
*RecordCallback
; // Callback function to call for state changes
1089 void *RecordContext
; // Context parameter for the callback function
1090 mDNSu8 HostTarget
; // Set if the target of this record (PTR, CNAME, SRV, etc.) is our host name
1092 // Transient state for Authoritative Records
1093 mDNSu8 Acknowledged
; // Set if we've given the success callback to the client
1094 mDNSu8 ProbeCount
; // Number of probes remaining before this record is valid (kDNSRecordTypeUnique)
1095 mDNSu8 AnnounceCount
; // Number of announcements remaining (kDNSRecordTypeShared)
1096 mDNSu8 IncludeInProbe
; // Set if this RR is being put into a probe right now
1097 mDNSInterfaceID ImmedAnswer
; // Someone on this interface issued a query we need to answer (all-ones for all interfaces)
1098 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
1099 mDNSs32 ImmedAnswerMarkTime
;
1101 mDNSInterfaceID ImmedAdditional
; // Hint that we might want to also send this record, just to be helpful
1102 mDNSInterfaceID SendRNow
; // The interface this query is being sent on right now
1103 mDNSv4Addr v4Requester
; // Recent v4 query for this record, or all-ones if more than one recent query
1104 mDNSv6Addr v6Requester
; // Recent v6 query for this record, or all-ones if more than one recent query
1105 AuthRecord
*NextResponse
; // Link to the next element in the chain of responses to generate
1106 const mDNSu8
*NR_AnswerTo
; // Set if this record was selected by virtue of being a direct answer to a question
1107 AuthRecord
*NR_AdditionalTo
; // Set if this record was selected by virtue of being additional to another
1108 mDNSs32 ThisAPInterval
; // In platform time units: Current interval for announce/probe
1109 mDNSs32 AnnounceUntil
; // In platform time units: Creation time + TTL
1110 mDNSs32 LastAPTime
; // In platform time units: Last time we sent announcement/probe
1111 mDNSs32 LastMCTime
; // Last time we multicast this record (used to guard against packet-storm attacks)
1112 mDNSInterfaceID LastMCInterface
; // Interface this record was multicast on at the time LastMCTime was recorded
1113 RData
*NewRData
; // Set if we are updating this record with new rdata
1114 mDNSu16 newrdlength
; // ... and the length of the new RData
1115 mDNSRecordUpdateCallback
*UpdateCallback
;
1116 mDNSu32 UpdateCredits
; // Token-bucket rate limiting of excessive updates
1117 mDNSs32 NextUpdateCredit
; // Time next token is added to bucket
1118 mDNSs32 UpdateBlocked
; // Set if update delaying is in effect
1120 RData rdatastorage
; // Normally the storage is right here, except for oversized records
1121 // rdatastorage MUST be the last thing in the structure -- when using oversized AuthRecords, extra bytes
1122 // are appended after the end of the AuthRecord, logically augmenting the size of the rdatastorage
1123 // DO NOT ADD ANY MORE FIELDS HERE
1126 struct CacheRecord_struct
1128 CacheRecord
*next
; // Next in list; first element of structure for efficiency reasons
1129 ResourceRecord resrec
;
1131 // Transient state for Cache Records
1132 CacheRecord
*NextInKAList
; // Link to the next element in the chain of known answers to send
1133 mDNSs32 TimeRcvd
; // In platform time units
1134 mDNSs32 NextRequiredQuery
; // In platform time units
1135 mDNSs32 LastUsed
; // In platform time units
1136 mDNSu32 UseCount
; // Number of times this RR has been used to answer a question
1137 DNSQuestion
*CRActiveQuestion
; // Points to an active question referencing this answer
1138 mDNSu32 UnansweredQueries
; // Number of times we've issued a query for this record without getting an answer
1139 mDNSs32 LastUnansweredTime
; // In platform time units; last time we incremented UnansweredQueries
1140 mDNSu32 MPUnansweredQ
; // Multi-packet query handling: Number of times we've seen a query for this record
1141 mDNSs32 MPLastUnansweredQT
; // Multi-packet query handling: Last time we incremented MPUnansweredQ
1142 mDNSu32 MPUnansweredKA
; // Multi-packet query handling: Number of times we've seen this record in a KA list
1143 mDNSBool MPExpectingKA
; // Multi-packet query handling: Set when we increment MPUnansweredQ; allows one KA
1144 CacheRecord
*NextInCFList
; // Set if this is in the list of records we just received with the cache flush bit set
1146 struct { mDNSu16 MaxRDLength
; mDNSu8 data
[InlineCacheRDSize
]; } rdatastorage
; // Storage for small records is right here
1152 mDNSu8 _extradata
[MaximumRDSize
-InlineCacheRDSize
]; // Glue on the necessary number of extra bytes
1155 typedef struct NetworkInterfaceInfo_struct NetworkInterfaceInfo
;
1160 mDNSBool registered
; // True if a name for the interface is globally registered
1161 domainname regname
; // the name registered to the update server
1162 } uDNS_NetworkInterfaceInfo
;
1164 // A NetworkInterfaceInfo_struct serves two purposes:
1165 // 1. It holds the address, PTR and HINFO records to advertise a given IP address on a given physical interface
1166 // 2. It tells mDNSCore which physical interfaces are available; each physical interface has its own unique InterfaceID.
1167 // Since there may be multiple IP addresses on a single physical interface,
1168 // there may be multiple NetworkInterfaceInfo_structs with the same InterfaceID.
1169 // In this case, to avoid sending the same packet n times, when there's more than one
1170 // struct with the same InterfaceID, mDNSCore picks one member of the set to be the
1171 // active representative of the set; all others have the 'InterfaceActive' flag unset.
1173 struct NetworkInterfaceInfo_struct
1175 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1176 NetworkInterfaceInfo
*next
;
1178 mDNSBool InterfaceActive
; // Set if interface is sending & receiving packets (see comment above)
1179 mDNSBool IPv4Available
; // If InterfaceActive, set if v4 available on this InterfaceID
1180 mDNSBool IPv6Available
; // If InterfaceActive, set if v6 available on this InterfaceID
1182 // Standard AuthRecords that every Responder host should have (one per active IP address)
1183 AuthRecord RR_A
; // 'A' or 'AAAA' (address) record for our ".local" name
1184 AuthRecord RR_PTR
; // PTR (reverse lookup) record
1185 AuthRecord RR_HINFO
;
1187 uDNS_NetworkInterfaceInfo uDNS_info
;
1189 // Client API fields: The client must set up these fields *before* calling mDNS_RegisterInterface()
1190 mDNSInterfaceID InterfaceID
; // Identifies physical interface; MUST NOT be 0, -1, or -2
1191 mDNSAddr ip
; // The IPv4 or IPv6 address to advertise
1192 mDNSBool Advertise
; // False if you are only searching on this interface
1193 mDNSBool McastTxRx
; // Send/Receive multicast on this { InterfaceID, address family } ?
1196 typedef struct ExtraResourceRecord_struct ExtraResourceRecord
;
1197 struct ExtraResourceRecord_struct
1199 ExtraResourceRecord
*next
;
1201 // Note: Add any additional fields *before* the AuthRecord in this structure, not at the end.
1202 // In some cases clients can allocate larger chunks of memory and set r->rdata->MaxRDLength to indicate
1203 // that this extra memory is available, which would result in any fields after the AuthRecord getting smashed
1206 // Note: Within an mDNSServiceCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Close(), mDNS_Execute()
1207 typedef struct ServiceRecordSet_struct ServiceRecordSet
;
1208 typedef void mDNSServiceCallback(mDNS
*const m
, ServiceRecordSet
*const sr
, mStatus result
);
1209 struct ServiceRecordSet_struct
1211 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1212 // No fields need to be set up by the client prior to calling mDNS_RegisterService();
1213 // all required data is passed as parameters to that function.
1214 ServiceRecordSet
*next
;
1215 uDNS_RegInfo uDNS_info
;
1216 mDNSServiceCallback
*ServiceCallback
;
1217 void *ServiceContext
;
1218 ExtraResourceRecord
*Extras
; // Optional list of extra AuthRecords attached to this service registration
1219 mDNSu32 NumSubTypes
;
1220 AuthRecord
*SubTypes
;
1221 mDNSBool Conflict
; // Set if this record set was forcibly deregistered because of a conflict
1222 domainname Host
; // Set if this service record does not use the standard target host name
1223 AuthRecord RR_ADV
; // e.g. _services._dns-sd._udp.local. PTR _printer._tcp.local.
1224 AuthRecord RR_PTR
; // e.g. _printer._tcp.local. PTR Name._printer._tcp.local.
1225 AuthRecord RR_SRV
; // e.g. Name._printer._tcp.local. SRV 0 0 port target
1226 AuthRecord RR_TXT
; // e.g. Name._printer._tcp.local. TXT PrintQueueName
1227 // Don't add any fields after AuthRecord RR_TXT.
1228 // This is where the implicit extra space goes if we allocate a ServiceRecordSet containing an oversized RR_TXT record
1231 // ***************************************************************************
1233 #pragma mark - Question structures
1236 // We record the last eight instances of each duplicate query
1237 // This gives us v4/v6 on each of Ethernet/AirPort and Firewire, and two free slots "for future expansion"
1238 // If the host has more active interfaces that this it is not fatal -- duplicate question suppression will degrade gracefully.
1239 // Since we will still remember the last eight, the busiest interfaces will still get the effective duplicate question suppression.
1240 #define DupSuppressInfoSize 8
1245 mDNSInterfaceID InterfaceID
;
1246 mDNSs32 Type
; // v4 or v6?
1252 LLQ_GetZoneInfo
= 1,
1253 LLQ_InitialRequest
= 2,
1254 LLQ_SecondaryRequest
= 3,
1255 LLQ_Established
= 4,
1259 // safe to re-start LLQ before this point
1270 mDNSIPPort servPort
;
1271 DNSQuestion
*question
;
1272 mDNSu32 origLease
; // seconds (relative)
1273 mDNSs32 retry
; // ticks (absolute)
1274 mDNSs32 expire
; // ticks (absolute)
1277 mDNSBool deriveRemovesOnResume
;
1281 #define kDNSOpt_LLQ 1 //!!!KRS
1282 #define kDNSOpt_Lease 2 //!!!KRS
1283 #define kLLQ_Vers 0 // prerelease
1284 #define kLLQ_DefLease 7200 // 2 hours
1285 #define kUpdate_DefLease 7200
1286 #define kLLQ_MAX_TRIES 3 // retry an operation 3 times max
1287 #define kLLQ_INIT_RESEND 2 // resend an un-ack'd packet after 2 seconds, then double for each additional
1288 #define kLLQ_DEF_RETRY 1800 // retry a failed operation after 30 minutes
1289 // LLQ Operation Codes
1290 #define kLLQ_Setup 1
1291 #define kLLQ_Refresh 2
1293 #define LLQ_OPT_SIZE (2 * sizeof(mDNSu16)) + sizeof(LLQOptData)
1294 #define LEASE_OPT_SIZE (2 * sizeof(mDNSu16)) + sizeof(mDNSs32)
1300 LLQErr_ServFull
= 1,
1303 LLQErr_NoSuchLLQ
= 4,
1305 LLQErr_UnknownErr
= 6
1308 typedef void (*InternalResponseHndlr
)(mDNS
*const m
, DNSMessage
*msg
, const mDNSu8
*end
, DNSQuestion
*question
, void *internalContext
);
1314 InternalResponseHndlr responseCallback
; // NULL if internal field is false
1315 LLQ_Info
*llq
; // NULL for 1-shot queries
1316 CacheRecord
*knownAnswers
;
1318 } uDNS_QuestionInfo
;
1320 // Note: Within an mDNSQuestionCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Close(), mDNS_Execute()
1321 typedef void mDNSQuestionCallback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, mDNSBool AddRecord
);
1322 struct DNSQuestion_struct
1324 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1327 mDNSs32 LastQTime
; // Last scheduled transmission of this Q on *all* applicable interfaces
1328 mDNSs32 ThisQInterval
; // LastQTime + ThisQInterval is the next scheduled transmission of this Q
1329 // ThisQInterval > 0 for an active question;
1330 // ThisQInterval = 0 for a suspended question that's still in the list
1331 // ThisQInterval = -1 for a cancelled question that's been removed from the list
1332 mDNSu32 RecentAnswers
; // Number of answers since the last time we sent this query
1333 mDNSu32 CurrentAnswers
; // Number of records currently in the cache that answer this question
1334 mDNSu32 LargeAnswers
; // Number of answers with rdata > 1024 bytes
1335 mDNSu32 UniqueAnswers
; // Number of answers received with kDNSClass_UniqueRRSet bit set
1336 DNSQuestion
*DuplicateOf
;
1337 DNSQuestion
*NextInDQList
;
1338 DupSuppressInfo DupSuppress
[DupSuppressInfoSize
];
1339 mDNSInterfaceID SendQNow
; // The interface this query is being sent on right now
1340 mDNSBool SendOnAll
; // Set if we're sending this question on all active interfaces
1341 mDNSs32 LastQTxTime
; // Last time this Q was sent on one (but not necessarily all) interfaces
1342 uDNS_QuestionInfo uDNS_info
;
1344 // Client API fields: The client must set up these fields *before* calling mDNS_StartQuery()
1345 mDNSInterfaceID InterfaceID
; // Non-zero if you want to issue queries only on a single specific IP interface
1346 mDNSAddr Target
; // Non-zero if you want to direct queries to a specific unicast target address
1347 mDNSIPPort TargetPort
; // Must be set if Target is set
1348 mDNSOpaque16 TargetQID
; // Must be set if Target is set
1352 mDNSQuestionCallback
*QuestionCallback
;
1353 void *QuestionContext
;
1354 mDNSBool LongLived
; // Set by client for calls to mDNS_StartQuery to indicate LLQs to unicast layer.
1355 // Set by mDNS.c in mDNS_StartBrowse.
1360 // Client API fields: The client must set up name and InterfaceID *before* calling mDNS_StartResolveService()
1361 // When the callback is invoked, ip, port, TXTlen and TXTinfo will have been filled in with the results learned from the network.
1363 mDNSInterfaceID InterfaceID
; // ID of the interface the response was received on
1364 mDNSAddr ip
; // Remote (destination) IP address where this service can be accessed
1365 mDNSIPPort port
; // Port where this service can be accessed
1367 mDNSu8 TXTinfo
[2048]; // Additional demultiplexing information (e.g. LPR queue name)
1370 // Note: Within an mDNSServiceInfoQueryCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Close(), mDNS_Execute()
1371 typedef struct ServiceInfoQuery_struct ServiceInfoQuery
;
1372 typedef void mDNSServiceInfoQueryCallback(mDNS
*const m
, ServiceInfoQuery
*query
);
1373 struct ServiceInfoQuery_struct
1375 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1376 // No fields need to be set up by the client prior to calling mDNS_StartResolveService();
1377 // all required data is passed as parameters to that function.
1378 // The ServiceInfoQuery structure memory is working storage for mDNSCore to discover the requested information
1379 // and place it in the ServiceInfo structure. After the client has called mDNS_StopResolveService(), it may
1380 // dispose of the ServiceInfoQuery structure while retaining the results in the ServiceInfo structure.
1390 mDNSServiceInfoQueryCallback
*ServiceInfoQueryCallback
;
1391 void *ServiceInfoQueryContext
;
1394 // ***************************************************************************
1396 #pragma mark - Main mDNS object, used to hold all the mDNS state
1399 typedef void mDNSCallback(mDNS
*const m
, mStatus result
);
1401 #define CACHE_HASH_SLOTS 499
1405 mDNS_KnownBug_PhantomInterfaces
= 1
1411 DNSQuestion
*ActiveQueries
; //!!!KRS this should be a hashtable (hash on messageID)
1412 DNSQuestion
*CurrentQuery
; // pointer to ActiveQueries list being examined in a loop. Functions that remove
1413 // elements from the ActiveQueries list must update this pointer (if non-NULL) as necessary.
1414 //!!!KRS do the same for registration lists
1415 ServiceRecordSet
*ServiceRegistrations
;
1416 AuthRecord
*RecordRegistrations
;
1417 mDNSu16 NextMessageID
;
1418 mDNSAddr Servers
[32]; //!!!KRS this should be a dynamically allocated linked list
1419 domainname hostname
; // global name for dynamic registration of address records
1420 char NameRegDomain
[MAX_ESCAPED_DOMAIN_NAME
];
1421 // domain in which above hostname is registered
1422 // currently set by the platform layer at startup
1423 // do not set if services / address records are not to be globally registered to an update server
1424 // !!!KRS this must go away once we can learn the reg domain from the network or prefs
1425 char ServiceRegDomain
[MAX_ESCAPED_DOMAIN_NAME
];
1426 // if set, all services that don't explicitly specify a domain upon registration will be
1427 // registered in this domain. if not set, .local will be used by default
1428 struct uDNS_AuthInfo
*AuthInfoList
; // list of domains required authentication for updates. !!!KRS this shoudl be a hashtable
1433 // Internal state fields. These hold the main internal state of mDNSCore;
1434 // the client layer needn't be concerned with them.
1435 // No fields need to be set up by the client prior to calling mDNS_Init();
1436 // all required data is passed as parameters to that function.
1438 mDNS_PlatformSupport
*p
; // Pointer to platform-specific data of indeterminite size
1440 mDNSBool CanReceiveUnicast
;
1441 mDNSBool AdvertiseLocalAddresses
;
1442 mStatus mDNSPlatformStatus
;
1443 mDNSCallback
*MainCallback
;
1446 // For debugging: To catch and report locking failures
1447 mDNSu32 mDNS_busy
; // Incremented between mDNS_Lock/mDNS_Unlock section
1448 mDNSu32 mDNS_reentrancy
; // Incremented when calling a client callback
1449 mDNSu8 mDNS_shutdown
; // Set when we're shutting down, allows us to skip some unnecessary steps
1450 mDNSu8 lock_rrcache
; // For debugging: Set at times when these lists may not be modified
1451 mDNSu8 lock_Questions
;
1452 mDNSu8 lock_Records
;
1453 char MsgBuffer
[80]; // Temp storage used while building error log messages
1455 // Task Scheduling variables
1456 mDNSs32 timenow
; // The time that this particular activation of the mDNS code started
1457 mDNSs32 timenow_last
; // The time the last time we ran
1458 mDNSs32 timenow_adjust
; // Correction applied if we ever discover time went backwards
1459 mDNSs32 NextScheduledEvent
; // Derived from values below
1460 mDNSs32 SuppressSending
; // Don't send *any* packets during this time
1461 mDNSs32 NextCacheCheck
; // Next time to refresh cache record before it expires
1462 mDNSs32 NextScheduledQuery
; // Next time to send query in its exponential backoff sequence
1463 mDNSs32 NextScheduledProbe
; // Next time to probe for new authoritative record
1464 mDNSs32 NextScheduledResponse
; // Next time to send authoritative record(s) in responses
1465 mDNSs32 ExpectUnicastResponse
; // Set when we send a query with the kDNSQClass_UnicastResponse bit set
1466 mDNSs32 RandomQueryDelay
; // For de-synchronization of query packets on the wire
1467 mDNSBool SendDeregistrations
; // Set if we need to send deregistrations (immediately)
1468 mDNSBool SendImmediateAnswers
; // Set if we need to send answers (immediately -- or as soon as SuppressSending clears)
1469 mDNSBool SleepState
; // Set if we're sleeping (send no more packets)
1471 // These fields only required for mDNS Searcher...
1472 DNSQuestion
*Questions
; // List of all registered questions, active and inactive
1473 DNSQuestion
*NewQuestions
; // Fresh questions not yet answered from cache
1474 DNSQuestion
*CurrentQuestion
; // Next question about to be examined in AnswerLocalQuestions()
1475 DNSQuestion
*LocalOnlyQuestions
; // Questions with InterfaceID set to mDNSInterface_LocalOnly
1476 DNSQuestion
*NewLocalOnlyQuestions
; // Fresh local-only questions not yet answered
1477 mDNSu32 rrcache_size
; // Total number of available cache entries
1478 mDNSu32 rrcache_totalused
; // Number of cache entries currently occupied
1479 mDNSu32 rrcache_active
; // Number of cache entries currently occupied by records that answer active questions
1480 mDNSu32 rrcache_report
;
1481 CacheRecord
*rrcache_free
;
1482 CacheRecord
*rrcache_hash
[CACHE_HASH_SLOTS
];
1483 CacheRecord
**rrcache_tail
[CACHE_HASH_SLOTS
];
1484 mDNSu32 rrcache_used
[CACHE_HASH_SLOTS
];
1486 // Fields below only required for mDNS Responder...
1487 domainlabel nicelabel
; // Rich text label encoded using canonically precomposed UTF-8
1488 domainlabel hostlabel
; // Conforms to RFC 1034 "letter-digit-hyphen" ARPANET host name rules
1489 domainname hostname
; // Host Name, e.g. "Foo.local."
1490 UTF8str255 HIHardware
;
1491 UTF8str255 HISoftware
;
1492 AuthRecord
*ResourceRecords
;
1493 AuthRecord
*DuplicateRecords
; // Records currently 'on hold' because they are duplicates of existing records
1494 AuthRecord
*LocalOnlyRecords
; // Local records registered with InterfaceID set to mDNSInterface_LocalOnly
1495 AuthRecord
*NewLocalOnlyRecords
; // Fresh local-only records not yet delivered to local-only questions
1496 mDNSBool DiscardLocalOnlyRecords
;// Set when we have "remove" events we need to deliver to local-only questions
1497 AuthRecord
*CurrentRecord
; // Next AuthRecord about to be examined
1498 NetworkInterfaceInfo
*HostInterfaces
;
1499 mDNSs32 ProbeFailTime
;
1500 mDNSu32 NumFailedProbes
;
1501 mDNSs32 SuppressProbes
;
1503 // unicast-specific data
1504 uDNS_GlobalInfo uDNS_info
;
1507 // ***************************************************************************
1509 #pragma mark - Useful Static Constants
1512 extern const mDNSIPPort zeroIPPort
;
1513 extern const mDNSv4Addr zeroIPAddr
;
1514 extern const mDNSv6Addr zerov6Addr
;
1515 extern const mDNSv4Addr onesIPv4Addr
;
1516 extern const mDNSv6Addr onesIPv6Addr
;
1517 extern const mDNSAddr zeroAddr
;
1519 extern const mDNSInterfaceID mDNSInterface_Any
; // Zero
1520 extern const mDNSInterfaceID mDNSInterface_LocalOnly
; // (mDNSInterfaceID)-1;
1521 extern const mDNSInterfaceID mDNSInterface_ForceMCast
; // (mDNSInterfaceID)-2;
1523 extern const mDNSIPPort UnicastDNSPort
;
1524 extern const mDNSIPPort MulticastDNSPort
;
1525 extern const mDNSv4Addr AllDNSAdminGroup
;
1526 extern const mDNSv4Addr AllDNSLinkGroup
;
1527 extern const mDNSv6Addr AllDNSLinkGroupv6
;
1528 extern const mDNSAddr AllDNSLinkGroup_v4
;
1529 extern const mDNSAddr AllDNSLinkGroup_v6
;
1531 extern const mDNSOpaque16 zeroID
;
1532 extern const mDNSOpaque16 QueryFlags
;
1533 extern const mDNSOpaque16 ResponseFlags
;
1534 extern const mDNSOpaque16 UpdateReqFlags
;
1535 extern const mDNSOpaque16 UpdateRespFlags
;
1537 // ***************************************************************************
1539 #pragma mark - Inline functions
1542 #if (defined(_MSC_VER))
1543 #define mDNSinline static __inline
1544 #elif ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
1545 #define mDNSinline static inline
1548 // If we're not doing inline functions, then this header needs to have the extern declarations
1549 #if !defined(mDNSinline)
1550 extern mDNSu16
mDNSVal16(mDNSOpaque16 x
);
1551 extern mDNSu32
mDNSVal32(mDNSOpaque32 x
);
1552 extern mDNSOpaque16
mDNSOpaque16fromIntVal(mDNSu16 v
);
1553 extern mDNSOpaque32
mDNSOpaque32fromIntVal(mDNSu32 v
);
1556 // If we're compiling the particular C file that instantiates our inlines, then we
1557 // define "mDNSinline" (to empty string) so that we generate code in the following section
1558 #if (!defined(mDNSinline) && mDNS_InstantiateInlines)
1564 mDNSinline mDNSu16
mDNSVal16(mDNSOpaque16 x
) { return((mDNSu16
)((mDNSu16
)x
.b
[0] << 8 | (mDNSu16
)x
.b
[1])); }
1565 mDNSinline mDNSu32
mDNSVal32(mDNSOpaque32 x
) { return((mDNSu32
)((mDNSu32
)x
.b
[0] << 24 | (mDNSu32
)x
.b
[1] << 16 | (mDNSu32
)x
.b
[2] << 8 | (mDNSu32
)x
.b
[3])); }
1567 mDNSinline mDNSOpaque16
mDNSOpaque16fromIntVal(mDNSu16 v
)
1570 x
.b
[0] = (mDNSu8
)(v
>> 8);
1571 x
.b
[1] = (mDNSu8
)(v
& 0xFF);
1575 mDNSinline mDNSOpaque32
mDNSOpaque32fromIntVal(mDNSu32 v
)
1578 x
.b
[0] = (mDNSu8
) (v
>> 24) ;
1579 x
.b
[1] = (mDNSu8
)((v
>> 16) & 0xFF);
1580 x
.b
[2] = (mDNSu8
)((v
>> 8 ) & 0xFF);
1581 x
.b
[3] = (mDNSu8
)((v
) & 0xFF);
1587 // ***************************************************************************
1589 #pragma mark - Main Client Functions
1592 // Every client should call mDNS_Init, passing in storage for the mDNS object and the mDNS_PlatformSupport object.
1594 // Clients that are only advertising services should use mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize.
1595 // Clients that plan to perform queries (mDNS_StartQuery, mDNS_StartBrowse, mDNS_StartResolveService, etc.)
1596 // need to provide storage for the resource record cache, or the query calls will return 'mStatus_NoCache'.
1597 // The rrcachestorage parameter is the address of memory for the resource record cache, and
1598 // the rrcachesize parameter is the number of entries in the CacheRecord array passed in.
1599 // (i.e. the size of the cache memory needs to be sizeof(CacheRecord) * rrcachesize).
1600 // OS X 10.3 Panther uses an initial cache size of 64 entries, and then mDNSCore sends an
1601 // mStatus_GrowCache message if it needs more.
1603 // Most clients should use mDNS_Init_AdvertiseLocalAddresses. This causes mDNSCore to automatically
1604 // create the correct address records for all the hosts interfaces. If you plan to advertise
1605 // services being offered by the local machine, this is almost always what you want.
1606 // There are two cases where you might use mDNS_Init_DontAdvertiseLocalAddresses:
1607 // 1. A client-only device, that browses for services but doesn't advertise any of its own.
1608 // 2. A proxy-registration service, that advertises services being offered by other machines, and takes
1609 // the appropriate steps to manually create the correct address records for those other machines.
1610 // In principle, a proxy-like registration service could manually create address records for its own machine too,
1611 // but this would be pointless extra effort when using mDNS_Init_AdvertiseLocalAddresses does that for you.
1613 // When mDNS has finished setting up the client's callback is called
1614 // A client can also spin and poll the mDNSPlatformStatus field to see when it changes from mStatus_Waiting to mStatus_NoError
1616 // Call mDNS_Close to tidy up before exiting
1618 // Call mDNS_Register with a completed AuthRecord object to register a resource record
1619 // If the resource record type is kDNSRecordTypeUnique (or kDNSknownunique) then if a conflicting resource record is discovered,
1620 // the resource record's mDNSRecordCallback will be called with error code mStatus_NameConflict. The callback should deregister
1621 // the record, and may then try registering the record again after picking a new name (e.g. by automatically appending a number).
1623 // Call mDNS_StartQuery to initiate a query. mDNS will proceed to issue Multicast DNS query packets, and any time a response
1624 // is received containing a record which matches the question, the DNSQuestion's mDNSAnswerCallback function will be called
1625 // Call mDNS_StopQuery when no more answers are required
1627 // Care should be taken on multi-threaded or interrupt-driven environments.
1628 // The main mDNS routines call mDNSPlatformLock() on entry and mDNSPlatformUnlock() on exit;
1629 // each platform layer needs to implement these appropriately for its respective platform.
1630 // For example, if the support code on a particular platform implements timer callbacks at interrupt time, then
1631 // mDNSPlatformLock/Unlock need to disable interrupts or do similar concurrency control to ensure that the mDNS
1632 // code is not entered by an interrupt-time timer callback while in the middle of processing a client call.
1634 extern mStatus
mDNS_Init (mDNS
*const m
, mDNS_PlatformSupport
*const p
,
1635 CacheRecord
*rrcachestorage
, mDNSu32 rrcachesize
,
1636 mDNSBool AdvertiseLocalAddresses
,
1637 mDNSCallback
*Callback
, void *Context
);
1638 // See notes above on use of NoCache/ZeroCacheSize
1639 #define mDNS_Init_NoCache mDNSNULL
1640 #define mDNS_Init_ZeroCacheSize 0
1641 // See notes above on use of Advertise/DontAdvertiseLocalAddresses
1642 #define mDNS_Init_AdvertiseLocalAddresses mDNStrue
1643 #define mDNS_Init_DontAdvertiseLocalAddresses mDNSfalse
1644 #define mDNS_Init_NoInitCallback mDNSNULL
1645 #define mDNS_Init_NoInitCallbackContext mDNSNULL
1647 extern void mDNS_GrowCache (mDNS
*const m
, CacheRecord
*storage
, mDNSu32 numrecords
);
1648 extern void mDNS_Close (mDNS
*const m
);
1649 extern mDNSs32
mDNS_Execute (mDNS
*const m
);
1651 extern mStatus
mDNS_Register (mDNS
*const m
, AuthRecord
*const rr
);
1652 extern mStatus
mDNS_Update (mDNS
*const m
, AuthRecord
*const rr
, mDNSu32 newttl
,
1653 const mDNSu16 newrdlength
,
1654 RData
*const newrdata
, mDNSRecordUpdateCallback
*Callback
);
1655 extern mStatus
mDNS_Deregister(mDNS
*const m
, AuthRecord
*const rr
);
1657 extern mStatus
mDNS_StartQuery(mDNS
*const m
, DNSQuestion
*const question
);
1658 extern mStatus
mDNS_StopQuery (mDNS
*const m
, DNSQuestion
*const question
);
1659 extern mStatus
mDNS_Reconfirm (mDNS
*const m
, CacheRecord
*const cacherr
);
1660 extern mStatus
mDNS_ReconfirmByValue(mDNS
*const m
, ResourceRecord
*const rr
);
1662 // ***************************************************************************
1664 #pragma mark - Platform support functions that are accessible to the client layer too
1667 extern mDNSs32 mDNSPlatformOneSecond
;
1668 extern mDNSs32
mDNSPlatformTimeNow(void);
1670 // ***************************************************************************
1672 #pragma mark - General utility and helper functions
1675 // mDNS_RegisterService is a single call to register the set of resource records associated with a given named service.
1677 // mDNS_StartResolveService is single call which is equivalent to multiple calls to mDNS_StartQuery,
1678 // to find the IP address, port number, and demultiplexing information for a given named service.
1679 // As with mDNS_StartQuery, it executes asynchronously, and calls the ServiceInfoQueryCallback when the answer is
1680 // found. After the service is resolved, the client should call mDNS_StopResolveService to complete the transaction.
1681 // The client can also call mDNS_StopResolveService at any time to abort the transaction.
1683 // mDNS_GetBrowseDomains is a special case of the mDNS_StartQuery call, where the resulting answers
1684 // are a list of PTR records indicating (in the rdata) domains that are recommended for browsing.
1685 // After getting the list of domains to browse, call mDNS_StopQuery to end the search.
1686 // mDNS_GetDefaultBrowseDomain returns the name of the domain that should be highlighted by default.
1688 // mDNS_GetRegistrationDomains and mDNS_GetDefaultRegistrationDomain are the equivalent calls to get the list
1689 // of one or more domains that should be offered to the user as choices for where they may register their service,
1690 // and the default domain in which to register in the case where the user has made no selection.
1692 extern void mDNS_SetupResourceRecord(AuthRecord
*rr
, RData
*RDataStorage
, mDNSInterfaceID InterfaceID
,
1693 mDNSu16 rrtype
, mDNSu32 ttl
, mDNSu8 RecordType
, mDNSRecordCallback Callback
, void *Context
);
1695 extern mStatus
mDNS_RegisterService (mDNS
*const m
, ServiceRecordSet
*sr
,
1696 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
1697 const domainname
*const host
, mDNSIPPort port
, const mDNSu8 txtinfo
[], mDNSu16 txtlen
,
1698 AuthRecord
*SubTypes
, mDNSu32 NumSubTypes
,
1699 const mDNSInterfaceID InterfaceID
, mDNSServiceCallback Callback
, void *Context
);
1700 extern mStatus
mDNS_AddRecordToService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
, RData
*rdata
, mDNSu32 ttl
);
1701 extern mStatus
mDNS_RemoveRecordFromService(mDNS
*const m
, ServiceRecordSet
*sr
, ExtraResourceRecord
*extra
);
1702 extern mStatus
mDNS_RenameAndReregisterService(mDNS
*const m
, ServiceRecordSet
*const sr
, const domainlabel
*newname
);
1703 extern mStatus
mDNS_DeregisterService(mDNS
*const m
, ServiceRecordSet
*sr
);
1705 extern mStatus
mDNS_RegisterNoSuchService(mDNS
*const m
, AuthRecord
*const rr
,
1706 const domainlabel
*const name
, const domainname
*const type
, const domainname
*const domain
,
1707 const domainname
*const host
,
1708 const mDNSInterfaceID InterfaceID
, mDNSRecordCallback Callback
, void *Context
);
1709 #define mDNS_DeregisterNoSuchService mDNS_Deregister
1711 extern mStatus
mDNS_StartBrowse(mDNS
*const m
, DNSQuestion
*const question
,
1712 const domainname
*const srv
, const domainname
*const domain
,
1713 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
);
1714 #define mDNS_StopBrowse mDNS_StopQuery
1716 extern mStatus
mDNS_StartResolveService(mDNS
*const m
, ServiceInfoQuery
*query
, ServiceInfo
*info
, mDNSServiceInfoQueryCallback
*Callback
, void *Context
);
1717 extern void mDNS_StopResolveService (mDNS
*const m
, ServiceInfoQuery
*query
);
1721 mDNS_DomainTypeBrowse
= 0,
1722 mDNS_DomainTypeBrowseDefault
= 1,
1723 mDNS_DomainTypeRegistration
= 2,
1724 mDNS_DomainTypeRegistrationDefault
= 3
1727 extern mStatus
mDNS_GetDomains(mDNS
*const m
, DNSQuestion
*const question
, mDNS_DomainType DomainType
, const domainname
*dom
,
1728 const mDNSInterfaceID InterfaceID
, mDNSQuestionCallback
*Callback
, void *Context
);
1729 #define mDNS_StopGetDomains mDNS_StopQuery
1730 extern mStatus
mDNS_AdvertiseDomains(mDNS
*const m
, AuthRecord
*rr
, mDNS_DomainType DomainType
, const mDNSInterfaceID InterfaceID
, char *domname
);
1731 #define mDNS_StopAdvertiseDomains mDNS_Deregister
1733 // ***************************************************************************
1735 #pragma mark - DNS name utility functions
1738 // In order to expose the full capabilities of the DNS protocol (which allows any arbitrary eight-bit values
1739 // in domain name labels, including unlikely characters like ascii nulls and even dots) all the mDNS APIs
1740 // work with DNS's native length-prefixed strings. For convenience in C, the following utility functions
1741 // are provided for converting between C's null-terminated strings and DNS's length-prefixed strings.
1744 // A simple C structure assignment of a domainname can cause a protection fault by accessing unmapped memory,
1745 // because that object is defined to be 256 bytes long, but not all domainname objects are truly the full size.
1746 // This macro uses mDNSPlatformMemCopy() to make sure it only touches the actual bytes that are valid.
1747 #define AssignDomainName(DST, SRC) mDNSPlatformMemCopy((SRC).c, (DST).c, DomainNameLength(&(SRC)))
1749 // Comparison functions
1750 extern mDNSBool
SameDomainLabel(const mDNSu8
*a
, const mDNSu8
*b
);
1751 extern mDNSBool
SameDomainName(const domainname
*const d1
, const domainname
*const d2
);
1752 extern mDNSBool
IsLocalDomain(const domainname
*d
); // returns true for domains that by default should be looked up using link-local multicast
1754 // Get total length of domain name, in native DNS format, including terminal root label
1755 // (e.g. length of "com." is 5 (length byte, three data bytes, final zero)
1756 extern mDNSu16
DomainNameLength(const domainname
*const name
);
1758 // Append functions to append one or more labels to an existing native format domain name:
1759 // AppendLiteralLabelString adds a single label from a literal C string, with no escape character interpretation.
1760 // AppendDNSNameString adds zero or more labels from a C string using conventional DNS dots-and-escaping interpretation
1761 // AppendDomainLabel adds a single label from a native format domainlabel
1762 // AppendDomainName adds zero or more labels from a native format domainname
1763 extern mDNSu8
*AppendLiteralLabelString(domainname
*const name
, const char *cstr
);
1764 extern mDNSu8
*AppendDNSNameString (domainname
*const name
, const char *cstr
);
1765 extern mDNSu8
*AppendDomainLabel (domainname
*const name
, const domainlabel
*const label
);
1766 extern mDNSu8
*AppendDomainName (domainname
*const name
, const domainname
*const append
);
1768 // Convert from null-terminated string to native DNS format:
1769 // The DomainLabel form makes a single label from a literal C string, with no escape character interpretation.
1770 // The DomainName form makes native format domain name from a C string using conventional DNS interpretation:
1771 // dots separate labels, and within each label, '\.' represents a literal dot, '\\' represents a literal
1772 // backslash and backslash with three decimal digits (e.g. \000) represents an arbitrary byte value.
1773 extern mDNSBool
MakeDomainLabelFromLiteralString(domainlabel
*const label
, const char *cstr
);
1774 extern mDNSu8
*MakeDomainNameFromDNSNameString (domainname
*const name
, const char *cstr
);
1776 // Convert native format domainlabel or domainname back to C string format
1778 // When using ConvertDomainLabelToCString, the target buffer must be MAX_ESCAPED_DOMAIN_LABEL (254) bytes long
1779 // to guarantee there will be no buffer overrun. It is only safe to use a buffer shorter than this in rare cases
1780 // where the label is known to be constrained somehow (for example, if the label is known to be either "_tcp" or "_udp").
1781 // Similarly, when using ConvertDomainNameToCString, the target buffer must be MAX_ESCAPED_DOMAIN_NAME (1005) bytes long.
1782 // See definitions of MAX_ESCAPED_DOMAIN_LABEL and MAX_ESCAPED_DOMAIN_NAME for more detailed explanation.
1783 extern char *ConvertDomainLabelToCString_withescape(const domainlabel
*const name
, char *cstr
, char esc
);
1784 #define ConvertDomainLabelToCString_unescaped(D,C) ConvertDomainLabelToCString_withescape((D), (C), 0)
1785 #define ConvertDomainLabelToCString(D,C) ConvertDomainLabelToCString_withescape((D), (C), '\\')
1786 extern char *ConvertDomainNameToCString_withescape(const domainname
*const name
, char *cstr
, char esc
);
1787 #define ConvertDomainNameToCString_unescaped(D,C) ConvertDomainNameToCString_withescape((D), (C), 0)
1788 #define ConvertDomainNameToCString(D,C) ConvertDomainNameToCString_withescape((D), (C), '\\')
1790 extern void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name
[], domainlabel
*const hostlabel
);
1792 extern mDNSu8
*ConstructServiceName(domainname
*const fqdn
, const domainlabel
*name
, const domainname
*type
, const domainname
*const domain
);
1793 extern mDNSBool
DeconstructServiceName(const domainname
*const fqdn
, domainlabel
*const name
, domainname
*const type
, domainname
*const domain
);
1795 // Note: Some old functions have been replaced by more sensibly-named versions.
1796 // You can uncomment the hash-defines below if you don't want to have to change your source code right away.
1797 // When updating your code, note that (unlike the old versions) *all* the new routines take the target object
1798 // as their first parameter.
1799 //#define ConvertCStringToDomainName(SRC,DST) MakeDomainNameFromDNSNameString((DST),(SRC))
1800 //#define ConvertCStringToDomainLabel(SRC,DST) MakeDomainLabelFromLiteralString((DST),(SRC))
1801 //#define AppendStringLabelToName(DST,SRC) AppendLiteralLabelString((DST),(SRC))
1802 //#define AppendStringNameToName(DST,SRC) AppendDNSNameString((DST),(SRC))
1803 //#define AppendDomainLabelToName(DST,SRC) AppendDomainLabel((DST),(SRC))
1804 //#define AppendDomainNameToName(DST,SRC) AppendDomainName((DST),(SRC))
1806 // ***************************************************************************
1808 #pragma mark - Other utility functions
1811 extern mDNSu32
mDNS_vsnprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, va_list arg
);
1812 extern mDNSu32
mDNS_snprintf(char *sbuffer
, mDNSu32 buflen
, const char *fmt
, ...) IS_A_PRINTF_STYLE_FUNCTION(3,4);
1813 extern mDNSu32
NumCacheRecordsForInterfaceID(const mDNS
*const m
, mDNSInterfaceID id
);
1814 extern char *DNSTypeName(mDNSu16 rrtype
);
1815 extern char *GetRRDisplayString_rdb(mDNS
*const m
, const ResourceRecord
*rr
, RDataBody
*rd
);
1816 #define GetRRDisplayString(m, rr) GetRRDisplayString_rdb((m), &(rr)->resrec, &(rr)->resrec.rdata->u)
1817 extern mDNSBool
mDNSSameAddress(const mDNSAddr
*ip1
, const mDNSAddr
*ip2
);
1818 extern void IncrementLabelSuffix(domainlabel
*name
, mDNSBool RichText
);
1820 // ***************************************************************************
1822 #pragma mark - Authentication Support
1826 #define HMAC_IPAD 0x36
1827 #define HMAC_OPAD 0x5c
1830 // padded keys for inned/outer hash rounds
1833 mDNSu8 ipad
[HMAC_LEN
];
1834 mDNSu8 opad
[HMAC_LEN
];
1837 // Internal data structure to maintain authentication information for an update domain
1838 typedef struct uDNS_AuthInfo
1843 struct uDNS_AuthInfo
*next
;
1846 // Platform Support for computing MD5
1847 // mDNSPlatformUTC returns the time, in seconds, since Jan 1st 1970 UTC and is required for generating TSIG records
1849 extern mDNSs32
mDNSPlatformUTC(void);
1852 // mDNS_UpdateDomainRequiresAuthentication tells the core to authenticate (via TSIG with an HMAC_MD5 hash)
1853 // when dynamically updating a given zone (and its subdomains). The key used in authentication must be in
1854 // domain name format. The shared secret must be a base64 encoded string with the base64 parameter set to
1855 // true, or binary data with the base64 parameter set to false. The length is the size of the secret in
1856 // bytes. (A minimum size of 16 bytes (128 bits) is recommended for an MD5 hash as per RFC 2485).
1857 // The This routine is normally called once for each secure domain at startup, though it can be called at any time.
1859 // mDNS_ClearAuthenticationList clears from the core's internal structures all domains previously passed to
1860 // mDNS_UpdateDomainRequiresAuthentication.
1862 extern mStatus
mDNS_UpdateDomainRequiresAuthentication(mDNS
*m
, domainname
*zone
, domainname
*key
,
1863 mDNSu8
*sharedSecret
, mDNSu32 ssLen
, mDNSBool base64
);
1865 extern void mDNS_ClearAuthenticationList(mDNS
*m
);
1867 // Routines called by the core, exported by DNSDigest.c
1869 // Convert a base64 encoded key into a binary byte stream
1870 extern mDNSs32
DNSDigest_Base64ToBin(const char *src
, mDNSu8
*target
, mDNSu32 targsize
);
1872 // Convert an arbitrary binary key (of any length) into an HMAC key (stored in AuthInfo struct)
1873 extern void DNSDigest_ConstructHMACKey(uDNS_AuthInfo
*info
, mDNSu8
*key
, mDNSu32 len
);
1875 // sign a DNS message. The message must be compete, with all values in network byte order. end points to the end
1876 // of the message, and is modified by this routine. numAdditionals is a pointer to the number of additional
1877 // records in HOST byte order, which is incremented upon successful completion of this routine. The function returns
1878 // the new end pointer on success, and NULL on failure.
1879 extern mDNSu8
*DNSDigest_SignMessage(DNSMessage
*msg
, mDNSu8
**end
, mDNSu16
*numAdditionals
, uDNS_AuthInfo
*info
);
1881 // MD5 hash function used by the core for signing TSIG records (impemented in DNSDigest.c)
1882 extern mStatus
DNSDigest_MD5(const DNSMessage
*msg
, mDNSu32 msglen
, mDNSOpaque16
*digest
);
1884 // ***************************************************************************
1886 #pragma mark - PlatformSupport interface
1889 // This section defines the interface to the Platform Support layer.
1890 // Normal client code should not use any of types defined here, or directly call any of the functions defined here.
1891 // The definitions are placed here because sometimes clients do use these calls indirectly, via other supported client operations.
1892 // For example, AssignDomainName is a macro defined using mDNSPlatformMemCopy()
1894 // Every platform support module must provide the following functions.
1895 // mDNSPlatformInit() typically opens a communication endpoint, and starts listening for mDNS packets.
1896 // When Setup is complete, the platform support layer calls mDNSCoreInitComplete().
1897 // mDNSPlatformSendUDP() sends one UDP packet
1898 // When a packet is received, the PlatformSupport code calls mDNSCoreReceive()
1899 // mDNSPlatformClose() tidies up on exit
1900 // Note: mDNSPlatformMemAllocate/mDNSPlatformMemFree are only required for handling oversized resource records and unicast DNS.
1901 // If your target platform has a well-defined specialized application, and you know that all the records it uses
1902 // are InlineCacheRDSize or less, then you can just make a simple mDNSPlatformMemAllocate() stub that always returns
1903 // NULL. InlineCacheRDSize is a compile-time constant, which is set by default to 64. If you need to handle records
1904 // a little larger than this and you don't want to have to implement run-time allocation and freeing, then you
1905 // can raise the value of this constant to a suitable value (at the expense of increased memory usage).
1906 extern mStatus
mDNSPlatformInit (mDNS
*const m
);
1907 extern void mDNSPlatformClose (mDNS
*const m
);
1908 extern mStatus
mDNSPlatformSendUDP(const mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
1909 mDNSInterfaceID InterfaceID
, const mDNSAddr
*dst
, mDNSIPPort dstport
);
1911 extern void mDNSPlatformLock (const mDNS
*const m
);
1912 extern void mDNSPlatformUnlock (const mDNS
*const m
);
1914 extern void mDNSPlatformStrCopy (const void *src
, void *dst
);
1915 extern mDNSu32
mDNSPlatformStrLen (const void *src
);
1916 extern void mDNSPlatformMemCopy (const void *src
, void *dst
, mDNSu32 len
);
1917 extern mDNSBool
mDNSPlatformMemSame (const void *src
, const void *dst
, mDNSu32 len
);
1918 extern void mDNSPlatformMemZero ( void *dst
, mDNSu32 len
);
1919 extern void * mDNSPlatformMemAllocate (mDNSu32 len
);
1920 extern void mDNSPlatformMemFree (void *mem
);
1921 extern mStatus
mDNSPlatformTimeInit (mDNSs32
*timenow
);
1923 // Platform support modules should provide the following functions to map between opaque interface IDs
1924 // and interface indexes in order to support the DNS-SD API. If your target platform does not support
1925 // multiple interfaces and/or does not support the DNS-SD API, these functions can be empty.
1926 extern mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(const mDNS
*const m
, mDNSu32 index
);
1927 extern mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(const mDNS
*const m
, mDNSInterfaceID id
);
1929 // Every platform support module must provide the following functions if it is to support unicast DNS
1930 // and Dynamic Update.
1931 // All TCP socket operations implemented by the platform layer MUST NOT BLOCK.
1932 // mDNSPlatformTCPConnect initiates a TCP connection with a peer, adding the socket descriptor to the
1933 // main event loop. The return value indicates whether the connection succeeded, failed, or is pending
1934 // (i.e. the call would block.) On return, the descriptor parameter is set to point to the connected socket.
1935 // The TCPConnectionCallback is subsequently invoked when the connection
1936 // completes (in which case the ConnectionEstablished parameter is true), or data is available for
1937 // reading on the socket (indicated by the ConnectionEstablished parameter being false.) If the connection
1938 // asyncronously fails, the TCPConnectionCallback should be invoked as usual, with the error being
1939 // returned in subsequent calls to PlatformReadTCP or PlatformWriteTCP. (This allows for platforms
1940 // with limited asyncronous error detection capabilities.) PlatformReadTCP and PlatformWriteTCP must
1941 // return the number of bytes read/written, 0 if the call would block, and -1 if an error.
1942 // PlatformTCPCloseConnection must close the connection to the peer and remove the descriptor from the
1943 // event loop. CloseConnectin may be called at any time, including in a ConnectionCallback.
1945 typedef void (*TCPConnectionCallback
)(int sd
, void *context
, mDNSBool ConnectionEstablished
);
1946 extern mStatus
mDNSPlatformTCPConnect(const mDNSAddr
*dst
, mDNSOpaque16 dstport
, mDNSInterfaceID InterfaceID
,
1947 TCPConnectionCallback callback
, void *context
, int *descriptor
);
1948 extern void mDNSPlatformTCPCloseConnection(int sd
);
1949 extern int mDNSPlatformReadTCP(int sd
, void *buf
, int buflen
);
1950 extern int mDNSPlatformWriteTCP(int sd
, const char *msg
, int len
);
1952 // Platforms that support unicast browsing and dynamic update registration for clients who do not specify a domain
1953 // in browse/registration calls must implement these routines to get the "default" browse/registration list.
1954 // The Get() functions must return a linked list of DNameListElem structs, allocated via mDNSPlatformMemAllocate.
1955 // Platforms may implement the Get() calls via the mDNS_CopyDNameList() helper routine.
1956 // Callers should free lists obtained via the Get() calls with th mDNS_FreeDNameList routine, provided by the core.
1958 typedef struct DNameListElem
1961 struct DNameListElem
*next
;
1964 extern DNameListElem
*mDNSPlatformGetSearchDomainList(void);
1965 extern DNameListElem
*mDNSPlatformGetRegDomainList(void);
1967 // Helper functions provided by the core
1968 extern DNameListElem
*mDNS_CopyDNameList(const DNameListElem
*orig
);
1969 extern void mDNS_FreeDNameList(DNameListElem
*list
);
1971 // The core mDNS code provides these functions, for the platform support code to call at appropriate times
1973 // mDNS_GenerateFQDN() is called once on startup (typically from mDNSPlatformInit())
1974 // and then again on each subsequent change of the dot-local host name.
1977 // mDNS_GenerateGlobalFQDN() is called to register a domain name via Dynamic DNS update. It should be
1978 // called on startup (after acquiring an IP address and DNS server) and on each change to the machine name
1979 // or registration domain. The domain parameter is the domain in which the address record is to be registered,
1980 // e.g. "mycompany.com". The full name is formed by appending this domain to the machine's host label.
1982 // mDNS_RegisterInterface() is used by the platform support layer to inform mDNSCore of what
1983 // physical and/or logical interfaces are available for sending and receiving packets.
1984 // Typically it is called on startup for each available interface, but register/deregister may be
1985 // called again later, on multiple occasions, to inform the core of interface configuration changes.
1986 // If set->Advertise is set non-zero, then mDNS_RegisterInterface() also registers the standard
1987 // resource records that should be associated with every publicised IP address/interface:
1988 // -- Name-to-address records (A/AAAA)
1989 // -- Address-to-name records (PTR)
1990 // -- Host information (HINFO)
1991 // IMPORTANT: The specified mDNSInterfaceID MUST NOT be 0, -1, or -2; these values have special meaning
1993 // mDNS_SetDynamicRegistrationDomain is used to enable dynamic update registrations of address records
1994 // in the specified domain.
1996 // mDNS_RegisterDNS() is used by the platform support layer to provide the core with the addresses of
1997 // available domain name servers for unicast queries/updates. RegisterDNS() should be called once for
1998 // each name server, typically at startup, or when a new name server becomes available. DeregiterDNS()
1999 // must be called whenever a registered name server becomes unavailable. DeregisterDNSList deregisters
2000 // all registered servers. mDNS_DNSRegistered() returns true if one or more servers are registered in the core.
2002 // mDNSCoreInitComplete() is called when the platform support layer is finished.
2003 // Typically this is at the end of mDNSPlatformInit(), but may be later
2004 // (on platforms like OT that allow asynchronous initialization of the networking stack).
2006 // mDNSCoreReceive() is called when a UDP packet is received
2008 // mDNSCoreMachineSleep() is called when the machine sleeps or wakes
2009 // (This refers to heavyweight laptop-style sleep/wake that disables network access,
2010 // not lightweight second-by-second CPU power management modes.)
2012 extern void mDNS_GenerateFQDN(mDNS
*const m
);
2013 extern void mDNS_GenerateGlobalFQDN(mDNS
*const m
);
2014 extern mStatus
mDNS_RegisterInterface (mDNS
*const m
, NetworkInterfaceInfo
*set
);
2015 extern void mDNS_DeregisterInterface(mDNS
*const m
, NetworkInterfaceInfo
*set
);
2016 extern void mDNS_RegisterDNS(mDNS
*const m
, mDNSv4Addr
*const dnsAddr
);
2017 extern void mDNS_DeregisterDNS(mDNS
*const m
, mDNSv4Addr
*const dnsAddr
);
2018 extern void mDNS_DeregisterDNSList(mDNS
*const m
);
2019 extern mDNSBool
mDNS_DNSRegistered(mDNS
*const m
);
2020 extern void mDNSCoreInitComplete(mDNS
*const m
, mStatus result
);
2021 extern void mDNSCoreReceive(mDNS
*const m
, DNSMessage
*const msg
, const mDNSu8
*const end
,
2022 const mDNSAddr
*const srcaddr
, const mDNSIPPort srcport
,
2023 const mDNSAddr
*const dstaddr
, const mDNSIPPort dstport
, const mDNSInterfaceID InterfaceID
, mDNSu8 ttl
);
2024 extern void mDNSCoreMachineSleep(mDNS
*const m
, mDNSBool wake
);
2026 extern mDNSBool
mDNSAddrIsDNSMulticast(const mDNSAddr
*ip
);
2028 // ***************************************************************************
2030 #pragma mark - Compile-Time assertion checks
2033 // Some C compiler cleverness. We can make the compiler check certain things for
2034 // us, and report compile-time errors if anything is wrong. The usual way to do
2035 // this would be to use a run-time "if" statement, but then you don't find out
2036 // what's wrong until you run the software. This way, if the assertion condition
2037 // is false, the array size is negative, and the complier complains immediately.
2039 struct mDNS_CompileTimeAssertionChecks
2041 // Check that the compiler generated our on-the-wire packet format structure definitions
2042 // properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
2043 char assert0
[(sizeof(rdataSRV
) == 262 ) ? 1 : -1];
2044 char assert1
[(sizeof(DNSMessageHeader
) == 12 ) ? 1 : -1];
2045 char assert2
[(sizeof(DNSMessage
) == 12+AbsoluteMaxDNSMessageData
) ? 1 : -1];
2046 char assert3
[(sizeof(mDNSs8
) == 1 ) ? 1 : -1];
2047 char assert4
[(sizeof(mDNSu8
) == 1 ) ? 1 : -1];
2048 char assert5
[(sizeof(mDNSs16
) == 2 ) ? 1 : -1];
2049 char assert6
[(sizeof(mDNSu16
) == 2 ) ? 1 : -1];
2050 char assert7
[(sizeof(mDNSs32
) == 4 ) ? 1 : -1];
2051 char assert8
[(sizeof(mDNSu32
) == 4 ) ? 1 : -1];
2052 char assert9
[(sizeof(mDNSOpaque16
) == 2 ) ? 1 : -1];
2053 char assertA
[(sizeof(mDNSOpaque32
) == 4 ) ? 1 : -1];
2054 char assertB
[(sizeof(mDNSOpaque128
) == 16 ) ? 1 : -1];
2057 // ***************************************************************************