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>
37 #include "DNSCommon.h"
38 #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
40 #include "uds_daemon.h" // Interface to the server side implementation of dns_sd.h
41 #include "xpc_services.h" // Interface to XPC services
44 #if TARGET_OS_EMBEDDED
48 #if APPLE_OSX_mDNSResponder
49 static os_log_t log_general
= NULL
;
53 // Used on OSX(10.11.x onwards) for manipulating mDNSResponder program arguments
54 #if APPLE_OSX_mDNSResponder
55 // plist file to read the user's preferences
56 #define kProgramArguments CFSTR("com.apple.mDNSResponder")
57 // possible arguments for external customers
58 #define kPreferencesKey_DebugLogging CFSTR("DebugLogging")
59 #define kPreferencesKey_UnicastPacketLogging CFSTR("UnicastPacketLogging")
60 #define kPreferencesKey_AlwaysAppendSearchDomains CFSTR("AlwaysAppendSearchDomains")
61 #define kPreferencesKey_NoMulticastAdvertisements CFSTR("NoMulticastAdvertisements")
62 #define kPreferencesKey_StrictUnicastOrdering CFSTR("StrictUnicastOrdering")
63 #define kPreferencesKey_OfferSleepProxyService CFSTR("OfferSleepProxyService")
64 #define kPreferencesKey_UseInternalSleepProxy CFSTR("UseInternalSleepProxy")
65 #define kPreferencesKey_EnableBLEBasedDiscovery CFSTR("EnableBLEBasedDiscovery")
68 //*************************************************************************************************************
69 #if COMPILER_LIKES_PRAGMA_MARK
70 #pragma mark - Globals
73 static mDNS_PlatformSupport PlatformStorage
;
75 // Start off with a default cache of 32K (141 records of 232 bytes each)
76 // Each time we grow the cache we add another 141 records
77 // 141 * 164 = 32712 bytes.
78 // This fits in eight 4kB pages, with 56 bytes spare for memory block headers and similar overhead
79 #define RR_CACHE_SIZE ((32*1024) / sizeof(CacheRecord))
80 static CacheEntity rrcachestorage
[RR_CACHE_SIZE
];
81 struct CompileTimeAssertionChecks_RR_CACHE_SIZE
{ char a
[(RR_CACHE_SIZE
>= 141) ? 1 : -1]; };
84 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
85 mDNSlocal
void PrepareForIdle(void *m_param
);
86 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
87 static mach_port_t signal_port
= MACH_PORT_NULL
;
88 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
90 static dnssd_sock_t
*launchd_fds
= mDNSNULL
;
91 static size_t launchd_fds_count
= 0;
93 static mDNSBool NoMulticastAdvertisements
= mDNSfalse
; // By default, advertise addresses (& other records) via multicast
95 extern mDNSBool StrictUnicastOrdering
;
96 extern mDNSBool AlwaysAppendSearchDomains
;
97 extern mDNSBool EnableBLEBasedDiscovery
;
99 // We keep a list of client-supplied event sources in KQSocketEventSource records
100 typedef struct KQSocketEventSource
102 struct KQSocketEventSource
*next
;
105 } KQSocketEventSource
;
107 static KQSocketEventSource
*gEventSources
;
109 //*************************************************************************************************************
110 #if COMPILER_LIKES_PRAGMA_MARK
112 #pragma mark - General Utility Functions
115 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
117 char _malloc_options
[] = "AXZ";
119 mDNSlocal
void validatelists(mDNS
*const m
)
121 #if BONJOUR_ON_DEMAND
122 mDNSu32 NumAllInterfaceRecords
= 0;
123 mDNSu32 NumAllInterfaceQuestions
= 0;
124 #endif // BONJOUR_ON_DEMAND
127 KQSocketEventSource
*k
;
128 for (k
= gEventSources
; k
; k
=k
->next
)
129 if (k
->next
== (KQSocketEventSource
*)~0 || k
->fd
< 0)
130 LogMemCorruption("gEventSources: %p is garbage (%d)", k
, k
->fd
);
132 // Check Unix Domain Socket client lists (uds_daemon.c)
135 // Check core mDNS lists
137 for (rr
= m
->ResourceRecords
; rr
; rr
=rr
->next
)
139 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
140 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
141 if (rr
->resrec
.name
!= &rr
->namestorage
)
142 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
143 rr
, rr
->resrec
.name
->c
, rr
->namestorage
.c
, rr
->namestorage
.c
);
144 #if BONJOUR_ON_DEMAND
145 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
146 #endif // BONJOUR_ON_DEMAND
149 for (rr
= m
->DuplicateRecords
; rr
; rr
=rr
->next
)
151 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
152 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
153 #if BONJOUR_ON_DEMAND
154 if (!AuthRecord_uDNS(rr
) && !RRLocalOnly(rr
)) NumAllInterfaceRecords
++;
155 #endif // BONJOUR_ON_DEMAND
158 rr
= m
->NewLocalRecords
;
160 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
161 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
163 rr
= m
->CurrentRecord
;
165 if (rr
->next
== (AuthRecord
*)~0 || rr
->resrec
.RecordType
== 0 || rr
->resrec
.RecordType
== 0xFF)
166 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr
, rr
->resrec
.RecordType
);
169 for (q
= m
->Questions
; q
; q
=q
->next
)
171 if (q
->next
== (DNSQuestion
*)~0 || q
->ThisQInterval
== (mDNSs32
) ~0)
172 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q
, q
->ThisQInterval
, q
->next
);
173 if (q
->DuplicateOf
&& q
->LocalSocket
)
174 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q
, q
->qname
.c
, DNSTypeName(q
->qtype
));
175 #if BONJOUR_ON_DEMAND
176 if (!LocalOnlyOrP2PInterface(q
->InterfaceID
) && mDNSOpaque16IsZero(q
->TargetQID
))
177 NumAllInterfaceQuestions
++;
178 #endif // BONJOUR_ON_DEMAND
184 FORALL_CACHERECORDS(slot
, cg
, cr
)
186 if (cr
->resrec
.RecordType
== 0 || cr
->resrec
.RecordType
== 0xFF)
187 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot
, cr
, cr
->resrec
.RecordType
);
188 if (cr
->CRActiveQuestion
)
190 for (q
= m
->Questions
; q
; q
=q
->next
) if (q
== cr
->CRActiveQuestion
) break;
191 if (!q
) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot
, cr
->CRActiveQuestion
, CRDisplayString(m
, cr
));
195 // Check core uDNS lists
196 udns_validatelists(m
);
198 // Check platform-layer lists
199 NetworkInterfaceInfoOSX
*i
;
200 for (i
= m
->p
->InterfaceList
; i
; i
= i
->next
)
201 if (i
->next
== (NetworkInterfaceInfoOSX
*)~0 || !i
->m
|| i
->m
== (mDNS
*)~0)
202 LogMemCorruption("m->p->InterfaceList: %p is garbage (%p)", i
, i
->ifinfo
.ifname
);
205 for (t
= m
->TunnelClients
; t
; t
=t
->next
)
206 if (t
->next
== (ClientTunnel
*)~0 || t
->dstname
.c
[0] > 63)
207 LogMemCorruption("m->TunnelClients: %p is garbage (%d)", t
, t
->dstname
.c
[0]);
209 #if BONJOUR_ON_DEMAND
210 if (m
->NumAllInterfaceRecords
!= NumAllInterfaceRecords
)
211 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m
->NumAllInterfaceRecords
, NumAllInterfaceRecords
);
213 if (m
->NumAllInterfaceQuestions
!= NumAllInterfaceQuestions
)
214 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m
->NumAllInterfaceQuestions
, NumAllInterfaceQuestions
);
215 #endif // BONJOUR_ON_DEMAND
218 mDNSexport
void *mallocL(char *msg
, unsigned int size
)
220 // Allocate space for two words of sanity checking data before the requested block
221 mDNSu32
*mem
= malloc(sizeof(mDNSu32
) * 2 + size
);
223 { LogMsg("malloc( %s : %d ) failed", msg
, size
); return(NULL
); }
226 if (size
> 32768) LogMsg("malloc( %s : %lu ) @ %p suspiciously large", msg
, size
, &mem
[2]);
227 else if (MACOSX_MDNS_MALLOC_DEBUGGING
>= 2) LogMsg("malloc( %s : %lu ) @ %p", msg
, size
, &mem
[2]);
230 //mDNSPlatformMemZero(&mem[2], size);
231 memset(&mem
[2], 0xFF, size
);
232 validatelists(&mDNSStorage
);
237 mDNSexport
void freeL(char *msg
, void *x
)
240 LogMsg("free( %s @ NULL )!", msg
);
243 mDNSu32
*mem
= ((mDNSu32
*)x
) - 2;
244 if (mem
[0] == 0xDEADDEAD) { LogMemCorruption("free( %s : %lu @ %p ) !!!! ALREADY DISPOSED !!!!", msg
, mem
[1], &mem
[2]); return; }
245 if (mem
[0] != 0xDEAD1234) { LogMemCorruption("free( %s : %lu @ %p ) !!!! NEVER ALLOCATED !!!!", msg
, mem
[1], &mem
[2]); return; }
246 if (mem
[1] > 32768) LogMsg("free( %s : %lu @ %p) suspiciously large", msg
, mem
[1], &mem
[2]);
247 else if (MACOSX_MDNS_MALLOC_DEBUGGING
>= 2) LogMsg("free( %s : %ld @ %p)", msg
, mem
[1], &mem
[2]);
249 memset(mem
+2, 0xFF, mem
[1]);
250 validatelists(&mDNSStorage
);
257 //*************************************************************************************************************
260 mDNSexport
void RecordUpdatedNiceLabel(mDNS
*const m
, mDNSs32 delay
)
262 m
->p
->NotifyUser
= NonZeroTime(m
->timenow
+ delay
);
265 mDNSlocal
void mDNSPreferencesSetNames(mDNS
*const m
, int key
, domainlabel
*old
, domainlabel
*new)
267 domainlabel
*prevold
, *prevnew
;
270 case kmDNSComputerName
:
271 case kmDNSLocalHostName
:
272 if (key
== kmDNSComputerName
)
274 prevold
= &m
->p
->prevoldnicelabel
;
275 prevnew
= &m
->p
->prevnewnicelabel
;
279 prevold
= &m
->p
->prevoldhostlabel
;
280 prevnew
= &m
->p
->prevnewhostlabel
;
282 // There are a few cases where we need to invoke the helper.
284 // 1. If the "old" label and "new" label are not same, it means there is a conflict. We need
285 // to invoke the helper so that it pops up a dialogue to inform the user about the
288 // 2. If the "old" label and "new" label are same, it means the user has set the host/nice label
289 // through the preferences pane. We may have to inform the helper as it may have popped up
290 // a dialogue previously (due to a conflict) and it needs to suppress it now. We can avoid invoking
291 // the helper in this case if the previous values (old and new) that we told helper last time
292 // are same. If the previous old and new values are same, helper does not care.
294 // Note: "new" can be NULL when we have repeated conflicts and we are asking helper to give up. "old"
295 // is not called with NULL today, but this makes it future proof.
296 if (!old
|| !new || !SameDomainLabelCS(old
->c
, new->c
) ||
297 !SameDomainLabelCS(old
->c
, prevold
->c
) ||
298 !SameDomainLabelCS(new->c
, prevnew
->c
))
300 // Work around bug radar:21397654
301 #ifndef __clang_analyzer__
311 mDNSPreferencesSetName(key
, old
, new);
315 LogInfo("mDNSPreferencesSetNames not invoking helper %s %#s, %s %#s, old %#s, new %#s",
316 (key
== kmDNSComputerName
? "prevoldnicelabel" : "prevoldhostlabel"), prevold
->c
,
317 (key
== kmDNSComputerName
? "prevnewnicelabel" : "prevnewhostlabel"), prevnew
->c
,
322 LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key
);
327 mDNSlocal
void mDNS_StatusCallback(mDNS
*const m
, mStatus result
)
330 if (result
== mStatus_NoError
)
332 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
333 LogInfo("Local Hostname changed from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
334 // One second pause in case we get a Computer Name update too -- don't want to alert the user twice
335 RecordUpdatedNiceLabel(m
, mDNSPlatformOneSecond
);
337 else if (result
== mStatus_NameConflict
)
339 LogInfo("Local Hostname conflict for \"%#s.local\"", m
->hostlabel
.c
);
340 if (!m
->p
->HostNameConflict
) m
->p
->HostNameConflict
= NonZeroTime(m
->timenow
);
341 else if (m
->timenow
- m
->p
->HostNameConflict
> 60 * mDNSPlatformOneSecond
)
343 // Tell the helper we've given up
344 mDNSPreferencesSetNames(m
, kmDNSLocalHostName
, &m
->p
->userhostlabel
, NULL
);
347 else if (result
== mStatus_GrowCache
)
349 // Allocate another chunk of cache storage
350 static unsigned int allocated
= 0;
352 if (allocated
>= 1000000) return; // For now we limit the cache to at most 1MB on iOS devices
354 allocated
+= sizeof(CacheEntity
) * RR_CACHE_SIZE
;
355 // LogMsg("GrowCache %d * %d = %d; total so far %6u", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE, allocated);
356 CacheEntity
*storage
= mallocL("mStatus_GrowCache", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
357 //LogInfo("GrowCache %d * %d = %d", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE);
358 if (storage
) mDNS_GrowCache(m
, storage
, RR_CACHE_SIZE
);
360 else if (result
== mStatus_ConfigChanged
)
362 // Tell the helper we've seen a change in the labels. It will dismiss the name conflict alert if needed.
363 mDNSPreferencesSetNames(m
, kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
364 mDNSPreferencesSetNames(m
, kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
366 // Then we call into the UDS daemon code, to let it do the same
367 udsserver_handle_configchange(m
);
372 //*************************************************************************************************************
373 #if COMPILER_LIKES_PRAGMA_MARK
375 #pragma mark - Startup, shutdown, and supporting code
378 mDNSlocal
void ExitCallback(int sig
)
381 LogMsg("%s stopping", mDNSResponderVersionString
);
383 if (udsserver_exit() < 0)
384 LogMsg("ExitCallback: udsserver_exit failed");
386 debugf("ExitCallback: mDNS_StartExit");
387 mDNS_StartExit(&mDNSStorage
);
390 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
392 // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
393 mDNSlocal
void HandleSIG(int sig
)
395 kern_return_t status
;
396 mach_msg_header_t header
;
398 // WARNING: can't call syslog or fprintf from signal handler
399 header
.msgh_bits
= MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND
, 0);
400 header
.msgh_remote_port
= signal_port
;
401 header
.msgh_local_port
= MACH_PORT_NULL
;
402 header
.msgh_size
= sizeof(header
);
403 header
.msgh_id
= sig
;
405 status
= mach_msg(&header
, MACH_SEND_MSG
| MACH_SEND_TIMEOUT
, header
.msgh_size
,
406 0, MACH_PORT_NULL
, 0, MACH_PORT_NULL
);
408 if (status
!= MACH_MSG_SUCCESS
)
410 if (status
== MACH_SEND_TIMED_OUT
) mach_msg_destroy(&header
);
411 if (sig
== SIGTERM
|| sig
== SIGINT
) exit(-1);
415 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
417 mDNSexport
void INFOCallback(void)
419 mDNSs32 utc
= mDNSPlatformUTC();
420 const mDNSs32 now
= mDNS_TimeNow(&mDNSStorage
);
421 NetworkInterfaceInfoOSX
*i
;
425 LogMsg("---- BEGIN STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
427 udsserver_info(&mDNSStorage
);
429 LogMsgNoIdent("----- Platform Timers -----");
430 LogTimer("m->NextCacheCheck ", mDNSStorage
.NextCacheCheck
);
431 LogTimer("m->NetworkChanged ", mDNSStorage
.NetworkChanged
);
432 LogTimer("m->p->NotifyUser ", mDNSStorage
.p
->NotifyUser
);
433 LogTimer("m->p->HostNameConflict ", mDNSStorage
.p
->HostNameConflict
);
434 LogTimer("m->p->KeyChainTimer ", mDNSStorage
.p
->KeyChainTimer
);
436 xpcserver_info(&mDNSStorage
);
438 LogMsgNoIdent("----- KQSocketEventSources -----");
439 if (!gEventSources
) LogMsgNoIdent("<None>");
442 KQSocketEventSource
*k
;
443 for (k
= gEventSources
; k
; k
=k
->next
)
444 LogMsgNoIdent("%3d %s %s", k
->fd
, k
->kqs
.KQtask
, k
->fd
== mDNSStorage
.uds_listener_skt
? "Listener for incoming UDS clients" : " ");
447 LogMsgNoIdent("------ Network Interfaces ------");
448 if (!mDNSStorage
.p
->InterfaceList
) LogMsgNoIdent("<None>");
451 for (i
= mDNSStorage
.p
->InterfaceList
; i
; i
= i
->next
)
453 // Allow six characters for interface name, for names like "vmnet8"
455 LogMsgNoIdent("%p %2ld, Registered %p, %s %-6s(%lu) %.6a %.6a %#-14a dormant for %d seconds",
456 i
, i
->ifinfo
.InterfaceID
, i
->Registered
,
457 i
->sa_family
== AF_INET
? "v4" : i
->sa_family
== AF_INET6
? "v6" : "??", i
->ifinfo
.ifname
, i
->scope_id
, &i
->ifinfo
.MAC
, &i
->BSSID
,
458 &i
->ifinfo
.ip
, utc
- i
->LastSeen
);
461 const CacheRecord
*sps
[3];
462 FindSPSInCache(&mDNSStorage
, &i
->ifinfo
.NetWakeBrowse
, sps
);
463 LogMsgNoIdent("%p %2ld, Registered %p, %s %-6s(%lu) %.6a %.6a %s %s %-15.4a %s %s %s %s %#a",
464 i
, i
->ifinfo
.InterfaceID
, i
->Registered
,
465 i
->sa_family
== AF_INET
? "v4" : i
->sa_family
== AF_INET6
? "v6" : "??", i
->ifinfo
.ifname
, i
->scope_id
, &i
->ifinfo
.MAC
, &i
->BSSID
,
466 i
->ifinfo
.InterfaceActive
? "Active" : " ",
467 i
->ifinfo
.IPv4Available
? "v4" : " ",
468 i
->ifinfo
.IPv4Available
? (mDNSv4Addr
*)&i
->ifa_v4addr
: &zerov4Addr
,
469 i
->ifinfo
.IPv6Available
? "v6" : " ",
470 i
->ifinfo
.Advertise
? "A" : " ",
471 i
->ifinfo
.McastTxRx
? "M" : " ",
472 !(i
->ifinfo
.InterfaceActive
&& i
->ifinfo
.NetWake
) ? " " : !sps
[0] ? "p" : "P",
475 if (sps
[0]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[0]->resrec
.rdata
->u
.name
.c
), sps
[0]->resrec
.rdata
->u
.name
.c
);
476 if (sps
[1]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[1]->resrec
.rdata
->u
.name
.c
), sps
[1]->resrec
.rdata
->u
.name
.c
);
477 if (sps
[2]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps
[2]->resrec
.rdata
->u
.name
.c
), sps
[2]->resrec
.rdata
->u
.name
.c
);
482 LogMsgNoIdent("--------- DNS Servers(%d) ----------", NumUnicastDNSServers
);
483 if (!mDNSStorage
.DNSServers
) LogMsgNoIdent("<None>");
486 for (s
= mDNSStorage
.DNSServers
; s
; s
= s
->next
)
488 NetworkInterfaceInfoOSX
*ifx
= IfindexToInterfaceInfoOSX(&mDNSStorage
, s
->interface
);
489 LogMsgNoIdent("DNS Server %##s %s%s%#a:%d %d %s %d %d %s %s %s %s",
490 s
->domain
.c
, ifx
? ifx
->ifinfo
.ifname
: "", ifx
? " " : "", &s
->addr
, mDNSVal16(s
->port
),
491 s
->penaltyTime
? s
->penaltyTime
- mDNS_TimeNow(&mDNSStorage
) : 0, DNSScopeToString(s
->scoped
),
492 s
->timeout
, s
->resGroupID
,
493 s
->req_A
? "v4" : "!v4",
494 s
->req_AAAA
? "v6" : "!v6",
495 s
->cellIntf
? "cell" : "!cell",
496 s
->DNSSECAware
? "DNSSECAware" : "!DNSSECAware");
500 LogMsgNoIdent("v4answers %d", mDNSStorage
.p
->v4answers
);
501 LogMsgNoIdent("v6answers %d", mDNSStorage
.p
->v6answers
);
502 LogMsgNoIdent("Last DNS Trigger: %d ms ago", (now
- mDNSStorage
.p
->DNSTrigger
));
504 LogMsgNoIdent("--------- Mcast Resolvers ----------");
505 if (!mDNSStorage
.McastResolvers
) LogMsgNoIdent("<None>");
508 for (mr
= mDNSStorage
.McastResolvers
; mr
; mr
= mr
->next
)
509 LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr
->domain
.c
, mr
->timeout
);
512 LogMsgNoIdent("------------ Hostnames -------------");
513 if (!mDNSStorage
.Hostnames
) LogMsgNoIdent("<None>");
517 for (hi
= mDNSStorage
.Hostnames
; hi
; hi
= hi
->next
)
519 LogMsgNoIdent("%##s v4 %d %s", hi
->fqdn
.c
, hi
->arv4
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv4
));
520 LogMsgNoIdent("%##s v6 %d %s", hi
->fqdn
.c
, hi
->arv6
.state
, ARDisplayString(&mDNSStorage
, &hi
->arv6
));
524 LogMsgNoIdent("--------------- FQDN ---------------");
525 if (!mDNSStorage
.FQDN
.c
[0]) LogMsgNoIdent("<None>");
528 LogMsgNoIdent("%##s", mDNSStorage
.FQDN
.c
);
531 #if TARGET_OS_EMBEDDED
534 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32
)now
, now
);
535 LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
539 mDNSexport
void mDNSPlatformLogToFile(int log_level
, const char *buffer
)
542 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in init_logging()");
544 os_log_with_type(log_general
, log_level
, "%s", buffer
);
548 // Writes the state out to the dynamic store and also affects the ASL filter level
549 mDNSexport
void UpdateDebugState()
554 CFMutableDictionaryRef dict
= CFDictionaryCreateMutable(NULL
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
557 LogMsg("UpdateDebugState: Could not create dict");
561 CFNumberRef numOne
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &one
);
564 LogMsg("UpdateDebugState: Could not create CFNumber one");
567 CFNumberRef numZero
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &zero
);
570 LogMsg("UpdateDebugState: Could not create CFNumber zero");
575 if (mDNS_LoggingEnabled
)
576 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numOne
);
578 CFDictionarySetValue(dict
, CFSTR("VerboseLogging"), numZero
);
580 if (mDNS_PacketLoggingEnabled
)
581 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numOne
);
583 CFDictionarySetValue(dict
, CFSTR("PacketLogging"), numZero
);
585 if (mDNS_McastLoggingEnabled
)
586 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numOne
);
588 CFDictionarySetValue(dict
, CFSTR("McastLogging"), numZero
);
590 if (mDNS_McastTracingEnabled
)
591 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numOne
);
593 CFDictionarySetValue(dict
, CFSTR("McastTracing"), numZero
);
597 mDNSDynamicStoreSetConfig(kmDNSDebugState
, mDNSNULL
, dict
);
603 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
605 mDNSlocal
void SignalCallback(CFMachPortRef port
, void *msg
, CFIndex size
, void *info
)
607 (void)port
; // Unused
608 (void)size
; // Unused
609 (void)info
; // Unused
610 mach_msg_header_t
*msg_header
= (mach_msg_header_t
*)msg
;
611 mDNS
*const m
= &mDNSStorage
;
613 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
615 switch(msg_header
->msgh_id
)
621 LogMsg("SIGHUP: Purge cache");
623 FORALL_CACHERECORDS(slot
, cg
, rr
)
625 mDNS_PurgeCacheResourceRecord(m
, rr
);
627 // Restart unicast and multicast queries
628 mDNSCoreRestartQueries(m
);
632 case SIGTERM
: ExitCallback(msg_header
->msgh_id
); break;
633 case SIGINFO
: INFOCallback(); break;
635 #if APPLE_OSX_mDNSResponder
636 mDNS_LoggingEnabled
= 1;
637 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
639 mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
640 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
642 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
644 LogInfo("USR1 Logging Enabled");
647 #if APPLE_OSX_mDNSResponder
648 mDNS_PacketLoggingEnabled
= 1;
649 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
651 mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
652 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
654 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
655 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
658 case SIGPROF
: mDNS_McastLoggingEnabled
= mDNS_McastLoggingEnabled
? mDNSfalse
: mDNStrue
;
659 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled
? "Enabled" : "Disabled");
660 LogMcastStateInfo(m
, mDNSfalse
, mDNStrue
, mDNStrue
);
661 mDNS_McastTracingEnabled
= (mDNS_PacketLoggingEnabled
&& mDNS_McastLoggingEnabled
) ? mDNStrue
: mDNSfalse
;
662 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled
? "Enabled" : "Disabled");
665 case SIGTSTP
: mDNS_LoggingEnabled
= mDNS_PacketLoggingEnabled
= mDNS_McastLoggingEnabled
= mDNS_McastTracingEnabled
= mDNSfalse
;
666 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
670 default: LogMsg("SignalCallback: Unknown signal %d", msg_header
->msgh_id
); break;
672 KQueueUnlock(m
, "Unix Signal");
675 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
676 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
680 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
681 rrcachestorage
, RR_CACHE_SIZE
,
682 !NoMulticastAdvertisements
,
683 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
687 LogMsg("Daemon start: mDNS_Init failed %d", err
);
691 CFMachPortRef i_port
= CFMachPortCreate(NULL
, SignalCallback
, NULL
, NULL
);
692 CFRunLoopSourceRef i_rls
= CFMachPortCreateRunLoopSource(NULL
, i_port
, 0);
693 signal_port
= CFMachPortGetPort(i_port
);
694 CFRunLoopAddSource(CFRunLoopGetMain(), i_rls
, kCFRunLoopDefaultMode
);
700 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
702 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
703 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
704 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
705 // of code from above. Alternatively we could remove the duplicated source code by having
706 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
708 mDNSlocal
void SignalDispatch(dispatch_source_t source
)
710 int sig
= (int)dispatch_source_get_handle(source
);
711 mDNS
*const m
= &mDNSStorage
;
719 LogMsg("SIGHUP: Purge cache");
721 FORALL_CACHERECORDS(slot
, cg
, rr
)
723 mDNS_PurgeCacheResourceRecord(m
, rr
);
725 // Restart unicast and multicast queries
726 mDNSCoreRestartQueries(m
);
730 case SIGTERM
: ExitCallback(sig
); break;
731 case SIGINFO
: INFOCallback(); break;
732 case SIGUSR1
: mDNS_LoggingEnabled
= mDNS_LoggingEnabled
? 0 : 1;
733 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled
? "Enabled" : "Disabled");
734 WatchDogReportingThreshold
= mDNS_LoggingEnabled
? 50 : 250;
737 case SIGUSR2
: mDNS_PacketLoggingEnabled
= mDNS_PacketLoggingEnabled
? 0 : 1;
738 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled
? "Enabled" : "Disabled");
741 default: LogMsg("SignalCallback: Unknown signal %d", sig
); break;
743 KQueueUnlock(m
, "Unix Signal");
746 mDNSlocal
void mDNSSetupSignal(dispatch_queue_t queue
, int sig
)
748 signal(sig
, SIG_IGN
);
749 dispatch_source_t source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL
, sig
, 0, queue
);
753 dispatch_source_set_event_handler(source
, ^{SignalDispatch(source
);});
754 // Start processing signals
755 dispatch_resume(source
);
759 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig
);
763 mDNSlocal kern_return_t
mDNSDaemonInitialize(void)
766 dispatch_queue_t queue
= dispatch_get_main_queue();
768 err
= mDNS_Init(&mDNSStorage
, &PlatformStorage
,
769 rrcachestorage
, RR_CACHE_SIZE
,
770 !NoMulticastAdvertisements
,
771 mDNS_StatusCallback
, mDNS_Init_NoInitCallbackContext
);
775 LogMsg("Daemon start: mDNS_Init failed %d", err
);
779 mDNSSetupSignal(queue
, SIGHUP
);
780 mDNSSetupSignal(queue
, SIGINT
);
781 mDNSSetupSignal(queue
, SIGTERM
);
782 mDNSSetupSignal(queue
, SIGINFO
);
783 mDNSSetupSignal(queue
, SIGUSR1
);
784 mDNSSetupSignal(queue
, SIGUSR2
);
786 // Create a custom handler for doing the housekeeping work. This is either triggered
787 // by the timer or an event source
788 PlatformStorage
.custom
= dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD
, 0, 0, queue
);
789 if (PlatformStorage
.custom
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
790 dispatch_source_set_event_handler(PlatformStorage
.custom
, ^{PrepareForIdle(&mDNSStorage
);});
791 dispatch_resume(PlatformStorage
.custom
);
793 // Create a timer source to trigger housekeeping work. The houskeeping work itself
794 // is done in the custom handler that we set below.
796 PlatformStorage
.timer
= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER
, 0, 0, queue
);
797 if (PlatformStorage
.timer
== mDNSNULL
) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
799 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
800 // always reset the time to the new time computed. In effect, we ignore the interval
801 dispatch_source_set_timer(PlatformStorage
.timer
, DISPATCH_TIME_NOW
, 1000ull * 1000000000, 0);
802 dispatch_source_set_event_handler(PlatformStorage
.timer
, ^{
803 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
805 dispatch_resume(PlatformStorage
.timer
);
807 LogMsg("DaemonIntialize done successfully");
812 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
814 mDNSlocal mDNSs32
mDNSDaemonIdle(mDNS
*const m
)
816 mDNSs32 now
= mDNS_TimeNow(m
);
818 // 1. If we need to set domain secrets, do so before handling the network change
820 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
821 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
822 if (m
->p
->KeyChainTimer
&& now
- m
->p
->KeyChainTimer
>= 0)
824 m
->p
->KeyChainTimer
= 0;
830 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
832 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
833 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
834 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
835 // we then systematically lose our own looped-back packets.
836 if (m
->NetworkChanged
&& now
- m
->NetworkChanged
>= 0) mDNSMacOSXNetworkChanged(m
);
838 if (m
->p
->RequestReSleep
&& now
- m
->p
->RequestReSleep
>= 0)
840 m
->p
->RequestReSleep
= 0;
841 mDNSPowerRequest(0, 0);
844 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
845 mDNSs32 nextevent
= mDNS_Execute(m
);
847 if (m
->NetworkChanged
)
848 if (nextevent
- m
->NetworkChanged
> 0)
849 nextevent
= m
->NetworkChanged
;
851 if (m
->p
->KeyChainTimer
)
852 if (nextevent
- m
->p
->KeyChainTimer
> 0)
853 nextevent
= m
->p
->KeyChainTimer
;
855 if (m
->p
->RequestReSleep
)
856 if (nextevent
- m
->p
->RequestReSleep
> 0)
857 nextevent
= m
->p
->RequestReSleep
;
860 if (m
->p
->NotifyUser
)
862 if (m
->p
->NotifyUser
- now
< 0)
864 if (!SameDomainLabelCS(m
->p
->usernicelabel
.c
, m
->nicelabel
.c
))
866 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m
->p
->usernicelabel
.c
, m
->nicelabel
.c
);
867 mDNSPreferencesSetNames(m
, kmDNSComputerName
, &m
->p
->usernicelabel
, &m
->nicelabel
);
868 m
->p
->usernicelabel
= m
->nicelabel
;
870 if (!SameDomainLabelCS(m
->p
->userhostlabel
.c
, m
->hostlabel
.c
))
872 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m
->p
->userhostlabel
.c
, m
->hostlabel
.c
);
873 mDNSPreferencesSetNames(m
, kmDNSLocalHostName
, &m
->p
->userhostlabel
, &m
->hostlabel
);
874 m
->p
->HostNameConflict
= 0; // Clear our indicator, now name change has been successful
875 m
->p
->userhostlabel
= m
->hostlabel
;
877 m
->p
->NotifyUser
= 0;
880 if (nextevent
- m
->p
->NotifyUser
> 0)
881 nextevent
= m
->p
->NotifyUser
;
887 // Right now we consider *ALL* of our DHCP leases
888 // It might make sense to be a bit more selective and only consider the leases on interfaces
889 // (a) that are capable and enabled for wake-on-LAN, and
890 // (b) where we have found (and successfully registered with) a Sleep Proxy
891 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
892 mDNSlocal mDNSu32
DHCPWakeTime(void)
894 mDNSu32 e
= 24 * 3600; // Maximum maintenance wake interval is 24 hours
895 const CFAbsoluteTime now
= CFAbsoluteTimeGetCurrent();
896 if (!now
) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
901 const void *pattern
= SCDynamicStoreKeyCreateNetworkServiceEntity(NULL
, kSCDynamicStoreDomainState
, kSCCompAnyRegex
, kSCEntNetDHCP
);
904 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
907 CFArrayRef dhcpinfo
= CFArrayCreate(NULL
, (const void **)&pattern
, 1, &kCFTypeArrayCallBacks
);
911 SCDynamicStoreRef store
= SCDynamicStoreCreate(NULL
, CFSTR("DHCP-LEASES"), NULL
, NULL
);
914 CFDictionaryRef dict
= SCDynamicStoreCopyMultiple(store
, NULL
, dhcpinfo
);
917 ic
= CFDictionaryGetCount(dict
);
918 const void *vals
[ic
];
919 CFDictionaryGetKeysAndValues(dict
, NULL
, vals
);
921 for (j
= 0; j
< ic
; j
++)
923 const CFDictionaryRef dhcp
= (CFDictionaryRef
)vals
[j
];
926 const CFDateRef start
= DHCPInfoGetLeaseStartTime(dhcp
);
927 const CFDataRef lease
= DHCPInfoGetOptionData(dhcp
, 51); // Option 51 = IP Address Lease Time
928 if (!start
|| !lease
|| CFDataGetLength(lease
) < 4)
929 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
930 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
931 j
, start
, lease
, lease
? CFDataGetLength(lease
) : 0);
934 const UInt8
*d
= CFDataGetBytePtr(lease
);
935 if (!d
) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j
);
938 const mDNSu32 elapsed
= now
- CFDateGetAbsoluteTime(start
);
939 const mDNSu32 lifetime
= (mDNSs32
) ((mDNSs32
)d
[0] << 24 | (mDNSs32
)d
[1] << 16 | (mDNSs32
)d
[2] << 8 | d
[3]);
940 const mDNSu32 remaining
= lifetime
- elapsed
;
941 const mDNSu32 wake
= remaining
> 60 ? remaining
- remaining
/10 : 54; // Wake at 90% of the lease time
942 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed
, lifetime
, remaining
, wake
);
943 if (e
> wake
) e
= wake
;
958 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
959 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
960 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
961 // for a few seconds and then waking again is silly and annoying.
962 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
963 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
964 // allowing us an adequate safety margin to renew our lease before we lose it.
966 mDNSlocal mDNSBool
AllowSleepNow(mDNS
*const m
, mDNSs32 now
)
968 mDNSBool ready
= mDNSCoreReadyForSleep(m
, now
);
969 if (m
->SleepState
&& !ready
&& now
- m
->SleepLimit
< 0) return(mDNSfalse
);
972 int result
= kIOReturnSuccess
;
973 CFDictionaryRef opts
= NULL
;
975 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
976 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
978 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m
->SleepLimit
- now
);
981 if (!m
->SystemWakeOnLANEnabled
|| !mDNSCoreHaveAdvertisedMulticastServices(m
))
982 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
983 m
->SystemWakeOnLANEnabled
? "is" : "not",
984 mDNSCoreHaveAdvertisedMulticastServices(m
) ? "have" : "no");
987 mDNSs32 dhcp
= DHCPWakeTime();
988 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp
);
989 mDNSs32 interval
= mDNSCoreIntervalToNextWake(m
, now
) / mDNSPlatformOneSecond
;
990 if (interval
> dhcp
) interval
= dhcp
;
992 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
993 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
994 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
995 // someone to go to the machine in person to wake it up again, which would be unacceptable.
996 if (!ready
&& interval
> 3600) interval
= 3600;
998 //interval = 48; // For testing
1000 #if !TARGET_OS_EMBEDDED
1001 #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1002 if (m
->p
->IOPMConnection
) // If lightweight-wake capability is available, use that
1004 const CFDateRef WakeDate
= CFDateCreate(NULL
, CFAbsoluteTimeGetCurrent() + interval
);
1005 if (!WakeDate
) LogMsg("ScheduleNextWake: CFDateCreate failed");
1008 const mDNSs32 reqs
= kIOPMSystemPowerStateCapabilityNetwork
;
1009 const CFNumberRef Requirements
= CFNumberCreate(NULL
, kCFNumberSInt32Type
, &reqs
);
1010 if (!Requirements
) LogMsg("ScheduleNextWake: CFNumberCreate failed");
1013 const void *OptionKeys
[2] = { kIOPMAckDHCPRenewWakeDate
, kIOPMAckSystemCapabilityRequirements
};
1014 const void *OptionVals
[2] = { WakeDate
, Requirements
};
1015 opts
= CFDictionaryCreate(NULL
, (void*)OptionKeys
, (void*)OptionVals
, 2, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1016 if (!opts
) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
1017 CFRelease(Requirements
);
1019 CFRelease(WakeDate
);
1021 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval
);
1023 else // else schedule the wakeup using the old API instead to
1024 #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1025 #endif // TARGET_OS_EMBEDDED
1027 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
1028 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
1029 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
1030 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
1034 result
= mDNSPowerRequest(1, interval
);
1036 if (result
== kIOReturnNotReady
)
1039 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval
);
1040 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
1041 // requested wake time is "too soon", but there's no API to find out what constitutes
1042 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
1043 // we just have to iterate with successively longer intervals until it doesn't fail.
1044 // We preserve the value of "result" because if our original power request was deemed "too soon"
1045 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
1046 // since the implication is that the system won't manage to be awake again at the time we need it.
1049 interval
+= (interval
< 20) ? 1 : ((interval
+3) / 4);
1050 r
= mDNSPowerRequest(1, interval
);
1052 while (r
== kIOReturnNotReady
);
1053 if (r
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, r
, r
);
1054 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval
);
1058 if (result
) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval
, result
, result
);
1059 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval
);
1061 m
->p
->WakeAtUTC
= mDNSPlatformUTC() + interval
;
1065 m
->SleepState
= SleepState_Sleeping
;
1066 // Clear our interface list to empty state, ready to go to sleep
1067 // As a side effect of doing this, we'll also cancel any outstanding SPS Resolve calls that didn't complete
1068 mDNSMacOSXNetworkChanged(m
);
1071 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1072 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1073 (m
->p
->IOPMConnection
) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1075 (result
== kIOReturnSuccess
) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1076 m
->p
->SleepCookie
, ready
? "ready for sleep" : "giving up", now
, m
->SleepLimit
- now
);
1078 m
->SleepLimit
= 0; // Don't clear m->SleepLimit until after we've logged it above
1079 m
->TimeSlept
= mDNSPlatformUTC();
1081 // accumulate total time awake for this statistics gathering interval
1082 if (m
->StatStartTime
)
1084 m
->ActiveStatTime
+= (m
->TimeSlept
- m
->StatStartTime
);
1086 // indicate this value is invalid until reinitialzed on wakeup
1087 m
->StatStartTime
= 0;
1090 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1091 if (m
->p
->IOPMConnection
) IOPMConnectionAcknowledgeEventWithOptions(m
->p
->IOPMConnection
, m
->p
->SleepCookie
, opts
);
1094 if (result
== kIOReturnSuccess
) IOAllowPowerChange (m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1095 else IOCancelPowerChange(m
->p
->PowerConnection
, m
->p
->SleepCookie
);
1097 if (opts
) CFRelease(opts
);
1101 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1103 mDNSexport
void TriggerEventCompletion()
1105 debugf("TriggerEventCompletion: Merge data");
1106 dispatch_source_merge_data(PlatformStorage
.custom
, 1);
1109 mDNSlocal
void PrepareForIdle(void *m_param
)
1112 int64_t time_offset
;
1113 dispatch_time_t dtime
;
1115 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1117 // This is the main work loop:
1118 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1119 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1120 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1122 debugf("PrepareForIdle: called");
1123 // Run mDNS_Execute to find out the time we next need to wake up
1124 mDNSs32 start
= mDNSPlatformRawTime();
1125 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1126 mDNSs32 end
= mDNSPlatformRawTime();
1127 if (end
- start
>= WatchDogReportingThreshold
)
1128 LogInfo("CustomSourceHandler:WARNING: Idle task took %dms to complete", end
- start
);
1130 mDNSs32 now
= mDNS_TimeNow(m
);
1132 if (m
->ShutdownTime
)
1134 if (mDNSStorage
.ResourceRecords
)
1136 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, mDNSStorage
.ResourceRecords
));
1137 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1139 if (mDNS_ExitNow(m
, now
))
1141 LogInfo("IdleLoop: mDNS_FinalExit");
1142 mDNS_FinalExit(&mDNSStorage
);
1143 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1146 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1147 nextTimerEvent
= m
->ShutdownTime
;
1151 if (!AllowSleepNow(m
, now
))
1152 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1153 nextTimerEvent
= m
->SleepLimit
;
1155 // Convert absolute wakeup time to a relative time from now
1156 mDNSs32 ticks
= nextTimerEvent
- now
;
1157 if (ticks
< 1) ticks
= 1;
1159 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1165 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1168 time_offset
= ((mDNSu32
)ticks
/ mDNSPlatformOneSecond
) * 1000000000 + (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1169 dtime
= dispatch_time(DISPATCH_TIME_NOW
, time_offset
);
1170 dispatch_source_set_timer(PlatformStorage
.timer
, dtime
, 1000ull*1000000000, 0);
1171 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks
);
1175 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1177 mDNSlocal
void KQWokenFlushBytes(int fd
, __unused
short filter
, __unused
void *context
)
1179 // Read all of the bytes so we won't wake again.
1181 while (recv(fd
, buffer
, sizeof(buffer
), MSG_DONTWAIT
) > 0) continue;
1184 mDNSlocal
void SetLowWater(const KQSocketSet
*const k
, const int r
)
1186 if (k
->sktv4
>=0 && setsockopt(k
->sktv4
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1187 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k
->sktv4
, r
, errno
, strerror(errno
));
1188 if (k
->sktv6
>=0 && setsockopt(k
->sktv6
, SOL_SOCKET
, SO_RCVLOWAT
, &r
, sizeof(r
)) < 0)
1189 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k
->sktv6
, r
, errno
, strerror(errno
));
1192 mDNSlocal
void * KQueueLoop(void *m_param
)
1197 #if USE_SELECT_WITH_KQUEUEFD
1200 const int multiplier
= 1000000 / mDNSPlatformOneSecond
;
1202 const int multiplier
= 1000000000 / mDNSPlatformOneSecond
;
1205 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1206 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32
)mDNSStorage
.timenow_last
, mDNSStorage
.timenow_last
);
1208 // This is the main work loop:
1209 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1210 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1211 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1212 // (4) On wakeup we first process *all* events
1213 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
1216 #define kEventsToReadAtOnce 1
1217 struct kevent new_events
[kEventsToReadAtOnce
];
1219 // Run mDNS_Execute to find out the time we next need to wake up
1220 mDNSs32 start
= mDNSPlatformRawTime();
1221 mDNSs32 nextTimerEvent
= udsserver_idle(mDNSDaemonIdle(m
));
1222 mDNSs32 end
= mDNSPlatformRawTime();
1223 if (end
- start
>= WatchDogReportingThreshold
)
1224 LogInfo("WARNING: Idle task took %dms to complete", end
- start
);
1226 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
1230 mDNSs32 now
= mDNS_TimeNow(m
);
1232 if (m
->ShutdownTime
)
1234 if (mDNSStorage
.ResourceRecords
)
1237 for (rr
= mDNSStorage
.ResourceRecords
; rr
; rr
=rr
->next
)
1239 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m
, rr
));
1240 if (mDNS_LoggingEnabled
) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1243 if (mDNS_ExitNow(m
, now
))
1245 LogInfo("mDNS_FinalExit");
1246 mDNS_FinalExit(&mDNSStorage
);
1247 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1250 if (nextTimerEvent
- m
->ShutdownTime
>= 0)
1251 nextTimerEvent
= m
->ShutdownTime
;
1255 if (!AllowSleepNow(m
, now
))
1256 if (nextTimerEvent
- m
->SleepLimit
>= 0)
1257 nextTimerEvent
= m
->SleepLimit
;
1259 // Convert absolute wakeup time to a relative time from now
1260 mDNSs32 ticks
= nextTimerEvent
- now
;
1261 if (ticks
< 1) ticks
= 1;
1263 static mDNSs32 RepeatedBusy
= 0; // Debugging sanity check, to guard against CPU spins
1269 if (++RepeatedBusy
>= mDNSPlatformOneSecond
) { ShowTaskSchedulingError(&mDNSStorage
); RepeatedBusy
= 0; }
1272 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents
, ticks
);
1275 // Release the lock, and sleep until:
1276 // 1. Something interesting happens like a packet arriving, or
1277 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
1278 // 3. The timeout expires
1279 pthread_mutex_unlock(&PlatformStorage
.BigMutex
);
1281 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1282 if (m
->p
->num_mcasts
)
1284 SetLowWater(&m
->p
->permanentsockets
, 0x10000);
1285 if (ticks
> mDNSPlatformOneSecond
/ 8) ticks
= mDNSPlatformOneSecond
/ 8;
1288 #if USE_SELECT_WITH_KQUEUEFD
1289 struct timeval timeout
;
1290 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1291 timeout
.tv_usec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1292 FD_SET(KQueueFD
, &readfds
);
1293 if (select(KQueueFD
+1, &readfds
, NULL
, NULL
, &timeout
) < 0)
1294 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1296 struct timespec timeout
;
1297 timeout
.tv_sec
= ticks
/ mDNSPlatformOneSecond
;
1298 timeout
.tv_nsec
= (ticks
% mDNSPlatformOneSecond
) * multiplier
;
1299 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
1300 // and have it work similarly to the way it does with nevents non-zero --
1301 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
1302 // In fact, what happens if you do this is that it just returns immediately. So, we have
1303 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
1304 if (kevent(KQueueFD
, NULL
, 0, new_events
, 1, &timeout
) < 0)
1305 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD
, errno
, strerror(errno
)); sleep(1); }
1308 pthread_mutex_lock(&PlatformStorage
.BigMutex
);
1309 // We have to ignore the event we may have been told about above, because that
1310 // was done without holding the lock, and between the time we woke up and the
1311 // time we reclaimed the lock the other thread could have done something that
1312 // makes the event no longer valid. Now we have the lock, we call kevent again
1313 // and this time we can safely process the events it tells us about.
1315 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
1316 if (m
->p
->num_mcasts
)
1318 SetLowWater(&m
->p
->permanentsockets
, 1);
1319 m
->p
->num_mcasts
= 0;
1322 static const struct timespec zero_timeout
= { 0, 0 };
1324 while ((events_found
= kevent(KQueueFD
, NULL
, 0, new_events
, kEventsToReadAtOnce
, &zero_timeout
)) != 0)
1326 if (events_found
> kEventsToReadAtOnce
|| (events_found
< 0 && errno
!= EINTR
))
1328 // Not sure what to do here, our kqueue has failed us - this isn't ideal
1329 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", errno
, strerror(errno
));
1333 numevents
+= events_found
;
1336 for (i
= 0; i
< events_found
; i
++)
1338 const KQueueEntry
*const kqentry
= new_events
[i
].udata
;
1339 mDNSs32 stime
= mDNSPlatformRawTime();
1340 const char *const KQtask
= kqentry
->KQtask
; // Grab a copy in case KQcallback deletes the task
1341 kqentry
->KQcallback(new_events
[i
].ident
, new_events
[i
].filter
, kqentry
->KQcontext
);
1342 mDNSs32 etime
= mDNSPlatformRawTime();
1343 if (etime
- stime
>= WatchDogReportingThreshold
)
1344 LogInfo("WARNING: %s took %dms to complete", KQtask
, etime
- stime
);
1352 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1354 mDNSlocal
size_t LaunchdCheckin(void)
1356 // Ask launchd for our socket
1357 int result
= launch_activate_socket("Listeners", &launchd_fds
, &launchd_fds_count
);
1358 if (result
!= 0) { LogMsg("launch_activate_socket() failed errno %d (%s)", errno
, strerror(errno
)); }
1359 return launchd_fds_count
;
1363 extern int sandbox_init(const char *profile
, uint64_t flags
, char **errorbuf
) __attribute__((weak_import
));
1365 #if APPLE_OSX_mDNSResponder
1366 mDNSlocal mDNSBool
PreferencesGetValueBool(CFStringRef key
, mDNSBool defaultValue
)
1368 CFBooleanRef boolean
;
1369 mDNSBool result
= defaultValue
;
1371 boolean
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1374 if (CFGetTypeID(boolean
) == CFBooleanGetTypeID())
1375 result
= CFBooleanGetValue(boolean
) ? mDNStrue
: mDNSfalse
;
1382 mDNSlocal
int PreferencesGetValueInt(CFStringRef key
, int defaultValue
)
1386 int result
= defaultValue
;
1388 number
= CFPreferencesCopyAppValue(key
, kProgramArguments
);
1391 if ((CFGetTypeID(number
) == CFNumberGetTypeID()) && CFNumberGetValue(number
, kCFNumberIntType
, &numberValue
))
1392 result
= numberValue
;
1400 mDNSlocal
void SandboxProcess(void)
1402 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1404 LogMsg("Note: Compiled without Apple Sandbox support");
1405 #else // MDNS_NO_SANDBOX
1407 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1411 uint64_t sandbox_flags
= SANDBOX_NAMED
;
1413 (void)confstr(_CS_DARWIN_USER_CACHE_DIR
, NULL
, 0);
1415 int sandbox_err
= sandbox_init("mDNSResponder", sandbox_flags
, &sandbox_msg
);
1418 LogMsg("WARNING: sandbox_init error %s", sandbox_msg
);
1419 // If we have errors in the sandbox during development, to prevent
1420 // exiting, uncomment the following line.
1421 //sandbox_free_error(sandbox_msg);
1423 errx(EX_OSERR
, "sandbox_init() failed: %s", sandbox_msg
);
1425 else LogInfo("Now running under Apple Sandbox restrictions");
1427 #endif // MDNS_NO_SANDBOX
1430 #if APPLE_OSX_mDNSResponder
1431 mDNSlocal
void init_logging(void)
1433 log_general
= os_log_create("com.apple.mDNSResponder", "AllINFO");
1437 // OS_LOG_DEFAULT is the default logging object, if you are not creating a custom subsystem/category
1438 os_log_error(OS_LOG_DEFAULT
, "Could NOT create log handle in mDNSResponder");
1443 mDNSexport
int main(int argc
, char **argv
)
1446 kern_return_t status
;
1449 bool useDebugSocket
= mDNSfalse
;
1450 bool useSandbox
= mDNStrue
;
1453 #if APPLE_OSX_mDNSResponder
1457 mDNSMacOSXSystemBuildNumber(NULL
);
1458 LogMsg("%s starting %s %d", mDNSResponderVersionString
, OSXVers
? "OSXVers" : "iOSVers", OSXVers
? OSXVers
: iOSVers
);
1461 LogMsg("CacheRecord %5d", sizeof(CacheRecord
));
1462 LogMsg("CacheGroup %5d", sizeof(CacheGroup
));
1463 LogMsg("ResourceRecord %5d", sizeof(ResourceRecord
));
1464 LogMsg("RData_small %5d", sizeof(RData_small
));
1466 LogMsg("sizeof(CacheEntity) %5d", sizeof(CacheEntity
));
1467 LogMsg("RR_CACHE_SIZE %5d", RR_CACHE_SIZE
);
1468 LogMsg("block bytes used %5d", sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1469 LogMsg("block bytes wasted %5d", 32*1024 - sizeof(CacheEntity
) * RR_CACHE_SIZE
);
1474 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1478 for (i
=1; i
<argc
; i
++)
1480 if (!strcasecmp(argv
[i
], "-d" )) mDNS_DebugMode
= mDNStrue
;
1481 if (!strcasecmp(argv
[i
], "-NoMulticastAdvertisements")) NoMulticastAdvertisements
= mDNStrue
;
1482 if (!strcasecmp(argv
[i
], "-DisableSleepProxyClient" )) DisableSleepProxyClient
= mDNStrue
;
1483 if (!strcasecmp(argv
[i
], "-DebugLogging" )) mDNS_LoggingEnabled
= mDNStrue
;
1484 if (!strcasecmp(argv
[i
], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled
= mDNStrue
;
1485 if (!strcasecmp(argv
[i
], "-OfferSleepProxyService" ))
1486 OfferSleepProxyService
= (i
+1 < argc
&& mDNSIsDigit(argv
[i
+1][0]) && mDNSIsDigit(argv
[i
+1][1]) && argv
[i
+1][2]==0) ? atoi(argv
[++i
]) : 100;
1487 if (!strcasecmp(argv
[i
], "-UseInternalSleepProxy" ))
1488 UseInternalSleepProxy
= (i
+1<argc
&& mDNSIsDigit(argv
[i
+1][0]) && argv
[i
+1][1]==0) ? atoi(argv
[++i
]) : 1;
1489 if (!strcasecmp(argv
[i
], "-StrictUnicastOrdering" )) StrictUnicastOrdering
= mDNStrue
;
1490 if (!strcasecmp(argv
[i
], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains
= mDNStrue
;
1492 if (!strcasecmp(argv
[i
], "-UseDebugSocket")) useDebugSocket
= mDNStrue
;
1493 if (!strcasecmp(argv
[i
], "-NoSandbox")) useSandbox
= mDNSfalse
;
1498 #if APPLE_OSX_mDNSResponder
1499 /* Reads the external user's program arguments for mDNSResponder starting 10.11.x(El Capitan) on OSX. The options for external user are:
1500 DebugLogging, UnicastPacketLogging, NoMulticastAdvertisements, StrictUnicastOrdering and AlwaysAppendSearchDomains
1502 To turn ON the particular option, here is what the user should do (as an example of setting two options)
1503 1] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool YES
1504 2] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
1507 To turn OFF all options, here is what the user should do
1508 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1511 To view the current options set, here is what the user should do
1512 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1514 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
1518 // Currently on Fuji/Whitetail releases we are keeping the logging always enabled.
1519 // Hence mDNS_LoggingEnabled and mDNS_PacketLoggingEnabled is set to true below by default.
1521 mDNS_LoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_DebugLogging
, mDNS_LoggingEnabled
);
1522 mDNS_PacketLoggingEnabled
= PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging
, mDNS_PacketLoggingEnabled
);
1525 mDNS_LoggingEnabled
= mDNStrue
;
1526 mDNS_PacketLoggingEnabled
= mDNStrue
;
1528 NoMulticastAdvertisements
= PreferencesGetValueBool(kPreferencesKey_NoMulticastAdvertisements
, NoMulticastAdvertisements
);
1529 StrictUnicastOrdering
= PreferencesGetValueBool(kPreferencesKey_StrictUnicastOrdering
, StrictUnicastOrdering
);
1530 AlwaysAppendSearchDomains
= PreferencesGetValueBool(kPreferencesKey_AlwaysAppendSearchDomains
, AlwaysAppendSearchDomains
);
1531 OfferSleepProxyService
= PreferencesGetValueInt(kPreferencesKey_OfferSleepProxyService
, OfferSleepProxyService
);
1532 UseInternalSleepProxy
= PreferencesGetValueInt(kPreferencesKey_UseInternalSleepProxy
, UseInternalSleepProxy
);
1533 EnableBLEBasedDiscovery
= PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery
, EnableBLEBasedDiscovery
);
1536 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
1537 if (NoMulticastAdvertisements
)
1538 LogMsg("-NoMulticastAdvertisements is set: Administratively prohibiting multicast advertisements");
1539 if (AlwaysAppendSearchDomains
)
1540 LogMsg("-AlwaysAppendSearchDomains is set");
1541 if (StrictUnicastOrdering
)
1542 LogMsg("-StrictUnicastOrdering is set");
1544 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1546 signal(SIGHUP
, HandleSIG
); // (Debugging) Purge the cache to check for cache handling bugs
1547 signal(SIGINT
, HandleSIG
); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
1548 signal(SIGPIPE
, SIG_IGN
); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
1549 signal(SIGTERM
, HandleSIG
); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
1550 signal(SIGINFO
, HandleSIG
); // (Debugging) Write state snapshot to syslog
1551 signal(SIGUSR1
, HandleSIG
); // (Debugging) Enable Logging
1552 signal(SIGUSR2
, HandleSIG
); // (Debugging) Enable Packet Logging
1553 signal(SIGPROF
, HandleSIG
); // (Debugging) Toggle Multicast Logging
1554 signal(SIGTSTP
, HandleSIG
); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
1556 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1558 mDNSStorage
.p
= &PlatformStorage
; // Make sure mDNSStorage.p is set up, because validatelists uses it
1559 // Need to Start XPC Server Before LaunchdCheckin() (Reason: rdar11023750)
1562 if (!useDebugSocket
) {
1563 if (LaunchdCheckin() == 0)
1564 useDebugSocket
= mDNStrue
;
1567 SetDebugBoundPath();
1572 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1574 // Create the kqueue, mutex and thread to support KQSockets
1575 KQueueFD
= kqueue();
1576 if (KQueueFD
== -1) { LogMsg("kqueue() failed errno %d (%s)", errno
, strerror(errno
)); status
= errno
; goto exit
; }
1578 i
= pthread_mutex_init(&PlatformStorage
.BigMutex
, NULL
);
1579 if (i
== -1) { LogMsg("pthread_mutex_init() failed errno %d (%s)", errno
, strerror(errno
)); status
= errno
; goto exit
; }
1581 int fdpair
[2] = {0, 0};
1582 i
= socketpair(AF_UNIX
, SOCK_STREAM
, 0, fdpair
);
1583 if (i
== -1) { LogMsg("socketpair() failed errno %d (%s)", errno
, strerror(errno
)); status
= errno
; goto exit
; }
1585 // Socket pair returned us two identical sockets connected to each other
1586 // We will use the first socket to send the second socket. The second socket
1587 // will be added to the kqueue so it will wake when data is sent.
1588 static const KQueueEntry wakeKQEntry
= { KQWokenFlushBytes
, NULL
, "kqueue wakeup after CFRunLoop event" };
1590 PlatformStorage
.WakeKQueueLoopFD
= fdpair
[0];
1591 KQueueSet(fdpair
[1], EV_ADD
, EVFILT_READ
, &wakeKQEntry
);
1593 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1600 #if TARGET_OS_EMBEDDED
1601 status
= MetricsInit();
1602 if (status
) { LogMsg("Daemon start: MetricsInit failed (%d)", status
); }
1605 status
= mDNSDaemonInitialize();
1606 if (status
) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit
; }
1608 status
= udsserver_init(launchd_fds
, launchd_fds_count
);
1609 if (status
) { LogMsg("Daemon start: udsserver_init failed"); goto exit
; }
1611 mDNSMacOSXNetworkChanged(&mDNSStorage
);
1614 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1615 LogInfo("Daemon Start: Using LibDispatch");
1616 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
1618 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1619 // Start the kqueue thread
1620 pthread_t KQueueThread
;
1621 i
= pthread_create(&KQueueThread
, NULL
, KQueueLoop
, &mDNSStorage
);
1622 if (i
== -1) { LogMsg("pthread_create() failed errno %d (%s)", errno
, strerror(errno
)); status
= errno
; goto exit
; }
1626 LogMsg("ERROR: CFRunLoopRun Exiting.");
1627 mDNS_Close(&mDNSStorage
);
1629 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1631 LogMsg("%s exiting", mDNSResponderVersionString
);
1637 // uds_daemon.c support routines /////////////////////////////////////////////
1639 // Arrange things so that when data appears on fd, callback is called with context
1640 mDNSexport mStatus
udsSupportAddFDToEventLoop(int fd
, udsEventCallback callback
, void *context
, void **platform_data
)
1642 KQSocketEventSource
**p
= &gEventSources
;
1643 (void) platform_data
;
1644 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1645 if (*p
) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd
); return mStatus_AlreadyRegistered
; }
1647 KQSocketEventSource
*newSource
= (KQSocketEventSource
*) mallocL("KQSocketEventSource", sizeof *newSource
);
1648 if (!newSource
) return mStatus_NoMemoryErr
;
1650 newSource
->next
= mDNSNULL
;
1652 newSource
->kqs
.KQcallback
= callback
;
1653 newSource
->kqs
.KQcontext
= context
;
1654 newSource
->kqs
.KQtask
= "UDS client";
1655 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1656 newSource
->kqs
.readSource
= mDNSNULL
;
1657 newSource
->kqs
.writeSource
= mDNSNULL
;
1658 newSource
->kqs
.fdClosed
= mDNSfalse
;
1659 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1661 if (KQueueSet(fd
, EV_ADD
, EVFILT_READ
, &newSource
->kqs
) == 0)
1664 return mStatus_NoError
;
1667 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd
, errno
, strerror(errno
));
1668 freeL("KQSocketEventSource", newSource
);
1669 return mStatus_BadParamErr
;
1672 int udsSupportReadFD(dnssd_sock_t fd
, char *buf
, int len
, int flags
, void *platform_data
)
1674 (void) platform_data
;
1675 return recv(fd
, buf
, len
, flags
);
1678 mDNSexport mStatus
udsSupportRemoveFDFromEventLoop(int fd
, void *platform_data
) // Note: This also CLOSES the file descriptor
1680 KQSocketEventSource
**p
= &gEventSources
;
1681 (void) platform_data
;
1682 while (*p
&& (*p
)->fd
!= fd
) p
= &(*p
)->next
;
1685 KQSocketEventSource
*s
= *p
;
1687 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
1688 // causes the kernel to automatically remove any associated kevents
1689 mDNSPlatformCloseFD(&s
->kqs
, s
->fd
);
1690 freeL("KQSocketEventSource", s
);
1691 return mStatus_NoError
;
1693 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd
);
1694 return mStatus_NoSuchNameErr
;
1697 #if _BUILDING_XCODE_PROJECT_
1698 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
1699 const char *__crashreporter_info__
= mDNSResponderVersionString
;
1700 asm (".desc ___crashreporter_info__, 0x10");
1703 // For convenience when using the "strings" command, this is the last thing in the file
1704 // The "@(#) " pattern is a special prefix the "what" command looks for
1705 mDNSexport
const char mDNSResponderVersionString_SCCS
[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion
) " (" __DATE__
" " __TIME__
")";