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