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