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