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>
38 #include "DNSCommon.h"
39 #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
41 #include "uds_daemon.h" // Interface to the server side implementation of dns_sd.h
42 #include "xpc_services.h" // Interface to XPC services
45 #if TARGET_OS_EMBEDDED
49 #if APPLE_OSX_mDNSResponder
50 static os_log_t log_general
= NULL
;
54 // Used on OSX(10.11.x onwards) for manipulating mDNSResponder program arguments
55 #if APPLE_OSX_mDNSResponder
56 // plist file to read the user's preferences
57 #define kProgramArguments CFSTR("com.apple.mDNSResponder")
58 // possible arguments for external customers
59 #define kPreferencesKey_DebugLogging CFSTR("DebugLogging")
60 #define kPreferencesKey_UnicastPacketLogging CFSTR("UnicastPacketLogging")
61 #define kPreferencesKey_AlwaysAppendSearchDomains CFSTR("AlwaysAppendSearchDomains")
62 #define kPreferencesKey_NoMulticastAdvertisements CFSTR("NoMulticastAdvertisements")
63 #define kPreferencesKey_StrictUnicastOrdering CFSTR("StrictUnicastOrdering")
64 #define kPreferencesKey_OfferSleepProxyService CFSTR("OfferSleepProxyService")
65 #define kPreferencesKey_UseInternalSleepProxy CFSTR("UseInternalSleepProxy")
66 #define kPreferencesKey_EnableBLEBasedDiscovery CFSTR("EnableBLEBasedDiscovery")
69 //*************************************************************************************************************
70 #if COMPILER_LIKES_PRAGMA_MARK
71 #pragma mark - Globals
74 static mDNS_PlatformSupport PlatformStorage
;
76 // Start off with a default cache of 32K (141 records of 232 bytes each)
77 // Each time we grow the cache we add another 141 records
78 // 141 * 164 = 32712 bytes.
79 // This fits in eight 4kB pages, with 56 bytes spare for memory block headers and similar overhead
80 #define RR_CACHE_SIZE ((32*1024) / sizeof(CacheRecord))
81 static CacheEntity rrcachestorage
[RR_CACHE_SIZE
];
82 struct CompileTimeAssertionChecks_RR_CACHE_SIZE
{ char a
[(RR_CACHE_SIZE
>= 141) ? 1 : -1]; };
85 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
86 mDNSlocal
void PrepareForIdle(void *m_param
);
87 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
88 static mach_port_t signal_port
= MACH_PORT_NULL
;
89 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
91 static dnssd_sock_t
*launchd_fds
= mDNSNULL
;
92 static size_t launchd_fds_count
= 0;
94 static mDNSBool NoMulticastAdvertisements
= mDNSfalse
; // By default, advertise addresses (& other records) via multicast
96 extern mDNSBool StrictUnicastOrdering
;
97 extern mDNSBool AlwaysAppendSearchDomains
;
98 extern mDNSBool EnableBLEBasedDiscovery
;
100 // We keep a list of client-supplied event sources in KQSocketEventSource records
101 typedef struct KQSocketEventSource
103 struct KQSocketEventSource
*next
;
106 } KQSocketEventSource
;
108 static KQSocketEventSource
*gEventSources
;
110 //*************************************************************************************************************
111 #if COMPILER_LIKES_PRAGMA_MARK
113 #pragma mark - General Utility Functions
116 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
118 char _malloc_options
[] = "AXZ";
120 mDNSlocal
void validatelists(mDNS
*const m
)
122 #if BONJOUR_ON_DEMAND
123 mDNSu32 NumAllInterfaceRecords
= 0;
124 mDNSu32 NumAllInterfaceQuestions
= 0;
125 #endif // BONJOUR_ON_DEMAND
128 KQSocketEventSource
*k
;
129 for (k
= gEventSources
; k
; k
=k
->next
)
130 if (k
->next
== (KQSocketEventSource
*)~0 || k
->fd
< 0)
131 LogMemCorruption("gEventSources: %p is garbage (%d)", k
, k
->fd
);
133 // Check Unix Domain Socket client lists (uds_daemon.c)
136 // Check core mDNS lists
138 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
140 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
141 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
142 if (rr
->resrec
.name
!= &rr
->namestorage
)
143 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
144 rr
, rr
->resrec
.name
->c
, rr
->namestorage
.c
, rr
->namestorage
.c
);
145 #if BONJOUR_ON_DEMAND
146 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
147 #endif // BONJOUR_ON_DEMAND
150 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
)
152 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
153 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
154 #if BONJOUR_ON_DEMAND
155 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
156 #endif // BONJOUR_ON_DEMAND
159 rr
= m
->NewLocalRecords
;
161 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
162 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
164 rr
= m
->CurrentRecord
;
166 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
167 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
170 for (q
= m
->Questions
; q
; q
=q
->next
)
172 if (q
->next
== (DNSQuestion
*)~0 || q
->ThisQInterval
== (mDNSs32
) ~0)
173 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q
, q
->ThisQInterval
, q
->next
);
174 if (q
->DuplicateOf
&& q
->LocalSocket
)
175 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
176 #if BONJOUR_ON_DEMAND
177 if (!LocalOnlyOrP2PInterface(q
->InterfaceID
) && mDNSOpaque16IsZero(q
->TargetQID
))
178 NumAllInterfaceQuestions
++;
179 #endif // BONJOUR_ON_DEMAND
185 FORALL_CACHERECORDS(slot
, cg
, cr
)
187 if (cr
->resrec
.RecordType
== 0 || cr
->resrec
.RecordType
== 0xFF)
188 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot
, cr
, cr
->resrec
.RecordType
);
189 if (cr
->CRActiveQuestion
)
191 for (q
= m
->Questions
; q
; q
=q
->next
) if (q
== cr
->CRActiveQuestion
) break;
192 if (!q
) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot
, cr
->CRActiveQuestion
, CRDisplayString(m
, cr
));
196 // Check core uDNS lists
197 udns_validatelists(m
);
199 // Check platform-layer lists
200 NetworkInterfaceInfoOSX
*i
;
201 for (i
= m
->p
->InterfaceList
; i
; i
= i
->next
)
202 if (i
->next
== (NetworkInterfaceInfoOSX
*)~0 || !i
->m
|| i
->m
== (mDNS
*)~0)
203 LogMemCorruption("m->p->InterfaceList: %p is garbage (%p)", i
, i
->ifinfo
.ifname
);
206 for (t
= m
->TunnelClients
; t
; t
=t
->next
)
207 if (t
->next
== (ClientTunnel
*)~0 || t
->dstname
.c
[0] > 63)
208 LogMemCorruption("m->TunnelClients: %p is garbage (%d)", t
, t
->dstname
.c
[0]);
210 #if BONJOUR_ON_DEMAND
211 if (m
->NumAllInterfaceRecords
!= NumAllInterfaceRecords
)
212 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m
->NumAllInterfaceRecords
, NumAllInterfaceRecords
);
214 if (m
->NumAllInterfaceQuestions
!= NumAllInterfaceQuestions
)
215 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m
->NumAllInterfaceQuestions
, NumAllInterfaceQuestions
);
216 #endif // BONJOUR_ON_DEMAND
219 mDNSexport
void *mallocL(char *msg
, unsigned int size
)
221 // Allocate space for two words of sanity checking data before the requested block
222 mDNSu32
*mem
= malloc(sizeof(mDNSu32
) * 2 + size
);
224 { LogMsg("malloc( %s : %d ) failed", msg
, size
); return(NULL
); }
227 if (size
> 32768) LogMsg("malloc( %s : %lu ) @ %p suspiciously large", msg
, size
, &mem
[2]);
228 else if (MACOSX_MDNS_MALLOC_DEBUGGING
>= 2) LogMsg("malloc( %s : %lu ) @ %p", msg
, size
, &mem
[2]);
231 //mDNSPlatformMemZero(&mem[2], size);
232 memset(&mem
[2], 0xFF, size
);
233 validatelists(&mDNSStorage
);
238 mDNSexport
void freeL(char *msg
, void *x
)
241 LogMsg("free( %s @ NULL )!", msg
);
244 mDNSu32
*mem
= ((mDNSu32
*)x
) - 2;
245 if (mem
[0] == 0xDEADDEAD) { LogMemCorruption("free( %s : %lu @ %p ) !!!! ALREADY DISPOSED !!!!", msg
, mem
[1], &mem
[2]); return; }
246 if (mem
[0] != 0xDEAD1234) { LogMemCorruption("free( %s : %lu @ %p ) !!!! NEVER ALLOCATED !!!!", msg
, mem
[1], &mem
[2]); return; }
247 if (mem
[1] > 32768) LogMsg("free( %s : %lu @ %p) suspiciously large", msg
, mem
[1], &mem
[2]);
248 else if (MACOSX_MDNS_MALLOC_DEBUGGING
>= 2) LogMsg("free( %s : %ld @ %p)", msg
, mem
[1], &mem
[2]);
250 memset(mem
+2, 0xFF, mem
[1]);
251 validatelists(&mDNSStorage
);
258 //*************************************************************************************************************
261 mDNSexport
void RecordUpdatedNiceLabel(mDNS
*const m
, mDNSs32 delay
)
263 m
->p
->NotifyUser
= NonZeroTime(m
->timenow
+ delay
);
266 mDNSlocal
void mDNSPreferencesSetNames(mDNS
*const m
, int key
, domainlabel
*old
, domainlabel
*new)
268 domainlabel
*prevold
, *prevnew
;
271 case kmDNSComputerName
:
272 case kmDNSLocalHostName
:
273 if (key
== kmDNSComputerName
)
275 prevold
= &m
->p
->prevoldnicelabel
;
276 prevnew
= &m
->p
->prevnewnicelabel
;
280 prevold
= &m
->p
->prevoldhostlabel
;
281 prevnew
= &m
->p
->prevnewhostlabel
;
283 // There are a few cases where we need to invoke the helper.
285 // 1. If the "old" label and "new" label are not same, it means there is a conflict. We need
286 // to invoke the helper so that it pops up a dialogue to inform the user about the
289 // 2. If the "old" label and "new" label are same, it means the user has set the host/nice label
290 // through the preferences pane. We may have to inform the helper as it may have popped up
291 // a dialogue previously (due to a conflict) and it needs to suppress it now. We can avoid invoking
292 // the helper in this case if the previous values (old and new) that we told helper last time
293 // are same. If the previous old and new values are same, helper does not care.
295 // Note: "new" can be NULL when we have repeated conflicts and we are asking helper to give up. "old"
296 // is not called with NULL today, but this makes it future proof.
297 if (!old
|| !new || !SameDomainLabelCS(old
->c
, new->c
) ||
298 !SameDomainLabelCS(old
->c
, prevold
->c
) ||
299 !SameDomainLabelCS(new->c
, prevnew
->c
))
301 // Work around bug radar:21397654
302 #ifndef __clang_analyzer__
312 mDNSPreferencesSetName(key
, old
, new);
316 LogInfo("mDNSPreferencesSetNames not invoking helper %s %#s, %s %#s, old %#s, new %#s",
317 (key
== kmDNSComputerName
? "prevoldnicelabel" : "prevoldhostlabel"), prevold
->c
,
318 (key
== kmDNSComputerName
? "prevnewnicelabel" : "prevnewhostlabel"), prevnew
->c
,
323 LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key
);
328 mDNSlocal
void mDNS_StatusCallback(mDNS
*const m
, mStatus result
)
331 if (result
== mStatus_NoError
)
333 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
334 LogInfo("Local Hostname changed from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
335 // One second pause in case we get a Computer Name update too -- don't want to alert the user twice
336 RecordUpdatedNiceLabel(m
, mDNSPlatformOneSecond
);
338 else if (result
== mStatus_NameConflict
)
340 LogInfo("Local Hostname conflict for \"%#s.local\"", m
->hostlabel
.c
);
341 if (!m
->p
->HostNameConflict
) m
->p
->HostNameConflict
= NonZeroTime(m
->timenow
);
342 else if (m
->timenow
- m
->p
->HostNameConflict
> 60 * mDNSPlatformOneSecond
)
344 // Tell the helper we've given up
345 mDNSPreferencesSetNames(m
, kmDNSLocalHostName
, &m
->p
->userhostlabel
, NULL
);
348 else if (result
== mStatus_GrowCache
)
350 // Allocate another chunk of cache storage
351 static unsigned int allocated
= 0;
353 if (allocated
>= 1000000) return; // For now we limit the cache to at most 1MB on iOS devices
355 allocated
+= sizeof(CacheEntity
) * RR_CACHE_SIZE
;
356 // LogMsg("GrowCache %d * %d = %d; total so far %6u", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE, allocated);
357 CacheEntity
*storage
= mallocL("mStatus_GrowCache", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
358 //LogInfo("GrowCache %d * %d = %d", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE);
359 if (storage
) mDNS_GrowCache(m
, storage
, RR_CACHE_SIZE
);
361 else if (result
== mStatus_ConfigChanged
)
363 // Tell the helper we've seen a change in the labels. It will dismiss the name conflict alert if needed.
364 mDNSPreferencesSetNames(m
, kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
365 mDNSPreferencesSetNames(m
, kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
367 // Then we call into the UDS daemon code, to let it do the same
368 udsserver_handle_configchange(m
);
373 //*************************************************************************************************************
374 #if COMPILER_LIKES_PRAGMA_MARK
376 #pragma mark - Startup, shutdown, and supporting code
379 mDNSlocal
void ExitCallback(int sig
)
382 LogMsg("%s stopping", mDNSResponderVersionString
);
384 if (udsserver_exit() < 0)
385 LogMsg("ExitCallback: udsserver_exit failed");
387 debugf("ExitCallback: mDNS_StartExit");
388 mDNS_StartExit(&mDNSStorage
);
391 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
393 // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
394 mDNSlocal
void HandleSIG(int sig
)
396 kern_return_t status
;
397 mach_msg_header_t header
;
399 // WARNING: can't call syslog or fprintf from signal handler
400 header
.msgh_bits
= MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND
, 0);
401 header
.msgh_remote_port
= signal_port
;
402 header
.msgh_local_port
= MACH_PORT_NULL
;
403 header
.msgh_size
= sizeof(header
);
404 header
.msgh_id
= sig
;
406 status
= mach_msg(&header
, MACH_SEND_MSG
| MACH_SEND_TIMEOUT
, header
.msgh_size
,
407 0, MACH_PORT_NULL
, 0, MACH_PORT_NULL
);
409 if (status
!= MACH_MSG_SUCCESS
)
411 if (status
== MACH_SEND_TIMED_OUT
) mach_msg_destroy(&header
);
412 if (sig
== SIGTERM
|| sig
== SIGINT
) exit(-1);
416 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
418 mDNSexport
void INFOCallback(void)
420 mDNSs32 utc
= mDNSPlatformUTC();
421 const mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
422 NetworkInterfaceInfoOSX
*i
;
426 LogMsg("---- BEGIN STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
428 udsserver_info(&mDNSStorage
);
430 LogMsgNoIdent("----- Platform Timers -----");
431 LogTimer("m->NextCacheCheck ", mDNSStorage
.NextCacheCheck
);
432 LogTimer("m->NetworkChanged ", mDNSStorage
.NetworkChanged
);
433 LogTimer("m->p->NotifyUser ", mDNSStorage
.p
->NotifyUser
);
434 LogTimer("m->p->HostNameConflict ", mDNSStorage
.p
->HostNameConflict
);
435 LogTimer("m->p->KeyChainTimer ", mDNSStorage
.p
->KeyChainTimer
);
437 xpcserver_info(&mDNSStorage
);
439 LogMsgNoIdent("----- KQSocketEventSources -----");
440 if (!gEventSources
) LogMsgNoIdent("<None>");
443 KQSocketEventSource
*k
;
444 for (k
= gEventSources
; k
; k
=k
->next
)
445 LogMsgNoIdent("%3d %s %s", k
->fd
, k
->kqs
.KQtask
, k
->fd
== mDNSStorage
.uds_listener_skt
? "Listener for incoming UDS clients" : " ");
448 LogMsgNoIdent("------ Network Interfaces ------");
449 if (!mDNSStorage
.p
->InterfaceList
) LogMsgNoIdent("<None>");
452 for (i
= mDNSStorage
.p
->InterfaceList
; i
; i
= i
->next
)
454 // Allow six characters for interface name, for names like "vmnet8"
456 LogMsgNoIdent("%p %2ld, Registered %p, %s %-6s(%lu) %.6a %.6a %#-14a dormant for %d seconds",
457 i
, i
->ifinfo
.InterfaceID
, i
->Registered
,
458 i
->sa_family
== AF_INET
? "v4" : i
->sa_family
== AF_INET6
? "v6" : "??", i
->ifinfo
.ifname
, i
->scope_id
, &i
->ifinfo
.MAC
, &i
->BSSID
,
459 &i
->ifinfo
.ip
, utc
- i
->LastSeen
);
462 const CacheRecord
*sps
[3];
463 FindSPSInCache(&mDNSStorage
, &i
->ifinfo
.NetWakeBrowse
, sps
);
464 LogMsgNoIdent("%p %2ld, Registered %p, %s %-6s(%lu) %.6a %.6a %s %s %-15.4a %s %s %s %s %#a",
465 i
, i
->ifinfo
.InterfaceID
, i
->Registered
,
466 i
->sa_family
== AF_INET
? "v4" : i
->sa_family
== AF_INET6
? "v6" : "??", i
->ifinfo
.ifname
, i
->scope_id
, &i
->ifinfo
.MAC
, &i
->BSSID
,
467 i
->ifinfo
.InterfaceActive
? "Active" : " ",
468 i
->ifinfo
.IPv4Available
? "v4" : " ",
469 i
->ifinfo
.IPv4Available
? (mDNSv4Addr
*)&i
->ifa_v4addr
: &zerov4Addr
,
470 i
->ifinfo
.IPv6Available
? "v6" : " ",
471 i
->ifinfo
.Advertise
? "A" : " ",
472 i
->ifinfo
.McastTxRx
? "M" : " ",
473 !(i
->ifinfo
.InterfaceActive
&& i
->ifinfo
.NetWake
) ? " " : !sps
[0] ? "p" : "P",
476 if (sps
[0]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[0]->resrec
.rdata
->u
.name
.c
), sps
[0]->resrec
.rdata
->u
.name
.c
);
477 if (sps
[1]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[1]->resrec
.rdata
->u
.name
.c
), sps
[1]->resrec
.rdata
->u
.name
.c
);
478 if (sps
[2]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[2]->resrec
.rdata
->u
.name
.c
), sps
[2]->resrec
.rdata
->u
.name
.c
);
483 LogMsgNoIdent("--------- DNS Servers(%d) ----------", NumUnicastDNSServers
);
484 if (!mDNSStorage
.DNSServers
) LogMsgNoIdent("<None>");
487 for (s
= mDNSStorage
.DNSServers
; s
; s
= s
->next
)
489 NetworkInterfaceInfoOSX
*ifx
= IfindexToInterfaceInfoOSX(&mDNSStorage
, s
->interface
);
490 LogMsgNoIdent("DNS Server %##s %s%s%#a:%d %d %s %d %d %s %s %s %s",
491 s
->domain
.c
, ifx
? ifx
->ifinfo
.ifname
: "", ifx
? " " : "", &s
->addr
, mDNSVal16(s
->port
),
492 s
->penaltyTime
? s
->penaltyTime
- mDNS_TimeNow(&mDNSStorage
) : 0, DNSScopeToString(s
->scoped
),
493 s
->timeout
, s
->resGroupID
,
494 s
->req_A
? "v4" : "!v4",
495 s
->req_AAAA
? "v6" : "!v6",
496 s
->cellIntf
? "cell" : "!cell",
497 s
->DNSSECAware
? "DNSSECAware" : "!DNSSECAware");
501 LogMsgNoIdent("v4answers %d", mDNSStorage
.p
->v4answers
);
502 LogMsgNoIdent("v6answers %d", mDNSStorage
.p
->v6answers
);
503 LogMsgNoIdent("Last DNS Trigger: %d ms ago", (now
- mDNSStorage
.p
->DNSTrigger
));
505 LogMsgNoIdent("--------- Mcast Resolvers ----------");
506 if (!mDNSStorage
.McastResolvers
) LogMsgNoIdent("<None>");
509 for (mr
= mDNSStorage
.McastResolvers
; mr
; mr
= mr
->next
)
510 LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr
->domain
.c
, mr
->timeout
);
513 LogMsgNoIdent("------------ Hostnames -------------");
514 if (!mDNSStorage
.Hostnames
) LogMsgNoIdent("<None>");
518 for (hi
= mDNSStorage
.Hostnames
; hi
; hi
= hi
->next
)
520 LogMsgNoIdent("%##s v4 %d %s", hi
->fqdn
.c
, hi
->arv4
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv4
));
521 LogMsgNoIdent("%##s v6 %d %s", hi
->fqdn
.c
, hi
->arv6
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv6
));
525 LogMsgNoIdent("--------------- FQDN ---------------");
526 if (!mDNSStorage
.FQDN
.c
[0]) LogMsgNoIdent("<None>");
529 LogMsgNoIdent("%##s", mDNSStorage
.FQDN
.c
);
532 #if TARGET_OS_EMBEDDED
535 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
536 LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
540 mDNSexport
void mDNSPlatformLogToFile(int log_level
, const char *buffer
)
543 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in init_logging()");
545 os_log_with_type(log_general
, log_level
, "%s", buffer
);
549 // Writes the state out to the dynamic store and also affects the ASL filter level
550 mDNSexport
void UpdateDebugState()
555 CFMutableDictionaryRef dict
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
558 LogMsg("UpdateDebugState: Could not create dict");
562 CFNumberRef numOne
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &one
);
565 LogMsg("UpdateDebugState: Could not create CFNumber one");
568 CFNumberRef numZero
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &zero
);
571 LogMsg("UpdateDebugState: Could not create CFNumber zero");
576 if (mDNS_LoggingEnabled
)
577 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numOne
);
579 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numZero
);
581 if (mDNS_PacketLoggingEnabled
)
582 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numOne
);
584 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numZero
);
586 if (mDNS_McastLoggingEnabled
)
587 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numOne
);
589 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numZero
);
591 if (mDNS_McastTracingEnabled
)
592 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numOne
);
594 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numZero
);
598 mDNSDynamicStoreSetConfig(kmDNSDebugState
, mDNSNULL
, dict
);
604 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
606 mDNSlocal
void SignalCallback(CFMachPortRef port
, void *msg
, CFIndex size
, void *info
)
608 (void)port
; // Unused
609 (void)size
; // Unused
610 (void)info
; // Unused
611 mach_msg_header_t
*msg_header
= (mach_msg_header_t
*)msg
;
612 mDNS
*const m
= &mDNSStorage
;
614 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
616 switch(msg_header
->msgh_id
)
622 LogMsg("SIGHUP: Purge cache");
624 FORALL_CACHERECORDS(slot
, cg
, rr
)
626 mDNS_PurgeCacheResourceRecord(m
, rr
);
628 // Restart unicast and multicast queries
629 mDNSCoreRestartQueries(m
);
633 case SIGTERM
: ExitCallback(msg_header
->msgh_id
); break;
634 case SIGINFO
: INFOCallback(); break;
636 #if APPLE_OSX_mDNSResponder
637 mDNS_LoggingEnabled
= 1;
638 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
640 mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
641 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
643 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
645 LogInfo("USR1 Logging Enabled");
648 #if APPLE_OSX_mDNSResponder
649 mDNS_PacketLoggingEnabled
= 1;
650 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
652 mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
653 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
655 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
656 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
659 case SIGPROF
: mDNS_McastLoggingEnabled
= mDNS_McastLoggingEnabled
? mDNSfalse
: mDNStrue
;
660 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled
? "Enabled" : "Disabled");
661 LogMcastStateInfo(m
, mDNSfalse
, mDNStrue
, mDNStrue
);
662 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
663 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
666 case SIGTSTP
: mDNS_LoggingEnabled
= mDNS_PacketLoggingEnabled
= mDNS_McastLoggingEnabled
= mDNS_McastTracingEnabled
= mDNSfalse
;
667 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
671 default: LogMsg("SignalCallback: Unknown signal %d", msg_header
->msgh_id
); break;
673 KQueueUnlock(m
, "Unix Signal");
676 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
677 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
681 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
682 rrcachestorage
, RR_CACHE_SIZE
,
683 !NoMulticastAdvertisements
,
684 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
688 LogMsg("Daemon start: mDNS_Init failed %d", err
);
692 CFMachPortRef i_port
= CFMachPortCreate(NULL
, SignalCallback
, NULL
, NULL
);
693 CFRunLoopSourceRef i_rls
= CFMachPortCreateRunLoopSource(NULL
, i_port
, 0);
694 signal_port
= CFMachPortGetPort(i_port
);
695 CFRunLoopAddSource(CFRunLoopGetMain(), i_rls
, kCFRunLoopDefaultMode
);
701 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
703 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
704 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
705 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
706 // of code from above. Alternatively we could remove the duplicated source code by having
707 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
709 mDNSlocal
void SignalDispatch(dispatch_source_t source
)
711 int sig
= (int)dispatch_source_get_handle(source
);
712 mDNS
*const m
= &mDNSStorage
;
720 LogMsg("SIGHUP: Purge cache");
722 FORALL_CACHERECORDS(slot
, cg
, rr
)
724 mDNS_PurgeCacheResourceRecord(m
, rr
);
726 // Restart unicast and multicast queries
727 mDNSCoreRestartQueries(m
);
731 case SIGTERM
: ExitCallback(sig
); break;
732 case SIGINFO
: INFOCallback(); break;
733 case SIGUSR1
: mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
734 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
735 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
738 case SIGUSR2
: mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
739 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
742 default: LogMsg("SignalCallback: Unknown signal %d", sig
); break;
744 KQueueUnlock(m
, "Unix Signal");
747 mDNSlocal
void mDNSSetupSignal(dispatch_queue_t queue
, int sig
)
749 signal(sig
, SIG_IGN
);
750 dispatch_source_t source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL
, sig
, 0, queue
);
754 dispatch_source_set_event_handler(source
, ^{SignalDispatch(source
);});
755 // Start processing signals
756 dispatch_resume(source
);
760 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig
);
764 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
767 dispatch_queue_t queue
= dispatch_get_main_queue();
769 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
770 rrcachestorage
, RR_CACHE_SIZE
,
771 !NoMulticastAdvertisements
,
772 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
776 LogMsg("Daemon start: mDNS_Init failed %d", err
);
780 mDNSSetupSignal(queue
, SIGHUP
);
781 mDNSSetupSignal(queue
, SIGINT
);
782 mDNSSetupSignal(queue
, SIGTERM
);
783 mDNSSetupSignal(queue
, SIGINFO
);
784 mDNSSetupSignal(queue
, SIGUSR1
);
785 mDNSSetupSignal(queue
, SIGUSR2
);
787 // Create a custom handler for doing the housekeeping work. This is either triggered
788 // by the timer or an event source
789 PlatformStorage
.custom
= dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD
, 0, 0, queue
);
790 if (PlatformStorage
.custom
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
791 dispatch_source_set_event_handler(PlatformStorage
.custom
, ^{PrepareForIdle(&mDNSStorage
);});
792 dispatch_resume(PlatformStorage
.custom
);
794 // Create a timer source to trigger housekeeping work. The houskeeping work itself
795 // is done in the custom handler that we set below.
797 PlatformStorage
.timer
= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER
, 0, 0, queue
);
798 if (PlatformStorage
.timer
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
800 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
801 // always reset the time to the new time computed. In effect, we ignore the interval
802 dispatch_source_set_timer(PlatformStorage
.timer
, DISPATCH_TIME_NOW
, 1000ull * 1000000000, 0);
803 dispatch_source_set_event_handler(PlatformStorage
.timer
, ^{
804 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
806 dispatch_resume(PlatformStorage
.timer
);
808 LogMsg("DaemonIntialize done successfully");
813 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
815 mDNSlocal mDNSs32
mDNSDaemonIdle(mDNS
*const m
)
817 mDNSs32 now
= mDNS_TimeNow(m
);
819 // 1. If we need to set domain secrets, do so before handling the network change
821 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
822 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
823 if (m
->p
->KeyChainTimer
&& now
- m
->p
->KeyChainTimer
>= 0)
825 m
->p
->KeyChainTimer
= 0;
831 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
833 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
834 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
835 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
836 // we then systematically lose our own looped-back packets.
837 if (m
->NetworkChanged
&& now
- m
->NetworkChanged
>= 0) mDNSMacOSXNetworkChanged(m
);
839 if (m
->p
->RequestReSleep
&& now
- m
->p
->RequestReSleep
>= 0)
841 m
->p
->RequestReSleep
= 0;
842 mDNSPowerRequest(0, 0);
845 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
846 mDNSs32 nextevent
= mDNS_Execute(m
);
848 if (m
->NetworkChanged
)
849 if (nextevent
- m
->NetworkChanged
> 0)
850 nextevent
= m
->NetworkChanged
;
852 if (m
->p
->KeyChainTimer
)
853 if (nextevent
- m
->p
->KeyChainTimer
> 0)
854 nextevent
= m
->p
->KeyChainTimer
;
856 if (m
->p
->RequestReSleep
)
857 if (nextevent
- m
->p
->RequestReSleep
> 0)
858 nextevent
= m
->p
->RequestReSleep
;
861 if (m
->p
->NotifyUser
)
863 if (m
->p
->NotifyUser
- now
< 0)
865 if (!SameDomainLabelCS(m
->p
->usernicelabel
.c
, m
->nicelabel
.c
))
867 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m
->p
->usernicelabel
.c
, m
->nicelabel
.c
);
868 mDNSPreferencesSetNames(m
, kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
869 m
->p
->usernicelabel
= m
->nicelabel
;
871 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
873 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
874 mDNSPreferencesSetNames(m
, kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
875 m
->p
->HostNameConflict
= 0; // Clear our indicator, now name change has been successful
876 m
->p
->userhostlabel
= m
->hostlabel
;
878 m
->p
->NotifyUser
= 0;
881 if (nextevent
- m
->p
->NotifyUser
> 0)
882 nextevent
= m
->p
->NotifyUser
;
888 // Right now we consider *ALL* of our DHCP leases
889 // It might make sense to be a bit more selective and only consider the leases on interfaces
890 // (a) that are capable and enabled for wake-on-LAN, and
891 // (b) where we have found (and successfully registered with) a Sleep Proxy
892 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
893 mDNSlocal mDNSu32
DHCPWakeTime(void)
895 mDNSu32 e
= 24 * 3600; // Maximum maintenance wake interval is 24 hours
896 const CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
897 if (!now
) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
902 const void *pattern
= SCDynamicStoreKeyCreateNetworkServiceEntity(NULL
, kSCDynamicStoreDomainState
, kSCCompAnyRegex
, kSCEntNetDHCP
);
905 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
908 CFArrayRef dhcpinfo
= CFArrayCreate(NULL
, (const void **)&pattern
, 1, &kCFTypeArrayCallBacks
);
912 SCDynamicStoreRef store
= SCDynamicStoreCreate(NULL
, CFSTR("DHCP-LEASES"), NULL
, NULL
);
915 CFDictionaryRef dict
= SCDynamicStoreCopyMultiple(store
, NULL
, dhcpinfo
);
918 ic
= CFDictionaryGetCount(dict
);
919 const void *vals
[ic
];
920 CFDictionaryGetKeysAndValues(dict
, NULL
, vals
);
922 for (j
= 0; j
< ic
; j
++)
924 const CFDictionaryRef dhcp
= (CFDictionaryRef
)vals
[j
];
927 const CFDateRef start
= DHCPInfoGetLeaseStartTime(dhcp
);
928 const CFDataRef lease
= DHCPInfoGetOptionData(dhcp
, 51); // Option 51 = IP Address Lease Time
929 if (!start
|| !lease
|| CFDataGetLength(lease
) < 4)
930 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
931 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
932 j
, start
, lease
, lease
? CFDataGetLength(lease
) : 0);
935 const UInt8
*d
= CFDataGetBytePtr(lease
);
936 if (!d
) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j
);
939 const mDNSu32 elapsed
= now
- CFDateGetAbsoluteTime(start
);
940 const mDNSu32 lifetime
= (mDNSs32
) ((mDNSs32
)d
[0] << 24 | (mDNSs32
)d
[1] << 16 | (mDNSs32
)d
[2] << 8 | d
[3]);
941 const mDNSu32 remaining
= lifetime
- elapsed
;
942 const mDNSu32 wake
= remaining
> 60 ? remaining
- remaining
/10 : 54; // Wake at 90% of the lease time
943 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed
, lifetime
, remaining
, wake
);
944 if (e
> wake
) e
= wake
;
959 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
960 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
961 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
962 // for a few seconds and then waking again is silly and annoying.
963 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
964 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
965 // allowing us an adequate safety margin to renew our lease before we lose it.
967 mDNSlocal mDNSBool
AllowSleepNow(mDNS
*const m
, mDNSs32 now
)
969 mDNSBool ready
= mDNSCoreReadyForSleep(m
, now
);
970 if (m
->SleepState
&& !ready
&& now
- m
->SleepLimit
< 0) return(mDNSfalse
);
973 int result
= kIOReturnSuccess
;
974 CFDictionaryRef opts
= NULL
;
976 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
977 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
979 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m
->SleepLimit
- now
);
982 if (!m
->SystemWakeOnLANEnabled
|| !mDNSCoreHaveAdvertisedMulticastServices(m
))
983 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
984 m
->SystemWakeOnLANEnabled
? "is" : "not",
985 mDNSCoreHaveAdvertisedMulticastServices(m
) ? "have" : "no");
988 mDNSs32 dhcp
= DHCPWakeTime();
989 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp
);
990 mDNSs32 interval
= mDNSCoreIntervalToNextWake(m
, now
) / mDNSPlatformOneSecond
;
991 if (interval
> dhcp
) interval
= dhcp
;
993 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
994 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
995 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
996 // someone to go to the machine in person to wake it up again, which would be unacceptable.
997 if (!ready
&& interval
> 3600) interval
= 3600;
999 //interval = 48; // For testing
1001 #if !TARGET_OS_EMBEDDED
1002 #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1003 if (m
->p
->IOPMConnection
) // If lightweight-wake capability is available, use that
1005 const CFDateRef WakeDate
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent() + interval
);
1006 if (!WakeDate
) LogMsg("ScheduleNextWake: CFDateCreate failed");
1009 const mDNSs32 reqs
= kIOPMSystemPowerStateCapabilityNetwork
;
1010 const CFNumberRef Requirements
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &reqs
);
1011 if (!Requirements
) LogMsg("ScheduleNextWake: CFNumberCreate failed");
1014 const void *OptionKeys
[2] = { kIOPMAckDHCPRenewWakeDate
, kIOPMAckSystemCapabilityRequirements
};
1015 const void *OptionVals
[2] = { WakeDate
, Requirements
};
1016 opts
= CFDictionaryCreate(NULL
, (void*)OptionKeys
, (void*)OptionVals
, 2, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1017 if (!opts
) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
1018 CFRelease(Requirements
);
1020 CFRelease(WakeDate
);
1022 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval
);
1024 else // else schedule the wakeup using the old API instead to
1025 #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1026 #endif // TARGET_OS_EMBEDDED
1028 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
1029 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
1030 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
1031 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
1035 result
= mDNSPowerRequest(1, interval
);
1037 if (result
== kIOReturnNotReady
)
1040 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval
);
1041 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
1042 // requested wake time is "too soon", but there's no API to find out what constitutes
1043 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
1044 // we just have to iterate with successively longer intervals until it doesn't fail.
1045 // We preserve the value of "result" because if our original power request was deemed "too soon"
1046 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
1047 // since the implication is that the system won't manage to be awake again at the time we need it.
1050 interval
+= (interval
< 20) ? 1 : ((interval
+3) / 4);
1051 r
= mDNSPowerRequest(1, interval
);
1053 while (r
== kIOReturnNotReady
);
1054 if (r
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, r
, r
);
1055 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval
);
1059 if (result
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, result
, result
);
1060 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval
);
1062 m
->p
->WakeAtUTC
= mDNSPlatformUTC() + interval
;
1066 m
->SleepState
= SleepState_Sleeping
;
1067 // Clear our interface list to empty state, ready to go to sleep
1068 // As a side effect of doing this, we'll also cancel any outstanding SPS Resolve calls that didn't complete
1069 mDNSMacOSXNetworkChanged(m
);
1072 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1073 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1074 (m
->p
->IOPMConnection
) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1076 (result
== kIOReturnSuccess
) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1077 m
->p
->SleepCookie
, ready
? "ready for sleep" : "giving up", now
, m
->SleepLimit
- now
);
1079 m
->SleepLimit
= 0; // Don't clear m->SleepLimit until after we've logged it above
1080 m
->TimeSlept
= mDNSPlatformUTC();
1082 // accumulate total time awake for this statistics gathering interval
1083 if (m
->StatStartTime
)
1085 m
->ActiveStatTime
+= (m
->TimeSlept
- m
->StatStartTime
);
1087 // indicate this value is invalid until reinitialzed on wakeup
1088 m
->StatStartTime
= 0;
1091 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1092 if (m
->p
->IOPMConnection
) IOPMConnectionAcknowledgeEventWithOptions(m
->p
->IOPMConnection
, m
->p
->SleepCookie
, opts
);
1095 if (result
== kIOReturnSuccess
) IOAllowPowerChange (m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1096 else IOCancelPowerChange(m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1098 if (opts
) CFRelease(opts
);
1102 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1104 mDNSexport
void TriggerEventCompletion()
1106 debugf("TriggerEventCompletion: Merge data");
1107 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
1110 mDNSlocal
void PrepareForIdle(void *m_param
)
1113 int64_t time_offset
;
1114 dispatch_time_t dtime
;
1116 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1118 // This is the main work loop:
1119 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1120 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1121 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1123 debugf("PrepareForIdle: called");
1124 // Run mDNS_Execute to find out the time we next need to wake up
1125 mDNSs32 start
= mDNSPlatformRawTime();
1126 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1127 mDNSs32 end
= mDNSPlatformRawTime();
1128 if (end
- start
>= WatchDogReportingThreshold
)
1129 LogInfo("CustomSourceHandler:WARNING: Idle task took %dms to complete", end
- start
);
1131 mDNSs32 now
= mDNS_TimeNow(m
);
1133 if (m
->ShutdownTime
)
1135 if (mDNSStorage
.ResourceRecords
)
1137 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, mDNSStorage
.ResourceRecords
));
1138 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1140 if (mDNS_ExitNow(m
, now
))
1142 LogInfo("IdleLoop: mDNS_FinalExit");
1143 mDNS_FinalExit(&mDNSStorage
);
1144 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1147 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1148 nextTimerEvent
= m
->ShutdownTime
;
1152 if (!AllowSleepNow(m
, now
))
1153 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1154 nextTimerEvent
= m
->SleepLimit
;
1156 // Convert absolute wakeup time to a relative time from now
1157 mDNSs32 ticks
= nextTimerEvent
- now
;
1158 if (ticks
< 1) ticks
= 1;
1160 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1166 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1169 time_offset
= ((mDNSu32
)ticks
/ mDNSPlatformOneSecond
) * 1000000000 + (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1170 dtime
= dispatch_time(DISPATCH_TIME_NOW
, time_offset
);
1171 dispatch_source_set_timer(PlatformStorage
.timer
, dtime
, 1000ull*1000000000, 0);
1172 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks
);
1176 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1178 mDNSlocal
void KQWokenFlushBytes(int fd
, __unused
short filter
, __unused
void *context
)
1180 // Read all of the bytes so we won't wake again.
1182 while (recv(fd
, buffer
, sizeof(buffer
), MSG_DONTWAIT
) > 0) continue;
1185 mDNSlocal
void SetLowWater(const KQSocketSet
*const k
, const int r
)
1187 if (k
->sktv4
>=0 && setsockopt(k
->sktv4
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1188 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k
->sktv4
, r
, errno
, strerror(errno
));
1189 if (k
->sktv6
>=0 && setsockopt(k
->sktv6
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1190 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k
->sktv6
, r
, errno
, strerror(errno
));
1193 mDNSlocal
void * KQueueLoop(void *m_param
)
1198 #if USE_SELECT_WITH_KQUEUEFD
1201 const int multiplier
= 1000000 / mDNSPlatformOneSecond
;
1203 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1206 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1207 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32
)mDNSStorage
.timenow_last
, mDNSStorage
.timenow_last
);
1209 // This is the main work loop:
1210 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1211 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1212 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1213 // (4) On wakeup we first process *all* events
1214 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
1217 #define kEventsToReadAtOnce 1
1218 struct kevent new_events
[kEventsToReadAtOnce
];
1220 // Run mDNS_Execute to find out the time we next need to wake up
1221 mDNSs32 start
= mDNSPlatformRawTime();
1222 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1223 mDNSs32 end
= mDNSPlatformRawTime();
1224 if (end
- start
>= WatchDogReportingThreshold
)
1225 LogInfo("WARNING: Idle task took %dms to complete", end
- start
);
1227 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
1231 mDNSs32 now
= mDNS_TimeNow(m
);
1233 if (m
->ShutdownTime
)
1235 if (mDNSStorage
.ResourceRecords
)
1238 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
1240 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, rr
));
1241 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1244 if (mDNS_ExitNow(m
, now
))
1246 LogInfo("mDNS_FinalExit");
1247 mDNS_FinalExit(&mDNSStorage
);
1248 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1251 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1252 nextTimerEvent
= m
->ShutdownTime
;
1256 if (!AllowSleepNow(m
, now
))
1257 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1258 nextTimerEvent
= m
->SleepLimit
;
1260 // Convert absolute wakeup time to a relative time from now
1261 mDNSs32 ticks
= nextTimerEvent
- now
;
1262 if (ticks
< 1) ticks
= 1;
1264 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1270 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1273 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents
, ticks
);
1276 // Release the lock, and sleep until:
1277 // 1. Something interesting happens like a packet arriving, or
1278 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
1279 // 3. The timeout expires
1280 pthread_mutex_unlock(&PlatformStorage
.BigMutex
);
1282 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1283 if (m
->p
->num_mcasts
)
1285 SetLowWater(&m
->p
->permanentsockets
, 0x10000);
1286 if (ticks
> mDNSPlatformOneSecond
/ 8) ticks
= mDNSPlatformOneSecond
/ 8;
1289 #if USE_SELECT_WITH_KQUEUEFD
1290 struct timeval timeout
;
1291 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1292 timeout
.tv_usec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1293 FD_SET(KQueueFD
, &readfds
);
1294 if (select(KQueueFD
+1, &readfds
, NULL
, NULL
, &timeout
) < 0)
1295 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1297 struct timespec timeout
;
1298 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1299 timeout
.tv_nsec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1300 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
1301 // and have it work similarly to the way it does with nevents non-zero --
1302 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
1303 // In fact, what happens if you do this is that it just returns immediately. So, we have
1304 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
1305 if (kevent(KQueueFD
, NULL
, 0, new_events
, 1, &timeout
) < 0)
1306 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1309 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1310 // We have to ignore the event we may have been told about above, because that
1311 // was done without holding the lock, and between the time we woke up and the
1312 // time we reclaimed the lock the other thread could have done something that
1313 // makes the event no longer valid. Now we have the lock, we call kevent again
1314 // and this time we can safely process the events it tells us about.
1316 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
1317 if (m
->p
->num_mcasts
)
1319 SetLowWater(&m
->p
->permanentsockets
, 1);
1320 m
->p
->num_mcasts
= 0;
1323 static const struct timespec zero_timeout
= { 0, 0 };
1325 while ((events_found
= kevent(KQueueFD
, NULL
, 0, new_events
, kEventsToReadAtOnce
, &zero_timeout
)) != 0)
1327 if (events_found
> kEventsToReadAtOnce
|| (events_found
< 0 && errno
!= EINTR
))
1329 // Not sure what to do here, our kqueue has failed us - this isn't ideal
1330 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", errno
, strerror(errno
));
1334 numevents
+= events_found
;
1337 for (i
= 0; i
< events_found
; i
++)
1339 const KQueueEntry
*const kqentry
= new_events
[i
].udata
;
1340 mDNSs32 stime
= mDNSPlatformRawTime();
1341 const char *const KQtask
= kqentry
->KQtask
; // Grab a copy in case KQcallback deletes the task
1342 kqentry
->KQcallback(new_events
[i
].ident
, new_events
[i
].filter
, kqentry
->KQcontext
);
1343 mDNSs32 etime
= mDNSPlatformRawTime();
1344 if (etime
- stime
>= WatchDogReportingThreshold
)
1345 LogInfo("WARNING: %s took %dms to complete", KQtask
, etime
- stime
);
1353 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1355 mDNSlocal
size_t LaunchdCheckin(void)
1357 // Ask launchd for our socket
1358 int result
= launch_activate_socket("Listeners", &launchd_fds
, &launchd_fds_count
);
1359 if (result
!= 0) { LogMsg("launch_activate_socket() failed errno %d (%s)", errno
, strerror(errno
)); }
1360 return launchd_fds_count
;
1364 extern int sandbox_init(const char *profile
, uint64_t flags
, char **errorbuf
) __attribute__((weak_import
));
1366 #if APPLE_OSX_mDNSResponder
1367 mDNSlocal mDNSBool
PreferencesGetValueBool(CFStringRef key
, mDNSBool defaultValue
)
1369 CFBooleanRef boolean
;
1370 mDNSBool result
= defaultValue
;
1372 boolean
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1375 if (CFGetTypeID(boolean
) == CFBooleanGetTypeID())
1376 result
= CFBooleanGetValue(boolean
) ? mDNStrue
: mDNSfalse
;
1383 mDNSlocal
int PreferencesGetValueInt(CFStringRef key
, int defaultValue
)
1387 int result
= defaultValue
;
1389 number
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1392 if ((CFGetTypeID(number
) == CFNumberGetTypeID()) && CFNumberGetValue(number
, kCFNumberIntType
, &numberValue
))
1393 result
= numberValue
;
1401 mDNSlocal
void SandboxProcess(void)
1403 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1405 LogMsg("Note: Compiled without Apple Sandbox support");
1406 #else // MDNS_NO_SANDBOX
1408 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1412 uint64_t sandbox_flags
= SANDBOX_NAMED
;
1414 (void)confstr(_CS_DARWIN_USER_CACHE_DIR
, NULL
, 0);
1416 int sandbox_err
= sandbox_init("mDNSResponder", sandbox_flags
, &sandbox_msg
);
1419 LogMsg("WARNING: sandbox_init error %s", sandbox_msg
);
1420 // If we have errors in the sandbox during development, to prevent
1421 // exiting, uncomment the following line.
1422 //sandbox_free_error(sandbox_msg);
1424 errx(EX_OSERR
, "sandbox_init() failed: %s", sandbox_msg
);
1426 else LogInfo("Now running under Apple Sandbox restrictions");
1428 #endif // MDNS_NO_SANDBOX
1431 #if APPLE_OSX_mDNSResponder
1432 mDNSlocal
void init_logging(void)
1434 log_general
= os_log_create("com.apple.mDNSResponder", "AllINFO");
1438 // OS_LOG_DEFAULT is the default logging object, if you are not creating a custom subsystem/category
1439 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in mDNSResponder");
1444 #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
1445 mDNSlocal mDNSBool
initialize_networkserviceproxy(void)
1447 void *NSPImage
= dlopen("/System/Library/PrivateFrameworks/NetworkServiceProxy.framework/NetworkServiceProxy", RTLD_LAZY
| RTLD_LOCAL
);
1448 if (NSPImage
== NULL
) {
1449 os_log_error(OS_LOG_DEFAULT
, "dlopen NetworkServiceProxy.framework failed");
1456 mDNSexport
int main(int argc
, char **argv
)
1459 kern_return_t status
;
1462 bool useDebugSocket
= mDNSfalse
;
1463 bool useSandbox
= mDNStrue
;
1466 #if APPLE_OSX_mDNSResponder
1470 mDNSMacOSXSystemBuildNumber(NULL
);
1471 LogMsg("%s starting %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
1474 LogMsg("CacheRecord %5d", sizeof(CacheRecord
));
1475 LogMsg("CacheGroup %5d", sizeof(CacheGroup
));
1476 LogMsg("ResourceRecord %5d", sizeof(ResourceRecord
));
1477 LogMsg("RData_small %5d", sizeof(RData_small
));
1479 LogMsg("sizeof(CacheEntity) %5d", sizeof(CacheEntity
));
1480 LogMsg("RR_CACHE_SIZE %5d", RR_CACHE_SIZE
);
1481 LogMsg("block bytes used %5d", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1482 LogMsg("block bytes wasted %5d", 32*1024 - sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1487 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1491 for (i
=1; i
<argc
; i
++)
1493 if (!strcasecmp(argv
[i
], "-d" )) mDNS_DebugMode
= mDNStrue
;
1494 if (!strcasecmp(argv
[i
], "-NoMulticastAdvertisements")) NoMulticastAdvertisements
= mDNStrue
;
1495 if (!strcasecmp(argv
[i
], "-DisableSleepProxyClient" )) DisableSleepProxyClient
= mDNStrue
;
1496 if (!strcasecmp(argv
[i
], "-DebugLogging" )) mDNS_LoggingEnabled
= mDNStrue
;
1497 if (!strcasecmp(argv
[i
], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled
= mDNStrue
;
1498 if (!strcasecmp(argv
[i
], "-OfferSleepProxyService" ))
1499 OfferSleepProxyService
= (i
+1 < argc
&& mDNSIsDigit(argv
[i
+1][0]) && mDNSIsDigit(argv
[i
+1][1]) && argv
[i
+1][2]==0) ? atoi(argv
[++i
]) : 100;
1500 if (!strcasecmp(argv
[i
], "-UseInternalSleepProxy" ))
1501 UseInternalSleepProxy
= (i
+1<argc
&& mDNSIsDigit(argv
[i
+1][0]) && argv
[i
+1][1]==0) ? atoi(argv
[++i
]) : 1;
1502 if (!strcasecmp(argv
[i
], "-StrictUnicastOrdering" )) StrictUnicastOrdering
= mDNStrue
;
1503 if (!strcasecmp(argv
[i
], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains
= mDNStrue
;
1505 if (!strcasecmp(argv
[i
], "-UseDebugSocket")) useDebugSocket
= mDNStrue
;
1506 if (!strcasecmp(argv
[i
], "-NoSandbox")) useSandbox
= mDNSfalse
;
1511 #if APPLE_OSX_mDNSResponder
1512 /* Reads the external user's program arguments for mDNSResponder starting 10.11.x(El Capitan) on OSX. The options for external user are:
1513 DebugLogging, UnicastPacketLogging, NoMulticastAdvertisements, StrictUnicastOrdering and AlwaysAppendSearchDomains
1515 To turn ON the particular option, here is what the user should do (as an example of setting two options)
1516 1] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool YES
1517 2] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
1520 To turn OFF all options, here is what the user should do
1521 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1524 To view the current options set, here is what the user should do
1525 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1527 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
1531 // Currently on Fuji/Whitetail releases we are keeping the logging always enabled.
1532 // Hence mDNS_LoggingEnabled and mDNS_PacketLoggingEnabled is set to true below by default.
1534 mDNS_LoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_DebugLogging
, mDNS_LoggingEnabled
);
1535 mDNS_PacketLoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging
, mDNS_PacketLoggingEnabled
);
1538 mDNS_LoggingEnabled
= mDNStrue
;
1539 mDNS_PacketLoggingEnabled
= mDNStrue
;
1541 NoMulticastAdvertisements
= PreferencesGetValueBool(kPreferencesKey_NoMulticastAdvertisements
, NoMulticastAdvertisements
);
1542 StrictUnicastOrdering
= PreferencesGetValueBool(kPreferencesKey_StrictUnicastOrdering
, StrictUnicastOrdering
);
1543 AlwaysAppendSearchDomains
= PreferencesGetValueBool(kPreferencesKey_AlwaysAppendSearchDomains
, AlwaysAppendSearchDomains
);
1544 OfferSleepProxyService
= PreferencesGetValueInt(kPreferencesKey_OfferSleepProxyService
, OfferSleepProxyService
);
1545 UseInternalSleepProxy
= PreferencesGetValueInt(kPreferencesKey_UseInternalSleepProxy
, UseInternalSleepProxy
);
1546 EnableBLEBasedDiscovery
= PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery
, EnableBLEBasedDiscovery
);
1549 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
1550 if (NoMulticastAdvertisements
)
1551 LogMsg("-NoMulticastAdvertisements is set: Administratively prohibiting multicast advertisements");
1552 if (AlwaysAppendSearchDomains
)
1553 LogMsg("-AlwaysAppendSearchDomains is set");
1554 if (StrictUnicastOrdering
)
1555 LogMsg("-StrictUnicastOrdering is set");
1557 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1559 signal(SIGHUP
, HandleSIG
); // (Debugging) Purge the cache to check for cache handling bugs
1560 signal(SIGINT
, HandleSIG
); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
1561 signal(SIGPIPE
, SIG_IGN
); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
1562 signal(SIGTERM
, HandleSIG
); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
1563 signal(SIGINFO
, HandleSIG
); // (Debugging) Write state snapshot to syslog
1564 signal(SIGUSR1
, HandleSIG
); // (Debugging) Enable Logging
1565 signal(SIGUSR2
, HandleSIG
); // (Debugging) Enable Packet Logging
1566 signal(SIGPROF
, HandleSIG
); // (Debugging) Toggle Multicast Logging
1567 signal(SIGTSTP
, HandleSIG
); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
1569 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1571 mDNSStorage
.p
= &PlatformStorage
; // Make sure mDNSStorage.p is set up, because validatelists uses it
1572 // Need to Start XPC Server Before LaunchdCheckin() (Reason: rdar11023750)
1575 if (!useDebugSocket
) {
1576 if (LaunchdCheckin() == 0)
1577 useDebugSocket
= mDNStrue
;
1580 SetDebugBoundPath();
1585 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1587 // Create the kqueue, mutex and thread to support KQSockets
1588 KQueueFD
= kqueue();
1589 if (KQueueFD
== -1) { LogMsg("kqueue() failed errno %d (%s)", errno
, strerror(errno
)); status
= errno
; goto exit
; }
1591 i
= pthread_mutex_init(&PlatformStorage
.BigMutex
, NULL
);
1592 if (i
== -1) { LogMsg("pthread_mutex_init() failed errno %d (%s)", errno
, strerror(errno
)); status
= errno
; goto exit
; }
1594 int fdpair
[2] = {0, 0};
1595 i
= socketpair(AF_UNIX
, SOCK_STREAM
, 0, fdpair
);
1596 if (i
== -1) { LogMsg("socketpair() failed errno %d (%s)", errno
, strerror(errno
)); status
= errno
; goto exit
; }
1598 // Socket pair returned us two identical sockets connected to each other
1599 // We will use the first socket to send the second socket. The second socket
1600 // will be added to the kqueue so it will wake when data is sent.
1601 static const KQueueEntry wakeKQEntry
= { KQWokenFlushBytes
, NULL
, "kqueue wakeup after CFRunLoop event" };
1603 PlatformStorage
.WakeKQueueLoopFD
= fdpair
[0];
1604 KQueueSet(fdpair
[1], EV_ADD
, EVFILT_READ
, &wakeKQEntry
);
1606 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1613 #if TARGET_OS_EMBEDDED
1614 status
= MetricsInit();
1615 if (status
) { LogMsg("Daemon start: MetricsInit failed (%d)", status
); }
1618 status
= mDNSDaemonInitialize();
1619 if (status
) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit
; }
1621 status
= udsserver_init(launchd_fds
, launchd_fds_count
);
1622 if (status
) { LogMsg("Daemon start: udsserver_init failed"); goto exit
; }
1624 mDNSMacOSXNetworkChanged(&mDNSStorage
);
1627 #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
1628 if (initialize_networkserviceproxy() == mDNSfalse
) {
1629 LogMsg("Failed to initialize NetworkServiceProxy");
1633 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1634 LogInfo("Daemon Start: Using LibDispatch");
1635 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
1637 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1638 // Start the kqueue thread
1639 pthread_t KQueueThread
;
1640 i
= pthread_create(&KQueueThread
, NULL
, KQueueLoop
, &mDNSStorage
);
1641 if (i
== -1) { LogMsg("pthread_create() failed errno %d (%s)", errno
, strerror(errno
)); status
= errno
; goto exit
; }
1645 LogMsg("ERROR: CFRunLoopRun Exiting.");
1646 mDNS_Close(&mDNSStorage
);
1648 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1650 LogMsg("%s exiting", mDNSResponderVersionString
);
1656 // uds_daemon.c support routines /////////////////////////////////////////////
1658 // Arrange things so that when data appears on fd, callback is called with context
1659 mDNSexport mStatus
udsSupportAddFDToEventLoop(int fd
, udsEventCallback callback
, void *context
, void **platform_data
)
1661 KQSocketEventSource
**p
= &gEventSources
;
1662 (void) platform_data
;
1663 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1664 if (*p
) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd
); return mStatus_AlreadyRegistered
; }
1666 KQSocketEventSource
*newSource
= (KQSocketEventSource
*) mallocL("KQSocketEventSource", sizeof *newSource
);
1667 if (!newSource
) return mStatus_NoMemoryErr
;
1669 newSource
->next
= mDNSNULL
;
1671 newSource
->kqs
.KQcallback
= callback
;
1672 newSource
->kqs
.KQcontext
= context
;
1673 newSource
->kqs
.KQtask
= "UDS client";
1674 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1675 newSource
->kqs
.readSource
= mDNSNULL
;
1676 newSource
->kqs
.writeSource
= mDNSNULL
;
1677 newSource
->kqs
.fdClosed
= mDNSfalse
;
1678 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1680 if (KQueueSet(fd
, EV_ADD
, EVFILT_READ
, &newSource
->kqs
) == 0)
1683 return mStatus_NoError
;
1686 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd
, errno
, strerror(errno
));
1687 freeL("KQSocketEventSource", newSource
);
1688 return mStatus_BadParamErr
;
1691 int udsSupportReadFD(dnssd_sock_t fd
, char *buf
, int len
, int flags
, void *platform_data
)
1693 (void) platform_data
;
1694 return recv(fd
, buf
, len
, flags
);
1697 mDNSexport mStatus
udsSupportRemoveFDFromEventLoop(int fd
, void *platform_data
) // Note: This also CLOSES the file descriptor
1699 KQSocketEventSource
**p
= &gEventSources
;
1700 (void) platform_data
;
1701 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1704 KQSocketEventSource
*s
= *p
;
1706 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
1707 // causes the kernel to automatically remove any associated kevents
1708 mDNSPlatformCloseFD(&s
->kqs
, s
->fd
);
1709 freeL("KQSocketEventSource", s
);
1710 return mStatus_NoError
;
1712 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd
);
1713 return mStatus_NoSuchNameErr
;
1716 #if _BUILDING_XCODE_PROJECT_
1717 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
1718 const char *__crashreporter_info__
= mDNSResponderVersionString
;
1719 asm (".desc ___crashreporter_info__, 0x10");
1722 // For convenience when using the "strings" command, this is the last thing in the file
1723 // The "@(#) " pattern is a special prefix the "what" command looks for
1724 mDNSexport
const char mDNSResponderVersionString_SCCS
[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion
) " (" __DATE__
" " __TIME__
")";