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_NoMulticastAdvertisements CFSTR("NoMulticastAdvertisements")
66 #define kPreferencesKey_StrictUnicastOrdering CFSTR("StrictUnicastOrdering")
67 #define kPreferencesKey_OfferSleepProxyService CFSTR("OfferSleepProxyService")
68 #define kPreferencesKey_UseInternalSleepProxy CFSTR("UseInternalSleepProxy")
70 #if ENABLE_BLE_TRIGGERED_BONJOUR
71 #define kPreferencesKey_EnableBLEBasedDiscovery CFSTR("EnableBLEBasedDiscovery")
72 #define kPreferencesKey_DefaultToBLETriggered CFSTR("DefaultToBLETriggered")
73 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
76 #define kPreferencesKey_PreallocateCacheMemory CFSTR("PreallocateCacheMemory")
80 //*************************************************************************************************************
81 #if COMPILER_LIKES_PRAGMA_MARK
82 #pragma mark - Globals
85 static mDNS_PlatformSupport PlatformStorage
;
87 // Start off with a default cache of 32K (141 records of 232 bytes each)
88 // Each time we grow the cache we add another 141 records
89 // 141 * 232 = 32712 bytes.
90 // This fits in eight 4kB pages, with 56 bytes spare for memory block headers and similar overhead
91 #define RR_CACHE_SIZE ((32*1024) / sizeof(CacheRecord))
92 static CacheEntity rrcachestorage
[RR_CACHE_SIZE
];
93 struct CompileTimeAssertionChecks_RR_CACHE_SIZE
{ char a
[(RR_CACHE_SIZE
>= 141) ? 1 : -1]; };
94 #define kRRCacheGrowSize (sizeof(CacheEntity) * RR_CACHE_SIZE)
97 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
98 mDNSlocal
void PrepareForIdle(void *m_param
);
99 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
100 static mach_port_t signal_port
= MACH_PORT_NULL
;
101 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
103 static dnssd_sock_t
*launchd_fds
= mDNSNULL
;
104 static size_t launchd_fds_count
= 0;
106 static mDNSBool NoMulticastAdvertisements
= mDNSfalse
; // By default, advertise addresses (& other records) via multicast
108 extern mDNSBool StrictUnicastOrdering
;
109 extern mDNSBool AlwaysAppendSearchDomains
;
111 #if ENABLE_BLE_TRIGGERED_BONJOUR
112 extern mDNSBool EnableBLEBasedDiscovery
;
113 extern mDNSBool DefaultToBLETriggered
;
114 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
117 static mDNSBool PreallocateCacheMemory
= mDNSfalse
;
118 #define kRRCacheMemoryLimit 1000000 // For now, we limit the cache to at most 1MB on iOS devices.
121 // We keep a list of client-supplied event sources in KQSocketEventSource records
122 typedef struct KQSocketEventSource
124 struct KQSocketEventSource
*next
;
127 udsEventCallback callback
;
129 } KQSocketEventSource
;
131 static KQSocketEventSource
*gEventSources
;
133 //*************************************************************************************************************
134 #if COMPILER_LIKES_PRAGMA_MARK
136 #pragma mark - General Utility Functions
139 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
141 char _malloc_options
[] = "AXZ";
143 mDNSlocal
void validatelists(mDNS
*const m
)
145 #if BONJOUR_ON_DEMAND
146 mDNSu32 NumAllInterfaceRecords
= 0;
147 mDNSu32 NumAllInterfaceQuestions
= 0;
148 #endif // BONJOUR_ON_DEMAND
151 KQSocketEventSource
*k
;
152 for (k
= gEventSources
; k
; k
=k
->next
)
153 if (k
->next
== (KQSocketEventSource
*)~0 || k
->fd
< 0)
154 LogMemCorruption("gEventSources: %p is garbage (%d)", k
, k
->fd
);
156 // Check Unix Domain Socket client lists (uds_daemon.c)
159 // Check core mDNS lists
161 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
163 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
164 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
165 if (rr
->resrec
.name
!= &rr
->namestorage
)
166 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
167 rr
, rr
->resrec
.name
->c
, rr
->namestorage
.c
, rr
->namestorage
.c
);
168 #if BONJOUR_ON_DEMAND
169 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
170 #endif // BONJOUR_ON_DEMAND
173 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
)
175 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
176 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
177 #if BONJOUR_ON_DEMAND
178 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
179 #endif // BONJOUR_ON_DEMAND
182 rr
= m
->NewLocalRecords
;
184 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
185 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
187 rr
= m
->CurrentRecord
;
189 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
190 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
193 for (q
= m
->Questions
; q
; q
=q
->next
)
195 if (q
->next
== (DNSQuestion
*)~0 || q
->ThisQInterval
== (mDNSs32
) ~0)
196 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q
, q
->ThisQInterval
, q
->next
);
197 if (q
->DuplicateOf
&& q
->LocalSocket
)
198 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
199 #if BONJOUR_ON_DEMAND
200 if (!LocalOnlyOrP2PInterface(q
->InterfaceID
) && mDNSOpaque16IsZero(q
->TargetQID
))
201 NumAllInterfaceQuestions
++;
202 #endif // BONJOUR_ON_DEMAND
208 FORALL_CACHERECORDS(slot
, cg
, cr
)
210 if (cr
->resrec
.RecordType
== 0 || cr
->resrec
.RecordType
== 0xFF)
211 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot
, cr
, cr
->resrec
.RecordType
);
212 if (cr
->CRActiveQuestion
)
214 for (q
= m
->Questions
; q
; q
=q
->next
) if (q
== cr
->CRActiveQuestion
) break;
215 if (!q
) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot
, cr
->CRActiveQuestion
, CRDisplayString(m
, cr
));
219 // Check core uDNS lists
220 udns_validatelists(m
);
222 // Check platform-layer lists
223 NetworkInterfaceInfoOSX
*i
;
224 for (i
= m
->p
->InterfaceList
; i
; i
= i
->next
)
225 if (i
->next
== (NetworkInterfaceInfoOSX
*)~0 || !i
->m
|| i
->m
== (mDNS
*)~0)
226 LogMemCorruption("m->p->InterfaceList: %p is garbage (%p)", i
, i
->ifinfo
.ifname
);
229 for (t
= m
->TunnelClients
; t
; t
=t
->next
)
230 if (t
->next
== (ClientTunnel
*)~0 || t
->dstname
.c
[0] > 63)
231 LogMemCorruption("m->TunnelClients: %p is garbage (%d)", t
, t
->dstname
.c
[0]);
233 #if BONJOUR_ON_DEMAND
234 if (m
->NumAllInterfaceRecords
!= NumAllInterfaceRecords
)
235 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m
->NumAllInterfaceRecords
, NumAllInterfaceRecords
);
237 if (m
->NumAllInterfaceQuestions
!= NumAllInterfaceQuestions
)
238 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m
->NumAllInterfaceQuestions
, NumAllInterfaceQuestions
);
239 #endif // BONJOUR_ON_DEMAND
242 mDNSexport
void *mallocL(char *msg
, unsigned int size
)
244 // Allocate space for two words of sanity checking data before the requested block
245 mDNSu32
*mem
= malloc(sizeof(mDNSu32
) * 2 + size
);
247 { LogMsg("malloc( %s : %d ) failed", msg
, size
); return(NULL
); }
250 if (size
> 32768) LogMsg("malloc( %s : %lu ) @ %p suspiciously large", msg
, size
, &mem
[2]);
251 else if (MACOSX_MDNS_MALLOC_DEBUGGING
>= 2) LogMsg("malloc( %s : %lu ) @ %p", msg
, size
, &mem
[2]);
254 //mDNSPlatformMemZero(&mem[2], size);
255 memset(&mem
[2], 0xFF, size
);
256 validatelists(&mDNSStorage
);
261 mDNSexport
void freeL(char *msg
, void *x
)
264 LogMsg("free( %s @ NULL )!", msg
);
267 mDNSu32
*mem
= ((mDNSu32
*)x
) - 2;
268 if (mem
[0] == 0xDEADDEAD) { LogMemCorruption("free( %s : %lu @ %p ) !!!! ALREADY DISPOSED !!!!", msg
, mem
[1], &mem
[2]); return; }
269 if (mem
[0] != 0xDEAD1234) { LogMemCorruption("free( %s : %lu @ %p ) !!!! NEVER ALLOCATED !!!!", msg
, mem
[1], &mem
[2]); return; }
270 if (mem
[1] > 32768) LogMsg("free( %s : %lu @ %p) suspiciously large", msg
, mem
[1], &mem
[2]);
271 else if (MACOSX_MDNS_MALLOC_DEBUGGING
>= 2) LogMsg("free( %s : %ld @ %p)", msg
, mem
[1], &mem
[2]);
273 memset(mem
+2, 0xFF, mem
[1]);
274 validatelists(&mDNSStorage
);
281 //*************************************************************************************************************
284 mDNSexport
void RecordUpdatedNiceLabel(mDNSs32 delay
)
286 mDNSStorage
.p
->NotifyUser
= NonZeroTime(mDNSStorage
.timenow
+ delay
);
289 mDNSlocal
void mDNSPreferencesSetNames(int key
, domainlabel
*old
, domainlabel
*new)
291 mDNS
*const m
= &mDNSStorage
;
292 domainlabel
*prevold
, *prevnew
;
295 case kmDNSComputerName
:
296 case kmDNSLocalHostName
:
297 if (key
== kmDNSComputerName
)
299 prevold
= &m
->p
->prevoldnicelabel
;
300 prevnew
= &m
->p
->prevnewnicelabel
;
304 prevold
= &m
->p
->prevoldhostlabel
;
305 prevnew
= &m
->p
->prevnewhostlabel
;
307 // There are a few cases where we need to invoke the helper.
309 // 1. If the "old" label and "new" label are not same, it means there is a conflict. We need
310 // to invoke the helper so that it pops up a dialogue to inform the user about the
313 // 2. If the "old" label and "new" label are same, it means the user has set the host/nice label
314 // through the preferences pane. We may have to inform the helper as it may have popped up
315 // a dialogue previously (due to a conflict) and it needs to suppress it now. We can avoid invoking
316 // the helper in this case if the previous values (old and new) that we told helper last time
317 // are same. If the previous old and new values are same, helper does not care.
319 // Note: "new" can be NULL when we have repeated conflicts and we are asking helper to give up. "old"
320 // is not called with NULL today, but this makes it future proof.
321 if (!old
|| !new || !SameDomainLabelCS(old
->c
, new->c
) ||
322 !SameDomainLabelCS(old
->c
, prevold
->c
) ||
323 !SameDomainLabelCS(new->c
, prevnew
->c
))
325 // Work around bug radar:21397654
326 #ifndef __clang_analyzer__
336 mDNSPreferencesSetName(key
, old
, new);
340 LogInfo("mDNSPreferencesSetNames not invoking helper %s %#s, %s %#s, old %#s, new %#s",
341 (key
== kmDNSComputerName
? "prevoldnicelabel" : "prevoldhostlabel"), prevold
->c
,
342 (key
== kmDNSComputerName
? "prevnewnicelabel" : "prevnewhostlabel"), prevnew
->c
,
347 LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key
);
352 mDNSlocal
void mDNS_StatusCallback(mDNS
*const m
, mStatus result
)
354 if (result
== mStatus_NoError
)
356 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
357 LogInfo("Local Hostname changed from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
358 // One second pause in case we get a Computer Name update too -- don't want to alert the user twice
359 RecordUpdatedNiceLabel(mDNSPlatformOneSecond
);
361 else if (result
== mStatus_NameConflict
)
363 LogInfo("Local Hostname conflict for \"%#s.local\"", m
->hostlabel
.c
);
364 if (!m
->p
->HostNameConflict
) m
->p
->HostNameConflict
= NonZeroTime(m
->timenow
);
365 else if (m
->timenow
- m
->p
->HostNameConflict
> 60 * mDNSPlatformOneSecond
)
367 // Tell the helper we've given up
368 mDNSPreferencesSetNames(kmDNSLocalHostName
, &m
->p
->userhostlabel
, NULL
);
371 else if (result
== mStatus_GrowCache
)
373 // Allocate another chunk of cache storage
374 static unsigned int allocated
= 0;
376 if (allocated
>= kRRCacheMemoryLimit
) return; // For now we limit the cache to at most 1MB on iOS devices
378 allocated
+= kRRCacheGrowSize
;
379 // LogMsg("GrowCache %d * %d = %d; total so far %6u", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE, allocated);
380 CacheEntity
*storage
= mallocL("mStatus_GrowCache", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
381 //LogInfo("GrowCache %d * %d = %d", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE);
382 if (storage
) mDNS_GrowCache(m
, storage
, RR_CACHE_SIZE
);
384 else if (result
== mStatus_ConfigChanged
)
386 // Tell the helper we've seen a change in the labels. It will dismiss the name conflict alert if needed.
387 mDNSPreferencesSetNames(kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
388 mDNSPreferencesSetNames(kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
390 // Then we call into the UDS daemon code, to let it do the same
391 udsserver_handle_configchange(m
);
396 //*************************************************************************************************************
397 #if COMPILER_LIKES_PRAGMA_MARK
399 #pragma mark - Startup, shutdown, and supporting code
402 mDNSlocal
void ExitCallback(int sig
)
405 LogMsg("%s stopping", mDNSResponderVersionString
);
407 if (udsserver_exit() < 0)
408 LogMsg("ExitCallback: udsserver_exit failed");
410 debugf("ExitCallback: mDNS_StartExit");
411 mDNS_StartExit(&mDNSStorage
);
414 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
416 // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
417 mDNSlocal
void HandleSIG(int sig
)
419 kern_return_t status
;
420 mach_msg_header_t header
;
422 // WARNING: can't call syslog or fprintf from signal handler
423 header
.msgh_bits
= MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND
, 0);
424 header
.msgh_remote_port
= signal_port
;
425 header
.msgh_local_port
= MACH_PORT_NULL
;
426 header
.msgh_size
= sizeof(header
);
427 header
.msgh_id
= sig
;
429 status
= mach_msg(&header
, MACH_SEND_MSG
| MACH_SEND_TIMEOUT
, header
.msgh_size
,
430 0, MACH_PORT_NULL
, 0, MACH_PORT_NULL
);
432 if (status
!= MACH_MSG_SUCCESS
)
434 if (status
== MACH_SEND_TIMED_OUT
) mach_msg_destroy(&header
);
435 if (sig
== SIGTERM
|| sig
== SIGINT
) exit(-1);
439 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
441 mDNSexport
void INFOCallback(void)
443 mDNSs32 utc
= mDNSPlatformUTC();
444 const mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
445 NetworkInterfaceInfoOSX
*i
;
449 LogMsg("---- BEGIN STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
453 LogMsgNoIdent("----- Platform Timers -----");
454 LogTimer("m->NextCacheCheck ", mDNSStorage
.NextCacheCheck
);
455 LogTimer("m->NetworkChanged ", mDNSStorage
.NetworkChanged
);
456 LogTimer("m->p->NotifyUser ", mDNSStorage
.p
->NotifyUser
);
457 LogTimer("m->p->HostNameConflict ", mDNSStorage
.p
->HostNameConflict
);
458 LogTimer("m->p->KeyChainTimer ", mDNSStorage
.p
->KeyChainTimer
);
460 xpcserver_info(&mDNSStorage
);
462 LogMsgNoIdent("----- KQSocketEventSources -----");
463 if (!gEventSources
) LogMsgNoIdent("<None>");
466 KQSocketEventSource
*k
;
467 for (k
= gEventSources
; k
; k
=k
->next
)
468 LogMsgNoIdent("%3d %s %s", k
->fd
, k
->kqs
.KQtask
, k
->fd
== mDNSStorage
.uds_listener_skt
? "Listener for incoming UDS clients" : " ");
471 LogMsgNoIdent("------ Network Interfaces ------");
472 if (!mDNSStorage
.p
->InterfaceList
) LogMsgNoIdent("<None>");
475 LogMsgNoIdent(" Struct addr Registered MAC BSSID Interface Address");
476 for (i
= mDNSStorage
.p
->InterfaceList
; i
; i
= i
->next
)
478 // Allow six characters for interface name, for names like "vmnet8"
480 LogMsgNoIdent("%p %2ld, %p, %s %-6s %.6a %.6a %#-14a dormant for %d seconds",
481 i
, i
->ifinfo
.InterfaceID
, i
->Registered
,
482 i
->sa_family
== AF_INET
? "v4" : i
->sa_family
== AF_INET6
? "v6" : "??", i
->ifinfo
.ifname
, &i
->ifinfo
.MAC
, &i
->BSSID
,
483 &i
->ifinfo
.ip
, utc
- i
->LastSeen
);
486 const CacheRecord
*sps
[3];
487 FindSPSInCache(&mDNSStorage
, &i
->ifinfo
.NetWakeBrowse
, sps
);
488 LogMsgNoIdent("%p %2ld, %p, %s %-6s %.6a %.6a %s %s %s %s %s %s %#a",
489 i
, i
->ifinfo
.InterfaceID
, i
->Registered
,
490 i
->sa_family
== AF_INET
? "v4" : i
->sa_family
== AF_INET6
? "v6" : "??", i
->ifinfo
.ifname
, &i
->ifinfo
.MAC
, &i
->BSSID
,
491 i
->ifinfo
.InterfaceActive
? "Active" : " ",
492 i
->ifinfo
.IPv4Available
? "v4" : " ",
493 i
->ifinfo
.IPv6Available
? "v6" : " ",
494 i
->ifinfo
.Advertise
? "A" : " ",
495 i
->ifinfo
.McastTxRx
? "M" : " ",
496 !(i
->ifinfo
.InterfaceActive
&& i
->ifinfo
.NetWake
) ? " " : !sps
[0] ? "p" : "P",
499 // Only print the discovered sleep proxies once for the lead/active interface of an interface set.
500 if (i
== i
->Registered
&& (sps
[0] || sps
[1] || sps
[2]))
502 LogMsgNoIdent(" Sleep Proxy Metric Name");
503 if (sps
[0]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[0]->resrec
.rdata
->u
.name
.c
), sps
[0]->resrec
.rdata
->u
.name
.c
);
504 if (sps
[1]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[1]->resrec
.rdata
->u
.name
.c
), sps
[1]->resrec
.rdata
->u
.name
.c
);
505 if (sps
[2]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[2]->resrec
.rdata
->u
.name
.c
), sps
[2]->resrec
.rdata
->u
.name
.c
);
511 LogMsgNoIdent("--------- DNS Servers(%d) ----------", NumUnicastDNSServers
);
512 if (!mDNSStorage
.DNSServers
) LogMsgNoIdent("<None>");
515 for (s
= mDNSStorage
.DNSServers
; s
; s
= s
->next
)
517 NetworkInterfaceInfoOSX
*ifx
= IfindexToInterfaceInfoOSX(s
->interface
);
518 LogMsgNoIdent("DNS Server %##s %s%s%#a:%d %d %s %d %d %s %s %s %s %s",
519 s
->domain
.c
, ifx
? ifx
->ifinfo
.ifname
: "", ifx
? " " : "", &s
->addr
, mDNSVal16(s
->port
),
520 s
->penaltyTime
? s
->penaltyTime
- mDNS_TimeNow(&mDNSStorage
) : 0, DNSScopeToString(s
->scoped
),
521 s
->timeout
, s
->resGroupID
,
522 s
->req_A
? "v4" : "!v4",
523 s
->req_AAAA
? "v6" : "!v6",
524 s
->cellIntf
? "cell" : "!cell",
525 s
->isExpensive
? "exp" : "!exp",
526 s
->DNSSECAware
? "DNSSECAware" : "!DNSSECAware");
530 LogMsgNoIdent("v4answers %d", mDNSStorage
.p
->v4answers
);
531 LogMsgNoIdent("v6answers %d", mDNSStorage
.p
->v6answers
);
532 LogMsgNoIdent("Last DNS Trigger: %d ms ago", (now
- mDNSStorage
.p
->DNSTrigger
));
534 LogMsgNoIdent("--------- Mcast Resolvers ----------");
535 if (!mDNSStorage
.McastResolvers
) LogMsgNoIdent("<None>");
538 for (mr
= mDNSStorage
.McastResolvers
; mr
; mr
= mr
->next
)
539 LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr
->domain
.c
, mr
->timeout
);
542 LogMsgNoIdent("------------ Hostnames -------------");
543 if (!mDNSStorage
.Hostnames
) LogMsgNoIdent("<None>");
547 for (hi
= mDNSStorage
.Hostnames
; hi
; hi
= hi
->next
)
549 LogMsgNoIdent("%##s v4 %d %s", hi
->fqdn
.c
, hi
->arv4
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv4
));
550 LogMsgNoIdent("%##s v6 %d %s", hi
->fqdn
.c
, hi
->arv6
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv6
));
554 LogMsgNoIdent("--------------- FQDN ---------------");
555 if (!mDNSStorage
.FQDN
.c
[0]) LogMsgNoIdent("<None>");
558 LogMsgNoIdent("%##s", mDNSStorage
.FQDN
.c
);
564 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
565 LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
569 mDNSexport
void mDNSPlatformLogToFile(int log_level
, const char *buffer
)
572 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in init_logging()");
574 os_log_with_type(log_general
, log_level
, "%s", buffer
);
578 // Writes the state out to the dynamic store and also affects the ASL filter level
579 mDNSexport
void UpdateDebugState()
584 CFMutableDictionaryRef dict
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
587 LogMsg("UpdateDebugState: Could not create dict");
591 CFNumberRef numOne
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &one
);
594 LogMsg("UpdateDebugState: Could not create CFNumber one");
597 CFNumberRef numZero
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &zero
);
600 LogMsg("UpdateDebugState: Could not create CFNumber zero");
605 if (mDNS_LoggingEnabled
)
606 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numOne
);
608 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numZero
);
610 if (mDNS_PacketLoggingEnabled
)
611 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numOne
);
613 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numZero
);
615 if (mDNS_McastLoggingEnabled
)
616 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numOne
);
618 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numZero
);
620 if (mDNS_McastTracingEnabled
)
621 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numOne
);
623 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numZero
);
627 mDNSDynamicStoreSetConfig(kmDNSDebugState
, mDNSNULL
, dict
);
633 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
635 mDNSlocal
void SignalCallback(CFMachPortRef port
, void *msg
, CFIndex size
, void *info
)
637 (void)port
; // Unused
638 (void)size
; // Unused
639 (void)info
; // Unused
640 mach_msg_header_t
*msg_header
= (mach_msg_header_t
*)msg
;
641 mDNS
*const m
= &mDNSStorage
;
643 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
645 switch(msg_header
->msgh_id
)
651 LogMsg("SIGHUP: Purge cache");
653 FORALL_CACHERECORDS(slot
, cg
, rr
)
655 mDNS_PurgeCacheResourceRecord(m
, rr
);
657 // Restart unicast and multicast queries
658 mDNSCoreRestartQueries(m
);
662 case SIGTERM
: ExitCallback(msg_header
->msgh_id
); break;
663 case SIGINFO
: INFOCallback(); break;
665 #if APPLE_OSX_mDNSResponder
666 mDNS_LoggingEnabled
= 1;
667 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
669 mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
670 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
672 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
674 LogInfo("USR1 Logging Enabled");
677 #if APPLE_OSX_mDNSResponder
678 mDNS_PacketLoggingEnabled
= 1;
679 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
681 mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
682 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
684 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
685 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
688 case SIGPROF
: mDNS_McastLoggingEnabled
= mDNS_McastLoggingEnabled
? mDNSfalse
: mDNStrue
;
689 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled
? "Enabled" : "Disabled");
690 LogMcastStateInfo(mDNSfalse
, mDNStrue
, mDNStrue
);
691 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
692 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
695 case SIGTSTP
: mDNS_LoggingEnabled
= mDNS_PacketLoggingEnabled
= mDNS_McastLoggingEnabled
= mDNS_McastTracingEnabled
= mDNSfalse
;
696 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
700 default: LogMsg("SignalCallback: Unknown signal %d", msg_header
->msgh_id
); break;
702 KQueueUnlock("Unix Signal");
705 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
706 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
710 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
711 rrcachestorage
, RR_CACHE_SIZE
,
712 !NoMulticastAdvertisements
,
713 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
717 LogMsg("Daemon start: mDNS_Init failed %d", err
);
722 if (PreallocateCacheMemory
)
724 const int growCount
= (kRRCacheMemoryLimit
+ kRRCacheGrowSize
- 1) / kRRCacheGrowSize
;
727 for (i
= 0; i
< growCount
; ++i
)
729 mDNS_StatusCallback(&mDNSStorage
, mStatus_GrowCache
);
734 CFMachPortRef i_port
= CFMachPortCreate(NULL
, SignalCallback
, NULL
, NULL
);
735 CFRunLoopSourceRef i_rls
= CFMachPortCreateRunLoopSource(NULL
, i_port
, 0);
736 signal_port
= CFMachPortGetPort(i_port
);
737 CFRunLoopAddSource(CFRunLoopGetMain(), i_rls
, kCFRunLoopDefaultMode
);
743 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
745 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
746 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
747 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
748 // of code from above. Alternatively we could remove the duplicated source code by having
749 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
751 mDNSlocal
void SignalDispatch(dispatch_source_t source
)
753 int sig
= (int)dispatch_source_get_handle(source
);
754 mDNS
*const m
= &mDNSStorage
;
762 LogMsg("SIGHUP: Purge cache");
764 FORALL_CACHERECORDS(slot
, cg
, rr
)
766 mDNS_PurgeCacheResourceRecord(m
, rr
);
768 // Restart unicast and multicast queries
769 mDNSCoreRestartQueries(m
);
773 case SIGTERM
: ExitCallback(sig
); break;
774 case SIGINFO
: INFOCallback(); break;
775 case SIGUSR1
: mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
776 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
777 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
780 case SIGUSR2
: mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
781 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
784 default: LogMsg("SignalCallback: Unknown signal %d", sig
); break;
786 KQueueUnlock("Unix Signal");
789 mDNSlocal
void mDNSSetupSignal(dispatch_queue_t queue
, int sig
)
791 signal(sig
, SIG_IGN
);
792 dispatch_source_t source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL
, sig
, 0, queue
);
796 dispatch_source_set_event_handler(source
, ^{SignalDispatch(source
);});
797 // Start processing signals
798 dispatch_resume(source
);
802 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig
);
806 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
809 dispatch_queue_t queue
= dispatch_get_main_queue();
811 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
812 rrcachestorage
, RR_CACHE_SIZE
,
813 !NoMulticastAdvertisements
,
814 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
818 LogMsg("Daemon start: mDNS_Init failed %d", err
);
822 mDNSSetupSignal(queue
, SIGHUP
);
823 mDNSSetupSignal(queue
, SIGINT
);
824 mDNSSetupSignal(queue
, SIGTERM
);
825 mDNSSetupSignal(queue
, SIGINFO
);
826 mDNSSetupSignal(queue
, SIGUSR1
);
827 mDNSSetupSignal(queue
, SIGUSR2
);
829 // Create a custom handler for doing the housekeeping work. This is either triggered
830 // by the timer or an event source
831 PlatformStorage
.custom
= dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD
, 0, 0, queue
);
832 if (PlatformStorage
.custom
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
833 dispatch_source_set_event_handler(PlatformStorage
.custom
, ^{PrepareForIdle(&mDNSStorage
);});
834 dispatch_resume(PlatformStorage
.custom
);
836 // Create a timer source to trigger housekeeping work. The houskeeping work itself
837 // is done in the custom handler that we set below.
839 PlatformStorage
.timer
= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER
, 0, 0, queue
);
840 if (PlatformStorage
.timer
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
842 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
843 // always reset the time to the new time computed. In effect, we ignore the interval
844 dispatch_source_set_timer(PlatformStorage
.timer
, DISPATCH_TIME_NOW
, 1000ull * 1000000000, 0);
845 dispatch_source_set_event_handler(PlatformStorage
.timer
, ^{
846 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
848 dispatch_resume(PlatformStorage
.timer
);
850 LogMsg("DaemonIntialize done successfully");
855 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
857 mDNSlocal mDNSs32
mDNSDaemonIdle(mDNS
*const m
)
859 mDNSs32 now
= mDNS_TimeNow(m
);
861 // 1. If we need to set domain secrets, do so before handling the network change
863 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
864 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
865 if (m
->p
->KeyChainTimer
&& now
- m
->p
->KeyChainTimer
>= 0)
867 m
->p
->KeyChainTimer
= 0;
873 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
875 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
876 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
877 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
878 // we then systematically lose our own looped-back packets.
879 if (m
->NetworkChanged
&& now
- m
->NetworkChanged
>= 0) mDNSMacOSXNetworkChanged();
881 if (m
->p
->RequestReSleep
&& now
- m
->p
->RequestReSleep
>= 0)
883 m
->p
->RequestReSleep
= 0;
884 mDNSPowerRequest(0, 0);
887 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
888 mDNSs32 nextevent
= mDNS_Execute(m
);
890 if (m
->NetworkChanged
)
891 if (nextevent
- m
->NetworkChanged
> 0)
892 nextevent
= m
->NetworkChanged
;
894 if (m
->p
->KeyChainTimer
)
895 if (nextevent
- m
->p
->KeyChainTimer
> 0)
896 nextevent
= m
->p
->KeyChainTimer
;
898 if (m
->p
->RequestReSleep
)
899 if (nextevent
- m
->p
->RequestReSleep
> 0)
900 nextevent
= m
->p
->RequestReSleep
;
903 if (m
->p
->NotifyUser
)
905 if (m
->p
->NotifyUser
- now
< 0)
907 if (!SameDomainLabelCS(m
->p
->usernicelabel
.c
, m
->nicelabel
.c
))
909 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m
->p
->usernicelabel
.c
, m
->nicelabel
.c
);
910 mDNSPreferencesSetNames(kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
911 m
->p
->usernicelabel
= m
->nicelabel
;
913 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
915 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
916 mDNSPreferencesSetNames(kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
917 m
->p
->HostNameConflict
= 0; // Clear our indicator, now name change has been successful
918 m
->p
->userhostlabel
= m
->hostlabel
;
920 m
->p
->NotifyUser
= 0;
923 if (nextevent
- m
->p
->NotifyUser
> 0)
924 nextevent
= m
->p
->NotifyUser
;
930 // Right now we consider *ALL* of our DHCP leases
931 // It might make sense to be a bit more selective and only consider the leases on interfaces
932 // (a) that are capable and enabled for wake-on-LAN, and
933 // (b) where we have found (and successfully registered with) a Sleep Proxy
934 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
935 mDNSlocal mDNSu32
DHCPWakeTime(void)
937 mDNSu32 e
= 24 * 3600; // Maximum maintenance wake interval is 24 hours
938 const CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
939 if (!now
) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
944 const void *pattern
= SCDynamicStoreKeyCreateNetworkServiceEntity(NULL
, kSCDynamicStoreDomainState
, kSCCompAnyRegex
, kSCEntNetDHCP
);
947 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
950 CFArrayRef dhcpinfo
= CFArrayCreate(NULL
, (const void **)&pattern
, 1, &kCFTypeArrayCallBacks
);
954 SCDynamicStoreRef store
= SCDynamicStoreCreate(NULL
, CFSTR("DHCP-LEASES"), NULL
, NULL
);
957 CFDictionaryRef dict
= SCDynamicStoreCopyMultiple(store
, NULL
, dhcpinfo
);
960 ic
= CFDictionaryGetCount(dict
);
961 const void *vals
[ic
];
962 CFDictionaryGetKeysAndValues(dict
, NULL
, vals
);
964 for (j
= 0; j
< ic
; j
++)
966 const CFDictionaryRef dhcp
= (CFDictionaryRef
)vals
[j
];
969 const CFDateRef start
= DHCPInfoGetLeaseStartTime(dhcp
);
970 const CFDataRef lease
= DHCPInfoGetOptionData(dhcp
, 51); // Option 51 = IP Address Lease Time
971 if (!start
|| !lease
|| CFDataGetLength(lease
) < 4)
972 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
973 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
974 j
, start
, lease
, lease
? CFDataGetLength(lease
) : 0);
977 const UInt8
*d
= CFDataGetBytePtr(lease
);
978 if (!d
) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j
);
981 const mDNSu32 elapsed
= now
- CFDateGetAbsoluteTime(start
);
982 const mDNSu32 lifetime
= (mDNSs32
) ((mDNSs32
)d
[0] << 24 | (mDNSs32
)d
[1] << 16 | (mDNSs32
)d
[2] << 8 | d
[3]);
983 const mDNSu32 remaining
= lifetime
- elapsed
;
984 const mDNSu32 wake
= remaining
> 60 ? remaining
- remaining
/10 : 54; // Wake at 90% of the lease time
985 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed
, lifetime
, remaining
, wake
);
986 if (e
> wake
) e
= wake
;
1001 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
1002 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
1003 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
1004 // for a few seconds and then waking again is silly and annoying.
1005 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
1006 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
1007 // allowing us an adequate safety margin to renew our lease before we lose it.
1009 mDNSlocal mDNSBool
AllowSleepNow(mDNSs32 now
)
1011 mDNS
*const m
= &mDNSStorage
;
1012 mDNSBool ready
= mDNSCoreReadyForSleep(m
, now
);
1013 if (m
->SleepState
&& !ready
&& now
- m
->SleepLimit
< 0) return(mDNSfalse
);
1015 m
->p
->WakeAtUTC
= 0;
1016 int result
= kIOReturnSuccess
;
1017 CFDictionaryRef opts
= NULL
;
1019 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
1020 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
1022 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m
->SleepLimit
- now
);
1025 if (!m
->SystemWakeOnLANEnabled
|| !mDNSCoreHaveAdvertisedMulticastServices(m
))
1026 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
1027 m
->SystemWakeOnLANEnabled
? "is" : "not",
1028 mDNSCoreHaveAdvertisedMulticastServices(m
) ? "have" : "no");
1031 mDNSs32 dhcp
= DHCPWakeTime();
1032 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp
);
1033 mDNSs32 interval
= mDNSCoreIntervalToNextWake(m
, now
) / mDNSPlatformOneSecond
;
1034 if (interval
> dhcp
) interval
= dhcp
;
1036 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
1037 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
1038 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
1039 // someone to go to the machine in person to wake it up again, which would be unacceptable.
1040 if (!ready
&& interval
> 3600) interval
= 3600;
1042 //interval = 48; // For testing
1044 #if !TARGET_OS_EMBEDDED
1045 #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1046 if (m
->p
->IOPMConnection
) // If lightweight-wake capability is available, use that
1048 const CFDateRef WakeDate
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent() + interval
);
1049 if (!WakeDate
) LogMsg("ScheduleNextWake: CFDateCreate failed");
1052 const mDNSs32 reqs
= kIOPMSystemPowerStateCapabilityNetwork
;
1053 const CFNumberRef Requirements
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &reqs
);
1054 if (!Requirements
) LogMsg("ScheduleNextWake: CFNumberCreate failed");
1057 const void *OptionKeys
[2] = { kIOPMAckDHCPRenewWakeDate
, kIOPMAckSystemCapabilityRequirements
};
1058 const void *OptionVals
[2] = { WakeDate
, Requirements
};
1059 opts
= CFDictionaryCreate(NULL
, (void*)OptionKeys
, (void*)OptionVals
, 2, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1060 if (!opts
) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
1061 CFRelease(Requirements
);
1063 CFRelease(WakeDate
);
1065 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval
);
1067 else // else schedule the wakeup using the old API instead to
1068 #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1069 #endif // TARGET_OS_EMBEDDED
1071 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
1072 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
1073 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
1074 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
1078 result
= mDNSPowerRequest(1, interval
);
1080 if (result
== kIOReturnNotReady
)
1083 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval
);
1084 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
1085 // requested wake time is "too soon", but there's no API to find out what constitutes
1086 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
1087 // we just have to iterate with successively longer intervals until it doesn't fail.
1088 // We preserve the value of "result" because if our original power request was deemed "too soon"
1089 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
1090 // since the implication is that the system won't manage to be awake again at the time we need it.
1093 interval
+= (interval
< 20) ? 1 : ((interval
+3) / 4);
1094 r
= mDNSPowerRequest(1, interval
);
1096 while (r
== kIOReturnNotReady
);
1097 if (r
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, r
, r
);
1098 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval
);
1102 if (result
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, result
, result
);
1103 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval
);
1105 m
->p
->WakeAtUTC
= mDNSPlatformUTC() + interval
;
1109 m
->SleepState
= SleepState_Sleeping
;
1110 // Clear our interface list to empty state, ready to go to sleep
1111 // As a side effect of doing this, we'll also cancel any outstanding SPS Resolve calls that didn't complete
1112 mDNSMacOSXNetworkChanged();
1115 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1116 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1117 (m
->p
->IOPMConnection
) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1119 (result
== kIOReturnSuccess
) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1120 m
->p
->SleepCookie
, ready
? "ready for sleep" : "giving up", now
, m
->SleepLimit
- now
);
1122 m
->SleepLimit
= 0; // Don't clear m->SleepLimit until after we've logged it above
1123 m
->TimeSlept
= mDNSPlatformUTC();
1125 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1126 if (m
->p
->IOPMConnection
) IOPMConnectionAcknowledgeEventWithOptions(m
->p
->IOPMConnection
, m
->p
->SleepCookie
, opts
);
1129 if (result
== kIOReturnSuccess
) IOAllowPowerChange (m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1130 else IOCancelPowerChange(m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1132 if (opts
) CFRelease(opts
);
1136 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1138 mDNSexport
void TriggerEventCompletion()
1140 debugf("TriggerEventCompletion: Merge data");
1141 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
1144 mDNSlocal
void PrepareForIdle(void *m_param
)
1147 int64_t time_offset
;
1148 dispatch_time_t dtime
;
1150 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1152 // This is the main work loop:
1153 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1154 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1155 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1157 debugf("PrepareForIdle: called");
1158 // Run mDNS_Execute to find out the time we next need to wake up
1159 mDNSs32 start
= mDNSPlatformRawTime();
1160 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1161 mDNSs32 end
= mDNSPlatformRawTime();
1162 if (end
- start
>= WatchDogReportingThreshold
)
1163 LogInfo("CustomSourceHandler:WARNING: Idle task took %dms to complete", end
- start
);
1165 mDNSs32 now
= mDNS_TimeNow(m
);
1167 if (m
->ShutdownTime
)
1169 if (mDNSStorage
.ResourceRecords
)
1171 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, mDNSStorage
.ResourceRecords
));
1172 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1174 if (mDNS_ExitNow(m
, now
))
1176 LogInfo("IdleLoop: mDNS_FinalExit");
1177 mDNS_FinalExit(&mDNSStorage
);
1178 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1181 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1182 nextTimerEvent
= m
->ShutdownTime
;
1186 if (!AllowSleepNow(now
))
1187 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1188 nextTimerEvent
= m
->SleepLimit
;
1190 // Convert absolute wakeup time to a relative time from now
1191 mDNSs32 ticks
= nextTimerEvent
- now
;
1192 if (ticks
< 1) ticks
= 1;
1194 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1200 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1203 time_offset
= ((mDNSu32
)ticks
/ mDNSPlatformOneSecond
) * 1000000000 + (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1204 dtime
= dispatch_time(DISPATCH_TIME_NOW
, time_offset
);
1205 dispatch_source_set_timer(PlatformStorage
.timer
, dtime
, 1000ull*1000000000, 0);
1206 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks
);
1210 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1212 mDNSlocal
void KQWokenFlushBytes(int fd
, __unused
short filter
, __unused
void *context
, __unused mDNSBool encounteredEOF
)
1214 // Read all of the bytes so we won't wake again.
1216 while (recv(fd
, buffer
, sizeof(buffer
), MSG_DONTWAIT
) > 0) continue;
1219 mDNSlocal
void SetLowWater(const KQSocketSet
*const k
, const int r
)
1221 if (k
->sktv4
>=0 && setsockopt(k
->sktv4
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1222 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k
->sktv4
, r
, errno
, strerror(errno
));
1223 if (k
->sktv6
>=0 && setsockopt(k
->sktv6
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1224 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k
->sktv6
, r
, errno
, strerror(errno
));
1227 mDNSlocal
void * KQueueLoop(void *m_param
)
1232 #if USE_SELECT_WITH_KQUEUEFD
1235 const int multiplier
= 1000000 / mDNSPlatformOneSecond
;
1237 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1240 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1241 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32
)mDNSStorage
.timenow_last
, mDNSStorage
.timenow_last
);
1243 // This is the main work loop:
1244 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1245 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1246 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1247 // (4) On wakeup we first process *all* events
1248 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
1251 #define kEventsToReadAtOnce 1
1252 struct kevent new_events
[kEventsToReadAtOnce
];
1254 // Run mDNS_Execute to find out the time we next need to wake up
1255 mDNSs32 start
= mDNSPlatformRawTime();
1256 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1257 mDNSs32 end
= mDNSPlatformRawTime();
1258 if (end
- start
>= WatchDogReportingThreshold
)
1259 LogInfo("WARNING: Idle task took %dms to complete", end
- start
);
1261 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
1265 mDNSs32 now
= mDNS_TimeNow(m
);
1267 if (m
->ShutdownTime
)
1269 if (mDNSStorage
.ResourceRecords
)
1272 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
1274 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, rr
));
1275 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1278 if (mDNS_ExitNow(m
, now
))
1280 LogInfo("mDNS_FinalExit");
1281 mDNS_FinalExit(&mDNSStorage
);
1282 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1285 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1286 nextTimerEvent
= m
->ShutdownTime
;
1290 if (!AllowSleepNow(now
))
1291 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1292 nextTimerEvent
= m
->SleepLimit
;
1294 // Convert absolute wakeup time to a relative time from now
1295 mDNSs32 ticks
= nextTimerEvent
- now
;
1296 if (ticks
< 1) ticks
= 1;
1298 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1304 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1307 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents
, ticks
);
1310 // Release the lock, and sleep until:
1311 // 1. Something interesting happens like a packet arriving, or
1312 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
1313 // 3. The timeout expires
1314 pthread_mutex_unlock(&PlatformStorage
.BigMutex
);
1316 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1317 if (m
->p
->num_mcasts
)
1319 SetLowWater(&m
->p
->permanentsockets
, 0x10000);
1320 if (ticks
> mDNSPlatformOneSecond
/ 8) ticks
= mDNSPlatformOneSecond
/ 8;
1323 #if USE_SELECT_WITH_KQUEUEFD
1324 struct timeval timeout
;
1325 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1326 timeout
.tv_usec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1327 FD_SET(KQueueFD
, &readfds
);
1328 if (select(KQueueFD
+1, &readfds
, NULL
, NULL
, &timeout
) < 0)
1329 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1331 struct timespec timeout
;
1332 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1333 timeout
.tv_nsec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1334 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
1335 // and have it work similarly to the way it does with nevents non-zero --
1336 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
1337 // In fact, what happens if you do this is that it just returns immediately. So, we have
1338 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
1339 if (kevent(KQueueFD
, NULL
, 0, new_events
, 1, &timeout
) < 0)
1340 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1343 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1344 // We have to ignore the event we may have been told about above, because that
1345 // was done without holding the lock, and between the time we woke up and the
1346 // time we reclaimed the lock the other thread could have done something that
1347 // makes the event no longer valid. Now we have the lock, we call kevent again
1348 // and this time we can safely process the events it tells us about.
1350 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
1351 if (m
->p
->num_mcasts
)
1353 SetLowWater(&m
->p
->permanentsockets
, 1);
1354 m
->p
->num_mcasts
= 0;
1357 static const struct timespec zero_timeout
= { 0, 0 };
1359 while ((events_found
= kevent(KQueueFD
, NULL
, 0, new_events
, kEventsToReadAtOnce
, &zero_timeout
)) != 0)
1361 if (events_found
> kEventsToReadAtOnce
|| (events_found
< 0 && errno
!= EINTR
))
1363 const int kevent_errno
= errno
;
1364 // Not sure what to do here, our kqueue has failed us - this isn't ideal
1365 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", kevent_errno
, strerror(kevent_errno
));
1369 numevents
+= events_found
;
1372 for (i
= 0; i
< events_found
; i
++)
1374 const KQueueEntry
*const kqentry
= new_events
[i
].udata
;
1375 mDNSs32 stime
= mDNSPlatformRawTime();
1376 const char *const KQtask
= kqentry
->KQtask
; // Grab a copy in case KQcallback deletes the task
1377 kqentry
->KQcallback(new_events
[i
].ident
, new_events
[i
].filter
, kqentry
->KQcontext
, (new_events
[i
].flags
& EV_EOF
) != 0);
1378 mDNSs32 etime
= mDNSPlatformRawTime();
1379 if (etime
- stime
>= WatchDogReportingThreshold
)
1380 LogInfo("WARNING: %s took %dms to complete", KQtask
, etime
- stime
);
1388 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1390 mDNSlocal
size_t LaunchdCheckin(void)
1392 // Ask launchd for our socket
1393 int result
= launch_activate_socket("Listeners", &launchd_fds
, &launchd_fds_count
);
1394 if (result
!= 0) { LogMsg("launch_activate_socket() failed error %d (%s)", result
, strerror(result
)); }
1395 return launchd_fds_count
;
1399 extern int sandbox_init(const char *profile
, uint64_t flags
, char **errorbuf
) __attribute__((weak_import
));
1401 #if APPLE_OSX_mDNSResponder
1402 mDNSlocal mDNSBool
PreferencesGetValueBool(CFStringRef key
, mDNSBool defaultValue
)
1404 CFBooleanRef boolean
;
1405 mDNSBool result
= defaultValue
;
1407 boolean
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1410 if (CFGetTypeID(boolean
) == CFBooleanGetTypeID())
1411 result
= CFBooleanGetValue(boolean
) ? mDNStrue
: mDNSfalse
;
1418 mDNSlocal
int PreferencesGetValueInt(CFStringRef key
, int defaultValue
)
1422 int result
= defaultValue
;
1424 number
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1427 if ((CFGetTypeID(number
) == CFNumberGetTypeID()) && CFNumberGetValue(number
, kCFNumberIntType
, &numberValue
))
1428 result
= numberValue
;
1436 mDNSlocal
void SandboxProcess(void)
1438 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1440 LogMsg("Note: Compiled without Apple Sandbox support");
1441 #else // MDNS_NO_SANDBOX
1443 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1447 uint64_t sandbox_flags
= SANDBOX_NAMED
;
1449 (void)confstr(_CS_DARWIN_USER_CACHE_DIR
, NULL
, 0);
1451 int sandbox_err
= sandbox_init("mDNSResponder", sandbox_flags
, &sandbox_msg
);
1454 LogMsg("WARNING: sandbox_init error %s", sandbox_msg
);
1455 // If we have errors in the sandbox during development, to prevent
1456 // exiting, uncomment the following line.
1457 //sandbox_free_error(sandbox_msg);
1459 errx(EX_OSERR
, "sandbox_init() failed: %s", sandbox_msg
);
1461 else LogInfo("Now running under Apple Sandbox restrictions");
1463 #endif // MDNS_NO_SANDBOX
1466 #if APPLE_OSX_mDNSResponder
1467 mDNSlocal
void init_logging(void)
1469 log_general
= os_log_create("com.apple.mDNSResponder", "AllINFO");
1473 // OS_LOG_DEFAULT is the default logging object, if you are not creating a custom subsystem/category
1474 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in mDNSResponder");
1480 // Run the unit test main
1483 mDNSexport
int main(int argc
, char **argv
)
1486 kern_return_t status
;
1489 bool useDebugSocket
= mDNSfalse
;
1490 bool useSandbox
= mDNStrue
;
1493 #if APPLE_OSX_mDNSResponder
1497 mDNSMacOSXSystemBuildNumber(NULL
);
1498 LogMsg("%s starting %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
1501 LogMsg("CacheRecord %5d", sizeof(CacheRecord
));
1502 LogMsg("CacheGroup %5d", sizeof(CacheGroup
));
1503 LogMsg("ResourceRecord %5d", sizeof(ResourceRecord
));
1504 LogMsg("RData_small %5d", sizeof(RData_small
));
1506 LogMsg("sizeof(CacheEntity) %5d", sizeof(CacheEntity
));
1507 LogMsg("RR_CACHE_SIZE %5d", RR_CACHE_SIZE
);
1508 LogMsg("block bytes used %5d", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1509 LogMsg("block bytes wasted %5d", 32*1024 - sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1514 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1518 for (i
=1; i
<argc
; i
++)
1520 if (!strcasecmp(argv
[i
], "-d" )) mDNS_DebugMode
= mDNStrue
;
1521 if (!strcasecmp(argv
[i
], "-NoMulticastAdvertisements")) NoMulticastAdvertisements
= mDNStrue
;
1522 if (!strcasecmp(argv
[i
], "-DisableSleepProxyClient" )) DisableSleepProxyClient
= mDNStrue
;
1523 if (!strcasecmp(argv
[i
], "-DebugLogging" )) mDNS_LoggingEnabled
= mDNStrue
;
1524 if (!strcasecmp(argv
[i
], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled
= mDNStrue
;
1525 if (!strcasecmp(argv
[i
], "-OfferSleepProxyService" ))
1526 OfferSleepProxyService
= (i
+1 < argc
&& mDNSIsDigit(argv
[i
+1][0]) && mDNSIsDigit(argv
[i
+1][1]) && argv
[i
+1][2]==0) ? atoi(argv
[++i
]) : 100;
1527 if (!strcasecmp(argv
[i
], "-UseInternalSleepProxy" ))
1528 UseInternalSleepProxy
= (i
+1<argc
&& mDNSIsDigit(argv
[i
+1][0]) && argv
[i
+1][1]==0) ? atoi(argv
[++i
]) : 1;
1529 if (!strcasecmp(argv
[i
], "-StrictUnicastOrdering" )) StrictUnicastOrdering
= mDNStrue
;
1530 if (!strcasecmp(argv
[i
], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains
= mDNStrue
;
1532 if (!strcasecmp(argv
[i
], "-UseDebugSocket")) useDebugSocket
= mDNStrue
;
1533 if (!strcasecmp(argv
[i
], "-NoSandbox")) useSandbox
= mDNSfalse
;
1538 #if APPLE_OSX_mDNSResponder
1539 /* Reads the external user's program arguments for mDNSResponder starting 10.11.x(El Capitan) on OSX. The options for external user are:
1540 DebugLogging, UnicastPacketLogging, NoMulticastAdvertisements, StrictUnicastOrdering and AlwaysAppendSearchDomains
1542 To turn ON the particular option, here is what the user should do (as an example of setting two options)
1543 1] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool YES
1544 2] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
1547 To turn OFF all options, here is what the user should do
1548 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1551 To view the current options set, here is what the user should do
1552 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1554 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
1558 // Currently on Fuji/Whitetail releases we are keeping the logging always enabled.
1559 // Hence mDNS_LoggingEnabled and mDNS_PacketLoggingEnabled is set to true below by default.
1561 mDNS_LoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_DebugLogging
, mDNS_LoggingEnabled
);
1562 mDNS_PacketLoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging
, mDNS_PacketLoggingEnabled
);
1565 mDNS_LoggingEnabled
= mDNStrue
;
1566 mDNS_PacketLoggingEnabled
= mDNStrue
;
1568 NoMulticastAdvertisements
= PreferencesGetValueBool(kPreferencesKey_NoMulticastAdvertisements
, NoMulticastAdvertisements
);
1569 StrictUnicastOrdering
= PreferencesGetValueBool(kPreferencesKey_StrictUnicastOrdering
, StrictUnicastOrdering
);
1570 AlwaysAppendSearchDomains
= PreferencesGetValueBool(kPreferencesKey_AlwaysAppendSearchDomains
, AlwaysAppendSearchDomains
);
1571 OfferSleepProxyService
= PreferencesGetValueInt(kPreferencesKey_OfferSleepProxyService
, OfferSleepProxyService
);
1572 UseInternalSleepProxy
= PreferencesGetValueInt(kPreferencesKey_UseInternalSleepProxy
, UseInternalSleepProxy
);
1574 #if ENABLE_BLE_TRIGGERED_BONJOUR
1575 EnableBLEBasedDiscovery
= PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery
, EnableBLEBasedDiscovery
);
1576 DefaultToBLETriggered
= PreferencesGetValueBool(kPreferencesKey_DefaultToBLETriggered
, DefaultToBLETriggered
);
1577 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
1579 #if TARGET_OS_IPHONE
1580 PreallocateCacheMemory
= PreferencesGetValueBool(kPreferencesKey_PreallocateCacheMemory
, PreallocateCacheMemory
);
1584 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
1585 if (NoMulticastAdvertisements
)
1586 LogMsg("-NoMulticastAdvertisements is set: Administratively prohibiting multicast advertisements");
1587 if (AlwaysAppendSearchDomains
)
1588 LogMsg("-AlwaysAppendSearchDomains is set");
1589 if (StrictUnicastOrdering
)
1590 LogMsg("-StrictUnicastOrdering is set");
1592 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1594 signal(SIGHUP
, HandleSIG
); // (Debugging) Purge the cache to check for cache handling bugs
1595 signal(SIGINT
, HandleSIG
); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
1596 signal(SIGPIPE
, SIG_IGN
); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
1597 signal(SIGTERM
, HandleSIG
); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
1598 signal(SIGINFO
, HandleSIG
); // (Debugging) Write state snapshot to syslog
1599 signal(SIGUSR1
, HandleSIG
); // (Debugging) Enable Logging
1600 signal(SIGUSR2
, HandleSIG
); // (Debugging) Enable Packet Logging
1601 signal(SIGPROF
, HandleSIG
); // (Debugging) Toggle Multicast Logging
1602 signal(SIGTSTP
, HandleSIG
); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
1604 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1606 mDNSStorage
.p
= &PlatformStorage
; // Make sure mDNSStorage.p is set up, because validatelists uses it
1607 // Need to Start XPC Server Before LaunchdCheckin() (Reason: rdar11023750)
1610 if (!useDebugSocket
) {
1611 if (LaunchdCheckin() == 0)
1612 useDebugSocket
= mDNStrue
;
1615 SetDebugBoundPath();
1620 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1622 // Create the kqueue, mutex and thread to support KQSockets
1623 KQueueFD
= kqueue();
1626 const int kqueue_errno
= errno
;
1627 LogMsg("kqueue() failed errno %d (%s)", kqueue_errno
, strerror(kqueue_errno
));
1628 status
= kqueue_errno
;
1632 i
= pthread_mutex_init(&PlatformStorage
.BigMutex
, NULL
);
1633 if (i
!= 0) { LogMsg("pthread_mutex_init() failed error %d (%s)", i
, strerror(i
)); status
= i
; goto exit
; }
1635 int fdpair
[2] = {0, 0};
1636 i
= socketpair(AF_UNIX
, SOCK_STREAM
, 0, fdpair
);
1639 const int socketpair_errno
= errno
;
1640 LogMsg("socketpair() failed errno %d (%s)", socketpair_errno
, strerror(socketpair_errno
));
1641 status
= socketpair_errno
;
1645 // Socket pair returned us two identical sockets connected to each other
1646 // We will use the first socket to send the second socket. The second socket
1647 // will be added to the kqueue so it will wake when data is sent.
1648 static const KQueueEntry wakeKQEntry
= { KQWokenFlushBytes
, NULL
, "kqueue wakeup after CFRunLoop event" };
1650 PlatformStorage
.WakeKQueueLoopFD
= fdpair
[0];
1651 KQueueSet(fdpair
[1], EV_ADD
, EVFILT_READ
, &wakeKQEntry
);
1653 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1661 status
= MetricsInit();
1662 if (status
) { LogMsg("Daemon start: MetricsInit failed (%d)", status
); }
1665 status
= mDNSDaemonInitialize();
1666 if (status
) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit
; }
1668 status
= udsserver_init(launchd_fds
, launchd_fds_count
);
1669 if (status
) { LogMsg("Daemon start: udsserver_init failed"); goto exit
; }
1671 mDNSMacOSXNetworkChanged();
1674 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1675 LogInfo("Daemon Start: Using LibDispatch");
1676 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
1678 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1679 // Start the kqueue thread
1680 pthread_t KQueueThread
;
1681 i
= pthread_create(&KQueueThread
, NULL
, KQueueLoop
, &mDNSStorage
);
1682 if (i
!= 0) { LogMsg("pthread_create() failed error %d (%s)", i
, strerror(i
)); status
= i
; goto exit
; }
1686 LogMsg("ERROR: CFRunLoopRun Exiting.");
1687 mDNS_Close(&mDNSStorage
);
1689 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1691 LogMsg("%s exiting", mDNSResponderVersionString
);
1698 // uds_daemon.c support routines /////////////////////////////////////////////
1700 mDNSlocal
void kqUDSEventCallback(int fd
, short filter
, void *context
, __unused mDNSBool encounteredEOF
)
1702 const KQSocketEventSource
*const source
= context
;
1703 source
->callback(fd
, filter
, source
->context
);
1706 // Arrange things so that when data appears on fd, callback is called with context
1707 mDNSexport mStatus
udsSupportAddFDToEventLoop(int fd
, udsEventCallback callback
, void *context
, void **platform_data
)
1709 KQSocketEventSource
**p
= &gEventSources
;
1710 (void) platform_data
;
1711 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1712 if (*p
) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd
); return mStatus_AlreadyRegistered
; }
1714 KQSocketEventSource
*newSource
= (KQSocketEventSource
*) mallocL("KQSocketEventSource", sizeof *newSource
);
1715 if (!newSource
) return mStatus_NoMemoryErr
;
1717 newSource
->next
= mDNSNULL
;
1719 newSource
->callback
= callback
;
1720 newSource
->context
= context
;
1721 newSource
->kqs
.KQcallback
= kqUDSEventCallback
;
1722 newSource
->kqs
.KQcontext
= newSource
;
1723 newSource
->kqs
.KQtask
= "UDS client";
1724 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1725 newSource
->kqs
.readSource
= mDNSNULL
;
1726 newSource
->kqs
.writeSource
= mDNSNULL
;
1727 newSource
->kqs
.fdClosed
= mDNSfalse
;
1728 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1730 if (KQueueSet(fd
, EV_ADD
, EVFILT_READ
, &newSource
->kqs
) == 0)
1733 return mStatus_NoError
;
1736 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd
, errno
, strerror(errno
));
1737 freeL("KQSocketEventSource", newSource
);
1738 return mStatus_BadParamErr
;
1741 int udsSupportReadFD(dnssd_sock_t fd
, char *buf
, int len
, int flags
, void *platform_data
)
1743 (void) platform_data
;
1744 return recv(fd
, buf
, len
, flags
);
1747 mDNSexport mStatus
udsSupportRemoveFDFromEventLoop(int fd
, void *platform_data
) // Note: This also CLOSES the file descriptor
1749 KQSocketEventSource
**p
= &gEventSources
;
1750 (void) platform_data
;
1751 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1754 KQSocketEventSource
*s
= *p
;
1756 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
1757 // causes the kernel to automatically remove any associated kevents
1758 mDNSPlatformCloseFD(&s
->kqs
, s
->fd
);
1759 freeL("KQSocketEventSource", s
);
1760 return mStatus_NoError
;
1762 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd
);
1763 return mStatus_NoSuchNameErr
;
1767 #include "../unittests/daemon_ut.c"
1770 #if _BUILDING_XCODE_PROJECT_
1771 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
1772 const char *__crashreporter_info__
= mDNSResponderVersionString
;
1773 asm (".desc ___crashreporter_info__, 0x10");
1776 // For convenience when using the "strings" command, this is the last thing in the file
1777 // The "@(#) " pattern is a special prefix the "what" command looks for
1778 mDNSexport
const char mDNSResponderVersionString_SCCS
[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion
) " (" __DATE__
" " __TIME__
")";