]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/daemon.c
mDNSResponder-878.200.35.tar.gz
[apple/mdnsresponder.git] / mDNSMacOSX / daemon.c
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
36 #ifdef UNIT_TEST
37 #include "unittest.h"
38 #endif
39
40 #include "uDNS.h"
41 #include "DNSCommon.h"
42 #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
43
44 #include "uds_daemon.h" // Interface to the server side implementation of dns_sd.h
45 #include "xpc_services.h" // Interface to XPC services
46 #include "helper.h"
47
48 #if AWD_METRICS
49 #include "Metrics.h"
50 #endif
51
52 #if APPLE_OSX_mDNSResponder
53 static os_log_t log_general = NULL;
54 #endif
55
56
57 // Used on OSX(10.11.x onwards) for manipulating mDNSResponder program arguments
58 #if APPLE_OSX_mDNSResponder
59 // plist file to read the user's preferences
60 #define kProgramArguments CFSTR("com.apple.mDNSResponder")
61 // possible arguments for external customers
62 #define kPreferencesKey_DebugLogging CFSTR("DebugLogging")
63 #define kPreferencesKey_UnicastPacketLogging CFSTR("UnicastPacketLogging")
64 #define kPreferencesKey_AlwaysAppendSearchDomains CFSTR("AlwaysAppendSearchDomains")
65 #define kPreferencesKey_EnableAllowExpired CFSTR("EnableAllowExpired")
66 #define kPreferencesKey_NoMulticastAdvertisements CFSTR("NoMulticastAdvertisements")
67 #define kPreferencesKey_StrictUnicastOrdering CFSTR("StrictUnicastOrdering")
68 #define kPreferencesKey_OfferSleepProxyService CFSTR("OfferSleepProxyService")
69 #define kPreferencesKey_UseInternalSleepProxy CFSTR("UseInternalSleepProxy")
70
71 #if ENABLE_BLE_TRIGGERED_BONJOUR
72 #define kPreferencesKey_EnableBLEBasedDiscovery CFSTR("EnableBLEBasedDiscovery")
73 #define kPreferencesKey_DefaultToBLETriggered CFSTR("DefaultToBLETriggered")
74 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
75
76 #if TARGET_OS_IPHONE
77 #define kPreferencesKey_PreallocateCacheMemory CFSTR("PreallocateCacheMemory")
78 #endif
79 #endif
80
81 //*************************************************************************************************************
82 #if COMPILER_LIKES_PRAGMA_MARK
83 #pragma mark - Globals
84 #endif
85
86 static mDNS_PlatformSupport PlatformStorage;
87
88 // Start off with a default cache of 32K (136 records of 240 bytes each)
89 // Each time we grow the cache we add another 136 records
90 // 136 * 240 = 32640 bytes.
91 // This fits in eight 4kB pages, with 128 bytes spare for memory block headers and similar overhead
92 #define RR_CACHE_SIZE ((32*1024) / sizeof(CacheRecord))
93 static CacheEntity rrcachestorage[RR_CACHE_SIZE];
94 struct CompileTimeAssertionChecks_RR_CACHE_SIZE { char a[(RR_CACHE_SIZE >= 136) ? 1 : -1]; };
95 #define kRRCacheGrowSize (sizeof(CacheEntity) * RR_CACHE_SIZE)
96
97
98 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
99 mDNSlocal void PrepareForIdle(void *m_param);
100 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
101 static mach_port_t signal_port = MACH_PORT_NULL;
102 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
103
104 static dnssd_sock_t *launchd_fds = mDNSNULL;
105 static size_t launchd_fds_count = 0;
106
107 static mDNSBool NoMulticastAdvertisements = mDNSfalse; // By default, advertise addresses (& other records) via multicast
108
109 extern mDNSBool StrictUnicastOrdering;
110 extern mDNSBool AlwaysAppendSearchDomains;
111 extern mDNSBool EnableAllowExpired;
112
113 #if ENABLE_BLE_TRIGGERED_BONJOUR
114 extern mDNSBool EnableBLEBasedDiscovery;
115 extern mDNSBool DefaultToBLETriggered;
116 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
117
118 #if TARGET_OS_IPHONE
119 static mDNSBool PreallocateCacheMemory = mDNSfalse;
120 #define kRRCacheMemoryLimit 1000000 // For now, we limit the cache to at most 1MB on iOS devices.
121 #endif
122
123 // We keep a list of client-supplied event sources in KQSocketEventSource records
124 typedef struct KQSocketEventSource
125 {
126 struct KQSocketEventSource *next;
127 int fd;
128 KQueueEntry kqs;
129 udsEventCallback callback;
130 void *context;
131 } KQSocketEventSource;
132
133 static KQSocketEventSource *gEventSources;
134
135 //*************************************************************************************************************
136 #if COMPILER_LIKES_PRAGMA_MARK
137 #pragma mark -
138 #pragma mark - General Utility Functions
139 #endif
140
141 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
142
143 char _malloc_options[] = "AXZ";
144
145 mDNSlocal void validatelists(mDNS *const m)
146 {
147 #if BONJOUR_ON_DEMAND
148 mDNSu32 NumAllInterfaceRecords = 0;
149 mDNSu32 NumAllInterfaceQuestions = 0;
150 #endif // BONJOUR_ON_DEMAND
151
152 // Check local lists
153 KQSocketEventSource *k;
154 for (k = gEventSources; k; k=k->next)
155 if (k->next == (KQSocketEventSource *)~0 || k->fd < 0)
156 LogMemCorruption("gEventSources: %p is garbage (%d)", k, k->fd);
157
158 // Check Unix Domain Socket client lists (uds_daemon.c)
159 uds_validatelists();
160
161 // Check core mDNS lists
162 AuthRecord *rr;
163 for (rr = m->ResourceRecords; rr; rr=rr->next)
164 {
165 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
166 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
167 if (rr->resrec.name != &rr->namestorage)
168 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
169 rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c);
170 #if BONJOUR_ON_DEMAND
171 if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
172 #endif // BONJOUR_ON_DEMAND
173 }
174
175 for (rr = m->DuplicateRecords; rr; rr=rr->next)
176 {
177 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
178 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
179 #if BONJOUR_ON_DEMAND
180 if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
181 #endif // BONJOUR_ON_DEMAND
182 }
183
184 rr = m->NewLocalRecords;
185 if (rr)
186 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
187 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr, rr->resrec.RecordType);
188
189 rr = m->CurrentRecord;
190 if (rr)
191 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
192 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr, rr->resrec.RecordType);
193
194 DNSQuestion *q;
195 for (q = m->Questions; q; q=q->next)
196 {
197 if (q->next == (DNSQuestion*)~0 || q->ThisQInterval == (mDNSs32) ~0)
198 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q, q->ThisQInterval, q->next);
199 if (q->DuplicateOf && q->LocalSocket)
200 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
201 #if BONJOUR_ON_DEMAND
202 if (!LocalOnlyOrP2PInterface(q->InterfaceID) && mDNSOpaque16IsZero(q->TargetQID))
203 NumAllInterfaceQuestions++;
204 #endif // BONJOUR_ON_DEMAND
205 }
206
207 CacheGroup *cg;
208 CacheRecord *cr;
209 mDNSu32 slot;
210 FORALL_CACHERECORDS(slot, cg, cr)
211 {
212 if (cr->resrec.RecordType == 0 || cr->resrec.RecordType == 0xFF)
213 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot, cr, cr->resrec.RecordType);
214 if (cr->CRActiveQuestion)
215 {
216 for (q = m->Questions; q; q=q->next) if (q == cr->CRActiveQuestion) break;
217 if (!q) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot, cr->CRActiveQuestion, CRDisplayString(m, cr));
218 }
219 }
220
221 // Check core uDNS lists
222 udns_validatelists(m);
223
224 // Check platform-layer lists
225 NetworkInterfaceInfoOSX *i;
226 for (i = m->p->InterfaceList; i; i = i->next)
227 if (i->next == (NetworkInterfaceInfoOSX *)~0 || !i->m || i->m == (mDNS *)~0)
228 LogMemCorruption("m->p->InterfaceList: %p is garbage (%p)", i, i->ifinfo.ifname);
229
230 ClientTunnel *t;
231 for (t = m->TunnelClients; t; t=t->next)
232 if (t->next == (ClientTunnel *)~0 || t->dstname.c[0] > 63)
233 LogMemCorruption("m->TunnelClients: %p is garbage (%d)", t, t->dstname.c[0]);
234
235 #if BONJOUR_ON_DEMAND
236 if (m->NumAllInterfaceRecords != NumAllInterfaceRecords)
237 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m->NumAllInterfaceRecords, NumAllInterfaceRecords);
238
239 if (m->NumAllInterfaceQuestions != NumAllInterfaceQuestions)
240 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m->NumAllInterfaceQuestions, NumAllInterfaceQuestions);
241 #endif // BONJOUR_ON_DEMAND
242 }
243
244 mDNSexport void *mallocL(char *msg, unsigned int size)
245 {
246 // Allocate space for two words of sanity checking data before the requested block
247 mDNSu32 *mem = malloc(sizeof(mDNSu32) * 2 + size);
248 if (!mem)
249 { LogMsg("malloc( %s : %d ) failed", msg, size); return(NULL); }
250 else
251 {
252 if (size > 32768) LogMsg("malloc( %s : %lu ) @ %p suspiciously large", msg, size, &mem[2]);
253 else if (MACOSX_MDNS_MALLOC_DEBUGGING >= 2) LogMsg("malloc( %s : %lu ) @ %p", msg, size, &mem[2]);
254 mem[0] = 0xDEAD1234;
255 mem[1] = size;
256 //mDNSPlatformMemZero(&mem[2], size);
257 memset(&mem[2], 0xFF, size);
258 validatelists(&mDNSStorage);
259 return(&mem[2]);
260 }
261 }
262
263 mDNSexport void freeL(char *msg, void *x)
264 {
265 if (!x)
266 LogMsg("free( %s @ NULL )!", msg);
267 else
268 {
269 mDNSu32 *mem = ((mDNSu32 *)x) - 2;
270 if (mem[0] == 0xDEADDEAD) { LogMemCorruption("free( %s : %lu @ %p ) !!!! ALREADY DISPOSED !!!!", msg, mem[1], &mem[2]); return; }
271 if (mem[0] != 0xDEAD1234) { LogMemCorruption("free( %s : %lu @ %p ) !!!! NEVER ALLOCATED !!!!", msg, mem[1], &mem[2]); return; }
272 if (mem[1] > 32768) LogMsg("free( %s : %lu @ %p) suspiciously large", msg, mem[1], &mem[2]);
273 else if (MACOSX_MDNS_MALLOC_DEBUGGING >= 2) LogMsg("free( %s : %ld @ %p)", msg, mem[1], &mem[2]);
274 mem[0] = 0xDEADDEAD;
275 memset(mem+2, 0xFF, mem[1]);
276 validatelists(&mDNSStorage);
277 free(mem);
278 }
279 }
280
281 #endif
282
283 //*************************************************************************************************************
284 // Registration
285
286 mDNSexport void RecordUpdatedNiceLabel(mDNSs32 delay)
287 {
288 mDNSStorage.p->NotifyUser = NonZeroTime(mDNSStorage.timenow + delay);
289 }
290
291 mDNSlocal void mDNSPreferencesSetNames(int key, domainlabel *old, domainlabel *new)
292 {
293 mDNS *const m = &mDNSStorage;
294 domainlabel *prevold, *prevnew;
295 switch (key)
296 {
297 case kmDNSComputerName:
298 case kmDNSLocalHostName:
299 if (key == kmDNSComputerName)
300 {
301 prevold = &m->p->prevoldnicelabel;
302 prevnew = &m->p->prevnewnicelabel;
303 }
304 else
305 {
306 prevold = &m->p->prevoldhostlabel;
307 prevnew = &m->p->prevnewhostlabel;
308 }
309 // There are a few cases where we need to invoke the helper.
310 //
311 // 1. If the "old" label and "new" label are not same, it means there is a conflict. We need
312 // to invoke the helper so that it pops up a dialogue to inform the user about the
313 // conflict
314 //
315 // 2. If the "old" label and "new" label are same, it means the user has set the host/nice label
316 // through the preferences pane. We may have to inform the helper as it may have popped up
317 // a dialogue previously (due to a conflict) and it needs to suppress it now. We can avoid invoking
318 // the helper in this case if the previous values (old and new) that we told helper last time
319 // are same. If the previous old and new values are same, helper does not care.
320 //
321 // Note: "new" can be NULL when we have repeated conflicts and we are asking helper to give up. "old"
322 // is not called with NULL today, but this makes it future proof.
323 if (!old || !new || !SameDomainLabelCS(old->c, new->c) ||
324 !SameDomainLabelCS(old->c, prevold->c) ||
325 !SameDomainLabelCS(new->c, prevnew->c))
326 {
327 // Work around bug radar:21397654
328 #ifndef __clang_analyzer__
329 if (old)
330 *prevold = *old;
331 else
332 prevold->c[0] = 0;
333 if (new)
334 *prevnew = *new;
335 else
336 prevnew->c[0] = 0;
337 #endif
338 mDNSPreferencesSetName(key, old, new);
339 }
340 else
341 {
342 LogInfo("mDNSPreferencesSetNames not invoking helper %s %#s, %s %#s, old %#s, new %#s",
343 (key == kmDNSComputerName ? "prevoldnicelabel" : "prevoldhostlabel"), prevold->c,
344 (key == kmDNSComputerName ? "prevnewnicelabel" : "prevnewhostlabel"), prevnew->c,
345 old->c, new->c);
346 }
347 break;
348 default:
349 LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key);
350 return;
351 }
352 }
353
354 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
355 {
356 if (result == mStatus_NoError)
357 {
358 if (!SameDomainLabelCS(m->p->userhostlabel.c, m->hostlabel.c))
359 LogInfo("Local Hostname changed from \"%#s.local\" to \"%#s.local\"", m->p->userhostlabel.c, m->hostlabel.c);
360 // One second pause in case we get a Computer Name update too -- don't want to alert the user twice
361 RecordUpdatedNiceLabel(mDNSPlatformOneSecond);
362 }
363 else if (result == mStatus_NameConflict)
364 {
365 LogInfo("Local Hostname conflict for \"%#s.local\"", m->hostlabel.c);
366 if (!m->p->HostNameConflict) m->p->HostNameConflict = NonZeroTime(m->timenow);
367 else if (m->timenow - m->p->HostNameConflict > 60 * mDNSPlatformOneSecond)
368 {
369 // Tell the helper we've given up
370 mDNSPreferencesSetNames(kmDNSLocalHostName, &m->p->userhostlabel, NULL);
371 }
372 }
373 else if (result == mStatus_GrowCache)
374 {
375 // Allocate another chunk of cache storage
376 static unsigned int allocated = 0;
377 #if TARGET_OS_IPHONE
378 if (allocated >= kRRCacheMemoryLimit) return; // For now we limit the cache to at most 1MB on iOS devices
379 #endif
380 allocated += kRRCacheGrowSize;
381 // LogMsg("GrowCache %d * %d = %d; total so far %6u", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE, allocated);
382 CacheEntity *storage = mallocL("mStatus_GrowCache", sizeof(CacheEntity) * RR_CACHE_SIZE);
383 //LogInfo("GrowCache %d * %d = %d", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE);
384 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
385 }
386 else if (result == mStatus_ConfigChanged)
387 {
388 // Tell the helper we've seen a change in the labels. It will dismiss the name conflict alert if needed.
389 mDNSPreferencesSetNames(kmDNSComputerName, &m->p->usernicelabel, &m->nicelabel);
390 mDNSPreferencesSetNames(kmDNSLocalHostName, &m->p->userhostlabel, &m->hostlabel);
391
392 // Then we call into the UDS daemon code, to let it do the same
393 udsserver_handle_configchange(m);
394 }
395 }
396
397
398 //*************************************************************************************************************
399 #if COMPILER_LIKES_PRAGMA_MARK
400 #pragma mark -
401 #pragma mark - Startup, shutdown, and supporting code
402 #endif
403
404 mDNSlocal void ExitCallback(int sig)
405 {
406 (void)sig; // Unused
407 LogMsg("%s stopping", mDNSResponderVersionString);
408
409 if (udsserver_exit() < 0)
410 LogMsg("ExitCallback: udsserver_exit failed");
411
412 debugf("ExitCallback: mDNS_StartExit");
413 mDNS_StartExit(&mDNSStorage);
414 }
415
416 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
417
418 // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
419 mDNSlocal void HandleSIG(int sig)
420 {
421 kern_return_t status;
422 mach_msg_header_t header;
423
424 // WARNING: can't call syslog or fprintf from signal handler
425 header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND, 0);
426 header.msgh_remote_port = signal_port;
427 header.msgh_local_port = MACH_PORT_NULL;
428 header.msgh_size = sizeof(header);
429 header.msgh_id = sig;
430
431 status = mach_msg(&header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, header.msgh_size,
432 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
433
434 if (status != MACH_MSG_SUCCESS)
435 {
436 if (status == MACH_SEND_TIMED_OUT) mach_msg_destroy(&header);
437 if (sig == SIGTERM || sig == SIGINT) exit(-1);
438 }
439 }
440
441 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
442
443 mDNSexport void INFOCallback(void)
444 {
445 mDNSs32 utc = mDNSPlatformUTC();
446 const mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
447 NetworkInterfaceInfoOSX *i;
448 DNSServer *s;
449 McastResolver *mr;
450
451 LogMsg("---- BEGIN STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
452
453 udsserver_info();
454
455 LogMsgNoIdent("----- Platform Timers -----");
456 LogTimer("m->NextCacheCheck ", mDNSStorage.NextCacheCheck);
457 LogTimer("m->NetworkChanged ", mDNSStorage.NetworkChanged);
458 LogTimer("m->p->NotifyUser ", mDNSStorage.p->NotifyUser);
459 LogTimer("m->p->HostNameConflict ", mDNSStorage.p->HostNameConflict);
460 LogTimer("m->p->KeyChainTimer ", mDNSStorage.p->KeyChainTimer);
461
462 xpcserver_info(&mDNSStorage);
463
464 LogMsgNoIdent("----- KQSocketEventSources -----");
465 if (!gEventSources) LogMsgNoIdent("<None>");
466 else
467 {
468 KQSocketEventSource *k;
469 for (k = gEventSources; k; k=k->next)
470 LogMsgNoIdent("%3d %s %s", k->fd, k->kqs.KQtask, k->fd == mDNSStorage.uds_listener_skt ? "Listener for incoming UDS clients" : " ");
471 }
472
473 LogMsgNoIdent("------ Network Interfaces ------");
474 if (!mDNSStorage.p->InterfaceList) LogMsgNoIdent("<None>");
475 else
476 {
477 LogMsgNoIdent(" Struct addr Registered MAC BSSID Interface Address");
478 for (i = mDNSStorage.p->InterfaceList; i; i = i->next)
479 {
480 // Allow six characters for interface name, for names like "vmnet8"
481 if (!i->Exists)
482 LogMsgNoIdent("%p %2ld, %p, %s %-6s %.6a %.6a %#-14a dormant for %d seconds",
483 i, i->ifinfo.InterfaceID, i->Registered,
484 i->sa_family == AF_INET ? "v4" : i->sa_family == AF_INET6 ? "v6" : "??", i->ifinfo.ifname, &i->ifinfo.MAC, &i->BSSID,
485 &i->ifinfo.ip, utc - i->LastSeen);
486 else
487 {
488 const CacheRecord *sps[3];
489 FindSPSInCache(&mDNSStorage, &i->ifinfo.NetWakeBrowse, sps);
490 LogMsgNoIdent("%p %2ld, %p, %s %-6s %.6a %.6a %s %s %s %s %s %s %#a",
491 i, i->ifinfo.InterfaceID, i->Registered,
492 i->sa_family == AF_INET ? "v4" : i->sa_family == AF_INET6 ? "v6" : "??", i->ifinfo.ifname, &i->ifinfo.MAC, &i->BSSID,
493 i->ifinfo.InterfaceActive ? "Active" : " ",
494 i->ifinfo.IPv4Available ? "v4" : " ",
495 i->ifinfo.IPv6Available ? "v6" : " ",
496 i->ifinfo.Advertise ? "A" : " ",
497 i->ifinfo.McastTxRx ? "M" : " ",
498 !(i->ifinfo.InterfaceActive && i->ifinfo.NetWake) ? " " : !sps[0] ? "p" : "P",
499 &i->ifinfo.ip);
500
501 // Only print the discovered sleep proxies once for the lead/active interface of an interface set.
502 if (i == i->Registered && (sps[0] || sps[1] || sps[2]))
503 {
504 LogMsgNoIdent(" Sleep Proxy Metric Name");
505 if (sps[0]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps[0]->resrec.rdata->u.name.c), sps[0]->resrec.rdata->u.name.c);
506 if (sps[1]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps[1]->resrec.rdata->u.name.c), sps[1]->resrec.rdata->u.name.c);
507 if (sps[2]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps[2]->resrec.rdata->u.name.c), sps[2]->resrec.rdata->u.name.c);
508 }
509 }
510 }
511 }
512
513 LogMsgNoIdent("--------- DNS Servers(%d) ----------", NumUnicastDNSServers);
514 if (!mDNSStorage.DNSServers) LogMsgNoIdent("<None>");
515 else
516 {
517 for (s = mDNSStorage.DNSServers; s; s = s->next)
518 {
519 NetworkInterfaceInfoOSX *ifx = IfindexToInterfaceInfoOSX(s->interface);
520 LogMsgNoIdent("DNS Server %##s %s%s%#a:%d %d %s %d %d %s %s %s %s %s",
521 s->domain.c, ifx ? ifx->ifinfo.ifname : "", ifx ? " " : "", &s->addr, mDNSVal16(s->port),
522 s->penaltyTime ? s->penaltyTime - mDNS_TimeNow(&mDNSStorage) : 0, DNSScopeToString(s->scoped),
523 s->timeout, s->resGroupID,
524 s->req_A ? "v4" : "!v4",
525 s->req_AAAA ? "v6" : "!v6",
526 s->cellIntf ? "cell" : "!cell",
527 s->isExpensive ? "exp" : "!exp",
528 s->DNSSECAware ? "DNSSECAware" : "!DNSSECAware");
529 }
530 }
531
532 LogMsgNoIdent("v4answers %d", mDNSStorage.p->v4answers);
533 LogMsgNoIdent("v6answers %d", mDNSStorage.p->v6answers);
534 LogMsgNoIdent("Last DNS Trigger: %d ms ago", (now - mDNSStorage.p->DNSTrigger));
535
536 LogMsgNoIdent("--------- Mcast Resolvers ----------");
537 if (!mDNSStorage.McastResolvers) LogMsgNoIdent("<None>");
538 else
539 {
540 for (mr = mDNSStorage.McastResolvers; mr; mr = mr->next)
541 LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr->domain.c, mr->timeout);
542 }
543
544 LogMsgNoIdent("------------ Hostnames -------------");
545 if (!mDNSStorage.Hostnames) LogMsgNoIdent("<None>");
546 else
547 {
548 HostnameInfo *hi;
549 for (hi = mDNSStorage.Hostnames; hi; hi = hi->next)
550 {
551 LogMsgNoIdent("%##s v4 %d %s", hi->fqdn.c, hi->arv4.state, ARDisplayString(&mDNSStorage, &hi->arv4));
552 LogMsgNoIdent("%##s v6 %d %s", hi->fqdn.c, hi->arv6.state, ARDisplayString(&mDNSStorage, &hi->arv6));
553 }
554 }
555
556 LogMsgNoIdent("--------------- FQDN ---------------");
557 if (!mDNSStorage.FQDN.c[0]) LogMsgNoIdent("<None>");
558 else
559 {
560 LogMsgNoIdent("%##s", mDNSStorage.FQDN.c);
561 }
562
563 #if AWD_METRICS
564 LogMetrics();
565 #endif
566 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
567 LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
568 }
569
570
571 mDNSexport void mDNSPlatformLogToFile(int log_level, const char *buffer)
572 {
573 if (!log_general)
574 os_log_error(OS_LOG_DEFAULT, "Could NOT create log handle in init_logging()");
575 else
576 os_log_with_type(log_general, log_level, "%{private}s", buffer);
577
578 }
579
580 // Writes the state out to the dynamic store and also affects the ASL filter level
581 mDNSexport void UpdateDebugState()
582 {
583 mDNSu32 one = 1;
584 mDNSu32 zero = 0;
585
586 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
587 if (!dict)
588 {
589 LogMsg("UpdateDebugState: Could not create dict");
590 return;
591 }
592
593 CFNumberRef numOne = CFNumberCreate(NULL, kCFNumberSInt32Type, &one);
594 if (!numOne)
595 {
596 LogMsg("UpdateDebugState: Could not create CFNumber one");
597 return;
598 }
599 CFNumberRef numZero = CFNumberCreate(NULL, kCFNumberSInt32Type, &zero);
600 if (!numZero)
601 {
602 LogMsg("UpdateDebugState: Could not create CFNumber zero");
603 CFRelease(numOne);
604 return;
605 }
606
607 if (mDNS_LoggingEnabled)
608 CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numOne);
609 else
610 CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numZero);
611
612 if (mDNS_PacketLoggingEnabled)
613 CFDictionarySetValue(dict, CFSTR("PacketLogging"), numOne);
614 else
615 CFDictionarySetValue(dict, CFSTR("PacketLogging"), numZero);
616
617 if (mDNS_McastLoggingEnabled)
618 CFDictionarySetValue(dict, CFSTR("McastLogging"), numOne);
619 else
620 CFDictionarySetValue(dict, CFSTR("McastLogging"), numZero);
621
622 if (mDNS_McastTracingEnabled)
623 CFDictionarySetValue(dict, CFSTR("McastTracing"), numOne);
624 else
625 CFDictionarySetValue(dict, CFSTR("McastTracing"), numZero);
626
627 CFRelease(numOne);
628 CFRelease(numZero);
629 mDNSDynamicStoreSetConfig(kmDNSDebugState, mDNSNULL, dict);
630 CFRelease(dict);
631
632 }
633
634
635 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
636
637 mDNSlocal void SignalCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
638 {
639 (void)port; // Unused
640 (void)size; // Unused
641 (void)info; // Unused
642 mach_msg_header_t *msg_header = (mach_msg_header_t *)msg;
643 mDNS *const m = &mDNSStorage;
644
645 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
646 KQueueLock();
647 switch(msg_header->msgh_id)
648 {
649 case SIGHUP: {
650 mDNSu32 slot;
651 CacheGroup *cg;
652 CacheRecord *rr;
653 LogMsg("SIGHUP: Purge cache");
654 mDNS_Lock(m);
655 FORALL_CACHERECORDS(slot, cg, rr)
656 {
657 rr->resrec.mortality = Mortality_Mortal;
658 mDNS_PurgeCacheResourceRecord(m, rr);
659 }
660 // Restart unicast and multicast queries
661 mDNSCoreRestartQueries(m);
662 mDNS_Unlock(m);
663 } break;
664 case SIGINT:
665 case SIGTERM: ExitCallback(msg_header->msgh_id); break;
666 case SIGINFO: INFOCallback(); break;
667 case SIGUSR1:
668 #if APPLE_OSX_mDNSResponder
669 mDNS_LoggingEnabled = 1;
670 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
671 #else
672 mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
673 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
674 #endif
675 WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250;
676 UpdateDebugState();
677 LogInfo("USR1 Logging Enabled");
678 break;
679 case SIGUSR2:
680 #if APPLE_OSX_mDNSResponder
681 mDNS_PacketLoggingEnabled = 1;
682 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
683 #else
684 mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
685 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
686 #endif
687 mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse;
688 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
689 UpdateDebugState();
690 break;
691 case SIGPROF: mDNS_McastLoggingEnabled = mDNS_McastLoggingEnabled ? mDNSfalse : mDNStrue;
692 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled ? "Enabled" : "Disabled");
693 LogMcastStateInfo(mDNSfalse, mDNStrue, mDNStrue);
694 mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse;
695 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
696 UpdateDebugState();
697 break;
698 case SIGTSTP: mDNS_LoggingEnabled = mDNS_PacketLoggingEnabled = mDNS_McastLoggingEnabled = mDNS_McastTracingEnabled = mDNSfalse;
699 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
700 UpdateDebugState();
701 break;
702
703 default: LogMsg("SignalCallback: Unknown signal %d", msg_header->msgh_id); break;
704 }
705 KQueueUnlock("Unix Signal");
706 }
707
708 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
709 mDNSlocal kern_return_t mDNSDaemonInitialize(void)
710 {
711 mStatus err;
712
713 err = mDNS_Init(&mDNSStorage, &PlatformStorage,
714 rrcachestorage, RR_CACHE_SIZE,
715 !NoMulticastAdvertisements,
716 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
717
718 if (err)
719 {
720 LogMsg("Daemon start: mDNS_Init failed %d", err);
721 return(err);
722 }
723
724 #if TARGET_OS_IPHONE
725 if (PreallocateCacheMemory)
726 {
727 const int growCount = (kRRCacheMemoryLimit + kRRCacheGrowSize - 1) / kRRCacheGrowSize;
728 int i;
729
730 for (i = 0; i < growCount; ++i)
731 {
732 mDNS_StatusCallback(&mDNSStorage, mStatus_GrowCache);
733 }
734 }
735 #endif
736
737 CFMachPortRef i_port = CFMachPortCreate(NULL, SignalCallback, NULL, NULL);
738 CFRunLoopSourceRef i_rls = CFMachPortCreateRunLoopSource(NULL, i_port, 0);
739 signal_port = CFMachPortGetPort(i_port);
740 CFRunLoopAddSource(CFRunLoopGetMain(), i_rls, kCFRunLoopDefaultMode);
741 CFRelease(i_rls);
742
743 return(err);
744 }
745
746 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
747
748 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
749 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
750 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
751 // of code from above. Alternatively we could remove the duplicated source code by having
752 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
753
754 mDNSlocal void SignalDispatch(dispatch_source_t source)
755 {
756 int sig = (int)dispatch_source_get_handle(source);
757 mDNS *const m = &mDNSStorage;
758 KQueueLock();
759 switch(sig)
760 {
761 case SIGHUP: {
762 mDNSu32 slot;
763 CacheGroup *cg;
764 CacheRecord *rr;
765 LogMsg("SIGHUP: Purge cache");
766 mDNS_Lock(m);
767 FORALL_CACHERECORDS(slot, cg, rr)
768 {
769 rr->resrec.mortality = Mortality_Mortal;
770 mDNS_PurgeCacheResourceRecord(m, rr);
771 }
772 // Restart unicast and multicast queries
773 mDNSCoreRestartQueries(m);
774 mDNS_Unlock(m);
775 } break;
776 case SIGINT:
777 case SIGTERM: ExitCallback(sig); break;
778 case SIGINFO: INFOCallback(); break;
779 case SIGUSR1: mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
780 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
781 WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250;
782 UpdateDebugState();
783 break;
784 case SIGUSR2: mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
785 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
786 UpdateDebugState();
787 break;
788 default: LogMsg("SignalCallback: Unknown signal %d", sig); break;
789 }
790 KQueueUnlock("Unix Signal");
791 }
792
793 mDNSlocal void mDNSSetupSignal(dispatch_queue_t queue, int sig)
794 {
795 signal(sig, SIG_IGN);
796 dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, sig, 0, queue);
797
798 if (source)
799 {
800 dispatch_source_set_event_handler(source, ^{SignalDispatch(source);});
801 // Start processing signals
802 dispatch_resume(source);
803 }
804 else
805 {
806 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig);
807 }
808 }
809
810 mDNSlocal kern_return_t mDNSDaemonInitialize(void)
811 {
812 mStatus err;
813 dispatch_queue_t queue = dispatch_get_main_queue();
814
815 err = mDNS_Init(&mDNSStorage, &PlatformStorage,
816 rrcachestorage, RR_CACHE_SIZE,
817 !NoMulticastAdvertisements,
818 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
819
820 if (err)
821 {
822 LogMsg("Daemon start: mDNS_Init failed %d", err);
823 return(err);
824 }
825
826 mDNSSetupSignal(queue, SIGHUP);
827 mDNSSetupSignal(queue, SIGINT);
828 mDNSSetupSignal(queue, SIGTERM);
829 mDNSSetupSignal(queue, SIGINFO);
830 mDNSSetupSignal(queue, SIGUSR1);
831 mDNSSetupSignal(queue, SIGUSR2);
832
833 // Create a custom handler for doing the housekeeping work. This is either triggered
834 // by the timer or an event source
835 PlatformStorage.custom = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, queue);
836 if (PlatformStorage.custom == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
837 dispatch_source_set_event_handler(PlatformStorage.custom, ^{PrepareForIdle(&mDNSStorage);});
838 dispatch_resume(PlatformStorage.custom);
839
840 // Create a timer source to trigger housekeeping work. The houskeeping work itself
841 // is done in the custom handler that we set below.
842
843 PlatformStorage.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
844 if (PlatformStorage.timer == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
845
846 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
847 // always reset the time to the new time computed. In effect, we ignore the interval
848 dispatch_source_set_timer(PlatformStorage.timer, DISPATCH_TIME_NOW, 1000ull * 1000000000, 0);
849 dispatch_source_set_event_handler(PlatformStorage.timer, ^{
850 dispatch_source_merge_data(PlatformStorage.custom, 1);
851 });
852 dispatch_resume(PlatformStorage.timer);
853
854 LogMsg("DaemonIntialize done successfully");
855
856 return(err);
857 }
858
859 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
860
861 mDNSlocal mDNSs32 mDNSDaemonIdle(mDNS *const m)
862 {
863 mDNSs32 now = mDNS_TimeNow(m);
864
865 // 1. If we need to set domain secrets, do so before handling the network change
866 // Detailed reason:
867 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
868 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
869 if (m->p->KeyChainTimer && now - m->p->KeyChainTimer >= 0)
870 {
871 m->p->KeyChainTimer = 0;
872 mDNS_Lock(m);
873 SetDomainSecrets(m);
874 mDNS_Unlock(m);
875 }
876
877 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
878 // Detailed reason:
879 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
880 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
881 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
882 // we then systematically lose our own looped-back packets.
883 if (m->NetworkChanged && now - m->NetworkChanged >= 0) mDNSMacOSXNetworkChanged();
884
885 if (m->p->RequestReSleep && now - m->p->RequestReSleep >= 0)
886 {
887 m->p->RequestReSleep = 0;
888 mDNSPowerRequest(0, 0);
889 }
890
891 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
892 mDNSs32 nextevent = mDNS_Execute(m);
893
894 if (m->NetworkChanged)
895 if (nextevent - m->NetworkChanged > 0)
896 nextevent = m->NetworkChanged;
897
898 if (m->p->KeyChainTimer)
899 if (nextevent - m->p->KeyChainTimer > 0)
900 nextevent = m->p->KeyChainTimer;
901
902 if (m->p->RequestReSleep)
903 if (nextevent - m->p->RequestReSleep > 0)
904 nextevent = m->p->RequestReSleep;
905
906
907 if (m->p->NotifyUser)
908 {
909 if (m->p->NotifyUser - now < 0)
910 {
911 if (!SameDomainLabelCS(m->p->usernicelabel.c, m->nicelabel.c))
912 {
913 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m->p->usernicelabel.c, m->nicelabel.c);
914 mDNSPreferencesSetNames(kmDNSComputerName, &m->p->usernicelabel, &m->nicelabel);
915 m->p->usernicelabel = m->nicelabel;
916 }
917 if (!SameDomainLabelCS(m->p->userhostlabel.c, m->hostlabel.c))
918 {
919 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m->p->userhostlabel.c, m->hostlabel.c);
920 mDNSPreferencesSetNames(kmDNSLocalHostName, &m->p->userhostlabel, &m->hostlabel);
921 m->p->HostNameConflict = 0; // Clear our indicator, now name change has been successful
922 m->p->userhostlabel = m->hostlabel;
923 }
924 m->p->NotifyUser = 0;
925 }
926 else
927 if (nextevent - m->p->NotifyUser > 0)
928 nextevent = m->p->NotifyUser;
929 }
930
931 return(nextevent);
932 }
933
934 // Right now we consider *ALL* of our DHCP leases
935 // It might make sense to be a bit more selective and only consider the leases on interfaces
936 // (a) that are capable and enabled for wake-on-LAN, and
937 // (b) where we have found (and successfully registered with) a Sleep Proxy
938 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
939 mDNSlocal mDNSu32 DHCPWakeTime(void)
940 {
941 mDNSu32 e = 24 * 3600; // Maximum maintenance wake interval is 24 hours
942 const CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
943 if (!now) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
944 else
945 {
946 int ic, j;
947
948 const void *pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetDHCP);
949 if (!pattern)
950 {
951 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
952 return e;
953 }
954 CFArrayRef dhcpinfo = CFArrayCreate(NULL, (const void **)&pattern, 1, &kCFTypeArrayCallBacks);
955 CFRelease(pattern);
956 if (dhcpinfo)
957 {
958 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("DHCP-LEASES"), NULL, NULL);
959 if (store)
960 {
961 CFDictionaryRef dict = SCDynamicStoreCopyMultiple(store, NULL, dhcpinfo);
962 if (dict)
963 {
964 ic = CFDictionaryGetCount(dict);
965 const void *vals[ic];
966 CFDictionaryGetKeysAndValues(dict, NULL, vals);
967
968 for (j = 0; j < ic; j++)
969 {
970 const CFDictionaryRef dhcp = (CFDictionaryRef)vals[j];
971 if (dhcp)
972 {
973 const CFDateRef start = DHCPInfoGetLeaseStartTime(dhcp);
974 const CFDataRef lease = DHCPInfoGetOptionData(dhcp, 51); // Option 51 = IP Address Lease Time
975 if (!start || !lease || CFDataGetLength(lease) < 4)
976 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
977 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
978 j, start, lease, lease ? CFDataGetLength(lease) : 0);
979 else
980 {
981 const UInt8 *d = CFDataGetBytePtr(lease);
982 if (!d) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j);
983 else
984 {
985 const mDNSu32 elapsed = now - CFDateGetAbsoluteTime(start);
986 const mDNSu32 lifetime = (mDNSs32) ((mDNSs32)d[0] << 24 | (mDNSs32)d[1] << 16 | (mDNSs32)d[2] << 8 | d[3]);
987 const mDNSu32 remaining = lifetime - elapsed;
988 const mDNSu32 wake = remaining > 60 ? remaining - remaining/10 : 54; // Wake at 90% of the lease time
989 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed, lifetime, remaining, wake);
990 if (e > wake) e = wake;
991 }
992 }
993 }
994 }
995 CFRelease(dict);
996 }
997 CFRelease(store);
998 }
999 CFRelease(dhcpinfo);
1000 }
1001 }
1002 return(e);
1003 }
1004
1005 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
1006 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
1007 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
1008 // for a few seconds and then waking again is silly and annoying.
1009 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
1010 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
1011 // allowing us an adequate safety margin to renew our lease before we lose it.
1012
1013 mDNSlocal mDNSBool AllowSleepNow(mDNSs32 now)
1014 {
1015 mDNS *const m = &mDNSStorage;
1016 mDNSBool ready = mDNSCoreReadyForSleep(m, now);
1017 if (m->SleepState && !ready && now - m->SleepLimit < 0) return(mDNSfalse);
1018
1019 m->p->WakeAtUTC = 0;
1020 int result = kIOReturnSuccess;
1021 CFDictionaryRef opts = NULL;
1022
1023 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
1024 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
1025 if (!m->SleepState)
1026 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m->SleepLimit - now);
1027 else
1028 {
1029 if (!m->SystemWakeOnLANEnabled || !mDNSCoreHaveAdvertisedMulticastServices(m))
1030 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
1031 m->SystemWakeOnLANEnabled ? "is" : "not",
1032 mDNSCoreHaveAdvertisedMulticastServices(m) ? "have" : "no");
1033 else
1034 {
1035 mDNSs32 dhcp = DHCPWakeTime();
1036 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp);
1037 mDNSs32 interval = mDNSCoreIntervalToNextWake(m, now) / mDNSPlatformOneSecond;
1038 if (interval > dhcp) interval = dhcp;
1039
1040 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
1041 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
1042 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
1043 // someone to go to the machine in person to wake it up again, which would be unacceptable.
1044 if (!ready && interval > 3600) interval = 3600;
1045
1046 //interval = 48; // For testing
1047
1048 #if !TARGET_OS_EMBEDDED
1049 #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1050 if (m->p->IOPMConnection) // If lightweight-wake capability is available, use that
1051 {
1052 const CFDateRef WakeDate = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent() + interval);
1053 if (!WakeDate) LogMsg("ScheduleNextWake: CFDateCreate failed");
1054 else
1055 {
1056 const mDNSs32 reqs = kIOPMSystemPowerStateCapabilityNetwork;
1057 const CFNumberRef Requirements = CFNumberCreate(NULL, kCFNumberSInt32Type, &reqs);
1058 if (!Requirements) LogMsg("ScheduleNextWake: CFNumberCreate failed");
1059 else
1060 {
1061 const void *OptionKeys[2] = { kIOPMAckDHCPRenewWakeDate, kIOPMAckSystemCapabilityRequirements };
1062 const void *OptionVals[2] = { WakeDate, Requirements };
1063 opts = CFDictionaryCreate(NULL, (void*)OptionKeys, (void*)OptionVals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1064 if (!opts) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
1065 CFRelease(Requirements);
1066 }
1067 CFRelease(WakeDate);
1068 }
1069 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval);
1070 }
1071 else // else schedule the wakeup using the old API instead to
1072 #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1073 #endif // TARGET_OS_EMBEDDED
1074 {
1075 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
1076 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
1077 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
1078 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
1079 if (interval < 60)
1080 interval = 60;
1081
1082 result = mDNSPowerRequest(1, interval);
1083
1084 if (result == kIOReturnNotReady)
1085 {
1086 int r;
1087 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval);
1088 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
1089 // requested wake time is "too soon", but there's no API to find out what constitutes
1090 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
1091 // we just have to iterate with successively longer intervals until it doesn't fail.
1092 // We preserve the value of "result" because if our original power request was deemed "too soon"
1093 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
1094 // since the implication is that the system won't manage to be awake again at the time we need it.
1095 do
1096 {
1097 interval += (interval < 20) ? 1 : ((interval+3) / 4);
1098 r = mDNSPowerRequest(1, interval);
1099 }
1100 while (r == kIOReturnNotReady);
1101 if (r) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval, r, r);
1102 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval);
1103 }
1104 else
1105 {
1106 if (result) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval, result, result);
1107 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval);
1108 }
1109 m->p->WakeAtUTC = mDNSPlatformUTC() + interval;
1110 }
1111 }
1112
1113 m->SleepState = SleepState_Sleeping;
1114 // Clear our interface list to empty state, ready to go to sleep
1115 // As a side effect of doing this, we'll also cancel any outstanding SPS Resolve calls that didn't complete
1116 mDNSMacOSXNetworkChanged();
1117 }
1118
1119 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1120 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1121 (m->p->IOPMConnection) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1122 #endif
1123 (result == kIOReturnSuccess) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1124 m->p->SleepCookie, ready ? "ready for sleep" : "giving up", now, m->SleepLimit - now);
1125
1126 m->SleepLimit = 0; // Don't clear m->SleepLimit until after we've logged it above
1127 m->TimeSlept = mDNSPlatformUTC();
1128
1129 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1130 if (m->p->IOPMConnection) IOPMConnectionAcknowledgeEventWithOptions(m->p->IOPMConnection, m->p->SleepCookie, opts);
1131 else
1132 #endif
1133 if (result == kIOReturnSuccess) IOAllowPowerChange (m->p->PowerConnection, m->p->SleepCookie);
1134 else IOCancelPowerChange(m->p->PowerConnection, m->p->SleepCookie);
1135
1136 if (opts) CFRelease(opts);
1137 return(mDNStrue);
1138 }
1139
1140 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1141
1142 mDNSexport void TriggerEventCompletion()
1143 {
1144 debugf("TriggerEventCompletion: Merge data");
1145 dispatch_source_merge_data(PlatformStorage.custom, 1);
1146 }
1147
1148 mDNSlocal void PrepareForIdle(void *m_param)
1149 {
1150 mDNS *m = m_param;
1151 int64_t time_offset;
1152 dispatch_time_t dtime;
1153
1154 const int multiplier = 1000000000 / mDNSPlatformOneSecond;
1155
1156 // This is the main work loop:
1157 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1158 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1159 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1160
1161 debugf("PrepareForIdle: called");
1162 // Run mDNS_Execute to find out the time we next need to wake up
1163 mDNSs32 start = mDNSPlatformRawTime();
1164 mDNSs32 nextTimerEvent = udsserver_idle(mDNSDaemonIdle(m));
1165 mDNSs32 end = mDNSPlatformRawTime();
1166 if (end - start >= WatchDogReportingThreshold)
1167 LogInfo("CustomSourceHandler:WARNING: Idle task took %dms to complete", end - start);
1168
1169 mDNSs32 now = mDNS_TimeNow(m);
1170
1171 if (m->ShutdownTime)
1172 {
1173 if (mDNSStorage.ResourceRecords)
1174 {
1175 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m, mDNSStorage.ResourceRecords));
1176 if (mDNS_LoggingEnabled) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1177 }
1178 if (mDNS_ExitNow(m, now))
1179 {
1180 LogInfo("IdleLoop: mDNS_FinalExit");
1181 mDNS_FinalExit(&mDNSStorage);
1182 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1183 exit(0);
1184 }
1185 if (nextTimerEvent - m->ShutdownTime >= 0)
1186 nextTimerEvent = m->ShutdownTime;
1187 }
1188
1189 if (m->SleepLimit)
1190 if (!AllowSleepNow(now))
1191 if (nextTimerEvent - m->SleepLimit >= 0)
1192 nextTimerEvent = m->SleepLimit;
1193
1194 // Convert absolute wakeup time to a relative time from now
1195 mDNSs32 ticks = nextTimerEvent - now;
1196 if (ticks < 1) ticks = 1;
1197
1198 static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins
1199 if (ticks > 1)
1200 RepeatedBusy = 0;
1201 else
1202 {
1203 ticks = 1;
1204 if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
1205 }
1206
1207 time_offset = ((mDNSu32)ticks / mDNSPlatformOneSecond) * 1000000000 + (ticks % mDNSPlatformOneSecond) * multiplier;
1208 dtime = dispatch_time(DISPATCH_TIME_NOW, time_offset);
1209 dispatch_source_set_timer(PlatformStorage.timer, dtime, 1000ull*1000000000, 0);
1210 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks);
1211 return;
1212 }
1213
1214 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1215
1216 mDNSlocal void KQWokenFlushBytes(int fd, __unused short filter, __unused void *context, __unused mDNSBool encounteredEOF)
1217 {
1218 // Read all of the bytes so we won't wake again.
1219 char buffer[100];
1220 while (recv(fd, buffer, sizeof(buffer), MSG_DONTWAIT) > 0) continue;
1221 }
1222
1223 mDNSlocal void SetLowWater(const KQSocketSet *const k, const int r)
1224 {
1225 if (k->sktv4 >=0 && setsockopt(k->sktv4, SOL_SOCKET, SO_RCVLOWAT, &r, sizeof(r)) < 0)
1226 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k->sktv4, r, errno, strerror(errno));
1227 if (k->sktv6 >=0 && setsockopt(k->sktv6, SOL_SOCKET, SO_RCVLOWAT, &r, sizeof(r)) < 0)
1228 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k->sktv6, r, errno, strerror(errno));
1229 }
1230
1231 mDNSlocal void * KQueueLoop(void *m_param)
1232 {
1233 mDNS *m = m_param;
1234 int numevents = 0;
1235
1236 #if USE_SELECT_WITH_KQUEUEFD
1237 fd_set readfds;
1238 FD_ZERO(&readfds);
1239 const int multiplier = 1000000 / mDNSPlatformOneSecond;
1240 #else
1241 const int multiplier = 1000000000 / mDNSPlatformOneSecond;
1242 #endif
1243
1244 pthread_mutex_lock(&PlatformStorage.BigMutex);
1245 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32)mDNSStorage.timenow_last, mDNSStorage.timenow_last);
1246
1247 // This is the main work loop:
1248 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1249 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1250 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1251 // (4) On wakeup we first process *all* events
1252 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
1253 for ( ; ; )
1254 {
1255 #define kEventsToReadAtOnce 1
1256 struct kevent new_events[kEventsToReadAtOnce];
1257
1258 // Run mDNS_Execute to find out the time we next need to wake up
1259 mDNSs32 start = mDNSPlatformRawTime();
1260 mDNSs32 nextTimerEvent = udsserver_idle(mDNSDaemonIdle(m));
1261 mDNSs32 end = mDNSPlatformRawTime();
1262 if (end - start >= WatchDogReportingThreshold)
1263 LogInfo("WARNING: Idle task took %dms to complete", end - start);
1264
1265 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
1266 validatelists(m);
1267 #endif
1268
1269 mDNSs32 now = mDNS_TimeNow(m);
1270
1271 if (m->ShutdownTime)
1272 {
1273 if (mDNSStorage.ResourceRecords)
1274 {
1275 AuthRecord *rr;
1276 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
1277 {
1278 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m, rr));
1279 if (mDNS_LoggingEnabled) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1280 }
1281 }
1282 if (mDNS_ExitNow(m, now))
1283 {
1284 LogInfo("mDNS_FinalExit");
1285 mDNS_FinalExit(&mDNSStorage);
1286 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1287 exit(0);
1288 }
1289 if (nextTimerEvent - m->ShutdownTime >= 0)
1290 nextTimerEvent = m->ShutdownTime;
1291 }
1292
1293 if (m->SleepLimit)
1294 if (!AllowSleepNow(now))
1295 if (nextTimerEvent - m->SleepLimit >= 0)
1296 nextTimerEvent = m->SleepLimit;
1297
1298 // Convert absolute wakeup time to a relative time from now
1299 mDNSs32 ticks = nextTimerEvent - now;
1300 if (ticks < 1) ticks = 1;
1301
1302 static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins
1303 if (ticks > 1)
1304 RepeatedBusy = 0;
1305 else
1306 {
1307 ticks = 1;
1308 if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
1309 }
1310
1311 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents, ticks);
1312 numevents = 0;
1313
1314 // Release the lock, and sleep until:
1315 // 1. Something interesting happens like a packet arriving, or
1316 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
1317 // 3. The timeout expires
1318 pthread_mutex_unlock(&PlatformStorage.BigMutex);
1319
1320 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1321 if (m->p->num_mcasts)
1322 {
1323 SetLowWater(&m->p->permanentsockets, 0x10000);
1324 if (ticks > mDNSPlatformOneSecond / 8) ticks = mDNSPlatformOneSecond / 8;
1325 }
1326
1327 #if USE_SELECT_WITH_KQUEUEFD
1328 struct timeval timeout;
1329 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
1330 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * multiplier;
1331 FD_SET(KQueueFD, &readfds);
1332 if (select(KQueueFD+1, &readfds, NULL, NULL, &timeout) < 0)
1333 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD, errno, strerror(errno)); sleep(1); }
1334 #else
1335 struct timespec timeout;
1336 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
1337 timeout.tv_nsec = (ticks % mDNSPlatformOneSecond) * multiplier;
1338 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
1339 // and have it work similarly to the way it does with nevents non-zero --
1340 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
1341 // In fact, what happens if you do this is that it just returns immediately. So, we have
1342 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
1343 if (kevent(KQueueFD, NULL, 0, new_events, 1, &timeout) < 0)
1344 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD, errno, strerror(errno)); sleep(1); }
1345 #endif
1346
1347 pthread_mutex_lock(&PlatformStorage.BigMutex);
1348 // We have to ignore the event we may have been told about above, because that
1349 // was done without holding the lock, and between the time we woke up and the
1350 // time we reclaimed the lock the other thread could have done something that
1351 // makes the event no longer valid. Now we have the lock, we call kevent again
1352 // and this time we can safely process the events it tells us about.
1353
1354 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
1355 if (m->p->num_mcasts)
1356 {
1357 SetLowWater(&m->p->permanentsockets, 1);
1358 m->p->num_mcasts = 0;
1359 }
1360
1361 static const struct timespec zero_timeout = { 0, 0 };
1362 int events_found;
1363 while ((events_found = kevent(KQueueFD, NULL, 0, new_events, kEventsToReadAtOnce, &zero_timeout)) != 0)
1364 {
1365 if (events_found > kEventsToReadAtOnce || (events_found < 0 && errno != EINTR))
1366 {
1367 const int kevent_errno = errno;
1368 // Not sure what to do here, our kqueue has failed us - this isn't ideal
1369 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", kevent_errno, strerror(kevent_errno));
1370 exit(kevent_errno);
1371 }
1372
1373 numevents += events_found;
1374
1375 int i;
1376 for (i = 0; i < events_found; i++)
1377 {
1378 const KQueueEntry *const kqentry = new_events[i].udata;
1379 mDNSs32 stime = mDNSPlatformRawTime();
1380 const char *const KQtask = kqentry->KQtask; // Grab a copy in case KQcallback deletes the task
1381 kqentry->KQcallback(new_events[i].ident, new_events[i].filter, kqentry->KQcontext, (new_events[i].flags & EV_EOF) != 0);
1382 mDNSs32 etime = mDNSPlatformRawTime();
1383 if (etime - stime >= WatchDogReportingThreshold)
1384 LogInfo("WARNING: %s took %dms to complete", KQtask, etime - stime);
1385 }
1386 }
1387 }
1388
1389 return NULL;
1390 }
1391
1392 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1393
1394 mDNSlocal size_t LaunchdCheckin(void)
1395 {
1396 // Ask launchd for our socket
1397 int result = launch_activate_socket("Listeners", &launchd_fds, &launchd_fds_count);
1398 if (result != 0) { LogMsg("launch_activate_socket() failed error %d (%s)", result, strerror(result)); }
1399 return launchd_fds_count;
1400 }
1401
1402
1403 extern int sandbox_init(const char *profile, uint64_t flags, char **errorbuf) __attribute__((weak_import));
1404
1405 #if APPLE_OSX_mDNSResponder
1406 mDNSlocal mDNSBool PreferencesGetValueBool(CFStringRef key, mDNSBool defaultValue)
1407 {
1408 CFBooleanRef boolean;
1409 mDNSBool result = defaultValue;
1410
1411 boolean = CFPreferencesCopyAppValue(key, kProgramArguments);
1412 if (boolean)
1413 {
1414 if (CFGetTypeID(boolean) == CFBooleanGetTypeID())
1415 result = CFBooleanGetValue(boolean) ? mDNStrue : mDNSfalse;
1416 CFRelease(boolean);
1417 }
1418
1419 return result;
1420 }
1421
1422 mDNSlocal int PreferencesGetValueInt(CFStringRef key, int defaultValue)
1423 {
1424 CFNumberRef number;
1425 int numberValue;
1426 int result = defaultValue;
1427
1428 number = CFPreferencesCopyAppValue(key, kProgramArguments);
1429 if (number)
1430 {
1431 if ((CFGetTypeID(number) == CFNumberGetTypeID()) && CFNumberGetValue(number, kCFNumberIntType, &numberValue))
1432 result = numberValue;
1433 CFRelease(number);
1434 }
1435
1436 return result;
1437 }
1438 #endif
1439
1440 mDNSlocal void SandboxProcess(void)
1441 {
1442 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1443 #if MDNS_NO_SANDBOX
1444 LogMsg("Note: Compiled without Apple Sandbox support");
1445 #else // MDNS_NO_SANDBOX
1446 if (!sandbox_init)
1447 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1448 else
1449 {
1450 char *sandbox_msg;
1451 uint64_t sandbox_flags = SANDBOX_NAMED;
1452
1453 (void)confstr(_CS_DARWIN_USER_CACHE_DIR, NULL, 0);
1454
1455 int sandbox_err = sandbox_init("mDNSResponder", sandbox_flags, &sandbox_msg);
1456 if (sandbox_err)
1457 {
1458 LogMsg("WARNING: sandbox_init error %s", sandbox_msg);
1459 // If we have errors in the sandbox during development, to prevent
1460 // exiting, uncomment the following line.
1461 //sandbox_free_error(sandbox_msg);
1462
1463 errx(EX_OSERR, "sandbox_init() failed: %s", sandbox_msg);
1464 }
1465 else LogInfo("Now running under Apple Sandbox restrictions");
1466 }
1467 #endif // MDNS_NO_SANDBOX
1468 }
1469
1470 #if APPLE_OSX_mDNSResponder
1471 mDNSlocal void init_logging(void)
1472 {
1473 log_general = os_log_create("com.apple.mDNSResponder", "AllINFO");
1474
1475 if (!log_general)
1476 {
1477 // OS_LOG_DEFAULT is the default logging object, if you are not creating a custom subsystem/category
1478 os_log_error(OS_LOG_DEFAULT, "Could NOT create log handle in mDNSResponder");
1479 }
1480 }
1481 #endif
1482
1483 #ifdef UNIT_TEST
1484 // Run the unit test main
1485 UNITTEST_MAIN
1486 #else
1487 mDNSexport int main(int argc, char **argv)
1488 {
1489 int i;
1490 kern_return_t status;
1491
1492 #if DEBUG
1493 bool useDebugSocket = mDNSfalse;
1494 bool useSandbox = mDNStrue;
1495 #endif
1496
1497 #if APPLE_OSX_mDNSResponder
1498 init_logging();
1499 #endif
1500
1501 mDNSMacOSXSystemBuildNumber(NULL);
1502 LogMsg("%s starting %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
1503
1504 #if 0
1505 LogMsg("CacheRecord %5d", sizeof(CacheRecord));
1506 LogMsg("CacheGroup %5d", sizeof(CacheGroup));
1507 LogMsg("ResourceRecord %5d", sizeof(ResourceRecord));
1508 LogMsg("RData_small %5d", sizeof(RData_small));
1509
1510 LogMsg("sizeof(CacheEntity) %5d", sizeof(CacheEntity));
1511 LogMsg("RR_CACHE_SIZE %5d", RR_CACHE_SIZE);
1512 LogMsg("block bytes used %5d", sizeof(CacheEntity) * RR_CACHE_SIZE);
1513 LogMsg("block bytes wasted %5d", 32*1024 - sizeof(CacheEntity) * RR_CACHE_SIZE);
1514 #endif
1515
1516 if (0 == geteuid())
1517 {
1518 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1519 return -1;
1520 }
1521
1522 for (i=1; i<argc; i++)
1523 {
1524 if (!strcasecmp(argv[i], "-d" )) mDNS_DebugMode = mDNStrue;
1525 if (!strcasecmp(argv[i], "-NoMulticastAdvertisements")) NoMulticastAdvertisements = mDNStrue;
1526 if (!strcasecmp(argv[i], "-DisableSleepProxyClient" )) DisableSleepProxyClient = mDNStrue;
1527 if (!strcasecmp(argv[i], "-DebugLogging" )) mDNS_LoggingEnabled = mDNStrue;
1528 if (!strcasecmp(argv[i], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled = mDNStrue;
1529 if (!strcasecmp(argv[i], "-OfferSleepProxyService" ))
1530 OfferSleepProxyService = (i+1 < argc && mDNSIsDigit(argv[i+1][0]) && mDNSIsDigit(argv[i+1][1]) && argv[i+1][2]==0) ? atoi(argv[++i]) : 100;
1531 if (!strcasecmp(argv[i], "-UseInternalSleepProxy" ))
1532 UseInternalSleepProxy = (i+1<argc && mDNSIsDigit(argv[i+1][0]) && argv[i+1][1]==0) ? atoi(argv[++i]) : 1;
1533 if (!strcasecmp(argv[i], "-StrictUnicastOrdering" )) StrictUnicastOrdering = mDNStrue;
1534 if (!strcasecmp(argv[i], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains = mDNStrue;
1535 if (!strcasecmp(argv[i], "-DisableAllowExpired" )) EnableAllowExpired = mDNSfalse;
1536 #if DEBUG
1537 if (!strcasecmp(argv[i], "-UseDebugSocket")) useDebugSocket = mDNStrue;
1538 if (!strcasecmp(argv[i], "-NoSandbox")) useSandbox = mDNSfalse;
1539 #endif
1540 }
1541
1542
1543 #if APPLE_OSX_mDNSResponder
1544 /* Reads the external user's program arguments for mDNSResponder starting 10.11.x(El Capitan) on OSX. The options for external user are:
1545 DebugLogging, UnicastPacketLogging, NoMulticastAdvertisements, StrictUnicastOrdering and AlwaysAppendSearchDomains
1546
1547 To turn ON the particular option, here is what the user should do (as an example of setting two options)
1548 1] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool YES
1549 2] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
1550 3] sudo reboot
1551
1552 To turn OFF all options, here is what the user should do
1553 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1554 2] sudo reboot
1555
1556 To view the current options set, here is what the user should do
1557 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1558 OR
1559 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
1560
1561 */
1562
1563 // Currently on Fuji/Whitetail releases we are keeping the logging always enabled.
1564 // Hence mDNS_LoggingEnabled and mDNS_PacketLoggingEnabled is set to true below by default.
1565 #if 0
1566 mDNS_LoggingEnabled = PreferencesGetValueBool(kPreferencesKey_DebugLogging, mDNS_LoggingEnabled);
1567 mDNS_PacketLoggingEnabled = PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging, mDNS_PacketLoggingEnabled);
1568 #endif
1569
1570 mDNS_LoggingEnabled = mDNStrue;
1571 mDNS_PacketLoggingEnabled = mDNStrue;
1572
1573 NoMulticastAdvertisements = PreferencesGetValueBool(kPreferencesKey_NoMulticastAdvertisements, NoMulticastAdvertisements);
1574 StrictUnicastOrdering = PreferencesGetValueBool(kPreferencesKey_StrictUnicastOrdering, StrictUnicastOrdering);
1575 AlwaysAppendSearchDomains = PreferencesGetValueBool(kPreferencesKey_AlwaysAppendSearchDomains, AlwaysAppendSearchDomains);
1576 EnableAllowExpired = PreferencesGetValueBool(kPreferencesKey_EnableAllowExpired, EnableAllowExpired);
1577 OfferSleepProxyService = PreferencesGetValueInt(kPreferencesKey_OfferSleepProxyService, OfferSleepProxyService);
1578 UseInternalSleepProxy = PreferencesGetValueInt(kPreferencesKey_UseInternalSleepProxy, UseInternalSleepProxy);
1579
1580 #if ENABLE_BLE_TRIGGERED_BONJOUR
1581 EnableBLEBasedDiscovery = PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery, EnableBLEBasedDiscovery);
1582 DefaultToBLETriggered = PreferencesGetValueBool(kPreferencesKey_DefaultToBLETriggered, DefaultToBLETriggered);
1583 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
1584
1585 #if TARGET_OS_IPHONE
1586 PreallocateCacheMemory = PreferencesGetValueBool(kPreferencesKey_PreallocateCacheMemory, PreallocateCacheMemory);
1587 #endif
1588 #endif
1589
1590 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
1591 if (NoMulticastAdvertisements)
1592 LogMsg("-NoMulticastAdvertisements is set: Administratively prohibiting multicast advertisements");
1593 if (AlwaysAppendSearchDomains)
1594 LogMsg("-AlwaysAppendSearchDomains is set");
1595 if (StrictUnicastOrdering)
1596 LogMsg("-StrictUnicastOrdering is set");
1597
1598 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1599
1600 signal(SIGHUP, HandleSIG); // (Debugging) Purge the cache to check for cache handling bugs
1601 signal(SIGINT, HandleSIG); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
1602 signal(SIGPIPE, SIG_IGN); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
1603 signal(SIGTERM, HandleSIG); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
1604 signal(SIGINFO, HandleSIG); // (Debugging) Write state snapshot to syslog
1605 signal(SIGUSR1, HandleSIG); // (Debugging) Enable Logging
1606 signal(SIGUSR2, HandleSIG); // (Debugging) Enable Packet Logging
1607 signal(SIGPROF, HandleSIG); // (Debugging) Toggle Multicast Logging
1608 signal(SIGTSTP, HandleSIG); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
1609
1610 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1611
1612 mDNSStorage.p = &PlatformStorage; // Make sure mDNSStorage.p is set up, because validatelists uses it
1613 // Need to Start XPC Server Before LaunchdCheckin() (Reason: rdar11023750)
1614 xpc_server_init();
1615 #if DEBUG
1616 if (!useDebugSocket) {
1617 if (LaunchdCheckin() == 0)
1618 useDebugSocket = mDNStrue;
1619 }
1620 if (useDebugSocket)
1621 SetDebugBoundPath();
1622 #else
1623 LaunchdCheckin();
1624 #endif
1625
1626 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1627
1628 // Create the kqueue, mutex and thread to support KQSockets
1629 KQueueFD = kqueue();
1630 if (KQueueFD == -1)
1631 {
1632 const int kqueue_errno = errno;
1633 LogMsg("kqueue() failed errno %d (%s)", kqueue_errno, strerror(kqueue_errno));
1634 status = kqueue_errno;
1635 goto exit;
1636 }
1637
1638 i = pthread_mutex_init(&PlatformStorage.BigMutex, NULL);
1639 if (i != 0) { LogMsg("pthread_mutex_init() failed error %d (%s)", i, strerror(i)); status = i; goto exit; }
1640
1641 int fdpair[2] = {0, 0};
1642 i = socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair);
1643 if (i == -1)
1644 {
1645 const int socketpair_errno = errno;
1646 LogMsg("socketpair() failed errno %d (%s)", socketpair_errno, strerror(socketpair_errno));
1647 status = socketpair_errno;
1648 goto exit;
1649 }
1650
1651 // Socket pair returned us two identical sockets connected to each other
1652 // We will use the first socket to send the second socket. The second socket
1653 // will be added to the kqueue so it will wake when data is sent.
1654 static const KQueueEntry wakeKQEntry = { KQWokenFlushBytes, NULL, "kqueue wakeup after CFRunLoop event" };
1655
1656 PlatformStorage.WakeKQueueLoopFD = fdpair[0];
1657 KQueueSet(fdpair[1], EV_ADD, EVFILT_READ, &wakeKQEntry);
1658
1659 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1660
1661 #if DEBUG
1662 if (useSandbox)
1663 #endif
1664 SandboxProcess();
1665
1666 #if AWD_METRICS
1667 status = MetricsInit();
1668 if (status) { LogMsg("Daemon start: MetricsInit failed (%d)", status); }
1669 #endif
1670
1671 status = mDNSDaemonInitialize();
1672 if (status) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit; }
1673
1674 status = udsserver_init(launchd_fds, launchd_fds_count);
1675 if (status) { LogMsg("Daemon start: udsserver_init failed"); goto exit; }
1676
1677 mDNSMacOSXNetworkChanged();
1678 UpdateDebugState();
1679
1680 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1681 LogInfo("Daemon Start: Using LibDispatch");
1682 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
1683 CFRunLoopRun();
1684 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1685 // Start the kqueue thread
1686 pthread_t KQueueThread;
1687 i = pthread_create(&KQueueThread, NULL, KQueueLoop, &mDNSStorage);
1688 if (i != 0) { LogMsg("pthread_create() failed error %d (%s)", i, strerror(i)); status = i; goto exit; }
1689 if (status == 0)
1690 {
1691 CFRunLoopRun();
1692 LogMsg("ERROR: CFRunLoopRun Exiting.");
1693 mDNS_Close(&mDNSStorage);
1694 }
1695 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1696
1697 LogMsg("%s exiting", mDNSResponderVersionString);
1698
1699 exit:
1700 return(status);
1701 }
1702 #endif // UNIT_TEST
1703
1704 // uds_daemon.c support routines /////////////////////////////////////////////
1705
1706 mDNSlocal void kqUDSEventCallback(int fd, short filter, void *context, __unused mDNSBool encounteredEOF)
1707 {
1708 const KQSocketEventSource *const source = context;
1709 source->callback(fd, filter, source->context);
1710 }
1711
1712 // Arrange things so that when data appears on fd, callback is called with context
1713 mDNSexport mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
1714 {
1715 KQSocketEventSource **p = &gEventSources;
1716 (void) platform_data;
1717 while (*p && (*p)->fd != fd) p = &(*p)->next;
1718 if (*p) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd); return mStatus_AlreadyRegistered; }
1719
1720 KQSocketEventSource *newSource = (KQSocketEventSource*) mallocL("KQSocketEventSource", sizeof *newSource);
1721 if (!newSource) return mStatus_NoMemoryErr;
1722
1723 newSource->next = mDNSNULL;
1724 newSource->fd = fd;
1725 newSource->callback = callback;
1726 newSource->context = context;
1727 newSource->kqs.KQcallback = kqUDSEventCallback;
1728 newSource->kqs.KQcontext = newSource;
1729 newSource->kqs.KQtask = "UDS client";
1730 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1731 newSource->kqs.readSource = mDNSNULL;
1732 newSource->kqs.writeSource = mDNSNULL;
1733 newSource->kqs.fdClosed = mDNSfalse;
1734 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1735
1736 if (KQueueSet(fd, EV_ADD, EVFILT_READ, &newSource->kqs) == 0)
1737 {
1738 *p = newSource;
1739 return mStatus_NoError;
1740 }
1741
1742 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd, errno, strerror(errno));
1743 freeL("KQSocketEventSource", newSource);
1744 return mStatus_BadParamErr;
1745 }
1746
1747 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
1748 {
1749 (void) platform_data;
1750 return recv(fd, buf, len, flags);
1751 }
1752
1753 mDNSexport mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor
1754 {
1755 KQSocketEventSource **p = &gEventSources;
1756 (void) platform_data;
1757 while (*p && (*p)->fd != fd) p = &(*p)->next;
1758 if (*p)
1759 {
1760 KQSocketEventSource *s = *p;
1761 *p = (*p)->next;
1762 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
1763 // causes the kernel to automatically remove any associated kevents
1764 mDNSPlatformCloseFD(&s->kqs, s->fd);
1765 freeL("KQSocketEventSource", s);
1766 return mStatus_NoError;
1767 }
1768 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd);
1769 return mStatus_NoSuchNameErr;
1770 }
1771
1772 #ifdef UNIT_TEST
1773 #include "../unittests/daemon_ut.c"
1774 #endif // UNIT_TEST
1775
1776 #if _BUILDING_XCODE_PROJECT_
1777 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
1778 const char *__crashreporter_info__ = mDNSResponderVersionString;
1779 asm (".desc ___crashreporter_info__, 0x10");
1780 #endif
1781
1782 // For convenience when using the "strings" command, this is the last thing in the file
1783 // The "@(#) " pattern is a special prefix the "what" command looks for
1784 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";