]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/mDNSEmbeddedAPI.h
6397c1fa6b42f75d6f7ce89051dfe5ec54fddd41
[apple/mdnsresponder.git] / mDNSCore / mDNSEmbeddedAPI.h
1 /*
2 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22
23
24 NOTE:
25 If you're building an application that uses DNS Service Discovery
26 this is probably NOT the header file you're looking for.
27 In most cases you will want to use /usr/include/dns_sd.h instead.
28
29 This header file defines the lowest level raw interface to mDNSCore,
30 which is appropriate *only* on tiny embedded systems where everything
31 runs in a single address space and memory is extremely constrained.
32 All the APIs here are malloc-free, which means that the caller is
33 responsible for passing in a pointer to the relevant storage that
34 will be used in the execution of that call, and (when called with
35 correct parameters) all the calls are guaranteed to succeed. There
36 is never a case where a call can suffer intermittent failures because
37 the implementation calls malloc() and sometimes malloc() returns NULL
38 because memory is so limited that no more is available.
39 This is primarily for devices that need to have precisely known fixed
40 memory requirements, with absolutely no uncertainty or run-time variation,
41 but that certainty comes at a cost of more difficult programming.
42
43 For applications running on general-purpose desktop operating systems
44 (Mac OS, Linux, Solaris, Windows, etc.) the API you should use is
45 /usr/include/dns_sd.h, which defines the API by which multiple
46 independent client processes communicate their DNS Service Discovery
47 requests to a single "mdnsd" daemon running in the background.
48
49 Even on platforms that don't run multiple independent processes in
50 multiple independent address spaces, you can still use the preferred
51 dns_sd.h APIs by linking in "dnssd_clientshim.c", which implements
52 the standard "dns_sd.h" API calls, allocates any required storage
53 using malloc(), and then calls through to the low-level malloc-free
54 mDNSCore routines defined here. This has the benefit that even though
55 you're running on a small embedded system with a single address space,
56 you can still use the exact same client C code as you'd use on a
57 general-purpose desktop system.
58
59
60 Change History (most recent first):
61
62 $Log: mDNSEmbeddedAPI.h,v $
63 Revision 1.275 2005/01/27 22:57:55 cheshire
64 Fix compile errors on gcc4
65
66 Revision 1.274 2005/01/19 21:01:54 ksekar
67 <rdar://problem/3955355> uDNS needs to support subtype registration and browsing
68
69 Revision 1.273 2005/01/19 19:15:31 ksekar
70 Refinement to <rdar://problem/3954575> - Simplify mDNS_PurgeResultsForDomain logic and move into daemon layer
71
72 Revision 1.272 2005/01/18 18:10:55 ksekar
73 <rdar://problem/3954575> Use 10.4 resolver API to get search domains
74
75 Revision 1.271 2005/01/15 00:56:41 ksekar
76 <rdar://problem/3954575> Unicast services don't disappear when logging
77 out of VPN
78
79 Revision 1.270 2005/01/14 18:34:22 ksekar
80 <rdar://problem/3954571> Services registered outside of firewall don't succeed after location change
81
82 Revision 1.269 2005/01/11 22:50:52 ksekar
83 Fixed constant naming (was using kLLQ_DefLease for update leases)
84
85 Revision 1.268 2004/12/22 22:25:47 ksekar
86 <rdar://problem/3734265> NATPMP: handle location changes
87
88 Revision 1.267 2004/12/22 00:13:49 ksekar
89 <rdar://problem/3873993> Change version, port, and polling interval for LLQ
90
91 Revision 1.266 2004/12/18 03:13:45 cheshire
92 <rdar://problem/3751638> kDNSServiceInterfaceIndexLocalOnly should return all local records
93
94 Revision 1.265 2004/12/17 23:37:45 cheshire
95 <rdar://problem/3485365> Guard against repeating wireless dissociation/re-association
96 (and other repetitive configuration changes)
97
98 Revision 1.264 2004/12/17 05:25:46 cheshire
99 <rdar://problem/3925163> Shorten DNS-SD queries to avoid NAT bugs
100
101 Revision 1.263 2004/12/16 20:40:25 cheshire
102 Fix compile warnings
103
104 Revision 1.262 2004/12/16 20:13:00 cheshire
105 <rdar://problem/3324626> Cache memory management improvements
106
107 Revision 1.261 2004/12/14 21:21:20 ksekar
108 <rdar://problem/3825979> NAT-PMP: Update response format to contain "Seconds Since Boot"
109
110 Revision 1.260 2004/12/12 23:51:42 ksekar
111 <rdar://problem/3845683> Wide-area registrations should fallback to using DHCP hostname as target
112
113 Revision 1.259 2004/12/11 20:55:29 ksekar
114 <rdar://problem/3916479> Clean up registration state machines
115
116 Revision 1.258 2004/12/10 20:48:32 cheshire
117 <rdar://problem/3705229> Need to pick final EDNS numbers for LLQ and GC
118
119 Revision 1.257 2004/12/10 02:09:23 cheshire
120 <rdar://problem/3898376> Modify default TTLs
121
122 Revision 1.256 2004/12/09 03:15:40 ksekar
123 <rdar://problem/3806610> use _legacy instead of _default to find "empty string" browse domains
124
125 Revision 1.255 2004/12/07 22:48:37 cheshire
126 Tidying
127
128 Revision 1.254 2004/12/07 21:26:04 ksekar
129 <rdar://problem/3908336> DNSServiceRegisterRecord() can crash on deregistration
130
131 Revision 1.253 2004/12/07 20:42:33 cheshire
132 Add explicit context parameter to mDNS_RemoveRecordFromService()
133
134 Revision 1.252 2004/12/07 03:02:12 ksekar
135 Fixed comments, grouped unicast-specific routines together
136
137 Revision 1.251 2004/12/06 21:15:22 ksekar
138 <rdar://problem/3884386> mDNSResponder crashed in CheckServiceRegistrations
139
140 Revision 1.250 2004/12/04 02:12:45 cheshire
141 <rdar://problem/3517236> mDNSResponder puts LargeCacheRecord on the stack
142
143 Revision 1.249 2004/12/03 05:18:33 ksekar
144 <rdar://problem/3810596> mDNSResponder needs to return more specific TSIG errors
145
146 Revision 1.248 2004/12/02 20:03:48 ksekar
147 <rdar://problem/3889647> Rendezvous still publishes wide-area domains even after switching to a local subnet
148
149 Revision 1.247 2004/12/01 20:57:19 ksekar
150 <rdar://problem/3873921> Wide Area Rendezvous must be split-DNS aware
151
152 Revision 1.246 2004/11/29 23:26:32 cheshire
153 Added NonZeroTime() function, which usually returns the value given, with the exception
154 that if the value given is zero, it returns one instead. For timer values where zero is
155 used to mean "not set", this can be used to ensure that setting them to the result of an
156 interval computation (e.g. "now+interval") does not inadvertently result in a zero value.
157
158 Revision 1.245 2004/11/25 01:28:09 cheshire
159 <rdar://problem/3557050> Need to implement random delay for 'QU' unicast replies (and set cache flush bit too)
160
161 Revision 1.244 2004/11/24 22:00:59 cheshire
162 Move definition of mDNSAddressIsAllDNSLinkGroup() from mDNSMacOSX.c to mDNSEmbeddedAPI.h
163
164 Revision 1.243 2004/11/23 22:43:53 cheshire
165 Tidy up code alignment
166
167 Revision 1.242 2004/11/23 03:39:46 cheshire
168 Let interface name/index mapping capability live directly in JNISupport.c,
169 instead of having to call through to the daemon via IPC to get this information.
170
171 Revision 1.241 2004/11/22 17:16:19 ksekar
172 <rdar://problem/3854298> Unicast services don't disappear when you disable all networking
173
174 Revision 1.240 2004/11/19 02:32:43 ksekar
175 Wide-Area Rendezvous Security: Add LLQ-ID to events
176
177 Revision 1.239 2004/11/15 20:09:23 ksekar
178 <rdar://problem/3719050> Wide Area support for Add/Remove record
179
180 Revision 1.238 2004/11/12 03:16:48 rpantos
181 rdar://problem/3809541 Add mDNSPlatformGetInterfaceByName, mDNSPlatformGetInterfaceName
182
183 Revision 1.237 2004/11/10 20:40:53 ksekar
184 <rdar://problem/3868216> LLQ mobility fragile on non-primary interface
185
186 Revision 1.236 2004/11/01 20:36:11 ksekar
187 <rdar://problem/3802395> mDNSResponder should not receive Keychain Notifications
188
189 Revision 1.235 2004/11/01 17:48:14 cheshire
190 Changed SOA serial number back to signed. RFC 1035 may describe it as "unsigned", but
191 it's wrong. The SOA serial is a modular counter, as explained in "DNS & BIND", page
192 137. Since C doesn't have a modular type, we used signed, C's closest approximation.
193
194 Revision 1.234 2004/10/29 21:59:02 ksekar
195 SOA serial should be a unsigned integer, as per RFC 1035
196
197 Revision 1.233 2004/10/28 03:24:41 cheshire
198 Rename m->CanReceiveUnicastOn as m->CanReceiveUnicastOn5353
199
200 Revision 1.232 2004/10/26 06:20:23 cheshire
201 Add mDNSAddressIsValidNonZero() macro
202
203 Revision 1.231 2004/10/26 06:11:41 cheshire
204 Add improved logging to aid in diagnosis of <rdar://problem/3842714> mDNSResponder crashed
205
206 Revision 1.230 2004/10/26 03:52:02 cheshire
207 Update checkin comments
208
209 Revision 1.229 2004/10/25 19:30:52 ksekar
210 <rdar://problem/3827956> Simplify dynamic host name structures
211
212 Revision 1.228 2004/10/23 01:16:00 cheshire
213 <rdar://problem/3851677> uDNS operations not always reliable on multi-homed hosts
214
215 Revision 1.227 2004/10/22 20:52:07 ksekar
216 <rdar://problem/3799260> Create NAT port mappings for Long Lived Queries
217
218 Revision 1.226 2004/10/20 01:50:40 cheshire
219 <rdar://problem/3844991> Cannot resolve non-local registrations using the mach API
220 Implemented ForceMCast mode for AuthRecords as well as for Questions
221
222 Revision 1.225 2004/10/19 21:33:17 cheshire
223 <rdar://problem/3844991> Cannot resolve non-local registrations using the mach API
224 Added flag 'kDNSServiceFlagsForceMulticast'. Passing through an interface id for a unicast name
225 doesn't force multicast unless you set this flag to indicate explicitly that this is what you want
226
227 Revision 1.224 2004/10/16 00:16:59 cheshire
228 <rdar://problem/3770558> Replace IP TTL 255 check with local subnet source address check
229
230 Revision 1.223 2004/10/15 23:00:17 ksekar
231 <rdar://problem/3799242> Need to update LLQs on location changes
232
233 Revision 1.222 2004/10/12 02:49:20 ksekar
234 <rdar://problem/3831228> Clean up LLQ sleep/wake, error handling
235
236 Revision 1.221 2004/10/10 06:57:15 cheshire
237 Change definition of "localdomain" to make code compile a little smaller
238
239 Revision 1.220 2004/10/06 01:44:19 cheshire
240 <rdar://problem/3813936> Resolving too quickly sometimes returns stale TXT record
241
242 Revision 1.219 2004/10/03 23:18:58 cheshire
243 Move address comparison macros from DNSCommon.h to mDNSEmbeddedAPI.h
244
245 Revision 1.218 2004/10/03 23:14:12 cheshire
246 Add "mDNSEthAddr" type and "zeroEthAddr" constant
247
248 Revision 1.217 2004/09/30 00:24:56 ksekar
249 <rdar://problem/3695802> Dynamically update default registration domains on config change
250
251 Revision 1.216 2004/09/27 23:24:32 cheshire
252 Fix typo: SOA refresh interval is supposed to be unsigned
253
254 Revision 1.215 2004/09/26 23:20:35 ksekar
255 <rdar://problem/3813108> Allow default registrations in multiple wide-area domains
256
257 Revision 1.214 2004/09/25 02:41:39 cheshire
258 <rdar://problem/3637266> Deliver near-pending "remove" events before new "add" events
259
260 Revision 1.213 2004/09/25 02:24:27 cheshire
261 Removed unused rr->UseCount
262
263 Revision 1.212 2004/09/24 20:57:39 cheshire
264 <rdar://problem/3680902> Eliminate inappropriate casts that cause misaligned-address errors
265
266 Revision 1.211 2004/09/24 20:33:22 cheshire
267 Remove unused DNSDigest_MD5 declaration
268
269 Revision 1.210 2004/09/23 20:21:07 cheshire
270 <rdar://problem/3426876> Refine "immediate answer burst; restarting exponential backoff sequence" logic
271 Associate a unique sequence number with each received packet, and only increment the count of recent answer
272 packets if the packet sequence number for this answer record is not one we've already seen and counted.
273
274 Revision 1.209 2004/09/23 20:14:39 cheshire
275 Rename "question->RecentAnswers" to "question->RecentAnswerPkts"
276
277 Revision 1.208 2004/09/23 00:50:53 cheshire
278 <rdar://problem/3419452> Don't send a (DE) if a service is unregistered after wake from sleep
279
280 Revision 1.207 2004/09/22 02:34:46 cheshire
281 Move definitions of default TTL times from mDNS.c to mDNSEmbeddedAPI.h
282
283 Revision 1.206 2004/09/22 00:41:59 cheshire
284 Move tcp connection status codes into the legal range allocated for mDNS use
285
286 Revision 1.205 2004/09/21 23:40:11 ksekar
287 <rdar://problem/3810349> mDNSResponder to return errors on NAT traversal failure
288
289 Revision 1.204 2004/09/21 23:29:50 cheshire
290 <rdar://problem/3680045> DNSServiceResolve should delay sending packets
291
292 Revision 1.203 2004/09/21 20:58:22 cheshire
293 Add ifname field to NetworkInterfaceInfo_struct
294
295 Revision 1.202 2004/09/17 00:46:34 cheshire
296 mDNS_TimeNow should take const mDNS parameter
297
298 Revision 1.201 2004/09/17 00:31:51 cheshire
299 For consistency with ipv6, renamed rdata field 'ip' to 'ipv4'
300
301 Revision 1.200 2004/09/17 00:19:10 cheshire
302 For consistency with AllDNSLinkGroupv6, rename AllDNSLinkGroup to AllDNSLinkGroupv4
303
304 Revision 1.199 2004/09/16 21:59:16 cheshire
305 For consistency with zerov6Addr, rename zeroIPAddr to zerov4Addr
306
307 Revision 1.198 2004/09/16 21:36:36 cheshire
308 <rdar://problem/3803162> Fix unsafe use of mDNSPlatformTimeNow()
309 Changes to add necessary locking calls around unicast DNS operations
310
311 Revision 1.197 2004/09/16 00:24:48 cheshire
312 <rdar://problem/3803162> Fix unsafe use of mDNSPlatformTimeNow()
313
314 Revision 1.196 2004/09/14 23:42:35 cheshire
315 <rdar://problem/3801296> Need to seed random number generator from platform-layer data
316
317 Revision 1.195 2004/09/14 23:27:46 cheshire
318 Fix compile errors
319
320 Revision 1.194 2004/09/10 00:49:57 cheshire
321 <rdar://problem/3787644> Add error code kDNSServiceErr_Firewall, for future use
322
323 Revision 1.193 2004/09/03 19:23:05 ksekar
324 <rdar://problem/3788460>: Need retransmission mechanism for wide-area service registrations
325
326 Revision 1.192 2004/09/02 03:48:47 cheshire
327 <rdar://problem/3709039> Disable targeted unicast query support by default
328 1. New flag kDNSServiceFlagsAllowRemoteQuery to indicate we want to allow remote queries for this record
329 2. New field AllowRemoteQuery in AuthRecord structure
330 3. uds_daemon.c sets AllowRemoteQuery if kDNSServiceFlagsAllowRemoteQuery is set
331 4. mDNS.c only answers remote queries if AllowRemoteQuery is set
332
333 Revision 1.191 2004/08/25 00:37:27 ksekar
334 <rdar://problem/3774635>: Cleanup DynDNS hostname registration code
335
336 Revision 1.190 2004/08/18 17:35:41 ksekar
337 <rdar://problem/3651443>: Feature #9586: Need support for Legacy NAT gateways
338
339 Revision 1.189 2004/08/14 03:22:41 cheshire
340 <rdar://problem/3762579> Dynamic DNS UI <-> mDNSResponder glue
341 Add GetUserSpecifiedDDNSName() routine
342 Convert ServiceRegDomain to domainname instead of C string
343 Replace mDNS_GenerateFQDN/mDNS_GenerateGlobalFQDN with mDNS_SetFQDNs
344
345 Revision 1.188 2004/08/13 23:46:58 cheshire
346 "asyncronous" -> "asynchronous"
347
348 Revision 1.187 2004/08/13 23:37:02 cheshire
349 Now that we do both uDNS and mDNS, global replace "uDNS_info.hostname" with
350 "uDNS_info.UnicastHostname" for clarity
351
352 Revision 1.186 2004/08/13 23:25:00 cheshire
353 Now that we do both uDNS and mDNS, global replace "m->hostname" with
354 "m->MulticastHostname" for clarity
355
356 Revision 1.185 2004/08/12 00:32:36 ksekar
357 <rdar://problem/3759567>: LLQ Refreshes never terminate if unanswered
358
359 Revision 1.184 2004/08/11 17:09:31 cheshire
360 Add comment clarifying the applicability of these APIs
361
362 Revision 1.183 2004/08/10 23:19:14 ksekar
363 <rdar://problem/3722542>: DNS Extension daemon for Wide Area Rendezvous
364 Moved routines/constants to allow extern access for garbage collection daemon
365
366 Revision 1.182 2004/07/30 17:40:06 ksekar
367 <rdar://problem/3739115>: TXT Record updates not available for wide-area services
368
369 Revision 1.181 2004/07/29 19:27:15 ksekar
370 NATPMP Support - minor fixes and cleanup
371
372 Revision 1.180 2004/07/29 02:03:35 ksekar
373 Delete unused #define and structure field
374
375 Revision 1.179 2004/07/26 22:49:30 ksekar
376 <rdar://problem/3651409>: Feature #9516: Need support for NATPMP in client
377
378 Revision 1.178 2004/07/13 21:24:24 rpantos
379 Fix for <rdar://problem/3701120>.
380
381 Revision 1.177 2004/06/05 00:04:26 cheshire
382 <rdar://problem/3668639>: wide-area domains should be returned in reg. domain enumeration
383
384 Revision 1.176 2004/06/04 08:58:29 ksekar
385 <rdar://problem/3668624>: Keychain integration for secure dynamic update
386
387 Revision 1.175 2004/06/04 00:15:06 cheshire
388 Move misplaced brackets
389
390 Revision 1.174 2004/06/03 23:30:16 cheshire
391 Remove extraneous blank lines and white space
392
393 Revision 1.173 2004/06/03 03:09:58 ksekar
394 <rdar://problem/3668626>: Garbage Collection for Dynamic Updates
395
396 Revision 1.172 2004/06/01 23:46:50 ksekar
397 <rdar://problem/3675149>: DynDNS: dynamically look up LLQ/Update ports
398
399 Revision 1.171 2004/05/28 23:42:37 ksekar
400 <rdar://problem/3258021>: Feature: DNS server->client notification on record changes (#7805)
401
402 Revision 1.170 2004/05/18 23:51:25 cheshire
403 Tidy up all checkin comments to use consistent "<rdar://problem/xxxxxxx>" format for bug numbers
404
405 Revision 1.169 2004/05/13 04:54:20 ksekar
406 Unified list copy/free code. Added symetric list for
407
408 Revision 1.168 2004/05/12 22:03:09 ksekar
409 Made GetSearchDomainList a true platform-layer call (declaration moved
410 from mDNSMacOSX.h to mDNSEmbeddedAPI.h), implemented to return "local"
411 only on non-OSX platforms. Changed call to return a copy of the list
412 to avoid shared memory issues. Added a routine to free the list.
413
414 Revision 1.167 2004/04/22 04:07:01 cheshire
415 Fix from Bob Bradley: Don't try to do inline functions on compilers that don't support it
416
417 Revision 1.166 2004/04/22 03:15:56 cheshire
418 Fix use of "struct __attribute__((__packed__))" so it only applies on GCC >= 2.9
419
420 Revision 1.165 2004/04/22 03:05:28 cheshire
421 kDNSClass_ANY should be kDNSQClass_ANY
422
423 Revision 1.164 2004/04/21 02:55:03 cheshire
424 Update comments describing 'InterfaceActive' field
425
426 Revision 1.163 2004/04/21 02:49:11 cheshire
427 To reduce future confusion, renamed 'TxAndRx' to 'McastTxRx'
428
429 Revision 1.162 2004/04/15 00:51:28 bradley
430 Minor tweaks for Windows and C++ builds. Added casts for signed/unsigned integers and 64-bit pointers.
431 Prefix some functions with mDNS to avoid conflicts. Disable benign warnings on Microsoft compilers.
432
433 Revision 1.161 2004/04/14 23:09:28 ksekar
434 Support for TSIG signed dynamic updates.
435
436 Revision 1.160 2004/04/09 17:40:26 cheshire
437 Remove unnecessary "Multicast" field -- it duplicates the semantics of the existing McastTxRx field
438
439 Revision 1.159 2004/04/09 16:37:15 cheshire
440 Suggestion from Bob Bradley:
441 Move NumCacheRecordsForInterfaceID() to DNSCommon.c so it's available to all platform layers
442
443 Revision 1.158 2004/04/02 19:38:33 cheshire
444 Update comment about typical RR TTLs
445
446 Revision 1.157 2004/04/02 19:35:53 cheshire
447 Add clarifying comments about legal mDNSInterfaceID values
448
449 Revision 1.156 2004/04/02 19:19:48 cheshire
450 Add code to do optional logging of multi-packet KA list time intervals
451
452 Revision 1.155 2004/03/24 00:29:45 ksekar
453 Make it safe to call StopQuery in a unicast question callback
454
455 Revision 1.154 2004/03/20 01:05:49 cheshire
456 Test __LP64__ and __ILP64__ to compile properly on a wider range of 64-bit architectures
457
458 Revision 1.153 2004/03/13 01:57:33 ksekar
459 <rdar://problem/3192546>: DynDNS: Dynamic update of service records
460
461 Revision 1.152 2004/03/09 02:27:16 cheshire
462 Remove erroneous underscore in 'packed_struct' (makes no difference now, but might in future)
463
464 Revision 1.151 2004/03/02 03:21:56 cheshire
465 <rdar://problem/3549576> Properly support "_services._dns-sd._udp" meta-queries
466
467 Revision 1.150 2004/02/21 02:06:24 cheshire
468 Can't use anonymous unions -- they're non-standard and don't work on all compilers
469
470 Revision 1.149 2004/02/06 23:04:19 ksekar
471 Basic Dynamic Update support via mDNS_Register (dissabled via
472 UNICAST_REGISTRATION #define)
473
474 Revision 1.148 2004/02/03 19:47:36 ksekar
475 Added an asynchronous state machine mechanism to uDNS.c, including
476 calls to find the parent zone for a domain name. Changes include code
477 in repository previously dissabled via "#if 0 incomplete". Codepath
478 is currently unused, and will be called to create update records, etc.
479
480 Revision 1.147 2004/02/03 18:57:35 cheshire
481 Update comment for "IsLocalDomain()"
482
483 Revision 1.146 2004/01/30 02:20:24 bradley
484 Map inline to __inline when building with Microsoft C compilers since they do not support C99 inline.
485
486 Revision 1.145 2004/01/29 02:59:17 ksekar
487 Unicast DNS: Changed from a resource record oriented question/response
488 matching to packet based matching. New callback architecture allows
489 collections of records in a response to be processed differently
490 depending on the nature of the request, and allows the same structure
491 to be used for internal and client-driven queries with different processing needs.
492
493 Revision 1.144 2004/01/28 20:20:45 ksekar
494 Unified ActiveQueries and ActiveInternalQueries lists, using a flag to
495 demux them. Check-in includes work-in-progress code, #ifdef'd out.
496
497 Revision 1.143 2004/01/28 03:41:00 cheshire
498 <rdar://problem/3541946>: Need ability to do targeted queries as well as multicast queries
499
500 Revision 1.142 2004/01/28 02:30:07 ksekar
501 Added default Search Domains to unicast browsing, controlled via
502 Networking sharing prefs pane. Stopped sending unicast messages on
503 every interface. Fixed unicast resolving via mach-port API.
504
505 Revision 1.141 2004/01/27 20:15:22 cheshire
506 <rdar://problem/3541288>: Time to prune obsolete code for listening on port 53
507
508 Revision 1.140 2004/01/24 23:37:08 cheshire
509 At Kiren's suggestion, made functions to convert mDNSOpaque16s to/from integer values
510
511 Revision 1.139 2004/01/24 08:46:26 bradley
512 Added InterfaceID<->Index platform interfaces since they are now used by all platforms for the DNS-SD APIs.
513
514 Revision 1.138 2004/01/24 04:59:15 cheshire
515 Fixes so that Posix/Linux, OS9, Windows, and VxWorks targets build again
516
517 Revision 1.137 2004/01/24 03:40:56 cheshire
518 Move mDNSAddrIsDNSMulticast() from DNSCommon.h to mDNSEmbeddedAPI.h so clients can use it
519
520 Revision 1.136 2004/01/24 03:38:27 cheshire
521 Fix minor syntactic error: Headers should use "extern" declarations, not "mDNSexport"
522
523 Revision 1.135 2004/01/23 23:23:15 ksekar
524 Added TCP support for truncated unicast messages.
525
526 Revision 1.134 2004/01/22 03:54:11 cheshire
527 Create special meta-interface 'mDNSInterface_ForceMCast' (-2),
528 which means "do this query via multicast, even if it's apparently a unicast domain"
529
530 Revision 1.133 2004/01/22 03:48:41 cheshire
531 Make sure uDNS client doesn't accidentally use query ID zero
532
533 Revision 1.132 2004/01/22 03:43:08 cheshire
534 Export constants like mDNSInterface_LocalOnly so that the client layers can use them
535
536 Revision 1.131 2004/01/21 21:53:18 cheshire
537 <rdar://problem/3448144>: Don't try to receive unicast responses if we're not the first to bind to the UDP port
538
539 Revision 1.130 2003/12/14 05:05:29 cheshire
540 Add comments explaining mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize
541
542 Revision 1.129 2003/12/13 03:05:27 ksekar
543 <rdar://problem/3192548>: DynDNS: Unicast query of service records
544
545 Revision 1.128 2003/12/01 21:44:23 cheshire
546 Add mStatus_BadInterfaceErr = -65552 for consistency with dns_sd.h
547
548 Revision 1.127 2003/12/01 18:26:37 cheshire
549 Also pack the OpaqueXX union types. Otherwise, on some systems, mDNSOpaque16 is four bytes!
550
551 Revision 1.126 2003/12/01 18:23:48 cheshire
552 <rdar://problem/3464646>: Scalar size problem in mDNS code on some 64-bit architectures
553
554 Revision 1.125 2003/11/22 00:18:27 cheshire
555 Add compile-time asserts to verify correct sizes of mDNSu32, mDNSOpaque16, etc.
556
557 Revision 1.124 2003/11/20 22:59:54 cheshire
558 Changed runtime checks in mDNS.c to be compile-time checks in mDNSEmbeddedAPI.h
559 Thanks to Bob Bradley for suggesting the ingenious compiler trick to make this work.
560
561 Revision 1.123 2003/11/20 22:53:01 cheshire
562 Add comment about MAX_ESCAPED_DOMAIN_LABEL
563
564 Revision 1.122 2003/11/20 20:49:53 cheshire
565 Another fix from HP: Use packedstruct macro to ensure proper packing for on-the-wire packet structures
566
567 Revision 1.121 2003/11/20 05:01:38 cheshire
568 Update comments; add explanation of Advertise/DontAdvertiseLocalAddresses
569
570 Revision 1.120 2003/11/14 20:59:08 cheshire
571 Clients can't use AssignDomainName macro because mDNSPlatformMemCopy is defined in mDNSPlatformFunctions.h.
572 Best solution is just to combine mDNSEmbeddedAPI.h and mDNSPlatformFunctions.h into a single file.
573
574 Revision 1.119 2003/11/14 19:47:52 cheshire
575 Define symbol MAX_ESCAPED_DOMAIN_NAME to indicate recommended buffer size for ConvertDomainNameToCString
576
577 Revision 1.118 2003/11/14 19:18:34 cheshire
578 Move AssignDomainName macro to mDNSEmbeddedAPI.h to that client layers can use it too
579
580 Revision 1.117 2003/11/08 23:32:24 cheshire
581 Gave name to anonymous struct, to avoid errors on certain compilers.
582 (Thanks to ramaprasad.kr@hp.com for reporting this.)
583
584 Revision 1.116 2003/11/07 03:32:56 cheshire
585 <rdar://problem/3472153> mDNSResponder delivers answers in inconsistent order
586 This is the real fix. Checkin 1.312 was overly simplistic; Calling GetFreeCacheRR() can sometimes
587 purge records from the cache, causing tail pointer *rp to be stale on return. The correct fix is
588 to maintain a system-wide tail pointer for each cache slot, and then if neccesary GetFreeCacheRR()
589 can update this pointer, so that mDNSCoreReceiveResponse() appends records in the right place.
590
591 Revision 1.115 2003/09/23 00:53:54 cheshire
592 NumFailedProbes should be unsigned
593
594 Revision 1.114 2003/08/29 19:44:15 cheshire
595 <rdar://problem/3400967> Traffic reduction: Eliminate synchronized QUs when a new service appears
596 1. Use m->RandomQueryDelay to impose a random delay in the range 0-500ms on queries
597 that already have at least one unique answer in the cache
598 2. For these queries, go straight to QM, skipping QU
599
600 Revision 1.113 2003/08/21 19:31:58 cheshire
601 Cosmetic: Swap order of fields
602
603 Revision 1.112 2003/08/21 19:27:36 cheshire
604 <rdar://problem/3387878> Traffic reduction: No need to announce record for longer than TTL
605
606 Revision 1.111 2003/08/21 02:21:50 cheshire
607 <rdar://problem/3386473> Efficiency: Reduce repeated queries
608
609 Revision 1.110 2003/08/20 23:39:31 cheshire
610 <rdar://problem/3344098> Review syslog messages, and remove as appropriate
611
612 Revision 1.109 2003/08/19 22:24:10 cheshire
613 Comment change
614
615 Revision 1.108 2003/08/19 22:20:00 cheshire
616 <rdar://problem/3376721> Don't use IPv6 on interfaces that have a routable IPv4 address configured
617 More minor refinements
618
619 Revision 1.107 2003/08/19 06:48:25 cheshire
620 <rdar://problem/3376552> Guard against excessive record updates
621 Each record starts with 10 UpdateCredits.
622 Every update consumes one UpdateCredit.
623 UpdateCredits are replenished at a rate of one one per minute, up to a maximum of 10.
624 As the number of UpdateCredits declines, the number of announcements is similarly scaled back.
625 When fewer than 5 UpdateCredits remain, the first announcement is also delayed by an increasing amount.
626
627 Revision 1.106 2003/08/19 04:49:28 cheshire
628 <rdar://problem/3368159> Interaction between v4, v6 and dual-stack hosts not working quite right
629 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.
630 2. When we see the first v4 (or first v6) member of a group, we re-trigger questions and probes on that interface.
631 3. When we see the last v4 (or v6) member of a group go away, we revalidate all the records received on that interface.
632
633 Revision 1.105 2003/08/19 02:33:37 cheshire
634 Update comments
635
636 Revision 1.104 2003/08/19 02:31:11 cheshire
637 <rdar://problem/3378386> mDNSResponder overenthusiastic with final expiration queries
638 Final expiration queries now only mark the question for sending on the particular interface
639 pertaining to the record that's expiring.
640
641 Revision 1.103 2003/08/18 19:05:44 cheshire
642 <rdar://problem/3382423> UpdateRecord not working right
643 Added "newrdlength" field to hold new length of updated rdata
644
645 Revision 1.102 2003/08/16 03:39:00 cheshire
646 <rdar://problem/3338440> InterfaceID -1 indicates "local only"
647
648 Revision 1.101 2003/08/15 20:16:02 cheshire
649 <rdar://problem/3366590> mDNSResponder takes too much RPRVT
650 We want to avoid touching the rdata pages, so we don't page them in.
651 1. RDLength was stored with the rdata, which meant touching the page just to find the length.
652 Moved this from the RData to the ResourceRecord object.
653 2. To avoid unnecessarily touching the rdata just to compare it,
654 compute a hash of the rdata and store the hash in the ResourceRecord object.
655
656 Revision 1.100 2003/08/14 19:29:04 cheshire
657 <rdar://problem/3378473> Include cache records in SIGINFO output
658 Moved declarations of DNSTypeName() and GetRRDisplayString to mDNSEmbeddedAPI.h so daemon.c can use them
659
660 Revision 1.99 2003/08/14 02:17:05 cheshire
661 <rdar://problem/3375491> Split generic ResourceRecord type into two separate types: AuthRecord and CacheRecord
662
663 Revision 1.98 2003/08/12 19:56:23 cheshire
664 Update to APSL 2.0
665
666 Revision 1.97 2003/08/12 14:59:27 cheshire
667 <rdar://problem/3374490> Rate-limiting blocks some legitimate responses
668 When setting LastMCTime also record LastMCInterface. When checking LastMCTime to determine
669 whether to suppress the response, also check LastMCInterface to see if it matches.
670
671 Revision 1.96 2003/08/12 13:57:04 cheshire
672 <rdar://problem/3323817> Improve cache performance
673 Changed the number of hash table slots from 37 to 499
674
675 Revision 1.95 2003/08/09 00:55:02 cheshire
676 <rdar://problem/3366553> mDNSResponder is taking 20-30% of the CPU
677 Don't scan the whole cache after every packet.
678
679 Revision 1.94 2003/08/09 00:35:29 cheshire
680
681 Revision 1.93 2003/08/08 18:55:48 cheshire
682 <rdar://problem/3370365> Guard against time going backwards
683
684 Revision 1.92 2003/08/08 18:36:04 cheshire
685 <rdar://problem/3344154> Only need to revalidate on interface removal on platforms that have the PhantomInterfaces bug
686
687 Revision 1.91 2003/08/06 21:33:39 cheshire
688 Fix compiler warnings on PocketPC 2003 (Windows CE)
689
690 Revision 1.90 2003/08/06 20:30:17 cheshire
691 Add structure definition for rdataMX (not currently used, but good to have it for completeness)
692
693 Revision 1.89 2003/08/06 18:58:19 cheshire
694 Update comments
695
696 Revision 1.88 2003/07/24 23:45:44 cheshire
697 To eliminate compiler warnings, changed definition of mDNSBool from
698 "unsigned char" to "int", since "int" is in fact truly the type that C uses
699 for the result of comparison operators (a<b) and logical operators (a||b)
700
701 Revision 1.87 2003/07/22 23:57:20 cheshire
702 Move platform-layer function prototypes from mDNSEmbeddedAPI.h to mDNSPlatformFunctions.h where they belong
703
704 Revision 1.86 2003/07/20 03:52:02 ksekar
705 <rdar://problem/3320722>: Feature: New DNS-SD APIs (#7875) (mDNSResponder component)
706 Added error type for incompatibility between daemon and client versions
707
708 Revision 1.85 2003/07/19 03:23:13 cheshire
709 <rdar://problem/2986147> mDNSResponder needs to receive and cache larger records
710
711 Revision 1.84 2003/07/18 23:52:12 cheshire
712 To improve consistency of field naming, global search-and-replace:
713 NextProbeTime -> NextScheduledProbe
714 NextResponseTime -> NextScheduledResponse
715
716 Revision 1.83 2003/07/18 00:29:59 cheshire
717 <rdar://problem/3268878> Remove mDNSResponder version from packet header and use HINFO record instead
718
719 Revision 1.82 2003/07/17 17:35:04 cheshire
720 <rdar://problem/3325583> Rate-limit responses, to guard against packet flooding
721
722 Revision 1.81 2003/07/16 05:01:36 cheshire
723 Add fields 'LargeAnswers' and 'ExpectUnicastResponse' in preparation for
724 <rdar://problem/3315761> Need to implement "unicast response" request, using top bit of qclass
725
726 Revision 1.80 2003/07/15 01:55:12 cheshire
727 <rdar://problem/3315777> Need to implement service registration with subtypes
728
729 Revision 1.79 2003/07/13 02:28:00 cheshire
730 <rdar://problem/3325166> SendResponses didn't all its responses
731 Delete all references to RRInterfaceActive -- it's now superfluous
732
733 Revision 1.78 2003/07/13 01:47:53 cheshire
734 Fix one error and one warning in the Windows build
735
736 Revision 1.77 2003/07/11 01:32:38 cheshire
737 Syntactic cleanup (no change to funcationality): Now that we only have one host name,
738 rename field "hostname1" to "hostname", and field "RR_A1" to "RR_A".
739
740 Revision 1.76 2003/07/11 01:28:00 cheshire
741 <rdar://problem/3161289> No more local.arpa
742
743 Revision 1.75 2003/07/02 21:19:45 cheshire
744 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
745
746 Revision 1.74 2003/07/02 02:41:23 cheshire
747 <rdar://problem/2986146> mDNSResponder needs to start with a smaller cache and then grow it as needed
748
749 Revision 1.73 2003/06/10 04:24:39 cheshire
750 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
751 Some additional refinements:
752 Don't try to do this for unicast-response queries
753 better tracking of Qs and KAs in multi-packet KA lists
754
755 Revision 1.72 2003/06/10 01:46:27 cheshire
756 Add better comments explaining how these data structures are intended to be used from the client layer
757
758 Revision 1.71 2003/06/07 06:45:05 cheshire
759 <rdar://problem/3283666> No need for multiple machines to all be sending the same queries
760
761 Revision 1.70 2003/06/07 04:50:53 cheshire
762 <rdar://problem/3283637> React when we observe other people query unsuccessfully for a record that's in our cache
763
764 Revision 1.69 2003/06/07 04:22:17 cheshire
765 Add MsgBuffer for error log and debug messages
766
767 Revision 1.68 2003/06/07 01:46:38 cheshire
768 <rdar://problem/3283540> When query produces zero results, call mDNS_Reconfirm() on any antecedent records
769
770 Revision 1.67 2003/06/07 01:22:14 cheshire
771 <rdar://problem/3283516> mDNSResponder needs an mDNS_Reconfirm() function
772
773 Revision 1.66 2003/06/07 00:59:43 cheshire
774 <rdar://problem/3283454> Need some randomness to spread queries on the network
775
776 Revision 1.65 2003/06/06 21:41:11 cheshire
777 For consistency, mDNS_StopQuery() should return an mStatus result, just like all the other mDNSCore routines
778
779 Revision 1.64 2003/06/06 21:38:55 cheshire
780 Renamed 'NewData' as 'FreshData' (The data may not be new data, just a refresh of data that we
781 already had in our cache. This refreshes our TTL on the data, but the data itself stays the same.)
782
783 Revision 1.63 2003/06/06 17:20:14 cheshire
784 For clarity, rename question fields name/rrtype/rrclass as qname/qtype/qclass
785 (Global search-and-replace; no functional change to code execution.)
786
787 Revision 1.62 2003/06/04 01:25:33 cheshire
788 <rdar://problem/3274950> Cannot perform multi-packet known-answer suppression messages
789 Display time interval between first and subsequent queries
790
791 Revision 1.61 2003/06/03 05:02:16 cheshire
792 <rdar://problem/3277080> Duplicate registrations not handled as efficiently as they should be
793
794 Revision 1.60 2003/05/31 00:09:49 cheshire
795 <rdar://problem/3274862> Add ability to discover what services are on a network
796
797 Revision 1.59 2003/05/29 06:11:35 cheshire
798 <rdar://problem/3272214>: Report if there appear to be too many "Resolve" callbacks
799
800 Revision 1.58 2003/05/29 05:48:06 cheshire
801 Minor fix for when generating printf warnings: mDNS_snprintf arguments are now 3,4
802
803 Revision 1.57 2003/05/26 03:21:27 cheshire
804 Tidy up address structure naming:
805 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
806 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
807 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
808
809 Revision 1.56 2003/05/26 03:01:27 cheshire
810 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
811
812 Revision 1.55 2003/05/26 00:47:30 cheshire
813 Comment clarification
814
815 Revision 1.54 2003/05/24 16:39:48 cheshire
816 <rdar://problem/3268631> SendResponses also needs to handle multihoming better
817
818 Revision 1.53 2003/05/23 02:15:37 cheshire
819 Fixed misleading use of the term "duplicate suppression" where it should have
820 said "known answer suppression". (Duplicate answer suppression is something
821 different, and duplicate question suppression is yet another thing, so the use
822 of the completely vague term "duplicate suppression" was particularly bad.)
823
824 Revision 1.52 2003/05/22 02:29:22 cheshire
825 <rdar://problem/2984918> SendQueries needs to handle multihoming better
826 Complete rewrite of SendQueries. Works much better now :-)
827
828 Revision 1.51 2003/05/21 20:14:55 cheshire
829 Fix comments and warnings
830
831 Revision 1.50 2003/05/14 07:08:36 cheshire
832 <rdar://problem/3159272> mDNSResponder should be smarter about reconfigurations
833 Previously, when there was any network configuration change, mDNSResponder
834 would tear down the entire list of active interfaces and start again.
835 That was very disruptive, and caused the entire cache to be flushed,
836 and caused lots of extra network traffic. Now it only removes interfaces
837 that have really gone, and only adds new ones that weren't there before.
838
839 Revision 1.49 2003/05/07 01:49:36 cheshire
840 Remove "const" in ConstructServiceName prototype
841
842 Revision 1.48 2003/05/07 00:18:44 cheshire
843 Fix typo: "kDNSQClass_Mask" should be "kDNSClass_Mask"
844
845 Revision 1.47 2003/05/06 00:00:46 cheshire
846 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
847
848 Revision 1.46 2003/04/30 20:39:09 cheshire
849 Add comment
850
851 Revision 1.45 2003/04/29 00:40:50 cheshire
852 Fix compiler warnings
853
854 Revision 1.44 2003/04/26 02:41:56 cheshire
855 <rdar://problem/3241281> Change timenow from a local variable to a structure member
856
857 Revision 1.43 2003/04/25 01:45:56 cheshire
858 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
859
860 Revision 1.42 2003/04/15 20:58:31 jgraessl
861
862 <rdar://problem/3229014> Added a hash to lookup records in the cache.
863
864 Revision 1.41 2003/04/15 18:09:13 jgraessl
865
866 <rdar://problem/3228892>
867 Reviewed by: Stuart Cheshire
868 Added code to keep track of when the next cache item will expire so we can
869 call TidyRRCache only when necessary.
870
871 Revision 1.40 2003/03/29 01:55:19 cheshire
872 <rdar://problem/3212360> mDNSResponder sometimes suffers false self-conflicts when it sees its own packets
873 Solution: Major cleanup of packet timing and conflict handling rules
874
875 Revision 1.39 2003/03/27 03:30:55 cheshire
876 <rdar://problem/3210018> Name conflicts not handled properly, resulting in memory corruption, and eventual crash
877 Problem was that HostNameCallback() was calling mDNS_DeregisterInterface(), which is not safe in a callback
878 Fixes:
879 1. Make mDNS_DeregisterInterface() safe to call from a callback
880 2. Make HostNameCallback() use mDNS_DeadvertiseInterface() instead
881 (it never really needed to deregister the interface at all)
882
883 Revision 1.38 2003/03/15 04:40:36 cheshire
884 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
885
886 Revision 1.37 2003/03/14 21:34:11 cheshire
887 <rdar://problem/3176950> Can't setup and print to Lexmark PS printers via Airport Extreme
888 Increase size of cache rdata from 512 to 768
889
890 Revision 1.36 2003/03/05 03:38:35 cheshire
891 <rdar://problem/3185731> Bogus error message in console: died or deallocated, but no record of client can be found!
892 Fixed by leaving client in list after conflict, until client explicitly deallocates
893
894 Revision 1.35 2003/02/21 02:47:54 cheshire
895 <rdar://problem/3099194> mDNSResponder needs performance improvements
896 Several places in the code were calling CacheRRActive(), which searched the entire
897 question list every time, to see if this cache resource record answers any question.
898 Instead, we now have a field "CRActiveQuestion" in the resource record structure
899
900 Revision 1.34 2003/02/21 01:54:08 cheshire
901 <rdar://problem/3099194> mDNSResponder needs performance improvements
902 Switched to using new "mDNS_Execute" model (see "Implementer Notes.txt")
903
904 Revision 1.33 2003/02/20 06:48:32 cheshire
905 <rdar://problem/3169535> Xserve RAID needs to do interface-specific registrations
906 Reviewed by: Josh Graessley, Bob Bradley
907
908 Revision 1.32 2003/01/31 03:35:59 cheshire
909 <rdar://problem/3147097> mDNSResponder sometimes fails to find the correct results
910 When there were *two* active questions in the list, they were incorrectly
911 finding *each other* and *both* being marked as duplicates of another question
912
913 Revision 1.31 2003/01/29 02:46:37 cheshire
914 Fix for IPv6:
915 A physical interface is identified solely by its InterfaceID (not by IP and type).
916 On a given InterfaceID, mDNSCore may send both v4 and v6 multicasts.
917 In cases where the requested outbound protocol (v4 or v6) is not supported on
918 that InterfaceID, the platform support layer should simply discard that packet.
919
920 Revision 1.30 2003/01/29 01:47:08 cheshire
921 Rename 'Active' to 'CRActive' or 'InterfaceActive' for improved clarity
922
923 Revision 1.29 2003/01/28 05:23:43 cheshire
924 <rdar://problem/3147097> mDNSResponder sometimes fails to find the correct results
925 Add 'Active' flag for interfaces
926
927 Revision 1.28 2003/01/28 01:35:56 cheshire
928 Revise comment about ThisQInterval to reflect new semantics
929
930 Revision 1.27 2003/01/13 23:49:42 jgraessl
931 Merged changes for the following fixes in to top of tree:
932 <rdar://problem/3086540> computer name changes not handled properly
933 <rdar://problem/3124348> service name changes are not properly handled
934 <rdar://problem/3124352> announcements sent in pairs, failing chattiness test
935
936 Revision 1.26 2002/12/23 22:13:28 jgraessl
937
938 Reviewed by: Stuart Cheshire
939 Initial IPv6 support for mDNSResponder.
940
941 Revision 1.25 2002/09/21 20:44:49 zarzycki
942 Added APSL info
943
944 Revision 1.24 2002/09/19 23:47:35 cheshire
945 Added mDNS_RegisterNoSuchService() function for assertion of non-existence
946 of a particular named service
947
948 Revision 1.23 2002/09/19 21:25:34 cheshire
949 mDNS_snprintf() doesn't need to be in a separate file
950
951 Revision 1.22 2002/09/19 04:20:43 cheshire
952 Remove high-ascii characters that confuse some systems
953
954 Revision 1.21 2002/09/17 01:06:35 cheshire
955 Change mDNS_AdvertiseLocalAddresses to be a parameter to mDNS_Init()
956
957 Revision 1.20 2002/09/16 18:41:41 cheshire
958 Merge in license terms from Quinn's copy, in preparation for Darwin release
959
960 */
961
962 #ifndef __mDNSClientAPI_h
963 #define __mDNSClientAPI_h
964
965 #include <stdarg.h> // stdarg.h is required for for va_list support for the mDNS_vsnprintf declaration
966 #include "mDNSDebug.h"
967
968 #ifdef __cplusplus
969 extern "C" {
970 #endif
971
972 // ***************************************************************************
973 // Function scope indicators
974
975 // If you see "mDNSlocal" before a function name in a C file, it means the function is not callable outside this file
976 #ifndef mDNSlocal
977 #define mDNSlocal static
978 #endif
979 // If you see "mDNSexport" before a symbol in a C file, it means the symbol is exported for use by clients
980 // For every "mDNSexport" in a C file, there needs to be a corresponding "extern" declaration in some header file
981 // (When a C file #includes a header file, the "extern" declarations tell the compiler:
982 // "This symbol exists -- but not necessarily in this C file.")
983 #ifndef mDNSexport
984 #define mDNSexport
985 #endif
986
987 // ***************************************************************************
988 // Structure packing macro
989
990 // If we're not using GNUC, it's not fatal.
991 // Most compilers naturally pack the on-the-wire structures correctly anyway, so a plain "struct" is usually fine.
992 // In the event that structures are not packed correctly, mDNS_Init() will detect this and report an error, so the
993 // developer will know what's wrong, and can investigate what needs to be done on that compiler to provide proper packing.
994 #ifndef packedstruct
995 #if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
996 #define packedstruct struct __attribute__((__packed__))
997 #define packedunion union __attribute__((__packed__))
998 #else
999 #define packedstruct struct
1000 #define packedunion union
1001 #endif
1002 #endif
1003
1004 // ***************************************************************************
1005 #if 0
1006 #pragma mark - DNS Resource Record class and type constants
1007 #endif
1008
1009 typedef enum // From RFC 1035
1010 {
1011 kDNSClass_IN = 1, // Internet
1012 kDNSClass_CS = 2, // CSNET
1013 kDNSClass_CH = 3, // CHAOS
1014 kDNSClass_HS = 4, // Hesiod
1015 kDNSClass_NONE = 254, // Used in DNS UPDATE [RFC 2136]
1016
1017 kDNSClass_Mask = 0x7FFF,// Multicast DNS uses the bottom 15 bits to identify the record class...
1018 kDNSClass_UniqueRRSet = 0x8000,// ... and the top bit indicates that all other cached records are now invalid
1019
1020 kDNSQClass_ANY = 255, // Not a DNS class, but a DNS query class, meaning "all classes"
1021 kDNSQClass_UnicastResponse = 0x8000 // Top bit set in a question means "unicast response acceptable"
1022 } DNS_ClassValues;
1023
1024 typedef enum // From RFC 1035
1025 {
1026 kDNSType_A = 1, // 1 Address
1027 kDNSType_NS, // 2 Name Server
1028 kDNSType_MD, // 3 Mail Destination
1029 kDNSType_MF, // 4 Mail Forwarder
1030 kDNSType_CNAME, // 5 Canonical Name
1031 kDNSType_SOA, // 6 Start of Authority
1032 kDNSType_MB, // 7 Mailbox
1033 kDNSType_MG, // 8 Mail Group
1034 kDNSType_MR, // 9 Mail Rename
1035 kDNSType_NULL, // 10 NULL RR
1036 kDNSType_WKS, // 11 Well-known-service
1037 kDNSType_PTR, // 12 Domain name pointer
1038 kDNSType_HINFO, // 13 Host information
1039 kDNSType_MINFO, // 14 Mailbox information
1040 kDNSType_MX, // 15 Mail Exchanger
1041 kDNSType_TXT, // 16 Arbitrary text string
1042
1043 kDNSType_AAAA = 28, // 28 IPv6 address
1044 kDNSType_SRV = 33, // 33 Service record
1045 kDNSType_OPT = 41, // EDNS0 OPT record
1046 kDNSType_TSIG = 250, // 250 Transaction Signature
1047
1048 kDNSQType_ANY = 255 // Not a DNS type, but a DNS query type, meaning "all types"
1049 } DNS_TypeValues;
1050
1051 // ***************************************************************************
1052 #if 0
1053 #pragma mark - Simple types
1054 #endif
1055
1056 // mDNS defines its own names for these common types to simplify portability across
1057 // multiple platforms that may each have their own (different) names for these types.
1058 typedef int mDNSBool;
1059 typedef signed char mDNSs8;
1060 typedef unsigned char mDNSu8;
1061 typedef signed short mDNSs16;
1062 typedef unsigned short mDNSu16;
1063
1064 // <http://gcc.gnu.org/onlinedocs/gcc-3.3.3/cpp/Common-Predefined-Macros.html> says
1065 // __LP64__ _LP64
1066 // These macros are defined, with value 1, if (and only if) the compilation is
1067 // for a target where long int and pointer both use 64-bits and int uses 32-bit.
1068 // <http://www.intel.com/software/products/compilers/clin/docs/ug/lin1077.htm> says
1069 // Macro Name __LP64__ Value 1
1070 // A quick Google search for "defined(__LP64__)" OR "#ifdef __LP64__" gives 2590 hits and
1071 // a search for "#if __LP64__" gives only 12, so I think we'll go with the majority and use defined()
1072 #if defined(_LP64) || defined(__LP64__)
1073 typedef signed int mDNSs32;
1074 typedef unsigned int mDNSu32;
1075 #elif defined(_ILP64) || defined(__ILP64__)
1076 typedef signed int32 mDNSs32;
1077 typedef unsigned int32 mDNSu32;
1078 #else
1079 typedef signed long mDNSs32;
1080 typedef unsigned long mDNSu32;
1081 #endif
1082
1083 // To enforce useful type checking, we make mDNSInterfaceID be a pointer to a dummy struct
1084 // This way, mDNSInterfaceIDs can be assigned, and compared with each other, but not with other types
1085 // Declaring the type to be the typical generic "void *" would lack this type checking
1086 typedef struct mDNSInterfaceID_dummystruct { void *dummy; } *mDNSInterfaceID;
1087
1088 // These types are for opaque two- and four-byte identifiers.
1089 // The "NotAnInteger" fields of the unions allow the value to be conveniently passed around in a
1090 // register for the sake of efficiency, and compared for equality or inequality, but don't forget --
1091 // just because it is in a register doesn't mean it is an integer. Operations like greater than,
1092 // less than, add, multiply, increment, decrement, etc., are undefined for opaque identifiers,
1093 // and if you make the mistake of trying to do those using the NotAnInteger field, then you'll
1094 // find you get code that doesn't work consistently on big-endian and little-endian machines.
1095 typedef packedunion { mDNSu8 b[ 2]; mDNSu16 NotAnInteger; } mDNSOpaque16;
1096 typedef packedunion { mDNSu8 b[ 4]; mDNSu32 NotAnInteger; } mDNSOpaque32;
1097 typedef packedunion { mDNSu8 b[ 6]; mDNSu16 w[3]; mDNSu32 l[1]; } mDNSOpaque48;
1098 typedef packedunion { mDNSu8 b[16]; mDNSu16 w[8]; mDNSu32 l[4]; } mDNSOpaque128;
1099
1100 typedef mDNSOpaque16 mDNSIPPort; // An IP port is a two-byte opaque identifier (not an integer)
1101 typedef mDNSOpaque32 mDNSv4Addr; // An IP address is a four-byte opaque identifier (not an integer)
1102 typedef mDNSOpaque128 mDNSv6Addr; // An IPv6 address is a 16-byte opaque identifier (not an integer)
1103 typedef mDNSOpaque48 mDNSEthAddr; // An Ethernet address is a six-byte opaque identifier (not an integer)
1104
1105 enum
1106 {
1107 mDNSAddrType_None = 0,
1108 mDNSAddrType_IPv4 = 4,
1109 mDNSAddrType_IPv6 = 6,
1110 mDNSAddrType_Unknown = ~0 // Special marker value used in known answer list recording
1111 };
1112
1113 typedef struct
1114 {
1115 mDNSs32 type;
1116 union { mDNSv6Addr v6; mDNSv4Addr v4; } ip;
1117 } mDNSAddr;
1118
1119 enum { mDNSfalse = 0, mDNStrue = 1 };
1120
1121 #define mDNSNULL 0L
1122
1123 enum
1124 {
1125 mStatus_Waiting = 1,
1126 mStatus_NoError = 0,
1127
1128 // mDNS return values are in the range FFFE FF00 (-65792) to FFFE FFFF (-65537)
1129 // The top end of the range (FFFE FFFF) is used for error codes;
1130 // the bottom end of the range (FFFE FF00) is used for non-error values;
1131
1132 // Error codes:
1133 mStatus_UnknownErr = -65537, // First value: 0xFFFE FFFF
1134 mStatus_NoSuchNameErr = -65538,
1135 mStatus_NoMemoryErr = -65539,
1136 mStatus_BadParamErr = -65540,
1137 mStatus_BadReferenceErr = -65541,
1138 mStatus_BadStateErr = -65542,
1139 mStatus_BadFlagsErr = -65543,
1140 mStatus_UnsupportedErr = -65544,
1141 mStatus_NotInitializedErr = -65545,
1142 mStatus_NoCache = -65546,
1143 mStatus_AlreadyRegistered = -65547,
1144 mStatus_NameConflict = -65548,
1145 mStatus_Invalid = -65549,
1146 mStatus_Firewall = -65550,
1147 mStatus_Incompatible = -65551,
1148 mStatus_BadInterfaceErr = -65552,
1149 mStatus_Refused = -65553,
1150 mStatus_NoSuchRecord = -65554,
1151 mStatus_NoAuth = -65555,
1152 mStatus_NoSuchKey = -65556,
1153 mStatus_NATTraversal = -65557,
1154 mStatus_DoubleNAT = -65558,
1155 mStatus_BadTime = -65559,
1156 mStatus_BadSig = -65560, // while we define this per RFC 2845, BIND 9 returns Refused for bad/missing signatures
1157 mStatus_BadKey = -65561,
1158
1159 // -65562 to -65786 currently unused; available for allocation
1160
1161 // tcp connection status
1162 mStatus_ConnPending = -65787,
1163 mStatus_ConnFailed = -65788,
1164 mStatus_ConnEstablished = -65789,
1165
1166 // Non-error values:
1167 mStatus_GrowCache = -65790,
1168 mStatus_ConfigChanged = -65791,
1169 mStatus_MemFree = -65792 // Last value: 0xFFFE FF00
1170
1171 // mStatus_MemFree is the last legal mDNS error code, at the end of the range allocated for mDNS
1172 };
1173
1174 typedef mDNSs32 mStatus;
1175
1176 // RFC 1034/1035 specify that a domain label consists of a length byte plus up to 63 characters
1177 #define MAX_DOMAIN_LABEL 63
1178 typedef struct { mDNSu8 c[ 64]; } domainlabel; // One label: length byte and up to 63 characters
1179
1180 // RFC 1034/1035 specify that a domain name, including length bytes, data bytes, and terminating zero, may be up to 255 bytes long
1181 #define MAX_DOMAIN_NAME 255
1182 typedef struct { mDNSu8 c[256]; } domainname; // Up to 255 bytes of length-prefixed domainlabels
1183
1184 typedef struct { mDNSu8 c[256]; } UTF8str255; // Null-terminated C string
1185
1186 // The longest legal textual form of a DNS name is 1005 bytes, including the C-string terminating NULL at the end.
1187 // Explanation:
1188 // When a native domainname object is converted to printable textual form using ConvertDomainNameToCString(),
1189 // non-printing characters are represented in the conventional DNS way, as '\ddd', where ddd is a three-digit decimal number.
1190 // The longest legal domain name is 255 bytes, in the form of four labels as shown below:
1191 // Length byte, 63 data bytes, length byte, 63 data bytes, length byte, 63 data bytes, length byte, 61 data bytes, zero byte.
1192 // Each label is encoded textually as characters followed by a trailing dot.
1193 // If every character has to be represented as a four-byte escape sequence, then this makes the maximum textual form four labels
1194 // plus the C-string terminating NULL as shown below:
1195 // 63*4+1 + 63*4+1 + 63*4+1 + 61*4+1 + 1 = 1005.
1196 // Note that MAX_ESCAPED_DOMAIN_LABEL is not normally used: If you're only decoding a single label, escaping is usually not required.
1197 // It is for domain names, where dots are used as label separators, that proper escaping is vital.
1198 #define MAX_ESCAPED_DOMAIN_LABEL 254
1199 #define MAX_ESCAPED_DOMAIN_NAME 1005
1200
1201 // Most records have a TTL of 75 minutes, so that their 80% cache-renewal query occurs once per hour.
1202 // For records containing a hostname (in the name on the left, or in the rdata on the right),
1203 // like A, AAAA, reverse-mapping PTR, and SRV, we use a two-minute TTL by default, because we don't want
1204 // them to hang around for too long in the cache if the host in question crashes or otherwise goes away.
1205 // Wide-area service discovery records have a very short TTL to aviod poluting intermediate caches with
1206 // dynamic records. When discovered via Long Lived Queries (with change notifications), resource record
1207 // TTLs can be safely ignored.
1208
1209 #define kStandardTTL (3600UL * 100 / 80)
1210 #define kHostNameTTL 120UL
1211 #define kWideAreaTTL 3
1212
1213 #define DefaultTTLforRRType(X) (((X) == kDNSType_A || (X) == kDNSType_AAAA || (X) == kDNSType_SRV) ? kHostNameTTL : kStandardTTL)
1214
1215 // ***************************************************************************
1216 #if 0
1217 #pragma mark - DNS Message structures
1218 #endif
1219
1220 #define mDNS_numZones numQuestions
1221 #define mDNS_numPrereqs numAnswers
1222 #define mDNS_numUpdates numAuthorities
1223
1224 typedef packedstruct
1225 {
1226 mDNSOpaque16 id;
1227 mDNSOpaque16 flags;
1228 mDNSu16 numQuestions;
1229 mDNSu16 numAnswers;
1230 mDNSu16 numAuthorities;
1231 mDNSu16 numAdditionals;
1232 } DNSMessageHeader;
1233
1234 // We can send and receive packets up to 9000 bytes (Ethernet Jumbo Frame size, if that ever becomes widely used)
1235 // However, in the normal case we try to limit packets to 1500 bytes so that we don't get IP fragmentation on standard Ethernet
1236 // 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
1237 #define AbsoluteMaxDNSMessageData 8940
1238 #define NormalMaxDNSMessageData 1440
1239 typedef packedstruct
1240 {
1241 DNSMessageHeader h; // Note: Size 12 bytes
1242 mDNSu8 data[AbsoluteMaxDNSMessageData]; // 40 (IPv6) + 8 (UDP) + 12 (DNS header) + 8940 (data) = 9000
1243 } DNSMessage;
1244
1245 // ***************************************************************************
1246 #if 0
1247 #pragma mark - Resource Record structures
1248 #endif
1249
1250 // Authoritative Resource Records:
1251 // There are four basic types: Shared, Advisory, Unique, Known Unique
1252
1253 // * Shared Resource Records do not have to be unique
1254 // -- Shared Resource Records are used for DNS-SD service PTRs
1255 // -- It is okay for several hosts to have RRs with the same name but different RDATA
1256 // -- We use a random delay on responses to reduce collisions when all the hosts respond to the same query
1257 // -- These RRs typically have moderately high TTLs (e.g. one hour)
1258 // -- These records are announced on startup and topology changes for the benefit of passive listeners
1259 // -- These records send a goodbye packet when deregistering
1260 //
1261 // * Advisory Resource Records are like Shared Resource Records, except they don't send a goodbye packet
1262 //
1263 // * Unique Resource Records should be unique among hosts within any given mDNS scope
1264 // -- The majority of Resource Records are of this type
1265 // -- If two entities on the network have RRs with the same name but different RDATA, this is a conflict
1266 // -- Responses may be sent immediately, because only one host should be responding to any particular query
1267 // -- These RRs typically have low TTLs (e.g. a few minutes)
1268 // -- On startup and after topology changes, a host issues queries to verify uniqueness
1269
1270 // * Known Unique Resource Records are treated like Unique Resource Records, except that mDNS does
1271 // not have to verify their uniqueness because this is already known by other means (e.g. the RR name
1272 // is derived from the host's IP or Ethernet address, which is already known to be a unique identifier).
1273
1274 // Summary of properties of different record types:
1275 // Probe? Does this record type send probes before announcing?
1276 // Conflict? Does this record type react if we observe an apparent conflict?
1277 // Goodbye? Does this record type send a goodbye packet on departure?
1278 //
1279 // Probe? Conflict? Goodbye? Notes
1280 // Unregistered Should not appear in any list (sanity check value)
1281 // Shared No No Yes e.g. Service PTR record
1282 // Deregistering No No Yes Shared record about to announce its departure and leave the list
1283 // Advisory No No No
1284 // Unique Yes Yes No Record intended to be unique -- will probe to verify
1285 // Verified Yes Yes No Record has completed probing, and is verified unique
1286 // KnownUnique No Yes No Record is assumed by other means to be unique
1287
1288 // Valid lifecycle of a record:
1289 // Unregistered -> Shared -> Deregistering -(goodbye)-> Unregistered
1290 // Unregistered -> Advisory -> Unregistered
1291 // Unregistered -> Unique -(probe)-> Verified -> Unregistered
1292 // Unregistered -> KnownUnique -> Unregistered
1293
1294 // Each Authoritative kDNSRecordType has only one bit set. This makes it easy to quickly see if a record
1295 // is one of a particular set of types simply by performing the appropriate bitwise masking operation.
1296
1297 // Cache Resource Records (received from the network):
1298 // There are four basic types: Answer, Unique Answer, Additional, Unique Additional
1299 // Bit 7 (the top bit) of kDNSRecordType is always set for Cache Resource Records; always clear for Authoritative Resource Records
1300 // Bit 6 (value 0x40) is set for answer records; clear for additional records
1301 // Bit 5 (value 0x20) is set for records received with the kDNSClass_UniqueRRSet
1302
1303 enum
1304 {
1305 kDNSRecordTypeUnregistered = 0x00, // Not currently in any list
1306 kDNSRecordTypeDeregistering = 0x01, // Shared record about to announce its departure and leave the list
1307
1308 kDNSRecordTypeUnique = 0x02, // Will become a kDNSRecordTypeVerified when probing is complete
1309
1310 kDNSRecordTypeAdvisory = 0x04, // Like Shared, but no goodbye packet
1311 kDNSRecordTypeShared = 0x08, // Shared means record name does not have to be unique -- use random delay on responses
1312
1313 kDNSRecordTypeVerified = 0x10, // Unique means mDNS should check that name is unique (and then send immediate responses)
1314 kDNSRecordTypeKnownUnique = 0x20, // Known Unique means mDNS can assume name is unique without checking
1315 // For Dynamic Update records, Known Unique means the record must already exist on the server.
1316 kDNSRecordTypeUniqueMask = (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique),
1317 kDNSRecordTypeActiveMask = (kDNSRecordTypeAdvisory | kDNSRecordTypeShared | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique),
1318
1319 kDNSRecordTypePacketAdd = 0x80, // Received in the Additional Section of a DNS Response
1320 kDNSRecordTypePacketAddUnique = 0x90, // Received in the Additional Section of a DNS Response with kDNSClass_UniqueRRSet set
1321 kDNSRecordTypePacketAuth = 0xA0, // Received in the Authorities Section of a DNS Response
1322 kDNSRecordTypePacketAuthUnique = 0xB0, // Received in the Authorities Section of a DNS Response with kDNSClass_UniqueRRSet set
1323 kDNSRecordTypePacketAns = 0xC0, // Received in the Answer Section of a DNS Response
1324 kDNSRecordTypePacketAnsUnique = 0xD0, // Received in the Answer Section of a DNS Response with kDNSClass_UniqueRRSet set
1325
1326 kDNSRecordTypePacketAnsMask = 0x40, // True for PacketAns and PacketAnsUnique
1327 kDNSRecordTypePacketUniqueMask = 0x10 // True for PacketAddUnique, PacketAnsUnique, PacketAuthUnique
1328 };
1329
1330 typedef packedstruct { mDNSu16 priority; mDNSu16 weight; mDNSIPPort port; domainname target; } rdataSRV;
1331 typedef packedstruct { mDNSu16 preference; domainname exchange; } rdataMX;
1332 typedef packedstruct
1333 {
1334 domainname mname;
1335 domainname rname;
1336 mDNSs32 serial; // Modular counter; increases when zone changes
1337 mDNSu32 refresh; // Time in seconds that a slave waits after successful replication of the database before it attempts replication again
1338 mDNSu32 retry; // Time in seconds that a slave waits after an unsuccessful replication attempt before it attempts replication again
1339 mDNSu32 expire; // Time in seconds that a slave holds on to old data while replication attempts remain unsuccessful
1340 mDNSu32 min; // Nominally the minimum record TTL for this zone, in seconds; also used for negative caching.
1341 } rdataSOA;
1342
1343 typedef packedstruct
1344 {
1345 mDNSu16 vers;
1346 mDNSu16 llqOp;
1347 mDNSu16 err;
1348 mDNSu8 id[8];
1349 mDNSu32 lease;
1350 } LLQOptData;
1351
1352 // NOTE: rdataOpt format may be repeated an arbitrary number of times in a single resource record
1353 typedef packedstruct
1354 {
1355 mDNSu16 opt;
1356 mDNSu16 optlen;
1357 union { LLQOptData llq; mDNSu32 lease; } OptData;
1358 } rdataOpt;
1359
1360 // StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record
1361 // MaximumRDSize is 8K the absolute maximum we support (at least for now)
1362 #define StandardAuthRDSize 264
1363 #define MaximumRDSize 8192
1364
1365 // InlineCacheRDSize is 64
1366 // Records received from the network with rdata this size or less have their rdata stored right in the CacheRecord object
1367 // Records received from the network with rdata larger than this have additional storage allocated for the rdata
1368 // A quick unscientific sample from a busy network at Apple with lots of machines revealed this:
1369 // 1461 records in cache
1370 // 292 were one-byte TXT records
1371 // 136 were four-byte A records
1372 // 184 were sixteen-byte AAAA records
1373 // 780 were various PTR, TXT and SRV records from 12-64 bytes
1374 // Only 69 records had rdata bigger than 64 bytes
1375 // Note that since CacheRecord object and a CacheGroup object are allocated out of the same pool, it's sensible to
1376 // have them both be the same size. Making one smaller without making the other smaller won't actually save any memory.
1377 #define InlineCacheRDSize 64
1378
1379 #define InlineCacheGroupNameSize 144
1380
1381 typedef union
1382 {
1383 mDNSu8 data[StandardAuthRDSize];
1384 mDNSv4Addr ipv4; // For 'A' record
1385 mDNSv6Addr ipv6; // For 'AAAA' record
1386 domainname name; // For PTR, NS, and CNAME records
1387 UTF8str255 txt; // For TXT record
1388 rdataSRV srv; // For SRV record
1389 rdataMX mx; // For MX record
1390 rdataSOA soa; // For SOA record
1391 rdataOpt opt; // For eDNS0 opt record
1392 } RDataBody;
1393
1394 typedef struct
1395 {
1396 mDNSu16 MaxRDLength; // Amount of storage allocated for rdata (usually sizeof(RDataBody))
1397 RDataBody u;
1398 } RData;
1399 #define sizeofRDataHeader (sizeof(RData) - sizeof(RDataBody))
1400
1401 typedef struct AuthRecord_struct AuthRecord;
1402 typedef struct CacheRecord_struct CacheRecord;
1403 typedef struct CacheGroup_struct CacheGroup;
1404 typedef struct DNSQuestion_struct DNSQuestion;
1405 typedef struct mDNS_struct mDNS;
1406 typedef struct mDNS_PlatformSupport_struct mDNS_PlatformSupport;
1407 typedef struct NATTraversalInfo_struct NATTraversalInfo;
1408
1409 // Note: Within an mDNSRecordCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Close(), mDNS_Execute()
1410 typedef void mDNSRecordCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
1411
1412 // Note:
1413 // Restrictions: An mDNSRecordUpdateCallback may not make any mDNS API calls.
1414 // The intent of this callback is to allow the client to free memory, if necessary.
1415 // The internal data structures of the mDNS code may not be in a state where mDNS API calls may be made safely.
1416 typedef void mDNSRecordUpdateCallback(mDNS *const m, AuthRecord *const rr, RData *OldRData);
1417
1418 typedef struct
1419 {
1420 mDNSu8 RecordType; // See enum above
1421 mDNSInterfaceID InterfaceID; // Set if this RR is specific to one interface
1422 // For records received off the wire, InterfaceID is *always* set to the receiving interface
1423 // For our authoritative records, InterfaceID is usually zero, except for those few records
1424 // that are interface-specific (e.g. address records, especially linklocal addresses)
1425 domainname *name;
1426 mDNSu16 rrtype;
1427 mDNSu16 rrclass;
1428 mDNSu32 rroriginalttl; // In seconds
1429 mDNSu16 rdlength; // Size of the raw rdata, in bytes
1430 mDNSu16 rdestimate; // Upper bound on size of rdata after name compression
1431 mDNSu32 namehash; // Name-based (i.e. case insensitive) hash of name
1432 mDNSu32 rdatahash; // 32-bit hash of the raw rdata
1433 mDNSu32 rdnamehash; // Set if this rdata contains a domain name (e.g. PTR, SRV, CNAME etc.)
1434 RData *rdata; // Pointer to storage for this rdata
1435 } ResourceRecord;
1436
1437 // Unless otherwise noted, states may apply to either independent record registrations or service registrations
1438 typedef enum
1439 {
1440 regState_FetchingZoneData = 1, // getting info - update not sent
1441 regState_Pending = 2, // update sent, reply not received
1442 regState_Registered = 3, // update sent, reply received
1443 regState_DeregPending = 4, // dereg sent, reply not received
1444 regState_DeregDeferred = 5, // dereg requested while in Pending state - send dereg AFTER registration is confirmed
1445 regState_Cancelled = 6, // update not sent, reg. cancelled by client
1446 regState_Unregistered = 8, // not in any list
1447 regState_Refresh = 9, // outstanding refresh (or target change) message
1448 regState_NATMap = 10, // establishing NAT port mapping or learning public address
1449 regState_UpdatePending = 11, // update in flight as result of mDNS_Update call
1450 regState_NoTarget = 12, // service registration pending registration of hostname (ServiceRegistrations only)
1451 regState_ExtraQueued = 13, // extra record to be registered upon completion of service registration (RecordRegistrations only)
1452 regState_NATError = 14 // unable to complete NAT traversal
1453 } regState_t;
1454
1455 // context for both ServiceRecordSet and individual AuthRec structs
1456 typedef struct
1457 {
1458 // registration/lease state
1459 regState_t state;
1460 mDNSBool lease; // dynamic update contains (should contain) lease option
1461 mDNSs32 expire; // expiration of lease (-1 for static)
1462 mDNSBool TestForSelfConflict; // on name conflict, check if we're just seeing our own orphaned records
1463
1464 // identifier to match update request and response
1465 mDNSOpaque16 id;
1466
1467 // server info
1468 domainname zone; // the zone that is updated
1469 mDNSAddr ns; // primary name server for the record's zone !!!KRS not technically correct to cache longer than TTL
1470 mDNSIPPort port; // port on which server accepts dynamic updates
1471
1472 // NAT traversal context
1473 NATTraversalInfo *NATinfo; // may be NULL
1474
1475 // state for deferred operations
1476 mDNSBool ClientCallbackDeferred; // invoke client callback on completion of pending operation(s)
1477 mStatus DeferredStatus; // status to deliver when above flag is set
1478 mDNSBool SRVUpdateDeferred; // do we need to change target or port once current operation completes?
1479 mDNSBool SRVChanged; // temporarily deregistered service because its SRV target or port changed
1480
1481 // uDNS_UpdateRecord support fields
1482 mDNSBool UpdateQueued; // Update the rdata once the current pending operation completes
1483 RData *UpdateRData; // Pointer to new RData while a record update is in flight
1484 mDNSu16 UpdateRDLen; // length of above field
1485 mDNSRecordUpdateCallback *UpdateRDCallback; // client callback to free old rdata
1486 } uDNS_RegInfo;
1487
1488 struct AuthRecord_struct
1489 {
1490 // For examples of how to set up this structure for use in mDNS_Register(),
1491 // see mDNS_AdvertiseInterface() or mDNS_RegisterService().
1492 // Basically, resrec and persistent metadata need to be set up before calling mDNS_Register().
1493 // mDNS_SetupResourceRecord() is avaliable as a helper routine to set up most fields to sensible default values for you
1494
1495 AuthRecord *next; // Next in list; first element of structure for efficiency reasons
1496 // Field Group 1: Common ResourceRecord fields
1497 ResourceRecord resrec;
1498 uDNS_RegInfo uDNS_info;
1499
1500 // Field Group 2: Persistent metadata for Authoritative Records
1501 AuthRecord *Additional1; // Recommended additional record to include in response
1502 AuthRecord *Additional2; // Another additional
1503 AuthRecord *DependentOn; // This record depends on another for its uniqueness checking
1504 AuthRecord *RRSet; // This unique record is part of an RRSet
1505 mDNSRecordCallback *RecordCallback; // Callback function to call for state changes, and to free memory asynchronously on deregistration
1506 void *RecordContext; // Context parameter for the callback function
1507 mDNSu8 HostTarget; // Set if the target of this record (PTR, CNAME, SRV, etc.) is our host name
1508 mDNSu8 AllowRemoteQuery; // Set if we allow hosts not on the local link to query this record
1509 mDNSu8 ForceMCast; // Set by client to advertise solely via multicast, even for apparently unicast names
1510
1511 // Field Group 3: Transient state for Authoritative Records
1512 mDNSu8 Acknowledged; // Set if we've given the success callback to the client
1513 mDNSu8 ProbeCount; // Number of probes remaining before this record is valid (kDNSRecordTypeUnique)
1514 mDNSu8 AnnounceCount; // Number of announcements remaining (kDNSRecordTypeShared)
1515 mDNSu8 RequireGoodbye; // Set if this RR has been announced on the wire and will require a goodbye packet
1516 mDNSu8 LocalAnswer; // Set if this RR has been delivered to LocalOnly questions
1517 mDNSu8 IncludeInProbe; // Set if this RR is being put into a probe right now
1518 mDNSInterfaceID ImmedAnswer; // Someone on this interface issued a query we need to answer (all-ones for all interfaces)
1519 mDNSu8 ImmedUnicast; // Set if we may send our response directly via unicast to the requester
1520 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
1521 mDNSs32 ImmedAnswerMarkTime;
1522 #endif
1523 mDNSInterfaceID ImmedAdditional; // Hint that we might want to also send this record, just to be helpful
1524 mDNSInterfaceID SendRNow; // The interface this query is being sent on right now
1525 mDNSv4Addr v4Requester; // Recent v4 query for this record, or all-ones if more than one recent query
1526 mDNSv6Addr v6Requester; // Recent v6 query for this record, or all-ones if more than one recent query
1527 AuthRecord *NextResponse; // Link to the next element in the chain of responses to generate
1528 const mDNSu8 *NR_AnswerTo; // Set if this record was selected by virtue of being a direct answer to a question
1529 AuthRecord *NR_AdditionalTo; // Set if this record was selected by virtue of being additional to another
1530 mDNSs32 ThisAPInterval; // In platform time units: Current interval for announce/probe
1531 mDNSs32 AnnounceUntil; // In platform time units: Creation time + TTL
1532 mDNSs32 LastAPTime; // In platform time units: Last time we sent announcement/probe
1533 mDNSs32 LastMCTime; // Last time we multicast this record (used to guard against packet-storm attacks)
1534 mDNSInterfaceID LastMCInterface; // Interface this record was multicast on at the time LastMCTime was recorded
1535 RData *NewRData; // Set if we are updating this record with new rdata
1536 mDNSu16 newrdlength; // ... and the length of the new RData
1537 mDNSRecordUpdateCallback *UpdateCallback;
1538 mDNSu32 UpdateCredits; // Token-bucket rate limiting of excessive updates
1539 mDNSs32 NextUpdateCredit; // Time next token is added to bucket
1540 mDNSs32 UpdateBlocked; // Set if update delaying is in effect
1541
1542 domainname namestorage;
1543 RData rdatastorage; // Normally the storage is right here, except for oversized records
1544 // rdatastorage MUST be the last thing in the structure -- when using oversized AuthRecords, extra bytes
1545 // are appended after the end of the AuthRecord, logically augmenting the size of the rdatastorage
1546 // DO NOT ADD ANY MORE FIELDS HERE
1547 };
1548
1549 // Wrapper struct for Auth Records for higher-level code that cannot use the AuthRecord's ->next pointer field
1550 typedef struct ARListElem
1551 {
1552 struct ARListElem *next;
1553 AuthRecord ar; // Note: Must be last struct in field to accomodate oversized AuthRecords
1554 } ARListElem;
1555
1556 struct CacheGroup_struct // Header object for a list of CacheRecords with the same name
1557 {
1558 CacheGroup *next; // Next CacheGroup object in this hash table bucket
1559 mDNSu32 namehash; // Name-based (i.e. case insensitive) hash of name
1560 CacheRecord *members; // List of CacheRecords with this same name
1561 CacheRecord **rrcache_tail; // Tail end of that list
1562 domainname *name; // Common name for all CacheRecords in this list
1563 mDNSu8 namestorage[InlineCacheGroupNameSize];
1564 };
1565
1566 struct CacheRecord_struct
1567 {
1568 CacheRecord *next; // Next in list; first element of structure for efficiency reasons
1569 ResourceRecord resrec;
1570
1571 // Transient state for Cache Records
1572 CacheRecord *NextInKAList; // Link to the next element in the chain of known answers to send
1573 mDNSs32 TimeRcvd; // In platform time units
1574 mDNSs32 DelayDelivery; // Set if we want to defer delivery of this answer to local clients
1575 mDNSs32 NextRequiredQuery; // In platform time units
1576 mDNSs32 LastUsed; // In platform time units
1577 DNSQuestion *CRActiveQuestion; // Points to an active question referencing this answer
1578 mDNSu32 UnansweredQueries; // Number of times we've issued a query for this record without getting an answer
1579 mDNSs32 LastUnansweredTime; // In platform time units; last time we incremented UnansweredQueries
1580 mDNSu32 MPUnansweredQ; // Multi-packet query handling: Number of times we've seen a query for this record
1581 mDNSs32 MPLastUnansweredQT; // Multi-packet query handling: Last time we incremented MPUnansweredQ
1582 mDNSu32 MPUnansweredKA; // Multi-packet query handling: Number of times we've seen this record in a KA list
1583 mDNSBool MPExpectingKA; // Multi-packet query handling: Set when we increment MPUnansweredQ; allows one KA
1584 CacheRecord *NextInCFList; // Set if this is in the list of records we just received with the cache flush bit set
1585
1586 struct { mDNSu16 MaxRDLength; mDNSu8 data[InlineCacheRDSize]; } rdatastorage; // Storage for small records is right here
1587 };
1588
1589 // Storage sufficient to hold either a CacheGroup header or a CacheRecord
1590 typedef union CacheEntity_union CacheEntity;
1591 union CacheEntity_union { CacheEntity *next; CacheGroup cg; CacheRecord cr; };
1592
1593 typedef struct
1594 {
1595 CacheRecord r;
1596 mDNSu8 _extradata[MaximumRDSize-InlineCacheRDSize]; // Glue on the necessary number of extra bytes
1597 domainname namestorage; // Needs to go *after* the extra rdata bytes
1598 } LargeCacheRecord;
1599
1600 typedef struct uDNS_HostnameInfo
1601 {
1602 struct uDNS_HostnameInfo *next;
1603 AuthRecord *ar; // registered address record
1604 mDNSRecordCallback *StatusCallback; // callback to deliver success or error code to client layer
1605 const void *StatusContext; // Client Context
1606 } uDNS_HostnameInfo;
1607
1608 typedef struct DNSServer
1609 {
1610 struct DNSServer *next;
1611 mDNSAddr addr;
1612 domainname domain; // name->server matching for "split dns"
1613 } DNSServer;
1614
1615 typedef struct NetworkInterfaceInfo_struct NetworkInterfaceInfo;
1616
1617 // A NetworkInterfaceInfo_struct serves two purposes:
1618 // 1. It holds the address, PTR and HINFO records to advertise a given IP address on a given physical interface
1619 // 2. It tells mDNSCore which physical interfaces are available; each physical interface has its own unique InterfaceID.
1620 // Since there may be multiple IP addresses on a single physical interface,
1621 // there may be multiple NetworkInterfaceInfo_structs with the same InterfaceID.
1622 // In this case, to avoid sending the same packet n times, when there's more than one
1623 // struct with the same InterfaceID, mDNSCore picks one member of the set to be the
1624 // active representative of the set; all others have the 'InterfaceActive' flag unset.
1625
1626 struct NetworkInterfaceInfo_struct
1627 {
1628 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1629 NetworkInterfaceInfo *next;
1630
1631 mDNSBool InterfaceActive; // Set if interface is sending & receiving packets (see comment above)
1632 mDNSBool IPv4Available; // If InterfaceActive, set if v4 available on this InterfaceID
1633 mDNSBool IPv6Available; // If InterfaceActive, set if v6 available on this InterfaceID
1634
1635 // Standard AuthRecords that every Responder host should have (one per active IP address)
1636 AuthRecord RR_A; // 'A' or 'AAAA' (address) record for our ".local" name
1637 AuthRecord RR_PTR; // PTR (reverse lookup) record
1638 AuthRecord RR_HINFO;
1639
1640 // Client API fields: The client must set up these fields *before* calling mDNS_RegisterInterface()
1641 mDNSInterfaceID InterfaceID; // Identifies physical interface; MUST NOT be 0, -1, or -2
1642 mDNSAddr ip; // The IPv4 or IPv6 address to advertise
1643 mDNSAddr mask;
1644 char ifname[16];
1645 mDNSBool Advertise; // False if you are only searching on this interface
1646 mDNSBool McastTxRx; // Send/Receive multicast on this { InterfaceID, address family } ?
1647 };
1648
1649 typedef struct ExtraResourceRecord_struct ExtraResourceRecord;
1650 struct ExtraResourceRecord_struct
1651 {
1652 ExtraResourceRecord *next;
1653 mDNSu32 ClientID; // Opaque ID field to be used by client to map an AddRecord call to a set of Extra records
1654 AuthRecord r;
1655 // Note: Add any additional fields *before* the AuthRecord in this structure, not at the end.
1656 // In some cases clients can allocate larger chunks of memory and set r->rdata->MaxRDLength to indicate
1657 // that this extra memory is available, which would result in any fields after the AuthRecord getting smashed
1658 };
1659
1660 // Note: Within an mDNSServiceCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Close(), mDNS_Execute()
1661 typedef struct ServiceRecordSet_struct ServiceRecordSet;
1662 typedef void mDNSServiceCallback(mDNS *const m, ServiceRecordSet *const sr, mStatus result);
1663 struct ServiceRecordSet_struct
1664 {
1665 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1666 // No fields need to be set up by the client prior to calling mDNS_RegisterService();
1667 // all required data is passed as parameters to that function.
1668 ServiceRecordSet *next;
1669 uDNS_RegInfo uDNS_info;
1670 mDNSServiceCallback *ServiceCallback;
1671 void *ServiceContext;
1672 ExtraResourceRecord *Extras; // Optional list of extra AuthRecords attached to this service registration
1673 mDNSu32 NumSubTypes;
1674 AuthRecord *SubTypes;
1675 mDNSBool Conflict; // Set if this record set was forcibly deregistered because of a conflict
1676 domainname Host; // Set if this service record does not use the standard target host name
1677 AuthRecord RR_ADV; // e.g. _services._dns-sd._udp.local. PTR _printer._tcp.local.
1678 AuthRecord RR_PTR; // e.g. _printer._tcp.local. PTR Name._printer._tcp.local.
1679 AuthRecord RR_SRV; // e.g. Name._printer._tcp.local. SRV 0 0 port target
1680 AuthRecord RR_TXT; // e.g. Name._printer._tcp.local. TXT PrintQueueName
1681 // Don't add any fields after AuthRecord RR_TXT.
1682 // This is where the implicit extra space goes if we allocate a ServiceRecordSet containing an oversized RR_TXT record
1683 };
1684
1685 // ***************************************************************************
1686 #if 0
1687 #pragma mark - Question structures
1688 #endif
1689
1690 // We record the last eight instances of each duplicate query
1691 // This gives us v4/v6 on each of Ethernet/AirPort and Firewire, and two free slots "for future expansion"
1692 // If the host has more active interfaces that this it is not fatal -- duplicate question suppression will degrade gracefully.
1693 // Since we will still remember the last eight, the busiest interfaces will still get the effective duplicate question suppression.
1694 #define DupSuppressInfoSize 8
1695
1696 typedef struct
1697 {
1698 mDNSs32 Time;
1699 mDNSInterfaceID InterfaceID;
1700 mDNSs32 Type; // v4 or v6?
1701 } DupSuppressInfo;
1702
1703 typedef enum
1704 {
1705 // Setup states
1706 LLQ_UnInit = 0,
1707 LLQ_GetZoneInfo = 1,
1708 LLQ_InitialRequest = 2,
1709 LLQ_SecondaryRequest = 3,
1710 LLQ_Refresh = 4,
1711 LLQ_Retry = 5,
1712 LLQ_Established = 6,
1713 LLQ_Suspended = 7,
1714 LLQ_SuspendDeferred = 8, // suspend once we get zone info
1715 LLQ_SuspendedPoll = 9, // suspended from polling state
1716 LLQ_NatMapWait = 10,
1717
1718 // Established/error states
1719 LLQ_Static = 16,
1720 LLQ_Poll = 17,
1721 LLQ_Error = 18,
1722 LLQ_Cancelled = 19
1723 } LLQ_State;
1724
1725 typedef struct
1726 {
1727 LLQ_State state;
1728 mDNSAddr servAddr;
1729 mDNSIPPort servPort;
1730 DNSQuestion *question;
1731 mDNSu32 origLease; // seconds (relative)
1732 mDNSs32 retry; // ticks (absolute)
1733 mDNSs32 expire; // ticks (absolute)
1734 mDNSs16 ntries;
1735 mDNSu8 id[8];
1736 mDNSBool deriveRemovesOnResume;
1737 mDNSBool NATMap; // does this LLQ use the global LLQ NAT mapping?
1738 } LLQ_Info;
1739
1740 // LLQ constants
1741 #define kDNSOpt_LLQ 1
1742 #define kDNSOpt_Lease 2
1743 #define kLLQ_Vers 1
1744 #define kLLQ_DefLease 7200 // 2 hours
1745 #define kLLQ_MAX_TRIES 3 // retry an operation 3 times max
1746 #define kLLQ_INIT_RESEND 2 // resend an un-ack'd packet after 2 seconds, then double for each additional
1747 #define kLLQ_DEF_RETRY 1800 // retry a failed operation after 30 minutes
1748 // LLQ Operation Codes
1749 #define kLLQOp_Setup 1
1750 #define kLLQOp_Refresh 2
1751 #define kLLQOp_Event 3
1752
1753 #define LLQ_OPT_SIZE (2 * sizeof(mDNSu16)) + sizeof(LLQOptData)
1754 #define LEASE_OPT_SIZE (2 * sizeof(mDNSu16)) + sizeof(mDNSs32)
1755
1756 // LLQ Errror Codes
1757 enum
1758 {
1759 LLQErr_NoError = 0,
1760 LLQErr_ServFull = 1,
1761 LLQErr_Static = 2,
1762 LLQErr_FormErr = 3,
1763 LLQErr_NoSuchLLQ = 4,
1764 LLQErr_BadVers = 5,
1765 LLQErr_UnknownErr = 6
1766 };
1767
1768 typedef void (*InternalResponseHndlr)(mDNS *const m, DNSMessage *msg, const mDNSu8 *end, DNSQuestion *question, void *internalContext);
1769 typedef struct
1770 {
1771 mDNSOpaque16 id;
1772 mDNSBool internal;
1773 InternalResponseHndlr responseCallback; // NULL if internal field is false
1774 LLQ_Info *llq; // NULL for 1-shot queries
1775 mDNSBool Answered; // have we received an answer (including NXDOMAIN) for this question?
1776 CacheRecord *knownAnswers;
1777 mDNSs32 RestartTime; // Mark when we restart a suspended query
1778 void *context;
1779 } uDNS_QuestionInfo;
1780
1781 // Note: Within an mDNSQuestionCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Close(), mDNS_Execute()
1782 typedef void mDNSQuestionCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, mDNSBool AddRecord);
1783 struct DNSQuestion_struct
1784 {
1785 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1786 DNSQuestion *next;
1787 mDNSu32 qnamehash;
1788 mDNSs32 DelayAnswering; // Set if we want to defer answering this question until the cache settles
1789 mDNSs32 LastQTime; // Last scheduled transmission of this Q on *all* applicable interfaces
1790 mDNSs32 ThisQInterval; // LastQTime + ThisQInterval is the next scheduled transmission of this Q
1791 // ThisQInterval > 0 for an active question;
1792 // ThisQInterval = 0 for a suspended question that's still in the list
1793 // ThisQInterval = -1 for a cancelled question that's been removed from the list
1794 mDNSs32 LastAnswerPktNum; // The sequence number of the last response packet containing an answer to this Q
1795 mDNSu32 RecentAnswerPkts; // Number of answers since the last time we sent this query
1796 mDNSu32 CurrentAnswers; // Number of records currently in the cache that answer this question
1797 mDNSu32 LargeAnswers; // Number of answers with rdata > 1024 bytes
1798 mDNSu32 UniqueAnswers; // Number of answers received with kDNSClass_UniqueRRSet bit set
1799 DNSQuestion *DuplicateOf;
1800 DNSQuestion *NextInDQList;
1801 DupSuppressInfo DupSuppress[DupSuppressInfoSize];
1802 mDNSInterfaceID SendQNow; // The interface this query is being sent on right now
1803 mDNSBool SendOnAll; // Set if we're sending this question on all active interfaces
1804 mDNSu32 RequestUnicast; // Non-zero if we want to send query with kDNSQClass_UnicastResponse bit set
1805 mDNSs32 LastQTxTime; // Last time this Q was sent on one (but not necessarily all) interfaces
1806 uDNS_QuestionInfo uDNS_info;
1807
1808 // Client API fields: The client must set up these fields *before* calling mDNS_StartQuery()
1809 mDNSInterfaceID InterfaceID; // Non-zero if you want to issue queries only on a single specific IP interface
1810 mDNSAddr Target; // Non-zero if you want to direct queries to a specific unicast target address
1811 mDNSIPPort TargetPort; // Must be set if Target is set
1812 mDNSOpaque16 TargetQID; // Must be set if Target is set
1813 domainname qname;
1814 mDNSu16 qtype;
1815 mDNSu16 qclass;
1816 mDNSBool LongLived; // Set by client for calls to mDNS_StartQuery to indicate LLQs to unicast layer.
1817 mDNSBool ExpectUnique; // Set by client if it's expecting unique RR(s) for this question, not shared RRs
1818 mDNSBool ForceMCast; // Set by client to force mDNS query, even for apparently uDNS names
1819 mDNSQuestionCallback *QuestionCallback;
1820 void *QuestionContext;
1821 };
1822
1823 typedef struct
1824 {
1825 // Client API fields: The client must set up name and InterfaceID *before* calling mDNS_StartResolveService()
1826 // When the callback is invoked, ip, port, TXTlen and TXTinfo will have been filled in with the results learned from the network.
1827 domainname name;
1828 mDNSInterfaceID InterfaceID; // ID of the interface the response was received on
1829 mDNSAddr ip; // Remote (destination) IP address where this service can be accessed
1830 mDNSIPPort port; // Port where this service can be accessed
1831 mDNSu16 TXTlen;
1832 mDNSu8 TXTinfo[2048]; // Additional demultiplexing information (e.g. LPR queue name)
1833 } ServiceInfo;
1834
1835 // Note: Within an mDNSServiceInfoQueryCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Close(), mDNS_Execute()
1836 typedef struct ServiceInfoQuery_struct ServiceInfoQuery;
1837 typedef void mDNSServiceInfoQueryCallback(mDNS *const m, ServiceInfoQuery *query);
1838 struct ServiceInfoQuery_struct
1839 {
1840 // Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
1841 // No fields need to be set up by the client prior to calling mDNS_StartResolveService();
1842 // all required data is passed as parameters to that function.
1843 // The ServiceInfoQuery structure memory is working storage for mDNSCore to discover the requested information
1844 // and place it in the ServiceInfo structure. After the client has called mDNS_StopResolveService(), it may
1845 // dispose of the ServiceInfoQuery structure while retaining the results in the ServiceInfo structure.
1846 DNSQuestion qSRV;
1847 DNSQuestion qTXT;
1848 DNSQuestion qAv4;
1849 DNSQuestion qAv6;
1850 mDNSu8 GotSRV;
1851 mDNSu8 GotTXT;
1852 mDNSu8 GotADD;
1853 mDNSu32 Answers;
1854 ServiceInfo *info;
1855 mDNSServiceInfoQueryCallback *ServiceInfoQueryCallback;
1856 void *ServiceInfoQueryContext;
1857 };
1858
1859 // ***************************************************************************
1860 #if 0
1861 #pragma mark - NAT Traversal structures and constants
1862 #endif
1863
1864 #define NATMAP_INIT_RETRY (mDNSPlatformOneSecond / 4) // start at 250ms w/ exponential decay
1865 #define NATMAP_MAX_RETRY mDNSPlatformOneSecond // back off to once per second
1866 #define NATMAP_MAX_TRIES 3 // for max 3 tries
1867 #define NATMAP_DEFAULT_LEASE (60 * 60) // lease life in seconds
1868 #define NATMAP_VERS 0
1869 #define NATMAP_PORT 5351
1870 #define NATMAP_RESPONSE_MASK 0x80
1871
1872 typedef enum
1873 {
1874 NATOp_AddrRequest = 0,
1875 NATOp_MapUDP = 1,
1876 NATOp_MapTCP = 2
1877 } NATOp_t;
1878
1879 enum
1880 {
1881 NATErr_None = 0,
1882 NATErr_Vers = 1,
1883 NATErr_Refused = 2,
1884 NATErr_NetFail = 3,
1885 NATErr_Res = 4,
1886 NATErr_Opcode = 5
1887 };
1888
1889 typedef mDNSu16 NATErr_t;
1890
1891 typedef enum
1892 {
1893 NATState_Init = 0,
1894 NATState_Request = 1,
1895 NATState_Established = 2,
1896 NATState_Legacy = 3,
1897 NATState_Error = 4,
1898 NATState_Refresh = 5,
1899 NATState_Deleted = 6
1900 } NATState_t;
1901 // Note: we have no explicit "cancelled" state, where a service/interface is deregistered while we
1902 // have an outstanding NAT request. This is conveyed by the "reg" pointer being set to NULL
1903
1904 typedef packedstruct
1905 {
1906 mDNSu8 vers;
1907 mDNSu8 opcode;
1908 } NATAddrRequest;
1909
1910 typedef packedstruct
1911 {
1912 mDNSu8 vers;
1913 mDNSu8 opcode;
1914 mDNSOpaque16 err;
1915 mDNSOpaque32 uptime;
1916 mDNSv4Addr PubAddr;
1917 } NATAddrReply;
1918
1919 typedef packedstruct
1920 {
1921 mDNSu8 vers;
1922 mDNSu8 opcode;
1923 mDNSOpaque16 unused;
1924 mDNSIPPort priv;
1925 mDNSIPPort pub;
1926 mDNSOpaque32 lease;
1927 } NATPortMapRequest;
1928
1929 typedef packedstruct
1930 {
1931 mDNSu8 vers;
1932 mDNSu8 opcode;
1933 mDNSOpaque16 err;
1934 mDNSOpaque32 uptime;
1935 mDNSIPPort priv;
1936 mDNSIPPort pub;
1937 mDNSOpaque32 lease;
1938 } NATPortMapReply;
1939
1940 // Pass NULL for pkt on error (including timeout)
1941 typedef void (*NATResponseHndlr)(NATTraversalInfo *n, mDNS *m, mDNSu8 *pkt, mDNSu16 len);
1942
1943 struct NATTraversalInfo_struct
1944 {
1945 NATOp_t op;
1946 NATResponseHndlr ReceiveResponse;
1947 union { AuthRecord *RecordRegistration; ServiceRecordSet *ServiceRegistration; } reg;
1948 mDNSAddr Router;
1949 mDNSIPPort PublicPort;
1950 union { NATAddrRequest AddrReq; NATPortMapRequest PortReq; } request;
1951 mDNSs32 retry; // absolute time when we retry
1952 mDNSs32 RetryInterval; // delta between time sent and retry
1953 int ntries;
1954 NATState_t state;
1955 NATTraversalInfo *next;
1956 };
1957
1958 // ***************************************************************************
1959 #if 0
1960 #pragma mark - Main mDNS object, used to hold all the mDNS state
1961 #endif
1962
1963 typedef void mDNSCallback(mDNS *const m, mStatus result);
1964
1965 #define CACHE_HASH_SLOTS 499
1966
1967 enum
1968 {
1969 mDNS_KnownBug_PhantomInterfaces = 1
1970 };
1971
1972 typedef struct
1973 {
1974 mDNSs32 nextevent;
1975 DNSQuestion *ActiveQueries; //!!!KRS this should be a hashtable (hash on messageID)
1976 DNSQuestion *CurrentQuery; // pointer to ActiveQueries list being examined in a loop. Functions that remove
1977 // elements from the ActiveQueries list must update this pointer (if non-NULL) as necessary.
1978 //!!!KRS do the same for registration lists
1979 ServiceRecordSet *ServiceRegistrations;
1980 AuthRecord *RecordRegistrations;
1981 NATTraversalInfo *NATTraversals;
1982 mDNSu16 NextMessageID;
1983 DNSServer *Servers; // list of DNS servers
1984 mDNSAddr Router;
1985 mDNSAddr PrimaryIP; // Address of primary interface
1986 mDNSAddr MappedPrimaryIP; // Cache of public address if PrimaryIP is behind a NAT
1987 NATTraversalInfo *LLQNatInfo; // Nat port mapping to receive LLQ events
1988 domainname ServiceRegDomain; // (going away w/ multi-user support)
1989 struct uDNS_AuthInfo *AuthInfoList; // list of domains requiring authentication for updates.
1990 uDNS_HostnameInfo *Hostnames; // List of registered hostnames + hostname metadata
1991 DNSQuestion ReverseMap; // Reverse-map query to find static hostname for service target
1992 mDNSBool ReverseMapActive; // Is above query active?
1993 domainname StaticHostname; // Current answer to reverse-map query (above)
1994 mDNSBool DelaySRVUpdate; // Delay SRV target/port update to avoid "flap"
1995 mDNSs32 NextSRVUpdate; // Time to perform delayed update
1996 } uDNS_GlobalInfo;
1997
1998 struct mDNS_struct
1999 {
2000 // Internal state fields. These hold the main internal state of mDNSCore;
2001 // the client layer needn't be concerned with them.
2002 // No fields need to be set up by the client prior to calling mDNS_Init();
2003 // all required data is passed as parameters to that function.
2004
2005 mDNS_PlatformSupport *p; // Pointer to platform-specific data of indeterminite size
2006 mDNSu32 KnownBugs;
2007 mDNSBool CanReceiveUnicastOn5353;
2008 mDNSBool AdvertiseLocalAddresses;
2009 mStatus mDNSPlatformStatus;
2010 mDNSIPPort UnicastPort4;
2011 mDNSIPPort UnicastPort6;
2012 mDNSCallback *MainCallback;
2013 void *MainContext;
2014
2015 // For debugging: To catch and report locking failures
2016 mDNSu32 mDNS_busy; // Incremented between mDNS_Lock/mDNS_Unlock section
2017 mDNSu32 mDNS_reentrancy; // Incremented when calling a client callback
2018 mDNSu8 mDNS_shutdown; // Set when we're shutting down, allows us to skip some unnecessary steps
2019 mDNSu8 lock_rrcache; // For debugging: Set at times when these lists may not be modified
2020 mDNSu8 lock_Questions;
2021 mDNSu8 lock_Records;
2022 char MsgBuffer[80]; // Temp storage used while building error log messages
2023
2024 // Task Scheduling variables
2025 mDNSs32 timenow; // The time that this particular activation of the mDNS code started
2026 mDNSs32 timenow_last; // The time the last time we ran
2027 mDNSs32 timenow_adjust; // Correction applied if we ever discover time went backwards
2028 mDNSs32 NextScheduledEvent; // Derived from values below
2029 mDNSs32 SuppressSending; // Don't send *any* packets during this time
2030 mDNSs32 NextCacheCheck; // Next time to refresh cache record before it expires
2031 mDNSs32 NextScheduledQuery; // Next time to send query in its exponential backoff sequence
2032 mDNSs32 NextScheduledProbe; // Next time to probe for new authoritative record
2033 mDNSs32 NextScheduledResponse; // Next time to send authoritative record(s) in responses
2034 mDNSs32 ExpectUnicastResponse; // Set when we send a query with the kDNSQClass_UnicastResponse bit set
2035 mDNSs32 RandomQueryDelay; // For de-synchronization of query packets on the wire
2036 mDNSs32 PktNum; // Unique sequence number assigned to each received packet
2037 mDNSBool SendDeregistrations; // Set if we need to send deregistrations (immediately)
2038 mDNSBool SendImmediateAnswers; // Set if we need to send answers (immediately -- or as soon as SuppressSending clears)
2039 mDNSBool SleepState; // Set if we're sleeping (send no more packets)
2040
2041 // These fields only required for mDNS Searcher...
2042 DNSQuestion *Questions; // List of all registered questions, active and inactive
2043 DNSQuestion *NewQuestions; // Fresh questions not yet answered from cache
2044 DNSQuestion *CurrentQuestion; // Next question about to be examined in AnswerLocalQuestions()
2045 DNSQuestion *LocalOnlyQuestions; // Questions with InterfaceID set to mDNSInterface_LocalOnly
2046 DNSQuestion *NewLocalOnlyQuestions; // Fresh local-only questions not yet answered
2047 mDNSu32 rrcache_size; // Total number of available cache entries
2048 mDNSu32 rrcache_totalused; // Number of cache entries currently occupied
2049 mDNSu32 rrcache_active; // Number of cache entries currently occupied by records that answer active questions
2050 mDNSu32 rrcache_report;
2051 CacheEntity *rrcache_free;
2052 CacheGroup *rrcache_hash[CACHE_HASH_SLOTS];
2053
2054 // Fields below only required for mDNS Responder...
2055 domainlabel nicelabel; // Rich text label encoded using canonically precomposed UTF-8
2056 domainlabel hostlabel; // Conforms to RFC 1034 "letter-digit-hyphen" ARPANET host name rules
2057 domainname MulticastHostname; // Fully Qualified "dot-local" Host Name, e.g. "Foo.local."
2058 UTF8str255 HIHardware;
2059 UTF8str255 HISoftware;
2060 AuthRecord *ResourceRecords;
2061 AuthRecord *DuplicateRecords; // Records currently 'on hold' because they are duplicates of existing records
2062 AuthRecord *NewLocalRecords; // Fresh local-only records not yet delivered to local-only questions
2063 AuthRecord *CurrentRecord; // Next AuthRecord about to be examined
2064 NetworkInterfaceInfo *HostInterfaces;
2065 mDNSs32 ProbeFailTime;
2066 mDNSu32 NumFailedProbes;
2067 mDNSs32 SuppressProbes;
2068
2069 // unicast-specific data
2070 uDNS_GlobalInfo uDNS_info;
2071
2072 // Fixed storage, to avoid creating large objects on the stack
2073 DNSMessage imsg; // Incoming message received from wire
2074 DNSMessage omsg; // Outgoing message we're building
2075 LargeCacheRecord rec; // Resource Record extracted from received message
2076 };
2077
2078 #define FORALL_CACHERECORDS(SLOT,CG,CR) \
2079 for ((SLOT) = 0; (SLOT) < CACHE_HASH_SLOTS; (SLOT)++) \
2080 for((CG)=m->rrcache_hash[(SLOT)]; (CG); (CG)=(CG)->next) \
2081 for ((CR) = (CG)->members; (CR); (CR)=(CR)->next)
2082
2083 // ***************************************************************************
2084 #if 0
2085 #pragma mark - Useful Static Constants
2086 #endif
2087
2088 extern const mDNSIPPort zeroIPPort;
2089 extern const mDNSv4Addr zerov4Addr;
2090 extern const mDNSv6Addr zerov6Addr;
2091 extern const mDNSEthAddr zeroEthAddr;
2092 extern const mDNSv4Addr onesIPv4Addr;
2093 extern const mDNSv6Addr onesIPv6Addr;
2094 extern const mDNSAddr zeroAddr;
2095
2096 extern const mDNSInterfaceID mDNSInterface_Any; // Zero
2097 extern const mDNSInterfaceID mDNSInterface_LocalOnly; // Special value
2098
2099 extern const mDNSIPPort UnicastDNSPort;
2100 extern const mDNSIPPort MulticastDNSPort;
2101 extern const mDNSv4Addr AllDNSAdminGroup;
2102 extern const mDNSv4Addr AllDNSLinkGroupv4;
2103 extern const mDNSv6Addr AllDNSLinkGroupv6;
2104 extern const mDNSAddr AllDNSLinkGroup_v4;
2105 extern const mDNSAddr AllDNSLinkGroup_v6;
2106
2107 extern const mDNSOpaque16 zeroID;
2108 extern const mDNSOpaque16 QueryFlags;
2109 extern const mDNSOpaque16 ResponseFlags;
2110 extern const mDNSOpaque16 UpdateReqFlags;
2111 extern const mDNSOpaque16 UpdateRespFlags;
2112
2113 #define localdomain (*(const domainname *)"\x5local")
2114 #define LocalReverseMapomain (*(const domainname *)"\x3" "254" "\x3" "169" "\x7" "in-addr" "\x4" "arpa")
2115
2116 // ***************************************************************************
2117 #if 0
2118 #pragma mark - Inline functions
2119 #endif
2120
2121 #if (defined(_MSC_VER))
2122 #define mDNSinline static __inline
2123 #elif ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
2124 #define mDNSinline static inline
2125 #endif
2126
2127 // If we're not doing inline functions, then this header needs to have the extern declarations
2128 #if !defined(mDNSinline)
2129 extern mDNSs32 NonZeroTime(mDNSs32 t);
2130 extern mDNSu16 mDNSVal16(mDNSOpaque16 x);
2131 extern mDNSu32 mDNSVal32(mDNSOpaque32 x);
2132 extern mDNSOpaque16 mDNSOpaque16fromIntVal(mDNSu16 v);
2133 extern mDNSOpaque32 mDNSOpaque32fromIntVal(mDNSu32 v);
2134 #endif
2135
2136 // If we're compiling the particular C file that instantiates our inlines, then we
2137 // define "mDNSinline" (to empty string) so that we generate code in the following section
2138 #if (!defined(mDNSinline) && mDNS_InstantiateInlines)
2139 #define mDNSinline
2140 #endif
2141
2142 #ifdef mDNSinline
2143
2144 mDNSinline mDNSs32 NonZeroTime(mDNSs32 t) { if (t) return(t); else return(1); }
2145
2146 mDNSinline mDNSu16 mDNSVal16(mDNSOpaque16 x) { return((mDNSu16)((mDNSu16)x.b[0] << 8 | (mDNSu16)x.b[1])); }
2147 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])); }
2148
2149 mDNSinline mDNSOpaque16 mDNSOpaque16fromIntVal(mDNSu16 v)
2150 {
2151 mDNSOpaque16 x;
2152 x.b[0] = (mDNSu8)(v >> 8);
2153 x.b[1] = (mDNSu8)(v & 0xFF);
2154 return(x);
2155 }
2156
2157 mDNSinline mDNSOpaque32 mDNSOpaque32fromIntVal(mDNSu32 v)
2158 {
2159 mDNSOpaque32 x;
2160 x.b[0] = (mDNSu8) (v >> 24) ;
2161 x.b[1] = (mDNSu8)((v >> 16) & 0xFF);
2162 x.b[2] = (mDNSu8)((v >> 8 ) & 0xFF);
2163 x.b[3] = (mDNSu8)((v ) & 0xFF);
2164 return x;
2165 }
2166
2167 #endif
2168
2169 // ***************************************************************************
2170 #if 0
2171 #pragma mark - Main Client Functions
2172 #endif
2173
2174 // Every client should call mDNS_Init, passing in storage for the mDNS object and the mDNS_PlatformSupport object.
2175 //
2176 // Clients that are only advertising services should use mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize.
2177 // Clients that plan to perform queries (mDNS_StartQuery, mDNS_StartBrowse, mDNS_StartResolveService, etc.)
2178 // need to provide storage for the resource record cache, or the query calls will return 'mStatus_NoCache'.
2179 // The rrcachestorage parameter is the address of memory for the resource record cache, and
2180 // the rrcachesize parameter is the number of entries in the CacheRecord array passed in.
2181 // (i.e. the size of the cache memory needs to be sizeof(CacheRecord) * rrcachesize).
2182 // OS X 10.3 Panther uses an initial cache size of 64 entries, and then mDNSCore sends an
2183 // mStatus_GrowCache message if it needs more.
2184 //
2185 // Most clients should use mDNS_Init_AdvertiseLocalAddresses. This causes mDNSCore to automatically
2186 // create the correct address records for all the hosts interfaces. If you plan to advertise
2187 // services being offered by the local machine, this is almost always what you want.
2188 // There are two cases where you might use mDNS_Init_DontAdvertiseLocalAddresses:
2189 // 1. A client-only device, that browses for services but doesn't advertise any of its own.
2190 // 2. A proxy-registration service, that advertises services being offered by other machines, and takes
2191 // the appropriate steps to manually create the correct address records for those other machines.
2192 // In principle, a proxy-like registration service could manually create address records for its own machine too,
2193 // but this would be pointless extra effort when using mDNS_Init_AdvertiseLocalAddresses does that for you.
2194 //
2195 // When mDNS has finished setting up the client's callback is called
2196 // A client can also spin and poll the mDNSPlatformStatus field to see when it changes from mStatus_Waiting to mStatus_NoError
2197 //
2198 // Call mDNS_Close to tidy up before exiting
2199 //
2200 // Call mDNS_Register with a completed AuthRecord object to register a resource record
2201 // If the resource record type is kDNSRecordTypeUnique (or kDNSknownunique) then if a conflicting resource record is discovered,
2202 // the resource record's mDNSRecordCallback will be called with error code mStatus_NameConflict. The callback should deregister
2203 // the record, and may then try registering the record again after picking a new name (e.g. by automatically appending a number).
2204 // Following deregistration, the RecordCallback will be called with result mStatus_MemFree to signal that it is safe to deallocate
2205 // the record's storage (memory must be freed asynchronously to allow for goodbye packets and dynamic update deregistration).
2206 //
2207 // Call mDNS_StartQuery to initiate a query. mDNS will proceed to issue Multicast DNS query packets, and any time a response
2208 // is received containing a record which matches the question, the DNSQuestion's mDNSAnswerCallback function will be called
2209 // Call mDNS_StopQuery when no more answers are required
2210 //
2211 // Care should be taken on multi-threaded or interrupt-driven environments.
2212 // The main mDNS routines call mDNSPlatformLock() on entry and mDNSPlatformUnlock() on exit;
2213 // each platform layer needs to implement these appropriately for its respective platform.
2214 // For example, if the support code on a particular platform implements timer callbacks at interrupt time, then
2215 // mDNSPlatformLock/Unlock need to disable interrupts or do similar concurrency control to ensure that the mDNS
2216 // code is not entered by an interrupt-time timer callback while in the middle of processing a client call.
2217
2218 extern mStatus mDNS_Init (mDNS *const m, mDNS_PlatformSupport *const p,
2219 CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
2220 mDNSBool AdvertiseLocalAddresses,
2221 mDNSCallback *Callback, void *Context);
2222 // See notes above on use of NoCache/ZeroCacheSize
2223 #define mDNS_Init_NoCache mDNSNULL
2224 #define mDNS_Init_ZeroCacheSize 0
2225 // See notes above on use of Advertise/DontAdvertiseLocalAddresses
2226 #define mDNS_Init_AdvertiseLocalAddresses mDNStrue
2227 #define mDNS_Init_DontAdvertiseLocalAddresses mDNSfalse
2228 #define mDNS_Init_NoInitCallback mDNSNULL
2229 #define mDNS_Init_NoInitCallbackContext mDNSNULL
2230
2231 extern void mDNS_GrowCache (mDNS *const m, CacheEntity *storage, mDNSu32 numrecords);
2232 extern void mDNS_Close (mDNS *const m);
2233 extern mDNSs32 mDNS_Execute (mDNS *const m);
2234
2235 extern mStatus mDNS_Register (mDNS *const m, AuthRecord *const rr);
2236 extern mStatus mDNS_Update (mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
2237 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback);
2238 extern mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr);
2239
2240 extern mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question);
2241 extern mStatus mDNS_StopQuery (mDNS *const m, DNSQuestion *const question);
2242 extern mStatus mDNS_Reconfirm (mDNS *const m, CacheRecord *const cacherr);
2243 extern mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr);
2244 extern mDNSs32 mDNS_TimeNow(const mDNS *const m);
2245
2246 // ***************************************************************************
2247 #if 0
2248 #pragma mark - Platform support functions that are accessible to the client layer too
2249 #endif
2250
2251 extern mDNSs32 mDNSPlatformOneSecond;
2252
2253 // ***************************************************************************
2254 #if 0
2255 #pragma mark - General utility and helper functions
2256 #endif
2257
2258 // mDNS_RegisterService is a single call to register the set of resource records associated with a given named service.
2259 //
2260 // mDNS_StartResolveService is single call which is equivalent to multiple calls to mDNS_StartQuery,
2261 // to find the IP address, port number, and demultiplexing information for a given named service.
2262 // As with mDNS_StartQuery, it executes asynchronously, and calls the ServiceInfoQueryCallback when the answer is
2263 // found. After the service is resolved, the client should call mDNS_StopResolveService to complete the transaction.
2264 // The client can also call mDNS_StopResolveService at any time to abort the transaction.
2265 //
2266 // mDNS_AddRecordToService adds an additional record to a Service Record Set. This record may be deregistered
2267 // via mDNS_RemoveRecordFromService, or by deregistering the service. mDNS_RemoveRecordFromService is passed a
2268 // callback to free the memory associated with the extra RR when it is safe to do so. The ExtraResourceRecord
2269 // object can be found in the record's context pointer.
2270
2271 // mDNS_GetBrowseDomains is a special case of the mDNS_StartQuery call, where the resulting answers
2272 // are a list of PTR records indicating (in the rdata) domains that are recommended for browsing.
2273 // After getting the list of domains to browse, call mDNS_StopQuery to end the search.
2274 // mDNS_GetDefaultBrowseDomain returns the name of the domain that should be highlighted by default.
2275 //
2276 // mDNS_GetRegistrationDomains and mDNS_GetDefaultRegistrationDomain are the equivalent calls to get the list
2277 // of one or more domains that should be offered to the user as choices for where they may register their service,
2278 // and the default domain in which to register in the case where the user has made no selection.
2279
2280 extern void mDNS_SetupResourceRecord(AuthRecord *rr, RData *RDataStorage, mDNSInterfaceID InterfaceID,
2281 mDNSu16 rrtype, mDNSu32 ttl, mDNSu8 RecordType, mDNSRecordCallback Callback, void *Context);
2282
2283 extern mStatus mDNS_RegisterService (mDNS *const m, ServiceRecordSet *sr,
2284 const domainlabel *const name, const domainname *const type, const domainname *const domain,
2285 const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
2286 AuthRecord *SubTypes, mDNSu32 NumSubTypes,
2287 const mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context);
2288 extern mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl);
2289 extern mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, mDNSRecordCallback MemFreeCallback, void *Context);
2290 extern mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname);
2291 extern mStatus mDNS_DeregisterService(mDNS *const m, ServiceRecordSet *sr);
2292
2293 extern mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
2294 const domainlabel *const name, const domainname *const type, const domainname *const domain,
2295 const domainname *const host,
2296 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context);
2297 #define mDNS_DeregisterNoSuchService mDNS_Deregister
2298
2299 extern mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
2300 const domainname *const srv, const domainname *const domain,
2301 const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context);
2302 #define mDNS_StopBrowse mDNS_StopQuery
2303
2304 extern mStatus mDNS_StartResolveService(mDNS *const m, ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context);
2305 extern void mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *query);
2306
2307 typedef enum
2308 {
2309 mDNS_DomainTypeBrowse = 0,
2310 mDNS_DomainTypeBrowseDefault = 1,
2311 mDNS_DomainTypeBrowseLegacy = 2,
2312 mDNS_DomainTypeRegistration = 3,
2313 mDNS_DomainTypeRegistrationDefault = 4,
2314
2315 mDNS_DomainTypeMax = 4
2316 } mDNS_DomainType;
2317
2318 extern const char *const mDNS_DomainTypeNames[];
2319
2320 extern mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
2321 const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context);
2322 #define mDNS_StopGetDomains mDNS_StopQuery
2323 extern mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr, mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname);
2324 #define mDNS_StopAdvertiseDomains mDNS_Deregister
2325
2326 // ***************************************************************************
2327 #if 0
2328 #pragma mark - DNS name utility functions
2329 #endif
2330
2331 // In order to expose the full capabilities of the DNS protocol (which allows any arbitrary eight-bit values
2332 // in domain name labels, including unlikely characters like ascii nulls and even dots) all the mDNS APIs
2333 // work with DNS's native length-prefixed strings. For convenience in C, the following utility functions
2334 // are provided for converting between C's null-terminated strings and DNS's length-prefixed strings.
2335
2336 // Assignment
2337 // A simple C structure assignment of a domainname can cause a protection fault by accessing unmapped memory,
2338 // because that object is defined to be 256 bytes long, but not all domainname objects are truly the full size.
2339 // This macro uses mDNSPlatformMemCopy() to make sure it only touches the actual bytes that are valid.
2340 #define AssignDomainName(DST, SRC) mDNSPlatformMemCopy((SRC)->c, (DST)->c, DomainNameLength((SRC)))
2341
2342 // Comparison functions
2343 extern mDNSBool SameDomainLabel(const mDNSu8 *a, const mDNSu8 *b);
2344 extern mDNSBool SameDomainName(const domainname *const d1, const domainname *const d2);
2345 extern mDNSBool IsLocalDomain(const domainname *d); // returns true for domains that by default should be looked up using link-local multicast
2346
2347 // Get total length of domain name, in native DNS format, including terminal root label
2348 // (e.g. length of "com." is 5 (length byte, three data bytes, final zero)
2349 extern mDNSu16 DomainNameLength(const domainname *const name);
2350
2351 // Append functions to append one or more labels to an existing native format domain name:
2352 // AppendLiteralLabelString adds a single label from a literal C string, with no escape character interpretation.
2353 // AppendDNSNameString adds zero or more labels from a C string using conventional DNS dots-and-escaping interpretation
2354 // AppendDomainLabel adds a single label from a native format domainlabel
2355 // AppendDomainName adds zero or more labels from a native format domainname
2356 extern mDNSu8 *AppendLiteralLabelString(domainname *const name, const char *cstr);
2357 extern mDNSu8 *AppendDNSNameString (domainname *const name, const char *cstr);
2358 extern mDNSu8 *AppendDomainLabel (domainname *const name, const domainlabel *const label);
2359 extern mDNSu8 *AppendDomainName (domainname *const name, const domainname *const append);
2360
2361 // Convert from null-terminated string to native DNS format:
2362 // The DomainLabel form makes a single label from a literal C string, with no escape character interpretation.
2363 // The DomainName form makes native format domain name from a C string using conventional DNS interpretation:
2364 // dots separate labels, and within each label, '\.' represents a literal dot, '\\' represents a literal
2365 // backslash and backslash with three decimal digits (e.g. \000) represents an arbitrary byte value.
2366 extern mDNSBool MakeDomainLabelFromLiteralString(domainlabel *const label, const char *cstr);
2367 extern mDNSu8 *MakeDomainNameFromDNSNameString (domainname *const name, const char *cstr);
2368
2369 // Convert native format domainlabel or domainname back to C string format
2370 // IMPORTANT:
2371 // When using ConvertDomainLabelToCString, the target buffer must be MAX_ESCAPED_DOMAIN_LABEL (254) bytes long
2372 // to guarantee there will be no buffer overrun. It is only safe to use a buffer shorter than this in rare cases
2373 // where the label is known to be constrained somehow (for example, if the label is known to be either "_tcp" or "_udp").
2374 // Similarly, when using ConvertDomainNameToCString, the target buffer must be MAX_ESCAPED_DOMAIN_NAME (1005) bytes long.
2375 // See definitions of MAX_ESCAPED_DOMAIN_LABEL and MAX_ESCAPED_DOMAIN_NAME for more detailed explanation.
2376 extern char *ConvertDomainLabelToCString_withescape(const domainlabel *const name, char *cstr, char esc);
2377 #define ConvertDomainLabelToCString_unescaped(D,C) ConvertDomainLabelToCString_withescape((D), (C), 0)
2378 #define ConvertDomainLabelToCString(D,C) ConvertDomainLabelToCString_withescape((D), (C), '\\')
2379 extern char *ConvertDomainNameToCString_withescape(const domainname *const name, char *cstr, char esc);
2380 #define ConvertDomainNameToCString_unescaped(D,C) ConvertDomainNameToCString_withescape((D), (C), 0)
2381 #define ConvertDomainNameToCString(D,C) ConvertDomainNameToCString_withescape((D), (C), '\\')
2382
2383 extern void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name[], domainlabel *const hostlabel);
2384
2385 extern mDNSu8 *ConstructServiceName(domainname *const fqdn, const domainlabel *name, const domainname *type, const domainname *const domain);
2386 extern mDNSBool DeconstructServiceName(const domainname *const fqdn, domainlabel *const name, domainname *const type, domainname *const domain);
2387
2388 // Note: Some old functions have been replaced by more sensibly-named versions.
2389 // You can uncomment the hash-defines below if you don't want to have to change your source code right away.
2390 // When updating your code, note that (unlike the old versions) *all* the new routines take the target object
2391 // as their first parameter.
2392 //#define ConvertCStringToDomainName(SRC,DST) MakeDomainNameFromDNSNameString((DST),(SRC))
2393 //#define ConvertCStringToDomainLabel(SRC,DST) MakeDomainLabelFromLiteralString((DST),(SRC))
2394 //#define AppendStringLabelToName(DST,SRC) AppendLiteralLabelString((DST),(SRC))
2395 //#define AppendStringNameToName(DST,SRC) AppendDNSNameString((DST),(SRC))
2396 //#define AppendDomainLabelToName(DST,SRC) AppendDomainLabel((DST),(SRC))
2397 //#define AppendDomainNameToName(DST,SRC) AppendDomainName((DST),(SRC))
2398
2399 // ***************************************************************************
2400 #if 0
2401 #pragma mark - Other utility functions and macros
2402 #endif
2403
2404 extern mDNSu32 mDNS_vsnprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, va_list arg);
2405 extern mDNSu32 mDNS_snprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, ...) IS_A_PRINTF_STYLE_FUNCTION(3,4);
2406 extern mDNSu32 NumCacheRecordsForInterfaceID(const mDNS *const m, mDNSInterfaceID id);
2407 extern char *DNSTypeName(mDNSu16 rrtype);
2408 extern char *GetRRDisplayString_rdb(const ResourceRecord *rr, RDataBody *rd, char *buffer);
2409 #define RRDisplayString(m, rr) GetRRDisplayString_rdb(rr, &(rr)->rdata->u, (m)->MsgBuffer)
2410 #define ARDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
2411 #define CRDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
2412 extern mDNSBool mDNSSameAddress(const mDNSAddr *ip1, const mDNSAddr *ip2);
2413 extern void IncrementLabelSuffix(domainlabel *name, mDNSBool RichText);
2414 extern mDNSBool IsPrivateV4Addr(mDNSAddr *addr); // returns true for RFC1918 private addresses
2415
2416 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
2417 #define mDNSSameIPv6Address(A,B) ((A).l[0] == (B).l[0] && (A).l[1] == (B).l[1] && (A).l[2] == (B).l[2] && (A).l[3] == (B).l[3])
2418 #define mDNSSameEthAddress(A,B) ((A)->w[0] == (B)->w[0] && (A)->w[1] == (B)->w[1] && (A)->w[2] == (B)->w[2])
2419
2420 #define mDNSIPv4AddressIsZero(A) mDNSSameIPv4Address((A), zerov4Addr)
2421 #define mDNSIPv6AddressIsZero(A) mDNSSameIPv6Address((A), zerov6Addr)
2422
2423 #define mDNSIPv4AddressIsOnes(A) mDNSSameIPv4Address((A), onesIPv4Addr)
2424 #define mDNSIPv6AddressIsOnes(A) mDNSSameIPv6Address((A), onesIPv6Addr)
2425
2426 #define mDNSAddressIsAllDNSLinkGroup(X) ( \
2427 ((X)->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address((X)->ip.v4, AllDNSLinkGroupv4)) || \
2428 ((X)->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address((X)->ip.v6, AllDNSLinkGroupv6)) )
2429
2430 #define mDNSAddressIsZero(X) ( \
2431 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4)) || \
2432 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6)) )
2433
2434 #define mDNSAddressIsValidNonZero(X) ( \
2435 ((X)->type == mDNSAddrType_IPv4 && !mDNSIPv4AddressIsZero((X)->ip.v4)) || \
2436 ((X)->type == mDNSAddrType_IPv6 && !mDNSIPv6AddressIsZero((X)->ip.v6)) )
2437
2438 #define mDNSAddressIsOnes(X) ( \
2439 ((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4)) || \
2440 ((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6)) )
2441
2442 #define mDNSAddressIsValid(X) ( \
2443 ((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) : \
2444 ((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
2445
2446
2447 // ***************************************************************************
2448 #if 0
2449 #pragma mark - Authentication Support
2450 #endif
2451
2452 #define HMAC_LEN 64
2453 #define HMAC_IPAD 0x36
2454 #define HMAC_OPAD 0x5c
2455 #define MD5_LEN 16
2456
2457 // padded keys for inned/outer hash rounds
2458 typedef struct
2459 {
2460 mDNSu8 ipad[HMAC_LEN];
2461 mDNSu8 opad[HMAC_LEN];
2462 } HMAC_Key;
2463
2464 // Internal data structure to maintain authentication information for an update domain
2465 typedef struct uDNS_AuthInfo
2466 {
2467 domainname zone;
2468 domainname keyname;
2469 HMAC_Key key;
2470 struct uDNS_AuthInfo *next;
2471 } uDNS_AuthInfo;
2472
2473 // Unicast DNS and Dynamic Update specific Client Calls
2474 //
2475 // mDNS_SetSecretForZone tells the core to authenticate (via TSIG with an HMAC_MD5 hash of the shared secret)
2476 // when dynamically updating a given zone (and its subdomains). The key used in authentication must be in
2477 // domain name format. The shared secret must be a base64 encoded string with the base64 parameter set to
2478 // true, or binary data with the base64 parameter set to false. The length is the size of the secret in
2479 // bytes. (A minimum size of 16 bytes (128 bits) is recommended for an MD5 hash as per RFC 2485).
2480 // Calling this routine multiple times for a zone replaces previously entered values. Call with a NULL key
2481 // to dissable authentication for the zone.
2482
2483 extern mStatus mDNS_SetSecretForZone(mDNS *m, const domainname *zone, const domainname *key, const char *sharedSecret, mDNSu32 ssLen, mDNSBool base64);
2484
2485 // Hostname/Unicast Interface Configuration
2486
2487 // All hostnames advertised point to a single IP address, set via SetPrimaryInterfaceInfo. Invoking this routine
2488 // updates all existing hostnames to point to the new address.
2489
2490 // A hostname is added via AddDynDNSHostName, which points to the primary interface's IP address.
2491
2492 // The status callback is invoked to convey success or failure codes - the callback should not modify the AuthRecord or free memory.
2493 // Added hostnames may be removed (deregistered) via mDNS_RemoveDynDNSHostName.
2494
2495 // Host domains added prior to specification of the primary interface address and computer name will be deferred until
2496 // these values are initialized.
2497
2498 // When routable V4 interfaces are added or removed, mDNS_UpdateLLQs should be called to re-estabish LLQs in case the
2499 // destination address for events (i.e. the route) has changed. For performance reasons, the caller is responsible for
2500 // batching changes, e.g. calling the routine only once if multiple interfaces are simultanously removed or added.
2501
2502 // DNS servers used to resolve unicast queries are specified by mDNS_AddDNSServer, and may later be removed via mDNS_DeleteDNSServers.
2503 // For "split" DNS configurations, in which queries for different domains are sent to different servers (e.g. VPN and external),
2504 // a domain may be associated with a DNS server. For standard configurations, specify the root label (".") or NULL.
2505
2506 extern void mDNS_AddDynDNSHostName(mDNS *m, const domainname *fqdn, mDNSRecordCallback *StatusCallback, const void *StatusContext);
2507 extern void mDNS_RemoveDynDNSHostName(mDNS *m, const domainname *fqdn);
2508 extern void mDNS_SetPrimaryInterfaceInfo(mDNS *m, const mDNSAddr *addr, const mDNSAddr *router);
2509 extern void mDNS_UpdateLLQs(mDNS *m);
2510 extern void mDNS_AddDNSServer(mDNS *const m, const mDNSAddr *dnsAddr, const domainname *domain);
2511 extern void mDNS_DeleteDNSServers(mDNS *const m);
2512
2513 // Routines called by the core, exported by DNSDigest.c
2514
2515 // Convert a base64 encoded key into a binary byte stream
2516 extern mDNSs32 DNSDigest_Base64ToBin(const char *src, mDNSu8 *target, mDNSu32 targsize);
2517
2518 // Convert an arbitrary binary key (of any length) into an HMAC key (stored in AuthInfo struct)
2519 extern void DNSDigest_ConstructHMACKey(uDNS_AuthInfo *info, const mDNSu8 *key, mDNSu32 len);
2520
2521 // sign a DNS message. The message must be compete, with all values in network byte order. end points to the end
2522 // of the message, and is modified by this routine. numAdditionals is a pointer to the number of additional
2523 // records in HOST byte order, which is incremented upon successful completion of this routine. The function returns
2524 // the new end pointer on success, and NULL on failure.
2525 extern mDNSu8 *DNSDigest_SignMessage(DNSMessage *msg, mDNSu8 **end, mDNSu16 *numAdditionals, uDNS_AuthInfo *info);
2526
2527 // ***************************************************************************
2528 #if 0
2529 #pragma mark - PlatformSupport interface
2530 #endif
2531
2532 // This section defines the interface to the Platform Support layer.
2533 // Normal client code should not use any of types defined here, or directly call any of the functions defined here.
2534 // The definitions are placed here because sometimes clients do use these calls indirectly, via other supported client operations.
2535 // For example, AssignDomainName is a macro defined using mDNSPlatformMemCopy()
2536
2537 // Every platform support module must provide the following functions.
2538 // mDNSPlatformInit() typically opens a communication endpoint, and starts listening for mDNS packets.
2539 // When Setup is complete, the platform support layer calls mDNSCoreInitComplete().
2540 // mDNSPlatformSendUDP() sends one UDP packet
2541 // When a packet is received, the PlatformSupport code calls mDNSCoreReceive()
2542 // mDNSPlatformClose() tidies up on exit
2543 //
2544 // Note: mDNSPlatformMemAllocate/mDNSPlatformMemFree are only required for handling oversized resource records and unicast DNS.
2545 // If your target platform has a well-defined specialized application, and you know that all the records it uses
2546 // are InlineCacheRDSize or less, then you can just make a simple mDNSPlatformMemAllocate() stub that always returns
2547 // NULL. InlineCacheRDSize is a compile-time constant, which is set by default to 64. If you need to handle records
2548 // a little larger than this and you don't want to have to implement run-time allocation and freeing, then you
2549 // can raise the value of this constant to a suitable value (at the expense of increased memory usage).
2550 //
2551 // USE CAUTION WHEN CALLING mDNSPlatformRawTime: The m->timenow_adjust correction factor needs to be added
2552 // Generally speaking:
2553 // Code that's protected by the main mDNS lock should just use the m->timenow value
2554 // Code outside the main mDNS lock should use mDNS_TimeNow(m) to get properly adjusted time
2555 //
2556 // mDNSPlatformUTC returns the time, in seconds, since Jan 1st 1970 UTC and is required for generating TSIG records
2557
2558 extern mStatus mDNSPlatformInit (mDNS *const m);
2559 extern void mDNSPlatformClose (mDNS *const m);
2560 extern mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
2561 mDNSInterfaceID InterfaceID, const mDNSAddr *dst, mDNSIPPort dstport);
2562
2563 extern void mDNSPlatformLock (const mDNS *const m);
2564 extern void mDNSPlatformUnlock (const mDNS *const m);
2565
2566 extern void mDNSPlatformStrCopy (const void *src, void *dst);
2567 extern mDNSu32 mDNSPlatformStrLen (const void *src);
2568 extern void mDNSPlatformMemCopy (const void *src, void *dst, mDNSu32 len);
2569 extern mDNSBool mDNSPlatformMemSame (const void *src, const void *dst, mDNSu32 len);
2570 extern void mDNSPlatformMemZero ( void *dst, mDNSu32 len);
2571 extern void * mDNSPlatformMemAllocate (mDNSu32 len);
2572 extern void mDNSPlatformMemFree (void *mem);
2573 extern mDNSu32 mDNSPlatformRandomSeed (void);
2574 extern mStatus mDNSPlatformTimeInit (void);
2575 extern mDNSs32 mDNSPlatformRawTime (void);
2576 extern mDNSs32 mDNSPlatformUTC (void);
2577
2578 // Platform support modules should provide the following functions to map between opaque interface IDs
2579 // and interface indexes in order to support the DNS-SD API. If your target platform does not support
2580 // multiple interfaces and/or does not support the DNS-SD API, these functions can be empty.
2581 extern mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(const mDNS *const m, mDNSu32 index);
2582 extern mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(const mDNS *const m, mDNSInterfaceID id);
2583
2584 // Every platform support module must provide the following functions if it is to support unicast DNS
2585 // and Dynamic Update.
2586 // All TCP socket operations implemented by the platform layer MUST NOT BLOCK.
2587 // mDNSPlatformTCPConnect initiates a TCP connection with a peer, adding the socket descriptor to the
2588 // main event loop. The return value indicates whether the connection succeeded, failed, or is pending
2589 // (i.e. the call would block.) On return, the descriptor parameter is set to point to the connected socket.
2590 // The TCPConnectionCallback is subsequently invoked when the connection
2591 // completes (in which case the ConnectionEstablished parameter is true), or data is available for
2592 // reading on the socket (indicated by the ConnectionEstablished parameter being false.) If the connection
2593 // asynchronously fails, the TCPConnectionCallback should be invoked as usual, with the error being
2594 // returned in subsequent calls to PlatformReadTCP or PlatformWriteTCP. (This allows for platforms
2595 // with limited asynchronous error detection capabilities.) PlatformReadTCP and PlatformWriteTCP must
2596 // return the number of bytes read/written, 0 if the call would block, and -1 if an error.
2597 // PlatformTCPCloseConnection must close the connection to the peer and remove the descriptor from the
2598 // event loop. CloseConnectin may be called at any time, including in a ConnectionCallback.
2599
2600 typedef void (*TCPConnectionCallback)(int sd, void *context, mDNSBool ConnectionEstablished);
2601 extern mStatus mDNSPlatformTCPConnect(const mDNSAddr *dst, mDNSOpaque16 dstport, mDNSInterfaceID InterfaceID,
2602 TCPConnectionCallback callback, void *context, int *descriptor);
2603 extern void mDNSPlatformTCPCloseConnection(int sd);
2604 extern int mDNSPlatformReadTCP(int sd, void *buf, int buflen);
2605 extern int mDNSPlatformWriteTCP(int sd, const char *msg, int len);
2606
2607 // Platforms that support unicast browsing and dynamic update registration for clients who do not specify a domain
2608 // in browse/registration calls must implement these routines to get the "default" browse/registration list.
2609 // The Get() functions must return a linked list of DNameListElem structs, allocated via mDNSPlatformMemAllocate.
2610 // Platforms may implement the Get() calls via the mDNS_CopyDNameList() helper routine.
2611 // Callers should free lists obtained via the Get() calls with th mDNS_FreeDNameList routine, provided by the core.
2612
2613 typedef struct DNameListElem
2614 {
2615 domainname name;
2616 struct DNameListElem *next;
2617 } DNameListElem;
2618
2619 extern DNameListElem *mDNSPlatformGetSearchDomainList(void);
2620 extern DNameListElem *mDNSPlatformGetRegDomainList(void);
2621
2622 // Helper functions provided by the core
2623 extern DNameListElem *mDNS_CopyDNameList(const DNameListElem *orig);
2624 extern void mDNS_FreeDNameList(DNameListElem *list);
2625
2626 #ifdef _LEGACY_NAT_TRAVERSAL_
2627 // Support for legacy NAT traversal protocols, implemented by the platform layer and callable by the core.
2628
2629 #define DYN_PORT_MIN 49152 // ephemeral port range
2630 #define DYN_PORT_MAX 65535
2631 #define LEGACY_NATMAP_MAX_TRIES 4 // if our desired mapping is taken, how many times we try mapping to a random port
2632
2633 extern mStatus LNT_GetPublicIP(mDNSOpaque32 *ip);
2634 extern mStatus LNT_MapPort(mDNSIPPort priv, mDNSIPPort pub, mDNSBool tcp);
2635 extern mStatus LNT_UnmapPort(mDNSIPPort PubPort, mDNSBool tcp);
2636 #endif // _LEGACY_NAT_TRAVERSAL_
2637
2638 // The core mDNS code provides these functions, for the platform support code to call at appropriate times
2639 //
2640 // mDNS_SetFQDN() is called once on startup (typically from mDNSPlatformInit())
2641 // and then again on each subsequent change of the host name.
2642 //
2643 // mDNS_RegisterInterface() is used by the platform support layer to inform mDNSCore of what
2644 // physical and/or logical interfaces are available for sending and receiving packets.
2645 // Typically it is called on startup for each available interface, but register/deregister may be
2646 // called again later, on multiple occasions, to inform the core of interface configuration changes.
2647 // If set->Advertise is set non-zero, then mDNS_RegisterInterface() also registers the standard
2648 // resource records that should be associated with every publicised IP address/interface:
2649 // -- Name-to-address records (A/AAAA)
2650 // -- Address-to-name records (PTR)
2651 // -- Host information (HINFO)
2652 // IMPORTANT: The specified mDNSInterfaceID MUST NOT be 0, -1, or -2; these values have special meaning
2653 // mDNS_RegisterInterface does not result in the registration of global hostnames via dynamic update -
2654 // see mDNS_SetPrimaryInterfaceInfo, mDNS_AddDynDNSHostName, etc. for this purpose.
2655 // Note that the set may be deallocated immediately after it is deregistered via mDNS_DeegisterInterface.
2656 //
2657 // mDNS_RegisterDNS() is used by the platform support layer to provide the core with the addresses of
2658 // available domain name servers for unicast queries/updates. RegisterDNS() should be called once for
2659 // each name server, typically at startup, or when a new name server becomes available. DeregiterDNS()
2660 // must be called whenever a registered name server becomes unavailable. DeregisterDNSList deregisters
2661 // all registered servers. mDNS_DNSRegistered() returns true if one or more servers are registered in the core.
2662 //
2663 // mDNSCoreInitComplete() is called when the platform support layer is finished.
2664 // Typically this is at the end of mDNSPlatformInit(), but may be later
2665 // (on platforms like OT that allow asynchronous initialization of the networking stack).
2666 //
2667 // mDNSCoreReceive() is called when a UDP packet is received
2668 //
2669 // mDNSCoreMachineSleep() is called when the machine sleeps or wakes
2670 // (This refers to heavyweight laptop-style sleep/wake that disables network access,
2671 // not lightweight second-by-second CPU power management modes.)
2672
2673 extern void mDNS_SetFQDN(mDNS *const m);
2674 extern mStatus mDNS_RegisterInterface (mDNS *const m, NetworkInterfaceInfo *set, mDNSs32 delay);
2675 extern void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set);
2676 extern void mDNSCoreInitComplete(mDNS *const m, mStatus result);
2677 extern void mDNSCoreReceive(mDNS *const m, void *const msg, const mDNSu8 *const end,
2678 const mDNSAddr *const srcaddr, const mDNSIPPort srcport,
2679 const mDNSAddr *const dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID);
2680 extern void mDNSCoreMachineSleep(mDNS *const m, mDNSBool wake);
2681
2682 extern mDNSBool mDNSAddrIsDNSMulticast(const mDNSAddr *ip);
2683
2684 // ***************************************************************************
2685 #if 0
2686 #pragma mark - Compile-Time assertion checks
2687 #endif
2688
2689 // Some C compiler cleverness. We can make the compiler check certain things for
2690 // us, and report compile-time errors if anything is wrong. The usual way to do
2691 // this would be to use a run-time "if" statement, but then you don't find out
2692 // what's wrong until you run the software. This way, if the assertion condition
2693 // is false, the array size is negative, and the complier complains immediately.
2694
2695 struct mDNS_CompileTimeAssertionChecks
2696 {
2697 // Check that the compiler generated our on-the-wire packet format structure definitions
2698 // properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
2699 char assert0[(sizeof(rdataSRV) == 262 ) ? 1 : -1];
2700 char assert1[(sizeof(DNSMessageHeader) == 12 ) ? 1 : -1];
2701 char assert2[(sizeof(DNSMessage) == 12+AbsoluteMaxDNSMessageData) ? 1 : -1];
2702 char assert3[(sizeof(mDNSs8) == 1 ) ? 1 : -1];
2703 char assert4[(sizeof(mDNSu8) == 1 ) ? 1 : -1];
2704 char assert5[(sizeof(mDNSs16) == 2 ) ? 1 : -1];
2705 char assert6[(sizeof(mDNSu16) == 2 ) ? 1 : -1];
2706 char assert7[(sizeof(mDNSs32) == 4 ) ? 1 : -1];
2707 char assert8[(sizeof(mDNSu32) == 4 ) ? 1 : -1];
2708 char assert9[(sizeof(mDNSOpaque16) == 2 ) ? 1 : -1];
2709 char assertA[(sizeof(mDNSOpaque32) == 4 ) ? 1 : -1];
2710 char assertB[(sizeof(mDNSOpaque128) == 16 ) ? 1 : -1];
2711 char assertC[(sizeof(CacheRecord ) >= sizeof(CacheGroup) ) ? 1 : -1];
2712 };
2713
2714 // ***************************************************************************
2715
2716 #ifdef __cplusplus
2717 }
2718 #endif
2719
2720 #endif