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