]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/daemon.c
mDNSResponder-1096.40.7.tar.gz
[apple/mdnsresponder.git] / mDNSMacOSX / daemon.c
1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil -*-
2 *
3 * Copyright (c) 2002-2019 Apple Inc. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #include <mach/mach.h>
19 #include <mach/mach_error.h>
20 #include <sys/types.h>
21 #include <errno.h>
22 #include <signal.h>
23 #include <unistd.h>
24 #include <paths.h>
25 #include <fcntl.h>
26 #include <launch.h>
27 #include <launch_priv.h> // for launch_socket_service_check_in()
28 #include <pwd.h>
29 #include <sys/event.h>
30 #include <pthread.h>
31 #include <sandbox.h>
32 #include <SystemConfiguration/SCDynamicStoreCopyDHCPInfo.h>
33 #include <err.h>
34 #include <sysexits.h>
35 #include <TargetConditionals.h>
36
37 #include "uDNS.h"
38 #include "DNSCommon.h"
39 #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
40
41 #include "uds_daemon.h" // Interface to the server side implementation of dns_sd.h
42 #include "xpc_services.h"
43 #include "xpc_service_dns_proxy.h"
44 #include "xpc_service_log_utility.h"
45 #include "helper.h"
46 #include "posix_utilities.h" // for getLocalTimestamp()
47
48 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
49 #include "Metrics.h"
50 #endif
51
52 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSD_XPC_SERVICE)
53 #include "dnssd_server.h"
54 #endif
55
56 // Used on OSX(10.11.x onwards) for manipulating mDNSResponder program arguments
57 #if APPLE_OSX_mDNSResponder
58 // plist file to read the user's preferences
59 #define kProgramArguments CFSTR("com.apple.mDNSResponder")
60 // possible arguments for external customers
61 #define kPreferencesKey_DebugLogging CFSTR("DebugLogging")
62 #define kPreferencesKey_UnicastPacketLogging CFSTR("UnicastPacketLogging")
63 #define kPreferencesKey_AlwaysAppendSearchDomains CFSTR("AlwaysAppendSearchDomains")
64 #define kPreferencesKey_EnableAllowExpired CFSTR("EnableAllowExpired")
65 #define kPreferencesKey_NoMulticastAdvertisements CFSTR("NoMulticastAdvertisements")
66 #define kPreferencesKey_StrictUnicastOrdering CFSTR("StrictUnicastOrdering")
67 #define kPreferencesKey_OfferSleepProxyService CFSTR("OfferSleepProxyService")
68 #define kPreferencesKey_UseInternalSleepProxy CFSTR("UseInternalSleepProxy")
69
70 #if ENABLE_BLE_TRIGGERED_BONJOUR
71 #define kPreferencesKey_EnableBLEBasedDiscovery CFSTR("EnableBLEBasedDiscovery")
72 #define kPreferencesKey_DefaultToBLETriggered CFSTR("DefaultToBLETriggered")
73 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
74
75 #if MDNSRESPONDER_SUPPORTS(APPLE, PREALLOCATED_CACHE)
76 #define kPreferencesKey_PreallocateCacheMemory CFSTR("PreallocateCacheMemory")
77 #endif
78 #endif
79
80 //*************************************************************************************************************
81 #if COMPILER_LIKES_PRAGMA_MARK
82 #pragma mark - Globals
83 #endif
84
85 static mDNS_PlatformSupport PlatformStorage;
86
87 // Start off with a default cache of 32K (136 records of 240 bytes each)
88 // Each time we grow the cache we add another 136 records
89 // 136 * 240 = 32640 bytes.
90 // This fits in eight 4kB pages, with 128 bytes spare for memory block headers and similar overhead
91 #define RR_CACHE_SIZE ((32*1024) / sizeof(CacheRecord))
92 static CacheEntity rrcachestorage[RR_CACHE_SIZE];
93 struct CompileTimeAssertionChecks_RR_CACHE_SIZE { char a[(RR_CACHE_SIZE >= 136) ? 1 : -1]; };
94 #define kRRCacheGrowSize (sizeof(CacheEntity) * RR_CACHE_SIZE)
95
96
97 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
98 mDNSlocal void PrepareForIdle(void *m_param);
99 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
100 static mach_port_t signal_port = MACH_PORT_NULL;
101 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
102
103 static dnssd_sock_t *launchd_fds = mDNSNULL;
104 static size_t launchd_fds_count = 0;
105
106 static mDNSBool NoMulticastAdvertisements = mDNSfalse; // By default, advertise addresses (& other records) via multicast
107
108 extern mDNSBool StrictUnicastOrdering;
109 extern mDNSBool AlwaysAppendSearchDomains;
110 extern mDNSBool EnableAllowExpired;
111 mDNSexport void INFOCallback(void);
112 mDNSexport void dump_state_to_fd(int fd);
113
114 #if ENABLE_BLE_TRIGGERED_BONJOUR
115 extern mDNSBool EnableBLEBasedDiscovery;
116 extern mDNSBool DefaultToBLETriggered;
117 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
118
119 #if MDNSRESPONDER_SUPPORTS(APPLE, PREALLOCATED_CACHE)
120 static mDNSBool PreallocateCacheMemory = mDNSfalse;
121 #endif
122
123 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_MEM_LIMIT)
124 #define kRRCacheMemoryLimit 1000000 // For now, we limit the cache to at most 1MB on iOS devices.
125 #endif
126
127 // We keep a list of client-supplied event sources in KQSocketEventSource records
128 typedef struct KQSocketEventSource
129 {
130 struct KQSocketEventSource *next;
131 int fd;
132 KQueueEntry kqs;
133 udsEventCallback callback;
134 void *context;
135 } KQSocketEventSource;
136
137 static KQSocketEventSource *gEventSources;
138
139 //*************************************************************************************************************
140 #if COMPILER_LIKES_PRAGMA_MARK
141 #pragma mark -
142 #pragma mark - General Utility Functions
143 #endif
144
145 #if MDNS_MALLOC_DEBUGGING
146 void mDNSPlatformValidateLists()
147 {
148 mDNS *const m = &mDNSStorage;
149
150 KQSocketEventSource *k;
151 for (k = gEventSources; k; k=k->next)
152 if (k->next == (KQSocketEventSource *)~0 || k->fd < 0)
153 LogMemCorruption("gEventSources: %p is garbage (%d)", k, k->fd);
154
155 // Check platform-layer lists
156 NetworkInterfaceInfoOSX *i;
157 for (i = m->p->InterfaceList; i; i = i->next)
158 if (i->next == (NetworkInterfaceInfoOSX *)~0 || !i->m || i->m == (mDNS *)~0)
159 LogMemCorruption("m->p->InterfaceList: %p is garbage (%p)", i, i->ifinfo.ifname);
160
161 ClientTunnel *t;
162 for (t = m->TunnelClients; t; t=t->next)
163 if (t->next == (ClientTunnel *)~0 || t->dstname.c[0] > 63)
164 LogMemCorruption("m->TunnelClients: %p is garbage (%d)", t, t->dstname.c[0]);
165 }
166 #endif // MDNS_MALLOC_DEBUGGING
167
168 //*************************************************************************************************************
169 // Registration
170
171 mDNSexport void RecordUpdatedNiceLabel(mDNSs32 delay)
172 {
173 mDNSStorage.p->NotifyUser = NonZeroTime(mDNSStorage.timenow + delay);
174 }
175
176 mDNSlocal void mDNSPreferencesSetNames(int key, domainlabel *old, domainlabel *new)
177 {
178 mDNS *const m = &mDNSStorage;
179 domainlabel *prevold, *prevnew;
180 switch (key)
181 {
182 case kmDNSComputerName:
183 case kmDNSLocalHostName:
184 if (key == kmDNSComputerName)
185 {
186 prevold = &m->p->prevoldnicelabel;
187 prevnew = &m->p->prevnewnicelabel;
188 }
189 else
190 {
191 prevold = &m->p->prevoldhostlabel;
192 prevnew = &m->p->prevnewhostlabel;
193 }
194 // There are a few cases where we need to invoke the helper.
195 //
196 // 1. If the "old" label and "new" label are not same, it means there is a conflict. We need
197 // to invoke the helper so that it pops up a dialogue to inform the user about the
198 // conflict
199 //
200 // 2. If the "old" label and "new" label are same, it means the user has set the host/nice label
201 // through the preferences pane. We may have to inform the helper as it may have popped up
202 // a dialogue previously (due to a conflict) and it needs to suppress it now. We can avoid invoking
203 // the helper in this case if the previous values (old and new) that we told helper last time
204 // are same. If the previous old and new values are same, helper does not care.
205 //
206 // Note: "new" can be NULL when we have repeated conflicts and we are asking helper to give up. "old"
207 // is not called with NULL today, but this makes it future proof.
208 if (!old || !new || !SameDomainLabelCS(old->c, new->c) ||
209 !SameDomainLabelCS(old->c, prevold->c) ||
210 !SameDomainLabelCS(new->c, prevnew->c))
211 {
212 // Work around bug radar:21397654
213 #ifndef __clang_analyzer__
214 if (old)
215 *prevold = *old;
216 else
217 prevold->c[0] = 0;
218 if (new)
219 *prevnew = *new;
220 else
221 prevnew->c[0] = 0;
222 #endif
223 mDNSPreferencesSetName(key, old, new);
224 }
225 else
226 {
227 LogInfo("mDNSPreferencesSetNames not invoking helper %s %#s, %s %#s, old %#s, new %#s",
228 (key == kmDNSComputerName ? "prevoldnicelabel" : "prevoldhostlabel"), prevold->c,
229 (key == kmDNSComputerName ? "prevnewnicelabel" : "prevnewhostlabel"), prevnew->c,
230 old->c, new->c);
231 }
232 break;
233 default:
234 LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key);
235 return;
236 }
237 }
238
239 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
240 {
241 if (result == mStatus_NoError)
242 {
243 if (!SameDomainLabelCS(m->p->userhostlabel.c, m->hostlabel.c))
244 LogInfo("Local Hostname changed from \"%#s.local\" to \"%#s.local\"", m->p->userhostlabel.c, m->hostlabel.c);
245 // One second pause in case we get a Computer Name update too -- don't want to alert the user twice
246 RecordUpdatedNiceLabel(mDNSPlatformOneSecond);
247 }
248 else if (result == mStatus_NameConflict)
249 {
250 LogInfo("Local Hostname conflict for \"%#s.local\"", m->hostlabel.c);
251 if (!m->p->HostNameConflict) m->p->HostNameConflict = NonZeroTime(m->timenow);
252 else if (m->timenow - m->p->HostNameConflict > 60 * mDNSPlatformOneSecond)
253 {
254 // Tell the helper we've given up
255 mDNSPreferencesSetNames(kmDNSLocalHostName, &m->p->userhostlabel, NULL);
256 }
257 }
258 else if (result == mStatus_GrowCache)
259 {
260 // Allocate another chunk of cache storage
261 static unsigned int allocated = 0;
262 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_MEM_LIMIT)
263 if (allocated >= kRRCacheMemoryLimit) return; // For now we limit the cache to at most 1MB on iOS devices
264 #endif
265 allocated += kRRCacheGrowSize;
266 // LogMsg("GrowCache %d * %d = %d; total so far %6u", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE, allocated);
267 CacheEntity *storage = mallocL("mStatus_GrowCache", sizeof(CacheEntity) * RR_CACHE_SIZE);
268 //LogInfo("GrowCache %d * %d = %d", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE);
269 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
270 }
271 else if (result == mStatus_ConfigChanged)
272 {
273 // Tell the helper we've seen a change in the labels. It will dismiss the name conflict alert if needed.
274 mDNSPreferencesSetNames(kmDNSComputerName, &m->p->usernicelabel, &m->nicelabel);
275 mDNSPreferencesSetNames(kmDNSLocalHostName, &m->p->userhostlabel, &m->hostlabel);
276
277 // Then we call into the UDS daemon code, to let it do the same
278 udsserver_handle_configchange(m);
279 }
280 }
281
282
283 //*************************************************************************************************************
284 #if COMPILER_LIKES_PRAGMA_MARK
285 #pragma mark -
286 #pragma mark - Startup, shutdown, and supporting code
287 #endif
288
289 mDNSlocal void ExitCallback(int sig)
290 {
291 (void)sig; // Unused
292 LogMsg("%s stopping", mDNSResponderVersionString);
293
294 if (udsserver_exit() < 0)
295 LogMsg("ExitCallback: udsserver_exit failed");
296
297 debugf("ExitCallback: mDNS_StartExit");
298 mDNS_StartExit(&mDNSStorage);
299 }
300
301 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
302
303 // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
304 mDNSlocal void HandleSIG(int sig)
305 {
306 kern_return_t status;
307 mach_msg_header_t header;
308
309 // WARNING: can't call syslog or fprintf from signal handler
310 header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND, 0);
311 header.msgh_remote_port = signal_port;
312 header.msgh_local_port = MACH_PORT_NULL;
313 header.msgh_size = sizeof(header);
314 header.msgh_id = sig;
315
316 status = mach_msg(&header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, header.msgh_size,
317 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
318
319 if (status != MACH_MSG_SUCCESS)
320 {
321 if (status == MACH_SEND_TIMED_OUT) mach_msg_destroy(&header);
322 if (sig == SIGTERM || sig == SIGINT) exit(-1);
323 }
324 }
325
326 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
327
328 mDNSexport void dump_state_to_fd(int fd)
329 {
330 mDNS *const m = &mDNSStorage;
331 char buffer[1024];
332 buffer[0] = '\0';
333
334 mDNSs32 utc = mDNSPlatformUTC();
335 const mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
336 NetworkInterfaceInfoOSX *i;
337 DNSServer *s;
338 McastResolver *mr;
339 char timestamp[64]; // 64 is enough to store the UTC timestmp
340
341 LogToFD(fd, "---- BEGIN STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
342 getLocalTimestamp(timestamp, sizeof(timestamp));
343 LogToFD(fd, "Date: %s", timestamp);
344 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "---- BEGIN STATE LOG ---- (" PUB_S ")", timestamp);
345
346 udsserver_info_dump_to_fd(fd);
347
348 LogToFD(fd, "----- Platform Timers -----");
349 LogTimerToFD(fd, "m->NextCacheCheck ", mDNSStorage.NextCacheCheck);
350 LogTimerToFD(fd, "m->NetworkChanged ", mDNSStorage.NetworkChanged);
351 LogTimerToFD(fd, "m->p->NotifyUser ", mDNSStorage.p->NotifyUser);
352 LogTimerToFD(fd, "m->p->HostNameConflict ", mDNSStorage.p->HostNameConflict);
353 LogTimerToFD(fd, "m->p->KeyChainTimer ", mDNSStorage.p->KeyChainTimer);
354
355 log_dnsproxy_info_to_fd(fd, &mDNSStorage);
356
357 LogToFD(fd, "----- KQSocketEventSources -----");
358 if (!gEventSources) LogToFD(fd, "<None>");
359 else
360 {
361 KQSocketEventSource *k;
362 for (k = gEventSources; k; k=k->next)
363 LogToFD(fd, "%3d %s %s", k->fd, k->kqs.KQtask, k->fd == mDNSStorage.uds_listener_skt ? "Listener for incoming UDS clients" : " ");
364 }
365
366 LogToFD(fd, "------ Network Interfaces ------");
367 if (!mDNSStorage.p->InterfaceList) LogToFD(fd, "<None>");
368 else
369 {
370 LogToFD(fd, " Struct addr Registered MAC BSSID Interface Address");
371 for (i = mDNSStorage.p->InterfaceList; i; i = i->next)
372 {
373 // Allow six characters for interface name, for names like "vmnet8"
374 if (!i->Exists)
375 LogToFD(fd, "%p %2ld, %p, %s %-6s %.6a %.6a %#-14a dormant for %d seconds",
376 i, i->ifinfo.InterfaceID, i->Registered,
377 i->sa_family == AF_INET ? "v4" : i->sa_family == AF_INET6 ? "v6" : "??", i->ifinfo.ifname, &i->ifinfo.MAC, &i->BSSID,
378 &i->ifinfo.ip, utc - i->LastSeen);
379 else
380 {
381 const CacheRecord *sps[3];
382 FindSPSInCache(&mDNSStorage, &i->ifinfo.NetWakeBrowse, sps);
383 LogToFD(fd, "%p %2ld, %p, %s %-6s %.6a %.6a %s %s %s %s %s %s %#a",
384 i, i->ifinfo.InterfaceID, i->Registered,
385 i->sa_family == AF_INET ? "v4" : i->sa_family == AF_INET6 ? "v6" : "??", i->ifinfo.ifname, &i->ifinfo.MAC, &i->BSSID,
386 i->ifinfo.InterfaceActive ? "Active" : " ",
387 i->ifinfo.IPv4Available ? "v4" : " ",
388 i->ifinfo.IPv6Available ? "v6" : " ",
389 i->ifinfo.Advertise ? "A" : " ",
390 i->ifinfo.McastTxRx ? "M" : " ",
391 !(i->ifinfo.InterfaceActive && i->ifinfo.NetWake) ? " " : !sps[0] ? "p" : "P",
392 &i->ifinfo.ip);
393
394 // Only print the discovered sleep proxies once for the lead/active interface of an interface set.
395 if (i == i->Registered && (sps[0] || sps[1] || sps[2]))
396 {
397 LogToFD(fd, " Sleep Proxy Metric Name");
398 if (sps[0]) LogToFD(fd, " %13d %#s", SPSMetric(sps[0]->resrec.rdata->u.name.c), sps[0]->resrec.rdata->u.name.c);
399 if (sps[1]) LogToFD(fd, " %13d %#s", SPSMetric(sps[1]->resrec.rdata->u.name.c), sps[1]->resrec.rdata->u.name.c);
400 if (sps[2]) LogToFD(fd, " %13d %#s", SPSMetric(sps[2]->resrec.rdata->u.name.c), sps[2]->resrec.rdata->u.name.c);
401 }
402 }
403 }
404 }
405
406 LogToFD(fd, "--------- DNS Servers(%d) ----------", CountOfUnicastDNSServers(&mDNSStorage));
407 if (!mDNSStorage.DNSServers) LogToFD(fd, "<None>");
408 else
409 {
410 for (s = mDNSStorage.DNSServers; s; s = s->next)
411 {
412 NetworkInterfaceInfoOSX *ifx = IfindexToInterfaceInfoOSX(s->interface);
413 LogToFD(fd, "DNS Server %##s %s%s%#a:%d %d %s %d %d %sv4 %sv6 %scell %sexp %sconstrained %sCLAT46 %sDNSSECAware",
414 s->domain.c, ifx ? ifx->ifinfo.ifname : "", ifx ? " " : "", &s->addr, mDNSVal16(s->port),
415 s->penaltyTime ? (s->penaltyTime - mDNS_TimeNow(&mDNSStorage)) : 0, DNSScopeToString(s->scopeType),
416 s->timeout, s->resGroupID,
417 s->usableA ? "" : "!",
418 s->usableAAAA ? "" : "!",
419 s->isCell ? "" : "!",
420 s->isExpensive ? "" : "!",
421 s->isConstrained ? "" : "!",
422 s->isCLAT46 ? "" : "!",
423 s->DNSSECAware ? "" : "!");
424 }
425 }
426
427 LogToFD(fd, "v4answers %d", mDNSStorage.p->v4answers);
428 LogToFD(fd, "v6answers %d", mDNSStorage.p->v6answers);
429 LogToFD(fd, "Last DNS Trigger: %d ms ago", (now - mDNSStorage.p->DNSTrigger));
430
431 LogToFD(fd, "-------- Interface Monitors --------");
432 const CFIndex n = m->p->InterfaceMonitors ? CFArrayGetCount(m->p->InterfaceMonitors) : 0;
433 if (n > 0)
434 {
435 for (CFIndex j = 0; j < n; j++)
436 {
437 mdns_interface_monitor_t monitor = (mdns_interface_monitor_t) CFArrayGetValueAtIndex(m->p->InterfaceMonitors, j);
438 char *description = mdns_copy_description(monitor);
439 if (description)
440 {
441 LogToFD(fd, "%s", description);
442 free(description);
443 }
444 else
445 {
446 LogToFD(fd, "monitor %p (no description)", monitor);
447 }
448 }
449 }
450 else
451 {
452 LogToFD(fd, "No interface monitors");
453 }
454
455 LogToFD(fd, "--------- Mcast Resolvers ----------");
456 if (!mDNSStorage.McastResolvers) LogToFD(fd, "<None>");
457 else
458 {
459 for (mr = mDNSStorage.McastResolvers; mr; mr = mr->next)
460 LogToFD(fd, "Mcast Resolver %##s timeout %u", mr->domain.c, mr->timeout);
461 }
462
463 LogToFD(fd, "------------ Hostnames -------------");
464 if (!mDNSStorage.Hostnames) LogToFD(fd, "<None>");
465 else
466 {
467 HostnameInfo *hi;
468 for (hi = mDNSStorage.Hostnames; hi; hi = hi->next)
469 {
470 LogToFD(fd, "%##s v4 %d %s", hi->fqdn.c, hi->arv4.state, ARDisplayString(&mDNSStorage, &hi->arv4));
471 LogToFD(fd, "%##s v6 %d %s", hi->fqdn.c, hi->arv6.state, ARDisplayString(&mDNSStorage, &hi->arv6));
472 }
473 }
474
475 LogToFD(fd, "--------------- FQDN ---------------");
476 if (!mDNSStorage.FQDN.c[0]) LogToFD(fd, "<None>");
477 else
478 {
479 LogToFD(fd, "%##s", mDNSStorage.FQDN.c);
480 }
481
482 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
483 LogMetricsToFD(fd);
484 #endif
485
486 // getLocalTimestamp(timestamp, sizeof(timestamp));
487 LogToFD(fd, "Date: %s", timestamp);
488 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "---- END STATE LOG ---- (" PUB_S ")", timestamp);
489 LogToFD(fd, "---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
490 }
491
492 mDNSexport void INFOCallback(void)
493 {
494 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING,
495 "Sending SIGINFO to mDNSResponder daemon is deprecated. To trigger state dump, please use 'dns-sd -O', enter 'dns-sd -h' for more information");
496 }
497
498 // Writes the state out to the dynamic store and also affects the ASL filter level
499 mDNSexport void UpdateDebugState()
500 {
501 mDNSu32 one = 1;
502 mDNSu32 zero = 0;
503
504 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
505 if (!dict)
506 {
507 LogMsg("UpdateDebugState: Could not create dict");
508 return;
509 }
510
511 CFNumberRef numOne = CFNumberCreate(NULL, kCFNumberSInt32Type, &one);
512 if (numOne == NULL)
513 {
514 LogMsg("UpdateDebugState: Could not create CFNumber one");
515 return;
516 }
517 CFNumberRef numZero = CFNumberCreate(NULL, kCFNumberSInt32Type, &zero);
518 if (numZero == NULL)
519 {
520 LogMsg("UpdateDebugState: Could not create CFNumber zero");
521 CFRelease(numOne);
522 return;
523 }
524
525 if (mDNS_LoggingEnabled)
526 CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numOne);
527 else
528 CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numZero);
529
530 if (mDNS_PacketLoggingEnabled)
531 CFDictionarySetValue(dict, CFSTR("PacketLogging"), numOne);
532 else
533 CFDictionarySetValue(dict, CFSTR("PacketLogging"), numZero);
534
535 if (mDNS_McastLoggingEnabled)
536 CFDictionarySetValue(dict, CFSTR("McastLogging"), numOne);
537 else
538 CFDictionarySetValue(dict, CFSTR("McastLogging"), numZero);
539
540 if (mDNS_McastTracingEnabled)
541 CFDictionarySetValue(dict, CFSTR("McastTracing"), numOne);
542 else
543 CFDictionarySetValue(dict, CFSTR("McastTracing"), numZero);
544
545 CFRelease(numOne);
546 CFRelease(numZero);
547 mDNSDynamicStoreSetConfig(kmDNSDebugState, mDNSNULL, dict);
548 CFRelease(dict);
549
550 }
551
552
553 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
554
555 mDNSlocal void SignalCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
556 {
557 (void)port; // Unused
558 (void)size; // Unused
559 (void)info; // Unused
560 mach_msg_header_t *msg_header = (mach_msg_header_t *)msg;
561 mDNS *const m = &mDNSStorage;
562
563 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
564 KQueueLock();
565 switch(msg_header->msgh_id)
566 {
567 case SIGHUP: {
568 mDNSu32 slot;
569 CacheGroup *cg;
570 CacheRecord *rr;
571 LogMsg("SIGHUP: Purge cache");
572 mDNS_Lock(m);
573 FORALL_CACHERECORDS(slot, cg, rr)
574 {
575 rr->resrec.mortality = Mortality_Mortal;
576 mDNS_PurgeCacheResourceRecord(m, rr);
577 }
578 // Restart unicast and multicast queries
579 mDNSCoreRestartQueries(m);
580 mDNS_Unlock(m);
581 } break;
582 case SIGINT:
583 case SIGTERM: ExitCallback(msg_header->msgh_id); break;
584 case SIGINFO: INFOCallback(); break;
585 case SIGUSR1:
586 #if APPLE_OSX_mDNSResponder
587 mDNS_LoggingEnabled = 1;
588 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
589 #else
590 mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
591 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
592 #endif
593 WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250;
594 UpdateDebugState();
595 LogInfo("USR1 Logging Enabled");
596 break;
597 case SIGUSR2:
598 #if APPLE_OSX_mDNSResponder
599 mDNS_PacketLoggingEnabled = 1;
600 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
601 #else
602 mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
603 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
604 #endif
605 mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse;
606 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
607 UpdateDebugState();
608 break;
609 case SIGPROF: mDNS_McastLoggingEnabled = mDNS_McastLoggingEnabled ? mDNSfalse : mDNStrue;
610 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled ? "Enabled" : "Disabled");
611 LogMcastStateInfo(mDNSfalse, mDNStrue, mDNStrue);
612 mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse;
613 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
614 UpdateDebugState();
615 break;
616 case SIGTSTP: mDNS_LoggingEnabled = mDNS_PacketLoggingEnabled = mDNS_McastLoggingEnabled = mDNS_McastTracingEnabled = mDNSfalse;
617 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
618 UpdateDebugState();
619 break;
620
621 default: LogMsg("SignalCallback: Unknown signal %d", msg_header->msgh_id); break;
622 }
623 KQueueUnlock("Unix Signal");
624 }
625
626 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
627 mDNSlocal kern_return_t mDNSDaemonInitialize(void)
628 {
629 mStatus err;
630
631 err = mDNS_Init(&mDNSStorage, &PlatformStorage,
632 rrcachestorage, RR_CACHE_SIZE,
633 !NoMulticastAdvertisements,
634 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
635
636 if (err)
637 {
638 LogMsg("Daemon start: mDNS_Init failed %d", err);
639 return(err);
640 }
641
642 #if MDNSRESPONDER_SUPPORTS(APPLE, PREALLOCATED_CACHE)
643 if (PreallocateCacheMemory)
644 {
645 const int growCount = (kRRCacheMemoryLimit + kRRCacheGrowSize - 1) / kRRCacheGrowSize;
646 int i;
647
648 for (i = 0; i < growCount; ++i)
649 {
650 mDNS_StatusCallback(&mDNSStorage, mStatus_GrowCache);
651 }
652 }
653 #endif
654
655 CFMachPortRef i_port = CFMachPortCreate(NULL, SignalCallback, NULL, NULL);
656 CFRunLoopSourceRef i_rls = CFMachPortCreateRunLoopSource(NULL, i_port, 0);
657 signal_port = CFMachPortGetPort(i_port);
658 CFRunLoopAddSource(CFRunLoopGetMain(), i_rls, kCFRunLoopDefaultMode);
659 CFRelease(i_rls);
660
661 return(err);
662 }
663
664 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
665
666 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
667 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
668 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
669 // of code from above. Alternatively we could remove the duplicated source code by having
670 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
671
672 mDNSlocal void SignalDispatch(dispatch_source_t source)
673 {
674 int sig = (int)dispatch_source_get_handle(source);
675 mDNS *const m = &mDNSStorage;
676 KQueueLock();
677 switch(sig)
678 {
679 case SIGHUP: {
680 mDNSu32 slot;
681 CacheGroup *cg;
682 CacheRecord *rr;
683 LogMsg("SIGHUP: Purge cache");
684 mDNS_Lock(m);
685 FORALL_CACHERECORDS(slot, cg, rr)
686 {
687 rr->resrec.mortality = Mortality_Mortal;
688 mDNS_PurgeCacheResourceRecord(m, rr);
689 }
690 // Restart unicast and multicast queries
691 mDNSCoreRestartQueries(m);
692 mDNS_Unlock(m);
693 } break;
694 case SIGINT:
695 case SIGTERM: ExitCallback(sig); break;
696 case SIGINFO: INFOCallback(); break;
697 case SIGUSR1: mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
698 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
699 WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250;
700 UpdateDebugState();
701 break;
702 case SIGUSR2: mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
703 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
704 UpdateDebugState();
705 break;
706 default: LogMsg("SignalCallback: Unknown signal %d", sig); break;
707 }
708 KQueueUnlock("Unix Signal");
709 }
710
711 mDNSlocal void mDNSSetupSignal(dispatch_queue_t queue, int sig)
712 {
713 signal(sig, SIG_IGN);
714 dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, sig, 0, queue);
715
716 if (source)
717 {
718 dispatch_source_set_event_handler(source, ^{SignalDispatch(source);});
719 // Start processing signals
720 dispatch_resume(source);
721 }
722 else
723 {
724 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig);
725 }
726 }
727
728 mDNSlocal kern_return_t mDNSDaemonInitialize(void)
729 {
730 mStatus err;
731 dispatch_queue_t queue = dispatch_get_main_queue();
732
733 err = mDNS_Init(&mDNSStorage, &PlatformStorage,
734 rrcachestorage, RR_CACHE_SIZE,
735 !NoMulticastAdvertisements,
736 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
737
738 if (err)
739 {
740 LogMsg("Daemon start: mDNS_Init failed %d", err);
741 return(err);
742 }
743
744 mDNSSetupSignal(queue, SIGHUP);
745 mDNSSetupSignal(queue, SIGINT);
746 mDNSSetupSignal(queue, SIGTERM);
747 mDNSSetupSignal(queue, SIGINFO);
748 mDNSSetupSignal(queue, SIGUSR1);
749 mDNSSetupSignal(queue, SIGUSR2);
750
751 // Create a custom handler for doing the housekeeping work. This is either triggered
752 // by the timer or an event source
753 PlatformStorage.custom = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, queue);
754 if (PlatformStorage.custom == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
755 dispatch_source_set_event_handler(PlatformStorage.custom, ^{PrepareForIdle(&mDNSStorage);});
756 dispatch_resume(PlatformStorage.custom);
757
758 // Create a timer source to trigger housekeeping work. The houskeeping work itself
759 // is done in the custom handler that we set below.
760
761 PlatformStorage.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
762 if (PlatformStorage.timer == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
763
764 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
765 // always reset the time to the new time computed. In effect, we ignore the interval
766 dispatch_source_set_timer(PlatformStorage.timer, DISPATCH_TIME_NOW, 1000ull * 1000000000, 0);
767 dispatch_source_set_event_handler(PlatformStorage.timer, ^{
768 dispatch_source_merge_data(PlatformStorage.custom, 1);
769 });
770 dispatch_resume(PlatformStorage.timer);
771
772 LogMsg("DaemonIntialize done successfully");
773
774 return(err);
775 }
776
777 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
778
779 mDNSlocal mDNSs32 mDNSDaemonIdle(mDNS *const m)
780 {
781 mDNSs32 now = mDNS_TimeNow(m);
782
783 // 1. If we need to set domain secrets, do so before handling the network change
784 // Detailed reason:
785 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
786 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
787 if (m->p->KeyChainTimer && now - m->p->KeyChainTimer >= 0)
788 {
789 m->p->KeyChainTimer = 0;
790 mDNS_Lock(m);
791 SetDomainSecrets(m);
792 mDNS_Unlock(m);
793 }
794
795 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
796 // Detailed reason:
797 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
798 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
799 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
800 // we then systematically lose our own looped-back packets.
801 if (m->NetworkChanged && now - m->NetworkChanged >= 0) mDNSMacOSXNetworkChanged();
802
803 if (m->p->RequestReSleep && now - m->p->RequestReSleep >= 0)
804 {
805 m->p->RequestReSleep = 0;
806 mDNSPowerRequest(0, 0);
807 }
808
809 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
810 mDNSs32 nextevent = mDNS_Execute(m);
811
812 if (m->NetworkChanged)
813 if (nextevent - m->NetworkChanged > 0)
814 nextevent = m->NetworkChanged;
815
816 if (m->p->KeyChainTimer)
817 if (nextevent - m->p->KeyChainTimer > 0)
818 nextevent = m->p->KeyChainTimer;
819
820 if (m->p->RequestReSleep)
821 if (nextevent - m->p->RequestReSleep > 0)
822 nextevent = m->p->RequestReSleep;
823
824
825 if (m->p->NotifyUser)
826 {
827 if (m->p->NotifyUser - now < 0)
828 {
829 if (!SameDomainLabelCS(m->p->usernicelabel.c, m->nicelabel.c))
830 {
831 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m->p->usernicelabel.c, m->nicelabel.c);
832 mDNSPreferencesSetNames(kmDNSComputerName, &m->p->usernicelabel, &m->nicelabel);
833 m->p->usernicelabel = m->nicelabel;
834 }
835 if (!SameDomainLabelCS(m->p->userhostlabel.c, m->hostlabel.c))
836 {
837 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m->p->userhostlabel.c, m->hostlabel.c);
838 mDNSPreferencesSetNames(kmDNSLocalHostName, &m->p->userhostlabel, &m->hostlabel);
839 m->p->HostNameConflict = 0; // Clear our indicator, now name change has been successful
840 m->p->userhostlabel = m->hostlabel;
841 }
842 m->p->NotifyUser = 0;
843 }
844 else
845 if (nextevent - m->p->NotifyUser > 0)
846 nextevent = m->p->NotifyUser;
847 }
848
849 return(nextevent);
850 }
851
852 // Right now we consider *ALL* of our DHCP leases
853 // It might make sense to be a bit more selective and only consider the leases on interfaces
854 // (a) that are capable and enabled for wake-on-LAN, and
855 // (b) where we have found (and successfully registered with) a Sleep Proxy
856 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
857 mDNSlocal mDNSu32 DHCPWakeTime(void)
858 {
859 mDNSu32 e = 24 * 3600; // Maximum maintenance wake interval is 24 hours
860 const CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
861 if (!now) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
862 else
863 {
864 int ic, j;
865
866 const void *pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetDHCP);
867 if (!pattern)
868 {
869 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
870 return e;
871 }
872 CFArrayRef dhcpinfo = CFArrayCreate(NULL, (const void **)&pattern, 1, &kCFTypeArrayCallBacks);
873 CFRelease(pattern);
874 if (dhcpinfo)
875 {
876 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("DHCP-LEASES"), NULL, NULL);
877 if (store)
878 {
879 CFDictionaryRef dict = SCDynamicStoreCopyMultiple(store, NULL, dhcpinfo);
880 if (dict)
881 {
882 ic = CFDictionaryGetCount(dict);
883 const void *vals[ic];
884 CFDictionaryGetKeysAndValues(dict, NULL, vals);
885
886 for (j = 0; j < ic; j++)
887 {
888 const CFDictionaryRef dhcp = (CFDictionaryRef)vals[j];
889 if (dhcp)
890 {
891 const CFDateRef start = DHCPInfoGetLeaseStartTime(dhcp);
892 const CFDataRef lease = DHCPInfoGetOptionData(dhcp, 51); // Option 51 = IP Address Lease Time
893 if (!start || !lease || CFDataGetLength(lease) < 4)
894 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
895 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
896 j, start, lease, lease ? CFDataGetLength(lease) : 0);
897 else
898 {
899 const UInt8 *d = CFDataGetBytePtr(lease);
900 if (!d) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j);
901 else
902 {
903 const mDNSu32 elapsed = now - CFDateGetAbsoluteTime(start);
904 const mDNSu32 lifetime = (mDNSs32) ((mDNSs32)d[0] << 24 | (mDNSs32)d[1] << 16 | (mDNSs32)d[2] << 8 | d[3]);
905 const mDNSu32 remaining = lifetime - elapsed;
906 const mDNSu32 wake = remaining > 60 ? remaining - remaining/10 : 54; // Wake at 90% of the lease time
907 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed, lifetime, remaining, wake);
908 if (e > wake) e = wake;
909 }
910 }
911 }
912 }
913 CFRelease(dict);
914 }
915 CFRelease(store);
916 }
917 CFRelease(dhcpinfo);
918 }
919 }
920 return(e);
921 }
922
923 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
924 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
925 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
926 // for a few seconds and then waking again is silly and annoying.
927 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
928 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
929 // allowing us an adequate safety margin to renew our lease before we lose it.
930
931 mDNSlocal mDNSBool AllowSleepNow(mDNSs32 now)
932 {
933 mDNS *const m = &mDNSStorage;
934 mDNSBool ready = mDNSCoreReadyForSleep(m, now);
935 if (m->SleepState && !ready && now - m->SleepLimit < 0) return(mDNSfalse);
936
937 m->p->WakeAtUTC = 0;
938 int result = kIOReturnSuccess;
939 CFDictionaryRef opts = NULL;
940
941 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
942 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
943 if (!m->SleepState)
944 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m->SleepLimit - now);
945 else
946 {
947 if (!m->SystemWakeOnLANEnabled || !mDNSCoreHaveAdvertisedMulticastServices(m))
948 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
949 m->SystemWakeOnLANEnabled ? "is" : "not",
950 mDNSCoreHaveAdvertisedMulticastServices(m) ? "have" : "no");
951 else
952 {
953 mDNSs32 dhcp = DHCPWakeTime();
954 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp);
955 mDNSs32 interval = mDNSCoreIntervalToNextWake(m, now) / mDNSPlatformOneSecond;
956 if (interval > dhcp) interval = dhcp;
957
958 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
959 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
960 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
961 // someone to go to the machine in person to wake it up again, which would be unacceptable.
962 if (!ready && interval > 3600) interval = 3600;
963
964 //interval = 48; // For testing
965
966 #if TARGET_OS_OSX && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
967 if (m->p->IOPMConnection) // If lightweight-wake capability is available, use that
968 {
969 const CFDateRef WakeDate = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent() + interval);
970 if (!WakeDate) LogMsg("ScheduleNextWake: CFDateCreate failed");
971 else
972 {
973 const mDNSs32 reqs = kIOPMSystemPowerStateCapabilityNetwork;
974 const CFNumberRef Requirements = CFNumberCreate(NULL, kCFNumberSInt32Type, &reqs);
975 if (Requirements == NULL) LogMsg("ScheduleNextWake: CFNumberCreate failed");
976 else
977 {
978 const void *OptionKeys[2] = { kIOPMAckDHCPRenewWakeDate, kIOPMAckSystemCapabilityRequirements };
979 const void *OptionVals[2] = { WakeDate, Requirements };
980 opts = CFDictionaryCreate(NULL, (void*)OptionKeys, (void*)OptionVals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
981 if (!opts) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
982 CFRelease(Requirements);
983 }
984 CFRelease(WakeDate);
985 }
986 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval);
987 }
988 else // else schedule the wakeup using the old API instead to
989 #endif
990 {
991 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
992 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
993 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
994 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
995 if (interval < 60)
996 interval = 60;
997
998 result = mDNSPowerRequest(1, interval);
999
1000 if (result == kIOReturnNotReady)
1001 {
1002 int r;
1003 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval);
1004 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
1005 // requested wake time is "too soon", but there's no API to find out what constitutes
1006 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
1007 // we just have to iterate with successively longer intervals until it doesn't fail.
1008 // We preserve the value of "result" because if our original power request was deemed "too soon"
1009 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
1010 // since the implication is that the system won't manage to be awake again at the time we need it.
1011 do
1012 {
1013 interval += (interval < 20) ? 1 : ((interval+3) / 4);
1014 r = mDNSPowerRequest(1, interval);
1015 }
1016 while (r == kIOReturnNotReady);
1017 if (r) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval, r, r);
1018 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval);
1019 }
1020 else
1021 {
1022 if (result) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval, result, result);
1023 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval);
1024 }
1025 m->p->WakeAtUTC = mDNSPlatformUTC() + interval;
1026 }
1027 }
1028
1029 m->SleepState = SleepState_Sleeping;
1030 // Clear our interface list to empty state, ready to go to sleep
1031 // As a side effect of doing this, we'll also cancel any outstanding SPS Resolve calls that didn't complete
1032 mDNSMacOSXNetworkChanged();
1033 }
1034
1035 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1036 #if TARGET_OS_OSX && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1037 (m->p->IOPMConnection) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1038 #endif
1039 (result == kIOReturnSuccess) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1040 m->p->SleepCookie, ready ? "ready for sleep" : "giving up", now, m->SleepLimit - now);
1041
1042 m->SleepLimit = 0; // Don't clear m->SleepLimit until after we've logged it above
1043 m->TimeSlept = mDNSPlatformUTC();
1044
1045 #if TARGET_OS_OSX && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1046 if (m->p->IOPMConnection) IOPMConnectionAcknowledgeEventWithOptions(m->p->IOPMConnection, m->p->SleepCookie, opts);
1047 else
1048 #endif
1049 if (result == kIOReturnSuccess) IOAllowPowerChange (m->p->PowerConnection, m->p->SleepCookie);
1050 else IOCancelPowerChange(m->p->PowerConnection, m->p->SleepCookie);
1051
1052 if (opts) CFRelease(opts);
1053 return(mDNStrue);
1054 }
1055
1056 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1057
1058 mDNSexport void TriggerEventCompletion()
1059 {
1060 debugf("TriggerEventCompletion: Merge data");
1061 dispatch_source_merge_data(PlatformStorage.custom, 1);
1062 }
1063
1064 mDNSlocal void PrepareForIdle(void *m_param)
1065 {
1066 mDNS *m = m_param;
1067 int64_t time_offset;
1068 dispatch_time_t dtime;
1069
1070 const int multiplier = 1000000000 / mDNSPlatformOneSecond;
1071
1072 // This is the main work loop:
1073 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1074 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1075 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1076
1077 debugf("PrepareForIdle: called");
1078 // Run mDNS_Execute to find out the time we next need to wake up
1079 mDNSs32 start = mDNSPlatformRawTime();
1080 mDNSs32 nextTimerEvent = udsserver_idle(mDNSDaemonIdle(m));
1081 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
1082 if (m->DNSPushServers != mDNSNULL)
1083 {
1084 nextTimerEvent = dso_idle(m, nextTimerEvent);
1085 }
1086 #endif
1087 mDNSs32 end = mDNSPlatformRawTime();
1088 if (end - start >= WatchDogReportingThreshold)
1089 {
1090 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING,
1091 "CustomSourceHandler: WARNING: Idle task took %d ms to complete", end - start);
1092 }
1093
1094 mDNSs32 now = mDNS_TimeNow(m);
1095
1096 if (m->ShutdownTime)
1097 {
1098 if (mDNSStorage.ResourceRecords)
1099 {
1100 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m, mDNSStorage.ResourceRecords));
1101 if (mDNS_LoggingEnabled) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1102 }
1103 if (mDNS_ExitNow(m, now))
1104 {
1105 LogInfo("IdleLoop: mDNS_FinalExit");
1106 mDNS_FinalExit(&mDNSStorage);
1107 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1108 exit(0);
1109 }
1110 if (nextTimerEvent - m->ShutdownTime >= 0)
1111 nextTimerEvent = m->ShutdownTime;
1112 }
1113
1114 if (m->SleepLimit)
1115 if (!AllowSleepNow(now))
1116 if (nextTimerEvent - m->SleepLimit >= 0)
1117 nextTimerEvent = m->SleepLimit;
1118
1119 // Convert absolute wakeup time to a relative time from now
1120 mDNSs32 ticks = nextTimerEvent - now;
1121 if (ticks < 1) ticks = 1;
1122
1123 static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins
1124 if (ticks > 1)
1125 RepeatedBusy = 0;
1126 else
1127 {
1128 ticks = 1;
1129 if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
1130 }
1131
1132 time_offset = ((mDNSu32)ticks / mDNSPlatformOneSecond) * 1000000000 + (ticks % mDNSPlatformOneSecond) * multiplier;
1133 dtime = dispatch_time(DISPATCH_TIME_NOW, time_offset);
1134 dispatch_source_set_timer(PlatformStorage.timer, dtime, 1000ull*1000000000, 0);
1135 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks);
1136 return;
1137 }
1138
1139 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1140
1141 mDNSlocal void KQWokenFlushBytes(int fd, __unused short filter, __unused void *context, __unused mDNSBool encounteredEOF)
1142 {
1143 // Read all of the bytes so we won't wake again.
1144 char buffer[100];
1145 while (recv(fd, buffer, sizeof(buffer), MSG_DONTWAIT) > 0) continue;
1146 }
1147
1148 mDNSlocal void SetLowWater(const KQSocketSet *const k, const int r)
1149 {
1150 if (k->sktv4 >=0 && setsockopt(k->sktv4, SOL_SOCKET, SO_RCVLOWAT, &r, sizeof(r)) < 0)
1151 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k->sktv4, r, errno, strerror(errno));
1152 if (k->sktv6 >=0 && setsockopt(k->sktv6, SOL_SOCKET, SO_RCVLOWAT, &r, sizeof(r)) < 0)
1153 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k->sktv6, r, errno, strerror(errno));
1154 }
1155
1156 mDNSlocal void * KQueueLoop(void *m_param)
1157 {
1158 mDNS *m = m_param;
1159 int numevents = 0;
1160
1161 #if USE_SELECT_WITH_KQUEUEFD
1162 fd_set readfds;
1163 FD_ZERO(&readfds);
1164 const int multiplier = 1000000 / mDNSPlatformOneSecond;
1165 #else
1166 const int multiplier = 1000000000 / mDNSPlatformOneSecond;
1167 #endif
1168
1169 pthread_mutex_lock(&PlatformStorage.BigMutex);
1170 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32)mDNSStorage.timenow_last, mDNSStorage.timenow_last);
1171
1172 // This is the main work loop:
1173 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1174 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1175 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1176 // (4) On wakeup we first process *all* events
1177 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
1178 for ( ; ; )
1179 {
1180 #define kEventsToReadAtOnce 1
1181 struct kevent new_events[kEventsToReadAtOnce];
1182
1183 // Run mDNS_Execute to find out the time we next need to wake up
1184 mDNSs32 start = mDNSPlatformRawTime();
1185 mDNSs32 nextTimerEvent = udsserver_idle(mDNSDaemonIdle(m));
1186 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSD_XPC_SERVICE)
1187 dnssd_server_idle();
1188 #endif
1189 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
1190 if (m->DNSPushServers != mDNSNULL)
1191 {
1192 mDNS_Lock(m);
1193 nextTimerEvent = dso_idle(m, m->timenow, nextTimerEvent);
1194 mDNS_Unlock(m);
1195 }
1196 #endif
1197 mDNSs32 end = mDNSPlatformRawTime();
1198 if (end - start >= WatchDogReportingThreshold)
1199 {
1200 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING, "WARNING: Idle task took %d ms to complete", end - start);
1201 }
1202
1203 #if MDNS_MALLOC_DEBUGGING >= 1
1204 mDNSPlatformValidateLists();
1205 #endif
1206
1207 mDNSs32 now = mDNS_TimeNow(m);
1208
1209 if (m->ShutdownTime)
1210 {
1211 if (mDNSStorage.ResourceRecords)
1212 {
1213 AuthRecord *rr;
1214 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
1215 {
1216 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m, rr));
1217 if (mDNS_LoggingEnabled) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1218 }
1219 }
1220 if (mDNS_ExitNow(m, now))
1221 {
1222 LogInfo("mDNS_FinalExit");
1223 mDNS_FinalExit(&mDNSStorage);
1224 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1225 exit(0);
1226 }
1227 if (nextTimerEvent - m->ShutdownTime >= 0)
1228 nextTimerEvent = m->ShutdownTime;
1229 }
1230
1231 if (m->SleepLimit)
1232 if (!AllowSleepNow(now))
1233 if (nextTimerEvent - m->SleepLimit >= 0)
1234 nextTimerEvent = m->SleepLimit;
1235
1236 // Convert absolute wakeup time to a relative time from now
1237 mDNSs32 ticks = nextTimerEvent - now;
1238 if (ticks < 1) ticks = 1;
1239
1240 static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins
1241 if (ticks > 1)
1242 RepeatedBusy = 0;
1243 else
1244 {
1245 ticks = 1;
1246 if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
1247 }
1248
1249 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents, ticks);
1250 numevents = 0;
1251
1252 // Release the lock, and sleep until:
1253 // 1. Something interesting happens like a packet arriving, or
1254 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
1255 // 3. The timeout expires
1256 pthread_mutex_unlock(&PlatformStorage.BigMutex);
1257
1258 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1259 if (m->p->num_mcasts)
1260 {
1261 SetLowWater(&m->p->permanentsockets, 0x10000);
1262 if (ticks > mDNSPlatformOneSecond / 8) ticks = mDNSPlatformOneSecond / 8;
1263 }
1264
1265 #if USE_SELECT_WITH_KQUEUEFD
1266 struct timeval timeout;
1267 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
1268 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * multiplier;
1269 FD_SET(KQueueFD, &readfds);
1270 if (select(KQueueFD+1, &readfds, NULL, NULL, &timeout) < 0)
1271 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD, errno, strerror(errno)); sleep(1); }
1272 #else
1273 struct timespec timeout;
1274 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
1275 timeout.tv_nsec = (ticks % mDNSPlatformOneSecond) * multiplier;
1276 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
1277 // and have it work similarly to the way it does with nevents non-zero --
1278 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
1279 // In fact, what happens if you do this is that it just returns immediately. So, we have
1280 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
1281 if (kevent(KQueueFD, NULL, 0, new_events, 1, &timeout) < 0)
1282 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD, errno, strerror(errno)); sleep(1); }
1283 #endif
1284
1285 pthread_mutex_lock(&PlatformStorage.BigMutex);
1286 // We have to ignore the event we may have been told about above, because that
1287 // was done without holding the lock, and between the time we woke up and the
1288 // time we reclaimed the lock the other thread could have done something that
1289 // makes the event no longer valid. Now we have the lock, we call kevent again
1290 // and this time we can safely process the events it tells us about.
1291
1292 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
1293 if (m->p->num_mcasts)
1294 {
1295 SetLowWater(&m->p->permanentsockets, 1);
1296 m->p->num_mcasts = 0;
1297 }
1298
1299 static const struct timespec zero_timeout = { 0, 0 };
1300 int events_found;
1301 while ((events_found = kevent(KQueueFD, NULL, 0, new_events, kEventsToReadAtOnce, &zero_timeout)) != 0)
1302 {
1303 if (events_found > kEventsToReadAtOnce || (events_found < 0 && errno != EINTR))
1304 {
1305 const int kevent_errno = errno;
1306 // Not sure what to do here, our kqueue has failed us - this isn't ideal
1307 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", kevent_errno, strerror(kevent_errno));
1308 exit(kevent_errno);
1309 }
1310
1311 numevents += events_found;
1312
1313 int i;
1314 for (i = 0; i < events_found; i++)
1315 {
1316 const KQueueEntry *const kqentry = new_events[i].udata;
1317 mDNSs32 stime = mDNSPlatformRawTime();
1318 const char *const KQtask = kqentry->KQtask; // Grab a copy in case KQcallback deletes the task
1319 kqentry->KQcallback(new_events[i].ident, new_events[i].filter, kqentry->KQcontext, (new_events[i].flags & EV_EOF) != 0);
1320 mDNSs32 etime = mDNSPlatformRawTime();
1321 if (etime - stime >= WatchDogReportingThreshold)
1322 {
1323 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_WARNING,
1324 "WARNING: " PUB_S " took %d ms to complete", KQtask, etime - stime);
1325 }
1326 }
1327 }
1328 }
1329
1330 return NULL;
1331 }
1332
1333 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1334
1335 mDNSlocal size_t LaunchdCheckin(void)
1336 {
1337 // Ask launchd for our socket
1338 int result = launch_activate_socket("Listeners", &launchd_fds, &launchd_fds_count);
1339 if (result != 0) { LogMsg("launch_activate_socket() failed error %d (%s)", result, strerror(result)); }
1340 return launchd_fds_count;
1341 }
1342
1343
1344 extern int sandbox_init(const char *profile, uint64_t flags, char **errorbuf) __attribute__((weak_import));
1345
1346 #if APPLE_OSX_mDNSResponder
1347 mDNSlocal mDNSBool PreferencesGetValueBool(CFStringRef key, mDNSBool defaultValue)
1348 {
1349 CFBooleanRef boolean;
1350 mDNSBool result = defaultValue;
1351
1352 boolean = CFPreferencesCopyAppValue(key, kProgramArguments);
1353 if (boolean != NULL)
1354 {
1355 if (CFGetTypeID(boolean) == CFBooleanGetTypeID())
1356 result = CFBooleanGetValue(boolean) ? mDNStrue : mDNSfalse;
1357 CFRelease(boolean);
1358 }
1359
1360 return result;
1361 }
1362
1363 mDNSlocal int PreferencesGetValueInt(CFStringRef key, int defaultValue)
1364 {
1365 CFNumberRef number;
1366 int numberValue;
1367 int result = defaultValue;
1368
1369 number = CFPreferencesCopyAppValue(key, kProgramArguments);
1370 if (number != NULL)
1371 {
1372 if ((CFGetTypeID(number) == CFNumberGetTypeID()) && CFNumberGetValue(number, kCFNumberIntType, &numberValue))
1373 result = numberValue;
1374 CFRelease(number);
1375 }
1376
1377 return result;
1378 }
1379 #endif
1380
1381 mDNSlocal void SandboxProcess(void)
1382 {
1383 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1384 #if MDNS_NO_SANDBOX
1385 LogMsg("Note: Compiled without Apple Sandbox support");
1386 #else // MDNS_NO_SANDBOX
1387 if (!sandbox_init)
1388 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1389 else
1390 {
1391 char *sandbox_msg;
1392 uint64_t sandbox_flags = SANDBOX_NAMED;
1393
1394 (void)confstr(_CS_DARWIN_USER_CACHE_DIR, NULL, 0);
1395
1396 int sandbox_err = sandbox_init("mDNSResponder", sandbox_flags, &sandbox_msg);
1397 if (sandbox_err)
1398 {
1399 LogMsg("WARNING: sandbox_init error %s", sandbox_msg);
1400 // If we have errors in the sandbox during development, to prevent
1401 // exiting, uncomment the following line.
1402 //sandbox_free_error(sandbox_msg);
1403
1404 errx(EX_OSERR, "sandbox_init() failed: %s", sandbox_msg);
1405 }
1406 else LogInfo("Now running under Apple Sandbox restrictions");
1407 }
1408 #endif // MDNS_NO_SANDBOX
1409 }
1410
1411 #if MDNSRESPONDER_SUPPORTS(APPLE, OS_LOG)
1412 #define MDNS_OS_LOG_CATEGORY_INIT(NAME) \
1413 do\
1414 { \
1415 mDNSLogCategory_ ## NAME = os_log_create("com.apple.mDNSResponder", # NAME ); \
1416 if (!mDNSLogCategory_ ## NAME ) \
1417 { \
1418 os_log_error(OS_LOG_DEFAULT, "Could NOT create the " # NAME " log handle in mDNSResponder"); \
1419 mDNSLogCategory_ ## NAME = OS_LOG_DEFAULT; \
1420 } \
1421 } \
1422 while (0)
1423
1424 os_log_t mDNSLogCategory_Default = NULL;
1425 os_log_t mDNSLogCategory_mDNS = NULL;
1426 os_log_t mDNSLogCategory_uDNS = NULL;
1427 os_log_t mDNSLogCategory_SPS = NULL;
1428 os_log_t mDNSLogCategory_XPC = NULL;
1429
1430 mDNSlocal void init_logging(void)
1431 {
1432 MDNS_OS_LOG_CATEGORY_INIT(Default);
1433 MDNS_OS_LOG_CATEGORY_INIT(mDNS);
1434 MDNS_OS_LOG_CATEGORY_INIT(uDNS);
1435 MDNS_OS_LOG_CATEGORY_INIT(SPS);
1436 MDNS_OS_LOG_CATEGORY_INIT(XPC);
1437 }
1438 #endif
1439
1440 mDNSexport int main(int argc, char **argv)
1441 {
1442 int i;
1443 kern_return_t status;
1444
1445 #if DEBUG
1446 bool useDebugSocket = mDNSfalse;
1447 bool useSandbox = mDNStrue;
1448 #endif
1449
1450 #if MDNSRESPONDER_SUPPORTS(APPLE, OS_LOG)
1451 init_logging();
1452 #endif
1453
1454 mDNSMacOSXSystemBuildNumber(NULL);
1455 LogMsg("%s starting %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
1456
1457 #if 0
1458 LogMsg("CacheRecord %5d", sizeof(CacheRecord));
1459 LogMsg("CacheGroup %5d", sizeof(CacheGroup));
1460 LogMsg("ResourceRecord %5d", sizeof(ResourceRecord));
1461 LogMsg("RData_small %5d", sizeof(RData_small));
1462
1463 LogMsg("sizeof(CacheEntity) %5d", sizeof(CacheEntity));
1464 LogMsg("RR_CACHE_SIZE %5d", RR_CACHE_SIZE);
1465 LogMsg("block bytes used %5d", sizeof(CacheEntity) * RR_CACHE_SIZE);
1466 LogMsg("block bytes wasted %5d", 32*1024 - sizeof(CacheEntity) * RR_CACHE_SIZE);
1467 #endif
1468
1469 if (0 == geteuid())
1470 {
1471 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1472 return -1;
1473 }
1474
1475 for (i=1; i<argc; i++)
1476 {
1477 if (!strcasecmp(argv[i], "-d" )) mDNS_DebugMode = mDNStrue;
1478 if (!strcasecmp(argv[i], "-NoMulticastAdvertisements")) NoMulticastAdvertisements = mDNStrue;
1479 if (!strcasecmp(argv[i], "-DisableSleepProxyClient" )) DisableSleepProxyClient = mDNStrue;
1480 if (!strcasecmp(argv[i], "-DebugLogging" )) mDNS_LoggingEnabled = mDNStrue;
1481 if (!strcasecmp(argv[i], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled = mDNStrue;
1482 if (!strcasecmp(argv[i], "-OfferSleepProxyService" ))
1483 OfferSleepProxyService = (i+1 < argc && mDNSIsDigit(argv[i+1][0]) && mDNSIsDigit(argv[i+1][1]) && argv[i+1][2]==0) ? atoi(argv[++i]) : 100;
1484 if (!strcasecmp(argv[i], "-UseInternalSleepProxy" ))
1485 UseInternalSleepProxy = (i+1<argc && mDNSIsDigit(argv[i+1][0]) && argv[i+1][1]==0) ? atoi(argv[++i]) : 1;
1486 if (!strcasecmp(argv[i], "-StrictUnicastOrdering" )) StrictUnicastOrdering = mDNStrue;
1487 if (!strcasecmp(argv[i], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains = mDNStrue;
1488 if (!strcasecmp(argv[i], "-DisableAllowExpired" )) EnableAllowExpired = mDNSfalse;
1489 #if DEBUG
1490 if (!strcasecmp(argv[i], "-UseDebugSocket")) useDebugSocket = mDNStrue;
1491 if (!strcasecmp(argv[i], "-NoSandbox")) useSandbox = mDNSfalse;
1492 #endif
1493 }
1494
1495
1496 #if APPLE_OSX_mDNSResponder
1497 /* Reads the external user's program arguments for mDNSResponder starting 10.11.x(El Capitan) on OSX. The options for external user are:
1498 DebugLogging, UnicastPacketLogging, NoMulticastAdvertisements, StrictUnicastOrdering and AlwaysAppendSearchDomains
1499
1500 To turn ON the particular option, here is what the user should do (as an example of setting two options)
1501 1] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool YES
1502 2] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
1503 3] sudo reboot
1504
1505 To turn OFF all options, here is what the user should do
1506 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1507 2] sudo reboot
1508
1509 To view the current options set, here is what the user should do
1510 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1511 OR
1512 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
1513
1514 */
1515
1516 // Currently on Fuji/Whitetail releases we are keeping the logging always enabled.
1517 // Hence mDNS_LoggingEnabled and mDNS_PacketLoggingEnabled is set to true below by default.
1518 #if 0
1519 mDNS_LoggingEnabled = PreferencesGetValueBool(kPreferencesKey_DebugLogging, mDNS_LoggingEnabled);
1520 mDNS_PacketLoggingEnabled = PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging, mDNS_PacketLoggingEnabled);
1521 #endif
1522
1523 mDNS_LoggingEnabled = mDNStrue;
1524 mDNS_PacketLoggingEnabled = mDNStrue;
1525
1526 NoMulticastAdvertisements = PreferencesGetValueBool(kPreferencesKey_NoMulticastAdvertisements, NoMulticastAdvertisements);
1527 StrictUnicastOrdering = PreferencesGetValueBool(kPreferencesKey_StrictUnicastOrdering, StrictUnicastOrdering);
1528 AlwaysAppendSearchDomains = PreferencesGetValueBool(kPreferencesKey_AlwaysAppendSearchDomains, AlwaysAppendSearchDomains);
1529 EnableAllowExpired = PreferencesGetValueBool(kPreferencesKey_EnableAllowExpired, EnableAllowExpired);
1530 OfferSleepProxyService = PreferencesGetValueInt(kPreferencesKey_OfferSleepProxyService, OfferSleepProxyService);
1531 UseInternalSleepProxy = PreferencesGetValueInt(kPreferencesKey_UseInternalSleepProxy, UseInternalSleepProxy);
1532
1533 #if ENABLE_BLE_TRIGGERED_BONJOUR
1534 EnableBLEBasedDiscovery = PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery, EnableBLEBasedDiscovery);
1535 DefaultToBLETriggered = PreferencesGetValueBool(kPreferencesKey_DefaultToBLETriggered, DefaultToBLETriggered);
1536 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
1537 #endif
1538
1539 #if MDNSRESPONDER_SUPPORTS(APPLE, PREALLOCATED_CACHE)
1540 PreallocateCacheMemory = PreferencesGetValueBool(kPreferencesKey_PreallocateCacheMemory, PreallocateCacheMemory);
1541 #endif
1542
1543 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
1544 if (NoMulticastAdvertisements)
1545 LogMsg("-NoMulticastAdvertisements is set: Administratively prohibiting multicast advertisements");
1546 if (AlwaysAppendSearchDomains)
1547 LogMsg("-AlwaysAppendSearchDomains is set");
1548 if (StrictUnicastOrdering)
1549 LogMsg("-StrictUnicastOrdering is set");
1550
1551 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1552
1553 signal(SIGHUP, HandleSIG); // (Debugging) Purge the cache to check for cache handling bugs
1554 signal(SIGINT, HandleSIG); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
1555 signal(SIGPIPE, SIG_IGN); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
1556 signal(SIGTERM, HandleSIG); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
1557 signal(SIGINFO, HandleSIG); // (Debugging) Write state snapshot to syslog
1558 signal(SIGUSR1, HandleSIG); // (Debugging) Enable Logging
1559 signal(SIGUSR2, HandleSIG); // (Debugging) Enable Packet Logging
1560 signal(SIGPROF, HandleSIG); // (Debugging) Toggle Multicast Logging
1561 signal(SIGTSTP, HandleSIG); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
1562
1563 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1564
1565 mDNSStorage.p = &PlatformStorage; // Make sure mDNSStorage.p is set up, because validatelists uses it
1566
1567 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1568
1569 // Create the kqueue, mutex and thread to support KQSockets
1570 KQueueFD = kqueue();
1571 if (KQueueFD == -1)
1572 {
1573 const int kqueue_errno = errno;
1574 LogMsg("kqueue() failed errno %d (%s)", kqueue_errno, strerror(kqueue_errno));
1575 status = kqueue_errno;
1576 goto exit;
1577 }
1578
1579 i = pthread_mutex_init(&PlatformStorage.BigMutex, NULL);
1580 if (i != 0) { LogMsg("pthread_mutex_init() failed error %d (%s)", i, strerror(i)); status = i; goto exit; }
1581
1582 int fdpair[2] = {0, 0};
1583 i = socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair);
1584 if (i == -1)
1585 {
1586 const int socketpair_errno = errno;
1587 LogMsg("socketpair() failed errno %d (%s)", socketpair_errno, strerror(socketpair_errno));
1588 status = socketpair_errno;
1589 goto exit;
1590 }
1591
1592 // Socket pair returned us two identical sockets connected to each other
1593 // We will use the first socket to send the second socket. The second socket
1594 // will be added to the kqueue so it will wake when data is sent.
1595 static const KQueueEntry wakeKQEntry = { KQWokenFlushBytes, NULL, "kqueue wakeup after CFRunLoop event" };
1596
1597 PlatformStorage.WakeKQueueLoopFD = fdpair[0];
1598 KQueueSet(fdpair[1], EV_ADD, EVFILT_READ, &wakeKQEntry);
1599
1600 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1601
1602 #if DEBUG
1603 if (useSandbox)
1604 #endif
1605 SandboxProcess();
1606
1607 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
1608 status = MetricsInit();
1609 if (status) { LogMsg("Daemon start: MetricsInit failed (%d)", status); }
1610 #endif
1611
1612 status = mDNSDaemonInitialize();
1613 if (status) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit; }
1614
1615 // Need to Start XPC Server Before LaunchdCheckin() (Reason: radar:11023750)
1616 xpc_server_init();
1617 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSD_XPC_SERVICE)
1618 dnssd_server_init();
1619 #endif
1620 #if DEBUG
1621 if (!useDebugSocket) {
1622 if (LaunchdCheckin() == 0)
1623 useDebugSocket = mDNStrue;
1624 }
1625 if (useDebugSocket)
1626 SetDebugBoundPath();
1627 #else
1628 LaunchdCheckin();
1629 #endif
1630
1631 status = udsserver_init(launchd_fds, launchd_fds_count);
1632 if (status) { LogMsg("Daemon start: udsserver_init failed"); goto exit; }
1633
1634 mDNSMacOSXNetworkChanged();
1635 UpdateDebugState();
1636
1637 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1638 LogInfo("Daemon Start: Using LibDispatch");
1639 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
1640 CFRunLoopRun();
1641 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1642 // Start the kqueue thread
1643 pthread_t KQueueThread;
1644 i = pthread_create(&KQueueThread, NULL, KQueueLoop, &mDNSStorage);
1645 if (i != 0) { LogMsg("pthread_create() failed error %d (%s)", i, strerror(i)); status = i; goto exit; }
1646 if (status == 0)
1647 {
1648 CFRunLoopRun();
1649 LogMsg("ERROR: CFRunLoopRun Exiting.");
1650 mDNS_Close(&mDNSStorage);
1651 }
1652 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1653
1654 LogMsg("%s exiting", mDNSResponderVersionString);
1655
1656 exit:
1657 return(status);
1658 }
1659
1660 // uds_daemon.c support routines /////////////////////////////////////////////
1661
1662 mDNSlocal void kqUDSEventCallback(int fd, short filter, void *context, mDNSBool encounteredEOF)
1663 {
1664 const KQSocketEventSource *const source = context;
1665 (void)filter; // unused
1666 (void)encounteredEOF; // unused
1667
1668 source->callback(fd, source->context);
1669 }
1670
1671 // Arrange things so that when data appears on fd, callback is called with context
1672 mDNSexport mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
1673 {
1674 KQSocketEventSource **p = &gEventSources;
1675 (void) platform_data;
1676 while (*p && (*p)->fd != fd) p = &(*p)->next;
1677 if (*p) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd); return mStatus_AlreadyRegistered; }
1678
1679 KQSocketEventSource *newSource = (KQSocketEventSource*) callocL("KQSocketEventSource", sizeof(*newSource));
1680 if (!newSource) return mStatus_NoMemoryErr;
1681
1682 newSource->next = mDNSNULL;
1683 newSource->fd = fd;
1684 newSource->callback = callback;
1685 newSource->context = context;
1686 newSource->kqs.KQcallback = kqUDSEventCallback;
1687 newSource->kqs.KQcontext = newSource;
1688 newSource->kqs.KQtask = "UDS client";
1689 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1690 newSource->kqs.readSource = mDNSNULL;
1691 newSource->kqs.writeSource = mDNSNULL;
1692 newSource->kqs.fdClosed = mDNSfalse;
1693 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1694
1695 if (KQueueSet(fd, EV_ADD, EVFILT_READ, &newSource->kqs) == 0)
1696 {
1697 *p = newSource;
1698 return mStatus_NoError;
1699 }
1700
1701 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd, errno, strerror(errno));
1702 freeL("KQSocketEventSource", newSource);
1703 return mStatus_BadParamErr;
1704 }
1705
1706 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
1707 {
1708 (void) platform_data;
1709 return recv(fd, buf, len, flags);
1710 }
1711
1712 mDNSexport mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor
1713 {
1714 KQSocketEventSource **p = &gEventSources;
1715 (void) platform_data;
1716 while (*p && (*p)->fd != fd) p = &(*p)->next;
1717 if (*p)
1718 {
1719 KQSocketEventSource *s = *p;
1720 *p = (*p)->next;
1721 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
1722 // causes the kernel to automatically remove any associated kevents
1723 mDNSPlatformCloseFD(&s->kqs, s->fd);
1724 freeL("KQSocketEventSource", s);
1725 return mStatus_NoError;
1726 }
1727 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd);
1728 return mStatus_NoSuchNameErr;
1729 }
1730
1731 #ifdef UNIT_TEST
1732 #include "../unittests/daemon_ut.c"
1733 #endif // UNIT_TEST
1734
1735 #if _BUILDING_XCODE_PROJECT_
1736 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
1737 const char *__crashreporter_info__ = mDNSResponderVersionString;
1738 asm (".desc ___crashreporter_info__, 0x10");
1739 #endif
1740
1741 // For convenience when using the "strings" command, this is the last thing in the file
1742 // The "@(#) " pattern is a special prefix the "what" command looks for
1743 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";