]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/daemon.c
mDNSResponder-567.tar.gz
[apple/mdnsresponder.git] / mDNSMacOSX / daemon.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2011 Apple Computer, 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
19 #include <mach/mach.h>
20 #include <mach/mach_error.h>
21 #include <sys/types.h>
22 #include <errno.h>
23 #include <signal.h>
24 #include <unistd.h>
25 #include <paths.h>
26 #include <fcntl.h>
27 #include <launch.h>
28 #include <launch_priv.h> // for launch_socket_service_check_in()
29 #include <vproc.h>
30 #include <pwd.h>
31 #include <sys/event.h>
32 #include <pthread.h>
33 #include <sandbox.h>
34 #include <SystemConfiguration/SCDynamicStoreCopyDHCPInfo.h>
35 #include <asl.h>
36 #include <syslog.h>
37 #include <err.h>
38 #include <sysexits.h>
39 #include <bootstrap_priv.h> // for bootstrap_check_in()
40
41 #include "DNSServiceDiscoveryRequestServer.h"
42 #include "DNSServiceDiscoveryReply.h"
43
44 #include "uDNS.h"
45 #include "DNSCommon.h"
46 #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
47
48 #include "uds_daemon.h" // Interface to the server side implementation of dns_sd.h
49 #include "xpc_services.h" // Interface to XPC services
50
51 #include "../mDNSMacOSX/DNSServiceDiscovery.h"
52 #include "helper.h"
53
54 static aslclient log_client = NULL;
55 static aslmsg log_msg = NULL;
56
57 // Used on Embedded Side for Reading mDNSResponder Managed Preferences Profile
58 #if TARGET_OS_EMBEDDED
59 #define kmDNSEnableLoggingStr CFSTR("EnableLogging")
60 #define kmDNSResponderPrefIDStr "com.apple.mDNSResponder.plist"
61 #define kmDNSResponderPrefID CFSTR(kmDNSResponderPrefIDStr)
62 #endif
63
64 //*************************************************************************************************************
65 #if COMPILER_LIKES_PRAGMA_MARK
66 #pragma mark - Globals
67 #endif
68
69 static mDNS_PlatformSupport PlatformStorage;
70
71 // Start off with a default cache of 16K (99 records)
72 // Each time we grow the cache we add another 99 records
73 // 99 * 164 = 16236 bytes.
74 // This fits in four 4kB pages, with 148 bytes spare for memory block headers and similar overhead
75 #define RR_CACHE_SIZE ((16*1024) / sizeof(CacheRecord))
76 static CacheEntity rrcachestorage[RR_CACHE_SIZE];
77
78 static mach_port_t m_port = MACH_PORT_NULL;
79
80 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
81 mDNSlocal void PrepareForIdle(void *m_param);
82 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
83 static mach_port_t client_death_port = MACH_PORT_NULL;
84 static mach_port_t signal_port = MACH_PORT_NULL;
85 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
86
87 static dnssd_sock_t *launchd_fds = mDNSNULL;
88 static mDNSu32 launchd_fds_count = 0;
89
90 // mDNS Mach Message Timeout, in milliseconds.
91 // We need this to be short enough that we don't deadlock the mDNSResponder if a client
92 // fails to service its mach message queue, but long enough to give a well-written
93 // client a chance to service its mach message queue without getting cut off.
94 // Empirically, 50ms seems to work, so we set the timeout to 250ms to give
95 // even extra-slow clients a fair chance before we cut them off.
96 #define MDNS_MM_TIMEOUT 250
97
98 static mDNSBool advertise = mDNS_Init_AdvertiseLocalAddresses; // By default, advertise addresses (& other records) via multicast
99
100 extern mDNSBool StrictUnicastOrdering;
101 extern mDNSBool AlwaysAppendSearchDomains;
102
103 //*************************************************************************************************************
104 #if COMPILER_LIKES_PRAGMA_MARK
105 #pragma mark -
106 #pragma mark - Active client list structures
107 #endif
108
109 typedef struct DNSServiceDomainEnumeration_struct DNSServiceDomainEnumeration;
110 struct DNSServiceDomainEnumeration_struct
111 {
112 DNSServiceDomainEnumeration *next;
113 mach_port_t ClientMachPort;
114 DNSQuestion dom; // Question asking for domains
115 DNSQuestion def; // Question asking for default domain
116 };
117
118 typedef struct DNSServiceBrowserResult_struct DNSServiceBrowserResult;
119 struct DNSServiceBrowserResult_struct
120 {
121 DNSServiceBrowserResult *next;
122 int resultType;
123 domainname result;
124 };
125
126 typedef struct DNSServiceBrowser_struct DNSServiceBrowser;
127
128 typedef struct DNSServiceBrowserQuestion
129 {
130 struct DNSServiceBrowserQuestion *next;
131 DNSQuestion q;
132 domainname domain;
133 } DNSServiceBrowserQuestion;
134
135 struct DNSServiceBrowser_struct
136 {
137 DNSServiceBrowser *next;
138 mach_port_t ClientMachPort;
139 DNSServiceBrowserQuestion *qlist;
140 DNSServiceBrowserResult *results;
141 mDNSs32 lastsuccess;
142 mDNSBool DefaultDomain; // was the browse started on an explicit domain?
143 domainname type; // registration type
144 };
145
146 typedef struct DNSServiceResolver_struct DNSServiceResolver;
147 struct DNSServiceResolver_struct
148 {
149 DNSServiceResolver *next;
150 mach_port_t ClientMachPort;
151 ServiceInfoQuery q;
152 ServiceInfo i;
153 mDNSs32 ReportTime;
154 };
155
156 // A single registered service: ServiceRecordSet + bookkeeping
157 // Note that we duplicate some fields from parent DNSServiceRegistration object
158 // to facilitate cleanup, when instances and parent may be deallocated at different times.
159 typedef struct ServiceInstance
160 {
161 struct ServiceInstance *next;
162 mach_port_t ClientMachPort;
163 mDNSBool autoname; // Set if this name is tied to the Computer Name
164 mDNSBool renameonmemfree; // Set if we just got a name conflict and now need to automatically pick a new name
165 domainlabel name;
166 domainname domain;
167 ServiceRecordSet srs;
168 // Don't add any fields after ServiceRecordSet.
169 // This is where the implicit extra space goes if we allocate an oversized ServiceRecordSet object
170 } ServiceInstance;
171
172 // A client-created service. May reference several ServiceInstance objects if default
173 // settings cause registration in multiple domains.
174 typedef struct DNSServiceRegistration
175 {
176 struct DNSServiceRegistration *next;
177 mach_port_t ClientMachPort;
178 mDNSBool DefaultDomain;
179 mDNSBool autoname;
180 size_t rdsize;
181 int NumSubTypes;
182 char regtype[MAX_ESCAPED_DOMAIN_NAME]; // for use in AllocateSubtypes
183 domainlabel name; // used only if autoname is false
184 domainname type;
185 mDNSIPPort port;
186 unsigned char txtinfo[1024];
187 size_t txt_len;
188 uint32_t NextRef;
189 ServiceInstance *regs;
190 } DNSServiceRegistration;
191
192 static DNSServiceDomainEnumeration *DNSServiceDomainEnumerationList = NULL;
193 static DNSServiceBrowser *DNSServiceBrowserList = NULL;
194 static DNSServiceResolver *DNSServiceResolverList = NULL;
195 static DNSServiceRegistration *DNSServiceRegistrationList = NULL;
196
197 // We keep a list of client-supplied event sources in KQSocketEventSource records
198 typedef struct KQSocketEventSource
199 {
200 struct KQSocketEventSource *next;
201 int fd;
202 KQueueEntry kqs;
203 } KQSocketEventSource;
204
205 static KQSocketEventSource *gEventSources;
206
207 //*************************************************************************************************************
208 #if COMPILER_LIKES_PRAGMA_MARK
209 #pragma mark -
210 #pragma mark - General Utility Functions
211 #endif
212
213 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
214
215 char _malloc_options[] = "AXZ";
216
217 mDNSexport void LogMemCorruption(const char *format, ...)
218 {
219 char buffer[512];
220 va_list ptr;
221 va_start(ptr,format);
222 buffer[mDNS_vsnprintf((char *)buffer, sizeof(buffer), format, ptr)] = 0;
223 va_end(ptr);
224 LogMsg("!!!! %s !!!!", buffer);
225 NotifyOfElusiveBug("Memory Corruption", buffer);
226 #if ForceAlerts
227 *(long*)0 = 0; // Trick to crash and get a stack trace right here, if that's what we want
228 #endif
229 }
230
231 mDNSlocal void validatelists(mDNS *const m)
232 {
233 // Check local lists
234 KQSocketEventSource *k;
235 for (k = gEventSources; k; k=k->next)
236 if (k->next == (KQSocketEventSource *)~0 || k->fd < 0)
237 LogMemCorruption("gEventSources: %p is garbage (%d)", k, k->fd);
238
239 // Check Mach client lists
240 DNSServiceDomainEnumeration *e;
241 for (e = DNSServiceDomainEnumerationList; e; e=e->next)
242 if (e->next == (DNSServiceDomainEnumeration *)~0 || e->ClientMachPort == 0 || e->ClientMachPort == (mach_port_t) ~0)
243 LogMemCorruption("DNSServiceDomainEnumerationList: %p is garbage (%X)", e, e->ClientMachPort);
244
245 DNSServiceBrowser *b;
246 for (b = DNSServiceBrowserList; b; b=b->next)
247 if (b->next == (DNSServiceBrowser *)~0 || b->ClientMachPort == 0 || b->ClientMachPort == (mach_port_t) ~0)
248 LogMemCorruption("DNSServiceBrowserList: %p is garbage (%X)", b, b->ClientMachPort);
249
250 DNSServiceResolver *l;
251 for (l = DNSServiceResolverList; l; l=l->next)
252 if (l->next == (DNSServiceResolver *)~0 || l->ClientMachPort == 0 || l->ClientMachPort == (mach_port_t) ~0)
253 LogMemCorruption("DNSServiceResolverList: %p is garbage (%X)", l, l->ClientMachPort);
254
255 DNSServiceRegistration *r;
256 for (r = DNSServiceRegistrationList; r; r=r->next)
257 if (r->next == (DNSServiceRegistration *)~0 || r->ClientMachPort == 0 || r->ClientMachPort == (mach_port_t) ~0)
258 LogMemCorruption("DNSServiceRegistrationList: %p is garbage (%X)", r, r->ClientMachPort);
259
260 // Check Unix Domain Socket client lists (uds_daemon.c)
261 uds_validatelists();
262
263 // Check core mDNS lists
264 AuthRecord *rr;
265 for (rr = m->ResourceRecords; rr; rr=rr->next)
266 {
267 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
268 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
269 if (rr->resrec.name != &rr->namestorage)
270 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
271 rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c);
272 }
273
274 for (rr = m->DuplicateRecords; rr; rr=rr->next)
275 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
276 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
277
278 rr = m->NewLocalRecords;
279 if (rr)
280 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
281 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr, rr->resrec.RecordType);
282
283 rr = m->CurrentRecord;
284 if (rr)
285 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
286 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr, rr->resrec.RecordType);
287
288 DNSQuestion *q;
289 for (q = m->Questions; q; q=q->next)
290 if (q->next == (DNSQuestion*)~0 || q->ThisQInterval == (mDNSs32) ~0)
291 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q, q->ThisQInterval, q->next);
292
293 CacheGroup *cg;
294 CacheRecord *cr;
295 mDNSu32 slot;
296 FORALL_CACHERECORDS(slot, cg, cr)
297 {
298 if (cr->resrec.RecordType == 0 || cr->resrec.RecordType == 0xFF)
299 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot, cr, cr->resrec.RecordType);
300 if (cr->CRActiveQuestion)
301 {
302 for (q = m->Questions; q; q=q->next) if (q == cr->CRActiveQuestion) break;
303 if (!q) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot, cr->CRActiveQuestion, CRDisplayString(m, cr));
304 }
305 }
306
307 // Check core uDNS lists
308 udns_validatelists(m);
309
310 // Check platform-layer lists
311 NetworkInterfaceInfoOSX *i;
312 for (i = m->p->InterfaceList; i; i = i->next)
313 if (i->next == (NetworkInterfaceInfoOSX *)~0 || !i->m || i->m == (mDNS *)~0)
314 LogMemCorruption("m->p->InterfaceList: %p is garbage (%p)", i, i->ifinfo.ifname);
315
316 ClientTunnel *t;
317 for (t = m->TunnelClients; t; t=t->next)
318 if (t->next == (ClientTunnel *)~0 || t->dstname.c[0] > 63)
319 LogMemCorruption("m->TunnelClients: %p is garbage (%d)", t, t->dstname.c[0]);
320 }
321
322 mDNSexport void *mallocL(char *msg, unsigned int size)
323 {
324 // Allocate space for two words of sanity checking data before the requested block
325 mDNSu32 *mem = malloc(sizeof(mDNSu32) * 2 + size);
326 if (!mem)
327 { LogMsg("malloc( %s : %d ) failed", msg, size); return(NULL); }
328 else
329 {
330 if (size > 24000) LogMsg("malloc( %s : %lu ) = %p suspiciously large", msg, size, &mem[2]);
331 else if (MACOSX_MDNS_MALLOC_DEBUGGING >= 2) LogMsg("malloc( %s : %lu ) = %p", msg, size, &mem[2]);
332 mem[0] = 0xDEAD1234;
333 mem[1] = size;
334 //mDNSPlatformMemZero(&mem[2], size);
335 memset(&mem[2], 0xFF, size);
336 validatelists(&mDNSStorage);
337 return(&mem[2]);
338 }
339 }
340
341 mDNSexport void freeL(char *msg, void *x)
342 {
343 if (!x)
344 LogMsg("free( %s @ NULL )!", msg);
345 else
346 {
347 mDNSu32 *mem = ((mDNSu32 *)x) - 2;
348 if (mem[0] != 0xDEAD1234) { LogMsg("free( %s @ %p ) !!!! NOT ALLOCATED !!!!", msg, &mem[2]); return; }
349 if (mem[1] > 24000) LogMsg("free( %s : %ld @ %p) suspiciously large", msg, mem[1], &mem[2]);
350 else if (MACOSX_MDNS_MALLOC_DEBUGGING >= 2) LogMsg("free( %s : %ld @ %p)", msg, mem[1], &mem[2]);
351 //mDNSPlatformMemZero(mem, sizeof(mDNSu32) * 2 + mem[1]);
352 memset(mem, 0xFF, sizeof(mDNSu32) * 2 + mem[1]);
353 validatelists(&mDNSStorage);
354 free(mem);
355 }
356 }
357
358 #endif
359
360 //*************************************************************************************************************
361 #if COMPILER_LIKES_PRAGMA_MARK
362 #pragma mark -
363 #pragma mark - Mach client request handlers
364 #endif
365
366 //*************************************************************************************************************
367 // Client Death Detection
368
369 // This gets called after ALL constituent records of the Service Record Set have been deregistered
370 mDNSlocal void FreeServiceInstance(ServiceInstance *x)
371 {
372 ServiceRecordSet *s = &x->srs;
373 ExtraResourceRecord *e = x->srs.Extras, *tmp;
374
375 while (e)
376 {
377 e->r.RecordContext = e;
378 tmp = e;
379 e = e->next;
380 FreeExtraRR(&mDNSStorage, &tmp->r, mStatus_MemFree);
381 }
382
383 if (s->RR_TXT.resrec.rdata != &s->RR_TXT.rdatastorage)
384 freeL("TXT RData", s->RR_TXT.resrec.rdata);
385
386 if (s->SubTypes) freeL("ServiceSubTypes", s->SubTypes);
387 freeL("ServiceInstance", x);
388 }
389
390 // AbortClient finds whatever client is identified by the given Mach port,
391 // stops whatever operation that client was doing, and frees its memory.
392 // In the case of a service registration, the actual freeing may be deferred
393 // until we get the mStatus_MemFree message, if necessary
394 mDNSlocal void AbortClient(mach_port_t ClientMachPort, void *m)
395 {
396 DNSServiceDomainEnumeration **e = &DNSServiceDomainEnumerationList;
397 DNSServiceBrowser **b = &DNSServiceBrowserList;
398 DNSServiceResolver **l = &DNSServiceResolverList;
399 DNSServiceRegistration **r = &DNSServiceRegistrationList;
400
401 while (*e && (*e)->ClientMachPort != ClientMachPort) e = &(*e)->next;
402 if (*e)
403 {
404 DNSServiceDomainEnumeration *x = *e;
405 *e = (*e)->next;
406 if (m && m != x)
407 LogMsg("%5d: DNSServiceDomainEnumeration(%##s) STOP; WARNING m %p != x %p", ClientMachPort, x->dom.qname.c, m, x);
408 else LogOperation("%5d: DNSServiceDomainEnumeration(%##s) STOP", ClientMachPort, x->dom.qname.c);
409 mDNS_StopGetDomains(&mDNSStorage, &x->dom);
410 mDNS_StopGetDomains(&mDNSStorage, &x->def);
411 freeL("DNSServiceDomainEnumeration", x);
412 return;
413 }
414
415 while (*b && (*b)->ClientMachPort != ClientMachPort) b = &(*b)->next;
416 if (*b)
417 {
418 DNSServiceBrowser *x = *b;
419 DNSServiceBrowserQuestion *freePtr, *qptr = x->qlist;
420 *b = (*b)->next;
421 while (qptr)
422 {
423 if (m && m != x)
424 LogMsg("%5d: DNSServiceBrowse(%##s) STOP; WARNING m %p != x %p", ClientMachPort, qptr->q.qname.c, m, x);
425 else LogOperation("%5d: DNSServiceBrowse(%##s) STOP", ClientMachPort, qptr->q.qname.c);
426 mDNS_StopBrowse(&mDNSStorage, &qptr->q);
427 freePtr = qptr;
428 qptr = qptr->next;
429 freeL("DNSServiceBrowserQuestion", freePtr);
430 }
431 while (x->results)
432 {
433 DNSServiceBrowserResult *t = x->results;
434 x->results = x->results->next;
435 freeL("DNSServiceBrowserResult", t);
436 }
437 freeL("DNSServiceBrowser", x);
438 return;
439 }
440
441 while (*l && (*l)->ClientMachPort != ClientMachPort) l = &(*l)->next;
442 if (*l)
443 {
444 DNSServiceResolver *x = *l;
445 *l = (*l)->next;
446 if (m && m != x)
447 LogMsg("%5d: DNSServiceResolve(%##s) STOP; WARNING m %p != x %p", ClientMachPort, x->i.name.c, m, x);
448 else LogOperation("%5d: DNSServiceResolve(%##s) STOP", ClientMachPort, x->i.name.c);
449 mDNS_StopResolveService(&mDNSStorage, &x->q);
450 freeL("DNSServiceResolver", x);
451 return;
452 }
453
454 while (*r && (*r)->ClientMachPort != ClientMachPort) r = &(*r)->next;
455 if (*r)
456 {
457 ServiceInstance *si = NULL;
458 DNSServiceRegistration *x = *r;
459 *r = (*r)->next;
460
461 si = x->regs;
462 while (si)
463 {
464 ServiceInstance *instance = si;
465 si = si->next;
466 instance->renameonmemfree = mDNSfalse;
467 if (m && m != x) LogMsg("%5d: DNSServiceRegistration(%##s, %u) STOP; WARNING m %p != x %p", ClientMachPort, instance->srs.RR_SRV.resrec.name->c, SRS_PORT(&instance->srs), m, x);
468 else LogOperation("%5d: DNSServiceRegistration(%##s, %u) STOP", ClientMachPort, instance->srs.RR_SRV.resrec.name->c, SRS_PORT(&instance->srs));
469
470 // If mDNS_DeregisterService() returns mStatus_NoError, that means that the service was found in the list,
471 // is sending its goodbye packet, and we'll get an mStatus_MemFree message when we can free the memory.
472 // If mDNS_DeregisterService() returns an error, it means that the service had already been removed from
473 // the list, so we should go ahead and free the memory right now
474 if (mDNS_DeregisterService(&mDNSStorage, &instance->srs)) FreeServiceInstance(instance); // FreeServiceInstance invalidates pointer
475 }
476 x->regs = NULL;
477 freeL("DNSServiceRegistration", x);
478 return;
479 }
480
481 LogMsg("%5d: died or deallocated, but no record of client can be found!", ClientMachPort);
482 }
483
484 #define AbortBlockedClient(C,MSG,M) AbortClientWithLogMessage((C), "stopped accepting Mach messages", " (" MSG ")", (M))
485
486 mDNSlocal void AbortClientWithLogMessage(mach_port_t c, char *reason, char *msg, void *m)
487 {
488 DNSServiceDomainEnumeration *e = DNSServiceDomainEnumerationList;
489 DNSServiceBrowser *b = DNSServiceBrowserList;
490 DNSServiceResolver *l = DNSServiceResolverList;
491 DNSServiceRegistration *r = DNSServiceRegistrationList;
492 DNSServiceBrowserQuestion *qptr;
493
494 while (e && e->ClientMachPort != c) e = e->next;
495 while (b && b->ClientMachPort != c) b = b->next;
496 while (l && l->ClientMachPort != c) l = l->next;
497 while (r && r->ClientMachPort != c) r = r->next;
498
499 if (e) LogMsg("%5d: DomainEnumeration(%##s) %s%s", c, e->dom.qname.c, reason, msg);
500 else if (b)
501 {
502 for (qptr = b->qlist; qptr; qptr = qptr->next)
503 LogMsg("%5d: Browser(%##s) %s%s", c, qptr->q.qname.c, reason, msg);
504 }
505 else if (l) LogMsg("%5d: Resolver(%##s) %s%s", c, l->i.name.c, reason, msg);
506 else if (r)
507 {
508 ServiceInstance *si;
509 for (si = r->regs; si; si = si->next)
510 LogMsg("%5d: Registration(%##s) %s%s", c, si->srs.RR_SRV.resrec.name->c, reason, msg);
511 }
512 else LogMsg("%5d: (%s) %s, but no record of client can be found!", c, reason, msg);
513
514 AbortClient(c, m);
515 }
516
517 mDNSlocal mDNSBool CheckForExistingClient(mach_port_t c)
518 {
519 DNSServiceDomainEnumeration *e = DNSServiceDomainEnumerationList;
520 DNSServiceBrowser *b = DNSServiceBrowserList;
521 DNSServiceResolver *l = DNSServiceResolverList;
522 DNSServiceRegistration *r = DNSServiceRegistrationList;
523 DNSServiceBrowserQuestion *qptr;
524
525 while (e && e->ClientMachPort != c) e = e->next;
526 while (b && b->ClientMachPort != c) b = b->next;
527 while (l && l->ClientMachPort != c) l = l->next;
528 while (r && r->ClientMachPort != c) r = r->next;
529 if (e) LogMsg("%5d: DomainEnumeration(%##s) already exists!", c, e->dom.qname.c);
530 if (b)
531 {
532 for (qptr = b->qlist; qptr; qptr = qptr->next)
533 LogMsg("%5d: Browser(%##s) already exists!", c, qptr->q.qname.c);
534 }
535 if (l) LogMsg("%5d: Resolver(%##s) already exists!", c, l->i.name.c);
536 if (r) LogMsg("%5d: Registration(%##s) already exists!", c, r->regs ? r->regs->srs.RR_SRV.resrec.name->c : NULL);
537 return(e || b || l || r);
538 }
539
540 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
541
542 mDNSlocal void ClientDeathCallback(CFMachPortRef unusedport, void *voidmsg, CFIndex size, void *info)
543 {
544 KQueueLock(&mDNSStorage);
545 mach_msg_header_t *msg = (mach_msg_header_t *)voidmsg;
546 (void)unusedport; // Unused
547 (void)size; // Unused
548 (void)info; // Unused
549 if (msg->msgh_id == MACH_NOTIFY_DEAD_NAME)
550 {
551 const mach_dead_name_notification_t *const deathMessage = (mach_dead_name_notification_t *)msg;
552 AbortClient(deathMessage->not_port, NULL);
553
554 /* Deallocate the send right that came in the dead name notification */
555 mach_port_destroy(mach_task_self(), deathMessage->not_port);
556 }
557 KQueueUnlock(&mDNSStorage, "Mach AbortClient");
558 }
559
560 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
561
562 mDNSlocal void EnableDeathNotificationForClient(mach_port_t ClientMachPort, void *m)
563 {
564 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
565 dispatch_source_t mach_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_SEND, ClientMachPort, 0, dispatch_get_main_queue());
566 if (mach_source == mDNSNULL)
567 {
568 AbortClientWithLogMessage(ClientMachPort, "died/deallocated before we could enable death notification", "", m);
569 return;
570 }
571 dispatch_source_set_event_handler(mach_source, ^{
572 mach_port_destroy(mach_task_self(), ClientMachPort);
573 });
574 dispatch_resume(mach_source);
575 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
576 mach_port_t prev;
577 kern_return_t r = mach_port_request_notification(mach_task_self(), ClientMachPort, MACH_NOTIFY_DEAD_NAME, 0,
578 client_death_port, MACH_MSG_TYPE_MAKE_SEND_ONCE, &prev);
579 // If the port already died while we were thinking about it, then abort the operation right away
580 if (r != KERN_SUCCESS)
581 AbortClientWithLogMessage(ClientMachPort, "died/deallocated before we could enable death notification", "", m);
582 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
583 }
584
585 //*************************************************************************************************************
586 // Domain Enumeration
587
588 mDNSlocal void DomainEnumFound(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
589 {
590 kern_return_t status;
591 char buffer[MAX_ESCAPED_DOMAIN_NAME];
592 DNSServiceDomainEnumerationReplyResultType rt;
593 DNSServiceDomainEnumeration *x = (DNSServiceDomainEnumeration *)question->QuestionContext;
594 (void)m; // Unused
595
596 debugf("DomainEnumFound: %##s PTR %##s", answer->name->c, answer->rdata->u.name.c);
597 if (answer->rrtype != kDNSType_PTR) return;
598 if (!x) { debugf("DomainEnumFound: DNSServiceDomainEnumeration is NULL"); return; }
599
600 if (AddRecord)
601 {
602 if (question == &x->dom) rt = DNSServiceDomainEnumerationReplyAddDomain;
603 else rt = DNSServiceDomainEnumerationReplyAddDomainDefault;
604 }
605 else
606 {
607 if (question == &x->dom) rt = DNSServiceDomainEnumerationReplyRemoveDomain;
608 else return;
609 }
610
611 LogOperation("%5d: DNSServiceDomainEnumeration(%##s) %##s %s",
612 x->ClientMachPort, x->dom.qname.c, answer->rdata->u.name.c,
613 !AddRecord ? "RemoveDomain" :
614 question == &x->dom ? "AddDomain" : "AddDomainDefault");
615
616 ConvertDomainNameToCString(&answer->rdata->u.name, buffer);
617 status = DNSServiceDomainEnumerationReply_rpc(x->ClientMachPort, rt, buffer, 0, MDNS_MM_TIMEOUT);
618 if (status == MACH_SEND_TIMED_OUT)
619 AbortBlockedClient(x->ClientMachPort, "enumeration", x);
620 }
621
622 mDNSexport kern_return_t provide_DNSServiceDomainEnumerationCreate_rpc(mach_port_t unusedserver, mach_port_t client,
623 int regDom)
624 {
625 // Check client parameter
626 (void)unusedserver; // Unused
627 mStatus err = mStatus_NoError;
628 const char *errormsg = "Unknown";
629 if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
630 if (CheckForExistingClient(client)) { err = mStatus_Invalid; errormsg = "Client id already in use"; goto fail; }
631
632 mDNS_DomainType dt1 = regDom ? mDNS_DomainTypeRegistration : mDNS_DomainTypeBrowse;
633 mDNS_DomainType dt2 = regDom ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
634
635 // Allocate memory, and handle failure
636 DNSServiceDomainEnumeration *x = mallocL("DNSServiceDomainEnumeration", sizeof(*x));
637 if (!x) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
638
639 // Set up object, and link into list
640 x->ClientMachPort = client;
641 x->next = DNSServiceDomainEnumerationList;
642 DNSServiceDomainEnumerationList = x;
643
644 verbosedebugf("%5d: Enumerate %s Domains", client, regDom ? "Registration" : "Browsing");
645
646 // Do the operation
647 err = mDNS_GetDomains(&mDNSStorage, &x->dom, dt1, NULL, mDNSInterface_LocalOnly, DomainEnumFound, x);
648 if (!err) err = mDNS_GetDomains(&mDNSStorage, &x->def, dt2, NULL, mDNSInterface_LocalOnly, DomainEnumFound, x);
649 if (err) { AbortClient(client, x); errormsg = "mDNS_GetDomains"; goto fail; }
650
651 // Succeeded: Wrap up and return
652 LogOperation("%5d: DNSServiceDomainEnumeration(%##s) START", client, x->dom.qname.c);
653 EnableDeathNotificationForClient(client, x);
654 return(mStatus_NoError);
655
656 fail:
657 LogMsg("%5d: DNSServiceDomainEnumeration(%d) failed: %s (%d)", client, regDom, errormsg, err);
658 return(err);
659 }
660
661 //*************************************************************************************************************
662 // Browse for services
663
664 mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
665 {
666 (void)m; // Unused
667
668 if (answer->rrtype != kDNSType_PTR)
669 { LogMsg("FoundInstance: Should not be called with rrtype %d (not a PTR record)", answer->rrtype); return; }
670
671 domainlabel name;
672 domainname type, domain;
673 if (!DeconstructServiceName(&answer->rdata->u.name, &name, &type, &domain))
674 {
675 LogMsg("FoundInstance: %##s PTR %##s received from network is not valid DNS-SD service pointer",
676 answer->name->c, answer->rdata->u.name.c);
677 return;
678 }
679
680 DNSServiceBrowserResult *x = mallocL("DNSServiceBrowserResult", sizeof(*x));
681 if (!x) { LogMsg("FoundInstance: Failed to allocate memory for result %##s", answer->rdata->u.name.c); return; }
682
683 verbosedebugf("FoundInstance: %s %##s", AddRecord ? "Add" : "Rmv", answer->rdata->u.name.c);
684 AssignDomainName(&x->result, &answer->rdata->u.name);
685 if (AddRecord)
686 x->resultType = DNSServiceBrowserReplyAddInstance;
687 else x->resultType = DNSServiceBrowserReplyRemoveInstance;
688 x->next = NULL;
689
690 DNSServiceBrowser *browser = (DNSServiceBrowser *)question->QuestionContext;
691 DNSServiceBrowserResult **p = &browser->results;
692 while (*p) p = &(*p)->next;
693 *p = x;
694
695 LogOperation("%5d: DNSServiceBrowse(%##s, %s) RESULT %s %s",
696 browser->ClientMachPort, question->qname.c, DNSTypeName(question->qtype), AddRecord ? "Add" : "Rmv", RRDisplayString(m, answer));
697 }
698
699 mDNSlocal mStatus AddDomainToBrowser(DNSServiceBrowser *browser, const domainname *d)
700 {
701 mStatus err = mStatus_NoError;
702 DNSServiceBrowserQuestion *ptr, *question = NULL;
703
704 for (ptr = browser->qlist; ptr; ptr = ptr->next)
705 {
706 if (SameDomainName(&ptr->q.qname, d))
707 { debugf("Domain %##s already contained in browser", d->c); return mStatus_AlreadyRegistered; }
708 }
709
710 question = mallocL("DNSServiceBrowserQuestion", sizeof(DNSServiceBrowserQuestion));
711 if (!question) { LogMsg("Error: malloc"); return mStatus_NoMemoryErr; }
712 AssignDomainName(&question->domain, d);
713 question->next = browser->qlist;
714 LogOperation("%5d: DNSServiceBrowse(%##s%##s) START", browser->ClientMachPort, browser->type.c, d->c);
715 err = mDNS_StartBrowse(&mDNSStorage, &question->q, &browser->type, d, mDNSNULL, mDNSInterface_Any, 0, mDNSfalse, mDNSfalse, FoundInstance, browser);
716 if (!err)
717 browser->qlist = question;
718 else
719 {
720 LogMsg("Error: AddDomainToBrowser: mDNS_StartBrowse %d", err);
721 freeL("DNSServiceBrowserQuestion", question);
722 }
723 return err;
724 }
725
726 mDNSexport void machserver_automatic_browse_domain_changed(const domainname *d, mDNSBool add)
727 {
728 DNSServiceBrowser *ptr;
729 for (ptr = DNSServiceBrowserList; ptr; ptr = ptr->next)
730 {
731 if (ptr->DefaultDomain)
732 {
733 if (add)
734 {
735 mStatus err = AddDomainToBrowser(ptr, d);
736 if (err && err != mStatus_AlreadyRegistered) LogMsg("Default browse in domain %##s for client %5d failed. Continuing", d, ptr->ClientMachPort);
737 }
738 else
739 {
740 DNSServiceBrowserQuestion **q = &ptr->qlist;
741 while (*q)
742 {
743 if (SameDomainName(&(*q)->domain, d))
744 {
745 DNSServiceBrowserQuestion *rem = *q;
746 *q = (*q)->next;
747 mDNS_StopQueryWithRemoves(&mDNSStorage, &rem->q);
748 freeL("DNSServiceBrowserQuestion", rem);
749 return;
750 }
751 q = &(*q)->next;
752 }
753 LogMsg("Requested removal of default domain %##s not in client %5d's list", d->c, ptr->ClientMachPort);
754 }
755 }
756 }
757 }
758
759 mDNSexport kern_return_t provide_DNSServiceBrowserCreate_rpc(mach_port_t unusedserver, mach_port_t client,
760 DNSCString regtype, DNSCString domain)
761 {
762 // Check client parameter
763 (void)unusedserver; // Unused
764 mStatus err = mStatus_NoError;
765 const char *errormsg = "Unknown";
766
767 if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
768 if (CheckForExistingClient(client)) { err = mStatus_Invalid; errormsg = "Client id already in use"; goto fail; }
769
770 // Check other parameters
771 domainname t, d;
772 t.c[0] = 0;
773 mDNSs32 NumSubTypes = ChopSubTypes(regtype, mDNSNULL); // Note: Modifies regtype string to remove trailing subtypes
774 if (NumSubTypes < 0 || NumSubTypes > 1) { errormsg = "Bad Service SubType"; goto badparam; }
775 if (NumSubTypes == 1 && !AppendDNSNameString(&t, regtype + strlen(regtype) + 1))
776 { errormsg = "Bad Service SubType"; goto badparam; }
777 if (!regtype[0] || !AppendDNSNameString(&t, regtype)) { errormsg = "Illegal regtype"; goto badparam; }
778 domainname temp;
779 if (!MakeDomainNameFromDNSNameString(&temp, regtype)) { errormsg = "Illegal regtype"; goto badparam; }
780 if (temp.c[0] > 15 && (!domain || domain[0] == 0)) domain = "local."; // For over-long service types, we only allow domain "local"
781
782 // Allocate memory, and handle failure
783 DNSServiceBrowser *x = mallocL("DNSServiceBrowser", sizeof(*x));
784 if (!x) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
785
786 // Set up object, and link into list
787 AssignDomainName(&x->type, &t);
788 x->ClientMachPort = client;
789 x->results = NULL;
790 x->lastsuccess = 0;
791 x->qlist = NULL;
792 x->next = DNSServiceBrowserList;
793 DNSServiceBrowserList = x;
794
795 if (domain[0])
796 {
797 // Start browser for an explicit domain
798 x->DefaultDomain = mDNSfalse;
799 if (!MakeDomainNameFromDNSNameString(&d, domain)) { errormsg = "Illegal domain"; goto badparam; }
800 err = AddDomainToBrowser(x, &d);
801 if (err) { AbortClient(client, x); errormsg = "AddDomainToBrowser"; goto fail; }
802 }
803 else
804 {
805 DNameListElem *sdPtr;
806 // Start browser on all domains
807 x->DefaultDomain = mDNStrue;
808 if (!AutoBrowseDomains) { AbortClient(client, x); errormsg = "GetSearchDomainList"; goto fail; }
809 for (sdPtr = AutoBrowseDomains; sdPtr; sdPtr = sdPtr->next)
810 {
811 err = AddDomainToBrowser(x, &sdPtr->name);
812 if (err)
813 {
814 // only terminally bail if .local fails
815 if (!SameDomainName(&localdomain, &sdPtr->name))
816 LogMsg("Default browse in domain %##s failed. Continuing", sdPtr->name.c);
817 else { AbortClient(client, x); errormsg = "AddDomainToBrowser"; goto fail; }
818 }
819 }
820 }
821
822 // Succeeded: Wrap up and return
823 EnableDeathNotificationForClient(client, x);
824 return(mStatus_NoError);
825
826 badparam:
827 err = mStatus_BadParamErr;
828 fail:
829 LogMsg("%5d: DNSServiceBrowse(\"%s\", \"%s\") failed: %s (%d)", client, regtype, domain, errormsg, err);
830 return(err);
831 }
832
833 //*************************************************************************************************************
834 // Resolve Service Info
835
836 mDNSlocal void FoundInstanceInfo(mDNS *const m, ServiceInfoQuery *query)
837 {
838 kern_return_t status;
839 DNSServiceResolver *x = (DNSServiceResolver *)query->ServiceInfoQueryContext;
840 NetworkInterfaceInfoOSX *ifx = IfindexToInterfaceInfoOSX(m, query->info->InterfaceID);
841 if (query->info->InterfaceID == mDNSInterface_LocalOnly || query->info->InterfaceID == mDNSInterface_P2P) ifx = mDNSNULL;
842 struct sockaddr_storage interface;
843 struct sockaddr_storage address;
844 char cstring[1024];
845 int i, pstrlen = query->info->TXTinfo[0];
846 (void)m; // Unused
847
848 //debugf("FoundInstanceInfo %.4a %.4a %##s", &query->info->InterfaceAddr, &query->info->ip, &query->info->name);
849
850 if (query->info->TXTlen > sizeof(cstring)) return;
851
852 mDNSPlatformMemZero(&interface, sizeof(interface));
853 mDNSPlatformMemZero(&address, sizeof(address));
854
855 if (ifx && ifx->ifinfo.ip.type == mDNSAddrType_IPv4)
856 {
857 struct sockaddr_in *s = (struct sockaddr_in*)&interface;
858 s->sin_len = sizeof(*s);
859 s->sin_family = AF_INET;
860 s->sin_port = 0;
861 s->sin_addr.s_addr = ifx->ifinfo.ip.ip.v4.NotAnInteger;
862 }
863 else if (ifx && ifx->ifinfo.ip.type == mDNSAddrType_IPv6)
864 {
865 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&interface;
866 sin6->sin6_len = sizeof(*sin6);
867 sin6->sin6_family = AF_INET6;
868 sin6->sin6_flowinfo = 0;
869 sin6->sin6_port = 0;
870 sin6->sin6_addr = *(struct in6_addr*)&ifx->ifinfo.ip.ip.v6;
871 sin6->sin6_scope_id = ifx->scope_id;
872 }
873
874 if (query->info->ip.type == mDNSAddrType_IPv4)
875 {
876 struct sockaddr_in *s = (struct sockaddr_in*)&address;
877 s->sin_len = sizeof(*s);
878 s->sin_family = AF_INET;
879 s->sin_port = query->info->port.NotAnInteger;
880 s->sin_addr.s_addr = query->info->ip.ip.v4.NotAnInteger;
881 }
882 else
883 {
884 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&address;
885 sin6->sin6_len = sizeof(*sin6);
886 sin6->sin6_family = AF_INET6;
887 sin6->sin6_port = query->info->port.NotAnInteger;
888 sin6->sin6_flowinfo = 0;
889 sin6->sin6_addr = *(struct in6_addr*)&query->info->ip.ip.v6;
890 sin6->sin6_scope_id = ifx ? ifx->scope_id : 0;
891 }
892
893 // The OS X DNSServiceResolverResolve() API is defined using a C-string,
894 // but the mDNS_StartResolveService() call actually returns a packed block of P-strings.
895 // Hence we have to convert the P-string(s) to a C-string before returning the result to the client.
896 // ASCII-1 characters are used in the C-string as boundary markers,
897 // to indicate the boundaries between the original constituent P-strings.
898 for (i=1; i<query->info->TXTlen; i++)
899 {
900 if (--pstrlen >= 0)
901 cstring[i-1] = query->info->TXTinfo[i];
902 else
903 {
904 cstring[i-1] = 1;
905 pstrlen = query->info->TXTinfo[i];
906 }
907 }
908 cstring[i-1] = 0; // Put the terminating NULL on the end
909
910 LogOperation("%5d: DNSServiceResolver(%##s) -> %#a:%u", x->ClientMachPort,
911 x->i.name.c, &query->info->ip, mDNSVal16(query->info->port));
912 status = DNSServiceResolverReply_rpc(x->ClientMachPort,
913 (char*)&interface, (char*)&address, cstring, 0, MDNS_MM_TIMEOUT);
914 if (status == MACH_SEND_TIMED_OUT)
915 AbortBlockedClient(x->ClientMachPort, "resolve", x);
916 }
917
918 mDNSexport kern_return_t provide_DNSServiceResolverResolve_rpc(mach_port_t unusedserver, mach_port_t client,
919 DNSCString name, DNSCString regtype, DNSCString domain)
920 {
921 // Check client parameter
922 (void)unusedserver; // Unused
923 mStatus err = mStatus_NoError;
924 const char *errormsg = "Unknown";
925 if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
926 if (CheckForExistingClient(client)) { err = mStatus_Invalid; errormsg = "Client id already in use"; goto fail; }
927
928 // Check other parameters
929 domainlabel n;
930 domainname t, d, srv;
931 if (!name[0] || !MakeDomainLabelFromLiteralString(&n, name)) { errormsg = "Bad Instance Name"; goto badparam; }
932 if (!regtype[0] || !MakeDomainNameFromDNSNameString(&t, regtype)) { errormsg = "Bad Service Type"; goto badparam; }
933 if (!domain[0] || !MakeDomainNameFromDNSNameString(&d, domain)) { errormsg = "Bad Domain"; goto badparam; }
934 if (!ConstructServiceName(&srv, &n, &t, &d)) { errormsg = "Bad Name"; goto badparam; }
935
936 // Allocate memory, and handle failure
937 DNSServiceResolver *x = mallocL("DNSServiceResolver", sizeof(*x));
938 if (!x) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
939
940 // Set up object, and link into list
941 x->ClientMachPort = client;
942 x->i.InterfaceID = mDNSInterface_Any;
943 x->i.name = srv;
944 x->ReportTime = NonZeroTime(mDNS_TimeNow(&mDNSStorage) + 130 * mDNSPlatformOneSecond);
945 x->next = DNSServiceResolverList;
946 DNSServiceResolverList = x;
947
948 // Do the operation
949 LogOperation("%5d: DNSServiceResolve(%##s) START", client, x->i.name.c);
950 err = mDNS_StartResolveService(&mDNSStorage, &x->q, &x->i, FoundInstanceInfo, x);
951 if (err) { AbortClient(client, x); errormsg = "mDNS_StartResolveService"; goto fail; }
952
953 // Succeeded: Wrap up and return
954 EnableDeathNotificationForClient(client, x);
955 return(mStatus_NoError);
956
957 badparam:
958 err = mStatus_BadParamErr;
959 fail:
960 LogMsg("%5d: DNSServiceResolve(\"%s\", \"%s\", \"%s\") failed: %s (%d)", client, name, regtype, domain, errormsg, err);
961 return(err);
962 }
963
964 //*************************************************************************************************************
965 // Registration
966
967 mDNSexport void RecordUpdatedNiceLabel(mDNS *const m, mDNSs32 delay)
968 {
969 m->p->NotifyUser = NonZeroTime(m->timenow + delay);
970 }
971
972 mDNSlocal void RegCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
973 {
974 ServiceInstance *si = (ServiceInstance*)srs->ServiceContext;
975
976 if (result == mStatus_NoError)
977 {
978 kern_return_t status;
979 LogOperation("%5d: DNSServiceRegistration(%##s, %u) Name Registered", si->ClientMachPort, srs->RR_SRV.resrec.name->c, SRS_PORT(srs));
980 status = DNSServiceRegistrationReply_rpc(si->ClientMachPort, result, MDNS_MM_TIMEOUT);
981 if (status == MACH_SEND_TIMED_OUT)
982 AbortBlockedClient(si->ClientMachPort, "registration success", si);
983 if (si->autoname && CountPeerRegistrations(m, srs) == 0)
984 RecordUpdatedNiceLabel(m, 0); // Successfully got new name, tell user immediately
985 }
986
987 else if (result == mStatus_NameConflict)
988 {
989 LogOperation("%5d: DNSServiceRegistration(%##s, %u) Name Conflict", si->ClientMachPort, srs->RR_SRV.resrec.name->c, SRS_PORT(srs));
990 // Note: By the time we get the mStatus_NameConflict message, the service is already deregistered
991 // and the memory is free, so we don't have to wait for an mStatus_MemFree message as well.
992 if (si->autoname && CountPeerRegistrations(m, srs) == 0)
993 {
994 // On conflict for an autoname service, rename and reregister *all* autoname services
995 IncrementLabelSuffix(&m->nicelabel, mDNStrue);
996 mDNS_ConfigChanged(m);
997 }
998 else if (si->autoname)
999 {
1000 mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
1001 return;
1002 }
1003 else
1004 {
1005 // If we get a name conflict, we tell the client about it, and then they are expected to dispose
1006 // of their registration in the usual way (which we will catch via client death notification).
1007 // If the Mach queue is full, we forcibly abort the client immediately.
1008 kern_return_t status = DNSServiceRegistrationReply_rpc(si->ClientMachPort, result, MDNS_MM_TIMEOUT);
1009 if (status == MACH_SEND_TIMED_OUT)
1010 AbortBlockedClient(si->ClientMachPort, "registration conflict", NULL);
1011 }
1012 }
1013
1014 else if (result == mStatus_MemFree)
1015 {
1016 if (si->renameonmemfree) // We intentionally terminated registration so we could re-register with new name
1017 {
1018 debugf("RegCallback renaming %#s to %#s", si->name.c, m->nicelabel.c);
1019 si->renameonmemfree = mDNSfalse;
1020 si->name = m->nicelabel;
1021 mDNS_RenameAndReregisterService(m, srs, &si->name);
1022 }
1023 else
1024 {
1025 // SANITY CHECK: make sure service instance is no longer in any ServiceRegistration's list
1026 DNSServiceRegistration *r;
1027 for (r = DNSServiceRegistrationList; r; r = r->next)
1028 {
1029 ServiceInstance **sp = &r->regs;
1030 while (*sp)
1031 {
1032 if (*sp == si) { LogMsg("RegCallback: %##s Still in list; removing", srs->RR_SRV.resrec.name->c); *sp = (*sp)->next; break; }
1033 sp = &(*sp)->next;
1034 }
1035 }
1036 // END SANITY CHECK
1037 FreeServiceInstance(si);
1038 }
1039 }
1040
1041 else if (result != mStatus_NATTraversal)
1042 LogMsg("%5d: DNSServiceRegistration(%##s, %u) Unknown Result %d", si->ClientMachPort, srs->RR_SRV.resrec.name->c, SRS_PORT(srs), result);
1043 }
1044
1045 mDNSlocal mStatus AddServiceInstance(DNSServiceRegistration *x, const domainname *domain)
1046 {
1047 mStatus err = 0;
1048 ServiceInstance *si = NULL;
1049 AuthRecord *SubTypes = NULL;
1050
1051 for (si = x->regs; si; si = si->next)
1052 {
1053 if (SameDomainName(&si->domain, domain))
1054 { LogMsg("Requested addition of domain %##s already in list", domain->c); return mStatus_AlreadyRegistered; }
1055 }
1056
1057 SubTypes = AllocateSubTypes(x->NumSubTypes, x->regtype, mDNSNULL);
1058 if (x->NumSubTypes && !SubTypes) return mStatus_NoMemoryErr;
1059
1060 si = mallocL("ServiceInstance", sizeof(*si) - sizeof(RDataBody) + x->rdsize);
1061 if (!si) return mStatus_NoMemoryErr;
1062
1063 si->ClientMachPort = x->ClientMachPort;
1064 si->renameonmemfree = mDNSfalse;
1065 si->autoname = x->autoname;
1066 si->name = x->autoname ? mDNSStorage.nicelabel : x->name;
1067 si->domain = *domain;
1068 si->srs.AnonData = mDNSNULL;
1069
1070 err = mDNS_RegisterService(&mDNSStorage, &si->srs, &si->name, &x->type, domain, NULL,
1071 x->port, x->txtinfo, x->txt_len, SubTypes, x->NumSubTypes, mDNSInterface_Any, RegCallback, si, 0);
1072 if (!err)
1073 {
1074 si->next = x->regs;
1075 x->regs = si;
1076 }
1077 else
1078 {
1079 LogMsg("Error %d for registration of service in domain %##s", err, domain->c);
1080 freeL("ServiceInstance", si);
1081 }
1082 return err;
1083 }
1084
1085 mDNSexport void machserver_automatic_registration_domain_changed(const domainname *d, mDNSBool add)
1086 {
1087 DNSServiceRegistration *reg;
1088
1089 for (reg = DNSServiceRegistrationList; reg; reg = reg->next)
1090 {
1091 if (reg->DefaultDomain)
1092 {
1093 if (add)
1094 AddServiceInstance(reg, d);
1095 else
1096 {
1097 ServiceInstance **si = &reg->regs;
1098 while (*si)
1099 {
1100 if (SameDomainName(&(*si)->domain, d))
1101 {
1102 ServiceInstance *s = *si;
1103 *si = (*si)->next;
1104 if (mDNS_DeregisterService(&mDNSStorage, &s->srs)) FreeServiceInstance(s); // only free memory synchronously on error
1105 break;
1106 }
1107 si = &(*si)->next;
1108 }
1109 if (!si) debugf("Requested removal of default domain %##s not in client %5d's list", d, reg->ClientMachPort); // normal if registration failed
1110 }
1111 }
1112 }
1113 }
1114
1115 mDNSexport kern_return_t provide_DNSServiceRegistrationCreate_rpc(mach_port_t unusedserver, mach_port_t client,
1116 DNSCString name, DNSCString regtype, DNSCString domain, IPPort IpPort, DNSCString txtRecord)
1117 {
1118 (void)unusedserver; // Unused
1119 mStatus err = mStatus_NoError;
1120 const char *errormsg = "Unknown";
1121
1122 // older versions of this code passed the port via mach IPC as an int.
1123 // we continue to pass it as 4 bytes to maintain binary compatibility,
1124 // but now ensure that the network byte order is preserved by using a struct
1125 mDNSIPPort port;
1126 port.b[0] = IpPort.bytes[2];
1127 port.b[1] = IpPort.bytes[3];
1128
1129 if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
1130 if (CheckForExistingClient(client)) { err = mStatus_Invalid; errormsg = "Client id already in use"; goto fail; }
1131
1132 // Check for sub-types after the service type
1133 size_t reglen = strlen(regtype) + 1;
1134 if (reglen > MAX_ESCAPED_DOMAIN_NAME) { errormsg = "reglen too long"; goto badparam; }
1135 mDNSs32 NumSubTypes = ChopSubTypes(regtype, mDNSNULL); // Note: Modifies regtype string to remove trailing subtypes
1136 if (NumSubTypes < 0) { errormsg = "Bad Service SubType"; goto badparam; }
1137
1138 // Check other parameters
1139 domainlabel n;
1140 domainname t, d;
1141 domainname srv;
1142 if (!name[0]) n = mDNSStorage.nicelabel;
1143 else if (!MakeDomainLabelFromLiteralString(&n, name)) { errormsg = "Bad Instance Name"; goto badparam; }
1144 if (!regtype[0] || !MakeDomainNameFromDNSNameString(&t, regtype)) { errormsg = "Bad Service Type"; goto badparam; }
1145 if (!MakeDomainNameFromDNSNameString(&d, *domain ? domain : "local.")) { errormsg = "Bad Domain"; goto badparam; }
1146 if (!ConstructServiceName(&srv, &n, &t, &d)) { errormsg = "Bad Name"; goto badparam; }
1147
1148 unsigned char txtinfo[1024] = "";
1149 unsigned int data_len = 0;
1150 unsigned int size = sizeof(RDataBody);
1151 unsigned char *pstring = &txtinfo[data_len];
1152 char *ptr = txtRecord;
1153
1154 // The OS X DNSServiceRegistrationCreate() API is defined using a C-string,
1155 // but the mDNS_RegisterService() call actually requires a packed block of P-strings.
1156 // Hence we have to convert the C-string to a P-string.
1157 // ASCII-1 characters are allowed in the C-string as boundary markers,
1158 // so that a single C-string can be used to represent one or more P-strings.
1159 while (*ptr)
1160 {
1161 if (++data_len >= sizeof(txtinfo)) { errormsg = "TXT record too long"; goto badtxt; }
1162 if (*ptr == 1) // If this is our boundary marker, start a new P-string
1163 {
1164 pstring = &txtinfo[data_len];
1165 pstring[0] = 0;
1166 ptr++;
1167 }
1168 else
1169 {
1170 if (pstring[0] == 255) { errormsg = "TXT record invalid (component longer than 255)"; goto badtxt; }
1171 pstring[++pstring[0]] = *ptr++;
1172 }
1173 }
1174
1175 data_len++;
1176 if (size < data_len)
1177 size = data_len;
1178
1179 // Some clients use mDNS for lightweight copy protection, registering a pseudo-service with
1180 // a port number of zero. When two instances of the protected client are allowed to run on one
1181 // machine, we don't want to see misleading "Bogus client" messages in syslog and the console.
1182 if (!mDNSIPPortIsZero(port))
1183 {
1184 int count = CountExistingRegistrations(&srv, port);
1185 if (count)
1186 LogMsg("%5d: Client application registered %d identical instances of service %##s port %u.",
1187 client, count+1, srv.c, mDNSVal16(port));
1188 }
1189
1190 // Allocate memory, and handle failure
1191 DNSServiceRegistration *x = mallocL("DNSServiceRegistration", sizeof(*x));
1192 if (!x) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
1193 mDNSPlatformMemZero(x, sizeof(*x));
1194
1195 // Set up object, and link into list
1196 x->ClientMachPort = client;
1197 x->DefaultDomain = !domain[0];
1198 x->autoname = (!name[0]);
1199 x->rdsize = size;
1200 x->NumSubTypes = NumSubTypes;
1201 memcpy(x->regtype, regtype, reglen);
1202 x->name = n;
1203 x->type = t;
1204 x->port = port;
1205 memcpy(x->txtinfo, txtinfo, 1024);
1206 x->txt_len = data_len;
1207 x->NextRef = 0;
1208 x->regs = NULL;
1209
1210 x->next = DNSServiceRegistrationList;
1211 DNSServiceRegistrationList = x;
1212
1213 LogOperation("%5d: DNSServiceRegistration(\"%s\", \"%s\", \"%s\", %u) START",
1214 x->ClientMachPort, name, regtype, domain, mDNSVal16(port));
1215
1216 err = AddServiceInstance(x, &d);
1217 if (err) { AbortClient(client, x); errormsg = "mDNS_RegisterService"; goto fail; } // bail if .local (or explicit domain) fails
1218
1219 if (x->DefaultDomain)
1220 {
1221 DNameListElem *p;
1222 for (p = AutoRegistrationDomains; p; p = p->next)
1223 AddServiceInstance(x, &p->name);
1224 }
1225
1226 // Succeeded: Wrap up and return
1227 EnableDeathNotificationForClient(client, x);
1228 return(mStatus_NoError);
1229
1230 badtxt:
1231 LogMsg("%5d: TXT record: %.100s...", client, txtRecord);
1232 badparam:
1233 err = mStatus_BadParamErr;
1234 fail:
1235 LogMsg("%5d: DNSServiceRegister(\"%s\", \"%s\", \"%s\", %d) failed: %s (%d)",
1236 client, name, regtype, domain, mDNSVal16(port), errormsg, err);
1237 return(err);
1238 }
1239
1240 mDNSlocal void mDNSPreferencesSetNames(mDNS *const m, int key, domainlabel *old, domainlabel *new)
1241 {
1242 domainlabel *prevold, *prevnew;
1243 switch (key)
1244 {
1245 case kmDNSComputerName:
1246 case kmDNSLocalHostName:
1247 if (key == kmDNSComputerName)
1248 {
1249 prevold = &m->p->prevoldnicelabel;
1250 prevnew = &m->p->prevnewnicelabel;
1251 }
1252 else
1253 {
1254 prevold = &m->p->prevoldhostlabel;
1255 prevnew = &m->p->prevnewhostlabel;
1256 }
1257 // There are a few cases where we need to invoke the helper.
1258 //
1259 // 1. If the "old" label and "new" label are not same, it means there is a conflict. We need
1260 // to invoke the helper so that it pops up a dialogue to inform the user about the
1261 // conflict
1262 //
1263 // 2. If the "old" label and "new" label are same, it means the user has set the host/nice label
1264 // through the preferences pane. We may have to inform the helper as it may have popped up
1265 // a dialogue previously (due to a conflict) and it needs to suppress it now. We can avoid invoking
1266 // the helper in this case if the previous values (old and new) that we told helper last time
1267 // are same. If the previous old and new values are same, helper does not care.
1268 //
1269 // Note: "new" can be NULL when we have repeated conflicts and we are asking helper to give up. "old"
1270 // is not called with NULL today, but this makes it future proof.
1271 if (!old || !new || !SameDomainLabelCS(old->c, new->c) ||
1272 !SameDomainLabelCS(old->c, prevold->c) ||
1273 !SameDomainLabelCS(new->c, prevnew->c))
1274 {
1275 if (old)
1276 *prevold = *old;
1277 else
1278 prevold->c[0] = 0;
1279 if (new)
1280 *prevnew = *new;
1281 else
1282 prevnew->c[0] = 0;
1283 mDNSPreferencesSetName(key, old, new);
1284 }
1285 else
1286 {
1287 LogInfo("mDNSPreferencesSetNames not invoking helper %s %#s, %s %#s, old %#s, new %#s",
1288 (key == kmDNSComputerName ? "prevoldnicelabel" : "prevoldhostlabel"), prevold->c,
1289 (key == kmDNSComputerName ? "prevnewnicelabel" : "prevnewhostlabel"), prevnew->c,
1290 old->c, new->c);
1291 }
1292 break;
1293 default:
1294 LogMsg("mDNSPreferencesSetNames: unrecognized key: %d", key);
1295 return;
1296 }
1297 }
1298
1299 mDNSlocal void mDNS_StatusCallback(mDNS *const m, mStatus result)
1300 {
1301 (void)m; // Unused
1302 if (result == mStatus_NoError)
1303 {
1304 if (!SameDomainLabelCS(m->p->userhostlabel.c, m->hostlabel.c))
1305 LogInfo("Local Hostname changed from \"%#s.local\" to \"%#s.local\"", m->p->userhostlabel.c, m->hostlabel.c);
1306 // One second pause in case we get a Computer Name update too -- don't want to alert the user twice
1307 RecordUpdatedNiceLabel(m, mDNSPlatformOneSecond);
1308 }
1309 else if (result == mStatus_NameConflict)
1310 {
1311 LogInfo("Local Hostname conflict for \"%#s.local\"", m->hostlabel.c);
1312 if (!m->p->HostNameConflict) m->p->HostNameConflict = NonZeroTime(m->timenow);
1313 else if (m->timenow - m->p->HostNameConflict > 60 * mDNSPlatformOneSecond)
1314 {
1315 // Tell the helper we've given up
1316 mDNSPreferencesSetNames(m, kmDNSLocalHostName, &m->p->userhostlabel, NULL);
1317 }
1318 }
1319 else if (result == mStatus_GrowCache)
1320 {
1321 // Allocate another chunk of cache storage
1322 CacheEntity *storage = mallocL("mStatus_GrowCache", sizeof(CacheEntity) * RR_CACHE_SIZE);
1323 //LogInfo("GrowCache %d * %d = %d", sizeof(CacheEntity), RR_CACHE_SIZE, sizeof(CacheEntity) * RR_CACHE_SIZE);
1324 if (storage) mDNS_GrowCache(m, storage, RR_CACHE_SIZE);
1325 }
1326 else if (result == mStatus_ConfigChanged)
1327 {
1328 // Tell the helper we've seen a change in the labels. It will dismiss the name conflict alert if needed.
1329 mDNSPreferencesSetNames(m, kmDNSComputerName, &m->p->usernicelabel, &m->nicelabel);
1330 mDNSPreferencesSetNames(m, kmDNSLocalHostName, &m->p->userhostlabel, &m->hostlabel);
1331
1332 // First we check our list of old Mach-based registered services, to see if any need to be updated to a new name
1333 DNSServiceRegistration *r;
1334 for (r = DNSServiceRegistrationList; r; r=r->next)
1335 if (r->autoname)
1336 {
1337 ServiceInstance *si;
1338 for (si = r->regs; si; si = si->next)
1339 {
1340 if (!SameDomainLabelCS(si->name.c, m->nicelabel.c))
1341 {
1342 debugf("NetworkChanged renaming %##s to %#s", si->srs.RR_SRV.resrec.name->c, m->nicelabel.c);
1343 si->renameonmemfree = mDNStrue;
1344 if (mDNS_DeregisterService_drt(m, &si->srs, mDNS_Dereg_rapid))
1345 RegCallback(m, &si->srs, mStatus_MemFree); // If service deregistered already, we can re-register immediately
1346 }
1347 }
1348 }
1349
1350 // Then we call into the UDS daemon code, to let it do the same
1351 udsserver_handle_configchange(m);
1352 }
1353 }
1354
1355 //*************************************************************************************************************
1356 // Add / Update / Remove records from existing Registration
1357
1358 mDNSexport kern_return_t provide_DNSServiceRegistrationAddRecord_rpc(mach_port_t unusedserver, mach_port_t client,
1359 int type, const char *data, mach_msg_type_number_t data_len, uint32_t ttl, natural_t *reference)
1360 {
1361 // Check client parameter
1362 uint32_t id;
1363 mStatus err = mStatus_NoError;
1364 const char *errormsg = "Unknown";
1365 DNSServiceRegistration *x = DNSServiceRegistrationList;
1366 if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
1367 ServiceInstance *si;
1368 size_t size;
1369 (void)unusedserver; // Unused
1370 while (x && x->ClientMachPort != client) x = x->next;
1371 if (!x) { err = mStatus_BadReferenceErr; errormsg = "No such client"; goto fail; }
1372
1373 // Check other parameters
1374 if (data_len > 8192) { err = mStatus_BadParamErr; errormsg = "data_len > 8K"; goto fail; }
1375 if (data_len > sizeof(RDataBody)) size = data_len;
1376 else size = sizeof(RDataBody);
1377
1378 id = x->NextRef++;
1379 *reference = (natural_t)id;
1380 for (si = x->regs; si; si = si->next)
1381 {
1382 // Allocate memory, and handle failure
1383 ExtraResourceRecord *extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
1384 if (!extra) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
1385
1386 // Fill in type, length, and data of new record
1387 extra->r.resrec.rrtype = type;
1388 extra->r.rdatastorage.MaxRDLength = size;
1389 extra->r.resrec.rdlength = data_len;
1390 memcpy(&extra->r.rdatastorage.u.data, data, data_len);
1391
1392 // Do the operation
1393 LogOperation("%5d: DNSServiceRegistrationAddRecord(%##s, type %d, length %d) REF %p",
1394 client, si->srs.RR_SRV.resrec.name->c, type, data_len, extra);
1395 err = mDNS_AddRecordToService(&mDNSStorage, &si->srs, extra, &extra->r.rdatastorage, ttl, 0);
1396
1397 if (err)
1398 {
1399 freeL("Extra Resource Record", extra);
1400 errormsg = "mDNS_AddRecordToService";
1401 goto fail;
1402 }
1403
1404 extra->ClientID = id;
1405 }
1406
1407 return mStatus_NoError;
1408
1409 fail:
1410 LogMsg("%5d: DNSServiceRegistrationAddRecord(%##s, type %d, length %d) failed: %s (%d)", client, x ? x->name.c : (mDNSu8*)"\x8" "«NULL»", type, data_len, errormsg, err);
1411 return mStatus_UnknownErr;
1412 }
1413
1414 mDNSlocal void UpdateCallback(mDNS *const m, AuthRecord *const rr, RData *OldRData, mDNSu16 OldRDLen)
1415 {
1416 (void)m; // Unused
1417 (void)OldRDLen; // Unused
1418 if (OldRData != &rr->rdatastorage)
1419 freeL("Old RData", OldRData);
1420 }
1421
1422 mDNSlocal mStatus UpdateRecord(ServiceRecordSet *srs, mach_port_t client, AuthRecord *rr, const char *data, mach_msg_type_number_t data_len, uint32_t ttl)
1423 {
1424 // Check client parameter
1425 mStatus err = mStatus_NoError;
1426 const char *errormsg = "Unknown";
1427 const domainname *name = (const domainname *)"";
1428
1429 name = srs->RR_SRV.resrec.name;
1430
1431 unsigned int size = sizeof(RDataBody);
1432 if (size < data_len)
1433 size = data_len;
1434
1435 // Allocate memory, and handle failure
1436 RData *newrdata = mallocL("RData", sizeof(*newrdata) - sizeof(RDataBody) + size);
1437 if (!newrdata) { err = mStatus_NoMemoryErr; errormsg = "No memory"; goto fail; }
1438
1439 // Fill in new length, and data
1440 newrdata->MaxRDLength = size;
1441 memcpy(&newrdata->u, data, data_len);
1442
1443 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1444 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1445 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1446 if (rr->resrec.rrtype == kDNSType_TXT && data_len == 0) { data_len = 1; newrdata->u.txt.c[0] = 0; }
1447
1448 // Do the operation
1449 LogOperation("%5d: DNSServiceRegistrationUpdateRecord(%##s, new length %d)",
1450 client, srs->RR_SRV.resrec.name->c, data_len);
1451
1452 err = mDNS_Update(&mDNSStorage, rr, ttl, data_len, newrdata, UpdateCallback);
1453 if (err)
1454 {
1455 errormsg = "mDNS_Update";
1456 freeL("RData", newrdata);
1457 return err;
1458 }
1459 return(mStatus_NoError);
1460
1461 fail:
1462 LogMsg("%5d: DNSServiceRegistrationUpdateRecord(%##s, %d) failed: %s (%d)", client, name->c, data_len, errormsg, err);
1463 return(err);
1464 }
1465
1466 mDNSexport kern_return_t provide_DNSServiceRegistrationUpdateRecord_rpc(mach_port_t unusedserver, mach_port_t client,
1467 natural_t reference, const char *data, mach_msg_type_number_t data_len, uint32_t ttl)
1468 {
1469 // Check client parameter
1470 mStatus err = mStatus_NoError;
1471 const char *errormsg = "Unknown";
1472 const domainname *name = (const domainname *)"";
1473 ServiceInstance *si;
1474
1475 (void)unusedserver; // unused
1476 if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
1477 DNSServiceRegistration *x = DNSServiceRegistrationList;
1478 while (x && x->ClientMachPort != client) x = x->next;
1479 if (!x) { err = mStatus_BadReferenceErr; errormsg = "No such client"; goto fail; }
1480
1481 // Check other parameters
1482 if (data_len > 8192) { err = mStatus_BadParamErr; errormsg = "data_len > 8K"; goto fail; }
1483
1484 for (si = x->regs; si; si = si->next)
1485 {
1486 AuthRecord *r = NULL;
1487
1488 // Find the record we're updating. NULL reference means update the primary TXT record
1489 if (!reference) r = &si->srs.RR_TXT;
1490 else
1491 {
1492 ExtraResourceRecord *ptr;
1493 for (ptr = si->srs.Extras; ptr; ptr = ptr->next)
1494 {
1495 if ((natural_t)ptr->ClientID == reference)
1496 { r = &ptr->r; break; }
1497 }
1498 if (!r) { err = mStatus_BadReferenceErr; errormsg = "No such record"; goto fail; }
1499 }
1500 err = UpdateRecord(&si->srs, client, r, data, data_len, ttl);
1501 if (err) goto fail; //!!!KRS this will cause failures for non-local defaults!
1502 }
1503
1504 return mStatus_NoError;
1505
1506 fail:
1507 LogMsg("%5d: DNSServiceRegistrationUpdateRecord(%##s, %X, %d) failed: %s (%d)", client, name->c, reference, data_len, errormsg, err);
1508 return(err);
1509 }
1510
1511 mDNSlocal mStatus RemoveRecord(ServiceRecordSet *srs, ExtraResourceRecord *extra, mach_port_t client)
1512 {
1513 const domainname *const name = srs->RR_SRV.resrec.name;
1514 mStatus err = mStatus_NoError;
1515
1516 // Do the operation
1517 LogOperation("%5d: DNSServiceRegistrationRemoveRecord(%##s)", client, srs->RR_SRV.resrec.name->c);
1518
1519 err = mDNS_RemoveRecordFromService(&mDNSStorage, srs, extra, FreeExtraRR, extra);
1520 if (err) LogMsg("%5d: DNSServiceRegistrationRemoveRecord (%##s) failed: %d", client, name->c, err);
1521
1522 return err;
1523 }
1524
1525 mDNSexport kern_return_t provide_DNSServiceRegistrationRemoveRecord_rpc(mach_port_t unusedserver, mach_port_t client,
1526 natural_t reference)
1527 {
1528 // Check client parameter
1529 (void)unusedserver; // Unused
1530 mStatus err = mStatus_NoError;
1531 const char *errormsg = "Unknown";
1532 if (client == (mach_port_t)-1) { err = mStatus_Invalid; errormsg = "Client id -1 invalid"; goto fail; }
1533 DNSServiceRegistration *x = DNSServiceRegistrationList;
1534 ServiceInstance *si;
1535
1536 while (x && x->ClientMachPort != client) x = x->next;
1537 if (!x) { err = mStatus_BadReferenceErr; errormsg = "No such client"; goto fail; }
1538
1539 for (si = x->regs; si; si = si->next)
1540 {
1541 ExtraResourceRecord *e;
1542 for (e = si->srs.Extras; e; e = e->next)
1543 {
1544 if ((natural_t)e->ClientID == reference)
1545 {
1546 err = RemoveRecord(&si->srs, e, client);
1547 break;
1548 }
1549 }
1550 if (!e) { err = mStatus_BadReferenceErr; errormsg = "No such reference"; goto fail; }
1551 }
1552
1553 return mStatus_NoError;
1554
1555 fail:
1556 LogMsg("%5d: DNSServiceRegistrationRemoveRecord(%X) failed: %s (%d)", client, reference, errormsg, err);
1557 return(err);
1558 }
1559
1560 //*************************************************************************************************************
1561 #if COMPILER_LIKES_PRAGMA_MARK
1562 #pragma mark -
1563 #pragma mark - Startup, shutdown, and supporting code
1564 #endif
1565
1566 mDNSlocal void ExitCallback(int sig)
1567 {
1568 (void)sig; // Unused
1569 LogMsg("%s stopping", mDNSResponderVersionString);
1570
1571 debugf("ExitCallback: Aborting MIG clients");
1572 while (DNSServiceDomainEnumerationList)
1573 AbortClient(DNSServiceDomainEnumerationList->ClientMachPort, DNSServiceDomainEnumerationList);
1574 while (DNSServiceBrowserList)
1575 AbortClient(DNSServiceBrowserList->ClientMachPort, DNSServiceBrowserList);
1576 while (DNSServiceResolverList)
1577 AbortClient(DNSServiceResolverList->ClientMachPort, DNSServiceResolverList);
1578 while (DNSServiceRegistrationList)
1579 AbortClient(DNSServiceRegistrationList->ClientMachPort, DNSServiceRegistrationList);
1580
1581 if (udsserver_exit() < 0)
1582 LogMsg("ExitCallback: udsserver_exit failed");
1583
1584 debugf("ExitCallback: mDNS_StartExit");
1585 mDNS_StartExit(&mDNSStorage);
1586 }
1587
1588 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1589
1590 mDNSlocal void DNSserverCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
1591 {
1592 mig_reply_error_t *request = msg;
1593 mig_reply_error_t *reply;
1594 mach_msg_return_t mr;
1595 int options;
1596 (void)port; // Unused
1597 (void)size; // Unused
1598 (void)info; // Unused
1599
1600 KQueueLock(&mDNSStorage);
1601
1602 /* allocate a reply buffer */
1603 reply = CFAllocatorAllocate(NULL, provide_DNSServiceDiscoveryRequest_subsystem.maxsize, 0);
1604
1605 /* call the MiG server routine */
1606 (void) DNSServiceDiscoveryRequest_server(&request->Head, &reply->Head);
1607
1608 if (!(reply->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) && (reply->RetCode != KERN_SUCCESS))
1609 {
1610 if (reply->RetCode == MIG_NO_REPLY)
1611 {
1612 /*
1613 * This return code is a little tricky -- it appears that the
1614 * demux routine found an error of some sort, but since that
1615 * error would not normally get returned either to the local
1616 * user or the remote one, we pretend it's ok.
1617 */
1618 CFAllocatorDeallocate(NULL, reply);
1619 goto done;
1620 }
1621
1622 /*
1623 * destroy any out-of-line data in the request buffer but don't destroy
1624 * the reply port right (since we need that to send an error message).
1625 */
1626 request->Head.msgh_remote_port = MACH_PORT_NULL;
1627 mach_msg_destroy(&request->Head);
1628 }
1629
1630 if (reply->Head.msgh_remote_port == MACH_PORT_NULL)
1631 {
1632 /* no reply port, so destroy the reply */
1633 if (reply->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX)
1634 mach_msg_destroy(&reply->Head);
1635 CFAllocatorDeallocate(NULL, reply);
1636 goto done;
1637 }
1638
1639 /*
1640 * send reply.
1641 *
1642 * We don't want to block indefinitely because the client
1643 * isn't receiving messages from the reply port.
1644 * If we have a send-once right for the reply port, then
1645 * this isn't a concern because the send won't block.
1646 * If we have a send right, we need to use MACH_SEND_TIMEOUT.
1647 * To avoid falling off the kernel's fast RPC path unnecessarily,
1648 * we only supply MACH_SEND_TIMEOUT when absolutely necessary.
1649 */
1650
1651 options = MACH_SEND_MSG;
1652 if (MACH_MSGH_BITS_REMOTE(reply->Head.msgh_bits) == MACH_MSG_TYPE_MOVE_SEND_ONCE)
1653 options |= MACH_SEND_TIMEOUT;
1654
1655 mr = mach_msg(&reply->Head, /* msg */
1656 options, /* option */
1657 reply->Head.msgh_size, /* send_size */
1658 0, /* rcv_size */
1659 MACH_PORT_NULL, /* rcv_name */
1660 MACH_MSG_TIMEOUT_NONE, /* timeout */
1661 MACH_PORT_NULL); /* notify */
1662
1663 /* Has a message error occurred? */
1664 switch (mr)
1665 {
1666 case MACH_SEND_INVALID_DEST:
1667 case MACH_SEND_TIMED_OUT:
1668 /* the reply can't be delivered, so destroy it */
1669 mach_msg_destroy(&reply->Head);
1670 break;
1671
1672 default:
1673 /* Includes success case. */
1674 break;
1675 }
1676
1677 CFAllocatorDeallocate(NULL, reply);
1678
1679 done:
1680 KQueueUnlock(&mDNSStorage, "Mach client event");
1681 }
1682
1683 // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
1684 mDNSlocal void HandleSIG(int sig)
1685 {
1686 kern_return_t status;
1687 mach_msg_header_t header;
1688
1689 // WARNING: can't call syslog or fprintf from signal handler
1690 header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND, 0);
1691 header.msgh_remote_port = signal_port;
1692 header.msgh_local_port = MACH_PORT_NULL;
1693 header.msgh_size = sizeof(header);
1694 header.msgh_id = sig;
1695
1696 status = mach_msg(&header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, header.msgh_size,
1697 0, MACH_PORT_NULL, 0, MACH_PORT_NULL);
1698
1699 if (status != MACH_MSG_SUCCESS)
1700 {
1701 if (status == MACH_SEND_TIMED_OUT) mach_msg_destroy(&header);
1702 if (sig == SIGTERM || sig == SIGINT) exit(-1);
1703 }
1704 }
1705
1706 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1707
1708 mDNSlocal void INFOCallback(void)
1709 {
1710 mDNSs32 utc = mDNSPlatformUTC();
1711 NetworkInterfaceInfoOSX *i;
1712 DNSServer *s;
1713 McastResolver *mr;
1714
1715 // Create LoggerID(Key)->com.apple.networking.mDNSResponder(Value) pair when SIGINFO is received.
1716 // This key-value pair is used as a condition by syslogd to Log to com.apple.networking.mDNSResponder.log file
1717 // present in /etc/asl/com.apple.networking.mDNSResponder.
1718 asl_set(log_msg, "LoggerID", "com.apple.networking.mDNSResponder");
1719
1720 LogMsg("---- BEGIN STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
1721
1722 udsserver_info(&mDNSStorage);
1723 xpcserver_info(&mDNSStorage);
1724
1725 LogMsgNoIdent("----- KQSocketEventSources -----");
1726 if (!gEventSources) LogMsgNoIdent("<None>");
1727 else
1728 {
1729 KQSocketEventSource *k;
1730 for (k = gEventSources; k; k=k->next)
1731 LogMsgNoIdent("%3d %s %s", k->fd, k->kqs.KQtask, k->fd == mDNSStorage.uds_listener_skt ? "Listener for incoming UDS clients" : " ");
1732 }
1733
1734 LogMsgNoIdent("------ Network Interfaces ------");
1735 if (!mDNSStorage.p->InterfaceList) LogMsgNoIdent("<None>");
1736 else
1737 {
1738 for (i = mDNSStorage.p->InterfaceList; i; i = i->next)
1739 {
1740 // Allow six characters for interface name, for names like "vmnet8"
1741 if (!i->Exists)
1742 LogMsgNoIdent("%p %2ld, Registered %p, %s %-6s(%lu) %.6a %.6a %#-14a dormant for %d seconds",
1743 i, i->ifinfo.InterfaceID, i->Registered,
1744 i->sa_family == AF_INET ? "v4" : i->sa_family == AF_INET6 ? "v6" : "??", i->ifinfo.ifname, i->scope_id, &i->ifinfo.MAC, &i->BSSID,
1745 &i->ifinfo.ip, utc - i->LastSeen);
1746 else
1747 {
1748 const CacheRecord *sps[3];
1749 FindSPSInCache(&mDNSStorage, &i->ifinfo.NetWakeBrowse, sps);
1750 LogMsgNoIdent("%p %2ld, Registered %p, %s %-6s(%lu) %.6a %.6a %s %s %-15.4a %s %s %s %s %#a",
1751 i, i->ifinfo.InterfaceID, i->Registered,
1752 i->sa_family == AF_INET ? "v4" : i->sa_family == AF_INET6 ? "v6" : "??", i->ifinfo.ifname, i->scope_id, &i->ifinfo.MAC, &i->BSSID,
1753 i->ifinfo.InterfaceActive ? "Active" : " ",
1754 i->ifinfo.IPv4Available ? "v4" : " ",
1755 i->ifinfo.IPv4Available ? (mDNSv4Addr*)&i->ifa_v4addr : &zerov4Addr,
1756 i->ifinfo.IPv6Available ? "v6" : " ",
1757 i->ifinfo.Advertise ? "A" : " ",
1758 i->ifinfo.McastTxRx ? "M" : " ",
1759 !(i->ifinfo.InterfaceActive && i->ifinfo.NetWake) ? " " : !sps[0] ? "p" : "P",
1760 &i->ifinfo.ip);
1761
1762 if (sps[0]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps[0]->resrec.rdata->u.name.c), sps[0]->resrec.rdata->u.name.c);
1763 if (sps[1]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps[1]->resrec.rdata->u.name.c), sps[1]->resrec.rdata->u.name.c);
1764 if (sps[2]) LogMsgNoIdent(" %13d %#s", SPSMetric(sps[2]->resrec.rdata->u.name.c), sps[2]->resrec.rdata->u.name.c);
1765 }
1766 }
1767 }
1768
1769 LogMsgNoIdent("--------- DNS Servers(%d) ----------", NumUnicastDNSServers);
1770 if (!mDNSStorage.DNSServers) LogMsgNoIdent("<None>");
1771 else
1772 {
1773 for (s = mDNSStorage.DNSServers; s; s = s->next)
1774 {
1775 NetworkInterfaceInfoOSX *ifx = IfindexToInterfaceInfoOSX(&mDNSStorage, s->interface);
1776 LogMsgNoIdent("DNS Server %##s %s%s%#a:%d %d %s %d %d %s %s %s %s %s",
1777 s->domain.c, ifx ? ifx->ifinfo.ifname : "", ifx ? " " : "", &s->addr, mDNSVal16(s->port),
1778 s->penaltyTime ? s->penaltyTime - mDNS_TimeNow(&mDNSStorage) : 0, DNSScopeToString(s->scoped),
1779 s->timeout, s->resGroupID,
1780 s->teststate == DNSServer_Untested ? "(Untested)" :
1781 s->teststate == DNSServer_Passed ? "" :
1782 s->teststate == DNSServer_Failed ? "(Failed)" :
1783 s->teststate == DNSServer_Disabled ? "(Disabled)" : "(Unknown state)",
1784 s->req_A ? "v4" : "!v4",
1785 s->req_AAAA ? "v6" : "!v6",
1786 s->cellIntf ? "cell" : "!cell",
1787 s->DNSSECAware ? "DNSSECAware" : "!DNSSECAware");
1788 }
1789 }
1790 mDNSs32 now = mDNS_TimeNow(&mDNSStorage);
1791 LogMsgNoIdent("v4answers %d", mDNSStorage.p->v4answers);
1792 LogMsgNoIdent("v6answers %d", mDNSStorage.p->v6answers);
1793 LogMsgNoIdent("Last DNS Trigger: %d ms ago", (now - mDNSStorage.p->DNSTrigger));
1794
1795 LogMsgNoIdent("--------- Mcast Resolvers ----------");
1796 if (!mDNSStorage.McastResolvers) LogMsgNoIdent("<None>");
1797 else
1798 {
1799 for (mr = mDNSStorage.McastResolvers; mr; mr = mr->next)
1800 LogMsgNoIdent("Mcast Resolver %##s timeout %u", mr->domain.c, mr->timeout);
1801 }
1802
1803 LogMsgNoIdent("Timenow 0x%08lX (%d)", (mDNSu32)now, now);
1804 LogMsg("---- END STATE LOG ---- %s %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
1805
1806 // If logging is disabled, only then clear the key we set at the top of this func
1807 if (!mDNS_LoggingEnabled)
1808 asl_unset(log_msg, "LoggerID");
1809 }
1810
1811 mDNSlocal void DebugSetFilter()
1812 {
1813 if (!log_client)
1814 return;
1815
1816 // When USR1 is turned on, we log only the LOG_WARNING and LOG_NOTICE messages by default.
1817 // The user has to manually do "syslog -c mDNSResponder -i" to get the LOG_INFO messages
1818 // also to be logged. Most of the times, we need the INFO level messages for debugging.
1819 // Hence, we set the filter to INFO level when USR1 logging is turned on to avoid
1820 // having the user to do this extra step manually.
1821
1822 if (mDNS_LoggingEnabled)
1823 {
1824 asl_set_filter(log_client, ASL_FILTER_MASK_UPTO(ASL_LEVEL_INFO));
1825 asl_set(log_msg, "LoggerID", "com.apple.networking.mDNSResponder");
1826 // Create LoggerID(Key)->com.apple.networking.mDNSResponder(Value) pair when USR1 Logging is Enabled.
1827 // This key-value pair is used as a condition by syslogd to Log to com.apple.networking.mDNSResponder.log file
1828 // present in /etc/asl/com.apple.networking.mDNSResponder.
1829 }
1830 else
1831 {
1832 asl_set_filter(log_client, ASL_FILTER_MASK_UPTO(ASL_LEVEL_ERR));
1833 asl_unset(log_msg, "LoggerID");
1834 // Clear the key-value pair when USR1 Logging is Disabled, as we do not want to log to
1835 // com.apple.networking.mDNSResponder.log file in this case.
1836 }
1837 }
1838
1839 mDNSexport void mDNSPlatformLogToFile(int log_level, const char *buffer)
1840 {
1841 int asl_level = ASL_LEVEL_ERR;
1842
1843 if (!log_client)
1844 {
1845 syslog(log_level, "%s", buffer);
1846 return;
1847 }
1848 switch (log_level)
1849 {
1850 case LOG_ERR:
1851 asl_level = ASL_LEVEL_ERR;
1852 break;
1853 case LOG_WARNING:
1854 asl_level = ASL_LEVEL_WARNING;
1855 break;
1856 case LOG_NOTICE:
1857 asl_level = ASL_LEVEL_NOTICE;
1858 break;
1859 case LOG_INFO:
1860 asl_level = ASL_LEVEL_INFO;
1861 break;
1862 case LOG_DEBUG:
1863 asl_level = ASL_LEVEL_DEBUG;
1864 break;
1865 default:
1866 break;
1867 }
1868 asl_log(log_client, log_msg, asl_level, "%s", buffer);
1869 }
1870
1871 // Writes the state out to the dynamic store and also affects the ASL filter level
1872 mDNSexport void UpdateDebugState()
1873 {
1874 mDNSu32 one = 1;
1875 mDNSu32 zero = 0;
1876
1877 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1878 if (!dict)
1879 {
1880 LogMsg("UpdateDebugState: Could not create dict");
1881 return;
1882 }
1883
1884 CFNumberRef numOne = CFNumberCreate(NULL, kCFNumberSInt32Type, &one);
1885 if (!numOne)
1886 {
1887 LogMsg("UpdateDebugState: Could not create CFNumber one");
1888 return;
1889 }
1890 CFNumberRef numZero = CFNumberCreate(NULL, kCFNumberSInt32Type, &zero);
1891 if (!numZero)
1892 {
1893 LogMsg("UpdateDebugState: Could not create CFNumber zero");
1894 CFRelease(numOne);
1895 return;
1896 }
1897
1898 if (mDNS_LoggingEnabled)
1899 CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numOne);
1900 else
1901 CFDictionarySetValue(dict, CFSTR("VerboseLogging"), numZero);
1902
1903 if (mDNS_PacketLoggingEnabled)
1904 CFDictionarySetValue(dict, CFSTR("PacketLogging"), numOne);
1905 else
1906 CFDictionarySetValue(dict, CFSTR("PacketLogging"), numZero);
1907
1908 if (mDNS_McastLoggingEnabled)
1909 CFDictionarySetValue(dict, CFSTR("McastLogging"), numOne);
1910 else
1911 CFDictionarySetValue(dict, CFSTR("McastLogging"), numZero);
1912
1913 if (mDNS_McastTracingEnabled)
1914 CFDictionarySetValue(dict, CFSTR("McastTracing"), numOne);
1915 else
1916 CFDictionarySetValue(dict, CFSTR("McastTracing"), numZero);
1917
1918 CFRelease(numOne);
1919 CFRelease(numZero);
1920 mDNSDynamicStoreSetConfig(kmDNSDebugState, mDNSNULL, dict);
1921 CFRelease(dict);
1922 // If we turned off USR1 logging, we need to reset the filter
1923 DebugSetFilter();
1924 }
1925
1926 #if TARGET_OS_EMBEDDED
1927 mDNSlocal void Prefschanged()
1928 {
1929 mDNSBool mDNSProf_installed;
1930 LogMsg("Prefschanged: mDNSResponder Managed Preferences have changed");
1931 mDNSProf_installed = GetmDNSManagedPref(kmDNSEnableLoggingStr);
1932 dispatch_async(dispatch_get_main_queue(),
1933 ^{
1934 if (mDNSProf_installed)
1935 {
1936 mDNS_LoggingEnabled = mDNS_PacketLoggingEnabled = 1;
1937 }
1938 else
1939 {
1940 LogMsg("Prefschanged: mDNSDebugProfile is uninstalled -> Turning OFF USR1/USR2 Logging with SIGINFO o/p");
1941 INFOCallback();
1942 mDNS_LoggingEnabled = mDNS_PacketLoggingEnabled = 0;
1943 }
1944 UpdateDebugState();
1945 // If Logging Enabled: Start Logging to com.apple.networking.mDNSResponder.log (has to be LogInfo)
1946 LogInfo("Prefschanged: mDNSDebugProfile is installed -> Turned ON USR1/USR2 Logging");
1947 });
1948 return;
1949 }
1950 #endif //TARGET_OS_EMBEDDED
1951
1952 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
1953
1954 mDNSlocal void SignalCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
1955 {
1956 (void)port; // Unused
1957 (void)size; // Unused
1958 (void)info; // Unused
1959 mach_msg_header_t *msg_header = (mach_msg_header_t *)msg;
1960 mDNS *const m = &mDNSStorage;
1961
1962 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
1963 KQueueLock(m);
1964 switch(msg_header->msgh_id)
1965 {
1966 case SIGURG:
1967 m->mDNSOppCaching = m->mDNSOppCaching ? mDNSfalse : mDNStrue;
1968 LogMsg("SIGURG: Opportunistic Caching %s", m->mDNSOppCaching ? "Enabled" : "Disabled");
1969 // FALL THROUGH to purge the cache so that we re-do the caching based on the new setting
1970 case SIGHUP: {
1971 mDNSu32 slot;
1972 CacheGroup *cg;
1973 CacheRecord *rr;
1974 LogMsg("SIGHUP: Purge cache");
1975 mDNS_Lock(m);
1976 FORALL_CACHERECORDS(slot, cg, rr)
1977 {
1978 mDNS_PurgeCacheResourceRecord(m, rr);
1979 }
1980 // Restart unicast and multicast queries
1981 mDNSCoreRestartQueries(m);
1982 mDNS_Unlock(m);
1983 } break;
1984 case SIGINT:
1985 case SIGTERM: ExitCallback(msg_header->msgh_id); break;
1986 case SIGINFO: INFOCallback(); break;
1987 case SIGUSR1: mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
1988 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
1989 WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250;
1990 UpdateDebugState();
1991 // If Logging Enabled: Start Logging to com.apple.networking.mDNSResponder.log
1992 LogInfo("USR1 Logging Enabled: Start Logging to mDNSResponder Log file");
1993 break;
1994 case SIGUSR2: mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
1995 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
1996 mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse;
1997 LogInfo("SIGUSR2: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
1998 UpdateDebugState();
1999 break;
2000 case SIGPROF: mDNS_McastLoggingEnabled = mDNS_McastLoggingEnabled ? mDNSfalse : mDNStrue;
2001 LogMsg("SIGPROF: Multicast Logging %s", mDNS_McastLoggingEnabled ? "Enabled" : "Disabled");
2002 LogMcastStateInfo(m, mDNSfalse, mDNStrue, mDNStrue);
2003 mDNS_McastTracingEnabled = (mDNS_PacketLoggingEnabled && mDNS_McastLoggingEnabled) ? mDNStrue : mDNSfalse;
2004 LogMsg("SIGPROF: Multicast Tracing is %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
2005 UpdateDebugState();
2006 break;
2007 case SIGTSTP: mDNS_LoggingEnabled = mDNS_PacketLoggingEnabled = mDNS_McastLoggingEnabled = mDNS_McastTracingEnabled = mDNSfalse;
2008 LogMsg("All mDNSResponder Debug Logging/Tracing Disabled (USR1/USR2/PROF)");
2009 UpdateDebugState();
2010 break;
2011
2012 default: LogMsg("SignalCallback: Unknown signal %d", msg_header->msgh_id); break;
2013 }
2014 KQueueUnlock(m, "Unix Signal");
2015 }
2016
2017 // MachServerName is com.apple.mDNSResponder (Supported only till 10.9.x)
2018 mDNSlocal kern_return_t mDNSDaemonInitialize(void)
2019 {
2020 mStatus err;
2021 CFMachPortRef s_port;
2022 CFRunLoopSourceRef s_rls;
2023 CFRunLoopSourceRef d_rls;
2024
2025 s_port = CFMachPortCreateWithPort(NULL, m_port, DNSserverCallback, NULL, NULL);
2026 CFMachPortRef d_port = CFMachPortCreate(NULL, ClientDeathCallback, NULL, NULL);
2027
2028 err = mDNS_Init(&mDNSStorage, &PlatformStorage,
2029 rrcachestorage, RR_CACHE_SIZE,
2030 advertise,
2031 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
2032
2033 if (err) { LogMsg("Daemon start: mDNS_Init failed %d", err); return(err); }
2034
2035 client_death_port = CFMachPortGetPort(d_port);
2036
2037 s_rls = CFMachPortCreateRunLoopSource(NULL, s_port, 0);
2038 CFRunLoopAddSource(PlatformStorage.CFRunLoop, s_rls, kCFRunLoopDefaultMode);
2039 CFRelease(s_rls);
2040
2041 d_rls = CFMachPortCreateRunLoopSource(NULL, d_port, 0);
2042 CFRunLoopAddSource(PlatformStorage.CFRunLoop, d_rls, kCFRunLoopDefaultMode);
2043 CFRelease(d_rls);
2044
2045 CFMachPortRef i_port = CFMachPortCreate(NULL, SignalCallback, NULL, NULL);
2046 CFRunLoopSourceRef i_rls = CFMachPortCreateRunLoopSource(NULL, i_port, 0);
2047 signal_port = CFMachPortGetPort(i_port);
2048 CFRunLoopAddSource(PlatformStorage.CFRunLoop, i_rls, kCFRunLoopDefaultMode);
2049 CFRelease(i_rls);
2050
2051 if (mDNS_DebugMode) printf("Service registered with Mach Port %d\n", m_port);
2052 return(err);
2053 }
2054
2055 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2056
2057 // SignalDispatch is mostly just a copy/paste of entire code block from SignalCallback above.
2058 // The common code should be a subroutine, or we end up having to fix bugs in two places all the time.
2059 // The same applies to mDNSDaemonInitialize, much of which is just a copy/paste of chunks
2060 // of code from above. Alternatively we could remove the duplicated source code by having
2061 // single routines, with the few differing parts bracketed with "#ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM"
2062
2063 mDNSlocal void SignalDispatch(dispatch_source_t source)
2064 {
2065 int sig = (int)dispatch_source_get_handle(source);
2066 mDNS *const m = &mDNSStorage;
2067 KQueueLock(m);
2068 switch(sig)
2069 {
2070 case SIGHUP: {
2071 mDNSu32 slot;
2072 CacheGroup *cg;
2073 CacheRecord *rr;
2074 LogMsg("SIGHUP: Purge cache");
2075 mDNS_Lock(m);
2076 FORALL_CACHERECORDS(slot, cg, rr)
2077 {
2078 mDNS_PurgeCacheResourceRecord(m, rr);
2079 }
2080 // Restart unicast and multicast queries
2081 mDNSCoreRestartQueries(m);
2082 mDNS_Unlock(m);
2083 } break;
2084 case SIGINT:
2085 case SIGTERM: ExitCallback(sig); break;
2086 case SIGINFO: INFOCallback(); break;
2087 case SIGUSR1: mDNS_LoggingEnabled = mDNS_LoggingEnabled ? 0 : 1;
2088 LogMsg("SIGUSR1: Logging %s", mDNS_LoggingEnabled ? "Enabled" : "Disabled");
2089 WatchDogReportingThreshold = mDNS_LoggingEnabled ? 50 : 250;
2090 UpdateDebugState();
2091 break;
2092 case SIGUSR2: mDNS_PacketLoggingEnabled = mDNS_PacketLoggingEnabled ? 0 : 1;
2093 LogMsg("SIGUSR2: Packet Logging %s", mDNS_PacketLoggingEnabled ? "Enabled" : "Disabled");
2094 UpdateDebugState();
2095 break;
2096 default: LogMsg("SignalCallback: Unknown signal %d", sig); break;
2097 }
2098 KQueueUnlock(m, "Unix Signal");
2099 }
2100
2101 mDNSlocal void mDNSSetupSignal(dispatch_queue_t queue, int sig)
2102 {
2103 signal(sig, SIG_IGN);
2104 dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, sig, 0, queue);
2105
2106 if (source)
2107 {
2108 dispatch_source_set_event_handler(source, ^{SignalDispatch(source);});
2109 // Start processing signals
2110 dispatch_resume(source);
2111 }
2112 else
2113 {
2114 LogMsg("mDNSSetupSignal: Cannot setup signal %d", sig);
2115 }
2116 }
2117
2118 // On 10.2 the MachServerName is DNSServiceDiscoveryServer
2119 // On 10.3 and later, the MachServerName is com.apple.mDNSResponder
2120 mDNSlocal kern_return_t mDNSDaemonInitialize(void)
2121 {
2122 mStatus err;
2123 dispatch_source_t mach_source;
2124 dispatch_queue_t queue = dispatch_get_main_queue();
2125
2126 err = mDNS_Init(&mDNSStorage, &PlatformStorage,
2127 rrcachestorage, RR_CACHE_SIZE,
2128 advertise,
2129 mDNS_StatusCallback, mDNS_Init_NoInitCallbackContext);
2130
2131 if (err) { LogMsg("Daemon start: mDNS_Init failed %d", err); return(err); }
2132
2133 mach_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, m_port, 0, queue);
2134 if (mach_source == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating source for m_port"); return -1;}
2135 dispatch_source_set_event_handler(mach_source, ^{
2136 dispatch_mig_server(mach_source, sizeof(union __RequestUnion__DNSServiceDiscoveryReply_subsystem),
2137 DNSServiceDiscoveryRequest_server);
2138 });
2139 dispatch_resume(mach_source);
2140
2141 mDNSSetupSignal(queue, SIGHUP);
2142 mDNSSetupSignal(queue, SIGINT);
2143 mDNSSetupSignal(queue, SIGTERM);
2144 mDNSSetupSignal(queue, SIGINFO);
2145 mDNSSetupSignal(queue, SIGUSR1);
2146 mDNSSetupSignal(queue, SIGUSR2);
2147 mDNSSetupSignal(queue, SIGURG);
2148
2149 // Create a custom handler for doing the housekeeping work. This is either triggered
2150 // by the timer or an event source
2151 PlatformStorage.custom = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, queue);
2152 if (PlatformStorage.custom == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating custom source"); return -1;}
2153 dispatch_source_set_event_handler(PlatformStorage.custom, ^{PrepareForIdle(&mDNSStorage);});
2154 dispatch_resume(PlatformStorage.custom);
2155
2156 // Create a timer source to trigger housekeeping work. The houskeeping work itself
2157 // is done in the custom handler that we set below.
2158
2159 PlatformStorage.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
2160 if (PlatformStorage.timer == mDNSNULL) {LogMsg("mDNSDaemonInitialize: Error creating timer source"); return -1;}
2161
2162 // As the API does not support one shot timers, we pass zero for the interval. In the custom handler, we
2163 // always reset the time to the new time computed. In effect, we ignore the interval
2164 dispatch_source_set_timer(PlatformStorage.timer, DISPATCH_TIME_NOW, 1000ull * 1000000000, 0);
2165 dispatch_source_set_event_handler(PlatformStorage.timer, ^{
2166 dispatch_source_merge_data(PlatformStorage.custom, 1);
2167 });
2168 dispatch_resume(PlatformStorage.timer);
2169
2170 LogMsg("DaemonIntialize done successfully");
2171
2172 if (mDNS_DebugMode) printf("Service registered with Mach Port %d\n", m_port);
2173 return(err);
2174 }
2175
2176 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2177
2178 mDNSlocal mDNSs32 mDNSDaemonIdle(mDNS *const m)
2179 {
2180 mDNSs32 now = mDNS_TimeNow(m);
2181
2182 // 1. If we need to set domain secrets, do so before handling the network change
2183 // Detailed reason:
2184 // BTMM domains listed in DynStore Setup:/Network/BackToMyMac are added to the registration domains list,
2185 // and we need to setup the associated AutoTunnel DomainAuthInfo entries before that happens.
2186 if (m->p->KeyChainTimer && now - m->p->KeyChainTimer >= 0)
2187 {
2188 m->p->KeyChainTimer = 0;
2189 mDNS_Lock(m);
2190 SetDomainSecrets(m);
2191 mDNS_Unlock(m);
2192 }
2193
2194 // 2. If we have network change events to handle, do them before calling mDNS_Execute()
2195 // Detailed reason:
2196 // mDNSMacOSXNetworkChanged() currently closes and re-opens its sockets. If there are received packets waiting, they are lost.
2197 // mDNS_Execute() generates packets, including multicasts that are looped back to ourself.
2198 // If we call mDNS_Execute() first, and generate packets, and then call mDNSMacOSXNetworkChanged() immediately afterwards
2199 // we then systematically lose our own looped-back packets.
2200 if (m->p->NetworkChanged && now - m->p->NetworkChanged >= 0) mDNSMacOSXNetworkChanged(m);
2201
2202 if (m->p->RequestReSleep && now - m->p->RequestReSleep >= 0) { m->p->RequestReSleep = 0; mDNSPowerRequest(0, 0); }
2203
2204 // 3. Call mDNS_Execute() to let mDNSCore do what it needs to do
2205 mDNSs32 nextevent = mDNS_Execute(m);
2206
2207 if (m->p->NetworkChanged)
2208 if (nextevent - m->p->NetworkChanged > 0)
2209 nextevent = m->p->NetworkChanged;
2210
2211 if (m->p->KeyChainTimer)
2212 if (nextevent - m->p->KeyChainTimer > 0)
2213 nextevent = m->p->KeyChainTimer;
2214
2215 if (m->p->RequestReSleep)
2216 if (nextevent - m->p->RequestReSleep > 0)
2217 nextevent = m->p->RequestReSleep;
2218
2219 // 4. Deliver any waiting browse messages to clients
2220 DNSServiceBrowser *b = DNSServiceBrowserList;
2221
2222 while (b)
2223 {
2224 // Note: Need to advance b to the next element BEFORE we call DeliverInstance(), because in the
2225 // event that the client Mach queue overflows, DeliverInstance() will call AbortBlockedClient()
2226 // and that will cause the DNSServiceBrowser object's memory to be freed before it returns
2227 DNSServiceBrowser *x = b;
2228 b = b->next;
2229 if (x->results) // Try to deliver the list of results
2230 {
2231 while (x->results)
2232 {
2233 DNSServiceBrowserResult *const r = x->results;
2234 domainlabel name;
2235 domainname type, domain;
2236 DeconstructServiceName(&r->result, &name, &type, &domain); // Don't need to check result; already validated in FoundInstance()
2237 char cname[MAX_DOMAIN_LABEL+1]; // Unescaped name: up to 63 bytes plus C-string terminating NULL.
2238 char ctype[MAX_ESCAPED_DOMAIN_NAME];
2239 char cdom [MAX_ESCAPED_DOMAIN_NAME];
2240 ConvertDomainLabelToCString_unescaped(&name, cname);
2241 ConvertDomainNameToCString(&type, ctype);
2242 ConvertDomainNameToCString(&domain, cdom);
2243 DNSServiceDiscoveryReplyFlags flags = (r->next) ? DNSServiceDiscoverReplyFlagsMoreComing : 0;
2244 kern_return_t status = DNSServiceBrowserReply_rpc(x->ClientMachPort, r->resultType, cname, ctype, cdom, flags, 1);
2245 // If we failed to send the mach message, try again in one second
2246 if (status == MACH_SEND_TIMED_OUT)
2247 {
2248 if (nextevent - now > mDNSPlatformOneSecond)
2249 nextevent = now + mDNSPlatformOneSecond;
2250 break;
2251 }
2252 else
2253 {
2254 x->lastsuccess = now;
2255 x->results = x->results->next;
2256 freeL("DNSServiceBrowserResult", r);
2257 }
2258 }
2259 // If this client hasn't read a single message in the last 60 seconds, abort it
2260 if (now - x->lastsuccess >= 60 * mDNSPlatformOneSecond)
2261 AbortBlockedClient(x->ClientMachPort, "browse", x);
2262 }
2263 }
2264
2265 DNSServiceResolver *l;
2266 for (l = DNSServiceResolverList; l; l=l->next)
2267 if (l->ReportTime && now - l->ReportTime >= 0)
2268 {
2269 l->ReportTime = 0;
2270 LogMsgNoIdent("Client application bug: DNSServiceResolver(%##s) active for over two minutes. "
2271 "This places considerable burden on the network.", l->i.name.c);
2272 }
2273
2274 if (m->p->NotifyUser)
2275 {
2276 if (m->p->NotifyUser - now < 0)
2277 {
2278 if (!SameDomainLabelCS(m->p->usernicelabel.c, m->nicelabel.c))
2279 {
2280 LogMsg("Name Conflict: Updated Computer Name from \"%#s\" to \"%#s\"", m->p->usernicelabel.c, m->nicelabel.c);
2281 mDNSPreferencesSetNames(m, kmDNSComputerName, &m->p->usernicelabel, &m->nicelabel);
2282 m->p->usernicelabel = m->nicelabel;
2283 }
2284 if (!SameDomainLabelCS(m->p->userhostlabel.c, m->hostlabel.c))
2285 {
2286 LogMsg("Name Conflict: Updated Local Hostname from \"%#s.local\" to \"%#s.local\"", m->p->userhostlabel.c, m->hostlabel.c);
2287 mDNSPreferencesSetNames(m, kmDNSLocalHostName, &m->p->userhostlabel, &m->hostlabel);
2288 m->p->HostNameConflict = 0; // Clear our indicator, now name change has been successful
2289 m->p->userhostlabel = m->hostlabel;
2290 }
2291 m->p->NotifyUser = 0;
2292 }
2293 else
2294 if (nextevent - m->p->NotifyUser > 0)
2295 nextevent = m->p->NotifyUser;
2296 }
2297
2298 return(nextevent);
2299 }
2300
2301 // Right now we consider *ALL* of our DHCP leases
2302 // It might make sense to be a bit more selective and only consider the leases on interfaces
2303 // (a) that are capable and enabled for wake-on-LAN, and
2304 // (b) where we have found (and successfully registered with) a Sleep Proxy
2305 // If we can't be woken for traffic on a given interface, then why keep waking to renew its lease?
2306 mDNSlocal mDNSu32 DHCPWakeTime(void)
2307 {
2308 mDNSu32 e = 24 * 3600; // Maximum maintenance wake interval is 24 hours
2309 const CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
2310 if (!now) LogMsg("DHCPWakeTime: CFAbsoluteTimeGetCurrent failed");
2311 else
2312 {
2313 int ic, j;
2314
2315 const void *pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetDHCP);
2316 if (!pattern)
2317 {
2318 LogMsg("DHCPWakeTime: SCDynamicStoreKeyCreateNetworkServiceEntity failed\n");
2319 return e;
2320 }
2321 CFArrayRef dhcpinfo = CFArrayCreate(NULL, (const void **)&pattern, 1, &kCFTypeArrayCallBacks);
2322 CFRelease(pattern);
2323 if (dhcpinfo)
2324 {
2325 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("DHCP-LEASES"), NULL, NULL);
2326 if (store)
2327 {
2328 CFDictionaryRef dict = SCDynamicStoreCopyMultiple(store, NULL, dhcpinfo);
2329 if (dict)
2330 {
2331 ic = CFDictionaryGetCount(dict);
2332 const void *vals[ic];
2333 CFDictionaryGetKeysAndValues(dict, NULL, vals);
2334
2335 for (j = 0; j < ic; j++)
2336 {
2337 const CFDictionaryRef dhcp = (CFDictionaryRef)vals[j];
2338 if (dhcp)
2339 {
2340 const CFDateRef start = DHCPInfoGetLeaseStartTime(dhcp);
2341 const CFDataRef lease = DHCPInfoGetOptionData(dhcp, 51); // Option 51 = IP Address Lease Time
2342 if (!start || !lease || CFDataGetLength(lease) < 4)
2343 LogMsg("DHCPWakeTime: SCDynamicStoreCopyDHCPInfo index %d failed "
2344 "CFDateRef start %p CFDataRef lease %p CFDataGetLength(lease) %d",
2345 j, start, lease, lease ? CFDataGetLength(lease) : 0);
2346 else
2347 {
2348 const UInt8 *d = CFDataGetBytePtr(lease);
2349 if (!d) LogMsg("DHCPWakeTime: CFDataGetBytePtr %d failed", j);
2350 else
2351 {
2352 const mDNSu32 elapsed = now - CFDateGetAbsoluteTime(start);
2353 const mDNSu32 lifetime = (mDNSs32) ((mDNSs32)d[0] << 24 | (mDNSs32)d[1] << 16 | (mDNSs32)d[2] << 8 | d[3]);
2354 const mDNSu32 remaining = lifetime - elapsed;
2355 const mDNSu32 wake = remaining > 60 ? remaining - remaining/10 : 54; // Wake at 90% of the lease time
2356 LogSPS("DHCP Address Lease Elapsed %6u Lifetime %6u Remaining %6u Wake %6u", elapsed, lifetime, remaining, wake);
2357 if (e > wake) e = wake;
2358 }
2359 }
2360 }
2361 }
2362 CFRelease(dict);
2363 }
2364 CFRelease(store);
2365 }
2366 CFRelease(dhcpinfo);
2367 }
2368 }
2369 return(e);
2370 }
2371
2372 // We deliberately schedule our wakeup for halfway between when we'd *like* it and when we *need* it.
2373 // For example, if our DHCP lease expires in two hours, we'll typically renew it at the halfway point, after one hour.
2374 // If we scheduled our wakeup for the one-hour renewal time, that might be just seconds from now, and sleeping
2375 // for a few seconds and then waking again is silly and annoying.
2376 // If we scheduled our wakeup for the two-hour expiry time, and we were slow to wake, we might lose our lease.
2377 // Scheduling our wakeup for halfway in between -- 90 minutes -- avoids short wakeups while still
2378 // allowing us an adequate safety margin to renew our lease before we lose it.
2379
2380 mDNSlocal mDNSBool AllowSleepNow(mDNS *const m, mDNSs32 now)
2381 {
2382 mDNSBool ready = mDNSCoreReadyForSleep(m, now);
2383 if (m->SleepState && !ready && now - m->SleepLimit < 0) return(mDNSfalse);
2384
2385 m->p->WakeAtUTC = 0;
2386 int result = kIOReturnSuccess;
2387 CFDictionaryRef opts = NULL;
2388
2389 // If the sleep request was cancelled, and we're no longer planning to sleep, don't need to
2390 // do the stuff below, but we *DO* still need to acknowledge the sleep message we received.
2391 if (!m->SleepState)
2392 LogMsg("AllowSleepNow: Sleep request was canceled with %d ticks remaining", m->SleepLimit - now);
2393 else
2394 {
2395 if (!m->SystemWakeOnLANEnabled || !mDNSCoreHaveAdvertisedMulticastServices(m))
2396 LogSPS("AllowSleepNow: Not scheduling wakeup: SystemWakeOnLAN %s enabled; %s advertised services",
2397 m->SystemWakeOnLANEnabled ? "is" : "not",
2398 mDNSCoreHaveAdvertisedMulticastServices(m) ? "have" : "no");
2399 else
2400 {
2401 mDNSs32 dhcp = DHCPWakeTime();
2402 LogSPS("ComputeWakeTime: DHCP Wake %d", dhcp);
2403 mDNSs32 interval = mDNSCoreIntervalToNextWake(m, now) / mDNSPlatformOneSecond;
2404 if (interval > dhcp) interval = dhcp;
2405
2406 // If we're not ready to sleep (failed to register with Sleep Proxy, maybe because of
2407 // transient network problem) then schedule a wakeup in one hour to try again. Otherwise,
2408 // a single SPS failure could result in a remote machine falling permanently asleep, requiring
2409 // someone to go to the machine in person to wake it up again, which would be unacceptable.
2410 if (!ready && interval > 3600) interval = 3600;
2411
2412 //interval = 48; // For testing
2413
2414 #ifdef kIOPMAcknowledgmentOptionSystemCapabilityRequirements
2415 if (m->p->IOPMConnection) // If lightweight-wake capability is available, use that
2416 {
2417 const CFDateRef WakeDate = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent() + interval);
2418 if (!WakeDate) LogMsg("ScheduleNextWake: CFDateCreate failed");
2419 else
2420 {
2421 const mDNSs32 reqs = kIOPMSystemPowerStateCapabilityNetwork;
2422 const CFNumberRef Requirements = CFNumberCreate(NULL, kCFNumberSInt32Type, &reqs);
2423 if (!Requirements) LogMsg("ScheduleNextWake: CFNumberCreate failed");
2424 else
2425 {
2426 const void *OptionKeys[2] = { CFSTR("WakeDate"), CFSTR("Requirements") };
2427 const void *OptionVals[2] = { WakeDate, Requirements };
2428 opts = CFDictionaryCreate(NULL, (void*)OptionKeys, (void*)OptionVals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
2429 if (!opts) LogMsg("ScheduleNextWake: CFDictionaryCreate failed");
2430 CFRelease(Requirements);
2431 }
2432 CFRelease(WakeDate);
2433 }
2434 LogSPS("AllowSleepNow: Will request lightweight wakeup in %d seconds", interval);
2435 }
2436 else // else schedule the wakeup using the old API instead to
2437 #endif
2438 {
2439 // If we wake within +/- 30 seconds of our requested time we'll assume the system woke for us,
2440 // so we should put it back to sleep. To avoid frustrating the user, we always request at least
2441 // 60 seconds sleep, so if they immediately re-wake the system within seconds of it going to sleep,
2442 // we then shouldn't hit our 30-second window, and we won't attempt to re-sleep the machine.
2443 if (interval < 60) interval = 60;
2444
2445 result = mDNSPowerRequest(1, interval);
2446
2447 if (result == kIOReturnNotReady)
2448 {
2449 int r;
2450 LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful; retrying with longer intervals", interval);
2451 // IOPMSchedulePowerEvent fails with kIOReturnNotReady (-536870184/0xe00002d8) if the
2452 // requested wake time is "too soon", but there's no API to find out what constitutes
2453 // "too soon" on any given OS/hardware combination, so if we get kIOReturnNotReady
2454 // we just have to iterate with successively longer intervals until it doesn't fail.
2455 // We preserve the value of "result" because if our original power request was deemed "too soon"
2456 // for the machine to get to sleep and wake back up again, we attempt to cancel the sleep request,
2457 // since the implication is that the system won't manage to be awake again at the time we need it.
2458 do
2459 {
2460 interval += (interval < 20) ? 1 : ((interval+3) / 4);
2461 r = mDNSPowerRequest(1, interval);
2462 }
2463 while (r == kIOReturnNotReady);
2464 if (r) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval, r, r);
2465 else LogSPS("AllowSleepNow: Requested later wakeup in %d seconds; will also attempt IOCancelPowerChange", interval);
2466 }
2467 else
2468 {
2469 if (result) LogMsg("AllowSleepNow: Requested wakeup in %d seconds unsuccessful: %d %X", interval, result, result);
2470 else LogSPS("AllowSleepNow: Requested wakeup in %d seconds", interval);
2471 }
2472 m->p->WakeAtUTC = mDNSPlatformUTC() + interval;
2473 }
2474 }
2475
2476 m->SleepState = SleepState_Sleeping;
2477 // We used to clear our interface list to empty state here before going to sleep.
2478 // The applications that try to connect to an external server during maintenance wakes, saw
2479 // DNS resolution errors as we don't have any interfaces (most queries use SuppressUnusable
2480 // flag). Thus, we don't remove our interfaces anymore on sleep.
2481 }
2482
2483 LogSPS("AllowSleepNow: %s(%lX) %s at %ld (%d ticks remaining)",
2484 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
2485 (m->p->IOPMConnection) ? "IOPMConnectionAcknowledgeEventWithOptions" :
2486 #endif
2487 (result == kIOReturnSuccess) ? "IOAllowPowerChange" : "IOCancelPowerChange",
2488 m->p->SleepCookie, ready ? "ready for sleep" : "giving up", now, m->SleepLimit - now);
2489
2490 m->SleepLimit = 0; // Don't clear m->SleepLimit until after we've logged it above
2491 m->TimeSlept = mDNSPlatformUTC();
2492
2493 // accumulate total time awake for this statistics gathering interval
2494 if (m->StatStartTime)
2495 {
2496 m->ActiveStatTime += (m->TimeSlept - m->StatStartTime);
2497
2498 // indicate this value is invalid until reinitialzed on wakeup
2499 m->StatStartTime = 0;
2500 }
2501
2502 #if !TARGET_OS_EMBEDDED && defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements)
2503 if (m->p->IOPMConnection) IOPMConnectionAcknowledgeEventWithOptions(m->p->IOPMConnection, m->p->SleepCookie, opts);
2504 else
2505 #endif
2506 if (result == kIOReturnSuccess) IOAllowPowerChange (m->p->PowerConnection, m->p->SleepCookie);
2507 else IOCancelPowerChange(m->p->PowerConnection, m->p->SleepCookie);
2508
2509 if (opts) CFRelease(opts);
2510 return(mDNStrue);
2511 }
2512
2513 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2514
2515 mDNSexport void TriggerEventCompletion()
2516 {
2517 debugf("TriggerEventCompletion: Merge data");
2518 dispatch_source_merge_data(PlatformStorage.custom, 1);
2519 }
2520
2521 mDNSlocal void PrepareForIdle(void *m_param)
2522 {
2523 mDNS *m = m_param;
2524 int64_t time_offset;
2525 dispatch_time_t dtime;
2526
2527 const int multiplier = 1000000000 / mDNSPlatformOneSecond;
2528
2529 // This is the main work loop:
2530 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
2531 // (2) Then we make sure we've delivered all waiting browse messages to our clients
2532 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
2533
2534 debugf("PrepareForIdle: called");
2535 // Run mDNS_Execute to find out the time we next need to wake up
2536 mDNSs32 start = mDNSPlatformRawTime();
2537 mDNSs32 nextTimerEvent = udsserver_idle(mDNSDaemonIdle(m));
2538 mDNSs32 end = mDNSPlatformRawTime();
2539 if (end - start >= WatchDogReportingThreshold)
2540 LogInfo("CustomSourceHandler:WARNING: Idle task took %dms to complete", end - start);
2541
2542 mDNSs32 now = mDNS_TimeNow(m);
2543
2544 if (m->ShutdownTime)
2545 {
2546 if (mDNSStorage.ResourceRecords)
2547 {
2548 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m, mDNSStorage.ResourceRecords));
2549 if (mDNS_LoggingEnabled) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
2550 }
2551 if (mDNS_ExitNow(m, now))
2552 {
2553 LogInfo("IdleLoop: mDNS_FinalExit");
2554 mDNS_FinalExit(&mDNSStorage);
2555 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
2556 exit(0);
2557 }
2558 if (nextTimerEvent - m->ShutdownTime >= 0)
2559 nextTimerEvent = m->ShutdownTime;
2560 }
2561
2562 if (m->SleepLimit)
2563 if (!AllowSleepNow(m, now))
2564 if (nextTimerEvent - m->SleepLimit >= 0)
2565 nextTimerEvent = m->SleepLimit;
2566
2567 // Convert absolute wakeup time to a relative time from now
2568 mDNSs32 ticks = nextTimerEvent - now;
2569 if (ticks < 1) ticks = 1;
2570
2571 static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins
2572 if (ticks > 1)
2573 RepeatedBusy = 0;
2574 else
2575 {
2576 ticks = 1;
2577 if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
2578 }
2579
2580 time_offset = ((mDNSu32)ticks / mDNSPlatformOneSecond) * 1000000000 + (ticks % mDNSPlatformOneSecond) * multiplier;
2581 dtime = dispatch_time(DISPATCH_TIME_NOW, time_offset);
2582 dispatch_source_set_timer(PlatformStorage.timer, dtime, 1000ull*1000000000, 0);
2583 debugf("PrepareForIdle: scheduling timer with ticks %d", ticks);
2584 return;
2585 }
2586
2587 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2588
2589 mDNSlocal void KQWokenFlushBytes(int fd, __unused short filter, __unused void *context)
2590 {
2591 // Read all of the bytes so we won't wake again.
2592 char buffer[100];
2593 while (recv(fd, buffer, sizeof(buffer), MSG_DONTWAIT) > 0) continue;
2594 }
2595
2596 mDNSlocal void SetLowWater(const KQSocketSet *const k, const int r)
2597 {
2598 if (setsockopt(k->sktv4, SOL_SOCKET, SO_RCVLOWAT, &r, sizeof(r)) < 0)
2599 LogMsg("SO_RCVLOWAT IPv4 %d error %d errno %d (%s)", k->sktv4, r, errno, strerror(errno));
2600 if (setsockopt(k->sktv6, SOL_SOCKET, SO_RCVLOWAT, &r, sizeof(r)) < 0)
2601 LogMsg("SO_RCVLOWAT IPv6 %d error %d errno %d (%s)", k->sktv6, r, errno, strerror(errno));
2602 }
2603
2604 mDNSlocal void * KQueueLoop(void *m_param)
2605 {
2606 mDNS *m = m_param;
2607 int numevents = 0;
2608
2609 #if USE_SELECT_WITH_KQUEUEFD
2610 fd_set readfds;
2611 FD_ZERO(&readfds);
2612 const int multiplier = 1000000 / mDNSPlatformOneSecond;
2613 #else
2614 const int multiplier = 1000000000 / mDNSPlatformOneSecond;
2615 #endif
2616
2617 pthread_mutex_lock(&PlatformStorage.BigMutex);
2618 LogInfo("Starting time value 0x%08lX (%ld)", (mDNSu32)mDNSStorage.timenow_last, mDNSStorage.timenow_last);
2619
2620 // This is the main work loop:
2621 // (1) First we give mDNSCore a chance to finish off any of its deferred work and calculate the next sleep time
2622 // (2) Then we make sure we've delivered all waiting browse messages to our clients
2623 // (3) Then we sleep for the time requested by mDNSCore, or until the next event, whichever is sooner
2624 // (4) On wakeup we first process *all* events
2625 // (5) then when no more events remain, we go back to (1) to finish off any deferred work and do it all again
2626 for ( ; ; )
2627 {
2628 #define kEventsToReadAtOnce 1
2629 struct kevent new_events[kEventsToReadAtOnce];
2630
2631 // Run mDNS_Execute to find out the time we next need to wake up
2632 mDNSs32 start = mDNSPlatformRawTime();
2633 mDNSs32 nextTimerEvent = udsserver_idle(mDNSDaemonIdle(m));
2634 mDNSs32 end = mDNSPlatformRawTime();
2635 if (end - start >= WatchDogReportingThreshold)
2636 LogInfo("WARNING: Idle task took %dms to complete", end - start);
2637
2638 mDNSs32 now = mDNS_TimeNow(m);
2639
2640 if (m->ShutdownTime)
2641 {
2642 if (mDNSStorage.ResourceRecords)
2643 {
2644 AuthRecord *rr;
2645 for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
2646 {
2647 LogInfo("Cannot exit yet; Resource Record still exists: %s", ARDisplayString(m, rr));
2648 if (mDNS_LoggingEnabled) usleep(10000); // Sleep 10ms so that we don't flood syslog with too many messages
2649 }
2650 }
2651 if (mDNS_ExitNow(m, now))
2652 {
2653 LogInfo("mDNS_FinalExit");
2654 mDNS_FinalExit(&mDNSStorage);
2655 usleep(1000); // Little 1ms pause before exiting, so we don't lose our final syslog messages
2656 exit(0);
2657 }
2658 if (nextTimerEvent - m->ShutdownTime >= 0)
2659 nextTimerEvent = m->ShutdownTime;
2660 }
2661
2662 if (m->SleepLimit)
2663 if (!AllowSleepNow(m, now))
2664 if (nextTimerEvent - m->SleepLimit >= 0)
2665 nextTimerEvent = m->SleepLimit;
2666
2667 // Convert absolute wakeup time to a relative time from now
2668 mDNSs32 ticks = nextTimerEvent - now;
2669 if (ticks < 1) ticks = 1;
2670
2671 static mDNSs32 RepeatedBusy = 0; // Debugging sanity check, to guard against CPU spins
2672 if (ticks > 1)
2673 RepeatedBusy = 0;
2674 else
2675 {
2676 ticks = 1;
2677 if (++RepeatedBusy >= mDNSPlatformOneSecond) { ShowTaskSchedulingError(&mDNSStorage); RepeatedBusy = 0; }
2678 }
2679
2680 verbosedebugf("KQueueLoop: Handled %d events; now sleeping for %d ticks", numevents, ticks);
2681 numevents = 0;
2682
2683 // Release the lock, and sleep until:
2684 // 1. Something interesting happens like a packet arriving, or
2685 // 2. The other thread writes a byte to WakeKQueueLoopFD to poke us and make us wake up, or
2686 // 3. The timeout expires
2687 pthread_mutex_unlock(&PlatformStorage.BigMutex);
2688
2689 // If we woke up to receive a multicast, set low-water mark to dampen excessive wakeup rate
2690 if (m->p->num_mcasts)
2691 {
2692 SetLowWater(&m->p->permanentsockets, 0x10000);
2693 if (ticks > mDNSPlatformOneSecond / 8) ticks = mDNSPlatformOneSecond / 8;
2694 }
2695
2696 #if USE_SELECT_WITH_KQUEUEFD
2697 struct timeval timeout;
2698 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
2699 timeout.tv_usec = (ticks % mDNSPlatformOneSecond) * multiplier;
2700 FD_SET(KQueueFD, &readfds);
2701 if (select(KQueueFD+1, &readfds, NULL, NULL, &timeout) < 0)
2702 { LogMsg("select(%d) failed errno %d (%s)", KQueueFD, errno, strerror(errno)); sleep(1); }
2703 #else
2704 struct timespec timeout;
2705 timeout.tv_sec = ticks / mDNSPlatformOneSecond;
2706 timeout.tv_nsec = (ticks % mDNSPlatformOneSecond) * multiplier;
2707 // In my opinion, you ought to be able to call kevent() with nevents set to zero,
2708 // and have it work similarly to the way it does with nevents non-zero --
2709 // i.e. it waits until either an event happens or the timeout expires, and then wakes up.
2710 // In fact, what happens if you do this is that it just returns immediately. So, we have
2711 // to pass nevents set to one, and then we just ignore the event it gives back to us. -- SC
2712 if (kevent(KQueueFD, NULL, 0, new_events, 1, &timeout) < 0)
2713 { LogMsg("kevent(%d) failed errno %d (%s)", KQueueFD, errno, strerror(errno)); sleep(1); }
2714 #endif
2715
2716 pthread_mutex_lock(&PlatformStorage.BigMutex);
2717 // We have to ignore the event we may have been told about above, because that
2718 // was done without holding the lock, and between the time we woke up and the
2719 // time we reclaimed the lock the other thread could have done something that
2720 // makes the event no longer valid. Now we have the lock, we call kevent again
2721 // and this time we can safely process the events it tells us about.
2722
2723 // If we changed UDP socket low-water mark, restore it, so we will be told about every packet
2724 if (m->p->num_mcasts)
2725 {
2726 SetLowWater(&m->p->permanentsockets, 1);
2727 m->p->num_mcasts = 0;
2728 }
2729
2730 static const struct timespec zero_timeout = { 0, 0 };
2731 int events_found;
2732 while ((events_found = kevent(KQueueFD, NULL, 0, new_events, kEventsToReadAtOnce, &zero_timeout)) != 0)
2733 {
2734 if (events_found > kEventsToReadAtOnce || (events_found < 0 && errno != EINTR))
2735 {
2736 // Not sure what to do here, our kqueue has failed us - this isn't ideal
2737 LogMsg("ERROR: KQueueLoop - kevent failed errno %d (%s)", errno, strerror(errno));
2738 exit(errno);
2739 }
2740
2741 numevents += events_found;
2742
2743 int i;
2744 for (i = 0; i < events_found; i++)
2745 {
2746 const KQueueEntry *const kqentry = new_events[i].udata;
2747 mDNSs32 stime = mDNSPlatformRawTime();
2748 const char *const KQtask = kqentry->KQtask; // Grab a copy in case KQcallback deletes the task
2749 kqentry->KQcallback(new_events[i].ident, new_events[i].filter, kqentry->KQcontext);
2750 mDNSs32 etime = mDNSPlatformRawTime();
2751 if (etime - stime >= WatchDogReportingThreshold)
2752 LogInfo("WARNING: %s took %dms to complete", KQtask, etime - stime);
2753 }
2754 }
2755 }
2756
2757 return NULL;
2758 }
2759
2760 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2761
2762 mDNSlocal void LaunchdCheckin(void)
2763 {
2764 // Ask launchd for our socket
2765 launch_data_t resp_sd = launch_socket_service_check_in();
2766 if (!resp_sd)
2767 {
2768 LogMsg("launch_socket_service_check_in returned NULL");
2769 return;
2770 }
2771 else
2772 {
2773 launch_data_t skts = launch_data_dict_lookup(resp_sd, LAUNCH_JOBKEY_SOCKETS);
2774 if (!skts) LogMsg("launch_data_dict_lookup LAUNCH_JOBKEY_SOCKETS returned NULL");
2775 else
2776 {
2777 launch_data_t skt = launch_data_dict_lookup(skts, "Listeners");
2778 if (!skt) LogMsg("launch_data_dict_lookup Listeners returned NULL");
2779 else
2780 {
2781 launchd_fds_count = launch_data_array_get_count(skt);
2782 if (launchd_fds_count == 0) LogMsg("launch_data_array_get_count(skt) returned 0");
2783 else
2784 {
2785 launchd_fds = mallocL("LaunchdCheckin", sizeof(dnssd_sock_t) * launchd_fds_count);
2786 if (!launchd_fds) LogMsg("LaunchdCheckin: malloc failed");
2787 else
2788 {
2789 size_t i;
2790 for(i = 0; i < launchd_fds_count; i++)
2791 {
2792 launch_data_t s = launch_data_array_get_index(skt, i);
2793 if (!s)
2794 {
2795 launchd_fds[i] = dnssd_InvalidSocket;
2796 LogMsg("launch_data_array_get_index(skt, %d) returned NULL", i);
2797 }
2798 else
2799 {
2800 launchd_fds[i] = launch_data_get_fd(s);
2801 LogInfo("Launchd Unix Domain Socket [%d]: %d", i, launchd_fds[i]);
2802 }
2803 }
2804 }
2805 // In some early versions of 10.4.x, the permissions on the UDS were not set correctly, so we fix them here
2806 chmod(MDNS_UDS_SERVERPATH, S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP | S_IROTH|S_IWOTH);
2807 }
2808 }
2809 }
2810 }
2811 launch_data_free(resp_sd);
2812 }
2813
2814 static mach_port_t RegisterMachService(const char *service_name)
2815 {
2816 mach_port_t port = MACH_PORT_NULL;
2817 kern_return_t kr;
2818
2819 if (KERN_SUCCESS != (kr = bootstrap_check_in(bootstrap_port, (char *)service_name, &port)))
2820 {
2821 LogMsg("RegisterMachService: %d %X %s", kr, kr, mach_error_string(kr));
2822 return MACH_PORT_NULL;
2823 }
2824
2825 if (KERN_SUCCESS != (kr = mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND)))
2826 {
2827 LogMsg("RegisterMachService: %d %X %s", kr, kr, mach_error_string(kr));
2828 mach_port_deallocate(mach_task_self(), port);
2829 return MACH_PORT_NULL;
2830 }
2831
2832 return port;
2833 }
2834
2835 extern int sandbox_init(const char *profile, uint64_t flags, char **errorbuf) __attribute__((weak_import));
2836
2837 mDNSexport int main(int argc, char **argv)
2838 {
2839 int i;
2840 kern_return_t status;
2841
2842 mDNSMacOSXSystemBuildNumber(NULL);
2843 LogMsg("%s starting %s %d", mDNSResponderVersionString, OSXVers ? "OSXVers" : "iOSVers", OSXVers ? OSXVers : iOSVers);
2844
2845 #if 0
2846 LogMsg("CacheRecord %d", sizeof(CacheRecord));
2847 LogMsg("CacheGroup %d", sizeof(CacheGroup));
2848 LogMsg("ResourceRecord %d", sizeof(ResourceRecord));
2849 LogMsg("RData_small %d", sizeof(RData_small));
2850
2851 LogMsg("sizeof(CacheEntity) %d", sizeof(CacheEntity));
2852 LogMsg("RR_CACHE_SIZE %d", RR_CACHE_SIZE);
2853 LogMsg("block usage %d", sizeof(CacheEntity) * RR_CACHE_SIZE);
2854 LogMsg("block wastage %d", 16*1024 - sizeof(CacheEntity) * RR_CACHE_SIZE);
2855 #endif
2856
2857 if (0 == geteuid())
2858 {
2859 LogMsg("mDNSResponder cannot be run as root !! Exiting..");
2860 return -1;
2861 }
2862
2863 for (i=1; i<argc; i++)
2864 {
2865 if (!strcasecmp(argv[i], "-d" )) mDNS_DebugMode = mDNStrue;
2866 if (!strcasecmp(argv[i], "-NoMulticastAdvertisements")) advertise = mDNS_Init_DontAdvertiseLocalAddresses;
2867 if (!strcasecmp(argv[i], "-DisableSleepProxyClient" )) DisableSleepProxyClient = mDNStrue;
2868 if (!strcasecmp(argv[i], "-DebugLogging" )) mDNS_LoggingEnabled = mDNStrue;
2869 if (!strcasecmp(argv[i], "-UnicastPacketLogging" )) mDNS_PacketLoggingEnabled = mDNStrue;
2870 if (!strcasecmp(argv[i], "-OfferSleepProxyService" ))
2871 OfferSleepProxyService = (i+1 < argc && mDNSIsDigit(argv[i+1][0]) && mDNSIsDigit(argv[i+1][1]) && argv[i+1][2]==0) ? atoi(argv[++i]) : 100;
2872 if (!strcasecmp(argv[i], "-UseInternalSleepProxy" ))
2873 UseInternalSleepProxy = (i+1<argc && mDNSIsDigit(argv[i+1][0]) && argv[i+1][1]==0) ? atoi(argv[++i]) : 1;
2874 if (!strcasecmp(argv[i], "-StrictUnicastOrdering" )) StrictUnicastOrdering = mDNStrue;
2875 if (!strcasecmp(argv[i], "-AlwaysAppendSearchDomains")) AlwaysAppendSearchDomains = mDNStrue;
2876 }
2877
2878 // Note that mDNSPlatformInit will set DivertMulticastAdvertisements in the mDNS structure
2879 if (!advertise) LogMsg("Administratively prohibiting multicast advertisements");
2880
2881 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2882
2883 signal(SIGHUP, HandleSIG); // (Debugging) Purge the cache to check for cache handling bugs
2884 signal(SIGINT, HandleSIG); // Ctrl-C: Detach from Mach BootstrapService and exit cleanly
2885 signal(SIGPIPE, SIG_IGN); // Don't want SIGPIPE signals -- we'll handle EPIPE errors directly
2886 signal(SIGTERM, HandleSIG); // Machine shutting down: Detach from and exit cleanly like Ctrl-C
2887 signal(SIGINFO, HandleSIG); // (Debugging) Write state snapshot to syslog
2888 signal(SIGUSR1, HandleSIG); // (Debugging) Enable Logging
2889 signal(SIGUSR2, HandleSIG); // (Debugging) Enable Packet Logging
2890 signal(SIGURG, HandleSIG); // (Debugging) Toggle Opportunistic Caching
2891 signal(SIGPROF, HandleSIG); // (Debugging) Toggle Multicast Logging
2892 signal(SIGTSTP, HandleSIG); // (Debugging) Disable all Debug Logging (USR1/USR2/PROF)
2893
2894 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2895
2896 mDNSStorage.p = &PlatformStorage; // Make sure mDNSStorage.p is set up, because validatelists uses it
2897 // Need to Start XPC Server Before LaunchdCheckin() (Reason: rdar11023750)
2898 xpc_server_init();
2899 LaunchdCheckin();
2900
2901 #ifndef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2902
2903 // Create the kqueue, mutex and thread to support KQSockets
2904 KQueueFD = kqueue();
2905 if (KQueueFD == -1) { LogMsg("kqueue() failed errno %d (%s)", errno, strerror(errno)); status = errno; goto exit; }
2906
2907 i = pthread_mutex_init(&PlatformStorage.BigMutex, NULL);
2908 if (i == -1) { LogMsg("pthread_mutex_init() failed errno %d (%s)", errno, strerror(errno)); status = errno; goto exit; }
2909
2910 int fdpair[2] = {0, 0};
2911 i = socketpair(AF_UNIX, SOCK_STREAM, 0, fdpair);
2912 if (i == -1) { LogMsg("socketpair() failed errno %d (%s)", errno, strerror(errno)); status = errno; goto exit; }
2913
2914 // Socket pair returned us two identical sockets connected to each other
2915 // We will use the first socket to send the second socket. The second socket
2916 // will be added to the kqueue so it will wake when data is sent.
2917 static const KQueueEntry wakeKQEntry = { KQWokenFlushBytes, NULL, "kqueue wakeup after CFRunLoop event" };
2918
2919 PlatformStorage.WakeKQueueLoopFD = fdpair[0];
2920 KQueueSet(fdpair[1], EV_ADD, EVFILT_READ, &wakeKQEntry);
2921
2922 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2923
2924 // Invoke sandbox profile /usr/share/sandbox/mDNSResponder.sb
2925 #if MDNS_NO_SANDBOX
2926 LogMsg("Note: Compiled without Apple Sandbox support");
2927 #else // MDNS_NO_SANDBOX
2928 if (!sandbox_init)
2929 LogMsg("Note: Running without Apple Sandbox support (not available on this OS)");
2930 else
2931 {
2932 char *sandbox_msg;
2933 uint64_t sandbox_flags = SANDBOX_NAMED;
2934
2935 int sandbox_err = sandbox_init("mDNSResponder", sandbox_flags, &sandbox_msg);
2936 if (sandbox_err)
2937 {
2938 LogMsg("WARNING: sandbox_init error %s", sandbox_msg);
2939 // If we have errors in the sandbox during development, to prevent
2940 // exiting, uncomment the following line.
2941 //sandbox_free_error(sandbox_msg);
2942
2943 errx(EX_OSERR, "sandbox_init() failed: %s", sandbox_msg);
2944 }
2945 else LogInfo("Now running under Apple Sandbox restrictions");
2946 }
2947 #endif // MDNS_NO_SANDBOX
2948
2949 // We use BeginTransactionAtShutdown in the plist that ensures that we will
2950 // receive a SIGTERM during shutdown rather than a SIGKILL. But launchd (due to some
2951 // limitation) currently requires us to still start and end the transaction for
2952 // its proper initialization.
2953 vproc_transaction_t vt = vproc_transaction_begin(NULL);
2954 if (vt) vproc_transaction_end(NULL, vt);
2955
2956 m_port = RegisterMachService(kmDNSResponderServName);
2957 // We should ALWAYS receive our Mach port from RegisterMachService() but sanity check before initializing daemon
2958 if (m_port == MACH_PORT_NULL)
2959 {
2960 LogMsg("! MACH PORT IS NULL ! bootstrap_checkin failed to give a mach port");
2961 return -1;
2962 }
2963
2964 status = mDNSDaemonInitialize();
2965 if (status) { LogMsg("Daemon start: mDNSDaemonInitialize failed"); goto exit; }
2966
2967 status = udsserver_init(launchd_fds, launchd_fds_count);
2968 if (status) { LogMsg("Daemon start: udsserver_init failed"); goto exit; }
2969
2970 log_client = asl_open(NULL, "mDNSResponder", 0);
2971 log_msg = asl_new(ASL_TYPE_MSG);
2972
2973 #if TARGET_OS_EMBEDDED
2974 _scprefs_observer_watch(scprefs_observer_type_global, kmDNSResponderPrefIDStr, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
2975 ^{
2976 Prefschanged();
2977 });
2978 #endif
2979
2980 mDNSMacOSXNetworkChanged(&mDNSStorage);
2981 UpdateDebugState();
2982
2983 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2984 LogInfo("Daemon Start: Using LibDispatch");
2985 // CFRunLoopRun runs both CFRunLoop sources and dispatch sources
2986 CFRunLoopRun();
2987 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2988 // Start the kqueue thread
2989 pthread_t KQueueThread;
2990 i = pthread_create(&KQueueThread, NULL, KQueueLoop, &mDNSStorage);
2991 if (i == -1) { LogMsg("pthread_create() failed errno %d (%s)", errno, strerror(errno)); status = errno; goto exit; }
2992 if (status == 0)
2993 {
2994 CFRunLoopRun();
2995 LogMsg("ERROR: CFRunLoopRun Exiting.");
2996 mDNS_Close(&mDNSStorage);
2997 }
2998 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2999
3000 LogMsg("%s exiting", mDNSResponderVersionString);
3001
3002 exit:
3003 return(status);
3004 }
3005
3006 // uds_daemon.c support routines /////////////////////////////////////////////
3007
3008 // Arrange things so that when data appears on fd, callback is called with context
3009 mDNSexport mStatus udsSupportAddFDToEventLoop(int fd, udsEventCallback callback, void *context, void **platform_data)
3010 {
3011 KQSocketEventSource **p = &gEventSources;
3012 (void) platform_data;
3013 while (*p && (*p)->fd != fd) p = &(*p)->next;
3014 if (*p) { LogMsg("udsSupportAddFDToEventLoop: ERROR fd %d already has EventLoop source entry", fd); return mStatus_AlreadyRegistered; }
3015
3016 KQSocketEventSource *newSource = (KQSocketEventSource*) mallocL("KQSocketEventSource", sizeof *newSource);
3017 if (!newSource) return mStatus_NoMemoryErr;
3018
3019 newSource->next = mDNSNULL;
3020 newSource->fd = fd;
3021 newSource->kqs.KQcallback = callback;
3022 newSource->kqs.KQcontext = context;
3023 newSource->kqs.KQtask = "UDS client";
3024 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
3025 newSource->kqs.readSource = mDNSNULL;
3026 newSource->kqs.writeSource = mDNSNULL;
3027 newSource->kqs.fdClosed = mDNSfalse;
3028 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
3029
3030 if (KQueueSet(fd, EV_ADD, EVFILT_READ, &newSource->kqs) == 0)
3031 {
3032 *p = newSource;
3033 return mStatus_NoError;
3034 }
3035
3036 LogMsg("KQueueSet failed for fd %d errno %d (%s)", fd, errno, strerror(errno));
3037 freeL("KQSocketEventSource", newSource);
3038 return mStatus_BadParamErr;
3039 }
3040
3041 int udsSupportReadFD(dnssd_sock_t fd, char *buf, int len, int flags, void *platform_data)
3042 {
3043 (void) platform_data;
3044 return recv(fd, buf, len, flags);
3045 }
3046
3047 mDNSexport mStatus udsSupportRemoveFDFromEventLoop(int fd, void *platform_data) // Note: This also CLOSES the file descriptor
3048 {
3049 KQSocketEventSource **p = &gEventSources;
3050 (void) platform_data;
3051 while (*p && (*p)->fd != fd) p = &(*p)->next;
3052 if (*p)
3053 {
3054 KQSocketEventSource *s = *p;
3055 *p = (*p)->next;
3056 // We don't have to explicitly do a kqueue EV_DELETE here because closing the fd
3057 // causes the kernel to automatically remove any associated kevents
3058 mDNSPlatformCloseFD(&s->kqs, s->fd);
3059 freeL("KQSocketEventSource", s);
3060 return mStatus_NoError;
3061 }
3062 LogMsg("udsSupportRemoveFDFromEventLoop: ERROR fd %d not found in EventLoop source list", fd);
3063 return mStatus_NoSuchNameErr;
3064 }
3065
3066 #if _BUILDING_XCODE_PROJECT_
3067 // If mDNSResponder crashes, then this string will be magically included in the automatically-generated crash log
3068 const char *__crashreporter_info__ = mDNSResponderVersionString;
3069 asm (".desc ___crashreporter_info__, 0x10");
3070 #endif
3071
3072 // For convenience when using the "strings" command, this is the last thing in the file
3073 // The "@(#) " pattern is a special prefix the "what" command looks for
3074 mDNSexport const char mDNSResponderVersionString_SCCS[] = "@(#) mDNSResponder " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";