1/* -*- Mode: C; tab-width: 4 -*- 2 * 3 * Copyright (c) 2003-2006 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 Change History (most recent first): 18 19Log: uds_daemon.c,v $ 20Revision 1.461 2009/06/19 23:15:07 cheshire 21<rdar://problem/6990066> Library: crash at handle_resolve_response + 183 22Made resolve_result_callback code more defensive and improved LogOperation messages 23 24Revision 1.460 2009/05/26 21:31:07 herscher 25Fix compile errors on Windows 26 27Revision 1.459 2009/04/30 20:07:51 mcguire 28<rdar://problem/6822674> Support multiple UDSs from launchd 29 30Revision 1.458 2009/04/25 00:59:06 mcguire 31Change a few stray LogInfo to LogOperation 32 33Revision 1.457 2009/04/22 01:19:57 jessic2 34<rdar://problem/6814585> Daemon: mDNSResponder is logging garbage for error codes because it's using %ld for int 32 35 36Revision 1.456 2009/04/21 01:56:34 jessic2 37<rdar://problem/6803941> BTMM: Back out change for preventing other local users from sending packets to your BTMM machines 38 39Revision 1.455 2009/04/20 19:19:57 cheshire 40<rdar://problem/6803941> BTMM: If multiple local users are logged in to same BTMM account, all but one fail 41Don't need "empty info->u.browser.browsers list" debugging message, now that we expect this to be 42a case that can legitimately happen. 43 44Revision 1.454 2009/04/18 20:56:43 jessic2 45<rdar://problem/6803941> BTMM: If multiple local users are logged in to same BTMM account, all but one fail 46 47Revision 1.453 2009/04/11 00:20:29 jessic2 48<rdar://problem/4426780> Daemon: Should be able to turn on LogOperation dynamically 49 50Revision 1.452 2009/04/07 01:17:42 jessic2 51<rdar://problem/6747917> BTMM: Multiple accounts lets me see others' remote services & send packets to others' remote hosts 52 53Revision 1.451 2009/04/02 22:34:26 jessic2 54<rdar://problem/6305347> Race condition: If fd has already been closed, SO_NOSIGPIPE returns errno 22 (Invalid argument) 55 56Revision 1.450 2009/04/01 21:11:28 herscher 57<rdar://problem/5925472> Current Bonjour code does not compile on Windows. Workaround use of recvmsg. 58 59Revision 1.449 2009/03/17 19:44:25 cheshire 60<rdar://problem/6688927> Don't let negative unicast answers block Multicast DNS responses 61 62Revision 1.448 2009/03/17 04:53:40 cheshire 63<rdar://problem/6688927> Don't let negative unicast answers block Multicast DNS responses 64 65Revision 1.447 2009/03/17 04:41:32 cheshire 66Moved LogOperation message to after check for "if (answer->RecordType == kDNSRecordTypePacketNegative)" 67 68Revision 1.446 2009/03/04 01:47:35 cheshire 69Include m->ProxyRecords in SIGINFO output 70 71Revision 1.445 2009/03/03 23:04:44 cheshire 72For clarity, renamed "MAC" field to "HMAC" (Host MAC, as opposed to Interface MAC) 73 74Revision 1.444 2009/03/03 22:51:55 cheshire 75<rdar://problem/6504236> Sleep Proxy: Waking on same network but different interface will cause conflicts 76 77Revision 1.443 2009/02/27 02:28:41 cheshire 78Need to declare "const AuthRecord *ar;" 79 80Revision 1.442 2009/02/27 00:58:17 cheshire 81Improved detail of SIGINFO logging for m->DuplicateRecords 82 83Revision 1.441 2009/02/24 22:18:59 cheshire 84Include interface name for interface-specific AuthRecords 85 86Revision 1.440 2009/02/21 01:38:08 cheshire 87Added report of m->SleepState value in SIGINFO output 88 89Revision 1.439 2009/02/18 23:38:44 cheshire 90<rdar://problem/6600780> Could not write data to client 13 - aborting connection 91Eliminated unnecessary "request_state *request" field from the reply_state structure. 92 93Revision 1.438 2009/02/18 23:23:14 cheshire 94Cleaned up debugging log messages 95 96Revision 1.437 2009/02/17 23:29:05 cheshire 97Throttle logging to a slower rate when running on SnowLeopard 98 99Revision 1.436 2009/02/13 06:28:02 cheshire 100Converted LogOperation messages to LogInfo 101 102Revision 1.435 2009/02/12 20:57:26 cheshire 103Renamed 'LogAllOperation' switch to 'LogClientOperations'; added new 'LogSleepProxyActions' switch 104 105Revision 1.434 2009/02/12 20:28:31 cheshire 106Added some missing "const" declarations 107 108Revision 1.433 2009/02/10 01:44:39 cheshire 109<rdar://problem/6553729> DNSServiceUpdateRecord fails with kDNSServiceErr_BadReference for otherwise valid reference 110 111Revision 1.432 2009/02/10 01:38:56 cheshire 112Move regservice_termination_callback() earlier in file in preparation for subsequent work 113 114Revision 1.431 2009/02/07 01:48:55 cheshire 115In SIGINFO output include sequence number for proxied records 116 117Revision 1.430 2009/01/31 21:58:05 cheshire 118<rdar://problem/4786302> Implement logic to determine when to send dot-local lookups via Unicast 119Only want to do unicast dot-local lookups for address queries and conventional (RFC 2782) SRV queries 120 121Revision 1.429 2009/01/31 00:45:26 cheshire 122<rdar://problem/4786302> Implement logic to determine when to send dot-local lookups via Unicast 123Further refinements 124 125Revision 1.428 2009/01/30 19:52:31 cheshire 126Eliminated unnecessary duplicated "dnssd_sock_t sd" fields in service_instance and reply_state structures 127 128Revision 1.427 2009/01/24 01:48:43 cheshire 129<rdar://problem/4786302> Implement logic to determine when to send dot-local lookups via Unicast 130 131Revision 1.426 2009/01/16 21:07:08 cheshire 132In SIGINFO "Duplicate Records" list, show expiry time for Sleep Proxy records 133 134Revision 1.425 2009/01/16 20:53:16 cheshire 135Include information about Sleep Proxy records in SIGINFO output 136 137Revision 1.424 2009/01/12 22:43:50 cheshire 138Fixed "unused variable" warning when SO_NOSIGPIPE is not defined 139 140Revision 1.423 2009/01/10 22:54:42 mkrochma 141<rdar://problem/5797544> Fixes from Igor Seleznev to get mdnsd working on Linux 142 143Revision 1.422 2009/01/10 01:52:48 cheshire 144Include DuplicateRecords and LocalOnlyQuestions in SIGINFO output 145 146Revision 1.421 2008/12/17 05:05:26 cheshire 147Fixed alignment of NAT mapping syslog messages 148 149Revision 1.420 2008/12/12 00:52:05 cheshire 150mDNSPlatformSetBPF is now called mDNSPlatformReceiveBPF_fd 151 152Revision 1.419 2008/12/10 02:11:44 cheshire 153ARMv5 compiler doesn't like uncommented stuff after #endif 154 155Revision 1.418 2008/12/09 05:12:53 cheshire 156Updated debugging messages 157 158Revision 1.417 2008/12/04 03:38:12 cheshire 159Miscellaneous defensive coding changes and improvements to debugging log messages 160 161Revision 1.416 2008/12/02 22:02:12 cheshire 162<rdar://problem/6320621> Adding domains after TXT record updates registers stale TXT record data 163 164Revision 1.415 2008/11/26 20:35:59 cheshire 165Changed some "LogOperation" debugging messages to "debugf" 166 167Revision 1.414 2008/11/26 00:02:25 cheshire 168Improved SIGINFO output to list AutoBrowseDomains and AutoRegistrationDomains 169 170Revision 1.413 2008/11/25 04:48:58 cheshire 171Added logging to show whether Sleep Proxy Service is active 172 173Revision 1.412 2008/11/24 23:05:43 cheshire 174Additional checking in uds_validatelists() 175 176Revision 1.411 2008/11/05 21:41:39 cheshire 177Updated LogOperation message 178 179Revision 1.410 2008/11/04 20:06:20 cheshire 180<rdar://problem/6186231> Change MAX_DOMAIN_NAME to 256 181 182Revision 1.409 2008/10/31 23:44:22 cheshire 183Fixed compile error in Posix build 184 185Revision 1.408 2008/10/29 21:32:33 cheshire 186Align "DNSServiceEnumerateDomains ... RESULT" log messages 187 188Revision 1.407 2008/10/27 07:34:36 cheshire 189Additional sanity checks for debugging 190 191Revision 1.406 2008/10/23 23:55:56 cheshire 192Fixed some missing "const" declarations 193 194Revision 1.405 2008/10/23 23:21:31 cheshire 195Moved definition of dnssd_strerror() to be with the definition of dnssd_errno, in dnssd_ipc.h 196 197Revision 1.404 2008/10/23 23:06:17 cheshire 198Removed () from dnssd_errno macro definition -- it's not a function and doesn't need any arguments 199 200Revision 1.403 2008/10/23 22:33:25 cheshire 201Changed "NOTE:" to "Note:" so that BBEdit 9 stops putting those comment lines into the funtion popup menu 202 203Revision 1.402 2008/10/22 19:47:59 cheshire 204Instead of SameRData(), use equivalent IdenticalSameNameRecord() macro 205 206Revision 1.401 2008/10/22 17:20:40 cheshire 207Don't give up if setsockopt SO_NOSIGPIPE fails 208 209Revision 1.400 2008/10/21 01:06:57 cheshire 210Pass BPF fd to mDNSMacOSX.c using mDNSPlatformSetBPF() instead of just writing it into a shared global variable 211 212Revision 1.399 2008/10/20 22:06:42 cheshire 213Updated debugging log messages 214 215Revision 1.398 2008/10/03 18:25:17 cheshire 216Instead of calling "m->MainCallback" function pointer directly, call mDNSCore routine "mDNS_ConfigChanged(m);" 217 218Revision 1.397 2008/10/02 22:26:21 cheshire 219Moved declaration of BPF_fd from uds_daemon.c to mDNSMacOSX.c, where it really belongs 220 221Revision 1.396 2008/09/30 01:04:55 cheshire 222Made BPF code a bit more defensive, to ignore subsequent BPF fds if we get passed more than one 223 224Revision 1.395 2008/09/27 01:28:43 cheshire 225Added code to receive and store BPF fd when passed via a send_bpf message 226 227Revision 1.394 2008/09/23 04:12:40 cheshire 228<rdar://problem/6238774> Remove "local" from the end of _services._dns-sd._udp PTR records 229Added a special-case to massage these new records for Bonjour Browser's benefit 230 231Revision 1.393 2008/09/23 03:01:58 cheshire 232Added operation logging of domain enumeration results 233 234Revision 1.392 2008/09/18 22:30:06 cheshire 235<rdar://problem/6230679> device-info record not removed when last service deregisters 236 237Revision 1.391 2008/09/18 22:05:44 cheshire 238Fixed "DNSServiceRegister ... ADDED" message to have escaping consistent with 239the other DNSServiceRegister operation messages 240 241Revision 1.390 2008/09/16 21:06:56 cheshire 242Improved syslog output to show if q->LongLived flag is set for multicast questions 243 244Revision 1.389 2008/07/25 22:34:11 mcguire 245fix sizecheck issues for 64bit 246 247Revision 1.388 2008/07/01 01:40:02 mcguire 248<rdar://problem/5823010> 64-bit fixes 249 250Revision 1.387 2008/02/26 21:24:13 cheshire 251Fixed spelling mistake in comment 252 253Revision 1.386 2008/02/26 20:23:15 cheshire 254Updated comments 255 256Revision 1.385 2008/02/19 21:50:52 cheshire 257Shortened some overly-long lines 258 259Revision 1.384 2007/12/22 01:38:05 cheshire 260Improve display of "Auth Records" SIGINFO output 261 262Revision 1.383 2007/12/07 00:45:58 cheshire 263<rdar://problem/5526800> BTMM: Need to deregister records and services on shutdown/sleep 264 265Revision 1.382 2007/11/30 20:11:48 cheshire 266Fixed compile warning: declaration of 'remove' shadows a global declaration 267 268Revision 1.381 2007/11/28 22:02:52 cheshire 269Remove pointless "if (!domain)" check (domain is an array on the stack, so its address can never be null) 270 271Revision 1.380 2007/11/28 18:38:41 cheshire 272Fixed typo in log message: "DNSServiceResolver" -> "DNSServiceResolve" 273 274Revision 1.379 2007/11/01 19:32:14 cheshire 275Added "DEBUG_64BIT_SCM_RIGHTS" debugging code 276 277Revision 1.378 2007/10/31 19:21:40 cheshire 278Don't show Expire time for records and services that aren't currently registered 279 280Revision 1.377 2007/10/30 23:48:20 cheshire 281Improved SIGINFO listing of question state 282 283Revision 1.376 2007/10/30 20:43:54 cheshire 284Fixed compiler warning when LogClientOperations is turned off 285 286Revision 1.375 2007/10/26 22:51:38 cheshire 287Improved SIGINFO output to show timers for AuthRecords and ServiceRegistrations 288 289Revision 1.374 2007/10/25 22:45:02 cheshire 290Tidied up code for DNSServiceRegister callback status messages 291 292Revision 1.373 2007/10/25 21:28:43 cheshire 293Add ServiceRegistrations to SIGINFO output 294 295Revision 1.372 2007/10/25 21:21:45 cheshire 296<rdar://problem/5496734> BTMM: Need to retry registrations after failures 297Don't unlink_and_free_service_instance at the first error 298 299Revision 1.371 2007/10/18 23:34:40 cheshire 300<rdar://problem/5532821> Need "considerable burden on the network" warning in uds_daemon.c 301 302Revision 1.370 2007/10/17 18:44:23 cheshire 303<rdar://problem/5539930> Goodbye packets not being sent for services on shutdown 304 305Revision 1.369 2007/10/16 17:18:27 cheshire 306Fixed Posix compile errors 307 308Revision 1.368 2007/10/16 16:58:58 cheshire 309Improved debugging error messages in read_msg() 310 311Revision 1.367 2007/10/15 22:55:14 cheshire 312Make read_msg return "void" (since request_callback just ignores the redundant return value anyway) 313 314Revision 1.366 2007/10/10 00:48:54 cheshire 315<rdar://problem/5526379> Daemon spins in an infinite loop when it doesn't get the control message it's expecting 316 317Revision 1.365 2007/10/06 03:25:23 cheshire 318<rdar://problem/5525267> MacBuddy exits abnormally when clicking "Continue" in AppleConnect pane 319 320Revision 1.364 2007/10/06 03:20:16 cheshire 321Improved LogOperation debugging messages 322 323Revision 1.363 2007/10/05 23:24:52 cheshire 324Improved LogOperation messages about separate error return socket 325 326Revision 1.362 2007/10/05 22:11:58 cheshire 327Improved "send_msg ERROR" debugging message 328 329Revision 1.361 2007/10/04 20:45:18 cheshire 330<rdar://problem/5518381> Race condition in kDNSServiceFlagsShareConnection-mode call handling 331 332Revision 1.360 2007/10/01 23:24:46 cheshire 333SIGINFO output was mislabeling mDNSInterface_Any queries as unicast queries 334 335Revision 1.359 2007/09/30 00:09:27 cheshire 336<rdar://problem/5492315> Pass socket fd via SCM_RIGHTS sendmsg instead of using named UDS in the filesystem 337 338Revision 1.358 2007/09/29 20:08:06 cheshire 339Fixed typo in comment 340 341Revision 1.357 2007/09/27 22:10:04 cheshire 342Add LogOperation line for DNSServiceRegisterRecord callbacks 343 344Revision 1.356 2007/09/26 21:29:30 cheshire 345Improved question list SIGINFO output 346 347Revision 1.355 2007/09/26 01:54:34 mcguire 348Debugging: In SIGINFO output, show ClientTunnel query interval, which is how we determine whether a query is still active 349 350Revision 1.354 2007/09/26 01:26:31 cheshire 351<rdar://problem/5501567> BTMM: mDNSResponder crashes in free_service_instance enabling/disabling BTMM 352Need to call SendServiceRemovalNotification *before* backpointer is cleared 353 354Revision 1.353 2007/09/25 20:46:33 cheshire 355Include DNSServiceRegisterRecord operations in SIGINFO output 356 357Revision 1.352 2007/09/25 20:23:40 cheshire 358<rdar://problem/5501567> BTMM: mDNSResponder crashes in free_service_instance enabling/disabling BTMM 359Need to clear si->request backpointer before calling mDNS_DeregisterService(&mDNSStorage, &si->srs); 360 361Revision 1.351 2007/09/25 18:20:34 cheshire 362Changed name of "free_service_instance" to more accurate "unlink_and_free_service_instance" 363 364Revision 1.350 2007/09/24 23:54:52 mcguire 365Additional list checking in uds_validatelists() 366 367Revision 1.349 2007/09/24 06:01:00 cheshire 368Debugging: In SIGINFO output, show NAT Traversal time values in seconds rather than platform ticks 369 370Revision 1.348 2007/09/24 05:02:41 cheshire 371Debugging: In SIGINFO output, indicate explicitly when a given section is empty 372 373Revision 1.347 2007/09/21 02:04:33 cheshire 374<rdar://problem/5440831> BTMM: mDNSResponder crashes in free_service_instance enabling/disabling BTMM 375 376Revision 1.346 2007/09/19 22:47:25 cheshire 377<rdar://problem/5490182> Memory corruption freeing a "no such service" service record 378 379Revision 1.345 2007/09/19 20:32:29 cheshire 380<rdar://problem/5482322> BTMM: Don't advertise SMB with BTMM because it doesn't support IPv6 381 382Revision 1.344 2007/09/19 19:27:50 cheshire 383<rdar://problem/5492182> Improved diagnostics when daemon can't connect to error return path socket 384 385Revision 1.343 2007/09/18 21:42:30 cheshire 386To reduce programming mistakes, renamed ExtPort to RequestedPort 387 388Revision 1.342 2007/09/14 22:38:20 cheshire 389Additional list checking in uds_validatelists() 390 391Revision 1.341 2007/09/13 00:16:43 cheshire 392<rdar://problem/5468706> Miscellaneous NAT Traversal improvements 393 394Revision 1.340 2007/09/12 23:03:08 cheshire 395<rdar://problem/5476978> DNSServiceNATPortMappingCreate callback not giving correct interface index 396 397Revision 1.339 2007/09/12 19:22:21 cheshire 398Variable renaming in preparation for upcoming fixes e.g. priv/pub renamed to intport/extport 399Made NAT Traversal packet handlers take typed data instead of anonymous "mDNSu8 *" byte pointers 400 401Revision 1.338 2007/09/12 01:22:13 cheshire 402Improve validatelists() checking to detect when 'next' pointer gets smashed to ~0 403 404Revision 1.337 2007/09/07 23:05:04 cheshire 405Add display of client_context field in handle_cancel_request() LogOperation message 406While loop was checking client_context.u32[2] instead of client_context.u32[1] 407 408Revision 1.336 2007/09/07 20:56:03 cheshire 409Renamed uint32_t field in client_context_t from "ptr64" to more accurate name "u32" 410 411Revision 1.335 2007/09/05 22:25:01 vazquez 412<rdar://problem/5400521> update_record mDNSResponder leak 413 414Revision 1.334 2007/09/05 20:43:57 cheshire 415Added LogOperation message showing fd of socket listening for incoming Unix Domain Socket client requests 416 417Revision 1.333 2007/08/28 23:32:35 cheshire 418Added LogOperation messages for DNSServiceNATPortMappingCreate() operations 419 420Revision 1.332 2007/08/27 22:59:31 cheshire 421Show reg_index in DNSServiceRegisterRecord/DNSServiceRemoveRecord messages 422 423Revision 1.331 2007/08/27 20:29:57 cheshire 424Added SIGINFO listing of TunnelClients 425 426Revision 1.330 2007/08/24 23:46:50 cheshire 427Added debugging messages and SIGINFO listing of DomainAuthInfo records 428 429Revision 1.329 2007/08/18 01:02:04 mcguire 430<rdar://problem/5415593> No Bonjour services are getting registered at boot 431 432Revision 1.328 2007/08/15 20:18:28 vazquez 433<rdar://problem/5400521> update_record mDNSResponder leak 434Make sure we free all ExtraResourceRecords 435 436Revision 1.327 2007/08/08 22:34:59 mcguire 437<rdar://problem/5197869> Security: Run mDNSResponder as user id mdnsresponder instead of root 438 439Revision 1.326 2007/08/01 16:09:14 cheshire 440Removed unused NATTraversalInfo substructure from AuthRecord; reduced structure sizecheck values accordingly 441 442Revision 1.325 2007/07/31 21:29:41 cheshire 443<rdar://problem/5372207> System Default registration domain(s) not listed in Domain Enumeration ("dns-sd -E") 444 445Revision 1.324 2007/07/31 01:56:21 cheshire 446Corrected function name in log message 447 448Revision 1.323 2007/07/27 23:57:23 cheshire 449Added compile-time structure size checks 450 451Revision 1.322 2007/07/27 19:37:19 cheshire 452Moved AutomaticBrowseDomainQ into main mDNS object 453 454Revision 1.321 2007/07/27 19:30:41 cheshire 455Changed mDNSQuestionCallback parameter from mDNSBool to QC_result, 456to properly reflect tri-state nature of the possible responses 457 458Revision 1.320 2007/07/27 00:48:27 cheshire 459<rdar://problem/4700198> BTMM: Services should only get registered in .Mac domain of current user 460<rdar://problem/4731180> BTMM: Only browse in the current user's .Mac domain by default 461 462Revision 1.319 2007/07/24 17:23:33 cheshire 463<rdar://problem/5357133> Add list validation checks for debugging 464 465Revision 1.318 2007/07/23 23:09:51 cheshire 466<rdar://problem/5351997> Reject oversized client requests 467 468Revision 1.317 2007/07/23 22:24:47 cheshire 469<rdar://problem/5352299> Make mDNSResponder more defensive against malicious local clients 470Additional refinements 471 472Revision 1.316 2007/07/23 22:12:53 cheshire 473<rdar://problem/5352299> Make mDNSResponder more defensive against malicious local clients 474 475Revision 1.315 2007/07/21 01:36:13 cheshire 476Need to also add ".local" as automatic browsing domain 477 478Revision 1.314 2007/07/20 20:12:37 cheshire 479Rename "mDNS_DomainTypeBrowseLegacy" as "mDNS_DomainTypeBrowseAutomatic" 480 481Revision 1.313 2007/07/20 00:54:21 cheshire 482<rdar://problem/4641118> Need separate SCPreferences for per-user .Mac settings 483 484Revision 1.312 2007/07/11 03:06:43 cheshire 485<rdar://problem/5303807> Register IPv6-only hostname and don't create port mappings for AutoTunnel services 486 487Revision 1.311 2007/07/06 21:19:18 cheshire 488Add list of NAT traversals to SIGINFO output 489 490Revision 1.310 2007/07/03 19:56:50 cheshire 491Add LogOperation message for DNSServiceSetDefaultDomainForUser 492 493Revision 1.309 2007/06/29 23:12:49 vazquez 494<rdar://problem/5294103> Stop using generate_final_fatal_reply_with_garbage 495 496Revision 1.308 2007/06/29 00:10:07 vazquez 497<rdar://problem/5301908> Clean up NAT state machine (necessary for 6 other fixes) 498 499Revision 1.307 2007/05/25 00:25:44 cheshire 500<rdar://problem/5227737> Need to enhance putRData to output all current known types 501 502Revision 1.306 2007/05/24 22:31:35 vazquez 503Bug #: 4272956 504Reviewed by: Stuart Cheshire 505<rdar://problem/4272956> WWDC API: Return ADD/REMOVE events in registration callback 506 507Revision 1.305 2007/05/23 18:59:22 cheshire 508Remove unnecessary IPC_FLAGS_REUSE_SOCKET 509 510Revision 1.304 2007/05/22 01:07:42 cheshire 511<rdar://problem/3563675> API: Need a way to get version/feature information 512 513Revision 1.303 2007/05/22 00:32:58 cheshire 514Make a send_all() subroutine -- will be helpful for implementing DNSServiceGetProperty(DaemonVersion) 515 516Revision 1.302 2007/05/21 18:54:54 cheshire 517Add "Cancel" LogOperation message when we get a cancel_request command over the UDS 518 519Revision 1.301 2007/05/18 23:55:22 cheshire 520<rdar://problem/4454655> Allow multiple register/browse/resolve operations to share single Unix Domain Socket 521 522Revision 1.300 2007/05/18 21:27:11 cheshire 523Rename connected_registration_termination to connection_termination 524 525Revision 1.299 2007/05/18 21:24:34 cheshire 526Rename rstate to request 527 528Revision 1.298 2007/05/18 21:22:35 cheshire 529Convert uint16_t etc. to their locally-defined equivalents, like the rest of the core code 530 531Revision 1.297 2007/05/18 20:33:11 cheshire 532Avoid declaring lots of uninitialized variables in read_rr_from_ipc_msg 533 534Revision 1.296 2007/05/18 19:04:19 cheshire 535Rename msgdata to msgptr (may be modified); rename (currently unused) bufsize to msgend 536 537Revision 1.295 2007/05/18 17:57:13 cheshire 538Reorder functions in file to arrange them in logical groups; added "#pragma mark" headers for each group 539 540Revision 1.294 2007/05/17 20:58:22 cheshire 541<rdar://problem/4647145> DNSServiceQueryRecord should return useful information with NXDOMAIN 542 543Revision 1.293 2007/05/17 19:46:20 cheshire 544Routine name deliver_async_error() is misleading. What it actually does is write a message header 545(containing an error code) followed by 256 bytes of garbage zeroes onto a client connection, 546thereby trashing it and making it useless for any subsequent communication. It's destructive, 547and not very useful. Changing name to generate_final_fatal_reply_with_garbage(). 548 549Revision 1.292 2007/05/16 01:06:52 cheshire 550<rdar://problem/4471320> Improve reliability of kDNSServiceFlagsMoreComing flag on multiprocessor machines 551 552Revision 1.291 2007/05/15 21:57:16 cheshire 553<rdar://problem/4608220> Use dnssd_SocketValid(x) macro instead of just 554assuming that all negative values (or zero!) are invalid socket numbers 555 556Revision 1.290 2007/05/10 23:30:57 cheshire 557<rdar://problem/4084490> Only one browse gets remove events when disabling browse domain 558 559Revision 1.289 2007/05/02 22:18:08 cheshire 560Renamed NATTraversalInfo_struct context to NATTraversalContext 561 562Revision 1.288 2007/04/30 21:33:39 cheshire 563Fix crash when a callback unregisters a service while the UpdateSRVRecords() loop 564is iterating through the m->ServiceRegistrations list 565 566Revision 1.287 2007/04/27 19:03:22 cheshire 567Check q->LongLived not q->llq to tell if a query is LongLived 568 569Revision 1.286 2007/04/26 16:00:01 cheshire 570Show interface number in DNSServiceBrowse RESULT output 571 572Revision 1.285 2007/04/22 19:03:39 cheshire 573Minor code tidying 574 575Revision 1.284 2007/04/22 06:02:03 cheshire 576<rdar://problem/4615977> Query should immediately return failure when no server 577 578Revision 1.283 2007/04/21 21:47:47 cheshire 579<rdar://problem/4376383> Daemon: Add watchdog timer 580 581Revision 1.282 2007/04/20 21:17:24 cheshire 582For naming consistency, kDNSRecordTypeNegative should be kDNSRecordTypePacketNegative 583 584Revision 1.281 2007/04/19 23:25:20 cheshire 585Added debugging message 586 587Revision 1.280 2007/04/17 19:21:29 cheshire 588<rdar://problem/5140339> Domain discovery not working over VPN 589 590Revision 1.279 2007/04/16 21:53:49 cheshire 591Improve display of negative cache entries 592 593Revision 1.278 2007/04/16 20:49:40 cheshire 594Fix compile errors for mDNSPosix build 595 596Revision 1.277 2007/04/05 22:55:36 cheshire 597<rdar://problem/5077076> Records are ending up in Lighthouse without expiry information 598 599Revision 1.276 2007/04/05 19:20:13 cheshire 600Non-blocking mode not being set correctly -- was clobbering other flags 601 602Revision 1.275 2007/04/04 21:21:25 cheshire 603<rdar://problem/4546810> Fix crash: In regservice_callback service_instance was being referenced after being freed 604 605Revision 1.274 2007/04/04 01:30:42 cheshire 606<rdar://problem/5075200> DNSServiceAddRecord is failing to advertise NULL record 607Add SIGINFO output lising our advertised Authoritative Records 608 609Revision 1.273 2007/04/04 00:03:27 cheshire 610<rdar://problem/5089862> DNSServiceQueryRecord is returning kDNSServiceErr_NoSuchRecord for empty rdata 611 612Revision 1.272 2007/04/03 20:10:32 cheshire 613Show ADD/RMV in DNSServiceQueryRecord log message instead of just "RESULT" 614 615Revision 1.271 2007/04/03 19:22:32 cheshire 616Use mDNSSameIPv4Address (and similar) instead of accessing internal fields directly 617 618Revision 1.270 2007/03/30 21:55:30 cheshire 619Added comments 620 621Revision 1.269 2007/03/29 01:31:44 cheshire 622Faulty logic was incorrectly suppressing some NAT port mapping callbacks 623 624Revision 1.268 2007/03/29 00:13:58 cheshire 625Remove unnecessary fields from service_instance structure: autoname, autorename, allowremotequery, name 626 627Revision 1.267 2007/03/28 20:59:27 cheshire 628<rdar://problem/4743285> Remove inappropriate use of IsPrivateV4Addr() 629 630Revision 1.266 2007/03/28 15:56:37 cheshire 631<rdar://problem/5085774> Add listing of NAT port mapping and GetAddrInfo requests in SIGINFO output 632 633Revision 1.265 2007/03/27 22:52:07 cheshire 634Fix crash in udsserver_automatic_browse_domain_changed 635 636Revision 1.264 2007/03/27 00:49:40 cheshire 637Should use mallocL, not plain malloc 638 639Revision 1.263 2007/03/27 00:45:01 cheshire 640Removed unnecessary "void *termination_context" pointer 641 642Revision 1.262 2007/03/27 00:40:43 cheshire 643Eliminate resolve_termination_t as a separately-allocated structure, and make it part of the request_state union 644 645Revision 1.261 2007/03/27 00:29:00 cheshire 646Eliminate queryrecord_request data as a separately-allocated structure, and make it part of the request_state union 647 648Revision 1.260 2007/03/27 00:18:42 cheshire 649Eliminate enum_termination_t and domain_enum_t as separately-allocated structures, 650and make them part of the request_state union 651 652Revision 1.259 2007/03/26 23:48:16 cheshire 653<rdar://problem/4848295> Advertise model information via Bonjour 654Refinements to reduce unnecessary transmissions of the DeviceInfo TXT record 655 656Revision 1.258 2007/03/24 00:40:04 cheshire 657Minor code cleanup 658 659Revision 1.257 2007/03/24 00:23:12 cheshire 660Eliminate port_mapping_info_t as a separately-allocated structure, and make it part of the request_state union 661 662Revision 1.256 2007/03/24 00:07:18 cheshire 663Eliminate addrinfo_info_t as a separately-allocated structure, and make it part of the request_state union 664 665Revision 1.255 2007/03/23 23:56:14 cheshire 666Move list of record registrations into the request_state union 667 668Revision 1.254 2007/03/23 23:48:56 cheshire 669Eliminate service_info as a separately-allocated structure, and make it part of the request_state union 670 671Revision 1.253 2007/03/23 23:04:29 cheshire 672Eliminate browser_info_t as a separately-allocated structure, and make it part of request_state 673 674Revision 1.252 2007/03/23 22:59:58 cheshire 675<rdar://problem/4848295> Advertise model information via Bonjour 676Use kStandardTTL, not kHostNameTTL 677 678Revision 1.251 2007/03/23 22:44:07 cheshire 679Instead of calling AbortUnlinkAndFree() haphazardly all over the place, make the handle* routines 680return an error code, and then request_callback() does all necessary cleanup in one place. 681 682Revision 1.250 2007/03/22 20:30:07 cheshire 683Remove pointless "if (request->ts != t_complete) ..." checks 684 685Revision 1.249 2007/03/22 20:13:27 cheshire 686Delete unused client_context field 687 688Revision 1.248 2007/03/22 20:03:37 cheshire 689Rename variables for clarity: instead of using variable rs for both request_state 690and reply_state, use req for request_state and rep for reply_state 691 692Revision 1.247 2007/03/22 19:31:42 cheshire 693<rdar://problem/4848295> Advertise model information via Bonjour 694Add missing "model=" at start of DeviceInfo data 695 696Revision 1.246 2007/03/22 18:31:48 cheshire 697Put dst parameter first in mDNSPlatformStrCopy/mDNSPlatformMemCopy, like conventional Posix strcpy/memcpy 698 699Revision 1.245 2007/03/22 00:49:20 cheshire 700<rdar://problem/4848295> Advertise model information via Bonjour 701 702Revision 1.244 2007/03/21 21:01:48 cheshire 703<rdar://problem/4789793> Leak on error path in regrecord_callback, uds_daemon.c 704 705Revision 1.243 2007/03/21 19:01:57 cheshire 706<rdar://problem/5078494> IPC code not 64-bit-savvy: assumes long=32bits, and short=16bits 707 708Revision 1.242 2007/03/21 18:51:21 cheshire 709<rdar://problem/4549320> Code in uds_daemon.c passes function name instead of type name to mallocL/freeL 710 711Revision 1.241 2007/03/20 00:04:50 cheshire 712<rdar://problem/4837929> Should allow "udp" or "tcp" for protocol command-line arg 713Fix LogOperation("DNSServiceNATPortMappingCreate(...)") message to actually show client arguments 714 715Revision 1.240 2007/03/16 23:25:35 cheshire 716<rdar://problem/5067001> NAT-PMP: Parameter validation not working correctly 717 718Revision 1.239 2007/03/10 02:29:36 cheshire 719Added comment about port_mapping_create_reply() 720 721Revision 1.238 2007/03/07 00:26:48 cheshire 722<rdar://problem/4426754> DNSServiceRemoveRecord log message should include record type 723 724Revision 1.237 2007/02/28 01:44:29 cheshire 725<rdar://problem/5027863> Byte order bugs in uDNS.c, uds_daemon.c, dnssd_clientstub.c 726 727Revision 1.236 2007/02/14 01:58:19 cheshire 728<rdar://problem/4995831> Don't delete Unix Domain Socket on exit if we didn't create it on startup 729 730Revision 1.235 2007/02/08 21:12:28 cheshire 731<rdar://problem/4386497> Stop reading /etc/mDNSResponder.conf on every sleep/wake 732 733Revision 1.234 2007/02/06 19:06:49 cheshire 734<rdar://problem/3956518> Need to go native with launchd 735 736Revision 1.233 2007/01/10 20:49:37 cheshire 737Remove unnecessary setting of q->Private fields 738 739Revision 1.232 2007/01/09 00:03:23 cheshire 740Call udsserver_handle_configchange() once at the end of udsserver_init() 741to set up the automatic registration and browsing domains. 742 743Revision 1.231 2007/01/06 02:50:19 cheshire 744<rdar://problem/4632919> Instead of copying SRV and TXT record data, just store pointers to cache entities 745 746Revision 1.230 2007/01/06 01:00:35 cheshire 747Improved SIGINFO output 748 749Revision 1.229 2007/01/05 08:30:56 cheshire 750Trim excessive "Log" checkin history from before 2006 751(checkin history still available via "cvs log ..." of course) 752 753Revision 1.228 2007/01/05 08:09:05 cheshire 754Reorder code into functional sections, with "#pragma mark" headers 755 756Revision 1.227 2007/01/05 07:04:24 cheshire 757Minor code tidying 758 759Revision 1.226 2007/01/05 05:44:35 cheshire 760Move automatic browse/registration management from uDNS.c to mDNSShared/uds_daemon.c, 761so that mDNSPosix embedded clients will compile again 762 763Revision 1.225 2007/01/04 23:11:15 cheshire 764<rdar://problem/4720673> uDNS: Need to start caching unicast records 765When an automatic browsing domain is removed, generate appropriate "remove" events for legacy queries 766 767Revision 1.224 2007/01/04 20:57:49 cheshire 768Rename ReturnCNAME to ReturnIntermed (for ReturnIntermediates) 769 770Revision 1.223 2006/12/21 01:25:49 cheshire 771Tidy up SIGINFO state log 772 773Revision 1.222 2006/12/21 00:15:22 cheshire 774Get rid of gmDNS macro; fixed a crash in udsserver_info() 775 776Revision 1.221 2006/12/20 04:07:38 cheshire 777Remove uDNS_info substructure from AuthRecord_struct 778 779Revision 1.220 2006/12/19 22:49:25 cheshire 780Remove uDNS_info substructure from ServiceRecordSet_struct 781 782Revision 1.219 2006/12/14 03:02:38 cheshire 783<rdar://problem/4838433> Tools: dns-sd -G 0 only returns IPv6 when you have a routable IPv6 address 784 785Revision 1.218 2006/11/18 05:01:33 cheshire 786Preliminary support for unifying the uDNS and mDNS code, 787including caching of uDNS answers 788 789Revision 1.217 2006/11/15 19:27:53 mkrochma 790<rdar://problem/4838433> Tools: dns-sd -G 0 only returns IPv6 when you have a routable IPv6 address 791 792Revision 1.216 2006/11/10 00:54:16 cheshire 793<rdar://problem/4816598> Changing case of Computer Name doesn't work 794 795Revision 1.215 2006/10/27 01:30:23 cheshire 796Need explicitly to set ReturnIntermed = mDNSfalse 797 798Revision 1.214 2006/10/20 05:37:23 herscher 799Display question list information in udsserver_info() 800 801Revision 1.213 2006/10/05 03:54:31 herscher 802Remove embedded uDNS_info struct from DNSQuestion_struct 803 804Revision 1.212 2006/09/30 01:22:35 cheshire 805Put back UTF-8 curly quotes in log messages 806 807Revision 1.211 2006/09/27 00:44:55 herscher 808<rdar://problem/4249761> API: Need DNSServiceGetAddrInfo() 809 810Revision 1.210 2006/09/26 01:52:41 herscher 811<rdar://problem/4245016> NAT Port Mapping API (for both NAT-PMP and UPnP Gateway Protocol) 812 813Revision 1.209 2006/09/21 21:34:09 cheshire 814<rdar://problem/4100000> Allow empty string name when using kDNSServiceFlagsNoAutoRename 815 816Revision 1.208 2006/09/21 21:28:24 cheshire 817Code cleanup to make it consistent with daemon.c: change rename_on_memfree to renameonmemfree 818 819Revision 1.207 2006/09/15 21:20:16 cheshire 820Remove uDNS_info substructure from mDNS_struct 821 822Revision 1.206 2006/08/14 23:24:56 cheshire 823Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0 824 825Revision 1.205 2006/07/20 22:07:30 mkrochma 826<rdar://problem/4633196> Wide-area browsing is currently broken in TOT 827More fixes for uninitialized variables 828 829Revision 1.204 2006/07/15 02:01:33 cheshire 830<rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder 831Fix broken "empty string" browsing 832 833Revision 1.203 2006/07/07 01:09:13 cheshire 834<rdar://problem/4472013> Add Private DNS server functionality to dnsextd 835Only use mallocL/freeL debugging routines when building mDNSResponder, not dnsextd 836 837Revision 1.202 2006/07/05 22:00:10 cheshire 838Wide-area cleanup: Rename mDNSPlatformGetRegDomainList() to uDNS_GetDefaultRegDomainList() 839 840Revision 1.201 2006/06/29 03:02:47 cheshire 841<rdar://problem/4607042> mDNSResponder NXDOMAIN and CNAME support 842 843Revision 1.200 2006/06/28 08:56:26 cheshire 844Added "_op" to the end of the operation code enum values, 845to differentiate them from the routines with the same names 846 847Revision 1.199 2006/06/28 08:53:39 cheshire 848Added (commented out) debugging messages 849 850Revision 1.198 2006/06/27 20:16:07 cheshire 851Fix code layout 852 853Revision 1.197 2006/05/18 01:32:35 cheshire 854<rdar://problem/4472706> iChat: Lost connection with Bonjour 855(mDNSResponder insufficiently defensive against malformed browsing PTR responses) 856 857Revision 1.196 2006/05/05 07:07:13 cheshire 858<rdar://problem/4538206> mDNSResponder fails when UDS reads deliver partial data 859 860Revision 1.195 2006/04/25 20:56:28 mkrochma 861Added comment about previous checkin 862 863Revision 1.194 2006/04/25 18:29:36 mkrochma 864Workaround for warning: unused variable 'status' when building mDNSPosix 865 866Revision 1.193 2006/03/19 17:14:38 cheshire 867<rdar://problem/4483117> Need faster purging of stale records 868read_rr_from_ipc_msg was not setting namehash and rdatahash 869 870Revision 1.192 2006/03/18 20:58:32 cheshire 871Misplaced curly brace 872 873Revision 1.191 2006/03/10 22:19:43 cheshire 874Update debugging message in resolve_result_callback() to indicate whether event is ADD or RMV 875 876Revision 1.190 2006/03/10 21:56:12 cheshire 877<rdar://problem/4111464> After record update, old record sometimes remains in cache 878When service TXT and SRV record both change, clients with active resolve calls get *two* callbacks, one 879when the TXT data changes, and then immediately afterwards a second callback with the new port number 880This change suppresses the first unneccessary (and confusing) callback 881 882Revision 1.189 2006/01/06 00:56:31 cheshire 883<rdar://problem/4400573> Should remove PID file on exit 884 885*/ 886 887#if defined(_WIN32) 888#include <process.h> 889#define usleep(X) Sleep(((X)+999)/1000) 890#else 891#include <fcntl.h> 892#include <errno.h> 893#include <sys/ioctl.h> 894#include <sys/types.h> 895#include <sys/time.h> 896#include <sys/resource.h> 897#endif 898 899#include <stdlib.h> 900#include <stdio.h> 901 902#include "mDNSEmbeddedAPI.h" 903#include "DNSCommon.h" 904#include "uDNS.h" 905#include "uds_daemon.h" 906 907// Apple-specific functionality, not required for other platforms 908#if APPLE_OSX_mDNSResponder 909#include <sys/ucred.h> 910#ifndef PID_FILE 911#define PID_FILE "" 912#endif 913#endif 914 915// User IDs 0-500 are system-wide processes, not actual users in the usual sense 916// User IDs for real user accounts start at 501 and count up from there 917#define SystemUID(X) ((X) <= 500) 918 919// *************************************************************************** 920#if COMPILER_LIKES_PRAGMA_MARK 921#pragma mark - 922#pragma mark - Types and Data Structures 923#endif 924 925typedef enum 926 { 927 t_uninitialized, 928 t_morecoming, 929 t_complete, 930 t_error, 931 t_terminated 932 } transfer_state; 933 934typedef struct request_state request_state; 935 936typedef void (*req_termination_fn)(request_state *request); 937 938typedef struct registered_record_entry 939 { 940 struct registered_record_entry *next; 941 mDNSu32 key; 942 AuthRecord *rr; // Pointer to variable-sized AuthRecord 943 client_context_t regrec_client_context; 944 request_state *request; 945 } registered_record_entry; 946 947// A single registered service: ServiceRecordSet + bookkeeping 948// Note that we duplicate some fields from parent service_info object 949// to facilitate cleanup, when instances and parent may be deallocated at different times. 950typedef struct service_instance 951 { 952 struct service_instance *next; 953 request_state *request; 954 AuthRecord *subtypes; 955 mDNSBool renameonmemfree; // Set on config change when we deregister original name 956 mDNSBool clientnotified; // Has client been notified of successful registration yet? 957 mDNSBool default_local; // is this the "local." from an empty-string registration? 958 domainname domain; 959 ServiceRecordSet srs; // note -- variable-sized object -- must be last field in struct 960 } service_instance; 961 962// for multi-domain default browsing 963typedef struct browser_t 964 { 965 struct browser_t *next; 966 domainname domain; 967 DNSQuestion q; 968 } browser_t; 969 970struct request_state 971 { 972 request_state *next; 973 request_state *primary; // If this operation is on a shared socket, pointer to primary 974 // request_state for the original DNSServiceConnect() operation 975 dnssd_sock_t sd; 976 dnssd_sock_t errsd; 977 mDNSu32 uid; 978 979 // Note: On a shared connection these fields in the primary structure, including hdr, are re-used 980 // for each new request. This is because, until we've read the ipc_msg_hdr to find out what the 981 // operation is, we don't know if we're going to need to allocate a new request_state or not. 982 transfer_state ts; 983 mDNSu32 hdr_bytes; // bytes of header already read 984 ipc_msg_hdr hdr; 985 mDNSu32 data_bytes; // bytes of message data already read 986 char *msgbuf; // pointer to data storage to pass to free() 987 const char *msgptr; // pointer to data to be read from (may be modified) 988 char *msgend; // pointer to byte after last byte of message 989 990 // reply, termination, error, and client context info 991 int no_reply; // don't send asynchronous replies to client 992 int time_blocked; // record time of a blocked client 993 struct reply_state *replies; // corresponding (active) reply list 994 req_termination_fn terminate; 995 996 union 997 { 998 registered_record_entry *reg_recs; // list of registrations for a connection-oriented request 999 struct 1000 { 1001 mDNSInterfaceID interface_id; 1002 mDNSBool default_domain; 1003 mDNSBool ForceMCast; 1004 domainname regtype; 1005 browser_t *browsers; 1006 } browser; 1007 struct 1008 { 1009 mDNSInterfaceID InterfaceID; 1010 mDNSu16 txtlen; 1011 void *txtdata; 1012 mDNSIPPort port; 1013 domainlabel name; 1014 char type_as_string[MAX_ESCAPED_DOMAIN_NAME]; 1015 domainname type; 1016 mDNSBool default_domain; 1017 domainname host; 1018 mDNSBool autoname; // Set if this name is tied to the Computer Name 1019 mDNSBool autorename; // Set if this client wants us to automatically rename on conflict 1020 mDNSBool allowremotequery; // Respond to unicast queries from outside the local link? 1021 int num_subtypes; 1022 service_instance *instances; 1023 } servicereg; 1024 struct 1025 { 1026 mDNSInterfaceID interface_id; 1027 mDNSu32 flags; 1028 mDNSu32 protocol; 1029 DNSQuestion q4; 1030 DNSQuestion q6; 1031 } addrinfo; 1032 struct 1033 { 1034 mDNSIPPort ReqExt; // External port we originally requested, for logging purposes 1035 NATTraversalInfo NATinfo; 1036 } pm; 1037 struct 1038 { 1039#if 0 1040 DNSServiceFlags flags; 1041#endif 1042 DNSQuestion q_all; 1043 DNSQuestion q_default; 1044 } enumeration; 1045 struct 1046 { 1047 DNSQuestion q; 1048 DNSQuestion q2; 1049 } queryrecord; 1050 struct 1051 { 1052 DNSQuestion qtxt; 1053 DNSQuestion qsrv; 1054 const ResourceRecord *txt; 1055 const ResourceRecord *srv; 1056 mDNSs32 ReportTime; 1057 } resolve; 1058 } u; 1059 }; 1060 1061// struct physically sits between ipc message header and call-specific fields in the message buffer 1062typedef struct 1063 { 1064 DNSServiceFlags flags; // Note: This field is in NETWORK byte order 1065 mDNSu32 ifi; // Note: This field is in NETWORK byte order 1066 DNSServiceErrorType error; // Note: This field is in NETWORK byte order 1067 } reply_hdr; 1068 1069typedef struct reply_state 1070 { 1071 struct reply_state *next; // If there are multiple unsent replies 1072 mDNSu32 totallen; 1073 mDNSu32 nwriten; 1074 ipc_msg_hdr mhdr[1]; 1075 reply_hdr rhdr[1]; 1076 } reply_state; 1077 1078// *************************************************************************** 1079#if COMPILER_LIKES_PRAGMA_MARK 1080#pragma mark - 1081#pragma mark - Globals 1082#endif 1083 1084// globals 1085mDNSexport mDNS mDNSStorage; 1086#ifndef PROGRAM_NAME 1087#define PROGRAM_NAME "mDNSResponder" 1088#endif 1089mDNSexport const char ProgramName[] = PROGRAM_NAME; 1090 1091static dnssd_sock_t listenfd = dnssd_InvalidSocket; 1092static request_state *all_requests = NULL; 1093 1094static DNameListElem *SCPrefBrowseDomains; // List of automatic browsing domains read from SCPreferences for "empty string" browsing 1095static ARListElem *LocalDomainEnumRecords; // List of locally-generated PTR records to augment those we learn from the network 1096mDNSexport DNameListElem *AutoBrowseDomains; // List created from those local-only PTR records plus records we get from the network 1097 1098mDNSexport DNameListElem *AutoRegistrationDomains; // Domains where we automatically register for empty-string registrations 1099 1100#define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee 1101 // n get_string() calls w/o buffer overrun 1102// initialization, setup/teardown functions 1103 1104// If a platform specifies its own PID file name, we use that 1105#ifndef PID_FILE 1106#define PID_FILE "/var/run/mDNSResponder.pid" 1107#endif 1108 1109// *************************************************************************** 1110#if COMPILER_LIKES_PRAGMA_MARK 1111#pragma mark - 1112#pragma mark - General Utility Functions 1113#endif 1114 1115mDNSlocal void FatalError(char *errmsg) 1116 { 1117 LogMsg("%s: %s", errmsg, dnssd_strerror(dnssd_errno)); 1118 *(volatile long*)0 = 0; // On OS X abort() doesn't generate a crash log, but writing to zero does 1119 abort(); // On platforms where writing to zero doesn't generate an exception, abort instead 1120 } 1121 1122mDNSlocal mDNSu32 dnssd_htonl(mDNSu32 l) 1123 { 1124 mDNSu32 ret; 1125 char *data = (char*) &ret; 1126 put_uint32(l, &data); 1127 return ret; 1128 } 1129 1130// hack to search-replace perror's to LogMsg's 1131mDNSlocal void my_perror(char *errmsg) 1132 { 1133 LogMsg("%s: %d (%s)", errmsg, dnssd_errno, dnssd_strerror(dnssd_errno)); 1134 } 1135 1136mDNSlocal void abort_request(request_state *req) 1137 { 1138 if (req->terminate == (req_termination_fn)~0) 1139 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req, req->terminate); return; } 1140 1141 // First stop whatever mDNSCore operation we were doing 1142 if (req->terminate) req->terminate(req); 1143 1144 if (!dnssd_SocketValid(req->sd)) 1145 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req, req->sd); return; } 1146 1147 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies 1148 if (!req->primary) 1149 { 1150 if (req->errsd != req->sd) LogOperation("%3d: Removing FD and closing errsd %d", req->sd, req->errsd); 1151 else LogOperation("%3d: Removing FD", req->sd); 1152 udsSupportRemoveFDFromEventLoop(req->sd); // Note: This also closes file descriptor req->sd for us 1153 if (req->errsd != req->sd) { dnssd_close(req->errsd); req->errsd = req->sd; } 1154 1155 while (req->replies) // free pending replies 1156 { 1157 reply_state *ptr = req->replies; 1158 req->replies = req->replies->next; 1159 freeL("reply_state (abort)", ptr); 1160 } 1161 } 1162 1163 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure 1164#if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING 1165 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses 1166 // for detecting when the memory for an object is inadvertently freed while the object is still on some list 1167 req->sd = req->errsd = -2; 1168#else 1169 req->sd = req->errsd = dnssd_InvalidSocket; 1170#endif 1171 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request 1172 req->terminate = (req_termination_fn)~0; 1173 } 1174 1175mDNSlocal void AbortUnlinkAndFree(request_state *req) 1176 { 1177 request_state **p = &all_requests; 1178 abort_request(req); 1179 while (*p && *p != req) p=&(*p)->next; 1180 if (*p) { *p = req->next; freeL("request_state/AbortUnlinkAndFree", req); } 1181 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req); 1182 } 1183 1184mDNSlocal reply_state *create_reply(const reply_op_t op, const size_t datalen, request_state *const request) 1185 { 1186 reply_state *reply; 1187 1188 if ((unsigned)datalen < sizeof(reply_hdr)) 1189 { 1190 LogMsg("ERROR: create_reply - data length less than length of required fields"); 1191 return NULL; 1192 } 1193 1194 reply = mallocL("reply_state", sizeof(reply_state) + datalen - sizeof(reply_hdr)); 1195 if (!reply) FatalError("ERROR: malloc"); 1196 1197 reply->next = mDNSNULL; 1198 reply->totallen = datalen + sizeof(ipc_msg_hdr); 1199 reply->nwriten = 0; 1200 1201 reply->mhdr->version = VERSION; 1202 reply->mhdr->datalen = datalen; 1203 reply->mhdr->ipc_flags = 0; 1204 reply->mhdr->op = op; 1205 reply->mhdr->client_context = request->hdr.client_context; 1206 reply->mhdr->reg_index = 0; 1207 1208 return reply; 1209 } 1210 1211// Append a reply to the list in a request object 1212// If our request is sharing a connection, then we append our reply_state onto the primary's list 1213mDNSlocal void append_reply(request_state *req, reply_state *rep) 1214 { 1215 request_state *r = req->primary ? req->primary : req; 1216 reply_state **ptr = &r->replies; 1217 while (*ptr) ptr = &(*ptr)->next; 1218 *ptr = rep; 1219 rep->next = NULL; 1220 } 1221 1222// Generates a response message giving name, type, domain, plus interface index, 1223// suitable for a browse result or service registration result. 1224// On successful completion rep is set to point to a malloc'd reply_state struct 1225mDNSlocal mStatus GenerateNTDResponse(const domainname *const servicename, const mDNSInterfaceID id, 1226 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err) 1227 { 1228 domainlabel name; 1229 domainname type, dom; 1230 *rep = NULL; 1231 if (!DeconstructServiceName(servicename, &name, &type, &dom)) 1232 return kDNSServiceErr_Invalid; 1233 else 1234 { 1235 char namestr[MAX_DOMAIN_LABEL+1]; 1236 char typestr[MAX_ESCAPED_DOMAIN_NAME]; 1237 char domstr [MAX_ESCAPED_DOMAIN_NAME]; 1238 int len; 1239 char *data; 1240 1241 ConvertDomainLabelToCString_unescaped(&name, namestr); 1242 ConvertDomainNameToCString(&type, typestr); 1243 ConvertDomainNameToCString(&dom, domstr); 1244 1245 // Calculate reply data length 1246 len = sizeof(DNSServiceFlags); 1247 len += sizeof(mDNSu32); // if index 1248 len += sizeof(DNSServiceErrorType); 1249 len += (int) (strlen(namestr) + 1); 1250 len += (int) (strlen(typestr) + 1); 1251 len += (int) (strlen(domstr) + 1); 1252 1253 // Build reply header 1254 *rep = create_reply(op, len, request); 1255 (*rep)->rhdr->flags = dnssd_htonl(flags); 1256 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id)); 1257 (*rep)->rhdr->error = dnssd_htonl(err); 1258 1259 // Build reply body 1260 data = (char *)&(*rep)->rhdr[1]; 1261 put_string(namestr, &data); 1262 put_string(typestr, &data); 1263 put_string(domstr, &data); 1264 1265 return mStatus_NoError; 1266 } 1267 } 1268 1269// Special support to enable the DNSServiceBrowse call made by Bonjour Browser 1270// Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse 1271mDNSlocal void GenerateBonjourBrowserResponse(const domainname *const servicename, const mDNSInterfaceID id, 1272 request_state *const request, reply_state **const rep, reply_op_t op, DNSServiceFlags flags, mStatus err) 1273 { 1274 char namestr[MAX_DOMAIN_LABEL+1]; 1275 char typestr[MAX_ESCAPED_DOMAIN_NAME]; 1276 static const char domstr[] = "."; 1277 int len; 1278 char *data; 1279 1280 *rep = NULL; 1281 1282 // 1. Put first label in namestr 1283 ConvertDomainLabelToCString_unescaped((const domainlabel *)servicename, namestr); 1284 1285 // 2. Put second label and "local" into typestr 1286 mDNS_snprintf(typestr, sizeof(typestr), "%#s.local.", SecondLabel(servicename)); 1287 1288 // Calculate reply data length 1289 len = sizeof(DNSServiceFlags); 1290 len += sizeof(mDNSu32); // if index 1291 len += sizeof(DNSServiceErrorType); 1292 len += (int) (strlen(namestr) + 1); 1293 len += (int) (strlen(typestr) + 1); 1294 len += (int) (strlen(domstr) + 1); 1295 1296 // Build reply header 1297 *rep = create_reply(op, len, request); 1298 (*rep)->rhdr->flags = dnssd_htonl(flags); 1299 (*rep)->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, id)); 1300 (*rep)->rhdr->error = dnssd_htonl(err); 1301 1302 // Build reply body 1303 data = (char *)&(*rep)->rhdr[1]; 1304 put_string(namestr, &data); 1305 put_string(typestr, &data); 1306 put_string(domstr, &data); 1307 } 1308 1309// Returns a resource record (allocated w/ malloc) containing the data found in an IPC message 1310// Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl 1311// (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error 1312mDNSlocal AuthRecord *read_rr_from_ipc_msg(request_state *request, int GetTTL, int validate_flags) 1313 { 1314 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 1315 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend); 1316 char name[256]; 1317 int str_err = get_string(&request->msgptr, request->msgend, name, sizeof(name)); 1318 mDNSu16 type = get_uint16(&request->msgptr, request->msgend); 1319 mDNSu16 class = get_uint16(&request->msgptr, request->msgend); 1320 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend); 1321 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen); 1322 mDNSu32 ttl = GetTTL ? get_uint32(&request->msgptr, request->msgend) : 0; 1323 int storage_size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody); 1324 AuthRecord *rr; 1325 1326 if (str_err) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL; } 1327 1328 if (!request->msgptr) { LogMsg("Error reading Resource Record from client"); return NULL; } 1329 1330 if (validate_flags && 1331 !((flags & kDNSServiceFlagsShared) == kDNSServiceFlagsShared) && 1332 !((flags & kDNSServiceFlagsUnique) == kDNSServiceFlagsUnique)) 1333 { 1334 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)"); 1335 return NULL; 1336 } 1337 1338 rr = mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord) - sizeof(RDataBody) + storage_size); 1339 if (!rr) FatalError("ERROR: malloc"); 1340 mDNS_SetupResourceRecord(rr, mDNSNULL, mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex), 1341 type, 0, (mDNSu8) ((flags & kDNSServiceFlagsShared) ? kDNSRecordTypeShared : kDNSRecordTypeUnique), mDNSNULL, mDNSNULL); 1342 1343 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, name)) 1344 { 1345 LogMsg("ERROR: bad name: %s", name); 1346 freeL("AuthRecord/read_rr_from_ipc_msg", rr); 1347 return NULL; 1348 } 1349 1350 if (flags & kDNSServiceFlagsAllowRemoteQuery) rr->AllowRemoteQuery = mDNStrue; 1351 rr->resrec.rrclass = class; 1352 rr->resrec.rdlength = rdlen; 1353 rr->resrec.rdata->MaxRDLength = rdlen; 1354 mDNSPlatformMemCopy(rr->resrec.rdata->u.data, rdata, rdlen); 1355 if (GetTTL) rr->resrec.rroriginalttl = ttl; 1356 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name); 1357 SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us 1358 return rr; 1359 } 1360 1361mDNSlocal int build_domainname_from_strings(domainname *srv, char *name, char *regtype, char *domain) 1362 { 1363 domainlabel n; 1364 domainname d, t; 1365 1366 if (!MakeDomainLabelFromLiteralString(&n, name)) return -1; 1367 if (!MakeDomainNameFromDNSNameString(&t, regtype)) return -1; 1368 if (!MakeDomainNameFromDNSNameString(&d, domain)) return -1; 1369 if (!ConstructServiceName(srv, &n, &t, &d)) return -1; 1370 return 0; 1371 } 1372 1373mDNSlocal void send_all(dnssd_sock_t s, const char *ptr, int len) 1374 { 1375 int n = send(s, ptr, len, 0); 1376 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us 1377 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)). 1378 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong. 1379 if (n < len) 1380 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)", 1381 s, n, len, dnssd_errno, dnssd_strerror(dnssd_errno)); 1382 } 1383 1384#if 0 1385mDNSlocal mDNSBool AuthorizedDomain(const request_state * const request, const domainname * const d, const DNameListElem * const doms) 1386{ 1387 const DNameListElem *delem = mDNSNULL; 1388 int bestDelta = -1; // the delta of the best match, lower is better 1389 int dLabels = 0; 1390 mDNSBool allow = mDNSfalse; 1391 1392 if (SystemUID(request->uid)) return mDNStrue; 1393 1394 dLabels = CountLabels(d); 1395 for (delem = doms; delem; delem = delem->next) 1396 { 1397 if (delem->uid) 1398 { 1399 int delemLabels = CountLabels(&delem->name); 1400 int delta = dLabels - delemLabels; 1401 if ((bestDelta == -1 || delta <= bestDelta) && SameDomainName(&delem->name, SkipLeadingLabels(d, delta))) 1402 { 1403 bestDelta = delta; 1404 allow = (allow || (delem->uid == request->uid)); 1405 } 1406 } 1407 } 1408 1409 return bestDelta == -1 ? mDNStrue : allow; 1410} 1411#endif 1412 1413// *************************************************************************** 1414#if COMPILER_LIKES_PRAGMA_MARK 1415#pragma mark - 1416#pragma mark - DNSServiceRegister 1417#endif 1418 1419mDNSexport void FreeExtraRR(mDNS *const m, AuthRecord *const rr, mStatus result) 1420 { 1421 ExtraResourceRecord *extra = (ExtraResourceRecord *)rr->RecordContext; 1422 (void)m; // Unused 1423 1424 if (result != mStatus_MemFree) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result); return; } 1425 1426 LogInfo(" FreeExtraRR %s", RRDisplayString(m, &rr->resrec)); 1427 1428 if (rr->resrec.rdata != &rr->rdatastorage) 1429 freeL("Extra RData", rr->resrec.rdata); 1430 freeL("ExtraResourceRecord/FreeExtraRR", extra); 1431 } 1432 1433mDNSlocal void unlink_and_free_service_instance(service_instance *srv) 1434 { 1435 ExtraResourceRecord *e = srv->srs.Extras, *tmp; 1436 1437 // clear pointers from parent struct 1438 if (srv->request) 1439 { 1440 service_instance **p = &srv->request->u.servicereg.instances; 1441 while (*p) 1442 { 1443 if (*p == srv) { *p = (*p)->next; break; } 1444 p = &(*p)->next; 1445 } 1446 } 1447 1448 while (e) 1449 { 1450 e->r.RecordContext = e; 1451 tmp = e; 1452 e = e->next; 1453 FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree); 1454 } 1455 1456 if (srv->srs.RR_TXT.resrec.rdata != &srv->srs.RR_TXT.rdatastorage) 1457 freeL("TXT RData", srv->srs.RR_TXT.resrec.rdata); 1458 1459 if (srv->subtypes) { freeL("ServiceSubTypes", srv->subtypes); srv->subtypes = NULL; } 1460 freeL("service_instance", srv); 1461 } 1462 1463// Count how many other service records we have locally with the same name, but different rdata. 1464// For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of 1465// the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming. 1466mDNSexport int CountPeerRegistrations(mDNS *const m, ServiceRecordSet *const srs) 1467 { 1468 int count = 0; 1469 ResourceRecord *r = &srs->RR_SRV.resrec; 1470 AuthRecord *rr; 1471 ServiceRecordSet *s; 1472 1473 for (rr = m->ResourceRecords; rr; rr=rr->next) 1474 if (rr->resrec.rrtype == kDNSType_SRV && SameDomainName(rr->resrec.name, r->name) && !IdenticalSameNameRecord(&rr->resrec, r)) 1475 count++; 1476 1477 for (s = m->ServiceRegistrations; s; s = s->uDNS_next) 1478 if (s->state != regState_Unregistered && SameDomainName(s->RR_SRV.resrec.name, r->name) && !IdenticalSameNameRecord(&s->RR_SRV.resrec, r)) 1479 count++; 1480 1481 verbosedebugf("%d peer registrations for %##s", count, r->name->c); 1482 return(count); 1483 } 1484 1485mDNSexport int CountExistingRegistrations(domainname *srv, mDNSIPPort port) 1486 { 1487 int count = 0; 1488 AuthRecord *rr; 1489 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next) 1490 if (rr->resrec.rrtype == kDNSType_SRV && 1491 mDNSSameIPPort(rr->resrec.rdata->u.srv.port, port) && 1492 SameDomainName(rr->resrec.name, srv)) 1493 count++; 1494 return(count); 1495 } 1496 1497mDNSlocal void SendServiceRemovalNotification(ServiceRecordSet *const srs) 1498 { 1499 reply_state *rep; 1500 service_instance *instance = srs->ServiceContext; 1501 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, 0, mStatus_NoError) != mStatus_NoError) 1502 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c); 1503 else { append_reply(instance->request, rep); instance->clientnotified = mDNSfalse; } 1504 } 1505 1506// service registration callback performs three duties - frees memory for deregistered services, 1507// handles name conflicts, and delivers completed registration information to the client 1508mDNSlocal void regservice_callback(mDNS *const m, ServiceRecordSet *const srs, mStatus result) 1509 { 1510 mStatus err; 1511 mDNSBool SuppressError = mDNSfalse; 1512 service_instance *instance = srs->ServiceContext; 1513 reply_state *rep; 1514 char *fmt = ""; 1515 if (mDNS_LoggingEnabled) 1516 fmt = (result == mStatus_NoError) ? "%3d: DNSServiceRegister(%##s, %u) REGISTERED" : 1517 (result == mStatus_MemFree) ? "%3d: DNSServiceRegister(%##s, %u) DEREGISTERED" : 1518 (result == mStatus_NameConflict) ? "%3d: DNSServiceRegister(%##s, %u) NAME CONFLICT" : 1519 "%3d: DNSServiceRegister(%##s, %u) %s %d"; 1520 (void)m; // Unused 1521 if (!srs) { LogMsg("regservice_callback: srs is NULL %d", result); return; } 1522 if (!instance) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result); return; } 1523 1524 // don't send errors up to client for wide-area, empty-string registrations 1525 if (instance->request && 1526 instance->request->u.servicereg.default_domain && 1527 !instance->default_local) 1528 SuppressError = mDNStrue; 1529 1530 LogOperation(fmt, instance->request ? instance->request->sd : -99, 1531 srs->RR_SRV.resrec.name->c, mDNSVal16(srs->RR_SRV.resrec.rdata->u.srv.port), SuppressError ? "suppressed error" : "CALLBACK", result); 1532 1533 if (!instance->request && result != mStatus_MemFree) { LogMsg("regservice_callback: instance->request is NULL %d", result); return; } 1534 1535 if (result == mStatus_NoError) 1536 { 1537 if (instance->request->u.servicereg.allowremotequery) 1538 { 1539 ExtraResourceRecord *e; 1540 srs->RR_ADV.AllowRemoteQuery = mDNStrue; 1541 srs->RR_PTR.AllowRemoteQuery = mDNStrue; 1542 srs->RR_SRV.AllowRemoteQuery = mDNStrue; 1543 srs->RR_TXT.AllowRemoteQuery = mDNStrue; 1544 for (e = instance->srs.Extras; e; e = e->next) e->r.AllowRemoteQuery = mDNStrue; 1545 } 1546 1547 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError) 1548 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c); 1549 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; } 1550 1551 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0) 1552 RecordUpdatedNiceLabel(m, 0); // Successfully got new name, tell user immediately 1553 } 1554 else if (result == mStatus_MemFree) 1555 { 1556 if (instance->request && instance->renameonmemfree) 1557 { 1558 instance->renameonmemfree = 0; 1559 err = mDNS_RenameAndReregisterService(m, srs, &instance->request->u.servicereg.name); 1560 if (err) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err); 1561 // error should never happen - safest to log and continue 1562 } 1563 else 1564 unlink_and_free_service_instance(instance); 1565 } 1566 else if (result == mStatus_NameConflict) 1567 { 1568 if (instance->request->u.servicereg.autorename) 1569 { 1570 if (instance->request->u.servicereg.autoname && CountPeerRegistrations(m, srs) == 0) 1571 { 1572 // On conflict for an autoname service, rename and reregister *all* autoname services 1573 IncrementLabelSuffix(&m->nicelabel, mDNStrue); 1574 mDNS_ConfigChanged(m); // Will call back into udsserver_handle_configchange() 1575 } 1576 else // On conflict for a non-autoname service, rename and reregister just that one service 1577 { 1578 if (instance->clientnotified) SendServiceRemovalNotification(srs); 1579 mDNS_RenameAndReregisterService(m, srs, mDNSNULL); 1580 } 1581 } 1582 else 1583 { 1584 if (!SuppressError) 1585 { 1586 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError) 1587 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c); 1588 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; } 1589 } 1590 unlink_and_free_service_instance(instance); 1591 } 1592 } 1593 else 1594 { 1595 if (!SuppressError) 1596 { 1597 if (GenerateNTDResponse(srs->RR_SRV.resrec.name, srs->RR_SRV.resrec.InterfaceID, instance->request, &rep, reg_service_reply_op, kDNSServiceFlagsAdd, result) != mStatus_NoError) 1598 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance->request->sd, srs->RR_SRV.resrec.name->c); 1599 else { append_reply(instance->request, rep); instance->clientnotified = mDNStrue; } 1600 } 1601 } 1602 } 1603 1604mDNSlocal void regrecord_callback(mDNS *const m, AuthRecord *rr, mStatus result) 1605 { 1606 (void)m; // Unused 1607 if (!rr->RecordContext) // parent struct already freed by termination callback 1608 { 1609 if (result == mStatus_NoError) 1610 LogMsg("Error: regrecord_callback: successful registration of orphaned record"); 1611 else 1612 { 1613 if (result != mStatus_MemFree) LogMsg("regrecord_callback: error %d received after parent termination", result); 1614 freeL("AuthRecord/regrecord_callback", rr); 1615 } 1616 } 1617 else 1618 { 1619 registered_record_entry *re = rr->RecordContext; 1620 request_state *request = re->request; 1621 int len = sizeof(DNSServiceFlags) + sizeof(mDNSu32) + sizeof(DNSServiceErrorType); 1622 reply_state *reply = create_reply(reg_record_reply_op, len, request); 1623 reply->mhdr->client_context = re->regrec_client_context; 1624 reply->rhdr->flags = dnssd_htonl(0); 1625 reply->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, rr->resrec.InterfaceID)); 1626 reply->rhdr->error = dnssd_htonl(result); 1627 1628 LogOperation("%3d: DNSServiceRegisterRecord(%u) result %d", request->sd, request->hdr.reg_index, result); 1629 if (result) 1630 { 1631 // unlink from list, free memory 1632 registered_record_entry **ptr = &request->u.reg_recs; 1633 while (*ptr && (*ptr) != re) ptr = &(*ptr)->next; 1634 if (!*ptr) { LogMsg("regrecord_callback - record not in list!"); return; } 1635 *ptr = (*ptr)->next; 1636 freeL("registered_record_entry AuthRecord regrecord_callback", re->rr); 1637 freeL("registered_record_entry regrecord_callback", re); 1638 } 1639 append_reply(request, reply); 1640 } 1641 } 1642 1643mDNSlocal void connection_termination(request_state *request) 1644 { 1645 request_state **req = &all_requests; 1646 while (*req) 1647 { 1648 if ((*req)->primary == request) 1649 { 1650 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree() 1651 request_state *tmp = *req; 1652 if (tmp->primary == tmp) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp, tmp->sd); 1653 if (tmp->replies) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp, tmp->sd); 1654 abort_request(tmp); 1655 *req = tmp->next; 1656 freeL("request_state/connection_termination", tmp); 1657 } 1658 else 1659 req = &(*req)->next; 1660 } 1661 1662 while (request->u.reg_recs) 1663 { 1664 registered_record_entry *ptr = request->u.reg_recs; 1665 request->u.reg_recs = request->u.reg_recs->next; 1666 ptr->rr->RecordContext = NULL; 1667 mDNS_Deregister(&mDNSStorage, ptr->rr); // Will free ptr->rr for us 1668 freeL("registered_record_entry/connection_termination", ptr); 1669 } 1670 } 1671 1672mDNSlocal void handle_cancel_request(request_state *request) 1673 { 1674 request_state **req = &all_requests; 1675 LogOperation("%3d: Cancel %08X %08X", request->sd, request->hdr.client_context.u32[1], request->hdr.client_context.u32[0]); 1676 while (*req) 1677 { 1678 if ((*req)->primary == request && 1679 (*req)->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] && 1680 (*req)->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) 1681 { 1682 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree() 1683 request_state *tmp = *req; 1684 abort_request(tmp); 1685 *req = tmp->next; 1686 freeL("request_state/handle_cancel_request", tmp); 1687 } 1688 else 1689 req = &(*req)->next; 1690 } 1691 } 1692 1693mDNSlocal mStatus handle_regrecord_request(request_state *request) 1694 { 1695 mStatus err = mStatus_BadParamErr; 1696 AuthRecord *rr = read_rr_from_ipc_msg(request, 1, 1); 1697 if (rr) 1698 { 1699 // allocate registration entry, link into list 1700 registered_record_entry *re = mallocL("registered_record_entry", sizeof(registered_record_entry)); 1701 if (!re) FatalError("ERROR: malloc"); 1702 re->key = request->hdr.reg_index; 1703 re->rr = rr; 1704 re->request = request; 1705 re->regrec_client_context = request->hdr.client_context; 1706 rr->RecordContext = re; 1707 rr->RecordCallback = regrecord_callback; 1708 re->next = request->u.reg_recs; 1709 request->u.reg_recs = re; 1710 1711#if 0 1712 if (!AuthorizedDomain(request, rr->resrec.name, AutoRegistrationDomains)) return (mStatus_NoError); 1713#endif 1714 if (rr->resrec.rroriginalttl == 0) 1715 rr->resrec.rroriginalttl = DefaultTTLforRRType(rr->resrec.rrtype); 1716 1717 LogOperation("%3d: DNSServiceRegisterRecord(%u %s)", request->sd, request->hdr.reg_index, RRDisplayString(&mDNSStorage, &rr->resrec)); 1718 err = mDNS_Register(&mDNSStorage, rr); 1719 } 1720 return(err); 1721 } 1722 1723mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m); 1724 1725mDNSlocal void regservice_termination_callback(request_state *request) 1726 { 1727 if (!request) { LogMsg("regservice_termination_callback context is NULL"); return; } 1728 while (request->u.servicereg.instances) 1729 { 1730 service_instance *p = request->u.servicereg.instances; 1731 request->u.servicereg.instances = request->u.servicereg.instances->next; 1732 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p) 1733 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP", 1734 request->sd, p->srs.RR_SRV.resrec.name->c, mDNSVal16(p->srs.RR_SRV.resrec.rdata->u.srv.port)); 1735 1736 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance 1737 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing 1738 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time 1739 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance 1740 // because by then we might have already freed p 1741 p->request = NULL; 1742 if (mDNS_DeregisterService(&mDNSStorage, &p->srs)) unlink_and_free_service_instance(p); 1743 // Don't touch service_instance *p after this -- it's likely to have been freed already 1744 } 1745 if (request->u.servicereg.txtdata) 1746 { freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; } 1747 if (request->u.servicereg.autoname) 1748 { 1749 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations 1750 request->u.servicereg.autoname = mDNSfalse; 1751 UpdateDeviceInfoRecord(&mDNSStorage); 1752 } 1753 } 1754 1755mDNSlocal request_state *LocateSubordinateRequest(request_state *request) 1756 { 1757 request_state *req; 1758 for (req = all_requests; req; req = req->next) 1759 if (req->primary == request && 1760 req->hdr.client_context.u32[0] == request->hdr.client_context.u32[0] && 1761 req->hdr.client_context.u32[1] == request->hdr.client_context.u32[1]) return(req); 1762 return(request); 1763 } 1764 1765mDNSlocal mStatus add_record_to_service(request_state *request, service_instance *instance, mDNSu16 rrtype, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl) 1766 { 1767 ServiceRecordSet *srs = &instance->srs; 1768 mStatus result; 1769 int size = rdlen > sizeof(RDataBody) ? rdlen : sizeof(RDataBody); 1770 ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size); 1771 if (!extra) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; } 1772 1773 mDNSPlatformMemZero(extra, sizeof(ExtraResourceRecord)); // OK if oversized rdata not zero'd 1774 extra->r.resrec.rrtype = rrtype; 1775 extra->r.rdatastorage.MaxRDLength = (mDNSu16) size; 1776 extra->r.resrec.rdlength = rdlen; 1777 mDNSPlatformMemCopy(&extra->r.rdatastorage.u.data, rdata, rdlen); 1778 1779 result = mDNS_AddRecordToService(&mDNSStorage, srs, extra, &extra->r.rdatastorage, ttl); 1780 if (result) { freeL("ExtraResourceRecord/add_record_to_service", extra); return result; } 1781 1782 extra->ClientID = request->hdr.reg_index; 1783 return result; 1784 } 1785 1786mDNSlocal mStatus handle_add_request(request_state *request) 1787 { 1788 service_instance *i; 1789 mStatus result = mStatus_UnknownErr; 1790 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend); 1791 mDNSu16 rrtype = get_uint16(&request->msgptr, request->msgend); 1792 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend); 1793 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen); 1794 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend); 1795 if (!ttl) ttl = DefaultTTLforRRType(rrtype); 1796 (void)flags; // Unused 1797 1798 if (!request->msgptr) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 1799 1800 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object 1801 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request); 1802 1803 if (request->terminate != regservice_termination_callback) 1804 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); } 1805 1806 LogOperation("%3d: DNSServiceAddRecord(%##s, %s, %d)", request->sd, 1807 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, DNSTypeName(rrtype), rdlen); 1808 1809 for (i = request->u.servicereg.instances; i; i = i->next) 1810 { 1811 result = add_record_to_service(request, i, rrtype, rdlen, rdata, ttl); 1812 if (result && i->default_local) break; 1813 else result = mStatus_NoError; // suppress non-local default errors 1814 } 1815 1816 return(result); 1817 } 1818 1819mDNSlocal void update_callback(mDNS *const m, AuthRecord *const rr, RData *oldrd) 1820 { 1821 (void)m; // Unused 1822 if (oldrd != &rr->rdatastorage) freeL("RData/update_callback", oldrd); 1823 } 1824 1825mDNSlocal mStatus update_record(AuthRecord *rr, mDNSu16 rdlen, const char *rdata, mDNSu32 ttl) 1826 { 1827 int rdsize; 1828 RData *newrd; 1829 mStatus result; 1830 1831 if (rdlen > sizeof(RDataBody)) rdsize = rdlen; 1832 else rdsize = sizeof(RDataBody); 1833 newrd = mallocL("RData/update_record", sizeof(RData) - sizeof(RDataBody) + rdsize); 1834 if (!newrd) FatalError("ERROR: malloc"); 1835 newrd->MaxRDLength = (mDNSu16) rdsize; 1836 mDNSPlatformMemCopy(&newrd->u, rdata, rdlen); 1837 1838 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct, 1839 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s". 1840 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here. 1841 if (rr->resrec.rrtype == kDNSType_TXT && rdlen == 0) { rdlen = 1; newrd->u.txt.c[0] = 0; } 1842 1843 result = mDNS_Update(&mDNSStorage, rr, ttl, rdlen, newrd, update_callback); 1844 if (result) { LogMsg("ERROR: mDNS_Update - %d", result); freeL("RData/update_record", newrd); } 1845 return result; 1846 } 1847 1848mDNSlocal mStatus handle_update_request(request_state *request) 1849 { 1850 const ipc_msg_hdr *const hdr = &request->hdr; 1851 mStatus result = mStatus_BadReferenceErr; 1852 service_instance *i; 1853 AuthRecord *rr = NULL; 1854 1855 // get the message data 1856 DNSServiceFlags flags = get_flags (&request->msgptr, request->msgend); // flags unused 1857 mDNSu16 rdlen = get_uint16(&request->msgptr, request->msgend); 1858 const char *rdata = get_rdata (&request->msgptr, request->msgend, rdlen); 1859 mDNSu32 ttl = get_uint32(&request->msgptr, request->msgend); 1860 (void)flags; // Unused 1861 1862 if (!request->msgptr) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 1863 1864 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object 1865 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request); 1866 1867 if (request->terminate == connection_termination) 1868 { 1869 // update an individually registered record 1870 registered_record_entry *reptr; 1871 for (reptr = request->u.reg_recs; reptr; reptr = reptr->next) 1872 { 1873 if (reptr->key == hdr->reg_index) 1874 { 1875 result = update_record(reptr->rr, rdlen, rdata, ttl); 1876 goto end; 1877 } 1878 } 1879 result = mStatus_BadReferenceErr; 1880 goto end; 1881 } 1882 1883 if (request->terminate != regservice_termination_callback) 1884 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); } 1885 1886 // update the saved off TXT data for the service 1887 if (hdr->reg_index == TXT_RECORD_INDEX) 1888 { 1889 if (request->u.servicereg.txtdata) 1890 { freeL("service_info txtdata", request->u.servicereg.txtdata); request->u.servicereg.txtdata = NULL; } 1891 if (rdlen > 0) 1892 { 1893 request->u.servicereg.txtdata = mallocL("service_info txtdata", rdlen); 1894 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_update_request - malloc"); 1895 mDNSPlatformMemCopy(request->u.servicereg.txtdata, rdata, rdlen); 1896 } 1897 else 1898 request->u.servicereg.txtdata = NULL; 1899 } 1900 1901 // update a record from a service record set 1902 for (i = request->u.servicereg.instances; i; i = i->next) 1903 { 1904 if (hdr->reg_index == TXT_RECORD_INDEX) rr = &i->srs.RR_TXT; 1905 else 1906 { 1907 ExtraResourceRecord *e; 1908 for (e = i->srs.Extras; e; e = e->next) 1909 if (e->ClientID == hdr->reg_index) { rr = &e->r; break; } 1910 } 1911 1912 if (!rr) { result = mStatus_BadReferenceErr; goto end; } 1913 result = update_record(rr, rdlen, rdata, ttl); 1914 if (result && i->default_local) goto end; 1915 else result = mStatus_NoError; // suppress non-local default errors 1916 } 1917 1918end: 1919 if (request->terminate == regservice_termination_callback) 1920 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)", request->sd, 1921 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, 1922 rr ? DNSTypeName(rr->resrec.rrtype) : "<NONE>"); 1923 1924 return(result); 1925 } 1926 1927// remove a resource record registered via DNSServiceRegisterRecord() 1928mDNSlocal mStatus remove_record(request_state *request) 1929 { 1930 mStatus err = mStatus_UnknownErr; 1931 registered_record_entry *e, **ptr = &request->u.reg_recs; 1932 1933 while (*ptr && (*ptr)->key != request->hdr.reg_index) ptr = &(*ptr)->next; 1934 if (!*ptr) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request->sd, request->hdr.reg_index); return mStatus_BadReferenceErr; } 1935 e = *ptr; 1936 *ptr = e->next; // unlink 1937 1938 LogOperation("%3d: DNSServiceRemoveRecord(%u %s)", request->sd, request->hdr.reg_index, RRDisplayString(&mDNSStorage, &e->rr->resrec)); 1939 e->rr->RecordContext = NULL; 1940 err = mDNS_Deregister(&mDNSStorage, e->rr); 1941 if (err) 1942 { 1943 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err); 1944 freeL("registered_record_entry AuthRecord remove_record", e->rr); 1945 } 1946 freeL("registered_record_entry remove_record", e); 1947 return err; 1948 } 1949 1950mDNSlocal mStatus remove_extra(const request_state *const request, service_instance *const serv, mDNSu16 *const rrtype) 1951 { 1952 mStatus err = mStatus_BadReferenceErr; 1953 ExtraResourceRecord *ptr; 1954 1955 for (ptr = serv->srs.Extras; ptr; ptr = ptr->next) 1956 { 1957 if (ptr->ClientID == request->hdr.reg_index) // found match 1958 { 1959 *rrtype = ptr->r.resrec.rrtype; 1960 return mDNS_RemoveRecordFromService(&mDNSStorage, &serv->srs, ptr, FreeExtraRR, ptr); 1961 } 1962 } 1963 return err; 1964 } 1965 1966mDNSlocal mStatus handle_removerecord_request(request_state *request) 1967 { 1968 mStatus err = mStatus_BadReferenceErr; 1969 get_flags(&request->msgptr, request->msgend); // flags unused 1970 1971 if (!request->msgptr) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 1972 1973 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object 1974 if (request->terminate == connection_termination) request = LocateSubordinateRequest(request); 1975 1976 if (request->terminate == connection_termination) 1977 err = remove_record(request); // remove individually registered record 1978 else if (request->terminate != regservice_termination_callback) 1979 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request->sd); return(mStatus_BadParamErr); } 1980 else 1981 { 1982 service_instance *i; 1983 mDNSu16 rrtype = 0; 1984 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s)", request->sd, 1985 (request->u.servicereg.instances) ? request->u.servicereg.instances->srs.RR_SRV.resrec.name->c : NULL, 1986 rrtype ? DNSTypeName(rrtype) : "<NONE>"); 1987 for (i = request->u.servicereg.instances; i; i = i->next) 1988 { 1989 err = remove_extra(request, i, &rrtype); 1990 if (err && i->default_local) break; 1991 else err = mStatus_NoError; // suppress non-local default errors 1992 } 1993 } 1994 1995 return(err); 1996 } 1997 1998// If there's a comma followed by another character, 1999// FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character. 2000// Otherwise, it returns a pointer to the final nul at the end of the string 2001mDNSlocal char *FindFirstSubType(char *p) 2002 { 2003 while (*p) 2004 { 2005 if (p[0] == '\\' && p[1]) p += 2; 2006 else if (p[0] == ',' && p[1]) { *p++ = 0; return(p); } 2007 else p++; 2008 } 2009 return(p); 2010 } 2011 2012// If there's a comma followed by another character, 2013// FindNextSubType overwrites the comma with a nul and returns the pointer to the next character. 2014// If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL 2015// Otherwise, it returns a pointer to the final nul at the end of the string 2016mDNSlocal char *FindNextSubType(char *p) 2017 { 2018 while (*p) 2019 { 2020 if (p[0] == '\\' && p[1]) // If escape character 2021 p += 2; // ignore following character 2022 else if (p[0] == ',') // If we found a comma 2023 { 2024 if (p[1]) *p++ = 0; 2025 return(p); 2026 } 2027 else if (p[0] == '.') 2028 return(mDNSNULL); 2029 else p++; 2030 } 2031 return(p); 2032 } 2033 2034// Returns -1 if illegal subtype found 2035mDNSexport mDNSs32 ChopSubTypes(char *regtype) 2036 { 2037 mDNSs32 NumSubTypes = 0; 2038 char *stp = FindFirstSubType(regtype); 2039 while (stp && *stp) // If we found a comma... 2040 { 2041 if (*stp == ',') return(-1); 2042 NumSubTypes++; 2043 stp = FindNextSubType(stp); 2044 } 2045 if (!stp) return(-1); 2046 return(NumSubTypes); 2047 } 2048 2049mDNSexport AuthRecord *AllocateSubTypes(mDNSs32 NumSubTypes, char *p) 2050 { 2051 AuthRecord *st = mDNSNULL; 2052 if (NumSubTypes) 2053 { 2054 mDNSs32 i; 2055 st = mallocL("ServiceSubTypes", NumSubTypes * sizeof(AuthRecord)); 2056 if (!st) return(mDNSNULL); 2057 for (i = 0; i < NumSubTypes; i++) 2058 { 2059 mDNS_SetupResourceRecord(&st[i], mDNSNULL, mDNSInterface_Any, kDNSQType_ANY, kStandardTTL, 0, mDNSNULL, mDNSNULL); 2060 while (*p) p++; 2061 p++; 2062 if (!MakeDomainNameFromDNSNameString(&st[i].namestorage, p)) 2063 { freeL("ServiceSubTypes", st); return(mDNSNULL); } 2064 } 2065 } 2066 return(st); 2067 } 2068 2069mDNSlocal mStatus register_service_instance(request_state *request, const domainname *domain) 2070 { 2071 service_instance **ptr, *instance; 2072 int instance_size; 2073 mStatus result; 2074 2075 for (ptr = &request->u.servicereg.instances; *ptr; ptr = &(*ptr)->next) 2076 { 2077 if (SameDomainName(&(*ptr)->domain, domain)) 2078 { 2079 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s", 2080 domain->c, &request->u.servicereg.name, &request->u.servicereg.type); 2081 return mStatus_AlreadyRegistered; 2082 } 2083 } 2084 2085 // Special-case hack: We don't advertise SMB service in AutoTunnel domains, because AutoTunnel 2086 // services have to support IPv6, and our SMB server does not 2087 // <rdar://problem/5482322> BTMM: Don't advertise SMB with BTMM because it doesn't support IPv6 2088 if (SameDomainName(&request->u.servicereg.type, (const domainname *) "\x4" "_smb" "\x4" "_tcp")) 2089 { 2090 DomainAuthInfo *AuthInfo = GetAuthInfoForName(&mDNSStorage, domain); 2091 if (AuthInfo && AuthInfo->AutoTunnel) return(kDNSServiceErr_Unsupported); 2092 } 2093 2094 instance_size = sizeof(*instance); 2095 if (request->u.servicereg.txtlen > sizeof(RDataBody)) instance_size += (request->u.servicereg.txtlen - sizeof(RDataBody)); 2096 instance = mallocL("service_instance", instance_size); 2097 if (!instance) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr; } 2098 2099 instance->next = mDNSNULL; 2100 instance->request = request; 2101 instance->subtypes = AllocateSubTypes(request->u.servicereg.num_subtypes, request->u.servicereg.type_as_string); 2102 instance->renameonmemfree = 0; 2103 instance->clientnotified = mDNSfalse; 2104 instance->default_local = (request->u.servicereg.default_domain && SameDomainName(domain, &localdomain)); 2105 AssignDomainName(&instance->domain, domain); 2106 2107 if (request->u.servicereg.num_subtypes && !instance->subtypes) 2108 { unlink_and_free_service_instance(instance); instance = NULL; FatalError("ERROR: malloc"); } 2109 2110 result = mDNS_RegisterService(&mDNSStorage, &instance->srs, 2111 &request->u.servicereg.name, &request->u.servicereg.type, domain, 2112 request->u.servicereg.host.c[0] ? &request->u.servicereg.host : NULL, 2113 request->u.servicereg.port, 2114 request->u.servicereg.txtdata, request->u.servicereg.txtlen, 2115 instance->subtypes, request->u.servicereg.num_subtypes, 2116 request->u.servicereg.InterfaceID, regservice_callback, instance); 2117 2118 if (!result) 2119 { 2120 *ptr = instance; // Append this to the end of our request->u.servicereg.instances list 2121 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED", 2122 instance->request->sd, instance->srs.RR_SRV.resrec.name->c, mDNSVal16(request->u.servicereg.port)); 2123 } 2124 else 2125 { 2126 LogMsg("register_service_instance %#s.%##s%##s error %d", 2127 &request->u.servicereg.name, &request->u.servicereg.type, domain->c, result); 2128 unlink_and_free_service_instance(instance); 2129 } 2130 2131 return result; 2132 } 2133 2134mDNSlocal void udsserver_default_reg_domain_changed(const DNameListElem *const d, const mDNSBool add) 2135 { 2136 request_state *request; 2137 2138#if APPLE_OSX_mDNSResponder 2139 machserver_automatic_registration_domain_changed(&d->name, add); 2140#endif // APPLE_OSX_mDNSResponder 2141 2142 LogMsg("%s registration domain %##s", add ? "Adding" : "Removing", d->name.c); 2143 for (request = all_requests; request; request = request->next) 2144 { 2145 if (request->terminate != regservice_termination_callback) continue; 2146 if (!request->u.servicereg.default_domain) continue; 2147 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid) 2148 { 2149 service_instance **ptr = &request->u.servicereg.instances; 2150 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next; 2151 if (add) 2152 { 2153 // If we don't already have this domain in our list for this registration, add it now 2154 if (!*ptr) register_service_instance(request, &d->name); 2155 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d->name); 2156 } 2157 else 2158 { 2159 // Normally we should not fail to find the specified instance 2160 // One case where this can happen is if a uDNS update fails for some reason, 2161 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance. 2162 if (!*ptr) 2163 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s", 2164 &d->name, request->u.servicereg.name.c, request->u.servicereg.type_as_string); 2165 else 2166 { 2167 DNameListElem *p; 2168 for (p = AutoRegistrationDomains; p; p=p->next) 2169 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid) 2170 if (SameDomainName(&d->name, &p->name)) break; 2171 if (p) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d->name); 2172 else 2173 { 2174 mStatus err; 2175 service_instance *si = *ptr; 2176 *ptr = si->next; 2177 if (si->clientnotified) SendServiceRemovalNotification(&si->srs); // Do this *before* clearing si->request backpointer 2178 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer. 2179 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the 2180 // process of completing asynchronously, the client cancels the entire operation, so 2181 // regservice_termination_callback then runs through the whole list deregistering each 2182 // instance, clearing the backpointers, and then disposing the parent request_state object. 2183 // However, because this service_instance isn't in the list any more, regservice_termination_callback 2184 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally 2185 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with 2186 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed. 2187 si->request = NULL; 2188 err = mDNS_DeregisterService(&mDNSStorage, &si->srs); 2189 if (err) { LogMsg("udsserver_default_reg_domain_changed err %d", err); unlink_and_free_service_instance(si); } 2190 } 2191 } 2192 } 2193 } 2194 } 2195 } 2196 2197mDNSlocal mStatus handle_regservice_request(request_state *request) 2198 { 2199 char name[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes 2200 char domain[MAX_ESCAPED_DOMAIN_NAME], host[MAX_ESCAPED_DOMAIN_NAME]; 2201 char type_as_string[MAX_ESCAPED_DOMAIN_NAME]; 2202 domainname d, srv; 2203 mStatus err; 2204 2205 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 2206 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend); 2207 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex); 2208 if (interfaceIndex && !InterfaceID) 2209 { LogMsg("ERROR: handle_regservice_request - Couldn't find interfaceIndex %d", interfaceIndex); return(mStatus_BadParamErr); } 2210 2211 if (get_string(&request->msgptr, request->msgend, name, sizeof(name)) < 0 || 2212 get_string(&request->msgptr, request->msgend, type_as_string, MAX_ESCAPED_DOMAIN_NAME) < 0 || 2213 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0 || 2214 get_string(&request->msgptr, request->msgend, host, MAX_ESCAPED_DOMAIN_NAME) < 0) 2215 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); } 2216 2217 request->u.servicereg.InterfaceID = InterfaceID; 2218 request->u.servicereg.instances = NULL; 2219 request->u.servicereg.txtlen = 0; 2220 request->u.servicereg.txtdata = NULL; 2221 mDNSPlatformStrCopy(request->u.servicereg.type_as_string, type_as_string); 2222 2223 if (request->msgptr + 2 > request->msgend) request->msgptr = NULL; 2224 else 2225 { 2226 request->u.servicereg.port.b[0] = *request->msgptr++; 2227 request->u.servicereg.port.b[1] = *request->msgptr++; 2228 } 2229 2230 request->u.servicereg.txtlen = get_uint16(&request->msgptr, request->msgend); 2231 if (request->u.servicereg.txtlen) 2232 { 2233 request->u.servicereg.txtdata = mallocL("service_info txtdata", request->u.servicereg.txtlen); 2234 if (!request->u.servicereg.txtdata) FatalError("ERROR: handle_regservice_request - malloc"); 2235 mDNSPlatformMemCopy(request->u.servicereg.txtdata, get_rdata(&request->msgptr, request->msgend, request->u.servicereg.txtlen), request->u.servicereg.txtlen); 2236 } 2237 else request->u.servicereg.txtdata = NULL; 2238 2239 if (!request->msgptr) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 2240 2241 // Check for sub-types after the service type 2242 request->u.servicereg.num_subtypes = ChopSubTypes(request->u.servicereg.type_as_string); // Note: Modifies regtype string to remove trailing subtypes 2243 if (request->u.servicereg.num_subtypes < 0) 2244 { LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request->u.servicereg.type_as_string); return(mStatus_BadParamErr); } 2245 2246 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic 2247 if (!*request->u.servicereg.type_as_string || !MakeDomainNameFromDNSNameString(&request->u.servicereg.type, request->u.servicereg.type_as_string)) 2248 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request->u.servicereg.type_as_string); return(mStatus_BadParamErr); } 2249 2250 if (!name[0]) 2251 { 2252 request->u.servicereg.name = mDNSStorage.nicelabel; 2253 request->u.servicereg.autoname = mDNStrue; 2254 } 2255 else 2256 { 2257 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel 2258 if ((flags & kDNSServiceFlagsNoAutoRename) == 0) 2259 { 2260 int newlen = TruncateUTF8ToLength((mDNSu8*)name, mDNSPlatformStrLen(name), MAX_DOMAIN_LABEL); 2261 name[newlen] = 0; 2262 } 2263 if (!MakeDomainLabelFromLiteralString(&request->u.servicereg.name, name)) 2264 { LogMsg("ERROR: handle_regservice_request - name bad %s", name); return(mStatus_BadParamErr); } 2265 request->u.servicereg.autoname = mDNSfalse; 2266 } 2267 2268 if (*domain) 2269 { 2270 request->u.servicereg.default_domain = mDNSfalse; 2271 if (!MakeDomainNameFromDNSNameString(&d, domain)) 2272 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain); return(mStatus_BadParamErr); } 2273 } 2274 else 2275 { 2276 request->u.servicereg.default_domain = mDNStrue; 2277 MakeDomainNameFromDNSNameString(&d, "local."); 2278 } 2279 2280 if (!ConstructServiceName(&srv, &request->u.servicereg.name, &request->u.servicereg.type, &d)) 2281 { 2282 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”", 2283 request->u.servicereg.name.c, request->u.servicereg.type.c, d.c); return(mStatus_BadParamErr); 2284 } 2285 2286 if (!MakeDomainNameFromDNSNameString(&request->u.servicereg.host, host)) 2287 { LogMsg("ERROR: handle_regservice_request - host bad %s", host); return(mStatus_BadParamErr); } 2288 request->u.servicereg.autorename = (flags & kDNSServiceFlagsNoAutoRename ) == 0; 2289 request->u.servicereg.allowremotequery = (flags & kDNSServiceFlagsAllowRemoteQuery) != 0; 2290 2291 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with 2292 // a port number of zero. When two instances of the protected client are allowed to run on one 2293 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console. 2294 if (!mDNSIPPortIsZero(request->u.servicereg.port)) 2295 { 2296 int count = CountExistingRegistrations(&srv, request->u.servicereg.port); 2297 if (count) 2298 LogMsg("Client application registered %d identical instances of service %##s port %u.", 2299 count+1, srv.c, mDNSVal16(request->u.servicereg.port)); 2300 } 2301 2302 LogOperation("%3d: DNSServiceRegister(\"%s\", \"%s\", \"%s\", \"%s\", %u) START", 2303 request->sd, name, request->u.servicereg.type_as_string, domain, host, mDNSVal16(request->u.servicereg.port)); 2304 2305 // We need to unconditionally set request->terminate, because even if we didn't successfully 2306 // start any registrations right now, subsequent configuration changes may cause successful 2307 // registrations to be added, and we'll need to cancel them before freeing this memory. 2308 // We also need to set request->terminate first, before adding additional service instances, 2309 // because the uds_validatelists uses the request->terminate function pointer to determine 2310 // what kind of request this is, and therefore what kind of list validation is required. 2311 request->terminate = regservice_termination_callback; 2312 2313 err = register_service_instance(request, &d); 2314 2315#if 0 2316 err = AuthorizedDomain(request, &d, AutoRegistrationDomains) ? register_service_instance(request, &d) : mStatus_NoError; 2317#endif 2318 if (!err) 2319 { 2320 if (request->u.servicereg.autoname) UpdateDeviceInfoRecord(&mDNSStorage); 2321 2322 if (!*domain) 2323 { 2324 DNameListElem *ptr; 2325 // Note that we don't report errors for non-local, non-explicit domains 2326 for (ptr = AutoRegistrationDomains; ptr; ptr = ptr->next) 2327 if (!ptr->uid || SystemUID(request->uid) || request->uid == ptr->uid) 2328 register_service_instance(request, &ptr->name); 2329 } 2330 } 2331 2332 return(err); 2333 } 2334 2335// *************************************************************************** 2336#if COMPILER_LIKES_PRAGMA_MARK 2337#pragma mark - 2338#pragma mark - DNSServiceBrowse 2339#endif 2340 2341mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord) 2342 { 2343 const DNSServiceFlags flags = AddRecord ? kDNSServiceFlagsAdd : 0; 2344 request_state *req = question->QuestionContext; 2345 reply_state *rep; 2346 (void)m; // Unused 2347 2348 if (answer->rrtype != kDNSType_PTR) 2349 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req->sd, answer->rrtype); return; } 2350 2351 if (GenerateNTDResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError) != mStatus_NoError) 2352 { 2353 if (SameDomainName(&req->u.browser.regtype, (const domainname*)"\x09_services\x07_dns-sd\x04_udp")) 2354 { 2355 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser 2356 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse 2357 GenerateBonjourBrowserResponse(&answer->rdata->u.name, answer->InterfaceID, req, &rep, browse_reply_op, flags, mStatus_NoError); 2358 goto bonjourbrowserhack; 2359 } 2360 2361 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer", 2362 req->sd, answer->name->c, answer->rdata->u.name.c); 2363 return; 2364 } 2365 2366bonjourbrowserhack: 2367 2368 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s", 2369 req->sd, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "Add" : "Rmv", 2370 mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID), RRDisplayString(m, answer)); 2371 2372 append_reply(req, rep); 2373 } 2374 2375mDNSlocal mStatus add_domain_to_browser(request_state *info, const domainname *d) 2376 { 2377 browser_t *b, *p; 2378 mStatus err; 2379 2380 for (p = info->u.browser.browsers; p; p = p->next) 2381 { 2382 if (SameDomainName(&p->domain, d)) 2383 { debugf("add_domain_to_browser %##s already in list", d->c); return mStatus_AlreadyRegistered; } 2384 } 2385 2386 b = mallocL("browser_t", sizeof(*b)); 2387 if (!b) return mStatus_NoMemoryErr; 2388 AssignDomainName(&b->domain, d); 2389 err = mDNS_StartBrowse(&mDNSStorage, &b->q, 2390 &info->u.browser.regtype, d, info->u.browser.interface_id, info->u.browser.ForceMCast, FoundInstance, info); 2391 if (err) 2392 { 2393 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err, info->u.browser.regtype.c, d->c); 2394 freeL("browser_t/add_domain_to_browser", b); 2395 } 2396 else 2397 { 2398 b->next = info->u.browser.browsers; 2399 info->u.browser.browsers = b; 2400 LogOperation("%3d: DNSServiceBrowse(%##s) START", info->sd, b->q.qname.c); 2401 } 2402 return err; 2403 } 2404 2405mDNSlocal void browse_termination_callback(request_state *info) 2406 { 2407 while (info->u.browser.browsers) 2408 { 2409 browser_t *ptr = info->u.browser.browsers; 2410 info->u.browser.browsers = ptr->next; 2411 LogOperation("%3d: DNSServiceBrowse(%##s) STOP", info->sd, ptr->q.qname.c); 2412 mDNS_StopBrowse(&mDNSStorage, &ptr->q); // no need to error-check result 2413 freeL("browser_t/browse_termination_callback", ptr); 2414 } 2415 } 2416 2417mDNSlocal void udsserver_automatic_browse_domain_changed(const DNameListElem *const d, const mDNSBool add) 2418 { 2419 request_state *request; 2420 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add ? "Adding" : "Removing", d->name.c); 2421 2422#if APPLE_OSX_mDNSResponder 2423 machserver_automatic_browse_domain_changed(&d->name, add); 2424#endif // APPLE_OSX_mDNSResponder 2425 2426 for (request = all_requests; request; request = request->next) 2427 { 2428 if (request->terminate != browse_termination_callback) continue; // Not a browse operation 2429 if (!request->u.browser.default_domain) continue; // Not an auto-browse operation 2430 if (!d->uid || SystemUID(request->uid) || request->uid == d->uid) 2431 { 2432 browser_t **ptr = &request->u.browser.browsers; 2433 while (*ptr && !SameDomainName(&(*ptr)->domain, &d->name)) ptr = &(*ptr)->next; 2434 if (add) 2435 { 2436 // If we don't already have this domain in our list for this browse operation, add it now 2437 if (!*ptr) add_domain_to_browser(request, &d->name); 2438 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d->name); 2439 } 2440 else 2441 { 2442 if (!*ptr) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d->name); 2443 else 2444 { 2445 DNameListElem *p; 2446 for (p = AutoBrowseDomains; p; p=p->next) 2447 if (!p->uid || SystemUID(request->uid) || request->uid == p->uid) 2448 if (SameDomainName(&d->name, &p->name)) break; 2449 if (p) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d->name); 2450 else 2451 { 2452 browser_t *rem = *ptr; 2453 *ptr = (*ptr)->next; 2454 mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q); 2455 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem); 2456 } 2457 } 2458 } 2459 } 2460 } 2461 } 2462 2463mDNSlocal void FreeARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result) 2464 { 2465 (void)m; // unused 2466 if (result == mStatus_MemFree) 2467 { 2468 // On shutdown, mDNS_Close automatically deregisters all records 2469 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record 2470 // from the LocalDomainEnumRecords list, we do this here before we free the memory. 2471 ARListElem **ptr = &LocalDomainEnumRecords; 2472 while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next; 2473 if (*ptr) *ptr = (*ptr)->next; 2474 mDNSPlatformMemFree(rr->RecordContext); 2475 } 2476 } 2477 2478mDNSlocal void RegisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type) 2479 { 2480 // allocate/register legacy and non-legacy _browse PTR record 2481 mStatus err; 2482 ARListElem *ptr = mDNSPlatformMemAllocate(sizeof(*ptr)); 2483 2484 debugf("Incrementing %s refcount for %##s", 2485 (type == mDNS_DomainTypeBrowse ) ? "browse domain " : 2486 (type == mDNS_DomainTypeRegistration ) ? "registration dom" : 2487 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c); 2488 2489 mDNS_SetupResourceRecord(&ptr->ar, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, 7200, kDNSRecordTypeShared, FreeARElemCallback, ptr); 2490 MakeDomainNameFromDNSNameString(&ptr->ar.namestorage, mDNS_DomainTypeNames[type]); 2491 AppendDNSNameString (&ptr->ar.namestorage, "local"); 2492 AssignDomainName(&ptr->ar.resrec.rdata->u.name, d); 2493 err = mDNS_Register(m, &ptr->ar); 2494 if (err) 2495 { 2496 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err); 2497 mDNSPlatformMemFree(ptr); 2498 } 2499 else 2500 { 2501 ptr->next = LocalDomainEnumRecords; 2502 LocalDomainEnumRecords = ptr; 2503 } 2504 } 2505 2506mDNSlocal void DeregisterLocalOnlyDomainEnumPTR(mDNS *m, const domainname *d, int type) 2507 { 2508 ARListElem **ptr = &LocalDomainEnumRecords; 2509 domainname lhs; // left-hand side of PTR, for comparison 2510 2511 debugf("Decrementing %s refcount for %##s", 2512 (type == mDNS_DomainTypeBrowse ) ? "browse domain " : 2513 (type == mDNS_DomainTypeRegistration ) ? "registration dom" : 2514 (type == mDNS_DomainTypeBrowseAutomatic) ? "automatic browse" : "?", d->c); 2515 2516 MakeDomainNameFromDNSNameString(&lhs, mDNS_DomainTypeNames[type]); 2517 AppendDNSNameString (&lhs, "local"); 2518 2519 while (*ptr) 2520 { 2521 if (SameDomainName(&(*ptr)->ar.resrec.rdata->u.name, d) && SameDomainName((*ptr)->ar.resrec.name, &lhs)) 2522 { 2523 ARListElem *rem = *ptr; 2524 *ptr = (*ptr)->next; 2525 mDNS_Deregister(m, &rem->ar); 2526 return; 2527 } 2528 else ptr = &(*ptr)->next; 2529 } 2530 } 2531 2532mDNSlocal void AddAutoBrowseDomain(const mDNSu32 uid, const domainname *const name) 2533 { 2534 DNameListElem *new = mDNSPlatformMemAllocate(sizeof(DNameListElem)); 2535 if (!new) { LogMsg("ERROR: malloc"); return; } 2536 AssignDomainName(&new->name, name); 2537 new->uid = uid; 2538 new->next = AutoBrowseDomains; 2539 AutoBrowseDomains = new; 2540 udsserver_automatic_browse_domain_changed(new, mDNStrue); 2541 } 2542 2543mDNSlocal void RmvAutoBrowseDomain(const mDNSu32 uid, const domainname *const name) 2544 { 2545 DNameListElem **p = &AutoBrowseDomains; 2546 while (*p && (!SameDomainName(&(*p)->name, name) || (*p)->uid != uid)) p = &(*p)->next; 2547 if (!*p) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name->c); 2548 else 2549 { 2550 DNameListElem *ptr = *p; 2551 *p = ptr->next; 2552 udsserver_automatic_browse_domain_changed(ptr, mDNSfalse); 2553 mDNSPlatformMemFree(ptr); 2554 } 2555 } 2556 2557mDNSlocal void SetPrefsBrowseDomains(mDNS *m, DNameListElem *browseDomains, mDNSBool add) 2558 { 2559 DNameListElem *d; 2560 for (d = browseDomains; d; d = d->next) 2561 { 2562 if (add) 2563 { 2564 RegisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse); 2565 AddAutoBrowseDomain(d->uid, &d->name); 2566 } 2567 else 2568 { 2569 DeregisterLocalOnlyDomainEnumPTR(m, &d->name, mDNS_DomainTypeBrowse); 2570 RmvAutoBrowseDomain(d->uid, &d->name); 2571 } 2572 } 2573 } 2574 2575mDNSlocal void UpdateDeviceInfoRecord(mDNS *const m) 2576 { 2577 int num_autoname = 0; 2578 request_state *req; 2579 for (req = all_requests; req; req = req->next) 2580 if (req->terminate == regservice_termination_callback && req->u.servicereg.autoname) 2581 num_autoname++; 2582 2583 // If DeviceInfo record is currently registered, see if we need to deregister it 2584 if (m->DeviceInfo.resrec.RecordType != kDNSRecordTypeUnregistered) 2585 if (num_autoname == 0 || !SameDomainLabelCS(m->DeviceInfo.resrec.name->c, m->nicelabel.c)) 2586 { 2587 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m->DeviceInfo.resrec.name); 2588 mDNS_Deregister(m, &m->DeviceInfo); 2589 } 2590 2591 // If DeviceInfo record is not currently registered, see if we need to register it 2592 if (m->DeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered) 2593 if (num_autoname > 0) 2594 { 2595 mDNSu8 len = m->HIHardware.c[0] < 255 - 6 ? m->HIHardware.c[0] : 255 - 6; 2596 mDNS_SetupResourceRecord(&m->DeviceInfo, mDNSNULL, mDNSNULL, kDNSType_TXT, kStandardTTL, kDNSRecordTypeAdvisory, mDNSNULL, mDNSNULL); 2597 ConstructServiceName(&m->DeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &localdomain); 2598 mDNSPlatformMemCopy(m->DeviceInfo.resrec.rdata->u.data + 1, "model=", 6); 2599 mDNSPlatformMemCopy(m->DeviceInfo.resrec.rdata->u.data + 7, m->HIHardware.c + 1, len); 2600 m->DeviceInfo.resrec.rdata->u.data[0] = 6 + len; // "model=" plus the device string 2601 m->DeviceInfo.resrec.rdlength = 7 + len; // One extra for the length byte at the start of the string 2602 LogOperation("UpdateDeviceInfoRecord Register %##s", m->DeviceInfo.resrec.name); 2603 mDNS_Register(m, &m->DeviceInfo); 2604 } 2605 } 2606 2607mDNSexport void udsserver_handle_configchange(mDNS *const m) 2608 { 2609 request_state *req; 2610 service_instance *ptr; 2611 DNameListElem *RegDomains = NULL; 2612 DNameListElem *BrowseDomains = NULL; 2613 DNameListElem *p; 2614 2615 UpdateDeviceInfoRecord(m); 2616 2617 // For autoname services, see if the default service name has changed, necessitating an automatic update 2618 for (req = all_requests; req; req = req->next) 2619 if (req->terminate == regservice_termination_callback) 2620 if (req->u.servicereg.autoname && !SameDomainLabelCS(req->u.servicereg.name.c, m->nicelabel.c)) 2621 { 2622 req->u.servicereg.name = m->nicelabel; 2623 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next) 2624 { 2625 ptr->renameonmemfree = 1; 2626 if (ptr->clientnotified) SendServiceRemovalNotification(&ptr->srs); 2627 if (mDNS_DeregisterService(m, &ptr->srs)) // If service was deregistered already 2628 regservice_callback(m, &ptr->srs, mStatus_MemFree); // we can re-register immediately 2629 } 2630 } 2631 2632 // Let the platform layer get the current DNS information 2633 mDNS_Lock(m); 2634 mDNSPlatformSetDNSConfig(m, mDNSfalse, mDNSfalse, mDNSNULL, &RegDomains, &BrowseDomains); 2635 mDNS_Unlock(m); 2636 2637 // Any automatic registration domains are also implicitly automatic browsing domains 2638 if (RegDomains) SetPrefsBrowseDomains(m, RegDomains, mDNStrue); // Add the new list first 2639 if (AutoRegistrationDomains) SetPrefsBrowseDomains(m, AutoRegistrationDomains, mDNSfalse); // Then clear the old list 2640 2641 // Add any new domains not already in our AutoRegistrationDomains list 2642 for (p=RegDomains; p; p=p->next) 2643 { 2644 DNameListElem **pp = &AutoRegistrationDomains; 2645 while (*pp && ((*pp)->uid != p->uid || !SameDomainName(&(*pp)->name, &p->name))) pp = &(*pp)->next; 2646 if (!*pp) // If not found in our existing list, this is a new default registration domain 2647 { 2648 RegisterLocalOnlyDomainEnumPTR(m, &p->name, mDNS_DomainTypeRegistration); 2649 udsserver_default_reg_domain_changed(p, mDNStrue); 2650 } 2651 else // else found same domainname in both old and new lists, so no change, just delete old copy 2652 { 2653 DNameListElem *del = *pp; 2654 *pp = (*pp)->next; 2655 mDNSPlatformMemFree(del); 2656 } 2657 } 2658 2659 // Delete any domains in our old AutoRegistrationDomains list that are now gone 2660 while (AutoRegistrationDomains) 2661 { 2662 DNameListElem *del = AutoRegistrationDomains; 2663 AutoRegistrationDomains = AutoRegistrationDomains->next; // Cut record from list FIRST, 2664 DeregisterLocalOnlyDomainEnumPTR(m, &del->name, mDNS_DomainTypeRegistration); 2665 udsserver_default_reg_domain_changed(del, mDNSfalse); // before calling udsserver_default_reg_domain_changed() 2666 mDNSPlatformMemFree(del); 2667 } 2668 2669 // Now we have our new updated automatic registration domain list 2670 AutoRegistrationDomains = RegDomains; 2671 2672 // Add new browse domains to internal list 2673 if (BrowseDomains) SetPrefsBrowseDomains(m, BrowseDomains, mDNStrue); 2674 2675 // Remove old browse domains from internal list 2676 if (SCPrefBrowseDomains) 2677 { 2678 SetPrefsBrowseDomains(m, SCPrefBrowseDomains, mDNSfalse); 2679 while (SCPrefBrowseDomains) 2680 { 2681 DNameListElem *fptr = SCPrefBrowseDomains; 2682 SCPrefBrowseDomains = SCPrefBrowseDomains->next; 2683 mDNSPlatformMemFree(fptr); 2684 } 2685 } 2686 2687 // Replace the old browse domains array with the new array 2688 SCPrefBrowseDomains = BrowseDomains; 2689 } 2690 2691mDNSlocal void AutomaticBrowseDomainChange(mDNS *const m, DNSQuestion *q, const ResourceRecord *const answer, QC_result AddRecord) 2692 { 2693 (void)m; // unused; 2694 (void)q; // unused 2695 2696 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s", 2697 AddRecord ? "Adding" : "Removing", answer->rdata->u.name.c); 2698 2699 if (AddRecord) AddAutoBrowseDomain(0, &answer->rdata->u.name); 2700 else RmvAutoBrowseDomain(0, &answer->rdata->u.name); 2701 } 2702 2703mDNSlocal mStatus handle_browse_request(request_state *request) 2704 { 2705 char regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME]; 2706 domainname typedn, d, temp; 2707 mDNSs32 NumSubTypes; 2708 mStatus err = mStatus_NoError; 2709 2710 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 2711 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend); 2712 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex); 2713 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr); 2714 2715 if (get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 || 2716 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) return(mStatus_BadParamErr); 2717 2718 if (!request->msgptr) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 2719 2720 if (domain[0] == '\0') uDNS_RegisterSearchDomains(&mDNSStorage); 2721 2722 typedn.c[0] = 0; 2723 NumSubTypes = ChopSubTypes(regtype); // Note: Modifies regtype string to remove trailing subtypes 2724 if (NumSubTypes < 0 || NumSubTypes > 1) return(mStatus_BadParamErr); 2725 if (NumSubTypes == 1 && !AppendDNSNameString(&typedn, regtype + strlen(regtype) + 1)) return(mStatus_BadParamErr); 2726 2727 if (!regtype[0] || !AppendDNSNameString(&typedn, regtype)) return(mStatus_BadParamErr); 2728 2729 if (!MakeDomainNameFromDNSNameString(&temp, regtype)) return(mStatus_BadParamErr); 2730 // For over-long service types, we only allow domain "local" 2731 if (temp.c[0] > 15 && domain[0] == 0) mDNSPlatformStrCopy(domain, "local."); 2732 2733 // Set up browser info 2734 request->u.browser.ForceMCast = (flags & kDNSServiceFlagsForceMulticast) != 0; 2735 request->u.browser.interface_id = InterfaceID; 2736 AssignDomainName(&request->u.browser.regtype, &typedn); 2737 request->u.browser.default_domain = !domain[0]; 2738 request->u.browser.browsers = NULL; 2739 2740 LogOperation("%3d: DNSServiceBrowse(\"%##s\", \"%s\") START", request->sd, request->u.browser.regtype.c, domain); 2741 2742 // We need to unconditionally set request->terminate, because even if we didn't successfully 2743 // start any browses right now, subsequent configuration changes may cause successful 2744 // browses to be added, and we'll need to cancel them before freeing this memory. 2745 request->terminate = browse_termination_callback; 2746 2747 if (domain[0]) 2748 { 2749 if (!MakeDomainNameFromDNSNameString(&d, domain)) return(mStatus_BadParamErr); 2750 err = add_domain_to_browser(request, &d); 2751#if 0 2752 err = AuthorizedDomain(request, &d, AutoBrowseDomains) ? add_domain_to_browser(request, &d) : mStatus_NoError; 2753#endif 2754 } 2755 else 2756 { 2757 DNameListElem *sdom; 2758 for (sdom = AutoBrowseDomains; sdom; sdom = sdom->next) 2759 if (!sdom->uid || SystemUID(request->uid) || request->uid == sdom->uid) 2760 { 2761 err = add_domain_to_browser(request, &sdom->name); 2762 if (err) 2763 { 2764 if (SameDomainName(&sdom->name, &localdomain)) break; 2765 else err = mStatus_NoError; // suppress errors for non-local "default" domains 2766 } 2767 } 2768 } 2769 2770 return(err); 2771 } 2772 2773// *************************************************************************** 2774#if COMPILER_LIKES_PRAGMA_MARK 2775#pragma mark - 2776#pragma mark - DNSServiceResolve 2777#endif 2778 2779mDNSlocal void resolve_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord) 2780 { 2781 size_t len = 0; 2782 char fullname[MAX_ESCAPED_DOMAIN_NAME], target[MAX_ESCAPED_DOMAIN_NAME]; 2783 char *data; 2784 reply_state *rep; 2785 request_state *req = question->QuestionContext; 2786 (void)m; // Unused 2787 2788 LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req->sd, question->qname.c, AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer)); 2789 2790 if (!AddRecord) 2791 { 2792 if (req->u.resolve.srv == answer) req->u.resolve.srv = mDNSNULL; 2793 if (req->u.resolve.txt == answer) req->u.resolve.txt = mDNSNULL; 2794 return; 2795 } 2796 2797 if (answer->rrtype == kDNSType_SRV) req->u.resolve.srv = answer; 2798 if (answer->rrtype == kDNSType_TXT) req->u.resolve.txt = answer; 2799 2800 if (!req->u.resolve.txt || !req->u.resolve.srv) return; // only deliver result to client if we have both answers 2801 2802 ConvertDomainNameToCString(answer->name, fullname); 2803 ConvertDomainNameToCString(&req->u.resolve.srv->rdata->u.srv.target, target); 2804 2805 // calculate reply length 2806 len += sizeof(DNSServiceFlags); 2807 len += sizeof(mDNSu32); // interface index 2808 len += sizeof(DNSServiceErrorType); 2809 len += strlen(fullname) + 1; 2810 len += strlen(target) + 1; 2811 len += 2 * sizeof(mDNSu16); // port, txtLen 2812 len += req->u.resolve.txt->rdlength; 2813 2814 // allocate/init reply header 2815 rep = create_reply(resolve_reply_op, len, req); 2816 rep->rhdr->flags = dnssd_htonl(0); 2817 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID)); 2818 rep->rhdr->error = dnssd_htonl(kDNSServiceErr_NoError); 2819 2820 data = (char *)&rep->rhdr[1]; 2821 2822 // write reply data to message 2823 put_string(fullname, &data); 2824 put_string(target, &data); 2825 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[0]; 2826 *data++ = req->u.resolve.srv->rdata->u.srv.port.b[1]; 2827 put_uint16(req->u.resolve.txt->rdlength, &data); 2828 put_rdata (req->u.resolve.txt->rdlength, req->u.resolve.txt->rdata->u.data, &data); 2829 2830 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req->sd, fullname, target, mDNSVal16(req->u.resolve.srv->rdata->u.srv.port)); 2831 append_reply(req, rep); 2832 } 2833 2834mDNSlocal void resolve_termination_callback(request_state *request) 2835 { 2836 LogOperation("%3d: DNSServiceResolve(%##s) STOP", request->sd, request->u.resolve.qtxt.qname.c); 2837 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qtxt); 2838 mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv); 2839 } 2840 2841mDNSlocal mStatus handle_resolve_request(request_state *request) 2842 { 2843 char name[256], regtype[MAX_ESCAPED_DOMAIN_NAME], domain[MAX_ESCAPED_DOMAIN_NAME]; 2844 domainname fqdn; 2845 mStatus err; 2846 2847 // extract the data from the message 2848 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 2849 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend); 2850 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex); 2851 if (interfaceIndex && !InterfaceID) 2852 { LogMsg("ERROR: handle_resolve_request bad interfaceIndex %d", interfaceIndex); return(mStatus_BadParamErr); } 2853 2854 if (get_string(&request->msgptr, request->msgend, name, 256) < 0 || 2855 get_string(&request->msgptr, request->msgend, regtype, MAX_ESCAPED_DOMAIN_NAME) < 0 || 2856 get_string(&request->msgptr, request->msgend, domain, MAX_ESCAPED_DOMAIN_NAME) < 0) 2857 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr); } 2858 2859 if (!request->msgptr) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 2860 2861 if (build_domainname_from_strings(&fqdn, name, regtype, domain) < 0) 2862 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name, regtype, domain); return(mStatus_BadParamErr); } 2863 2864 mDNSPlatformMemZero(&request->u.resolve, sizeof(request->u.resolve)); 2865 2866 // format questions 2867 request->u.resolve.qsrv.InterfaceID = InterfaceID; 2868 request->u.resolve.qsrv.Target = zeroAddr; 2869 AssignDomainName(&request->u.resolve.qsrv.qname, &fqdn); 2870 request->u.resolve.qsrv.qtype = kDNSType_SRV; 2871 request->u.resolve.qsrv.qclass = kDNSClass_IN; 2872 request->u.resolve.qsrv.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0; 2873 request->u.resolve.qsrv.ExpectUnique = mDNStrue; 2874 request->u.resolve.qsrv.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0; 2875 request->u.resolve.qsrv.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0; 2876 request->u.resolve.qsrv.QuestionCallback = resolve_result_callback; 2877 request->u.resolve.qsrv.QuestionContext = request; 2878 2879 request->u.resolve.qtxt.InterfaceID = InterfaceID; 2880 request->u.resolve.qtxt.Target = zeroAddr; 2881 AssignDomainName(&request->u.resolve.qtxt.qname, &fqdn); 2882 request->u.resolve.qtxt.qtype = kDNSType_TXT; 2883 request->u.resolve.qtxt.qclass = kDNSClass_IN; 2884 request->u.resolve.qtxt.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0; 2885 request->u.resolve.qtxt.ExpectUnique = mDNStrue; 2886 request->u.resolve.qtxt.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0; 2887 request->u.resolve.qtxt.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0; 2888 request->u.resolve.qtxt.QuestionCallback = resolve_result_callback; 2889 request->u.resolve.qtxt.QuestionContext = request; 2890 2891 request->u.resolve.ReportTime = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond); 2892 2893#if 0 2894 if (!AuthorizedDomain(request, &fqdn, AutoBrowseDomains)) return(mStatus_NoError); 2895#endif 2896 2897 // ask the questions 2898 LogOperation("%3d: DNSServiceResolve(%##s) START", request->sd, request->u.resolve.qsrv.qname.c); 2899 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qsrv); 2900 if (!err) 2901 { 2902 err = mDNS_StartQuery(&mDNSStorage, &request->u.resolve.qtxt); 2903 if (err) mDNS_StopQuery(&mDNSStorage, &request->u.resolve.qsrv); 2904 else request->terminate = resolve_termination_callback; 2905 } 2906 2907 return(err); 2908 } 2909 2910// *************************************************************************** 2911#if COMPILER_LIKES_PRAGMA_MARK 2912#pragma mark - 2913#pragma mark - DNSServiceQueryRecord 2914#endif 2915 2916// mDNS operation functions. Each operation has 3 associated functions - a request handler that parses 2917// the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback 2918// to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts 2919// the mDNSCore operation if the client dies or closes its socket. 2920 2921mDNSlocal void queryrecord_result_callback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord) 2922 { 2923 char name[MAX_ESCAPED_DOMAIN_NAME]; 2924 request_state *req = question->QuestionContext; 2925 reply_state *rep; 2926 char *data; 2927 size_t len; 2928 DNSServiceErrorType error = kDNSServiceErr_NoError; 2929 (void)m; // Unused 2930 2931#if APPLE_OSX_mDNSResponder 2932 if (question == &req->u.queryrecord.q2) 2933 { 2934 mDNS_StopQuery(&mDNSStorage, question); 2935 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query 2936 if (answer->RecordType == kDNSRecordTypePacketNegative || 2937 (question->qtype == req->u.queryrecord.q.qtype && SameDomainName(&question->qname, &req->u.queryrecord.q.qname))) 2938 question->QuestionCallback = mDNSNULL; 2939 else 2940 { 2941 *question = req->u.queryrecord.q; 2942 question->InterfaceID = mDNSInterface_Unicast; 2943 question->ExpectUnique = mDNStrue; 2944 mStatus err = mDNS_StartQuery(&mDNSStorage, question); 2945 if (!err) LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", req->sd, question->qname.c, DNSTypeName(question->qtype)); 2946 else LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req->sd, question->qname.c, DNSTypeName(question->qtype), (int)err); 2947 } 2948 return; 2949 } 2950#endif // APPLE_OSX_mDNSResponder 2951 2952 if (answer->RecordType == kDNSRecordTypePacketNegative) 2953 { 2954 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft 2955 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative 2956 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory 2957 // server is going to assert that pretty much every single multicast name doesn't exist. 2958 if (!answer->InterfaceID && IsLocalDomain(answer->name)) return; 2959 error = kDNSServiceErr_NoSuchRecord; 2960 AddRecord = mDNStrue; 2961 } 2962 2963 ConvertDomainNameToCString(answer->name, name); 2964 2965 LogOperation("%3d: %s(%##s, %s) %s %s", req->sd, 2966 req->hdr.op == query_request ? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo", 2967 question->qname.c, DNSTypeName(question->qtype), AddRecord ? "ADD" : "RMV", RRDisplayString(m, answer)); 2968 2969 len = sizeof(DNSServiceFlags); // calculate reply data length 2970 len += sizeof(mDNSu32); // interface index 2971 len += sizeof(DNSServiceErrorType); 2972 len += strlen(name) + 1; 2973 len += 3 * sizeof(mDNSu16); // type, class, rdlen 2974 len += answer->rdlength; 2975 len += sizeof(mDNSu32); // TTL 2976 2977 rep = create_reply(req->hdr.op == query_request ? query_reply_op : addrinfo_reply_op, len, req); 2978 2979 rep->rhdr->flags = dnssd_htonl(AddRecord ? kDNSServiceFlagsAdd : 0); 2980 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, answer->InterfaceID)); 2981 rep->rhdr->error = dnssd_htonl(error); 2982 2983 data = (char *)&rep->rhdr[1]; 2984 2985 put_string(name, &data); 2986 put_uint16(answer->rrtype, &data); 2987 put_uint16(answer->rrclass, &data); 2988 put_uint16(answer->rdlength, &data); 2989 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata 2990 // function just does a blind memory copy without regard to structures that may have holes in them. 2991 if (answer->rdlength) 2992 if (!putRData(mDNSNULL, (mDNSu8 *)data, (mDNSu8 *)rep->rhdr + len, answer)) 2993 LogMsg("queryrecord_result_callback putRData failed %d", (mDNSu8 *)rep->rhdr + len - (mDNSu8 *)data); 2994 data += answer->rdlength; 2995 put_uint32(AddRecord ? answer->rroriginalttl : 0, &data); 2996 2997 append_reply(req, rep); 2998 } 2999 3000mDNSlocal void queryrecord_termination_callback(request_state *request) 3001 { 3002 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP", 3003 request->sd, request->u.queryrecord.q.qname.c, DNSTypeName(request->u.queryrecord.q.qtype)); 3004 mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q); // no need to error check 3005 if (request->u.queryrecord.q2.QuestionCallback) mDNS_StopQuery(&mDNSStorage, &request->u.queryrecord.q2); 3006 } 3007 3008mDNSlocal mStatus handle_queryrecord_request(request_state *request) 3009 { 3010 DNSQuestion *const q = &request->u.queryrecord.q; 3011 char name[256]; 3012 mDNSu16 rrtype, rrclass; 3013 mStatus err; 3014 3015 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 3016 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend); 3017 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex); 3018 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr); 3019 3020 if (get_string(&request->msgptr, request->msgend, name, 256) < 0) return(mStatus_BadParamErr); 3021 rrtype = get_uint16(&request->msgptr, request->msgend); 3022 rrclass = get_uint16(&request->msgptr, request->msgend); 3023 3024 if (!request->msgptr) 3025 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 3026 3027 mDNSPlatformMemZero(&request->u.queryrecord, sizeof(request->u.queryrecord)); 3028 3029 q->InterfaceID = InterfaceID; 3030 q->Target = zeroAddr; 3031 if (!MakeDomainNameFromDNSNameString(&q->qname, name)) return(mStatus_BadParamErr); 3032#if 0 3033 if (!AuthorizedDomain(request, &q->qname, AutoBrowseDomains)) return (mStatus_NoError); 3034#endif 3035 q->qtype = rrtype; 3036 q->qclass = rrclass; 3037 q->LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0; 3038 q->ExpectUnique = mDNSfalse; 3039 q->ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0; 3040 q->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0; 3041 q->QuestionCallback = queryrecord_result_callback; 3042 q->QuestionContext = request; 3043 3044 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s, %X) START", request->sd, q->qname.c, DNSTypeName(q->qtype), flags); 3045 err = mDNS_StartQuery(&mDNSStorage, q); 3046 if (err) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q->qname.c, DNSTypeName(q->qtype), (int)err); 3047 else request->terminate = queryrecord_termination_callback; 3048 3049#if APPLE_OSX_mDNSResponder 3050 // Workaround for networks using Microsoft Active Directory using "local" as a private internal top-level domain 3051 extern domainname ActiveDirectoryPrimaryDomain; 3052 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp")) 3053 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname))) 3054 3055 if (!q->ForceMCast && SameDomainLabel(LastLabel(&q->qname), (const mDNSu8 *)&localdomain)) 3056 if (q->qtype == kDNSType_A || q->qtype == kDNSType_AAAA || VALID_MSAD_SRV(q)) 3057 { 3058 int labels = CountLabels(&q->qname); 3059 DNSQuestion *const q2 = &request->u.queryrecord.q2; 3060 *q2 = *q; 3061 q2->InterfaceID = mDNSInterface_Unicast; 3062 q2->ExpectUnique = mDNStrue; 3063 3064 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel. 3065 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query. 3066 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP 3067 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser) 3068 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the 3069 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries 3070 // for names in the "local" domain will be safely answered privately before they hit the root name servers. 3071 if (labels == 2 && !SameDomainName(&q->qname, &ActiveDirectoryPrimaryDomain)) 3072 { 3073 AssignDomainName(&q2->qname, &localdomain); 3074 q2->qtype = kDNSType_SOA; 3075 q2->LongLived = mDNSfalse; 3076 q2->ForceMCast = mDNSfalse; 3077 q2->ReturnIntermed = mDNStrue; 3078 } 3079 err = mDNS_StartQuery(&mDNSStorage, q2); 3080 if (!err) LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request->sd, q2->qname.c, DNSTypeName(q2->qtype)); 3081 else LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request->sd, q2->qname.c, DNSTypeName(q2->qtype), (int)err); 3082 } 3083#endif // APPLE_OSX_mDNSResponder 3084 3085 return(err); 3086 } 3087 3088// *************************************************************************** 3089#if COMPILER_LIKES_PRAGMA_MARK 3090#pragma mark - 3091#pragma mark - DNSServiceEnumerateDomains 3092#endif 3093 3094mDNSlocal reply_state *format_enumeration_reply(request_state *request, 3095 const char *domain, DNSServiceFlags flags, mDNSu32 ifi, DNSServiceErrorType err) 3096 { 3097 size_t len; 3098 reply_state *reply; 3099 char *data; 3100 3101 len = sizeof(DNSServiceFlags); 3102 len += sizeof(mDNSu32); 3103 len += sizeof(DNSServiceErrorType); 3104 len += strlen(domain) + 1; 3105 3106 reply = create_reply(enumeration_reply_op, len, request); 3107 reply->rhdr->flags = dnssd_htonl(flags); 3108 reply->rhdr->ifi = dnssd_htonl(ifi); 3109 reply->rhdr->error = dnssd_htonl(err); 3110 data = (char *)&reply->rhdr[1]; 3111 put_string(domain, &data); 3112 return reply; 3113 } 3114 3115mDNSlocal void enum_termination_callback(request_state *request) 3116 { 3117 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all); 3118 mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_default); 3119 } 3120 3121mDNSlocal void enum_result_callback(mDNS *const m, 3122 DNSQuestion *const question, const ResourceRecord *const answer, QC_result AddRecord) 3123 { 3124 char domain[MAX_ESCAPED_DOMAIN_NAME]; 3125 request_state *request = question->QuestionContext; 3126 DNSServiceFlags flags = 0; 3127 reply_state *reply; 3128 (void)m; // Unused 3129 3130 if (answer->rrtype != kDNSType_PTR) return; 3131 3132#if 0 3133 if (!AuthorizedDomain(request, &answer->rdata->u.name, request->u.enumeration.flags ? AutoRegistrationDomains : AutoBrowseDomains)) return; 3134#endif 3135 3136 // We only return add/remove events for the browse and registration lists 3137 // For the default browse and registration answers, we only give an "ADD" event 3138 if (question == &request->u.enumeration.q_default && !AddRecord) return; 3139 3140 if (AddRecord) 3141 { 3142 flags |= kDNSServiceFlagsAdd; 3143 if (question == &request->u.enumeration.q_default) flags |= kDNSServiceFlagsDefault; 3144 } 3145 3146 ConvertDomainNameToCString(&answer->rdata->u.name, domain); 3147 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from 3148 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the 3149 // network, so we just pass kDNSServiceInterfaceIndexAny 3150 reply = format_enumeration_reply(request, domain, flags, kDNSServiceInterfaceIndexAny, kDNSServiceErr_NoError); 3151 if (!reply) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; } 3152 3153 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request->sd, question->qname.c, AddRecord ? "Add" : "Rmv", domain); 3154 3155 append_reply(request, reply); 3156 } 3157 3158mDNSlocal mStatus handle_enum_request(request_state *request) 3159 { 3160 mStatus err; 3161 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 3162 DNSServiceFlags reg = flags & kDNSServiceFlagsRegistrationDomains; 3163 mDNS_DomainType t_all = reg ? mDNS_DomainTypeRegistration : mDNS_DomainTypeBrowse; 3164 mDNS_DomainType t_default = reg ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault; 3165 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend); 3166 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex); 3167 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr); 3168 3169 if (!request->msgptr) 3170 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 3171 3172 // allocate context structures 3173 uDNS_RegisterSearchDomains(&mDNSStorage); 3174 3175#if 0 3176 // mark which kind of enumeration we're doing so we can (de)authorize certain domains 3177 request->u.enumeration.flags = reg; 3178#endif 3179 3180 // enumeration requires multiple questions, so we must link all the context pointers so that 3181 // necessary context can be reached from the callbacks 3182 request->u.enumeration.q_all .QuestionContext = request; 3183 request->u.enumeration.q_default.QuestionContext = request; 3184 3185 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list. 3186 if (!InterfaceID) InterfaceID = mDNSInterface_LocalOnly; 3187 3188 // make the calls 3189 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request->sd, flags, 3190 (flags & kDNSServiceFlagsBrowseDomains ) ? "kDNSServiceFlagsBrowseDomains" : 3191 (flags & kDNSServiceFlagsRegistrationDomains) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>"); 3192 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_all, t_all, NULL, InterfaceID, enum_result_callback, request); 3193 if (!err) 3194 { 3195 err = mDNS_GetDomains(&mDNSStorage, &request->u.enumeration.q_default, t_default, NULL, InterfaceID, enum_result_callback, request); 3196 if (err) mDNS_StopGetDomains(&mDNSStorage, &request->u.enumeration.q_all); 3197 else request->terminate = enum_termination_callback; 3198 } 3199 3200 return(err); 3201 } 3202 3203// *************************************************************************** 3204#if COMPILER_LIKES_PRAGMA_MARK 3205#pragma mark - 3206#pragma mark - DNSServiceReconfirmRecord & Misc 3207#endif 3208 3209mDNSlocal mStatus handle_reconfirm_request(request_state *request) 3210 { 3211 mStatus status = mStatus_BadParamErr; 3212 AuthRecord *rr = read_rr_from_ipc_msg(request, 0, 0); 3213 if (rr) 3214 { 3215 status = mDNS_ReconfirmByValue(&mDNSStorage, &rr->resrec); 3216 LogOperation( 3217 (status == mStatus_NoError) ? 3218 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" : 3219 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d", 3220 request->sd, RRDisplayString(&mDNSStorage, &rr->resrec), 3221 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage, rr->resrec.InterfaceID), status); 3222 freeL("AuthRecord/handle_reconfirm_request", rr); 3223 } 3224 return(status); 3225 } 3226 3227mDNSlocal mStatus handle_setdomain_request(request_state *request) 3228 { 3229 char domainstr[MAX_ESCAPED_DOMAIN_NAME]; 3230 domainname domain; 3231 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 3232 (void)flags; // Unused 3233 if (get_string(&request->msgptr, request->msgend, domainstr, MAX_ESCAPED_DOMAIN_NAME) < 0 || 3234 !MakeDomainNameFromDNSNameString(&domain, domainstr)) 3235 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 3236 3237 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request->sd, domain.c); 3238 return(mStatus_NoError); 3239 } 3240 3241typedef packedstruct 3242 { 3243 mStatus err; 3244 mDNSu32 len; 3245 mDNSu32 vers; 3246 } DaemonVersionReply; 3247 3248mDNSlocal void handle_getproperty_request(request_state *request) 3249 { 3250 const mStatus BadParamErr = dnssd_htonl(mStatus_BadParamErr); 3251 char prop[256]; 3252 if (get_string(&request->msgptr, request->msgend, prop, sizeof(prop)) >= 0) 3253 { 3254 LogOperation("%3d: DNSServiceGetProperty(%s)", request->sd, prop); 3255 if (!strcmp(prop, kDNSServiceProperty_DaemonVersion)) 3256 { 3257 DaemonVersionReply x = { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H) }; 3258 send_all(request->sd, (const char *)&x, sizeof(x)); 3259 return; 3260 } 3261 } 3262 3263 // If we didn't recogize the requested property name, return BadParamErr 3264 send_all(request->sd, (const char *)&BadParamErr, sizeof(BadParamErr)); 3265 } 3266 3267// *************************************************************************** 3268#if COMPILER_LIKES_PRAGMA_MARK 3269#pragma mark - 3270#pragma mark - DNSServiceNATPortMappingCreate 3271#endif 3272 3273#define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP) 3274 3275mDNSlocal void port_mapping_termination_callback(request_state *request) 3276 { 3277 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP", request->sd, 3278 DNSServiceProtocol(request->u.pm.NATinfo.Protocol), 3279 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease); 3280 mDNS_StopNATOperation(&mDNSStorage, &request->u.pm.NATinfo); 3281 } 3282 3283// Called via function pointer when we get a NAT-PMP address request or port mapping response 3284mDNSlocal void port_mapping_create_request_callback(mDNS *m, NATTraversalInfo *n) 3285 { 3286 request_state *request = (request_state *)n->clientContext; 3287 reply_state *rep; 3288 int replyLen; 3289 char *data; 3290 3291 if (!request) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; } 3292 3293 // calculate reply data length 3294 replyLen = sizeof(DNSServiceFlags); 3295 replyLen += 3 * sizeof(mDNSu32); // if index + addr + ttl 3296 replyLen += sizeof(DNSServiceErrorType); 3297 replyLen += 2 * sizeof(mDNSu16); // Internal Port + External Port 3298 replyLen += sizeof(mDNSu8); // protocol 3299 3300 rep = create_reply(port_mapping_reply_op, replyLen, request); 3301 3302 rep->rhdr->flags = dnssd_htonl(0); 3303 rep->rhdr->ifi = dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m, n->InterfaceID)); 3304 rep->rhdr->error = dnssd_htonl(n->Result); 3305 3306 data = (char *)&rep->rhdr[1]; 3307 3308 *data++ = request->u.pm.NATinfo.ExternalAddress.b[0]; 3309 *data++ = request->u.pm.NATinfo.ExternalAddress.b[1]; 3310 *data++ = request->u.pm.NATinfo.ExternalAddress.b[2]; 3311 *data++ = request->u.pm.NATinfo.ExternalAddress.b[3]; 3312 *data++ = DNSServiceProtocol(request->u.pm.NATinfo.Protocol); 3313 *data++ = request->u.pm.NATinfo.IntPort.b[0]; 3314 *data++ = request->u.pm.NATinfo.IntPort.b[1]; 3315 *data++ = request->u.pm.NATinfo.ExternalPort.b[0]; 3316 *data++ = request->u.pm.NATinfo.ExternalPort.b[1]; 3317 put_uint32(request->u.pm.NATinfo.Lifetime, &data); 3318 3319 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request->sd, 3320 DNSServiceProtocol(request->u.pm.NATinfo.Protocol), 3321 mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease, 3322 &request->u.pm.NATinfo.ExternalAddress, mDNSVal16(request->u.pm.NATinfo.ExternalPort), request->u.pm.NATinfo.Lifetime); 3323 3324 append_reply(request, rep); 3325 } 3326 3327mDNSlocal mStatus handle_port_mapping_request(request_state *request) 3328 { 3329 mDNSu32 ttl = 0; 3330 mStatus err = mStatus_NoError; 3331 3332 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 3333 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend); 3334 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex); 3335 mDNSu8 protocol = get_uint32(&request->msgptr, request->msgend); 3336 (void)flags; // Unused 3337 if (interfaceIndex && !InterfaceID) return(mStatus_BadParamErr); 3338 if (request->msgptr + 8 > request->msgend) request->msgptr = NULL; 3339 else 3340 { 3341 request->u.pm.NATinfo.IntPort.b[0] = *request->msgptr++; 3342 request->u.pm.NATinfo.IntPort.b[1] = *request->msgptr++; 3343 request->u.pm.ReqExt.b[0] = *request->msgptr++; 3344 request->u.pm.ReqExt.b[1] = *request->msgptr++; 3345 ttl = get_uint32(&request->msgptr, request->msgend); 3346 } 3347 3348 if (!request->msgptr) 3349 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 3350 3351 if (protocol == 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too 3352 { 3353 if (!mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort) || !mDNSIPPortIsZero(request->u.pm.ReqExt) || ttl) return(mStatus_BadParamErr); 3354 } 3355 else 3356 { 3357 if (mDNSIPPortIsZero(request->u.pm.NATinfo.IntPort)) return(mStatus_BadParamErr); 3358 if (!(protocol & (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP))) return(mStatus_BadParamErr); 3359 } 3360 3361 request->u.pm.NATinfo.Protocol = !protocol ? NATOp_AddrRequest : (protocol == kDNSServiceProtocol_UDP) ? NATOp_MapUDP : NATOp_MapTCP; 3362 // u.pm.NATinfo.IntPort = already set above 3363 request->u.pm.NATinfo.RequestedPort = request->u.pm.ReqExt; 3364 request->u.pm.NATinfo.NATLease = ttl; 3365 request->u.pm.NATinfo.clientCallback = port_mapping_create_request_callback; 3366 request->u.pm.NATinfo.clientContext = request; 3367 3368 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START", request->sd, 3369 protocol, mDNSVal16(request->u.pm.NATinfo.IntPort), mDNSVal16(request->u.pm.ReqExt), request->u.pm.NATinfo.NATLease); 3370 err = mDNS_StartNATOperation(&mDNSStorage, &request->u.pm.NATinfo); 3371 if (err) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err); 3372 else request->terminate = port_mapping_termination_callback; 3373 3374 return(err); 3375 } 3376 3377// *************************************************************************** 3378#if COMPILER_LIKES_PRAGMA_MARK 3379#pragma mark - 3380#pragma mark - DNSServiceGetAddrInfo 3381#endif 3382 3383mDNSlocal void addrinfo_termination_callback(request_state *request) 3384 { 3385 if (request->u.addrinfo.q4.QuestionContext) 3386 { 3387 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q4); 3388 request->u.addrinfo.q4.QuestionContext = mDNSNULL; 3389 } 3390 3391 if (request->u.addrinfo.q6.QuestionContext) 3392 { 3393 mDNS_StopQuery(&mDNSStorage, &request->u.addrinfo.q6); 3394 request->u.addrinfo.q6.QuestionContext = mDNSNULL; 3395 } 3396 } 3397 3398mDNSlocal mStatus handle_addrinfo_request(request_state *request) 3399 { 3400 char hostname[256]; 3401 domainname d; 3402 mStatus err = 0; 3403 3404 DNSServiceFlags flags = get_flags(&request->msgptr, request->msgend); 3405 mDNSu32 interfaceIndex = get_uint32(&request->msgptr, request->msgend); 3406 3407 mDNSPlatformMemZero(&request->u.addrinfo, sizeof(request->u.addrinfo)); 3408 request->u.addrinfo.interface_id = mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage, interfaceIndex); 3409 request->u.addrinfo.flags = flags; 3410 request->u.addrinfo.protocol = get_uint32(&request->msgptr, request->msgend); 3411 3412 if (interfaceIndex && !request->u.addrinfo.interface_id) return(mStatus_BadParamErr); 3413 if (request->u.addrinfo.protocol > (kDNSServiceProtocol_IPv4|kDNSServiceProtocol_IPv6)) return(mStatus_BadParamErr); 3414 3415 if (get_string(&request->msgptr, request->msgend, hostname, 256) < 0) return(mStatus_BadParamErr); 3416 3417 if (!request->msgptr) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request->sd); return(mStatus_BadParamErr); } 3418 3419 if (!MakeDomainNameFromDNSNameString(&d, hostname)) 3420 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname); return(mStatus_BadParamErr); } 3421 3422#if 0 3423 if (!AuthorizedDomain(request, &d, AutoBrowseDomains)) return (mStatus_NoError); 3424#endif 3425 3426 if (!request->u.addrinfo.protocol) 3427 { 3428 NetworkInterfaceInfo *i; 3429 if (IsLocalDomain(&d)) 3430 { 3431 for (i = mDNSStorage.HostInterfaces; i; i = i->next) 3432 { 3433 if ((i->ip.type == mDNSAddrType_IPv4) && !mDNSIPv4AddressIsZero(i->ip.ip.v4)) request->u.addrinfo.protocol |= kDNSServiceProtocol_IPv4; 3434 else if ((i->ip.type == mDNSAddrType_IPv6) && !mDNSIPv6AddressIsZero(i->ip.ip.v6)) request->u.addrinfo.protocol |= kDNSServiceProtocol_IPv6; 3435 } 3436 } 3437 else 3438 { 3439 for (i = mDNSStorage.HostInterfaces; i; i = i->next) 3440 { 3441 if ((i->ip.type == mDNSAddrType_IPv4) && !mDNSv4AddressIsLinkLocal(&i->ip.ip.v4)) request->u.addrinfo.protocol |= kDNSServiceProtocol_IPv4; 3442 else if ((i->ip.type == mDNSAddrType_IPv6) && !mDNSv4AddressIsLinkLocal(&i->ip.ip.v6)) request->u.addrinfo.protocol |= kDNSServiceProtocol_IPv6; 3443 } 3444 } 3445 } 3446 3447 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4) 3448 { 3449 request->u.addrinfo.q4.InterfaceID = request->u.addrinfo.interface_id; 3450 request->u.addrinfo.q4.Target = zeroAddr; 3451 request->u.addrinfo.q4.qname = d; 3452 request->u.addrinfo.q4.qtype = kDNSServiceType_A; 3453 request->u.addrinfo.q4.qclass = kDNSServiceClass_IN; 3454 request->u.addrinfo.q4.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0; 3455 request->u.addrinfo.q4.ExpectUnique = mDNSfalse; 3456 request->u.addrinfo.q4.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0; 3457 request->u.addrinfo.q4.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0; 3458 request->u.addrinfo.q4.QuestionCallback = queryrecord_result_callback; 3459 request->u.addrinfo.q4.QuestionContext = request; 3460 3461 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q4); 3462 if (err != mStatus_NoError) 3463 { 3464 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err); 3465 request->u.addrinfo.q4.QuestionContext = mDNSNULL; 3466 } 3467 } 3468 3469 if (!err && (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv6)) 3470 { 3471 request->u.addrinfo.q6.InterfaceID = request->u.addrinfo.interface_id; 3472 request->u.addrinfo.q6.Target = zeroAddr; 3473 request->u.addrinfo.q6.qname = d; 3474 request->u.addrinfo.q6.qtype = kDNSServiceType_AAAA; 3475 request->u.addrinfo.q6.qclass = kDNSServiceClass_IN; 3476 request->u.addrinfo.q6.LongLived = (flags & kDNSServiceFlagsLongLivedQuery ) != 0; 3477 request->u.addrinfo.q6.ExpectUnique = mDNSfalse; 3478 request->u.addrinfo.q6.ForceMCast = (flags & kDNSServiceFlagsForceMulticast ) != 0; 3479 request->u.addrinfo.q6.ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0; 3480 request->u.addrinfo.q6.QuestionCallback = queryrecord_result_callback; 3481 request->u.addrinfo.q6.QuestionContext = request; 3482 3483 err = mDNS_StartQuery(&mDNSStorage, &request->u.addrinfo.q6); 3484 if (err != mStatus_NoError) 3485 { 3486 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err); 3487 request->u.addrinfo.q6.QuestionContext = mDNSNULL; 3488 if (request->u.addrinfo.protocol & kDNSServiceProtocol_IPv4) // If we started a query for IPv4, 3489 addrinfo_termination_callback(request); // we need to cancel it 3490 } 3491 } 3492 3493 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) START", request->sd, d.c); 3494 3495 if (!err) request->terminate = addrinfo_termination_callback; 3496 3497 return(err); 3498 } 3499 3500// *************************************************************************** 3501#if COMPILER_LIKES_PRAGMA_MARK 3502#pragma mark - 3503#pragma mark - Main Request Handler etc. 3504#endif 3505 3506mDNSlocal request_state *NewRequest(void) 3507 { 3508 request_state **p = &all_requests; 3509 while (*p) p=&(*p)->next; 3510 *p = mallocL("request_state", sizeof(request_state)); 3511 if (!*p) FatalError("ERROR: malloc"); 3512 mDNSPlatformMemZero(*p, sizeof(request_state)); 3513 return(*p); 3514 } 3515 3516// read_msg may be called any time when the transfer state (req->ts) is t_morecoming. 3517// if there is no data on the socket, the socket will be closed and t_terminated will be returned 3518mDNSlocal void read_msg(request_state *req) 3519 { 3520 if (req->ts == t_terminated || req->ts == t_error) 3521 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req->sd); req->ts = t_error; return; } 3522 3523 if (req->ts == t_complete) // this must be death or something is wrong 3524 { 3525 char buf[4]; // dummy for death notification 3526 int nread = recv(req->sd, buf, 4, 0); 3527 if (!nread) { req->ts = t_terminated; return; } 3528 if (nread < 0) goto rerror; 3529 LogMsg("%3d: ERROR: read data from a completed request", req->sd); 3530 req->ts = t_error; 3531 return; 3532 } 3533 3534 if (req->ts != t_morecoming) 3535 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req->sd, req->ts); req->ts = t_error; return; } 3536 3537 if (req->hdr_bytes < sizeof(ipc_msg_hdr)) 3538 { 3539 mDNSu32 nleft = sizeof(ipc_msg_hdr) - req->hdr_bytes; 3540 int nread = recv(req->sd, (char *)&req->hdr + req->hdr_bytes, nleft, 0); 3541 if (nread == 0) { req->ts = t_terminated; return; } 3542 if (nread < 0) goto rerror; 3543 req->hdr_bytes += nread; 3544 if (req->hdr_bytes > sizeof(ipc_msg_hdr)) 3545 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req->sd); req->ts = t_error; return; } 3546 3547 // only read data if header is complete 3548 if (req->hdr_bytes == sizeof(ipc_msg_hdr)) 3549 { 3550 ConvertHeaderBytes(&req->hdr); 3551 if (req->hdr.version != VERSION) 3552 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req->sd, req->hdr.version, VERSION); req->ts = t_error; return; } 3553 3554 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord() 3555 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin 3556 // for other overhead, this means any message above 70kB is definitely bogus. 3557 if (req->hdr.datalen > 70000) 3558 { LogMsg("%3d: ERROR: read_msg - hdr.datalen %lu (%X) > 70000", req->sd, req->hdr.datalen, req->hdr.datalen); req->ts = t_error; return; } 3559 req->msgbuf = mallocL("request_state msgbuf", req->hdr.datalen + MSG_PAD_BYTES); 3560 if (!req->msgbuf) { my_perror("ERROR: malloc"); req->ts = t_error; return; } 3561 req->msgptr = req->msgbuf; 3562 req->msgend = req->msgbuf + req->hdr.datalen; 3563 mDNSPlatformMemZero(req->msgbuf, req->hdr.datalen + MSG_PAD_BYTES); 3564 } 3565 } 3566 3567 // If our header is complete, but we're still needing more body data, then try to read it now 3568 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request 3569 // Any time we need to get the error return socket we know we'll have at least one data byte 3570 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter) 3571 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes < req->hdr.datalen) 3572 { 3573 mDNSu32 nleft = req->hdr.datalen - req->data_bytes; 3574 int nread; 3575#if !defined(_WIN32) 3576 struct iovec vec = { req->msgbuf + req->data_bytes, nleft }; // Tell recvmsg where we want the bytes put 3577 struct msghdr msg; 3578 struct cmsghdr *cmsg; 3579 char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))]; 3580 msg.msg_name = 0; 3581 msg.msg_namelen = 0; 3582 msg.msg_iov = &vec; 3583 msg.msg_iovlen = 1; 3584 msg.msg_control = cbuf; 3585 msg.msg_controllen = sizeof(cbuf); 3586 msg.msg_flags = 0; 3587 nread = recvmsg(req->sd, &msg, 0); 3588#else 3589 nread = recv(req->sd, (char *)req->msgbuf + req->data_bytes, nleft, 0); 3590#endif 3591 if (nread == 0) { req->ts = t_terminated; return; } 3592 if (nread < 0) goto rerror; 3593 req->data_bytes += nread; 3594 if (req->data_bytes > req->hdr.datalen) 3595 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req->sd); req->ts = t_error; return; } 3596#if !defined(_WIN32) 3597 cmsg = CMSG_FIRSTHDR(&msg); 3598#if DEBUG_64BIT_SCM_RIGHTS 3599 LogMsg("%3d: Expecting %d %d %d %d", req->sd, sizeof(cbuf), CMSG_LEN(sizeof(dnssd_sock_t)), SOL_SOCKET, SCM_RIGHTS); 3600 if (cmsg) 3601 LogMsg("%3d: Got %d %d %d %d", req->sd, msg.msg_controllen, cmsg->cmsg_len, cmsg->cmsg_level, cmsg->cmsg_type); 3602 else 3603 LogMsg("%3d: Got %d NULL", req->sd, msg.msg_controllen); 3604#endif // DEBUG_64BIT_SCM_RIGHTS 3605 if (msg.msg_controllen == sizeof(cbuf) && 3606 cmsg->cmsg_len == CMSG_LEN(sizeof(dnssd_sock_t)) && 3607 cmsg->cmsg_level == SOL_SOCKET && 3608 cmsg->cmsg_type == SCM_RIGHTS) 3609 { 3610#if APPLE_OSX_mDNSResponder 3611 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because 3612 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper, 3613 // and it's convenient to repurpose the existing fd-passing code here for that task 3614 if (req->hdr.op == send_bpf) 3615 { 3616 dnssd_sock_t x = *(dnssd_sock_t *)CMSG_DATA(cmsg); 3617 LogOperation("%3d: Got BPF %d", req->sd, x); 3618 mDNSPlatformReceiveBPF_fd(&mDNSStorage, x); 3619 } 3620 else 3621#endif // APPLE_OSX_mDNSResponder 3622 req->errsd = *(dnssd_sock_t *)CMSG_DATA(cmsg); 3623#if DEBUG_64BIT_SCM_RIGHTS 3624 LogMsg("%3d: read req->errsd %d", req->sd, req->errsd); 3625#endif // DEBUG_64BIT_SCM_RIGHTS 3626 if (req->data_bytes < req->hdr.datalen) 3627 { 3628 LogMsg("%3d: Client sent error socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d", 3629 req->sd, req->errsd, req->data_bytes, req->hdr.datalen); 3630 req->ts = t_error; 3631 return; 3632 } 3633 } 3634#endif 3635 } 3636 3637 // If our header and data are both complete, see if we need to make our separate error return socket 3638 if (req->hdr_bytes == sizeof(ipc_msg_hdr) && req->data_bytes == req->hdr.datalen) 3639 { 3640 if (req->terminate && req->hdr.op != cancel_request) 3641 { 3642 dnssd_sockaddr_t cliaddr; 3643#if defined(USE_TCP_LOOPBACK) 3644 mDNSOpaque16 port; 3645 int opt = 1; 3646 port.b[0] = req->msgptr[0]; 3647 port.b[1] = req->msgptr[1]; 3648 req->msgptr += 2; 3649 cliaddr.sin_family = AF_INET; 3650 cliaddr.sin_port = port.NotAnInteger; 3651 cliaddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR); 3652#else 3653 char ctrl_path[MAX_CTLPATH]; 3654 get_string(&req->msgptr, req->msgend, ctrl_path, MAX_CTLPATH); // path is first element in message buffer 3655 mDNSPlatformMemZero(&cliaddr, sizeof(cliaddr)); 3656 cliaddr.sun_family = AF_LOCAL; 3657 mDNSPlatformStrCopy(cliaddr.sun_path, ctrl_path); 3658 // If the error return path UDS name is empty string, that tells us 3659 // that this is a new version of the library that's going to pass us 3660 // the error return path socket via sendmsg/recvmsg 3661 if (ctrl_path[0] == 0) 3662 { 3663 if (req->errsd == req->sd) 3664 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req->sd); req->ts = t_error; return; } 3665 goto got_errfd; 3666 } 3667#endif 3668 3669 req->errsd = socket(AF_DNSSD, SOCK_STREAM, 0); 3670 if (!dnssd_SocketValid(req->errsd)) { my_perror("ERROR: socket"); req->ts = t_error; return; } 3671 3672 if (connect(req->errsd, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) < 0) 3673 { 3674#if !defined(USE_TCP_LOOPBACK) 3675 struct stat sb; 3676 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)", 3677 req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno)); 3678 if (stat(cliaddr.sun_path, &sb) < 0) 3679 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req->sd, cliaddr.sun_path, dnssd_errno, dnssd_strerror(dnssd_errno)); 3680 else 3681 LogMsg("%3d: read_msg: file “%s” mode %o (octal) uid %d gid %d", req->sd, cliaddr.sun_path, sb.st_mode, sb.st_uid, sb.st_gid); 3682#endif 3683 req->ts = t_error; 3684 return; 3685 } 3686 3687got_errfd: 3688 LogOperation("%3d: Error socket %d created %08X %08X", req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0]); 3689#if defined(_WIN32) 3690 if (ioctlsocket(req->errsd, FIONBIO, &opt) != 0) 3691#else 3692 if (fcntl(req->errsd, F_SETFL, fcntl(req->errsd, F_GETFL, 0) | O_NONBLOCK) != 0) 3693#endif 3694 { 3695 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)", 3696 req->sd, dnssd_errno, dnssd_strerror(dnssd_errno)); 3697 req->ts = t_error; 3698 return; 3699 } 3700 } 3701 3702 req->ts = t_complete; 3703 } 3704 3705 return; 3706 3707rerror: 3708 if (dnssd_errno == dnssd_EWOULDBLOCK || dnssd_errno == dnssd_EINTR) return; 3709 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req->sd, dnssd_errno, dnssd_strerror(dnssd_errno)); 3710 req->ts = t_error; 3711 } 3712 3713#define RecordOrientedOp(X) \ 3714 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request) 3715 3716// The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them 3717#define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request) 3718 3719mDNSlocal void request_callback(int fd, short filter, void *info) 3720 { 3721 mStatus err = 0; 3722 request_state *req = info; 3723#if defined(_WIN32) 3724 u_long opt = 1; 3725#endif 3726 mDNSs32 min_size = sizeof(DNSServiceFlags); 3727 (void)fd; // Unused 3728 (void)filter; // Unused 3729 3730 read_msg(req); 3731 if (req->ts == t_morecoming) return; 3732 if (req->ts == t_terminated || req->ts == t_error) { AbortUnlinkAndFree(req); return; } 3733 if (req->ts != t_complete) { LogMsg("req->ts %d != t_complete", req->ts); AbortUnlinkAndFree(req); return; } 3734 3735 if (req->hdr.version != VERSION) 3736 { 3737 LogMsg("ERROR: client version %d incompatible with daemon version %d", req->hdr.version, VERSION); 3738 AbortUnlinkAndFree(req); 3739 return; 3740 } 3741 3742 switch(req->hdr.op) // Interface + other data 3743 { 3744 case connection_request: min_size = 0; break; 3745 case reg_service_request: min_size += sizeof(mDNSu32) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break; 3746 case add_record_request: min_size += 4 /* type, rdlen */ + 4 /* ttl */; break; 3747 case update_record_request: min_size += 2 /* rdlen */ + 4 /* ttl */; break; 3748 case remove_record_request: break; 3749 case browse_request: min_size += sizeof(mDNSu32) + 2 /* type, domain */; break; 3750 case resolve_request: min_size += sizeof(mDNSu32) + 3 /* type, type, domain */; break; 3751 case query_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 4 /* type, class*/; break; 3752 case enumeration_request: min_size += sizeof(mDNSu32); break; 3753 case reg_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break; 3754 case reconfirm_record_request: min_size += sizeof(mDNSu32) + 1 /* name */ + 6 /* type, class, rdlen */; break; 3755 case setdomain_request: min_size += 1 /* domain */; break; 3756 case getproperty_request: min_size = 2; break; 3757 case port_mapping_request: min_size += sizeof(mDNSu32) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break; 3758 case addrinfo_request: min_size += sizeof(mDNSu32) + 4 /* v4/v6 */ + 1 /* hostname */; break; 3759 case send_bpf: // Same as cancel_request below 3760 case cancel_request: min_size = 0; break; 3761 default: LogMsg("ERROR: validate_message - unsupported req type: %d", req->hdr.op); min_size = -1; break; 3762 } 3763 3764 if ((mDNSs32)req->data_bytes < min_size) 3765 { LogMsg("Invalid message %d bytes; min for %d is %d", req->data_bytes, req->hdr.op, min_size); AbortUnlinkAndFree(req); return; } 3766 3767 if (LightweightOp(req->hdr.op) && !req->terminate) 3768 { LogMsg("Reg/Add/Update/Remove %d require existing connection", req->hdr.op); AbortUnlinkAndFree(req); return; } 3769 3770 // check if client wants silent operation 3771 if (req->hdr.ipc_flags & IPC_FLAGS_NOREPLY) req->no_reply = 1; 3772 3773 // If req->terminate is already set, this means this operation is sharing an existing connection 3774 if (req->terminate && !LightweightOp(req->hdr.op)) 3775 { 3776 request_state *newreq = NewRequest(); 3777 newreq->primary = req; 3778 newreq->sd = req->sd; 3779 newreq->errsd = req->errsd; 3780 newreq->uid = req->uid; 3781 newreq->hdr = req->hdr; 3782 newreq->msgbuf = req->msgbuf; 3783 newreq->msgptr = req->msgptr; 3784 newreq->msgend = req->msgend; 3785 req = newreq; 3786 } 3787 3788 // If we're shutting down, don't allow new client requests 3789 // We do allow "cancel" and "getproperty" during shutdown 3790 if (mDNSStorage.ShutdownTime && req->hdr.op != cancel_request && req->hdr.op != getproperty_request) 3791 { 3792 err = mStatus_ServiceNotRunning; 3793 } 3794 else switch(req->hdr.op) 3795 { 3796 // These are all operations that have their own first-class request_state object 3797 case connection_request: LogOperation("%3d: DNSServiceCreateConnection START", req->sd); 3798 req->terminate = connection_termination; break; 3799 case resolve_request: err = handle_resolve_request (req); break; 3800 case query_request: err = handle_queryrecord_request (req); break; 3801 case browse_request: err = handle_browse_request (req); break; 3802 case reg_service_request: err = handle_regservice_request (req); break; 3803 case enumeration_request: err = handle_enum_request (req); break; 3804 case reconfirm_record_request: err = handle_reconfirm_request (req); break; 3805 case setdomain_request: err = handle_setdomain_request (req); break; 3806 case getproperty_request: handle_getproperty_request (req); break; 3807 case port_mapping_request: err = handle_port_mapping_request(req); break; 3808 case addrinfo_request: err = handle_addrinfo_request (req); break; 3809 case send_bpf: /* Do nothing for send_bpf */ break; 3810 3811 // These are all operations that work with an existing request_state object 3812 case reg_record_request: err = handle_regrecord_request (req); break; 3813 case add_record_request: err = handle_add_request (req); break; 3814 case update_record_request: err = handle_update_request (req); break; 3815 case remove_record_request: err = handle_removerecord_request(req); break; 3816 case cancel_request: handle_cancel_request (req); break; 3817 default: LogMsg("%3d: ERROR: Unsupported UDS req: %d", req->sd, req->hdr.op); 3818 } 3819 3820 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request 3821 if (req->msgbuf) freeL("request_state msgbuf", req->msgbuf); 3822 3823 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result) 3824 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here 3825 if (req->hdr.op != cancel_request && req->hdr.op != getproperty_request && req->hdr.op != send_bpf) 3826 { 3827 const mStatus err_netorder = dnssd_htonl(err); 3828 send_all(req->errsd, (const char *)&err_netorder, sizeof(err_netorder)); 3829 if (req->errsd != req->sd) 3830 { 3831 LogOperation("%3d: Error socket %d closed %08X %08X (%d)", 3832 req->sd, req->errsd, req->hdr.client_context.u32[1], req->hdr.client_context.u32[0], err); 3833 dnssd_close(req->errsd); 3834 req->errsd = req->sd; 3835 // Also need to reset the parent's errsd, if this is a subordinate operation 3836 if (req->primary) req->primary->errsd = req->primary->sd; 3837 } 3838 } 3839 3840 // Reset ready to accept the next req on this pipe 3841 if (req->primary) req = req->primary; 3842 req->ts = t_morecoming; 3843 req->hdr_bytes = 0; 3844 req->data_bytes = 0; 3845 req->msgbuf = mDNSNULL; 3846 req->msgptr = mDNSNULL; 3847 req->msgend = 0; 3848 } 3849 3850mDNSlocal void connect_callback(int fd, short filter, void *info) 3851 { 3852 dnssd_sockaddr_t cliaddr; 3853 dnssd_socklen_t len = (dnssd_socklen_t) sizeof(cliaddr); 3854 dnssd_sock_t sd = accept(fd, (struct sockaddr*) &cliaddr, &len); 3855#if defined(SO_NOSIGPIPE) || defined(_WIN32) 3856 const unsigned long optval = 1; 3857#endif 3858 3859 (void)filter; // Unused 3860 (void)info; // Unused 3861 3862 if (!dnssd_SocketValid(sd)) 3863 { 3864 if (dnssd_errno != dnssd_EWOULDBLOCK) my_perror("ERROR: accept"); 3865 return; 3866 } 3867 3868#ifdef SO_NOSIGPIPE 3869 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket 3870 if (setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) < 0) 3871 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd, dnssd_errno, dnssd_strerror(dnssd_errno)); 3872#endif 3873 3874#if defined(_WIN32) 3875 if (ioctlsocket(sd, FIONBIO, &optval) != 0) 3876#else 3877 if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) != 0) 3878#endif 3879 { 3880 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client"); 3881 dnssd_close(sd); 3882 return; 3883 } 3884 else 3885 { 3886 request_state *request = NewRequest(); 3887 request->ts = t_morecoming; 3888 request->sd = sd; 3889 request->errsd = sd; 3890#if APPLE_OSX_mDNSResponder 3891 struct xucred x; 3892 socklen_t xucredlen = sizeof(x); 3893 if (getsockopt(sd, 0, LOCAL_PEERCRED, &x, &xucredlen) >= 0 && x.cr_version == XUCRED_VERSION) request->uid = x.cr_uid; 3894 else my_perror("ERROR: getsockopt, LOCAL_PEERCRED"); 3895 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen, x.cr_version, x.cr_uid, x.cr_ngroups); 3896#endif // APPLE_OSX_mDNSResponder 3897 LogOperation("%3d: Adding FD for uid %u", request->sd, request->uid); 3898 udsSupportAddFDToEventLoop(sd, request_callback, request); 3899 } 3900 } 3901 3902mDNSlocal mDNSBool uds_socket_setup(dnssd_sock_t skt) 3903 { 3904#if defined(SO_NP_EXTENSIONS) 3905 struct so_np_extensions sonpx; 3906 socklen_t optlen = sizeof(struct so_np_extensions); 3907 sonpx.npx_flags = SONPX_SETOPTSHUT; 3908 sonpx.npx_mask = SONPX_SETOPTSHUT; 3909 if (setsockopt(skt, SOL_SOCKET, SO_NP_EXTENSIONS, &sonpx, optlen) < 0) 3910 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS"); 3911#endif 3912#if defined(_WIN32) 3913 // SEH: do we even need to do this on windows? 3914 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking 3915 u_long opt = 1; 3916 if (ioctlsocket(skt, FIONBIO, &opt) != 0) 3917#else 3918 if (fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK) != 0) 3919#endif 3920 { 3921 my_perror("ERROR: could not set listen socket to non-blocking mode"); 3922 return mDNSfalse; 3923 } 3924 3925 if (listen(skt, LISTENQ) != 0) 3926 { 3927 my_perror("ERROR: could not listen on listen socket"); 3928 return mDNSfalse; 3929 } 3930 3931 if (mStatus_NoError != udsSupportAddFDToEventLoop(skt, connect_callback, (void *) NULL)) 3932 { 3933 my_perror("ERROR: could not add listen socket to event loop"); 3934 return mDNSfalse; 3935 } 3936 else LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt); 3937 3938 return mDNStrue; 3939 } 3940 3941mDNSexport int udsserver_init(dnssd_sock_t skts[], mDNSu32 count) 3942 { 3943 dnssd_sockaddr_t laddr; 3944 int ret; 3945 mDNSu32 i = 0; 3946#if defined(_WIN32) 3947 u_long opt = 1; 3948#endif 3949 3950 LogInfo("udsserver_init"); 3951 3952 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be "" 3953 if (PID_FILE[0]) 3954 { 3955 FILE *fp = fopen(PID_FILE, "w"); 3956 if (fp != NULL) 3957 { 3958 fprintf(fp, "%d\n", getpid()); 3959 fclose(fp); 3960 } 3961 } 3962 3963 if (skts) 3964 { 3965 for (i = 0; i < count; i++) 3966 if (dnssd_SocketValid(skts[i]) && !uds_socket_setup(skts[i])) 3967 goto error; 3968 } 3969 else 3970 { 3971 listenfd = socket(AF_DNSSD, SOCK_STREAM, 0); 3972 if (!dnssd_SocketValid(listenfd)) 3973 { 3974 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed"); 3975 goto error; 3976 } 3977 3978 mDNSPlatformMemZero(&laddr, sizeof(laddr)); 3979 3980 #if defined(USE_TCP_LOOPBACK) 3981 { 3982 laddr.sin_family = AF_INET; 3983 laddr.sin_port = htons(MDNS_TCP_SERVERPORT); 3984 laddr.sin_addr.s_addr = inet_addr(MDNS_TCP_SERVERADDR); 3985 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); 3986 if (ret < 0) 3987 { 3988 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed"); 3989 goto error; 3990 } 3991 } 3992 #else 3993 { 3994 mode_t mask = umask(0); 3995 unlink(MDNS_UDS_SERVERPATH); // OK if this fails 3996 laddr.sun_family = AF_LOCAL; 3997 #ifndef NOT_HAVE_SA_LEN 3998 // According to Stevens (section 3.2), there is no portable way to 3999 // determine whether sa_len is defined on a particular platform. 4000 laddr.sun_len = sizeof(struct sockaddr_un); 4001 #endif 4002 mDNSPlatformStrCopy(laddr.sun_path, MDNS_UDS_SERVERPATH); 4003 ret = bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); 4004 umask(mask); 4005 if (ret < 0) 4006 { 4007 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed"); 4008 goto error; 4009 } 4010 } 4011 #endif 4012 4013 if (!uds_socket_setup(listenfd)) goto error; 4014 } 4015 4016#if !defined(PLATFORM_NO_RLIMIT) 4017 { 4018 // Set maximum number of open file descriptors 4019 #define MIN_OPENFILES 10240 4020 struct rlimit maxfds, newfds; 4021 4022 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>) 4023 // you have to get and set rlimits once before getrlimit will return sensible values 4024 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; } 4025 if (setrlimit(RLIMIT_NOFILE, &maxfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit"); 4026 4027 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; } 4028 newfds.rlim_max = (maxfds.rlim_max > MIN_OPENFILES) ? maxfds.rlim_max : MIN_OPENFILES; 4029 newfds.rlim_cur = (maxfds.rlim_cur > MIN_OPENFILES) ? maxfds.rlim_cur : MIN_OPENFILES; 4030 if (newfds.rlim_max != maxfds.rlim_max || newfds.rlim_cur != maxfds.rlim_cur) 4031 if (setrlimit(RLIMIT_NOFILE, &newfds) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit"); 4032 4033 if (getrlimit(RLIMIT_NOFILE, &maxfds) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; } 4034 debugf("maxfds.rlim_max %d", (long)maxfds.rlim_max); 4035 debugf("maxfds.rlim_cur %d", (long)maxfds.rlim_cur); 4036 } 4037#endif 4038 4039 // We start a "LocalOnly" query looking for Automatic Browse Domain records. 4040 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, it creates a 4041 // "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked 4042 mDNS_GetDomains(&mDNSStorage, &mDNSStorage.AutomaticBrowseDomainQ, mDNS_DomainTypeBrowseAutomatic, 4043 mDNSNULL, mDNSInterface_LocalOnly, AutomaticBrowseDomainChange, mDNSNULL); 4044 4045 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain 4046 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeRegistration); 4047 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage, &localdomain, mDNS_DomainTypeBrowse); 4048 AddAutoBrowseDomain(0, &localdomain); 4049 4050 udsserver_handle_configchange(&mDNSStorage); 4051 return 0; 4052 4053error: 4054 4055 my_perror("ERROR: udsserver_init"); 4056 return -1; 4057 } 4058 4059mDNSexport int udsserver_exit(void) 4060 { 4061 // If the launching environment created no listening socket, 4062 // that means we created it ourselves, so we should clean it up on exit 4063 if (dnssd_SocketValid(listenfd)) 4064 { 4065 dnssd_close(listenfd); 4066#if !defined(USE_TCP_LOOPBACK) 4067 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody" 4068 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket. 4069 // It would be nice if we could find a solution to this problem 4070 if (unlink(MDNS_UDS_SERVERPATH)) 4071 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH); 4072#endif 4073 } 4074 4075 if (PID_FILE[0]) unlink(PID_FILE); 4076 4077 return 0; 4078 } 4079 4080mDNSlocal void LogClientInfo(mDNS *const m, request_state *req) 4081 { 4082 if (!req->terminate) 4083 LogMsgNoIdent("%3d: No operation yet on this socket", req->sd); 4084 else if (req->terminate == connection_termination) 4085 { 4086 registered_record_entry *p; 4087 LogMsgNoIdent("%3d: DNSServiceCreateConnection", req->sd); 4088 for (p = req->u.reg_recs; p; p=p->next) 4089 LogMsgNoIdent(" -> DNSServiceRegisterRecord %3d %s", p->key, ARDisplayString(m, p->rr)); 4090 } 4091 else if (req->terminate == regservice_termination_callback) 4092 { 4093 service_instance *ptr; 4094 for (ptr = req->u.servicereg.instances; ptr; ptr = ptr->next) 4095 LogMsgNoIdent("%3d: DNSServiceRegister %##s %u/%u", 4096 req->sd, ptr->srs.RR_SRV.resrec.name->c, mDNSVal16(req->u.servicereg.port), SRS_PORT(&ptr->srs)); 4097 } 4098 else if (req->terminate == browse_termination_callback) 4099 { 4100 browser_t *blist; 4101 for (blist = req->u.browser.browsers; blist; blist = blist->next) 4102 LogMsgNoIdent("%3d: DNSServiceBrowse %##s", req->sd, blist->q.qname.c); 4103 } 4104 else if (req->terminate == resolve_termination_callback) 4105 LogMsgNoIdent("%3d: DNSServiceResolve %##s", req->sd, req->u.resolve.qsrv.qname.c); 4106 else if (req->terminate == queryrecord_termination_callback) 4107 LogMsgNoIdent("%3d: DNSServiceQueryRecord %##s (%s)", req->sd, req->u.queryrecord.q.qname.c, DNSTypeName(req->u.queryrecord.q.qtype)); 4108 else if (req->terminate == enum_termination_callback) 4109 LogMsgNoIdent("%3d: DNSServiceEnumerateDomains %##s", req->sd, req->u.enumeration.q_all.qname.c); 4110 else if (req->terminate == port_mapping_termination_callback) 4111 LogMsgNoIdent("%3d: DNSServiceNATPortMapping %.4a %s%s Int %d Req %d Ext %d Req TTL %d Granted TTL %d", 4112 req->sd, 4113 &req->u.pm.NATinfo.ExternalAddress, 4114 req->u.pm.NATinfo.Protocol & NATOp_MapTCP ? "TCP" : " ", 4115 req->u.pm.NATinfo.Protocol & NATOp_MapUDP ? "UDP" : " ", 4116 mDNSVal16(req->u.pm.NATinfo.IntPort), 4117 mDNSVal16(req->u.pm.ReqExt), 4118 mDNSVal16(req->u.pm.NATinfo.ExternalPort), 4119 req->u.pm.NATinfo.NATLease, 4120 req->u.pm.NATinfo.Lifetime); 4121 else if (req->terminate == addrinfo_termination_callback) 4122 LogMsgNoIdent("%3d: DNSServiceGetAddrInfo %s%s %##s", req->sd, 4123 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv4 ? "v4" : " ", 4124 req->u.addrinfo.protocol & kDNSServiceProtocol_IPv6 ? "v6" : " ", 4125 req->u.addrinfo.q4.qname.c); 4126 else 4127 LogMsgNoIdent("%3d: Unrecognized operation %p", req->sd, req->terminate); 4128 } 4129 4130mDNSlocal void LogAuthRecords(mDNS *const m, const mDNSs32 now, AuthRecord *ResourceRecords, int *proxy) 4131 { 4132 if (!ResourceRecords) LogMsgNoIdent("<None>"); 4133 else 4134 { 4135 const AuthRecord *ar; 4136 mDNSEthAddr owner = zeroEthAddr; 4137 LogMsgNoIdent(" Int Next Expire State"); 4138 for (ar = ResourceRecords; ar; ar=ar->next) 4139 { 4140 NetworkInterfaceInfo *info = (NetworkInterfaceInfo *)ar->resrec.InterfaceID; 4141 if (ar->WakeUp.HMAC.l[0]) (*proxy)++; 4142 if (!mDNSSameEthAddress(&owner, &ar->WakeUp.HMAC)) 4143 { 4144 owner = ar->WakeUp.HMAC; 4145 if (ar->WakeUp.password.l[0]) 4146 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &ar->WakeUp.HMAC, &ar->WakeUp.IMAC, &ar->WakeUp.password, ar->WakeUp.seq); 4147 else if (!mDNSSameEthAddress(&ar->WakeUp.HMAC, &ar->WakeUp.IMAC)) 4148 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &ar->WakeUp.HMAC, &ar->WakeUp.IMAC, ar->WakeUp.seq); 4149 else 4150 LogMsgNoIdent("Proxying for %.6a seq %d", &ar->WakeUp.HMAC, ar->WakeUp.seq); 4151 } 4152 if (AuthRecord_uDNS(ar)) 4153 LogMsgNoIdent("%7d %7d %7d %7d %s", 4154 ar->ThisAPInterval / mDNSPlatformOneSecond, 4155 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond, 4156 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0, 4157 ar->state, ARDisplayString(m, ar)); 4158 else if (ar->resrec.InterfaceID != mDNSInterface_LocalOnly) 4159 LogMsgNoIdent("%7d %7d %7d %7s %s", 4160 ar->ThisAPInterval / mDNSPlatformOneSecond, 4161 ar->AnnounceCount ? (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond : 0, 4162 ar->TimeExpire ? (ar->TimeExpire - now) / mDNSPlatformOneSecond : 0, 4163 info ? info->ifname : "ALL", 4164 ARDisplayString(m, ar)); 4165 else 4166 LogMsgNoIdent(" LO %s", ARDisplayString(m, ar)); 4167 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000); 4168 } 4169 } 4170 } 4171 4172mDNSexport void udsserver_info(mDNS *const m) 4173 { 4174 const mDNSs32 now = mDNS_TimeNow(m); 4175 mDNSu32 CacheUsed = 0, CacheActive = 0, slot; 4176 int ProxyA = 0, ProxyD = 0; 4177 const CacheGroup *cg; 4178 const CacheRecord *cr; 4179 const DNSQuestion *q; 4180 const DNameListElem *d; 4181 4182 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now); 4183 LogMsgNoIdent("------------ Cache -------------"); 4184 4185 LogMsgNoIdent("Slt Q TTL if U Type rdlen"); 4186 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) 4187 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next) 4188 { 4189 CacheUsed++; // Count one cache entity for the CacheGroup object 4190 for (cr = cg->members; cr; cr=cr->next) 4191 { 4192 mDNSs32 remain = cr->resrec.rroriginalttl - (now - cr->TimeRcvd) / mDNSPlatformOneSecond; 4193 NetworkInterfaceInfo *info = (NetworkInterfaceInfo *)cr->resrec.InterfaceID; 4194 CacheUsed++; 4195 if (cr->CRActiveQuestion) CacheActive++; 4196 LogMsgNoIdent("%3d %s%8ld %-7s%s %-6s%s", 4197 slot, 4198 cr->CRActiveQuestion ? "*" : " ", 4199 remain, 4200 info ? info->ifname : "-U-", 4201 (cr->resrec.RecordType == kDNSRecordTypePacketNegative) ? "-" : 4202 (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) ? " " : "+", 4203 DNSTypeName(cr->resrec.rrtype), 4204 CRDisplayString(m, cr)); 4205 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000); 4206 } 4207 } 4208 4209 if (m->rrcache_totalused != CacheUsed) 4210 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m->rrcache_totalused, CacheUsed); 4211 if (m->rrcache_active != CacheActive) 4212 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m->rrcache_active, CacheActive); 4213 LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed, CacheActive); 4214 4215 LogMsgNoIdent("--------- Auth Records ---------"); 4216 LogAuthRecords(m, now, m->ResourceRecords, &ProxyA); 4217 4218 LogMsgNoIdent("------ Duplicate Records -------"); 4219 LogAuthRecords(m, now, m->DuplicateRecords, &ProxyD); 4220 4221 LogMsgNoIdent("----- ServiceRegistrations -----"); 4222 if (!m->ServiceRegistrations) LogMsgNoIdent("<None>"); 4223 else 4224 { 4225 ServiceRecordSet *s; 4226 LogMsgNoIdent(" Int Next Expire State"); 4227 for (s = m->ServiceRegistrations; s; s = s->uDNS_next) 4228 LogMsgNoIdent("%7d %7d %7d %7d %s", 4229 s->RR_SRV.ThisAPInterval / mDNSPlatformOneSecond, 4230 (s->RR_SRV.LastAPTime + s->RR_SRV.ThisAPInterval - now) / mDNSPlatformOneSecond, 4231 s->RR_SRV.expire ? (s->RR_SRV.expire - now) / mDNSPlatformOneSecond : 0, 4232 s->state, ARDisplayString(m, &s->RR_SRV)); 4233 } 4234 4235 LogMsgNoIdent("---------- Questions -----------"); 4236 if (!m->Questions) LogMsgNoIdent("<None>"); 4237 else 4238 { 4239 CacheUsed = 0; 4240 CacheActive = 0; 4241 LogMsgNoIdent(" Int Next if T NumAns Type Name"); 4242 for (q = m->Questions; q; q=q->next) 4243 { 4244 mDNSs32 i = q->ThisQInterval / mDNSPlatformOneSecond; 4245 mDNSs32 n = (q->LastQTime + q->ThisQInterval - now) / mDNSPlatformOneSecond; 4246 NetworkInterfaceInfo *info = (NetworkInterfaceInfo *)q->InterfaceID; 4247 CacheUsed++; 4248 if (q->ThisQInterval) CacheActive++; 4249 LogMsgNoIdent("%6d%6d %-7s%s%s %5d %-6s%##s%s", 4250 i, n, 4251 info ? info->ifname : mDNSOpaque16IsZero(q->TargetQID) ? "" : "-U-", 4252 mDNSOpaque16IsZero(q->TargetQID) ? (q->LongLived ? "l" : " ") : (q->LongLived ? "L" : "O"), 4253 q->AuthInfo ? "P" : " ", 4254 q->CurrentAnswers, 4255 DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : ""); 4256 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000); 4257 } 4258 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed, CacheUsed > 1 ? "s" : "", CacheActive); 4259 } 4260 4261 LogMsgNoIdent("----- Local-Only Questions -----"); 4262 if (!m->LocalOnlyQuestions) LogMsgNoIdent("<None>"); 4263 else for (q = m->LocalOnlyQuestions; q; q=q->next) 4264 LogMsgNoIdent(" %5d %-6s%##s%s", 4265 q->CurrentAnswers, DNSTypeName(q->qtype), q->qname.c, q->DuplicateOf ? " (dup)" : ""); 4266 4267 LogMsgNoIdent("---- Active Client Requests ----"); 4268 if (!all_requests) LogMsgNoIdent("<None>"); 4269 else 4270 { 4271 request_state *req; 4272 for (req = all_requests; req; req=req->next) 4273 LogClientInfo(m, req); 4274 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000); 4275 } 4276 4277 LogMsgNoIdent("-------- NAT Traversals --------"); 4278 if (!m->NATTraversals) LogMsgNoIdent("<None>"); 4279 else 4280 { 4281 NATTraversalInfo *nat; 4282 for (nat = m->NATTraversals; nat; nat=nat->next) 4283 { 4284 if (nat->Protocol) 4285 LogMsgNoIdent("%p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d", 4286 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP", 4287 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result, 4288 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0, 4289 nat->retryInterval / mDNSPlatformOneSecond, 4290 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0); 4291 else 4292 LogMsgNoIdent("%p Address Request Retry %5d Interval %5d", nat, 4293 (m->retryGetAddr - now) / mDNSPlatformOneSecond, 4294 m->retryIntervalGetAddr / mDNSPlatformOneSecond); 4295 usleep((m->KnownBugs & mDNS_KnownBug_LossySyslog) ? 3333 : 1000); 4296 } 4297 } 4298 4299 LogMsgNoIdent("--------- AuthInfoList ---------"); 4300 if (!m->AuthInfoList) LogMsgNoIdent("<None>"); 4301 else 4302 { 4303 DomainAuthInfo *a; 4304 for (a = m->AuthInfoList; a; a = a->next) 4305 LogMsgNoIdent("%##s %##s%s", a->domain.c, a->keyname.c, a->AutoTunnel ? " AutoTunnel" : ""); 4306 } 4307 4308 #if APPLE_OSX_mDNSResponder 4309 LogMsgNoIdent("--------- TunnelClients --------"); 4310 if (!m->TunnelClients) LogMsgNoIdent("<None>"); 4311 else 4312 { 4313 ClientTunnel *c; 4314 for (c = m->TunnelClients; c; c = c->next) 4315 LogMsgNoIdent("%##s local %.16a %.4a remote %.16a %.4a %5d interval %d", 4316 c->dstname.c, &c->loc_inner, &c->loc_outer, &c->rmt_inner, &c->rmt_outer, mDNSVal16(c->rmt_outer_port), c->q.ThisQInterval); 4317 } 4318 #endif // APPLE_OSX_mDNSResponder 4319 4320 LogMsgNoIdent("---------- Misc State ----------"); 4321 4322 LogMsgNoIdent("PrimaryMAC: %.6a", &m->PrimaryMAC); 4323 4324 LogMsgNoIdent("m->SleepState %d (%s) seq %d", 4325 m->SleepState, 4326 m->SleepState == SleepState_Awake ? "Awake" : 4327 m->SleepState == SleepState_Transferring ? "Transferring" : 4328 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", 4329 m->SleepSeqNum); 4330 4331 if (!m->SPSSocket) LogMsgNoIdent("Not offering Sleep Proxy Service"); 4332 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m->SPSRecords.RR_SRV.resrec.name->c); 4333 4334 if (m->ProxyRecords == ProxyA + ProxyD) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA, ProxyD, ProxyA + ProxyD); 4335 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA, ProxyD, ProxyA + ProxyD, m->ProxyRecords); 4336 4337 LogMsgNoIdent("------ Auto Browse Domains -----"); 4338 if (!AutoBrowseDomains) LogMsgNoIdent("<None>"); 4339 else for (d=AutoBrowseDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c); 4340 4341 LogMsgNoIdent("--- Auto Registration Domains --"); 4342 if (!AutoRegistrationDomains) LogMsgNoIdent("<None>"); 4343 else for (d=AutoRegistrationDomains; d; d=d->next) LogMsgNoIdent("%##s", d->name.c); 4344 } 4345 4346#if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING 4347mDNSexport void uds_validatelists(void) 4348 { 4349 const request_state *req, *p; 4350 for (req = all_requests; req; req=req->next) 4351 { 4352 if (req->next == (request_state *)~0 || (req->sd < 0 && req->sd != -2)) 4353 LogMemCorruption("UDS request list: %p is garbage (%d)", req, req->sd); 4354 4355 if (req->primary == req) 4356 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req, req->sd); 4357 4358 if (req->primary && req->replies) 4359 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)", 4360 req, req->sd, req->primary && req->replies); 4361 4362 p = req->primary; 4363 if ((long)p & 3) 4364 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req, p, req->sd); 4365 else if (p && (p->next == (request_state *)~0 || (p->sd < 0 && p->sd != -2))) 4366 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req, p, p->sd); 4367 4368 reply_state *rep; 4369 for (rep = req->replies; rep; rep=rep->next) 4370 if (rep->next == (reply_state *)~0) 4371 LogMemCorruption("UDS req->replies: %p is garbage", rep); 4372 4373 if (req->terminate == connection_termination) 4374 { 4375 registered_record_entry *r; 4376 for (r = req->u.reg_recs; r; r=r->next) 4377 if (r->next == (registered_record_entry *)~0) 4378 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r); 4379 } 4380 else if (req->terminate == regservice_termination_callback) 4381 { 4382 service_instance *s; 4383 for (s = req->u.servicereg.instances; s; s=s->next) 4384 if (s->next == (service_instance *)~0) 4385 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s); 4386 } 4387 else if (req->terminate == browse_termination_callback) 4388 { 4389 browser_t *b; 4390 for (b = req->u.browser.browsers; b; b=b->next) 4391 if (b->next == (browser_t *)~0) 4392 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b); 4393 } 4394 } 4395 4396 DNameListElem *d; 4397 for (d = SCPrefBrowseDomains; d; d=d->next) 4398 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63) 4399 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d, d->name.c[0]); 4400 4401 ARListElem *b; 4402 for (b = LocalDomainEnumRecords; b; b=b->next) 4403 if (b->next == (ARListElem *)~0 || b->ar.resrec.name->c[0] > 63) 4404 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b, b->ar.resrec.name->c[0]); 4405 4406 for (d = AutoBrowseDomains; d; d=d->next) 4407 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63) 4408 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d, d->name.c[0]); 4409 4410 for (d = AutoRegistrationDomains; d; d=d->next) 4411 if (d->next == (DNameListElem *)~0 || d->name.c[0] > 63) 4412 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d, d->name.c[0]); 4413 } 4414#endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING 4415 4416mDNSlocal int send_msg(request_state *const req) 4417 { 4418 reply_state *const rep = req->replies; // Send the first waiting reply 4419 ssize_t nwriten; 4420 if (req->no_reply) return(t_complete); 4421 4422 ConvertHeaderBytes(rep->mhdr); 4423 nwriten = send(req->sd, (char *)&rep->mhdr + rep->nwriten, rep->totallen - rep->nwriten, 0); 4424 ConvertHeaderBytes(rep->mhdr); 4425 4426 if (nwriten < 0) 4427 { 4428 if (dnssd_errno == dnssd_EINTR || dnssd_errno == dnssd_EWOULDBLOCK) nwriten = 0; 4429 else 4430 { 4431#if !defined(PLATFORM_NO_EPIPE) 4432 if (dnssd_errno == EPIPE) 4433 return(req->ts = t_terminated); 4434 else 4435#endif 4436 { 4437 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)", 4438 rep->totallen - rep->nwriten, rep->totallen, req->sd, dnssd_errno, dnssd_strerror(dnssd_errno)); 4439 return(t_error); 4440 } 4441 } 4442 } 4443 rep->nwriten += nwriten; 4444 return (rep->nwriten == rep->totallen) ? t_complete : t_morecoming; 4445 } 4446 4447mDNSexport mDNSs32 udsserver_idle(mDNSs32 nextevent) 4448 { 4449 mDNSs32 now = mDNS_TimeNow(&mDNSStorage); 4450 request_state **req = &all_requests; 4451 4452 while (*req) 4453 { 4454 request_state *const r = *req; 4455 4456 if (r->terminate == resolve_termination_callback) 4457 if (r->u.resolve.ReportTime && now - r->u.resolve.ReportTime >= 0) 4458 { 4459 r->u.resolve.ReportTime = 0; 4460 LogMsgNoIdent("Client application bug: DNSServiceResolve(%##s) active for over two minutes. " 4461 "This places considerable burden on the network.", r->u.resolve.qsrv.qname.c); 4462 } 4463 4464 // Note: Only primary req's have reply lists, not subordinate req's. 4465 while (r->replies) // Send queued replies 4466 { 4467 transfer_state result; 4468 if (r->replies->next) r->replies->rhdr->flags |= dnssd_htonl(kDNSServiceFlagsMoreComing); 4469 result = send_msg(r); // Returns t_morecoming if buffer full because client is not reading 4470 if (result == t_complete) 4471 { 4472 reply_state *fptr = r->replies; 4473 r->replies = r->replies->next; 4474 freeL("reply_state/udsserver_idle", fptr); 4475 r->time_blocked = 0; // reset failure counter after successful send 4476 continue; 4477 } 4478 else if (result == t_terminated || result == t_error) 4479 { 4480 LogMsg("%3d: Could not write data to client because of error - aborting connection", r->sd); 4481 LogClientInfo(&mDNSStorage, r); 4482 abort_request(r); 4483 } 4484 break; 4485 } 4486 4487 if (r->replies) // If we failed to send everything, check our time_blocked timer 4488 { 4489 if (!r->time_blocked) r->time_blocked = NonZeroTime(now); 4490 if (now - r->time_blocked >= 60 * mDNSPlatformOneSecond) 4491 { 4492 LogMsg("%3d: Could not write data to client after %ld seconds - aborting connection", r->sd, 4493 (now - r->time_blocked) / mDNSPlatformOneSecond); 4494 LogClientInfo(&mDNSStorage, r); 4495 abort_request(r); 4496 } 4497 else if (nextevent - now > mDNSPlatformOneSecond) nextevent = now + mDNSPlatformOneSecond; 4498 } 4499 4500 if (!dnssd_SocketValid(r->sd)) // If this request is finished, unlink it from the list and free the memory 4501 { 4502 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree() 4503 *req = r->next; 4504 freeL("request_state/udsserver_idle", r); 4505 } 4506 else 4507 req = &r->next; 4508 } 4509 return nextevent; 4510 } 4511 4512struct CompileTimeAssertionChecks_uds_daemon 4513 { 4514 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding 4515 // other overly-large structures instead of having a pointer to them, can inadvertently 4516 // cause structure sizes (and therefore memory usage) to balloon unreasonably. 4517 char sizecheck_request_state [(sizeof(request_state) <= 1760) ? 1 : -1]; 4518 char sizecheck_registered_record_entry[(sizeof(registered_record_entry) <= 40) ? 1 : -1]; 4519 char sizecheck_service_instance [(sizeof(service_instance) <= 6552) ? 1 : -1]; 4520 char sizecheck_browser_t [(sizeof(browser_t) <= 992) ? 1 : -1]; 4521 char sizecheck_reply_hdr [(sizeof(reply_hdr) <= 12) ? 1 : -1]; 4522 char sizecheck_reply_state [(sizeof(reply_state) <= 64) ? 1 : -1]; 4523 }; 4524