1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2015 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>
41 #include "DNSCommon.h"
42 #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
44 #include "uds_daemon.h" // Interface to the server side implementation of dns_sd.h
45 #include "xpc_services.h" // Interface to XPC services
52 #if APPLE_OSX_mDNSResponder
53 static os_log_t log_general
= NULL
;
57 // Used on OSX(10.11.x onwards) for manipulating mDNSResponder program arguments
58 #if APPLE_OSX_mDNSResponder
59 // plist file to read the user's preferences
60 #define kProgramArguments CFSTR("com.apple.mDNSResponder")
61 // possible arguments for external customers
62 #define kPreferencesKey_DebugLogging CFSTR("DebugLogging")
63 #define kPreferencesKey_UnicastPacketLogging CFSTR("UnicastPacketLogging")
64 #define kPreferencesKey_AlwaysAppendSearchDomains CFSTR("AlwaysAppendSearchDomains")
65 #define kPreferencesKey_EnableAllowExpired CFSTR("EnableAllowExpired")
66 #define kPreferencesKey_NoMulticastAdvertisements CFSTR("NoMulticastAdvertisements")
67 #define kPreferencesKey_StrictUnicastOrdering CFSTR("StrictUnicastOrdering")
68 #define kPreferencesKey_OfferSleepProxyService CFSTR("OfferSleepProxyService")
69 #define kPreferencesKey_UseInternalSleepProxy CFSTR("UseInternalSleepProxy")
71 #if ENABLE_BLE_TRIGGERED_BONJOUR
72 #define kPreferencesKey_EnableBLEBasedDiscovery CFSTR("EnableBLEBasedDiscovery")
73 #define kPreferencesKey_DefaultToBLETriggered CFSTR("DefaultToBLETriggered")
74 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
77 #define kPreferencesKey_PreallocateCacheMemory CFSTR("PreallocateCacheMemory")
81 //*************************************************************************************************************
82 #if COMPILER_LIKES_PRAGMA_MARK
83 #pragma mark - Globals
86 static mDNS_PlatformSupport PlatformStorage
;
88 // Start off with a default cache of 32K (136 records of 240 bytes each)
89 // Each time we grow the cache we add another 136 records
90 // 136 * 240 = 32640 bytes.
91 // This fits in eight 4kB pages, with 128 bytes spare for memory block headers and similar overhead
92 #define RR_CACHE_SIZE ((32*1024) / sizeof(CacheRecord))
93 static CacheEntity rrcachestorage
[RR_CACHE_SIZE
];
94 struct CompileTimeAssertionChecks_RR_CACHE_SIZE
{ char a
[(RR_CACHE_SIZE
>= 136) ? 1 : -1]; };
95 #define kRRCacheGrowSize (sizeof(CacheEntity) * RR_CACHE_SIZE)
98 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
99 mDNSlocal
void PrepareForIdle(void *m_param
);
100 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
101 static mach_port_t signal_port
= MACH_PORT_NULL
;
102 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
104 static dnssd_sock_t
*launchd_fds
= mDNSNULL
;
105 static size_t launchd_fds_count
= 0;
107 static mDNSBool NoMulticastAdvertisements
= mDNSfalse
; // By default, advertise addresses (& other records) via multicast
109 extern mDNSBool StrictUnicastOrdering
;
110 extern mDNSBool AlwaysAppendSearchDomains
;
111 extern mDNSBool EnableAllowExpired
;
113 #if ENABLE_BLE_TRIGGERED_BONJOUR
114 extern mDNSBool EnableBLEBasedDiscovery
;
115 extern mDNSBool DefaultToBLETriggered
;
116 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
119 static mDNSBool PreallocateCacheMemory
= mDNSfalse
;
120 #define kRRCacheMemoryLimit 1000000 // For now, we limit the cache to at most 1MB on iOS devices.
123 // We keep a list of client-supplied event sources in KQSocketEventSource records
124 typedef struct KQSocketEventSource
126 struct KQSocketEventSource
*next
;
129 udsEventCallback callback
;
131 } KQSocketEventSource
;
133 static KQSocketEventSource
*gEventSources
;
135 //*************************************************************************************************************
136 #if COMPILER_LIKES_PRAGMA_MARK
138 #pragma mark - General Utility Functions
141 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
143 char _malloc_options
[] = "AXZ";
145 mDNSlocal
void validatelists(mDNS
*const m
)
147 #if BONJOUR_ON_DEMAND
148 mDNSu32 NumAllInterfaceRecords
= 0;
149 mDNSu32 NumAllInterfaceQuestions
= 0;
150 #endif // BONJOUR_ON_DEMAND
153 KQSocketEventSource
*k
;
154 for (k
= gEventSources
; k
; k
=k
->next
)
155 if (k
->next
== (KQSocketEventSource
*)~0 || k
->fd
< 0)
156 LogMemCorruption("gEventSources: %p is garbage (%d)", k
, k
->fd
);
158 // Check Unix Domain Socket client lists (uds_daemon.c)
161 // Check core mDNS lists
163 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
165 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
166 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
167 if (rr
->resrec
.name
!= &rr
->namestorage
)
168 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
169 rr
, rr
->resrec
.name
->c
, rr
->namestorage
.c
, rr
->namestorage
.c
);
170 #if BONJOUR_ON_DEMAND
171 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
172 #endif // BONJOUR_ON_DEMAND
175 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
)
177 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
178 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
179 #if BONJOUR_ON_DEMAND
180 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
181 #endif // BONJOUR_ON_DEMAND
184 rr
= m
->NewLocalRecords
;
186 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
187 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
189 rr
= m
->CurrentRecord
;
191 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
192 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
195 for (q
= m
->Questions
; q
; q
=q
->next
)
197 if (q
->next
== (DNSQuestion
*)~0 || q
->ThisQInterval
== (mDNSs32
) ~0)
198 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q
, q
->ThisQInterval
, q
->next
);
199 if (q
->DuplicateOf
&& q
->LocalSocket
)
200 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
201 #if BONJOUR_ON_DEMAND
202 if (!LocalOnlyOrP2PInterface(q
->InterfaceID
) && mDNSOpaque16IsZero(q
->TargetQID
))
203 NumAllInterfaceQuestions
++;
204 #endif // BONJOUR_ON_DEMAND
210 FORALL_CACHERECORDS(slot
, cg
, cr
)
212 if (cr
->resrec
.RecordType
== 0 || cr
->resrec
.RecordType
== 0xFF)
213 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot
, cr
, cr
->resrec
.RecordType
);
214 if (cr
->CRActiveQuestion
)
216 for (q
= m
->Questions
; q
; q
=q
->next
) if (q
== cr
->CRActiveQuestion
) break;
217 if (!q
) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot
, cr
->CRActiveQuestion
, CRDisplayString(m
, cr
));
221 // Check core uDNS lists
222 udns_validatelists(m
);
224 // Check platform-layer lists
225 NetworkInterfaceInfoOSX
*i
;
226 for (i
= m
->p
->InterfaceList
; i
; i
= i
->next
)
227 if (i
->next
== (NetworkInterfaceInfoOSX
*)~0 || !i
->m
|| i
->m
== (mDNS
*)~0)
228 LogMemCorruption("m->p->InterfaceList: %p is garbage (%p)", i
, i
->ifinfo
.ifname
);
231 for (t
= m
->TunnelClients
; t
; t
=t
->next
)
232 if (t
->next
== (ClientTunnel
*)~0 || t
->dstname
.c
[0] > 63)
233 LogMemCorruption("m->TunnelClients: %p is garbage (%d)", t
, t
->dstname
.c
[0]);
235 #if BONJOUR_ON_DEMAND
236 if (m
->NumAllInterfaceRecords
!= NumAllInterfaceRecords
)
237 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m
->NumAllInterfaceRecords
, NumAllInterfaceRecords
);
239 if (m
->NumAllInterfaceQuestions
!= NumAllInterfaceQuestions
)
240 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m
->NumAllInterfaceQuestions
, NumAllInterfaceQuestions
);
241 #endif // BONJOUR_ON_DEMAND
244 mDNSexport
void *mallocL(char *msg
, unsigned int size
)
246 // Allocate space for two words of sanity checking data before the requested block
247 mDNSu32
*mem
= malloc(sizeof(mDNSu32
) * 2 + size
);
249 { LogMsg("malloc( %s : %d ) failed", msg
, size
); return(NULL
); }
252 if (size
> 32768) LogMsg("malloc( %s : %lu ) @ %p suspiciously large", msg
, size
, &mem
[2]);
253 else if (MACOSX_MDNS_MALLOC_DEBUGGING
>= 2) LogMsg("malloc( %s : %lu ) @ %p", msg
, size
, &mem
[2]);
256 //mDNSPlatformMemZero(&mem[2], size);
257 memset(&mem
[2], 0xFF, size
);
258 validatelists(&mDNSStorage
);
263 mDNSexport
void freeL(char *msg
, void *x
)
266 LogMsg("free( %s @ NULL )!", msg
);
269 mDNSu32
*mem
= ((mDNSu32
*)x
) - 2;
270 if (mem
[0] == 0xDEADDEAD) { LogMemCorruption("free( %s : %lu @ %p ) !!!! ALREADY DISPOSED !!!!", msg
, mem
[1], &mem
[2]); return; }
271 if (mem
[0] != 0xDEAD1234) { LogMemCorruption("free( %s : %lu @ %p ) !!!! NEVER ALLOCATED !!!!", msg
, mem
[1], &mem
[2]); return; }
272 if (mem
[1] > 32768) LogMsg("free( %s : %lu @ %p) suspiciously large", msg
, mem
[1], &mem
[2]);
273 else if (MACOSX_MDNS_MALLOC_DEBUGGING
>= 2) LogMsg("free( %s : %ld @ %p)", msg
, mem
[1], &mem
[2]);
275 memset(mem
+2, 0xFF, mem
[1]);
276 validatelists(&mDNSStorage
);
283 //*************************************************************************************************************
286 mDNSexport
void RecordUpdatedNiceLabel(mDNSs32 delay
)
288 mDNSStorage
.p
->NotifyUser
= NonZeroTime(mDNSStorage
.timenow
+ delay
);
291 mDNSlocal
void mDNSPreferencesSetNames(int key
, domainlabel
*old
, domainlabel
*new)
293 mDNS
*const m
= &mDNSStorage
;
294 domainlabel
*prevold
, *prevnew
;
297 case kmDNSComputerName
:
298 case kmDNSLocalHostName
:
299 if (key
== kmDNSComputerName
)
301 prevold
= &m
->p
->prevoldnicelabel
;
302 prevnew
= &m
->p
->prevnewnicelabel
;
306 prevold
= &m
->p
->prevoldhostlabel
;
307 prevnew
= &m
->p
->prevnewhostlabel
;
309 // There are a few cases where we need to invoke the helper.
311 // 1. If the "old" label and "new" label are not same, it means there is a conflict. We need
312 // to invoke the helper so that it pops up a dialogue to inform the user about the
315 // 2. If the "old" label and "new" label are same, it means the user has set the host/nice label
316 // through the preferences pane. We may have to inform the helper as it may have popped up
317 // a dialogue previously (due to a conflict) and it needs to suppress it now. We can avoid invoking
318 // the helper in this case if the previous values (old and new) that we told helper last time
319 // are same. If the previous old and new values are same, helper does not care.
321 // Note: "new" can be NULL when we have repeated conflicts and we are asking helper to give up. "old"
322 // is not called with NULL today, but this makes it future proof.
323 if (!old
|| !new || !SameDomainLabelCS(old
->c
, new->c
) ||
324 !SameDomainLabelCS(old
->c
, prevold
->c
) ||
325 !SameDomainLabelCS(new->c
, prevnew
->c
))
327 // Work around bug radar:21397654
328 #ifndef __clang_analyzer__
338 mDNSPreferencesSetName(key
, old
, new);
342 LogInfo("mDNSPreferencesSetNames not invoking helper %s %#s, %s %#s, old %#s, new %#s",
343 (key
== kmDNSComputerName
? "prevoldnicelabel" : "prevoldhostlabel"), prevold
->c
,
344 (key
== kmDNSComputerName
? "prevnewnicelabel" : "prevnewhostlabel"), prevnew
->c
,
349 LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key
);
354 mDNSlocal
void mDNS_StatusCallback(mDNS
*const m
, mStatus result
)
356 if (result
== mStatus_NoError
)
358 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
359 LogInfo("Local Hostname changed from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
360 // One second pause in case we get a Computer Name update too -- don't want to alert the user twice
361 RecordUpdatedNiceLabel(mDNSPlatformOneSecond
);
363 else if (result
== mStatus_NameConflict
)
365 LogInfo("Local Hostname conflict for \"%#s.local\"", m
->hostlabel
.c
);
366 if (!m
->p
->HostNameConflict
) m
->p
->HostNameConflict
= NonZeroTime(m
->timenow
);
367 else if (m
->timenow
- m
->p
->HostNameConflict
> 60 * mDNSPlatformOneSecond
)
369 // Tell the helper we've given up
370 mDNSPreferencesSetNames(kmDNSLocalHostName
, &m
->p
->userhostlabel
, NULL
);
373 else if (result
== mStatus_GrowCache
)
375 // Allocate another chunk of cache storage
376 static unsigned int allocated
= 0;
378 if (allocated
>= kRRCacheMemoryLimit
) return; // For now we limit the cache to at most 1MB on iOS devices
380 allocated
+= kRRCacheGrowSize
;
381 // LogMsg("GrowCache %d * %d = %d; total so far %6u", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE, allocated);
382 CacheEntity
*storage
= mallocL("mStatus_GrowCache", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
383 //LogInfo("GrowCache %d * %d = %d", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE);
384 if (storage
) mDNS_GrowCache(m
, storage
, RR_CACHE_SIZE
);
386 else if (result
== mStatus_ConfigChanged
)
388 // Tell the helper we've seen a change in the labels. It will dismiss the name conflict alert if needed.
389 mDNSPreferencesSetNames(kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
390 mDNSPreferencesSetNames(kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
392 // Then we call into the UDS daemon code, to let it do the same
393 udsserver_handle_configchange(m
);
398 //*************************************************************************************************************
399 #if COMPILER_LIKES_PRAGMA_MARK
401 #pragma mark - Startup, shutdown, and supporting code
404 mDNSlocal
void ExitCallback(int sig
)
407 LogMsg("%s stopping", mDNSResponderVersionString
);
409 if (udsserver_exit() < 0)
410 LogMsg("ExitCallback: udsserver_exit failed");
412 debugf("ExitCallback: mDNS_StartExit");
413 mDNS_StartExit(&mDNSStorage
);
416 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
418 // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
419 mDNSlocal
void HandleSIG(int sig
)
421 kern_return_t status
;
422 mach_msg_header_t header
;
424 // WARNING: can't call syslog or fprintf from signal handler
425 header
.msgh_bits
= MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND
, 0);
426 header
.msgh_remote_port
= signal_port
;
427 header
.msgh_local_port
= MACH_PORT_NULL
;
428 header
.msgh_size
= sizeof(header
);
429 header
.msgh_id
= sig
;
431 status
= mach_msg(&header
, MACH_SEND_MSG
| MACH_SEND_TIMEOUT
, header
.msgh_size
,
432 0, MACH_PORT_NULL
, 0, MACH_PORT_NULL
);
434 if (status
!= MACH_MSG_SUCCESS
)
436 if (status
== MACH_SEND_TIMED_OUT
) mach_msg_destroy(&header
);
437 if (sig
== SIGTERM
|| sig
== SIGINT
) exit(-1);
441 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
443 mDNSexport
void INFOCallback(void)
445 mDNSs32 utc
= mDNSPlatformUTC();
446 const mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
447 NetworkInterfaceInfoOSX
*i
;
451 LogMsg("---- BEGIN STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
455 LogMsgNoIdent("----- Platform Timers -----");
456 LogTimer("m->NextCacheCheck ", mDNSStorage
.NextCacheCheck
);
457 LogTimer("m->NetworkChanged ", mDNSStorage
.NetworkChanged
);
458 LogTimer("m->p->NotifyUser ", mDNSStorage
.p
->NotifyUser
);
459 LogTimer("m->p->HostNameConflict ", mDNSStorage
.p
->HostNameConflict
);
460 LogTimer("m->p->KeyChainTimer ", mDNSStorage
.p
->KeyChainTimer
);
462 xpcserver_info(&mDNSStorage
);
464 LogMsgNoIdent("----- KQSocketEventSources -----");
465 if (!gEventSources
) LogMsgNoIdent("<None>");
468 KQSocketEventSource
*k
;
469 for (k
= gEventSources
; k
; k
=k
->next
)
470 LogMsgNoIdent("%3d %s %s", k
->fd
, k
->kqs
.KQtask
, k
->fd
== mDNSStorage
.uds_listener_skt
? "Listener for incoming UDS clients" : " ");
473 LogMsgNoIdent("------ Network Interfaces ------");
474 if (!mDNSStorage
.p
->InterfaceList
) LogMsgNoIdent("<None>");
477 LogMsgNoIdent(" Struct addr Registered MAC BSSID Interface Address");
478 for (i
= mDNSStorage
.p
->InterfaceList
; i
; i
= i
->next
)
480 // Allow six characters for interface name, for names like "vmnet8"
482 LogMsgNoIdent("%p %2ld, %p, %s %-6s %.6a %.6a %#-14a dormant for %d seconds",
483 i
, i
->ifinfo
.InterfaceID
, i
->Registered
,
484 i
->sa_family
== AF_INET
? "v4" : i
->sa_family
== AF_INET6
? "v6" : "??", i
->ifinfo
.ifname
, &i
->ifinfo
.MAC
, &i
->BSSID
,
485 &i
->ifinfo
.ip
, utc
- i
->LastSeen
);
488 const CacheRecord
*sps
[3];
489 FindSPSInCache(&mDNSStorage
, &i
->ifinfo
.NetWakeBrowse
, sps
);
490 LogMsgNoIdent("%p %2ld, %p, %s %-6s %.6a %.6a %s %s %s %s %s %s %#a",
491 i
, i
->ifinfo
.InterfaceID
, i
->Registered
,
492 i
->sa_family
== AF_INET
? "v4" : i
->sa_family
== AF_INET6
? "v6" : "??", i
->ifinfo
.ifname
, &i
->ifinfo
.MAC
, &i
->BSSID
,
493 i
->ifinfo
.InterfaceActive
? "Active" : " ",
494 i
->ifinfo
.IPv4Available
? "v4" : " ",
495 i
->ifinfo
.IPv6Available
? "v6" : " ",
496 i
->ifinfo
.Advertise
? "A" : " ",
497 i
->ifinfo
.McastTxRx
? "M" : " ",
498 !(i
->ifinfo
.InterfaceActive
&& i
->ifinfo
.NetWake
) ? " " : !sps
[0] ? "p" : "P",
501 // Only print the discovered sleep proxies once for the lead/active interface of an interface set.
502 if (i
== i
->Registered
&& (sps
[0] || sps
[1] || sps
[2]))
504 LogMsgNoIdent(" Sleep Proxy Metric Name");
505 if (sps
[0]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[0]->resrec
.rdata
->u
.name
.c
), sps
[0]->resrec
.rdata
->u
.name
.c
);
506 if (sps
[1]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[1]->resrec
.rdata
->u
.name
.c
), sps
[1]->resrec
.rdata
->u
.name
.c
);
507 if (sps
[2]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[2]->resrec
.rdata
->u
.name
.c
), sps
[2]->resrec
.rdata
->u
.name
.c
);
513 LogMsgNoIdent("--------- DNS Servers(%d) ----------", NumUnicastDNSServers
);
514 if (!mDNSStorage
.DNSServers
) LogMsgNoIdent("<None>");
517 for (s
= mDNSStorage
.DNSServers
; s
; s
= s
->next
)
519 NetworkInterfaceInfoOSX
*ifx
= IfindexToInterfaceInfoOSX(s
->interface
);
520 LogMsgNoIdent("DNS Server %##s %s%s%#a:%d %d %s %d %d %s %s %s %s %s %s",
521 s
->domain
.c
, ifx
? ifx
->ifinfo
.ifname
: "", ifx
? " " : "", &s
->addr
, mDNSVal16(s
->port
),
522 s
->penaltyTime
? s
->penaltyTime
- mDNS_TimeNow(&mDNSStorage
) : 0, DNSScopeToString(s
->scoped
),
523 s
->timeout
, s
->resGroupID
,
524 s
->req_A
? "v4" : "!v4",
525 s
->req_AAAA
? "v6" : "!v6",
526 s
->cellIntf
? "cell" : "!cell",
527 s
->isExpensive
? "exp" : "!exp",
528 s
->isCLAT46
? "clat46" : "!clat46",
529 s
->DNSSECAware
? "DNSSECAware" : "!DNSSECAware");
533 LogMsgNoIdent("v4answers %d", mDNSStorage
.p
->v4answers
);
534 LogMsgNoIdent("v6answers %d", mDNSStorage
.p
->v6answers
);
535 LogMsgNoIdent("Last DNS Trigger: %d ms ago", (now
- mDNSStorage
.p
->DNSTrigger
));
537 LogMsgNoIdent("--------- Mcast Resolvers ----------");
538 if (!mDNSStorage
.McastResolvers
) LogMsgNoIdent("<None>");
541 for (mr
= mDNSStorage
.McastResolvers
; mr
; mr
= mr
->next
)
542 LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr
->domain
.c
, mr
->timeout
);
545 LogMsgNoIdent("------------ Hostnames -------------");
546 if (!mDNSStorage
.Hostnames
) LogMsgNoIdent("<None>");
550 for (hi
= mDNSStorage
.Hostnames
; hi
; hi
= hi
->next
)
552 LogMsgNoIdent("%##s v4 %d %s", hi
->fqdn
.c
, hi
->arv4
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv4
));
553 LogMsgNoIdent("%##s v6 %d %s", hi
->fqdn
.c
, hi
->arv6
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv6
));
557 LogMsgNoIdent("--------------- FQDN ---------------");
558 if (!mDNSStorage
.FQDN
.c
[0]) LogMsgNoIdent("<None>");
561 LogMsgNoIdent("%##s", mDNSStorage
.FQDN
.c
);
567 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
568 LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
572 mDNSexport
void mDNSPlatformLogToFile(int log_level
, const char *buffer
)
575 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in init_logging()");
577 os_log_with_type(log_general
, log_level
, "%{private}s", buffer
);
581 // Writes the state out to the dynamic store and also affects the ASL filter level
582 mDNSexport
void UpdateDebugState()
587 CFMutableDictionaryRef dict
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
590 LogMsg("UpdateDebugState: Could not create dict");
594 CFNumberRef numOne
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &one
);
597 LogMsg("UpdateDebugState: Could not create CFNumber one");
600 CFNumberRef numZero
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &zero
);
603 LogMsg("UpdateDebugState: Could not create CFNumber zero");
608 if (mDNS_LoggingEnabled
)
609 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numOne
);
611 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numZero
);
613 if (mDNS_PacketLoggingEnabled
)
614 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numOne
);
616 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numZero
);
618 if (mDNS_McastLoggingEnabled
)
619 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numOne
);
621 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numZero
);
623 if (mDNS_McastTracingEnabled
)
624 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numOne
);
626 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numZero
);
630 mDNSDynamicStoreSetConfig(kmDNSDebugState
, mDNSNULL
, dict
);
636 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
638 mDNSlocal
void SignalCallback(CFMachPortRef port
, void *msg
, CFIndex size
, void *info
)
640 (void)port
; // Unused
641 (void)size
; // Unused
642 (void)info
; // Unused
643 mach_msg_header_t
*msg_header
= (mach_msg_header_t
*)msg
;
644 mDNS
*const m
= &mDNSStorage
;
646 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
648 switch(msg_header
->msgh_id
)
654 LogMsg("SIGHUP: Purge cache");
656 FORALL_CACHERECORDS(slot
, cg
, rr
)
658 rr
->resrec
.mortality
= Mortality_Mortal
;
659 mDNS_PurgeCacheResourceRecord(m
, rr
);
661 // Restart unicast and multicast queries
662 mDNSCoreRestartQueries(m
);
666 case SIGTERM
: ExitCallback(msg_header
->msgh_id
); break;
667 case SIGINFO
: INFOCallback(); break;
669 #if APPLE_OSX_mDNSResponder
670 mDNS_LoggingEnabled
= 1;
671 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
673 mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
674 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
676 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
678 LogInfo("USR1 Logging Enabled");
681 #if APPLE_OSX_mDNSResponder
682 mDNS_PacketLoggingEnabled
= 1;
683 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
685 mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
686 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
688 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
689 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
692 case SIGPROF
: mDNS_McastLoggingEnabled
= mDNS_McastLoggingEnabled
? mDNSfalse
: mDNStrue
;
693 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled
? "Enabled" : "Disabled");
694 LogMcastStateInfo(mDNSfalse
, mDNStrue
, mDNStrue
);
695 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
696 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
699 case SIGTSTP
: mDNS_LoggingEnabled
= mDNS_PacketLoggingEnabled
= mDNS_McastLoggingEnabled
= mDNS_McastTracingEnabled
= mDNSfalse
;
700 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
704 default: LogMsg("SignalCallback: Unknown signal %d", msg_header
->msgh_id
); break;
706 KQueueUnlock("Unix Signal");
709 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
710 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
714 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
715 rrcachestorage
, RR_CACHE_SIZE
,
716 !NoMulticastAdvertisements
,
717 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
721 LogMsg("Daemon start: mDNS_Init failed %d", err
);
726 if (PreallocateCacheMemory
)
728 const int growCount
= (kRRCacheMemoryLimit
+ kRRCacheGrowSize
- 1) / kRRCacheGrowSize
;
731 for (i
= 0; i
< growCount
; ++i
)
733 mDNS_StatusCallback(&mDNSStorage
, mStatus_GrowCache
);
738 CFMachPortRef i_port
= CFMachPortCreate(NULL
, SignalCallback
, NULL
, NULL
);
739 CFRunLoopSourceRef i_rls
= CFMachPortCreateRunLoopSource(NULL
, i_port
, 0);
740 signal_port
= CFMachPortGetPort(i_port
);
741 CFRunLoopAddSource(CFRunLoopGetMain(), i_rls
, kCFRunLoopDefaultMode
);
747 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
749 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
750 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
751 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
752 // of code from above. Alternatively we could remove the duplicated source code by having
753 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
755 mDNSlocal
void SignalDispatch(dispatch_source_t source
)
757 int sig
= (int)dispatch_source_get_handle(source
);
758 mDNS
*const m
= &mDNSStorage
;
766 LogMsg("SIGHUP: Purge cache");
768 FORALL_CACHERECORDS(slot
, cg
, rr
)
770 rr
->resrec
.mortality
= Mortality_Mortal
;
771 mDNS_PurgeCacheResourceRecord(m
, rr
);
773 // Restart unicast and multicast queries
774 mDNSCoreRestartQueries(m
);
778 case SIGTERM
: ExitCallback(sig
); break;
779 case SIGINFO
: INFOCallback(); break;
780 case SIGUSR1
: mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
781 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
782 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
785 case SIGUSR2
: mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
786 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
789 default: LogMsg("SignalCallback: Unknown signal %d", sig
); break;
791 KQueueUnlock("Unix Signal");
794 mDNSlocal
void mDNSSetupSignal(dispatch_queue_t queue
, int sig
)
796 signal(sig
, SIG_IGN
);
797 dispatch_source_t source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL
, sig
, 0, queue
);
801 dispatch_source_set_event_handler(source
, ^{SignalDispatch(source
);});
802 // Start processing signals
803 dispatch_resume(source
);
807 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig
);
811 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
814 dispatch_queue_t queue
= dispatch_get_main_queue();
816 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
817 rrcachestorage
, RR_CACHE_SIZE
,
818 !NoMulticastAdvertisements
,
819 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
823 LogMsg("Daemon start: mDNS_Init failed %d", err
);
827 mDNSSetupSignal(queue
, SIGHUP
);
828 mDNSSetupSignal(queue
, SIGINT
);
829 mDNSSetupSignal(queue
, SIGTERM
);
830 mDNSSetupSignal(queue
, SIGINFO
);
831 mDNSSetupSignal(queue
, SIGUSR1
);
832 mDNSSetupSignal(queue
, SIGUSR2
);
834 // Create a custom handler for doing the housekeeping work. This is either triggered
835 // by the timer or an event source
836 PlatformStorage
.custom
= dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD
, 0, 0, queue
);
837 if (PlatformStorage
.custom
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
838 dispatch_source_set_event_handler(PlatformStorage
.custom
, ^{PrepareForIdle(&mDNSStorage
);});
839 dispatch_resume(PlatformStorage
.custom
);
841 // Create a timer source to trigger housekeeping work. The houskeeping work itself
842 // is done in the custom handler that we set below.
844 PlatformStorage
.timer
= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER
, 0, 0, queue
);
845 if (PlatformStorage
.timer
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
847 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
848 // always reset the time to the new time computed. In effect, we ignore the interval
849 dispatch_source_set_timer(PlatformStorage
.timer
, DISPATCH_TIME_NOW
, 1000ull * 1000000000, 0);
850 dispatch_source_set_event_handler(PlatformStorage
.timer
, ^{
851 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
853 dispatch_resume(PlatformStorage
.timer
);
855 LogMsg("DaemonIntialize done successfully");
860 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
862 mDNSlocal mDNSs32
mDNSDaemonIdle(mDNS
*const m
)
864 mDNSs32 now
= mDNS_TimeNow(m
);
866 // 1. If we need to set domain secrets, do so before handling the network change
868 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
869 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
870 if (m
->p
->KeyChainTimer
&& now
- m
->p
->KeyChainTimer
>= 0)
872 m
->p
->KeyChainTimer
= 0;
878 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
880 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
881 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
882 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
883 // we then systematically lose our own looped-back packets.
884 if (m
->NetworkChanged
&& now
- m
->NetworkChanged
>= 0) mDNSMacOSXNetworkChanged();
886 if (m
->p
->RequestReSleep
&& now
- m
->p
->RequestReSleep
>= 0)
888 m
->p
->RequestReSleep
= 0;
889 mDNSPowerRequest(0, 0);
892 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
893 mDNSs32 nextevent
= mDNS_Execute(m
);
895 if (m
->NetworkChanged
)
896 if (nextevent
- m
->NetworkChanged
> 0)
897 nextevent
= m
->NetworkChanged
;
899 if (m
->p
->KeyChainTimer
)
900 if (nextevent
- m
->p
->KeyChainTimer
> 0)
901 nextevent
= m
->p
->KeyChainTimer
;
903 if (m
->p
->RequestReSleep
)
904 if (nextevent
- m
->p
->RequestReSleep
> 0)
905 nextevent
= m
->p
->RequestReSleep
;
908 if (m
->p
->NotifyUser
)
910 if (m
->p
->NotifyUser
- now
< 0)
912 if (!SameDomainLabelCS(m
->p
->usernicelabel
.c
, m
->nicelabel
.c
))
914 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m
->p
->usernicelabel
.c
, m
->nicelabel
.c
);
915 mDNSPreferencesSetNames(kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
916 m
->p
->usernicelabel
= m
->nicelabel
;
918 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
920 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
921 mDNSPreferencesSetNames(kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
922 m
->p
->HostNameConflict
= 0; // Clear our indicator, now name change has been successful
923 m
->p
->userhostlabel
= m
->hostlabel
;
925 m
->p
->NotifyUser
= 0;
928 if (nextevent
- m
->p
->NotifyUser
> 0)
929 nextevent
= m
->p
->NotifyUser
;
935 // Right now we consider *ALL* of our DHCP leases
936 // It might make sense to be a bit more selective and only consider the leases on interfaces
937 // (a) that are capable and enabled for wake-on-LAN, and
938 // (b) where we have found (and successfully registered with) a Sleep Proxy
939 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
940 mDNSlocal mDNSu32
DHCPWakeTime(void)
942 mDNSu32 e
= 24 * 3600; // Maximum maintenance wake interval is 24 hours
943 const CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
944 if (!now
) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
949 const void *pattern
= SCDynamicStoreKeyCreateNetworkServiceEntity(NULL
, kSCDynamicStoreDomainState
, kSCCompAnyRegex
, kSCEntNetDHCP
);
952 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
955 CFArrayRef dhcpinfo
= CFArrayCreate(NULL
, (const void **)&pattern
, 1, &kCFTypeArrayCallBacks
);
959 SCDynamicStoreRef store
= SCDynamicStoreCreate(NULL
, CFSTR("DHCP-LEASES"), NULL
, NULL
);
962 CFDictionaryRef dict
= SCDynamicStoreCopyMultiple(store
, NULL
, dhcpinfo
);
965 ic
= CFDictionaryGetCount(dict
);
966 const void *vals
[ic
];
967 CFDictionaryGetKeysAndValues(dict
, NULL
, vals
);
969 for (j
= 0; j
< ic
; j
++)
971 const CFDictionaryRef dhcp
= (CFDictionaryRef
)vals
[j
];
974 const CFDateRef start
= DHCPInfoGetLeaseStartTime(dhcp
);
975 const CFDataRef lease
= DHCPInfoGetOptionData(dhcp
, 51); // Option 51 = IP Address Lease Time
976 if (!start
|| !lease
|| CFDataGetLength(lease
) < 4)
977 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
978 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
979 j
, start
, lease
, lease
? CFDataGetLength(lease
) : 0);
982 const UInt8
*d
= CFDataGetBytePtr(lease
);
983 if (!d
) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j
);
986 const mDNSu32 elapsed
= now
- CFDateGetAbsoluteTime(start
);
987 const mDNSu32 lifetime
= (mDNSs32
) ((mDNSs32
)d
[0] << 24 | (mDNSs32
)d
[1] << 16 | (mDNSs32
)d
[2] << 8 | d
[3]);
988 const mDNSu32 remaining
= lifetime
- elapsed
;
989 const mDNSu32 wake
= remaining
> 60 ? remaining
- remaining
/10 : 54; // Wake at 90% of the lease time
990 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed
, lifetime
, remaining
, wake
);
991 if (e
> wake
) e
= wake
;
1000 CFRelease(dhcpinfo
);
1006 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
1007 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
1008 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
1009 // for a few seconds and then waking again is silly and annoying.
1010 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
1011 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
1012 // allowing us an adequate safety margin to renew our lease before we lose it.
1014 mDNSlocal mDNSBool
AllowSleepNow(mDNSs32 now
)
1016 mDNS
*const m
= &mDNSStorage
;
1017 mDNSBool ready
= mDNSCoreReadyForSleep(m
, now
);
1018 if (m
->SleepState
&& !ready
&& now
- m
->SleepLimit
< 0) return(mDNSfalse
);
1020 m
->p
->WakeAtUTC
= 0;
1021 int result
= kIOReturnSuccess
;
1022 CFDictionaryRef opts
= NULL
;
1024 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
1025 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
1027 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m
->SleepLimit
- now
);
1030 if (!m
->SystemWakeOnLANEnabled
|| !mDNSCoreHaveAdvertisedMulticastServices(m
))
1031 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
1032 m
->SystemWakeOnLANEnabled
? "is" : "not",
1033 mDNSCoreHaveAdvertisedMulticastServices(m
) ? "have" : "no");
1036 mDNSs32 dhcp
= DHCPWakeTime();
1037 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp
);
1038 mDNSs32 interval
= mDNSCoreIntervalToNextWake(m
, now
) / mDNSPlatformOneSecond
;
1039 if (interval
> dhcp
) interval
= dhcp
;
1041 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
1042 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
1043 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
1044 // someone to go to the machine in person to wake it up again, which would be unacceptable.
1045 if (!ready
&& interval
> 3600) interval
= 3600;
1047 //interval = 48; // For testing
1049 #if !TARGET_OS_EMBEDDED
1050 #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1051 if (m
->p
->IOPMConnection
) // If lightweight-wake capability is available, use that
1053 const CFDateRef WakeDate
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent() + interval
);
1054 if (!WakeDate
) LogMsg("ScheduleNextWake: CFDateCreate failed");
1057 const mDNSs32 reqs
= kIOPMSystemPowerStateCapabilityNetwork
;
1058 const CFNumberRef Requirements
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &reqs
);
1059 if (!Requirements
) LogMsg("ScheduleNextWake: CFNumberCreate failed");
1062 const void *OptionKeys
[2] = { kIOPMAckDHCPRenewWakeDate
, kIOPMAckSystemCapabilityRequirements
};
1063 const void *OptionVals
[2] = { WakeDate
, Requirements
};
1064 opts
= CFDictionaryCreate(NULL
, (void*)OptionKeys
, (void*)OptionVals
, 2, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1065 if (!opts
) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
1066 CFRelease(Requirements
);
1068 CFRelease(WakeDate
);
1070 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval
);
1072 else // else schedule the wakeup using the old API instead to
1073 #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1074 #endif // TARGET_OS_EMBEDDED
1076 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
1077 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
1078 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
1079 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
1083 result
= mDNSPowerRequest(1, interval
);
1085 if (result
== kIOReturnNotReady
)
1088 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval
);
1089 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
1090 // requested wake time is "too soon", but there's no API to find out what constitutes
1091 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
1092 // we just have to iterate with successively longer intervals until it doesn't fail.
1093 // We preserve the value of "result" because if our original power request was deemed "too soon"
1094 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
1095 // since the implication is that the system won't manage to be awake again at the time we need it.
1098 interval
+= (interval
< 20) ? 1 : ((interval
+3) / 4);
1099 r
= mDNSPowerRequest(1, interval
);
1101 while (r
== kIOReturnNotReady
);
1102 if (r
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, r
, r
);
1103 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval
);
1107 if (result
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, result
, result
);
1108 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval
);
1110 m
->p
->WakeAtUTC
= mDNSPlatformUTC() + interval
;
1114 m
->SleepState
= SleepState_Sleeping
;
1115 // Clear our interface list to empty state, ready to go to sleep
1116 // As a side effect of doing this, we'll also cancel any outstanding SPS Resolve calls that didn't complete
1117 mDNSMacOSXNetworkChanged();
1120 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1121 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1122 (m
->p
->IOPMConnection
) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1124 (result
== kIOReturnSuccess
) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1125 m
->p
->SleepCookie
, ready
? "ready for sleep" : "giving up", now
, m
->SleepLimit
- now
);
1127 m
->SleepLimit
= 0; // Don't clear m->SleepLimit until after we've logged it above
1128 m
->TimeSlept
= mDNSPlatformUTC();
1130 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1131 if (m
->p
->IOPMConnection
) IOPMConnectionAcknowledgeEventWithOptions(m
->p
->IOPMConnection
, m
->p
->SleepCookie
, opts
);
1134 if (result
== kIOReturnSuccess
) IOAllowPowerChange (m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1135 else IOCancelPowerChange(m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1137 if (opts
) CFRelease(opts
);
1141 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1143 mDNSexport
void TriggerEventCompletion()
1145 debugf("TriggerEventCompletion: Merge data");
1146 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
1149 mDNSlocal
void PrepareForIdle(void *m_param
)
1152 int64_t time_offset
;
1153 dispatch_time_t dtime
;
1155 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1157 // This is the main work loop:
1158 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1159 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1160 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1162 debugf("PrepareForIdle: called");
1163 // Run mDNS_Execute to find out the time we next need to wake up
1164 mDNSs32 start
= mDNSPlatformRawTime();
1165 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1166 mDNSs32 end
= mDNSPlatformRawTime();
1167 if (end
- start
>= WatchDogReportingThreshold
)
1168 LogInfo("CustomSourceHandler:WARNING: Idle task took %dms to complete", end
- start
);
1170 mDNSs32 now
= mDNS_TimeNow(m
);
1172 if (m
->ShutdownTime
)
1174 if (mDNSStorage
.ResourceRecords
)
1176 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, mDNSStorage
.ResourceRecords
));
1177 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1179 if (mDNS_ExitNow(m
, now
))
1181 LogInfo("IdleLoop: mDNS_FinalExit");
1182 mDNS_FinalExit(&mDNSStorage
);
1183 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1186 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1187 nextTimerEvent
= m
->ShutdownTime
;
1191 if (!AllowSleepNow(now
))
1192 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1193 nextTimerEvent
= m
->SleepLimit
;
1195 // Convert absolute wakeup time to a relative time from now
1196 mDNSs32 ticks
= nextTimerEvent
- now
;
1197 if (ticks
< 1) ticks
= 1;
1199 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1205 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1208 time_offset
= ((mDNSu32
)ticks
/ mDNSPlatformOneSecond
) * 1000000000 + (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1209 dtime
= dispatch_time(DISPATCH_TIME_NOW
, time_offset
);
1210 dispatch_source_set_timer(PlatformStorage
.timer
, dtime
, 1000ull*1000000000, 0);
1211 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks
);
1215 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1217 mDNSlocal
void KQWokenFlushBytes(int fd
, __unused
short filter
, __unused
void *context
, __unused mDNSBool encounteredEOF
)
1219 // Read all of the bytes so we won't wake again.
1221 while (recv(fd
, buffer
, sizeof(buffer
), MSG_DONTWAIT
) > 0) continue;
1224 mDNSlocal
void SetLowWater(const KQSocketSet
*const k
, const int r
)
1226 if (k
->sktv4
>=0 && setsockopt(k
->sktv4
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1227 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k
->sktv4
, r
, errno
, strerror(errno
));
1228 if (k
->sktv6
>=0 && setsockopt(k
->sktv6
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1229 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k
->sktv6
, r
, errno
, strerror(errno
));
1232 mDNSlocal
void * KQueueLoop(void *m_param
)
1237 #if USE_SELECT_WITH_KQUEUEFD
1240 const int multiplier
= 1000000 / mDNSPlatformOneSecond
;
1242 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1245 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1246 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32
)mDNSStorage
.timenow_last
, mDNSStorage
.timenow_last
);
1248 // This is the main work loop:
1249 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1250 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1251 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1252 // (4) On wakeup we first process *all* events
1253 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
1256 #define kEventsToReadAtOnce 1
1257 struct kevent new_events
[kEventsToReadAtOnce
];
1259 // Run mDNS_Execute to find out the time we next need to wake up
1260 mDNSs32 start
= mDNSPlatformRawTime();
1261 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1262 mDNSs32 end
= mDNSPlatformRawTime();
1263 if (end
- start
>= WatchDogReportingThreshold
)
1264 LogInfo("WARNING: Idle task took %dms to complete", end
- start
);
1266 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
1270 mDNSs32 now
= mDNS_TimeNow(m
);
1272 if (m
->ShutdownTime
)
1274 if (mDNSStorage
.ResourceRecords
)
1277 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
1279 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, rr
));
1280 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1283 if (mDNS_ExitNow(m
, now
))
1285 LogInfo("mDNS_FinalExit");
1286 mDNS_FinalExit(&mDNSStorage
);
1287 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1290 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1291 nextTimerEvent
= m
->ShutdownTime
;
1295 if (!AllowSleepNow(now
))
1296 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1297 nextTimerEvent
= m
->SleepLimit
;
1299 // Convert absolute wakeup time to a relative time from now
1300 mDNSs32 ticks
= nextTimerEvent
- now
;
1301 if (ticks
< 1) ticks
= 1;
1303 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1309 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1312 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents
, ticks
);
1315 // Release the lock, and sleep until:
1316 // 1. Something interesting happens like a packet arriving, or
1317 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
1318 // 3. The timeout expires
1319 pthread_mutex_unlock(&PlatformStorage
.BigMutex
);
1321 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1322 if (m
->p
->num_mcasts
)
1324 SetLowWater(&m
->p
->permanentsockets
, 0x10000);
1325 if (ticks
> mDNSPlatformOneSecond
/ 8) ticks
= mDNSPlatformOneSecond
/ 8;
1328 #if USE_SELECT_WITH_KQUEUEFD
1329 struct timeval timeout
;
1330 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1331 timeout
.tv_usec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1332 FD_SET(KQueueFD
, &readfds
);
1333 if (select(KQueueFD
+1, &readfds
, NULL
, NULL
, &timeout
) < 0)
1334 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1336 struct timespec timeout
;
1337 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1338 timeout
.tv_nsec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1339 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
1340 // and have it work similarly to the way it does with nevents non-zero --
1341 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
1342 // In fact, what happens if you do this is that it just returns immediately. So, we have
1343 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
1344 if (kevent(KQueueFD
, NULL
, 0, new_events
, 1, &timeout
) < 0)
1345 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1348 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1349 // We have to ignore the event we may have been told about above, because that
1350 // was done without holding the lock, and between the time we woke up and the
1351 // time we reclaimed the lock the other thread could have done something that
1352 // makes the event no longer valid. Now we have the lock, we call kevent again
1353 // and this time we can safely process the events it tells us about.
1355 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
1356 if (m
->p
->num_mcasts
)
1358 SetLowWater(&m
->p
->permanentsockets
, 1);
1359 m
->p
->num_mcasts
= 0;
1362 static const struct timespec zero_timeout
= { 0, 0 };
1364 while ((events_found
= kevent(KQueueFD
, NULL
, 0, new_events
, kEventsToReadAtOnce
, &zero_timeout
)) != 0)
1366 if (events_found
> kEventsToReadAtOnce
|| (events_found
< 0 && errno
!= EINTR
))
1368 const int kevent_errno
= errno
;
1369 // Not sure what to do here, our kqueue has failed us - this isn't ideal
1370 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", kevent_errno
, strerror(kevent_errno
));
1374 numevents
+= events_found
;
1377 for (i
= 0; i
< events_found
; i
++)
1379 const KQueueEntry
*const kqentry
= new_events
[i
].udata
;
1380 mDNSs32 stime
= mDNSPlatformRawTime();
1381 const char *const KQtask
= kqentry
->KQtask
; // Grab a copy in case KQcallback deletes the task
1382 kqentry
->KQcallback(new_events
[i
].ident
, new_events
[i
].filter
, kqentry
->KQcontext
, (new_events
[i
].flags
& EV_EOF
) != 0);
1383 mDNSs32 etime
= mDNSPlatformRawTime();
1384 if (etime
- stime
>= WatchDogReportingThreshold
)
1385 LogInfo("WARNING: %s took %dms to complete", KQtask
, etime
- stime
);
1393 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1395 mDNSlocal
size_t LaunchdCheckin(void)
1397 // Ask launchd for our socket
1398 int result
= launch_activate_socket("Listeners", &launchd_fds
, &launchd_fds_count
);
1399 if (result
!= 0) { LogMsg("launch_activate_socket() failed error %d (%s)", result
, strerror(result
)); }
1400 return launchd_fds_count
;
1404 extern int sandbox_init(const char *profile
, uint64_t flags
, char **errorbuf
) __attribute__((weak_import
));
1406 #if APPLE_OSX_mDNSResponder
1407 mDNSlocal mDNSBool
PreferencesGetValueBool(CFStringRef key
, mDNSBool defaultValue
)
1409 CFBooleanRef boolean
;
1410 mDNSBool result
= defaultValue
;
1412 boolean
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1415 if (CFGetTypeID(boolean
) == CFBooleanGetTypeID())
1416 result
= CFBooleanGetValue(boolean
) ? mDNStrue
: mDNSfalse
;
1423 mDNSlocal
int PreferencesGetValueInt(CFStringRef key
, int defaultValue
)
1427 int result
= defaultValue
;
1429 number
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1432 if ((CFGetTypeID(number
) == CFNumberGetTypeID()) && CFNumberGetValue(number
, kCFNumberIntType
, &numberValue
))
1433 result
= numberValue
;
1441 mDNSlocal
void SandboxProcess(void)
1443 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1445 LogMsg("Note: Compiled without Apple Sandbox support");
1446 #else // MDNS_NO_SANDBOX
1448 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1452 uint64_t sandbox_flags
= SANDBOX_NAMED
;
1454 (void)confstr(_CS_DARWIN_USER_CACHE_DIR
, NULL
, 0);
1456 int sandbox_err
= sandbox_init("mDNSResponder", sandbox_flags
, &sandbox_msg
);
1459 LogMsg("WARNING: sandbox_init error %s", sandbox_msg
);
1460 // If we have errors in the sandbox during development, to prevent
1461 // exiting, uncomment the following line.
1462 //sandbox_free_error(sandbox_msg);
1464 errx(EX_OSERR
, "sandbox_init() failed: %s", sandbox_msg
);
1466 else LogInfo("Now running under Apple Sandbox restrictions");
1468 #endif // MDNS_NO_SANDBOX
1471 #if APPLE_OSX_mDNSResponder
1472 mDNSlocal
void init_logging(void)
1474 log_general
= os_log_create("com.apple.mDNSResponder", "AllINFO");
1478 // OS_LOG_DEFAULT is the default logging object, if you are not creating a custom subsystem/category
1479 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in mDNSResponder");
1485 // Run the unit test main
1488 mDNSexport
int main(int argc
, char **argv
)
1491 kern_return_t status
;
1494 bool useDebugSocket
= mDNSfalse
;
1495 bool useSandbox
= mDNStrue
;
1498 #if APPLE_OSX_mDNSResponder
1502 mDNSMacOSXSystemBuildNumber(NULL
);
1503 LogMsg("%s starting %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
1506 LogMsg("CacheRecord %5d", sizeof(CacheRecord
));
1507 LogMsg("CacheGroup %5d", sizeof(CacheGroup
));
1508 LogMsg("ResourceRecord %5d", sizeof(ResourceRecord
));
1509 LogMsg("RData_small %5d", sizeof(RData_small
));
1511 LogMsg("sizeof(CacheEntity) %5d", sizeof(CacheEntity
));
1512 LogMsg("RR_CACHE_SIZE %5d", RR_CACHE_SIZE
);
1513 LogMsg("block bytes used %5d", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1514 LogMsg("block bytes wasted %5d", 32*1024 - sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1519 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1523 for (i
=1; i
<argc
; i
++)
1525 if (!strcasecmp(argv
[i
], "-d" )) mDNS_DebugMode
= mDNStrue
;
1526 if (!strcasecmp(argv
[i
], "-NoMulticastAdvertisements")) NoMulticastAdvertisements
= mDNStrue
;
1527 if (!strcasecmp(argv
[i
], "-DisableSleepProxyClient" )) DisableSleepProxyClient
= mDNStrue
;
1528 if (!strcasecmp(argv
[i
], "-DebugLogging" )) mDNS_LoggingEnabled
= mDNStrue
;
1529 if (!strcasecmp(argv
[i
], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled
= mDNStrue
;
1530 if (!strcasecmp(argv
[i
], "-OfferSleepProxyService" ))
1531 OfferSleepProxyService
= (i
+1 < argc
&& mDNSIsDigit(argv
[i
+1][0]) && mDNSIsDigit(argv
[i
+1][1]) && argv
[i
+1][2]==0) ? atoi(argv
[++i
]) : 100;
1532 if (!strcasecmp(argv
[i
], "-UseInternalSleepProxy" ))
1533 UseInternalSleepProxy
= (i
+1<argc
&& mDNSIsDigit(argv
[i
+1][0]) && argv
[i
+1][1]==0) ? atoi(argv
[++i
]) : 1;
1534 if (!strcasecmp(argv
[i
], "-StrictUnicastOrdering" )) StrictUnicastOrdering
= mDNStrue
;
1535 if (!strcasecmp(argv
[i
], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains
= mDNStrue
;
1536 if (!strcasecmp(argv
[i
], "-DisableAllowExpired" )) EnableAllowExpired
= mDNSfalse
;
1538 if (!strcasecmp(argv
[i
], "-UseDebugSocket")) useDebugSocket
= mDNStrue
;
1539 if (!strcasecmp(argv
[i
], "-NoSandbox")) useSandbox
= mDNSfalse
;
1544 #if APPLE_OSX_mDNSResponder
1545 /* Reads the external user's program arguments for mDNSResponder starting 10.11.x(El Capitan) on OSX. The options for external user are:
1546 DebugLogging, UnicastPacketLogging, NoMulticastAdvertisements, StrictUnicastOrdering and AlwaysAppendSearchDomains
1548 To turn ON the particular option, here is what the user should do (as an example of setting two options)
1549 1] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool YES
1550 2] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
1553 To turn OFF all options, here is what the user should do
1554 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1557 To view the current options set, here is what the user should do
1558 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1560 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
1564 // Currently on Fuji/Whitetail releases we are keeping the logging always enabled.
1565 // Hence mDNS_LoggingEnabled and mDNS_PacketLoggingEnabled is set to true below by default.
1567 mDNS_LoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_DebugLogging
, mDNS_LoggingEnabled
);
1568 mDNS_PacketLoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging
, mDNS_PacketLoggingEnabled
);
1571 mDNS_LoggingEnabled
= mDNStrue
;
1572 mDNS_PacketLoggingEnabled
= mDNStrue
;
1574 NoMulticastAdvertisements
= PreferencesGetValueBool(kPreferencesKey_NoMulticastAdvertisements
, NoMulticastAdvertisements
);
1575 StrictUnicastOrdering
= PreferencesGetValueBool(kPreferencesKey_StrictUnicastOrdering
, StrictUnicastOrdering
);
1576 AlwaysAppendSearchDomains
= PreferencesGetValueBool(kPreferencesKey_AlwaysAppendSearchDomains
, AlwaysAppendSearchDomains
);
1577 EnableAllowExpired
= PreferencesGetValueBool(kPreferencesKey_EnableAllowExpired
, EnableAllowExpired
);
1578 OfferSleepProxyService
= PreferencesGetValueInt(kPreferencesKey_OfferSleepProxyService
, OfferSleepProxyService
);
1579 UseInternalSleepProxy
= PreferencesGetValueInt(kPreferencesKey_UseInternalSleepProxy
, UseInternalSleepProxy
);
1581 #if ENABLE_BLE_TRIGGERED_BONJOUR
1582 EnableBLEBasedDiscovery
= PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery
, EnableBLEBasedDiscovery
);
1583 DefaultToBLETriggered
= PreferencesGetValueBool(kPreferencesKey_DefaultToBLETriggered
, DefaultToBLETriggered
);
1584 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
1586 #if TARGET_OS_IPHONE
1587 PreallocateCacheMemory
= PreferencesGetValueBool(kPreferencesKey_PreallocateCacheMemory
, PreallocateCacheMemory
);
1591 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
1592 if (NoMulticastAdvertisements
)
1593 LogMsg("-NoMulticastAdvertisements is set: Administratively prohibiting multicast advertisements");
1594 if (AlwaysAppendSearchDomains
)
1595 LogMsg("-AlwaysAppendSearchDomains is set");
1596 if (StrictUnicastOrdering
)
1597 LogMsg("-StrictUnicastOrdering is set");
1599 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1601 signal(SIGHUP
, HandleSIG
); // (Debugging) Purge the cache to check for cache handling bugs
1602 signal(SIGINT
, HandleSIG
); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
1603 signal(SIGPIPE
, SIG_IGN
); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
1604 signal(SIGTERM
, HandleSIG
); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
1605 signal(SIGINFO
, HandleSIG
); // (Debugging) Write state snapshot to syslog
1606 signal(SIGUSR1
, HandleSIG
); // (Debugging) Enable Logging
1607 signal(SIGUSR2
, HandleSIG
); // (Debugging) Enable Packet Logging
1608 signal(SIGPROF
, HandleSIG
); // (Debugging) Toggle Multicast Logging
1609 signal(SIGTSTP
, HandleSIG
); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
1611 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1613 mDNSStorage
.p
= &PlatformStorage
; // Make sure mDNSStorage.p is set up, because validatelists uses it
1614 // Need to Start XPC Server Before LaunchdCheckin() (Reason: rdar11023750)
1617 if (!useDebugSocket
) {
1618 if (LaunchdCheckin() == 0)
1619 useDebugSocket
= mDNStrue
;
1622 SetDebugBoundPath();
1627 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1629 // Create the kqueue, mutex and thread to support KQSockets
1630 KQueueFD
= kqueue();
1633 const int kqueue_errno
= errno
;
1634 LogMsg("kqueue() failed errno %d (%s)", kqueue_errno
, strerror(kqueue_errno
));
1635 status
= kqueue_errno
;
1639 i
= pthread_mutex_init(&PlatformStorage
.BigMutex
, NULL
);
1640 if (i
!= 0) { LogMsg("pthread_mutex_init() failed error %d (%s)", i
, strerror(i
)); status
= i
; goto exit
; }
1642 int fdpair
[2] = {0, 0};
1643 i
= socketpair(AF_UNIX
, SOCK_STREAM
, 0, fdpair
);
1646 const int socketpair_errno
= errno
;
1647 LogMsg("socketpair() failed errno %d (%s)", socketpair_errno
, strerror(socketpair_errno
));
1648 status
= socketpair_errno
;
1652 // Socket pair returned us two identical sockets connected to each other
1653 // We will use the first socket to send the second socket. The second socket
1654 // will be added to the kqueue so it will wake when data is sent.
1655 static const KQueueEntry wakeKQEntry
= { KQWokenFlushBytes
, NULL
, "kqueue wakeup after CFRunLoop event" };
1657 PlatformStorage
.WakeKQueueLoopFD
= fdpair
[0];
1658 KQueueSet(fdpair
[1], EV_ADD
, EVFILT_READ
, &wakeKQEntry
);
1660 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1668 status
= MetricsInit();
1669 if (status
) { LogMsg("Daemon start: MetricsInit failed (%d)", status
); }
1672 status
= mDNSDaemonInitialize();
1673 if (status
) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit
; }
1675 status
= udsserver_init(launchd_fds
, launchd_fds_count
);
1676 if (status
) { LogMsg("Daemon start: udsserver_init failed"); goto exit
; }
1678 mDNSMacOSXNetworkChanged();
1681 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1682 LogInfo("Daemon Start: Using LibDispatch");
1683 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
1685 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1686 // Start the kqueue thread
1687 pthread_t KQueueThread
;
1688 i
= pthread_create(&KQueueThread
, NULL
, KQueueLoop
, &mDNSStorage
);
1689 if (i
!= 0) { LogMsg("pthread_create() failed error %d (%s)", i
, strerror(i
)); status
= i
; goto exit
; }
1693 LogMsg("ERROR: CFRunLoopRun Exiting.");
1694 mDNS_Close(&mDNSStorage
);
1696 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1698 LogMsg("%s exiting", mDNSResponderVersionString
);
1705 // uds_daemon.c support routines /////////////////////////////////////////////
1707 mDNSlocal
void kqUDSEventCallback(int fd
, short filter
, void *context
, __unused mDNSBool encounteredEOF
)
1709 const KQSocketEventSource
*const source
= context
;
1710 source
->callback(fd
, filter
, source
->context
);
1713 // Arrange things so that when data appears on fd, callback is called with context
1714 mDNSexport mStatus
udsSupportAddFDToEventLoop(int fd
, udsEventCallback callback
, void *context
, void **platform_data
)
1716 KQSocketEventSource
**p
= &gEventSources
;
1717 (void) platform_data
;
1718 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1719 if (*p
) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd
); return mStatus_AlreadyRegistered
; }
1721 KQSocketEventSource
*newSource
= (KQSocketEventSource
*) mallocL("KQSocketEventSource", sizeof *newSource
);
1722 if (!newSource
) return mStatus_NoMemoryErr
;
1724 newSource
->next
= mDNSNULL
;
1726 newSource
->callback
= callback
;
1727 newSource
->context
= context
;
1728 newSource
->kqs
.KQcallback
= kqUDSEventCallback
;
1729 newSource
->kqs
.KQcontext
= newSource
;
1730 newSource
->kqs
.KQtask
= "UDS client";
1731 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1732 newSource
->kqs
.readSource
= mDNSNULL
;
1733 newSource
->kqs
.writeSource
= mDNSNULL
;
1734 newSource
->kqs
.fdClosed
= mDNSfalse
;
1735 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1737 if (KQueueSet(fd
, EV_ADD
, EVFILT_READ
, &newSource
->kqs
) == 0)
1740 return mStatus_NoError
;
1743 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd
, errno
, strerror(errno
));
1744 freeL("KQSocketEventSource", newSource
);
1745 return mStatus_BadParamErr
;
1748 int udsSupportReadFD(dnssd_sock_t fd
, char *buf
, int len
, int flags
, void *platform_data
)
1750 (void) platform_data
;
1751 return recv(fd
, buf
, len
, flags
);
1754 mDNSexport mStatus
udsSupportRemoveFDFromEventLoop(int fd
, void *platform_data
) // Note: This also CLOSES the file descriptor
1756 KQSocketEventSource
**p
= &gEventSources
;
1757 (void) platform_data
;
1758 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1761 KQSocketEventSource
*s
= *p
;
1763 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
1764 // causes the kernel to automatically remove any associated kevents
1765 mDNSPlatformCloseFD(&s
->kqs
, s
->fd
);
1766 freeL("KQSocketEventSource", s
);
1767 return mStatus_NoError
;
1769 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd
);
1770 return mStatus_NoSuchNameErr
;
1774 #include "../unittests/daemon_ut.c"
1777 #if _BUILDING_XCODE_PROJECT_
1778 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
1779 const char *__crashreporter_info__
= mDNSResponderVersionString
;
1780 asm (".desc ___crashreporter_info__, 0x10");
1783 // For convenience when using the "strings" command, this is the last thing in the file
1784 // The "@(#) " pattern is a special prefix the "what" command looks for
1785 mDNSexport
const char mDNSResponderVersionString_SCCS
[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion
) " (" __DATE__
" " __TIME__
")";