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