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",
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
->DNSSECAware
? "DNSSECAware" : "!DNSSECAware");
532 LogMsgNoIdent("v4answers %d", mDNSStorage
.p
->v4answers
);
533 LogMsgNoIdent("v6answers %d", mDNSStorage
.p
->v6answers
);
534 LogMsgNoIdent("Last DNS Trigger: %d ms ago", (now
- mDNSStorage
.p
->DNSTrigger
));
536 LogMsgNoIdent("--------- Mcast Resolvers ----------");
537 if (!mDNSStorage
.McastResolvers
) LogMsgNoIdent("<None>");
540 for (mr
= mDNSStorage
.McastResolvers
; mr
; mr
= mr
->next
)
541 LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr
->domain
.c
, mr
->timeout
);
544 LogMsgNoIdent("------------ Hostnames -------------");
545 if (!mDNSStorage
.Hostnames
) LogMsgNoIdent("<None>");
549 for (hi
= mDNSStorage
.Hostnames
; hi
; hi
= hi
->next
)
551 LogMsgNoIdent("%##s v4 %d %s", hi
->fqdn
.c
, hi
->arv4
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv4
));
552 LogMsgNoIdent("%##s v6 %d %s", hi
->fqdn
.c
, hi
->arv6
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv6
));
556 LogMsgNoIdent("--------------- FQDN ---------------");
557 if (!mDNSStorage
.FQDN
.c
[0]) LogMsgNoIdent("<None>");
560 LogMsgNoIdent("%##s", mDNSStorage
.FQDN
.c
);
566 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
567 LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
571 mDNSexport
void mDNSPlatformLogToFile(int log_level
, const char *buffer
)
574 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in init_logging()");
576 os_log_with_type(log_general
, log_level
, "%{private}s", buffer
);
580 // Writes the state out to the dynamic store and also affects the ASL filter level
581 mDNSexport
void UpdateDebugState()
586 CFMutableDictionaryRef dict
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
589 LogMsg("UpdateDebugState: Could not create dict");
593 CFNumberRef numOne
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &one
);
596 LogMsg("UpdateDebugState: Could not create CFNumber one");
599 CFNumberRef numZero
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &zero
);
602 LogMsg("UpdateDebugState: Could not create CFNumber zero");
607 if (mDNS_LoggingEnabled
)
608 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numOne
);
610 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numZero
);
612 if (mDNS_PacketLoggingEnabled
)
613 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numOne
);
615 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numZero
);
617 if (mDNS_McastLoggingEnabled
)
618 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numOne
);
620 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numZero
);
622 if (mDNS_McastTracingEnabled
)
623 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numOne
);
625 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numZero
);
629 mDNSDynamicStoreSetConfig(kmDNSDebugState
, mDNSNULL
, dict
);
635 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
637 mDNSlocal
void SignalCallback(CFMachPortRef port
, void *msg
, CFIndex size
, void *info
)
639 (void)port
; // Unused
640 (void)size
; // Unused
641 (void)info
; // Unused
642 mach_msg_header_t
*msg_header
= (mach_msg_header_t
*)msg
;
643 mDNS
*const m
= &mDNSStorage
;
645 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
647 switch(msg_header
->msgh_id
)
653 LogMsg("SIGHUP: Purge cache");
655 FORALL_CACHERECORDS(slot
, cg
, rr
)
657 rr
->resrec
.mortality
= Mortality_Mortal
;
658 mDNS_PurgeCacheResourceRecord(m
, rr
);
660 // Restart unicast and multicast queries
661 mDNSCoreRestartQueries(m
);
665 case SIGTERM
: ExitCallback(msg_header
->msgh_id
); break;
666 case SIGINFO
: INFOCallback(); break;
668 #if APPLE_OSX_mDNSResponder
669 mDNS_LoggingEnabled
= 1;
670 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
672 mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
673 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
675 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
677 LogInfo("USR1 Logging Enabled");
680 #if APPLE_OSX_mDNSResponder
681 mDNS_PacketLoggingEnabled
= 1;
682 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
684 mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
685 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
687 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
688 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
691 case SIGPROF
: mDNS_McastLoggingEnabled
= mDNS_McastLoggingEnabled
? mDNSfalse
: mDNStrue
;
692 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled
? "Enabled" : "Disabled");
693 LogMcastStateInfo(mDNSfalse
, mDNStrue
, mDNStrue
);
694 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
695 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
698 case SIGTSTP
: mDNS_LoggingEnabled
= mDNS_PacketLoggingEnabled
= mDNS_McastLoggingEnabled
= mDNS_McastTracingEnabled
= mDNSfalse
;
699 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
703 default: LogMsg("SignalCallback: Unknown signal %d", msg_header
->msgh_id
); break;
705 KQueueUnlock("Unix Signal");
708 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
709 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
713 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
714 rrcachestorage
, RR_CACHE_SIZE
,
715 !NoMulticastAdvertisements
,
716 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
720 LogMsg("Daemon start: mDNS_Init failed %d", err
);
725 if (PreallocateCacheMemory
)
727 const int growCount
= (kRRCacheMemoryLimit
+ kRRCacheGrowSize
- 1) / kRRCacheGrowSize
;
730 for (i
= 0; i
< growCount
; ++i
)
732 mDNS_StatusCallback(&mDNSStorage
, mStatus_GrowCache
);
737 CFMachPortRef i_port
= CFMachPortCreate(NULL
, SignalCallback
, NULL
, NULL
);
738 CFRunLoopSourceRef i_rls
= CFMachPortCreateRunLoopSource(NULL
, i_port
, 0);
739 signal_port
= CFMachPortGetPort(i_port
);
740 CFRunLoopAddSource(CFRunLoopGetMain(), i_rls
, kCFRunLoopDefaultMode
);
746 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
748 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
749 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
750 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
751 // of code from above. Alternatively we could remove the duplicated source code by having
752 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
754 mDNSlocal
void SignalDispatch(dispatch_source_t source
)
756 int sig
= (int)dispatch_source_get_handle(source
);
757 mDNS
*const m
= &mDNSStorage
;
765 LogMsg("SIGHUP: Purge cache");
767 FORALL_CACHERECORDS(slot
, cg
, rr
)
769 rr
->resrec
.mortality
= Mortality_Mortal
;
770 mDNS_PurgeCacheResourceRecord(m
, rr
);
772 // Restart unicast and multicast queries
773 mDNSCoreRestartQueries(m
);
777 case SIGTERM
: ExitCallback(sig
); break;
778 case SIGINFO
: INFOCallback(); break;
779 case SIGUSR1
: mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
780 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
781 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
784 case SIGUSR2
: mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
785 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
788 default: LogMsg("SignalCallback: Unknown signal %d", sig
); break;
790 KQueueUnlock("Unix Signal");
793 mDNSlocal
void mDNSSetupSignal(dispatch_queue_t queue
, int sig
)
795 signal(sig
, SIG_IGN
);
796 dispatch_source_t source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL
, sig
, 0, queue
);
800 dispatch_source_set_event_handler(source
, ^{SignalDispatch(source
);});
801 // Start processing signals
802 dispatch_resume(source
);
806 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig
);
810 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
813 dispatch_queue_t queue
= dispatch_get_main_queue();
815 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
816 rrcachestorage
, RR_CACHE_SIZE
,
817 !NoMulticastAdvertisements
,
818 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
822 LogMsg("Daemon start: mDNS_Init failed %d", err
);
826 mDNSSetupSignal(queue
, SIGHUP
);
827 mDNSSetupSignal(queue
, SIGINT
);
828 mDNSSetupSignal(queue
, SIGTERM
);
829 mDNSSetupSignal(queue
, SIGINFO
);
830 mDNSSetupSignal(queue
, SIGUSR1
);
831 mDNSSetupSignal(queue
, SIGUSR2
);
833 // Create a custom handler for doing the housekeeping work. This is either triggered
834 // by the timer or an event source
835 PlatformStorage
.custom
= dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD
, 0, 0, queue
);
836 if (PlatformStorage
.custom
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
837 dispatch_source_set_event_handler(PlatformStorage
.custom
, ^{PrepareForIdle(&mDNSStorage
);});
838 dispatch_resume(PlatformStorage
.custom
);
840 // Create a timer source to trigger housekeeping work. The houskeeping work itself
841 // is done in the custom handler that we set below.
843 PlatformStorage
.timer
= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER
, 0, 0, queue
);
844 if (PlatformStorage
.timer
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
846 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
847 // always reset the time to the new time computed. In effect, we ignore the interval
848 dispatch_source_set_timer(PlatformStorage
.timer
, DISPATCH_TIME_NOW
, 1000ull * 1000000000, 0);
849 dispatch_source_set_event_handler(PlatformStorage
.timer
, ^{
850 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
852 dispatch_resume(PlatformStorage
.timer
);
854 LogMsg("DaemonIntialize done successfully");
859 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
861 mDNSlocal mDNSs32
mDNSDaemonIdle(mDNS
*const m
)
863 mDNSs32 now
= mDNS_TimeNow(m
);
865 // 1. If we need to set domain secrets, do so before handling the network change
867 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
868 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
869 if (m
->p
->KeyChainTimer
&& now
- m
->p
->KeyChainTimer
>= 0)
871 m
->p
->KeyChainTimer
= 0;
877 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
879 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
880 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
881 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
882 // we then systematically lose our own looped-back packets.
883 if (m
->NetworkChanged
&& now
- m
->NetworkChanged
>= 0) mDNSMacOSXNetworkChanged();
885 if (m
->p
->RequestReSleep
&& now
- m
->p
->RequestReSleep
>= 0)
887 m
->p
->RequestReSleep
= 0;
888 mDNSPowerRequest(0, 0);
891 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
892 mDNSs32 nextevent
= mDNS_Execute(m
);
894 if (m
->NetworkChanged
)
895 if (nextevent
- m
->NetworkChanged
> 0)
896 nextevent
= m
->NetworkChanged
;
898 if (m
->p
->KeyChainTimer
)
899 if (nextevent
- m
->p
->KeyChainTimer
> 0)
900 nextevent
= m
->p
->KeyChainTimer
;
902 if (m
->p
->RequestReSleep
)
903 if (nextevent
- m
->p
->RequestReSleep
> 0)
904 nextevent
= m
->p
->RequestReSleep
;
907 if (m
->p
->NotifyUser
)
909 if (m
->p
->NotifyUser
- now
< 0)
911 if (!SameDomainLabelCS(m
->p
->usernicelabel
.c
, m
->nicelabel
.c
))
913 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m
->p
->usernicelabel
.c
, m
->nicelabel
.c
);
914 mDNSPreferencesSetNames(kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
915 m
->p
->usernicelabel
= m
->nicelabel
;
917 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
919 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
920 mDNSPreferencesSetNames(kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
921 m
->p
->HostNameConflict
= 0; // Clear our indicator, now name change has been successful
922 m
->p
->userhostlabel
= m
->hostlabel
;
924 m
->p
->NotifyUser
= 0;
927 if (nextevent
- m
->p
->NotifyUser
> 0)
928 nextevent
= m
->p
->NotifyUser
;
934 // Right now we consider *ALL* of our DHCP leases
935 // It might make sense to be a bit more selective and only consider the leases on interfaces
936 // (a) that are capable and enabled for wake-on-LAN, and
937 // (b) where we have found (and successfully registered with) a Sleep Proxy
938 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
939 mDNSlocal mDNSu32
DHCPWakeTime(void)
941 mDNSu32 e
= 24 * 3600; // Maximum maintenance wake interval is 24 hours
942 const CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
943 if (!now
) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
948 const void *pattern
= SCDynamicStoreKeyCreateNetworkServiceEntity(NULL
, kSCDynamicStoreDomainState
, kSCCompAnyRegex
, kSCEntNetDHCP
);
951 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
954 CFArrayRef dhcpinfo
= CFArrayCreate(NULL
, (const void **)&pattern
, 1, &kCFTypeArrayCallBacks
);
958 SCDynamicStoreRef store
= SCDynamicStoreCreate(NULL
, CFSTR("DHCP-LEASES"), NULL
, NULL
);
961 CFDictionaryRef dict
= SCDynamicStoreCopyMultiple(store
, NULL
, dhcpinfo
);
964 ic
= CFDictionaryGetCount(dict
);
965 const void *vals
[ic
];
966 CFDictionaryGetKeysAndValues(dict
, NULL
, vals
);
968 for (j
= 0; j
< ic
; j
++)
970 const CFDictionaryRef dhcp
= (CFDictionaryRef
)vals
[j
];
973 const CFDateRef start
= DHCPInfoGetLeaseStartTime(dhcp
);
974 const CFDataRef lease
= DHCPInfoGetOptionData(dhcp
, 51); // Option 51 = IP Address Lease Time
975 if (!start
|| !lease
|| CFDataGetLength(lease
) < 4)
976 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
977 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
978 j
, start
, lease
, lease
? CFDataGetLength(lease
) : 0);
981 const UInt8
*d
= CFDataGetBytePtr(lease
);
982 if (!d
) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j
);
985 const mDNSu32 elapsed
= now
- CFDateGetAbsoluteTime(start
);
986 const mDNSu32 lifetime
= (mDNSs32
) ((mDNSs32
)d
[0] << 24 | (mDNSs32
)d
[1] << 16 | (mDNSs32
)d
[2] << 8 | d
[3]);
987 const mDNSu32 remaining
= lifetime
- elapsed
;
988 const mDNSu32 wake
= remaining
> 60 ? remaining
- remaining
/10 : 54; // Wake at 90% of the lease time
989 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed
, lifetime
, remaining
, wake
);
990 if (e
> wake
) e
= wake
;
1005 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
1006 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
1007 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
1008 // for a few seconds and then waking again is silly and annoying.
1009 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
1010 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
1011 // allowing us an adequate safety margin to renew our lease before we lose it.
1013 mDNSlocal mDNSBool
AllowSleepNow(mDNSs32 now
)
1015 mDNS
*const m
= &mDNSStorage
;
1016 mDNSBool ready
= mDNSCoreReadyForSleep(m
, now
);
1017 if (m
->SleepState
&& !ready
&& now
- m
->SleepLimit
< 0) return(mDNSfalse
);
1019 m
->p
->WakeAtUTC
= 0;
1020 int result
= kIOReturnSuccess
;
1021 CFDictionaryRef opts
= NULL
;
1023 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
1024 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
1026 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m
->SleepLimit
- now
);
1029 if (!m
->SystemWakeOnLANEnabled
|| !mDNSCoreHaveAdvertisedMulticastServices(m
))
1030 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
1031 m
->SystemWakeOnLANEnabled
? "is" : "not",
1032 mDNSCoreHaveAdvertisedMulticastServices(m
) ? "have" : "no");
1035 mDNSs32 dhcp
= DHCPWakeTime();
1036 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp
);
1037 mDNSs32 interval
= mDNSCoreIntervalToNextWake(m
, now
) / mDNSPlatformOneSecond
;
1038 if (interval
> dhcp
) interval
= dhcp
;
1040 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
1041 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
1042 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
1043 // someone to go to the machine in person to wake it up again, which would be unacceptable.
1044 if (!ready
&& interval
> 3600) interval
= 3600;
1046 //interval = 48; // For testing
1048 #if !TARGET_OS_EMBEDDED
1049 #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1050 if (m
->p
->IOPMConnection
) // If lightweight-wake capability is available, use that
1052 const CFDateRef WakeDate
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent() + interval
);
1053 if (!WakeDate
) LogMsg("ScheduleNextWake: CFDateCreate failed");
1056 const mDNSs32 reqs
= kIOPMSystemPowerStateCapabilityNetwork
;
1057 const CFNumberRef Requirements
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &reqs
);
1058 if (!Requirements
) LogMsg("ScheduleNextWake: CFNumberCreate failed");
1061 const void *OptionKeys
[2] = { kIOPMAckDHCPRenewWakeDate
, kIOPMAckSystemCapabilityRequirements
};
1062 const void *OptionVals
[2] = { WakeDate
, Requirements
};
1063 opts
= CFDictionaryCreate(NULL
, (void*)OptionKeys
, (void*)OptionVals
, 2, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1064 if (!opts
) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
1065 CFRelease(Requirements
);
1067 CFRelease(WakeDate
);
1069 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval
);
1071 else // else schedule the wakeup using the old API instead to
1072 #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1073 #endif // TARGET_OS_EMBEDDED
1075 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
1076 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
1077 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
1078 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
1082 result
= mDNSPowerRequest(1, interval
);
1084 if (result
== kIOReturnNotReady
)
1087 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval
);
1088 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
1089 // requested wake time is "too soon", but there's no API to find out what constitutes
1090 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
1091 // we just have to iterate with successively longer intervals until it doesn't fail.
1092 // We preserve the value of "result" because if our original power request was deemed "too soon"
1093 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
1094 // since the implication is that the system won't manage to be awake again at the time we need it.
1097 interval
+= (interval
< 20) ? 1 : ((interval
+3) / 4);
1098 r
= mDNSPowerRequest(1, interval
);
1100 while (r
== kIOReturnNotReady
);
1101 if (r
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, r
, r
);
1102 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval
);
1106 if (result
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, result
, result
);
1107 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval
);
1109 m
->p
->WakeAtUTC
= mDNSPlatformUTC() + interval
;
1113 m
->SleepState
= SleepState_Sleeping
;
1114 // Clear our interface list to empty state, ready to go to sleep
1115 // As a side effect of doing this, we'll also cancel any outstanding SPS Resolve calls that didn't complete
1116 mDNSMacOSXNetworkChanged();
1119 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1120 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1121 (m
->p
->IOPMConnection
) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1123 (result
== kIOReturnSuccess
) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1124 m
->p
->SleepCookie
, ready
? "ready for sleep" : "giving up", now
, m
->SleepLimit
- now
);
1126 m
->SleepLimit
= 0; // Don't clear m->SleepLimit until after we've logged it above
1127 m
->TimeSlept
= mDNSPlatformUTC();
1129 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1130 if (m
->p
->IOPMConnection
) IOPMConnectionAcknowledgeEventWithOptions(m
->p
->IOPMConnection
, m
->p
->SleepCookie
, opts
);
1133 if (result
== kIOReturnSuccess
) IOAllowPowerChange (m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1134 else IOCancelPowerChange(m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1136 if (opts
) CFRelease(opts
);
1140 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1142 mDNSexport
void TriggerEventCompletion()
1144 debugf("TriggerEventCompletion: Merge data");
1145 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
1148 mDNSlocal
void PrepareForIdle(void *m_param
)
1151 int64_t time_offset
;
1152 dispatch_time_t dtime
;
1154 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1156 // This is the main work loop:
1157 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1158 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1159 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1161 debugf("PrepareForIdle: called");
1162 // Run mDNS_Execute to find out the time we next need to wake up
1163 mDNSs32 start
= mDNSPlatformRawTime();
1164 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1165 mDNSs32 end
= mDNSPlatformRawTime();
1166 if (end
- start
>= WatchDogReportingThreshold
)
1167 LogInfo("CustomSourceHandler:WARNING: Idle task took %dms to complete", end
- start
);
1169 mDNSs32 now
= mDNS_TimeNow(m
);
1171 if (m
->ShutdownTime
)
1173 if (mDNSStorage
.ResourceRecords
)
1175 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, mDNSStorage
.ResourceRecords
));
1176 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1178 if (mDNS_ExitNow(m
, now
))
1180 LogInfo("IdleLoop: mDNS_FinalExit");
1181 mDNS_FinalExit(&mDNSStorage
);
1182 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1185 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1186 nextTimerEvent
= m
->ShutdownTime
;
1190 if (!AllowSleepNow(now
))
1191 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1192 nextTimerEvent
= m
->SleepLimit
;
1194 // Convert absolute wakeup time to a relative time from now
1195 mDNSs32 ticks
= nextTimerEvent
- now
;
1196 if (ticks
< 1) ticks
= 1;
1198 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1204 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1207 time_offset
= ((mDNSu32
)ticks
/ mDNSPlatformOneSecond
) * 1000000000 + (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1208 dtime
= dispatch_time(DISPATCH_TIME_NOW
, time_offset
);
1209 dispatch_source_set_timer(PlatformStorage
.timer
, dtime
, 1000ull*1000000000, 0);
1210 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks
);
1214 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1216 mDNSlocal
void KQWokenFlushBytes(int fd
, __unused
short filter
, __unused
void *context
, __unused mDNSBool encounteredEOF
)
1218 // Read all of the bytes so we won't wake again.
1220 while (recv(fd
, buffer
, sizeof(buffer
), MSG_DONTWAIT
) > 0) continue;
1223 mDNSlocal
void SetLowWater(const KQSocketSet
*const k
, const int r
)
1225 if (k
->sktv4
>=0 && setsockopt(k
->sktv4
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1226 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k
->sktv4
, r
, errno
, strerror(errno
));
1227 if (k
->sktv6
>=0 && setsockopt(k
->sktv6
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1228 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k
->sktv6
, r
, errno
, strerror(errno
));
1231 mDNSlocal
void * KQueueLoop(void *m_param
)
1236 #if USE_SELECT_WITH_KQUEUEFD
1239 const int multiplier
= 1000000 / mDNSPlatformOneSecond
;
1241 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1244 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1245 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32
)mDNSStorage
.timenow_last
, mDNSStorage
.timenow_last
);
1247 // This is the main work loop:
1248 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1249 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1250 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1251 // (4) On wakeup we first process *all* events
1252 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
1255 #define kEventsToReadAtOnce 1
1256 struct kevent new_events
[kEventsToReadAtOnce
];
1258 // Run mDNS_Execute to find out the time we next need to wake up
1259 mDNSs32 start
= mDNSPlatformRawTime();
1260 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1261 mDNSs32 end
= mDNSPlatformRawTime();
1262 if (end
- start
>= WatchDogReportingThreshold
)
1263 LogInfo("WARNING: Idle task took %dms to complete", end
- start
);
1265 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
1269 mDNSs32 now
= mDNS_TimeNow(m
);
1271 if (m
->ShutdownTime
)
1273 if (mDNSStorage
.ResourceRecords
)
1276 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
1278 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, rr
));
1279 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1282 if (mDNS_ExitNow(m
, now
))
1284 LogInfo("mDNS_FinalExit");
1285 mDNS_FinalExit(&mDNSStorage
);
1286 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1289 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1290 nextTimerEvent
= m
->ShutdownTime
;
1294 if (!AllowSleepNow(now
))
1295 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1296 nextTimerEvent
= m
->SleepLimit
;
1298 // Convert absolute wakeup time to a relative time from now
1299 mDNSs32 ticks
= nextTimerEvent
- now
;
1300 if (ticks
< 1) ticks
= 1;
1302 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1308 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1311 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents
, ticks
);
1314 // Release the lock, and sleep until:
1315 // 1. Something interesting happens like a packet arriving, or
1316 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
1317 // 3. The timeout expires
1318 pthread_mutex_unlock(&PlatformStorage
.BigMutex
);
1320 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1321 if (m
->p
->num_mcasts
)
1323 SetLowWater(&m
->p
->permanentsockets
, 0x10000);
1324 if (ticks
> mDNSPlatformOneSecond
/ 8) ticks
= mDNSPlatformOneSecond
/ 8;
1327 #if USE_SELECT_WITH_KQUEUEFD
1328 struct timeval timeout
;
1329 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1330 timeout
.tv_usec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1331 FD_SET(KQueueFD
, &readfds
);
1332 if (select(KQueueFD
+1, &readfds
, NULL
, NULL
, &timeout
) < 0)
1333 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1335 struct timespec timeout
;
1336 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1337 timeout
.tv_nsec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1338 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
1339 // and have it work similarly to the way it does with nevents non-zero --
1340 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
1341 // In fact, what happens if you do this is that it just returns immediately. So, we have
1342 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
1343 if (kevent(KQueueFD
, NULL
, 0, new_events
, 1, &timeout
) < 0)
1344 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1347 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1348 // We have to ignore the event we may have been told about above, because that
1349 // was done without holding the lock, and between the time we woke up and the
1350 // time we reclaimed the lock the other thread could have done something that
1351 // makes the event no longer valid. Now we have the lock, we call kevent again
1352 // and this time we can safely process the events it tells us about.
1354 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
1355 if (m
->p
->num_mcasts
)
1357 SetLowWater(&m
->p
->permanentsockets
, 1);
1358 m
->p
->num_mcasts
= 0;
1361 static const struct timespec zero_timeout
= { 0, 0 };
1363 while ((events_found
= kevent(KQueueFD
, NULL
, 0, new_events
, kEventsToReadAtOnce
, &zero_timeout
)) != 0)
1365 if (events_found
> kEventsToReadAtOnce
|| (events_found
< 0 && errno
!= EINTR
))
1367 const int kevent_errno
= errno
;
1368 // Not sure what to do here, our kqueue has failed us - this isn't ideal
1369 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", kevent_errno
, strerror(kevent_errno
));
1373 numevents
+= events_found
;
1376 for (i
= 0; i
< events_found
; i
++)
1378 const KQueueEntry
*const kqentry
= new_events
[i
].udata
;
1379 mDNSs32 stime
= mDNSPlatformRawTime();
1380 const char *const KQtask
= kqentry
->KQtask
; // Grab a copy in case KQcallback deletes the task
1381 kqentry
->KQcallback(new_events
[i
].ident
, new_events
[i
].filter
, kqentry
->KQcontext
, (new_events
[i
].flags
& EV_EOF
) != 0);
1382 mDNSs32 etime
= mDNSPlatformRawTime();
1383 if (etime
- stime
>= WatchDogReportingThreshold
)
1384 LogInfo("WARNING: %s took %dms to complete", KQtask
, etime
- stime
);
1392 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1394 mDNSlocal
size_t LaunchdCheckin(void)
1396 // Ask launchd for our socket
1397 int result
= launch_activate_socket("Listeners", &launchd_fds
, &launchd_fds_count
);
1398 if (result
!= 0) { LogMsg("launch_activate_socket() failed error %d (%s)", result
, strerror(result
)); }
1399 return launchd_fds_count
;
1403 extern int sandbox_init(const char *profile
, uint64_t flags
, char **errorbuf
) __attribute__((weak_import
));
1405 #if APPLE_OSX_mDNSResponder
1406 mDNSlocal mDNSBool
PreferencesGetValueBool(CFStringRef key
, mDNSBool defaultValue
)
1408 CFBooleanRef boolean
;
1409 mDNSBool result
= defaultValue
;
1411 boolean
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1414 if (CFGetTypeID(boolean
) == CFBooleanGetTypeID())
1415 result
= CFBooleanGetValue(boolean
) ? mDNStrue
: mDNSfalse
;
1422 mDNSlocal
int PreferencesGetValueInt(CFStringRef key
, int defaultValue
)
1426 int result
= defaultValue
;
1428 number
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1431 if ((CFGetTypeID(number
) == CFNumberGetTypeID()) && CFNumberGetValue(number
, kCFNumberIntType
, &numberValue
))
1432 result
= numberValue
;
1440 mDNSlocal
void SandboxProcess(void)
1442 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1444 LogMsg("Note: Compiled without Apple Sandbox support");
1445 #else // MDNS_NO_SANDBOX
1447 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1451 uint64_t sandbox_flags
= SANDBOX_NAMED
;
1453 (void)confstr(_CS_DARWIN_USER_CACHE_DIR
, NULL
, 0);
1455 int sandbox_err
= sandbox_init("mDNSResponder", sandbox_flags
, &sandbox_msg
);
1458 LogMsg("WARNING: sandbox_init error %s", sandbox_msg
);
1459 // If we have errors in the sandbox during development, to prevent
1460 // exiting, uncomment the following line.
1461 //sandbox_free_error(sandbox_msg);
1463 errx(EX_OSERR
, "sandbox_init() failed: %s", sandbox_msg
);
1465 else LogInfo("Now running under Apple Sandbox restrictions");
1467 #endif // MDNS_NO_SANDBOX
1470 #if APPLE_OSX_mDNSResponder
1471 mDNSlocal
void init_logging(void)
1473 log_general
= os_log_create("com.apple.mDNSResponder", "AllINFO");
1477 // OS_LOG_DEFAULT is the default logging object, if you are not creating a custom subsystem/category
1478 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in mDNSResponder");
1484 // Run the unit test main
1487 mDNSexport
int main(int argc
, char **argv
)
1490 kern_return_t status
;
1493 bool useDebugSocket
= mDNSfalse
;
1494 bool useSandbox
= mDNStrue
;
1497 #if APPLE_OSX_mDNSResponder
1501 mDNSMacOSXSystemBuildNumber(NULL
);
1502 LogMsg("%s starting %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
1505 LogMsg("CacheRecord %5d", sizeof(CacheRecord
));
1506 LogMsg("CacheGroup %5d", sizeof(CacheGroup
));
1507 LogMsg("ResourceRecord %5d", sizeof(ResourceRecord
));
1508 LogMsg("RData_small %5d", sizeof(RData_small
));
1510 LogMsg("sizeof(CacheEntity) %5d", sizeof(CacheEntity
));
1511 LogMsg("RR_CACHE_SIZE %5d", RR_CACHE_SIZE
);
1512 LogMsg("block bytes used %5d", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1513 LogMsg("block bytes wasted %5d", 32*1024 - sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1518 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1522 for (i
=1; i
<argc
; i
++)
1524 if (!strcasecmp(argv
[i
], "-d" )) mDNS_DebugMode
= mDNStrue
;
1525 if (!strcasecmp(argv
[i
], "-NoMulticastAdvertisements")) NoMulticastAdvertisements
= mDNStrue
;
1526 if (!strcasecmp(argv
[i
], "-DisableSleepProxyClient" )) DisableSleepProxyClient
= mDNStrue
;
1527 if (!strcasecmp(argv
[i
], "-DebugLogging" )) mDNS_LoggingEnabled
= mDNStrue
;
1528 if (!strcasecmp(argv
[i
], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled
= mDNStrue
;
1529 if (!strcasecmp(argv
[i
], "-OfferSleepProxyService" ))
1530 OfferSleepProxyService
= (i
+1 < argc
&& mDNSIsDigit(argv
[i
+1][0]) && mDNSIsDigit(argv
[i
+1][1]) && argv
[i
+1][2]==0) ? atoi(argv
[++i
]) : 100;
1531 if (!strcasecmp(argv
[i
], "-UseInternalSleepProxy" ))
1532 UseInternalSleepProxy
= (i
+1<argc
&& mDNSIsDigit(argv
[i
+1][0]) && argv
[i
+1][1]==0) ? atoi(argv
[++i
]) : 1;
1533 if (!strcasecmp(argv
[i
], "-StrictUnicastOrdering" )) StrictUnicastOrdering
= mDNStrue
;
1534 if (!strcasecmp(argv
[i
], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains
= mDNStrue
;
1535 if (!strcasecmp(argv
[i
], "-DisableAllowExpired" )) EnableAllowExpired
= mDNSfalse
;
1537 if (!strcasecmp(argv
[i
], "-UseDebugSocket")) useDebugSocket
= mDNStrue
;
1538 if (!strcasecmp(argv
[i
], "-NoSandbox")) useSandbox
= mDNSfalse
;
1543 #if APPLE_OSX_mDNSResponder
1544 /* Reads the external user's program arguments for mDNSResponder starting 10.11.x(El Capitan) on OSX. The options for external user are:
1545 DebugLogging, UnicastPacketLogging, NoMulticastAdvertisements, StrictUnicastOrdering and AlwaysAppendSearchDomains
1547 To turn ON the particular option, here is what the user should do (as an example of setting two options)
1548 1] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool YES
1549 2] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
1552 To turn OFF all options, here is what the user should do
1553 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1556 To view the current options set, here is what the user should do
1557 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1559 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
1563 // Currently on Fuji/Whitetail releases we are keeping the logging always enabled.
1564 // Hence mDNS_LoggingEnabled and mDNS_PacketLoggingEnabled is set to true below by default.
1566 mDNS_LoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_DebugLogging
, mDNS_LoggingEnabled
);
1567 mDNS_PacketLoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging
, mDNS_PacketLoggingEnabled
);
1570 mDNS_LoggingEnabled
= mDNStrue
;
1571 mDNS_PacketLoggingEnabled
= mDNStrue
;
1573 NoMulticastAdvertisements
= PreferencesGetValueBool(kPreferencesKey_NoMulticastAdvertisements
, NoMulticastAdvertisements
);
1574 StrictUnicastOrdering
= PreferencesGetValueBool(kPreferencesKey_StrictUnicastOrdering
, StrictUnicastOrdering
);
1575 AlwaysAppendSearchDomains
= PreferencesGetValueBool(kPreferencesKey_AlwaysAppendSearchDomains
, AlwaysAppendSearchDomains
);
1576 EnableAllowExpired
= PreferencesGetValueBool(kPreferencesKey_EnableAllowExpired
, EnableAllowExpired
);
1577 OfferSleepProxyService
= PreferencesGetValueInt(kPreferencesKey_OfferSleepProxyService
, OfferSleepProxyService
);
1578 UseInternalSleepProxy
= PreferencesGetValueInt(kPreferencesKey_UseInternalSleepProxy
, UseInternalSleepProxy
);
1580 #if ENABLE_BLE_TRIGGERED_BONJOUR
1581 EnableBLEBasedDiscovery
= PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery
, EnableBLEBasedDiscovery
);
1582 DefaultToBLETriggered
= PreferencesGetValueBool(kPreferencesKey_DefaultToBLETriggered
, DefaultToBLETriggered
);
1583 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
1585 #if TARGET_OS_IPHONE
1586 PreallocateCacheMemory
= PreferencesGetValueBool(kPreferencesKey_PreallocateCacheMemory
, PreallocateCacheMemory
);
1590 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
1591 if (NoMulticastAdvertisements
)
1592 LogMsg("-NoMulticastAdvertisements is set: Administratively prohibiting multicast advertisements");
1593 if (AlwaysAppendSearchDomains
)
1594 LogMsg("-AlwaysAppendSearchDomains is set");
1595 if (StrictUnicastOrdering
)
1596 LogMsg("-StrictUnicastOrdering is set");
1598 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1600 signal(SIGHUP
, HandleSIG
); // (Debugging) Purge the cache to check for cache handling bugs
1601 signal(SIGINT
, HandleSIG
); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
1602 signal(SIGPIPE
, SIG_IGN
); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
1603 signal(SIGTERM
, HandleSIG
); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
1604 signal(SIGINFO
, HandleSIG
); // (Debugging) Write state snapshot to syslog
1605 signal(SIGUSR1
, HandleSIG
); // (Debugging) Enable Logging
1606 signal(SIGUSR2
, HandleSIG
); // (Debugging) Enable Packet Logging
1607 signal(SIGPROF
, HandleSIG
); // (Debugging) Toggle Multicast Logging
1608 signal(SIGTSTP
, HandleSIG
); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
1610 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1612 mDNSStorage
.p
= &PlatformStorage
; // Make sure mDNSStorage.p is set up, because validatelists uses it
1613 // Need to Start XPC Server Before LaunchdCheckin() (Reason: rdar11023750)
1616 if (!useDebugSocket
) {
1617 if (LaunchdCheckin() == 0)
1618 useDebugSocket
= mDNStrue
;
1621 SetDebugBoundPath();
1626 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1628 // Create the kqueue, mutex and thread to support KQSockets
1629 KQueueFD
= kqueue();
1632 const int kqueue_errno
= errno
;
1633 LogMsg("kqueue() failed errno %d (%s)", kqueue_errno
, strerror(kqueue_errno
));
1634 status
= kqueue_errno
;
1638 i
= pthread_mutex_init(&PlatformStorage
.BigMutex
, NULL
);
1639 if (i
!= 0) { LogMsg("pthread_mutex_init() failed error %d (%s)", i
, strerror(i
)); status
= i
; goto exit
; }
1641 int fdpair
[2] = {0, 0};
1642 i
= socketpair(AF_UNIX
, SOCK_STREAM
, 0, fdpair
);
1645 const int socketpair_errno
= errno
;
1646 LogMsg("socketpair() failed errno %d (%s)", socketpair_errno
, strerror(socketpair_errno
));
1647 status
= socketpair_errno
;
1651 // Socket pair returned us two identical sockets connected to each other
1652 // We will use the first socket to send the second socket. The second socket
1653 // will be added to the kqueue so it will wake when data is sent.
1654 static const KQueueEntry wakeKQEntry
= { KQWokenFlushBytes
, NULL
, "kqueue wakeup after CFRunLoop event" };
1656 PlatformStorage
.WakeKQueueLoopFD
= fdpair
[0];
1657 KQueueSet(fdpair
[1], EV_ADD
, EVFILT_READ
, &wakeKQEntry
);
1659 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1667 status
= MetricsInit();
1668 if (status
) { LogMsg("Daemon start: MetricsInit failed (%d)", status
); }
1671 status
= mDNSDaemonInitialize();
1672 if (status
) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit
; }
1674 status
= udsserver_init(launchd_fds
, launchd_fds_count
);
1675 if (status
) { LogMsg("Daemon start: udsserver_init failed"); goto exit
; }
1677 mDNSMacOSXNetworkChanged();
1680 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1681 LogInfo("Daemon Start: Using LibDispatch");
1682 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
1684 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1685 // Start the kqueue thread
1686 pthread_t KQueueThread
;
1687 i
= pthread_create(&KQueueThread
, NULL
, KQueueLoop
, &mDNSStorage
);
1688 if (i
!= 0) { LogMsg("pthread_create() failed error %d (%s)", i
, strerror(i
)); status
= i
; goto exit
; }
1692 LogMsg("ERROR: CFRunLoopRun Exiting.");
1693 mDNS_Close(&mDNSStorage
);
1695 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1697 LogMsg("%s exiting", mDNSResponderVersionString
);
1704 // uds_daemon.c support routines /////////////////////////////////////////////
1706 mDNSlocal
void kqUDSEventCallback(int fd
, short filter
, void *context
, __unused mDNSBool encounteredEOF
)
1708 const KQSocketEventSource
*const source
= context
;
1709 source
->callback(fd
, filter
, source
->context
);
1712 // Arrange things so that when data appears on fd, callback is called with context
1713 mDNSexport mStatus
udsSupportAddFDToEventLoop(int fd
, udsEventCallback callback
, void *context
, void **platform_data
)
1715 KQSocketEventSource
**p
= &gEventSources
;
1716 (void) platform_data
;
1717 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1718 if (*p
) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd
); return mStatus_AlreadyRegistered
; }
1720 KQSocketEventSource
*newSource
= (KQSocketEventSource
*) mallocL("KQSocketEventSource", sizeof *newSource
);
1721 if (!newSource
) return mStatus_NoMemoryErr
;
1723 newSource
->next
= mDNSNULL
;
1725 newSource
->callback
= callback
;
1726 newSource
->context
= context
;
1727 newSource
->kqs
.KQcallback
= kqUDSEventCallback
;
1728 newSource
->kqs
.KQcontext
= newSource
;
1729 newSource
->kqs
.KQtask
= "UDS client";
1730 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1731 newSource
->kqs
.readSource
= mDNSNULL
;
1732 newSource
->kqs
.writeSource
= mDNSNULL
;
1733 newSource
->kqs
.fdClosed
= mDNSfalse
;
1734 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1736 if (KQueueSet(fd
, EV_ADD
, EVFILT_READ
, &newSource
->kqs
) == 0)
1739 return mStatus_NoError
;
1742 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd
, errno
, strerror(errno
));
1743 freeL("KQSocketEventSource", newSource
);
1744 return mStatus_BadParamErr
;
1747 int udsSupportReadFD(dnssd_sock_t fd
, char *buf
, int len
, int flags
, void *platform_data
)
1749 (void) platform_data
;
1750 return recv(fd
, buf
, len
, flags
);
1753 mDNSexport mStatus
udsSupportRemoveFDFromEventLoop(int fd
, void *platform_data
) // Note: This also CLOSES the file descriptor
1755 KQSocketEventSource
**p
= &gEventSources
;
1756 (void) platform_data
;
1757 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1760 KQSocketEventSource
*s
= *p
;
1762 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
1763 // causes the kernel to automatically remove any associated kevents
1764 mDNSPlatformCloseFD(&s
->kqs
, s
->fd
);
1765 freeL("KQSocketEventSource", s
);
1766 return mStatus_NoError
;
1768 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd
);
1769 return mStatus_NoSuchNameErr
;
1773 #include "../unittests/daemon_ut.c"
1776 #if _BUILDING_XCODE_PROJECT_
1777 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
1778 const char *__crashreporter_info__
= mDNSResponderVersionString
;
1779 asm (".desc ___crashreporter_info__, 0x10");
1782 // For convenience when using the "strings" command, this is the last thing in the file
1783 // The "@(#) " pattern is a special prefix the "what" command looks for
1784 mDNSexport
const char mDNSResponderVersionString_SCCS
[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion
) " (" __DATE__
" " __TIME__
")";