1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2003-2006 Apple Computer, Inc. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 Change History (most recent first):
19 $Log: uds_daemon.c,v $
20 Revision 1.461 2009/06/19 23:15:07 cheshire
21 <rdar://problem/6990066> Library: crash at handle_resolve_response + 183
22 Made resolve_result_callback code more defensive and improved LogOperation messages
24 Revision 1.460 2009/05/26 21:31:07 herscher
25 Fix compile errors on Windows
27 Revision 1.459 2009/04/30 20:07:51 mcguire
28 <rdar://problem/6822674> Support multiple UDSs from launchd
30 Revision 1.458 2009/04/25 00:59:06 mcguire
31 Change a few stray LogInfo to LogOperation
33 Revision 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
36 Revision 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
39 Revision 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
41 Don't need "empty info->u.browser.browsers list" debugging message, now that we expect this to be
42 a case that can legitimately happen.
44 Revision 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
47 Revision 1.453 2009/04/11 00:20:29 jessic2
48 <rdar://problem/4426780> Daemon: Should be able to turn on LogOperation dynamically
50 Revision 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
53 Revision 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)
56 Revision 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.
59 Revision 1.449 2009/03/17 19:44:25 cheshire
60 <rdar://problem/6688927> Don't let negative unicast answers block Multicast DNS responses
62 Revision 1.448 2009/03/17 04:53:40 cheshire
63 <rdar://problem/6688927> Don't let negative unicast answers block Multicast DNS responses
65 Revision 1.447 2009/03/17 04:41:32 cheshire
66 Moved LogOperation message to after check for "if (answer->RecordType == kDNSRecordTypePacketNegative)"
68 Revision 1.446 2009/03/04 01:47:35 cheshire
69 Include m->ProxyRecords in SIGINFO output
71 Revision 1.445 2009/03/03 23:04:44 cheshire
72 For clarity, renamed "MAC" field to "HMAC" (Host MAC, as opposed to Interface MAC)
74 Revision 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
77 Revision 1.443 2009/02/27 02:28:41 cheshire
78 Need to declare "const AuthRecord *ar;"
80 Revision 1.442 2009/02/27 00:58:17 cheshire
81 Improved detail of SIGINFO logging for m->DuplicateRecords
83 Revision 1.441 2009/02/24 22:18:59 cheshire
84 Include interface name for interface-specific AuthRecords
86 Revision 1.440 2009/02/21 01:38:08 cheshire
87 Added report of m->SleepState value in SIGINFO output
89 Revision 1.439 2009/02/18 23:38:44 cheshire
90 <rdar://problem/6600780> Could not write data to client 13 - aborting connection
91 Eliminated unnecessary "request_state *request" field from the reply_state structure.
93 Revision 1.438 2009/02/18 23:23:14 cheshire
94 Cleaned up debugging log messages
96 Revision 1.437 2009/02/17 23:29:05 cheshire
97 Throttle logging to a slower rate when running on SnowLeopard
99 Revision 1.436 2009/02/13 06:28:02 cheshire
100 Converted LogOperation messages to LogInfo
102 Revision 1.435 2009/02/12 20:57:26 cheshire
103 Renamed 'LogAllOperation' switch to 'LogClientOperations'; added new 'LogSleepProxyActions' switch
105 Revision 1.434 2009/02/12 20:28:31 cheshire
106 Added some missing "const" declarations
108 Revision 1.433 2009/02/10 01:44:39 cheshire
109 <rdar://problem/6553729> DNSServiceUpdateRecord fails with kDNSServiceErr_BadReference for otherwise valid reference
111 Revision 1.432 2009/02/10 01:38:56 cheshire
112 Move regservice_termination_callback() earlier in file in preparation for subsequent work
114 Revision 1.431 2009/02/07 01:48:55 cheshire
115 In SIGINFO output include sequence number for proxied records
117 Revision 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
119 Only want to do unicast dot-local lookups for address queries and conventional (RFC 2782) SRV queries
121 Revision 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
125 Revision 1.428 2009/01/30 19:52:31 cheshire
126 Eliminated unnecessary duplicated "dnssd_sock_t sd" fields in service_instance and reply_state structures
128 Revision 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
131 Revision 1.426 2009/01/16 21:07:08 cheshire
132 In SIGINFO "Duplicate Records" list, show expiry time for Sleep Proxy records
134 Revision 1.425 2009/01/16 20:53:16 cheshire
135 Include information about Sleep Proxy records in SIGINFO output
137 Revision 1.424 2009/01/12 22:43:50 cheshire
138 Fixed "unused variable" warning when SO_NOSIGPIPE is not defined
140 Revision 1.423 2009/01/10 22:54:42 mkrochma
141 <rdar://problem/5797544> Fixes from Igor Seleznev to get mdnsd working on Linux
143 Revision 1.422 2009/01/10 01:52:48 cheshire
144 Include DuplicateRecords and LocalOnlyQuestions in SIGINFO output
146 Revision 1.421 2008/12/17 05:05:26 cheshire
147 Fixed alignment of NAT mapping syslog messages
149 Revision 1.420 2008/12/12 00:52:05 cheshire
150 mDNSPlatformSetBPF is now called mDNSPlatformReceiveBPF_fd
152 Revision 1.419 2008/12/10 02:11:44 cheshire
153 ARMv5 compiler doesn't like uncommented stuff after #endif
155 Revision 1.418 2008/12/09 05:12:53 cheshire
156 Updated debugging messages
158 Revision 1.417 2008/12/04 03:38:12 cheshire
159 Miscellaneous defensive coding changes and improvements to debugging log messages
161 Revision 1.416 2008/12/02 22:02:12 cheshire
162 <rdar://problem/6320621> Adding domains after TXT record updates registers stale TXT record data
164 Revision 1.415 2008/11/26 20:35:59 cheshire
165 Changed some "LogOperation" debugging messages to "debugf"
167 Revision 1.414 2008/11/26 00:02:25 cheshire
168 Improved SIGINFO output to list AutoBrowseDomains and AutoRegistrationDomains
170 Revision 1.413 2008/11/25 04:48:58 cheshire
171 Added logging to show whether Sleep Proxy Service is active
173 Revision 1.412 2008/11/24 23:05:43 cheshire
174 Additional checking in uds_validatelists()
176 Revision 1.411 2008/11/05 21:41:39 cheshire
177 Updated LogOperation message
179 Revision 1.410 2008/11/04 20:06:20 cheshire
180 <rdar://problem/6186231> Change MAX_DOMAIN_NAME to 256
182 Revision 1.409 2008/10/31 23:44:22 cheshire
183 Fixed compile error in Posix build
185 Revision 1.408 2008/10/29 21:32:33 cheshire
186 Align "DNSServiceEnumerateDomains ... RESULT" log messages
188 Revision 1.407 2008/10/27 07:34:36 cheshire
189 Additional sanity checks for debugging
191 Revision 1.406 2008/10/23 23:55:56 cheshire
192 Fixed some missing "const" declarations
194 Revision 1.405 2008/10/23 23:21:31 cheshire
195 Moved definition of dnssd_strerror() to be with the definition of dnssd_errno, in dnssd_ipc.h
197 Revision 1.404 2008/10/23 23:06:17 cheshire
198 Removed () from dnssd_errno macro definition -- it's not a function and doesn't need any arguments
200 Revision 1.403 2008/10/23 22:33:25 cheshire
201 Changed "NOTE:" to "Note:" so that BBEdit 9 stops putting those comment lines into the funtion popup menu
203 Revision 1.402 2008/10/22 19:47:59 cheshire
204 Instead of SameRData(), use equivalent IdenticalSameNameRecord() macro
206 Revision 1.401 2008/10/22 17:20:40 cheshire
207 Don't give up if setsockopt SO_NOSIGPIPE fails
209 Revision 1.400 2008/10/21 01:06:57 cheshire
210 Pass BPF fd to mDNSMacOSX.c using mDNSPlatformSetBPF() instead of just writing it into a shared global variable
212 Revision 1.399 2008/10/20 22:06:42 cheshire
213 Updated debugging log messages
215 Revision 1.398 2008/10/03 18:25:17 cheshire
216 Instead of calling "m->MainCallback" function pointer directly, call mDNSCore routine "mDNS_ConfigChanged(m);"
218 Revision 1.397 2008/10/02 22:26:21 cheshire
219 Moved declaration of BPF_fd from uds_daemon.c to mDNSMacOSX.c, where it really belongs
221 Revision 1.396 2008/09/30 01:04:55 cheshire
222 Made BPF code a bit more defensive, to ignore subsequent BPF fds if we get passed more than one
224 Revision 1.395 2008/09/27 01:28:43 cheshire
225 Added code to receive and store BPF fd when passed via a send_bpf message
227 Revision 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
229 Added a special-case to massage these new records for Bonjour Browser's benefit
231 Revision 1.393 2008/09/23 03:01:58 cheshire
232 Added operation logging of domain enumeration results
234 Revision 1.392 2008/09/18 22:30:06 cheshire
235 <rdar://problem/6230679> device-info record not removed when last service deregisters
237 Revision 1.391 2008/09/18 22:05:44 cheshire
238 Fixed "DNSServiceRegister ... ADDED" message to have escaping consistent with
239 the other DNSServiceRegister operation messages
241 Revision 1.390 2008/09/16 21:06:56 cheshire
242 Improved syslog output to show if q->LongLived flag is set for multicast questions
244 Revision 1.389 2008/07/25 22:34:11 mcguire
245 fix sizecheck issues for 64bit
247 Revision 1.388 2008/07/01 01:40:02 mcguire
248 <rdar://problem/5823010> 64-bit fixes
250 Revision 1.387 2008/02/26 21:24:13 cheshire
251 Fixed spelling mistake in comment
253 Revision 1.386 2008/02/26 20:23:15 cheshire
256 Revision 1.385 2008/02/19 21:50:52 cheshire
257 Shortened some overly-long lines
259 Revision 1.384 2007/12/22 01:38:05 cheshire
260 Improve display of "Auth Records" SIGINFO output
262 Revision 1.383 2007/12/07 00:45:58 cheshire
263 <rdar://problem/5526800> BTMM: Need to deregister records and services on shutdown/sleep
265 Revision 1.382 2007/11/30 20:11:48 cheshire
266 Fixed compile warning: declaration of 'remove' shadows a global declaration
268 Revision 1.381 2007/11/28 22:02:52 cheshire
269 Remove pointless "if (!domain)" check (domain is an array on the stack, so its address can never be null)
271 Revision 1.380 2007/11/28 18:38:41 cheshire
272 Fixed typo in log message: "DNSServiceResolver" -> "DNSServiceResolve"
274 Revision 1.379 2007/11/01 19:32:14 cheshire
275 Added "DEBUG_64BIT_SCM_RIGHTS" debugging code
277 Revision 1.378 2007/10/31 19:21:40 cheshire
278 Don't show Expire time for records and services that aren't currently registered
280 Revision 1.377 2007/10/30 23:48:20 cheshire
281 Improved SIGINFO listing of question state
283 Revision 1.376 2007/10/30 20:43:54 cheshire
284 Fixed compiler warning when LogClientOperations is turned off
286 Revision 1.375 2007/10/26 22:51:38 cheshire
287 Improved SIGINFO output to show timers for AuthRecords and ServiceRegistrations
289 Revision 1.374 2007/10/25 22:45:02 cheshire
290 Tidied up code for DNSServiceRegister callback status messages
292 Revision 1.373 2007/10/25 21:28:43 cheshire
293 Add ServiceRegistrations to SIGINFO output
295 Revision 1.372 2007/10/25 21:21:45 cheshire
296 <rdar://problem/5496734> BTMM: Need to retry registrations after failures
297 Don't unlink_and_free_service_instance at the first error
299 Revision 1.371 2007/10/18 23:34:40 cheshire
300 <rdar://problem/5532821> Need "considerable burden on the network" warning in uds_daemon.c
302 Revision 1.370 2007/10/17 18:44:23 cheshire
303 <rdar://problem/5539930> Goodbye packets not being sent for services on shutdown
305 Revision 1.369 2007/10/16 17:18:27 cheshire
306 Fixed Posix compile errors
308 Revision 1.368 2007/10/16 16:58:58 cheshire
309 Improved debugging error messages in read_msg()
311 Revision 1.367 2007/10/15 22:55:14 cheshire
312 Make read_msg return "void" (since request_callback just ignores the redundant return value anyway)
314 Revision 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
317 Revision 1.365 2007/10/06 03:25:23 cheshire
318 <rdar://problem/5525267> MacBuddy exits abnormally when clicking "Continue" in AppleConnect pane
320 Revision 1.364 2007/10/06 03:20:16 cheshire
321 Improved LogOperation debugging messages
323 Revision 1.363 2007/10/05 23:24:52 cheshire
324 Improved LogOperation messages about separate error return socket
326 Revision 1.362 2007/10/05 22:11:58 cheshire
327 Improved "send_msg ERROR" debugging message
329 Revision 1.361 2007/10/04 20:45:18 cheshire
330 <rdar://problem/5518381> Race condition in kDNSServiceFlagsShareConnection-mode call handling
332 Revision 1.360 2007/10/01 23:24:46 cheshire
333 SIGINFO output was mislabeling mDNSInterface_Any queries as unicast queries
335 Revision 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
338 Revision 1.358 2007/09/29 20:08:06 cheshire
339 Fixed typo in comment
341 Revision 1.357 2007/09/27 22:10:04 cheshire
342 Add LogOperation line for DNSServiceRegisterRecord callbacks
344 Revision 1.356 2007/09/26 21:29:30 cheshire
345 Improved question list SIGINFO output
347 Revision 1.355 2007/09/26 01:54:34 mcguire
348 Debugging: In SIGINFO output, show ClientTunnel query interval, which is how we determine whether a query is still active
350 Revision 1.354 2007/09/26 01:26:31 cheshire
351 <rdar://problem/5501567> BTMM: mDNSResponder crashes in free_service_instance enabling/disabling BTMM
352 Need to call SendServiceRemovalNotification *before* backpointer is cleared
354 Revision 1.353 2007/09/25 20:46:33 cheshire
355 Include DNSServiceRegisterRecord operations in SIGINFO output
357 Revision 1.352 2007/09/25 20:23:40 cheshire
358 <rdar://problem/5501567> BTMM: mDNSResponder crashes in free_service_instance enabling/disabling BTMM
359 Need to clear si->request backpointer before calling mDNS_DeregisterService(&mDNSStorage, &si->srs);
361 Revision 1.351 2007/09/25 18:20:34 cheshire
362 Changed name of "free_service_instance" to more accurate "unlink_and_free_service_instance"
364 Revision 1.350 2007/09/24 23:54:52 mcguire
365 Additional list checking in uds_validatelists()
367 Revision 1.349 2007/09/24 06:01:00 cheshire
368 Debugging: In SIGINFO output, show NAT Traversal time values in seconds rather than platform ticks
370 Revision 1.348 2007/09/24 05:02:41 cheshire
371 Debugging: In SIGINFO output, indicate explicitly when a given section is empty
373 Revision 1.347 2007/09/21 02:04:33 cheshire
374 <rdar://problem/5440831> BTMM: mDNSResponder crashes in free_service_instance enabling/disabling BTMM
376 Revision 1.346 2007/09/19 22:47:25 cheshire
377 <rdar://problem/5490182> Memory corruption freeing a "no such service" service record
379 Revision 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
382 Revision 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
385 Revision 1.343 2007/09/18 21:42:30 cheshire
386 To reduce programming mistakes, renamed ExtPort to RequestedPort
388 Revision 1.342 2007/09/14 22:38:20 cheshire
389 Additional list checking in uds_validatelists()
391 Revision 1.341 2007/09/13 00:16:43 cheshire
392 <rdar://problem/5468706> Miscellaneous NAT Traversal improvements
394 Revision 1.340 2007/09/12 23:03:08 cheshire
395 <rdar://problem/5476978> DNSServiceNATPortMappingCreate callback not giving correct interface index
397 Revision 1.339 2007/09/12 19:22:21 cheshire
398 Variable renaming in preparation for upcoming fixes e.g. priv/pub renamed to intport/extport
399 Made NAT Traversal packet handlers take typed data instead of anonymous "mDNSu8 *" byte pointers
401 Revision 1.338 2007/09/12 01:22:13 cheshire
402 Improve validatelists() checking to detect when 'next' pointer gets smashed to ~0
404 Revision 1.337 2007/09/07 23:05:04 cheshire
405 Add display of client_context field in handle_cancel_request() LogOperation message
406 While loop was checking client_context.u32[2] instead of client_context.u32[1]
408 Revision 1.336 2007/09/07 20:56:03 cheshire
409 Renamed uint32_t field in client_context_t from "ptr64" to more accurate name "u32"
411 Revision 1.335 2007/09/05 22:25:01 vazquez
412 <rdar://problem/5400521> update_record mDNSResponder leak
414 Revision 1.334 2007/09/05 20:43:57 cheshire
415 Added LogOperation message showing fd of socket listening for incoming Unix Domain Socket client requests
417 Revision 1.333 2007/08/28 23:32:35 cheshire
418 Added LogOperation messages for DNSServiceNATPortMappingCreate() operations
420 Revision 1.332 2007/08/27 22:59:31 cheshire
421 Show reg_index in DNSServiceRegisterRecord/DNSServiceRemoveRecord messages
423 Revision 1.331 2007/08/27 20:29:57 cheshire
424 Added SIGINFO listing of TunnelClients
426 Revision 1.330 2007/08/24 23:46:50 cheshire
427 Added debugging messages and SIGINFO listing of DomainAuthInfo records
429 Revision 1.329 2007/08/18 01:02:04 mcguire
430 <rdar://problem/5415593> No Bonjour services are getting registered at boot
432 Revision 1.328 2007/08/15 20:18:28 vazquez
433 <rdar://problem/5400521> update_record mDNSResponder leak
434 Make sure we free all ExtraResourceRecords
436 Revision 1.327 2007/08/08 22:34:59 mcguire
437 <rdar://problem/5197869> Security: Run mDNSResponder as user id mdnsresponder instead of root
439 Revision 1.326 2007/08/01 16:09:14 cheshire
440 Removed unused NATTraversalInfo substructure from AuthRecord; reduced structure sizecheck values accordingly
442 Revision 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")
445 Revision 1.324 2007/07/31 01:56:21 cheshire
446 Corrected function name in log message
448 Revision 1.323 2007/07/27 23:57:23 cheshire
449 Added compile-time structure size checks
451 Revision 1.322 2007/07/27 19:37:19 cheshire
452 Moved AutomaticBrowseDomainQ into main mDNS object
454 Revision 1.321 2007/07/27 19:30:41 cheshire
455 Changed mDNSQuestionCallback parameter from mDNSBool to QC_result,
456 to properly reflect tri-state nature of the possible responses
458 Revision 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
462 Revision 1.319 2007/07/24 17:23:33 cheshire
463 <rdar://problem/5357133> Add list validation checks for debugging
465 Revision 1.318 2007/07/23 23:09:51 cheshire
466 <rdar://problem/5351997> Reject oversized client requests
468 Revision 1.317 2007/07/23 22:24:47 cheshire
469 <rdar://problem/5352299> Make mDNSResponder more defensive against malicious local clients
470 Additional refinements
472 Revision 1.316 2007/07/23 22:12:53 cheshire
473 <rdar://problem/5352299> Make mDNSResponder more defensive against malicious local clients
475 Revision 1.315 2007/07/21 01:36:13 cheshire
476 Need to also add ".local" as automatic browsing domain
478 Revision 1.314 2007/07/20 20:12:37 cheshire
479 Rename "mDNS_DomainTypeBrowseLegacy" as "mDNS_DomainTypeBrowseAutomatic"
481 Revision 1.313 2007/07/20 00:54:21 cheshire
482 <rdar://problem/4641118> Need separate SCPreferences for per-user .Mac settings
484 Revision 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
487 Revision 1.311 2007/07/06 21:19:18 cheshire
488 Add list of NAT traversals to SIGINFO output
490 Revision 1.310 2007/07/03 19:56:50 cheshire
491 Add LogOperation message for DNSServiceSetDefaultDomainForUser
493 Revision 1.309 2007/06/29 23:12:49 vazquez
494 <rdar://problem/5294103> Stop using generate_final_fatal_reply_with_garbage
496 Revision 1.308 2007/06/29 00:10:07 vazquez
497 <rdar://problem/5301908> Clean up NAT state machine (necessary for 6 other fixes)
499 Revision 1.307 2007/05/25 00:25:44 cheshire
500 <rdar://problem/5227737> Need to enhance putRData to output all current known types
502 Revision 1.306 2007/05/24 22:31:35 vazquez
504 Reviewed by: Stuart Cheshire
505 <rdar://problem/4272956> WWDC API: Return ADD/REMOVE events in registration callback
507 Revision 1.305 2007/05/23 18:59:22 cheshire
508 Remove unnecessary IPC_FLAGS_REUSE_SOCKET
510 Revision 1.304 2007/05/22 01:07:42 cheshire
511 <rdar://problem/3563675> API: Need a way to get version/feature information
513 Revision 1.303 2007/05/22 00:32:58 cheshire
514 Make a send_all() subroutine -- will be helpful for implementing DNSServiceGetProperty(DaemonVersion)
516 Revision 1.302 2007/05/21 18:54:54 cheshire
517 Add "Cancel" LogOperation message when we get a cancel_request command over the UDS
519 Revision 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
522 Revision 1.300 2007/05/18 21:27:11 cheshire
523 Rename connected_registration_termination to connection_termination
525 Revision 1.299 2007/05/18 21:24:34 cheshire
526 Rename rstate to request
528 Revision 1.298 2007/05/18 21:22:35 cheshire
529 Convert uint16_t etc. to their locally-defined equivalents, like the rest of the core code
531 Revision 1.297 2007/05/18 20:33:11 cheshire
532 Avoid declaring lots of uninitialized variables in read_rr_from_ipc_msg
534 Revision 1.296 2007/05/18 19:04:19 cheshire
535 Rename msgdata to msgptr (may be modified); rename (currently unused) bufsize to msgend
537 Revision 1.295 2007/05/18 17:57:13 cheshire
538 Reorder functions in file to arrange them in logical groups; added "#pragma mark" headers for each group
540 Revision 1.294 2007/05/17 20:58:22 cheshire
541 <rdar://problem/4647145> DNSServiceQueryRecord should return useful information with NXDOMAIN
543 Revision 1.293 2007/05/17 19:46:20 cheshire
544 Routine 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,
546 thereby trashing it and making it useless for any subsequent communication. It's destructive,
547 and not very useful. Changing name to generate_final_fatal_reply_with_garbage().
549 Revision 1.292 2007/05/16 01:06:52 cheshire
550 <rdar://problem/4471320> Improve reliability of kDNSServiceFlagsMoreComing flag on multiprocessor machines
552 Revision 1.291 2007/05/15 21:57:16 cheshire
553 <rdar://problem/4608220> Use dnssd_SocketValid(x) macro instead of just
554 assuming that all negative values (or zero!) are invalid socket numbers
556 Revision 1.290 2007/05/10 23:30:57 cheshire
557 <rdar://problem/4084490> Only one browse gets remove events when disabling browse domain
559 Revision 1.289 2007/05/02 22:18:08 cheshire
560 Renamed NATTraversalInfo_struct context to NATTraversalContext
562 Revision 1.288 2007/04/30 21:33:39 cheshire
563 Fix crash when a callback unregisters a service while the UpdateSRVRecords() loop
564 is iterating through the m->ServiceRegistrations list
566 Revision 1.287 2007/04/27 19:03:22 cheshire
567 Check q->LongLived not q->llq to tell if a query is LongLived
569 Revision 1.286 2007/04/26 16:00:01 cheshire
570 Show interface number in DNSServiceBrowse RESULT output
572 Revision 1.285 2007/04/22 19:03:39 cheshire
575 Revision 1.284 2007/04/22 06:02:03 cheshire
576 <rdar://problem/4615977> Query should immediately return failure when no server
578 Revision 1.283 2007/04/21 21:47:47 cheshire
579 <rdar://problem/4376383> Daemon: Add watchdog timer
581 Revision 1.282 2007/04/20 21:17:24 cheshire
582 For naming consistency, kDNSRecordTypeNegative should be kDNSRecordTypePacketNegative
584 Revision 1.281 2007/04/19 23:25:20 cheshire
585 Added debugging message
587 Revision 1.280 2007/04/17 19:21:29 cheshire
588 <rdar://problem/5140339> Domain discovery not working over VPN
590 Revision 1.279 2007/04/16 21:53:49 cheshire
591 Improve display of negative cache entries
593 Revision 1.278 2007/04/16 20:49:40 cheshire
594 Fix compile errors for mDNSPosix build
596 Revision 1.277 2007/04/05 22:55:36 cheshire
597 <rdar://problem/5077076> Records are ending up in Lighthouse without expiry information
599 Revision 1.276 2007/04/05 19:20:13 cheshire
600 Non-blocking mode not being set correctly -- was clobbering other flags
602 Revision 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
605 Revision 1.274 2007/04/04 01:30:42 cheshire
606 <rdar://problem/5075200> DNSServiceAddRecord is failing to advertise NULL record
607 Add SIGINFO output lising our advertised Authoritative Records
609 Revision 1.273 2007/04/04 00:03:27 cheshire
610 <rdar://problem/5089862> DNSServiceQueryRecord is returning kDNSServiceErr_NoSuchRecord for empty rdata
612 Revision 1.272 2007/04/03 20:10:32 cheshire
613 Show ADD/RMV in DNSServiceQueryRecord log message instead of just "RESULT"
615 Revision 1.271 2007/04/03 19:22:32 cheshire
616 Use mDNSSameIPv4Address (and similar) instead of accessing internal fields directly
618 Revision 1.270 2007/03/30 21:55:30 cheshire
621 Revision 1.269 2007/03/29 01:31:44 cheshire
622 Faulty logic was incorrectly suppressing some NAT port mapping callbacks
624 Revision 1.268 2007/03/29 00:13:58 cheshire
625 Remove unnecessary fields from service_instance structure: autoname, autorename, allowremotequery, name
627 Revision 1.267 2007/03/28 20:59:27 cheshire
628 <rdar://problem/4743285> Remove inappropriate use of IsPrivateV4Addr()
630 Revision 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
633 Revision 1.265 2007/03/27 22:52:07 cheshire
634 Fix crash in udsserver_automatic_browse_domain_changed
636 Revision 1.264 2007/03/27 00:49:40 cheshire
637 Should use mallocL, not plain malloc
639 Revision 1.263 2007/03/27 00:45:01 cheshire
640 Removed unnecessary "void *termination_context" pointer
642 Revision 1.262 2007/03/27 00:40:43 cheshire
643 Eliminate resolve_termination_t as a separately-allocated structure, and make it part of the request_state union
645 Revision 1.261 2007/03/27 00:29:00 cheshire
646 Eliminate queryrecord_request data as a separately-allocated structure, and make it part of the request_state union
648 Revision 1.260 2007/03/27 00:18:42 cheshire
649 Eliminate enum_termination_t and domain_enum_t as separately-allocated structures,
650 and make them part of the request_state union
652 Revision 1.259 2007/03/26 23:48:16 cheshire
653 <rdar://problem/4848295> Advertise model information via Bonjour
654 Refinements to reduce unnecessary transmissions of the DeviceInfo TXT record
656 Revision 1.258 2007/03/24 00:40:04 cheshire
659 Revision 1.257 2007/03/24 00:23:12 cheshire
660 Eliminate port_mapping_info_t as a separately-allocated structure, and make it part of the request_state union
662 Revision 1.256 2007/03/24 00:07:18 cheshire
663 Eliminate addrinfo_info_t as a separately-allocated structure, and make it part of the request_state union
665 Revision 1.255 2007/03/23 23:56:14 cheshire
666 Move list of record registrations into the request_state union
668 Revision 1.254 2007/03/23 23:48:56 cheshire
669 Eliminate service_info as a separately-allocated structure, and make it part of the request_state union
671 Revision 1.253 2007/03/23 23:04:29 cheshire
672 Eliminate browser_info_t as a separately-allocated structure, and make it part of request_state
674 Revision 1.252 2007/03/23 22:59:58 cheshire
675 <rdar://problem/4848295> Advertise model information via Bonjour
676 Use kStandardTTL, not kHostNameTTL
678 Revision 1.251 2007/03/23 22:44:07 cheshire
679 Instead of calling AbortUnlinkAndFree() haphazardly all over the place, make the handle* routines
680 return an error code, and then request_callback() does all necessary cleanup in one place.
682 Revision 1.250 2007/03/22 20:30:07 cheshire
683 Remove pointless "if (request->ts != t_complete) ..." checks
685 Revision 1.249 2007/03/22 20:13:27 cheshire
686 Delete unused client_context field
688 Revision 1.248 2007/03/22 20:03:37 cheshire
689 Rename variables for clarity: instead of using variable rs for both request_state
690 and reply_state, use req for request_state and rep for reply_state
692 Revision 1.247 2007/03/22 19:31:42 cheshire
693 <rdar://problem/4848295> Advertise model information via Bonjour
694 Add missing "model=" at start of DeviceInfo data
696 Revision 1.246 2007/03/22 18:31:48 cheshire
697 Put dst parameter first in mDNSPlatformStrCopy/mDNSPlatformMemCopy, like conventional Posix strcpy/memcpy
699 Revision 1.245 2007/03/22 00:49:20 cheshire
700 <rdar://problem/4848295> Advertise model information via Bonjour
702 Revision 1.244 2007/03/21 21:01:48 cheshire
703 <rdar://problem/4789793> Leak on error path in regrecord_callback, uds_daemon.c
705 Revision 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
708 Revision 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
711 Revision 1.241 2007/03/20 00:04:50 cheshire
712 <rdar://problem/4837929> Should allow "udp" or "tcp" for protocol command-line arg
713 Fix LogOperation("DNSServiceNATPortMappingCreate(...)") message to actually show client arguments
715 Revision 1.240 2007/03/16 23:25:35 cheshire
716 <rdar://problem/5067001> NAT-PMP: Parameter validation not working correctly
718 Revision 1.239 2007/03/10 02:29:36 cheshire
719 Added comment about port_mapping_create_reply()
721 Revision 1.238 2007/03/07 00:26:48 cheshire
722 <rdar://problem/4426754> DNSServiceRemoveRecord log message should include record type
724 Revision 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
727 Revision 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
730 Revision 1.235 2007/02/08 21:12:28 cheshire
731 <rdar://problem/4386497> Stop reading /etc/mDNSResponder.conf on every sleep/wake
733 Revision 1.234 2007/02/06 19:06:49 cheshire
734 <rdar://problem/3956518> Need to go native with launchd
736 Revision 1.233 2007/01/10 20:49:37 cheshire
737 Remove unnecessary setting of q->Private fields
739 Revision 1.232 2007/01/09 00:03:23 cheshire
740 Call udsserver_handle_configchange() once at the end of udsserver_init()
741 to set up the automatic registration and browsing domains.
743 Revision 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
746 Revision 1.230 2007/01/06 01:00:35 cheshire
747 Improved SIGINFO output
749 Revision 1.229 2007/01/05 08:30:56 cheshire
750 Trim excessive "$Log" checkin history from before 2006
751 (checkin history still available via "cvs log ..." of course)
753 Revision 1.228 2007/01/05 08:09:05 cheshire
754 Reorder code into functional sections, with "#pragma mark" headers
756 Revision 1.227 2007/01/05 07:04:24 cheshire
759 Revision 1.226 2007/01/05 05:44:35 cheshire
760 Move automatic browse/registration management from uDNS.c to mDNSShared/uds_daemon.c,
761 so that mDNSPosix embedded clients will compile again
763 Revision 1.225 2007/01/04 23:11:15 cheshire
764 <rdar://problem/4720673> uDNS: Need to start caching unicast records
765 When an automatic browsing domain is removed, generate appropriate "remove" events for legacy queries
767 Revision 1.224 2007/01/04 20:57:49 cheshire
768 Rename ReturnCNAME to ReturnIntermed (for ReturnIntermediates)
770 Revision 1.223 2006/12/21 01:25:49 cheshire
771 Tidy up SIGINFO state log
773 Revision 1.222 2006/12/21 00:15:22 cheshire
774 Get rid of gmDNS macro; fixed a crash in udsserver_info()
776 Revision 1.221 2006/12/20 04:07:38 cheshire
777 Remove uDNS_info substructure from AuthRecord_struct
779 Revision 1.220 2006/12/19 22:49:25 cheshire
780 Remove uDNS_info substructure from ServiceRecordSet_struct
782 Revision 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
785 Revision 1.218 2006/11/18 05:01:33 cheshire
786 Preliminary support for unifying the uDNS and mDNS code,
787 including caching of uDNS answers
789 Revision 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
792 Revision 1.216 2006/11/10 00:54:16 cheshire
793 <rdar://problem/4816598> Changing case of Computer Name doesn't work
795 Revision 1.215 2006/10/27 01:30:23 cheshire
796 Need explicitly to set ReturnIntermed = mDNSfalse
798 Revision 1.214 2006/10/20 05:37:23 herscher
799 Display question list information in udsserver_info()
801 Revision 1.213 2006/10/05 03:54:31 herscher
802 Remove embedded uDNS_info struct from DNSQuestion_struct
804 Revision 1.212 2006/09/30 01:22:35 cheshire
805 Put back UTF-8 curly quotes in log messages
807 Revision 1.211 2006/09/27 00:44:55 herscher
808 <rdar://problem/4249761> API: Need DNSServiceGetAddrInfo()
810 Revision 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)
813 Revision 1.209 2006/09/21 21:34:09 cheshire
814 <rdar://problem/4100000> Allow empty string name when using kDNSServiceFlagsNoAutoRename
816 Revision 1.208 2006/09/21 21:28:24 cheshire
817 Code cleanup to make it consistent with daemon.c: change rename_on_memfree to renameonmemfree
819 Revision 1.207 2006/09/15 21:20:16 cheshire
820 Remove uDNS_info substructure from mDNS_struct
822 Revision 1.206 2006/08/14 23:24:56 cheshire
823 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
825 Revision 1.205 2006/07/20 22:07:30 mkrochma
826 <rdar://problem/4633196> Wide-area browsing is currently broken in TOT
827 More fixes for uninitialized variables
829 Revision 1.204 2006/07/15 02:01:33 cheshire
830 <rdar://problem/4472014> Add Private DNS client functionality to mDNSResponder
831 Fix broken "empty string" browsing
833 Revision 1.203 2006/07/07 01:09:13 cheshire
834 <rdar://problem/4472013> Add Private DNS server functionality to dnsextd
835 Only use mallocL/freeL debugging routines when building mDNSResponder, not dnsextd
837 Revision 1.202 2006/07/05 22:00:10 cheshire
838 Wide-area cleanup: Rename mDNSPlatformGetRegDomainList() to uDNS_GetDefaultRegDomainList()
840 Revision 1.201 2006/06/29 03:02:47 cheshire
841 <rdar://problem/4607042> mDNSResponder NXDOMAIN and CNAME support
843 Revision 1.200 2006/06/28 08:56:26 cheshire
844 Added "_op" to the end of the operation code enum values,
845 to differentiate them from the routines with the same names
847 Revision 1.199 2006/06/28 08:53:39 cheshire
848 Added (commented out) debugging messages
850 Revision 1.198 2006/06/27 20:16:07 cheshire
853 Revision 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)
857 Revision 1.196 2006/05/05 07:07:13 cheshire
858 <rdar://problem/4538206> mDNSResponder fails when UDS reads deliver partial data
860 Revision 1.195 2006/04/25 20:56:28 mkrochma
861 Added comment about previous checkin
863 Revision 1.194 2006/04/25 18:29:36 mkrochma
864 Workaround for warning: unused variable 'status' when building mDNSPosix
866 Revision 1.193 2006/03/19 17:14:38 cheshire
867 <rdar://problem/4483117> Need faster purging of stale records
868 read_rr_from_ipc_msg was not setting namehash and rdatahash
870 Revision 1.192 2006/03/18 20:58:32 cheshire
871 Misplaced curly brace
873 Revision 1.191 2006/03/10 22:19:43 cheshire
874 Update debugging message in resolve_result_callback() to indicate whether event is ADD or RMV
876 Revision 1.190 2006/03/10 21:56:12 cheshire
877 <rdar://problem/4111464> After record update, old record sometimes remains in cache
878 When service TXT and SRV record both change, clients with active resolve calls get *two* callbacks, one
879 when the TXT data changes, and then immediately afterwards a second callback with the new port number
880 This change suppresses the first unneccessary (and confusing) callback
882 Revision 1.189 2006/01/06 00:56:31 cheshire
883 <rdar://problem/4400573> Should remove PID file on exit
889 #define usleep(X) Sleep(((X)+999)/1000)
893 #include <sys/ioctl.h>
894 #include <sys/types.h>
895 #include <sys/time.h>
896 #include <sys/resource.h>
902 #include "mDNSEmbeddedAPI.h"
903 #include "DNSCommon.h"
905 #include "uds_daemon.h"
907 // Apple-specific functionality, not required for other platforms
908 #if APPLE_OSX_mDNSResponder
909 #include <sys/ucred.h>
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)
919 // ***************************************************************************
920 #if COMPILER_LIKES_PRAGMA_MARK
922 #pragma mark - Types and Data Structures
934 typedef struct request_state request_state
;
936 typedef void (*req_termination_fn
)(request_state
*request
);
938 typedef struct registered_record_entry
940 struct registered_record_entry
*next
;
942 AuthRecord
*rr
; // Pointer to variable-sized AuthRecord
943 client_context_t regrec_client_context
;
944 request_state
*request
;
945 } registered_record_entry
;
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.
950 typedef struct service_instance
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?
959 ServiceRecordSet srs
; // note -- variable-sized object -- must be last field in struct
962 // for multi-domain default browsing
963 typedef struct browser_t
965 struct browser_t
*next
;
973 request_state
*primary
; // If this operation is on a shared socket, pointer to primary
974 // request_state for the original DNSServiceConnect() operation
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.
983 mDNSu32 hdr_bytes
; // bytes of header already read
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
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
;
998 registered_record_entry
*reg_recs
; // list of registrations for a connection-oriented request
1001 mDNSInterfaceID interface_id
;
1002 mDNSBool default_domain
;
1003 mDNSBool ForceMCast
;
1005 browser_t
*browsers
;
1009 mDNSInterfaceID InterfaceID
;
1014 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
];
1016 mDNSBool default_domain
;
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?
1022 service_instance
*instances
;
1026 mDNSInterfaceID interface_id
;
1034 mDNSIPPort ReqExt
; // External port we originally requested, for logging purposes
1035 NATTraversalInfo NATinfo
;
1040 DNSServiceFlags flags
;
1043 DNSQuestion q_default
;
1054 const ResourceRecord
*txt
;
1055 const ResourceRecord
*srv
;
1061 // struct physically sits between ipc message header and call-specific fields in the message buffer
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
1069 typedef struct reply_state
1071 struct reply_state
*next
; // If there are multiple unsent replies
1074 ipc_msg_hdr mhdr
[1];
1078 // ***************************************************************************
1079 #if COMPILER_LIKES_PRAGMA_MARK
1081 #pragma mark - Globals
1085 mDNSexport mDNS mDNSStorage
;
1086 mDNSexport
const char ProgramName
[] = "mDNSResponder";
1088 static dnssd_sock_t listenfd
= dnssd_InvalidSocket
;
1089 static request_state
*all_requests
= NULL
;
1091 static DNameListElem
*SCPrefBrowseDomains
; // List of automatic browsing domains read from SCPreferences for "empty string" browsing
1092 static ARListElem
*LocalDomainEnumRecords
; // List of locally-generated PTR records to augment those we learn from the network
1093 mDNSexport DNameListElem
*AutoBrowseDomains
; // List created from those local-only PTR records plus records we get from the network
1095 mDNSexport DNameListElem
*AutoRegistrationDomains
; // Domains where we automatically register for empty-string registrations
1097 #define MSG_PAD_BYTES 5 // pad message buffer (read from client) with n zero'd bytes to guarantee
1098 // n get_string() calls w/o buffer overrun
1099 // initialization, setup/teardown functions
1101 // If a platform specifies its own PID file name, we use that
1103 #define PID_FILE "/var/run/mDNSResponder.pid"
1106 // ***************************************************************************
1107 #if COMPILER_LIKES_PRAGMA_MARK
1109 #pragma mark - General Utility Functions
1112 mDNSlocal
void FatalError(char *errmsg
)
1114 LogMsg("%s: %s", errmsg
, dnssd_strerror(dnssd_errno
));
1115 *(long*)0 = 0; // On OS X abort() doesn't generate a crash log, but writing to zero does
1116 abort(); // On platforms where writing to zero doesn't generate an exception, abort instead
1119 mDNSlocal mDNSu32
dnssd_htonl(mDNSu32 l
)
1122 char *data
= (char*) &ret
;
1123 put_uint32(l
, &data
);
1127 // hack to search-replace perror's to LogMsg's
1128 mDNSlocal
void my_perror(char *errmsg
)
1130 LogMsg("%s: %d (%s)", errmsg
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
1133 mDNSlocal
void abort_request(request_state
*req
)
1135 if (req
->terminate
== (req_termination_fn
)~0)
1136 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with req->terminate %p", req
, req
->terminate
); return; }
1138 // First stop whatever mDNSCore operation we were doing
1139 if (req
->terminate
) req
->terminate(req
);
1141 if (!dnssd_SocketValid(req
->sd
))
1142 { LogMsg("abort_request: ERROR: Attempt to abort operation %p with invalid fd %d", req
, req
->sd
); return; }
1144 // Now, if this request_state is not subordinate to some other primary, close file descriptor and discard replies
1147 if (req
->errsd
!= req
->sd
) LogOperation("%3d: Removing FD and closing errsd %d", req
->sd
, req
->errsd
);
1148 else LogOperation("%3d: Removing FD", req
->sd
);
1149 udsSupportRemoveFDFromEventLoop(req
->sd
); // Note: This also closes file descriptor req->sd for us
1150 if (req
->errsd
!= req
->sd
) { dnssd_close(req
->errsd
); req
->errsd
= req
->sd
; }
1152 while (req
->replies
) // free pending replies
1154 reply_state
*ptr
= req
->replies
;
1155 req
->replies
= req
->replies
->next
;
1156 freeL("reply_state (abort)", ptr
);
1160 // Set req->sd to something invalid, so that udsserver_idle knows to unlink and free this structure
1161 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
1162 // Don't use dnssd_InvalidSocket (-1) because that's the sentinel value MACOSX_MDNS_MALLOC_DEBUGGING uses
1163 // for detecting when the memory for an object is inadvertently freed while the object is still on some list
1164 req
->sd
= req
->errsd
= -2;
1166 req
->sd
= req
->errsd
= dnssd_InvalidSocket
;
1168 // We also set req->terminate to a bogus value so we know if abort_request() gets called again for this request
1169 req
->terminate
= (req_termination_fn
)~0;
1172 mDNSlocal
void AbortUnlinkAndFree(request_state
*req
)
1174 request_state
**p
= &all_requests
;
1176 while (*p
&& *p
!= req
) p
=&(*p
)->next
;
1177 if (*p
) { *p
= req
->next
; freeL("request_state/AbortUnlinkAndFree", req
); }
1178 else LogMsg("AbortUnlinkAndFree: ERROR: Attempt to abort operation %p not in list", req
);
1181 mDNSlocal reply_state
*create_reply(const reply_op_t op
, const size_t datalen
, request_state
*const request
)
1185 if ((unsigned)datalen
< sizeof(reply_hdr
))
1187 LogMsg("ERROR: create_reply - data length less than length of required fields");
1191 reply
= mallocL("reply_state", sizeof(reply_state
) + datalen
- sizeof(reply_hdr
));
1192 if (!reply
) FatalError("ERROR: malloc");
1194 reply
->next
= mDNSNULL
;
1195 reply
->totallen
= datalen
+ sizeof(ipc_msg_hdr
);
1198 reply
->mhdr
->version
= VERSION
;
1199 reply
->mhdr
->datalen
= datalen
;
1200 reply
->mhdr
->ipc_flags
= 0;
1201 reply
->mhdr
->op
= op
;
1202 reply
->mhdr
->client_context
= request
->hdr
.client_context
;
1203 reply
->mhdr
->reg_index
= 0;
1208 // Append a reply to the list in a request object
1209 // If our request is sharing a connection, then we append our reply_state onto the primary's list
1210 mDNSlocal
void append_reply(request_state
*req
, reply_state
*rep
)
1212 request_state
*r
= req
->primary
? req
->primary
: req
;
1213 reply_state
**ptr
= &r
->replies
;
1214 while (*ptr
) ptr
= &(*ptr
)->next
;
1219 // Generates a response message giving name, type, domain, plus interface index,
1220 // suitable for a browse result or service registration result.
1221 // On successful completion rep is set to point to a malloc'd reply_state struct
1222 mDNSlocal mStatus
GenerateNTDResponse(const domainname
*const servicename
, const mDNSInterfaceID id
,
1223 request_state
*const request
, reply_state
**const rep
, reply_op_t op
, DNSServiceFlags flags
, mStatus err
)
1226 domainname type
, dom
;
1228 if (!DeconstructServiceName(servicename
, &name
, &type
, &dom
))
1229 return kDNSServiceErr_Invalid
;
1232 char namestr
[MAX_DOMAIN_LABEL
+1];
1233 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
1234 char domstr
[MAX_ESCAPED_DOMAIN_NAME
];
1238 ConvertDomainLabelToCString_unescaped(&name
, namestr
);
1239 ConvertDomainNameToCString(&type
, typestr
);
1240 ConvertDomainNameToCString(&dom
, domstr
);
1242 // Calculate reply data length
1243 len
= sizeof(DNSServiceFlags
);
1244 len
+= sizeof(mDNSu32
); // if index
1245 len
+= sizeof(DNSServiceErrorType
);
1246 len
+= (int) (strlen(namestr
) + 1);
1247 len
+= (int) (strlen(typestr
) + 1);
1248 len
+= (int) (strlen(domstr
) + 1);
1250 // Build reply header
1251 *rep
= create_reply(op
, len
, request
);
1252 (*rep
)->rhdr
->flags
= dnssd_htonl(flags
);
1253 (*rep
)->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, id
));
1254 (*rep
)->rhdr
->error
= dnssd_htonl(err
);
1257 data
= (char *)&(*rep
)->rhdr
[1];
1258 put_string(namestr
, &data
);
1259 put_string(typestr
, &data
);
1260 put_string(domstr
, &data
);
1262 return mStatus_NoError
;
1266 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
1267 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
1268 mDNSlocal
void GenerateBonjourBrowserResponse(const domainname
*const servicename
, const mDNSInterfaceID id
,
1269 request_state
*const request
, reply_state
**const rep
, reply_op_t op
, DNSServiceFlags flags
, mStatus err
)
1271 char namestr
[MAX_DOMAIN_LABEL
+1];
1272 char typestr
[MAX_ESCAPED_DOMAIN_NAME
];
1273 static const char domstr
[] = ".";
1279 // 1. Put first label in namestr
1280 ConvertDomainLabelToCString_unescaped((const domainlabel
*)servicename
, namestr
);
1282 // 2. Put second label and "local" into typestr
1283 mDNS_snprintf(typestr
, sizeof(typestr
), "%#s.local.", SecondLabel(servicename
));
1285 // Calculate reply data length
1286 len
= sizeof(DNSServiceFlags
);
1287 len
+= sizeof(mDNSu32
); // if index
1288 len
+= sizeof(DNSServiceErrorType
);
1289 len
+= (int) (strlen(namestr
) + 1);
1290 len
+= (int) (strlen(typestr
) + 1);
1291 len
+= (int) (strlen(domstr
) + 1);
1293 // Build reply header
1294 *rep
= create_reply(op
, len
, request
);
1295 (*rep
)->rhdr
->flags
= dnssd_htonl(flags
);
1296 (*rep
)->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, id
));
1297 (*rep
)->rhdr
->error
= dnssd_htonl(err
);
1300 data
= (char *)&(*rep
)->rhdr
[1];
1301 put_string(namestr
, &data
);
1302 put_string(typestr
, &data
);
1303 put_string(domstr
, &data
);
1306 // Returns a resource record (allocated w/ malloc) containing the data found in an IPC message
1307 // Data must be in the following format: flags, interfaceIndex, name, rrtype, rrclass, rdlen, rdata, (optional) ttl
1308 // (ttl only extracted/set if ttl argument is non-zero). Returns NULL for a bad-parameter error
1309 mDNSlocal AuthRecord
*read_rr_from_ipc_msg(request_state
*request
, int GetTTL
, int validate_flags
)
1311 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
1312 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
1314 int str_err
= get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
));
1315 mDNSu16 type
= get_uint16(&request
->msgptr
, request
->msgend
);
1316 mDNSu16
class = get_uint16(&request
->msgptr
, request
->msgend
);
1317 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1318 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1319 mDNSu32 ttl
= GetTTL
? get_uint32(&request
->msgptr
, request
->msgend
) : 0;
1320 int storage_size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1323 if (str_err
) { LogMsg("ERROR: read_rr_from_ipc_msg - get_string"); return NULL
; }
1325 if (!request
->msgptr
) { LogMsg("Error reading Resource Record from client"); return NULL
; }
1327 if (validate_flags
&&
1328 !((flags
& kDNSServiceFlagsShared
) == kDNSServiceFlagsShared
) &&
1329 !((flags
& kDNSServiceFlagsUnique
) == kDNSServiceFlagsUnique
))
1331 LogMsg("ERROR: Bad resource record flags (must be kDNSServiceFlagsShared or kDNSServiceFlagsUnique)");
1335 rr
= mallocL("AuthRecord/read_rr_from_ipc_msg", sizeof(AuthRecord
) - sizeof(RDataBody
) + storage_size
);
1336 if (!rr
) FatalError("ERROR: malloc");
1337 mDNS_SetupResourceRecord(rr
, mDNSNULL
, mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
),
1338 type
, 0, (mDNSu8
) ((flags
& kDNSServiceFlagsShared
) ? kDNSRecordTypeShared
: kDNSRecordTypeUnique
), mDNSNULL
, mDNSNULL
);
1340 if (!MakeDomainNameFromDNSNameString(&rr
->namestorage
, name
))
1342 LogMsg("ERROR: bad name: %s", name
);
1343 freeL("AuthRecord/read_rr_from_ipc_msg", rr
);
1347 if (flags
& kDNSServiceFlagsAllowRemoteQuery
) rr
->AllowRemoteQuery
= mDNStrue
;
1348 rr
->resrec
.rrclass
= class;
1349 rr
->resrec
.rdlength
= rdlen
;
1350 rr
->resrec
.rdata
->MaxRDLength
= rdlen
;
1351 mDNSPlatformMemCopy(rr
->resrec
.rdata
->u
.data
, rdata
, rdlen
);
1352 if (GetTTL
) rr
->resrec
.rroriginalttl
= ttl
;
1353 rr
->resrec
.namehash
= DomainNameHashValue(rr
->resrec
.name
);
1354 SetNewRData(&rr
->resrec
, mDNSNULL
, 0); // Sets rr->rdatahash for us
1358 mDNSlocal
int build_domainname_from_strings(domainname
*srv
, char *name
, char *regtype
, char *domain
)
1363 if (!MakeDomainLabelFromLiteralString(&n
, name
)) return -1;
1364 if (!MakeDomainNameFromDNSNameString(&t
, regtype
)) return -1;
1365 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return -1;
1366 if (!ConstructServiceName(srv
, &n
, &t
, &d
)) return -1;
1370 mDNSlocal
void send_all(dnssd_sock_t s
, const char *ptr
, int len
)
1372 int n
= send(s
, ptr
, len
, 0);
1373 // On a freshly-created Unix Domain Socket, the kernel should *never* fail to buffer a small write for us
1374 // (four bytes for a typical error code return, 12 bytes for DNSServiceGetProperty(DaemonVersion)).
1375 // If it does fail, we don't attempt to handle this failure, but we do log it so we know something is wrong.
1377 LogMsg("ERROR: send_all(%d) wrote %d of %d errno %d (%s)",
1378 s
, n
, len
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
1382 mDNSlocal mDNSBool
AuthorizedDomain(const request_state
* const request
, const domainname
* const d
, const DNameListElem
* const doms
)
1384 const DNameListElem
*delem
= mDNSNULL
;
1385 int bestDelta
= -1; // the delta of the best match, lower is better
1387 mDNSBool allow
= mDNSfalse
;
1389 if (SystemUID(request
->uid
)) return mDNStrue
;
1391 dLabels
= CountLabels(d
);
1392 for (delem
= doms
; delem
; delem
= delem
->next
)
1396 int delemLabels
= CountLabels(&delem
->name
);
1397 int delta
= dLabels
- delemLabels
;
1398 if ((bestDelta
== -1 || delta
<= bestDelta
) && SameDomainName(&delem
->name
, SkipLeadingLabels(d
, delta
)))
1401 allow
= (allow
|| (delem
->uid
== request
->uid
));
1406 return bestDelta
== -1 ? mDNStrue
: allow
;
1410 // ***************************************************************************
1411 #if COMPILER_LIKES_PRAGMA_MARK
1413 #pragma mark - DNSServiceRegister
1416 mDNSexport
void FreeExtraRR(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
1418 ExtraResourceRecord
*extra
= (ExtraResourceRecord
*)rr
->RecordContext
;
1421 if (result
!= mStatus_MemFree
) { LogMsg("Error: FreeExtraRR invoked with unexpected error %d", result
); return; }
1423 LogInfo(" FreeExtraRR %s", RRDisplayString(m
, &rr
->resrec
));
1425 if (rr
->resrec
.rdata
!= &rr
->rdatastorage
)
1426 freeL("Extra RData", rr
->resrec
.rdata
);
1427 freeL("ExtraResourceRecord/FreeExtraRR", extra
);
1430 mDNSlocal
void unlink_and_free_service_instance(service_instance
*srv
)
1432 ExtraResourceRecord
*e
= srv
->srs
.Extras
, *tmp
;
1434 // clear pointers from parent struct
1437 service_instance
**p
= &srv
->request
->u
.servicereg
.instances
;
1440 if (*p
== srv
) { *p
= (*p
)->next
; break; }
1447 e
->r
.RecordContext
= e
;
1450 FreeExtraRR(&mDNSStorage
, &tmp
->r
, mStatus_MemFree
);
1453 if (srv
->srs
.RR_TXT
.resrec
.rdata
!= &srv
->srs
.RR_TXT
.rdatastorage
)
1454 freeL("TXT RData", srv
->srs
.RR_TXT
.resrec
.rdata
);
1456 if (srv
->subtypes
) { freeL("ServiceSubTypes", srv
->subtypes
); srv
->subtypes
= NULL
; }
1457 freeL("service_instance", srv
);
1460 // Count how many other service records we have locally with the same name, but different rdata.
1461 // For auto-named services, we can have at most one per machine -- if we allowed two auto-named services of
1462 // the same type on the same machine, we'd get into an infinite autoimmune-response loop of continuous renaming.
1463 mDNSexport
int CountPeerRegistrations(mDNS
*const m
, ServiceRecordSet
*const srs
)
1466 ResourceRecord
*r
= &srs
->RR_SRV
.resrec
;
1468 ServiceRecordSet
*s
;
1470 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
1471 if (rr
->resrec
.rrtype
== kDNSType_SRV
&& SameDomainName(rr
->resrec
.name
, r
->name
) && !IdenticalSameNameRecord(&rr
->resrec
, r
))
1474 for (s
= m
->ServiceRegistrations
; s
; s
= s
->uDNS_next
)
1475 if (s
->state
!= regState_Unregistered
&& SameDomainName(s
->RR_SRV
.resrec
.name
, r
->name
) && !IdenticalSameNameRecord(&s
->RR_SRV
.resrec
, r
))
1478 verbosedebugf("%d peer registrations for %##s", count
, r
->name
->c
);
1482 mDNSexport
int CountExistingRegistrations(domainname
*srv
, mDNSIPPort port
)
1486 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
1487 if (rr
->resrec
.rrtype
== kDNSType_SRV
&&
1488 mDNSSameIPPort(rr
->resrec
.rdata
->u
.srv
.port
, port
) &&
1489 SameDomainName(rr
->resrec
.name
, srv
))
1494 mDNSlocal
void SendServiceRemovalNotification(ServiceRecordSet
*const srs
)
1497 service_instance
*instance
= srs
->ServiceContext
;
1498 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, 0, mStatus_NoError
) != mStatus_NoError
)
1499 LogMsg("%3d: SendServiceRemovalNotification: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
1500 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNSfalse
; }
1503 // service registration callback performs three duties - frees memory for deregistered services,
1504 // handles name conflicts, and delivers completed registration information to the client
1505 mDNSlocal
void regservice_callback(mDNS
*const m
, ServiceRecordSet
*const srs
, mStatus result
)
1508 mDNSBool SuppressError
= mDNSfalse
;
1509 service_instance
*instance
= srs
->ServiceContext
;
1512 if (mDNS_LoggingEnabled
)
1513 fmt
= (result
== mStatus_NoError
) ? "%3d: DNSServiceRegister(%##s, %u) REGISTERED" :
1514 (result
== mStatus_MemFree
) ? "%3d: DNSServiceRegister(%##s, %u) DEREGISTERED" :
1515 (result
== mStatus_NameConflict
) ? "%3d: DNSServiceRegister(%##s, %u) NAME CONFLICT" :
1516 "%3d: DNSServiceRegister(%##s, %u) %s %d";
1518 if (!srs
) { LogMsg("regservice_callback: srs is NULL %d", result
); return; }
1519 if (!instance
) { LogMsg("regservice_callback: srs->ServiceContext is NULL %d", result
); return; }
1521 // don't send errors up to client for wide-area, empty-string registrations
1522 if (instance
->request
&&
1523 instance
->request
->u
.servicereg
.default_domain
&&
1524 !instance
->default_local
)
1525 SuppressError
= mDNStrue
;
1527 LogOperation(fmt
, instance
->request
? instance
->request
->sd
: -99,
1528 srs
->RR_SRV
.resrec
.name
->c
, mDNSVal16(srs
->RR_SRV
.resrec
.rdata
->u
.srv
.port
), SuppressError
? "suppressed error" : "CALLBACK", result
);
1530 if (!instance
->request
&& result
!= mStatus_MemFree
) { LogMsg("regservice_callback: instance->request is NULL %d", result
); return; }
1532 if (result
== mStatus_NoError
)
1534 if (instance
->request
->u
.servicereg
.allowremotequery
)
1536 ExtraResourceRecord
*e
;
1537 srs
->RR_ADV
.AllowRemoteQuery
= mDNStrue
;
1538 srs
->RR_PTR
.AllowRemoteQuery
= mDNStrue
;
1539 srs
->RR_SRV
.AllowRemoteQuery
= mDNStrue
;
1540 srs
->RR_TXT
.AllowRemoteQuery
= mDNStrue
;
1541 for (e
= instance
->srs
.Extras
; e
; e
= e
->next
) e
->r
.AllowRemoteQuery
= mDNStrue
;
1544 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
1545 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
1546 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
1548 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(m
, srs
) == 0)
1549 RecordUpdatedNiceLabel(m
, 0); // Successfully got new name, tell user immediately
1551 else if (result
== mStatus_MemFree
)
1553 if (instance
->request
&& instance
->renameonmemfree
)
1555 instance
->renameonmemfree
= 0;
1556 err
= mDNS_RenameAndReregisterService(m
, srs
, &instance
->request
->u
.servicereg
.name
);
1557 if (err
) LogMsg("ERROR: regservice_callback - RenameAndReregisterService returned %d", err
);
1558 // error should never happen - safest to log and continue
1561 unlink_and_free_service_instance(instance
);
1563 else if (result
== mStatus_NameConflict
)
1565 if (instance
->request
->u
.servicereg
.autorename
)
1567 if (instance
->request
->u
.servicereg
.autoname
&& CountPeerRegistrations(m
, srs
) == 0)
1569 // On conflict for an autoname service, rename and reregister *all* autoname services
1570 IncrementLabelSuffix(&m
->nicelabel
, mDNStrue
);
1571 mDNS_ConfigChanged(m
); // Will call back into udsserver_handle_configchange()
1573 else // On conflict for a non-autoname service, rename and reregister just that one service
1575 if (instance
->clientnotified
) SendServiceRemovalNotification(srs
);
1576 mDNS_RenameAndReregisterService(m
, srs
, mDNSNULL
);
1583 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
1584 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
1585 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
1587 unlink_and_free_service_instance(instance
);
1594 if (GenerateNTDResponse(srs
->RR_SRV
.resrec
.name
, srs
->RR_SRV
.resrec
.InterfaceID
, instance
->request
, &rep
, reg_service_reply_op
, kDNSServiceFlagsAdd
, result
) != mStatus_NoError
)
1595 LogMsg("%3d: regservice_callback: %##s is not valid DNS-SD SRV name", instance
->request
->sd
, srs
->RR_SRV
.resrec
.name
->c
);
1596 else { append_reply(instance
->request
, rep
); instance
->clientnotified
= mDNStrue
; }
1601 mDNSlocal
void regrecord_callback(mDNS
*const m
, AuthRecord
*rr
, mStatus result
)
1604 if (!rr
->RecordContext
) // parent struct already freed by termination callback
1606 if (result
== mStatus_NoError
)
1607 LogMsg("Error: regrecord_callback: successful registration of orphaned record");
1610 if (result
!= mStatus_MemFree
) LogMsg("regrecord_callback: error %d received after parent termination", result
);
1611 freeL("AuthRecord/regrecord_callback", rr
);
1616 registered_record_entry
*re
= rr
->RecordContext
;
1617 request_state
*request
= re
->request
;
1618 int len
= sizeof(DNSServiceFlags
) + sizeof(mDNSu32
) + sizeof(DNSServiceErrorType
);
1619 reply_state
*reply
= create_reply(reg_record_reply_op
, len
, request
);
1620 reply
->mhdr
->client_context
= re
->regrec_client_context
;
1621 reply
->rhdr
->flags
= dnssd_htonl(0);
1622 reply
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, rr
->resrec
.InterfaceID
));
1623 reply
->rhdr
->error
= dnssd_htonl(result
);
1625 LogOperation("%3d: DNSServiceRegisterRecord(%u) result %d", request
->sd
, request
->hdr
.reg_index
, result
);
1628 // unlink from list, free memory
1629 registered_record_entry
**ptr
= &request
->u
.reg_recs
;
1630 while (*ptr
&& (*ptr
) != re
) ptr
= &(*ptr
)->next
;
1631 if (!*ptr
) { LogMsg("regrecord_callback - record not in list!"); return; }
1632 *ptr
= (*ptr
)->next
;
1633 freeL("registered_record_entry AuthRecord regrecord_callback", re
->rr
);
1634 freeL("registered_record_entry regrecord_callback", re
);
1636 append_reply(request
, reply
);
1640 mDNSlocal
void connection_termination(request_state
*request
)
1642 request_state
**req
= &all_requests
;
1645 if ((*req
)->primary
== request
)
1647 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1648 request_state
*tmp
= *req
;
1649 if (tmp
->primary
== tmp
) LogMsg("connection_termination ERROR (*req)->primary == *req for %p %d", tmp
, tmp
->sd
);
1650 if (tmp
->replies
) LogMsg("connection_termination ERROR How can subordinate req %p %d have replies queued?", tmp
, tmp
->sd
);
1653 freeL("request_state/connection_termination", tmp
);
1656 req
= &(*req
)->next
;
1659 while (request
->u
.reg_recs
)
1661 registered_record_entry
*ptr
= request
->u
.reg_recs
;
1662 request
->u
.reg_recs
= request
->u
.reg_recs
->next
;
1663 ptr
->rr
->RecordContext
= NULL
;
1664 mDNS_Deregister(&mDNSStorage
, ptr
->rr
); // Will free ptr->rr for us
1665 freeL("registered_record_entry/connection_termination", ptr
);
1669 mDNSlocal
void handle_cancel_request(request_state
*request
)
1671 request_state
**req
= &all_requests
;
1672 LogOperation("%3d: Cancel %08X %08X", request
->sd
, request
->hdr
.client_context
.u32
[1], request
->hdr
.client_context
.u32
[0]);
1675 if ((*req
)->primary
== request
&&
1676 (*req
)->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1677 (*req
)->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1])
1679 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
1680 request_state
*tmp
= *req
;
1683 freeL("request_state/handle_cancel_request", tmp
);
1686 req
= &(*req
)->next
;
1690 mDNSlocal mStatus
handle_regrecord_request(request_state
*request
)
1692 mStatus err
= mStatus_BadParamErr
;
1693 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 1, 1);
1696 // allocate registration entry, link into list
1697 registered_record_entry
*re
= mallocL("registered_record_entry", sizeof(registered_record_entry
));
1698 if (!re
) FatalError("ERROR: malloc");
1699 re
->key
= request
->hdr
.reg_index
;
1701 re
->request
= request
;
1702 re
->regrec_client_context
= request
->hdr
.client_context
;
1703 rr
->RecordContext
= re
;
1704 rr
->RecordCallback
= regrecord_callback
;
1705 re
->next
= request
->u
.reg_recs
;
1706 request
->u
.reg_recs
= re
;
1709 if (!AuthorizedDomain(request
, rr
->resrec
.name
, AutoRegistrationDomains
)) return (mStatus_NoError
);
1711 if (rr
->resrec
.rroriginalttl
== 0)
1712 rr
->resrec
.rroriginalttl
= DefaultTTLforRRType(rr
->resrec
.rrtype
);
1714 LogOperation("%3d: DNSServiceRegisterRecord(%u %s)", request
->sd
, request
->hdr
.reg_index
, RRDisplayString(&mDNSStorage
, &rr
->resrec
));
1715 err
= mDNS_Register(&mDNSStorage
, rr
);
1720 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
);
1722 mDNSlocal
void regservice_termination_callback(request_state
*request
)
1724 if (!request
) { LogMsg("regservice_termination_callback context is NULL"); return; }
1725 while (request
->u
.servicereg
.instances
)
1727 service_instance
*p
= request
->u
.servicereg
.instances
;
1728 request
->u
.servicereg
.instances
= request
->u
.servicereg
.instances
->next
;
1729 // only safe to free memory if registration is not valid, i.e. deregister fails (which invalidates p)
1730 LogOperation("%3d: DNSServiceRegister(%##s, %u) STOP",
1731 request
->sd
, p
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(p
->srs
.RR_SRV
.resrec
.rdata
->u
.srv
.port
));
1733 // Clear backpointer *before* calling mDNS_DeregisterService/unlink_and_free_service_instance
1734 // We don't need unlink_and_free_service_instance to cut its element from the list, because we're already advancing
1735 // request->u.servicereg.instances as we work our way through the list, implicitly cutting one element at a time
1736 // We can't clear p->request *after* the calling mDNS_DeregisterService/unlink_and_free_service_instance
1737 // because by then we might have already freed p
1739 if (mDNS_DeregisterService(&mDNSStorage
, &p
->srs
)) unlink_and_free_service_instance(p
);
1740 // Don't touch service_instance *p after this -- it's likely to have been freed already
1742 if (request
->u
.servicereg
.txtdata
)
1743 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1744 if (request
->u
.servicereg
.autoname
)
1746 // Clear autoname before calling UpdateDeviceInfoRecord() so it doesn't mistakenly include this in its count of active autoname registrations
1747 request
->u
.servicereg
.autoname
= mDNSfalse
;
1748 UpdateDeviceInfoRecord(&mDNSStorage
);
1752 mDNSlocal request_state
*LocateSubordinateRequest(request_state
*request
)
1755 for (req
= all_requests
; req
; req
= req
->next
)
1756 if (req
->primary
== request
&&
1757 req
->hdr
.client_context
.u32
[0] == request
->hdr
.client_context
.u32
[0] &&
1758 req
->hdr
.client_context
.u32
[1] == request
->hdr
.client_context
.u32
[1]) return(req
);
1762 mDNSlocal mStatus
add_record_to_service(request_state
*request
, service_instance
*instance
, mDNSu16 rrtype
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
)
1764 ServiceRecordSet
*srs
= &instance
->srs
;
1766 int size
= rdlen
> sizeof(RDataBody
) ? rdlen
: sizeof(RDataBody
);
1767 ExtraResourceRecord
*extra
= mallocL("ExtraResourceRecord", sizeof(*extra
) - sizeof(RDataBody
) + size
);
1768 if (!extra
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
1770 mDNSPlatformMemZero(extra
, sizeof(ExtraResourceRecord
)); // OK if oversized rdata not zero'd
1771 extra
->r
.resrec
.rrtype
= rrtype
;
1772 extra
->r
.rdatastorage
.MaxRDLength
= (mDNSu16
) size
;
1773 extra
->r
.resrec
.rdlength
= rdlen
;
1774 mDNSPlatformMemCopy(&extra
->r
.rdatastorage
.u
.data
, rdata
, rdlen
);
1776 result
= mDNS_AddRecordToService(&mDNSStorage
, srs
, extra
, &extra
->r
.rdatastorage
, ttl
);
1777 if (result
) { freeL("ExtraResourceRecord/add_record_to_service", extra
); return result
; }
1779 extra
->ClientID
= request
->hdr
.reg_index
;
1783 mDNSlocal mStatus
handle_add_request(request_state
*request
)
1785 service_instance
*i
;
1786 mStatus result
= mStatus_UnknownErr
;
1787 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
);
1788 mDNSu16 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
1789 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1790 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1791 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1792 if (!ttl
) ttl
= DefaultTTLforRRType(rrtype
);
1793 (void)flags
; // Unused
1795 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceAddRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1797 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1798 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1800 if (request
->terminate
!= regservice_termination_callback
)
1801 { LogMsg("%3d: DNSServiceAddRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1803 LogOperation("%3d: DNSServiceAddRecord(%##s, %s, %d)", request
->sd
,
1804 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
, DNSTypeName(rrtype
), rdlen
);
1806 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1808 result
= add_record_to_service(request
, i
, rrtype
, rdlen
, rdata
, ttl
);
1809 if (result
&& i
->default_local
) break;
1810 else result
= mStatus_NoError
; // suppress non-local default errors
1816 mDNSlocal
void update_callback(mDNS
*const m
, AuthRecord
*const rr
, RData
*oldrd
)
1819 if (oldrd
!= &rr
->rdatastorage
) freeL("RData/update_callback", oldrd
);
1822 mDNSlocal mStatus
update_record(AuthRecord
*rr
, mDNSu16 rdlen
, const char *rdata
, mDNSu32 ttl
)
1828 if (rdlen
> sizeof(RDataBody
)) rdsize
= rdlen
;
1829 else rdsize
= sizeof(RDataBody
);
1830 newrd
= mallocL("RData/update_record", sizeof(RData
) - sizeof(RDataBody
) + rdsize
);
1831 if (!newrd
) FatalError("ERROR: malloc");
1832 newrd
->MaxRDLength
= (mDNSu16
) rdsize
;
1833 mDNSPlatformMemCopy(&newrd
->u
, rdata
, rdlen
);
1835 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1836 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1837 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1838 if (rr
->resrec
.rrtype
== kDNSType_TXT
&& rdlen
== 0) { rdlen
= 1; newrd
->u
.txt
.c
[0] = 0; }
1840 result
= mDNS_Update(&mDNSStorage
, rr
, ttl
, rdlen
, newrd
, update_callback
);
1841 if (result
) { LogMsg("ERROR: mDNS_Update - %d", result
); freeL("RData/update_record", newrd
); }
1845 mDNSlocal mStatus
handle_update_request(request_state
*request
)
1847 const ipc_msg_hdr
*const hdr
= &request
->hdr
;
1848 mStatus result
= mStatus_BadReferenceErr
;
1849 service_instance
*i
;
1850 AuthRecord
*rr
= NULL
;
1852 // get the message data
1853 DNSServiceFlags flags
= get_flags (&request
->msgptr
, request
->msgend
); // flags unused
1854 mDNSu16 rdlen
= get_uint16(&request
->msgptr
, request
->msgend
);
1855 const char *rdata
= get_rdata (&request
->msgptr
, request
->msgend
, rdlen
);
1856 mDNSu32 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
1857 (void)flags
; // Unused
1859 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceUpdateRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1861 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1862 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1864 if (request
->terminate
== connection_termination
)
1866 // update an individually registered record
1867 registered_record_entry
*reptr
;
1868 for (reptr
= request
->u
.reg_recs
; reptr
; reptr
= reptr
->next
)
1870 if (reptr
->key
== hdr
->reg_index
)
1872 result
= update_record(reptr
->rr
, rdlen
, rdata
, ttl
);
1876 result
= mStatus_BadReferenceErr
;
1880 if (request
->terminate
!= regservice_termination_callback
)
1881 { LogMsg("%3d: DNSServiceUpdateRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1883 // update the saved off TXT data for the service
1884 if (hdr
->reg_index
== TXT_RECORD_INDEX
)
1886 if (request
->u
.servicereg
.txtdata
)
1887 { freeL("service_info txtdata", request
->u
.servicereg
.txtdata
); request
->u
.servicereg
.txtdata
= NULL
; }
1890 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", rdlen
);
1891 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_update_request - malloc");
1892 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, rdata
, rdlen
);
1895 request
->u
.servicereg
.txtdata
= NULL
;
1898 // update a record from a service record set
1899 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1901 if (hdr
->reg_index
== TXT_RECORD_INDEX
) rr
= &i
->srs
.RR_TXT
;
1904 ExtraResourceRecord
*e
;
1905 for (e
= i
->srs
.Extras
; e
; e
= e
->next
)
1906 if (e
->ClientID
== hdr
->reg_index
) { rr
= &e
->r
; break; }
1909 if (!rr
) { result
= mStatus_BadReferenceErr
; goto end
; }
1910 result
= update_record(rr
, rdlen
, rdata
, ttl
);
1911 if (result
&& i
->default_local
) goto end
;
1912 else result
= mStatus_NoError
; // suppress non-local default errors
1916 if (request
->terminate
== regservice_termination_callback
)
1917 LogOperation("%3d: DNSServiceUpdateRecord(%##s, %s)", request
->sd
,
1918 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1919 rr
? DNSTypeName(rr
->resrec
.rrtype
) : "<NONE>");
1924 // remove a resource record registered via DNSServiceRegisterRecord()
1925 mDNSlocal mStatus
remove_record(request_state
*request
)
1927 mStatus err
= mStatus_UnknownErr
;
1928 registered_record_entry
*e
, **ptr
= &request
->u
.reg_recs
;
1930 while (*ptr
&& (*ptr
)->key
!= request
->hdr
.reg_index
) ptr
= &(*ptr
)->next
;
1931 if (!*ptr
) { LogMsg("%3d: DNSServiceRemoveRecord(%u) not found", request
->sd
, request
->hdr
.reg_index
); return mStatus_BadReferenceErr
; }
1933 *ptr
= e
->next
; // unlink
1935 LogOperation("%3d: DNSServiceRemoveRecord(%u %s)", request
->sd
, request
->hdr
.reg_index
, RRDisplayString(&mDNSStorage
, &e
->rr
->resrec
));
1936 e
->rr
->RecordContext
= NULL
;
1937 err
= mDNS_Deregister(&mDNSStorage
, e
->rr
);
1940 LogMsg("ERROR: remove_record, mDNS_Deregister: %d", err
);
1941 freeL("registered_record_entry AuthRecord remove_record", e
->rr
);
1943 freeL("registered_record_entry remove_record", e
);
1947 mDNSlocal mStatus
remove_extra(const request_state
*const request
, service_instance
*const serv
, mDNSu16
*const rrtype
)
1949 mStatus err
= mStatus_BadReferenceErr
;
1950 ExtraResourceRecord
*ptr
;
1952 for (ptr
= serv
->srs
.Extras
; ptr
; ptr
= ptr
->next
)
1954 if (ptr
->ClientID
== request
->hdr
.reg_index
) // found match
1956 *rrtype
= ptr
->r
.resrec
.rrtype
;
1957 return mDNS_RemoveRecordFromService(&mDNSStorage
, &serv
->srs
, ptr
, FreeExtraRR
, ptr
);
1963 mDNSlocal mStatus
handle_removerecord_request(request_state
*request
)
1965 mStatus err
= mStatus_BadReferenceErr
;
1966 get_flags(&request
->msgptr
, request
->msgend
); // flags unused
1968 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRemoveRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
1970 // If this is a shared connection, check if the operation actually applies to a subordinate request_state object
1971 if (request
->terminate
== connection_termination
) request
= LocateSubordinateRequest(request
);
1973 if (request
->terminate
== connection_termination
)
1974 err
= remove_record(request
); // remove individually registered record
1975 else if (request
->terminate
!= regservice_termination_callback
)
1976 { LogMsg("%3d: DNSServiceRemoveRecord(not a registered service ref)", request
->sd
); return(mStatus_BadParamErr
); }
1979 service_instance
*i
;
1981 LogOperation("%3d: DNSServiceRemoveRecord(%##s, %s)", request
->sd
,
1982 (request
->u
.servicereg
.instances
) ? request
->u
.servicereg
.instances
->srs
.RR_SRV
.resrec
.name
->c
: NULL
,
1983 rrtype
? DNSTypeName(rrtype
) : "<NONE>");
1984 for (i
= request
->u
.servicereg
.instances
; i
; i
= i
->next
)
1986 err
= remove_extra(request
, i
, &rrtype
);
1987 if (err
&& i
->default_local
) break;
1988 else err
= mStatus_NoError
; // suppress non-local default errors
1995 // If there's a comma followed by another character,
1996 // FindFirstSubType overwrites the comma with a nul and returns the pointer to the next character.
1997 // Otherwise, it returns a pointer to the final nul at the end of the string
1998 mDNSlocal
char *FindFirstSubType(char *p
)
2002 if (p
[0] == '\\' && p
[1]) p
+= 2;
2003 else if (p
[0] == ',' && p
[1]) { *p
++ = 0; return(p
); }
2009 // If there's a comma followed by another character,
2010 // FindNextSubType overwrites the comma with a nul and returns the pointer to the next character.
2011 // If it finds an illegal unescaped dot in the subtype name, it returns mDNSNULL
2012 // Otherwise, it returns a pointer to the final nul at the end of the string
2013 mDNSlocal
char *FindNextSubType(char *p
)
2017 if (p
[0] == '\\' && p
[1]) // If escape character
2018 p
+= 2; // ignore following character
2019 else if (p
[0] == ',') // If we found a comma
2024 else if (p
[0] == '.')
2031 // Returns -1 if illegal subtype found
2032 mDNSexport mDNSs32
ChopSubTypes(char *regtype
)
2034 mDNSs32 NumSubTypes
= 0;
2035 char *stp
= FindFirstSubType(regtype
);
2036 while (stp
&& *stp
) // If we found a comma...
2038 if (*stp
== ',') return(-1);
2040 stp
= FindNextSubType(stp
);
2042 if (!stp
) return(-1);
2043 return(NumSubTypes
);
2046 mDNSexport AuthRecord
*AllocateSubTypes(mDNSs32 NumSubTypes
, char *p
)
2048 AuthRecord
*st
= mDNSNULL
;
2052 st
= mallocL("ServiceSubTypes", NumSubTypes
* sizeof(AuthRecord
));
2053 if (!st
) return(mDNSNULL
);
2054 for (i
= 0; i
< NumSubTypes
; i
++)
2056 mDNS_SetupResourceRecord(&st
[i
], mDNSNULL
, mDNSInterface_Any
, kDNSQType_ANY
, kStandardTTL
, 0, mDNSNULL
, mDNSNULL
);
2059 if (!MakeDomainNameFromDNSNameString(&st
[i
].namestorage
, p
))
2060 { freeL("ServiceSubTypes", st
); return(mDNSNULL
); }
2066 mDNSlocal mStatus
register_service_instance(request_state
*request
, const domainname
*domain
)
2068 service_instance
**ptr
, *instance
;
2072 for (ptr
= &request
->u
.servicereg
.instances
; *ptr
; ptr
= &(*ptr
)->next
)
2074 if (SameDomainName(&(*ptr
)->domain
, domain
))
2076 LogMsg("register_service_instance: domain %##s already registered for %#s.%##s",
2077 domain
->c
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
);
2078 return mStatus_AlreadyRegistered
;
2082 // Special-case hack: We don't advertise SMB service in AutoTunnel domains, because AutoTunnel
2083 // services have to support IPv6, and our SMB server does not
2084 // <rdar://problem/5482322> BTMM: Don't advertise SMB with BTMM because it doesn't support IPv6
2085 if (SameDomainName(&request
->u
.servicereg
.type
, (const domainname
*) "\x4" "_smb" "\x4" "_tcp"))
2087 DomainAuthInfo
*AuthInfo
= GetAuthInfoForName(&mDNSStorage
, domain
);
2088 if (AuthInfo
&& AuthInfo
->AutoTunnel
) return(kDNSServiceErr_Unsupported
);
2091 instance_size
= sizeof(*instance
);
2092 if (request
->u
.servicereg
.txtlen
> sizeof(RDataBody
)) instance_size
+= (request
->u
.servicereg
.txtlen
- sizeof(RDataBody
));
2093 instance
= mallocL("service_instance", instance_size
);
2094 if (!instance
) { my_perror("ERROR: malloc"); return mStatus_NoMemoryErr
; }
2096 instance
->next
= mDNSNULL
;
2097 instance
->request
= request
;
2098 instance
->subtypes
= AllocateSubTypes(request
->u
.servicereg
.num_subtypes
, request
->u
.servicereg
.type_as_string
);
2099 instance
->renameonmemfree
= 0;
2100 instance
->clientnotified
= mDNSfalse
;
2101 instance
->default_local
= (request
->u
.servicereg
.default_domain
&& SameDomainName(domain
, &localdomain
));
2102 AssignDomainName(&instance
->domain
, domain
);
2104 if (request
->u
.servicereg
.num_subtypes
&& !instance
->subtypes
)
2105 { unlink_and_free_service_instance(instance
); instance
= NULL
; FatalError("ERROR: malloc"); }
2107 result
= mDNS_RegisterService(&mDNSStorage
, &instance
->srs
,
2108 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
,
2109 request
->u
.servicereg
.host
.c
[0] ? &request
->u
.servicereg
.host
: NULL
,
2110 request
->u
.servicereg
.port
,
2111 request
->u
.servicereg
.txtdata
, request
->u
.servicereg
.txtlen
,
2112 instance
->subtypes
, request
->u
.servicereg
.num_subtypes
,
2113 request
->u
.servicereg
.InterfaceID
, regservice_callback
, instance
);
2117 *ptr
= instance
; // Append this to the end of our request->u.servicereg.instances list
2118 LogOperation("%3d: DNSServiceRegister(%##s, %u) ADDED",
2119 instance
->request
->sd
, instance
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(request
->u
.servicereg
.port
));
2123 LogMsg("register_service_instance %#s.%##s%##s error %d",
2124 &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, domain
->c
, result
);
2125 unlink_and_free_service_instance(instance
);
2131 mDNSlocal
void udsserver_default_reg_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
2133 request_state
*request
;
2135 #if APPLE_OSX_mDNSResponder
2136 machserver_automatic_registration_domain_changed(&d
->name
, add
);
2137 #endif // APPLE_OSX_mDNSResponder
2139 LogMsg("%s registration domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
2140 for (request
= all_requests
; request
; request
= request
->next
)
2142 if (request
->terminate
!= regservice_termination_callback
) continue;
2143 if (!request
->u
.servicereg
.default_domain
) continue;
2144 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
2146 service_instance
**ptr
= &request
->u
.servicereg
.instances
;
2147 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
2150 // If we don't already have this domain in our list for this registration, add it now
2151 if (!*ptr
) register_service_instance(request
, &d
->name
);
2152 else debugf("udsserver_default_reg_domain_changed %##s already in list, not re-adding", &d
->name
);
2156 // Normally we should not fail to find the specified instance
2157 // One case where this can happen is if a uDNS update fails for some reason,
2158 // and regservice_callback then calls unlink_and_free_service_instance and disposes of that instance.
2160 LogMsg("udsserver_default_reg_domain_changed domain %##s not found for service %#s type %s",
2161 &d
->name
, request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type_as_string
);
2165 for (p
= AutoRegistrationDomains
; p
; p
=p
->next
)
2166 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
2167 if (SameDomainName(&d
->name
, &p
->name
)) break;
2168 if (p
) debugf("udsserver_default_reg_domain_changed %##s still in list, not removing", &d
->name
);
2172 service_instance
*si
= *ptr
;
2174 if (si
->clientnotified
) SendServiceRemovalNotification(&si
->srs
); // Do this *before* clearing si->request backpointer
2175 // Now that we've cut this service_instance from the list, we MUST clear the si->request backpointer.
2176 // Otherwise what can happen is this: While our mDNS_DeregisterService is in the
2177 // process of completing asynchronously, the client cancels the entire operation, so
2178 // regservice_termination_callback then runs through the whole list deregistering each
2179 // instance, clearing the backpointers, and then disposing the parent request_state object.
2180 // However, because this service_instance isn't in the list any more, regservice_termination_callback
2181 // has no way to find it and clear its backpointer, and then when our mDNS_DeregisterService finally
2182 // completes later with a mStatus_MemFree message, it calls unlink_and_free_service_instance() with
2183 // a service_instance with a stale si->request backpointer pointing to memory that's already been freed.
2185 err
= mDNS_DeregisterService(&mDNSStorage
, &si
->srs
);
2186 if (err
) { LogMsg("udsserver_default_reg_domain_changed err %d", err
); unlink_and_free_service_instance(si
); }
2194 mDNSlocal mStatus
handle_regservice_request(request_state
*request
)
2196 char name
[256]; // Lots of spare space for extra-long names that we'll auto-truncate down to 63 bytes
2197 char domain
[MAX_ESCAPED_DOMAIN_NAME
], host
[MAX_ESCAPED_DOMAIN_NAME
];
2198 char type_as_string
[MAX_ESCAPED_DOMAIN_NAME
];
2202 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2203 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2204 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2205 if (interfaceIndex
&& !InterfaceID
)
2206 { LogMsg("ERROR: handle_regservice_request - Couldn't find interfaceIndex %d", interfaceIndex
); return(mStatus_BadParamErr
); }
2208 if (get_string(&request
->msgptr
, request
->msgend
, name
, sizeof(name
)) < 0 ||
2209 get_string(&request
->msgptr
, request
->msgend
, type_as_string
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2210 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2211 get_string(&request
->msgptr
, request
->msgend
, host
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
2212 { LogMsg("ERROR: handle_regservice_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
2214 request
->u
.servicereg
.InterfaceID
= InterfaceID
;
2215 request
->u
.servicereg
.instances
= NULL
;
2216 request
->u
.servicereg
.txtlen
= 0;
2217 request
->u
.servicereg
.txtdata
= NULL
;
2218 mDNSPlatformStrCopy(request
->u
.servicereg
.type_as_string
, type_as_string
);
2220 if (request
->msgptr
+ 2 > request
->msgend
) request
->msgptr
= NULL
;
2223 request
->u
.servicereg
.port
.b
[0] = *request
->msgptr
++;
2224 request
->u
.servicereg
.port
.b
[1] = *request
->msgptr
++;
2227 request
->u
.servicereg
.txtlen
= get_uint16(&request
->msgptr
, request
->msgend
);
2228 if (request
->u
.servicereg
.txtlen
)
2230 request
->u
.servicereg
.txtdata
= mallocL("service_info txtdata", request
->u
.servicereg
.txtlen
);
2231 if (!request
->u
.servicereg
.txtdata
) FatalError("ERROR: handle_regservice_request - malloc");
2232 mDNSPlatformMemCopy(request
->u
.servicereg
.txtdata
, get_rdata(&request
->msgptr
, request
->msgend
, request
->u
.servicereg
.txtlen
), request
->u
.servicereg
.txtlen
);
2234 else request
->u
.servicereg
.txtdata
= NULL
;
2236 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceRegister(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2238 // Check for sub-types after the service type
2239 request
->u
.servicereg
.num_subtypes
= ChopSubTypes(request
->u
.servicereg
.type_as_string
); // Note: Modifies regtype string to remove trailing subtypes
2240 if (request
->u
.servicereg
.num_subtypes
< 0)
2241 { LogMsg("ERROR: handle_regservice_request - ChopSubTypes failed %s", request
->u
.servicereg
.type_as_string
); return(mStatus_BadParamErr
); }
2243 // Don't try to construct "domainname t" until *after* ChopSubTypes has worked its magic
2244 if (!*request
->u
.servicereg
.type_as_string
|| !MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.type
, request
->u
.servicereg
.type_as_string
))
2245 { LogMsg("ERROR: handle_regservice_request - type_as_string bad %s", request
->u
.servicereg
.type_as_string
); return(mStatus_BadParamErr
); }
2249 request
->u
.servicereg
.name
= mDNSStorage
.nicelabel
;
2250 request
->u
.servicereg
.autoname
= mDNStrue
;
2254 // If the client is allowing AutoRename, then truncate name to legal length before converting it to a DomainLabel
2255 if ((flags
& kDNSServiceFlagsNoAutoRename
) == 0)
2257 int newlen
= TruncateUTF8ToLength((mDNSu8
*)name
, mDNSPlatformStrLen(name
), MAX_DOMAIN_LABEL
);
2260 if (!MakeDomainLabelFromLiteralString(&request
->u
.servicereg
.name
, name
))
2261 { LogMsg("ERROR: handle_regservice_request - name bad %s", name
); return(mStatus_BadParamErr
); }
2262 request
->u
.servicereg
.autoname
= mDNSfalse
;
2267 request
->u
.servicereg
.default_domain
= mDNSfalse
;
2268 if (!MakeDomainNameFromDNSNameString(&d
, domain
))
2269 { LogMsg("ERROR: handle_regservice_request - domain bad %s", domain
); return(mStatus_BadParamErr
); }
2273 request
->u
.servicereg
.default_domain
= mDNStrue
;
2274 MakeDomainNameFromDNSNameString(&d
, "local.");
2277 if (!ConstructServiceName(&srv
, &request
->u
.servicereg
.name
, &request
->u
.servicereg
.type
, &d
))
2279 LogMsg("ERROR: handle_regservice_request - Couldn't ConstructServiceName from, “%#s” “%##s” “%##s”",
2280 request
->u
.servicereg
.name
.c
, request
->u
.servicereg
.type
.c
, d
.c
); return(mStatus_BadParamErr
);
2283 if (!MakeDomainNameFromDNSNameString(&request
->u
.servicereg
.host
, host
))
2284 { LogMsg("ERROR: handle_regservice_request - host bad %s", host
); return(mStatus_BadParamErr
); }
2285 request
->u
.servicereg
.autorename
= (flags
& kDNSServiceFlagsNoAutoRename
) == 0;
2286 request
->u
.servicereg
.allowremotequery
= (flags
& kDNSServiceFlagsAllowRemoteQuery
) != 0;
2288 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
2289 // a port number of zero. When two instances of the protected client are allowed to run on one
2290 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
2291 if (!mDNSIPPortIsZero(request
->u
.servicereg
.port
))
2293 int count
= CountExistingRegistrations(&srv
, request
->u
.servicereg
.port
);
2295 LogMsg("Client application registered %d identical instances of service %##s port %u.",
2296 count
+1, srv
.c
, mDNSVal16(request
->u
.servicereg
.port
));
2299 LogOperation("%3d: DNSServiceRegister(\"%s\", \"%s\", \"%s\", \"%s\", %u) START",
2300 request
->sd
, name
, request
->u
.servicereg
.type_as_string
, domain
, host
, mDNSVal16(request
->u
.servicereg
.port
));
2302 // We need to unconditionally set request->terminate, because even if we didn't successfully
2303 // start any registrations right now, subsequent configuration changes may cause successful
2304 // registrations to be added, and we'll need to cancel them before freeing this memory.
2305 // We also need to set request->terminate first, before adding additional service instances,
2306 // because the uds_validatelists uses the request->terminate function pointer to determine
2307 // what kind of request this is, and therefore what kind of list validation is required.
2308 request
->terminate
= regservice_termination_callback
;
2310 err
= register_service_instance(request
, &d
);
2313 err
= AuthorizedDomain(request
, &d
, AutoRegistrationDomains
) ? register_service_instance(request
, &d
) : mStatus_NoError
;
2317 if (request
->u
.servicereg
.autoname
) UpdateDeviceInfoRecord(&mDNSStorage
);
2322 // Note that we don't report errors for non-local, non-explicit domains
2323 for (ptr
= AutoRegistrationDomains
; ptr
; ptr
= ptr
->next
)
2324 if (!ptr
->uid
|| SystemUID(request
->uid
) || request
->uid
== ptr
->uid
)
2325 register_service_instance(request
, &ptr
->name
);
2332 // ***************************************************************************
2333 #if COMPILER_LIKES_PRAGMA_MARK
2335 #pragma mark - DNSServiceBrowse
2338 mDNSlocal
void FoundInstance(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2340 const DNSServiceFlags flags
= AddRecord
? kDNSServiceFlagsAdd
: 0;
2341 request_state
*req
= question
->QuestionContext
;
2345 if (answer
->rrtype
!= kDNSType_PTR
)
2346 { LogMsg("%3d: FoundInstance: Should not be called with rrtype %d (not a PTR record)", req
->sd
, answer
->rrtype
); return; }
2348 if (GenerateNTDResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
) != mStatus_NoError
)
2350 if (SameDomainName(&req
->u
.browser
.regtype
, (const domainname
*)"\x09_services\x07_dns-sd\x04_udp"))
2352 // Special support to enable the DNSServiceBrowse call made by Bonjour Browser
2353 // Remove after Bonjour Browser is updated to use DNSServiceQueryRecord instead of DNSServiceBrowse
2354 GenerateBonjourBrowserResponse(&answer
->rdata
->u
.name
, answer
->InterfaceID
, req
, &rep
, browse_reply_op
, flags
, mStatus_NoError
);
2355 goto bonjourbrowserhack
;
2358 LogMsg("%3d: FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
2359 req
->sd
, answer
->name
->c
, answer
->rdata
->u
.name
.c
);
2365 LogOperation("%3d: DNSServiceBrowse(%##s, %s) RESULT %s %d: %s",
2366 req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), AddRecord
? "Add" : "Rmv",
2367 mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
), RRDisplayString(m
, answer
));
2369 append_reply(req
, rep
);
2372 mDNSlocal mStatus
add_domain_to_browser(request_state
*info
, const domainname
*d
)
2377 for (p
= info
->u
.browser
.browsers
; p
; p
= p
->next
)
2379 if (SameDomainName(&p
->domain
, d
))
2380 { debugf("add_domain_to_browser %##s already in list", d
->c
); return mStatus_AlreadyRegistered
; }
2383 b
= mallocL("browser_t", sizeof(*b
));
2384 if (!b
) return mStatus_NoMemoryErr
;
2385 AssignDomainName(&b
->domain
, d
);
2386 err
= mDNS_StartBrowse(&mDNSStorage
, &b
->q
,
2387 &info
->u
.browser
.regtype
, d
, info
->u
.browser
.interface_id
, info
->u
.browser
.ForceMCast
, FoundInstance
, info
);
2390 LogMsg("mDNS_StartBrowse returned %d for type %##s domain %##s", err
, info
->u
.browser
.regtype
.c
, d
->c
);
2391 freeL("browser_t/add_domain_to_browser", b
);
2395 b
->next
= info
->u
.browser
.browsers
;
2396 info
->u
.browser
.browsers
= b
;
2397 LogOperation("%3d: DNSServiceBrowse(%##s) START", info
->sd
, b
->q
.qname
.c
);
2402 mDNSlocal
void browse_termination_callback(request_state
*info
)
2404 while (info
->u
.browser
.browsers
)
2406 browser_t
*ptr
= info
->u
.browser
.browsers
;
2407 info
->u
.browser
.browsers
= ptr
->next
;
2408 LogOperation("%3d: DNSServiceBrowse(%##s) STOP", info
->sd
, ptr
->q
.qname
.c
);
2409 mDNS_StopBrowse(&mDNSStorage
, &ptr
->q
); // no need to error-check result
2410 freeL("browser_t/browse_termination_callback", ptr
);
2414 mDNSlocal
void udsserver_automatic_browse_domain_changed(const DNameListElem
*const d
, const mDNSBool add
)
2416 request_state
*request
;
2417 debugf("udsserver_automatic_browse_domain_changed: %s default browse domain %##s", add
? "Adding" : "Removing", d
->name
.c
);
2419 #if APPLE_OSX_mDNSResponder
2420 machserver_automatic_browse_domain_changed(&d
->name
, add
);
2421 #endif // APPLE_OSX_mDNSResponder
2423 for (request
= all_requests
; request
; request
= request
->next
)
2425 if (request
->terminate
!= browse_termination_callback
) continue; // Not a browse operation
2426 if (!request
->u
.browser
.default_domain
) continue; // Not an auto-browse operation
2427 if (!d
->uid
|| SystemUID(request
->uid
) || request
->uid
== d
->uid
)
2429 browser_t
**ptr
= &request
->u
.browser
.browsers
;
2430 while (*ptr
&& !SameDomainName(&(*ptr
)->domain
, &d
->name
)) ptr
= &(*ptr
)->next
;
2433 // If we don't already have this domain in our list for this browse operation, add it now
2434 if (!*ptr
) add_domain_to_browser(request
, &d
->name
);
2435 else debugf("udsserver_automatic_browse_domain_changed %##s already in list, not re-adding", &d
->name
);
2439 if (!*ptr
) LogMsg("udsserver_automatic_browse_domain_changed ERROR %##s not found", &d
->name
);
2443 for (p
= AutoBrowseDomains
; p
; p
=p
->next
)
2444 if (!p
->uid
|| SystemUID(request
->uid
) || request
->uid
== p
->uid
)
2445 if (SameDomainName(&d
->name
, &p
->name
)) break;
2446 if (p
) debugf("udsserver_automatic_browse_domain_changed %##s still in list, not removing", &d
->name
);
2449 browser_t
*rem
= *ptr
;
2450 *ptr
= (*ptr
)->next
;
2451 mDNS_StopQueryWithRemoves(&mDNSStorage
, &rem
->q
);
2452 freeL("browser_t/udsserver_automatic_browse_domain_changed", rem
);
2460 mDNSlocal
void FreeARElemCallback(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
2463 if (result
== mStatus_MemFree
)
2465 // On shutdown, mDNS_Close automatically deregisters all records
2466 // Since in this case no one has called DeregisterLocalOnlyDomainEnumPTR to cut the record
2467 // from the LocalDomainEnumRecords list, we do this here before we free the memory.
2468 ARListElem
**ptr
= &LocalDomainEnumRecords
;
2469 while (*ptr
&& &(*ptr
)->ar
!= rr
) ptr
= &(*ptr
)->next
;
2470 if (*ptr
) *ptr
= (*ptr
)->next
;
2471 mDNSPlatformMemFree(rr
->RecordContext
);
2475 mDNSlocal
void RegisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
2477 // allocate/register legacy and non-legacy _browse PTR record
2479 ARListElem
*ptr
= mDNSPlatformMemAllocate(sizeof(*ptr
));
2481 debugf("Incrementing %s refcount for %##s",
2482 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
2483 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
2484 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
2486 mDNS_SetupResourceRecord(&ptr
->ar
, mDNSNULL
, mDNSInterface_LocalOnly
, kDNSType_PTR
, 7200, kDNSRecordTypeShared
, FreeARElemCallback
, ptr
);
2487 MakeDomainNameFromDNSNameString(&ptr
->ar
.namestorage
, mDNS_DomainTypeNames
[type
]);
2488 AppendDNSNameString (&ptr
->ar
.namestorage
, "local");
2489 AssignDomainName(&ptr
->ar
.resrec
.rdata
->u
.name
, d
);
2490 err
= mDNS_Register(m
, &ptr
->ar
);
2493 LogMsg("SetSCPrefsBrowseDomain: mDNS_Register returned error %d", err
);
2494 mDNSPlatformMemFree(ptr
);
2498 ptr
->next
= LocalDomainEnumRecords
;
2499 LocalDomainEnumRecords
= ptr
;
2503 mDNSlocal
void DeregisterLocalOnlyDomainEnumPTR(mDNS
*m
, const domainname
*d
, int type
)
2505 ARListElem
**ptr
= &LocalDomainEnumRecords
;
2506 domainname lhs
; // left-hand side of PTR, for comparison
2508 debugf("Decrementing %s refcount for %##s",
2509 (type
== mDNS_DomainTypeBrowse
) ? "browse domain " :
2510 (type
== mDNS_DomainTypeRegistration
) ? "registration dom" :
2511 (type
== mDNS_DomainTypeBrowseAutomatic
) ? "automatic browse" : "?", d
->c
);
2513 MakeDomainNameFromDNSNameString(&lhs
, mDNS_DomainTypeNames
[type
]);
2514 AppendDNSNameString (&lhs
, "local");
2518 if (SameDomainName(&(*ptr
)->ar
.resrec
.rdata
->u
.name
, d
) && SameDomainName((*ptr
)->ar
.resrec
.name
, &lhs
))
2520 ARListElem
*rem
= *ptr
;
2521 *ptr
= (*ptr
)->next
;
2522 mDNS_Deregister(m
, &rem
->ar
);
2525 else ptr
= &(*ptr
)->next
;
2529 mDNSlocal
void AddAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
2531 DNameListElem
*new = mDNSPlatformMemAllocate(sizeof(DNameListElem
));
2532 if (!new) { LogMsg("ERROR: malloc"); return; }
2533 AssignDomainName(&new->name
, name
);
2535 new->next
= AutoBrowseDomains
;
2536 AutoBrowseDomains
= new;
2537 udsserver_automatic_browse_domain_changed(new, mDNStrue
);
2540 mDNSlocal
void RmvAutoBrowseDomain(const mDNSu32 uid
, const domainname
*const name
)
2542 DNameListElem
**p
= &AutoBrowseDomains
;
2543 while (*p
&& (!SameDomainName(&(*p
)->name
, name
) || (*p
)->uid
!= uid
)) p
= &(*p
)->next
;
2544 if (!*p
) LogMsg("RmvAutoBrowseDomain: Got remove event for domain %##s not in list", name
->c
);
2547 DNameListElem
*ptr
= *p
;
2549 udsserver_automatic_browse_domain_changed(ptr
, mDNSfalse
);
2550 mDNSPlatformMemFree(ptr
);
2554 mDNSlocal
void SetPrefsBrowseDomains(mDNS
*m
, DNameListElem
*browseDomains
, mDNSBool add
)
2557 for (d
= browseDomains
; d
; d
= d
->next
)
2561 RegisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
2562 AddAutoBrowseDomain(d
->uid
, &d
->name
);
2566 DeregisterLocalOnlyDomainEnumPTR(m
, &d
->name
, mDNS_DomainTypeBrowse
);
2567 RmvAutoBrowseDomain(d
->uid
, &d
->name
);
2572 mDNSlocal
void UpdateDeviceInfoRecord(mDNS
*const m
)
2574 int num_autoname
= 0;
2576 for (req
= all_requests
; req
; req
= req
->next
)
2577 if (req
->terminate
== regservice_termination_callback
&& req
->u
.servicereg
.autoname
)
2580 // If DeviceInfo record is currently registered, see if we need to deregister it
2581 if (m
->DeviceInfo
.resrec
.RecordType
!= kDNSRecordTypeUnregistered
)
2582 if (num_autoname
== 0 || !SameDomainLabelCS(m
->DeviceInfo
.resrec
.name
->c
, m
->nicelabel
.c
))
2584 LogOperation("UpdateDeviceInfoRecord Deregister %##s", m
->DeviceInfo
.resrec
.name
);
2585 mDNS_Deregister(m
, &m
->DeviceInfo
);
2588 // If DeviceInfo record is not currently registered, see if we need to register it
2589 if (m
->DeviceInfo
.resrec
.RecordType
== kDNSRecordTypeUnregistered
)
2590 if (num_autoname
> 0)
2592 mDNSu8 len
= m
->HIHardware
.c
[0] < 255 - 6 ? m
->HIHardware
.c
[0] : 255 - 6;
2593 mDNS_SetupResourceRecord(&m
->DeviceInfo
, mDNSNULL
, mDNSNULL
, kDNSType_TXT
, kStandardTTL
, kDNSRecordTypeAdvisory
, mDNSNULL
, mDNSNULL
);
2594 ConstructServiceName(&m
->DeviceInfo
.namestorage
, &m
->nicelabel
, &DeviceInfoName
, &localdomain
);
2595 mDNSPlatformMemCopy(m
->DeviceInfo
.resrec
.rdata
->u
.data
+ 1, "model=", 6);
2596 mDNSPlatformMemCopy(m
->DeviceInfo
.resrec
.rdata
->u
.data
+ 7, m
->HIHardware
.c
+ 1, len
);
2597 m
->DeviceInfo
.resrec
.rdata
->u
.data
[0] = 6 + len
; // "model=" plus the device string
2598 m
->DeviceInfo
.resrec
.rdlength
= 7 + len
; // One extra for the length byte at the start of the string
2599 LogOperation("UpdateDeviceInfoRecord Register %##s", m
->DeviceInfo
.resrec
.name
);
2600 mDNS_Register(m
, &m
->DeviceInfo
);
2604 mDNSexport
void udsserver_handle_configchange(mDNS
*const m
)
2607 service_instance
*ptr
;
2608 DNameListElem
*RegDomains
= NULL
;
2609 DNameListElem
*BrowseDomains
= NULL
;
2612 UpdateDeviceInfoRecord(m
);
2614 // For autoname services, see if the default service name has changed, necessitating an automatic update
2615 for (req
= all_requests
; req
; req
= req
->next
)
2616 if (req
->terminate
== regservice_termination_callback
)
2617 if (req
->u
.servicereg
.autoname
&& !SameDomainLabelCS(req
->u
.servicereg
.name
.c
, m
->nicelabel
.c
))
2619 req
->u
.servicereg
.name
= m
->nicelabel
;
2620 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
2622 ptr
->renameonmemfree
= 1;
2623 if (ptr
->clientnotified
) SendServiceRemovalNotification(&ptr
->srs
);
2624 if (mDNS_DeregisterService(m
, &ptr
->srs
)) // If service was deregistered already
2625 regservice_callback(m
, &ptr
->srs
, mStatus_MemFree
); // we can re-register immediately
2629 // Let the platform layer get the current DNS information
2631 mDNSPlatformSetDNSConfig(m
, mDNSfalse
, mDNSfalse
, mDNSNULL
, &RegDomains
, &BrowseDomains
);
2634 // Any automatic registration domains are also implicitly automatic browsing domains
2635 if (RegDomains
) SetPrefsBrowseDomains(m
, RegDomains
, mDNStrue
); // Add the new list first
2636 if (AutoRegistrationDomains
) SetPrefsBrowseDomains(m
, AutoRegistrationDomains
, mDNSfalse
); // Then clear the old list
2638 // Add any new domains not already in our AutoRegistrationDomains list
2639 for (p
=RegDomains
; p
; p
=p
->next
)
2641 DNameListElem
**pp
= &AutoRegistrationDomains
;
2642 while (*pp
&& ((*pp
)->uid
!= p
->uid
|| !SameDomainName(&(*pp
)->name
, &p
->name
))) pp
= &(*pp
)->next
;
2643 if (!*pp
) // If not found in our existing list, this is a new default registration domain
2645 RegisterLocalOnlyDomainEnumPTR(m
, &p
->name
, mDNS_DomainTypeRegistration
);
2646 udsserver_default_reg_domain_changed(p
, mDNStrue
);
2648 else // else found same domainname in both old and new lists, so no change, just delete old copy
2650 DNameListElem
*del
= *pp
;
2652 mDNSPlatformMemFree(del
);
2656 // Delete any domains in our old AutoRegistrationDomains list that are now gone
2657 while (AutoRegistrationDomains
)
2659 DNameListElem
*del
= AutoRegistrationDomains
;
2660 AutoRegistrationDomains
= AutoRegistrationDomains
->next
; // Cut record from list FIRST,
2661 DeregisterLocalOnlyDomainEnumPTR(m
, &del
->name
, mDNS_DomainTypeRegistration
);
2662 udsserver_default_reg_domain_changed(del
, mDNSfalse
); // before calling udsserver_default_reg_domain_changed()
2663 mDNSPlatformMemFree(del
);
2666 // Now we have our new updated automatic registration domain list
2667 AutoRegistrationDomains
= RegDomains
;
2669 // Add new browse domains to internal list
2670 if (BrowseDomains
) SetPrefsBrowseDomains(m
, BrowseDomains
, mDNStrue
);
2672 // Remove old browse domains from internal list
2673 if (SCPrefBrowseDomains
)
2675 SetPrefsBrowseDomains(m
, SCPrefBrowseDomains
, mDNSfalse
);
2676 while (SCPrefBrowseDomains
)
2678 DNameListElem
*fptr
= SCPrefBrowseDomains
;
2679 SCPrefBrowseDomains
= SCPrefBrowseDomains
->next
;
2680 mDNSPlatformMemFree(fptr
);
2684 // Replace the old browse domains array with the new array
2685 SCPrefBrowseDomains
= BrowseDomains
;
2688 mDNSlocal
void AutomaticBrowseDomainChange(mDNS
*const m
, DNSQuestion
*q
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2693 LogOperation("AutomaticBrowseDomainChange: %s automatic browse domain %##s",
2694 AddRecord
? "Adding" : "Removing", answer
->rdata
->u
.name
.c
);
2696 if (AddRecord
) AddAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2697 else RmvAutoBrowseDomain(0, &answer
->rdata
->u
.name
);
2700 mDNSlocal mStatus
handle_browse_request(request_state
*request
)
2702 char regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2703 domainname typedn
, d
, temp
;
2704 mDNSs32 NumSubTypes
;
2705 mStatus err
= mStatus_NoError
;
2707 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2708 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2709 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2710 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
2712 if (get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2713 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0) return(mStatus_BadParamErr
);
2715 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceBrowse(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2717 if (domain
[0] == '\0') uDNS_RegisterSearchDomains(&mDNSStorage
);
2720 NumSubTypes
= ChopSubTypes(regtype
); // Note: Modifies regtype string to remove trailing subtypes
2721 if (NumSubTypes
< 0 || NumSubTypes
> 1) return(mStatus_BadParamErr
);
2722 if (NumSubTypes
== 1 && !AppendDNSNameString(&typedn
, regtype
+ strlen(regtype
) + 1)) return(mStatus_BadParamErr
);
2724 if (!regtype
[0] || !AppendDNSNameString(&typedn
, regtype
)) return(mStatus_BadParamErr
);
2726 if (!MakeDomainNameFromDNSNameString(&temp
, regtype
)) return(mStatus_BadParamErr
);
2727 // For over-long service types, we only allow domain "local"
2728 if (temp
.c
[0] > 15 && domain
[0] == 0) mDNSPlatformStrCopy(domain
, "local.");
2730 // Set up browser info
2731 request
->u
.browser
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2732 request
->u
.browser
.interface_id
= InterfaceID
;
2733 AssignDomainName(&request
->u
.browser
.regtype
, &typedn
);
2734 request
->u
.browser
.default_domain
= !domain
[0];
2735 request
->u
.browser
.browsers
= NULL
;
2737 LogOperation("%3d: DNSServiceBrowse(\"%##s\", \"%s\") START", request
->sd
, request
->u
.browser
.regtype
.c
, domain
);
2739 // We need to unconditionally set request->terminate, because even if we didn't successfully
2740 // start any browses right now, subsequent configuration changes may cause successful
2741 // browses to be added, and we'll need to cancel them before freeing this memory.
2742 request
->terminate
= browse_termination_callback
;
2746 if (!MakeDomainNameFromDNSNameString(&d
, domain
)) return(mStatus_BadParamErr
);
2747 err
= add_domain_to_browser(request
, &d
);
2749 err
= AuthorizedDomain(request
, &d
, AutoBrowseDomains
) ? add_domain_to_browser(request
, &d
) : mStatus_NoError
;
2754 DNameListElem
*sdom
;
2755 for (sdom
= AutoBrowseDomains
; sdom
; sdom
= sdom
->next
)
2756 if (!sdom
->uid
|| SystemUID(request
->uid
) || request
->uid
== sdom
->uid
)
2758 err
= add_domain_to_browser(request
, &sdom
->name
);
2761 if (SameDomainName(&sdom
->name
, &localdomain
)) break;
2762 else err
= mStatus_NoError
; // suppress errors for non-local "default" domains
2770 // ***************************************************************************
2771 #if COMPILER_LIKES_PRAGMA_MARK
2773 #pragma mark - DNSServiceResolve
2776 mDNSlocal
void resolve_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2779 char fullname
[MAX_ESCAPED_DOMAIN_NAME
], target
[MAX_ESCAPED_DOMAIN_NAME
];
2782 request_state
*req
= question
->QuestionContext
;
2785 LogOperation("%3d: DNSServiceResolve(%##s) %s %s", req
->sd
, question
->qname
.c
, AddRecord
? "ADD" : "RMV", RRDisplayString(m
, answer
));
2789 if (req
->u
.resolve
.srv
== answer
) req
->u
.resolve
.srv
= mDNSNULL
;
2790 if (req
->u
.resolve
.txt
== answer
) req
->u
.resolve
.txt
= mDNSNULL
;
2794 if (answer
->rrtype
== kDNSType_SRV
) req
->u
.resolve
.srv
= answer
;
2795 if (answer
->rrtype
== kDNSType_TXT
) req
->u
.resolve
.txt
= answer
;
2797 if (!req
->u
.resolve
.txt
|| !req
->u
.resolve
.srv
) return; // only deliver result to client if we have both answers
2799 ConvertDomainNameToCString(answer
->name
, fullname
);
2800 ConvertDomainNameToCString(&req
->u
.resolve
.srv
->rdata
->u
.srv
.target
, target
);
2802 // calculate reply length
2803 len
+= sizeof(DNSServiceFlags
);
2804 len
+= sizeof(mDNSu32
); // interface index
2805 len
+= sizeof(DNSServiceErrorType
);
2806 len
+= strlen(fullname
) + 1;
2807 len
+= strlen(target
) + 1;
2808 len
+= 2 * sizeof(mDNSu16
); // port, txtLen
2809 len
+= req
->u
.resolve
.txt
->rdlength
;
2811 // allocate/init reply header
2812 rep
= create_reply(resolve_reply_op
, len
, req
);
2813 rep
->rhdr
->flags
= dnssd_htonl(0);
2814 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
));
2815 rep
->rhdr
->error
= dnssd_htonl(kDNSServiceErr_NoError
);
2817 data
= (char *)&rep
->rhdr
[1];
2819 // write reply data to message
2820 put_string(fullname
, &data
);
2821 put_string(target
, &data
);
2822 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[0];
2823 *data
++ = req
->u
.resolve
.srv
->rdata
->u
.srv
.port
.b
[1];
2824 put_uint16(req
->u
.resolve
.txt
->rdlength
, &data
);
2825 put_rdata (req
->u
.resolve
.txt
->rdlength
, req
->u
.resolve
.txt
->rdata
->u
.data
, &data
);
2827 LogOperation("%3d: DNSServiceResolve(%s) RESULT %s:%d", req
->sd
, fullname
, target
, mDNSVal16(req
->u
.resolve
.srv
->rdata
->u
.srv
.port
));
2828 append_reply(req
, rep
);
2831 mDNSlocal
void resolve_termination_callback(request_state
*request
)
2833 LogOperation("%3d: DNSServiceResolve(%##s) STOP", request
->sd
, request
->u
.resolve
.qtxt
.qname
.c
);
2834 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2835 mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2838 mDNSlocal mStatus
handle_resolve_request(request_state
*request
)
2840 char name
[256], regtype
[MAX_ESCAPED_DOMAIN_NAME
], domain
[MAX_ESCAPED_DOMAIN_NAME
];
2844 // extract the data from the message
2845 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
2846 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
2847 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
2848 if (interfaceIndex
&& !InterfaceID
)
2849 { LogMsg("ERROR: handle_resolve_request bad interfaceIndex %d", interfaceIndex
); return(mStatus_BadParamErr
); }
2851 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0 ||
2852 get_string(&request
->msgptr
, request
->msgend
, regtype
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
2853 get_string(&request
->msgptr
, request
->msgend
, domain
, MAX_ESCAPED_DOMAIN_NAME
) < 0)
2854 { LogMsg("ERROR: handle_resolve_request - Couldn't read name/regtype/domain"); return(mStatus_BadParamErr
); }
2856 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceResolve(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
2858 if (build_domainname_from_strings(&fqdn
, name
, regtype
, domain
) < 0)
2859 { LogMsg("ERROR: handle_resolve_request bad “%s” “%s” “%s”", name
, regtype
, domain
); return(mStatus_BadParamErr
); }
2861 mDNSPlatformMemZero(&request
->u
.resolve
, sizeof(request
->u
.resolve
));
2864 request
->u
.resolve
.qsrv
.InterfaceID
= InterfaceID
;
2865 request
->u
.resolve
.qsrv
.Target
= zeroAddr
;
2866 AssignDomainName(&request
->u
.resolve
.qsrv
.qname
, &fqdn
);
2867 request
->u
.resolve
.qsrv
.qtype
= kDNSType_SRV
;
2868 request
->u
.resolve
.qsrv
.qclass
= kDNSClass_IN
;
2869 request
->u
.resolve
.qsrv
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2870 request
->u
.resolve
.qsrv
.ExpectUnique
= mDNStrue
;
2871 request
->u
.resolve
.qsrv
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2872 request
->u
.resolve
.qsrv
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2873 request
->u
.resolve
.qsrv
.QuestionCallback
= resolve_result_callback
;
2874 request
->u
.resolve
.qsrv
.QuestionContext
= request
;
2876 request
->u
.resolve
.qtxt
.InterfaceID
= InterfaceID
;
2877 request
->u
.resolve
.qtxt
.Target
= zeroAddr
;
2878 AssignDomainName(&request
->u
.resolve
.qtxt
.qname
, &fqdn
);
2879 request
->u
.resolve
.qtxt
.qtype
= kDNSType_TXT
;
2880 request
->u
.resolve
.qtxt
.qclass
= kDNSClass_IN
;
2881 request
->u
.resolve
.qtxt
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
2882 request
->u
.resolve
.qtxt
.ExpectUnique
= mDNStrue
;
2883 request
->u
.resolve
.qtxt
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
2884 request
->u
.resolve
.qtxt
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
2885 request
->u
.resolve
.qtxt
.QuestionCallback
= resolve_result_callback
;
2886 request
->u
.resolve
.qtxt
.QuestionContext
= request
;
2888 request
->u
.resolve
.ReportTime
= NonZeroTime(mDNS_TimeNow(&mDNSStorage
) + 130 * mDNSPlatformOneSecond
);
2891 if (!AuthorizedDomain(request
, &fqdn
, AutoBrowseDomains
)) return(mStatus_NoError
);
2894 // ask the questions
2895 LogOperation("%3d: DNSServiceResolve(%##s) START", request
->sd
, request
->u
.resolve
.qsrv
.qname
.c
);
2896 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2899 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.resolve
.qtxt
);
2900 if (err
) mDNS_StopQuery(&mDNSStorage
, &request
->u
.resolve
.qsrv
);
2901 else request
->terminate
= resolve_termination_callback
;
2907 // ***************************************************************************
2908 #if COMPILER_LIKES_PRAGMA_MARK
2910 #pragma mark - DNSServiceQueryRecord
2913 // mDNS operation functions. Each operation has 3 associated functions - a request handler that parses
2914 // the client's request and makes the appropriate mDNSCore call, a result handler (passed as a callback
2915 // to the mDNSCore routine) that sends results back to the client, and a termination routine that aborts
2916 // the mDNSCore operation if the client dies or closes its socket.
2918 mDNSlocal
void queryrecord_result_callback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
2920 char name
[MAX_ESCAPED_DOMAIN_NAME
];
2921 request_state
*req
= question
->QuestionContext
;
2925 DNSServiceErrorType error
= kDNSServiceErr_NoError
;
2928 #if APPLE_OSX_mDNSResponder
2929 if (question
== &req
->u
.queryrecord
.q2
)
2931 mDNS_StopQuery(&mDNSStorage
, question
);
2932 // If we got a non-negative answer for our "local SOA" test query, start an additional parallel unicast query
2933 if (answer
->RecordType
== kDNSRecordTypePacketNegative
||
2934 (question
->qtype
== req
->u
.queryrecord
.q
.qtype
&& SameDomainName(&question
->qname
, &req
->u
.queryrecord
.q
.qname
)))
2935 question
->QuestionCallback
= mDNSNULL
;
2938 *question
= req
->u
.queryrecord
.q
;
2939 question
->InterfaceID
= mDNSInterface_Unicast
;
2940 question
->ExpectUnique
= mDNStrue
;
2941 mStatus err
= mDNS_StartQuery(&mDNSStorage
, question
);
2942 if (!err
) LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
));
2943 else LogMsg("%3d: ERROR: queryrecord_result_callback %##s %s mDNS_StartQuery: %d", req
->sd
, question
->qname
.c
, DNSTypeName(question
->qtype
), (int)err
);
2947 #endif // APPLE_OSX_mDNSResponder
2949 if (answer
->RecordType
== kDNSRecordTypePacketNegative
)
2951 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
2952 // Active Directory sites) we need to ignore negative unicast answers. Otherwise we'll generate negative
2953 // answers for just about every single multicast name we ever look up, since the Microsoft Active Directory
2954 // server is going to assert that pretty much every single multicast name doesn't exist.
2955 if (!answer
->InterfaceID
&& IsLocalDomain(answer
->name
)) return;
2956 error
= kDNSServiceErr_NoSuchRecord
;
2957 AddRecord
= mDNStrue
;
2960 ConvertDomainNameToCString(answer
->name
, name
);
2962 LogOperation("%3d: %s(%##s, %s) %s %s", req
->sd
,
2963 req
->hdr
.op
== query_request
? "DNSServiceQueryRecord" : "DNSServiceGetAddrInfo",
2964 question
->qname
.c
, DNSTypeName(question
->qtype
), AddRecord
? "ADD" : "RMV", RRDisplayString(m
, answer
));
2966 len
= sizeof(DNSServiceFlags
); // calculate reply data length
2967 len
+= sizeof(mDNSu32
); // interface index
2968 len
+= sizeof(DNSServiceErrorType
);
2969 len
+= strlen(name
) + 1;
2970 len
+= 3 * sizeof(mDNSu16
); // type, class, rdlen
2971 len
+= answer
->rdlength
;
2972 len
+= sizeof(mDNSu32
); // TTL
2974 rep
= create_reply(req
->hdr
.op
== query_request
? query_reply_op
: addrinfo_reply_op
, len
, req
);
2976 rep
->rhdr
->flags
= dnssd_htonl(AddRecord
? kDNSServiceFlagsAdd
: 0);
2977 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, answer
->InterfaceID
));
2978 rep
->rhdr
->error
= dnssd_htonl(error
);
2980 data
= (char *)&rep
->rhdr
[1];
2982 put_string(name
, &data
);
2983 put_uint16(answer
->rrtype
, &data
);
2984 put_uint16(answer
->rrclass
, &data
);
2985 put_uint16(answer
->rdlength
, &data
);
2986 // We need to use putRData here instead of the crude put_rdata function, because the crude put_rdata
2987 // function just does a blind memory copy without regard to structures that may have holes in them.
2988 if (answer
->rdlength
)
2989 if (!putRData(mDNSNULL
, (mDNSu8
*)data
, (mDNSu8
*)rep
->rhdr
+ len
, answer
))
2990 LogMsg("queryrecord_result_callback putRData failed %d", (mDNSu8
*)rep
->rhdr
+ len
- (mDNSu8
*)data
);
2991 data
+= answer
->rdlength
;
2992 put_uint32(AddRecord
? answer
->rroriginalttl
: 0, &data
);
2994 append_reply(req
, rep
);
2997 mDNSlocal
void queryrecord_termination_callback(request_state
*request
)
2999 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) STOP",
3000 request
->sd
, request
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(request
->u
.queryrecord
.q
.qtype
));
3001 mDNS_StopQuery(&mDNSStorage
, &request
->u
.queryrecord
.q
); // no need to error check
3002 if (request
->u
.queryrecord
.q2
.QuestionCallback
) mDNS_StopQuery(&mDNSStorage
, &request
->u
.queryrecord
.q2
);
3005 mDNSlocal mStatus
handle_queryrecord_request(request_state
*request
)
3007 DNSQuestion
*const q
= &request
->u
.queryrecord
.q
;
3009 mDNSu16 rrtype
, rrclass
;
3012 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3013 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3014 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3015 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3017 if (get_string(&request
->msgptr
, request
->msgend
, name
, 256) < 0) return(mStatus_BadParamErr
);
3018 rrtype
= get_uint16(&request
->msgptr
, request
->msgend
);
3019 rrclass
= get_uint16(&request
->msgptr
, request
->msgend
);
3021 if (!request
->msgptr
)
3022 { LogMsg("%3d: DNSServiceQueryRecord(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3024 mDNSPlatformMemZero(&request
->u
.queryrecord
, sizeof(request
->u
.queryrecord
));
3026 q
->InterfaceID
= InterfaceID
;
3027 q
->Target
= zeroAddr
;
3028 if (!MakeDomainNameFromDNSNameString(&q
->qname
, name
)) return(mStatus_BadParamErr
);
3030 if (!AuthorizedDomain(request
, &q
->qname
, AutoBrowseDomains
)) return (mStatus_NoError
);
3033 q
->qclass
= rrclass
;
3034 q
->LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
3035 q
->ExpectUnique
= mDNSfalse
;
3036 q
->ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
3037 q
->ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
3038 q
->QuestionCallback
= queryrecord_result_callback
;
3039 q
->QuestionContext
= request
;
3041 LogOperation("%3d: DNSServiceQueryRecord(%##s, %s, %X) START", request
->sd
, q
->qname
.c
, DNSTypeName(q
->qtype
), flags
);
3042 err
= mDNS_StartQuery(&mDNSStorage
, q
);
3043 if (err
) LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request
->sd
, q
->qname
.c
, DNSTypeName(q
->qtype
), (int)err
);
3044 else request
->terminate
= queryrecord_termination_callback
;
3046 #if APPLE_OSX_mDNSResponder
3047 // Workaround for networks using Microsoft Active Directory using "local" as a private internal top-level domain
3048 extern domainname ActiveDirectoryPrimaryDomain
;
3049 #define VALID_MSAD_SRV_TRANSPORT(T) (SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_tcp") || SameDomainLabel((T)->c, (const mDNSu8 *)"\x4_udp"))
3050 #define VALID_MSAD_SRV(Q) ((Q)->qtype == kDNSType_SRV && VALID_MSAD_SRV_TRANSPORT(SecondLabel(&(Q)->qname)))
3052 if (!q
->ForceMCast
&& SameDomainLabel(LastLabel(&q
->qname
), (const mDNSu8
*)&localdomain
))
3053 if (q
->qtype
== kDNSType_A
|| q
->qtype
== kDNSType_AAAA
|| VALID_MSAD_SRV(q
))
3055 int labels
= CountLabels(&q
->qname
);
3056 DNSQuestion
*const q2
= &request
->u
.queryrecord
.q2
;
3058 q2
->InterfaceID
= mDNSInterface_Unicast
;
3059 q2
->ExpectUnique
= mDNStrue
;
3061 // For names of the form "<one-or-more-labels>.bar.local." we always do a second unicast query in parallel.
3062 // For names of the form "<one-label>.local." it's less clear whether we should do a unicast query.
3063 // If the name being queried is exactly the same as the name in the DHCP "domain" option (e.g. the DHCP
3064 // "domain" is my-small-company.local, and the user types "my-small-company.local" into their web browser)
3065 // then that's a hint that it's worth doing a unicast query. Otherwise, we first check to see if the
3066 // site's DNS server claims there's an SOA record for "local", and if so, that's also a hint that queries
3067 // for names in the "local" domain will be safely answered privately before they hit the root name servers.
3068 if (labels
== 2 && !SameDomainName(&q
->qname
, &ActiveDirectoryPrimaryDomain
))
3070 AssignDomainName(&q2
->qname
, &localdomain
);
3071 q2
->qtype
= kDNSType_SOA
;
3072 q2
->LongLived
= mDNSfalse
;
3073 q2
->ForceMCast
= mDNSfalse
;
3074 q2
->ReturnIntermed
= mDNStrue
;
3076 err
= mDNS_StartQuery(&mDNSStorage
, q2
);
3077 if (!err
) LogOperation("%3d: DNSServiceQueryRecord(%##s, %s) unicast", request
->sd
, q2
->qname
.c
, DNSTypeName(q2
->qtype
));
3078 else LogMsg("%3d: ERROR: DNSServiceQueryRecord %##s %s mDNS_StartQuery: %d", request
->sd
, q2
->qname
.c
, DNSTypeName(q2
->qtype
), (int)err
);
3080 #endif // APPLE_OSX_mDNSResponder
3085 // ***************************************************************************
3086 #if COMPILER_LIKES_PRAGMA_MARK
3088 #pragma mark - DNSServiceEnumerateDomains
3091 mDNSlocal reply_state
*format_enumeration_reply(request_state
*request
,
3092 const char *domain
, DNSServiceFlags flags
, mDNSu32 ifi
, DNSServiceErrorType err
)
3098 len
= sizeof(DNSServiceFlags
);
3099 len
+= sizeof(mDNSu32
);
3100 len
+= sizeof(DNSServiceErrorType
);
3101 len
+= strlen(domain
) + 1;
3103 reply
= create_reply(enumeration_reply_op
, len
, request
);
3104 reply
->rhdr
->flags
= dnssd_htonl(flags
);
3105 reply
->rhdr
->ifi
= dnssd_htonl(ifi
);
3106 reply
->rhdr
->error
= dnssd_htonl(err
);
3107 data
= (char *)&reply
->rhdr
[1];
3108 put_string(domain
, &data
);
3112 mDNSlocal
void enum_termination_callback(request_state
*request
)
3114 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3115 mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
);
3118 mDNSlocal
void enum_result_callback(mDNS
*const m
,
3119 DNSQuestion
*const question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
3121 char domain
[MAX_ESCAPED_DOMAIN_NAME
];
3122 request_state
*request
= question
->QuestionContext
;
3123 DNSServiceFlags flags
= 0;
3127 if (answer
->rrtype
!= kDNSType_PTR
) return;
3130 if (!AuthorizedDomain(request
, &answer
->rdata
->u
.name
, request
->u
.enumeration
.flags
? AutoRegistrationDomains
: AutoBrowseDomains
)) return;
3133 // We only return add/remove events for the browse and registration lists
3134 // For the default browse and registration answers, we only give an "ADD" event
3135 if (question
== &request
->u
.enumeration
.q_default
&& !AddRecord
) return;
3139 flags
|= kDNSServiceFlagsAdd
;
3140 if (question
== &request
->u
.enumeration
.q_default
) flags
|= kDNSServiceFlagsDefault
;
3143 ConvertDomainNameToCString(&answer
->rdata
->u
.name
, domain
);
3144 // Note that we do NOT propagate specific interface indexes to the client - for example, a domain we learn from
3145 // a machine's system preferences may be discovered on the LocalOnly interface, but should be browsed on the
3146 // network, so we just pass kDNSServiceInterfaceIndexAny
3147 reply
= format_enumeration_reply(request
, domain
, flags
, kDNSServiceInterfaceIndexAny
, kDNSServiceErr_NoError
);
3148 if (!reply
) { LogMsg("ERROR: enum_result_callback, format_enumeration_reply"); return; }
3150 LogOperation("%3d: DNSServiceEnumerateDomains(%#2s) RESULT %s: %s", request
->sd
, question
->qname
.c
, AddRecord
? "Add" : "Rmv", domain
);
3152 append_reply(request
, reply
);
3155 mDNSlocal mStatus
handle_enum_request(request_state
*request
)
3158 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3159 DNSServiceFlags reg
= flags
& kDNSServiceFlagsRegistrationDomains
;
3160 mDNS_DomainType t_all
= reg
? mDNS_DomainTypeRegistration
: mDNS_DomainTypeBrowse
;
3161 mDNS_DomainType t_default
= reg
? mDNS_DomainTypeRegistrationDefault
: mDNS_DomainTypeBrowseDefault
;
3162 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3163 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3164 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3166 if (!request
->msgptr
)
3167 { LogMsg("%3d: DNSServiceEnumerateDomains(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3169 // allocate context structures
3170 uDNS_RegisterSearchDomains(&mDNSStorage
);
3173 // mark which kind of enumeration we're doing so we can (de)authorize certain domains
3174 request
->u
.enumeration
.flags
= reg
;
3177 // enumeration requires multiple questions, so we must link all the context pointers so that
3178 // necessary context can be reached from the callbacks
3179 request
->u
.enumeration
.q_all
.QuestionContext
= request
;
3180 request
->u
.enumeration
.q_default
.QuestionContext
= request
;
3182 // if the caller hasn't specified an explicit interface, we use local-only to get the system-wide list.
3183 if (!InterfaceID
) InterfaceID
= mDNSInterface_LocalOnly
;
3186 LogOperation("%3d: DNSServiceEnumerateDomains(%X=%s)", request
->sd
, flags
,
3187 (flags
& kDNSServiceFlagsBrowseDomains
) ? "kDNSServiceFlagsBrowseDomains" :
3188 (flags
& kDNSServiceFlagsRegistrationDomains
) ? "kDNSServiceFlagsRegistrationDomains" : "<<Unknown>>");
3189 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
, t_all
, NULL
, InterfaceID
, enum_result_callback
, request
);
3192 err
= mDNS_GetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_default
, t_default
, NULL
, InterfaceID
, enum_result_callback
, request
);
3193 if (err
) mDNS_StopGetDomains(&mDNSStorage
, &request
->u
.enumeration
.q_all
);
3194 else request
->terminate
= enum_termination_callback
;
3200 // ***************************************************************************
3201 #if COMPILER_LIKES_PRAGMA_MARK
3203 #pragma mark - DNSServiceReconfirmRecord & Misc
3206 mDNSlocal mStatus
handle_reconfirm_request(request_state
*request
)
3208 mStatus status
= mStatus_BadParamErr
;
3209 AuthRecord
*rr
= read_rr_from_ipc_msg(request
, 0, 0);
3212 status
= mDNS_ReconfirmByValue(&mDNSStorage
, &rr
->resrec
);
3214 (status
== mStatus_NoError
) ?
3215 "%3d: DNSServiceReconfirmRecord(%s) interface %d initiated" :
3216 "%3d: DNSServiceReconfirmRecord(%s) interface %d failed: %d",
3217 request
->sd
, RRDisplayString(&mDNSStorage
, &rr
->resrec
),
3218 mDNSPlatformInterfaceIndexfromInterfaceID(&mDNSStorage
, rr
->resrec
.InterfaceID
), status
);
3219 freeL("AuthRecord/handle_reconfirm_request", rr
);
3224 mDNSlocal mStatus
handle_setdomain_request(request_state
*request
)
3226 char domainstr
[MAX_ESCAPED_DOMAIN_NAME
];
3228 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3229 (void)flags
; // Unused
3230 if (get_string(&request
->msgptr
, request
->msgend
, domainstr
, MAX_ESCAPED_DOMAIN_NAME
) < 0 ||
3231 !MakeDomainNameFromDNSNameString(&domain
, domainstr
))
3232 { LogMsg("%3d: DNSServiceSetDefaultDomainForUser(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3234 LogOperation("%3d: DNSServiceSetDefaultDomainForUser(%##s)", request
->sd
, domain
.c
);
3235 return(mStatus_NoError
);
3238 typedef packedstruct
3243 } DaemonVersionReply
;
3245 mDNSlocal
void handle_getproperty_request(request_state
*request
)
3247 const mStatus BadParamErr
= dnssd_htonl(mStatus_BadParamErr
);
3249 if (get_string(&request
->msgptr
, request
->msgend
, prop
, sizeof(prop
)) >= 0)
3251 LogOperation("%3d: DNSServiceGetProperty(%s)", request
->sd
, prop
);
3252 if (!strcmp(prop
, kDNSServiceProperty_DaemonVersion
))
3254 DaemonVersionReply x
= { 0, dnssd_htonl(4), dnssd_htonl(_DNS_SD_H
) };
3255 send_all(request
->sd
, (const char *)&x
, sizeof(x
));
3260 // If we didn't recogize the requested property name, return BadParamErr
3261 send_all(request
->sd
, (const char *)&BadParamErr
, sizeof(BadParamErr
));
3264 // ***************************************************************************
3265 #if COMPILER_LIKES_PRAGMA_MARK
3267 #pragma mark - DNSServiceNATPortMappingCreate
3270 #define DNSServiceProtocol(X) ((X) == NATOp_AddrRequest ? 0 : (X) == NATOp_MapUDP ? kDNSServiceProtocol_UDP : kDNSServiceProtocol_TCP)
3272 mDNSlocal
void port_mapping_termination_callback(request_state
*request
)
3274 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) STOP", request
->sd
,
3275 DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
3276 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
);
3277 mDNS_StopNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
3280 // Called via function pointer when we get a NAT-PMP address request or port mapping response
3281 mDNSlocal
void port_mapping_create_request_callback(mDNS
*m
, NATTraversalInfo
*n
)
3283 request_state
*request
= (request_state
*)n
->clientContext
;
3288 if (!request
) { LogMsg("port_mapping_create_request_callback called with unknown request_state object"); return; }
3290 // calculate reply data length
3291 replyLen
= sizeof(DNSServiceFlags
);
3292 replyLen
+= 3 * sizeof(mDNSu32
); // if index + addr + ttl
3293 replyLen
+= sizeof(DNSServiceErrorType
);
3294 replyLen
+= 2 * sizeof(mDNSu16
); // Internal Port + External Port
3295 replyLen
+= sizeof(mDNSu8
); // protocol
3297 rep
= create_reply(port_mapping_reply_op
, replyLen
, request
);
3299 rep
->rhdr
->flags
= dnssd_htonl(0);
3300 rep
->rhdr
->ifi
= dnssd_htonl(mDNSPlatformInterfaceIndexfromInterfaceID(m
, n
->InterfaceID
));
3301 rep
->rhdr
->error
= dnssd_htonl(n
->Result
);
3303 data
= (char *)&rep
->rhdr
[1];
3305 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[0];
3306 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[1];
3307 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[2];
3308 *data
++ = request
->u
.pm
.NATinfo
.ExternalAddress
.b
[3];
3309 *data
++ = DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
);
3310 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[0];
3311 *data
++ = request
->u
.pm
.NATinfo
.IntPort
.b
[1];
3312 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[0];
3313 *data
++ = request
->u
.pm
.NATinfo
.ExternalPort
.b
[1];
3314 put_uint32(request
->u
.pm
.NATinfo
.Lifetime
, &data
);
3316 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) RESULT %.4a:%u TTL %u", request
->sd
,
3317 DNSServiceProtocol(request
->u
.pm
.NATinfo
.Protocol
),
3318 mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
,
3319 &request
->u
.pm
.NATinfo
.ExternalAddress
, mDNSVal16(request
->u
.pm
.NATinfo
.ExternalPort
), request
->u
.pm
.NATinfo
.Lifetime
);
3321 append_reply(request
, rep
);
3324 mDNSlocal mStatus
handle_port_mapping_request(request_state
*request
)
3327 mStatus err
= mStatus_NoError
;
3329 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3330 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3331 mDNSInterfaceID InterfaceID
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3332 mDNSu8 protocol
= get_uint32(&request
->msgptr
, request
->msgend
);
3333 (void)flags
; // Unused
3334 if (interfaceIndex
&& !InterfaceID
) return(mStatus_BadParamErr
);
3335 if (request
->msgptr
+ 8 > request
->msgend
) request
->msgptr
= NULL
;
3338 request
->u
.pm
.NATinfo
.IntPort
.b
[0] = *request
->msgptr
++;
3339 request
->u
.pm
.NATinfo
.IntPort
.b
[1] = *request
->msgptr
++;
3340 request
->u
.pm
.ReqExt
.b
[0] = *request
->msgptr
++;
3341 request
->u
.pm
.ReqExt
.b
[1] = *request
->msgptr
++;
3342 ttl
= get_uint32(&request
->msgptr
, request
->msgend
);
3345 if (!request
->msgptr
)
3346 { LogMsg("%3d: DNSServiceNATPortMappingCreate(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3348 if (protocol
== 0) // If protocol == 0 (i.e. just request public address) then IntPort, ExtPort, ttl must be zero too
3350 if (!mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
) || !mDNSIPPortIsZero(request
->u
.pm
.ReqExt
) || ttl
) return(mStatus_BadParamErr
);
3354 if (mDNSIPPortIsZero(request
->u
.pm
.NATinfo
.IntPort
)) return(mStatus_BadParamErr
);
3355 if (!(protocol
& (kDNSServiceProtocol_UDP
| kDNSServiceProtocol_TCP
))) return(mStatus_BadParamErr
);
3358 request
->u
.pm
.NATinfo
.Protocol
= !protocol
? NATOp_AddrRequest
: (protocol
== kDNSServiceProtocol_UDP
) ? NATOp_MapUDP
: NATOp_MapTCP
;
3359 // u.pm.NATinfo.IntPort = already set above
3360 request
->u
.pm
.NATinfo
.RequestedPort
= request
->u
.pm
.ReqExt
;
3361 request
->u
.pm
.NATinfo
.NATLease
= ttl
;
3362 request
->u
.pm
.NATinfo
.clientCallback
= port_mapping_create_request_callback
;
3363 request
->u
.pm
.NATinfo
.clientContext
= request
;
3365 LogOperation("%3d: DNSServiceNATPortMappingCreate(%X, %u, %u, %d) START", request
->sd
,
3366 protocol
, mDNSVal16(request
->u
.pm
.NATinfo
.IntPort
), mDNSVal16(request
->u
.pm
.ReqExt
), request
->u
.pm
.NATinfo
.NATLease
);
3367 err
= mDNS_StartNATOperation(&mDNSStorage
, &request
->u
.pm
.NATinfo
);
3368 if (err
) LogMsg("ERROR: mDNS_StartNATOperation: %d", (int)err
);
3369 else request
->terminate
= port_mapping_termination_callback
;
3374 // ***************************************************************************
3375 #if COMPILER_LIKES_PRAGMA_MARK
3377 #pragma mark - DNSServiceGetAddrInfo
3380 mDNSlocal
void addrinfo_termination_callback(request_state
*request
)
3382 if (request
->u
.addrinfo
.q4
.QuestionContext
)
3384 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
3385 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
3388 if (request
->u
.addrinfo
.q6
.QuestionContext
)
3390 mDNS_StopQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
3391 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
3395 mDNSlocal mStatus
handle_addrinfo_request(request_state
*request
)
3401 DNSServiceFlags flags
= get_flags(&request
->msgptr
, request
->msgend
);
3402 mDNSu32 interfaceIndex
= get_uint32(&request
->msgptr
, request
->msgend
);
3404 mDNSPlatformMemZero(&request
->u
.addrinfo
, sizeof(request
->u
.addrinfo
));
3405 request
->u
.addrinfo
.interface_id
= mDNSPlatformInterfaceIDfromInterfaceIndex(&mDNSStorage
, interfaceIndex
);
3406 request
->u
.addrinfo
.flags
= flags
;
3407 request
->u
.addrinfo
.protocol
= get_uint32(&request
->msgptr
, request
->msgend
);
3409 if (interfaceIndex
&& !request
->u
.addrinfo
.interface_id
) return(mStatus_BadParamErr
);
3410 if (request
->u
.addrinfo
.protocol
> (kDNSServiceProtocol_IPv4
|kDNSServiceProtocol_IPv6
)) return(mStatus_BadParamErr
);
3412 if (get_string(&request
->msgptr
, request
->msgend
, hostname
, 256) < 0) return(mStatus_BadParamErr
);
3414 if (!request
->msgptr
) { LogMsg("%3d: DNSServiceGetAddrInfo(unreadable parameters)", request
->sd
); return(mStatus_BadParamErr
); }
3416 if (!MakeDomainNameFromDNSNameString(&d
, hostname
))
3417 { LogMsg("ERROR: handle_addrinfo_request: bad hostname: %s", hostname
); return(mStatus_BadParamErr
); }
3420 if (!AuthorizedDomain(request
, &d
, AutoBrowseDomains
)) return (mStatus_NoError
);
3423 if (!request
->u
.addrinfo
.protocol
)
3425 NetworkInterfaceInfo
*i
;
3426 if (IsLocalDomain(&d
))
3428 for (i
= mDNSStorage
.HostInterfaces
; i
; i
= i
->next
)
3430 if ((i
->ip
.type
== mDNSAddrType_IPv4
) && !mDNSIPv4AddressIsZero(i
->ip
.ip
.v4
)) request
->u
.addrinfo
.protocol
|= kDNSServiceProtocol_IPv4
;
3431 else if ((i
->ip
.type
== mDNSAddrType_IPv6
) && !mDNSIPv6AddressIsZero(i
->ip
.ip
.v6
)) request
->u
.addrinfo
.protocol
|= kDNSServiceProtocol_IPv6
;
3436 for (i
= mDNSStorage
.HostInterfaces
; i
; i
= i
->next
)
3438 if ((i
->ip
.type
== mDNSAddrType_IPv4
) && !mDNSv4AddressIsLinkLocal(&i
->ip
.ip
.v4
)) request
->u
.addrinfo
.protocol
|= kDNSServiceProtocol_IPv4
;
3439 else if ((i
->ip
.type
== mDNSAddrType_IPv6
) && !mDNSv4AddressIsLinkLocal(&i
->ip
.ip
.v6
)) request
->u
.addrinfo
.protocol
|= kDNSServiceProtocol_IPv6
;
3444 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
)
3446 request
->u
.addrinfo
.q4
.InterfaceID
= request
->u
.addrinfo
.interface_id
;
3447 request
->u
.addrinfo
.q4
.Target
= zeroAddr
;
3448 request
->u
.addrinfo
.q4
.qname
= d
;
3449 request
->u
.addrinfo
.q4
.qtype
= kDNSServiceType_A
;
3450 request
->u
.addrinfo
.q4
.qclass
= kDNSServiceClass_IN
;
3451 request
->u
.addrinfo
.q4
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
3452 request
->u
.addrinfo
.q4
.ExpectUnique
= mDNSfalse
;
3453 request
->u
.addrinfo
.q4
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
3454 request
->u
.addrinfo
.q4
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
3455 request
->u
.addrinfo
.q4
.QuestionCallback
= queryrecord_result_callback
;
3456 request
->u
.addrinfo
.q4
.QuestionContext
= request
;
3458 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.addrinfo
.q4
);
3459 if (err
!= mStatus_NoError
)
3461 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err
);
3462 request
->u
.addrinfo
.q4
.QuestionContext
= mDNSNULL
;
3466 if (!err
&& (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
))
3468 request
->u
.addrinfo
.q6
.InterfaceID
= request
->u
.addrinfo
.interface_id
;
3469 request
->u
.addrinfo
.q6
.Target
= zeroAddr
;
3470 request
->u
.addrinfo
.q6
.qname
= d
;
3471 request
->u
.addrinfo
.q6
.qtype
= kDNSServiceType_AAAA
;
3472 request
->u
.addrinfo
.q6
.qclass
= kDNSServiceClass_IN
;
3473 request
->u
.addrinfo
.q6
.LongLived
= (flags
& kDNSServiceFlagsLongLivedQuery
) != 0;
3474 request
->u
.addrinfo
.q6
.ExpectUnique
= mDNSfalse
;
3475 request
->u
.addrinfo
.q6
.ForceMCast
= (flags
& kDNSServiceFlagsForceMulticast
) != 0;
3476 request
->u
.addrinfo
.q6
.ReturnIntermed
= (flags
& kDNSServiceFlagsReturnIntermediates
) != 0;
3477 request
->u
.addrinfo
.q6
.QuestionCallback
= queryrecord_result_callback
;
3478 request
->u
.addrinfo
.q6
.QuestionContext
= request
;
3480 err
= mDNS_StartQuery(&mDNSStorage
, &request
->u
.addrinfo
.q6
);
3481 if (err
!= mStatus_NoError
)
3483 LogMsg("ERROR: mDNS_StartQuery: %d", (int)err
);
3484 request
->u
.addrinfo
.q6
.QuestionContext
= mDNSNULL
;
3485 if (request
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
) // If we started a query for IPv4,
3486 addrinfo_termination_callback(request
); // we need to cancel it
3490 LogOperation("%3d: DNSServiceGetAddrInfo(%##s) START", request
->sd
, d
.c
);
3492 if (!err
) request
->terminate
= addrinfo_termination_callback
;
3497 // ***************************************************************************
3498 #if COMPILER_LIKES_PRAGMA_MARK
3500 #pragma mark - Main Request Handler etc.
3503 mDNSlocal request_state
*NewRequest(void)
3505 request_state
**p
= &all_requests
;
3506 while (*p
) p
=&(*p
)->next
;
3507 *p
= mallocL("request_state", sizeof(request_state
));
3508 if (!*p
) FatalError("ERROR: malloc");
3509 mDNSPlatformMemZero(*p
, sizeof(request_state
));
3513 // read_msg may be called any time when the transfer state (req->ts) is t_morecoming.
3514 // if there is no data on the socket, the socket will be closed and t_terminated will be returned
3515 mDNSlocal
void read_msg(request_state
*req
)
3517 if (req
->ts
== t_terminated
|| req
->ts
== t_error
)
3518 { LogMsg("%3d: ERROR: read_msg called with transfer state terminated or error", req
->sd
); req
->ts
= t_error
; return; }
3520 if (req
->ts
== t_complete
) // this must be death or something is wrong
3522 char buf
[4]; // dummy for death notification
3523 int nread
= recv(req
->sd
, buf
, 4, 0);
3524 if (!nread
) { req
->ts
= t_terminated
; return; }
3525 if (nread
< 0) goto rerror
;
3526 LogMsg("%3d: ERROR: read data from a completed request", req
->sd
);
3531 if (req
->ts
!= t_morecoming
)
3532 { LogMsg("%3d: ERROR: read_msg called with invalid transfer state (%d)", req
->sd
, req
->ts
); req
->ts
= t_error
; return; }
3534 if (req
->hdr_bytes
< sizeof(ipc_msg_hdr
))
3536 mDNSu32 nleft
= sizeof(ipc_msg_hdr
) - req
->hdr_bytes
;
3537 int nread
= recv(req
->sd
, (char *)&req
->hdr
+ req
->hdr_bytes
, nleft
, 0);
3538 if (nread
== 0) { req
->ts
= t_terminated
; return; }
3539 if (nread
< 0) goto rerror
;
3540 req
->hdr_bytes
+= nread
;
3541 if (req
->hdr_bytes
> sizeof(ipc_msg_hdr
))
3542 { LogMsg("%3d: ERROR: read_msg - read too many header bytes", req
->sd
); req
->ts
= t_error
; return; }
3544 // only read data if header is complete
3545 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
))
3547 ConvertHeaderBytes(&req
->hdr
);
3548 if (req
->hdr
.version
!= VERSION
)
3549 { LogMsg("%3d: ERROR: client version 0x%08X daemon version 0x%08X", req
->sd
, req
->hdr
.version
, VERSION
); req
->ts
= t_error
; return; }
3551 // Largest conceivable single request is a DNSServiceRegisterRecord() or DNSServiceAddRecord()
3552 // with 64kB of rdata. Adding 1009 byte for a maximal domain name, plus a safety margin
3553 // for other overhead, this means any message above 70kB is definitely bogus.
3554 if (req
->hdr
.datalen
> 70000)
3555 { LogMsg("%3d: ERROR: read_msg - hdr.datalen %lu (%X) > 70000", req
->sd
, req
->hdr
.datalen
, req
->hdr
.datalen
); req
->ts
= t_error
; return; }
3556 req
->msgbuf
= mallocL("request_state msgbuf", req
->hdr
.datalen
+ MSG_PAD_BYTES
);
3557 if (!req
->msgbuf
) { my_perror("ERROR: malloc"); req
->ts
= t_error
; return; }
3558 req
->msgptr
= req
->msgbuf
;
3559 req
->msgend
= req
->msgbuf
+ req
->hdr
.datalen
;
3560 mDNSPlatformMemZero(req
->msgbuf
, req
->hdr
.datalen
+ MSG_PAD_BYTES
);
3564 // If our header is complete, but we're still needing more body data, then try to read it now
3565 // Note: For cancel_request req->hdr.datalen == 0, but there's no error return socket for cancel_request
3566 // Any time we need to get the error return socket we know we'll have at least one data byte
3567 // (even if only the one-byte empty C string placeholder for the old ctrl_path parameter)
3568 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
< req
->hdr
.datalen
)
3570 mDNSu32 nleft
= req
->hdr
.datalen
- req
->data_bytes
;
3572 #if !defined(_WIN32)
3573 struct iovec vec
= { req
->msgbuf
+ req
->data_bytes
, nleft
}; // Tell recvmsg where we want the bytes put
3575 struct cmsghdr
*cmsg
;
3576 char cbuf
[CMSG_SPACE(sizeof(dnssd_sock_t
))];
3578 msg
.msg_namelen
= 0;
3581 msg
.msg_control
= cbuf
;
3582 msg
.msg_controllen
= sizeof(cbuf
);
3584 nread
= recvmsg(req
->sd
, &msg
, 0);
3586 nread
= recv(req
->sd
, (char *)req
->msgbuf
+ req
->data_bytes
, nleft
, 0);
3588 if (nread
== 0) { req
->ts
= t_terminated
; return; }
3589 if (nread
< 0) goto rerror
;
3590 req
->data_bytes
+= nread
;
3591 if (req
->data_bytes
> req
->hdr
.datalen
)
3592 { LogMsg("%3d: ERROR: read_msg - read too many data bytes", req
->sd
); req
->ts
= t_error
; return; }
3593 #if !defined(_WIN32)
3594 cmsg
= CMSG_FIRSTHDR(&msg
);
3595 #if DEBUG_64BIT_SCM_RIGHTS
3596 LogMsg("%3d: Expecting %d %d %d %d", req
->sd
, sizeof(cbuf
), sizeof(cbuf
), SOL_SOCKET
, SCM_RIGHTS
);
3597 LogMsg("%3d: Got %d %d %d %d", req
->sd
, msg
.msg_controllen
, cmsg
->cmsg_len
, cmsg
->cmsg_level
, cmsg
->cmsg_type
);
3598 #endif // DEBUG_64BIT_SCM_RIGHTS
3599 if (msg
.msg_controllen
== sizeof(cbuf
) &&
3600 cmsg
->cmsg_len
== sizeof(cbuf
) &&
3601 cmsg
->cmsg_level
== SOL_SOCKET
&&
3602 cmsg
->cmsg_type
== SCM_RIGHTS
)
3604 #if APPLE_OSX_mDNSResponder
3605 // Strictly speaking BPF_fd belongs solely in the platform support layer, but because
3606 // of privilege separation on Mac OS X we need to get BPF_fd from mDNSResponderHelper,
3607 // and it's convenient to repurpose the existing fd-passing code here for that task
3608 if (req
->hdr
.op
== send_bpf
)
3610 dnssd_sock_t x
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3611 LogOperation("%3d: Got BPF %d", req
->sd
, x
);
3612 mDNSPlatformReceiveBPF_fd(&mDNSStorage
, x
);
3615 #endif // APPLE_OSX_mDNSResponder
3616 req
->errsd
= *(dnssd_sock_t
*)CMSG_DATA(cmsg
);
3617 #if DEBUG_64BIT_SCM_RIGHTS
3618 LogMsg("%3d: read req->errsd %d", req
->sd
, req
->errsd
);
3619 #endif // DEBUG_64BIT_SCM_RIGHTS
3620 if (req
->data_bytes
< req
->hdr
.datalen
)
3622 LogMsg("%3d: Client sent error socket %d via SCM_RIGHTS with req->data_bytes %d < req->hdr.datalen %d",
3623 req
->sd
, req
->errsd
, req
->data_bytes
, req
->hdr
.datalen
);
3631 // If our header and data are both complete, see if we need to make our separate error return socket
3632 if (req
->hdr_bytes
== sizeof(ipc_msg_hdr
) && req
->data_bytes
== req
->hdr
.datalen
)
3634 if (req
->terminate
&& req
->hdr
.op
!= cancel_request
)
3636 dnssd_sockaddr_t cliaddr
;
3637 #if defined(USE_TCP_LOOPBACK)
3640 port
.b
[0] = req
->msgptr
[0];
3641 port
.b
[1] = req
->msgptr
[1];
3643 cliaddr
.sin_family
= AF_INET
;
3644 cliaddr
.sin_port
= port
.NotAnInteger
;
3645 cliaddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
3647 char ctrl_path
[MAX_CTLPATH
];
3648 get_string(&req
->msgptr
, req
->msgend
, ctrl_path
, MAX_CTLPATH
); // path is first element in message buffer
3649 mDNSPlatformMemZero(&cliaddr
, sizeof(cliaddr
));
3650 cliaddr
.sun_family
= AF_LOCAL
;
3651 mDNSPlatformStrCopy(cliaddr
.sun_path
, ctrl_path
);
3652 // If the error return path UDS name is empty string, that tells us
3653 // that this is a new version of the library that's going to pass us
3654 // the error return path socket via sendmsg/recvmsg
3655 if (ctrl_path
[0] == 0)
3657 if (req
->errsd
== req
->sd
)
3658 { LogMsg("%3d: read_msg: ERROR failed to get errsd via SCM_RIGHTS", req
->sd
); req
->ts
= t_error
; return; }
3663 req
->errsd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
3664 if (!dnssd_SocketValid(req
->errsd
)) { my_perror("ERROR: socket"); req
->ts
= t_error
; return; }
3666 if (connect(req
->errsd
, (struct sockaddr
*)&cliaddr
, sizeof(cliaddr
)) < 0)
3668 #if !defined(USE_TCP_LOOPBACK)
3670 LogMsg("%3d: read_msg: Couldn't connect to error return path socket “%s” errno %d (%s)",
3671 req
->sd
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3672 if (stat(cliaddr
.sun_path
, &sb
) < 0)
3673 LogMsg("%3d: read_msg: stat failed “%s” errno %d (%s)", req
->sd
, cliaddr
.sun_path
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3675 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 LogOperation("%3d: Error socket %d created %08X %08X", req
->sd
, req
->errsd
, req
->hdr
.client_context
.u32
[1], req
->hdr
.client_context
.u32
[0]);
3684 if (ioctlsocket(req
->errsd
, FIONBIO
, &opt
) != 0)
3686 if (fcntl(req
->errsd
, F_SETFL
, fcntl(req
->errsd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3689 LogMsg("%3d: ERROR: could not set control socket to non-blocking mode errno %d (%s)",
3690 req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3696 req
->ts
= t_complete
;
3702 if (dnssd_errno
== dnssd_EWOULDBLOCK
|| dnssd_errno
== dnssd_EINTR
) return;
3703 LogMsg("%3d: ERROR: read_msg errno %d (%s)", req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3707 #define RecordOrientedOp(X) \
3708 ((X) == reg_record_request || (X) == add_record_request || (X) == update_record_request || (X) == remove_record_request)
3710 // The lightweight operations are the ones that don't need a dedicated request_state structure allocated for them
3711 #define LightweightOp(X) (RecordOrientedOp(X) || (X) == cancel_request)
3713 mDNSlocal
void request_callback(int fd
, short filter
, void *info
)
3716 request_state
*req
= info
;
3720 mDNSs32 min_size
= sizeof(DNSServiceFlags
);
3722 (void)filter
; // Unused
3725 if (req
->ts
== t_morecoming
) return;
3726 if (req
->ts
== t_terminated
|| req
->ts
== t_error
) { AbortUnlinkAndFree(req
); return; }
3727 if (req
->ts
!= t_complete
) { LogMsg("req->ts %d != t_complete", req
->ts
); AbortUnlinkAndFree(req
); return; }
3729 if (req
->hdr
.version
!= VERSION
)
3731 LogMsg("ERROR: client version %d incompatible with daemon version %d", req
->hdr
.version
, VERSION
);
3732 AbortUnlinkAndFree(req
);
3736 switch(req
->hdr
.op
) // Interface + other data
3738 case connection_request
: min_size
= 0; break;
3739 case reg_service_request
: min_size
+= sizeof(mDNSu32
) + 4 /* name, type, domain, host */ + 4 /* port, textlen */; break;
3740 case add_record_request
: min_size
+= 4 /* type, rdlen */ + 4 /* ttl */; break;
3741 case update_record_request
: min_size
+= 2 /* rdlen */ + 4 /* ttl */; break;
3742 case remove_record_request
: break;
3743 case browse_request
: min_size
+= sizeof(mDNSu32
) + 2 /* type, domain */; break;
3744 case resolve_request
: min_size
+= sizeof(mDNSu32
) + 3 /* type, type, domain */; break;
3745 case query_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 4 /* type, class*/; break;
3746 case enumeration_request
: min_size
+= sizeof(mDNSu32
); break;
3747 case reg_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */ + 4 /* ttl */; break;
3748 case reconfirm_record_request
: min_size
+= sizeof(mDNSu32
) + 1 /* name */ + 6 /* type, class, rdlen */; break;
3749 case setdomain_request
: min_size
+= 1 /* domain */; break;
3750 case getproperty_request
: min_size
= 2; break;
3751 case port_mapping_request
: min_size
+= sizeof(mDNSu32
) + 4 /* udp/tcp */ + 4 /* int/ext port */ + 4 /* ttl */; break;
3752 case addrinfo_request
: min_size
+= sizeof(mDNSu32
) + 4 /* v4/v6 */ + 1 /* hostname */; break;
3753 case send_bpf
: // Same as cancel_request below
3754 case cancel_request
: min_size
= 0; break;
3755 default: LogMsg("ERROR: validate_message - unsupported req type: %d", req
->hdr
.op
); min_size
= -1; break;
3758 if ((mDNSs32
)req
->data_bytes
< min_size
)
3759 { LogMsg("Invalid message %d bytes; min for %d is %d", req
->data_bytes
, req
->hdr
.op
, min_size
); AbortUnlinkAndFree(req
); return; }
3761 if (LightweightOp(req
->hdr
.op
) && !req
->terminate
)
3762 { LogMsg("Reg/Add/Update/Remove %d require existing connection", req
->hdr
.op
); AbortUnlinkAndFree(req
); return; }
3764 // check if client wants silent operation
3765 if (req
->hdr
.ipc_flags
& IPC_FLAGS_NOREPLY
) req
->no_reply
= 1;
3767 // If req->terminate is already set, this means this operation is sharing an existing connection
3768 if (req
->terminate
&& !LightweightOp(req
->hdr
.op
))
3770 request_state
*newreq
= NewRequest();
3771 newreq
->primary
= req
;
3772 newreq
->sd
= req
->sd
;
3773 newreq
->errsd
= req
->errsd
;
3774 newreq
->uid
= req
->uid
;
3775 newreq
->hdr
= req
->hdr
;
3776 newreq
->msgbuf
= req
->msgbuf
;
3777 newreq
->msgptr
= req
->msgptr
;
3778 newreq
->msgend
= req
->msgend
;
3782 // If we're shutting down, don't allow new client requests
3783 // We do allow "cancel" and "getproperty" during shutdown
3784 if (mDNSStorage
.ShutdownTime
&& req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
)
3786 err
= mStatus_ServiceNotRunning
;
3788 else switch(req
->hdr
.op
)
3790 // These are all operations that have their own first-class request_state object
3791 case connection_request
: LogOperation("%3d: DNSServiceCreateConnection START", req
->sd
);
3792 req
->terminate
= connection_termination
; break;
3793 case resolve_request
: err
= handle_resolve_request (req
); break;
3794 case query_request
: err
= handle_queryrecord_request (req
); break;
3795 case browse_request
: err
= handle_browse_request (req
); break;
3796 case reg_service_request
: err
= handle_regservice_request (req
); break;
3797 case enumeration_request
: err
= handle_enum_request (req
); break;
3798 case reconfirm_record_request
: err
= handle_reconfirm_request (req
); break;
3799 case setdomain_request
: err
= handle_setdomain_request (req
); break;
3800 case getproperty_request
: handle_getproperty_request (req
); break;
3801 case port_mapping_request
: err
= handle_port_mapping_request(req
); break;
3802 case addrinfo_request
: err
= handle_addrinfo_request (req
); break;
3803 case send_bpf
: /* Do nothing for send_bpf */ break;
3805 // These are all operations that work with an existing request_state object
3806 case reg_record_request
: err
= handle_regrecord_request (req
); break;
3807 case add_record_request
: err
= handle_add_request (req
); break;
3808 case update_record_request
: err
= handle_update_request (req
); break;
3809 case remove_record_request
: err
= handle_removerecord_request(req
); break;
3810 case cancel_request
: handle_cancel_request (req
); break;
3811 default: LogMsg("%3d: ERROR: Unsupported UDS req: %d", req
->sd
, req
->hdr
.op
);
3814 // req->msgbuf may be NULL, e.g. for connection_request or remove_record_request
3815 if (req
->msgbuf
) freeL("request_state msgbuf", req
->msgbuf
);
3817 // There's no return data for a cancel request (DNSServiceRefDeallocate returns no result)
3818 // For a DNSServiceGetProperty call, the handler already generated the response, so no need to do it again here
3819 if (req
->hdr
.op
!= cancel_request
&& req
->hdr
.op
!= getproperty_request
&& req
->hdr
.op
!= send_bpf
)
3821 const mStatus err_netorder
= dnssd_htonl(err
);
3822 send_all(req
->errsd
, (const char *)&err_netorder
, sizeof(err_netorder
));
3823 if (req
->errsd
!= req
->sd
)
3825 LogOperation("%3d: Error socket %d closed %08X %08X (%d)",
3826 req
->sd
, req
->errsd
, req
->hdr
.client_context
.u32
[1], req
->hdr
.client_context
.u32
[0], err
);
3827 dnssd_close(req
->errsd
);
3828 req
->errsd
= req
->sd
;
3829 // Also need to reset the parent's errsd, if this is a subordinate operation
3830 if (req
->primary
) req
->primary
->errsd
= req
->primary
->sd
;
3834 // Reset ready to accept the next req on this pipe
3835 if (req
->primary
) req
= req
->primary
;
3836 req
->ts
= t_morecoming
;
3838 req
->data_bytes
= 0;
3839 req
->msgbuf
= mDNSNULL
;
3840 req
->msgptr
= mDNSNULL
;
3844 mDNSlocal
void connect_callback(int fd
, short filter
, void *info
)
3846 dnssd_sockaddr_t cliaddr
;
3847 dnssd_socklen_t len
= (dnssd_socklen_t
) sizeof(cliaddr
);
3848 dnssd_sock_t sd
= accept(fd
, (struct sockaddr
*) &cliaddr
, &len
);
3849 #if defined(SO_NOSIGPIPE) || defined(_WIN32)
3850 const unsigned long optval
= 1;
3853 (void)filter
; // Unused
3854 (void)info
; // Unused
3856 if (!dnssd_SocketValid(sd
))
3858 if (dnssd_errno
!= dnssd_EWOULDBLOCK
) my_perror("ERROR: accept");
3863 // Some environments (e.g. OS X) support turning off SIGPIPE for a socket
3864 if (setsockopt(sd
, SOL_SOCKET
, SO_NOSIGPIPE
, &optval
, sizeof(optval
)) < 0)
3865 LogMsg("%3d: WARNING: setsockopt - SO_NOSIGPIPE %d (%s)", sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
3869 if (ioctlsocket(sd
, FIONBIO
, &optval
) != 0)
3871 if (fcntl(sd
, F_SETFL
, fcntl(sd
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3874 my_perror("ERROR: fcntl(sd, F_SETFL, O_NONBLOCK) - aborting client");
3880 request_state
*request
= NewRequest();
3881 request
->ts
= t_morecoming
;
3883 request
->errsd
= sd
;
3884 #if APPLE_OSX_mDNSResponder
3886 socklen_t xucredlen
= sizeof(x
);
3887 if (getsockopt(sd
, 0, LOCAL_PEERCRED
, &x
, &xucredlen
) >= 0 && x
.cr_version
== XUCRED_VERSION
) request
->uid
= x
.cr_uid
;
3888 else my_perror("ERROR: getsockopt, LOCAL_PEERCRED");
3889 debugf("LOCAL_PEERCRED %d %u %u %d", xucredlen
, x
.cr_version
, x
.cr_uid
, x
.cr_ngroups
);
3890 #endif // APPLE_OSX_mDNSResponder
3891 LogOperation("%3d: Adding FD for uid %u", request
->sd
, request
->uid
);
3892 udsSupportAddFDToEventLoop(sd
, request_callback
, request
);
3896 mDNSlocal mDNSBool
uds_socket_setup(dnssd_sock_t skt
)
3898 #if defined(SO_NP_EXTENSIONS)
3899 struct so_np_extensions sonpx
;
3900 socklen_t optlen
= sizeof(struct so_np_extensions
);
3901 sonpx
.npx_flags
= SONPX_SETOPTSHUT
;
3902 sonpx
.npx_mask
= SONPX_SETOPTSHUT
;
3903 if (setsockopt(skt
, SOL_SOCKET
, SO_NP_EXTENSIONS
, &sonpx
, optlen
) < 0)
3904 my_perror("WARNING: could not set sockopt - SO_NP_EXTENSIONS");
3907 // SEH: do we even need to do this on windows?
3908 // This socket will be given to WSAEventSelect which will automatically set it to non-blocking
3910 if (ioctlsocket(skt
, FIONBIO
, &opt
) != 0)
3912 if (fcntl(skt
, F_SETFL
, fcntl(skt
, F_GETFL
, 0) | O_NONBLOCK
) != 0)
3915 my_perror("ERROR: could not set listen socket to non-blocking mode");
3919 if (listen(skt
, LISTENQ
) != 0)
3921 my_perror("ERROR: could not listen on listen socket");
3925 if (mStatus_NoError
!= udsSupportAddFDToEventLoop(skt
, connect_callback
, (void *) NULL
))
3927 my_perror("ERROR: could not add listen socket to event loop");
3930 else LogOperation("%3d: Listening for incoming Unix Domain Socket client requests", skt
);
3935 mDNSexport
int udsserver_init(dnssd_sock_t skts
[], mDNSu32 count
)
3937 dnssd_sockaddr_t laddr
;
3944 LogInfo("udsserver_init");
3946 // If a particular platform wants to opt out of having a PID file, define PID_FILE to be ""
3949 FILE *fp
= fopen(PID_FILE
, "w");
3952 fprintf(fp
, "%d\n", getpid());
3959 for (i
= 0; i
< count
; i
++)
3960 if (dnssd_SocketValid(skts
[i
]) && !uds_socket_setup(skts
[i
]))
3965 listenfd
= socket(AF_DNSSD
, SOCK_STREAM
, 0);
3966 if (!dnssd_SocketValid(listenfd
))
3968 my_perror("ERROR: socket(AF_DNSSD, SOCK_STREAM, 0); failed");
3972 mDNSPlatformMemZero(&laddr
, sizeof(laddr
));
3974 #if defined(USE_TCP_LOOPBACK)
3976 laddr
.sin_family
= AF_INET
;
3977 laddr
.sin_port
= htons(MDNS_TCP_SERVERPORT
);
3978 laddr
.sin_addr
.s_addr
= inet_addr(MDNS_TCP_SERVERADDR
);
3979 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
3982 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
3988 mode_t mask
= umask(0);
3989 unlink(MDNS_UDS_SERVERPATH
); // OK if this fails
3990 laddr
.sun_family
= AF_LOCAL
;
3991 #ifndef NOT_HAVE_SA_LEN
3992 // According to Stevens (section 3.2), there is no portable way to
3993 // determine whether sa_len is defined on a particular platform.
3994 laddr
.sun_len
= sizeof(struct sockaddr_un
);
3996 mDNSPlatformStrCopy(laddr
.sun_path
, MDNS_UDS_SERVERPATH
);
3997 ret
= bind(listenfd
, (struct sockaddr
*) &laddr
, sizeof(laddr
));
4001 my_perror("ERROR: bind(listenfd, (struct sockaddr *) &laddr, sizeof(laddr)); failed");
4007 if (!uds_socket_setup(listenfd
)) goto error
;
4010 #if !defined(PLATFORM_NO_RLIMIT)
4012 // Set maximum number of open file descriptors
4013 #define MIN_OPENFILES 10240
4014 struct rlimit maxfds
, newfds
;
4016 // Due to bugs in OS X (<rdar://problem/2941095>, <rdar://problem/3342704>, <rdar://problem/3839173>)
4017 // you have to get and set rlimits once before getrlimit will return sensible values
4018 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4019 if (setrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4021 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4022 newfds
.rlim_max
= (maxfds
.rlim_max
> MIN_OPENFILES
) ? maxfds
.rlim_max
: MIN_OPENFILES
;
4023 newfds
.rlim_cur
= (maxfds
.rlim_cur
> MIN_OPENFILES
) ? maxfds
.rlim_cur
: MIN_OPENFILES
;
4024 if (newfds
.rlim_max
!= maxfds
.rlim_max
|| newfds
.rlim_cur
!= maxfds
.rlim_cur
)
4025 if (setrlimit(RLIMIT_NOFILE
, &newfds
) < 0) my_perror("ERROR: Unable to set maximum file descriptor limit");
4027 if (getrlimit(RLIMIT_NOFILE
, &maxfds
) < 0) { my_perror("ERROR: Unable to get file descriptor limit"); return 0; }
4028 debugf("maxfds.rlim_max %d", (long)maxfds
.rlim_max
);
4029 debugf("maxfds.rlim_cur %d", (long)maxfds
.rlim_cur
);
4033 // We start a "LocalOnly" query looking for Automatic Browse Domain records.
4034 // When Domain Enumeration in uDNS.c finds an "lb" record from the network, it creates a
4035 // "LocalOnly" record, which results in our AutomaticBrowseDomainChange callback being invoked
4036 mDNS_GetDomains(&mDNSStorage
, &mDNSStorage
.AutomaticBrowseDomainQ
, mDNS_DomainTypeBrowseAutomatic
,
4037 mDNSNULL
, mDNSInterface_LocalOnly
, AutomaticBrowseDomainChange
, mDNSNULL
);
4039 // Add "local" as recommended registration domain ("dns-sd -E"), recommended browsing domain ("dns-sd -F"), and automatic browsing domain
4040 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeRegistration
);
4041 RegisterLocalOnlyDomainEnumPTR(&mDNSStorage
, &localdomain
, mDNS_DomainTypeBrowse
);
4042 AddAutoBrowseDomain(0, &localdomain
);
4044 udsserver_handle_configchange(&mDNSStorage
);
4049 my_perror("ERROR: udsserver_init");
4053 mDNSexport
int udsserver_exit(void)
4055 // If the launching environment created no listening socket,
4056 // that means we created it ourselves, so we should clean it up on exit
4057 if (dnssd_SocketValid(listenfd
))
4059 dnssd_close(listenfd
);
4060 #if !defined(USE_TCP_LOOPBACK)
4061 // Currently, we're unable to remove /var/run/mdnsd because we've changed to userid "nobody"
4062 // to give up unnecessary privilege, but we need to be root to remove this Unix Domain Socket.
4063 // It would be nice if we could find a solution to this problem
4064 if (unlink(MDNS_UDS_SERVERPATH
))
4065 debugf("Unable to remove %s", MDNS_UDS_SERVERPATH
);
4069 if (PID_FILE
[0]) unlink(PID_FILE
);
4074 mDNSlocal
void LogClientInfo(mDNS
*const m
, request_state
*req
)
4076 if (!req
->terminate
)
4077 LogMsgNoIdent("%3d: No operation yet on this socket", req
->sd
);
4078 else if (req
->terminate
== connection_termination
)
4080 registered_record_entry
*p
;
4081 LogMsgNoIdent("%3d: DNSServiceCreateConnection", req
->sd
);
4082 for (p
= req
->u
.reg_recs
; p
; p
=p
->next
)
4083 LogMsgNoIdent(" -> DNSServiceRegisterRecord %3d %s", p
->key
, ARDisplayString(m
, p
->rr
));
4085 else if (req
->terminate
== regservice_termination_callback
)
4087 service_instance
*ptr
;
4088 for (ptr
= req
->u
.servicereg
.instances
; ptr
; ptr
= ptr
->next
)
4089 LogMsgNoIdent("%3d: DNSServiceRegister %##s %u/%u",
4090 req
->sd
, ptr
->srs
.RR_SRV
.resrec
.name
->c
, mDNSVal16(req
->u
.servicereg
.port
), SRS_PORT(&ptr
->srs
));
4092 else if (req
->terminate
== browse_termination_callback
)
4095 for (blist
= req
->u
.browser
.browsers
; blist
; blist
= blist
->next
)
4096 LogMsgNoIdent("%3d: DNSServiceBrowse %##s", req
->sd
, blist
->q
.qname
.c
);
4098 else if (req
->terminate
== resolve_termination_callback
)
4099 LogMsgNoIdent("%3d: DNSServiceResolve %##s", req
->sd
, req
->u
.resolve
.qsrv
.qname
.c
);
4100 else if (req
->terminate
== queryrecord_termination_callback
)
4101 LogMsgNoIdent("%3d: DNSServiceQueryRecord %##s (%s)", req
->sd
, req
->u
.queryrecord
.q
.qname
.c
, DNSTypeName(req
->u
.queryrecord
.q
.qtype
));
4102 else if (req
->terminate
== enum_termination_callback
)
4103 LogMsgNoIdent("%3d: DNSServiceEnumerateDomains %##s", req
->sd
, req
->u
.enumeration
.q_all
.qname
.c
);
4104 else if (req
->terminate
== port_mapping_termination_callback
)
4105 LogMsgNoIdent("%3d: DNSServiceNATPortMapping %.4a %s%s Int %d Req %d Ext %d Req TTL %d Granted TTL %d",
4107 &req
->u
.pm
.NATinfo
.ExternalAddress
,
4108 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapTCP
? "TCP" : " ",
4109 req
->u
.pm
.NATinfo
.Protocol
& NATOp_MapUDP
? "UDP" : " ",
4110 mDNSVal16(req
->u
.pm
.NATinfo
.IntPort
),
4111 mDNSVal16(req
->u
.pm
.ReqExt
),
4112 mDNSVal16(req
->u
.pm
.NATinfo
.ExternalPort
),
4113 req
->u
.pm
.NATinfo
.NATLease
,
4114 req
->u
.pm
.NATinfo
.Lifetime
);
4115 else if (req
->terminate
== addrinfo_termination_callback
)
4116 LogMsgNoIdent("%3d: DNSServiceGetAddrInfo %s%s %##s", req
->sd
,
4117 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv4
? "v4" : " ",
4118 req
->u
.addrinfo
.protocol
& kDNSServiceProtocol_IPv6
? "v6" : " ",
4119 req
->u
.addrinfo
.q4
.qname
.c
);
4121 LogMsgNoIdent("%3d: Unrecognized operation %p", req
->sd
, req
->terminate
);
4124 mDNSlocal
void LogAuthRecords(mDNS
*const m
, const mDNSs32 now
, AuthRecord
*ResourceRecords
, int *proxy
)
4126 if (!ResourceRecords
) LogMsgNoIdent("<None>");
4129 const AuthRecord
*ar
;
4130 mDNSEthAddr owner
= zeroEthAddr
;
4131 LogMsgNoIdent(" Int Next Expire State");
4132 for (ar
= ResourceRecords
; ar
; ar
=ar
->next
)
4134 NetworkInterfaceInfo
*info
= (NetworkInterfaceInfo
*)ar
->resrec
.InterfaceID
;
4135 if (ar
->WakeUp
.HMAC
.l
[0]) (*proxy
)++;
4136 if (!mDNSSameEthAddress(&owner
, &ar
->WakeUp
.HMAC
))
4138 owner
= ar
->WakeUp
.HMAC
;
4139 if (ar
->WakeUp
.password
.l
[0])
4140 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
);
4141 else if (!mDNSSameEthAddress(&ar
->WakeUp
.HMAC
, &ar
->WakeUp
.IMAC
))
4142 LogMsgNoIdent("Proxying for H-MAC %.6a I-MAC %.6a seq %d", &ar
->WakeUp
.HMAC
, &ar
->WakeUp
.IMAC
, ar
->WakeUp
.seq
);
4144 LogMsgNoIdent("Proxying for %.6a seq %d", &ar
->WakeUp
.HMAC
, ar
->WakeUp
.seq
);
4146 if (AuthRecord_uDNS(ar
))
4147 LogMsgNoIdent("%7d %7d %7d %7d %s",
4148 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4149 (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
4150 ar
->expire
? (ar
->expire
- now
) / mDNSPlatformOneSecond
: 0,
4151 ar
->state
, ARDisplayString(m
, ar
));
4152 else if (ar
->resrec
.InterfaceID
!= mDNSInterface_LocalOnly
)
4153 LogMsgNoIdent("%7d %7d %7d %7s %s",
4154 ar
->ThisAPInterval
/ mDNSPlatformOneSecond
,
4155 ar
->AnnounceCount
? (ar
->LastAPTime
+ ar
->ThisAPInterval
- now
) / mDNSPlatformOneSecond
: 0,
4156 ar
->TimeExpire
? (ar
->TimeExpire
- now
) / mDNSPlatformOneSecond
: 0,
4157 info
? info
->ifname
: "ALL",
4158 ARDisplayString(m
, ar
));
4160 LogMsgNoIdent(" LO %s", ARDisplayString(m
, ar
));
4161 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4166 mDNSexport
void udsserver_info(mDNS
*const m
)
4168 const mDNSs32 now
= mDNS_TimeNow(m
);
4169 mDNSu32 CacheUsed
= 0, CacheActive
= 0, slot
;
4170 int ProxyA
= 0, ProxyD
= 0;
4171 const CacheGroup
*cg
;
4172 const CacheRecord
*cr
;
4173 const DNSQuestion
*q
;
4174 const DNameListElem
*d
;
4176 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
4177 LogMsgNoIdent("------------ Cache -------------");
4179 LogMsgNoIdent("Slt Q TTL if U Type rdlen");
4180 for (slot
= 0; slot
< CACHE_HASH_SLOTS
; slot
++)
4181 for (cg
= m
->rrcache_hash
[slot
]; cg
; cg
=cg
->next
)
4183 CacheUsed
++; // Count one cache entity for the CacheGroup object
4184 for (cr
= cg
->members
; cr
; cr
=cr
->next
)
4186 mDNSs32 remain
= cr
->resrec
.rroriginalttl
- (now
- cr
->TimeRcvd
) / mDNSPlatformOneSecond
;
4187 NetworkInterfaceInfo
*info
= (NetworkInterfaceInfo
*)cr
->resrec
.InterfaceID
;
4189 if (cr
->CRActiveQuestion
) CacheActive
++;
4190 LogMsgNoIdent("%3d %s%8ld %-7s%s %-6s%s",
4192 cr
->CRActiveQuestion
? "*" : " ",
4194 info
? info
->ifname
: "-U-",
4195 (cr
->resrec
.RecordType
== kDNSRecordTypePacketNegative
) ? "-" :
4196 (cr
->resrec
.RecordType
& kDNSRecordTypePacketUniqueMask
) ? " " : "+",
4197 DNSTypeName(cr
->resrec
.rrtype
),
4198 CRDisplayString(m
, cr
));
4199 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4203 if (m
->rrcache_totalused
!= CacheUsed
)
4204 LogMsgNoIdent("Cache use mismatch: rrcache_totalused is %lu, true count %lu", m
->rrcache_totalused
, CacheUsed
);
4205 if (m
->rrcache_active
!= CacheActive
)
4206 LogMsgNoIdent("Cache use mismatch: rrcache_active is %lu, true count %lu", m
->rrcache_active
, CacheActive
);
4207 LogMsgNoIdent("Cache currently contains %lu entities; %lu referenced by active questions", CacheUsed
, CacheActive
);
4209 LogMsgNoIdent("--------- Auth Records ---------");
4210 LogAuthRecords(m
, now
, m
->ResourceRecords
, &ProxyA
);
4212 LogMsgNoIdent("------ Duplicate Records -------");
4213 LogAuthRecords(m
, now
, m
->DuplicateRecords
, &ProxyD
);
4215 LogMsgNoIdent("----- ServiceRegistrations -----");
4216 if (!m
->ServiceRegistrations
) LogMsgNoIdent("<None>");
4219 ServiceRecordSet
*s
;
4220 LogMsgNoIdent(" Int Next Expire State");
4221 for (s
= m
->ServiceRegistrations
; s
; s
= s
->uDNS_next
)
4222 LogMsgNoIdent("%7d %7d %7d %7d %s",
4223 s
->RR_SRV
.ThisAPInterval
/ mDNSPlatformOneSecond
,
4224 (s
->RR_SRV
.LastAPTime
+ s
->RR_SRV
.ThisAPInterval
- now
) / mDNSPlatformOneSecond
,
4225 s
->RR_SRV
.expire
? (s
->RR_SRV
.expire
- now
) / mDNSPlatformOneSecond
: 0,
4226 s
->state
, ARDisplayString(m
, &s
->RR_SRV
));
4229 LogMsgNoIdent("---------- Questions -----------");
4230 if (!m
->Questions
) LogMsgNoIdent("<None>");
4235 LogMsgNoIdent(" Int Next if T NumAns Type Name");
4236 for (q
= m
->Questions
; q
; q
=q
->next
)
4238 mDNSs32 i
= q
->ThisQInterval
/ mDNSPlatformOneSecond
;
4239 mDNSs32 n
= (q
->LastQTime
+ q
->ThisQInterval
- now
) / mDNSPlatformOneSecond
;
4240 NetworkInterfaceInfo
*info
= (NetworkInterfaceInfo
*)q
->InterfaceID
;
4242 if (q
->ThisQInterval
) CacheActive
++;
4243 LogMsgNoIdent("%6d%6d %-7s%s%s %5d %-6s%##s%s",
4245 info
? info
->ifname
: mDNSOpaque16IsZero(q
->TargetQID
) ? "" : "-U-",
4246 mDNSOpaque16IsZero(q
->TargetQID
) ? (q
->LongLived
? "l" : " ") : (q
->LongLived
? "L" : "O"),
4247 q
->AuthInfo
? "P" : " ",
4249 DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
4250 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4252 LogMsgNoIdent("%lu question%s; %lu active", CacheUsed
, CacheUsed
> 1 ? "s" : "", CacheActive
);
4255 LogMsgNoIdent("----- Local-Only Questions -----");
4256 if (!m
->LocalOnlyQuestions
) LogMsgNoIdent("<None>");
4257 else for (q
= m
->LocalOnlyQuestions
; q
; q
=q
->next
)
4258 LogMsgNoIdent(" %5d %-6s%##s%s",
4259 q
->CurrentAnswers
, DNSTypeName(q
->qtype
), q
->qname
.c
, q
->DuplicateOf
? " (dup)" : "");
4261 LogMsgNoIdent("---- Active Client Requests ----");
4262 if (!all_requests
) LogMsgNoIdent("<None>");
4266 for (req
= all_requests
; req
; req
=req
->next
)
4267 LogClientInfo(m
, req
);
4268 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4271 LogMsgNoIdent("-------- NAT Traversals --------");
4272 if (!m
->NATTraversals
) LogMsgNoIdent("<None>");
4275 NATTraversalInfo
*nat
;
4276 for (nat
= m
->NATTraversals
; nat
; nat
=nat
->next
)
4279 LogMsgNoIdent("%p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d",
4280 nat
, nat
->Protocol
== NATOp_MapTCP
? "TCP" : "UDP",
4281 mDNSVal16(nat
->IntPort
), mDNSVal16(nat
->ExternalPort
), nat
->Result
,
4282 nat
->retryPortMap
? (nat
->retryPortMap
- now
) / mDNSPlatformOneSecond
: 0,
4283 nat
->retryInterval
/ mDNSPlatformOneSecond
,
4284 nat
->ExpiryTime
? (nat
->ExpiryTime
- now
) / mDNSPlatformOneSecond
: 0);
4286 LogMsgNoIdent("%p Address Request Retry %5d Interval %5d", nat
,
4287 (m
->retryGetAddr
- now
) / mDNSPlatformOneSecond
,
4288 m
->retryIntervalGetAddr
/ mDNSPlatformOneSecond
);
4289 usleep((m
->KnownBugs
& mDNS_KnownBug_LossySyslog
) ? 3333 : 1000);
4293 LogMsgNoIdent("--------- AuthInfoList ---------");
4294 if (!m
->AuthInfoList
) LogMsgNoIdent("<None>");
4298 for (a
= m
->AuthInfoList
; a
; a
= a
->next
)
4299 LogMsgNoIdent("%##s %##s%s", a
->domain
.c
, a
->keyname
.c
, a
->AutoTunnel
? " AutoTunnel" : "");
4302 #if APPLE_OSX_mDNSResponder
4303 LogMsgNoIdent("--------- TunnelClients --------");
4304 if (!m
->TunnelClients
) LogMsgNoIdent("<None>");
4308 for (c
= m
->TunnelClients
; c
; c
= c
->next
)
4309 LogMsgNoIdent("%##s local %.16a %.4a remote %.16a %.4a %5d interval %d",
4310 c
->dstname
.c
, &c
->loc_inner
, &c
->loc_outer
, &c
->rmt_inner
, &c
->rmt_outer
, mDNSVal16(c
->rmt_outer_port
), c
->q
.ThisQInterval
);
4312 #endif // APPLE_OSX_mDNSResponder
4314 LogMsgNoIdent("---------- Misc State ----------");
4316 LogMsgNoIdent("PrimaryMAC: %.6a", &m
->PrimaryMAC
);
4318 LogMsgNoIdent("m->SleepState %d (%s) seq %d",
4320 m
->SleepState
== SleepState_Awake
? "Awake" :
4321 m
->SleepState
== SleepState_Transferring
? "Transferring" :
4322 m
->SleepState
== SleepState_Sleeping
? "Sleeping" : "?",
4325 if (!m
->SPSSocket
) LogMsgNoIdent("Not offering Sleep Proxy Service");
4326 else LogMsgNoIdent("Offering Sleep Proxy Service: %#s", m
->SPSRecords
.RR_SRV
.resrec
.name
->c
);
4328 if (m
->ProxyRecords
== ProxyA
+ ProxyD
) LogMsgNoIdent("ProxyRecords: %d + %d = %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
);
4329 else LogMsgNoIdent("ProxyRecords: MISMATCH %d + %d = %d ≠ %d", ProxyA
, ProxyD
, ProxyA
+ ProxyD
, m
->ProxyRecords
);
4331 LogMsgNoIdent("------ Auto Browse Domains -----");
4332 if (!AutoBrowseDomains
) LogMsgNoIdent("<None>");
4333 else for (d
=AutoBrowseDomains
; d
; d
=d
->next
) LogMsgNoIdent("%##s", d
->name
.c
);
4335 LogMsgNoIdent("--- Auto Registration Domains --");
4336 if (!AutoRegistrationDomains
) LogMsgNoIdent("<None>");
4337 else for (d
=AutoRegistrationDomains
; d
; d
=d
->next
) LogMsgNoIdent("%##s", d
->name
.c
);
4340 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4341 mDNSexport
void uds_validatelists(void)
4343 const request_state
*req
, *p
;
4344 for (req
= all_requests
; req
; req
=req
->next
)
4346 if (req
->next
== (request_state
*)~0 || (req
->sd
< 0 && req
->sd
!= -2))
4347 LogMemCorruption("UDS request list: %p is garbage (%d)", req
, req
->sd
);
4349 if (req
->primary
== req
)
4350 LogMemCorruption("UDS request list: req->primary should not point to self %p/%d", req
, req
->sd
);
4352 if (req
->primary
&& req
->replies
)
4353 LogMemCorruption("UDS request list: Subordinate request %p/%d/%p should not have replies (%p)",
4354 req
, req
->sd
, req
->primary
&& req
->replies
);
4358 LogMemCorruption("UDS request list: req %p primary %p is misaligned (%d)", req
, p
, req
->sd
);
4359 else if (p
&& (p
->next
== (request_state
*)~0 || (p
->sd
< 0 && p
->sd
!= -2)))
4360 LogMemCorruption("UDS request list: req %p primary %p is garbage (%d)", req
, p
, p
->sd
);
4363 for (rep
= req
->replies
; rep
; rep
=rep
->next
)
4364 if (rep
->next
== (reply_state
*)~0)
4365 LogMemCorruption("UDS req->replies: %p is garbage", rep
);
4367 if (req
->terminate
== connection_termination
)
4369 registered_record_entry
*r
;
4370 for (r
= req
->u
.reg_recs
; r
; r
=r
->next
)
4371 if (r
->next
== (registered_record_entry
*)~0)
4372 LogMemCorruption("UDS req->u.reg_recs: %p is garbage", r
);
4374 else if (req
->terminate
== regservice_termination_callback
)
4376 service_instance
*s
;
4377 for (s
= req
->u
.servicereg
.instances
; s
; s
=s
->next
)
4378 if (s
->next
== (service_instance
*)~0)
4379 LogMemCorruption("UDS req->u.servicereg.instances: %p is garbage", s
);
4381 else if (req
->terminate
== browse_termination_callback
)
4384 for (b
= req
->u
.browser
.browsers
; b
; b
=b
->next
)
4385 if (b
->next
== (browser_t
*)~0)
4386 LogMemCorruption("UDS req->u.browser.browsers: %p is garbage", b
);
4391 for (d
= SCPrefBrowseDomains
; d
; d
=d
->next
)
4392 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
4393 LogMemCorruption("SCPrefBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
4396 for (b
= LocalDomainEnumRecords
; b
; b
=b
->next
)
4397 if (b
->next
== (ARListElem
*)~0 || b
->ar
.resrec
.name
->c
[0] > 63)
4398 LogMemCorruption("LocalDomainEnumRecords: %p is garbage (%d)", b
, b
->ar
.resrec
.name
->c
[0]);
4400 for (d
= AutoBrowseDomains
; d
; d
=d
->next
)
4401 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
4402 LogMemCorruption("AutoBrowseDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
4404 for (d
= AutoRegistrationDomains
; d
; d
=d
->next
)
4405 if (d
->next
== (DNameListElem
*)~0 || d
->name
.c
[0] > 63)
4406 LogMemCorruption("AutoRegistrationDomains: %p is garbage (%d)", d
, d
->name
.c
[0]);
4408 #endif // APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
4410 mDNSlocal
int send_msg(request_state
*const req
)
4412 reply_state
*const rep
= req
->replies
; // Send the first waiting reply
4414 if (req
->no_reply
) return(t_complete
);
4416 ConvertHeaderBytes(rep
->mhdr
);
4417 nwriten
= send(req
->sd
, (char *)&rep
->mhdr
+ rep
->nwriten
, rep
->totallen
- rep
->nwriten
, 0);
4418 ConvertHeaderBytes(rep
->mhdr
);
4422 if (dnssd_errno
== dnssd_EINTR
|| dnssd_errno
== dnssd_EWOULDBLOCK
) nwriten
= 0;
4425 #if !defined(PLATFORM_NO_EPIPE)
4426 if (dnssd_errno
== EPIPE
)
4427 return(req
->ts
= t_terminated
);
4431 LogMsg("send_msg ERROR: failed to write %d of %d bytes to fd %d errno %d (%s)",
4432 rep
->totallen
- rep
->nwriten
, rep
->totallen
, req
->sd
, dnssd_errno
, dnssd_strerror(dnssd_errno
));
4437 rep
->nwriten
+= nwriten
;
4438 return (rep
->nwriten
== rep
->totallen
) ? t_complete
: t_morecoming
;
4441 mDNSexport mDNSs32
udsserver_idle(mDNSs32 nextevent
)
4443 mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
4444 request_state
**req
= &all_requests
;
4448 request_state
*const r
= *req
;
4450 if (r
->terminate
== resolve_termination_callback
)
4451 if (r
->u
.resolve
.ReportTime
&& now
- r
->u
.resolve
.ReportTime
>= 0)
4453 r
->u
.resolve
.ReportTime
= 0;
4454 LogMsgNoIdent("Client application bug: DNSServiceResolve(%##s) active for over two minutes. "
4455 "This places considerable burden on the network.", r
->u
.resolve
.qsrv
.qname
.c
);
4458 // Note: Only primary req's have reply lists, not subordinate req's.
4459 while (r
->replies
) // Send queued replies
4461 transfer_state result
;
4462 if (r
->replies
->next
) r
->replies
->rhdr
->flags
|= dnssd_htonl(kDNSServiceFlagsMoreComing
);
4463 result
= send_msg(r
); // Returns t_morecoming if buffer full because client is not reading
4464 if (result
== t_complete
)
4466 reply_state
*fptr
= r
->replies
;
4467 r
->replies
= r
->replies
->next
;
4468 freeL("reply_state/udsserver_idle", fptr
);
4469 r
->time_blocked
= 0; // reset failure counter after successful send
4472 else if (result
== t_terminated
|| result
== t_error
)
4474 LogMsg("%3d: Could not write data to client because of error - aborting connection", r
->sd
);
4475 LogClientInfo(&mDNSStorage
, r
);
4481 if (r
->replies
) // If we failed to send everything, check our time_blocked timer
4483 if (!r
->time_blocked
) r
->time_blocked
= NonZeroTime(now
);
4484 if (now
- r
->time_blocked
>= 60 * mDNSPlatformOneSecond
)
4486 LogMsg("%3d: Could not write data to client after %ld seconds - aborting connection", r
->sd
,
4487 (now
- r
->time_blocked
) / mDNSPlatformOneSecond
);
4488 LogClientInfo(&mDNSStorage
, r
);
4491 else if (nextevent
- now
> mDNSPlatformOneSecond
) nextevent
= now
+ mDNSPlatformOneSecond
;
4494 if (!dnssd_SocketValid(r
->sd
)) // If this request is finished, unlink it from the list and free the memory
4496 // Since we're already doing a list traversal, we unlink the request directly instead of using AbortUnlinkAndFree()
4498 freeL("request_state/udsserver_idle", r
);
4506 struct CompileTimeAssertionChecks_uds_daemon
4508 // Check our structures are reasonable sizes. Including overly-large buffers, or embedding
4509 // other overly-large structures instead of having a pointer to them, can inadvertently
4510 // cause structure sizes (and therefore memory usage) to balloon unreasonably.
4511 char sizecheck_request_state
[(sizeof(request_state
) <= 1760) ? 1 : -1];
4512 char sizecheck_registered_record_entry
[(sizeof(registered_record_entry
) <= 40) ? 1 : -1];
4513 char sizecheck_service_instance
[(sizeof(service_instance
) <= 6552) ? 1 : -1];
4514 char sizecheck_browser_t
[(sizeof(browser_t
) <= 992) ? 1 : -1];
4515 char sizecheck_reply_hdr
[(sizeof(reply_hdr
) <= 12) ? 1 : -1];
4516 char sizecheck_reply_state
[(sizeof(reply_state
) <= 64) ? 1 : -1];