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