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