1 | /* -*- Mode: C; tab-width: 4 -*- |
---|
2 | * |
---|
3 | * Copyright (c) 2002-2015 Apple Inc. All rights reserved. |
---|
4 | * |
---|
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 |
---|
8 | * |
---|
9 | * http://www.apache.org/licenses/LICENSE-2.0 |
---|
10 | * |
---|
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. |
---|
16 | */ |
---|
17 | |
---|
18 | #include <mach/mach.h> |
---|
19 | #include <mach/mach_error.h> |
---|
20 | #include <sys/types.h> |
---|
21 | #include <errno.h> |
---|
22 | #include <signal.h> |
---|
23 | #include <unistd.h> |
---|
24 | #include <paths.h> |
---|
25 | #include <fcntl.h> |
---|
26 | #include <launch.h> |
---|
27 | #include <launch_priv.h> // for launch_socket_service_check_in() |
---|
28 | #include <pwd.h> |
---|
29 | #include <sys/event.h> |
---|
30 | #include <pthread.h> |
---|
31 | #include <sandbox.h> |
---|
32 | #include <SystemConfiguration/SCDynamicStoreCopyDHCPInfo.h> |
---|
33 | #include <err.h> |
---|
34 | #include <sysexits.h> |
---|
35 | #include <dlfcn.h> |
---|
36 | |
---|
37 | #include "uDNS.h" |
---|
38 | #include "DNSCommon.h" |
---|
39 | #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform |
---|
40 | |
---|
41 | #include "uds_daemon.h" // Interface to the server side implementation of dns_sd.h |
---|
42 | #include "xpc_services.h" // Interface to XPC services |
---|
43 | #include "helper.h" |
---|
44 | |
---|
45 | #if TARGET_OS_EMBEDDED |
---|
46 | #include "Metrics.h" |
---|
47 | #endif |
---|
48 | |
---|
49 | #if APPLE_OSX_mDNSResponder |
---|
50 | static os_log_t log_general = NULL; |
---|
51 | #endif |
---|
52 | |
---|
53 | |
---|
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") |
---|
67 | #endif |
---|
68 | |
---|
69 | //************************************************************************************************************* |
---|
70 | #if COMPILER_LIKES_PRAGMA_MARK |
---|
71 | #pragma mark - Globals |
---|
72 | #endif |
---|
73 | |
---|
74 | static mDNS_PlatformSupport PlatformStorage; |
---|
75 | |
---|
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]; }; |
---|
83 | |
---|
84 | |
---|
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 |
---|
90 | |
---|
91 | static dnssd_sock_t *launchd_fds = mDNSNULL; |
---|
92 | static size_t launchd_fds_count = 0; |
---|
93 | |
---|
94 | static mDNSBool NoMulticastAdvertisements = mDNSfalse; // By default, advertise addresses (& other records) via multicast |
---|
95 | |
---|
96 | extern mDNSBool StrictUnicastOrdering; |
---|
97 | extern mDNSBool AlwaysAppendSearchDomains; |
---|
98 | extern mDNSBool EnableBLEBasedDiscovery; |
---|
99 | |
---|
100 | // We keep a list of client-supplied event sources in KQSocketEventSource records |
---|
101 | typedef struct KQSocketEventSource |
---|
102 | { |
---|
103 | struct KQSocketEventSource *next; |
---|
104 | int fd; |
---|
105 | KQueueEntry kqs; |
---|
106 | } KQSocketEventSource; |
---|
107 | |
---|
108 | static KQSocketEventSource *gEventSources; |
---|
109 | |
---|
110 | //************************************************************************************************************* |
---|
111 | #if COMPILER_LIKES_PRAGMA_MARK |
---|
112 | #pragma mark - |
---|
113 | #pragma mark - General Utility Functions |
---|
114 | #endif |
---|
115 | |
---|
116 | #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING |
---|
117 | |
---|
118 | char _malloc_options[] = "AXZ"; |
---|
119 | |
---|
120 | mDNSlocal void validatelists(mDNS *const m) |
---|
121 | { |
---|
122 | #if BONJOUR_ON_DEMAND |
---|
123 | mDNSu32 NumAllInterfaceRecords = 0; |
---|
124 | mDNSu32 NumAllInterfaceQuestions = 0; |
---|
125 | #endif // BONJOUR_ON_DEMAND |
---|
126 | |
---|
127 | // Check local lists |
---|
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); |
---|
132 | |
---|
133 | // Check Unix Domain Socket client lists (uds_daemon.c) |
---|
134 | uds_validatelists(); |
---|
135 | |
---|
136 | // Check core mDNS lists |
---|
137 | AuthRecord *rr; |
---|
138 | for (rr = m->ResourceRecords; rr; rr=rr->next) |
---|
139 | { |
---|
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 |
---|
148 | } |
---|
149 | |
---|
150 | for (rr = m->DuplicateRecords; rr; rr=rr->next) |
---|
151 | { |
---|
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 |
---|
157 | } |
---|
158 | |
---|
159 | rr = m->NewLocalRecords; |
---|
160 | if (rr) |
---|
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); |
---|
163 | |
---|
164 | rr = m->CurrentRecord; |
---|
165 | if (rr) |
---|
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); |
---|
168 | |
---|
169 | DNSQuestion *q; |
---|
170 | for (q = m->Questions; q; q=q->next) |
---|
171 | { |
---|
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 |
---|
180 | } |
---|
181 | |
---|
182 | CacheGroup *cg; |
---|
183 | CacheRecord *cr; |
---|
184 | mDNSu32 slot; |
---|
185 | FORALL_CACHERECORDS(slot, cg, cr) |
---|
186 | { |
---|
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) |
---|
190 | { |
---|
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)); |
---|
193 | } |
---|
194 | } |
---|
195 | |
---|
196 | // Check core uDNS lists |
---|
197 | udns_validatelists(m); |
---|
198 | |
---|
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); |
---|
204 | |
---|
205 | ClientTunnel *t; |
---|
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]); |
---|
209 | |
---|
210 | #if BONJOUR_ON_DEMAND |
---|
211 | if (m->NumAllInterfaceRecords != NumAllInterfaceRecords) |
---|
212 | LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m->NumAllInterfaceRecords, NumAllInterfaceRecords); |
---|
213 | |
---|
214 | if (m->NumAllInterfaceQuestions != NumAllInterfaceQuestions) |
---|
215 | LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m->NumAllInterfaceQuestions, NumAllInterfaceQuestions); |
---|
216 | #endif // BONJOUR_ON_DEMAND |
---|
217 | } |
---|
218 | |
---|
219 | mDNSexport void *mallocL(char *msg, unsigned int size) |
---|
220 | { |
---|
221 | // Allocate space for two words of sanity checking data before the requested block |
---|
222 | mDNSu32 *mem = malloc(sizeof(mDNSu32) * 2 + size); |
---|
223 | if (!mem) |
---|
224 | { LogMsg("malloc( %s : %d ) failed", msg, size); return(NULL); } |
---|
225 | else |
---|
226 | { |
---|
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]); |
---|
229 | mem[0] = 0xDEAD1234; |
---|
230 | mem[1] = size; |
---|
231 | //mDNSPlatformMemZero(&mem[2], size); |
---|
232 | memset(&mem[2], 0xFF, size); |
---|
233 | validatelists(&mDNSStorage); |
---|
234 | return(&mem[2]); |
---|
235 | } |
---|
236 | } |
---|
237 | |
---|
238 | mDNSexport void freeL(char *msg, void *x) |
---|
239 | { |
---|
240 | if (!x) |
---|
241 | LogMsg("free( %s @ NULL )!", msg); |
---|
242 | else |
---|
243 | { |
---|
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]); |
---|
249 | mem[0] = 0xDEADDEAD; |
---|
250 | memset(mem+2, 0xFF, mem[1]); |
---|
251 | validatelists(&mDNSStorage); |
---|
252 | free(mem); |
---|
253 | } |
---|
254 | } |
---|
255 | |
---|
256 | #endif |
---|
257 | |
---|
258 | //************************************************************************************************************* |
---|
259 | // Registration |
---|
260 | |
---|
261 | mDNSexport void RecordUpdatedNiceLabel(mDNS *const m, mDNSs32 delay) |
---|
262 | { |
---|
263 | m->p->NotifyUser = NonZeroTime(m->timenow + delay); |
---|
264 | } |
---|
265 | |
---|
266 | mDNSlocal void mDNSPreferencesSetNames(mDNS *const m, int key, domainlabel *old, domainlabel *new) |
---|
267 | { |
---|
268 | domainlabel *prevold, *prevnew; |
---|
269 | switch (key) |
---|
270 | { |
---|
271 | case kmDNSComputerName: |
---|
272 | case kmDNSLocalHostName: |
---|
273 | if (key == kmDNSComputerName) |
---|
274 | { |
---|
275 | prevold = &m->p->prevoldnicelabel; |
---|
276 | prevnew = &m->p->prevnewnicelabel; |
---|
277 | } |
---|
278 | else |
---|
279 | { |
---|
280 | prevold = &m->p->prevoldhostlabel; |
---|
281 | prevnew = &m->p->prevnewhostlabel; |
---|
282 | } |
---|
283 | // There are a few cases where we need to invoke the helper. |
---|
284 | // |
---|
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 |
---|
287 | // conflict |
---|
288 | // |
---|
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. |
---|
294 | // |
---|
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)) |
---|
300 | { |
---|
301 | // Work around bug radar:21397654 |
---|
302 | #ifndef __clang_analyzer__ |
---|
303 | if (old) |
---|
304 | *prevold = *old; |
---|
305 | else |
---|
306 | prevold->c[0] = 0; |
---|
307 | if (new) |
---|
308 | *prevnew = *new; |
---|
309 | else |
---|
310 | prevnew->c[0] = 0; |
---|
311 | #endif |
---|
312 | mDNSPreferencesSetName(key, old, new); |
---|
313 | } |
---|
314 | else |
---|
315 | { |
---|
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, |
---|
319 | old->c, new->c); |
---|
320 | } |
---|
321 | break; |
---|
322 | default: |
---|
323 | LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key); |
---|
324 | return; |
---|
325 | } |
---|
326 | } |
---|
327 | |
---|
328 | mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result) |
---|
329 | { |
---|
330 | (void)m; // Unused |
---|
331 | if (result == mStatus_NoError) |
---|
332 | { |
---|
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); |
---|
337 | } |
---|
338 | else if (result == mStatus_NameConflict) |
---|
339 | { |
---|
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) |
---|
343 | { |
---|
344 | // Tell the helper we've given up |
---|
345 | mDNSPreferencesSetNames(m, kmDNSLocalHostName, &m->p->userhostlabel, NULL); |
---|
346 | } |
---|
347 | } |
---|
348 | else if (result == mStatus_GrowCache) |
---|
349 | { |
---|
350 | // Allocate another chunk of cache storage |
---|
351 | static unsigned int allocated = 0; |
---|
352 | #if TARGET_OS_IPHONE |
---|
353 | if (allocated >= 1000000) return; // For now we limit the cache to at most 1MB on iOS devices |
---|
354 | #endif |
---|
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); |
---|
360 | } |
---|
361 | else if (result == mStatus_ConfigChanged) |
---|
362 | { |
---|
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); |
---|
366 | |
---|
367 | // Then we call into the UDS daemon code, to let it do the same |
---|
368 | udsserver_handle_configchange(m); |
---|
369 | } |
---|
370 | } |
---|
371 | |
---|
372 | |
---|
373 | //************************************************************************************************************* |
---|
374 | #if COMPILER_LIKES_PRAGMA_MARK |
---|
375 | #pragma mark - |
---|
376 | #pragma mark - Startup, shutdown, and supporting code |
---|
377 | #endif |
---|
378 | |
---|
379 | mDNSlocal void ExitCallback(int sig) |
---|
380 | { |
---|
381 | (void)sig; // Unused |
---|
382 | LogMsg("%s stopping", mDNSResponderVersionString); |
---|
383 | |
---|
384 | if (udsserver_exit() < 0) |
---|
385 | LogMsg("ExitCallback: udsserver_exit failed"); |
---|
386 | |
---|
387 | debugf("ExitCallback: mDNS_StartExit"); |
---|
388 | mDNS_StartExit(&mDNSStorage); |
---|
389 | } |
---|
390 | |
---|
391 | #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
392 | |
---|
393 | // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit |
---|
394 | mDNSlocal void HandleSIG(int sig) |
---|
395 | { |
---|
396 | kern_return_t status; |
---|
397 | mach_msg_header_t header; |
---|
398 | |
---|
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; |
---|
405 | |
---|
406 | status = mach_msg(&header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, header.msgh_size, |
---|
407 | 0, MACH_PORT_NULL, 0, MACH_PORT_NULL); |
---|
408 | |
---|
409 | if (status != MACH_MSG_SUCCESS) |
---|
410 | { |
---|
411 | if (status == MACH_SEND_TIMED_OUT) mach_msg_destroy(&header); |
---|
412 | if (sig == SIGTERM || sig == SIGINT) exit(-1); |
---|
413 | } |
---|
414 | } |
---|
415 | |
---|
416 | #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
417 | |
---|
418 | mDNSexport void INFOCallback(void) |
---|
419 | { |
---|
420 | mDNSs32 utc = mDNSPlatformUTC(); |
---|
421 | const mDNSs32 now = mDNS_TimeNow(&mDNSStorage); |
---|
422 | NetworkInterfaceInfoOSX *i; |
---|
423 | DNSServer *s; |
---|
424 | McastResolver *mr; |
---|
425 | |
---|
426 | LogMsg("---- BEGIN STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers); |
---|
427 | |
---|
428 | udsserver_info(&mDNSStorage); |
---|
429 | |
---|
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); |
---|
436 | |
---|
437 | xpcserver_info(&mDNSStorage); |
---|
438 | |
---|
439 | LogMsgNoIdent("----- KQSocketEventSources -----"); |
---|
440 | if (!gEventSources) LogMsgNoIdent("<None>"); |
---|
441 | else |
---|
442 | { |
---|
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" : " "); |
---|
446 | } |
---|
447 | |
---|
448 | LogMsgNoIdent("------ Network Interfaces ------"); |
---|
449 | if (!mDNSStorage.p->InterfaceList) LogMsgNoIdent("<None>"); |
---|
450 | else |
---|
451 | { |
---|
452 | for (i = mDNSStorage.p->InterfaceList; i; i = i->next) |
---|
453 | { |
---|
454 | // Allow six characters for interface name, for names like "vmnet8" |
---|
455 | if (!i->Exists) |
---|
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); |
---|
460 | else |
---|
461 | { |
---|
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", |
---|
474 | &i->ifinfo.ip); |
---|
475 | |
---|
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); |
---|
479 | } |
---|
480 | } |
---|
481 | } |
---|
482 | |
---|
483 | LogMsgNoIdent("--------- DNS Servers(%d) ----------", NumUnicastDNSServers); |
---|
484 | if (!mDNSStorage.DNSServers) LogMsgNoIdent("<None>"); |
---|
485 | else |
---|
486 | { |
---|
487 | for (s = mDNSStorage.DNSServers; s; s = s->next) |
---|
488 | { |
---|
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"); |
---|
498 | } |
---|
499 | } |
---|
500 | |
---|
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)); |
---|
504 | |
---|
505 | LogMsgNoIdent("--------- Mcast Resolvers ----------"); |
---|
506 | if (!mDNSStorage.McastResolvers) LogMsgNoIdent("<None>"); |
---|
507 | else |
---|
508 | { |
---|
509 | for (mr = mDNSStorage.McastResolvers; mr; mr = mr->next) |
---|
510 | LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr->domain.c, mr->timeout); |
---|
511 | } |
---|
512 | |
---|
513 | LogMsgNoIdent("------------ Hostnames -------------"); |
---|
514 | if (!mDNSStorage.Hostnames) LogMsgNoIdent("<None>"); |
---|
515 | else |
---|
516 | { |
---|
517 | HostnameInfo *hi; |
---|
518 | for (hi = mDNSStorage.Hostnames; hi; hi = hi->next) |
---|
519 | { |
---|
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)); |
---|
522 | } |
---|
523 | } |
---|
524 | |
---|
525 | LogMsgNoIdent("--------------- FQDN ---------------"); |
---|
526 | if (!mDNSStorage.FQDN.c[0]) LogMsgNoIdent("<None>"); |
---|
527 | else |
---|
528 | { |
---|
529 | LogMsgNoIdent("%##s", mDNSStorage.FQDN.c); |
---|
530 | } |
---|
531 | |
---|
532 | #if TARGET_OS_EMBEDDED |
---|
533 | LogMetrics(); |
---|
534 | #endif |
---|
535 | LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now); |
---|
536 | LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers); |
---|
537 | } |
---|
538 | |
---|
539 | |
---|
540 | mDNSexport void mDNSPlatformLogToFile(int log_level, const char *buffer) |
---|
541 | { |
---|
542 | if (!log_general) |
---|
543 | os_log_error(OS_LOG_DEFAULT, "Could NOT create log handle in init_logging()"); |
---|
544 | else |
---|
545 | os_log_with_type(log_general, log_level, "%s", buffer); |
---|
546 | |
---|
547 | } |
---|
548 | |
---|
549 | // Writes the state out to the dynamic store and also affects the ASL filter level |
---|
550 | mDNSexport void UpdateDebugState() |
---|
551 | { |
---|
552 | mDNSu32 one = 1; |
---|
553 | mDNSu32 zero = 0; |
---|
554 | |
---|
555 | CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); |
---|
556 | if (!dict) |
---|
557 | { |
---|
558 | LogMsg("UpdateDebugState: Could not create dict"); |
---|
559 | return; |
---|
560 | } |
---|
561 | |
---|
562 | CFNumberRef numOne = CFNumberCreate(NULL, kCFNumberSInt32Type, &one); |
---|
563 | if (!numOne) |
---|
564 | { |
---|
565 | LogMsg("UpdateDebugState: Could not create CFNumber one"); |
---|
566 | return; |
---|
567 | } |
---|
568 | CFNumberRef numZero = CFNumberCreate(NULL, kCFNumberSInt32Type, &zero); |
---|
569 | if (!numZero) |
---|
570 | { |
---|
571 | LogMsg("UpdateDebugState: Could not create CFNumber zero"); |
---|
572 | CFRelease(numOne); |
---|
573 | return; |
---|
574 | } |
---|
575 | |
---|
576 | if (mDNS_LoggingEnabled) |
---|
577 | CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numOne); |
---|
578 | else |
---|
579 | CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numZero); |
---|
580 | |
---|
581 | if (mDNS_PacketLoggingEnabled) |
---|
582 | CFDictionarySetValue(dict, CFSTR("PacketLogging"), numOne); |
---|
583 | else |
---|
584 | CFDictionarySetValue(dict, CFSTR("PacketLogging"), numZero); |
---|
585 | |
---|
586 | if (mDNS_McastLoggingEnabled) |
---|
587 | CFDictionarySetValue(dict, CFSTR("McastLogging"), numOne); |
---|
588 | else |
---|
589 | CFDictionarySetValue(dict, CFSTR("McastLogging"), numZero); |
---|
590 | |
---|
591 | if (mDNS_McastTracingEnabled) |
---|
592 | CFDictionarySetValue(dict, CFSTR("McastTracing"), numOne); |
---|
593 | else |
---|
594 | CFDictionarySetValue(dict, CFSTR("McastTracing"), numZero); |
---|
595 | |
---|
596 | CFRelease(numOne); |
---|
597 | CFRelease(numZero); |
---|
598 | mDNSDynamicStoreSetConfig(kmDNSDebugState, mDNSNULL, dict); |
---|
599 | CFRelease(dict); |
---|
600 | |
---|
601 | } |
---|
602 | |
---|
603 | |
---|
604 | #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
605 | |
---|
606 | mDNSlocal void SignalCallback(CFMachPortRef port, void *msg, CFIndex size, void *info) |
---|
607 | { |
---|
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; |
---|
613 | |
---|
614 | // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding |
---|
615 | KQueueLock(m); |
---|
616 | switch(msg_header->msgh_id) |
---|
617 | { |
---|
618 | case SIGHUP: { |
---|
619 | mDNSu32 slot; |
---|
620 | CacheGroup *cg; |
---|
621 | CacheRecord *rr; |
---|
622 | LogMsg("SIGHUP: Purge cache"); |
---|
623 | mDNS_Lock(m); |
---|
624 | FORALL_CACHERECORDS(slot, cg, rr) |
---|
625 | { |
---|
626 | mDNS_PurgeCacheResourceRecord(m, rr); |
---|
627 | } |
---|
628 | // Restart unicast and multicast queries |
---|
629 | mDNSCoreRestartQueries(m); |
---|
630 | mDNS_Unlock(m); |
---|
631 | } break; |
---|
632 | case SIGINT: |
---|
633 | case SIGTERM: ExitCallback(msg_header->msgh_id); break; |
---|
634 | case SIGINFO: INFOCallback(); break; |
---|
635 | case SIGUSR1: |
---|
636 | #if APPLE_OSX_mDNSResponder |
---|
637 | mDNS_LoggingEnabled = 1; |
---|
638 | LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled ? "Enabled" : "Disabled"); |
---|
639 | #else |
---|
640 | mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1; |
---|
641 | LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled"); |
---|
642 | #endif |
---|
643 | WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250; |
---|
644 | UpdateDebugState(); |
---|
645 | LogInfo("USR1 Logging Enabled"); |
---|
646 | break; |
---|
647 | case SIGUSR2: |
---|
648 | #if APPLE_OSX_mDNSResponder |
---|
649 | mDNS_PacketLoggingEnabled = 1; |
---|
650 | LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled"); |
---|
651 | #else |
---|
652 | mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1; |
---|
653 | LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled"); |
---|
654 | #endif |
---|
655 | mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse; |
---|
656 | LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled"); |
---|
657 | UpdateDebugState(); |
---|
658 | break; |
---|
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"); |
---|
664 | UpdateDebugState(); |
---|
665 | break; |
---|
666 | case SIGTSTP: mDNS_LoggingEnabled = mDNS_PacketLoggingEnabled = mDNS_McastLoggingEnabled = mDNS_McastTracingEnabled = mDNSfalse; |
---|
667 | LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)"); |
---|
668 | UpdateDebugState(); |
---|
669 | break; |
---|
670 | |
---|
671 | default: LogMsg("SignalCallback: Unknown signal %d", msg_header->msgh_id); break; |
---|
672 | } |
---|
673 | KQueueUnlock(m, "Unix Signal"); |
---|
674 | } |
---|
675 | |
---|
676 | // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x) |
---|
677 | mDNSlocal kern_return_t mDNSDaemonInitialize(void) |
---|
678 | { |
---|
679 | mStatus err; |
---|
680 | |
---|
681 | err = mDNS_Init(&mDNSStorage, &PlatformStorage, |
---|
682 | rrcachestorage, RR_CACHE_SIZE, |
---|
683 | !NoMulticastAdvertisements, |
---|
684 | mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext); |
---|
685 | |
---|
686 | if (err) |
---|
687 | { |
---|
688 | LogMsg("Daemon start: mDNS_Init failed %d", err); |
---|
689 | return(err); |
---|
690 | } |
---|
691 | |
---|
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); |
---|
696 | CFRelease(i_rls); |
---|
697 | |
---|
698 | return(err); |
---|
699 | } |
---|
700 | |
---|
701 | #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
702 | |
---|
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" |
---|
708 | |
---|
709 | mDNSlocal void SignalDispatch(dispatch_source_t source) |
---|
710 | { |
---|
711 | int sig = (int)dispatch_source_get_handle(source); |
---|
712 | mDNS *const m = &mDNSStorage; |
---|
713 | KQueueLock(m); |
---|
714 | switch(sig) |
---|
715 | { |
---|
716 | case SIGHUP: { |
---|
717 | mDNSu32 slot; |
---|
718 | CacheGroup *cg; |
---|
719 | CacheRecord *rr; |
---|
720 | LogMsg("SIGHUP: Purge cache"); |
---|
721 | mDNS_Lock(m); |
---|
722 | FORALL_CACHERECORDS(slot, cg, rr) |
---|
723 | { |
---|
724 | mDNS_PurgeCacheResourceRecord(m, rr); |
---|
725 | } |
---|
726 | // Restart unicast and multicast queries |
---|
727 | mDNSCoreRestartQueries(m); |
---|
728 | mDNS_Unlock(m); |
---|
729 | } break; |
---|
730 | case SIGINT: |
---|
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; |
---|
736 | UpdateDebugState(); |
---|
737 | break; |
---|
738 | case SIGUSR2: mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1; |
---|
739 | LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled"); |
---|
740 | UpdateDebugState(); |
---|
741 | break; |
---|
742 | default: LogMsg("SignalCallback: Unknown signal %d", sig); break; |
---|
743 | } |
---|
744 | KQueueUnlock(m, "Unix Signal"); |
---|
745 | } |
---|
746 | |
---|
747 | mDNSlocal void mDNSSetupSignal(dispatch_queue_t queue, int sig) |
---|
748 | { |
---|
749 | signal(sig, SIG_IGN); |
---|
750 | dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, sig, 0, queue); |
---|
751 | |
---|
752 | if (source) |
---|
753 | { |
---|
754 | dispatch_source_set_event_handler(source, ^{SignalDispatch(source);}); |
---|
755 | // Start processing signals |
---|
756 | dispatch_resume(source); |
---|
757 | } |
---|
758 | else |
---|
759 | { |
---|
760 | LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig); |
---|
761 | } |
---|
762 | } |
---|
763 | |
---|
764 | mDNSlocal kern_return_t mDNSDaemonInitialize(void) |
---|
765 | { |
---|
766 | mStatus err; |
---|
767 | dispatch_queue_t queue = dispatch_get_main_queue(); |
---|
768 | |
---|
769 | err = mDNS_Init(&mDNSStorage, &PlatformStorage, |
---|
770 | rrcachestorage, RR_CACHE_SIZE, |
---|
771 | !NoMulticastAdvertisements, |
---|
772 | mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext); |
---|
773 | |
---|
774 | if (err) |
---|
775 | { |
---|
776 | LogMsg("Daemon start: mDNS_Init failed %d", err); |
---|
777 | return(err); |
---|
778 | } |
---|
779 | |
---|
780 | mDNSSetupSignal(queue, SIGHUP); |
---|
781 | mDNSSetupSignal(queue, SIGINT); |
---|
782 | mDNSSetupSignal(queue, SIGTERM); |
---|
783 | mDNSSetupSignal(queue, SIGINFO); |
---|
784 | mDNSSetupSignal(queue, SIGUSR1); |
---|
785 | mDNSSetupSignal(queue, SIGUSR2); |
---|
786 | |
---|
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); |
---|
793 | |
---|
794 | // Create a timer source to trigger housekeeping work. The houskeeping work itself |
---|
795 | // is done in the custom handler that we set below. |
---|
796 | |
---|
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;} |
---|
799 | |
---|
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); |
---|
805 | }); |
---|
806 | dispatch_resume(PlatformStorage.timer); |
---|
807 | |
---|
808 | LogMsg("DaemonIntialize done successfully"); |
---|
809 | |
---|
810 | return(err); |
---|
811 | } |
---|
812 | |
---|
813 | #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
814 | |
---|
815 | mDNSlocal mDNSs32 mDNSDaemonIdle(mDNS *const m) |
---|
816 | { |
---|
817 | mDNSs32 now = mDNS_TimeNow(m); |
---|
818 | |
---|
819 | // 1. If we need to set domain secrets, do so before handling the network change |
---|
820 | // Detailed reason: |
---|
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) |
---|
824 | { |
---|
825 | m->p->KeyChainTimer = 0; |
---|
826 | mDNS_Lock(m); |
---|
827 | SetDomainSecrets(m); |
---|
828 | mDNS_Unlock(m); |
---|
829 | } |
---|
830 | |
---|
831 | // 2. If we have network change events to handle, do them before calling mDNS_Execute() |
---|
832 | // Detailed reason: |
---|
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); |
---|
838 | |
---|
839 | if (m->p->RequestReSleep && now - m->p->RequestReSleep >= 0) |
---|
840 | { |
---|
841 | m->p->RequestReSleep = 0; |
---|
842 | mDNSPowerRequest(0, 0); |
---|
843 | } |
---|
844 | |
---|
845 | // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do |
---|
846 | mDNSs32 nextevent = mDNS_Execute(m); |
---|
847 | |
---|
848 | if (m->NetworkChanged) |
---|
849 | if (nextevent - m->NetworkChanged > 0) |
---|
850 | nextevent = m->NetworkChanged; |
---|
851 | |
---|
852 | if (m->p->KeyChainTimer) |
---|
853 | if (nextevent - m->p->KeyChainTimer > 0) |
---|
854 | nextevent = m->p->KeyChainTimer; |
---|
855 | |
---|
856 | if (m->p->RequestReSleep) |
---|
857 | if (nextevent - m->p->RequestReSleep > 0) |
---|
858 | nextevent = m->p->RequestReSleep; |
---|
859 | |
---|
860 | |
---|
861 | if (m->p->NotifyUser) |
---|
862 | { |
---|
863 | if (m->p->NotifyUser - now < 0) |
---|
864 | { |
---|
865 | if (!SameDomainLabelCS(m->p->usernicelabel.c, m->nicelabel.c)) |
---|
866 | { |
---|
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; |
---|
870 | } |
---|
871 | if (!SameDomainLabelCS(m->p->userhostlabel.c, m->hostlabel.c)) |
---|
872 | { |
---|
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; |
---|
877 | } |
---|
878 | m->p->NotifyUser = 0; |
---|
879 | } |
---|
880 | else |
---|
881 | if (nextevent - m->p->NotifyUser > 0) |
---|
882 | nextevent = m->p->NotifyUser; |
---|
883 | } |
---|
884 | |
---|
885 | return(nextevent); |
---|
886 | } |
---|
887 | |
---|
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) |
---|
894 | { |
---|
895 | mDNSu32 e = 24 * 3600; // Maximum maintenance wake interval is 24 hours |
---|
896 | const CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); |
---|
897 | if (!now) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed"); |
---|
898 | else |
---|
899 | { |
---|
900 | int ic, j; |
---|
901 | |
---|
902 | const void *pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetDHCP); |
---|
903 | if (!pattern) |
---|
904 | { |
---|
905 | LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n"); |
---|
906 | return e; |
---|
907 | } |
---|
908 | CFArrayRef dhcpinfo = CFArrayCreate(NULL, (const void **)&pattern, 1, &kCFTypeArrayCallBacks); |
---|
909 | CFRelease(pattern); |
---|
910 | if (dhcpinfo) |
---|
911 | { |
---|
912 | SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("DHCP-LEASES"), NULL, NULL); |
---|
913 | if (store) |
---|
914 | { |
---|
915 | CFDictionaryRef dict = SCDynamicStoreCopyMultiple(store, NULL, dhcpinfo); |
---|
916 | if (dict) |
---|
917 | { |
---|
918 | ic = CFDictionaryGetCount(dict); |
---|
919 | const void *vals[ic]; |
---|
920 | CFDictionaryGetKeysAndValues(dict, NULL, vals); |
---|
921 | |
---|
922 | for (j = 0; j < ic; j++) |
---|
923 | { |
---|
924 | const CFDictionaryRef dhcp = (CFDictionaryRef)vals[j]; |
---|
925 | if (dhcp) |
---|
926 | { |
---|
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); |
---|
933 | else |
---|
934 | { |
---|
935 | const UInt8 *d = CFDataGetBytePtr(lease); |
---|
936 | if (!d) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j); |
---|
937 | else |
---|
938 | { |
---|
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; |
---|
945 | } |
---|
946 | } |
---|
947 | } |
---|
948 | } |
---|
949 | CFRelease(dict); |
---|
950 | } |
---|
951 | CFRelease(store); |
---|
952 | } |
---|
953 | CFRelease(dhcpinfo); |
---|
954 | } |
---|
955 | } |
---|
956 | return(e); |
---|
957 | } |
---|
958 | |
---|
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. |
---|
966 | |
---|
967 | mDNSlocal mDNSBool AllowSleepNow(mDNS *const m, mDNSs32 now) |
---|
968 | { |
---|
969 | mDNSBool ready = mDNSCoreReadyForSleep(m, now); |
---|
970 | if (m->SleepState && !ready && now - m->SleepLimit < 0) return(mDNSfalse); |
---|
971 | |
---|
972 | m->p->WakeAtUTC = 0; |
---|
973 | int result = kIOReturnSuccess; |
---|
974 | CFDictionaryRef opts = NULL; |
---|
975 | |
---|
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. |
---|
978 | if (!m->SleepState) |
---|
979 | LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m->SleepLimit - now); |
---|
980 | else |
---|
981 | { |
---|
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"); |
---|
986 | else |
---|
987 | { |
---|
988 | mDNSs32 dhcp = DHCPWakeTime(); |
---|
989 | LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp); |
---|
990 | mDNSs32 interval = mDNSCoreIntervalToNextWake(m, now) / mDNSPlatformOneSecond; |
---|
991 | if (interval > dhcp) interval = dhcp; |
---|
992 | |
---|
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; |
---|
998 | |
---|
999 | //interval = 48; // For testing |
---|
1000 | |
---|
1001 | #if !TARGET_OS_EMBEDDED |
---|
1002 | #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements |
---|
1003 | if (m->p->IOPMConnection) // If lightweight-wake capability is available, use that |
---|
1004 | { |
---|
1005 | const CFDateRef WakeDate = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent() + interval); |
---|
1006 | if (!WakeDate) LogMsg("ScheduleNextWake: CFDateCreate failed"); |
---|
1007 | else |
---|
1008 | { |
---|
1009 | const mDNSs32 reqs = kIOPMSystemPowerStateCapabilityNetwork; |
---|
1010 | const CFNumberRef Requirements = CFNumberCreate(NULL, kCFNumberSInt32Type, &reqs); |
---|
1011 | if (!Requirements) LogMsg("ScheduleNextWake: CFNumberCreate failed"); |
---|
1012 | else |
---|
1013 | { |
---|
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); |
---|
1019 | } |
---|
1020 | CFRelease(WakeDate); |
---|
1021 | } |
---|
1022 | LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval); |
---|
1023 | } |
---|
1024 | else // else schedule the wakeup using the old API instead to |
---|
1025 | #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements |
---|
1026 | #endif // TARGET_OS_EMBEDDED |
---|
1027 | { |
---|
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. |
---|
1032 | if (interval < 60) |
---|
1033 | interval = 60; |
---|
1034 | |
---|
1035 | result = mDNSPowerRequest(1, interval); |
---|
1036 | |
---|
1037 | if (result == kIOReturnNotReady) |
---|
1038 | { |
---|
1039 | int r; |
---|
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. |
---|
1048 | do |
---|
1049 | { |
---|
1050 | interval += (interval < 20) ? 1 : ((interval+3) / 4); |
---|
1051 | r = mDNSPowerRequest(1, interval); |
---|
1052 | } |
---|
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); |
---|
1056 | } |
---|
1057 | else |
---|
1058 | { |
---|
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); |
---|
1061 | } |
---|
1062 | m->p->WakeAtUTC = mDNSPlatformUTC() + interval; |
---|
1063 | } |
---|
1064 | } |
---|
1065 | |
---|
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); |
---|
1070 | } |
---|
1071 | |
---|
1072 | LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)", |
---|
1073 | #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements) |
---|
1074 | (m->p->IOPMConnection) ? "IOPMConnectionAcknowledgeEventWithOptions" : |
---|
1075 | #endif |
---|
1076 | (result == kIOReturnSuccess) ? "IOAllowPowerChange" : "IOCancelPowerChange", |
---|
1077 | m->p->SleepCookie, ready ? "ready for sleep" : "giving up", now, m->SleepLimit - now); |
---|
1078 | |
---|
1079 | m->SleepLimit = 0; // Don't clear m->SleepLimit until after we've logged it above |
---|
1080 | m->TimeSlept = mDNSPlatformUTC(); |
---|
1081 | |
---|
1082 | // accumulate total time awake for this statistics gathering interval |
---|
1083 | if (m->StatStartTime) |
---|
1084 | { |
---|
1085 | m->ActiveStatTime += (m->TimeSlept - m->StatStartTime); |
---|
1086 | |
---|
1087 | // indicate this value is invalid until reinitialzed on wakeup |
---|
1088 | m->StatStartTime = 0; |
---|
1089 | } |
---|
1090 | |
---|
1091 | #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements) |
---|
1092 | if (m->p->IOPMConnection) IOPMConnectionAcknowledgeEventWithOptions(m->p->IOPMConnection, m->p->SleepCookie, opts); |
---|
1093 | else |
---|
1094 | #endif |
---|
1095 | if (result == kIOReturnSuccess) IOAllowPowerChange (m->p->PowerConnection, m->p->SleepCookie); |
---|
1096 | else IOCancelPowerChange(m->p->PowerConnection, m->p->SleepCookie); |
---|
1097 | |
---|
1098 | if (opts) CFRelease(opts); |
---|
1099 | return(mDNStrue); |
---|
1100 | } |
---|
1101 | |
---|
1102 | #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
1103 | |
---|
1104 | mDNSexport void TriggerEventCompletion() |
---|
1105 | { |
---|
1106 | debugf("TriggerEventCompletion: Merge data"); |
---|
1107 | dispatch_source_merge_data(PlatformStorage.custom, 1); |
---|
1108 | } |
---|
1109 | |
---|
1110 | mDNSlocal void PrepareForIdle(void *m_param) |
---|
1111 | { |
---|
1112 | mDNS *m = m_param; |
---|
1113 | int64_t time_offset; |
---|
1114 | dispatch_time_t dtime; |
---|
1115 | |
---|
1116 | const int multiplier = 1000000000 / mDNSPlatformOneSecond; |
---|
1117 | |
---|
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 |
---|
1122 | |
---|
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); |
---|
1130 | |
---|
1131 | mDNSs32 now = mDNS_TimeNow(m); |
---|
1132 | |
---|
1133 | if (m->ShutdownTime) |
---|
1134 | { |
---|
1135 | if (mDNSStorage.ResourceRecords) |
---|
1136 | { |
---|
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 |
---|
1139 | } |
---|
1140 | if (mDNS_ExitNow(m, now)) |
---|
1141 | { |
---|
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 |
---|
1145 | exit(0); |
---|
1146 | } |
---|
1147 | if (nextTimerEvent - m->ShutdownTime >= 0) |
---|
1148 | nextTimerEvent = m->ShutdownTime; |
---|
1149 | } |
---|
1150 | |
---|
1151 | if (m->SleepLimit) |
---|
1152 | if (!AllowSleepNow(m, now)) |
---|
1153 | if (nextTimerEvent - m->SleepLimit >= 0) |
---|
1154 | nextTimerEvent = m->SleepLimit; |
---|
1155 | |
---|
1156 | // Convert absolute wakeup time to a relative time from now |
---|
1157 | mDNSs32 ticks = nextTimerEvent - now; |
---|
1158 | if (ticks < 1) ticks = 1; |
---|
1159 | |
---|
1160 | static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins |
---|
1161 | if (ticks > 1) |
---|
1162 | RepeatedBusy = 0; |
---|
1163 | else |
---|
1164 | { |
---|
1165 | ticks = 1; |
---|
1166 | if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; } |
---|
1167 | } |
---|
1168 | |
---|
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); |
---|
1173 | return; |
---|
1174 | } |
---|
1175 | |
---|
1176 | #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
1177 | |
---|
1178 | mDNSlocal void KQWokenFlushBytes(int fd, __unused short filter, __unused void *context) |
---|
1179 | { |
---|
1180 | // Read all of the bytes so we won't wake again. |
---|
1181 | char buffer[100]; |
---|
1182 | while (recv(fd, buffer, sizeof(buffer), MSG_DONTWAIT) > 0) continue; |
---|
1183 | } |
---|
1184 | |
---|
1185 | mDNSlocal void SetLowWater(const KQSocketSet *const k, const int r) |
---|
1186 | { |
---|
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)); |
---|
1191 | } |
---|
1192 | |
---|
1193 | mDNSlocal void * KQueueLoop(void *m_param) |
---|
1194 | { |
---|
1195 | mDNS *m = m_param; |
---|
1196 | int numevents = 0; |
---|
1197 | |
---|
1198 | #if USE_SELECT_WITH_KQUEUEFD |
---|
1199 | fd_set readfds; |
---|
1200 | FD_ZERO(&readfds); |
---|
1201 | const int multiplier = 1000000 / mDNSPlatformOneSecond; |
---|
1202 | #else |
---|
1203 | const int multiplier = 1000000000 / mDNSPlatformOneSecond; |
---|
1204 | #endif |
---|
1205 | |
---|
1206 | pthread_mutex_lock(&PlatformStorage.BigMutex); |
---|
1207 | LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32)mDNSStorage.timenow_last, mDNSStorage.timenow_last); |
---|
1208 | |
---|
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 |
---|
1215 | for ( ; ; ) |
---|
1216 | { |
---|
1217 | #define kEventsToReadAtOnce 1 |
---|
1218 | struct kevent new_events[kEventsToReadAtOnce]; |
---|
1219 | |
---|
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); |
---|
1226 | |
---|
1227 | #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1 |
---|
1228 | validatelists(m); |
---|
1229 | #endif |
---|
1230 | |
---|
1231 | mDNSs32 now = mDNS_TimeNow(m); |
---|
1232 | |
---|
1233 | if (m->ShutdownTime) |
---|
1234 | { |
---|
1235 | if (mDNSStorage.ResourceRecords) |
---|
1236 | { |
---|
1237 | AuthRecord *rr; |
---|
1238 | for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next) |
---|
1239 | { |
---|
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 |
---|
1242 | } |
---|
1243 | } |
---|
1244 | if (mDNS_ExitNow(m, now)) |
---|
1245 | { |
---|
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 |
---|
1249 | exit(0); |
---|
1250 | } |
---|
1251 | if (nextTimerEvent - m->ShutdownTime >= 0) |
---|
1252 | nextTimerEvent = m->ShutdownTime; |
---|
1253 | } |
---|
1254 | |
---|
1255 | if (m->SleepLimit) |
---|
1256 | if (!AllowSleepNow(m, now)) |
---|
1257 | if (nextTimerEvent - m->SleepLimit >= 0) |
---|
1258 | nextTimerEvent = m->SleepLimit; |
---|
1259 | |
---|
1260 | // Convert absolute wakeup time to a relative time from now |
---|
1261 | mDNSs32 ticks = nextTimerEvent - now; |
---|
1262 | if (ticks < 1) ticks = 1; |
---|
1263 | |
---|
1264 | static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins |
---|
1265 | if (ticks > 1) |
---|
1266 | RepeatedBusy = 0; |
---|
1267 | else |
---|
1268 | { |
---|
1269 | ticks = 1; |
---|
1270 | if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; } |
---|
1271 | } |
---|
1272 | |
---|
1273 | verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents, ticks); |
---|
1274 | numevents = 0; |
---|
1275 | |
---|
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); |
---|
1281 | |
---|
1282 | // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate |
---|
1283 | if (m->p->num_mcasts) |
---|
1284 | { |
---|
1285 | SetLowWater(&m->p->permanentsockets, 0x10000); |
---|
1286 | if (ticks > mDNSPlatformOneSecond / 8) ticks = mDNSPlatformOneSecond / 8; |
---|
1287 | } |
---|
1288 | |
---|
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); } |
---|
1296 | #else |
---|
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); } |
---|
1307 | #endif |
---|
1308 | |
---|
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. |
---|
1315 | |
---|
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) |
---|
1318 | { |
---|
1319 | SetLowWater(&m->p->permanentsockets, 1); |
---|
1320 | m->p->num_mcasts = 0; |
---|
1321 | } |
---|
1322 | |
---|
1323 | static const struct timespec zero_timeout = { 0, 0 }; |
---|
1324 | int events_found; |
---|
1325 | while ((events_found = kevent(KQueueFD, NULL, 0, new_events, kEventsToReadAtOnce, &zero_timeout)) != 0) |
---|
1326 | { |
---|
1327 | if (events_found > kEventsToReadAtOnce || (events_found < 0 && errno != EINTR)) |
---|
1328 | { |
---|
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)); |
---|
1331 | exit(errno); |
---|
1332 | } |
---|
1333 | |
---|
1334 | numevents += events_found; |
---|
1335 | |
---|
1336 | int i; |
---|
1337 | for (i = 0; i < events_found; i++) |
---|
1338 | { |
---|
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); |
---|
1346 | } |
---|
1347 | } |
---|
1348 | } |
---|
1349 | |
---|
1350 | return NULL; |
---|
1351 | } |
---|
1352 | |
---|
1353 | #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
1354 | |
---|
1355 | mDNSlocal size_t LaunchdCheckin(void) |
---|
1356 | { |
---|
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; |
---|
1361 | } |
---|
1362 | |
---|
1363 | |
---|
1364 | extern int sandbox_init(const char *profile, uint64_t flags, char **errorbuf) __attribute__((weak_import)); |
---|
1365 | |
---|
1366 | #if APPLE_OSX_mDNSResponder |
---|
1367 | mDNSlocal mDNSBool PreferencesGetValueBool(CFStringRef key, mDNSBool defaultValue) |
---|
1368 | { |
---|
1369 | CFBooleanRef boolean; |
---|
1370 | mDNSBool result = defaultValue; |
---|
1371 | |
---|
1372 | boolean = CFPreferencesCopyAppValue(key, kProgramArguments); |
---|
1373 | if (boolean) |
---|
1374 | { |
---|
1375 | if (CFGetTypeID(boolean) == CFBooleanGetTypeID()) |
---|
1376 | result = CFBooleanGetValue(boolean) ? mDNStrue : mDNSfalse; |
---|
1377 | CFRelease(boolean); |
---|
1378 | } |
---|
1379 | |
---|
1380 | return result; |
---|
1381 | } |
---|
1382 | |
---|
1383 | mDNSlocal int PreferencesGetValueInt(CFStringRef key, int defaultValue) |
---|
1384 | { |
---|
1385 | CFNumberRef number; |
---|
1386 | int numberValue; |
---|
1387 | int result = defaultValue; |
---|
1388 | |
---|
1389 | number = CFPreferencesCopyAppValue(key, kProgramArguments); |
---|
1390 | if (number) |
---|
1391 | { |
---|
1392 | if ((CFGetTypeID(number) == CFNumberGetTypeID()) && CFNumberGetValue(number, kCFNumberIntType, &numberValue)) |
---|
1393 | result = numberValue; |
---|
1394 | CFRelease(number); |
---|
1395 | } |
---|
1396 | |
---|
1397 | return result; |
---|
1398 | } |
---|
1399 | #endif |
---|
1400 | |
---|
1401 | mDNSlocal void SandboxProcess(void) |
---|
1402 | { |
---|
1403 | // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb |
---|
1404 | #if MDNS_NO_SANDBOX |
---|
1405 | LogMsg("Note: Compiled without Apple Sandbox support"); |
---|
1406 | #else // MDNS_NO_SANDBOX |
---|
1407 | if (!sandbox_init) |
---|
1408 | LogMsg("Note: Running without Apple Sandbox support (not available on this OS)"); |
---|
1409 | else |
---|
1410 | { |
---|
1411 | char *sandbox_msg; |
---|
1412 | uint64_t sandbox_flags = SANDBOX_NAMED; |
---|
1413 | |
---|
1414 | (void)confstr(_CS_DARWIN_USER_CACHE_DIR, NULL, 0); |
---|
1415 | |
---|
1416 | int sandbox_err = sandbox_init("mDNSResponder", sandbox_flags, &sandbox_msg); |
---|
1417 | if (sandbox_err) |
---|
1418 | { |
---|
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); |
---|
1423 | |
---|
1424 | errx(EX_OSERR, "sandbox_init() failed: %s", sandbox_msg); |
---|
1425 | } |
---|
1426 | else LogInfo("Now running under Apple Sandbox restrictions"); |
---|
1427 | } |
---|
1428 | #endif // MDNS_NO_SANDBOX |
---|
1429 | } |
---|
1430 | |
---|
1431 | #if APPLE_OSX_mDNSResponder |
---|
1432 | mDNSlocal void init_logging(void) |
---|
1433 | { |
---|
1434 | log_general = os_log_create("com.apple.mDNSResponder", "AllINFO"); |
---|
1435 | |
---|
1436 | if (!log_general) |
---|
1437 | { |
---|
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"); |
---|
1440 | } |
---|
1441 | } |
---|
1442 | #endif |
---|
1443 | |
---|
1444 | #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR |
---|
1445 | mDNSlocal mDNSBool initialize_networkserviceproxy(void) |
---|
1446 | { |
---|
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"); |
---|
1450 | return mDNSfalse; |
---|
1451 | } |
---|
1452 | return mDNStrue; |
---|
1453 | } |
---|
1454 | #endif |
---|
1455 | |
---|
1456 | mDNSexport int main(int argc, char **argv) |
---|
1457 | { |
---|
1458 | int i; |
---|
1459 | kern_return_t status; |
---|
1460 | |
---|
1461 | #if DEBUG |
---|
1462 | bool useDebugSocket = mDNSfalse; |
---|
1463 | bool useSandbox = mDNStrue; |
---|
1464 | #endif |
---|
1465 | |
---|
1466 | #if APPLE_OSX_mDNSResponder |
---|
1467 | init_logging(); |
---|
1468 | #endif |
---|
1469 | |
---|
1470 | mDNSMacOSXSystemBuildNumber(NULL); |
---|
1471 | LogMsg("%s starting %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers); |
---|
1472 | |
---|
1473 | #if 0 |
---|
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)); |
---|
1478 | |
---|
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); |
---|
1483 | #endif |
---|
1484 | |
---|
1485 | if (0 == geteuid()) |
---|
1486 | { |
---|
1487 | LogMsg("mDNSResponder cannot be run as root !! Exiting.."); |
---|
1488 | return -1; |
---|
1489 | } |
---|
1490 | |
---|
1491 | for (i=1; i<argc; i++) |
---|
1492 | { |
---|
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; |
---|
1504 | #if DEBUG |
---|
1505 | if (!strcasecmp(argv[i], "-UseDebugSocket")) useDebugSocket = mDNStrue; |
---|
1506 | if (!strcasecmp(argv[i], "-NoSandbox")) useSandbox = mDNSfalse; |
---|
1507 | #endif |
---|
1508 | } |
---|
1509 | |
---|
1510 | |
---|
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 |
---|
1514 | |
---|
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 |
---|
1518 | 3] sudo reboot |
---|
1519 | |
---|
1520 | To turn OFF all options, here is what the user should do |
---|
1521 | 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist |
---|
1522 | 2] sudo reboot |
---|
1523 | |
---|
1524 | To view the current options set, here is what the user should do |
---|
1525 | 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist |
---|
1526 | OR |
---|
1527 | 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist |
---|
1528 | |
---|
1529 | */ |
---|
1530 | |
---|
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. |
---|
1533 | #if 0 |
---|
1534 | mDNS_LoggingEnabled = PreferencesGetValueBool(kPreferencesKey_DebugLogging, mDNS_LoggingEnabled); |
---|
1535 | mDNS_PacketLoggingEnabled = PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging, mDNS_PacketLoggingEnabled); |
---|
1536 | #endif |
---|
1537 | |
---|
1538 | mDNS_LoggingEnabled = mDNStrue; |
---|
1539 | mDNS_PacketLoggingEnabled = mDNStrue; |
---|
1540 | |
---|
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); |
---|
1547 | #endif |
---|
1548 | |
---|
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"); |
---|
1556 | |
---|
1557 | #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
1558 | |
---|
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) |
---|
1568 | |
---|
1569 | #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
1570 | |
---|
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) |
---|
1573 | xpc_server_init(); |
---|
1574 | #if DEBUG |
---|
1575 | if (!useDebugSocket) { |
---|
1576 | if (LaunchdCheckin() == 0) |
---|
1577 | useDebugSocket = mDNStrue; |
---|
1578 | } |
---|
1579 | if (useDebugSocket) |
---|
1580 | SetDebugBoundPath(); |
---|
1581 | #else |
---|
1582 | LaunchdCheckin(); |
---|
1583 | #endif |
---|
1584 | |
---|
1585 | #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
1586 | |
---|
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; } |
---|
1590 | |
---|
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; } |
---|
1593 | |
---|
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; } |
---|
1597 | |
---|
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" }; |
---|
1602 | |
---|
1603 | PlatformStorage.WakeKQueueLoopFD = fdpair[0]; |
---|
1604 | KQueueSet(fdpair[1], EV_ADD, EVFILT_READ, &wakeKQEntry); |
---|
1605 | |
---|
1606 | #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
1607 | |
---|
1608 | #if DEBUG |
---|
1609 | if (useSandbox) |
---|
1610 | #endif |
---|
1611 | SandboxProcess(); |
---|
1612 | |
---|
1613 | #if TARGET_OS_EMBEDDED |
---|
1614 | status = MetricsInit(); |
---|
1615 | if (status) { LogMsg("Daemon start: MetricsInit failed (%d)", status); } |
---|
1616 | #endif |
---|
1617 | |
---|
1618 | status = mDNSDaemonInitialize(); |
---|
1619 | if (status) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit; } |
---|
1620 | |
---|
1621 | status = udsserver_init(launchd_fds, launchd_fds_count); |
---|
1622 | if (status) { LogMsg("Daemon start: udsserver_init failed"); goto exit; } |
---|
1623 | |
---|
1624 | mDNSMacOSXNetworkChanged(&mDNSStorage); |
---|
1625 | UpdateDebugState(); |
---|
1626 | |
---|
1627 | #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR |
---|
1628 | if (initialize_networkserviceproxy() == mDNSfalse) { |
---|
1629 | LogMsg("Failed to initialize NetworkServiceProxy"); |
---|
1630 | } |
---|
1631 | #endif |
---|
1632 | |
---|
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 |
---|
1636 | CFRunLoopRun(); |
---|
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; } |
---|
1642 | if (status == 0) |
---|
1643 | { |
---|
1644 | CFRunLoopRun(); |
---|
1645 | LogMsg("ERROR: CFRunLoopRun Exiting."); |
---|
1646 | mDNS_Close(&mDNSStorage); |
---|
1647 | } |
---|
1648 | #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM |
---|
1649 | |
---|
1650 | LogMsg("%s exiting", mDNSResponderVersionString); |
---|
1651 | |
---|
1652 | exit: |
---|
1653 | return(status); |
---|
1654 | } |
---|
1655 | |
---|
1656 | // uds_daemon.c support routines ///////////////////////////////////////////// |
---|
1657 | |
---|
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) |
---|
1660 | { |
---|
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; } |
---|
1665 | |
---|
1666 | KQSocketEventSource *newSource = (KQSocketEventSource*) mallocL("KQSocketEventSource", sizeof *newSource); |
---|
1667 | if (!newSource) return mStatus_NoMemoryErr; |
---|
1668 | |
---|
1669 | newSource->next = mDNSNULL; |
---|
1670 | newSource->fd = fd; |
---|
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 |
---|
1679 | |
---|
1680 | if (KQueueSet(fd, EV_ADD, EVFILT_READ, &newSource->kqs) == 0) |
---|
1681 | { |
---|
1682 | *p = newSource; |
---|
1683 | return mStatus_NoError; |
---|
1684 | } |
---|
1685 | |
---|
1686 | LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd, errno, strerror(errno)); |
---|
1687 | freeL("KQSocketEventSource", newSource); |
---|
1688 | return mStatus_BadParamErr; |
---|
1689 | } |
---|
1690 | |
---|
1691 | int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data) |
---|
1692 | { |
---|
1693 | (void) platform_data; |
---|
1694 | return recv(fd, buf, len, flags); |
---|
1695 | } |
---|
1696 | |
---|
1697 | mDNSexport mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor |
---|
1698 | { |
---|
1699 | KQSocketEventSource **p = &gEventSources; |
---|
1700 | (void) platform_data; |
---|
1701 | while (*p && (*p)->fd != fd) p = &(*p)->next; |
---|
1702 | if (*p) |
---|
1703 | { |
---|
1704 | KQSocketEventSource *s = *p; |
---|
1705 | *p = (*p)->next; |
---|
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; |
---|
1711 | } |
---|
1712 | LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd); |
---|
1713 | return mStatus_NoSuchNameErr; |
---|
1714 | } |
---|
1715 | |
---|
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"); |
---|
1720 | #endif |
---|
1721 | |
---|
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__ ")"; |
---|