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