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