1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil -*-
3 * Copyright (c) 2002-2019 Apple Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #include <mach/mach.h>
19 #include <mach/mach_error.h>
20 #include <sys/types.h>
27 #include <launch_priv.h> // for launch_socket_service_check_in()
29 #include <sys/event.h>
32 #include <SystemConfiguration/SCDynamicStoreCopyDHCPInfo.h>
35 #include <TargetConditionals.h>
38 #include "DNSCommon.h"
39 #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
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"
46 #include "posix_utilities.h" // for getLocalTimestamp()
48 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
52 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSD_XPC_SERVICE)
53 #include "dnssd_server.h"
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")
70 #if ENABLE_BLE_TRIGGERED_BONJOUR
71 #define kPreferencesKey_EnableBLEBasedDiscovery CFSTR("EnableBLEBasedDiscovery")
72 #define kPreferencesKey_DefaultToBLETriggered CFSTR("DefaultToBLETriggered")
73 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
75 #if MDNSRESPONDER_SUPPORTS(APPLE, PREALLOCATED_CACHE)
76 #define kPreferencesKey_PreallocateCacheMemory CFSTR("PreallocateCacheMemory")
80 //*************************************************************************************************************
81 #if COMPILER_LIKES_PRAGMA_MARK
82 #pragma mark - Globals
85 static mDNS_PlatformSupport PlatformStorage
;
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)
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
103 static dnssd_sock_t
*launchd_fds
= mDNSNULL
;
104 static size_t launchd_fds_count
= 0;
106 static mDNSBool NoMulticastAdvertisements
= mDNSfalse
; // By default, advertise addresses (& other records) via multicast
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
);
114 #if ENABLE_BLE_TRIGGERED_BONJOUR
115 extern mDNSBool EnableBLEBasedDiscovery
;
116 extern mDNSBool DefaultToBLETriggered
;
117 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
119 #if MDNSRESPONDER_SUPPORTS(APPLE, PREALLOCATED_CACHE)
120 static mDNSBool PreallocateCacheMemory
= mDNSfalse
;
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.
127 // We keep a list of client-supplied event sources in KQSocketEventSource records
128 typedef struct KQSocketEventSource
130 struct KQSocketEventSource
*next
;
133 udsEventCallback callback
;
135 } KQSocketEventSource
;
137 static KQSocketEventSource
*gEventSources
;
139 //*************************************************************************************************************
140 #if COMPILER_LIKES_PRAGMA_MARK
142 #pragma mark - General Utility Functions
145 #if MDNS_MALLOC_DEBUGGING
146 void mDNSPlatformValidateLists()
148 mDNS
*const m
= &mDNSStorage
;
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
);
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
);
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]);
166 #endif // MDNS_MALLOC_DEBUGGING
168 //*************************************************************************************************************
171 mDNSexport
void RecordUpdatedNiceLabel(mDNSs32 delay
)
173 mDNSStorage
.p
->NotifyUser
= NonZeroTime(mDNSStorage
.timenow
+ delay
);
176 mDNSlocal
void mDNSPreferencesSetNames(int key
, domainlabel
*old
, domainlabel
*new)
178 mDNS
*const m
= &mDNSStorage
;
179 domainlabel
*prevold
, *prevnew
;
182 case kmDNSComputerName
:
183 case kmDNSLocalHostName
:
184 if (key
== kmDNSComputerName
)
186 prevold
= &m
->p
->prevoldnicelabel
;
187 prevnew
= &m
->p
->prevnewnicelabel
;
191 prevold
= &m
->p
->prevoldhostlabel
;
192 prevnew
= &m
->p
->prevnewhostlabel
;
194 // There are a few cases where we need to invoke the helper.
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
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.
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
))
212 // Work around bug radar:21397654
213 #ifndef __clang_analyzer__
223 mDNSPreferencesSetName(key
, old
, new);
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
,
234 LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key
);
239 mDNSlocal
void mDNS_StatusCallback(mDNS
*const m
, mStatus result
)
241 if (result
== mStatus_NoError
)
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
);
248 else if (result
== mStatus_NameConflict
)
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
)
254 // Tell the helper we've given up
255 mDNSPreferencesSetNames(kmDNSLocalHostName
, &m
->p
->userhostlabel
, NULL
);
258 else if (result
== mStatus_GrowCache
)
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
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
);
271 else if (result
== mStatus_ConfigChanged
)
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
);
277 // Then we call into the UDS daemon code, to let it do the same
278 udsserver_handle_configchange(m
);
283 //*************************************************************************************************************
284 #if COMPILER_LIKES_PRAGMA_MARK
286 #pragma mark - Startup, shutdown, and supporting code
289 mDNSlocal
void ExitCallback(int sig
)
292 LogMsg("%s stopping", mDNSResponderVersionString
);
294 if (udsserver_exit() < 0)
295 LogMsg("ExitCallback: udsserver_exit failed");
297 debugf("ExitCallback: mDNS_StartExit");
298 mDNS_StartExit(&mDNSStorage
);
301 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
303 // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
304 mDNSlocal
void HandleSIG(int sig
)
306 kern_return_t status
;
307 mach_msg_header_t header
;
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
;
316 status
= mach_msg(&header
, MACH_SEND_MSG
| MACH_SEND_TIMEOUT
, header
.msgh_size
,
317 0, MACH_PORT_NULL
, 0, MACH_PORT_NULL
);
319 if (status
!= MACH_MSG_SUCCESS
)
321 if (status
== MACH_SEND_TIMED_OUT
) mach_msg_destroy(&header
);
322 if (sig
== SIGTERM
|| sig
== SIGINT
) exit(-1);
326 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
328 mDNSexport
void dump_state_to_fd(int fd
)
330 mDNS
*const m
= &mDNSStorage
;
334 mDNSs32 utc
= mDNSPlatformUTC();
335 const mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
336 NetworkInterfaceInfoOSX
*i
;
339 char timestamp
[64]; // 64 is enough to store the UTC timestmp
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
);
346 udsserver_info_dump_to_fd(fd
);
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
);
355 log_dnsproxy_info_to_fd(fd
, &mDNSStorage
);
357 LogToFD(fd
, "----- KQSocketEventSources -----");
358 if (!gEventSources
) LogToFD(fd
, "<None>");
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" : " ");
366 LogToFD(fd
, "------ Network Interfaces ------");
367 if (!mDNSStorage
.p
->InterfaceList
) LogToFD(fd
, "<None>");
370 LogToFD(fd
, " Struct addr Registered MAC BSSID Interface Address");
371 for (i
= mDNSStorage
.p
->InterfaceList
; i
; i
= i
->next
)
373 // Allow six characters for interface name, for names like "vmnet8"
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
);
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",
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]))
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
);
406 LogToFD(fd
, "--------- DNS Servers(%d) ----------", CountOfUnicastDNSServers(&mDNSStorage
));
407 if (!mDNSStorage
.DNSServers
) LogToFD(fd
, "<None>");
410 for (s
= mDNSStorage
.DNSServers
; s
; s
= s
->next
)
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
? "" : "!");
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
));
431 LogToFD(fd
, "-------- Interface Monitors --------");
432 const CFIndex n
= m
->p
->InterfaceMonitors
? CFArrayGetCount(m
->p
->InterfaceMonitors
) : 0;
435 for (CFIndex j
= 0; j
< n
; j
++)
437 mdns_interface_monitor_t monitor
= (mdns_interface_monitor_t
) CFArrayGetValueAtIndex(m
->p
->InterfaceMonitors
, j
);
438 char *description
= mdns_copy_description(monitor
);
441 LogToFD(fd
, "%s", description
);
446 LogToFD(fd
, "monitor %p (no description)", monitor
);
452 LogToFD(fd
, "No interface monitors");
455 LogToFD(fd
, "--------- Mcast Resolvers ----------");
456 if (!mDNSStorage
.McastResolvers
) LogToFD(fd
, "<None>");
459 for (mr
= mDNSStorage
.McastResolvers
; mr
; mr
= mr
->next
)
460 LogToFD(fd
, "Mcast Resolver %##s timeout %u", mr
->domain
.c
, mr
->timeout
);
463 LogToFD(fd
, "------------ Hostnames -------------");
464 if (!mDNSStorage
.Hostnames
) LogToFD(fd
, "<None>");
468 for (hi
= mDNSStorage
.Hostnames
; hi
; hi
= hi
->next
)
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
));
475 LogToFD(fd
, "--------------- FQDN ---------------");
476 if (!mDNSStorage
.FQDN
.c
[0]) LogToFD(fd
, "<None>");
479 LogToFD(fd
, "%##s", mDNSStorage
.FQDN
.c
);
482 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
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
);
492 mDNSexport
void INFOCallback(void)
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");
498 // Writes the state out to the dynamic store and also affects the ASL filter level
499 mDNSexport
void UpdateDebugState()
504 CFMutableDictionaryRef dict
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
507 LogMsg("UpdateDebugState: Could not create dict");
511 CFNumberRef numOne
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &one
);
514 LogMsg("UpdateDebugState: Could not create CFNumber one");
517 CFNumberRef numZero
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &zero
);
520 LogMsg("UpdateDebugState: Could not create CFNumber zero");
525 if (mDNS_LoggingEnabled
)
526 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numOne
);
528 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numZero
);
530 if (mDNS_PacketLoggingEnabled
)
531 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numOne
);
533 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numZero
);
535 if (mDNS_McastLoggingEnabled
)
536 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numOne
);
538 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numZero
);
540 if (mDNS_McastTracingEnabled
)
541 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numOne
);
543 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numZero
);
547 mDNSDynamicStoreSetConfig(kmDNSDebugState
, mDNSNULL
, dict
);
553 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
555 mDNSlocal
void SignalCallback(CFMachPortRef port
, void *msg
, CFIndex size
, void *info
)
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
;
563 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
565 switch(msg_header
->msgh_id
)
571 LogMsg("SIGHUP: Purge cache");
573 FORALL_CACHERECORDS(slot
, cg
, rr
)
575 rr
->resrec
.mortality
= Mortality_Mortal
;
576 mDNS_PurgeCacheResourceRecord(m
, rr
);
578 // Restart unicast and multicast queries
579 mDNSCoreRestartQueries(m
);
583 case SIGTERM
: ExitCallback(msg_header
->msgh_id
); break;
584 case SIGINFO
: INFOCallback(); break;
586 #if APPLE_OSX_mDNSResponder
587 mDNS_LoggingEnabled
= 1;
588 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
590 mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
591 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
593 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
595 LogInfo("USR1 Logging Enabled");
598 #if APPLE_OSX_mDNSResponder
599 mDNS_PacketLoggingEnabled
= 1;
600 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
602 mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
603 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
605 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
606 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
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");
616 case SIGTSTP
: mDNS_LoggingEnabled
= mDNS_PacketLoggingEnabled
= mDNS_McastLoggingEnabled
= mDNS_McastTracingEnabled
= mDNSfalse
;
617 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
621 default: LogMsg("SignalCallback: Unknown signal %d", msg_header
->msgh_id
); break;
623 KQueueUnlock("Unix Signal");
626 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
627 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
631 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
632 rrcachestorage
, RR_CACHE_SIZE
,
633 !NoMulticastAdvertisements
,
634 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
638 LogMsg("Daemon start: mDNS_Init failed %d", err
);
642 #if MDNSRESPONDER_SUPPORTS(APPLE, PREALLOCATED_CACHE)
643 if (PreallocateCacheMemory
)
645 const int growCount
= (kRRCacheMemoryLimit
+ kRRCacheGrowSize
- 1) / kRRCacheGrowSize
;
648 for (i
= 0; i
< growCount
; ++i
)
650 mDNS_StatusCallback(&mDNSStorage
, mStatus_GrowCache
);
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
);
664 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
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"
672 mDNSlocal
void SignalDispatch(dispatch_source_t source
)
674 int sig
= (int)dispatch_source_get_handle(source
);
675 mDNS
*const m
= &mDNSStorage
;
683 LogMsg("SIGHUP: Purge cache");
685 FORALL_CACHERECORDS(slot
, cg
, rr
)
687 rr
->resrec
.mortality
= Mortality_Mortal
;
688 mDNS_PurgeCacheResourceRecord(m
, rr
);
690 // Restart unicast and multicast queries
691 mDNSCoreRestartQueries(m
);
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;
702 case SIGUSR2
: mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
703 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
706 default: LogMsg("SignalCallback: Unknown signal %d", sig
); break;
708 KQueueUnlock("Unix Signal");
711 mDNSlocal
void mDNSSetupSignal(dispatch_queue_t queue
, int sig
)
713 signal(sig
, SIG_IGN
);
714 dispatch_source_t source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL
, sig
, 0, queue
);
718 dispatch_source_set_event_handler(source
, ^{SignalDispatch(source
);});
719 // Start processing signals
720 dispatch_resume(source
);
724 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig
);
728 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
731 dispatch_queue_t queue
= dispatch_get_main_queue();
733 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
734 rrcachestorage
, RR_CACHE_SIZE
,
735 !NoMulticastAdvertisements
,
736 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
740 LogMsg("Daemon start: mDNS_Init failed %d", err
);
744 mDNSSetupSignal(queue
, SIGHUP
);
745 mDNSSetupSignal(queue
, SIGINT
);
746 mDNSSetupSignal(queue
, SIGTERM
);
747 mDNSSetupSignal(queue
, SIGINFO
);
748 mDNSSetupSignal(queue
, SIGUSR1
);
749 mDNSSetupSignal(queue
, SIGUSR2
);
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
);
758 // Create a timer source to trigger housekeeping work. The houskeeping work itself
759 // is done in the custom handler that we set below.
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;}
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);
770 dispatch_resume(PlatformStorage
.timer
);
772 LogMsg("DaemonIntialize done successfully");
777 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
779 mDNSlocal mDNSs32
mDNSDaemonIdle(mDNS
*const m
)
781 mDNSs32 now
= mDNS_TimeNow(m
);
783 // 1. If we need to set domain secrets, do so before handling the network change
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)
789 m
->p
->KeyChainTimer
= 0;
795 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
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();
803 if (m
->p
->RequestReSleep
&& now
- m
->p
->RequestReSleep
>= 0)
805 m
->p
->RequestReSleep
= 0;
806 mDNSPowerRequest(0, 0);
809 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
810 mDNSs32 nextevent
= mDNS_Execute(m
);
812 if (m
->NetworkChanged
)
813 if (nextevent
- m
->NetworkChanged
> 0)
814 nextevent
= m
->NetworkChanged
;
816 if (m
->p
->KeyChainTimer
)
817 if (nextevent
- m
->p
->KeyChainTimer
> 0)
818 nextevent
= m
->p
->KeyChainTimer
;
820 if (m
->p
->RequestReSleep
)
821 if (nextevent
- m
->p
->RequestReSleep
> 0)
822 nextevent
= m
->p
->RequestReSleep
;
825 if (m
->p
->NotifyUser
)
827 if (m
->p
->NotifyUser
- now
< 0)
829 if (!SameDomainLabelCS(m
->p
->usernicelabel
.c
, m
->nicelabel
.c
))
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
;
835 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
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
;
842 m
->p
->NotifyUser
= 0;
845 if (nextevent
- m
->p
->NotifyUser
> 0)
846 nextevent
= m
->p
->NotifyUser
;
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)
859 mDNSu32 e
= 24 * 3600; // Maximum maintenance wake interval is 24 hours
860 const CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
861 if (!now
) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
866 const void *pattern
= SCDynamicStoreKeyCreateNetworkServiceEntity(NULL
, kSCDynamicStoreDomainState
, kSCCompAnyRegex
, kSCEntNetDHCP
);
869 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
872 CFArrayRef dhcpinfo
= CFArrayCreate(NULL
, (const void **)&pattern
, 1, &kCFTypeArrayCallBacks
);
876 SCDynamicStoreRef store
= SCDynamicStoreCreate(NULL
, CFSTR("DHCP-LEASES"), NULL
, NULL
);
879 CFDictionaryRef dict
= SCDynamicStoreCopyMultiple(store
, NULL
, dhcpinfo
);
882 ic
= CFDictionaryGetCount(dict
);
883 const void *vals
[ic
];
884 CFDictionaryGetKeysAndValues(dict
, NULL
, vals
);
886 for (j
= 0; j
< ic
; j
++)
888 const CFDictionaryRef dhcp
= (CFDictionaryRef
)vals
[j
];
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);
899 const UInt8
*d
= CFDataGetBytePtr(lease
);
900 if (!d
) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j
);
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
;
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.
931 mDNSlocal mDNSBool
AllowSleepNow(mDNSs32 now
)
933 mDNS
*const m
= &mDNSStorage
;
934 mDNSBool ready
= mDNSCoreReadyForSleep(m
, now
);
935 if (m
->SleepState
&& !ready
&& now
- m
->SleepLimit
< 0) return(mDNSfalse
);
938 int result
= kIOReturnSuccess
;
939 CFDictionaryRef opts
= NULL
;
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.
944 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m
->SleepLimit
- now
);
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");
953 mDNSs32 dhcp
= DHCPWakeTime();
954 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp
);
955 mDNSs32 interval
= mDNSCoreIntervalToNextWake(m
, now
) / mDNSPlatformOneSecond
;
956 if (interval
> dhcp
) interval
= dhcp
;
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;
964 //interval = 48; // For testing
966 #if TARGET_OS_OSX && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
967 if (m
->p
->IOPMConnection
) // If lightweight-wake capability is available, use that
969 const CFDateRef WakeDate
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent() + interval
);
970 if (!WakeDate
) LogMsg("ScheduleNextWake: CFDateCreate failed");
973 const mDNSs32 reqs
= kIOPMSystemPowerStateCapabilityNetwork
;
974 const CFNumberRef Requirements
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &reqs
);
975 if (Requirements
== NULL
) LogMsg("ScheduleNextWake: CFNumberCreate failed");
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
);
986 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval
);
988 else // else schedule the wakeup using the old API instead to
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.
998 result
= mDNSPowerRequest(1, interval
);
1000 if (result
== kIOReturnNotReady
)
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.
1013 interval
+= (interval
< 20) ? 1 : ((interval
+3) / 4);
1014 r
= mDNSPowerRequest(1, interval
);
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
);
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
);
1025 m
->p
->WakeAtUTC
= mDNSPlatformUTC() + interval
;
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();
1035 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1036 #if TARGET_OS_OSX && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1037 (m
->p
->IOPMConnection
) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1039 (result
== kIOReturnSuccess
) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1040 m
->p
->SleepCookie
, ready
? "ready for sleep" : "giving up", now
, m
->SleepLimit
- now
);
1042 m
->SleepLimit
= 0; // Don't clear m->SleepLimit until after we've logged it above
1043 m
->TimeSlept
= mDNSPlatformUTC();
1045 #if TARGET_OS_OSX && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1046 if (m
->p
->IOPMConnection
) IOPMConnectionAcknowledgeEventWithOptions(m
->p
->IOPMConnection
, m
->p
->SleepCookie
, opts
);
1049 if (result
== kIOReturnSuccess
) IOAllowPowerChange (m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1050 else IOCancelPowerChange(m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1052 if (opts
) CFRelease(opts
);
1056 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1058 mDNSexport
void TriggerEventCompletion()
1060 debugf("TriggerEventCompletion: Merge data");
1061 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
1064 mDNSlocal
void PrepareForIdle(void *m_param
)
1067 int64_t time_offset
;
1068 dispatch_time_t dtime
;
1070 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
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
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
)
1084 nextTimerEvent
= dso_idle(m
, nextTimerEvent
);
1087 mDNSs32 end
= mDNSPlatformRawTime();
1088 if (end
- start
>= WatchDogReportingThreshold
)
1090 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_WARNING
,
1091 "CustomSourceHandler: WARNING: Idle task took %d ms to complete", end
- start
);
1094 mDNSs32 now
= mDNS_TimeNow(m
);
1096 if (m
->ShutdownTime
)
1098 if (mDNSStorage
.ResourceRecords
)
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
1103 if (mDNS_ExitNow(m
, now
))
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
1110 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1111 nextTimerEvent
= m
->ShutdownTime
;
1115 if (!AllowSleepNow(now
))
1116 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1117 nextTimerEvent
= m
->SleepLimit
;
1119 // Convert absolute wakeup time to a relative time from now
1120 mDNSs32 ticks
= nextTimerEvent
- now
;
1121 if (ticks
< 1) ticks
= 1;
1123 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1129 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
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
);
1139 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1141 mDNSlocal
void KQWokenFlushBytes(int fd
, __unused
short filter
, __unused
void *context
, __unused mDNSBool encounteredEOF
)
1143 // Read all of the bytes so we won't wake again.
1145 while (recv(fd
, buffer
, sizeof(buffer
), MSG_DONTWAIT
) > 0) continue;
1148 mDNSlocal
void SetLowWater(const KQSocketSet
*const k
, const int r
)
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
));
1156 mDNSlocal
void * KQueueLoop(void *m_param
)
1161 #if USE_SELECT_WITH_KQUEUEFD
1164 const int multiplier
= 1000000 / mDNSPlatformOneSecond
;
1166 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1169 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1170 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32
)mDNSStorage
.timenow_last
, mDNSStorage
.timenow_last
);
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
1180 #define kEventsToReadAtOnce 1
1181 struct kevent new_events
[kEventsToReadAtOnce
];
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();
1189 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
1190 if (m
->DNSPushServers
!= mDNSNULL
)
1193 nextTimerEvent
= dso_idle(m
, m
->timenow
, nextTimerEvent
);
1197 mDNSs32 end
= mDNSPlatformRawTime();
1198 if (end
- start
>= WatchDogReportingThreshold
)
1200 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_WARNING
, "WARNING: Idle task took %d ms to complete", end
- start
);
1203 #if MDNS_MALLOC_DEBUGGING >= 1
1204 mDNSPlatformValidateLists();
1207 mDNSs32 now
= mDNS_TimeNow(m
);
1209 if (m
->ShutdownTime
)
1211 if (mDNSStorage
.ResourceRecords
)
1214 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
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
1220 if (mDNS_ExitNow(m
, now
))
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
1227 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1228 nextTimerEvent
= m
->ShutdownTime
;
1232 if (!AllowSleepNow(now
))
1233 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1234 nextTimerEvent
= m
->SleepLimit
;
1236 // Convert absolute wakeup time to a relative time from now
1237 mDNSs32 ticks
= nextTimerEvent
- now
;
1238 if (ticks
< 1) ticks
= 1;
1240 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1246 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1249 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents
, ticks
);
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
);
1258 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1259 if (m
->p
->num_mcasts
)
1261 SetLowWater(&m
->p
->permanentsockets
, 0x10000);
1262 if (ticks
> mDNSPlatformOneSecond
/ 8) ticks
= mDNSPlatformOneSecond
/ 8;
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); }
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); }
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.
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
)
1295 SetLowWater(&m
->p
->permanentsockets
, 1);
1296 m
->p
->num_mcasts
= 0;
1299 static const struct timespec zero_timeout
= { 0, 0 };
1301 while ((events_found
= kevent(KQueueFD
, NULL
, 0, new_events
, kEventsToReadAtOnce
, &zero_timeout
)) != 0)
1303 if (events_found
> kEventsToReadAtOnce
|| (events_found
< 0 && errno
!= EINTR
))
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
));
1311 numevents
+= events_found
;
1314 for (i
= 0; i
< events_found
; i
++)
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
)
1323 LogRedact(MDNS_LOG_CATEGORY_DEFAULT
, MDNS_LOG_WARNING
,
1324 "WARNING: " PUB_S
" took %d ms to complete", KQtask
, etime
- stime
);
1333 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1335 mDNSlocal
size_t LaunchdCheckin(void)
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
;
1344 extern int sandbox_init(const char *profile
, uint64_t flags
, char **errorbuf
) __attribute__((weak_import
));
1346 #if APPLE_OSX_mDNSResponder
1347 mDNSlocal mDNSBool
PreferencesGetValueBool(CFStringRef key
, mDNSBool defaultValue
)
1349 CFBooleanRef boolean
;
1350 mDNSBool result
= defaultValue
;
1352 boolean
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1353 if (boolean
!= NULL
)
1355 if (CFGetTypeID(boolean
) == CFBooleanGetTypeID())
1356 result
= CFBooleanGetValue(boolean
) ? mDNStrue
: mDNSfalse
;
1363 mDNSlocal
int PreferencesGetValueInt(CFStringRef key
, int defaultValue
)
1367 int result
= defaultValue
;
1369 number
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1372 if ((CFGetTypeID(number
) == CFNumberGetTypeID()) && CFNumberGetValue(number
, kCFNumberIntType
, &numberValue
))
1373 result
= numberValue
;
1381 mDNSlocal
void SandboxProcess(void)
1383 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1385 LogMsg("Note: Compiled without Apple Sandbox support");
1386 #else // MDNS_NO_SANDBOX
1388 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1392 uint64_t sandbox_flags
= SANDBOX_NAMED
;
1394 (void)confstr(_CS_DARWIN_USER_CACHE_DIR
, NULL
, 0);
1396 int sandbox_err
= sandbox_init("mDNSResponder", sandbox_flags
, &sandbox_msg
);
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);
1404 errx(EX_OSERR
, "sandbox_init() failed: %s", sandbox_msg
);
1406 else LogInfo("Now running under Apple Sandbox restrictions");
1408 #endif // MDNS_NO_SANDBOX
1411 #if MDNSRESPONDER_SUPPORTS(APPLE, OS_LOG)
1412 #define MDNS_OS_LOG_CATEGORY_INIT(NAME) \
1415 mDNSLogCategory_ ## NAME = os_log_create("com.apple.mDNSResponder", # NAME ); \
1416 if (!mDNSLogCategory_ ## NAME ) \
1418 os_log_error(OS_LOG_DEFAULT, "Could NOT create the " # NAME " log handle in mDNSResponder"); \
1419 mDNSLogCategory_ ## NAME = OS_LOG_DEFAULT; \
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
;
1430 mDNSlocal
void init_logging(void)
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
);
1440 mDNSexport
int main(int argc
, char **argv
)
1443 kern_return_t status
;
1446 bool useDebugSocket
= mDNSfalse
;
1447 bool useSandbox
= mDNStrue
;
1450 #if MDNSRESPONDER_SUPPORTS(APPLE, OS_LOG)
1454 mDNSMacOSXSystemBuildNumber(NULL
);
1455 LogMsg("%s starting %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
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
));
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
);
1471 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1475 for (i
=1; i
<argc
; i
++)
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
;
1490 if (!strcasecmp(argv
[i
], "-UseDebugSocket")) useDebugSocket
= mDNStrue
;
1491 if (!strcasecmp(argv
[i
], "-NoSandbox")) useSandbox
= mDNSfalse
;
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
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
1505 To turn OFF all options, here is what the user should do
1506 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1509 To view the current options set, here is what the user should do
1510 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1512 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
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.
1519 mDNS_LoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_DebugLogging
, mDNS_LoggingEnabled
);
1520 mDNS_PacketLoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging
, mDNS_PacketLoggingEnabled
);
1523 mDNS_LoggingEnabled
= mDNStrue
;
1524 mDNS_PacketLoggingEnabled
= mDNStrue
;
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
);
1533 #if ENABLE_BLE_TRIGGERED_BONJOUR
1534 EnableBLEBasedDiscovery
= PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery
, EnableBLEBasedDiscovery
);
1535 DefaultToBLETriggered
= PreferencesGetValueBool(kPreferencesKey_DefaultToBLETriggered
, DefaultToBLETriggered
);
1536 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
1539 #if MDNSRESPONDER_SUPPORTS(APPLE, PREALLOCATED_CACHE)
1540 PreallocateCacheMemory
= PreferencesGetValueBool(kPreferencesKey_PreallocateCacheMemory
, PreallocateCacheMemory
);
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");
1551 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
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)
1563 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1565 mDNSStorage
.p
= &PlatformStorage
; // Make sure mDNSStorage.p is set up, because validatelists uses it
1567 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1569 // Create the kqueue, mutex and thread to support KQSockets
1570 KQueueFD
= kqueue();
1573 const int kqueue_errno
= errno
;
1574 LogMsg("kqueue() failed errno %d (%s)", kqueue_errno
, strerror(kqueue_errno
));
1575 status
= kqueue_errno
;
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
; }
1582 int fdpair
[2] = {0, 0};
1583 i
= socketpair(AF_UNIX
, SOCK_STREAM
, 0, fdpair
);
1586 const int socketpair_errno
= errno
;
1587 LogMsg("socketpair() failed errno %d (%s)", socketpair_errno
, strerror(socketpair_errno
));
1588 status
= socketpair_errno
;
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" };
1597 PlatformStorage
.WakeKQueueLoopFD
= fdpair
[0];
1598 KQueueSet(fdpair
[1], EV_ADD
, EVFILT_READ
, &wakeKQEntry
);
1600 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1607 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
1608 status
= MetricsInit();
1609 if (status
) { LogMsg("Daemon start: MetricsInit failed (%d)", status
); }
1612 status
= mDNSDaemonInitialize();
1613 if (status
) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit
; }
1615 // Need to Start XPC Server Before LaunchdCheckin() (Reason: radar:11023750)
1617 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSD_XPC_SERVICE)
1618 dnssd_server_init();
1621 if (!useDebugSocket
) {
1622 if (LaunchdCheckin() == 0)
1623 useDebugSocket
= mDNStrue
;
1626 SetDebugBoundPath();
1631 status
= udsserver_init(launchd_fds
, launchd_fds_count
);
1632 if (status
) { LogMsg("Daemon start: udsserver_init failed"); goto exit
; }
1634 mDNSMacOSXNetworkChanged();
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
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
; }
1649 LogMsg("ERROR: CFRunLoopRun Exiting.");
1650 mDNS_Close(&mDNSStorage
);
1652 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1654 LogMsg("%s exiting", mDNSResponderVersionString
);
1660 // uds_daemon.c support routines /////////////////////////////////////////////
1662 mDNSlocal
void kqUDSEventCallback(int fd
, short filter
, void *context
, mDNSBool encounteredEOF
)
1664 const KQSocketEventSource
*const source
= context
;
1665 (void)filter
; // unused
1666 (void)encounteredEOF
; // unused
1668 source
->callback(fd
, source
->context
);
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
)
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
; }
1679 KQSocketEventSource
*newSource
= (KQSocketEventSource
*) callocL("KQSocketEventSource", sizeof(*newSource
));
1680 if (!newSource
) return mStatus_NoMemoryErr
;
1682 newSource
->next
= mDNSNULL
;
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
1695 if (KQueueSet(fd
, EV_ADD
, EVFILT_READ
, &newSource
->kqs
) == 0)
1698 return mStatus_NoError
;
1701 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd
, errno
, strerror(errno
));
1702 freeL("KQSocketEventSource", newSource
);
1703 return mStatus_BadParamErr
;
1706 int udsSupportReadFD(dnssd_sock_t fd
, char *buf
, int len
, int flags
, void *platform_data
)
1708 (void) platform_data
;
1709 return recv(fd
, buf
, len
, flags
);
1712 mDNSexport mStatus
udsSupportRemoveFDFromEventLoop(int fd
, void *platform_data
) // Note: This also CLOSES the file descriptor
1714 KQSocketEventSource
**p
= &gEventSources
;
1715 (void) platform_data
;
1716 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1719 KQSocketEventSource
*s
= *p
;
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
;
1727 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd
);
1728 return mStatus_NoSuchNameErr
;
1732 #include "../unittests/daemon_ut.c"
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");
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__
")";