]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/daemon.c
mDNSResponder-878.230.2.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 %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->isCLAT46 ? "clat46" : "!clat46",
529 s->DNSSECAware ? "DNSSECAware" : "!DNSSECAware");
530 }
531 }
532
533 LogMsgNoIdent("v4answers %d", mDNSStorage.p->v4answers);
534 LogMsgNoIdent("v6answers %d", mDNSStorage.p->v6answers);
535 LogMsgNoIdent("Last DNS Trigger: %d ms ago", (now - mDNSStorage.p->DNSTrigger));
536
537 LogMsgNoIdent("--------- Mcast Resolvers ----------");
538 if (!mDNSStorage.McastResolvers) LogMsgNoIdent("<None>");
539 else
540 {
541 for (mr = mDNSStorage.McastResolvers; mr; mr = mr->next)
542 LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr->domain.c, mr->timeout);
543 }
544
545 LogMsgNoIdent("------------ Hostnames -------------");
546 if (!mDNSStorage.Hostnames) LogMsgNoIdent("<None>");
547 else
548 {
549 HostnameInfo *hi;
550 for (hi = mDNSStorage.Hostnames; hi; hi = hi->next)
551 {
552 LogMsgNoIdent("%##s v4 %d %s", hi->fqdn.c, hi->arv4.state, ARDisplayString(&mDNSStorage, &hi->arv4));
553 LogMsgNoIdent("%##s v6 %d %s", hi->fqdn.c, hi->arv6.state, ARDisplayString(&mDNSStorage, &hi->arv6));
554 }
555 }
556
557 LogMsgNoIdent("--------------- FQDN ---------------");
558 if (!mDNSStorage.FQDN.c[0]) LogMsgNoIdent("<None>");
559 else
560 {
561 LogMsgNoIdent("%##s", mDNSStorage.FQDN.c);
562 }
563
564 #if AWD_METRICS
565 LogMetrics();
566 #endif
567 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
568 LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
569 }
570
571
572 mDNSexport void mDNSPlatformLogToFile(int log_level, const char *buffer)
573 {
574 if (!log_general)
575 os_log_error(OS_LOG_DEFAULT, "Could NOT create log handle in init_logging()");
576 else
577 os_log_with_type(log_general, log_level, "%{private}s", buffer);
578
579 }
580
581 // Writes the state out to the dynamic store and also affects the ASL filter level
582 mDNSexport void UpdateDebugState()
583 {
584 mDNSu32 one = 1;
585 mDNSu32 zero = 0;
586
587 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
588 if (!dict)
589 {
590 LogMsg("UpdateDebugState: Could not create dict");
591 return;
592 }
593
594 CFNumberRef numOne = CFNumberCreate(NULL, kCFNumberSInt32Type, &one);
595 if (!numOne)
596 {
597 LogMsg("UpdateDebugState: Could not create CFNumber one");
598 return;
599 }
600 CFNumberRef numZero = CFNumberCreate(NULL, kCFNumberSInt32Type, &zero);
601 if (!numZero)
602 {
603 LogMsg("UpdateDebugState: Could not create CFNumber zero");
604 CFRelease(numOne);
605 return;
606 }
607
608 if (mDNS_LoggingEnabled)
609 CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numOne);
610 else
611 CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numZero);
612
613 if (mDNS_PacketLoggingEnabled)
614 CFDictionarySetValue(dict, CFSTR("PacketLogging"), numOne);
615 else
616 CFDictionarySetValue(dict, CFSTR("PacketLogging"), numZero);
617
618 if (mDNS_McastLoggingEnabled)
619 CFDictionarySetValue(dict, CFSTR("McastLogging"), numOne);
620 else
621 CFDictionarySetValue(dict, CFSTR("McastLogging"), numZero);
622
623 if (mDNS_McastTracingEnabled)
624 CFDictionarySetValue(dict, CFSTR("McastTracing"), numOne);
625 else
626 CFDictionarySetValue(dict, CFSTR("McastTracing"), numZero);
627
628 CFRelease(numOne);
629 CFRelease(numZero);
630 mDNSDynamicStoreSetConfig(kmDNSDebugState, mDNSNULL, dict);
631 CFRelease(dict);
632
633 }
634
635
636 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
637
638 mDNSlocal void SignalCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
639 {
640 (void)port; // Unused
641 (void)size; // Unused
642 (void)info; // Unused
643 mach_msg_header_t *msg_header = (mach_msg_header_t *)msg;
644 mDNS *const m = &mDNSStorage;
645
646 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
647 KQueueLock();
648 switch(msg_header->msgh_id)
649 {
650 case SIGHUP: {
651 mDNSu32 slot;
652 CacheGroup *cg;
653 CacheRecord *rr;
654 LogMsg("SIGHUP: Purge cache");
655 mDNS_Lock(m);
656 FORALL_CACHERECORDS(slot, cg, rr)
657 {
658 rr->resrec.mortality = Mortality_Mortal;
659 mDNS_PurgeCacheResourceRecord(m, rr);
660 }
661 // Restart unicast and multicast queries
662 mDNSCoreRestartQueries(m);
663 mDNS_Unlock(m);
664 } break;
665 case SIGINT:
666 case SIGTERM: ExitCallback(msg_header->msgh_id); break;
667 case SIGINFO: INFOCallback(); break;
668 case SIGUSR1:
669 #if APPLE_OSX_mDNSResponder
670 mDNS_LoggingEnabled = 1;
671 LogMsg("SIGUSR1: Logging %s on Apple Platforms", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
672 #else
673 mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
674 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
675 #endif
676 WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250;
677 UpdateDebugState();
678 LogInfo("USR1 Logging Enabled");
679 break;
680 case SIGUSR2:
681 #if APPLE_OSX_mDNSResponder
682 mDNS_PacketLoggingEnabled = 1;
683 LogMsg("SIGUSR2: Packet Logging %s on Apple Platforms", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
684 #else
685 mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
686 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
687 #endif
688 mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse;
689 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
690 UpdateDebugState();
691 break;
692 case SIGPROF: mDNS_McastLoggingEnabled = mDNS_McastLoggingEnabled ? mDNSfalse : mDNStrue;
693 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled ? "Enabled" : "Disabled");
694 LogMcastStateInfo(mDNSfalse, mDNStrue, mDNStrue);
695 mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse;
696 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
697 UpdateDebugState();
698 break;
699 case SIGTSTP: mDNS_LoggingEnabled = mDNS_PacketLoggingEnabled = mDNS_McastLoggingEnabled = mDNS_McastTracingEnabled = mDNSfalse;
700 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
701 UpdateDebugState();
702 break;
703
704 default: LogMsg("SignalCallback: Unknown signal %d", msg_header->msgh_id); break;
705 }
706 KQueueUnlock("Unix Signal");
707 }
708
709 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
710 mDNSlocal kern_return_t mDNSDaemonInitialize(void)
711 {
712 mStatus err;
713
714 err = mDNS_Init(&mDNSStorage, &PlatformStorage,
715 rrcachestorage, RR_CACHE_SIZE,
716 !NoMulticastAdvertisements,
717 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
718
719 if (err)
720 {
721 LogMsg("Daemon start: mDNS_Init failed %d", err);
722 return(err);
723 }
724
725 #if TARGET_OS_IPHONE
726 if (PreallocateCacheMemory)
727 {
728 const int growCount = (kRRCacheMemoryLimit + kRRCacheGrowSize - 1) / kRRCacheGrowSize;
729 int i;
730
731 for (i = 0; i < growCount; ++i)
732 {
733 mDNS_StatusCallback(&mDNSStorage, mStatus_GrowCache);
734 }
735 }
736 #endif
737
738 CFMachPortRef i_port = CFMachPortCreate(NULL, SignalCallback, NULL, NULL);
739 CFRunLoopSourceRef i_rls = CFMachPortCreateRunLoopSource(NULL, i_port, 0);
740 signal_port = CFMachPortGetPort(i_port);
741 CFRunLoopAddSource(CFRunLoopGetMain(), i_rls, kCFRunLoopDefaultMode);
742 CFRelease(i_rls);
743
744 return(err);
745 }
746
747 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
748
749 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
750 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
751 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
752 // of code from above. Alternatively we could remove the duplicated source code by having
753 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
754
755 mDNSlocal void SignalDispatch(dispatch_source_t source)
756 {
757 int sig = (int)dispatch_source_get_handle(source);
758 mDNS *const m = &mDNSStorage;
759 KQueueLock();
760 switch(sig)
761 {
762 case SIGHUP: {
763 mDNSu32 slot;
764 CacheGroup *cg;
765 CacheRecord *rr;
766 LogMsg("SIGHUP: Purge cache");
767 mDNS_Lock(m);
768 FORALL_CACHERECORDS(slot, cg, rr)
769 {
770 rr->resrec.mortality = Mortality_Mortal;
771 mDNS_PurgeCacheResourceRecord(m, rr);
772 }
773 // Restart unicast and multicast queries
774 mDNSCoreRestartQueries(m);
775 mDNS_Unlock(m);
776 } break;
777 case SIGINT:
778 case SIGTERM: ExitCallback(sig); break;
779 case SIGINFO: INFOCallback(); break;
780 case SIGUSR1: mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
781 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
782 WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250;
783 UpdateDebugState();
784 break;
785 case SIGUSR2: mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
786 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
787 UpdateDebugState();
788 break;
789 default: LogMsg("SignalCallback: Unknown signal %d", sig); break;
790 }
791 KQueueUnlock("Unix Signal");
792 }
793
794 mDNSlocal void mDNSSetupSignal(dispatch_queue_t queue, int sig)
795 {
796 signal(sig, SIG_IGN);
797 dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, sig, 0, queue);
798
799 if (source)
800 {
801 dispatch_source_set_event_handler(source, ^{SignalDispatch(source);});
802 // Start processing signals
803 dispatch_resume(source);
804 }
805 else
806 {
807 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig);
808 }
809 }
810
811 mDNSlocal kern_return_t mDNSDaemonInitialize(void)
812 {
813 mStatus err;
814 dispatch_queue_t queue = dispatch_get_main_queue();
815
816 err = mDNS_Init(&mDNSStorage, &PlatformStorage,
817 rrcachestorage, RR_CACHE_SIZE,
818 !NoMulticastAdvertisements,
819 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
820
821 if (err)
822 {
823 LogMsg("Daemon start: mDNS_Init failed %d", err);
824 return(err);
825 }
826
827 mDNSSetupSignal(queue, SIGHUP);
828 mDNSSetupSignal(queue, SIGINT);
829 mDNSSetupSignal(queue, SIGTERM);
830 mDNSSetupSignal(queue, SIGINFO);
831 mDNSSetupSignal(queue, SIGUSR1);
832 mDNSSetupSignal(queue, SIGUSR2);
833
834 // Create a custom handler for doing the housekeeping work. This is either triggered
835 // by the timer or an event source
836 PlatformStorage.custom = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, queue);
837 if (PlatformStorage.custom == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
838 dispatch_source_set_event_handler(PlatformStorage.custom, ^{PrepareForIdle(&mDNSStorage);});
839 dispatch_resume(PlatformStorage.custom);
840
841 // Create a timer source to trigger housekeeping work. The houskeeping work itself
842 // is done in the custom handler that we set below.
843
844 PlatformStorage.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
845 if (PlatformStorage.timer == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
846
847 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
848 // always reset the time to the new time computed. In effect, we ignore the interval
849 dispatch_source_set_timer(PlatformStorage.timer, DISPATCH_TIME_NOW, 1000ull * 1000000000, 0);
850 dispatch_source_set_event_handler(PlatformStorage.timer, ^{
851 dispatch_source_merge_data(PlatformStorage.custom, 1);
852 });
853 dispatch_resume(PlatformStorage.timer);
854
855 LogMsg("DaemonIntialize done successfully");
856
857 return(err);
858 }
859
860 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
861
862 mDNSlocal mDNSs32 mDNSDaemonIdle(mDNS *const m)
863 {
864 mDNSs32 now = mDNS_TimeNow(m);
865
866 // 1. If we need to set domain secrets, do so before handling the network change
867 // Detailed reason:
868 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
869 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
870 if (m->p->KeyChainTimer && now - m->p->KeyChainTimer >= 0)
871 {
872 m->p->KeyChainTimer = 0;
873 mDNS_Lock(m);
874 SetDomainSecrets(m);
875 mDNS_Unlock(m);
876 }
877
878 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
879 // Detailed reason:
880 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
881 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
882 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
883 // we then systematically lose our own looped-back packets.
884 if (m->NetworkChanged && now - m->NetworkChanged >= 0) mDNSMacOSXNetworkChanged();
885
886 if (m->p->RequestReSleep && now - m->p->RequestReSleep >= 0)
887 {
888 m->p->RequestReSleep = 0;
889 mDNSPowerRequest(0, 0);
890 }
891
892 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
893 mDNSs32 nextevent = mDNS_Execute(m);
894
895 if (m->NetworkChanged)
896 if (nextevent - m->NetworkChanged > 0)
897 nextevent = m->NetworkChanged;
898
899 if (m->p->KeyChainTimer)
900 if (nextevent - m->p->KeyChainTimer > 0)
901 nextevent = m->p->KeyChainTimer;
902
903 if (m->p->RequestReSleep)
904 if (nextevent - m->p->RequestReSleep > 0)
905 nextevent = m->p->RequestReSleep;
906
907
908 if (m->p->NotifyUser)
909 {
910 if (m->p->NotifyUser - now < 0)
911 {
912 if (!SameDomainLabelCS(m->p->usernicelabel.c, m->nicelabel.c))
913 {
914 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m->p->usernicelabel.c, m->nicelabel.c);
915 mDNSPreferencesSetNames(kmDNSComputerName, &m->p->usernicelabel, &m->nicelabel);
916 m->p->usernicelabel = m->nicelabel;
917 }
918 if (!SameDomainLabelCS(m->p->userhostlabel.c, m->hostlabel.c))
919 {
920 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m->p->userhostlabel.c, m->hostlabel.c);
921 mDNSPreferencesSetNames(kmDNSLocalHostName, &m->p->userhostlabel, &m->hostlabel);
922 m->p->HostNameConflict = 0; // Clear our indicator, now name change has been successful
923 m->p->userhostlabel = m->hostlabel;
924 }
925 m->p->NotifyUser = 0;
926 }
927 else
928 if (nextevent - m->p->NotifyUser > 0)
929 nextevent = m->p->NotifyUser;
930 }
931
932 return(nextevent);
933 }
934
935 // Right now we consider *ALL* of our DHCP leases
936 // It might make sense to be a bit more selective and only consider the leases on interfaces
937 // (a) that are capable and enabled for wake-on-LAN, and
938 // (b) where we have found (and successfully registered with) a Sleep Proxy
939 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
940 mDNSlocal mDNSu32 DHCPWakeTime(void)
941 {
942 mDNSu32 e = 24 * 3600; // Maximum maintenance wake interval is 24 hours
943 const CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
944 if (!now) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
945 else
946 {
947 int ic, j;
948
949 const void *pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetDHCP);
950 if (!pattern)
951 {
952 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
953 return e;
954 }
955 CFArrayRef dhcpinfo = CFArrayCreate(NULL, (const void **)&pattern, 1, &kCFTypeArrayCallBacks);
956 CFRelease(pattern);
957 if (dhcpinfo)
958 {
959 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("DHCP-LEASES"), NULL, NULL);
960 if (store)
961 {
962 CFDictionaryRef dict = SCDynamicStoreCopyMultiple(store, NULL, dhcpinfo);
963 if (dict)
964 {
965 ic = CFDictionaryGetCount(dict);
966 const void *vals[ic];
967 CFDictionaryGetKeysAndValues(dict, NULL, vals);
968
969 for (j = 0; j < ic; j++)
970 {
971 const CFDictionaryRef dhcp = (CFDictionaryRef)vals[j];
972 if (dhcp)
973 {
974 const CFDateRef start = DHCPInfoGetLeaseStartTime(dhcp);
975 const CFDataRef lease = DHCPInfoGetOptionData(dhcp, 51); // Option 51 = IP Address Lease Time
976 if (!start || !lease || CFDataGetLength(lease) < 4)
977 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
978 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
979 j, start, lease, lease ? CFDataGetLength(lease) : 0);
980 else
981 {
982 const UInt8 *d = CFDataGetBytePtr(lease);
983 if (!d) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j);
984 else
985 {
986 const mDNSu32 elapsed = now - CFDateGetAbsoluteTime(start);
987 const mDNSu32 lifetime = (mDNSs32) ((mDNSs32)d[0] << 24 | (mDNSs32)d[1] << 16 | (mDNSs32)d[2] << 8 | d[3]);
988 const mDNSu32 remaining = lifetime - elapsed;
989 const mDNSu32 wake = remaining > 60 ? remaining - remaining/10 : 54; // Wake at 90% of the lease time
990 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed, lifetime, remaining, wake);
991 if (e > wake) e = wake;
992 }
993 }
994 }
995 }
996 CFRelease(dict);
997 }
998 CFRelease(store);
999 }
1000 CFRelease(dhcpinfo);
1001 }
1002 }
1003 return(e);
1004 }
1005
1006 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
1007 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
1008 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
1009 // for a few seconds and then waking again is silly and annoying.
1010 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
1011 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
1012 // allowing us an adequate safety margin to renew our lease before we lose it.
1013
1014 mDNSlocal mDNSBool AllowSleepNow(mDNSs32 now)
1015 {
1016 mDNS *const m = &mDNSStorage;
1017 mDNSBool ready = mDNSCoreReadyForSleep(m, now);
1018 if (m->SleepState && !ready && now - m->SleepLimit < 0) return(mDNSfalse);
1019
1020 m->p->WakeAtUTC = 0;
1021 int result = kIOReturnSuccess;
1022 CFDictionaryRef opts = NULL;
1023
1024 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
1025 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
1026 if (!m->SleepState)
1027 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m->SleepLimit - now);
1028 else
1029 {
1030 if (!m->SystemWakeOnLANEnabled || !mDNSCoreHaveAdvertisedMulticastServices(m))
1031 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
1032 m->SystemWakeOnLANEnabled ? "is" : "not",
1033 mDNSCoreHaveAdvertisedMulticastServices(m) ? "have" : "no");
1034 else
1035 {
1036 mDNSs32 dhcp = DHCPWakeTime();
1037 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp);
1038 mDNSs32 interval = mDNSCoreIntervalToNextWake(m, now) / mDNSPlatformOneSecond;
1039 if (interval > dhcp) interval = dhcp;
1040
1041 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
1042 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
1043 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
1044 // someone to go to the machine in person to wake it up again, which would be unacceptable.
1045 if (!ready && interval > 3600) interval = 3600;
1046
1047 //interval = 48; // For testing
1048
1049 #if !TARGET_OS_EMBEDDED
1050 #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1051 if (m->p->IOPMConnection) // If lightweight-wake capability is available, use that
1052 {
1053 const CFDateRef WakeDate = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent() + interval);
1054 if (!WakeDate) LogMsg("ScheduleNextWake: CFDateCreate failed");
1055 else
1056 {
1057 const mDNSs32 reqs = kIOPMSystemPowerStateCapabilityNetwork;
1058 const CFNumberRef Requirements = CFNumberCreate(NULL, kCFNumberSInt32Type, &reqs);
1059 if (!Requirements) LogMsg("ScheduleNextWake: CFNumberCreate failed");
1060 else
1061 {
1062 const void *OptionKeys[2] = { kIOPMAckDHCPRenewWakeDate, kIOPMAckSystemCapabilityRequirements };
1063 const void *OptionVals[2] = { WakeDate, Requirements };
1064 opts = CFDictionaryCreate(NULL, (void*)OptionKeys, (void*)OptionVals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1065 if (!opts) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
1066 CFRelease(Requirements);
1067 }
1068 CFRelease(WakeDate);
1069 }
1070 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval);
1071 }
1072 else // else schedule the wakeup using the old API instead to
1073 #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements
1074 #endif // TARGET_OS_EMBEDDED
1075 {
1076 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
1077 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
1078 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
1079 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
1080 if (interval < 60)
1081 interval = 60;
1082
1083 result = mDNSPowerRequest(1, interval);
1084
1085 if (result == kIOReturnNotReady)
1086 {
1087 int r;
1088 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval);
1089 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
1090 // requested wake time is "too soon", but there's no API to find out what constitutes
1091 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
1092 // we just have to iterate with successively longer intervals until it doesn't fail.
1093 // We preserve the value of "result" because if our original power request was deemed "too soon"
1094 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
1095 // since the implication is that the system won't manage to be awake again at the time we need it.
1096 do
1097 {
1098 interval += (interval < 20) ? 1 : ((interval+3) / 4);
1099 r = mDNSPowerRequest(1, interval);
1100 }
1101 while (r == kIOReturnNotReady);
1102 if (r) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval, r, r);
1103 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval);
1104 }
1105 else
1106 {
1107 if (result) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval, result, result);
1108 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval);
1109 }
1110 m->p->WakeAtUTC = mDNSPlatformUTC() + interval;
1111 }
1112 }
1113
1114 m->SleepState = SleepState_Sleeping;
1115 // Clear our interface list to empty state, ready to go to sleep
1116 // As a side effect of doing this, we'll also cancel any outstanding SPS Resolve calls that didn't complete
1117 mDNSMacOSXNetworkChanged();
1118 }
1119
1120 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
1121 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1122 (m->p->IOPMConnection) ? "IOPMConnectionAcknowledgeEventWithOptions" :
1123 #endif
1124 (result == kIOReturnSuccess) ? "IOAllowPowerChange" : "IOCancelPowerChange",
1125 m->p->SleepCookie, ready ? "ready for sleep" : "giving up", now, m->SleepLimit - now);
1126
1127 m->SleepLimit = 0; // Don't clear m->SleepLimit until after we've logged it above
1128 m->TimeSlept = mDNSPlatformUTC();
1129
1130 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
1131 if (m->p->IOPMConnection) IOPMConnectionAcknowledgeEventWithOptions(m->p->IOPMConnection, m->p->SleepCookie, opts);
1132 else
1133 #endif
1134 if (result == kIOReturnSuccess) IOAllowPowerChange (m->p->PowerConnection, m->p->SleepCookie);
1135 else IOCancelPowerChange(m->p->PowerConnection, m->p->SleepCookie);
1136
1137 if (opts) CFRelease(opts);
1138 return(mDNStrue);
1139 }
1140
1141 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1142
1143 mDNSexport void TriggerEventCompletion()
1144 {
1145 debugf("TriggerEventCompletion: Merge data");
1146 dispatch_source_merge_data(PlatformStorage.custom, 1);
1147 }
1148
1149 mDNSlocal void PrepareForIdle(void *m_param)
1150 {
1151 mDNS *m = m_param;
1152 int64_t time_offset;
1153 dispatch_time_t dtime;
1154
1155 const int multiplier = 1000000000 / mDNSPlatformOneSecond;
1156
1157 // This is the main work loop:
1158 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1159 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1160 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1161
1162 debugf("PrepareForIdle: called");
1163 // Run mDNS_Execute to find out the time we next need to wake up
1164 mDNSs32 start = mDNSPlatformRawTime();
1165 mDNSs32 nextTimerEvent = udsserver_idle(mDNSDaemonIdle(m));
1166 mDNSs32 end = mDNSPlatformRawTime();
1167 if (end - start >= WatchDogReportingThreshold)
1168 LogInfo("CustomSourceHandler:WARNING: Idle task took %dms to complete", end - start);
1169
1170 mDNSs32 now = mDNS_TimeNow(m);
1171
1172 if (m->ShutdownTime)
1173 {
1174 if (mDNSStorage.ResourceRecords)
1175 {
1176 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m, mDNSStorage.ResourceRecords));
1177 if (mDNS_LoggingEnabled) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1178 }
1179 if (mDNS_ExitNow(m, now))
1180 {
1181 LogInfo("IdleLoop: mDNS_FinalExit");
1182 mDNS_FinalExit(&mDNSStorage);
1183 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1184 exit(0);
1185 }
1186 if (nextTimerEvent - m->ShutdownTime >= 0)
1187 nextTimerEvent = m->ShutdownTime;
1188 }
1189
1190 if (m->SleepLimit)
1191 if (!AllowSleepNow(now))
1192 if (nextTimerEvent - m->SleepLimit >= 0)
1193 nextTimerEvent = m->SleepLimit;
1194
1195 // Convert absolute wakeup time to a relative time from now
1196 mDNSs32 ticks = nextTimerEvent - now;
1197 if (ticks < 1) ticks = 1;
1198
1199 static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins
1200 if (ticks > 1)
1201 RepeatedBusy = 0;
1202 else
1203 {
1204 ticks = 1;
1205 if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
1206 }
1207
1208 time_offset = ((mDNSu32)ticks / mDNSPlatformOneSecond) * 1000000000 + (ticks % mDNSPlatformOneSecond) * multiplier;
1209 dtime = dispatch_time(DISPATCH_TIME_NOW, time_offset);
1210 dispatch_source_set_timer(PlatformStorage.timer, dtime, 1000ull*1000000000, 0);
1211 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks);
1212 return;
1213 }
1214
1215 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1216
1217 mDNSlocal void KQWokenFlushBytes(int fd, __unused short filter, __unused void *context, __unused mDNSBool encounteredEOF)
1218 {
1219 // Read all of the bytes so we won't wake again.
1220 char buffer[100];
1221 while (recv(fd, buffer, sizeof(buffer), MSG_DONTWAIT) > 0) continue;
1222 }
1223
1224 mDNSlocal void SetLowWater(const KQSocketSet *const k, const int r)
1225 {
1226 if (k->sktv4 >=0 && setsockopt(k->sktv4, SOL_SOCKET, SO_RCVLOWAT, &r, sizeof(r)) < 0)
1227 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k->sktv4, r, errno, strerror(errno));
1228 if (k->sktv6 >=0 && setsockopt(k->sktv6, SOL_SOCKET, SO_RCVLOWAT, &r, sizeof(r)) < 0)
1229 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k->sktv6, r, errno, strerror(errno));
1230 }
1231
1232 mDNSlocal void * KQueueLoop(void *m_param)
1233 {
1234 mDNS *m = m_param;
1235 int numevents = 0;
1236
1237 #if USE_SELECT_WITH_KQUEUEFD
1238 fd_set readfds;
1239 FD_ZERO(&readfds);
1240 const int multiplier = 1000000 / mDNSPlatformOneSecond;
1241 #else
1242 const int multiplier = 1000000000 / mDNSPlatformOneSecond;
1243 #endif
1244
1245 pthread_mutex_lock(&PlatformStorage.BigMutex);
1246 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32)mDNSStorage.timenow_last, mDNSStorage.timenow_last);
1247
1248 // This is the main work loop:
1249 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
1250 // (2) Then we make sure we've delivered all waiting browse messages to our clients
1251 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
1252 // (4) On wakeup we first process *all* events
1253 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
1254 for ( ; ; )
1255 {
1256 #define kEventsToReadAtOnce 1
1257 struct kevent new_events[kEventsToReadAtOnce];
1258
1259 // Run mDNS_Execute to find out the time we next need to wake up
1260 mDNSs32 start = mDNSPlatformRawTime();
1261 mDNSs32 nextTimerEvent = udsserver_idle(mDNSDaemonIdle(m));
1262 mDNSs32 end = mDNSPlatformRawTime();
1263 if (end - start >= WatchDogReportingThreshold)
1264 LogInfo("WARNING: Idle task took %dms to complete", end - start);
1265
1266 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
1267 validatelists(m);
1268 #endif
1269
1270 mDNSs32 now = mDNS_TimeNow(m);
1271
1272 if (m->ShutdownTime)
1273 {
1274 if (mDNSStorage.ResourceRecords)
1275 {
1276 AuthRecord *rr;
1277 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
1278 {
1279 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m, rr));
1280 if (mDNS_LoggingEnabled) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
1281 }
1282 }
1283 if (mDNS_ExitNow(m, now))
1284 {
1285 LogInfo("mDNS_FinalExit");
1286 mDNS_FinalExit(&mDNSStorage);
1287 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
1288 exit(0);
1289 }
1290 if (nextTimerEvent - m->ShutdownTime >= 0)
1291 nextTimerEvent = m->ShutdownTime;
1292 }
1293
1294 if (m->SleepLimit)
1295 if (!AllowSleepNow(now))
1296 if (nextTimerEvent - m->SleepLimit >= 0)
1297 nextTimerEvent = m->SleepLimit;
1298
1299 // Convert absolute wakeup time to a relative time from now
1300 mDNSs32 ticks = nextTimerEvent - now;
1301 if (ticks < 1) ticks = 1;
1302
1303 static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins
1304 if (ticks > 1)
1305 RepeatedBusy = 0;
1306 else
1307 {
1308 ticks = 1;
1309 if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
1310 }
1311
1312 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents, ticks);
1313 numevents = 0;
1314
1315 // Release the lock, and sleep until:
1316 // 1. Something interesting happens like a packet arriving, or
1317 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
1318 // 3. The timeout expires
1319 pthread_mutex_unlock(&PlatformStorage.BigMutex);
1320
1321 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
1322 if (m->p->num_mcasts)
1323 {
1324 SetLowWater(&m->p->permanentsockets, 0x10000);
1325 if (ticks > mDNSPlatformOneSecond / 8) ticks = mDNSPlatformOneSecond / 8;
1326 }
1327
1328 #if USE_SELECT_WITH_KQUEUEFD
1329 struct timeval timeout;
1330 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
1331 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * multiplier;
1332 FD_SET(KQueueFD, &readfds);
1333 if (select(KQueueFD+1, &readfds, NULL, NULL, &timeout) < 0)
1334 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD, errno, strerror(errno)); sleep(1); }
1335 #else
1336 struct timespec timeout;
1337 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
1338 timeout.tv_nsec = (ticks % mDNSPlatformOneSecond) * multiplier;
1339 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
1340 // and have it work similarly to the way it does with nevents non-zero --
1341 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
1342 // In fact, what happens if you do this is that it just returns immediately. So, we have
1343 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
1344 if (kevent(KQueueFD, NULL, 0, new_events, 1, &timeout) < 0)
1345 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD, errno, strerror(errno)); sleep(1); }
1346 #endif
1347
1348 pthread_mutex_lock(&PlatformStorage.BigMutex);
1349 // We have to ignore the event we may have been told about above, because that
1350 // was done without holding the lock, and between the time we woke up and the
1351 // time we reclaimed the lock the other thread could have done something that
1352 // makes the event no longer valid. Now we have the lock, we call kevent again
1353 // and this time we can safely process the events it tells us about.
1354
1355 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
1356 if (m->p->num_mcasts)
1357 {
1358 SetLowWater(&m->p->permanentsockets, 1);
1359 m->p->num_mcasts = 0;
1360 }
1361
1362 static const struct timespec zero_timeout = { 0, 0 };
1363 int events_found;
1364 while ((events_found = kevent(KQueueFD, NULL, 0, new_events, kEventsToReadAtOnce, &zero_timeout)) != 0)
1365 {
1366 if (events_found > kEventsToReadAtOnce || (events_found < 0 && errno != EINTR))
1367 {
1368 const int kevent_errno = errno;
1369 // Not sure what to do here, our kqueue has failed us - this isn't ideal
1370 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", kevent_errno, strerror(kevent_errno));
1371 exit(kevent_errno);
1372 }
1373
1374 numevents += events_found;
1375
1376 int i;
1377 for (i = 0; i < events_found; i++)
1378 {
1379 const KQueueEntry *const kqentry = new_events[i].udata;
1380 mDNSs32 stime = mDNSPlatformRawTime();
1381 const char *const KQtask = kqentry->KQtask; // Grab a copy in case KQcallback deletes the task
1382 kqentry->KQcallback(new_events[i].ident, new_events[i].filter, kqentry->KQcontext, (new_events[i].flags & EV_EOF) != 0);
1383 mDNSs32 etime = mDNSPlatformRawTime();
1384 if (etime - stime >= WatchDogReportingThreshold)
1385 LogInfo("WARNING: %s took %dms to complete", KQtask, etime - stime);
1386 }
1387 }
1388 }
1389
1390 return NULL;
1391 }
1392
1393 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1394
1395 mDNSlocal size_t LaunchdCheckin(void)
1396 {
1397 // Ask launchd for our socket
1398 int result = launch_activate_socket("Listeners", &launchd_fds, &launchd_fds_count);
1399 if (result != 0) { LogMsg("launch_activate_socket() failed error %d (%s)", result, strerror(result)); }
1400 return launchd_fds_count;
1401 }
1402
1403
1404 extern int sandbox_init(const char *profile, uint64_t flags, char **errorbuf) __attribute__((weak_import));
1405
1406 #if APPLE_OSX_mDNSResponder
1407 mDNSlocal mDNSBool PreferencesGetValueBool(CFStringRef key, mDNSBool defaultValue)
1408 {
1409 CFBooleanRef boolean;
1410 mDNSBool result = defaultValue;
1411
1412 boolean = CFPreferencesCopyAppValue(key, kProgramArguments);
1413 if (boolean)
1414 {
1415 if (CFGetTypeID(boolean) == CFBooleanGetTypeID())
1416 result = CFBooleanGetValue(boolean) ? mDNStrue : mDNSfalse;
1417 CFRelease(boolean);
1418 }
1419
1420 return result;
1421 }
1422
1423 mDNSlocal int PreferencesGetValueInt(CFStringRef key, int defaultValue)
1424 {
1425 CFNumberRef number;
1426 int numberValue;
1427 int result = defaultValue;
1428
1429 number = CFPreferencesCopyAppValue(key, kProgramArguments);
1430 if (number)
1431 {
1432 if ((CFGetTypeID(number) == CFNumberGetTypeID()) && CFNumberGetValue(number, kCFNumberIntType, &numberValue))
1433 result = numberValue;
1434 CFRelease(number);
1435 }
1436
1437 return result;
1438 }
1439 #endif
1440
1441 mDNSlocal void SandboxProcess(void)
1442 {
1443 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
1444 #if MDNS_NO_SANDBOX
1445 LogMsg("Note: Compiled without Apple Sandbox support");
1446 #else // MDNS_NO_SANDBOX
1447 if (!sandbox_init)
1448 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
1449 else
1450 {
1451 char *sandbox_msg;
1452 uint64_t sandbox_flags = SANDBOX_NAMED;
1453
1454 (void)confstr(_CS_DARWIN_USER_CACHE_DIR, NULL, 0);
1455
1456 int sandbox_err = sandbox_init("mDNSResponder", sandbox_flags, &sandbox_msg);
1457 if (sandbox_err)
1458 {
1459 LogMsg("WARNING: sandbox_init error %s", sandbox_msg);
1460 // If we have errors in the sandbox during development, to prevent
1461 // exiting, uncomment the following line.
1462 //sandbox_free_error(sandbox_msg);
1463
1464 errx(EX_OSERR, "sandbox_init() failed: %s", sandbox_msg);
1465 }
1466 else LogInfo("Now running under Apple Sandbox restrictions");
1467 }
1468 #endif // MDNS_NO_SANDBOX
1469 }
1470
1471 #if APPLE_OSX_mDNSResponder
1472 mDNSlocal void init_logging(void)
1473 {
1474 log_general = os_log_create("com.apple.mDNSResponder", "AllINFO");
1475
1476 if (!log_general)
1477 {
1478 // OS_LOG_DEFAULT is the default logging object, if you are not creating a custom subsystem/category
1479 os_log_error(OS_LOG_DEFAULT, "Could NOT create log handle in mDNSResponder");
1480 }
1481 }
1482 #endif
1483
1484 #ifdef UNIT_TEST
1485 // Run the unit test main
1486 UNITTEST_MAIN
1487 #else
1488 mDNSexport int main(int argc, char **argv)
1489 {
1490 int i;
1491 kern_return_t status;
1492
1493 #if DEBUG
1494 bool useDebugSocket = mDNSfalse;
1495 bool useSandbox = mDNStrue;
1496 #endif
1497
1498 #if APPLE_OSX_mDNSResponder
1499 init_logging();
1500 #endif
1501
1502 mDNSMacOSXSystemBuildNumber(NULL);
1503 LogMsg("%s starting %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
1504
1505 #if 0
1506 LogMsg("CacheRecord %5d", sizeof(CacheRecord));
1507 LogMsg("CacheGroup %5d", sizeof(CacheGroup));
1508 LogMsg("ResourceRecord %5d", sizeof(ResourceRecord));
1509 LogMsg("RData_small %5d", sizeof(RData_small));
1510
1511 LogMsg("sizeof(CacheEntity) %5d", sizeof(CacheEntity));
1512 LogMsg("RR_CACHE_SIZE %5d", RR_CACHE_SIZE);
1513 LogMsg("block bytes used %5d", sizeof(CacheEntity) * RR_CACHE_SIZE);
1514 LogMsg("block bytes wasted %5d", 32*1024 - sizeof(CacheEntity) * RR_CACHE_SIZE);
1515 #endif
1516
1517 if (0 == geteuid())
1518 {
1519 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
1520 return -1;
1521 }
1522
1523 for (i=1; i<argc; i++)
1524 {
1525 if (!strcasecmp(argv[i], "-d" )) mDNS_DebugMode = mDNStrue;
1526 if (!strcasecmp(argv[i], "-NoMulticastAdvertisements")) NoMulticastAdvertisements = mDNStrue;
1527 if (!strcasecmp(argv[i], "-DisableSleepProxyClient" )) DisableSleepProxyClient = mDNStrue;
1528 if (!strcasecmp(argv[i], "-DebugLogging" )) mDNS_LoggingEnabled = mDNStrue;
1529 if (!strcasecmp(argv[i], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled = mDNStrue;
1530 if (!strcasecmp(argv[i], "-OfferSleepProxyService" ))
1531 OfferSleepProxyService = (i+1 < argc && mDNSIsDigit(argv[i+1][0]) && mDNSIsDigit(argv[i+1][1]) && argv[i+1][2]==0) ? atoi(argv[++i]) : 100;
1532 if (!strcasecmp(argv[i], "-UseInternalSleepProxy" ))
1533 UseInternalSleepProxy = (i+1<argc && mDNSIsDigit(argv[i+1][0]) && argv[i+1][1]==0) ? atoi(argv[++i]) : 1;
1534 if (!strcasecmp(argv[i], "-StrictUnicastOrdering" )) StrictUnicastOrdering = mDNStrue;
1535 if (!strcasecmp(argv[i], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains = mDNStrue;
1536 if (!strcasecmp(argv[i], "-DisableAllowExpired" )) EnableAllowExpired = mDNSfalse;
1537 #if DEBUG
1538 if (!strcasecmp(argv[i], "-UseDebugSocket")) useDebugSocket = mDNStrue;
1539 if (!strcasecmp(argv[i], "-NoSandbox")) useSandbox = mDNSfalse;
1540 #endif
1541 }
1542
1543
1544 #if APPLE_OSX_mDNSResponder
1545 /* Reads the external user's program arguments for mDNSResponder starting 10.11.x(El Capitan) on OSX. The options for external user are:
1546 DebugLogging, UnicastPacketLogging, NoMulticastAdvertisements, StrictUnicastOrdering and AlwaysAppendSearchDomains
1547
1548 To turn ON the particular option, here is what the user should do (as an example of setting two options)
1549 1] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist AlwaysAppendSearchDomains -bool YES
1550 2] sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
1551 3] sudo reboot
1552
1553 To turn OFF all options, here is what the user should do
1554 1] sudo defaults delete /Library/Preferences/com.apple.mDNSResponder.plist
1555 2] sudo reboot
1556
1557 To view the current options set, here is what the user should do
1558 1] plutil -p /Library/Preferences/com.apple.mDNSResponder.plist
1559 OR
1560 1] sudo defaults read /Library/Preferences/com.apple.mDNSResponder.plist
1561
1562 */
1563
1564 // Currently on Fuji/Whitetail releases we are keeping the logging always enabled.
1565 // Hence mDNS_LoggingEnabled and mDNS_PacketLoggingEnabled is set to true below by default.
1566 #if 0
1567 mDNS_LoggingEnabled = PreferencesGetValueBool(kPreferencesKey_DebugLogging, mDNS_LoggingEnabled);
1568 mDNS_PacketLoggingEnabled = PreferencesGetValueBool(kPreferencesKey_UnicastPacketLogging, mDNS_PacketLoggingEnabled);
1569 #endif
1570
1571 mDNS_LoggingEnabled = mDNStrue;
1572 mDNS_PacketLoggingEnabled = mDNStrue;
1573
1574 NoMulticastAdvertisements = PreferencesGetValueBool(kPreferencesKey_NoMulticastAdvertisements, NoMulticastAdvertisements);
1575 StrictUnicastOrdering = PreferencesGetValueBool(kPreferencesKey_StrictUnicastOrdering, StrictUnicastOrdering);
1576 AlwaysAppendSearchDomains = PreferencesGetValueBool(kPreferencesKey_AlwaysAppendSearchDomains, AlwaysAppendSearchDomains);
1577 EnableAllowExpired = PreferencesGetValueBool(kPreferencesKey_EnableAllowExpired, EnableAllowExpired);
1578 OfferSleepProxyService = PreferencesGetValueInt(kPreferencesKey_OfferSleepProxyService, OfferSleepProxyService);
1579 UseInternalSleepProxy = PreferencesGetValueInt(kPreferencesKey_UseInternalSleepProxy, UseInternalSleepProxy);
1580
1581 #if ENABLE_BLE_TRIGGERED_BONJOUR
1582 EnableBLEBasedDiscovery = PreferencesGetValueBool(kPreferencesKey_EnableBLEBasedDiscovery, EnableBLEBasedDiscovery);
1583 DefaultToBLETriggered = PreferencesGetValueBool(kPreferencesKey_DefaultToBLETriggered, DefaultToBLETriggered);
1584 #endif // ENABLE_BLE_TRIGGERED_BONJOUR
1585
1586 #if TARGET_OS_IPHONE
1587 PreallocateCacheMemory = PreferencesGetValueBool(kPreferencesKey_PreallocateCacheMemory, PreallocateCacheMemory);
1588 #endif
1589 #endif
1590
1591 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
1592 if (NoMulticastAdvertisements)
1593 LogMsg("-NoMulticastAdvertisements is set: Administratively prohibiting multicast advertisements");
1594 if (AlwaysAppendSearchDomains)
1595 LogMsg("-AlwaysAppendSearchDomains is set");
1596 if (StrictUnicastOrdering)
1597 LogMsg("-StrictUnicastOrdering is set");
1598
1599 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1600
1601 signal(SIGHUP, HandleSIG); // (Debugging) Purge the cache to check for cache handling bugs
1602 signal(SIGINT, HandleSIG); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
1603 signal(SIGPIPE, SIG_IGN); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
1604 signal(SIGTERM, HandleSIG); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
1605 signal(SIGINFO, HandleSIG); // (Debugging) Write state snapshot to syslog
1606 signal(SIGUSR1, HandleSIG); // (Debugging) Enable Logging
1607 signal(SIGUSR2, HandleSIG); // (Debugging) Enable Packet Logging
1608 signal(SIGPROF, HandleSIG); // (Debugging) Toggle Multicast Logging
1609 signal(SIGTSTP, HandleSIG); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
1610
1611 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1612
1613 mDNSStorage.p = &PlatformStorage; // Make sure mDNSStorage.p is set up, because validatelists uses it
1614 // Need to Start XPC Server Before LaunchdCheckin() (Reason: rdar11023750)
1615 xpc_server_init();
1616 #if DEBUG
1617 if (!useDebugSocket) {
1618 if (LaunchdCheckin() == 0)
1619 useDebugSocket = mDNStrue;
1620 }
1621 if (useDebugSocket)
1622 SetDebugBoundPath();
1623 #else
1624 LaunchdCheckin();
1625 #endif
1626
1627 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1628
1629 // Create the kqueue, mutex and thread to support KQSockets
1630 KQueueFD = kqueue();
1631 if (KQueueFD == -1)
1632 {
1633 const int kqueue_errno = errno;
1634 LogMsg("kqueue() failed errno %d (%s)", kqueue_errno, strerror(kqueue_errno));
1635 status = kqueue_errno;
1636 goto exit;
1637 }
1638
1639 i = pthread_mutex_init(&PlatformStorage.BigMutex, NULL);
1640 if (i != 0) { LogMsg("pthread_mutex_init() failed error %d (%s)", i, strerror(i)); status = i; goto exit; }
1641
1642 int fdpair[2] = {0, 0};
1643 i = socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair);
1644 if (i == -1)
1645 {
1646 const int socketpair_errno = errno;
1647 LogMsg("socketpair() failed errno %d (%s)", socketpair_errno, strerror(socketpair_errno));
1648 status = socketpair_errno;
1649 goto exit;
1650 }
1651
1652 // Socket pair returned us two identical sockets connected to each other
1653 // We will use the first socket to send the second socket. The second socket
1654 // will be added to the kqueue so it will wake when data is sent.
1655 static const KQueueEntry wakeKQEntry = { KQWokenFlushBytes, NULL, "kqueue wakeup after CFRunLoop event" };
1656
1657 PlatformStorage.WakeKQueueLoopFD = fdpair[0];
1658 KQueueSet(fdpair[1], EV_ADD, EVFILT_READ, &wakeKQEntry);
1659
1660 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1661
1662 #if DEBUG
1663 if (useSandbox)
1664 #endif
1665 SandboxProcess();
1666
1667 #if AWD_METRICS
1668 status = MetricsInit();
1669 if (status) { LogMsg("Daemon start: MetricsInit failed (%d)", status); }
1670 #endif
1671
1672 status = mDNSDaemonInitialize();
1673 if (status) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit; }
1674
1675 status = udsserver_init(launchd_fds, launchd_fds_count);
1676 if (status) { LogMsg("Daemon start: udsserver_init failed"); goto exit; }
1677
1678 mDNSMacOSXNetworkChanged();
1679 UpdateDebugState();
1680
1681 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1682 LogInfo("Daemon Start: Using LibDispatch");
1683 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
1684 CFRunLoopRun();
1685 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1686 // Start the kqueue thread
1687 pthread_t KQueueThread;
1688 i = pthread_create(&KQueueThread, NULL, KQueueLoop, &mDNSStorage);
1689 if (i != 0) { LogMsg("pthread_create() failed error %d (%s)", i, strerror(i)); status = i; goto exit; }
1690 if (status == 0)
1691 {
1692 CFRunLoopRun();
1693 LogMsg("ERROR: CFRunLoopRun Exiting.");
1694 mDNS_Close(&mDNSStorage);
1695 }
1696 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1697
1698 LogMsg("%s exiting", mDNSResponderVersionString);
1699
1700 exit:
1701 return(status);
1702 }
1703 #endif // UNIT_TEST
1704
1705 // uds_daemon.c support routines /////////////////////////////////////////////
1706
1707 mDNSlocal void kqUDSEventCallback(int fd, short filter, void *context, __unused mDNSBool encounteredEOF)
1708 {
1709 const KQSocketEventSource *const source = context;
1710 source->callback(fd, filter, source->context);
1711 }
1712
1713 // Arrange things so that when data appears on fd, callback is called with context
1714 mDNSexport mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
1715 {
1716 KQSocketEventSource **p = &gEventSources;
1717 (void) platform_data;
1718 while (*p && (*p)->fd != fd) p = &(*p)->next;
1719 if (*p) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd); return mStatus_AlreadyRegistered; }
1720
1721 KQSocketEventSource *newSource = (KQSocketEventSource*) mallocL("KQSocketEventSource", sizeof *newSource);
1722 if (!newSource) return mStatus_NoMemoryErr;
1723
1724 newSource->next = mDNSNULL;
1725 newSource->fd = fd;
1726 newSource->callback = callback;
1727 newSource->context = context;
1728 newSource->kqs.KQcallback = kqUDSEventCallback;
1729 newSource->kqs.KQcontext = newSource;
1730 newSource->kqs.KQtask = "UDS client";
1731 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1732 newSource->kqs.readSource = mDNSNULL;
1733 newSource->kqs.writeSource = mDNSNULL;
1734 newSource->kqs.fdClosed = mDNSfalse;
1735 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1736
1737 if (KQueueSet(fd, EV_ADD, EVFILT_READ, &newSource->kqs) == 0)
1738 {
1739 *p = newSource;
1740 return mStatus_NoError;
1741 }
1742
1743 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd, errno, strerror(errno));
1744 freeL("KQSocketEventSource", newSource);
1745 return mStatus_BadParamErr;
1746 }
1747
1748 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
1749 {
1750 (void) platform_data;
1751 return recv(fd, buf, len, flags);
1752 }
1753
1754 mDNSexport mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor
1755 {
1756 KQSocketEventSource **p = &gEventSources;
1757 (void) platform_data;
1758 while (*p && (*p)->fd != fd) p = &(*p)->next;
1759 if (*p)
1760 {
1761 KQSocketEventSource *s = *p;
1762 *p = (*p)->next;
1763 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
1764 // causes the kernel to automatically remove any associated kevents
1765 mDNSPlatformCloseFD(&s->kqs, s->fd);
1766 freeL("KQSocketEventSource", s);
1767 return mStatus_NoError;
1768 }
1769 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd);
1770 return mStatus_NoSuchNameErr;
1771 }
1772
1773 #ifdef UNIT_TEST
1774 #include "../unittests/daemon_ut.c"
1775 #endif // UNIT_TEST
1776
1777 #if _BUILDING_XCODE_PROJECT_
1778 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
1779 const char *__crashreporter_info__ = mDNSResponderVersionString;
1780 asm (".desc ___crashreporter_info__, 0x10");
1781 #endif
1782
1783 // For convenience when using the "strings" command, this is the last thing in the file
1784 // The "@(#) " pattern is a special prefix the "what" command looks for
1785 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";