]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/mDNSMacOSX.c
6547b10038d143a872e98322b87ca4dec2518a54
[apple/mdnsresponder.git] / mDNSMacOSX / mDNSMacOSX.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2013 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 // mDNSMacOSX.c:
20 // Supporting routines to run mDNS on a CFRunLoop platform
21 // ***************************************************************************
22
23 // For debugging, set LIST_ALL_INTERFACES to 1 to display all found interfaces,
24 // including ones that mDNSResponder chooses not to use.
25 #define LIST_ALL_INTERFACES 0
26
27 #include "mDNSEmbeddedAPI.h" // Defines the interface provided to the client layer above
28 #include "DNSCommon.h"
29 #include "uDNS.h"
30 #include "mDNSMacOSX.h" // Defines the specific types needed to run mDNS on this platform
31 #include "dns_sd.h" // For mDNSInterface_LocalOnly etc.
32 #include "PlatformCommon.h"
33 #include "uds_daemon.h"
34 #include "CryptoSupport.h"
35
36 #include <stdio.h>
37 #include <stdarg.h> // For va_list support
38 #include <stdlib.h> // For arc4random
39 #include <net/if.h>
40 #include <net/if_types.h> // For IFT_ETHER
41 #include <net/if_dl.h>
42 #include <net/bpf.h> // For BIOCSETIF etc.
43 #include <sys/uio.h>
44 #include <sys/param.h>
45 #include <sys/socket.h>
46 #include <sys/sysctl.h>
47 #include <sys/event.h>
48 #include <fcntl.h>
49 #include <sys/ioctl.h>
50 #include <time.h> // platform support for UTC time
51 #include <arpa/inet.h> // for inet_aton
52 #include <pthread.h>
53 #include <netdb.h> // for getaddrinfo
54 #include <sys/sockio.h> // for SIOCGIFEFLAGS
55 #include <notify.h>
56 #include <netinet/in.h> // For IP_RECVTTL
57 #ifndef IP_RECVTTL
58 #define IP_RECVTTL 24 // bool; receive reception TTL w/dgram
59 #endif
60
61 #include <netinet/in_systm.h> // For n_long, required by <netinet/ip.h> below
62 #include <netinet/ip.h> // For IPTOS_LOWDELAY etc.
63 #include <netinet6/in6_var.h> // For IN6_IFF_NOTREADY etc.
64 #include <netinet6/nd6.h> // For ND6_INFINITE_LIFETIME etc.
65
66 #include <netinet/tcp.h>
67
68 #include <DebugServices.h>
69 #include "dnsinfo.h"
70
71 #include <ifaddrs.h>
72
73 #include <IOKit/IOKitLib.h>
74 #include <IOKit/IOMessage.h>
75
76 #include <IOKit/ps/IOPowerSources.h>
77 #include <IOKit/ps/IOPowerSourcesPrivate.h>
78 #include <IOKit/ps/IOPSKeys.h>
79
80 #include <mach/mach_error.h>
81 #include <mach/mach_port.h>
82 #include <mach/mach_time.h>
83 #include "helper.h"
84 #include "P2PPacketFilter.h"
85
86 #include <asl.h>
87 #include <SystemConfiguration/SCPrivate.h>
88
89 // Include definition of opaque_presence_indication for KEV_DL_NODE_PRESENCE handling logic.
90 #include <Kernel/IOKit/apple80211/apple80211_var.h>
91
92 #if APPLE_OSX_mDNSResponder
93 #include <DeviceToDeviceManager/DeviceToDeviceManager.h>
94 #include <AWACS.h>
95 #if !NO_D2D
96 D2DStatus D2DInitialize(CFRunLoopRef runLoop, D2DServiceCallback serviceCallback, void* userData) __attribute__((weak_import));
97 D2DStatus D2DRetain(D2DServiceInstance instanceHandle, D2DTransportType transportType) __attribute__((weak_import));
98 D2DStatus D2DStopAdvertisingPairOnTransport(const Byte *key, const size_t keySize, const Byte *value, const size_t valueSize, D2DTransportType transport) __attribute__((weak_import));
99 D2DStatus D2DRelease(D2DServiceInstance instanceHandle, D2DTransportType transportType) __attribute__((weak_import));
100 D2DStatus D2DStartAdvertisingPairOnTransport(const Byte *key, const size_t keySize, const Byte *value, const size_t valueSize, D2DTransportType transport) __attribute__((weak_import));
101 D2DStatus D2DStartBrowsingForKeyOnTransport(const Byte *key, const size_t keySize, D2DTransportType transport) __attribute__((weak_import));
102 D2DStatus D2DStopBrowsingForKeyOnTransport(const Byte *key, const size_t keySize, D2DTransportType transport) __attribute__((weak_import));
103 void D2DStartResolvingPairOnTransport(const Byte *key, const size_t keySize, const Byte *value, const size_t valueSize, D2DTransportType transport) __attribute__((weak_import));
104 void D2DStopResolvingPairOnTransport(const Byte *key, const size_t keySize, const Byte *value, const size_t valueSize, D2DTransportType transport) __attribute__((weak_import));
105 D2DStatus D2DTerminate() __attribute__((weak_import));
106
107 #endif // ! NO_D2D
108
109 #else
110 #define NO_D2D 1
111 #define NO_AWACS 1
112 #endif // APPLE_OSX_mDNSResponder
113
114 #if APPLE_OSX_mDNSResponder && !TARGET_OS_EMBEDDED
115 #include <IOKit/platform/IOPlatformSupportPrivate.h>
116 #endif // APPLE_OSX_mDNSResponder && !TARGET_OS_EMBEDDED
117
118
119 #define kInterfaceSpecificOption "interface="
120
121 #define mDNS_IOREG_KEY "mDNS_KEY"
122 #define mDNS_IOREG_VALUE "2009-07-30"
123 #define mDNS_IOREG_KA_KEY "mDNS_Keepalive"
124 #define mDNS_USER_CLIENT_CREATE_TYPE 'mDNS'
125
126 // cache the InterfaceID of the AWDL interface
127 static mDNSInterfaceID AWDLInterfaceID;
128
129 // ***************************************************************************
130 // Globals
131
132 #if COMPILER_LIKES_PRAGMA_MARK
133 #pragma mark - Globals
134 #endif
135
136 // By default we don't offer sleep proxy service
137 // If OfferSleepProxyService is set non-zero (typically via command-line switch),
138 // then we'll offer sleep proxy service on desktop Macs that are set to never sleep.
139 // We currently do not offer sleep proxy service on laptops, or on machines that are set to go to sleep.
140 mDNSexport int OfferSleepProxyService = 0;
141 mDNSexport int DisableSleepProxyClient = 0;
142 mDNSexport int UseInternalSleepProxy = 1; // Set to non-zero to use internal (in-NIC) Sleep Proxy
143
144 mDNSexport int OSXVers, iOSVers;
145 mDNSexport int KQueueFD;
146
147 #ifndef NO_SECURITYFRAMEWORK
148 static CFArrayRef ServerCerts;
149 OSStatus SSLSetAllowAnonymousCiphers(SSLContextRef context, Boolean enable);
150 #endif /* NO_SECURITYFRAMEWORK */
151
152 static CFStringRef NetworkChangedKey_IPv4;
153 static CFStringRef NetworkChangedKey_IPv6;
154 static CFStringRef NetworkChangedKey_Hostnames;
155 static CFStringRef NetworkChangedKey_Computername;
156 static CFStringRef NetworkChangedKey_DNS;
157 static CFStringRef NetworkChangedKey_StateInterfacePrefix;
158 static CFStringRef NetworkChangedKey_DynamicDNS = CFSTR("Setup:/Network/DynamicDNS");
159 static CFStringRef NetworkChangedKey_BackToMyMac = CFSTR("Setup:/Network/BackToMyMac");
160 static CFStringRef NetworkChangedKey_BTMMConnectivity = CFSTR("State:/Network/Connectivity");
161 static CFStringRef NetworkChangedKey_PowerSettings = CFSTR("State:/IOKit/PowerManagement/CurrentSettings");
162
163 static char HINFO_HWstring_buffer[32];
164 static char *HINFO_HWstring = "Device";
165 static int HINFO_HWstring_prefixlen = 6;
166
167 mDNSexport int WatchDogReportingThreshold = 250;
168
169 dispatch_queue_t SSLqueue;
170
171 //To prevent blocking the main queue, all writes to DynamicStore happen on the DynamicStoreQueue
172 static dispatch_queue_t DynamicStoreQueue;
173
174 #if TARGET_OS_EMBEDDED
175 #define kmDNSResponderManagedPrefsID CFSTR("/Library/Managed Preferences/mobile/com.apple.mDNSResponder.plist")
176 #endif
177
178 #if APPLE_OSX_mDNSResponder
179 static mDNSu8 SPMetricPortability = 99;
180 static mDNSu8 SPMetricMarginalPower = 99;
181 static mDNSu8 SPMetricTotalPower = 99;
182 static mDNSu8 SPMetricFeatures = 1; /* The current version supports TCP Keep Alive Feature */
183 mDNSexport domainname ActiveDirectoryPrimaryDomain;
184 mDNSexport int ActiveDirectoryPrimaryDomainLabelCount;
185 mDNSexport mDNSAddr ActiveDirectoryPrimaryDomainServer;
186 #endif // APPLE_OSX_mDNSResponder
187
188 // Don't send triggers too often. We arbitrarily limit it to three minutes.
189 #define DNS_TRIGGER_INTERVAL (180 * mDNSPlatformOneSecond)
190
191 // Used by AutoTunnel
192 const char btmmprefix[] = "btmmdns:";
193 const char dnsprefix[] = "dns:";
194
195 // String Array used to write list of private domains to Dynamic Store
196 static CFArrayRef privateDnsArray = NULL;
197
198 // ***************************************************************************
199 #if COMPILER_LIKES_PRAGMA_MARK
200 #pragma mark -
201 #pragma mark - D2D Support
202 #endif
203
204 #if !NO_D2D
205
206 mDNSexport void D2D_start_advertising_interface(NetworkInterfaceInfo *interface)
207 {
208 // AWDL wants the address and reverse address PTR record communicated
209 // via the D2D interface layer.
210 if (interface->InterfaceID == AWDLInterfaceID)
211 {
212 // only log if we have a valid record to start advertising
213 if (interface->RR_A.resrec.RecordType || interface->RR_PTR.resrec.RecordType)
214 LogInfo("D2D_start_advertising_interface: %s", interface->ifname);
215
216 if (interface->RR_A.resrec.RecordType)
217 external_start_advertising_service(&interface->RR_A.resrec, NULL);
218 if (interface->RR_PTR.resrec.RecordType)
219 external_start_advertising_service(&interface->RR_PTR.resrec, NULL);
220 }
221 }
222
223 mDNSexport void D2D_stop_advertising_interface(NetworkInterfaceInfo *interface)
224 {
225 if (interface->InterfaceID == AWDLInterfaceID)
226 {
227 // only log if we have a valid record to stop advertising
228 if (interface->RR_A.resrec.RecordType || interface->RR_PTR.resrec.RecordType)
229 LogInfo("D2D_stop_advertising_interface: %s", interface->ifname);
230
231 if (interface->RR_A.resrec.RecordType)
232 external_stop_advertising_service(&interface->RR_A.resrec, NULL);
233 if (interface->RR_PTR.resrec.RecordType)
234 external_stop_advertising_service(&interface->RR_PTR.resrec, NULL);
235 }
236 }
237
238 // Name compression items for fake packet version number 1
239 static const mDNSu8 compression_packet_v1 = 0x01;
240
241 static DNSMessage compression_base_msg = { { {{0}}, {{0}}, 2, 0, 0, 0 }, "\x04_tcp\x05local\x00\x00\x0C\x00\x01\x04_udp\xC0\x11\x00\x0C\x00\x01" };
242 static mDNSu8 *const compression_limit = (mDNSu8 *) &compression_base_msg + sizeof(DNSMessage);
243 static mDNSu8 *const compression_lhs = (mDNSu8 *const) compression_base_msg.data + 27;
244
245 mDNSlocal void FreeD2DARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
246 mDNSlocal void PrintHex(mDNSu8 *data, mDNSu16 len);
247
248 typedef struct D2DRecordListElem
249 {
250 struct D2DRecordListElem *next;
251 AuthRecord ar;
252 D2DServiceInstance instanceHandle;
253 D2DTransportType transportType;
254 } D2DRecordListElem;
255
256 static D2DRecordListElem *D2DRecords = NULL; // List of records returned with D2DServiceFound events
257
258 typedef struct D2DBrowseListElem
259 {
260 struct D2DBrowseListElem *next;
261 domainname name;
262 mDNSu16 type;
263 unsigned int refCount;
264 } D2DBrowseListElem;
265
266 D2DBrowseListElem* D2DBrowseList = NULL;
267
268 mDNSlocal mDNSu8 *putVal16(mDNSu8 *ptr, mDNSu16 val)
269 {
270 ptr[0] = (mDNSu8)((val >> 8 ) & 0xFF);
271 ptr[1] = (mDNSu8)((val ) & 0xFF);
272 return ptr + sizeof(mDNSu16);
273 }
274
275 mDNSlocal mDNSu8 *putVal32(mDNSu8 *ptr, mDNSu32 val)
276 {
277 ptr[0] = (mDNSu8)((val >> 24) & 0xFF);
278 ptr[1] = (mDNSu8)((val >> 16) & 0xFF);
279 ptr[2] = (mDNSu8)((val >> 8) & 0xFF);
280 ptr[3] = (mDNSu8)((val ) & 0xFF);
281 return ptr + sizeof(mDNSu32);
282 }
283
284 mDNSlocal void DomainnameToLower(const domainname * const in, domainname * const out)
285 {
286 const mDNSu8 * const start = (const mDNSu8 * const)in;
287 mDNSu8 *ptr = (mDNSu8*)start;
288 while(*ptr)
289 {
290 mDNSu8 c = *ptr;
291 out->c[ptr-start] = *ptr;
292 ptr++;
293 for (; c; c--,ptr++) out->c[ptr-start] = mDNSIsUpperCase(*ptr) ? (*ptr - 'A' + 'a') : *ptr;
294 }
295 out->c[ptr-start] = *ptr;
296 }
297
298 mDNSlocal mStatus DNSNameCompressionParseBytes(mDNS *const m, const mDNSu8 *const lhs, const mDNSu16 lhs_len, const mDNSu8 *const rhs, const mDNSu16 rhs_len, AuthRecord *rr)
299 {
300 if (mDNS_LoggingEnabled)
301 {
302 LogInfo("%s", __func__);
303 LogInfo(" Static Bytes: (%d bytes)", compression_lhs - (mDNSu8*)&compression_base_msg);
304 PrintHex((mDNSu8*)&compression_base_msg, compression_lhs - (mDNSu8*)&compression_base_msg);
305 }
306
307 mDNSu8 *ptr = compression_lhs; // pointer to the end of our fake packet
308
309 // Check to make sure we're not going to go past the end of the DNSMessage data
310 // 7 = 2 for CLASS (-1 for our version) + 4 for TTL + 2 for RDLENGTH
311 if (ptr + lhs_len - 7 + rhs_len >= compression_limit) return mStatus_NoMemoryErr;
312
313 // Copy the LHS onto our fake wire packet
314 mDNSPlatformMemCopy(ptr, lhs, lhs_len);
315 ptr += lhs_len - 1;
316
317 // Check the 'fake packet' version number, to ensure that we know how to decompress this data
318 if (*ptr != compression_packet_v1) return mStatus_Incompatible;
319
320 // two bytes of CLASS
321 ptr = putVal16(ptr, kDNSClass_IN | kDNSClass_UniqueRRSet);
322
323 // four bytes of TTL
324 ptr = putVal32(ptr, 120);
325
326 // Copy the RHS length into the RDLENGTH of our fake wire packet
327 ptr = putVal16(ptr, rhs_len);
328
329 // Copy the RHS onto our fake wire packet
330 mDNSPlatformMemCopy(ptr, rhs, rhs_len);
331 ptr += rhs_len;
332
333 if (mDNS_LoggingEnabled)
334 {
335 LogInfo(" Our Bytes (%d bytes): ", ptr - compression_lhs);
336 PrintHex(compression_lhs, ptr - compression_lhs);
337 }
338
339 ptr = (mDNSu8 *) GetLargeResourceRecord(m, &compression_base_msg, compression_lhs, ptr, mDNSInterface_Any, kDNSRecordTypePacketAns, &m->rec);
340 if (!ptr || m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
341 { LogMsg("DNSNameCompressionParseBytes: failed to get large RR"); m->rec.r.resrec.RecordType = 0; return mStatus_UnknownErr; }
342 else LogInfo("DNSNameCompressionParseBytes: got rr: %s", CRDisplayString(m, &m->rec.r));
343
344 mDNS_SetupResourceRecord(rr, mDNSNULL, mDNSInterface_P2P, m->rec.r.resrec.rrtype, 7200, kDNSRecordTypeShared, AuthRecordP2P, FreeD2DARElemCallback, NULL);
345 AssignDomainName(&rr->namestorage, &m->rec.namestorage);
346 rr->resrec.rdlength = m->rec.r.resrec.rdlength;
347 rr->resrec.rdata->MaxRDLength = m->rec.r.resrec.rdlength;
348 mDNSPlatformMemCopy(rr->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, m->rec.r.resrec.rdlength);
349 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
350 SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
351
352 m->rec.r.resrec.RecordType = 0; // Mark m->rec as no longer in use
353
354 return mStatus_NoError;
355 }
356
357 mDNSlocal mDNSu8 * DNSNameCompressionBuildLHS(const domainname* typeDomain, DNS_TypeValues qtype)
358 {
359 mDNSu8 *ptr = putDomainNameAsLabels(&compression_base_msg, compression_lhs, compression_limit, typeDomain);
360 if (!ptr) return ptr;
361 *ptr = (qtype >> 8) & 0xff;
362 ptr += 1;
363 *ptr = qtype & 0xff;
364 ptr += 1;
365 *ptr = compression_packet_v1;
366 return ptr + 1;
367 }
368
369 mDNSlocal mDNSu8 * DNSNameCompressionBuildRHS(mDNSu8 *start, const ResourceRecord *const resourceRecord)
370 {
371 return putRData(&compression_base_msg, start, compression_limit, resourceRecord);
372 }
373
374 #define PRINT_DEBUG_BYTES_LIMIT 64 // set limit on number of record bytes printed for debugging
375
376 mDNSlocal void PrintHex(mDNSu8 *data, mDNSu16 len)
377 {
378 mDNSu8 *end;
379 char buffer[49] = {0};
380 char *bufend = buffer + sizeof(buffer);
381
382 if (len > PRINT_DEBUG_BYTES_LIMIT)
383 {
384 LogInfo(" (limiting debug output to %d bytes)", PRINT_DEBUG_BYTES_LIMIT);
385 len = PRINT_DEBUG_BYTES_LIMIT;
386 }
387 end = data + len;
388
389 while(data < end)
390 {
391 char *ptr = buffer;
392 for(; data < end && ptr < bufend-1; ptr+=3,data++)
393 mDNS_snprintf(ptr, bufend - ptr, "%02X ", *data);
394 LogInfo(" %s", buffer);
395 }
396 }
397
398 mDNSlocal void PrintHelper(const char *const tag, mDNSu8 *lhs, mDNSu16 lhs_len, mDNSu8 *rhs, mDNSu16 rhs_len)
399 {
400 if (!mDNS_LoggingEnabled) return;
401
402 LogInfo("%s:", tag);
403 LogInfo(" LHS: (%d bytes)", lhs_len);
404 PrintHex(lhs, lhs_len);
405
406 if (!rhs) return;
407
408 LogInfo(" RHS: (%d bytes)", rhs_len);
409 PrintHex(rhs, rhs_len);
410 }
411
412 mDNSlocal void FreeD2DARElemCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
413 {
414 (void)m; // unused
415 if (result == mStatus_MemFree)
416 {
417 D2DRecordListElem **ptr = &D2DRecords;
418 D2DRecordListElem *tmp;
419 while (*ptr && &(*ptr)->ar != rr) ptr = &(*ptr)->next;
420 if (!*ptr) { LogMsg("FreeD2DARElemCallback: Could not find in D2DRecords: %s", ARDisplayString(m, rr)); return; }
421 LogInfo("FreeD2DARElemCallback: Found in D2DRecords: %s", ARDisplayString(m, rr));
422 tmp = *ptr;
423 *ptr = (*ptr)->next;
424 // Just because we stoppped browsing, doesn't mean we should tear down the PAN connection.
425 mDNSPlatformMemFree(tmp);
426 }
427 }
428
429 mDNSexport void external_connection_release(const domainname *instance)
430 {
431 (void) instance;
432 D2DRecordListElem *ptr = D2DRecords;
433
434 for ( ; ptr ; ptr = ptr->next)
435 {
436 if ((ptr->ar.resrec.rrtype == kDNSServiceType_PTR) &&
437 SameDomainName(&ptr->ar.rdatastorage.u.name, instance))
438 {
439 LogInfo("external_connection_release: Calling D2DRelease(instanceHandle = %p, transportType = %d",
440 ptr->instanceHandle, ptr->transportType);
441 if (D2DRelease) D2DRelease(ptr->instanceHandle, ptr->transportType);
442 }
443 }
444 }
445
446 mDNSlocal void xD2DClearCache(const domainname *regType, DNS_TypeValues qtype)
447 {
448 D2DRecordListElem *ptr = D2DRecords;
449 for ( ; ptr ; ptr = ptr->next)
450 {
451 if ((ptr->ar.resrec.rrtype == qtype) && SameDomainName(&ptr->ar.namestorage, regType))
452 {
453 mDNS_Deregister(&mDNSStorage, &ptr->ar);
454 LogInfo("xD2DClearCache: Clearing cache record and deregistering %s", ARDisplayString(&mDNSStorage, &ptr->ar));
455 }
456 }
457 }
458
459 mDNSlocal D2DBrowseListElem ** D2DFindInBrowseList(const domainname *const name, mDNSu16 type)
460 {
461 D2DBrowseListElem **ptr = &D2DBrowseList;
462
463 for ( ; *ptr; ptr = &(*ptr)->next)
464 if ((*ptr)->type == type && SameDomainName(&(*ptr)->name, name))
465 break;
466
467 return ptr;
468 }
469
470 mDNSlocal unsigned int D2DBrowseListRefCount(const domainname *const name, mDNSu16 type)
471 {
472 D2DBrowseListElem **ptr = D2DFindInBrowseList(name, type);
473 return *ptr ? (*ptr)->refCount : 0;
474 }
475
476 mDNSlocal void D2DBrowseListRetain(const domainname *const name, mDNSu16 type)
477 {
478 D2DBrowseListElem **ptr = D2DFindInBrowseList(name, type);
479
480 if (!*ptr)
481 {
482 *ptr = mDNSPlatformMemAllocate(sizeof(**ptr));
483 mDNSPlatformMemZero(*ptr, sizeof(**ptr));
484 (*ptr)->type = type;
485 AssignDomainName(&(*ptr)->name, name);
486 }
487 (*ptr)->refCount += 1;
488
489 LogInfo("D2DBrowseListRetain: %##s %s refcount now %u", (*ptr)->name.c, DNSTypeName((*ptr)->type), (*ptr)->refCount);
490 }
491
492 mDNSlocal void D2DBrowseListRelease(const domainname *const name, mDNSu16 type)
493 {
494 D2DBrowseListElem **ptr = D2DFindInBrowseList(name, type);
495
496 if (!*ptr) { LogMsg("D2DBrowseListRelease: Didn't find %##s %s in list", name->c, DNSTypeName(type)); return; }
497
498 (*ptr)->refCount -= 1;
499
500 LogInfo("D2DBrowseListRelease: %##s %s refcount now %u", (*ptr)->name.c, DNSTypeName((*ptr)->type), (*ptr)->refCount);
501
502 if (!(*ptr)->refCount)
503 {
504 D2DBrowseListElem *tmp = *ptr;
505 *ptr = (*ptr)->next;
506 mDNSPlatformMemFree(tmp);
507 }
508 }
509
510 mDNSlocal mStatus xD2DParse(mDNS *const m, const mDNSu8 * const lhs, const mDNSu16 lhs_len, const mDNSu8 * const rhs, const mDNSu16 rhs_len, AuthRecord *rr)
511 {
512 if (*(lhs + (lhs_len - 1)) == compression_packet_v1)
513 return DNSNameCompressionParseBytes(m, lhs, lhs_len, rhs, rhs_len, rr);
514 else
515 return mStatus_Incompatible;
516 }
517
518 mDNSlocal void xD2DAddToCache(mDNS *const m, D2DStatus result, D2DServiceInstance instanceHandle, D2DTransportType transportType, const Byte *key, size_t keySize, const Byte *value, size_t valueSize)
519 {
520 if (result == kD2DSuccess)
521 {
522 if ( key == NULL || value == NULL || keySize == 0 || valueSize == 0) { LogMsg("xD2DAddToCache: NULL Byte * passed in or length == 0"); return; }
523
524 mStatus err;
525 D2DRecordListElem *ptr = mDNSPlatformMemAllocate(sizeof(D2DRecordListElem) + (valueSize < sizeof(RData) ? 0 : valueSize - sizeof(RData)));
526
527 if (ptr == NULL) { LogMsg("xD2DAddToCache: memory allocation failure"); return; }
528
529 err = xD2DParse(m, (const mDNSu8 * const)key, (const mDNSu16)keySize, (const mDNSu8 * const)value, (const mDNSu16)valueSize, &ptr->ar);
530 if (err)
531 {
532 LogMsg("xD2DAddToCache: xD2DParse returned error: %d", err);
533 PrintHelper(__func__, (mDNSu8 *)key, (mDNSu16)keySize, (mDNSu8 *)value, (mDNSu16)valueSize);
534 mDNSPlatformMemFree(ptr);
535 return;
536 }
537 err = mDNS_Register(m, &ptr->ar);
538 if (err)
539 {
540 LogMsg("xD2DAddToCache: mDNS_Register returned error %d for %s", err, ARDisplayString(m, &ptr->ar));
541 mDNSPlatformMemFree(ptr);
542 return;
543 }
544
545 LogInfo("xD2DAddToCache: mDNS_Register succeeded for %s", ARDisplayString(m, &ptr->ar));
546 ptr->instanceHandle = instanceHandle;
547 ptr->transportType = transportType;
548 ptr->next = D2DRecords;
549 D2DRecords = ptr;
550 }
551 else
552 LogMsg("xD2DAddToCache: Unexpected result %d", result);
553 }
554
555 mDNSlocal D2DRecordListElem * xD2DFindInList(mDNS *const m, const Byte *const key, const size_t keySize, const Byte *const value, const size_t valueSize)
556 {
557 D2DRecordListElem *ptr = D2DRecords;
558 D2DRecordListElem *arptr;
559
560 if ( key == NULL || value == NULL || keySize == 0 || valueSize == 0) { LogMsg("xD2DFindInList: NULL Byte * passed in or length == 0"); return NULL; }
561
562 arptr = mDNSPlatformMemAllocate(sizeof(D2DRecordListElem) + (valueSize < sizeof(RData) ? 0 : valueSize - sizeof(RData)));
563 if (arptr == NULL) { LogMsg("xD2DFindInList: memory allocation failure"); return NULL; }
564
565 if (xD2DParse(m, (const mDNSu8 *const)key, (const mDNSu16)keySize, (const mDNSu8 *const)value, (const mDNSu16)valueSize, &arptr->ar) != mStatus_NoError)
566 {
567 LogMsg("xD2DFindInList: xD2DParse failed for key: %p (%u) value: %p (%u)", key, keySize, value, valueSize);
568 mDNSPlatformMemFree(arptr);
569 return NULL;
570 }
571
572 while (ptr)
573 {
574 if (IdenticalResourceRecord(&arptr->ar.resrec, &ptr->ar.resrec)) break;
575 ptr = ptr->next;
576 }
577
578 if (!ptr) LogMsg("xD2DFindInList: Could not find in D2DRecords: %s", ARDisplayString(m, &arptr->ar));
579 mDNSPlatformMemFree(arptr);
580 return ptr;
581 }
582
583 mDNSlocal void xD2DRemoveFromCache(mDNS *const m, D2DStatus result, D2DServiceInstance instanceHandle, D2DTransportType transportType, const Byte *key, size_t keySize, const Byte *value, size_t valueSize)
584 {
585 (void)transportType; // We don't care about this, yet.
586 (void)instanceHandle; // We don't care about this, yet.
587
588 if (result == kD2DSuccess)
589 {
590 D2DRecordListElem *ptr = xD2DFindInList(m, key, keySize, value, valueSize);
591 if (ptr)
592 {
593 LogInfo("xD2DRemoveFromCache: Remove from cache: %s", ARDisplayString(m, &ptr->ar));
594 mDNS_Deregister(m, &ptr->ar);
595 }
596 }
597 else
598 LogMsg("xD2DRemoveFromCache: Unexpected result %d", result);
599 }
600
601 mDNSlocal void xD2DServiceResolved(mDNS *const m, D2DStatus result, D2DServiceInstance instanceHandle, D2DTransportType transportType, const Byte *key, size_t keySize, const Byte *value, size_t valueSize)
602 {
603 (void)m;
604 (void)key;
605 (void)keySize;
606 (void)value;
607 (void)valueSize;
608
609 if (result == kD2DSuccess)
610 {
611 LogInfo("xD2DServiceResolved: Starting up PAN connection for %p", instanceHandle);
612 if (D2DRetain) D2DRetain(instanceHandle, transportType);
613 }
614 else LogMsg("xD2DServiceResolved: Unexpected result %d", result);
615 }
616
617 mDNSlocal void xD2DRetainHappened(mDNS *const m, D2DStatus result, D2DServiceInstance instanceHandle, D2DTransportType transportType, const Byte *key, size_t keySize, const Byte *value, size_t valueSize)
618 {
619 (void)m;
620 (void)instanceHandle;
621 (void)transportType;
622 (void)key;
623 (void)keySize;
624 (void)value;
625 (void)valueSize;
626
627 if (result == kD2DSuccess) LogInfo("xD2DRetainHappened: Opening up PAN connection for %p", instanceHandle);
628 else LogMsg("xD2DRetainHappened: Unexpected result %d", result);
629 }
630
631 mDNSlocal void xD2DReleaseHappened(mDNS *const m, D2DStatus result, D2DServiceInstance instanceHandle, D2DTransportType transportType, const Byte *key, size_t keySize, const Byte *value, size_t valueSize)
632 {
633 (void)m;
634 (void)instanceHandle;
635 (void)transportType;
636 (void)key;
637 (void)keySize;
638 (void)value;
639 (void)valueSize;
640
641 if (result == kD2DSuccess) LogInfo("xD2DReleaseHappened: Closing PAN connection for %p", instanceHandle);
642 else LogMsg("xD2DReleaseHappened: Unexpected result %d", result);
643 }
644
645 mDNSlocal void xD2DServiceCallback(D2DServiceEvent event, D2DStatus result, D2DServiceInstance instanceHandle, D2DTransportType transportType, const Byte *key, size_t keySize, const Byte *value, size_t valueSize, void *userData)
646 {
647 mDNS *m = (mDNS *) userData;
648 const char *eventString = "unknown";
649
650 KQueueLock(m);
651
652 if (keySize > 0xFFFF) LogMsg("xD2DServiceCallback: keySize too large: %u", keySize);
653 if (valueSize > 0xFFFF) LogMsg("xD2DServiceCallback: valueSize too large: %u", valueSize);
654
655 switch (event)
656 {
657 case D2DServiceFound:
658 eventString = "D2DServiceFound";
659 break;
660 case D2DServiceLost:
661 eventString = "D2DServiceLost";
662 break;
663 case D2DServiceResolved:
664 eventString = "D2DServiceResolved";
665 break;
666 case D2DServiceRetained:
667 eventString = "D2DServiceRetained";
668 break;
669 case D2DServiceReleased:
670 eventString = "D2DServiceReleased";
671 break;
672 default:
673 break;
674 }
675
676 LogInfo("xD2DServiceCallback: event=%s result=%d instanceHandle=%p transportType=%d LHS=%p (%u) RHS=%p (%u) userData=%p", eventString, result, instanceHandle, transportType, key, keySize, value, valueSize, userData);
677 PrintHelper(__func__, (mDNSu8 *)key, (mDNSu16)keySize, (mDNSu8 *)value, (mDNSu16)valueSize);
678
679 switch (event)
680 {
681 case D2DServiceFound:
682 xD2DAddToCache(m, result, instanceHandle, transportType, key, keySize, value, valueSize);
683 break;
684 case D2DServiceLost:
685 xD2DRemoveFromCache(m, result, instanceHandle, transportType, key, keySize, value, valueSize);
686 break;
687 case D2DServiceResolved:
688 xD2DServiceResolved(m, result, instanceHandle, transportType, key, keySize, value, valueSize);
689 break;
690 case D2DServiceRetained:
691 xD2DRetainHappened(m, result, instanceHandle, transportType, key, keySize, value, valueSize);
692 break;
693 case D2DServiceReleased:
694 xD2DReleaseHappened(m, result, instanceHandle, transportType, key, keySize, value, valueSize);
695 break;
696 default:
697 break;
698 }
699
700 // Need to tickle the main kqueue loop to potentially handle records we removed or added.
701 KQueueUnlock(m, "xD2DServiceCallback");
702 }
703
704 // Map interface index and flags to a specific D2D transport type or D2DTransportMax if all plugins
705 // should be called.
706 // When D2DTransportMax is returned, if a specific transport should not be called, *excludedTransportType
707 // will be set to the excluded transport value, otherwise, it will be set to D2DTransportMax.
708 // If the return value is not D2DTransportMax, excludedTransportType is undefined.
709
710 mDNSlocal D2DTransportType xD2DInterfaceToTransportType(mDNSInterfaceID InterfaceID, DNSServiceFlags flags, D2DTransportType * excludedTransportType)
711 {
712 NetworkInterfaceInfoOSX *info;
713
714 // Default exludes the D2DAWDLTransport when D2DTransportMax is returned.
715 *excludedTransportType = D2DAWDLTransport;
716
717 // Call all D2D plugins when both kDNSServiceFlagsIncludeP2P and kDNSServiceFlagsIncludeAWDL are set.
718 if ((flags & kDNSServiceFlagsIncludeP2P) && (flags & kDNSServiceFlagsIncludeAWDL))
719 {
720 LogInfo("xD2DInterfaceToTransportType: returning D2DTransportMax (including AWDL) since both kDNSServiceFlagsIncludeP2P and kDNSServiceFlagsIncludeAWDL are set");
721 *excludedTransportType = D2DTransportMax;
722 return D2DTransportMax;
723 }
724 // Call all D2D plugins (exlcluding AWDL) when only kDNSServiceFlagsIncludeP2P is set.
725 else if (flags & kDNSServiceFlagsIncludeP2P)
726 {
727 LogInfo("xD2DInterfaceToTransportType: returning D2DTransportMax (excluding AWDL) since only kDNSServiceFlagsIncludeP2P is set");
728 return D2DTransportMax;
729 }
730 // Call AWDL D2D plugin when only kDNSServiceFlagsIncludeAWDL is set.
731 else if (flags & kDNSServiceFlagsIncludeAWDL)
732 {
733 LogInfo("xD2DInterfaceToTransportType: returning D2DAWDLTransport since only kDNSServiceFlagsIncludeAWDL is set");
734 return D2DAWDLTransport;
735 }
736
737 if (InterfaceID == mDNSInterface_P2P)
738 {
739 LogInfo("xD2DInterfaceToTransportType: returning D2DTransportMax (excluding AWDL) for interface index mDNSInterface_P2P");
740 return D2DTransportMax;
741 }
742
743 // Compare to cached AWDL interface ID.
744 if (AWDLInterfaceID && (InterfaceID == AWDLInterfaceID))
745 {
746 LogInfo("xD2DInterfaceToTransportType: returning D2DAWDLTransport for interface index %d", InterfaceID);
747 return D2DAWDLTransport;
748 }
749
750 info = IfindexToInterfaceInfoOSX(&mDNSStorage, InterfaceID);
751 if (info == NULL)
752 {
753 LogInfo("xD2DInterfaceToTransportType: Invalid interface index %d", InterfaceID);
754 return D2DTransportMax;
755 }
756
757 // Recognize AirDrop specific p2p* interface based on interface name.
758 if (strncmp(info->ifinfo.ifname, "p2p", 3) == 0)
759 {
760 LogInfo("xD2DInterfaceToTransportType: returning D2DWifiPeerToPeerTransport for interface index %d", InterfaceID);
761 return D2DWifiPeerToPeerTransport;
762 }
763
764 // Currently there is no way to identify Bluetooth interface by name,
765 // since they use "en*" based name strings.
766
767 LogInfo("xD2DInterfaceToTransportType: returning default D2DTransportMax for interface index %d", InterfaceID);
768 return D2DTransportMax;
769 }
770
771 mDNSexport void external_start_browsing_for_service(mDNSInterfaceID InterfaceID, const domainname *const typeDomain, DNS_TypeValues qtype, DNSServiceFlags flags)
772 {
773 domainname lower;
774
775 if (qtype == kDNSServiceType_A || qtype == kDNSServiceType_AAAA)
776 {
777 LogInfo("external_start_browsing_for_service: ignoring address record");
778 return;
779 }
780
781 DomainnameToLower(typeDomain, &lower);
782
783 if (!D2DBrowseListRefCount(&lower, qtype))
784 {
785 D2DTransportType transportType, excludedTransport;
786
787 LogInfo("external_start_browsing_for_service: Starting browse for: %##s %s", lower.c, DNSTypeName(qtype));
788 mDNSu8 *end = DNSNameCompressionBuildLHS(&lower, qtype);
789 PrintHelper(__func__, compression_lhs, end - compression_lhs, mDNSNULL, 0);
790
791 transportType = xD2DInterfaceToTransportType(InterfaceID, flags, & excludedTransport);
792 if (transportType == D2DTransportMax)
793 {
794 D2DTransportType i;
795 for (i = 0; i < D2DTransportMax; i++)
796 {
797 if (i == excludedTransport) continue;
798 if (D2DStartBrowsingForKeyOnTransport) D2DStartBrowsingForKeyOnTransport(compression_lhs, end - compression_lhs, i);
799 }
800 }
801 else
802 {
803 if (D2DStartBrowsingForKeyOnTransport) D2DStartBrowsingForKeyOnTransport(compression_lhs, end - compression_lhs, transportType);
804 }
805 }
806 D2DBrowseListRetain(&lower, qtype);
807 }
808
809 mDNSexport void external_stop_browsing_for_service(mDNSInterfaceID InterfaceID, const domainname *const typeDomain, DNS_TypeValues qtype, DNSServiceFlags flags)
810 {
811 domainname lower;
812
813 if (qtype == kDNSServiceType_A || qtype == kDNSServiceType_AAAA)
814 {
815 LogInfo("external_stop_browsing_for_service: ignoring address record");
816 return;
817 }
818
819 DomainnameToLower(typeDomain, &lower);
820
821 D2DBrowseListRelease(&lower, qtype);
822 if (!D2DBrowseListRefCount(&lower, qtype))
823 {
824 D2DTransportType transportType, excludedTransport;
825
826 LogInfo("external_stop_browsing_for_service: Stopping browse for: %##s %s", lower.c, DNSTypeName(qtype));
827 mDNSu8 *end = DNSNameCompressionBuildLHS(&lower, qtype);
828 PrintHelper(__func__, compression_lhs, end - compression_lhs, mDNSNULL, 0);
829
830 transportType = xD2DInterfaceToTransportType(InterfaceID, flags, & excludedTransport);
831 if (transportType == D2DTransportMax)
832 {
833 D2DTransportType i;
834 for (i = 0; i < D2DTransportMax; i++)
835 {
836 if (i == excludedTransport) continue;
837 if (D2DStopBrowsingForKeyOnTransport) D2DStopBrowsingForKeyOnTransport(compression_lhs, end - compression_lhs, i);
838 }
839 }
840 else
841 {
842 if (D2DStopBrowsingForKeyOnTransport) D2DStopBrowsingForKeyOnTransport(compression_lhs, end - compression_lhs, transportType);
843 }
844
845 // The D2D driver may not generate the D2DServiceLost event for this key after
846 // the D2DStopBrowsingForKey*() call above. So, we flush the key from the D2D
847 // record cache now.
848 xD2DClearCache(&lower, qtype);
849 }
850 }
851
852 mDNSexport void external_start_advertising_service(const ResourceRecord *const resourceRecord, DNSServiceFlags flags)
853 {
854 domainname lower;
855 mDNSu8 *rhs = NULL;
856 mDNSu8 *end = NULL;
857 D2DTransportType transportType, excludedTransport;
858 DomainnameToLower(resourceRecord->name, &lower);
859
860 LogInfo("external_start_advertising_service: %s", RRDisplayString(&mDNSStorage, resourceRecord));
861 // For SRV records, update packet filter if p2p interface already exists, otherwise,
862 // if will be updated when we get the KEV_DL_IF_ATTACHED event for the interface.
863 if (resourceRecord->rrtype == kDNSType_SRV)
864 mDNSUpdatePacketFilter(NULL);
865
866 rhs = DNSNameCompressionBuildLHS(&lower, resourceRecord->rrtype);
867 end = DNSNameCompressionBuildRHS(rhs, resourceRecord);
868 PrintHelper(__func__, compression_lhs, rhs - compression_lhs, rhs, end - rhs);
869
870 transportType = xD2DInterfaceToTransportType(resourceRecord->InterfaceID, flags, & excludedTransport);
871 if (transportType == D2DTransportMax)
872 {
873 D2DTransportType i;
874 for (i = 0; i < D2DTransportMax; i++)
875 {
876 if (i == excludedTransport) continue;
877 if (D2DStartAdvertisingPairOnTransport) D2DStartAdvertisingPairOnTransport(compression_lhs, rhs - compression_lhs, rhs, end - rhs, i);
878 }
879 }
880 else
881 {
882 if (D2DStartAdvertisingPairOnTransport) D2DStartAdvertisingPairOnTransport(compression_lhs, rhs - compression_lhs, rhs, end - rhs, transportType);
883 }
884 }
885
886 mDNSexport void external_stop_advertising_service(const ResourceRecord *const resourceRecord, DNSServiceFlags flags)
887 {
888 domainname lower;
889 mDNSu8 *rhs = NULL;
890 mDNSu8 *end = NULL;
891 D2DTransportType transportType, excludedTransport;
892 DomainnameToLower(resourceRecord->name, &lower);
893
894 LogInfo("external_stop_advertising_service: %s", RRDisplayString(&mDNSStorage, resourceRecord));
895
896 // For SRV records, update packet filter to to remove this port from list
897 if (resourceRecord->rrtype == kDNSType_SRV)
898 mDNSUpdatePacketFilter(resourceRecord);
899
900 rhs = DNSNameCompressionBuildLHS(&lower, resourceRecord->rrtype);
901 end = DNSNameCompressionBuildRHS(rhs, resourceRecord);
902 PrintHelper(__func__, compression_lhs, rhs - compression_lhs, rhs, end - rhs);
903
904 transportType = xD2DInterfaceToTransportType(resourceRecord->InterfaceID, flags, & excludedTransport);
905 if (transportType == D2DTransportMax)
906 {
907 D2DTransportType i;
908 for (i = 0; i < D2DTransportMax; i++)
909 {
910 if (i == excludedTransport) continue;
911 if (D2DStopAdvertisingPairOnTransport) D2DStopAdvertisingPairOnTransport(compression_lhs, rhs - compression_lhs, rhs, end - rhs, i);
912 }
913 }
914 else
915 {
916 if (D2DStopAdvertisingPairOnTransport) D2DStopAdvertisingPairOnTransport(compression_lhs, rhs - compression_lhs, rhs, end - rhs, transportType);
917 }
918 }
919
920 mDNSexport void external_start_resolving_service(mDNSInterfaceID InterfaceID, const domainname *const fqdn, DNSServiceFlags flags)
921 {
922 domainname lower;
923 mDNSu8 *rhs = NULL;
924 mDNSu8 *end = NULL;
925 mDNSBool AWDL_used = false; // whether AWDL was used for this resolve
926 D2DTransportType transportType, excludedTransport;
927 DomainnameToLower(SkipLeadingLabels(fqdn, 1), &lower);
928
929 LogInfo("external_start_resolving_service: %##s", fqdn->c);
930 rhs = DNSNameCompressionBuildLHS(&lower, kDNSType_PTR);
931 end = putDomainNameAsLabels(&compression_base_msg, rhs, compression_limit, fqdn);
932 PrintHelper(__func__, compression_lhs, rhs - compression_lhs, rhs, end - rhs);
933
934 transportType = xD2DInterfaceToTransportType(InterfaceID, flags, & excludedTransport);
935 if (transportType == D2DTransportMax)
936 {
937 // Resolving over all the transports, except for excludedTransport if set.
938 D2DTransportType i;
939 for (i = 0; i < D2DTransportMax; i++)
940 {
941 if (i == excludedTransport) continue;
942 if (D2DStartResolvingPairOnTransport) D2DStartResolvingPairOnTransport(compression_lhs, rhs - compression_lhs, rhs, end - rhs, i);
943
944 if (i == D2DAWDLTransport)
945 AWDL_used = true;
946 }
947 }
948 else
949 {
950 // Resolving over one specific transport.
951 if (D2DStartResolvingPairOnTransport) D2DStartResolvingPairOnTransport(compression_lhs, rhs - compression_lhs, rhs, end - rhs, transportType);
952
953 if (transportType == D2DAWDLTransport)
954 AWDL_used = true;
955 }
956
957 // AWDL wants the SRV and TXT record queries communicated over the D2D interface.
958 // We only want these records going to AWDL, so use AWDLInterfaceID as the
959 // interface and don't set any other flags.
960 if (AWDL_used && AWDLInterfaceID)
961 {
962 LogInfo("external_start_resolving_service: browse for TXT and SRV over AWDL");
963 external_start_browsing_for_service(AWDLInterfaceID, fqdn, kDNSType_TXT, NULL);
964 external_start_browsing_for_service(AWDLInterfaceID, fqdn, kDNSType_SRV, NULL);
965 }
966 }
967
968 mDNSexport void external_stop_resolving_service(mDNSInterfaceID InterfaceID, const domainname *const fqdn, DNSServiceFlags flags)
969 {
970 domainname lower;
971 mDNSu8 *rhs = NULL;
972 mDNSu8 *end = NULL;
973 mDNSBool AWDL_used = false; // whether AWDL was used for this resolve
974 D2DTransportType transportType, excludedTransport;
975 DomainnameToLower(SkipLeadingLabels(fqdn, 1), &lower);
976
977 LogInfo("external_stop_resolving_service: %##s", fqdn->c);
978 rhs = DNSNameCompressionBuildLHS(&lower, kDNSType_PTR);
979 end = putDomainNameAsLabels(&compression_base_msg, rhs, compression_limit, fqdn);
980 PrintHelper(__func__, compression_lhs, rhs - compression_lhs, rhs, end - rhs);
981
982 transportType = xD2DInterfaceToTransportType(InterfaceID, flags, & excludedTransport);
983 if (transportType == D2DTransportMax)
984 {
985 D2DTransportType i;
986 for (i = 0; i < D2DTransportMax; i++)
987 {
988 if (i == excludedTransport) continue;
989 if (D2DStopResolvingPairOnTransport) D2DStopResolvingPairOnTransport(compression_lhs, rhs - compression_lhs, rhs, end - rhs, i);
990
991 if (i == D2DAWDLTransport)
992 AWDL_used = true;
993 }
994 }
995 else
996 {
997 if (D2DStopResolvingPairOnTransport) D2DStopResolvingPairOnTransport(compression_lhs, rhs - compression_lhs, rhs, end - rhs, transportType);
998
999 if (transportType == D2DAWDLTransport)
1000 AWDL_used = true;
1001 }
1002
1003 // AWDL wants the SRV and TXT record queries communicated over the D2D interface.
1004 // We only want these records going to AWDL, so use AWDLInterfaceID as the
1005 // interface and don't set any other flags.
1006 if (AWDL_used && AWDLInterfaceID)
1007 {
1008 LogInfo("external_stop_resolving_service: stop browse for TXT and SRV on AWDL");
1009 external_stop_browsing_for_service(AWDLInterfaceID, fqdn, kDNSType_TXT, NULL);
1010 external_stop_browsing_for_service(AWDLInterfaceID, fqdn, kDNSType_SRV, NULL);
1011 }
1012 }
1013
1014 #elif APPLE_OSX_mDNSResponder
1015
1016 mDNSexport void external_start_browsing_for_service(mDNS *const m, const domainname *const type, DNS_TypeValues qtype, DNSServiceFlags flags) { (void)m; (void)type; (void)qtype; (void)flags;}
1017 mDNSexport void external_stop_browsing_for_service(mDNS *const m, const domainname *const type, DNS_TypeValues qtype, DNSServiceFlags flags) { (void)m; (void)type; (void)qtype; (void)flags;}
1018 mDNSexport void external_start_advertising_service(const ResourceRecord *const resourceRecord, DNSServiceFlags flags) { (void)resourceRecord; (void)flags;}
1019 mDNSexport void external_stop_advertising_service(const ResourceRecord *const resourceRecord, DNSServiceFlags flags) { (void)resourceRecord; (void)flags;}
1020 mDNSexport void external_start_resolving_service(const domainname *const fqdn, DNSServiceFlags flags) { (void)fqdn; (void)flags;}
1021 mDNSexport void external_stop_resolving_service(const domainname *const fqdn, DNSServiceFlags flags) { (void)fqdn; (void)flags;}
1022
1023 #endif // ! NO_D2D
1024
1025 // ***************************************************************************
1026 // Functions
1027
1028 #if COMPILER_LIKES_PRAGMA_MARK
1029 #pragma mark -
1030 #pragma mark - Utility Functions
1031 #endif
1032
1033 // We only attempt to send and receive multicast packets on interfaces that are
1034 // (a) flagged as multicast-capable
1035 // (b) *not* flagged as point-to-point (e.g. modem)
1036 // Typically point-to-point interfaces are modems (including mobile-phone pseudo-modems), and we don't want
1037 // to run up the user's bill sending multicast traffic over a link where there's only a single device at the
1038 // other end, and that device (e.g. a modem bank) is probably not answering Multicast DNS queries anyway.
1039 #define MulticastInterface(i) (((i)->ifa_flags & IFF_MULTICAST) && !((i)->ifa_flags & IFF_POINTOPOINT))
1040
1041 mDNSexport void NotifyOfElusiveBug(const char *title, const char *msg) // Both strings are UTF-8 text
1042 {
1043 static int notifyCount = 0;
1044 if (notifyCount) return;
1045
1046 // If we display our alert early in the boot process, then it vanishes once the desktop appears.
1047 // To avoid this, we don't try to display alerts in the first three minutes after boot.
1048 if ((mDNSu32)(mDNSPlatformRawTime()) < (mDNSu32)(mDNSPlatformOneSecond * 180)) return;
1049
1050 // Unless ForceAlerts is defined, we only show these bug report alerts on machines that have a 17.x.x.x address
1051 #if !ForceAlerts
1052 {
1053 // Determine if we're at Apple (17.*.*.*)
1054 NetworkInterfaceInfoOSX *i;
1055 for (i = mDNSStorage.p->InterfaceList; i; i = i->next)
1056 if (i->ifinfo.ip.type == mDNSAddrType_IPv4 && i->ifinfo.ip.ip.v4.b[0] == 17)
1057 break;
1058 if (!i) return; // If not at Apple, don't show the alert
1059 }
1060 #endif
1061
1062 LogMsg("%s", title);
1063 LogMsg("%s", msg);
1064 // Display a notification to the user
1065 notifyCount++;
1066
1067 #ifndef NO_CFUSERNOTIFICATION
1068 mDNSNotify(title, msg);
1069 #endif /* NO_CFUSERNOTIFICATION */
1070 }
1071
1072 // Returns true if it is an AppleTV based hardware running iOS, false otherwise
1073 mDNSlocal mDNSBool IsAppleTV(void)
1074 {
1075 #if TARGET_OS_EMBEDDED
1076 static mDNSBool sInitialized = mDNSfalse;
1077 static mDNSBool sIsAppleTV = mDNSfalse;
1078 CFStringRef deviceClass = NULL;
1079
1080 if(!sInitialized)
1081 {
1082 deviceClass = (CFStringRef) MGCopyAnswer(kMGQDeviceClass, NULL);
1083 if(deviceClass)
1084 {
1085 if(CFEqual(deviceClass, kMGDeviceClassAppleTV))
1086 sIsAppleTV = mDNStrue;
1087 CFRelease(deviceClass);
1088 }
1089 sInitialized = mDNStrue;
1090 }
1091 return(sIsAppleTV);
1092 #else
1093 return mDNSfalse;
1094 #endif // TARGET_OS_EMBEDDED
1095 }
1096
1097 mDNSlocal struct ifaddrs *myGetIfAddrs(int refresh)
1098 {
1099 static struct ifaddrs *ifa = NULL;
1100
1101 if (refresh && ifa)
1102 {
1103 freeifaddrs(ifa);
1104 ifa = NULL;
1105 }
1106
1107 if (ifa == NULL)
1108 getifaddrs(&ifa);
1109 return ifa;
1110 }
1111
1112 mDNSlocal void DynamicStoreWrite(int key, const char* subkey, uintptr_t value, signed long valueCnt)
1113 {
1114 CFStringRef sckey = NULL;
1115 Boolean release_sckey = FALSE;
1116 CFDataRef bytes = NULL;
1117 CFPropertyListRef plist = NULL;
1118 SCDynamicStoreRef store = NULL;
1119
1120 switch ((enum mDNSDynamicStoreSetConfigKey)key)
1121 {
1122 case kmDNSMulticastConfig:
1123 sckey = CFSTR("State:/Network/" kDNSServiceCompMulticastDNS);
1124 break;
1125 case kmDNSDynamicConfig:
1126 sckey = CFSTR("State:/Network/DynamicDNS");
1127 break;
1128 case kmDNSPrivateConfig:
1129 sckey = CFSTR("State:/Network/" kDNSServiceCompPrivateDNS);
1130 break;
1131 case kmDNSBackToMyMacConfig:
1132 sckey = CFSTR("State:/Network/BackToMyMac");
1133 break;
1134 case kmDNSSleepProxyServersState:
1135 {
1136 CFMutableStringRef tmp = CFStringCreateMutable(kCFAllocatorDefault, 0);
1137 CFStringAppend(tmp, CFSTR("State:/Network/Interface/"));
1138 CFStringAppendCString(tmp, subkey, kCFStringEncodingUTF8);
1139 CFStringAppend(tmp, CFSTR("/SleepProxyServers"));
1140 sckey = CFStringCreateCopy(kCFAllocatorDefault, tmp);
1141 release_sckey = TRUE;
1142 CFRelease(tmp);
1143 break;
1144 }
1145 case kmDNSDebugState:
1146 sckey = CFSTR("State:/Network/mDNSResponder/DebugState");
1147 break;
1148 default:
1149 LogMsg("unrecognized key %d", key);
1150 goto fin;
1151 }
1152 if (NULL == (bytes = CFDataCreateWithBytesNoCopy(NULL, (void *)value,
1153 valueCnt, kCFAllocatorNull)))
1154 {
1155 LogMsg("CFDataCreateWithBytesNoCopy of value failed");
1156 goto fin;
1157 }
1158 if (NULL == (plist = CFPropertyListCreateFromXMLData(NULL, bytes,
1159 kCFPropertyListImmutable, NULL)))
1160 {
1161 LogMsg("CFPropertyListCreateFromXMLData of bytes failed");
1162 goto fin;
1163 }
1164 CFRelease(bytes);
1165 bytes = NULL;
1166 if (NULL == (store = SCDynamicStoreCreate(NULL,
1167 CFSTR(kmDNSResponderServName), NULL, NULL)))
1168 {
1169 LogMsg("SCDynamicStoreCreate failed: %s", SCErrorString(SCError()));
1170 goto fin;
1171 }
1172 SCDynamicStoreSetValue(store, sckey, plist);
1173
1174 fin:
1175 if (NULL != bytes)
1176 CFRelease(bytes);
1177 if (NULL != plist)
1178 CFRelease(plist);
1179 if (NULL != store)
1180 CFRelease(store);
1181 if (release_sckey && sckey)
1182 CFRelease(sckey);
1183 }
1184
1185 mDNSexport void mDNSDynamicStoreSetConfig(int key, const char *subkey, CFPropertyListRef value)
1186 {
1187 CFPropertyListRef valueCopy;
1188 char *subkeyCopy = NULL;
1189 if (!value)
1190 return;
1191
1192 // We need to copy the key and value before we dispatch off the block below as the
1193 // caller will free the memory once we return from this function.
1194 valueCopy = CFPropertyListCreateDeepCopy(NULL, value, kCFPropertyListImmutable);
1195 if (!valueCopy)
1196 {
1197 LogMsg("mDNSDynamicStoreSetConfig: ERROR valueCopy NULL");
1198 return;
1199 }
1200 if (subkey)
1201 {
1202 int len = strlen(subkey);
1203 subkeyCopy = mDNSPlatformMemAllocate(len + 1);
1204 if (!subkeyCopy)
1205 {
1206 LogMsg("mDNSDynamicStoreSetConfig: ERROR subkeyCopy NULL");
1207 return;
1208 }
1209 mDNSPlatformMemCopy(subkeyCopy, subkey, len);
1210 subkeyCopy[len] = 0;
1211 }
1212
1213 dispatch_async(DynamicStoreQueue, ^{
1214 CFWriteStreamRef stream = NULL;
1215 CFDataRef bytes = NULL;
1216 CFStringRef error;
1217 CFIndex ret;
1218
1219 if (NULL == (stream = CFWriteStreamCreateWithAllocatedBuffers(NULL, NULL)))
1220 {
1221 LogMsg("mDNSDynamicStoreSetConfig : CFWriteStreamCreateWithAllocatedBuffers failed (Object creation failed)");
1222 goto END;
1223 }
1224 CFWriteStreamOpen(stream);
1225 ret = CFPropertyListWriteToStream(valueCopy, stream, kCFPropertyListBinaryFormat_v1_0, &error);
1226 if (ret == 0)
1227 {
1228 LogMsg("mDNSDynamicStoreSetConfig : CFPropertyListWriteToStream failed (Could not write property list to stream)");
1229 goto END;
1230 }
1231 if (NULL == (bytes = CFWriteStreamCopyProperty(stream, kCFStreamPropertyDataWritten)))
1232 {
1233 LogMsg("mDNSDynamicStoreSetConfig : CFWriteStreamCopyProperty failed (Object creation failed) ");
1234 goto END;
1235 }
1236 CFWriteStreamClose(stream);
1237 CFRelease(stream);
1238 stream = NULL;
1239 LogInfo("mDNSDynamicStoreSetConfig: key %d subkey %s", key, subkeyCopy);
1240 DynamicStoreWrite(key, subkeyCopy ? subkeyCopy : "", (uintptr_t)CFDataGetBytePtr(bytes), CFDataGetLength(bytes));
1241
1242 END:
1243 CFRelease(valueCopy);
1244 if (NULL != stream)
1245 {
1246 CFWriteStreamClose(stream);
1247 CFRelease(stream);
1248 }
1249 if (NULL != bytes)
1250 CFRelease(bytes);
1251 if (subkeyCopy)
1252 mDNSPlatformMemFree(subkeyCopy);
1253 });
1254 }
1255
1256 // To match *either* a v4 or v6 instance of this interface name, pass AF_UNSPEC for type
1257 mDNSlocal NetworkInterfaceInfoOSX *SearchForInterfaceByName(mDNS *const m, const char *ifname, int type)
1258 {
1259 NetworkInterfaceInfoOSX *i;
1260 for (i = m->p->InterfaceList; i; i = i->next)
1261 if (i->Exists && !strcmp(i->ifinfo.ifname, ifname) &&
1262 ((type == AF_UNSPEC ) ||
1263 (type == AF_INET && i->ifinfo.ip.type == mDNSAddrType_IPv4) ||
1264 (type == AF_INET6 && i->ifinfo.ip.type == mDNSAddrType_IPv6))) return(i);
1265 return(NULL);
1266 }
1267
1268 #if TARGET_OS_EMBEDDED
1269 mDNSlocal SCPreferencesRef mDNSManagedPrefsGet(void)
1270 {
1271 SCPreferencesRef smDNSManagedPrefs = NULL;
1272 smDNSManagedPrefs = SCPreferencesCreate(kCFAllocatorDefault, CFSTR("mDNSManagedPrefs"), kmDNSResponderManagedPrefsID);
1273
1274 return (smDNSManagedPrefs);
1275 }
1276
1277 mDNSlocal mDNSBool GetmDNSManagedPrefKeyVal(SCPreferencesRef prefs, CFStringRef key)
1278 {
1279 mDNSBool val = mDNSfalse;
1280 CFBooleanRef val_cf = NULL;
1281
1282 if (prefs != NULL)
1283 {
1284 val_cf = SCPreferencesGetValue(prefs, key);
1285 if (isA_CFBoolean(val_cf) != NULL)
1286 val = CFBooleanGetValue(val_cf); //When mDNSResponder-Debug-profile is Installed
1287 else
1288 val = mDNSfalse; //When mDNSResponder-Debug-profile is Uninstalled
1289 }
1290 else
1291 {
1292 LogMsg("GetmDNSManagedPrefKeyVal: mDNSManagedPrefs are NULL!");
1293 val = mDNSfalse;
1294 }
1295 if (val_cf)
1296 CFRelease(val_cf);
1297 return (val);
1298 }
1299
1300 mDNSexport mDNSBool GetmDNSManagedPref(CFStringRef key)
1301 {
1302 SCPreferencesRef managed = NULL;
1303 mDNSBool ret_value;
1304
1305 managed = mDNSManagedPrefsGet();
1306 ret_value = GetmDNSManagedPrefKeyVal(managed, key);
1307
1308 if (managed)
1309 CFRelease(managed);
1310 return (ret_value);
1311 }
1312 #endif //TARGET_OS_EMBEDDED
1313
1314 mDNSlocal int myIfIndexToName(u_short ifindex, char *name)
1315 {
1316 struct ifaddrs *ifa;
1317 for (ifa = myGetIfAddrs(0); ifa; ifa = ifa->ifa_next)
1318 if (ifa->ifa_addr->sa_family == AF_LINK)
1319 if (((struct sockaddr_dl*)ifa->ifa_addr)->sdl_index == ifindex)
1320 { strlcpy(name, ifa->ifa_name, IF_NAMESIZE); return 0; }
1321 return -1;
1322 }
1323
1324 mDNSexport NetworkInterfaceInfoOSX *IfindexToInterfaceInfoOSX(const mDNS *const m, mDNSInterfaceID ifindex)
1325 {
1326 mDNSu32 scope_id = (mDNSu32)(uintptr_t)ifindex;
1327 NetworkInterfaceInfoOSX *i;
1328
1329 // Don't get tricked by inactive interfaces
1330 for (i = m->p->InterfaceList; i; i = i->next)
1331 if (i->Registered && i->scope_id == scope_id) return(i);
1332
1333 return mDNSNULL;
1334 }
1335
1336 mDNSexport mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 ifindex)
1337 {
1338 if (ifindex == kDNSServiceInterfaceIndexLocalOnly) return(mDNSInterface_LocalOnly);
1339 if (ifindex == kDNSServiceInterfaceIndexP2P ) return(mDNSInterface_P2P);
1340 if (ifindex == kDNSServiceInterfaceIndexAny ) return(mDNSNULL);
1341
1342 NetworkInterfaceInfoOSX* ifi = IfindexToInterfaceInfoOSX(m, (mDNSInterfaceID)(uintptr_t)ifindex);
1343 if (!ifi)
1344 {
1345 // Not found. Make sure our interface list is up to date, then try again.
1346 LogInfo("mDNSPlatformInterfaceIDfromInterfaceIndex: InterfaceID for interface index %d not found; Updating interface list", ifindex);
1347 mDNSMacOSXNetworkChanged(m);
1348 ifi = IfindexToInterfaceInfoOSX(m, (mDNSInterfaceID)(uintptr_t)ifindex);
1349 }
1350
1351 if (!ifi) return(mDNSNULL);
1352
1353 return(ifi->ifinfo.InterfaceID);
1354 }
1355
1356
1357 mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange)
1358 {
1359 NetworkInterfaceInfoOSX *i;
1360 if (id == mDNSInterface_LocalOnly) return(kDNSServiceInterfaceIndexLocalOnly);
1361 if (id == mDNSInterface_P2P ) return(kDNSServiceInterfaceIndexP2P);
1362 if (id == mDNSInterface_Any ) return(0);
1363
1364 mDNSu32 scope_id = (mDNSu32)(uintptr_t)id;
1365
1366 // Don't use i->Registered here, because we DO want to find inactive interfaces, which have no Registered set
1367 for (i = m->p->InterfaceList; i; i = i->next)
1368 if (i->scope_id == scope_id) return(i->scope_id);
1369
1370 // If we are supposed to suppress network change, return "id" back
1371 if (suppressNetworkChange) return scope_id;
1372
1373 // Not found. Make sure our interface list is up to date, then try again.
1374 LogInfo("Interface index for InterfaceID %p not found; Updating interface list", id);
1375 mDNSMacOSXNetworkChanged(m);
1376 for (i = m->p->InterfaceList; i; i = i->next)
1377 if (i->scope_id == scope_id) return(i->scope_id);
1378
1379 return(0);
1380 }
1381
1382 #if APPLE_OSX_mDNSResponder
1383 mDNSexport void mDNSASLLog(uuid_t *uuid, const char *subdomain, const char *result, const char *signature, const char *fmt, ...)
1384 {
1385 if (iOSVers)
1386 return; // No ASL on iOS
1387
1388 static char buffer[512];
1389 aslmsg asl_msg = asl_new(ASL_TYPE_MSG);
1390
1391 if (!asl_msg) { LogMsg("mDNSASLLog: asl_new failed"); return; }
1392 if (uuid)
1393 {
1394 char uuidStr[37];
1395 uuid_unparse(*uuid, uuidStr);
1396 asl_set (asl_msg, "com.apple.message.uuid", uuidStr);
1397 }
1398
1399 static char domainBase[] = "com.apple.mDNSResponder.%s";
1400 mDNS_snprintf (buffer, sizeof(buffer), domainBase, subdomain);
1401 asl_set (asl_msg, "com.apple.message.domain", buffer);
1402
1403 if (result) asl_set(asl_msg, "com.apple.message.result", result);
1404 if (signature) asl_set(asl_msg, "com.apple.message.signature", signature);
1405
1406 va_list ptr;
1407 va_start(ptr,fmt);
1408 mDNS_vsnprintf(buffer, sizeof(buffer), fmt, ptr);
1409 va_end(ptr);
1410
1411 int old_filter = asl_set_filter(NULL,ASL_FILTER_MASK_UPTO(ASL_LEVEL_DEBUG));
1412 asl_log(NULL, asl_msg, ASL_LEVEL_DEBUG, "%s", buffer);
1413 asl_set_filter(NULL, old_filter);
1414 asl_free(asl_msg);
1415 }
1416
1417
1418 mDNSlocal void mDNSLogDNSSECStatistics(mDNS *const m)
1419 {
1420 char buffer[16];
1421
1422 aslmsg aslmsg = asl_new(ASL_TYPE_MSG);
1423
1424 // If we failed to allocate an aslmsg structure, keep accumulating
1425 // the statistics and try again at the next log interval.
1426 if (!aslmsg)
1427 {
1428 LogMsg("mDNSLogDNSSECStatistics: asl_new() failed!");
1429 return;
1430 }
1431
1432 asl_set(aslmsg,"com.apple.message.domain", "com.apple.mDNSResponder.DNSSECstatistics");
1433
1434 if (m->rrcache_totalused_unicast)
1435 {
1436 mDNS_snprintf(buffer, sizeof(buffer), "%u", (mDNSu32) ((unsigned long)(m->DNSSECStats.TotalMemUsed * 100))/m->rrcache_totalused_unicast);
1437 }
1438 else
1439 {
1440 LogMsg("mDNSLogDNSSECStatistics: unicast is zero");
1441 buffer[0] = 0;
1442 }
1443 asl_set(aslmsg,"com.apple.message.MemUsage", buffer);
1444
1445 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.Latency0);
1446 asl_set(aslmsg,"com.apple.message.Latency0", buffer);
1447 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.Latency10);
1448 asl_set(aslmsg,"com.apple.message.Latency10", buffer);
1449 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.Latency20);
1450 asl_set(aslmsg,"com.apple.message.Latency20", buffer);
1451 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.Latency50);
1452 asl_set(aslmsg,"com.apple.message.Latency50", buffer);
1453 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.Latency100);
1454 asl_set(aslmsg,"com.apple.message.Latency100", buffer);
1455
1456 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.ExtraPackets0);
1457 asl_set(aslmsg,"com.apple.message.ExtraPackets0", buffer);
1458 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.ExtraPackets3);
1459 asl_set(aslmsg,"com.apple.message.ExtraPackets3", buffer);
1460 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.ExtraPackets7);
1461 asl_set(aslmsg,"com.apple.message.ExtraPackets7", buffer);
1462 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.ExtraPackets10);
1463 asl_set(aslmsg,"com.apple.message.ExtraPackets10", buffer);
1464
1465 // Ignore IndeterminateStatus as we don't log them
1466 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.SecureStatus);
1467 asl_set(aslmsg,"com.apple.message.SecureStatus", buffer);
1468 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.InsecureStatus);
1469 asl_set(aslmsg,"com.apple.message.InsecureStatus", buffer);
1470 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.BogusStatus);
1471 asl_set(aslmsg,"com.apple.message.BogusStatus", buffer);
1472 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.NoResponseStatus);
1473 asl_set(aslmsg,"com.apple.message.NoResponseStatus", buffer);
1474
1475 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.NumProbesSent);
1476 asl_set(aslmsg,"com.apple.message.NumProbesSent", buffer);
1477 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.MsgSize0);
1478 asl_set(aslmsg,"com.apple.message.MsgSize0", buffer);
1479 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.MsgSize1);
1480 asl_set(aslmsg,"com.apple.message.MsgSize1", buffer);
1481 mDNS_snprintf(buffer, sizeof(buffer), "%u", m->DNSSECStats.MsgSize2);
1482 asl_set(aslmsg,"com.apple.message.MsgSize2", buffer);
1483
1484 asl_log(NULL, aslmsg, ASL_LEVEL_NOTICE, "");
1485 asl_free(aslmsg);
1486 }
1487
1488 // Calculate packets per hour given total packet count and interval in seconds.
1489 // Cast one term of multiplication to (long) to use 64-bit arithmetic
1490 // and avoid a potential 32-bit overflow prior to the division.
1491 #define ONE_HOUR 3600
1492 #define PACKET_RATE(PACKETS, INTERVAL) (int)(((long) (PACKETS) * ONE_HOUR)/(INTERVAL))
1493
1494 // Put packet rate data in discrete buckets.
1495 mDNSlocal int mDNSBucketData(int inputData, int interval)
1496 {
1497 if (!interval)
1498 {
1499 LogMsg("mDNSBucketData: interval is zero!");
1500 return 0;
1501 }
1502
1503 int ratePerHour = PACKET_RATE(inputData, interval);
1504 int bucket;
1505
1506 if (ratePerHour == 0)
1507 bucket = 0;
1508 else if (ratePerHour <= 10)
1509 bucket = 10;
1510 else if (ratePerHour <= 100)
1511 bucket = 100;
1512 else if (ratePerHour <= 1000)
1513 bucket = 1000;
1514 else if (ratePerHour <= 5000)
1515 bucket = 5000;
1516 else if (ratePerHour <= 10000)
1517 bucket = 10000;
1518 else if (ratePerHour <= 50000)
1519 bucket = 50000;
1520 else if (ratePerHour <= 100000)
1521 bucket = 100000;
1522 else if (ratePerHour <= 250000)
1523 bucket = 250000;
1524 else if (ratePerHour <= 500000)
1525 bucket = 500000;
1526 else
1527 bucket = 1000000;
1528
1529 return bucket;
1530 }
1531
1532 mDNSlocal void mDNSLogBonjourStatistics(mDNS *const m)
1533 {
1534 static mDNSs32 last_PktNum, last_MPktNum;
1535 static mDNSs32 last_UnicastPacketsSent, last_MulticastPacketsSent;
1536 static mDNSs32 last_RemoteSubnet;
1537
1538 mDNSs32 interval;
1539 char buffer[16];
1540 mDNSs32 inMulticast = m->MPktNum - last_MPktNum;
1541 mDNSs32 inUnicast = m->PktNum - last_PktNum - inMulticast;
1542 mDNSs32 outUnicast = m->UnicastPacketsSent - last_UnicastPacketsSent;
1543 mDNSs32 outMulticast = m->MulticastPacketsSent - last_MulticastPacketsSent;
1544 mDNSs32 remoteSubnet = m->RemoteSubnet - last_RemoteSubnet;
1545
1546
1547 // save starting values for new interval
1548 last_PktNum = m->PktNum;
1549 last_MPktNum = m->MPktNum;
1550 last_UnicastPacketsSent = m->UnicastPacketsSent;
1551 last_MulticastPacketsSent = m->MulticastPacketsSent;
1552 last_RemoteSubnet = m->RemoteSubnet;
1553
1554 // Need a non-zero active time interval.
1555 if (!m->ActiveStatTime)
1556 return;
1557
1558 // Round interval time to nearest hour boundary. Less then 30 minutes rounds to zero.
1559 interval = (m->ActiveStatTime + ONE_HOUR/2)/ONE_HOUR;
1560
1561 // Use a minimum of 30 minutes of awake time to calculate average packet rates.
1562 // The rounded awake interval should not be greater than the rounded reporting
1563 // interval.
1564 if ((interval == 0) || (interval > (kDefaultNextStatsticsLogTime + ONE_HOUR/2)/ONE_HOUR))
1565 return;
1566
1567 aslmsg aslmsg = asl_new(ASL_TYPE_MSG);
1568
1569 if (!aslmsg)
1570 {
1571 LogMsg("mDNSLogBonjourStatistics: asl_new() failed!");
1572 return;
1573 }
1574 // log in MessageTracer format
1575 asl_set(aslmsg,"com.apple.message.domain", "com.apple.mDNSResponder.statistics");
1576
1577 snprintf(buffer, sizeof(buffer), "%d", interval);
1578 asl_set(aslmsg,"com.apple.message.interval", buffer);
1579
1580 // log the packet rates as packets per hour
1581 snprintf(buffer, sizeof(buffer), "%d",
1582 mDNSBucketData(inUnicast, m->ActiveStatTime));
1583 asl_set(aslmsg,"com.apple.message.UnicastIn", buffer);
1584
1585 snprintf(buffer, sizeof(buffer), "%d",
1586 mDNSBucketData(inMulticast, m->ActiveStatTime));
1587 asl_set(aslmsg,"com.apple.message.MulticastIn", buffer);
1588
1589 snprintf(buffer, sizeof(buffer), "%d",
1590 mDNSBucketData(outUnicast, m->ActiveStatTime));
1591 asl_set(aslmsg,"com.apple.message.UnicastOut", buffer);
1592
1593 snprintf(buffer, sizeof(buffer), "%d",
1594 mDNSBucketData(outMulticast, m->ActiveStatTime));
1595 asl_set(aslmsg,"com.apple.message.MulticastOut", buffer);
1596
1597 snprintf(buffer, sizeof(buffer), "%d",
1598 mDNSBucketData(remoteSubnet, m->ActiveStatTime));
1599 asl_set(aslmsg,"com.apple.message.RemoteSubnet", buffer);
1600
1601 asl_log(NULL, aslmsg, ASL_LEVEL_NOTICE, "");
1602
1603 asl_free(aslmsg);
1604 }
1605
1606 // Log multicast and unicast traffic statistics to MessageTracer on OSX
1607 mDNSexport void mDNSLogStatistics(mDNS *const m)
1608 {
1609 // MessageTracer only available on OSX
1610 if (iOSVers)
1611 return;
1612
1613 mDNSs32 currentUTC = mDNSPlatformUTC();
1614
1615 // log runtime statistics
1616 if ((currentUTC - m->NextStatLogTime) >= 0)
1617 {
1618 m->NextStatLogTime = currentUTC + kDefaultNextStatsticsLogTime;
1619 // If StatStartTime is zero, it hasn't been reinitialized yet
1620 // in the wakeup code path.
1621 if (m->StatStartTime)
1622 {
1623 m->ActiveStatTime += currentUTC - m->StatStartTime;
1624 }
1625
1626 // Only log statistics if we have recorded some active time during
1627 // this statistics interval.
1628 if (m->ActiveStatTime)
1629 {
1630 mDNSLogBonjourStatistics(m);
1631 mDNSLogDNSSECStatistics(m);
1632 }
1633
1634 // Start a new statistics gathering interval.
1635 m->StatStartTime = currentUTC;
1636 m->ActiveStatTime = 0;
1637 }
1638 }
1639
1640 #endif // APPLE_OSX_mDNSResponder
1641
1642 #if COMPILER_LIKES_PRAGMA_MARK
1643 #pragma mark -
1644 #pragma mark - UDP & TCP send & receive
1645 #endif
1646
1647 mDNSlocal mDNSBool AddrRequiresPPPConnection(const struct sockaddr *addr)
1648 {
1649 mDNSBool result = mDNSfalse;
1650 SCNetworkConnectionFlags flags;
1651 CFDataRef remote_addr;
1652 CFMutableDictionaryRef options;
1653 SCNetworkReachabilityRef ReachRef = NULL;
1654
1655 options = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1656 remote_addr = CFDataCreate(NULL, (const UInt8 *)addr, addr->sa_len);
1657 CFDictionarySetValue(options, kSCNetworkReachabilityOptionRemoteAddress, remote_addr);
1658 CFDictionarySetValue(options, kSCNetworkReachabilityOptionServerBypass, kCFBooleanTrue);
1659 ReachRef = SCNetworkReachabilityCreateWithOptions(kCFAllocatorDefault, options);
1660 CFRelease(options);
1661 CFRelease(remote_addr);
1662
1663 if (!ReachRef)
1664 {
1665 LogMsg("ERROR: RequiresConnection - SCNetworkReachabilityCreateWithOptions");
1666 goto end;
1667 }
1668 if (!SCNetworkReachabilityGetFlags(ReachRef, &flags))
1669 {
1670 LogMsg("ERROR: AddrRequiresPPPConnection - SCNetworkReachabilityGetFlags");
1671 goto end;
1672 }
1673 result = flags & kSCNetworkFlagsConnectionRequired;
1674
1675 end:
1676 if (ReachRef)
1677 CFRelease(ReachRef);
1678 return result;
1679 }
1680
1681 // Set traffic class for socket
1682 mDNSlocal void setTrafficClass(int socketfd, mDNSBool useBackgroundTrafficClass)
1683 {
1684 int traffic_class;
1685
1686 if (useBackgroundTrafficClass)
1687 traffic_class = SO_TC_BK_SYS;
1688 else
1689 traffic_class = SO_TC_CTL;
1690
1691 (void) setsockopt(socketfd, SOL_SOCKET, SO_TRAFFIC_CLASS, (void *)&traffic_class, sizeof(traffic_class));
1692 }
1693
1694 mDNSexport void mDNSPlatformSetDelegatePID(UDPSocket *src, const mDNSAddr *dst, DNSQuestion *q)
1695 {
1696 if (src)
1697 {
1698 int s;
1699
1700 if (dst->type == mDNSAddrType_IPv4)
1701 {
1702 s = src->ss.sktv4;
1703 }
1704 else
1705 {
1706 s = src->ss.sktv6;
1707 }
1708
1709 if (q->pid)
1710 {
1711 if (setsockopt(s, SOL_SOCKET, SO_DELEGATED, &q->pid, sizeof(q->pid)) == -1)
1712 {
1713 LogInfo("mDNSPlatformSetDelegatePID: Delegate PID failed %s for PID %d", strerror(errno), q->pid);
1714 }
1715 }
1716 else
1717 {
1718 if (setsockopt(s, SOL_SOCKET, SO_DELEGATED_UUID, &q->uuid, sizeof(q->uuid)) == -1)
1719 {
1720 LogInfo("mDNSPlatformSetDelegatePID: Delegate UUID failed %s", strerror(errno));
1721 }
1722 }
1723 }
1724 }
1725
1726 // Note: If InterfaceID is NULL, it means, "send this packet through our anonymous unicast socket"
1727 // Note: If InterfaceID is non-NULL it means, "send this packet through our port 5353 socket on the specified interface"
1728 // OR send via our primary v4 unicast socket
1729 // UPDATE: The UDPSocket *src parameter now allows the caller to specify the source socket
1730 mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
1731 mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
1732 mDNSIPPort dstPort, mDNSBool useBackgroundTrafficClass)
1733 {
1734 NetworkInterfaceInfoOSX *info = mDNSNULL;
1735 struct sockaddr_storage to;
1736 int s = -1, err;
1737 mStatus result = mStatus_NoError;
1738
1739 if (InterfaceID)
1740 {
1741 info = IfindexToInterfaceInfoOSX(m, InterfaceID);
1742 if (info == NULL)
1743 {
1744 // We may not have registered interfaces with the "core" as we may not have
1745 // seen any interface notifications yet. This typically happens during wakeup
1746 // where we might try to send DNS requests (non-SuppressUnusable questions internal
1747 // to mDNSResponder) before we receive network notifications.
1748 LogInfo("mDNSPlatformSendUDP: Invalid interface index %p", InterfaceID);
1749 return mStatus_BadParamErr;
1750 }
1751 }
1752
1753 char *ifa_name = InterfaceID ? info->ifinfo.ifname : "unicast";
1754
1755 if (dst->type == mDNSAddrType_IPv4)
1756 {
1757 struct sockaddr_in *sin_to = (struct sockaddr_in*)&to;
1758 sin_to->sin_len = sizeof(*sin_to);
1759 sin_to->sin_family = AF_INET;
1760 sin_to->sin_port = dstPort.NotAnInteger;
1761 sin_to->sin_addr.s_addr = dst->ip.v4.NotAnInteger;
1762 s = (src ? src->ss : m->p->permanentsockets).sktv4;
1763
1764 if (info) // Specify outgoing interface
1765 {
1766 if (!mDNSAddrIsDNSMulticast(dst))
1767 {
1768 #ifdef IP_BOUND_IF
1769 if (info->scope_id == 0)
1770 LogInfo("IP_BOUND_IF socket option not set -- info %p (%s) scope_id is zero", info, ifa_name);
1771 else
1772 setsockopt(s, IPPROTO_IP, IP_BOUND_IF, &info->scope_id, sizeof(info->scope_id));
1773 #else
1774 {
1775 static int displayed = 0;
1776 if (displayed < 1000)
1777 {
1778 displayed++;
1779 LogInfo("IP_BOUND_IF socket option not defined -- cannot specify interface for unicast packets");
1780 }
1781 }
1782 #endif
1783 }
1784 else
1785 #ifdef IP_MULTICAST_IFINDEX
1786 {
1787 err = setsockopt(s, IPPROTO_IP, IP_MULTICAST_IFINDEX, &info->scope_id, sizeof(info->scope_id));
1788 // We get an error when we compile on a machine that supports this option and run the binary on
1789 // a different machine that does not support it
1790 if (err < 0)
1791 {
1792 if (errno != ENOPROTOOPT) LogInfo("mDNSPlatformSendUDP: setsockopt: IP_MUTLTICAST_IFINDEX returned %d", errno);
1793 err = setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &info->ifa_v4addr, sizeof(info->ifa_v4addr));
1794 if (err < 0 && !m->p->NetworkChanged)
1795 LogMsg("setsockopt - IP_MULTICAST_IF error %.4a %d errno %d (%s)", &info->ifa_v4addr, err, errno, strerror(errno));
1796 }
1797 }
1798 #else
1799 {
1800 err = setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &info->ifa_v4addr, sizeof(info->ifa_v4addr));
1801 if (err < 0 && !m->p->NetworkChanged)
1802 LogMsg("setsockopt - IP_MULTICAST_IF error %.4a %d errno %d (%s)", &info->ifa_v4addr, err, errno, strerror(errno));
1803
1804 }
1805 #endif
1806 }
1807 }
1808
1809 else if (dst->type == mDNSAddrType_IPv6)
1810 {
1811 struct sockaddr_in6 *sin6_to = (struct sockaddr_in6*)&to;
1812 sin6_to->sin6_len = sizeof(*sin6_to);
1813 sin6_to->sin6_family = AF_INET6;
1814 sin6_to->sin6_port = dstPort.NotAnInteger;
1815 sin6_to->sin6_flowinfo = 0;
1816 sin6_to->sin6_addr = *(struct in6_addr*)&dst->ip.v6;
1817 sin6_to->sin6_scope_id = info ? info->scope_id : 0;
1818 s = (src ? src->ss : m->p->permanentsockets).sktv6;
1819 if (info && mDNSAddrIsDNSMulticast(dst)) // Specify outgoing interface
1820 {
1821 err = setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_IF, &info->scope_id, sizeof(info->scope_id));
1822 if (err < 0)
1823 {
1824 char name[IFNAMSIZ];
1825 if (if_indextoname(info->scope_id, name) != NULL)
1826 LogMsg("setsockopt - IPV6_MULTICAST_IF error %d errno %d (%s)", err, errno, strerror(errno));
1827 else
1828 LogInfo("setsockopt - IPV6_MUTLICAST_IF scopeid %d, not a valid interface", info->scope_id);
1829 }
1830 }
1831 }
1832
1833 else
1834 {
1835 LogMsg("mDNSPlatformSendUDP: dst is not an IPv4 or IPv6 address!");
1836 #if ForceAlerts
1837 *(long*)0 = 0;
1838 #endif
1839 return mStatus_BadParamErr;
1840 }
1841
1842 if (s >= 0)
1843 verbosedebugf("mDNSPlatformSendUDP: sending on InterfaceID %p %5s/%ld to %#a:%d skt %d",
1844 InterfaceID, ifa_name, dst->type, dst, mDNSVal16(dstPort), s);
1845 else
1846 verbosedebugf("mDNSPlatformSendUDP: NOT sending on InterfaceID %p %5s/%ld (socket of this type not available)",
1847 InterfaceID, ifa_name, dst->type, dst, mDNSVal16(dstPort));
1848
1849 // Note: When sending, mDNSCore may often ask us to send both a v4 multicast packet and then a v6 multicast packet
1850 // If we don't have the corresponding type of socket available, then return mStatus_Invalid
1851 if (s < 0) return(mStatus_Invalid);
1852
1853 // switch to background traffic class for this message if requested
1854 if (useBackgroundTrafficClass)
1855 setTrafficClass(s, useBackgroundTrafficClass);
1856
1857 err = sendto(s, msg, (UInt8*)end - (UInt8*)msg, 0, (struct sockaddr *)&to, to.ss_len);
1858
1859 // set traffic class back to default value
1860 if (useBackgroundTrafficClass)
1861 setTrafficClass(s, mDNSfalse);
1862
1863 if (err < 0)
1864 {
1865 static int MessageCount = 0;
1866 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
1867 if (!mDNSAddressIsAllDNSLinkGroup(dst))
1868 if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);
1869 // Don't report EHOSTUNREACH in the first three minutes after boot
1870 // This is because mDNSResponder intentionally starts up early in the boot process (See <rdar://problem/3409090>)
1871 // but this means that sometimes it starts before configd has finished setting up the multicast routing entries.
1872 if (errno == EHOSTUNREACH && (mDNSu32)(mDNSPlatformRawTime()) < (mDNSu32)(mDNSPlatformOneSecond * 180)) return(mStatus_TransientErr);
1873 // Don't report EADDRNOTAVAIL ("Can't assign requested address") if we're in the middle of a network configuration change
1874 if (errno == EADDRNOTAVAIL && m->p->NetworkChanged) return(mStatus_TransientErr);
1875 if (errno == EHOSTUNREACH || errno == EADDRNOTAVAIL || errno == ENETDOWN)
1876 LogInfo("mDNSPlatformSendUDP sendto(%d) failed to send packet on InterfaceID %p %5s/%d to %#a:%d skt %d error %d errno %d (%s) %lu",
1877 s, InterfaceID, ifa_name, dst->type, dst, mDNSVal16(dstPort), s, err, errno, strerror(errno), (mDNSu32)(m->timenow));
1878 else
1879 {
1880 MessageCount++;
1881 if (MessageCount < 50) // Cap and ensure NO spamming of LogMsgs
1882 LogMsg("mDNSPlatformSendUDP: sendto(%d) failed to send packet on InterfaceID %p %5s/%d to %#a:%d skt %d error %d errno %d (%s) %lu MessageCount is %d",
1883 s, InterfaceID, ifa_name, dst->type, dst, mDNSVal16(dstPort), s, err, errno, strerror(errno), (mDNSu32)(m->timenow), MessageCount);
1884 else // If logging is enabled, remove the cap and log aggressively
1885 LogInfo("mDNSPlatformSendUDP: sendto(%d) failed to send packet on InterfaceID %p %5s/%d to %#a:%d skt %d error %d errno %d (%s) %lu MessageCount is %d",
1886 s, InterfaceID, ifa_name, dst->type, dst, mDNSVal16(dstPort), s, err, errno, strerror(errno), (mDNSu32)(m->timenow), MessageCount);
1887 }
1888
1889 result = mStatus_UnknownErr;
1890 }
1891
1892 #ifdef IP_BOUND_IF
1893 if (dst->type == mDNSAddrType_IPv4 && info && !mDNSAddrIsDNSMulticast(dst))
1894 {
1895 static const mDNSu32 ifindex = 0;
1896 setsockopt(s, IPPROTO_IP, IP_BOUND_IF, &ifindex, sizeof(ifindex));
1897 }
1898 #endif
1899
1900 return(result);
1901 }
1902
1903 mDNSexport ssize_t myrecvfrom(const int s, void *const buffer, const size_t max,
1904 struct sockaddr *const from, size_t *const fromlen, mDNSAddr *dstaddr, char ifname[IF_NAMESIZE], mDNSu8 *ttl)
1905 {
1906 static unsigned int numLogMessages = 0;
1907 struct iovec databuffers = { (char *)buffer, max };
1908 struct msghdr msg;
1909 ssize_t n;
1910 struct cmsghdr *cmPtr;
1911 char ancillary[1024];
1912
1913 *ttl = 255; // If kernel fails to provide TTL data (e.g. Jaguar doesn't) then assume the TTL was 255 as it should be
1914
1915 // Set up the message
1916 msg.msg_name = (caddr_t)from;
1917 msg.msg_namelen = *fromlen;
1918 msg.msg_iov = &databuffers;
1919 msg.msg_iovlen = 1;
1920 msg.msg_control = (caddr_t)&ancillary;
1921 msg.msg_controllen = sizeof(ancillary);
1922 msg.msg_flags = 0;
1923
1924 // Receive the data
1925 n = recvmsg(s, &msg, 0);
1926 if (n<0)
1927 {
1928 if (errno != EWOULDBLOCK && numLogMessages++ < 100) LogMsg("mDNSMacOSX.c: recvmsg(%d) returned error %d errno %d", s, n, errno);
1929 return(-1);
1930 }
1931 if (msg.msg_controllen < (int)sizeof(struct cmsghdr))
1932 {
1933 if (numLogMessages++ < 100) LogMsg("mDNSMacOSX.c: recvmsg(%d) returned %d msg.msg_controllen %d < sizeof(struct cmsghdr) %lu, errno %d",
1934 s, n, msg.msg_controllen, sizeof(struct cmsghdr), errno);
1935 return(-1);
1936 }
1937 if (msg.msg_flags & MSG_CTRUNC)
1938 {
1939 if (numLogMessages++ < 100) LogMsg("mDNSMacOSX.c: recvmsg(%d) msg.msg_flags & MSG_CTRUNC", s);
1940 return(-1);
1941 }
1942
1943 *fromlen = msg.msg_namelen;
1944
1945 // Parse each option out of the ancillary data.
1946 for (cmPtr = CMSG_FIRSTHDR(&msg); cmPtr; cmPtr = CMSG_NXTHDR(&msg, cmPtr))
1947 {
1948 // debugf("myrecvfrom cmsg_level %d cmsg_type %d", cmPtr->cmsg_level, cmPtr->cmsg_type);
1949 if (cmPtr->cmsg_level == IPPROTO_IP && cmPtr->cmsg_type == IP_RECVDSTADDR)
1950 {
1951 dstaddr->type = mDNSAddrType_IPv4;
1952 dstaddr->ip.v4 = *(mDNSv4Addr*)CMSG_DATA(cmPtr);
1953 //LogMsg("mDNSMacOSX.c: recvmsg IP_RECVDSTADDR %.4a", &dstaddr->ip.v4);
1954 }
1955 if (cmPtr->cmsg_level == IPPROTO_IP && cmPtr->cmsg_type == IP_RECVIF)
1956 {
1957 struct sockaddr_dl *sdl = (struct sockaddr_dl *)CMSG_DATA(cmPtr);
1958 if (sdl->sdl_nlen < IF_NAMESIZE)
1959 {
1960 mDNSPlatformMemCopy(ifname, sdl->sdl_data, sdl->sdl_nlen);
1961 ifname[sdl->sdl_nlen] = 0;
1962 // debugf("IP_RECVIF sdl_index %d, sdl_data %s len %d", sdl->sdl_index, ifname, sdl->sdl_nlen);
1963 }
1964 }
1965 if (cmPtr->cmsg_level == IPPROTO_IP && cmPtr->cmsg_type == IP_RECVTTL)
1966 *ttl = *(u_char*)CMSG_DATA(cmPtr);
1967 if (cmPtr->cmsg_level == IPPROTO_IPV6 && cmPtr->cmsg_type == IPV6_PKTINFO)
1968 {
1969 struct in6_pktinfo *ip6_info = (struct in6_pktinfo*)CMSG_DATA(cmPtr);
1970 dstaddr->type = mDNSAddrType_IPv6;
1971 dstaddr->ip.v6 = *(mDNSv6Addr*)&ip6_info->ipi6_addr;
1972 myIfIndexToName(ip6_info->ipi6_ifindex, ifname);
1973 }
1974 if (cmPtr->cmsg_level == IPPROTO_IPV6 && cmPtr->cmsg_type == IPV6_HOPLIMIT)
1975 *ttl = *(int*)CMSG_DATA(cmPtr);
1976 }
1977
1978 return(n);
1979 }
1980
1981 mDNSlocal mDNSInterfaceID FindMyInterface(mDNS *const m, const mDNSAddr *addr)
1982 {
1983 NetworkInterfaceInfo *intf;
1984
1985 if (addr->type == mDNSAddrType_IPv4)
1986 {
1987 for (intf = m->HostInterfaces; intf; intf = intf->next)
1988 {
1989 if (intf->ip.type == addr->type && intf->McastTxRx)
1990 {
1991 if ((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) == 0)
1992 {
1993 return(intf->InterfaceID);
1994 }
1995 }
1996 }
1997 }
1998
1999 if (addr->type == mDNSAddrType_IPv6)
2000 {
2001 for (intf = m->HostInterfaces; intf; intf = intf->next)
2002 {
2003 if (intf->ip.type == addr->type && intf->McastTxRx)
2004 {
2005 if (((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) == 0) &&
2006 ((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) == 0) &&
2007 ((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) == 0) &&
2008 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) == 0)))
2009 {
2010 return(intf->InterfaceID);
2011 }
2012 }
2013 }
2014 }
2015 return(mDNSInterface_Any);
2016 }
2017
2018 mDNSexport mDNSBool mDNSPlatformPeekUDP(mDNS *const m, UDPSocket *src)
2019 {
2020 // We should have a DNSMessage header followed by the question and an answer
2021 // which also includes a CNAME (that's when this function is called). To keep it
2022 // simple, we expect at least the size of DNSMessage header(12) and size of "A"
2023 // record (14 bytes).
2024 char buffer[26];
2025 int ret;
2026
2027 (void) m;
2028
2029 if (!src)
2030 return mDNSfalse;
2031
2032 ret = recv(src->ss.sktv4, buffer, sizeof(buffer), MSG_PEEK);
2033 if (ret > 0)
2034 return mDNStrue;
2035 else
2036 return mDNSfalse;
2037 }
2038
2039 mDNSexport void myKQSocketCallBack(int s1, short filter, void *context)
2040 {
2041 KQSocketSet *const ss = (KQSocketSet *)context;
2042 mDNS *const m = ss->m;
2043 int err = 0, count = 0, closed = 0;
2044
2045 if (filter != EVFILT_READ)
2046 LogMsg("myKQSocketCallBack: Why is filter %d not EVFILT_READ (%d)?", filter, EVFILT_READ);
2047
2048 if (s1 != ss->sktv4 && s1 != ss->sktv6)
2049 {
2050 LogMsg("myKQSocketCallBack: native socket %d", s1);
2051 LogMsg("myKQSocketCallBack: sktv4 %d sktv6 %d", ss->sktv4, ss->sktv6);
2052 }
2053
2054 while (!closed)
2055 {
2056 mDNSAddr senderAddr, destAddr;
2057 mDNSIPPort senderPort;
2058 struct sockaddr_storage from;
2059 size_t fromlen = sizeof(from);
2060 char packetifname[IF_NAMESIZE] = "";
2061 mDNSu8 ttl;
2062 err = myrecvfrom(s1, &m->imsg, sizeof(m->imsg), (struct sockaddr *)&from, &fromlen, &destAddr, packetifname, &ttl);
2063 if (err < 0) break;
2064
2065 count++;
2066 if (from.ss_family == AF_INET)
2067 {
2068 struct sockaddr_in *s = (struct sockaddr_in*)&from;
2069 senderAddr.type = mDNSAddrType_IPv4;
2070 senderAddr.ip.v4.NotAnInteger = s->sin_addr.s_addr;
2071 senderPort.NotAnInteger = s->sin_port;
2072 //LogInfo("myKQSocketCallBack received IPv4 packet from %#-15a to %#-15a on skt %d %s", &senderAddr, &destAddr, s1, packetifname);
2073 }
2074 else if (from.ss_family == AF_INET6)
2075 {
2076 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&from;
2077 senderAddr.type = mDNSAddrType_IPv6;
2078 senderAddr.ip.v6 = *(mDNSv6Addr*)&sin6->sin6_addr;
2079 senderPort.NotAnInteger = sin6->sin6_port;
2080 //LogInfo("myKQSocketCallBack received IPv6 packet from %#-15a to %#-15a on skt %d %s", &senderAddr, &destAddr, s1, packetifname);
2081 }
2082 else
2083 {
2084 LogMsg("myKQSocketCallBack from is unknown address family %d", from.ss_family);
2085 return;
2086 }
2087
2088 // Note: When handling multiple packets in a batch, MUST reset InterfaceID before handling each packet
2089 mDNSInterfaceID InterfaceID = mDNSNULL;
2090 NetworkInterfaceInfoOSX *intf = m->p->InterfaceList;
2091 while (intf)
2092 {
2093 if (intf->Exists && !strcmp(intf->ifinfo.ifname, packetifname))
2094 break;
2095 intf = intf->next;
2096 }
2097
2098 // When going to sleep we deregister all our interfaces, but if the machine
2099 // takes a few seconds to sleep we may continue to receive multicasts
2100 // during that time, which would confuse mDNSCoreReceive, because as far
2101 // as it's concerned, we should have no active interfaces any more.
2102 // Hence we ignore multicasts for which we can find no matching InterfaceID.
2103 if (intf)
2104 InterfaceID = intf->ifinfo.InterfaceID;
2105 else if (mDNSAddrIsDNSMulticast(&destAddr))
2106 continue;
2107
2108 if (!InterfaceID)
2109 {
2110 InterfaceID = FindMyInterface(m, &destAddr);
2111 }
2112
2113 // LogMsg("myKQSocketCallBack got packet from %#a to %#a on interface %#a/%s",
2114 // &senderAddr, &destAddr, &ss->info->ifinfo.ip, ss->info->ifinfo.ifname);
2115
2116 // mDNSCoreReceive may close the socket we're reading from. We must break out of our
2117 // loop when that happens, or we may try to read from an invalid FD. We do this by
2118 // setting the closeFlag pointer in the socketset, so CloseSocketSet can inform us
2119 // if it closes the socketset.
2120 ss->closeFlag = &closed;
2121
2122 if (ss->proxy)
2123 {
2124 m->p->UDPProxyCallback(m, &m->p->UDPProxy, (unsigned char *)&m->imsg, (unsigned char*)&m->imsg + err, &senderAddr,
2125 senderPort, &destAddr, ss->port, InterfaceID, NULL);
2126 }
2127 else
2128 {
2129 mDNSCoreReceive(m, &m->imsg, (unsigned char*)&m->imsg + err, &senderAddr, senderPort, &destAddr, ss->port, InterfaceID);
2130 }
2131
2132 // if we didn't close, we can safely dereference the socketset, and should to
2133 // reset the closeFlag, since it points to something on the stack
2134 if (!closed) ss->closeFlag = mDNSNULL;
2135 }
2136
2137 if (err < 0 && (errno != EWOULDBLOCK || count == 0))
2138 {
2139 // Something is busted here.
2140 // kqueue says there is a packet, but myrecvfrom says there is not.
2141 // Try calling select() to get another opinion.
2142 // Find out about other socket parameter that can help understand why select() says the socket is ready for read
2143 // All of this is racy, as data may have arrived after the call to select()
2144 static unsigned int numLogMessages = 0;
2145 int save_errno = errno;
2146 int so_error = -1;
2147 int so_nread = -1;
2148 int fionread = -1;
2149 socklen_t solen = sizeof(int);
2150 fd_set readfds;
2151 struct timeval timeout;
2152 int selectresult;
2153 FD_ZERO(&readfds);
2154 FD_SET(s1, &readfds);
2155 timeout.tv_sec = 0;
2156 timeout.tv_usec = 0;
2157 selectresult = select(s1+1, &readfds, NULL, NULL, &timeout);
2158 if (getsockopt(s1, SOL_SOCKET, SO_ERROR, &so_error, &solen) == -1)
2159 LogMsg("myKQSocketCallBack getsockopt(SO_ERROR) error %d", errno);
2160 if (getsockopt(s1, SOL_SOCKET, SO_NREAD, &so_nread, &solen) == -1)
2161 LogMsg("myKQSocketCallBack getsockopt(SO_NREAD) error %d", errno);
2162 if (ioctl(s1, FIONREAD, &fionread) == -1)
2163 LogMsg("myKQSocketCallBack ioctl(FIONREAD) error %d", errno);
2164 if (numLogMessages++ < 100)
2165 LogMsg("myKQSocketCallBack recvfrom skt %d error %d errno %d (%s) select %d (%spackets waiting) so_error %d so_nread %d fionread %d count %d",
2166 s1, err, save_errno, strerror(save_errno), selectresult, FD_ISSET(s1, &readfds) ? "" : "*NO* ", so_error, so_nread, fionread, count);
2167 if (numLogMessages > 5)
2168 NotifyOfElusiveBug("Flaw in Kernel (select/recvfrom mismatch)",
2169 "Congratulations, you've reproduced an elusive bug.\r"
2170 "Please contact the current assignee of <rdar://problem/3375328>.\r"
2171 "Alternatively, you can send email to radar-3387020@group.apple.com. (Note number is different.)\r"
2172 "If possible, please leave your machine undisturbed so that someone can come to investigate the problem.");
2173
2174 sleep(1); // After logging this error, rate limit so we don't flood syslog
2175 }
2176 }
2177
2178 mDNSlocal void doTcpSocketCallback(TCPSocket *sock)
2179 {
2180 mDNSBool c = !sock->connected;
2181 sock->connected = mDNStrue;
2182 sock->callback(sock, sock->context, c, sock->err);
2183 // Note: the callback may call CloseConnection here, which frees the context structure!
2184 }
2185
2186 #ifndef NO_SECURITYFRAMEWORK
2187
2188 mDNSlocal OSStatus tlsWriteSock(SSLConnectionRef connection, const void *data, size_t *dataLength)
2189 {
2190 int ret = send(((TCPSocket *)connection)->fd, data, *dataLength, 0);
2191 if (ret >= 0 && (size_t)ret < *dataLength) { *dataLength = ret; return(errSSLWouldBlock); }
2192 if (ret >= 0) { *dataLength = ret; return(noErr); }
2193 *dataLength = 0;
2194 if (errno == EAGAIN ) return(errSSLWouldBlock);
2195 if (errno == ENOENT ) return(errSSLClosedGraceful);
2196 if (errno == EPIPE || errno == ECONNRESET) return(errSSLClosedAbort);
2197 LogMsg("ERROR: tlsWriteSock: %d error %d (%s)\n", ((TCPSocket *)connection)->fd, errno, strerror(errno));
2198 return(errSSLClosedAbort);
2199 }
2200
2201 mDNSlocal OSStatus tlsReadSock(SSLConnectionRef connection, void *data, size_t *dataLength)
2202 {
2203 int ret = recv(((TCPSocket *)connection)->fd, data, *dataLength, 0);
2204 if (ret > 0 && (size_t)ret < *dataLength) { *dataLength = ret; return(errSSLWouldBlock); }
2205 if (ret > 0) { *dataLength = ret; return(noErr); }
2206 *dataLength = 0;
2207 if (ret == 0 || errno == ENOENT ) return(errSSLClosedGraceful);
2208 if ( errno == EAGAIN ) return(errSSLWouldBlock);
2209 if ( errno == ECONNRESET) return(errSSLClosedAbort);
2210 LogMsg("ERROR: tlsSockRead: error %d (%s)\n", errno, strerror(errno));
2211 return(errSSLClosedAbort);
2212 }
2213
2214 mDNSlocal OSStatus tlsSetupSock(TCPSocket *sock, SSLProtocolSide pside, SSLConnectionType ctype)
2215 {
2216 char domname_cstr[MAX_ESCAPED_DOMAIN_NAME];
2217
2218 sock->tlsContext = SSLCreateContext(kCFAllocatorDefault, pside, ctype);
2219 if (!sock->tlsContext)
2220 {
2221 LogMsg("ERROR: tlsSetupSock: SSLCreateContext failed");
2222 return(mStatus_UnknownErr);
2223 }
2224
2225 mStatus err = SSLSetIOFuncs(sock->tlsContext, tlsReadSock, tlsWriteSock);
2226 if (err)
2227 {
2228 LogMsg("ERROR: tlsSetupSock: SSLSetIOFuncs failed with error code: %d", err);
2229 goto fail;
2230 }
2231
2232 err = SSLSetConnection(sock->tlsContext, (SSLConnectionRef) sock);
2233 if (err)
2234 {
2235 LogMsg("ERROR: tlsSetupSock: SSLSetConnection failed with error code: %d", err);
2236 goto fail;
2237 }
2238
2239 // Instead of listing all the acceptable ciphers, we just disable the bad ciphers. It does not disable
2240 // all the bad ciphers like RC4_MD5, but it assumes that the servers don't offer them.
2241 err = SSLSetAllowAnonymousCiphers(sock->tlsContext, 0);
2242 if (err)
2243 {
2244 LogMsg("ERROR: tlsSetupSock: SSLSetAllowAnonymousCiphers failed with error code: %d", err);
2245 goto fail;
2246 }
2247
2248 // We already checked for NULL in hostname and this should never happen. Hence, returning -1
2249 // (error not in OSStatus space) is okay.
2250 if (!sock->hostname.c[0])
2251 {
2252 LogMsg("ERROR: tlsSetupSock: hostname NULL");
2253 err = -1;
2254 goto fail;
2255 }
2256
2257 ConvertDomainNameToCString(&sock->hostname, domname_cstr);
2258 err = SSLSetPeerDomainName(sock->tlsContext, domname_cstr, strlen(domname_cstr));
2259 if (err)
2260 {
2261 LogMsg("ERROR: tlsSetupSock: SSLSetPeerDomainname: %s failed with error code: %d", domname_cstr, err);
2262 goto fail;
2263 }
2264
2265 return(err);
2266
2267 fail:
2268 if (sock->tlsContext)
2269 CFRelease(sock->tlsContext);
2270 return(err);
2271 }
2272
2273 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2274 mDNSlocal void doSSLHandshake(TCPSocket *sock)
2275 {
2276 mStatus err = SSLHandshake(sock->tlsContext);
2277
2278 //Can't have multiple threads in mDNS core. When MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM is
2279 //defined, KQueueLock is a noop. Hence we need to serialize here
2280 //
2281 //NOTE: We just can't serialize doTcpSocketCallback alone on the main queue.
2282 //We need the rest of the logic also. Otherwise, we can enable the READ
2283 //events below, dispatch a doTcpSocketCallback on the main queue. Assume it is
2284 //ConnFailed which means we are going to free the tcpInfo. While it
2285 //is waiting to be dispatched, another read event can come into tcpKQSocketCallback
2286 //and potentially call doTCPCallback with error which can close the fd and free the
2287 //tcpInfo. Later when the thread gets dispatched it will crash because the tcpInfo
2288 //is already freed.
2289
2290 dispatch_async(dispatch_get_main_queue(), ^{
2291
2292 LogInfo("doSSLHandshake %p: got lock", sock); // Log *after* we get the lock
2293
2294 if (sock->handshake == handshake_to_be_closed)
2295 {
2296 LogInfo("SSLHandshake completed after close");
2297 mDNSPlatformTCPCloseConnection(sock);
2298 }
2299 else
2300 {
2301 if (sock->fd != -1) KQueueSet(sock->fd, EV_ADD, EVFILT_READ, sock->kqEntry);
2302 else LogMsg("doSSLHandshake: sock->fd is -1");
2303
2304 if (err == errSSLWouldBlock)
2305 sock->handshake = handshake_required;
2306 else
2307 {
2308 if (err)
2309 {
2310 LogMsg("SSLHandshake failed: %d%s", err, err == errSSLPeerInternalError ? " (server busy)" : "");
2311 CFRelease(sock->tlsContext);
2312 sock->tlsContext = NULL;
2313 }
2314
2315 sock->err = err ? mStatus_ConnFailed : 0;
2316 sock->handshake = handshake_completed;
2317
2318 LogInfo("doSSLHandshake: %p calling doTcpSocketCallback fd %d", sock, sock->fd);
2319 doTcpSocketCallback(sock);
2320 }
2321 }
2322
2323 LogInfo("SSLHandshake %p: dropping lock for fd %d", sock, sock->fd);
2324 return;
2325 });
2326 }
2327 #else // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2328 mDNSlocal void *doSSLHandshake(TCPSocket *sock)
2329 {
2330 // Warning: Touching sock without the kqueue lock!
2331 // We're protected because sock->handshake == handshake_in_progress
2332 mDNS * const m = sock->m; // Get m now, as we may free sock if marked to be closed while we're waiting on SSLHandshake
2333 mStatus err = SSLHandshake(sock->tlsContext);
2334
2335 KQueueLock(m);
2336 debugf("doSSLHandshake %p: got lock", sock); // Log *after* we get the lock
2337
2338 if (sock->handshake == handshake_to_be_closed)
2339 {
2340 LogInfo("SSLHandshake completed after close");
2341 mDNSPlatformTCPCloseConnection(sock);
2342 }
2343 else
2344 {
2345 if (sock->fd != -1) KQueueSet(sock->fd, EV_ADD, EVFILT_READ, sock->kqEntry);
2346 else LogMsg("doSSLHandshake: sock->fd is -1");
2347
2348 if (err == errSSLWouldBlock)
2349 sock->handshake = handshake_required;
2350 else
2351 {
2352 if (err)
2353 {
2354 LogMsg("SSLHandshake failed: %d%s", err, err == errSSLPeerInternalError ? " (server busy)" : "");
2355 CFRelease(sock->tlsContext);
2356 sock->tlsContext = NULL;
2357 }
2358
2359 sock->err = err ? mStatus_ConnFailed : 0;
2360 sock->handshake = handshake_completed;
2361
2362 debugf("doSSLHandshake: %p calling doTcpSocketCallback fd %d", sock, sock->fd);
2363 doTcpSocketCallback(sock);
2364 }
2365 }
2366
2367 debugf("SSLHandshake %p: dropping lock for fd %d", sock, sock->fd);
2368 KQueueUnlock(m, "doSSLHandshake");
2369 return NULL;
2370 }
2371 #endif // MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2372
2373 mDNSlocal void spawnSSLHandshake(TCPSocket* sock)
2374 {
2375 debugf("spawnSSLHandshake %p: entry", sock);
2376
2377 if (sock->handshake != handshake_required) LogMsg("spawnSSLHandshake: handshake status not required: %d", sock->handshake);
2378 sock->handshake = handshake_in_progress;
2379 KQueueSet(sock->fd, EV_DELETE, EVFILT_READ, sock->kqEntry);
2380
2381 // Dispatch it on a separate queue to help avoid blocking other threads/queues, and
2382 // to limit the number of threads used for SSLHandshake
2383 dispatch_async(SSLqueue, ^{doSSLHandshake(sock);});
2384
2385 debugf("spawnSSLHandshake %p: done for %d", sock, sock->fd);
2386 }
2387
2388 #endif /* NO_SECURITYFRAMEWORK */
2389
2390 mDNSlocal void tcpKQSocketCallback(__unused int fd, short filter, void *context)
2391 {
2392 TCPSocket *sock = context;
2393 sock->err = mStatus_NoError;
2394
2395 //if (filter == EVFILT_READ ) LogMsg("myKQSocketCallBack: tcpKQSocketCallback %d is EVFILT_READ", filter);
2396 //if (filter == EVFILT_WRITE) LogMsg("myKQSocketCallBack: tcpKQSocketCallback %d is EVFILT_WRITE", filter);
2397 // EV_ONESHOT doesn't seem to work, so we add the filter with EV_ADD, and explicitly delete it here with EV_DELETE
2398 if (filter == EVFILT_WRITE)
2399 KQueueSet(sock->fd, EV_DELETE, EVFILT_WRITE, sock->kqEntry);
2400
2401 if (sock->flags & kTCPSocketFlags_UseTLS)
2402 {
2403 #ifndef NO_SECURITYFRAMEWORK
2404 if (!sock->setup)
2405 {
2406 sock->setup = mDNStrue;
2407 sock->err = tlsSetupSock(sock, kSSLClientSide, kSSLStreamType);
2408 if (sock->err)
2409 {
2410 LogMsg("ERROR: tcpKQSocketCallback: tlsSetupSock failed with error code: %d", sock->err);
2411 return;
2412 }
2413 }
2414 if (sock->handshake == handshake_required)
2415 {
2416 spawnSSLHandshake(sock);
2417 return;
2418 }
2419 else if (sock->handshake == handshake_in_progress || sock->handshake == handshake_to_be_closed)
2420 {
2421 return;
2422 }
2423 else if (sock->handshake != handshake_completed)
2424 {
2425 if (!sock->err)
2426 sock->err = mStatus_UnknownErr;
2427 LogMsg("tcpKQSocketCallback called with unexpected SSLHandshake status: %d", sock->handshake);
2428 }
2429 #else /* NO_SECURITYFRAMEWORK */
2430 sock->err = mStatus_UnsupportedErr;
2431 #endif /* NO_SECURITYFRAMEWORK */
2432 }
2433
2434 doTcpSocketCallback(sock);
2435 }
2436
2437 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2438 mDNSexport int KQueueSet(int fd, u_short flags, short filter, KQueueEntry *const entryRef)
2439 {
2440 dispatch_queue_t queue = dispatch_get_main_queue();
2441 dispatch_source_t source;
2442 if (flags == EV_DELETE)
2443 {
2444 if (filter == EVFILT_READ)
2445 {
2446 dispatch_source_cancel(entryRef->readSource);
2447 dispatch_release(entryRef->readSource);
2448 entryRef->readSource = mDNSNULL;
2449 debugf("KQueueSet: source cancel for read %p, %p", entryRef->readSource, entryRef->writeSource);
2450 }
2451 else if (filter == EVFILT_WRITE)
2452 {
2453 dispatch_source_cancel(entryRef->writeSource);
2454 dispatch_release(entryRef->writeSource);
2455 entryRef->writeSource = mDNSNULL;
2456 debugf("KQueueSet: source cancel for write %p, %p", entryRef->readSource, entryRef->writeSource);
2457 }
2458 else
2459 LogMsg("KQueueSet: ERROR: Wrong filter value %d for EV_DELETE", filter);
2460 return 0;
2461 }
2462 if (flags != EV_ADD) LogMsg("KQueueSet: Invalid flags %d", flags);
2463
2464 if (filter == EVFILT_READ)
2465 {
2466 source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, queue);
2467 }
2468 else if (filter == EVFILT_WRITE)
2469 {
2470 source = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, fd, 0, queue);
2471 }
2472 else
2473 {
2474 LogMsg("KQueueSet: ERROR: Wrong filter value %d for EV_ADD", filter);
2475 return -1;
2476 }
2477 if (!source) return -1;
2478 dispatch_source_set_event_handler(source, ^{
2479
2480 mDNSs32 stime = mDNSPlatformRawTime();
2481 entryRef->KQcallback(fd, filter, entryRef->KQcontext);
2482 mDNSs32 etime = mDNSPlatformRawTime();
2483 if (etime - stime >= WatchDogReportingThreshold)
2484 LogInfo("KQEntryCallback Block: WARNING: took %dms to complete", etime - stime);
2485
2486 // Trigger the event delivery to the application. Even though we trigger the
2487 // event completion after handling every event source, these all will hopefully
2488 // get merged
2489 TriggerEventCompletion();
2490
2491 });
2492 dispatch_source_set_cancel_handler(source, ^{
2493 if (entryRef->fdClosed)
2494 {
2495 //LogMsg("CancelHandler: closing fd %d", fd);
2496 close(fd);
2497 }
2498 });
2499 dispatch_resume(source);
2500 if (filter == EVFILT_READ)
2501 entryRef->readSource = source;
2502 else
2503 entryRef->writeSource = source;
2504
2505 return 0;
2506 }
2507
2508 mDNSexport void KQueueLock(mDNS *const m)
2509 {
2510 (void)m; //unused
2511 }
2512 mDNSexport void KQueueUnlock(mDNS *const m, const char const *task)
2513 {
2514 (void)m; //unused
2515 (void)task; //unused
2516 }
2517 #else
2518 mDNSexport int KQueueSet(int fd, u_short flags, short filter, const KQueueEntry *const entryRef)
2519 {
2520 struct kevent new_event;
2521 EV_SET(&new_event, fd, filter, flags, 0, 0, (void*)entryRef);
2522 return (kevent(KQueueFD, &new_event, 1, NULL, 0, NULL) < 0) ? errno : 0;
2523 }
2524
2525 mDNSexport void KQueueLock(mDNS *const m)
2526 {
2527 pthread_mutex_lock(&m->p->BigMutex);
2528 m->p->BigMutexStartTime = mDNSPlatformRawTime();
2529 }
2530
2531 mDNSexport void KQueueUnlock(mDNS *const m, const char* task)
2532 {
2533 mDNSs32 end = mDNSPlatformRawTime();
2534 (void)task;
2535 if (end - m->p->BigMutexStartTime >= WatchDogReportingThreshold)
2536 LogInfo("WARNING: %s took %dms to complete", task, end - m->p->BigMutexStartTime);
2537
2538 pthread_mutex_unlock(&m->p->BigMutex);
2539
2540 char wake = 1;
2541 if (send(m->p->WakeKQueueLoopFD, &wake, sizeof(wake), 0) == -1)
2542 LogMsg("ERROR: KQueueWake: send failed with error code: %d (%s)", errno, strerror(errno));
2543 }
2544 #endif
2545
2546 mDNSexport void mDNSPlatformCloseFD(KQueueEntry *kq, int fd)
2547 {
2548 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2549 (void) fd; //unused
2550 if (kq->readSource)
2551 {
2552 dispatch_source_cancel(kq->readSource);
2553 kq->readSource = mDNSNULL;
2554 }
2555 if (kq->writeSource)
2556 {
2557 dispatch_source_cancel(kq->writeSource);
2558 kq->writeSource = mDNSNULL;
2559 }
2560 // Close happens in the cancellation handler
2561 debugf("mDNSPlatformCloseFD: resetting sources for %d", fd);
2562 kq->fdClosed = mDNStrue;
2563 #else
2564 (void)kq; //unused
2565 close(fd);
2566 #endif
2567 }
2568
2569 mDNSlocal mStatus SetupTCPSocket(TCPSocket *sock, u_short sa_family, mDNSIPPort *port, mDNSBool useBackgroundTrafficClass)
2570 {
2571 KQSocketSet *cp = &sock->ss;
2572 int *s = (sa_family == AF_INET) ? &cp->sktv4 : &cp->sktv6;
2573 KQueueEntry *k = (sa_family == AF_INET) ? &cp->kqsv4 : &cp->kqsv6;
2574 const int on = 1; // "on" for setsockopt
2575 mStatus err;
2576
2577 int skt = socket(sa_family, SOCK_STREAM, IPPROTO_TCP);
2578 if (skt < 3) { if (errno != EAFNOSUPPORT) LogMsg("SetupTCPSocket: socket error %d errno %d (%s)", skt, errno, strerror(errno));return(skt); }
2579
2580 // for TCP sockets, the traffic class is set once and not changed
2581 setTrafficClass(skt, useBackgroundTrafficClass);
2582
2583 if (sa_family == AF_INET)
2584 {
2585 // Bind it
2586 struct sockaddr_in addr;
2587 mDNSPlatformMemZero(&addr, sizeof(addr));
2588 addr.sin_family = AF_INET;
2589 addr.sin_port = port->NotAnInteger;
2590 err = bind(skt, (struct sockaddr*) &addr, sizeof(addr));
2591 if (err < 0) { LogMsg("ERROR: bind %s", strerror(errno)); return err; }
2592
2593 // Receive interface identifiers
2594 err = setsockopt(skt, IPPROTO_IP, IP_RECVIF, &on, sizeof(on));
2595 if (err < 0) { LogMsg("setsockopt IP_RECVIF - %s", strerror(errno)); return err; }
2596
2597 mDNSPlatformMemZero(&addr, sizeof(addr));
2598 socklen_t len = sizeof(addr);
2599 err = getsockname(skt, (struct sockaddr*) &addr, &len);
2600 if (err < 0) { LogMsg("getsockname - %s", strerror(errno)); return err; }
2601
2602 port->NotAnInteger = addr.sin_port;
2603 }
2604 else
2605 {
2606 // Bind it
2607 struct sockaddr_in6 addr6;
2608 mDNSPlatformMemZero(&addr6, sizeof(addr6));
2609 addr6.sin6_family = AF_INET6;
2610 addr6.sin6_port = port->NotAnInteger;
2611 err = bind(skt, (struct sockaddr*) &addr6, sizeof(addr6));
2612 if (err < 0) { LogMsg("ERROR: bind6 %s", strerror(errno)); return err; }
2613
2614 // We want to receive destination addresses and receive interface identifiers
2615 err = setsockopt(skt, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on));
2616 if (err < 0) { LogMsg("ERROR: setsockopt IPV6_RECVPKTINFO %s", strerror(errno)); return err; }
2617
2618 mDNSPlatformMemZero(&addr6, sizeof(addr6));
2619 socklen_t len = sizeof(addr6);
2620 err = getsockname(skt, (struct sockaddr *) &addr6, &len);
2621 if (err < 0) { LogMsg("getsockname6 - %s", strerror(errno)); return err; }
2622
2623 port->NotAnInteger = addr6.sin6_port;
2624
2625 }
2626 *s = skt;
2627 k->KQcallback = tcpKQSocketCallback;
2628 k->KQcontext = sock;
2629 k->KQtask = "mDNSPlatformTCPSocket";
2630 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
2631 k->readSource = mDNSNULL;
2632 k->writeSource = mDNSNULL;
2633 k->fdClosed = mDNSfalse;
2634 #endif
2635 return mStatus_NoError;
2636 }
2637
2638 mDNSexport TCPSocket *mDNSPlatformTCPSocket(mDNS *const m, TCPSocketFlags flags, mDNSIPPort *port, mDNSBool useBackgroundTrafficClass)
2639 {
2640 mStatus err;
2641 (void) m;
2642
2643 TCPSocket *sock = mallocL("TCPSocket/mDNSPlatformTCPSocket", sizeof(TCPSocket));
2644 if (!sock) { LogMsg("mDNSPlatformTCPSocket: memory allocation failure"); return(mDNSNULL); }
2645
2646 mDNSPlatformMemZero(sock, sizeof(TCPSocket));
2647
2648 sock->ss.m = m;
2649 sock->ss.sktv4 = -1;
2650 sock->ss.sktv6 = -1;
2651 err = SetupTCPSocket(sock, AF_INET, port, useBackgroundTrafficClass);
2652
2653 if (!err)
2654 {
2655 err = SetupTCPSocket(sock, AF_INET6, port, useBackgroundTrafficClass);
2656 if (err) { mDNSPlatformCloseFD(&sock->ss.kqsv4, sock->ss.sktv4); sock->ss.sktv4 = -1; }
2657 }
2658 if (err)
2659 {
2660 LogMsg("mDNSPlatformTCPSocket: socket error %d errno %d (%s)", sock->fd, errno, strerror(errno));
2661 freeL("TCPSocket/mDNSPlatformTCPSocket", sock);
2662 return(mDNSNULL);
2663 }
2664 // sock->fd is used as the default fd if the caller does not call mDNSPlatformTCPConnect
2665 sock->fd = sock->ss.sktv4;
2666 sock->callback = mDNSNULL;
2667 sock->flags = flags;
2668 sock->context = mDNSNULL;
2669 sock->setup = mDNSfalse;
2670 sock->connected = mDNSfalse;
2671 sock->handshake = handshake_required;
2672 sock->m = m;
2673 sock->err = mStatus_NoError;
2674
2675 return sock;
2676 }
2677
2678 mDNSexport mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport, domainname *hostname, mDNSInterfaceID InterfaceID, TCPConnectionCallback callback, void *context)
2679 {
2680 KQSocketSet *cp = &sock->ss;
2681 int *s = (dst->type == mDNSAddrType_IPv4) ? &cp->sktv4 : &cp->sktv6;
2682 KQueueEntry *k = (dst->type == mDNSAddrType_IPv4) ? &cp->kqsv4 : &cp->kqsv6;
2683 mStatus err = mStatus_NoError;
2684 struct sockaddr_storage ss;
2685
2686 sock->callback = callback;
2687 sock->context = context;
2688 sock->setup = mDNSfalse;
2689 sock->connected = mDNSfalse;
2690 sock->handshake = handshake_required;
2691 sock->err = mStatus_NoError;
2692
2693 if (hostname) { debugf("mDNSPlatformTCPConnect: hostname %##s", hostname->c); AssignDomainName(&sock->hostname, hostname); }
2694
2695 if (dst->type == mDNSAddrType_IPv4)
2696 {
2697 struct sockaddr_in *saddr = (struct sockaddr_in *)&ss;
2698 mDNSPlatformMemZero(saddr, sizeof(*saddr));
2699 saddr->sin_family = AF_INET;
2700 saddr->sin_port = dstport.NotAnInteger;
2701 saddr->sin_len = sizeof(*saddr);
2702 saddr->sin_addr.s_addr = dst->ip.v4.NotAnInteger;
2703 }
2704 else
2705 {
2706 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)&ss;
2707 mDNSPlatformMemZero(saddr6, sizeof(*saddr6));
2708 saddr6->sin6_family = AF_INET6;
2709 saddr6->sin6_port = dstport.NotAnInteger;
2710 saddr6->sin6_len = sizeof(*saddr6);
2711 saddr6->sin6_addr = *(struct in6_addr *)&dst->ip.v6;
2712 }
2713
2714 // Watch for connect complete (write is ready)
2715 // EV_ONESHOT doesn't seem to work, so we add the filter with EV_ADD, and explicitly delete it in tcpKQSocketCallback using EV_DELETE
2716 if (KQueueSet(*s, EV_ADD /* | EV_ONESHOT */, EVFILT_WRITE, k))
2717 {
2718 LogMsg("ERROR: mDNSPlatformTCPConnect - KQueueSet failed");
2719 return errno;
2720 }
2721
2722 // Watch for incoming data
2723 if (KQueueSet(*s, EV_ADD, EVFILT_READ, k))
2724 {
2725 LogMsg("ERROR: mDNSPlatformTCPConnect - KQueueSet failed");
2726 return errno;
2727 }
2728
2729 if (fcntl(*s, F_SETFL, fcntl(*s, F_GETFL, 0) | O_NONBLOCK) < 0) // set non-blocking
2730 {
2731 LogMsg("ERROR: setsockopt O_NONBLOCK - %s", strerror(errno));
2732 return mStatus_UnknownErr;
2733 }
2734
2735 // We bind to the interface and all subsequent packets including the SYN will be sent out
2736 // on this interface
2737 //
2738 // Note: If we are in Active Directory domain, we may try TCP (if the response can't fit in
2739 // UDP). mDNSInterface_Unicast indicates this case and not a valid interface.
2740 if (InterfaceID && InterfaceID != mDNSInterface_Unicast)
2741 {
2742 NetworkInterfaceInfoOSX *info = IfindexToInterfaceInfoOSX(&mDNSStorage, InterfaceID);
2743 if (dst->type == mDNSAddrType_IPv4)
2744 {
2745 #ifdef IP_BOUND_IF
2746 if (info) setsockopt(*s, IPPROTO_IP, IP_BOUND_IF, &info->scope_id, sizeof(info->scope_id));
2747 else { LogMsg("mDNSPlatformTCPConnect: Invalid interface index %p", InterfaceID); return mStatus_BadParamErr; }
2748 #else
2749 (void)InterfaceID; // Unused
2750 (void)info; // Unused
2751 #endif
2752 }
2753 else
2754 {
2755 #ifdef IPV6_BOUND_IF
2756 if (info) setsockopt(*s, IPPROTO_IPV6, IPV6_BOUND_IF, &info->scope_id, sizeof(info->scope_id));
2757 else { LogMsg("mDNSPlatformTCPConnect: Invalid interface index %p", InterfaceID); return mStatus_BadParamErr; }
2758 #else
2759 (void)InterfaceID; // Unused
2760 (void)info; // Unused
2761 #endif
2762 }
2763 }
2764
2765 // mDNSPlatformReadTCP/WriteTCP (unlike the UDP counterpart) does not provide the destination address
2766 // from which we can infer the destination address family. Hence we need to remember that here.
2767 // Instead of remembering the address family, we remember the right fd.
2768 sock->fd = *s;
2769 sock->kqEntry = k;
2770 // initiate connection wth peer
2771 if (connect(*s, (struct sockaddr *)&ss, ss.ss_len) < 0)
2772 {
2773 if (errno == EINPROGRESS) return mStatus_ConnPending;
2774 if (errno == EHOSTUNREACH || errno == EADDRNOTAVAIL || errno == ENETDOWN)
2775 LogInfo("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s)", sock->fd, errno, strerror(errno));
2776 else
2777 LogMsg("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s) length %d", sock->fd, errno, strerror(errno), ss.ss_len);
2778 return mStatus_ConnFailed;
2779 }
2780
2781 LogMsg("NOTE: mDNSPlatformTCPConnect completed synchronously");
2782 // kQueue should notify us, but this LogMsg is to help track down if it doesn't
2783 return err;
2784 }
2785
2786 // Why doesn't mDNSPlatformTCPAccept actually call accept() ?
2787 mDNSexport TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int fd)
2788 {
2789 mStatus err = mStatus_NoError;
2790
2791 TCPSocket *sock = mallocL("TCPSocket/mDNSPlatformTCPAccept", sizeof(TCPSocket));
2792 if (!sock) return(mDNSNULL);
2793
2794 mDNSPlatformMemZero(sock, sizeof(*sock));
2795 sock->fd = fd;
2796 sock->flags = flags;
2797
2798 if (flags & kTCPSocketFlags_UseTLS)
2799 {
2800 #ifndef NO_SECURITYFRAMEWORK
2801 if (!ServerCerts) { LogMsg("ERROR: mDNSPlatformTCPAccept: unable to find TLS certificates"); err = mStatus_UnknownErr; goto exit; }
2802
2803 err = tlsSetupSock(sock, kSSLServerSide, kSSLStreamType);
2804 if (err) { LogMsg("ERROR: mDNSPlatformTCPAccept: tlsSetupSock failed with error code: %d", err); goto exit; }
2805
2806 err = SSLSetCertificate(sock->tlsContext, ServerCerts);
2807 if (err) { LogMsg("ERROR: mDNSPlatformTCPAccept: SSLSetCertificate failed with error code: %d", err); goto exit; }
2808 #else
2809 err = mStatus_UnsupportedErr;
2810 #endif /* NO_SECURITYFRAMEWORK */
2811 }
2812 #ifndef NO_SECURITYFRAMEWORK
2813 exit:
2814 #endif
2815
2816 if (err) { freeL("TCPSocket/mDNSPlatformTCPAccept", sock); return(mDNSNULL); }
2817 return(sock);
2818 }
2819
2820 mDNSexport mDNSu16 mDNSPlatformGetUDPPort(UDPSocket *sock)
2821 {
2822 mDNSu16 port;
2823
2824 port = -1;
2825 if (sock)
2826 {
2827 port = sock->ss.port.NotAnInteger;
2828 }
2829 return port;
2830 }
2831
2832 mDNSlocal void CloseSocketSet(KQSocketSet *ss)
2833 {
2834 if (ss->sktv4 != -1)
2835 {
2836 mDNSPlatformCloseFD(&ss->kqsv4, ss->sktv4);
2837 ss->sktv4 = -1;
2838 }
2839 if (ss->sktv6 != -1)
2840 {
2841 mDNSPlatformCloseFD(&ss->kqsv6, ss->sktv6);
2842 ss->sktv6 = -1;
2843 }
2844 if (ss->closeFlag) *ss->closeFlag = 1;
2845 }
2846
2847 mDNSexport void mDNSPlatformTCPCloseConnection(TCPSocket *sock)
2848 {
2849 if (sock)
2850 {
2851 #ifndef NO_SECURITYFRAMEWORK
2852 if (sock->tlsContext)
2853 {
2854 if (sock->handshake == handshake_in_progress) // SSLHandshake thread using this sock (esp. tlsContext)
2855 {
2856 LogInfo("mDNSPlatformTCPCloseConnection: called while handshake in progress");
2857 // When we come back from SSLHandshake, we will notice that a close was here and
2858 // call this function again which will do the cleanup then.
2859 sock->handshake = handshake_to_be_closed;
2860 return;
2861 }
2862
2863 SSLClose(sock->tlsContext);
2864 CFRelease(sock->tlsContext);
2865 sock->tlsContext = NULL;
2866 }
2867 #endif /* NO_SECURITYFRAMEWORK */
2868 if (sock->ss.sktv4 != -1)
2869 shutdown(sock->ss.sktv4, 2);
2870 if (sock->ss.sktv6 != -1)
2871 shutdown(sock->ss.sktv6, 2);
2872 CloseSocketSet(&sock->ss);
2873 sock->fd = -1;
2874
2875 freeL("TCPSocket/mDNSPlatformTCPCloseConnection", sock);
2876 }
2877 }
2878
2879 mDNSexport long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool *closed)
2880 {
2881 ssize_t nread = 0;
2882 *closed = mDNSfalse;
2883
2884 if (sock->flags & kTCPSocketFlags_UseTLS)
2885 {
2886 #ifndef NO_SECURITYFRAMEWORK
2887 if (sock->handshake == handshake_required) { LogMsg("mDNSPlatformReadTCP called while handshake required"); return 0; }
2888 else if (sock->handshake == handshake_in_progress) return 0;
2889 else if (sock->handshake != handshake_completed) LogMsg("mDNSPlatformReadTCP called with unexpected SSLHandshake status: %d", sock->handshake);
2890
2891 //LogMsg("Starting SSLRead %d %X", sock->fd, fcntl(sock->fd, F_GETFL, 0));
2892 mStatus err = SSLRead(sock->tlsContext, buf, buflen, (size_t *)&nread);
2893 //LogMsg("SSLRead returned %d (%d) nread %d buflen %d", err, errSSLWouldBlock, nread, buflen);
2894 if (err == errSSLClosedGraceful) { nread = 0; *closed = mDNStrue; }
2895 else if (err && err != errSSLWouldBlock)
2896 { LogMsg("ERROR: mDNSPlatformReadTCP - SSLRead: %d", err); nread = -1; *closed = mDNStrue; }
2897 #else
2898 nread = -1;
2899 *closed = mDNStrue;
2900 #endif /* NO_SECURITYFRAMEWORK */
2901 }
2902 else
2903 {
2904 static int CLOSEDcount = 0;
2905 static int EAGAINcount = 0;
2906 nread = recv(sock->fd, buf, buflen, 0);
2907
2908 if (nread > 0)
2909 {
2910 CLOSEDcount = 0;
2911 EAGAINcount = 0;
2912 } // On success, clear our error counters
2913 else if (nread == 0)
2914 {
2915 *closed = mDNStrue;
2916 if ((++CLOSEDcount % 1000) == 0)
2917 {
2918 LogMsg("ERROR: mDNSPlatformReadTCP - recv %d got CLOSED %d times", sock->fd, CLOSEDcount);
2919 assert(CLOSEDcount < 1000);
2920 // Recovery Mechanism to bail mDNSResponder out of trouble: Instead of logging the same error msg multiple times,
2921 // crash mDNSResponder using assert() and restart fresh. See advantages below:
2922 // 1.Better User Experience
2923 // 2.CrashLogs frequency can be monitored
2924 // 3.StackTrace can be used for more info
2925 }
2926 }
2927 // else nread is negative -- see what kind of error we got
2928 else if (errno == ECONNRESET) { nread = 0; *closed = mDNStrue; }
2929 else if (errno != EAGAIN) { LogMsg("ERROR: mDNSPlatformReadTCP - recv: %d (%s)", errno, strerror(errno)); nread = -1; }
2930 else // errno is EAGAIN (EWOULDBLOCK) -- no data available
2931 {
2932 nread = 0;
2933 if ((++EAGAINcount % 1000) == 0) { LogMsg("ERROR: mDNSPlatformReadTCP - recv %d got EAGAIN %d times", sock->fd, EAGAINcount); sleep(1); }
2934 }
2935 }
2936
2937 return nread;
2938 }
2939
2940 mDNSexport long mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len)
2941 {
2942 int nsent;
2943
2944 if (sock->flags & kTCPSocketFlags_UseTLS)
2945 {
2946 #ifndef NO_SECURITYFRAMEWORK
2947 size_t processed;
2948 if (sock->handshake == handshake_required) { LogMsg("mDNSPlatformWriteTCP called while handshake required"); return 0; }
2949 if (sock->handshake == handshake_in_progress) return 0;
2950 else if (sock->handshake != handshake_completed) LogMsg("mDNSPlatformWriteTCP called with unexpected SSLHandshake status: %d", sock->handshake);
2951
2952 mStatus err = SSLWrite(sock->tlsContext, msg, len, &processed);
2953
2954 if (!err) nsent = (int) processed;
2955 else if (err == errSSLWouldBlock) nsent = 0;
2956 else { LogMsg("ERROR: mDNSPlatformWriteTCP - SSLWrite returned %d", err); nsent = -1; }
2957 #else
2958 nsent = -1;
2959 #endif /* NO_SECURITYFRAMEWORK */
2960 }
2961 else
2962 {
2963 nsent = send(sock->fd, msg, len, 0);
2964 if (nsent < 0)
2965 {
2966 if (errno == EAGAIN) nsent = 0;
2967 else { LogMsg("ERROR: mDNSPlatformWriteTCP - send %s", strerror(errno)); nsent = -1; }
2968 }
2969 }
2970
2971 return nsent;
2972 }
2973
2974 mDNSexport int mDNSPlatformTCPGetFD(TCPSocket *sock)
2975 {
2976 return sock->fd;
2977 }
2978
2979 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
2980 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
2981 mDNSlocal mStatus SetupSocket(KQSocketSet *cp, const mDNSIPPort port, u_short sa_family, mDNSIPPort *const outport)
2982 {
2983 int *s = (sa_family == AF_INET) ? &cp->sktv4 : &cp->sktv6;
2984 KQueueEntry *k = (sa_family == AF_INET) ? &cp->kqsv4 : &cp->kqsv6;
2985 const int on = 1;
2986 const int twofivefive = 255;
2987 mStatus err = mStatus_NoError;
2988 char *errstr = mDNSNULL;
2989 const int mtu = 0;
2990
2991 cp->closeFlag = mDNSNULL;
2992
2993 int skt = socket(sa_family, SOCK_DGRAM, IPPROTO_UDP);
2994 if (skt < 3) { if (errno != EAFNOSUPPORT) LogMsg("SetupSocket: socket error %d errno %d (%s)", skt, errno, strerror(errno));return(skt); }
2995
2996 // set default traffic class
2997 setTrafficClass(skt, mDNSfalse);
2998
2999 #ifdef SO_RECV_ANYIF
3000 // Enable inbound packets on IFEF_AWDL interface.
3001 // Only done for multicast sockets, since we don't expect unicast socket operations
3002 // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
3003 if (mDNSSameIPPort(port, MulticastDNSPort))
3004 {
3005 err = setsockopt(skt, SOL_SOCKET, SO_RECV_ANYIF, &on, sizeof(on));
3006 if (err < 0) { errstr = "setsockopt - SO_RECV_ANYIF"; goto fail; }
3007 }
3008 #endif // SO_RECV_ANYIF
3009
3010 // ... with a shared UDP port, if it's for multicast receiving
3011 if (mDNSSameIPPort(port, MulticastDNSPort) || mDNSSameIPPort(port, NATPMPAnnouncementPort)) err = setsockopt(skt, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
3012 if (err < 0) { errstr = "setsockopt - SO_REUSEPORT"; goto fail; }
3013
3014 if (sa_family == AF_INET)
3015 {
3016 // We want to receive destination addresses
3017 err = setsockopt(skt, IPPROTO_IP, IP_RECVDSTADDR, &on, sizeof(on));
3018 if (err < 0) { errstr = "setsockopt - IP_RECVDSTADDR"; goto fail; }
3019
3020 // We want to receive interface identifiers
3021 err = setsockopt(skt, IPPROTO_IP, IP_RECVIF, &on, sizeof(on));
3022 if (err < 0) { errstr = "setsockopt - IP_RECVIF"; goto fail; }
3023
3024 // We want to receive packet TTL value so we can check it
3025 err = setsockopt(skt, IPPROTO_IP, IP_RECVTTL, &on, sizeof(on));
3026 // We ignore errors here -- we already know Jaguar doesn't support this, but we can get by without it
3027
3028 // Send unicast packets with TTL 255
3029 err = setsockopt(skt, IPPROTO_IP, IP_TTL, &twofivefive, sizeof(twofivefive));
3030 if (err < 0) { errstr = "setsockopt - IP_TTL"; goto fail; }
3031
3032 // And multicast packets with TTL 255 too
3033 err = setsockopt(skt, IPPROTO_IP, IP_MULTICAST_TTL, &twofivefive, sizeof(twofivefive));
3034 if (err < 0) { errstr = "setsockopt - IP_MULTICAST_TTL"; goto fail; }
3035
3036 // And start listening for packets
3037 struct sockaddr_in listening_sockaddr;
3038 listening_sockaddr.sin_family = AF_INET;
3039 listening_sockaddr.sin_port = port.NotAnInteger; // Pass in opaque ID without any byte swapping
3040 listening_sockaddr.sin_addr.s_addr = mDNSSameIPPort(port, NATPMPAnnouncementPort) ? AllHosts_v4.NotAnInteger : 0;
3041 err = bind(skt, (struct sockaddr *) &listening_sockaddr, sizeof(listening_sockaddr));
3042 if (err) { errstr = "bind"; goto fail; }
3043 if (outport) outport->NotAnInteger = listening_sockaddr.sin_port;
3044 }
3045 else if (sa_family == AF_INET6)
3046 {
3047 // NAT-PMP Announcements make no sense on IPv6, and we don't support IPv6 for PCP, so bail early w/o error
3048 if (mDNSSameIPPort(port, NATPMPAnnouncementPort)) { if (outport) *outport = zeroIPPort;return mStatus_NoError; }
3049
3050 // We want to receive destination addresses and receive interface identifiers
3051 err = setsockopt(skt, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on));
3052 if (err < 0) { errstr = "setsockopt - IPV6_RECVPKTINFO"; goto fail; }
3053
3054 // We want to receive packet hop count value so we can check it
3055 err = setsockopt(skt, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on, sizeof(on));
3056 if (err < 0) { errstr = "setsockopt - IPV6_RECVHOPLIMIT"; goto fail; }
3057
3058 // We want to receive only IPv6 packets. Without this option we get IPv4 packets too,
3059 // with mapped addresses of the form 0:0:0:0:0:FFFF:xxxx:xxxx, where xxxx:xxxx is the IPv4 address
3060 err = setsockopt(skt, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3061 if (err < 0) { errstr = "setsockopt - IPV6_V6ONLY"; goto fail; }
3062
3063 // Send unicast packets with TTL 255
3064 err = setsockopt(skt, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &twofivefive, sizeof(twofivefive));
3065 if (err < 0) { errstr = "setsockopt - IPV6_UNICAST_HOPS"; goto fail; }
3066
3067 // And multicast packets with TTL 255 too
3068 err = setsockopt(skt, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &twofivefive, sizeof(twofivefive));
3069 if (err < 0) { errstr = "setsockopt - IPV6_MULTICAST_HOPS"; goto fail; }
3070
3071 // Want to receive our own packets
3072 err = setsockopt(skt, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &on, sizeof(on));
3073 if (err < 0) { errstr = "setsockopt - IPV6_MULTICAST_LOOP"; goto fail; }
3074
3075 // Disable default option to send mDNSv6 packets at min IPv6 MTU: RFC 3542, Sec 11
3076 err = setsockopt(skt, IPPROTO_IPV6, IPV6_USE_MIN_MTU, &mtu, sizeof(mtu));
3077 if (err < 0) // Since it is an optimization if we fail just log the err, no need to close the skt
3078 LogMsg("SetupSocket: setsockopt - IPV6_USE_MIN_MTU: IP6PO_MINMTU_DISABLE socket %d err %d errno %d (%s)",
3079 skt, err, errno, strerror(errno));
3080
3081 // And start listening for packets
3082 struct sockaddr_in6 listening_sockaddr6;
3083 mDNSPlatformMemZero(&listening_sockaddr6, sizeof(listening_sockaddr6));
3084 listening_sockaddr6.sin6_len = sizeof(listening_sockaddr6);
3085 listening_sockaddr6.sin6_family = AF_INET6;
3086 listening_sockaddr6.sin6_port = port.NotAnInteger; // Pass in opaque ID without any byte swapping
3087 listening_sockaddr6.sin6_flowinfo = 0;
3088 listening_sockaddr6.sin6_addr = in6addr_any; // Want to receive multicasts AND unicasts on this socket
3089 listening_sockaddr6.sin6_scope_id = 0;
3090 err = bind(skt, (struct sockaddr *) &listening_sockaddr6, sizeof(listening_sockaddr6));
3091 if (err) { errstr = "bind"; goto fail; }
3092 if (outport) outport->NotAnInteger = listening_sockaddr6.sin6_port;
3093 }
3094
3095 fcntl(skt, F_SETFL, fcntl(skt, F_GETFL, 0) | O_NONBLOCK); // set non-blocking
3096 fcntl(skt, F_SETFD, 1); // set close-on-exec
3097 *s = skt;
3098 k->KQcallback = myKQSocketCallBack;
3099 k->KQcontext = cp;
3100 k->KQtask = "UDP packet reception";
3101 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
3102 k->readSource = mDNSNULL;
3103 k->writeSource = mDNSNULL;
3104 k->fdClosed = mDNSfalse;
3105 #endif
3106 KQueueSet(*s, EV_ADD, EVFILT_READ, k);
3107
3108 return(err);
3109
3110 fail:
3111 // For "bind" failures, only write log messages for our shared mDNS port, or for binding to zero
3112 if (strcmp(errstr, "bind") || mDNSSameIPPort(port, MulticastDNSPort) || mDNSIPPortIsZero(port))
3113 LogMsg("%s skt %d port %d error %d errno %d (%s)", errstr, skt, mDNSVal16(port), err, errno, strerror(errno));
3114
3115 // If we got a "bind" failure of EADDRINUSE, inform the caller as it might need to try another random port
3116 if (!strcmp(errstr, "bind") && errno == EADDRINUSE)
3117 {
3118 err = EADDRINUSE;
3119 if (mDNSSameIPPort(port, MulticastDNSPort))
3120 NotifyOfElusiveBug("Setsockopt SO_REUSEPORT failed",
3121 "Congratulations, you've reproduced an elusive bug.\r"
3122 "Please contact the current assignee of <rdar://problem/3814904>.\r"
3123 "Alternatively, you can send email to radar-3387020@group.apple.com. (Note number is different.)\r"
3124 "If possible, please leave your machine undisturbed so that someone can come to investigate the problem.");
3125 }
3126
3127 mDNSPlatformCloseFD(k, skt);
3128 return(err);
3129 }
3130
3131 mDNSexport UDPSocket *mDNSPlatformUDPSocket(mDNS *const m, const mDNSIPPort requestedport)
3132 {
3133 mStatus err;
3134 mDNSIPPort port = requestedport;
3135 mDNSBool randomizePort = mDNSIPPortIsZero(requestedport);
3136 int i = 10000; // Try at most 10000 times to get a unique random port
3137 UDPSocket *p = mallocL("UDPSocket", sizeof(UDPSocket));
3138 if (!p) { LogMsg("mDNSPlatformUDPSocket: memory exhausted"); return(mDNSNULL); }
3139 mDNSPlatformMemZero(p, sizeof(UDPSocket));
3140 p->ss.port = zeroIPPort;
3141 p->ss.m = m;
3142 p->ss.sktv4 = -1;
3143 p->ss.sktv6 = -1;
3144 p->ss.proxy = mDNSfalse;
3145
3146 do
3147 {
3148 // The kernel doesn't do cryptographically strong random port allocation, so we do it ourselves here
3149 if (randomizePort) port = mDNSOpaque16fromIntVal(0xC000 + mDNSRandom(0x3FFF));
3150 err = SetupSocket(&p->ss, port, AF_INET, &p->ss.port);
3151 if (!err)
3152 {
3153 err = SetupSocket(&p->ss, port, AF_INET6, &p->ss.port);
3154 if (err) { mDNSPlatformCloseFD(&p->ss.kqsv4, p->ss.sktv4); p->ss.sktv4 = -1; }
3155 }
3156 i--;
3157 } while (err == EADDRINUSE && randomizePort && i);
3158
3159 if (err)
3160 {
3161 // In customer builds we don't want to log failures with port 5351, because this is a known issue
3162 // of failing to bind to this port when Internet Sharing has already bound to it
3163 // We also don't want to log about port 5350, due to a known bug when some other
3164 // process is bound to it.
3165 if (mDNSSameIPPort(requestedport, NATPMPPort) || mDNSSameIPPort(requestedport, NATPMPAnnouncementPort))
3166 LogInfo("mDNSPlatformUDPSocket: SetupSocket %d failed error %d errno %d (%s)", mDNSVal16(requestedport), err, errno, strerror(errno));
3167 else LogMsg("mDNSPlatformUDPSocket: SetupSocket %d failed error %d errno %d (%s)", mDNSVal16(requestedport), err, errno, strerror(errno));
3168 freeL("UDPSocket", p);
3169 return(mDNSNULL);
3170 }
3171 return(p);
3172 }
3173
3174 mDNSexport void mDNSPlatformUDPClose(UDPSocket *sock)
3175 {
3176 CloseSocketSet(&sock->ss);
3177 freeL("UDPSocket", sock);
3178 }
3179
3180 #if COMPILER_LIKES_PRAGMA_MARK
3181 #pragma mark -
3182 #pragma mark - BPF Raw packet sending/receiving
3183 #endif
3184
3185 #if APPLE_OSX_mDNSResponder
3186
3187 mDNSexport void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID)
3188 {
3189 if (!InterfaceID) { LogMsg("mDNSPlatformSendRawPacket: No InterfaceID specified"); return; }
3190 NetworkInterfaceInfoOSX *info;
3191
3192 info = IfindexToInterfaceInfoOSX(&mDNSStorage, InterfaceID);
3193 if (info == NULL)
3194 {
3195 LogMsg("mDNSPlatformSendUDP: Invalid interface index %p", InterfaceID);
3196 return;
3197 }
3198 if (info->BPF_fd < 0)
3199 LogMsg("mDNSPlatformSendRawPacket: %s BPF_fd %d not ready", info->ifinfo.ifname, info->BPF_fd);
3200 else
3201 {
3202 //LogMsg("mDNSPlatformSendRawPacket %d bytes on %s", end - (mDNSu8 *)msg, info->ifinfo.ifname);
3203 if (write(info->BPF_fd, msg, end - (mDNSu8 *)msg) < 0)
3204 LogMsg("mDNSPlatformSendRawPacket: BPF write(%d) failed %d (%s)", info->BPF_fd, errno, strerror(errno));
3205 }
3206 }
3207
3208 mDNSexport void mDNSPlatformSetLocalAddressCacheEntry(mDNS *const m, const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID)
3209 {
3210 if (!InterfaceID) { LogMsg("mDNSPlatformSetLocalAddressCacheEntry: No InterfaceID specified"); return; }
3211 NetworkInterfaceInfoOSX *info;
3212 info = IfindexToInterfaceInfoOSX(m, InterfaceID);
3213 if (info == NULL) { LogMsg("mDNSPlatformSetLocalAddressCacheEntry: Invalid interface index %p", InterfaceID); return; }
3214 // Manually inject an entry into our local ARP cache.
3215 // (We can't do this by sending an ARP broadcast, because the kernel only pays attention to incoming ARP packets, not outgoing.)
3216 if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, tpa, mDNSNULL))
3217 LogSPS("Don't need address cache entry for %s %#a %.6a", info->ifinfo.ifname, tpa, tha);
3218 else
3219 {
3220 int result = mDNSSetLocalAddressCacheEntry(info->scope_id, tpa->type, tpa->ip.v6.b, tha->b);
3221 if (result) LogMsg("Set local address cache entry for %s %#a %.6a failed: %d", info->ifinfo.ifname, tpa, tha, result);
3222 else LogSPS("Set local address cache entry for %s %#a %.6a", info->ifinfo.ifname, tpa, tha);
3223 }
3224 }
3225
3226 mDNSlocal void CloseBPF(NetworkInterfaceInfoOSX *const i)
3227 {
3228 LogSPS("%s closing BPF fd %d", i->ifinfo.ifname, i->BPF_fd);
3229 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
3230 // close will happen in the cancel handler
3231 dispatch_source_cancel(i->BPF_source);
3232 #else
3233
3234 // Note: MUST NOT close() the underlying native BSD sockets.
3235 // CFSocketInvalidate() will do that for us, in its own good time, which may not necessarily be immediately, because
3236 // it first has to unhook the sockets from its select() call on its other thread, before it can safely close them.
3237 CFRunLoopRemoveSource(i->m->p->CFRunLoop, i->BPF_rls, kCFRunLoopDefaultMode);
3238 CFRelease(i->BPF_rls);
3239 CFSocketInvalidate(i->BPF_cfs);
3240 CFRelease(i->BPF_cfs);
3241 #endif
3242 i->BPF_fd = -1;
3243 if (i->BPF_mcfd >= 0) { close(i->BPF_mcfd); i->BPF_mcfd = -1; }
3244 }
3245
3246 mDNSlocal void bpf_callback_common(NetworkInterfaceInfoOSX *info)
3247 {
3248 KQueueLock(info->m);
3249
3250 // Now we've got the lock, make sure the kqueue thread didn't close the fd out from under us (will not be a problem once the OS X
3251 // kernel has a mechanism for dispatching all events to a single thread, but for now we have to guard against this race condition).
3252 if (info->BPF_fd < 0) goto exit;
3253
3254 ssize_t n = read(info->BPF_fd, &info->m->imsg, info->BPF_len);
3255 const mDNSu8 *ptr = (const mDNSu8 *)&info->m->imsg;
3256 const mDNSu8 *end = (const mDNSu8 *)&info->m->imsg + n;
3257 debugf("%3d: bpf_callback got %d bytes on %s", info->BPF_fd, n, info->ifinfo.ifname);
3258
3259 if (n<0)
3260 {
3261 /* <rdar://problem/10287386>
3262 * sometimes there can be a race condition btw when the bpf socket
3263 * gets data and the callback get scheduled and when we call BIOCSETF (which
3264 * clears the socket). this can cause the read to hang for a really long time
3265 * and effectively prevent us from responding to requests for long periods of time.
3266 * to prevent this make the socket non blocking and just bail if we dont get anything
3267 */
3268 if (errno == EAGAIN)
3269 {
3270 LogMsg("bpf_callback got EAGAIN bailing");
3271 goto exit;
3272 }
3273 LogMsg("Closing %s BPF fd %d due to error %d (%s)", info->ifinfo.ifname, info->BPF_fd, errno, strerror(errno));
3274 CloseBPF(info);
3275 goto exit;
3276 }
3277
3278 while (ptr < end)
3279 {
3280 const struct bpf_hdr *const bh = (const struct bpf_hdr *)ptr;
3281 debugf("%3d: bpf_callback ptr %p bh_hdrlen %d data %p bh_caplen %4d bh_datalen %4d next %p remaining %4d",
3282 info->BPF_fd, ptr, bh->bh_hdrlen, ptr + bh->bh_hdrlen, bh->bh_caplen, bh->bh_datalen,
3283 ptr + BPF_WORDALIGN(bh->bh_hdrlen + bh->bh_caplen), end - (ptr + BPF_WORDALIGN(bh->bh_hdrlen + bh->bh_caplen)));
3284 // Note that BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
3285 // Given that An Ethernet header is 14 bytes, this means that if the network layer header (e.g. IP header,
3286 // ARP message, etc.) is 4-byte aligned, then necessarily the Ethernet header will be NOT be 4-byte aligned.
3287 mDNSCoreReceiveRawPacket(info->m, ptr + bh->bh_hdrlen, ptr + bh->bh_hdrlen + bh->bh_caplen, info->ifinfo.InterfaceID);
3288 ptr += BPF_WORDALIGN(bh->bh_hdrlen + bh->bh_caplen);
3289 }
3290 exit:
3291 KQueueUnlock(info->m, "bpf_callback");
3292 }
3293 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
3294 mDNSlocal void bpf_callback_dispatch(NetworkInterfaceInfoOSX *const info)
3295 {
3296 bpf_callback_common(info);
3297 }
3298 #else
3299 mDNSlocal void bpf_callback(const CFSocketRef cfs, const CFSocketCallBackType CallBackType, const CFDataRef address, const void *const data, void *const context)
3300 {
3301 (void)cfs;
3302 (void)CallBackType;
3303 (void)address;
3304 (void)data;
3305 bpf_callback_common((NetworkInterfaceInfoOSX *)context);
3306 }
3307 #endif
3308
3309 mDNSexport void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win)
3310 {
3311 LogMsg("mDNSPlatformSendKeepalive called\n");
3312 mDNSSendKeepalive(sadd->ip.v6.b, dadd->ip.v6.b, lport->NotAnInteger, rport->NotAnInteger, seq, ack, win);
3313 }
3314
3315 mDNSexport mStatus mDNSPlatformClearSPSMACAddr(void)
3316 {
3317 SCDynamicStoreRef store = NULL;
3318 CFStringRef entityname = NULL;
3319
3320 if ((store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:ClearSPSMACAddress"), NULL, NULL)))
3321 {
3322 if ((entityname = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%s%s%s"), "State:/Network/Interface/", "[^/]", "/BonjourSleepProxyAddress")))
3323 {
3324 if (SCDynamicStoreRemoveValue(store, entityname) == false)
3325 LogMsg("mDNSPlatformClearSPSMACAddr: Unable to remove key");
3326 }
3327 }
3328
3329 if (entityname) CFRelease(entityname);
3330 if (store) CFRelease(store);
3331 return KERN_SUCCESS;
3332 }
3333
3334 mDNSexport mStatus mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname)
3335 {
3336 int family = (spsaddr->type == mDNSAddrType_IPv4) ? AF_INET : AF_INET6;
3337 LogSPS("mDNSPlatformStoreSPSMACAddr : Storing %#a on interface %s", spsaddr, ifname);
3338 mDNSStoreSPSMACAddress(family, spsaddr->ip.v6.b, ifname);
3339 return KERN_SUCCESS;
3340 }
3341
3342 mDNSexport mStatus mDNSPlatformGetRemoteMacAddr(mDNS *const m, mDNSAddr *raddr)
3343 {
3344 int family = (raddr->type == mDNSAddrType_IPv4) ? AF_INET : AF_INET6;
3345
3346 mDNSGetRemoteMAC(m, family, raddr->ip.v6.b);
3347 return KERN_SUCCESS;
3348 }
3349
3350 mDNSexport mStatus mDNSPlatformRetrieveTCPInfo(mDNS *const m, mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti)
3351 {
3352 mDNSs32 intfid;
3353 mDNSs32 error = 0;
3354 int family = (laddr->type == mDNSAddrType_IPv4) ? AF_INET : AF_INET6;
3355
3356 error = mDNSRetrieveTCPInfo(family, laddr->ip.v6.b, lport->NotAnInteger, raddr->ip.v6.b, rport->NotAnInteger, (uint32_t *)&(mti->seq), (uint32_t *)&(mti->ack), (uint16_t *)&(mti->window), (int32_t*)&intfid);
3357 if (error != KERN_SUCCESS)
3358 {
3359 LogMsg("%s: mDNSRetrieveTCPInfo returned : %d", __func__, error);
3360 return error;
3361 }
3362 mti->IntfId = mDNSPlatformInterfaceIDfromInterfaceIndex(m, intfid);
3363 return error;
3364 }
3365
3366 #define BPF_SetOffset(from, cond, to) (from)->cond = (to) - 1 - (from)
3367
3368 mDNSlocal int CountProxyTargets(mDNS *const m, NetworkInterfaceInfoOSX *x, int *p4, int *p6)
3369 {
3370 int numv4 = 0, numv6 = 0;
3371 AuthRecord *rr;
3372
3373 for (rr = m->ResourceRecords; rr; rr=rr->next)
3374 if (rr->resrec.InterfaceID == x->ifinfo.InterfaceID && rr->AddressProxy.type == mDNSAddrType_IPv4)
3375 {
3376 if (p4) LogSPS("CountProxyTargets: fd %d %-7s IP%2d %.4a", x->BPF_fd, x->ifinfo.ifname, numv4, &rr->AddressProxy.ip.v4);
3377 numv4++;
3378 }
3379
3380 for (rr = m->ResourceRecords; rr; rr=rr->next)
3381 if (rr->resrec.InterfaceID == x->ifinfo.InterfaceID && rr->AddressProxy.type == mDNSAddrType_IPv6)
3382 {
3383 if (p6) LogSPS("CountProxyTargets: fd %d %-7s IP%2d %.16a", x->BPF_fd, x->ifinfo.ifname, numv6, &rr->AddressProxy.ip.v6);
3384 numv6++;
3385 }
3386
3387 if (p4) *p4 = numv4;
3388 if (p6) *p6 = numv6;
3389 return(numv4 + numv6);
3390 }
3391
3392 mDNSexport void mDNSPlatformUpdateProxyList(mDNS *const m, const mDNSInterfaceID InterfaceID)
3393 {
3394 NetworkInterfaceInfoOSX *x;
3395
3396 // Note: We can't use IfIndexToInterfaceInfoOSX because that looks for Registered also.
3397 for (x = m->p->InterfaceList; x; x = x->next) if (x->ifinfo.InterfaceID == InterfaceID) break;
3398
3399 if (!x) { LogMsg("mDNSPlatformUpdateProxyList: ERROR InterfaceID %p not found", InterfaceID); return; }
3400
3401 #define MAX_BPF_ADDRS 250
3402 int numv4 = 0, numv6 = 0;
3403
3404 if (CountProxyTargets(m, x, &numv4, &numv6) > MAX_BPF_ADDRS)
3405 {
3406 LogMsg("mDNSPlatformUpdateProxyList: ERROR Too many address proxy records v4 %d v6 %d", numv4, numv6);
3407 if (numv4 > MAX_BPF_ADDRS) numv4 = MAX_BPF_ADDRS;
3408 numv6 = MAX_BPF_ADDRS - numv4;
3409 }
3410
3411 LogSPS("mDNSPlatformUpdateProxyList: fd %d %-7s MAC %.6a %d v4 %d v6", x->BPF_fd, x->ifinfo.ifname, &x->ifinfo.MAC, numv4, numv6);
3412
3413 // Caution: This is a static structure, so we need to be careful that any modifications we make to it
3414 // are done in such a way that they work correctly when mDNSPlatformUpdateProxyList is called multiple times
3415 static struct bpf_insn filter[17 + MAX_BPF_ADDRS] =
3416 {
3417 BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12), // 0 Read Ethertype (bytes 12,13)
3418
3419 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0806, 0, 1), // 1 If Ethertype == ARP goto next, else 3
3420 BPF_STMT(BPF_RET + BPF_K, 42), // 2 Return 42-byte ARP
3421
3422 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x0800, 4, 0), // 3 If Ethertype == IPv4 goto 8 (IPv4 address list check) else next
3423
3424 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x86DD, 0, 9), // 4 If Ethertype == IPv6 goto next, else exit
3425 BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20), // 5 Read Protocol and Hop Limit (bytes 20,21)
3426 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 0x3AFF, 0, 9), // 6 If (Prot,TTL) == (3A,FF) goto next, else IPv6 address list check
3427 BPF_STMT(BPF_RET + BPF_K, 86), // 7 Return 86-byte ND
3428
3429 // Is IPv4 packet; check if it's addressed to any IPv4 address we're proxying for
3430 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, 30), // 8 Read IPv4 Dst (bytes 30,31,32,33)
3431 };
3432
3433 struct bpf_insn *pc = &filter[9];
3434 struct bpf_insn *chk6 = pc + numv4 + 1; // numv4 address checks, plus a "return 0"
3435 struct bpf_insn *fail = chk6 + 1 + numv6; // Get v6 Dst LSW, plus numv6 address checks
3436 struct bpf_insn *ret4 = fail + 1;
3437 struct bpf_insn *ret6 = ret4 + 4;
3438
3439 static const struct bpf_insn rf = BPF_STMT(BPF_RET + BPF_K, 0); // No match: Return nothing
3440
3441 static const struct bpf_insn g6 = BPF_STMT(BPF_LD + BPF_W + BPF_ABS, 50); // Read IPv6 Dst LSW (bytes 50,51,52,53)
3442
3443 static const struct bpf_insn r4a = BPF_STMT(BPF_LDX + BPF_B + BPF_MSH, 14); // Get IP Header length (normally 20)
3444 static const struct bpf_insn r4b = BPF_STMT(BPF_LD + BPF_IMM, 54); // A = 54 (14-byte Ethernet plus 20-byte TCP + 20 bytes spare)
3445 static const struct bpf_insn r4c = BPF_STMT(BPF_ALU + BPF_ADD + BPF_X, 0); // A += IP Header length
3446 static const struct bpf_insn r4d = BPF_STMT(BPF_RET + BPF_A, 0); // Success: Return Ethernet + IP + TCP + 20 bytes spare (normally 74)
3447
3448 static const struct bpf_insn r6a = BPF_STMT(BPF_RET + BPF_K, 94); // Success: Return Eth + IPv6 + TCP + 20 bytes spare
3449
3450 BPF_SetOffset(&filter[4], jf, fail); // If Ethertype not ARP, IPv4, or IPv6, fail
3451 BPF_SetOffset(&filter[6], jf, chk6); // If IPv6 but not ICMPv6, go to IPv6 address list check
3452
3453 // BPF Byte-Order Note
3454 // The BPF API designers apparently thought that programmers would not be smart enough to use htons
3455 // and htonl correctly to convert numeric values to network byte order on little-endian machines,
3456 // so instead they chose to make the API implicitly byte-swap *ALL* values, even literal byte strings
3457 // that shouldn't be byte-swapped, like ASCII text, Ethernet addresses, IP addresses, etc.
3458 // As a result, if we put Ethernet addresses and IP addresses in the right byte order, the BPF API
3459 // will byte-swap and make them backwards, and then our filter won't work. So, we have to arrange
3460 // that on little-endian machines we deliberately put addresses in memory with the bytes backwards,
3461 // so that when the BPF API goes through and swaps them all, they end up back as they should be.
3462 // In summary, if we byte-swap all the non-numeric fields that shouldn't be swapped, and we *don't*
3463 // swap any of the numeric values that *should* be byte-swapped, then the filter will work correctly.
3464
3465 // IPSEC capture size notes:
3466 // 8 bytes UDP header
3467 // 4 bytes Non-ESP Marker
3468 // 28 bytes IKE Header
3469 // --
3470 // 40 Total. Capturing TCP Header + 20 gets us enough bytes to receive the IKE Header in a UDP-encapsulated IKE packet.
3471
3472 AuthRecord *rr;
3473 for (rr = m->ResourceRecords; rr; rr=rr->next)
3474 if (rr->resrec.InterfaceID == InterfaceID && rr->AddressProxy.type == mDNSAddrType_IPv4)
3475 {
3476 mDNSv4Addr a = rr->AddressProxy.ip.v4;
3477 pc->code = BPF_JMP + BPF_JEQ + BPF_K;
3478 BPF_SetOffset(pc, jt, ret4);
3479 pc->jf = 0;
3480 pc->k = (bpf_u_int32)a.b[0] << 24 | (bpf_u_int32)a.b[1] << 16 | (bpf_u_int32)a.b[2] << 8 | (bpf_u_int32)a.b[3];
3481 pc++;
3482 }
3483 *pc++ = rf;
3484
3485 if (pc != chk6) LogMsg("mDNSPlatformUpdateProxyList: pc %p != chk6 %p", pc, chk6);
3486 *pc++ = g6; // chk6 points here
3487
3488 // First cancel any previous ND group memberships we had, then create a fresh socket
3489 if (x->BPF_mcfd >= 0) close(x->BPF_mcfd);
3490 x->BPF_mcfd = socket(AF_INET6, SOCK_DGRAM, 0);
3491
3492 for (rr = m->ResourceRecords; rr; rr=rr->next)
3493 if (rr->resrec.InterfaceID == InterfaceID && rr->AddressProxy.type == mDNSAddrType_IPv6)
3494 {
3495 const mDNSv6Addr *const a = &rr->AddressProxy.ip.v6;
3496 pc->code = BPF_JMP + BPF_JEQ + BPF_K;
3497 BPF_SetOffset(pc, jt, ret6);
3498 pc->jf = 0;
3499 pc->k = (bpf_u_int32)a->b[0x0C] << 24 | (bpf_u_int32)a->b[0x0D] << 16 | (bpf_u_int32)a->b[0x0E] << 8 | (bpf_u_int32)a->b[0x0F];
3500 pc++;
3501
3502 struct ipv6_mreq i6mr;
3503 i6mr.ipv6mr_interface = x->scope_id;
3504 i6mr.ipv6mr_multiaddr = *(const struct in6_addr*)&NDP_prefix;
3505 i6mr.ipv6mr_multiaddr.s6_addr[0xD] = a->b[0xD];
3506 i6mr.ipv6mr_multiaddr.s6_addr[0xE] = a->b[0xE];
3507 i6mr.ipv6mr_multiaddr.s6_addr[0xF] = a->b[0xF];
3508
3509 // Do precautionary IPV6_LEAVE_GROUP first, necessary to clear stale kernel state
3510 mStatus err = setsockopt(x->BPF_mcfd, IPPROTO_IPV6, IPV6_LEAVE_GROUP, &i6mr, sizeof(i6mr));
3511 if (err < 0 && (errno != EADDRNOTAVAIL))
3512 LogMsg("mDNSPlatformUpdateProxyList: IPV6_LEAVE_GROUP error %d errno %d (%s) group %.16a on %u", err, errno, strerror(errno), &i6mr.ipv6mr_multiaddr, i6mr.ipv6mr_interface);
3513
3514 err = setsockopt(x->BPF_mcfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &i6mr, sizeof(i6mr));
3515 if (err < 0 && (errno != EADDRINUSE)) // Joining same group twice can give "Address already in use" error -- no need to report that
3516 LogMsg("mDNSPlatformUpdateProxyList: IPV6_JOIN_GROUP error %d errno %d (%s) group %.16a on %u", err, errno, strerror(errno), &i6mr.ipv6mr_multiaddr, i6mr.ipv6mr_interface);
3517
3518 LogSPS("Joined IPv6 ND multicast group %.16a for %.16a", &i6mr.ipv6mr_multiaddr, a);
3519 }
3520
3521 if (pc != fail) LogMsg("mDNSPlatformUpdateProxyList: pc %p != fail %p", pc, fail);
3522 *pc++ = rf; // fail points here
3523
3524 if (pc != ret4) LogMsg("mDNSPlatformUpdateProxyList: pc %p != ret4 %p", pc, ret4);
3525 *pc++ = r4a; // ret4 points here
3526 *pc++ = r4b;
3527 *pc++ = r4c;
3528 *pc++ = r4d;
3529
3530 if (pc != ret6) LogMsg("mDNSPlatformUpdateProxyList: pc %p != ret6 %p", pc, ret6);
3531 *pc++ = r6a; // ret6 points here
3532
3533 struct bpf_program prog = { pc - filter, filter };
3534
3535 #if 0
3536 // For debugging BPF filter program
3537 unsigned int q;
3538 for (q=0; q<prog.bf_len; q++)
3539 LogSPS("mDNSPlatformUpdateProxyList: %2d { 0x%02x, %d, %d, 0x%08x },", q, prog.bf_insns[q].code, prog.bf_insns[q].jt, prog.bf_insns[q].jf, prog.bf_insns[q].k);
3540 #endif
3541
3542 if (!numv4 && !numv6)
3543 {
3544 LogSPS("mDNSPlatformUpdateProxyList: No need for filter");
3545 if (m->timenow == 0) LogMsg("mDNSPlatformUpdateProxyList: m->timenow == 0");
3546 // Schedule check to see if we can close this BPF_fd now
3547 if (!m->p->NetworkChanged) m->p->NetworkChanged = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 2);
3548 // prog.bf_len = 0; This seems to panic the kernel
3549 if (x->BPF_fd < 0) return; // If we've already closed our BPF_fd, no need to generate an error message below
3550 }
3551
3552 if (ioctl(x->BPF_fd, BIOCSETFNR, &prog) < 0) LogMsg("mDNSPlatformUpdateProxyList: BIOCSETFNR(%d) failed %d (%s)", prog.bf_len, errno, strerror(errno));
3553 else LogSPS("mDNSPlatformUpdateProxyList: BIOCSETFNR(%d) successful", prog.bf_len);
3554 }
3555
3556 mDNSexport void mDNSPlatformReceiveBPF_fd(mDNS *const m, int fd)
3557 {
3558 mDNS_Lock(m);
3559
3560 NetworkInterfaceInfoOSX *i;
3561 for (i = m->p->InterfaceList; i; i = i->next) if (i->BPF_fd == -2) break;
3562 if (!i) { LogSPS("mDNSPlatformReceiveBPF_fd: No Interfaces awaiting BPF fd %d; closing", fd); close(fd); }
3563 else
3564 {
3565 LogSPS("%s using BPF fd %d", i->ifinfo.ifname, fd);
3566
3567 struct bpf_version v;
3568 if (ioctl(fd, BIOCVERSION, &v) < 0)
3569 LogMsg("mDNSPlatformReceiveBPF_fd: %d %s BIOCVERSION failed %d (%s)", fd, i->ifinfo.ifname, errno, strerror(errno));
3570 else if (BPF_MAJOR_VERSION != v.bv_major || BPF_MINOR_VERSION != v.bv_minor)
3571 LogMsg("mDNSPlatformReceiveBPF_fd: %d %s BIOCVERSION header %d.%d kernel %d.%d",
3572 fd, i->ifinfo.ifname, BPF_MAJOR_VERSION, BPF_MINOR_VERSION, v.bv_major, v.bv_minor);
3573
3574 if (ioctl(fd, BIOCGBLEN, &i->BPF_len) < 0)
3575 LogMsg("mDNSPlatformReceiveBPF_fd: %d %s BIOCGBLEN failed %d (%s)", fd, i->ifinfo.ifname, errno, strerror(errno));
3576
3577 if (i->BPF_len > sizeof(m->imsg))
3578 {
3579 i->BPF_len = sizeof(m->imsg);
3580 if (ioctl(fd, BIOCSBLEN, &i->BPF_len) < 0)
3581 LogMsg("mDNSPlatformReceiveBPF_fd: %d %s BIOCSBLEN failed %d (%s)", fd, i->ifinfo.ifname, errno, strerror(errno));
3582 else
3583 LogSPS("mDNSPlatformReceiveBPF_fd: %d %s BIOCSBLEN %d", fd, i->ifinfo.ifname, i->BPF_len);
3584 }
3585
3586 static const u_int opt_one = 1;
3587 if (ioctl(fd, BIOCIMMEDIATE, &opt_one) < 0)
3588 LogMsg("mDNSPlatformReceiveBPF_fd: %d %s BIOCIMMEDIATE failed %d (%s)", fd, i->ifinfo.ifname, errno, strerror(errno));
3589
3590 //if (ioctl(fd, BIOCPROMISC, &opt_one) < 0)
3591 // LogMsg("mDNSPlatformReceiveBPF_fd: %d %s BIOCPROMISC failed %d (%s)", fd, i->ifinfo.ifname, errno, strerror(errno));
3592
3593 //if (ioctl(fd, BIOCSHDRCMPLT, &opt_one) < 0)
3594 // LogMsg("mDNSPlatformReceiveBPF_fd: %d %s BIOCSHDRCMPLT failed %d (%s)", fd, i->ifinfo.ifname, errno, strerror(errno));
3595
3596 /* <rdar://problem/10287386>
3597 * make socket non blocking see comments in bpf_callback_common for more info
3598 */
3599 if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK) < 0) // set non-blocking
3600 {
3601 LogMsg("mDNSPlatformReceiveBPF_fd: %d %s O_NONBLOCK failed %d (%s)", fd, i->ifinfo.ifname, errno, strerror(errno));
3602 }
3603
3604 struct ifreq ifr;
3605 mDNSPlatformMemZero(&ifr, sizeof(ifr));
3606 strlcpy(ifr.ifr_name, i->ifinfo.ifname, sizeof(ifr.ifr_name));
3607 if (ioctl(fd, BIOCSETIF, &ifr) < 0)
3608 { LogMsg("mDNSPlatformReceiveBPF_fd: %d %s BIOCSETIF failed %d (%s)", fd, i->ifinfo.ifname, errno, strerror(errno)); i->BPF_fd = -3; }
3609 else
3610 {
3611 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
3612 i->BPF_fd = fd;
3613 i->BPF_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, dispatch_get_main_queue());
3614 if (!i->BPF_source) {LogMsg("mDNSPlatformReceiveBPF_fd: dispatch source create failed"); return;}
3615 dispatch_source_set_event_handler(i->BPF_source, ^{bpf_callback_dispatch(i);});
3616 dispatch_source_set_cancel_handler(i->BPF_source, ^{close(fd);});
3617 dispatch_resume(i->BPF_source);
3618 #else
3619 CFSocketContext myCFSocketContext = { 0, i, NULL, NULL, NULL };
3620 i->BPF_fd = fd;
3621 i->BPF_cfs = CFSocketCreateWithNative(kCFAllocatorDefault, fd, kCFSocketReadCallBack, bpf_callback, &myCFSocketContext);
3622 i->BPF_rls = CFSocketCreateRunLoopSource(kCFAllocatorDefault, i->BPF_cfs, 0);
3623 CFRunLoopAddSource(i->m->p->CFRunLoop, i->BPF_rls, kCFRunLoopDefaultMode);
3624 #endif
3625 mDNSPlatformUpdateProxyList(m, i->ifinfo.InterfaceID);
3626 }
3627 }
3628
3629 mDNS_Unlock(m);
3630 }
3631
3632 #endif // APPLE_OSX_mDNSResponder
3633
3634 #if COMPILER_LIKES_PRAGMA_MARK
3635 #pragma mark -
3636 #pragma mark - Key Management
3637 #endif
3638
3639 #ifndef NO_SECURITYFRAMEWORK
3640 mDNSlocal CFArrayRef GetCertChain(SecIdentityRef identity)
3641 {
3642 CFMutableArrayRef certChain = NULL;
3643 if (!identity) { LogMsg("getCertChain: identity is NULL"); return(NULL); }
3644 SecCertificateRef cert;
3645 OSStatus err = SecIdentityCopyCertificate(identity, &cert);
3646 if (err || !cert) LogMsg("getCertChain: SecIdentityCopyCertificate() returned %d", (int) err);
3647 else
3648 {
3649 SecPolicySearchRef searchRef;
3650 err = SecPolicySearchCreate(CSSM_CERT_X_509v3, &CSSMOID_APPLE_X509_BASIC, NULL, &searchRef);
3651 if (err || !searchRef) LogMsg("getCertChain: SecPolicySearchCreate() returned %d", (int) err);
3652 else
3653 {
3654 SecPolicyRef policy;
3655 err = SecPolicySearchCopyNext(searchRef, &policy);
3656 if (err || !policy) LogMsg("getCertChain: SecPolicySearchCopyNext() returned %d", (int) err);
3657 else
3658 {
3659 CFArrayRef wrappedCert = CFArrayCreate(NULL, (const void**) &cert, 1, &kCFTypeArrayCallBacks);
3660 if (!wrappedCert) LogMsg("getCertChain: wrappedCert is NULL");
3661 else
3662 {
3663 SecTrustRef trust;
3664 err = SecTrustCreateWithCertificates(wrappedCert, policy, &trust);
3665 if (err || !trust) LogMsg("getCertChain: SecTrustCreateWithCertificates() returned %d", (int) err);
3666 else
3667 {
3668 err = SecTrustEvaluate(trust, NULL);
3669 if (err) LogMsg("getCertChain: SecTrustEvaluate() returned %d", (int) err);
3670 else
3671 {
3672 CFArrayRef rawCertChain;
3673 CSSM_TP_APPLE_EVIDENCE_INFO *statusChain = NULL;
3674 err = SecTrustGetResult(trust, NULL, &rawCertChain, &statusChain);
3675 if (err || !rawCertChain || !statusChain) LogMsg("getCertChain: SecTrustGetResult() returned %d", (int) err);
3676 else
3677 {
3678 certChain = CFArrayCreateMutableCopy(NULL, 0, rawCertChain);
3679 if (!certChain) LogMsg("getCertChain: certChain is NULL");
3680 else
3681 {
3682 // Replace the SecCertificateRef at certChain[0] with a SecIdentityRef per documentation for SSLSetCertificate:
3683 // <http://devworld.apple.com/documentation/Security/Reference/secureTransportRef/index.html>
3684 CFArraySetValueAtIndex(certChain, 0, identity);
3685 // Remove root from cert chain, but keep any and all intermediate certificates that have been signed by the root certificate
3686 if (CFArrayGetCount(certChain) > 1) CFArrayRemoveValueAtIndex(certChain, CFArrayGetCount(certChain) - 1);
3687 }
3688 CFRelease(rawCertChain);
3689 // Do not free statusChain:
3690 // <http://developer.apple.com/documentation/Security/Reference/certifkeytrustservices/Reference/reference.html> says:
3691 // certChain: Call the CFRelease function to release this object when you are finished with it.
3692 // statusChain: Do not attempt to free this pointer; it remains valid until the trust management object is released...
3693 }
3694 }
3695 CFRelease(trust);
3696 }
3697 CFRelease(wrappedCert);
3698 }
3699 CFRelease(policy);
3700 }
3701 CFRelease(searchRef);
3702 }
3703 CFRelease(cert);
3704 }
3705 return certChain;
3706 }
3707 #endif /* NO_SECURITYFRAMEWORK */
3708
3709 mDNSexport mStatus mDNSPlatformTLSSetupCerts(void)
3710 {
3711 #ifdef NO_SECURITYFRAMEWORK
3712 return mStatus_UnsupportedErr;
3713 #else
3714 SecIdentityRef identity = nil;
3715 SecIdentitySearchRef srchRef = nil;
3716 OSStatus err;
3717
3718 // search for "any" identity matching specified key use
3719 // In this app, we expect there to be exactly one
3720 err = SecIdentitySearchCreate(NULL, CSSM_KEYUSE_DECRYPT, &srchRef);
3721 if (err) { LogMsg("ERROR: mDNSPlatformTLSSetupCerts: SecIdentitySearchCreate returned %d", (int) err); return err; }
3722
3723 err = SecIdentitySearchCopyNext(srchRef, &identity);
3724 if (err) { LogMsg("ERROR: mDNSPlatformTLSSetupCerts: SecIdentitySearchCopyNext returned %d", (int) err); return err; }
3725
3726 if (CFGetTypeID(identity) != SecIdentityGetTypeID())
3727 { LogMsg("ERROR: mDNSPlatformTLSSetupCerts: SecIdentitySearchCopyNext CFTypeID failure"); return mStatus_UnknownErr; }
3728
3729 // Found one. Call getCertChain to create the correct certificate chain.
3730 ServerCerts = GetCertChain(identity);
3731 if (ServerCerts == nil) { LogMsg("ERROR: mDNSPlatformTLSSetupCerts: getCertChain error"); return mStatus_UnknownErr; }
3732
3733 return mStatus_NoError;
3734 #endif /* NO_SECURITYFRAMEWORK */
3735 }
3736
3737 mDNSexport void mDNSPlatformTLSTearDownCerts(void)
3738 {
3739 #ifndef NO_SECURITYFRAMEWORK
3740 if (ServerCerts) { CFRelease(ServerCerts); ServerCerts = NULL; }
3741 #endif /* NO_SECURITYFRAMEWORK */
3742 }
3743
3744 // This gets the text of the field currently labelled "Computer Name" in the Sharing Prefs Control Panel
3745 mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
3746 {
3747 CFStringEncoding encoding = kCFStringEncodingUTF8;
3748 CFStringRef cfs = SCDynamicStoreCopyComputerName(NULL, &encoding);
3749 if (cfs)
3750 {
3751 CFStringGetPascalString(cfs, namelabel->c, sizeof(*namelabel), kCFStringEncodingUTF8);
3752 CFRelease(cfs);
3753 }
3754 }
3755
3756 // This gets the text of the field currently labelled "Local Hostname" in the Sharing Prefs Control Panel
3757 mDNSlocal void GetUserSpecifiedLocalHostName(domainlabel *const namelabel)
3758 {
3759 CFStringRef cfs = SCDynamicStoreCopyLocalHostName(NULL);
3760 if (cfs)
3761 {
3762 CFStringGetPascalString(cfs, namelabel->c, sizeof(*namelabel), kCFStringEncodingUTF8);
3763 CFRelease(cfs);
3764 }
3765 }
3766
3767 mDNSexport mDNSBool DictionaryIsEnabled(CFDictionaryRef dict)
3768 {
3769 mDNSs32 val;
3770 CFNumberRef state = (CFNumberRef)CFDictionaryGetValue(dict, CFSTR("Enabled"));
3771 if (!state) return mDNSfalse;
3772 if (!CFNumberGetValue(state, kCFNumberSInt32Type, &val))
3773 { LogMsg("ERROR: DictionaryIsEnabled - CFNumberGetValue"); return mDNSfalse; }
3774 return val ? mDNStrue : mDNSfalse;
3775 }
3776
3777 mDNSlocal mStatus SetupAddr(mDNSAddr *ip, const struct sockaddr *const sa)
3778 {
3779 if (!sa) { LogMsg("SetupAddr ERROR: NULL sockaddr"); return(mStatus_Invalid); }
3780
3781 if (sa->sa_family == AF_INET)
3782 {
3783 struct sockaddr_in *ifa_addr = (struct sockaddr_in *)sa;
3784 ip->type = mDNSAddrType_IPv4;
3785 ip->ip.v4.NotAnInteger = ifa_addr->sin_addr.s_addr;
3786 return(mStatus_NoError);
3787 }
3788
3789 if (sa->sa_family == AF_INET6)
3790 {
3791 struct sockaddr_in6 *ifa_addr = (struct sockaddr_in6 *)sa;
3792 // Inside the BSD kernel they use a hack where they stuff the sin6->sin6_scope_id
3793 // value into the second word of the IPv6 link-local address, so they can just
3794 // pass around IPv6 address structures instead of full sockaddr_in6 structures.
3795 // Those hacked IPv6 addresses aren't supposed to escape the kernel in that form, but they do.
3796 // To work around this we always whack the second word of any IPv6 link-local address back to zero.
3797 if (IN6_IS_ADDR_LINKLOCAL(&ifa_addr->sin6_addr)) ifa_addr->sin6_addr.__u6_addr.__u6_addr16[1] = 0;
3798 ip->type = mDNSAddrType_IPv6;
3799 ip->ip.v6 = *(mDNSv6Addr*)&ifa_addr->sin6_addr;
3800 return(mStatus_NoError);
3801 }
3802
3803 LogMsg("SetupAddr invalid sa_family %d", sa->sa_family);
3804 return(mStatus_Invalid);
3805 }
3806
3807 mDNSlocal mDNSEthAddr GetBSSID(char *ifa_name)
3808 {
3809 mDNSEthAddr eth = zeroEthAddr;
3810 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:GetBSSID"), NULL, NULL);
3811 if (!store)
3812 LogMsg("GetBSSID: SCDynamicStoreCreate failed: %s", SCErrorString(SCError()));
3813 else
3814 {
3815 CFStringRef entityname = CFStringCreateWithFormat(NULL, NULL, CFSTR("State:/Network/Interface/%s/AirPort"), ifa_name);
3816 if (entityname)
3817 {
3818 CFDictionaryRef dict = SCDynamicStoreCopyValue(store, entityname);
3819 if (dict)
3820 {
3821 CFRange range = { 0, 6 }; // Offset, length
3822 CFDataRef data = CFDictionaryGetValue(dict, CFSTR("BSSID"));
3823 if (data && CFDataGetLength(data) == 6) CFDataGetBytes(data, range, eth.b);
3824 CFRelease(dict);
3825 }
3826 CFRelease(entityname);
3827 }
3828 CFRelease(store);
3829 }
3830 return(eth);
3831 }
3832
3833 mDNSlocal int GetMAC(mDNSEthAddr *eth, u_short ifindex)
3834 {
3835 struct ifaddrs *ifa;
3836 for (ifa = myGetIfAddrs(0); ifa; ifa = ifa->ifa_next)
3837 if (ifa->ifa_addr->sa_family == AF_LINK)
3838 {
3839 const struct sockaddr_dl *const sdl = (const struct sockaddr_dl *)ifa->ifa_addr;
3840 if (sdl->sdl_index == ifindex)
3841 { mDNSPlatformMemCopy(eth->b, sdl->sdl_data + sdl->sdl_nlen, 6); return 0; }
3842 }
3843 *eth = zeroEthAddr;
3844 return -1;
3845 }
3846
3847 #ifndef SIOCGIFWAKEFLAGS
3848 #define SIOCGIFWAKEFLAGS _IOWR('i', 136, struct ifreq) /* get interface wake property flags */
3849 #endif
3850
3851 #ifndef IF_WAKE_ON_MAGIC_PACKET
3852 #define IF_WAKE_ON_MAGIC_PACKET 0x01
3853 #endif
3854
3855 #ifndef ifr_wake_flags
3856 #define ifr_wake_flags ifr_ifru.ifru_intval
3857 #endif
3858
3859 mDNSlocal mDNSBool CheckInterfaceSupport(NetworkInterfaceInfo *const intf, const char *key)
3860 {
3861 io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOBSDNameMatching(kIOMasterPortDefault, 0, intf->ifname));
3862 if (!service)
3863 {
3864 LogSPS("CheckInterfaceSupport: No service for interface %s", intf->ifname);
3865 return mDNSfalse;
3866 }
3867
3868 io_name_t n1, n2;
3869 IOObjectGetClass(service, n1);
3870 io_object_t parent;
3871 mDNSBool ret = mDNSfalse;
3872 kern_return_t kr = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent);
3873 if (kr == KERN_SUCCESS)
3874 {
3875 CFStringRef keystr = CFStringCreateWithCString(NULL, key, kCFStringEncodingUTF8);
3876 IOObjectGetClass(parent, n2);
3877 LogSPS("CheckInterfaceSupport: Interface %s service %s parent %s", intf->ifname, n1, n2);
3878 const CFTypeRef ref = IORegistryEntryCreateCFProperty(parent, keystr, kCFAllocatorDefault, mDNSNULL);
3879 if (!ref)
3880 {
3881 LogSPS("CheckInterfaceSupport: No mDNS_IOREG_KEY for interface %s/%s/%s", intf->ifname, n1, n2);
3882 ret = mDNSfalse;
3883 }
3884 else
3885 {
3886 ret = mDNStrue;
3887 CFRelease(ref);
3888 }
3889 IOObjectRelease(parent);
3890 CFRelease(keystr);
3891 }
3892 else
3893 {
3894 LogSPS("CheckInterfaceSupport: IORegistryEntryGetParentEntry for %s/%s failed %d", intf->ifname, n1, kr);
3895 ret = mDNSfalse;
3896 }
3897 IOObjectRelease(service);
3898 return ret;
3899 }
3900
3901
3902 mDNSlocal mDNSBool InterfaceSupportsKeepAlive(NetworkInterfaceInfo *const intf)
3903 {
3904 return CheckInterfaceSupport(intf, mDNS_IOREG_KA_KEY);
3905 }
3906
3907 mDNSlocal mDNSBool NetWakeInterface(NetworkInterfaceInfoOSX *i)
3908 {
3909 if (!MulticastInterface(i) ) return(mDNSfalse); // We only use Sleep Proxy Service on multicast-capable interfaces
3910 if (i->ifa_flags & IFF_LOOPBACK) return(mDNSfalse); // except loopback
3911
3912 // If the interface supports TCPKeepalive, it is capable of waking up for a magic packet
3913 // This check is needed since the SIOCGIFWAKEFLAGS ioctl returns wrong values for WOMP capability
3914 // when the power source is not AC Power.
3915 if (InterfaceSupportsKeepAlive(&i->ifinfo))
3916 {
3917 LogSPS("NetWakeInterface: %s supports TCP Keepalive returning true", i->ifinfo.ifname);
3918 return mDNStrue;
3919 }
3920
3921 int s = socket(AF_INET, SOCK_DGRAM, 0);
3922 if (s < 0) { LogMsg("NetWakeInterface socket failed %s error %d errno %d (%s)", i->ifinfo.ifname, s, errno, strerror(errno)); return(mDNSfalse); }
3923
3924 struct ifreq ifr;
3925 strlcpy(ifr.ifr_name, i->ifinfo.ifname, sizeof(ifr.ifr_name));
3926 if (ioctl(s, SIOCGIFWAKEFLAGS, &ifr) < 0)
3927 {
3928 // For some strange reason, in /usr/include/sys/errno.h, EOPNOTSUPP is defined to be
3929 // 102 when compiling kernel code, and 45 when compiling user-level code. Since this
3930 // error code is being returned from the kernel, we need to use the kernel version.
3931 #define KERNEL_EOPNOTSUPP 102
3932 if (errno != KERNEL_EOPNOTSUPP) // "Operation not supported on socket", the expected result on Leopard and earlier
3933 LogMsg("NetWakeInterface SIOCGIFWAKEFLAGS %s errno %d (%s)", i->ifinfo.ifname, errno, strerror(errno));
3934 // If on Leopard or earlier, we get EOPNOTSUPP, so in that case
3935 // we enable WOL if this interface is not AirPort and "Wake for Network access" is turned on.
3936 ifr.ifr_wake_flags = (errno == KERNEL_EOPNOTSUPP && !(i)->BSSID.l[0] && i->m->SystemWakeOnLANEnabled) ? IF_WAKE_ON_MAGIC_PACKET : 0;
3937 }
3938
3939 close(s);
3940
3941 // ifr.ifr_wake_flags = IF_WAKE_ON_MAGIC_PACKET; // For testing with MacBook Air, using a USB dongle that doesn't actually support Wake-On-LAN
3942
3943 LogSPS("%-6s %#-14a %s WOMP", i->ifinfo.ifname, &i->ifinfo.ip, (ifr.ifr_wake_flags & IF_WAKE_ON_MAGIC_PACKET) ? "supports" : "no");
3944
3945 return((ifr.ifr_wake_flags & IF_WAKE_ON_MAGIC_PACKET) != 0);
3946 }
3947
3948 mDNSlocal u_int64_t getExtendedFlags(char * ifa_name)
3949 {
3950 int sockFD;
3951 struct ifreq ifr;
3952
3953 sockFD = socket(AF_INET, SOCK_DGRAM, 0);
3954 if (sockFD < 0)
3955 {
3956 LogMsg("getExtendedFlags: socket() call failed, errno = %d (%s)", errno, strerror(errno));
3957 return 0;
3958 }
3959
3960 ifr.ifr_addr.sa_family = AF_INET;
3961 strlcpy(ifr.ifr_name, ifa_name, sizeof(ifr.ifr_name));
3962
3963 if (ioctl(sockFD, SIOCGIFEFLAGS, (caddr_t)&ifr) == -1)
3964 {
3965 LogMsg("getExtendedFlags: SIOCGIFEFLAGS failed, errno = %d (%s)", errno, strerror(errno));
3966 ifr.ifr_eflags = 0;
3967 }
3968 LogInfo("getExtendedFlags: %s ifr_eflags = 0x%x", ifa_name, ifr.ifr_eflags);
3969
3970 close(sockFD);
3971 return ifr.ifr_eflags;
3972 }
3973
3974 // Returns pointer to newly created NetworkInterfaceInfoOSX object, or
3975 // pointer to already-existing NetworkInterfaceInfoOSX object found in list, or
3976 // may return NULL if out of memory (unlikely) or parameters are invalid for some reason
3977 // (e.g. sa_family not AF_INET or AF_INET6)
3978 mDNSlocal NetworkInterfaceInfoOSX *AddInterfaceToList(mDNS *const m, struct ifaddrs *ifa, mDNSs32 utc)
3979 {
3980 mDNSu32 scope_id = if_nametoindex(ifa->ifa_name);
3981 mDNSEthAddr bssid = GetBSSID(ifa->ifa_name);
3982 u_int64_t eflags = getExtendedFlags(ifa->ifa_name);
3983
3984 mDNSAddr ip, mask;
3985 if (SetupAddr(&ip, ifa->ifa_addr ) != mStatus_NoError) return(NULL);
3986 if (SetupAddr(&mask, ifa->ifa_netmask) != mStatus_NoError) return(NULL);
3987
3988 NetworkInterfaceInfoOSX **p;
3989 for (p = &m->p->InterfaceList; *p; p = &(*p)->next)
3990 if (scope_id == (*p)->scope_id &&
3991 mDNSSameAddress(&ip, &(*p)->ifinfo.ip) &&
3992 mDNSSameEthAddress(&bssid, &(*p)->BSSID))
3993 {
3994 debugf("AddInterfaceToList: Found existing interface %lu %.6a with address %#a at %p, ifname before %s, after %s", scope_id, &bssid, &ip, *p, (*p)->ifinfo.ifname, ifa->ifa_name);
3995 // The name should be updated to the new name so that we don't report a wrong name in our SIGINFO output.
3996 // When interfaces are created with same MAC address, kernel resurrects the old interface.
3997 // Even though the interface index is the same (which should be sufficient), when we receive a UDP packet
3998 // we get the corresponding name for the interface index on which the packet was received and check against
3999 // the InterfaceList for a matching name. So, keep the name in sync
4000 strlcpy((*p)->ifinfo.ifname, ifa->ifa_name, sizeof((*p)->ifinfo.ifname));
4001 (*p)->Exists = mDNStrue;
4002 // If interface was not in getifaddrs list last time we looked, but it is now, update 'AppearanceTime' for this record
4003 if ((*p)->LastSeen != utc) (*p)->AppearanceTime = utc;
4004
4005 // If Wake-on-LAN capability of this interface has changed (e.g. because power cable on laptop has been disconnected)
4006 // we may need to start or stop or sleep proxy browse operation
4007 const mDNSBool NetWake = NetWakeInterface(*p);
4008 if ((*p)->ifinfo.NetWake != NetWake)
4009 {
4010 (*p)->ifinfo.NetWake = NetWake;
4011 // If this interface is already registered with mDNSCore, then we need to start or stop its NetWake browse on-the-fly.
4012 // If this interface is not already registered (i.e. it's a dormant interface we had in our list
4013 // from when we previously saw it) then we mustn't do that, because mDNSCore doesn't know about it yet.
4014 // In this case, the mDNS_RegisterInterface() call will take care of starting the NetWake browse if necessary.
4015 if ((*p)->Registered)
4016 {
4017 mDNS_Lock(m);
4018 if (NetWake) mDNS_ActivateNetWake_internal (m, &(*p)->ifinfo);
4019 else mDNS_DeactivateNetWake_internal(m, &(*p)->ifinfo);
4020 mDNS_Unlock(m);
4021 }
4022 }
4023 // Reset the flag if it has changed this time.
4024 (*p)->ifinfo.IgnoreIPv4LL = ((eflags & IFEF_ARPLL) != 0) ? mDNSfalse : mDNStrue;
4025
4026 return(*p);
4027 }
4028
4029 NetworkInterfaceInfoOSX *i = (NetworkInterfaceInfoOSX *)mallocL("NetworkInterfaceInfoOSX", sizeof(*i));
4030 debugf("AddInterfaceToList: Making new interface %lu %.6a with address %#a at %p", scope_id, &bssid, &ip, i);
4031 if (!i) return(mDNSNULL);
4032 mDNSPlatformMemZero(i, sizeof(NetworkInterfaceInfoOSX));
4033 i->ifinfo.InterfaceID = (mDNSInterfaceID)(uintptr_t)scope_id;
4034 i->ifinfo.ip = ip;
4035 i->ifinfo.mask = mask;
4036 strlcpy(i->ifinfo.ifname, ifa->ifa_name, sizeof(i->ifinfo.ifname));
4037 i->ifinfo.ifname[sizeof(i->ifinfo.ifname)-1] = 0;
4038 // We can be configured to disable multicast advertisement, but we want to to support
4039 // local-only services, which need a loopback address record.
4040 i->ifinfo.Advertise = m->DivertMulticastAdvertisements ? ((ifa->ifa_flags & IFF_LOOPBACK) ? mDNStrue : mDNSfalse) : m->AdvertiseLocalAddresses;
4041 i->ifinfo.McastTxRx = mDNSfalse; // For now; will be set up later at the end of UpdateInterfaceList
4042 i->ifinfo.Loopback = ((ifa->ifa_flags & IFF_LOOPBACK) != 0) ? mDNStrue : mDNSfalse;
4043 i->ifinfo.IgnoreIPv4LL = ((eflags & IFEF_ARPLL) != 0) ? mDNSfalse : mDNStrue;
4044 i->ifinfo.DirectLink = (eflags & IFEF_DIRECTLINK) ? mDNStrue: mDNSfalse;
4045
4046 i->next = mDNSNULL;
4047 i->m = m;
4048 i->Exists = mDNStrue;
4049 i->Flashing = mDNSfalse;
4050 i->Occulting = mDNSfalse;
4051 i->D2DInterface = (eflags & IFEF_LOCALNET_PRIVATE) ? mDNStrue: mDNSfalse;
4052 if (eflags & IFEF_AWDL)
4053 {
4054 AWDLInterfaceID = i->ifinfo.InterfaceID;
4055 LogInfo("AddInterfaceToList: AWDLInterfaceID = %d", (int) AWDLInterfaceID);
4056 }
4057 i->AppearanceTime = utc; // Brand new interface; AppearanceTime is now
4058 i->LastSeen = utc;
4059 i->ifa_flags = ifa->ifa_flags;
4060 i->scope_id = scope_id;
4061 i->BSSID = bssid;
4062 i->sa_family = ifa->ifa_addr->sa_family;
4063 i->BPF_fd = -1;
4064 i->BPF_mcfd = -1;
4065 i->BPF_len = 0;
4066 i->Registered = mDNSNULL;
4067
4068 // Do this AFTER i->BSSID has been set up
4069 i->ifinfo.NetWake = NetWakeInterface(i);
4070 GetMAC(&i->ifinfo.MAC, scope_id);
4071 if (i->ifinfo.NetWake && !i->ifinfo.MAC.l[0])
4072 LogMsg("AddInterfaceToList: Bad MAC address %.6a for %d %s %#a", &i->ifinfo.MAC, scope_id, i->ifinfo.ifname, &ip);
4073
4074 *p = i;
4075 return(i);
4076 }
4077
4078 #if APPLE_OSX_mDNSResponder
4079
4080 #if COMPILER_LIKES_PRAGMA_MARK
4081 #pragma mark -
4082 #pragma mark - AutoTunnel
4083 #endif
4084
4085 #define kRacoonPort 4500
4086
4087 static DomainAuthInfo* AnonymousRacoonConfig = mDNSNULL;
4088
4089 #ifndef NO_SECURITYFRAMEWORK
4090
4091 static CFMutableDictionaryRef domainStatusDict = NULL;
4092
4093 mDNSlocal mStatus CheckQuestionForStatus(const DNSQuestion *const q)
4094 {
4095 if (q->LongLived)
4096 {
4097 if (q->servAddr.type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes(q->servAddr.ip.v4))
4098 return mStatus_NoSuchRecord;
4099 else if (q->state == LLQ_Poll)
4100 return mStatus_PollingMode;
4101 else if (q->state != LLQ_Established && !q->DuplicateOf)
4102 return mStatus_TransientErr;
4103 }
4104
4105 return mStatus_NoError;
4106 }
4107
4108 mDNSlocal mStatus UpdateLLQStatus(const mDNS *const m, char *buffer, int bufsz, const DomainAuthInfo *const info)
4109 {
4110 mStatus status = mStatus_NoError;
4111 DNSQuestion* q, *worst_q = mDNSNULL;
4112 for (q = m->Questions; q; q=q->next)
4113 if (q->AuthInfo == info)
4114 {
4115 mStatus newStatus = CheckQuestionForStatus(q);
4116 if (newStatus == mStatus_NoSuchRecord) { status = newStatus; worst_q = q; break; }
4117 else if (newStatus == mStatus_PollingMode) { status = newStatus; worst_q = q; }
4118 else if (newStatus == mStatus_TransientErr && status == mStatus_NoError) { status = newStatus; worst_q = q; }
4119 }
4120
4121 if (status == mStatus_NoError) mDNS_snprintf(buffer, bufsz, "Success");
4122 else if (status == mStatus_NoSuchRecord) mDNS_snprintf(buffer, bufsz, "GetZoneData %s: %##s", worst_q->nta ? "not yet complete" : "failed", worst_q->qname.c);
4123 else if (status == mStatus_PollingMode) mDNS_snprintf(buffer, bufsz, "Query polling %##s", worst_q->qname.c);
4124 else if (status == mStatus_TransientErr) mDNS_snprintf(buffer, bufsz, "Query not yet established %##s", worst_q->qname.c);
4125 return status;
4126 }
4127
4128 mDNSlocal mStatus UpdateRRStatus(const mDNS *const m, char *buffer, int bufsz, const DomainAuthInfo *const info)
4129 {
4130 AuthRecord *r;
4131
4132 if (info->deltime) return mStatus_NoError;
4133 for (r = m->ResourceRecords; r; r = r->next)
4134 {
4135 // This function is called from UpdateAutoTunnelDomainStatus which in turn may be called from
4136 // a callback e.g., CheckNATMappings. GetAuthInfoFor_internal does not like that (reentrancy being 1),
4137 // hence we inline the code here. We just need the lock to walk the list of AuthInfos which the caller
4138 // has already checked
4139 const domainname *n = r->resrec.name;
4140 while (n->c[0])
4141 {
4142 DomainAuthInfo *ptr;
4143 for (ptr = m->AuthInfoList; ptr; ptr = ptr->next)
4144 if (SameDomainName(&ptr->domain, n))
4145 {
4146 if (ptr == info && (r->updateError == mStatus_BadSig || r->updateError == mStatus_BadKey || r->updateError == mStatus_BadTime))
4147 {
4148 mDNS_snprintf(buffer, bufsz, "Resource record update failed for %##s", r->resrec.name);
4149 return r->updateError;
4150 }
4151 }
4152 n = (const domainname *)(n->c + 1 + n->c[0]);
4153 }
4154 }
4155 return mStatus_NoError;
4156 }
4157
4158 #endif // ndef NO_SECURITYFRAMEWORK
4159
4160 // MUST be called with lock held
4161 mDNSlocal void UpdateAutoTunnelDomainStatus(const mDNS *const m, const DomainAuthInfo *const info)
4162 {
4163 #ifdef NO_SECURITYFRAMEWORK
4164 (void) m;
4165 (void)info;
4166 #else
4167 // Note that in the LLQNAT, the clientCallback being non-zero means it's in use,
4168 // whereas in the AutoTunnelNAT, the clientContext being non-zero means it's in use
4169 const NATTraversalInfo *const llq = m->LLQNAT.clientCallback ? &m->LLQNAT : mDNSNULL;
4170 const NATTraversalInfo *const tun = m->AutoTunnelNAT.clientContext ? &m->AutoTunnelNAT : mDNSNULL;
4171 char buffer[1024];
4172 mDNSu32 buflen = 0;
4173 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
4174 CFStringRef domain = NULL;
4175 CFStringRef tmp = NULL;
4176 CFNumberRef num = NULL;
4177 mStatus status = mStatus_NoError;
4178 mStatus llqStatus = mStatus_NoError;
4179 char llqBuffer[1024];
4180
4181 mDNS_CheckLock(m);
4182
4183 if (!domainStatusDict)
4184 {
4185 domainStatusDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
4186 if (!domainStatusDict) { LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFDictionary domainStatusDict"); return; }
4187 }
4188
4189 if (!dict) { LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFDictionary dict"); return; }
4190
4191 buflen = mDNS_snprintf(buffer, sizeof(buffer), "%##s", info->domain.c);
4192 domain = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
4193 if (!domain) { LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFString domain"); return; }
4194
4195 if (info->deltime)
4196 {
4197 if (CFDictionaryContainsKey(domainStatusDict, domain))
4198 {
4199 CFDictionaryRemoveValue(domainStatusDict, domain);
4200 if (!m->ShutdownTime) mDNSDynamicStoreSetConfig(kmDNSBackToMyMacConfig, mDNSNULL, domainStatusDict);
4201 }
4202 CFRelease(domain);
4203 CFRelease(dict);
4204
4205 return;
4206 }
4207
4208 mDNS_snprintf(buffer, sizeof(buffer), "%#a", &m->Router);
4209 tmp = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
4210 if (!tmp)
4211 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFString RouterAddress");
4212 else
4213 {
4214 CFDictionarySetValue(dict, CFSTR("RouterAddress"), tmp);
4215 CFRelease(tmp);
4216 }
4217
4218 if (llq)
4219 {
4220 mDNSu32 port = mDNSVal16(llq->ExternalPort);
4221
4222 num = CFNumberCreate(NULL, kCFNumberSInt32Type, &port);
4223 if (!num)
4224 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFNumber LLQExternalPort");
4225 else
4226 {
4227 CFDictionarySetValue(dict, CFSTR("LLQExternalPort"), num);
4228 CFRelease(num);
4229 }
4230
4231 if (llq->Result)
4232 {
4233 num = CFNumberCreate(NULL, kCFNumberSInt32Type, &llq->Result);
4234 if (!num)
4235 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFNumber LLQNPMStatus");
4236 else
4237 {
4238 CFDictionarySetValue(dict, CFSTR("LLQNPMStatus"), num);
4239 CFRelease(num);
4240 }
4241 }
4242 }
4243
4244 if (tun)
4245 {
4246 mDNSu32 port = mDNSVal16(tun->ExternalPort);
4247
4248 num = CFNumberCreate(NULL, kCFNumberSInt32Type, &port);
4249 if (!num)
4250 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFNumber AutoTunnelExternalPort");
4251 else
4252 {
4253 CFDictionarySetValue(dict, CFSTR("AutoTunnelExternalPort"), num);
4254 CFRelease(num);
4255 }
4256
4257 mDNS_snprintf(buffer, sizeof(buffer), "%.4a", &tun->ExternalAddress);
4258 tmp = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
4259 if (!tmp)
4260 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFString ExternalAddress");
4261 else
4262 {
4263 CFDictionarySetValue(dict, CFSTR("ExternalAddress"), tmp);
4264 CFRelease(tmp);
4265 }
4266
4267 if (tun->Result)
4268 {
4269 num = CFNumberCreate(NULL, kCFNumberSInt32Type, &tun->Result);
4270 if (!num)
4271 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFNumber AutoTunnelNPMStatus");
4272 else
4273 {
4274 CFDictionarySetValue(dict, CFSTR("AutoTunnelNPMStatus"), num);
4275 CFRelease(num);
4276 }
4277 }
4278 }
4279 if (tun || llq)
4280 {
4281 mDNSu32 code = m->LastNATMapResultCode;
4282
4283 num = CFNumberCreate(NULL, kCFNumberSInt32Type, &code);
4284 if (!num)
4285 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFNumber LastNATMapResultCode");
4286 else
4287 {
4288 CFDictionarySetValue(dict, CFSTR("LastNATMapResultCode"), num);
4289 CFRelease(num);
4290 }
4291 }
4292
4293 mDNS_snprintf(buffer, sizeof(buffer), "Success");
4294 llqStatus = UpdateLLQStatus(m, llqBuffer, sizeof(llqBuffer), info);
4295 status = UpdateRRStatus(m, buffer, sizeof(buffer), info);
4296
4297 // If we have a bad signature error updating a RR, it overrides any error as it needs to be
4298 // reported so that it can be fixed automatically (or the user needs to be notified)
4299 if (status != mStatus_NoError)
4300 {
4301 LogInfo("UpdateAutoTunnelDomainStatus: RR Status %d, %s", status, buffer);
4302 }
4303 else if (m->Router.type == mDNSAddrType_None)
4304 {
4305 status = mStatus_NoRouter;
4306 mDNS_snprintf(buffer, sizeof(buffer), "No network connection - none");
4307 }
4308 else if (m->Router.type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero(m->Router.ip.v4))
4309 {
4310 status = mStatus_NoRouter;
4311 mDNS_snprintf(buffer, sizeof(buffer), "No network connection - v4 zero");
4312 }
4313 else if (mDNSIPv6AddressIsZero(info->AutoTunnelInnerAddress))
4314 {
4315 status = mStatus_ServiceNotRunning;
4316 mDNS_snprintf(buffer, sizeof(buffer), "No inner address");
4317 }
4318 else if (!llq && !tun)
4319 {
4320 status = mStatus_NotInitializedErr;
4321 mDNS_snprintf(buffer, sizeof(buffer), "Neither LLQ nor AutoTunnel NAT port mapping is currently active");
4322 }
4323 else if (llqStatus == mStatus_NoSuchRecord)
4324 {
4325 status = llqStatus;
4326 mDNS_snprintf(buffer, sizeof(buffer), llqBuffer);
4327 }
4328 else if ((llq && llq->Result == mStatus_DoubleNAT) || (tun && tun->Result == mStatus_DoubleNAT))
4329 {
4330 status = mStatus_DoubleNAT;
4331 mDNS_snprintf(buffer, sizeof(buffer), "Double NAT: Router is reporting a private address");
4332 }
4333 else if ((llq && llq->Result == mStatus_NATPortMappingDisabled) ||
4334 (tun && tun->Result == mStatus_NATPortMappingDisabled) ||
4335 (m->LastNATMapResultCode == NATErr_Refused && ((llq && !llq->Result && mDNSIPPortIsZero(llq->ExternalPort)) || (tun && !tun->Result && mDNSIPPortIsZero(tun->ExternalPort)))))
4336 {
4337 status = mStatus_NATPortMappingDisabled;
4338 mDNS_snprintf(buffer, sizeof(buffer), "PCP/NAT-PMP is disabled on the router");
4339 }
4340 else if ((llq && llq->Result) || (tun && tun->Result))
4341 {
4342 status = mStatus_NATTraversal;
4343 mDNS_snprintf(buffer, sizeof(buffer), "Error obtaining NAT port mapping from router");
4344 }
4345 else if ((llq && mDNSIPPortIsZero(llq->ExternalPort)) || (tun && mDNSIPPortIsZero(tun->ExternalPort)))
4346 {
4347 status = mStatus_NATTraversal;
4348 mDNS_snprintf(buffer, sizeof(buffer), "Unable to obtain NAT port mapping from router");
4349 }
4350 else
4351 {
4352 status = llqStatus;
4353 mDNS_snprintf(buffer, sizeof(buffer), llqBuffer);
4354 LogInfo("UpdateAutoTunnelDomainStatus: LLQ Status %d, %s", status, buffer);
4355 }
4356
4357 num = CFNumberCreate(NULL, kCFNumberSInt32Type, &status);
4358 if (!num)
4359 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFNumber StatusCode");
4360 else
4361 {
4362 CFDictionarySetValue(dict, CFSTR("StatusCode"), num);
4363 CFRelease(num);
4364 }
4365
4366 tmp = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
4367 if (!tmp)
4368 LogMsg("UpdateAutoTunnelDomainStatus: Could not create CFString StatusMessage");
4369 else
4370 {
4371 CFDictionarySetValue(dict, CFSTR("StatusMessage"), tmp);
4372 CFRelease(tmp);
4373 }
4374
4375 if (!CFDictionaryContainsKey(domainStatusDict, domain) ||
4376 !CFEqual(dict, (CFMutableDictionaryRef)CFDictionaryGetValue(domainStatusDict, domain)))
4377 {
4378 CFDictionarySetValue(domainStatusDict, domain, dict);
4379 if (!m->ShutdownTime)
4380 {
4381 static char statusBuf[16];
4382 mDNS_snprintf(statusBuf, sizeof(statusBuf), "%d", (int)status);
4383 mDNSASLLog((uuid_t *)&m->asl_uuid, "autotunnel.domainstatus", status ? "failure" : "success", statusBuf, "");
4384 mDNSDynamicStoreSetConfig(kmDNSBackToMyMacConfig, mDNSNULL, domainStatusDict);
4385 }
4386 }
4387
4388 CFRelease(domain);
4389 CFRelease(dict);
4390
4391 debugf("UpdateAutoTunnelDomainStatus: %s", buffer);
4392 #endif // def NO_SECURITYFRAMEWORK
4393 }
4394
4395 // MUST be called with lock held
4396 mDNSexport void UpdateAutoTunnelDomainStatuses(const mDNS *const m)
4397 {
4398 #ifdef NO_SECURITYFRAMEWORK
4399 (void) m;
4400 #else
4401 mDNS_CheckLock(m);
4402 DomainAuthInfo* info;
4403 for (info = m->AuthInfoList; info; info = info->next)
4404 if (info->AutoTunnel && !info->deltime)
4405 UpdateAutoTunnelDomainStatus(m, info);
4406 #endif // def NO_SECURITYFRAMEWORK
4407 }
4408
4409 mDNSlocal void UpdateAnonymousRacoonConfig(mDNS *m) // Determine whether we need racoon to accept incoming connections
4410 {
4411 DomainAuthInfo *info;
4412
4413 for (info = m->AuthInfoList; info; info = info->next)
4414 if (info->AutoTunnel && !info->deltime && (!mDNSIPPortIsZero(m->AutoTunnelNAT.ExternalPort) || !mDNSIPv6AddressIsZero(m->AutoTunnelRelayAddr)))
4415 break;
4416
4417 if (info != AnonymousRacoonConfig)
4418 {
4419 AnonymousRacoonConfig = info;
4420 // Create or revert configuration file, and start (or SIGHUP) Racoon
4421 (void)mDNSConfigureServer(AnonymousRacoonConfig ? kmDNSUp : kmDNSDown, AnonymousRacoonConfig ? btmmprefix : mDNSNULL, AnonymousRacoonConfig ? &AnonymousRacoonConfig->domain : mDNSNULL);
4422 }
4423 }
4424
4425 mDNSlocal void AutoTunnelRecordCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
4426
4427 // Caller must hold the lock
4428 mDNSlocal mDNSBool DeregisterAutoTunnelRecord(mDNS *m, DomainAuthInfo *info, AuthRecord* record)
4429 {
4430 mDNS_CheckLock(m);
4431
4432 LogInfo("DeregisterAutoTunnelRecord %##s %##s", &info->domain.c, record->namestorage.c);
4433
4434 if (record->resrec.RecordType > kDNSRecordTypeDeregistering)
4435 {
4436 mStatus err = mDNS_Deregister_internal(m, record, mDNS_Dereg_normal);
4437 if (err)
4438 {
4439 record->resrec.RecordType = kDNSRecordTypeUnregistered;
4440 LogMsg("DeregisterAutoTunnelRecord error %d deregistering %##s %##s", err, info->domain.c, record->namestorage.c);
4441 return mDNSfalse;
4442 }
4443 else LogInfo("DeregisterAutoTunnelRecord: Deregistered");
4444 }
4445 else LogInfo("DeregisterAutoTunnelRecord: Not deregistering, state:%d", record->resrec.RecordType);
4446
4447 return mDNStrue;
4448 }
4449
4450 // Caller must hold the lock
4451 mDNSlocal void DeregisterAutoTunnelHostRecord(mDNS *m, DomainAuthInfo *info)
4452 {
4453 if (!DeregisterAutoTunnelRecord(m, info, &info->AutoTunnelHostRecord))
4454 {
4455 info->AutoTunnelHostRecord.namestorage.c[0] = 0;
4456 m->NextSRVUpdate = NonZeroTime(m->timenow);
4457 }
4458 }
4459
4460 // Caller must hold the lock
4461 mDNSlocal void UpdateAutoTunnelHostRecord(mDNS *m, DomainAuthInfo *info)
4462 {
4463 mStatus err;
4464 mDNSBool NATProblem = mDNSIPPortIsZero(m->AutoTunnelNAT.ExternalPort) || m->AutoTunnelNAT.Result;
4465
4466 mDNS_CheckLock(m);
4467
4468 if (!info->AutoTunnelServiceStarted || info->deltime || m->ShutdownTime || mDNSIPv6AddressIsZero(info->AutoTunnelInnerAddress) || (m->SleepState != SleepState_Awake && NATProblem))
4469 {
4470 LogInfo("UpdateAutoTunnelHostRecord: Dereg %##s : AutoTunnelServiceStarted(%d) deltime(%d) address(%.16a) sleepstate(%d)",
4471 info->domain.c, info->AutoTunnelServiceStarted, info->deltime, &info->AutoTunnelInnerAddress, m->SleepState);
4472 DeregisterAutoTunnelHostRecord(m, info);
4473 }
4474 else if (info->AutoTunnelHostRecord.resrec.RecordType == kDNSRecordTypeUnregistered)
4475 {
4476 mDNS_SetupResourceRecord(&info->AutoTunnelHostRecord, mDNSNULL, mDNSInterface_Any, kDNSType_AAAA, kHostNameTTL,
4477 kDNSRecordTypeUnregistered, AuthRecordAny, AutoTunnelRecordCallback, info);
4478 info->AutoTunnelHostRecord.namestorage.c[0] = 0;
4479 AppendDomainLabel(&info->AutoTunnelHostRecord.namestorage, &m->hostlabel);
4480 AppendDomainName (&info->AutoTunnelHostRecord.namestorage, &info->domain);
4481 info->AutoTunnelHostRecord.resrec.rdata->u.ipv6 = info->AutoTunnelInnerAddress;
4482 info->AutoTunnelHostRecord.resrec.RecordType = kDNSRecordTypeKnownUnique;
4483
4484 err = mDNS_Register_internal(m, &info->AutoTunnelHostRecord);
4485 if (err) LogMsg("UpdateAutoTunnelHostRecord error %d registering %##s", err, info->AutoTunnelHostRecord.namestorage.c);
4486 else
4487 {
4488 // Make sure we trigger the registration of all SRV records in regState_NoTarget again
4489 m->NextSRVUpdate = NonZeroTime(m->timenow);
4490 LogInfo("UpdateAutoTunnelHostRecord registering %##s", info->AutoTunnelHostRecord.namestorage.c);
4491 }
4492 }
4493 else LogInfo("UpdateAutoTunnelHostRecord: Type %d", info->AutoTunnelHostRecord.resrec.RecordType);
4494 }
4495
4496 // Caller must hold the lock
4497 mDNSlocal void DeregisterAutoTunnelServiceRecords(mDNS *m, DomainAuthInfo *info)
4498 {
4499 LogInfo("DeregisterAutoTunnelServiceRecords %##s", info->domain.c);
4500
4501 DeregisterAutoTunnelRecord(m, info, &info->AutoTunnelTarget);
4502 DeregisterAutoTunnelRecord(m, info, &info->AutoTunnelService);
4503 UpdateAutoTunnelHostRecord(m, info);
4504 }
4505
4506 // Caller must hold the lock
4507 mDNSlocal void UpdateAutoTunnelServiceRecords(mDNS *m, DomainAuthInfo *info)
4508 {
4509 mDNS_CheckLock(m);
4510
4511 if (!info->AutoTunnelServiceStarted || info->deltime || m->ShutdownTime || mDNSIPPortIsZero(m->AutoTunnelNAT.ExternalPort) || m->AutoTunnelNAT.Result)
4512 {
4513 LogInfo("UpdateAutoTunnelServiceRecords: Dereg %##s : AutoTunnelServiceStarted(%d) deltime(%d) ExtPort(%d) NATResult(%d)", info->domain.c, info->AutoTunnelServiceStarted, info->deltime, mDNSVal16(m->AutoTunnelNAT.ExternalPort), m->AutoTunnelNAT.Result);
4514 DeregisterAutoTunnelServiceRecords(m, info);
4515 }
4516 else
4517 {
4518 if (info->AutoTunnelTarget.resrec.RecordType == kDNSRecordTypeUnregistered)
4519 {
4520 // 1. Set up our address record for the external tunnel address
4521 // (Constructed name, not generally user-visible, used as target in IKE tunnel's SRV record)
4522 mDNS_SetupResourceRecord(&info->AutoTunnelTarget, mDNSNULL, mDNSInterface_Any, kDNSType_A, kHostNameTTL,
4523 kDNSRecordTypeUnregistered, AuthRecordAny, AutoTunnelRecordCallback, info);
4524 AssignDomainName (&info->AutoTunnelTarget.namestorage, (const domainname*) "\x0B" "_autotunnel");
4525 AppendDomainLabel(&info->AutoTunnelTarget.namestorage, &m->hostlabel);
4526 AppendDomainName (&info->AutoTunnelTarget.namestorage, &info->domain);
4527 info->AutoTunnelTarget.resrec.rdata->u.ipv4 = m->AutoTunnelNAT.ExternalAddress;
4528 info->AutoTunnelTarget.resrec.RecordType = kDNSRecordTypeKnownUnique;
4529
4530 mStatus err = mDNS_Register_internal(m, &info->AutoTunnelTarget);
4531 if (err) LogMsg("UpdateAutoTunnelServiceRecords error %d registering %##s", err, info->AutoTunnelTarget.namestorage.c);
4532 else LogInfo("UpdateAutoTunnelServiceRecords registering %##s", info->AutoTunnelTarget.namestorage.c);
4533 }
4534 else LogInfo("UpdateAutoTunnelServiceRecords: NOOP Target state(%d)", info->AutoTunnelTarget.resrec.RecordType);
4535
4536 if (info->AutoTunnelService.resrec.RecordType == kDNSRecordTypeUnregistered)
4537 {
4538 // 2. Set up IKE tunnel's SRV record: _autotunnel._udp.AutoTunnelHost SRV 0 0 port AutoTunnelTarget
4539 mDNS_SetupResourceRecord(&info->AutoTunnelService, mDNSNULL, mDNSInterface_Any, kDNSType_SRV, kHostNameTTL,
4540 kDNSRecordTypeUnregistered, AuthRecordAny, AutoTunnelRecordCallback, info);
4541 AssignDomainName (&info->AutoTunnelService.namestorage, (const domainname*) "\x0B" "_autotunnel" "\x04" "_udp");
4542 AppendDomainLabel(&info->AutoTunnelService.namestorage, &m->hostlabel);
4543 AppendDomainName (&info->AutoTunnelService.namestorage, &info->domain);
4544 info->AutoTunnelService.resrec.rdata->u.srv.priority = 0;
4545 info->AutoTunnelService.resrec.rdata->u.srv.weight = 0;
4546 info->AutoTunnelService.resrec.rdata->u.srv.port = m->AutoTunnelNAT.ExternalPort;
4547 AssignDomainName(&info->AutoTunnelService.resrec.rdata->u.srv.target, &info->AutoTunnelTarget.namestorage);
4548 info->AutoTunnelService.resrec.RecordType = kDNSRecordTypeKnownUnique;
4549
4550 mStatus err = mDNS_Register_internal(m, &info->AutoTunnelService);
4551 if (err) LogMsg("UpdateAutoTunnelServiceRecords error %d registering %##s", err, info->AutoTunnelService.namestorage.c);
4552 else LogInfo("UpdateAutoTunnelServiceRecords registering %##s", info->AutoTunnelService.namestorage.c);
4553 }
4554 else LogInfo("UpdateAutoTunnelServiceRecords: NOOP Service state(%d)", info->AutoTunnelService.resrec.RecordType);
4555
4556 UpdateAutoTunnelHostRecord(m, info);
4557
4558 LogInfo("AutoTunnel server listening for connections on %##s[%.4a]:%d:%##s[%.16a]",
4559 info->AutoTunnelTarget.namestorage.c, &m->AdvertisedV4.ip.v4, mDNSVal16(m->AutoTunnelNAT.IntPort),
4560 info->AutoTunnelHostRecord.namestorage.c, &info->AutoTunnelInnerAddress);
4561
4562 }
4563 }
4564
4565 // Caller must hold the lock
4566 mDNSlocal void DeregisterAutoTunnelDeviceInfoRecord(mDNS *m, DomainAuthInfo *info)
4567 {
4568 DeregisterAutoTunnelRecord(m, info, &info->AutoTunnelDeviceInfo);
4569 }
4570
4571 // Caller must hold the lock
4572 mDNSlocal void UpdateAutoTunnelDeviceInfoRecord(mDNS *m, DomainAuthInfo *info)
4573 {
4574 mDNS_CheckLock(m);
4575
4576 if (!info->AutoTunnelServiceStarted || info->deltime || m->ShutdownTime)
4577 DeregisterAutoTunnelDeviceInfoRecord(m, info);
4578 else if (info->AutoTunnelDeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered)
4579 {
4580 mDNS_SetupResourceRecord(&info->AutoTunnelDeviceInfo, mDNSNULL, mDNSInterface_Any, kDNSType_TXT, kStandardTTL, kDNSRecordTypeUnregistered, AuthRecordAny, AutoTunnelRecordCallback, info);
4581 ConstructServiceName(&info->AutoTunnelDeviceInfo.namestorage, &m->nicelabel, &DeviceInfoName, &info->domain);
4582
4583 info->AutoTunnelDeviceInfo.resrec.rdlength = initializeDeviceInfoTXT(m, info->AutoTunnelDeviceInfo.resrec.rdata->u.data);
4584 info->AutoTunnelDeviceInfo.resrec.RecordType = kDNSRecordTypeKnownUnique;
4585
4586 mStatus err = mDNS_Register_internal(m, &info->AutoTunnelDeviceInfo);
4587 if (err) LogMsg("UpdateAutoTunnelDeviceInfoRecord error %d registering %##s", err, info->AutoTunnelDeviceInfo.namestorage.c);
4588 else LogInfo("UpdateAutoTunnelDeviceInfoRecord registering %##s", info->AutoTunnelDeviceInfo.namestorage.c);
4589 }
4590 else
4591 LogInfo("UpdateAutoTunnelDeviceInfoRecord: not in Unregistered state: %d",info->AutoTunnelDeviceInfo.resrec.RecordType);
4592 }
4593
4594 // Caller must hold the lock
4595 mDNSlocal void DeregisterAutoTunnel6Record(mDNS *m, DomainAuthInfo *info)
4596 {
4597 LogInfo("DeregisterAutoTunnel6Record %##s", info->domain.c);
4598
4599 DeregisterAutoTunnelRecord(m, info, &info->AutoTunnel6Record);
4600 UpdateAutoTunnelHostRecord(m, info);
4601 UpdateAutoTunnelDomainStatus(m, info);
4602 }
4603
4604 // Caller must hold the lock
4605 mDNSlocal void UpdateAutoTunnel6Record(mDNS *m, DomainAuthInfo *info)
4606 {
4607 mDNS_CheckLock(m);
4608
4609 if (!info->AutoTunnelServiceStarted || info->deltime || m->ShutdownTime || mDNSIPv6AddressIsZero(m->AutoTunnelRelayAddr) || m->SleepState != SleepState_Awake)
4610 DeregisterAutoTunnel6Record(m, info);
4611 else if (info->AutoTunnel6Record.resrec.RecordType == kDNSRecordTypeUnregistered)
4612 {
4613 mDNS_SetupResourceRecord(&info->AutoTunnel6Record, mDNSNULL, mDNSInterface_Any, kDNSType_AAAA, kHostNameTTL,
4614 kDNSRecordTypeUnregistered, AuthRecordAny, AutoTunnelRecordCallback, info);
4615 AssignDomainName (&info->AutoTunnel6Record.namestorage, (const domainname*) "\x0C" "_autotunnel6");
4616 AppendDomainLabel(&info->AutoTunnel6Record.namestorage, &m->hostlabel);
4617 AppendDomainName (&info->AutoTunnel6Record.namestorage, &info->domain);
4618 info->AutoTunnel6Record.resrec.rdata->u.ipv6 = m->AutoTunnelRelayAddr;
4619 info->AutoTunnel6Record.resrec.RecordType = kDNSRecordTypeKnownUnique;
4620
4621 mStatus err = mDNS_Register_internal(m, &info->AutoTunnel6Record);
4622 if (err) LogMsg("UpdateAutoTunnel6Record error %d registering %##s", err, info->AutoTunnel6Record.namestorage.c);
4623 else LogInfo("UpdateAutoTunnel6Record registering %##s", info->AutoTunnel6Record.namestorage.c);
4624
4625 UpdateAutoTunnelHostRecord(m, info);
4626
4627 LogInfo("AutoTunnel6 server listening for connections on %##s[%.16a] :%##s[%.16a]",
4628 info->AutoTunnel6Record.namestorage.c, &m->AutoTunnelRelayAddr,
4629 info->AutoTunnelHostRecord.namestorage.c, &info->AutoTunnelInnerAddress);
4630
4631 }
4632 else LogInfo("UpdateAutoTunnel6Record NOOP state(%d)",info->AutoTunnel6Record.resrec.RecordType);
4633 }
4634
4635 mDNSlocal void AutoTunnelRecordCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
4636 {
4637 DomainAuthInfo *info = (DomainAuthInfo *)rr->RecordContext;
4638 if (result == mStatus_MemFree)
4639 {
4640 LogInfo("AutoTunnelRecordCallback MemFree %s", ARDisplayString(m, rr));
4641
4642 mDNS_Lock(m);
4643
4644 // Reset the host record namestorage to force high-level PTR/SRV/TXT to deregister
4645 if (rr == &info->AutoTunnelHostRecord)
4646 {
4647 rr->namestorage.c[0] = 0;
4648 m->NextSRVUpdate = NonZeroTime(m->timenow);
4649 LogInfo("AutoTunnelRecordCallback: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
4650 }
4651 if (m->ShutdownTime)
4652 {
4653 LogInfo("AutoTunnelRecordCallback: Shutdown, returning");
4654 mDNS_Unlock(m);
4655 return;
4656 }
4657 if (rr == &info->AutoTunnelHostRecord)
4658 {
4659 LogInfo("AutoTunnelRecordCallback: calling UpdateAutoTunnelHostRecord");
4660 UpdateAutoTunnelHostRecord(m,info);
4661 }
4662 else if (rr == &info->AutoTunnelDeviceInfo)
4663 {
4664 LogInfo("AutoTunnelRecordCallback: Calling UpdateAutoTunnelDeviceInfoRecord");
4665 UpdateAutoTunnelDeviceInfoRecord(m,info);
4666 }
4667 else if (rr == &info->AutoTunnelService || rr == &info->AutoTunnelTarget)
4668 {
4669 LogInfo("AutoTunnelRecordCallback: Calling UpdateAutoTunnelServiceRecords");
4670 UpdateAutoTunnelServiceRecords(m,info);
4671 }
4672 else if (rr == &info->AutoTunnel6Record)
4673 {
4674 LogInfo("AutoTunnelRecordCallback: Calling UpdateAutoTunnel6Record");
4675 UpdateAutoTunnel6Record(m,info);
4676 }
4677
4678 mDNS_Unlock(m);
4679 }
4680 }
4681
4682 mDNSlocal void AutoTunnelNATCallback(mDNS *m, NATTraversalInfo *n)
4683 {
4684 DomainAuthInfo *info;
4685
4686 LogInfo("AutoTunnelNATCallback Result %d %.4a Internal %d External %d",
4687 n->Result, &n->ExternalAddress, mDNSVal16(n->IntPort), mDNSVal16(n->ExternalPort));
4688
4689 mDNS_Lock(m);
4690
4691 m->NextSRVUpdate = NonZeroTime(m->timenow);
4692 LogInfo("AutoTunnelNATCallback: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
4693
4694 for (info = m->AuthInfoList; info; info = info->next)
4695 if (info->AutoTunnel)
4696 UpdateAutoTunnelServiceRecords(m, info);
4697
4698 UpdateAnonymousRacoonConfig(m); // Determine whether we need racoon to accept incoming connections
4699
4700 UpdateAutoTunnelDomainStatuses(m);
4701
4702 mDNS_Unlock(m);
4703 }
4704
4705 mDNSlocal void AutoTunnelHostNameChanged(mDNS *m, DomainAuthInfo *info)
4706 {
4707 LogInfo("AutoTunnelHostNameChanged %#s.%##s", m->hostlabel.c, info->domain.c);
4708
4709 mDNS_Lock(m);
4710 // We forcibly deregister the records that are based on the hostname.
4711 // When deregistration of each completes, the MemFree callback will make the
4712 // appropriate Update* call to use the new name to reregister.
4713 DeregisterAutoTunnelHostRecord(m, info);
4714 DeregisterAutoTunnelDeviceInfoRecord(m, info);
4715 DeregisterAutoTunnelServiceRecords(m, info);
4716 DeregisterAutoTunnel6Record(m, info);
4717 m->NextSRVUpdate = NonZeroTime(m->timenow);
4718 mDNS_Unlock(m);
4719 }
4720
4721 // Must be called with the lock held
4722 mDNSexport void StartServerTunnel(mDNS *const m, DomainAuthInfo *const info)
4723 {
4724 if (info->deltime) return;
4725
4726 if (info->AutoTunnelServiceStarted)
4727 {
4728 // On wake from sleep, this function will be called when determining SRV targets,
4729 // and needs to re-register the host record for the target to be set correctly
4730 UpdateAutoTunnelHostRecord(m, info);
4731 return;
4732 }
4733
4734 info->AutoTunnelServiceStarted = mDNStrue;
4735
4736 // Now that we have a service in this domain, we need to try to register the
4737 // AutoTunnel records, because the relay connection & NAT-T may have already been
4738 // started for another domain. If the relay connection is not up or the NAT-T has not
4739 // yet succeeded, the Update* functions are smart enough to not register the records.
4740 // Note: This should be done after we set AutoTunnelServiceStarted, as that variable is used to
4741 // decide whether to register the AutoTunnel records in the calls below.
4742 UpdateAutoTunnelServiceRecords(m, info);
4743 UpdateAutoTunnel6Record(m, info);
4744 UpdateAutoTunnelDeviceInfoRecord(m, info);
4745 UpdateAutoTunnelHostRecord(m, info);
4746
4747 // If the global AutoTunnel NAT-T is not yet started, start it.
4748 if (!m->AutoTunnelNAT.clientContext)
4749 {
4750 m->AutoTunnelNAT.clientCallback = AutoTunnelNATCallback;
4751 m->AutoTunnelNAT.clientContext = (void*)1; // Means AutoTunnelNAT Traversal is active;
4752 m->AutoTunnelNAT.Protocol = NATOp_MapUDP;
4753 m->AutoTunnelNAT.IntPort = IPSECPort;
4754 m->AutoTunnelNAT.RequestedPort = IPSECPort;
4755 m->AutoTunnelNAT.NATLease = 0;
4756 mStatus err = mDNS_StartNATOperation_internal(m, &m->AutoTunnelNAT);
4757 if (err) LogMsg("StartServerTunnel: error %d starting NAT mapping", err);
4758 }
4759 }
4760
4761 mDNSlocal mStatus AutoTunnelSetKeys(ClientTunnel *tun, mDNSBool AddNew)
4762 {
4763 mDNSv6Addr loc_outer6;
4764 mDNSv6Addr rmt_outer6;
4765
4766 // When we are tunneling over IPv6 Relay address, the port number is zero
4767 if (mDNSIPPortIsZero(tun->rmt_outer_port))
4768 {
4769 loc_outer6 = tun->loc_outer6;
4770 rmt_outer6 = tun->rmt_outer6;
4771 }
4772 else
4773 {
4774 loc_outer6 = zerov6Addr;
4775 loc_outer6.b[0] = tun->loc_outer.b[0];
4776 loc_outer6.b[1] = tun->loc_outer.b[1];
4777 loc_outer6.b[2] = tun->loc_outer.b[2];
4778 loc_outer6.b[3] = tun->loc_outer.b[3];
4779
4780 rmt_outer6 = zerov6Addr;
4781 rmt_outer6.b[0] = tun->rmt_outer.b[0];
4782 rmt_outer6.b[1] = tun->rmt_outer.b[1];
4783 rmt_outer6.b[2] = tun->rmt_outer.b[2];
4784 rmt_outer6.b[3] = tun->rmt_outer.b[3];
4785 }
4786
4787 return(mDNSAutoTunnelSetKeys(AddNew ? kmDNSAutoTunnelSetKeysReplace : kmDNSAutoTunnelSetKeysDelete, tun->loc_inner.b, loc_outer6.b, kRacoonPort, tun->rmt_inner.b, rmt_outer6.b, mDNSVal16(tun->rmt_outer_port), btmmprefix, SkipLeadingLabels(&tun->dstname, 1)));
4788 }
4789
4790 // If the EUI-64 part of the IPv6 ULA matches, then that means the two addresses point to the same machine
4791 #define mDNSSameClientTunnel(A,B) ((A)->l[2] == (B)->l[2] && (A)->l[3] == (B)->l[3])
4792
4793 mDNSlocal void ReissueBlockedQuestionWithType(mDNS *const m, domainname *d, mDNSBool success, mDNSu16 qtype)
4794 {
4795 DNSQuestion *q = m->Questions;
4796 while (q)
4797 {
4798 if (q->NoAnswer == NoAnswer_Suspended && q->qtype == qtype && q->AuthInfo && q->AuthInfo->AutoTunnel && SameDomainName(&q->qname, d))
4799 {
4800 LogInfo("Restart %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4801 mDNSQuestionCallback *tmp = q->QuestionCallback;
4802 q->QuestionCallback = AutoTunnelCallback; // Set QuestionCallback to suppress another call back to AddNewClientTunnel
4803 mDNS_StopQuery(m, q);
4804 mDNS_StartQuery(m, q);
4805 q->QuestionCallback = tmp; // Restore QuestionCallback back to the real value
4806 if (!success) q->NoAnswer = NoAnswer_Fail;
4807 // When we call mDNS_StopQuery, it's possible for other subordinate questions like the GetZoneData query to be cancelled too.
4808 // In general we have to assume that the question list might have changed in arbitrary ways.
4809 // This code is itself called from a question callback, so the m->CurrentQuestion mechanism is
4810 // already in use. The safest solution is just to go back to the start of the list and start again.
4811 // In principle this sounds like an n^2 algorithm, but in practice we almost always activate
4812 // just one suspended question, so it's really a 2n algorithm.
4813 q = m->Questions;
4814 }
4815 else
4816 q = q->next;
4817 }
4818 }
4819
4820 mDNSlocal void ReissueBlockedQuestions(mDNS *const m, domainname *d, mDNSBool success)
4821 {
4822 // 1. We deliberately restart AAAA queries before A queries, because in the common case where a BTTM host has
4823 // a v6 address but no v4 address, we prefer the caller to get the positive AAAA response before the A NXDOMAIN.
4824 // 2. In the case of AAAA queries, if our tunnel setup failed, then we return a deliberate failure indication to the caller --
4825 // even if the name does have a valid AAAA record, we don't want clients trying to connect to it without a properly encrypted tunnel.
4826 // 3. For A queries we never fabricate failures -- if a BTTM service is really using raw IPv4, then it doesn't need the IPv6 tunnel.
4827 ReissueBlockedQuestionWithType(m, d, success, kDNSType_AAAA);
4828 ReissueBlockedQuestionWithType(m, d, mDNStrue, kDNSType_A);
4829 }
4830
4831 mDNSlocal void UnlinkAndReissueBlockedQuestions(mDNS *const m, ClientTunnel *tun, mDNSBool success)
4832 {
4833 ClientTunnel **p = &m->TunnelClients;
4834 while (*p != tun && *p) p = &(*p)->next;
4835 if (*p) *p = tun->next;
4836 ReissueBlockedQuestions(m, &tun->dstname, success);
4837 LogInfo("UnlinkAndReissueBlockedQuestions: Disposing ClientTunnel %p", tun);
4838 freeL("ClientTunnel", tun);
4839 }
4840
4841 mDNSlocal mDNSBool TunnelClientDeleteMatching(mDNS *const m, ClientTunnel *tun, mDNSBool v6Tunnel)
4842 {
4843 ClientTunnel **p;
4844 mDNSBool needSetKeys = mDNStrue;
4845
4846 p = &tun->next;
4847 while (*p)
4848 {
4849 // Is this a tunnel to the same host that we are trying to setup now?
4850 if (!mDNSSameClientTunnel(&(*p)->rmt_inner, &tun->rmt_inner)) p = &(*p)->next;
4851 else
4852 {
4853 ClientTunnel *old = *p;
4854 if (v6Tunnel)
4855 {
4856 if (!mDNSIPPortIsZero(old->rmt_outer_port)) { p = &old->next; continue; }
4857 LogInfo("TunnelClientDeleteMatching: Found existing IPv6 AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4858 if (old->q.ThisQInterval >= 0)
4859 {
4860 LogInfo("TunnelClientDeleteMatching: Stopping query on IPv6 AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4861 mDNS_StopQuery(m, &old->q);
4862 }
4863 else if (!mDNSSameIPv6Address((*p)->rmt_inner, tun->rmt_inner) ||
4864 !mDNSSameIPv6Address(old->loc_inner, tun->loc_inner) ||
4865 !mDNSSameIPv6Address(old->loc_outer6, tun->loc_outer6) ||
4866 !mDNSSameIPv6Address(old->rmt_outer6, tun->rmt_outer6))
4867 {
4868 // Delete the old tunnel if the current tunnel to the same host does not have the same ULA or
4869 // the other parameters of the tunnel are different
4870 LogInfo("TunnelClientDeleteMatching: Deleting existing IPv6 AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4871 AutoTunnelSetKeys(old, mDNSfalse);
4872 }
4873 else
4874 {
4875 // Reusing the existing tunnel means that we reuse the IPsec SAs and the policies. We delete the old
4876 // as "tun" and "old" are identical
4877 LogInfo("TunnelClientDeleteMatching: Reusing the existing IPv6 AutoTunnel for %##s %.16a", old->dstname.c,
4878 &old->rmt_inner);
4879 needSetKeys = mDNSfalse;
4880 }
4881 }
4882 else
4883 {
4884 if (mDNSIPPortIsZero(old->rmt_outer_port)) { p = &old->next; continue; }
4885 LogInfo("TunnelClientDeleteMatching: Found existing IPv4 AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4886 if (old->q.ThisQInterval >= 0)
4887 {
4888 LogInfo("TunnelClientDeleteMatching: Stopping query on IPv4 AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4889 mDNS_StopQuery(m, &old->q);
4890 }
4891 else if (!mDNSSameIPv6Address((*p)->rmt_inner, tun->rmt_inner) ||
4892 !mDNSSameIPv6Address(old->loc_inner, tun->loc_inner) ||
4893 !mDNSSameIPv4Address(old->loc_outer, tun->loc_outer) ||
4894 !mDNSSameIPv4Address(old->rmt_outer, tun->rmt_outer) ||
4895 !mDNSSameIPPort(old->rmt_outer_port, tun->rmt_outer_port))
4896 {
4897 // Delete the old tunnel if the current tunnel to the same host does not have the same ULA or
4898 // the other parameters of the tunnel are different
4899 LogInfo("TunnelClientDeleteMatching: Deleting existing IPv4 AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4900 AutoTunnelSetKeys(old, mDNSfalse);
4901 }
4902 else
4903 {
4904 // Reusing the existing tunnel means that we reuse the IPsec SAs and the policies. We delete the old
4905 // as "tun" and "old" are identical
4906 LogInfo("TunnelClientDeleteMatching: Reusing the existing IPv4 AutoTunnel for %##s %.16a", old->dstname.c,
4907 &old->rmt_inner);
4908 needSetKeys = mDNSfalse;
4909 }
4910 }
4911
4912 *p = old->next;
4913 LogInfo("TunnelClientDeleteMatching: Disposing ClientTunnel %p", old);
4914 freeL("ClientTunnel", old);
4915 }
4916 }
4917 return needSetKeys;
4918 }
4919
4920 // v6Tunnel indicates whether to delete a tunnel whose outer header is IPv6. If false, outer IPv4
4921 // tunnel will be deleted
4922 mDNSlocal void TunnelClientDeleteAny(mDNS *const m, ClientTunnel *tun, mDNSBool v6Tunnel)
4923 {
4924 ClientTunnel **p;
4925
4926 p = &tun->next;
4927 while (*p)
4928 {
4929 // If there is more than one client tunnel to the same host, delete all of them.
4930 // We do this by just checking against the EUI64 rather than the full address
4931 if (!mDNSSameClientTunnel(&(*p)->rmt_inner, &tun->rmt_inner)) p = &(*p)->next;
4932 else
4933 {
4934 ClientTunnel *old = *p;
4935 if (v6Tunnel)
4936 {
4937 if (!mDNSIPPortIsZero(old->rmt_outer_port)) { p = &old->next; continue;}
4938 LogInfo("TunnelClientDeleteAny: Found existing IPv6 AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4939 }
4940 else
4941 {
4942 if (mDNSIPPortIsZero(old->rmt_outer_port)) { p = &old->next; continue;}
4943 LogInfo("TunnelClientDeleteAny: Found existing IPv4 AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4944 }
4945 if (old->q.ThisQInterval >= 0)
4946 {
4947 LogInfo("TunnelClientDeleteAny: Stopping query on AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4948 mDNS_StopQuery(m, &old->q);
4949 }
4950 else
4951 {
4952 LogInfo("TunnelClientDeleteAny: Deleting existing AutoTunnel for %##s %.16a", old->dstname.c, &old->rmt_inner);
4953 AutoTunnelSetKeys(old, mDNSfalse);
4954 }
4955 *p = old->next;
4956 LogInfo("TunnelClientDeleteAny: Disposing ClientTunnel %p", old);
4957 freeL("ClientTunnel", old);
4958 }
4959 }
4960 }
4961
4962 mDNSlocal void TunnelClientFinish(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer)
4963 {
4964 mDNSBool needSetKeys = mDNStrue;
4965 ClientTunnel *tun = (ClientTunnel *)question->QuestionContext;
4966 mDNSBool v6Tunnel = mDNSfalse;
4967 DomainAuthInfo *info;
4968
4969 // If the port is zero, then we have a relay address of the peer
4970 if (mDNSIPPortIsZero(tun->rmt_outer_port))
4971 v6Tunnel = mDNStrue;
4972
4973 if (v6Tunnel)
4974 {
4975 LogInfo("TunnelClientFinish: Relay address %.16a", &answer->rdata->u.ipv6);
4976 tun->rmt_outer6 = answer->rdata->u.ipv6;
4977 tun->loc_outer6 = m->AutoTunnelRelayAddr;
4978 }
4979 else
4980 {
4981 LogInfo("TunnelClientFinish: SRV target address %.4a", &answer->rdata->u.ipv4);
4982 tun->rmt_outer = answer->rdata->u.ipv4;
4983 mDNSAddr tmpDst = { mDNSAddrType_IPv4, {{{0}}} };
4984 tmpDst.ip.v4 = tun->rmt_outer;
4985 mDNSAddr tmpSrc = zeroAddr;
4986 mDNSPlatformSourceAddrForDest(&tmpSrc, &tmpDst);
4987 if (tmpSrc.type == mDNSAddrType_IPv4) tun->loc_outer = tmpSrc.ip.v4;
4988 else tun->loc_outer = m->AdvertisedV4.ip.v4;
4989 }
4990
4991 question->ThisQInterval = -1; // So we know this tunnel setup has completed
4992
4993 info = GetAuthInfoForName(m, &tun->dstname);
4994 if (!info)
4995 {
4996 LogMsg("TunnelClientFinish: Could not get AuthInfo for %##s", tun->dstname.c);
4997 ReissueBlockedQuestions(m, &tun->dstname, mDNSfalse);
4998 return;
4999 }
5000
5001 tun->loc_inner = info->AutoTunnelInnerAddress;
5002
5003 // If we found a v6Relay address for our peer, delete all the v4Tunnels for our peer and
5004 // look for existing tunnels to see whether they have the same information for our peer.
5005 // If not, delete them and need to create a new tunnel. If they are same, just use the
5006 // same tunnel. Do the similar thing if we found a v4Tunnel end point for our peer.
5007 TunnelClientDeleteAny(m, tun, !v6Tunnel);
5008 needSetKeys = TunnelClientDeleteMatching(m, tun, v6Tunnel);
5009
5010 if (needSetKeys) LogInfo("TunnelClientFinish: New %s AutoTunnel for %##s %.16a", (v6Tunnel ? "IPv6" : "IPv4"), tun->dstname.c, &tun->rmt_inner);
5011 else LogInfo("TunnelClientFinish: Reusing exiting %s AutoTunnel for %##s %.16a", (v6Tunnel ? "IPv6" : "IPv4"), tun->dstname.c, &tun->rmt_inner);
5012
5013 mStatus result = needSetKeys ? AutoTunnelSetKeys(tun, mDNStrue) : mStatus_NoError;
5014 static char msgbuf[32];
5015 mDNS_snprintf(msgbuf, sizeof(msgbuf), "Tunnel setup - %d", result);
5016 mDNSASLLog((uuid_t *)&m->asl_uuid, "autotunnel.config", result ? "failure" : "success", msgbuf, "");
5017 // Kick off any questions that were held pending this tunnel setup
5018 ReissueBlockedQuestions(m, &tun->dstname, (result == mStatus_NoError) ? mDNStrue : mDNSfalse);
5019 }
5020
5021 mDNSexport void AutoTunnelCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
5022 {
5023 ClientTunnel *tun = (ClientTunnel *)question->QuestionContext;
5024 DomainAuthInfo *info;
5025
5026 LogInfo("AutoTunnelCallback tun %p AddRecord %d rdlength %d qtype %d", tun, AddRecord, answer->rdlength, question->qtype);
5027
5028 if (!AddRecord) return;
5029 mDNS_StopQuery(m, question);
5030
5031 // If we are looking up the AAAA record for _autotunnel6, don't consider it as failure.
5032 // The code below will look for _autotunnel._udp SRV record followed by A record
5033 if (tun->tc_state != TC_STATE_AAAA_PEER_RELAY && !answer->rdlength)
5034 {
5035 LogInfo("AutoTunnelCallback NXDOMAIN %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
5036 static char msgbuf[16];
5037 mDNS_snprintf(msgbuf, sizeof(msgbuf), "%s lookup", DNSTypeName(question->qtype));
5038 mDNSASLLog((uuid_t *)&m->asl_uuid, "autotunnel.config", "failure", msgbuf, "");
5039 UnlinkAndReissueBlockedQuestions(m, tun, mDNSfalse);
5040 return;
5041 }
5042
5043 switch (tun->tc_state)
5044 {
5045 case TC_STATE_AAAA_PEER:
5046 if (question->qtype != kDNSType_AAAA)
5047 {
5048 LogMsg("AutoTunnelCallback: Bad question type %d in TC_STATE_AAAA_PEER", question->qtype);
5049 }
5050 info = GetAuthInfoForName(m, &tun->dstname);
5051 if (!info)
5052 {
5053 LogMsg("AutoTunnelCallback: Could not get AuthInfo for %##s", tun->dstname.c);
5054 UnlinkAndReissueBlockedQuestions(m, tun, mDNStrue);
5055 return;
5056 }
5057 if (mDNSSameIPv6Address(answer->rdata->u.ipv6, info->AutoTunnelInnerAddress))
5058 {
5059 LogInfo("AutoTunnelCallback: suppressing tunnel to self %.16a", &answer->rdata->u.ipv6);
5060 UnlinkAndReissueBlockedQuestions(m, tun, mDNStrue);
5061 return;
5062 }
5063 if (info && mDNSSameIPv6NetworkPart(answer->rdata->u.ipv6, info->AutoTunnelInnerAddress))
5064 {
5065 LogInfo("AutoTunnelCallback: suppressing tunnel to peer %.16a", &answer->rdata->u.ipv6);
5066 UnlinkAndReissueBlockedQuestions(m, tun, mDNStrue);
5067 return;
5068 }
5069 tun->rmt_inner = answer->rdata->u.ipv6;
5070 LogInfo("AutoTunnelCallback:TC_STATE_AAAA_PEER: dst host %.16a", &tun->rmt_inner);
5071 if (!mDNSIPv6AddressIsZero(m->AutoTunnelRelayAddr))
5072 {
5073 LogInfo("AutoTunnelCallback: Looking up _autotunnel6 AAAA");
5074 tun->tc_state = TC_STATE_AAAA_PEER_RELAY;
5075 question->qtype = kDNSType_AAAA;
5076 AssignDomainName(&question->qname, (const domainname*) "\x0C" "_autotunnel6");
5077 }
5078 else
5079 {
5080 LogInfo("AutoTunnelCallback: Looking up _autotunnel._udp SRV");
5081 tun->tc_state = TC_STATE_SRV_PEER;
5082 question->qtype = kDNSType_SRV;
5083 AssignDomainName(&question->qname, (const domainname*) "\x0B" "_autotunnel" "\x04" "_udp");
5084 }
5085 AppendDomainName(&question->qname, &tun->dstname);
5086 mDNS_StartQuery(m, &tun->q);
5087 return;
5088 case TC_STATE_AAAA_PEER_RELAY:
5089 if (question->qtype != kDNSType_AAAA)
5090 {
5091 LogMsg("AutoTunnelCallback: Bad question type %d in TC_STATE_AAAA_PEER_RELAY", question->qtype);
5092 }
5093 // If it failed, look for the SRV record.
5094 if (!answer->rdlength)
5095 {
5096 LogInfo("AutoTunnelCallback: Looking up _autotunnel6 AAAA failed, trying SRV");
5097 tun->tc_state = TC_STATE_SRV_PEER;
5098 AssignDomainName(&question->qname, (const domainname*) "\x0B" "_autotunnel" "\x04" "_udp");
5099 AppendDomainName(&question->qname, &tun->dstname);
5100 question->qtype = kDNSType_SRV;
5101 mDNS_StartQuery(m, &tun->q);
5102 return;
5103 }
5104 TunnelClientFinish(m, question, answer);
5105 return;
5106 case TC_STATE_SRV_PEER:
5107 if (question->qtype != kDNSType_SRV)
5108 {
5109 LogMsg("AutoTunnelCallback: Bad question type %d in TC_STATE_SRV_PEER", question->qtype);
5110 }
5111 LogInfo("AutoTunnelCallback: SRV target name %##s", answer->rdata->u.srv.target.c);
5112 tun->tc_state = TC_STATE_ADDR_PEER;
5113 AssignDomainName(&tun->q.qname, &answer->rdata->u.srv.target);
5114 tun->rmt_outer_port = answer->rdata->u.srv.port;
5115 question->qtype = kDNSType_A;
5116 mDNS_StartQuery(m, &tun->q);
5117 return;
5118 case TC_STATE_ADDR_PEER:
5119 if (question->qtype != kDNSType_A)
5120 {
5121 LogMsg("AutoTunnelCallback: Bad question type %d in TC_STATE_ADDR_PEER", question->qtype);
5122 }
5123 TunnelClientFinish(m, question, answer);
5124 return;
5125 default:
5126 LogMsg("AutoTunnelCallback: Unknown question %p", question);
5127 }
5128 }
5129
5130 // Must be called with the lock held
5131 mDNSexport void AddNewClientTunnel(mDNS *const m, DNSQuestion *const q)
5132 {
5133 ClientTunnel *p = mallocL("ClientTunnel", sizeof(ClientTunnel));
5134 if (!p) return;
5135 AssignDomainName(&p->dstname, &q->qname);
5136 p->MarkedForDeletion = mDNSfalse;
5137 p->loc_inner = zerov6Addr;
5138 p->loc_outer = zerov4Addr;
5139 p->loc_outer6 = zerov6Addr;
5140 p->rmt_inner = zerov6Addr;
5141 p->rmt_outer = zerov4Addr;
5142 p->rmt_outer6 = zerov6Addr;
5143 p->rmt_outer_port = zeroIPPort;
5144 p->tc_state = TC_STATE_AAAA_PEER;
5145 p->next = m->TunnelClients;
5146 m->TunnelClients = p; // We intentionally build list in reverse order
5147
5148 p->q.InterfaceID = mDNSInterface_Any;
5149 p->q.flags = 0;
5150 p->q.Target = zeroAddr;
5151 AssignDomainName(&p->q.qname, &q->qname);
5152 p->q.qtype = kDNSType_AAAA;
5153 p->q.qclass = kDNSClass_IN;
5154 p->q.LongLived = mDNSfalse;
5155 p->q.ExpectUnique = mDNStrue;
5156 p->q.ForceMCast = mDNSfalse;
5157 p->q.ReturnIntermed = mDNStrue;
5158 p->q.SuppressUnusable = mDNSfalse;
5159 p->q.SearchListIndex = 0;
5160 p->q.AppendSearchDomains = 0;
5161 p->q.RetryWithSearchDomains = mDNSfalse;
5162 p->q.TimeoutQuestion = 0;
5163 p->q.WakeOnResolve = 0;
5164 p->q.UseBackgroundTrafficClass = mDNSfalse;
5165 p->q.ValidationRequired = 0;
5166 p->q.ValidatingResponse = 0;
5167 p->q.ProxyQuestion = 0;
5168 p->q.qnameOrig = mDNSNULL;
5169 p->q.AnonInfo = mDNSNULL;
5170 p->q.pid = mDNSPlatformGetPID();
5171 p->q.QuestionCallback = AutoTunnelCallback;
5172 p->q.QuestionContext = p;
5173
5174 LogInfo("AddNewClientTunnel start tun %p %##s (%s)%s", p, &q->qname.c, DNSTypeName(q->qtype), q->LongLived ? " LongLived" : "");
5175 mDNS_StartQuery_internal(m, &p->q);
5176 }
5177
5178 #endif // APPLE_OSX_mDNSResponder
5179
5180 #if COMPILER_LIKES_PRAGMA_MARK
5181 #pragma mark -
5182 #pragma mark - Power State & Configuration Change Management
5183 #endif
5184
5185 mDNSlocal mStatus UpdateInterfaceList(mDNS *const m, mDNSs32 utc)
5186 {
5187 mDNSBool foundav4 = mDNSfalse;
5188 mDNSBool foundav6 = mDNSfalse;
5189 struct ifaddrs *ifa = myGetIfAddrs(1);
5190 struct ifaddrs *v4Loopback = NULL;
5191 struct ifaddrs *v6Loopback = NULL;
5192 char defaultname[64];
5193 int InfoSocket = socket(AF_INET6, SOCK_DGRAM, 0);
5194 if (InfoSocket < 3 && errno != EAFNOSUPPORT)
5195 LogMsg("UpdateInterfaceList: InfoSocket error %d errno %d (%s)", InfoSocket, errno, strerror(errno));
5196
5197 while (ifa)
5198 {
5199 #if LIST_ALL_INTERFACES
5200 if (ifa->ifa_addr->sa_family == AF_APPLETALK)
5201 LogMsg("UpdateInterfaceList: %5s(%d) Flags %04X Family %2d is AF_APPLETALK",
5202 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family);
5203 else if (ifa->ifa_addr->sa_family == AF_LINK)
5204 LogMsg("UpdateInterfaceList: %5s(%d) Flags %04X Family %2d is AF_LINK",
5205 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family);
5206 else if (ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6)
5207 LogMsg("UpdateInterfaceList: %5s(%d) Flags %04X Family %2d not AF_INET (2) or AF_INET6 (30)",
5208 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family);
5209 if (!(ifa->ifa_flags & IFF_UP))
5210 LogMsg("UpdateInterfaceList: %5s(%d) Flags %04X Family %2d Interface not IFF_UP",
5211 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family);
5212 if (!(ifa->ifa_flags & IFF_MULTICAST))
5213 LogMsg("UpdateInterfaceList: %5s(%d) Flags %04X Family %2d Interface not IFF_MULTICAST",
5214 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family);
5215 if (ifa->ifa_flags & IFF_POINTOPOINT)
5216 LogMsg("UpdateInterfaceList: %5s(%d) Flags %04X Family %2d Interface IFF_POINTOPOINT",
5217 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family);
5218 if (ifa->ifa_flags & IFF_LOOPBACK)
5219 LogMsg("UpdateInterfaceList: %5s(%d) Flags %04X Family %2d Interface IFF_LOOPBACK",
5220 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family);
5221 #endif
5222
5223 if (ifa->ifa_addr->sa_family == AF_LINK)
5224 {
5225 struct sockaddr_dl *sdl = (struct sockaddr_dl *)ifa->ifa_addr;
5226 if (sdl->sdl_type == IFT_ETHER && sdl->sdl_alen == sizeof(m->PrimaryMAC) && mDNSSameEthAddress(&m->PrimaryMAC, &zeroEthAddr))
5227 mDNSPlatformMemCopy(m->PrimaryMAC.b, sdl->sdl_data + sdl->sdl_nlen, 6);
5228 }
5229
5230 if (ifa->ifa_flags & IFF_UP && ifa->ifa_addr)
5231 if (ifa->ifa_addr->sa_family == AF_INET || ifa->ifa_addr->sa_family == AF_INET6)
5232 {
5233 if (!ifa->ifa_netmask)
5234 {
5235 mDNSAddr ip;
5236 SetupAddr(&ip, ifa->ifa_addr);
5237 LogMsg("getifaddrs: ifa_netmask is NULL for %5s(%d) Flags %04X Family %2d %#a",
5238 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family, &ip);
5239 }
5240 // Apparently it's normal for the sa_family of an ifa_netmask to sometimes be zero, so we don't complain about that
5241 // <rdar://problem/5492035> getifaddrs is returning invalid netmask family for fw0 and vmnet
5242 else if (ifa->ifa_netmask->sa_family != ifa->ifa_addr->sa_family && ifa->ifa_netmask->sa_family != 0)
5243 {
5244 mDNSAddr ip;
5245 SetupAddr(&ip, ifa->ifa_addr);
5246 LogMsg("getifaddrs ifa_netmask for %5s(%d) Flags %04X Family %2d %#a has different family: %d",
5247 ifa->ifa_name, if_nametoindex(ifa->ifa_name), ifa->ifa_flags, ifa->ifa_addr->sa_family, &ip, ifa->ifa_netmask->sa_family);
5248 }
5249 // Currently we use a few internal ones like mDNSInterfaceID_LocalOnly etc. that are negative values (0, -1, -2).
5250 else if ((int)if_nametoindex(ifa->ifa_name) <= 0)
5251 {
5252 LogMsg("UpdateInterfaceList: if_nametoindex returned zero/negative value for %5s(%d)", ifa->ifa_name, if_nametoindex(ifa->ifa_name));
5253 }
5254 else
5255 {
5256 // Make sure ifa_netmask->sa_family is set correctly
5257 // <rdar://problem/5492035> getifaddrs is returning invalid netmask family for fw0 and vmnet
5258 ifa->ifa_netmask->sa_family = ifa->ifa_addr->sa_family;
5259 int ifru_flags6 = 0;
5260
5261 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
5262 if (ifa->ifa_addr->sa_family == AF_INET6 && InfoSocket >= 0)
5263 {
5264 struct in6_ifreq ifr6;
5265 mDNSPlatformMemZero((char *)&ifr6, sizeof(ifr6));
5266 strlcpy(ifr6.ifr_name, ifa->ifa_name, sizeof(ifr6.ifr_name));
5267 ifr6.ifr_addr = *sin6;
5268 if (ioctl(InfoSocket, SIOCGIFAFLAG_IN6, &ifr6) != -1)
5269 ifru_flags6 = ifr6.ifr_ifru.ifru_flags6;
5270 verbosedebugf("%s %.16a %04X %04X", ifa->ifa_name, &sin6->sin6_addr, ifa->ifa_flags, ifru_flags6);
5271 }
5272
5273 if (!(ifru_flags6 & (IN6_IFF_NOTREADY | IN6_IFF_DETACHED | IN6_IFF_DEPRECATED | IN6_IFF_TEMPORARY)))
5274 {
5275 if (ifa->ifa_flags & IFF_LOOPBACK)
5276 {
5277 if (ifa->ifa_addr->sa_family == AF_INET)
5278 v4Loopback = ifa;
5279 else if (sin6->sin6_addr.s6_addr[0] != 0xFD)
5280 v6Loopback = ifa;
5281 }
5282 else
5283 {
5284 NetworkInterfaceInfoOSX *i = AddInterfaceToList(m, ifa, utc);
5285 if (i && MulticastInterface(i) && i->ifinfo.Advertise)
5286 {
5287 if (ifa->ifa_addr->sa_family == AF_INET)
5288 foundav4 = mDNStrue;
5289 else
5290 foundav6 = mDNStrue;
5291 }
5292 }
5293 }
5294 }
5295 }
5296 ifa = ifa->ifa_next;
5297 }
5298
5299 // For efficiency, we don't register a loopback interface when other interfaces of that family are available and advertising
5300 if (!foundav4 && v4Loopback) AddInterfaceToList(m, v4Loopback, utc);
5301 if (!foundav6 && v6Loopback) AddInterfaceToList(m, v6Loopback, utc);
5302
5303 // Now the list is complete, set the McastTxRx setting for each interface.
5304 NetworkInterfaceInfoOSX *i;
5305 for (i = m->p->InterfaceList; i; i = i->next)
5306 if (i->Exists)
5307 {
5308 mDNSBool txrx = MulticastInterface(i);
5309 if (i->ifinfo.McastTxRx != txrx)
5310 {
5311 i->ifinfo.McastTxRx = txrx;
5312 i->Exists = 2; // State change; need to deregister and reregister this interface
5313 }
5314 }
5315
5316 if (InfoSocket >= 0)
5317 close(InfoSocket);
5318
5319 mDNS_snprintf(defaultname, sizeof(defaultname), "%.*s-%02X%02X%02X%02X%02X%02X", HINFO_HWstring_prefixlen, HINFO_HWstring,
5320 m->PrimaryMAC.b[0], m->PrimaryMAC.b[1], m->PrimaryMAC.b[2], m->PrimaryMAC.b[3], m->PrimaryMAC.b[4], m->PrimaryMAC.b[5]);
5321
5322 // Set up the nice label
5323 domainlabel nicelabel;
5324 nicelabel.c[0] = 0;
5325 GetUserSpecifiedFriendlyComputerName(&nicelabel);
5326 if (nicelabel.c[0] == 0)
5327 {
5328 debugf("Couldn’t read user-specified Computer Name; using default “%s” instead", defaultname);
5329 MakeDomainLabelFromLiteralString(&nicelabel, defaultname);
5330 }
5331
5332 // Set up the RFC 1034-compliant label
5333 domainlabel hostlabel;
5334 hostlabel.c[0] = 0;
5335 GetUserSpecifiedLocalHostName(&hostlabel);
5336 if (hostlabel.c[0] == 0)
5337 {
5338 debugf("Couldn’t read user-specified Local Hostname; using default “%s.local” instead", defaultname);
5339 MakeDomainLabelFromLiteralString(&hostlabel, defaultname);
5340 }
5341
5342 mDNSBool namechange = mDNSfalse;
5343
5344 // We use a case-sensitive comparison here because even though changing the capitalization
5345 // of the name alone is not significant to DNS, it's still a change from the user's point of view
5346 if (SameDomainLabelCS(m->p->usernicelabel.c, nicelabel.c))
5347 debugf("Usernicelabel (%#s) unchanged since last time; not changing m->nicelabel (%#s)", m->p->usernicelabel.c, m->nicelabel.c);
5348 else
5349 {
5350 if (m->p->usernicelabel.c[0]) // Don't show message first time through, when we first read name from prefs on boot
5351 LogMsg("User updated Computer Name from “%#s” to “%#s”", m->p->usernicelabel.c, nicelabel.c);
5352 m->p->usernicelabel = m->nicelabel = nicelabel;
5353 namechange = mDNStrue;
5354 }
5355
5356 if (SameDomainLabelCS(m->p->userhostlabel.c, hostlabel.c))
5357 debugf("Userhostlabel (%#s) unchanged since last time; not changing m->hostlabel (%#s)", m->p->userhostlabel.c, m->hostlabel.c);
5358 else
5359 {
5360 if (m->p->userhostlabel.c[0]) // Don't show message first time through, when we first read name from prefs on boot
5361 LogMsg("User updated Local Hostname from “%#s” to “%#s”", m->p->userhostlabel.c, hostlabel.c);
5362 m->p->userhostlabel = m->hostlabel = hostlabel;
5363 mDNS_SetFQDN(m);
5364 namechange = mDNStrue;
5365 }
5366
5367 #if APPLE_OSX_mDNSResponder
5368 if (namechange) // If either name has changed, we need to tickle our AutoTunnel state machine to update its registered records
5369 {
5370 DomainAuthInfo *info;
5371 for (info = m->AuthInfoList; info; info = info->next)
5372 if (info->AutoTunnel) AutoTunnelHostNameChanged(m, info);
5373 }
5374 #endif // APPLE_OSX_mDNSResponder
5375
5376 return(mStatus_NoError);
5377 }
5378
5379 // Returns number of leading one-bits in mask: 0-32 for IPv4, 0-128 for IPv6
5380 // Returns -1 if all the one-bits are not contiguous
5381 mDNSlocal int CountMaskBits(mDNSAddr *mask)
5382 {
5383 int i = 0, bits = 0;
5384 int bytes = mask->type == mDNSAddrType_IPv4 ? 4 : mask->type == mDNSAddrType_IPv6 ? 16 : 0;
5385 while (i < bytes)
5386 {
5387 mDNSu8 b = mask->ip.v6.b[i++];
5388 while (b & 0x80) { bits++; b <<= 1; }
5389 if (b) return(-1);
5390 }
5391 while (i < bytes) if (mask->ip.v6.b[i++]) return(-1);
5392 return(bits);
5393 }
5394
5395 // returns count of non-link local V4 addresses registered
5396 mDNSlocal int SetupActiveInterfaces(mDNS *const m, mDNSs32 utc)
5397 {
5398 NetworkInterfaceInfoOSX *i;
5399 int count = 0;
5400 for (i = m->p->InterfaceList; i; i = i->next)
5401 if (i->Exists)
5402 {
5403 NetworkInterfaceInfo *const n = &i->ifinfo;
5404 NetworkInterfaceInfoOSX *primary = SearchForInterfaceByName(m, i->ifinfo.ifname, AF_UNSPEC);
5405 if (!primary) LogMsg("SetupActiveInterfaces ERROR! SearchForInterfaceByName didn't find %s", i->ifinfo.ifname);
5406
5407 if (i->Registered && i->Registered != primary) // Sanity check
5408 {
5409 LogMsg("SetupActiveInterfaces ERROR! n->Registered %p != primary %p", i->Registered, primary);
5410 i->Registered = mDNSNULL;
5411 }
5412
5413 if (!i->Registered)
5414 {
5415 // Note: If i->Registered is set, that means we've called mDNS_RegisterInterface() for this interface,
5416 // so we need to make sure we call mDNS_DeregisterInterface() before disposing it.
5417 // If i->Registered is NOT set, then we haven't registered it and we should not try to deregister it
5418 //
5419
5420 i->Registered = primary;
5421
5422 // If i->LastSeen == utc, then this is a brand-new interface, just created, or an interface that never went away.
5423 // If i->LastSeen != utc, then this is an old interface, previously seen, that went away for (utc - i->LastSeen) seconds.
5424 // If the interface is an old one that went away and came back in less than a minute, then we're in a flapping scenario.
5425 i->Occulting = !(i->ifa_flags & IFF_LOOPBACK) && (utc - i->LastSeen > 0 && utc - i->LastSeen < 60);
5426
5427 // Temporary fix to handle P2P flapping. P2P reuses the scope-id, mac address and the IP address
5428 // everytime it creates a new interface. We think it is a duplicate and hence consider it
5429 // as flashing and occulting, that is, flapping. If an interface is marked as flapping,
5430 // mDNS_RegisterInterface() changes the probe delay from 1/2 second to 5 seconds and
5431 // logs a warning message to system.log noting frequent interface transitions.
5432 // Same logic applies when IFEF_DIRECTLINK flag is set on the interface.
5433 if ((strncmp(i->ifinfo.ifname, "p2p", 3) == 0) || i->ifinfo.DirectLink)
5434 {
5435 LogInfo("SetupActiveInterfaces: %s interface registering %s %s", i->ifinfo.ifname,
5436 i->Flashing ? " (Flashing)" : "",
5437 i->Occulting ? " (Occulting)" : "");
5438 mDNS_RegisterInterface(m, n, 0);
5439 }
5440 else
5441 {
5442 mDNS_RegisterInterface(m, n, i->Flashing && i->Occulting);
5443 }
5444
5445 if (!mDNSAddressIsLinkLocal(&n->ip)) count++;
5446 LogInfo("SetupActiveInterfaces: Registered %5s(%lu) %.6a InterfaceID %p(%p), primary %p, %#a/%d%s%s%s",
5447 i->ifinfo.ifname, i->scope_id, &i->BSSID, i->ifinfo.InterfaceID, i, primary, &n->ip, CountMaskBits(&n->mask),
5448 i->Flashing ? " (Flashing)" : "",
5449 i->Occulting ? " (Occulting)" : "",
5450 n->InterfaceActive ? " (Primary)" : "");
5451
5452 if (!n->McastTxRx)
5453 debugf("SetupActiveInterfaces: No Tx/Rx on %5s(%lu) %.6a InterfaceID %p %#a", i->ifinfo.ifname, i->scope_id, &i->BSSID, i->ifinfo.InterfaceID, &n->ip);
5454 else
5455 {
5456 if (i->sa_family == AF_INET)
5457 {
5458 struct ip_mreq imr;
5459 primary->ifa_v4addr.s_addr = n->ip.ip.v4.NotAnInteger;
5460 imr.imr_multiaddr.s_addr = AllDNSLinkGroup_v4.ip.v4.NotAnInteger;
5461 imr.imr_interface = primary->ifa_v4addr;
5462
5463 // If this is our *first* IPv4 instance for this interface name, we need to do a IP_DROP_MEMBERSHIP first,
5464 // before trying to join the group, to clear out stale kernel state which may be lingering.
5465 // In particular, this happens with removable network interfaces like USB Ethernet adapters -- the kernel has stale state
5466 // from the last time the USB Ethernet adapter was connected, and part of the kernel thinks we've already joined the group
5467 // on that interface (so we get EADDRINUSE when we try to join again) but a different part of the kernel thinks we haven't
5468 // joined the group (so we receive no multicasts). Doing an IP_DROP_MEMBERSHIP before joining seems to flush the stale state.
5469 // Also, trying to make the code leave the group when the adapter is removed doesn't work either,
5470 // because by the time we get the configuration change notification, the interface is already gone,
5471 // so attempts to unsubscribe fail with EADDRNOTAVAIL (errno 49 "Can't assign requested address").
5472 // <rdar://problem/5585972> IP_ADD_MEMBERSHIP fails for previously-connected removable interfaces
5473 if (SearchForInterfaceByName(m, i->ifinfo.ifname, AF_INET) == i)
5474 {
5475 LogInfo("SetupActiveInterfaces: %5s(%lu) Doing precautionary IP_DROP_MEMBERSHIP for %.4a on %.4a", i->ifinfo.ifname, i->scope_id, &imr.imr_multiaddr, &imr.imr_interface);
5476 mStatus err = setsockopt(m->p->permanentsockets.sktv4, IPPROTO_IP, IP_DROP_MEMBERSHIP, &imr, sizeof(imr));
5477 if (err < 0 && (errno != EADDRNOTAVAIL))
5478 LogMsg("setsockopt - IP_DROP_MEMBERSHIP error %d errno %d (%s)", err, errno, strerror(errno));
5479 }
5480
5481 LogInfo("SetupActiveInterfaces: %5s(%lu) joining IPv4 mcast group %.4a on %.4a", i->ifinfo.ifname, i->scope_id, &imr.imr_multiaddr, &imr.imr_interface);
5482 mStatus err = setsockopt(m->p->permanentsockets.sktv4, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
5483 // Joining same group twice can give "Address already in use" error -- no need to report that
5484 if (err < 0 && (errno != EADDRINUSE))
5485 LogMsg("setsockopt - IP_ADD_MEMBERSHIP error %d errno %d (%s) group %.4a on %.4a", err, errno, strerror(errno), &imr.imr_multiaddr, &imr.imr_interface);
5486 }
5487 if (i->sa_family == AF_INET6)
5488 {
5489 struct ipv6_mreq i6mr;
5490 i6mr.ipv6mr_interface = primary->scope_id;
5491 i6mr.ipv6mr_multiaddr = *(struct in6_addr*)&AllDNSLinkGroup_v6.ip.v6;
5492
5493 if (SearchForInterfaceByName(m, i->ifinfo.ifname, AF_INET6) == i)
5494 {
5495 LogInfo("SetupActiveInterfaces: %5s(%lu) Doing precautionary IPV6_LEAVE_GROUP for %.16a on %u", i->ifinfo.ifname, i->scope_id, &i6mr.ipv6mr_multiaddr, i6mr.ipv6mr_interface);
5496 mStatus err = setsockopt(m->p->permanentsockets.sktv6, IPPROTO_IPV6, IPV6_LEAVE_GROUP, &i6mr, sizeof(i6mr));
5497 if (err < 0 && (errno != EADDRNOTAVAIL))
5498 LogMsg("setsockopt - IPV6_LEAVE_GROUP error %d errno %d (%s) group %.16a on %u", err, errno, strerror(errno), &i6mr.ipv6mr_multiaddr, i6mr.ipv6mr_interface);
5499 }
5500
5501 LogInfo("SetupActiveInterfaces: %5s(%lu) joining IPv6 mcast group %.16a on %u", i->ifinfo.ifname, i->scope_id, &i6mr.ipv6mr_multiaddr, i6mr.ipv6mr_interface);
5502 mStatus err = setsockopt(m->p->permanentsockets.sktv6, IPPROTO_IPV6, IPV6_JOIN_GROUP, &i6mr, sizeof(i6mr));
5503 // Joining same group twice can give "Address already in use" error -- no need to report that
5504 if (err < 0 && (errno != EADDRINUSE))
5505 LogMsg("setsockopt - IPV6_JOIN_GROUP error %d errno %d (%s) group %.16a on %u", err, errno, strerror(errno), &i6mr.ipv6mr_multiaddr, i6mr.ipv6mr_interface);
5506 }
5507 }
5508 }
5509 }
5510
5511 return count;
5512 }
5513
5514 mDNSlocal void MarkAllInterfacesInactive(mDNS *const m, mDNSs32 utc)
5515 {
5516 NetworkInterfaceInfoOSX *i;
5517 for (i = m->p->InterfaceList; i; i = i->next)
5518 {
5519 if (i->Exists) i->LastSeen = utc;
5520 i->Exists = mDNSfalse;
5521 }
5522 }
5523
5524 // returns count of non-link local V4 addresses deregistered
5525 mDNSlocal int ClearInactiveInterfaces(mDNS *const m, mDNSs32 utc)
5526 {
5527 // First pass:
5528 // If an interface is going away, then deregister this from the mDNSCore.
5529 // We also have to deregister it if the primary interface that it's using for its InterfaceID is going away.
5530 // We have to do this because mDNSCore will use that InterfaceID when sending packets, and if the memory
5531 // it refers to has gone away we'll crash.
5532 NetworkInterfaceInfoOSX *i;
5533 int count = 0;
5534 for (i = m->p->InterfaceList; i; i = i->next)
5535 {
5536 // If this interface is no longer active, or its InterfaceID is changing, deregister it
5537 NetworkInterfaceInfoOSX *primary = SearchForInterfaceByName(m, i->ifinfo.ifname, AF_UNSPEC);
5538 if (i->Registered)
5539 if (i->Exists == 0 || i->Exists == 2 || i->Registered != primary)
5540 {
5541 i->Flashing = !(i->ifa_flags & IFF_LOOPBACK) && (utc - i->AppearanceTime < 60);
5542 LogInfo("ClearInactiveInterfaces: Deregistering %5s(%lu) %.6a InterfaceID %p(%p), primary %p, %#a/%d%s%s%s",
5543 i->ifinfo.ifname, i->scope_id, &i->BSSID, i->ifinfo.InterfaceID, i, primary,
5544 &i->ifinfo.ip, CountMaskBits(&i->ifinfo.mask),
5545 i->Flashing ? " (Flashing)" : "",
5546 i->Occulting ? " (Occulting)" : "",
5547 i->ifinfo.InterfaceActive ? " (Primary)" : "");
5548
5549 // Temporary fix to handle P2P flapping. P2P reuses the scope-id, mac address and the IP address
5550 // everytime it creates a new interface. We think it is a duplicate and hence consider it
5551 // as flashing and occulting. The "core" does not flush the cache for this case. This leads to
5552 // stale data returned to the application even after the interface is removed. The application
5553 // then starts to send data but the new interface is not yet created.
5554 // Same logic applies when IFEF_DIRECTLINK flag is set on the interface.
5555 if ((strncmp(i->ifinfo.ifname, "p2p", 3) == 0) || i->ifinfo.DirectLink)
5556 {
5557 LogInfo("ClearInactiveInterfaces: %s interface deregistering %s %s", i->ifinfo.ifname,
5558 i->Flashing ? " (Flashing)" : "",
5559 i->Occulting ? " (Occulting)" : "");
5560 mDNS_DeregisterInterface(m, &i->ifinfo, 0);
5561 }
5562 else
5563 {
5564 mDNS_DeregisterInterface(m, &i->ifinfo, i->Flashing && i->Occulting);
5565 }
5566 if (!mDNSAddressIsLinkLocal(&i->ifinfo.ip)) count++;
5567 i->Registered = mDNSNULL;
5568 // Note: If i->Registered is set, that means we've called mDNS_RegisterInterface() for this interface,
5569 // so we need to make sure we call mDNS_DeregisterInterface() before disposing it.
5570 // If i->Registered is NOT set, then it's not registered and we should not call mDNS_DeregisterInterface() on it.
5571
5572 // Caution: If we ever decide to add code here to leave the multicast group, we need to make sure that this
5573 // is the LAST representative of this physical interface, or we'll unsubscribe from the group prematurely.
5574 }
5575 }
5576
5577 // Second pass:
5578 // Now that everything that's going to deregister has done so, we can clean up and free the memory
5579 NetworkInterfaceInfoOSX **p = &m->p->InterfaceList;
5580 while (*p)
5581 {
5582 i = *p;
5583 // If no longer active, delete interface from list and free memory
5584 if (!i->Exists)
5585 {
5586 if (i->LastSeen == utc) i->LastSeen = utc - 1;
5587 mDNSBool delete = (NumCacheRecordsForInterfaceID(m, i->ifinfo.InterfaceID) == 0) && (utc - i->LastSeen >= 60);
5588 LogInfo("ClearInactiveInterfaces: %-13s %5s(%lu) %.6a InterfaceID %p(%p) %#a/%d Age %d%s", delete ? "Deleting" : "Holding",
5589 i->ifinfo.ifname, i->scope_id, &i->BSSID, i->ifinfo.InterfaceID, i,
5590 &i->ifinfo.ip, CountMaskBits(&i->ifinfo.mask), utc - i->LastSeen,
5591 i->ifinfo.InterfaceActive ? " (Primary)" : "");
5592 #if APPLE_OSX_mDNSResponder
5593 if (i->BPF_fd >= 0) CloseBPF(i);
5594 #endif // APPLE_OSX_mDNSResponder
5595 if (delete)
5596 {
5597 *p = i->next;
5598 freeL("NetworkInterfaceInfoOSX", i);
5599 continue; // After deleting this object, don't want to do the "p = &i->next;" thing at the end of the loop
5600 }
5601 }
5602 p = &i->next;
5603 }
5604 return count;
5605 }
5606
5607 mDNSlocal void AppendDNameListElem(DNameListElem ***List, mDNSu32 uid, domainname *name)
5608 {
5609 DNameListElem *dnle = (DNameListElem*) mallocL("DNameListElem/AppendDNameListElem", sizeof(DNameListElem));
5610 if (!dnle) LogMsg("ERROR: AppendDNameListElem: memory exhausted");
5611 else
5612 {
5613 dnle->next = mDNSNULL;
5614 dnle->uid = uid;
5615 AssignDomainName(&dnle->name, name);
5616 **List = dnle;
5617 *List = &dnle->next;
5618 }
5619 }
5620
5621 mDNSlocal int compare_dns_configs(const void *aa, const void *bb)
5622 {
5623 dns_resolver_t *a = *(dns_resolver_t**)aa;
5624 dns_resolver_t *b = *(dns_resolver_t**)bb;
5625
5626 return (a->search_order < b->search_order) ? -1 : (a->search_order == b->search_order) ? 0 : 1;
5627 }
5628
5629 mDNSlocal void UpdateSearchDomainHash(mDNS *const m, MD5_CTX *sdc, char *domain, mDNSInterfaceID InterfaceID)
5630 {
5631 char *buf = ".";
5632 mDNSu32 scopeid = 0;
5633 char ifid_buf[16];
5634
5635 if (domain)
5636 buf = domain;
5637 //
5638 // Hash the search domain name followed by the InterfaceID.
5639 // As we have scoped search domains, we also included InterfaceID. If either of them change,
5640 // we will detect it. Even if the order of them change, we will detect it.
5641 //
5642 // Note: We have to handle a few of these tricky cases.
5643 //
5644 // 1) Current: com, apple.com Changing to: comapple.com
5645 // 2) Current: a.com,b.com Changing to a.comb.com
5646 // 3) Current: a.com,b.com (ifid 8), Changing to a.com8b.com (ifid 8)
5647 // 4) Current: a.com (ifid 12), Changing to a.com1 (ifid: 2)
5648 //
5649 // There are more variants of the above. The key thing is if we include the null in each case
5650 // at the end of name and the InterfaceID, it will prevent a new name (which can't include
5651 // NULL as part of the name) to be mistakenly thought of as a old name.
5652
5653 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
5654 // mDNS_snprintf always null terminates
5655 if (mDNS_snprintf(ifid_buf, sizeof(ifid_buf), "%u", scopeid) >= sizeof(ifid_buf))
5656 LogMsg("UpdateSearchDomainHash: mDNS_snprintf failed for scopeid %u", scopeid);
5657
5658 LogInfo("UpdateSearchDomainHash: buf %s, ifid_buf %s", buf, ifid_buf);
5659 MD5_Update(sdc, buf, strlen(buf) + 1);
5660 MD5_Update(sdc, ifid_buf, strlen(ifid_buf) + 1);
5661 }
5662
5663 mDNSlocal void FinalizeSearchDomainHash(mDNS *const m, MD5_CTX *sdc)
5664 {
5665 mDNSu8 md5_hash[MD5_LEN];
5666
5667 MD5_Final(md5_hash, sdc);
5668
5669 if (memcmp(md5_hash, m->SearchDomainsHash, MD5_LEN))
5670 {
5671 // If the hash is different, either the search domains have changed or
5672 // the ordering between them has changed. Restart the questions that
5673 // would be affected by this.
5674 LogInfo("FinalizeSearchDomains: The hash is different");
5675 memcpy(m->SearchDomainsHash, md5_hash, MD5_LEN);
5676 RetrySearchDomainQuestions(m);
5677 }
5678 else { LogInfo("FinalizeSearchDomains: The hash is same"); }
5679 }
5680
5681 mDNSexport const char *DNSScopeToString(mDNSu32 scope)
5682 {
5683 switch (scope)
5684 {
5685 case kScopeNone:
5686 return "Unscoped";
5687 case kScopeInterfaceID:
5688 return "InterfaceScoped";
5689 case kScopeServiceID:
5690 return "ServiceScoped";
5691 default:
5692 return "Unknown";
5693 }
5694 }
5695
5696 mDNSlocal void ConfigSearchDomains(mDNS *const m, dns_resolver_t *resolver, mDNSInterfaceID interface, mDNSu32 scope, MD5_CTX *sdc)
5697 {
5698 const char *scopeString = DNSScopeToString(scope);
5699 int j;
5700
5701 if (scope != kScopeNone)
5702 {
5703 LogInfo("ConfigSearchDomains: (%s) Ignoring search domain for Interface %p", scopeString, interface);
5704 return;
5705 }
5706 for (j = 0; j < resolver->n_search; j++)
5707 {
5708 LogInfo("ConfigSearchDomains: (%s) configuring search list %s", scopeString, resolver->search[j]);
5709 UpdateSearchDomainHash(m, sdc, resolver->search[j], NULL);
5710 mDNS_AddSearchDomain_CString(resolver->search[j], NULL);
5711 }
5712 }
5713
5714 mDNSlocal mDNSInterfaceID ConfigParseInterfaceID(mDNS *const m, mDNSu32 ifindex)
5715 {
5716 NetworkInterfaceInfoOSX *ni;
5717 mDNSInterfaceID interface;
5718
5719 for (ni = m->p->InterfaceList; ni; ni = ni->next)
5720 {
5721 if (ni->ifinfo.InterfaceID && ni->scope_id == ifindex)
5722 break;
5723 }
5724 if (ni != NULL)
5725 {
5726 interface = ni->ifinfo.InterfaceID;
5727 }
5728 else
5729 {
5730 // In rare circumstances, we could potentially hit this case where we cannot parse the InterfaceID
5731 // (see <rdar://problem/13214785>). At this point, we still accept the DNS Config from configd
5732 // Note: We currently ack the whole dns configuration and not individual resolvers or DNS servers.
5733 // As the caller is going to ack the configuration always, we have to add all the DNS servers
5734 // in the configuration. Otherwise, we won't have any DNS servers up until the network change.
5735
5736 LogMsg("ConfigParseInterfaceID: interface specific index %d not found (interface may not be UP)",ifindex);
5737
5738 // Set the correct interface from configd before passing this to mDNS_AddDNSServer() below
5739 interface = (mDNSInterfaceID)(unsigned long)ifindex;
5740 }
5741 return interface;
5742 }
5743
5744 mDNSlocal void ConfigNonUnicastResolver(mDNS *const m, dns_resolver_t *r)
5745 {
5746 char *opt = r->options;
5747 domainname d;
5748
5749 if (opt && !strncmp(opt, "mdns", strlen(opt)))
5750 {
5751 if (!MakeDomainNameFromDNSNameString(&d, r->domain))
5752 {
5753 LogMsg("ConfigNonUnicastResolver: config->resolver bad domain %s", r->domain);
5754 return;
5755 }
5756 mDNS_AddMcastResolver(m, &d, mDNSInterface_Any, r->timeout);
5757 }
5758 }
5759
5760 mDNSlocal void ConfigDNSServers(mDNS *const m, dns_resolver_t *r, mDNSInterfaceID interface, mDNSu32 scope, mDNSu16 resGroupID)
5761 {
5762 int n;
5763 domainname d;
5764 int serviceID = 0;
5765 mDNSBool cellIntf = mDNSfalse;
5766 mDNSBool scopedDNS = mDNSfalse;
5767 mDNSBool reqA, reqAAAA;
5768
5769 if (!r->domain || !*r->domain)
5770 {
5771 d.c[0] = 0;
5772 }
5773 else if (!MakeDomainNameFromDNSNameString(&d, r->domain))
5774 {
5775 LogMsg("ConfigDNSServers: bad domain %s", r->domain);
5776 return;
5777 }
5778 // Parse the resolver specific attributes that affects all the DNS servers.
5779 if (scope == kScopeInterfaceID)
5780 {
5781 scopedDNS = mDNStrue;
5782 }
5783 else if (scope == kScopeServiceID)
5784 {
5785 serviceID = r->service_identifier;
5786 }
5787
5788 #if TARGET_OS_IPHONE
5789 cellIntf = (r->reach_flags & kSCNetworkReachabilityFlagsIsWWAN) ? mDNStrue : mDNSfalse;
5790 #endif
5791 reqA = (r->flags & DNS_RESOLVER_FLAGS_REQUEST_A_RECORDS ? mDNStrue : mDNSfalse);
5792 reqAAAA = (r->flags & DNS_RESOLVER_FLAGS_REQUEST_AAAA_RECORDS ? mDNStrue : mDNSfalse);
5793
5794 for (n = 0; n < r->n_nameserver; n++)
5795 {
5796 mDNSAddr saddr;
5797 DNSServer *s;
5798
5799 if (r->nameserver[n]->sa_family != AF_INET && r->nameserver[n]->sa_family != AF_INET6)
5800 continue;
5801
5802 if (SetupAddr(&saddr, r->nameserver[n]))
5803 {
5804 LogMsg("ConfigDNSServers: Bad address");
5805 continue;
5806 }
5807
5808 // The timeout value is for all the DNS servers in a given resolver, hence we pass
5809 // the timeout value only for the first DNSServer. If we don't have a value in the
5810 // resolver, then use the core's default value
5811 //
5812 // Note: this assumes that when the core picks a list of DNSServers for a question,
5813 // it takes the sum of all the timeout values for all DNS servers. By doing this, it
5814 // tries all the DNS servers in a specified timeout
5815 s = mDNS_AddDNSServer(m, &d, interface, serviceID, &saddr, r->port ? mDNSOpaque16fromIntVal(r->port) : UnicastDNSPort, scope,
5816 (n == 0 ? (r->timeout ? r->timeout : DEFAULT_UDNS_TIMEOUT) : 0), cellIntf, resGroupID, reqA, reqAAAA, mDNStrue);
5817 if (s)
5818 {
5819 LogInfo("ConfigDNSServers(%s): DNS server %#a:%d for domain %##s", DNSScopeToString(scope), &s->addr, mDNSVal16(s->port), d.c);
5820 }
5821 }
5822 }
5823
5824 // ConfigResolvers is called for different types of resolvers: Unscoped resolver, Interface scope resolver and
5825 // Service scope resolvers. This is indicated by the scope argument.
5826 //
5827 // "resolver" has entries that should only be used for unscoped questions.
5828 //
5829 // "scoped_resolver" has entries that should only be used for Interface scoped question i.e., questions that specify an
5830 // interface index (q->InterfaceID)
5831 //
5832 // "service_specific_resolver" has entries that should be used for Service scoped question i.e., questions that specify
5833 // a service identifier (q->ServiceID)
5834 //
5835 mDNSlocal void ConfigResolvers(mDNS *const m, dns_config_t *config, mDNSu32 scope, mDNSBool setsearch, mDNSBool setservers, MD5_CTX *sdc, mDNSu16 resGroupID)
5836 {
5837 int i;
5838 dns_resolver_t **resolver;
5839 int nresolvers;
5840 const char *scopeString = DNSScopeToString(scope);
5841 mDNSInterfaceID interface;
5842
5843 switch (scope)
5844 {
5845 case kScopeNone:
5846 resolver = config->resolver;
5847 nresolvers = config->n_resolver;
5848 break;
5849 case kScopeInterfaceID:
5850 resolver = config->scoped_resolver;
5851 nresolvers = config->n_scoped_resolver;
5852 break;
5853 case kScopeServiceID:
5854 resolver = config->service_specific_resolver;
5855 nresolvers = config->n_service_specific_resolver;
5856 break;
5857 default:
5858 return;
5859 }
5860 qsort(resolver, nresolvers, sizeof(dns_resolver_t*), compare_dns_configs);
5861
5862 for (i = 0; i < nresolvers; i++)
5863 {
5864 dns_resolver_t *r = resolver[i];
5865
5866 LogInfo("ConfigResolvers: %s resolver[%d] domain %s n_nameserver %d", scopeString, i, r->domain, r->n_nameserver);
5867
5868 interface = mDNSInterface_Any;
5869
5870 // Parse the interface index
5871 if (r->if_index != 0)
5872 {
5873 interface = ConfigParseInterfaceID(m, r->if_index);
5874 }
5875
5876 if (setsearch)
5877 {
5878 ConfigSearchDomains(m, resolver[i], interface, scope, sdc);
5879 // Parse other scoped resolvers for search lists
5880 if (!setservers)
5881 continue;
5882 }
5883
5884 if (r->port == 5353 || r->n_nameserver == 0)
5885 {
5886 ConfigNonUnicastResolver(m, r);
5887 }
5888 else
5889 {
5890 // Each scoped resolver gets its own ID (i.e., they are in their own group) so that responses from the
5891 // scoped resolver are not used by other non-scoped or scoped resolvers.
5892 if (scope != kScopeNone)
5893 resGroupID++;
5894
5895 ConfigDNSServers(m, r, interface, scope, resGroupID);
5896 }
5897 }
5898 }
5899
5900 #if APPLE_OSX_mDNSResponder
5901 mDNSlocal mDNSBool QuestionValidForDNSTrigger(DNSQuestion *q)
5902 {
5903 if (QuerySuppressed(q))
5904 {
5905 debugf("QuestionValidForDNSTrigger: Suppressed: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5906 return mDNSfalse;
5907 }
5908 if (mDNSOpaque16IsZero(q->TargetQID))
5909 {
5910 debugf("QuestionValidForDNSTrigger: Multicast: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5911 return mDNSfalse;
5912 }
5913 // If we answered using LocalOnly records e.g., /etc/hosts, don't consider that a valid response
5914 // for trigger.
5915 if (q->LOAddressAnswers)
5916 {
5917 debugf("QuestionValidForDNSTrigger: LocalOnly answers: %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5918 return mDNSfalse;
5919 }
5920 return mDNStrue;
5921 }
5922 #endif
5923
5924 // This function is called if we are not delivering unicast answers to "A" or "AAAA" questions.
5925 // We set our state appropriately so that if we start receiving answers, trigger the
5926 // upper layer to retry DNS questions.
5927 #if APPLE_OSX_mDNSResponder
5928 mDNSexport void mDNSPlatformUpdateDNSStatus(mDNS *const m, DNSQuestion *q)
5929 {
5930 if (!QuestionValidForDNSTrigger(q))
5931 return;
5932
5933 // Ignore applications that start and stop queries for no reason before we ever talk
5934 // to any DNS server.
5935 if (!q->triedAllServersOnce)
5936 {
5937 LogInfo("QuestionValidForDNSTrigger: question %##s (%s) stopped too soon", q->qname.c, DNSTypeName(q->qtype));
5938 return;
5939 }
5940 if (q->qtype == kDNSType_A)
5941 m->p->v4answers = 0;
5942 if (q->qtype == kDNSType_AAAA)
5943 m->p->v6answers = 0;
5944 if (!m->p->v4answers || !m->p->v6answers)
5945 {
5946 LogInfo("mDNSPlatformUpdateDNSStatus: Trigger needed v4 %d, v6 %d, quesiton %##s (%s)", m->p->v4answers, m->p->v6answers, q->qname.c,
5947 DNSTypeName(q->qtype));
5948 }
5949 }
5950 #endif
5951
5952 mDNSlocal void AckConfigd(mDNS *const m, dns_config_t *config)
5953 {
5954 mDNS_CheckLock(m);
5955
5956 // Acking the configuration triggers configd to reissue the reachability queries
5957 m->p->DNSTrigger = NonZeroTime(m->timenow);
5958 _dns_configuration_ack(config, "com.apple.mDNSResponder");
5959 }
5960
5961 // If v4q is non-NULL, it means we have received some answers for "A" type questions
5962 // If v6q is non-NULL, it means we have received some answers for "AAAA" type questions
5963 #if APPLE_OSX_mDNSResponder
5964 mDNSexport void mDNSPlatformTriggerDNSRetry(mDNS *const m, DNSQuestion *v4q, DNSQuestion *v6q)
5965 {
5966 mDNSBool trigger = mDNSfalse;
5967 mDNSs32 timenow;
5968
5969 // Don't send triggers too often.
5970 // If we have started delivering answers to questions, we should send a trigger
5971 // if the time permits. If we are delivering answers, we should set the state
5972 // of v4answers/v6answers to 1 and avoid sending a trigger. But, we don't know
5973 // whether the answers that are being delivered currently is for configd or some
5974 // other application. If we set the v4answers/v6answers to 1 and not deliver a trigger,
5975 // then we won't deliver the trigger later when it is okay to send one as the
5976 // "answers" are already set to 1. Hence, don't affect the state of v4answers and
5977 // v6answers if we are not delivering triggers.
5978 mDNS_Lock(m);
5979 timenow = m->timenow;
5980 if (m->p->DNSTrigger && (timenow - m->p->DNSTrigger) < DNS_TRIGGER_INTERVAL)
5981 {
5982 if (!m->p->v4answers || !m->p->v6answers)
5983 {
5984 debugf("mDNSPlatformTriggerDNSRetry: not triggering, time since last trigger %d ms, v4ans %d, v6ans %d",
5985 (timenow - m->p->DNSTrigger), m->p->v4answers, m->p->v6answers);
5986 }
5987 mDNS_Unlock(m);
5988 return;
5989 }
5990 mDNS_Unlock(m);
5991 if (v4q != NULL && QuestionValidForDNSTrigger(v4q))
5992 {
5993 int old = m->p->v4answers;
5994
5995 m->p->v4answers = 1;
5996
5997 // If there are IPv4 answers now and previously we did not have
5998 // any answers, trigger a DNS change so that reachability
5999 // can retry the queries again.
6000 if (!old)
6001 {
6002 LogInfo("mDNSPlatformTriggerDNSRetry: Triggering because of IPv4, last trigger %d ms, %##s (%s)", (timenow - m->p->DNSTrigger),
6003 v4q->qname.c, DNSTypeName(v4q->qtype));
6004 trigger = mDNStrue;
6005 }
6006 }
6007 if (v6q != NULL && QuestionValidForDNSTrigger(v6q))
6008 {
6009 int old = m->p->v6answers;
6010
6011 m->p->v6answers = 1;
6012 // If there are IPv6 answers now and previously we did not have
6013 // any answers, trigger a DNS change so that reachability
6014 // can retry the queries again.
6015 if (!old)
6016 {
6017 LogInfo("mDNSPlatformTriggerDNSRetry: Triggering because of IPv6, last trigger %d ms, %##s (%s)", (timenow - m->p->DNSTrigger),
6018 v6q->qname.c, DNSTypeName(v6q->qtype));
6019 trigger = mDNStrue;
6020 }
6021 }
6022 if (trigger)
6023 {
6024 dns_config_t *config = dns_configuration_copy();
6025 if (config)
6026 {
6027 mDNS_Lock(m);
6028 AckConfigd(m, config);
6029 mDNS_Unlock(m);
6030 dns_configuration_free(config);
6031 }
6032 else
6033 {
6034 LogMsg("mDNSPlatformTriggerDNSRetry: ERROR!! configd did not return config");
6035 }
6036 }
6037 }
6038
6039 mDNSlocal void SetupActiveDirectoryDomain(dns_config_t *config)
6040 {
6041 // Record the so-called "primary" domain, which we use as a hint to tell if the user is on a network set up
6042 // by someone using Microsoft Active Directory using "local" as a private internal top-level domain
6043 if (config->n_resolver && config->resolver[0]->domain && config->resolver[0]->n_nameserver &&
6044 config->resolver[0]->nameserver[0])
6045 {
6046 MakeDomainNameFromDNSNameString(&ActiveDirectoryPrimaryDomain, config->resolver[0]->domain);
6047 }
6048 else
6049 {
6050 ActiveDirectoryPrimaryDomain.c[0] = 0;
6051 }
6052
6053 //MakeDomainNameFromDNSNameString(&ActiveDirectoryPrimaryDomain, "test.local");
6054 ActiveDirectoryPrimaryDomainLabelCount = CountLabels(&ActiveDirectoryPrimaryDomain);
6055 if (config->n_resolver && config->resolver[0]->n_nameserver &&
6056 SameDomainName(SkipLeadingLabels(&ActiveDirectoryPrimaryDomain, ActiveDirectoryPrimaryDomainLabelCount - 1), &localdomain))
6057 {
6058 SetupAddr(&ActiveDirectoryPrimaryDomainServer, config->resolver[0]->nameserver[0]);
6059 }
6060 else
6061 {
6062 AssignDomainName(&ActiveDirectoryPrimaryDomain, (const domainname *)"");
6063 ActiveDirectoryPrimaryDomainLabelCount = 0;
6064 ActiveDirectoryPrimaryDomainServer = zeroAddr;
6065 }
6066 }
6067 #endif
6068
6069 mDNSlocal void SetupDDNSDomains(domainname *const fqdn, DNameListElem **RegDomains, DNameListElem **BrowseDomains)
6070 {
6071 int i;
6072 char buf[MAX_ESCAPED_DOMAIN_NAME]; // Max legal C-string name, including terminating NUL
6073 domainname d;
6074
6075 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:mDNSPlatformSetDNSConfig"), NULL, NULL);
6076 if (!store)
6077 {
6078 LogMsg("SetupDDNSDomains: SCDynamicStoreCreate failed: %s", SCErrorString(SCError()));
6079 }
6080 else
6081 {
6082 CFDictionaryRef ddnsdict = SCDynamicStoreCopyValue(store, NetworkChangedKey_DynamicDNS);
6083 if (ddnsdict)
6084 {
6085 if (fqdn)
6086 {
6087 CFArrayRef fqdnArray = CFDictionaryGetValue(ddnsdict, CFSTR("HostNames"));
6088 if (fqdnArray && CFArrayGetCount(fqdnArray) > 0)
6089 {
6090 // for now, we only look at the first array element. if we ever support multiple configurations, we will walk the list
6091 CFDictionaryRef fqdnDict = CFArrayGetValueAtIndex(fqdnArray, 0);
6092 if (fqdnDict && DictionaryIsEnabled(fqdnDict))
6093 {
6094 CFStringRef name = CFDictionaryGetValue(fqdnDict, CFSTR("Domain"));
6095 if (name)
6096 {
6097 if (!CFStringGetCString(name, buf, sizeof(buf), kCFStringEncodingUTF8) ||
6098 !MakeDomainNameFromDNSNameString(fqdn, buf) || !fqdn->c[0])
6099 LogMsg("GetUserSpecifiedDDNSConfig SCDynamicStore bad DDNS host name: %s", buf[0] ? buf : "(unknown)");
6100 else debugf("GetUserSpecifiedDDNSConfig SCDynamicStore DDNS host name: %s", buf);
6101 }
6102 }
6103 }
6104 }
6105
6106 if (RegDomains)
6107 {
6108 CFArrayRef regArray = CFDictionaryGetValue(ddnsdict, CFSTR("RegistrationDomains"));
6109 if (regArray && CFArrayGetCount(regArray) > 0)
6110 {
6111 CFDictionaryRef regDict = CFArrayGetValueAtIndex(regArray, 0);
6112 if (regDict && DictionaryIsEnabled(regDict))
6113 {
6114 CFStringRef name = CFDictionaryGetValue(regDict, CFSTR("Domain"));
6115 if (name)
6116 {
6117 if (!CFStringGetCString(name, buf, sizeof(buf), kCFStringEncodingUTF8) ||
6118 !MakeDomainNameFromDNSNameString(&d, buf) || !d.c[0])
6119 LogMsg("GetUserSpecifiedDDNSConfig SCDynamicStore bad DDNS registration domain: %s", buf[0] ? buf : "(unknown)");
6120 else
6121 {
6122 debugf("GetUserSpecifiedDDNSConfig SCDynamicStore DDNS registration domain: %s", buf);
6123 AppendDNameListElem(&RegDomains, 0, &d);
6124 }
6125 }
6126 }
6127 }
6128 }
6129
6130 if (BrowseDomains)
6131 {
6132 CFArrayRef browseArray = CFDictionaryGetValue(ddnsdict, CFSTR("BrowseDomains"));
6133 if (browseArray)
6134 {
6135 for (i = 0; i < CFArrayGetCount(browseArray); i++)
6136 {
6137 CFDictionaryRef browseDict = CFArrayGetValueAtIndex(browseArray, i);
6138 if (browseDict && DictionaryIsEnabled(browseDict))
6139 {
6140 CFStringRef name = CFDictionaryGetValue(browseDict, CFSTR("Domain"));
6141 if (name)
6142 {
6143 if (!CFStringGetCString(name, buf, sizeof(buf), kCFStringEncodingUTF8) ||
6144 !MakeDomainNameFromDNSNameString(&d, buf) || !d.c[0])
6145 LogMsg("GetUserSpecifiedDDNSConfig SCDynamicStore bad DDNS browsing domain: %s", buf[0] ? buf : "(unknown)");
6146 else
6147 {
6148 debugf("GetUserSpecifiedDDNSConfig SCDynamicStore DDNS browsing domain: %s", buf);
6149 AppendDNameListElem(&BrowseDomains, 0, &d);
6150 }
6151 }
6152 }
6153 }
6154 }
6155 }
6156 CFRelease(ddnsdict);
6157 }
6158
6159 if (RegDomains)
6160 {
6161 CFDictionaryRef btmm = SCDynamicStoreCopyValue(store, NetworkChangedKey_BackToMyMac);
6162 if (btmm)
6163 {
6164 CFIndex size = CFDictionaryGetCount(btmm);
6165 const void *key[size];
6166 const void *val[size];
6167 CFDictionaryGetKeysAndValues(btmm, key, val);
6168 for (i = 0; i < size; i++)
6169 {
6170 LogInfo("BackToMyMac %d", i);
6171 if (!CFStringGetCString(key[i], buf, sizeof(buf), kCFStringEncodingUTF8))
6172 LogMsg("Can't read BackToMyMac %d key %s", i, buf);
6173 else
6174 {
6175 mDNSu32 uid = atoi(buf);
6176 if (!CFStringGetCString(val[i], buf, sizeof(buf), kCFStringEncodingUTF8))
6177 LogMsg("Can't read BackToMyMac %d val %s", i, buf);
6178 else if (MakeDomainNameFromDNSNameString(&d, buf) && d.c[0])
6179 {
6180 LogInfo("BackToMyMac %d %d %##s", i, uid, d.c);
6181 AppendDNameListElem(&RegDomains, uid, &d);
6182 }
6183 }
6184 }
6185 CFRelease(btmm);
6186 }
6187 }
6188 CFRelease(store);
6189 }
6190 }
6191
6192 // Returns mDNSfalse, if it does not set the configuration i.e., if the DNS configuration did not change
6193 mDNSexport mDNSBool mDNSPlatformSetDNSConfig(mDNS *const m, mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn,
6194 DNameListElem **RegDomains, DNameListElem **BrowseDomains, mDNSBool ackConfig)
6195 {
6196 MD5_CTX sdc; // search domain context
6197 static mDNSu16 resolverGroupID = 0;
6198
6199 // Need to set these here because we need to do this even if SCDynamicStoreCreate() or SCDynamicStoreCopyValue() below don't succeed
6200 if (fqdn) fqdn->c[0] = 0;
6201 if (RegDomains ) *RegDomains = NULL;
6202 if (BrowseDomains) *BrowseDomains = NULL;
6203
6204 LogInfo("mDNSPlatformSetDNSConfig:%s%s%s%s%s",
6205 setservers ? " setservers" : "",
6206 setsearch ? " setsearch" : "",
6207 fqdn ? " fqdn" : "",
6208 RegDomains ? " RegDomains" : "",
6209 BrowseDomains ? " BrowseDomains" : "");
6210
6211 if (setsearch) MD5_Init(&sdc);
6212
6213 // Add the inferred address-based configuration discovery domains
6214 // (should really be in core code I think, not platform-specific)
6215 if (setsearch)
6216 {
6217 struct ifaddrs *ifa = mDNSNULL;
6218 struct sockaddr_in saddr;
6219 mDNSPlatformMemZero(&saddr, sizeof(saddr));
6220 saddr.sin_len = sizeof(saddr);
6221 saddr.sin_family = AF_INET;
6222 saddr.sin_port = 0;
6223 saddr.sin_addr.s_addr = *(in_addr_t *)&m->Router.ip.v4;
6224
6225 // Don't add any reverse-IP search domains if doing the WAB bootstrap queries would cause dial-on-demand connection initiation
6226 if (!AddrRequiresPPPConnection((struct sockaddr *)&saddr)) ifa = myGetIfAddrs(1);
6227
6228 while (ifa)
6229 {
6230 mDNSAddr a, n;
6231 char buf[64];
6232
6233 if (ifa->ifa_addr->sa_family == AF_INET &&
6234 ifa->ifa_netmask &&
6235 !(ifa->ifa_flags & IFF_LOOPBACK) &&
6236 !SetupAddr(&a, ifa->ifa_addr) &&
6237 !mDNSv4AddressIsLinkLocal(&a.ip.v4) )
6238 {
6239 // Apparently it's normal for the sa_family of an ifa_netmask to sometimes be incorrect, so we explicitly fix it here before calling SetupAddr
6240 // <rdar://problem/5492035> getifaddrs is returning invalid netmask family for fw0 and vmnet
6241 ifa->ifa_netmask->sa_family = ifa->ifa_addr->sa_family; // Make sure ifa_netmask->sa_family is set correctly
6242 SetupAddr(&n, ifa->ifa_netmask);
6243 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
6244 mDNS_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa.", a.ip.v4.b[3] & n.ip.v4.b[3],
6245 a.ip.v4.b[2] & n.ip.v4.b[2],
6246 a.ip.v4.b[1] & n.ip.v4.b[1],
6247 a.ip.v4.b[0] & n.ip.v4.b[0]);
6248 UpdateSearchDomainHash(m, &sdc, buf, NULL);
6249 mDNS_AddSearchDomain_CString(buf, mDNSNULL);
6250 }
6251 ifa = ifa->ifa_next;
6252 }
6253 }
6254
6255 #ifndef MDNS_NO_DNSINFO
6256 if (setservers || setsearch)
6257 {
6258 dns_config_t *config = dns_configuration_copy();
6259 if (!config)
6260 {
6261 // When running on 10.3 (build 7xxx) and earlier, we don't expect dns_configuration_copy() to succeed
6262 // On 10.4, calls to dns_configuration_copy() early in the boot process often fail.
6263 // Apparently this is expected behaviour -- "not a bug".
6264 // Accordingly, we suppress syslog messages for the first three minutes after boot.
6265 // If we are still getting failures after three minutes, then we log them.
6266 if ((mDNSu32)mDNSPlatformRawTime() > (mDNSu32)(mDNSPlatformOneSecond * 180))
6267 LogMsg("mDNSPlatformSetDNSConfig: Error: dns_configuration_copy returned NULL");
6268 }
6269 else
6270 {
6271 LogInfo("mDNSPlatformSetDNSConfig: config->n_resolver = %d, generation %llu", config->n_resolver, config->generation);
6272 if (m->p->LastConfigGeneration == config->generation)
6273 {
6274 LogInfo("mDNSPlatformSetDNSConfig: generation number %llu same, not processing", config->generation);
6275 dns_configuration_free(config);
6276 SetupDDNSDomains(fqdn, RegDomains, BrowseDomains);
6277 return mDNSfalse;
6278 }
6279 #if APPLE_OSX_mDNSResponder
6280 SetupActiveDirectoryDomain(config);
6281 #endif
6282
6283 // With scoped DNS, we don't want to answer a non-scoped question using a scoped cache entry
6284 // and vice-versa. As we compare resolverGroupID for matching cache entry with question, we need
6285 // to make sure that they don't match. We ensure this by always bumping up resolverGroupID between
6286 // the two calls to ConfigResolvers DNSServers for scoped and non-scoped can never have the
6287 // same resolverGroupID.
6288 //
6289 // All non-scoped resolvers use the same resolverGroupID i.e, we treat them all equally.
6290 ConfigResolvers(m, config, kScopeNone, setsearch, setservers, &sdc, ++resolverGroupID);
6291 resolverGroupID += config->n_resolver;
6292
6293 ConfigResolvers(m, config, kScopeInterfaceID, setsearch, setservers, &sdc, resolverGroupID);
6294 resolverGroupID += config->n_scoped_resolver;
6295
6296 ConfigResolvers(m, config, kScopeServiceID, setsearch, setservers, &sdc, resolverGroupID);
6297
6298 // Acking provides a hint that we processed this current configuration and
6299 // we will use that from now on, assuming we don't get another one immediately
6300 // after we return from here.
6301 if (ackConfig)
6302 {
6303 // Note: We have to set the generation number here when we are acking.
6304 // For every DNS configuration change, we do the following:
6305 //
6306 // 1) Copy dns configuration, handle search domains change
6307 // 2) Copy dns configuration, handle dns server change
6308 //
6309 // If we update the generation number at step (1), we won't process the
6310 // DNS servers the second time because generation number would be the same.
6311 // As we ack only when we process dns servers, we set the generation number
6312 // during acking.
6313 m->p->LastConfigGeneration = config->generation;
6314 LogInfo("mDNSPlatformSetDNSConfig: Acking configuration setservers %d, setsearch %d", setservers, setsearch);
6315 AckConfigd(m, config);
6316 }
6317 dns_configuration_free(config);
6318 if (setsearch) FinalizeSearchDomainHash(m, &sdc);
6319 setservers = mDNSfalse; // Done these now -- no need to fetch the same data from SCDynamicStore
6320 setsearch = mDNSfalse;
6321 }
6322 }
6323 #endif // MDNS_NO_DNSINFO
6324 SetupDDNSDomains(fqdn, RegDomains, BrowseDomains);
6325 return mDNStrue;
6326 }
6327
6328
6329 mDNSexport mStatus mDNSPlatformGetPrimaryInterface(mDNS *const m, mDNSAddr *v4, mDNSAddr *v6, mDNSAddr *r)
6330 {
6331 char buf[256];
6332 (void)m; // Unused
6333
6334 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:mDNSPlatformGetPrimaryInterface"), NULL, NULL);
6335 if (!store)
6336 LogMsg("mDNSPlatformGetPrimaryInterface: SCDynamicStoreCreate failed: %s", SCErrorString(SCError()));
6337 else
6338 {
6339 CFDictionaryRef dict = SCDynamicStoreCopyValue(store, NetworkChangedKey_IPv4);
6340 if (dict)
6341 {
6342 r->type = mDNSAddrType_IPv4;
6343 r->ip.v4 = zerov4Addr;
6344 CFStringRef string = CFDictionaryGetValue(dict, kSCPropNetIPv4Router);
6345 if (string)
6346 {
6347 if (!CFStringGetCString(string, buf, 256, kCFStringEncodingUTF8))
6348 LogMsg("Could not convert router to CString");
6349 else
6350 {
6351 struct sockaddr_in saddr;
6352 saddr.sin_len = sizeof(saddr);
6353 saddr.sin_family = AF_INET;
6354 saddr.sin_port = 0;
6355 inet_aton(buf, &saddr.sin_addr);
6356
6357 *(in_addr_t *)&r->ip.v4 = saddr.sin_addr.s_addr;
6358 }
6359 }
6360
6361 string = CFDictionaryGetValue(dict, kSCDynamicStorePropNetPrimaryInterface);
6362 if (string)
6363 {
6364 mDNSBool HavePrimaryGlobalv6 = mDNSfalse; // does the primary interface have a global v6 address?
6365 struct ifaddrs *ifa = myGetIfAddrs(1);
6366
6367 *v4 = *v6 = zeroAddr;
6368
6369 if (!CFStringGetCString(string, buf, 256, kCFStringEncodingUTF8)) { LogMsg("Could not convert router to CString"); goto exit; }
6370
6371 // find primary interface in list
6372 while (ifa && (mDNSIPv4AddressIsZero(v4->ip.v4) || mDNSv4AddressIsLinkLocal(&v4->ip.v4) || !HavePrimaryGlobalv6))
6373 {
6374 mDNSAddr tmp6 = zeroAddr;
6375 if (!strcmp(buf, ifa->ifa_name))
6376 {
6377 if (ifa->ifa_addr->sa_family == AF_INET)
6378 {
6379 if (mDNSIPv4AddressIsZero(v4->ip.v4) || mDNSv4AddressIsLinkLocal(&v4->ip.v4)) SetupAddr(v4, ifa->ifa_addr);
6380 }
6381 else if (ifa->ifa_addr->sa_family == AF_INET6)
6382 {
6383 SetupAddr(&tmp6, ifa->ifa_addr);
6384 if (tmp6.ip.v6.b[0] >> 5 == 1) // global prefix: 001
6385 { HavePrimaryGlobalv6 = mDNStrue; *v6 = tmp6; }
6386 }
6387 }
6388 else
6389 {
6390 // We'll take a V6 address from the non-primary interface if the primary interface doesn't have a global V6 address
6391 if (!HavePrimaryGlobalv6 && ifa->ifa_addr->sa_family == AF_INET6 && !v6->ip.v6.b[0])
6392 {
6393 SetupAddr(&tmp6, ifa->ifa_addr);
6394 if (tmp6.ip.v6.b[0] >> 5 == 1) *v6 = tmp6;
6395 }
6396 }
6397 ifa = ifa->ifa_next;
6398 }
6399
6400 // Note that while we advertise v6, we still require v4 (possibly NAT'd, but not link-local) because we must use
6401 // V4 to communicate w/ our DNS server
6402 }
6403
6404 exit:
6405 CFRelease(dict);
6406 }
6407 CFRelease(store);
6408 }
6409 return mStatus_NoError;
6410 }
6411
6412 mDNSexport void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status)
6413 {
6414 LogInfo("mDNSPlatformDynDNSHostNameStatusChanged %d %##s", status, dname->c);
6415 char uname[MAX_ESCAPED_DOMAIN_NAME]; // Max legal C-string name, including terminating NUL
6416 ConvertDomainNameToCString(dname, uname);
6417
6418 char *p = uname;
6419 while (*p)
6420 {
6421 *p = tolower(*p);
6422 if (!(*(p+1)) && *p == '.') *p = 0; // if last character, strip trailing dot
6423 p++;
6424 }
6425
6426 // We need to make a CFDictionary called "State:/Network/DynamicDNS" containing (at present) a single entity.
6427 // That single entity is a CFDictionary with name "HostNames".
6428 // The "HostNames" CFDictionary contains a set of name/value pairs, where the each name is the FQDN
6429 // in question, and the corresponding value is a CFDictionary giving the state for that FQDN.
6430 // (At present we only support a single FQDN, so this dictionary holds just a single name/value pair.)
6431 // The CFDictionary for each FQDN holds (at present) a single name/value pair,
6432 // where the name is "Status" and the value is a CFNumber giving an errror code (with zero meaning success).
6433
6434 const CFStringRef StateKeys [1] = { CFSTR("HostNames") };
6435 const CFStringRef HostKeys [1] = { CFStringCreateWithCString(NULL, uname, kCFStringEncodingUTF8) };
6436 const CFStringRef StatusKeys[1] = { CFSTR("Status") };
6437 if (!HostKeys[0]) LogMsg("SetDDNSNameStatus: CFStringCreateWithCString(%s) failed", uname);
6438 else
6439 {
6440 const CFNumberRef StatusVals[1] = { CFNumberCreate(NULL, kCFNumberSInt32Type, &status) };
6441 if (!StatusVals[0]) LogMsg("SetDDNSNameStatus: CFNumberCreate(%d) failed", status);
6442 else
6443 {
6444 const CFDictionaryRef HostVals[1] = { CFDictionaryCreate(NULL, (void*)StatusKeys, (void*)StatusVals, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) };
6445 if (HostVals[0])
6446 {
6447 const CFDictionaryRef StateVals[1] = { CFDictionaryCreate(NULL, (void*)HostKeys, (void*)HostVals, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) };
6448 if (StateVals[0])
6449 {
6450 CFDictionaryRef StateDict = CFDictionaryCreate(NULL, (void*)StateKeys, (void*)StateVals, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
6451 if (StateDict)
6452 {
6453 mDNSDynamicStoreSetConfig(kmDNSDynamicConfig, mDNSNULL, StateDict);
6454 CFRelease(StateDict);
6455 }
6456 CFRelease(StateVals[0]);
6457 }
6458 CFRelease(HostVals[0]);
6459 }
6460 CFRelease(StatusVals[0]);
6461 }
6462 CFRelease(HostKeys[0]);
6463 }
6464 }
6465
6466 #if APPLE_OSX_mDNSResponder
6467 #if !NO_AWACS
6468
6469 // checks whether a domain is present in Setup:/Network/BackToMyMac. Just because there is a key in the
6470 // keychain for a domain, it does not become a valid BTMM domain. If things get inconsistent, this will
6471 // help catch it
6472 mDNSlocal mDNSBool IsBTMMDomain(domainname *d)
6473 {
6474 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:IsBTMMDomain"), NULL, NULL);
6475 if (!store)
6476 {
6477 LogMsg("IsBTMMDomain: SCDynamicStoreCreate failed: %s", SCErrorString(SCError()));
6478 return mDNSfalse;
6479 }
6480 CFDictionaryRef btmm = SCDynamicStoreCopyValue(store, NetworkChangedKey_BackToMyMac);
6481 if (btmm)
6482 {
6483 CFIndex size = CFDictionaryGetCount(btmm);
6484 char buf[MAX_ESCAPED_DOMAIN_NAME]; // Max legal C-string name, including terminating NUL
6485 const void *key[size];
6486 const void *val[size];
6487 domainname dom;
6488 int i;
6489 CFDictionaryGetKeysAndValues(btmm, key, val);
6490 for (i = 0; i < size; i++)
6491 {
6492 LogInfo("BackToMyMac %d", i);
6493 if (!CFStringGetCString(key[i], buf, sizeof(buf), kCFStringEncodingUTF8))
6494 LogMsg("IsBTMMDomain: ERROR!! Can't read BackToMyMac %d key %s", i, buf);
6495 else
6496 {
6497 mDNSu32 uid = atoi(buf);
6498 if (!CFStringGetCString(val[i], buf, sizeof(buf), kCFStringEncodingUTF8))
6499 LogMsg("IsBTMMDomain: Can't read BackToMyMac %d val %s", i, buf);
6500 else if (MakeDomainNameFromDNSNameString(&dom, buf) && dom.c[0])
6501 {
6502 if (SameDomainName(&dom, d))
6503 {
6504 LogInfo("IsBTMMDomain: Domain %##s is a btmm domain, uid %u", d->c, uid);
6505 CFRelease(btmm);
6506 CFRelease(store);
6507 return mDNStrue;
6508 }
6509 }
6510 }
6511 }
6512 CFRelease(btmm);
6513 }
6514 CFRelease(store);
6515 LogInfo("IsBTMMDomain: Domain %##s not a btmm domain", d->c);
6516 return mDNSfalse;
6517 }
6518
6519 // Appends data to the buffer
6520 mDNSlocal int AddOneItem(char *buf, int bufsz, char *data, int *currlen)
6521 {
6522 int len;
6523
6524 len = strlcpy(buf + *currlen, data, bufsz - *currlen);
6525 if (len >= (bufsz - *currlen))
6526 {
6527 // if we have exceeded the space in buf, it has already been NULL terminated
6528 // and we have nothing more to do. Set currlen to the last byte so that the caller
6529 // knows to do the right thing
6530 LogMsg("AddOneItem: Exceeded the max buffer size currlen %d, len %d", *currlen, len);
6531 *currlen = bufsz - 1;
6532 return -1;
6533 }
6534 else { (*currlen) += len; }
6535
6536 buf[*currlen] = ',';
6537 if (*currlen >= bufsz)
6538 {
6539 LogMsg("AddOneItem: ERROR!! How can currlen be %d", *currlen);
6540 *currlen = bufsz - 1;
6541 buf[*currlen] = 0;
6542 return -1;
6543 }
6544 // if we have filled up the buffer exactly, then there is no more work to do
6545 if (*currlen == bufsz - 1) { buf[*currlen] = 0; return -1; }
6546 (*currlen)++;
6547 return *currlen;
6548 }
6549
6550 // If we have at least one BTMM domain, then trigger the connection to the relay. If we have no
6551 // BTMM domains, then bring down the connection to the relay.
6552 mDNSlocal void UpdateBTMMRelayConnection(mDNS *const m)
6553 {
6554 DomainAuthInfo *BTMMDomain = mDNSNULL;
6555 DomainAuthInfo *FoundInList;
6556 static mDNSBool AWACSDConnected = mDNSfalse;
6557 char AllUsers[1024]; // maximum size of mach message
6558 char AllPass[1024]; // maximum size of mach message
6559 char username[MAX_DOMAIN_LABEL + 1];
6560 int currulen = 0;
6561 int currplen = 0;
6562
6563 // if a domain is being deleted, we want to send a disconnect. If we send a disconnect now,
6564 // we may not be able to send the dns queries over the relay connection which may be needed
6565 // for sending the deregistrations. Hence, we need to delay sending the disconnect. But we
6566 // need to make sure that we send the disconnect before attempting the next connect as the
6567 // awacs connections are redirected based on usernames.
6568 //
6569 // For now we send a disconnect immediately. When we start sending dns queries over the relay
6570 // connection, we will need to fix this.
6571
6572 for (FoundInList = m->AuthInfoList; FoundInList; FoundInList = FoundInList->next)
6573 if (!FoundInList->deltime && FoundInList->AutoTunnel && IsBTMMDomain(&FoundInList->domain))
6574 {
6575 // We need the passwd from the first domain.
6576 BTMMDomain = FoundInList;
6577 ConvertDomainLabelToCString_unescaped((domainlabel *)BTMMDomain->domain.c, username);
6578 LogInfo("UpdateBTMMRelayConnection: user %s for domain %##s", username, BTMMDomain->domain.c);
6579 if (AddOneItem(AllUsers, sizeof(AllUsers), username, &currulen) == -1) break;
6580 if (AddOneItem(AllPass, sizeof(AllPass), BTMMDomain->b64keydata, &currplen) == -1) break;
6581 }
6582
6583 if (BTMMDomain)
6584 {
6585 // In the normal case (where we neither exceed the buffer size nor write bytes that
6586 // fit exactly into the buffer), currulen/currplen should be a different size than
6587 // (AllUsers - 1) / (AllPass - 1). In that case, we need to override the "," with a NULL byte.
6588
6589 if (currulen != (int)(sizeof(AllUsers) - 1)) AllUsers[currulen - 1] = 0;
6590 if (currplen != (int)(sizeof(AllPass) - 1)) AllPass[currplen - 1] = 0;
6591
6592 LogInfo("UpdateBTMMRelayConnection: AWS_Connect for user %s", AllUsers);
6593 AWACS_Connect(AllUsers, AllPass, "hello.connectivity.me.com");
6594 AWACSDConnected = mDNStrue;
6595 }
6596 else
6597 {
6598 // Disconnect only if we connected previously
6599 if (AWACSDConnected)
6600 {
6601 LogInfo("UpdateBTMMRelayConnection: AWS_Disconnect");
6602 AWACS_Disconnect();
6603 AWACSDConnected = mDNSfalse;
6604 }
6605 else LogInfo("UpdateBTMMRelayConnection: Not calling AWS_Disconnect");
6606 }
6607 }
6608 #else
6609 mDNSlocal void UpdateBTMMRelayConnection(mDNS *const m)
6610 {
6611 (void) m; // Unused
6612 LogInfo("UpdateBTMMRelayConnection: AWACS connection not started, no AWACS library");
6613 }
6614 #endif // ! NO_AWACS
6615
6616 mDNSlocal void ProcessConndConfigChanges(mDNS *const m);
6617
6618 #endif // APPLE_OSX_mDNSResponder
6619
6620 // MUST be called holding the lock
6621 mDNSexport void SetDomainSecrets(mDNS *m)
6622 {
6623 #ifdef NO_SECURITYFRAMEWORK
6624 (void) m;
6625 LogMsg("Note: SetDomainSecrets: no keychain support");
6626 #else
6627 mDNSBool haveAutoTunnels = mDNSfalse;
6628
6629 LogInfo("SetDomainSecrets");
6630
6631 // Rather than immediately deleting all keys now, we mark them for deletion in ten seconds.
6632 // In the case where the user simultaneously removes their DDNS host name and the key
6633 // for it, this gives mDNSResponder ten seconds to gracefully delete the name from the
6634 // server before it loses access to the necessary key. Otherwise, we'd leave orphaned
6635 // address records behind that we no longer have permission to delete.
6636 DomainAuthInfo *ptr;
6637 for (ptr = m->AuthInfoList; ptr; ptr = ptr->next)
6638 ptr->deltime = NonZeroTime(m->timenow + mDNSPlatformOneSecond*10);
6639
6640 #if APPLE_OSX_mDNSResponder
6641 {
6642 // Mark all TunnelClients for deletion
6643 ClientTunnel *client;
6644 for (client = m->TunnelClients; client; client = client->next)
6645 {
6646 LogInfo("SetDomainSecrets: tunnel to %##s marked for deletion", client->dstname.c);
6647 client->MarkedForDeletion = mDNStrue;
6648 }
6649 }
6650 #endif // APPLE_OSX_mDNSResponder
6651
6652 // String Array used to write list of private domains to Dynamic Store
6653 CFMutableArrayRef sa = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
6654 if (!sa) { LogMsg("SetDomainSecrets: CFArrayCreateMutable failed"); return; }
6655 CFIndex i;
6656 CFDataRef data = NULL;
6657 const int itemsPerEntry = 4; // domain name, key name, key value, Name value
6658 CFArrayRef secrets = NULL;
6659 int err = mDNSKeychainGetSecrets(&secrets);
6660 if (err || !secrets)
6661 LogMsg("SetDomainSecrets: mDNSKeychainGetSecrets failed error %d CFArrayRef %p", err, secrets);
6662 else
6663 {
6664 CFIndex ArrayCount = CFArrayGetCount(secrets);
6665 // Iterate through the secrets
6666 for (i = 0; i < ArrayCount; ++i)
6667 {
6668 mDNSBool AutoTunnel;
6669 int j, offset;
6670 CFArrayRef entry = CFArrayGetValueAtIndex(secrets, i);
6671 if (CFArrayGetTypeID() != CFGetTypeID(entry) || itemsPerEntry != CFArrayGetCount(entry))
6672 { LogMsg("SetDomainSecrets: malformed entry %d, itemsPerEntry %d", i, itemsPerEntry); continue; }
6673 for (j = 0; j < CFArrayGetCount(entry); ++j)
6674 if (CFDataGetTypeID() != CFGetTypeID(CFArrayGetValueAtIndex(entry, j)))
6675 { LogMsg("SetDomainSecrets: malformed entry item %d", j); continue; }
6676
6677 // The names have already been vetted by the helper, but checking them again here helps humans and automated tools verify correctness
6678
6679 // Max legal domainname as C-string, including space for btmmprefix and terminating NUL
6680 // Get DNS domain this key is for (kmDNSKcWhere)
6681 char stringbuf[MAX_ESCAPED_DOMAIN_NAME + sizeof(btmmprefix)];
6682 data = CFArrayGetValueAtIndex(entry, kmDNSKcWhere);
6683 if (CFDataGetLength(data) >= (int)sizeof(stringbuf))
6684 { LogMsg("SetDomainSecrets: Bad kSecServiceItemAttr length %d", CFDataGetLength(data)); continue; }
6685 CFDataGetBytes(data, CFRangeMake(0, CFDataGetLength(data)), (UInt8 *)stringbuf);
6686 stringbuf[CFDataGetLength(data)] = '\0';
6687
6688 AutoTunnel = mDNSfalse;
6689 offset = 0;
6690 if (!strncmp(stringbuf, dnsprefix, strlen(dnsprefix)))
6691 offset = strlen(dnsprefix);
6692 else if (!strncmp(stringbuf, btmmprefix, strlen(btmmprefix)))
6693 {
6694 AutoTunnel = mDNStrue;
6695 offset = strlen(btmmprefix);
6696 }
6697 domainname domain;
6698 if (!MakeDomainNameFromDNSNameString(&domain, stringbuf + offset)) { LogMsg("SetDomainSecrets: bad key domain %s", stringbuf); continue; }
6699
6700 // Get key name (kmDNSKcAccount)
6701 data = CFArrayGetValueAtIndex(entry, kmDNSKcAccount);
6702 if (CFDataGetLength(data) >= (int)sizeof(stringbuf))
6703 { LogMsg("SetDomainSecrets: Bad kSecAccountItemAttr length %d", CFDataGetLength(data)); continue; }
6704 CFDataGetBytes(data, CFRangeMake(0,CFDataGetLength(data)), (UInt8 *)stringbuf);
6705 stringbuf[CFDataGetLength(data)] = '\0';
6706
6707 domainname keyname;
6708 if (!MakeDomainNameFromDNSNameString(&keyname, stringbuf)) { LogMsg("SetDomainSecrets: bad key name %s", stringbuf); continue; }
6709
6710 // Get key data (kmDNSKcKey)
6711 data = CFArrayGetValueAtIndex(entry, kmDNSKcKey);
6712 if (CFDataGetLength(data) >= (int)sizeof(stringbuf))
6713 {
6714 LogMsg("SetDomainSecrets: Shared secret too long: %d", CFDataGetLength(data));
6715 continue;
6716 }
6717 CFDataGetBytes(data, CFRangeMake(0, CFDataGetLength(data)), (UInt8 *)stringbuf);
6718 stringbuf[CFDataGetLength(data)] = '\0'; // mDNS_SetSecretForDomain requires NULL-terminated C string for key
6719
6720 // Get the Name of the keychain entry (kmDNSKcName) host or host:port
6721 // The hostname also has the port number and ":". It should take a maximum of 6 bytes.
6722 char hostbuf[MAX_ESCAPED_DOMAIN_NAME + 6]; // Max legal domainname as C-string, including terminating NUL
6723 data = CFArrayGetValueAtIndex(entry, kmDNSKcName);
6724 if (CFDataGetLength(data) >= (int)sizeof(hostbuf))
6725 {
6726 LogMsg("SetDomainSecrets: host:port data too long: %d", CFDataGetLength(data));
6727 continue;
6728 }
6729 CFDataGetBytes(data, CFRangeMake(0,CFDataGetLength(data)), (UInt8 *)hostbuf);
6730 hostbuf[CFDataGetLength(data)] = '\0';
6731
6732 domainname hostname;
6733 mDNSIPPort port;
6734 char *hptr;
6735 hptr = strchr(hostbuf, ':');
6736
6737 port.NotAnInteger = 0;
6738 if (hptr)
6739 {
6740 mDNSu8 *p;
6741 mDNSu16 val = 0;
6742
6743 *hptr++ = '\0';
6744 while(hptr && *hptr != 0)
6745 {
6746 if (*hptr < '0' || *hptr > '9')
6747 { LogMsg("SetDomainSecrets: Malformed Port number %d, val %d", *hptr, val); val = 0; break;}
6748 val = val * 10 + *hptr - '0';
6749 hptr++;
6750 }
6751 if (!val) continue;
6752 p = (mDNSu8 *)&val;
6753 port.NotAnInteger = p[0] << 8 | p[1];
6754 }
6755 // The hostbuf is of the format dsid@hostname:port. We don't care about the dsid.
6756 hptr = strchr(hostbuf, '@');
6757 if (hptr)
6758 hptr++;
6759 else
6760 hptr = hostbuf;
6761 if (!MakeDomainNameFromDNSNameString(&hostname, hptr)) { LogMsg("SetDomainSecrets: bad host name %s", hptr); continue; }
6762
6763 DomainAuthInfo *FoundInList;
6764 for (FoundInList = m->AuthInfoList; FoundInList; FoundInList = FoundInList->next)
6765 if (SameDomainName(&FoundInList->domain, &domain)) break;
6766
6767 #if APPLE_OSX_mDNSResponder
6768 if (FoundInList)
6769 {
6770 // If any client tunnel destination is in this domain, set deletion flag to false
6771 ClientTunnel *client;
6772 for (client = m->TunnelClients; client; client = client->next)
6773 if (FoundInList == GetAuthInfoForName_internal(m, &client->dstname))
6774 {
6775 LogInfo("SetDomainSecrets: tunnel to %##s no longer marked for deletion", client->dstname.c);
6776 client->MarkedForDeletion = mDNSfalse;
6777 }
6778 }
6779
6780 #endif // APPLE_OSX_mDNSResponder
6781
6782 // Uncomment the line below to view the keys as they're read out of the system keychain
6783 // DO NOT SHIP CODE THIS WAY OR YOU'LL LEAK SECRET DATA INTO A PUBLICLY READABLE FILE!
6784 //LogInfo("SetDomainSecrets: domain %##s keyname %##s key %s hostname %##s port %d", &domain.c, &keyname.c, stringbuf, hostname.c, (port.b[0] << 8 | port.b[1]));
6785 LogInfo("SetDomainSecrets: domain %##s keyname %##s hostname %##s port %d", &domain.c, &keyname.c, hostname.c, (port.b[0] << 8 | port.b[1]));
6786
6787 // If didn't find desired domain in the list, make a new entry
6788 ptr = FoundInList;
6789 if (FoundInList && FoundInList->AutoTunnel && haveAutoTunnels == mDNSfalse) haveAutoTunnels = mDNStrue;
6790 if (!FoundInList)
6791 {
6792 ptr = (DomainAuthInfo*)mallocL("DomainAuthInfo", sizeof(*ptr));
6793 if (!ptr) { LogMsg("SetDomainSecrets: No memory"); continue; }
6794 }
6795
6796 //LogInfo("SetDomainSecrets: %d of %d %##s", i, ArrayCount, &domain);
6797
6798 // It is an AutoTunnel if the keychains tells us so (with btmm prefix) or if it is a TunnelModeDomain
6799 if (mDNS_SetSecretForDomain(m, ptr, &domain, &keyname, stringbuf, &hostname, &port, AutoTunnel) == mStatus_BadParamErr)
6800 {
6801 if (!FoundInList) mDNSPlatformMemFree(ptr); // If we made a new DomainAuthInfo here, and it turned out bad, dispose it immediately
6802 continue;
6803 }
6804
6805 ConvertDomainNameToCString(&domain, stringbuf);
6806 CFStringRef cfs = CFStringCreateWithCString(NULL, stringbuf, kCFStringEncodingUTF8);
6807 if (cfs) { CFArrayAppendValue(sa, cfs); CFRelease(cfs); }
6808 }
6809 CFRelease(secrets);
6810 }
6811
6812 if (!privateDnsArray || !CFEqual(privateDnsArray, sa))
6813 {
6814 if (privateDnsArray)
6815 CFRelease(privateDnsArray);
6816
6817 privateDnsArray = sa;
6818 CFRetain(privateDnsArray);
6819 mDNSDynamicStoreSetConfig(kmDNSPrivateConfig, mDNSNULL, privateDnsArray);
6820 }
6821 CFRelease(sa);
6822
6823 #if APPLE_OSX_mDNSResponder
6824 {
6825 // clean up ClientTunnels
6826 ClientTunnel **pp = &m->TunnelClients;
6827 while (*pp)
6828 {
6829 if ((*pp)->MarkedForDeletion)
6830 {
6831 ClientTunnel *cur = *pp;
6832 LogInfo("SetDomainSecrets: removing client %p %##s from list", cur, cur->dstname.c);
6833 if (cur->q.ThisQInterval >= 0) mDNS_StopQuery(m, &cur->q);
6834 AutoTunnelSetKeys(cur, mDNSfalse);
6835 *pp = cur->next;
6836 freeL("ClientTunnel", cur);
6837 }
6838 else
6839 pp = &(*pp)->next;
6840 }
6841
6842 mDNSBool needAutoTunnelNAT = mDNSfalse;
6843 DomainAuthInfo *info;
6844 for (info = m->AuthInfoList; info; info = info->next)
6845 {
6846 if (info->AutoTunnel)
6847 {
6848 UpdateAutoTunnelDeviceInfoRecord(m, info);
6849 UpdateAutoTunnelHostRecord(m, info);
6850 UpdateAutoTunnelServiceRecords(m, info);
6851 UpdateAutoTunnel6Record(m, info);
6852 if (info->deltime)
6853 {
6854 if (info->AutoTunnelServiceStarted) info->AutoTunnelServiceStarted = mDNSfalse;
6855 }
6856 else if (info->AutoTunnelServiceStarted)
6857 needAutoTunnelNAT = true;
6858
6859 UpdateAutoTunnelDomainStatus(m, info);
6860 }
6861 }
6862
6863 // If the AutoTunnel NAT-T is no longer needed (& is currently running), stop it
6864 if (!needAutoTunnelNAT && m->AutoTunnelNAT.clientContext)
6865 {
6866 // stop the NAT operation, reset port, cleanup state
6867 mDNS_StopNATOperation_internal(m, &m->AutoTunnelNAT);
6868 m->AutoTunnelNAT.ExternalAddress = zerov4Addr;
6869 m->AutoTunnelNAT.NewAddress = zerov4Addr;
6870 m->AutoTunnelNAT.ExternalPort = zeroIPPort;
6871 m->AutoTunnelNAT.RequestedPort = zeroIPPort;
6872 m->AutoTunnelNAT.Lifetime = 0;
6873 m->AutoTunnelNAT.Result = mStatus_NoError;
6874 m->AutoTunnelNAT.clientContext = mDNSNULL;
6875 }
6876
6877 UpdateAnonymousRacoonConfig(m); // Determine whether we need racoon to accept incoming connections
6878 ProcessConndConfigChanges(m); // Update AutoTunnelInnerAddress values and default ipsec policies as necessary
6879 }
6880 #endif // APPLE_OSX_mDNSResponder
6881
6882 CheckSuppressUnusableQuestions(m);
6883
6884 #endif /* NO_SECURITYFRAMEWORK */
6885 }
6886
6887 mDNSlocal void SetLocalDomains(void)
6888 {
6889 CFMutableArrayRef sa = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
6890 if (!sa) { LogMsg("SetLocalDomains: CFArrayCreateMutable failed"); return; }
6891
6892 CFArrayAppendValue(sa, CFSTR("local"));
6893 CFArrayAppendValue(sa, CFSTR("254.169.in-addr.arpa"));
6894 CFArrayAppendValue(sa, CFSTR("8.e.f.ip6.arpa"));
6895 CFArrayAppendValue(sa, CFSTR("9.e.f.ip6.arpa"));
6896 CFArrayAppendValue(sa, CFSTR("a.e.f.ip6.arpa"));
6897 CFArrayAppendValue(sa, CFSTR("b.e.f.ip6.arpa"));
6898
6899 mDNSDynamicStoreSetConfig(kmDNSMulticastConfig, mDNSNULL, sa);
6900 CFRelease(sa);
6901 }
6902
6903 mDNSlocal void GetCurrentPMSetting(const CFStringRef name, mDNSs32 *val)
6904 {
6905 #if USE_IOPMCOPYACTIVEPMPREFERENCES
6906 CFTypeRef blob = NULL;
6907 CFStringRef str = NULL;
6908 CFDictionaryRef odict = NULL;
6909 CFDictionaryRef idict = NULL;
6910 CFNumberRef number = NULL;
6911
6912 blob = IOPSCopyPowerSourcesInfo();
6913 if (!blob) { LogMsg("GetCurrentPMSetting: IOPSCopyPowerSourcesInfo failed!"); goto end; }
6914
6915 odict = IOPMCopyActivePMPreferences();
6916 if (!odict) { LogMsg("GetCurrentPMSetting: IOPMCopyActivePMPreferences failed!"); goto end; }
6917
6918 str = IOPSGetProvidingPowerSourceType(blob);
6919 if (!str) { LogMsg("GetCurrentPMSetting: IOPSGetProvidingPowerSourceType failed!"); goto end; }
6920
6921 idict = CFDictionaryGetValue(odict, str);
6922 if (!idict)
6923 {
6924 char buf[256];
6925 if (!CFStringGetCString(str, buf, sizeof(buf), kCFStringEncodingUTF8)) buf[0] = 0;
6926 LogMsg("GetCurrentPMSetting: CFDictionaryGetValue (%s) failed!", buf);
6927 goto end;
6928 }
6929
6930 number = CFDictionaryGetValue(idict, name);
6931 if (!number || CFGetTypeID(number) != CFNumberGetTypeID() || !CFNumberGetValue(number, kCFNumberSInt32Type, val))
6932 *val = 0;
6933 end:
6934 if (blob) CFRelease(blob);
6935 if (odict) CFRelease(odict);
6936
6937 #else
6938
6939 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:GetCurrentPMSetting"), NULL, NULL);
6940 if (!store) LogMsg("GetCurrentPMSetting: SCDynamicStoreCreate failed: %s", SCErrorString(SCError()));
6941 else
6942 {
6943 CFDictionaryRef dict = SCDynamicStoreCopyValue(store, NetworkChangedKey_PowerSettings);
6944 if (!dict) LogSPS("GetCurrentPMSetting: Could not get IOPM CurrentSettings dict");
6945 else
6946 {
6947 CFNumberRef number = CFDictionaryGetValue(dict, name);
6948 if (!number || CFGetTypeID(number) != CFNumberGetTypeID() || !CFNumberGetValue(number, kCFNumberSInt32Type, val))
6949 *val = 0;
6950 CFRelease(dict);
6951 }
6952 CFRelease(store);
6953 }
6954
6955 #endif
6956 }
6957
6958 #if APPLE_OSX_mDNSResponder
6959
6960 static CFMutableDictionaryRef spsStatusDict = NULL;
6961 static const CFStringRef kMetricRef = CFSTR("Metric");
6962
6963 mDNSlocal void SPSStatusPutNumber(CFMutableDictionaryRef dict, const mDNSu8* const ptr, CFStringRef key)
6964 {
6965 mDNSu8 tmp = (ptr[0] - '0') * 10 + ptr[1] - '0';
6966 CFNumberRef num = CFNumberCreate(NULL, kCFNumberSInt8Type, &tmp);
6967 if (!num)
6968 LogMsg("SPSStatusPutNumber: Could not create CFNumber");
6969 else
6970 {
6971 CFDictionarySetValue(dict, key, num);
6972 CFRelease(num);
6973 }
6974 }
6975
6976 mDNSlocal CFMutableDictionaryRef SPSCreateDict(const mDNSu8* const ptr)
6977 {
6978 CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
6979 if (!dict) { LogMsg("SPSCreateDict: Could not create CFDictionary dict"); return dict; }
6980
6981 char buffer[1024];
6982 buffer[mDNS_snprintf(buffer, sizeof(buffer), "%##s", ptr) - 1] = 0;
6983 CFStringRef spsname = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
6984 if (!spsname) { LogMsg("SPSCreateDict: Could not create CFString spsname full"); CFRelease(dict); return NULL; }
6985 CFDictionarySetValue(dict, CFSTR("FullName"), spsname);
6986 CFRelease(spsname);
6987
6988 if (ptr[0] >= 2) SPSStatusPutNumber(dict, ptr + 1, CFSTR("Type"));
6989 if (ptr[0] >= 5) SPSStatusPutNumber(dict, ptr + 4, CFSTR("Portability"));
6990 if (ptr[0] >= 8) SPSStatusPutNumber(dict, ptr + 7, CFSTR("MarginalPower"));
6991 if (ptr[0] >= 11) SPSStatusPutNumber(dict, ptr +10, CFSTR("TotalPower"));
6992
6993 mDNSu32 tmp = SPSMetric(ptr);
6994 CFNumberRef num = CFNumberCreate(NULL, kCFNumberSInt32Type, &tmp);
6995 if (!num)
6996 LogMsg("SPSCreateDict: Could not create CFNumber");
6997 else
6998 {
6999 CFDictionarySetValue(dict, kMetricRef, num);
7000 CFRelease(num);
7001 }
7002
7003 if (ptr[0] >= 12)
7004 {
7005 memcpy(buffer, ptr + 13, ptr[0] - 12);
7006 buffer[ptr[0] - 12] = 0;
7007 spsname = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
7008 if (!spsname) { LogMsg("SPSCreateDict: Could not create CFString spsname"); CFRelease(dict); return NULL; }
7009 else
7010 {
7011 CFDictionarySetValue(dict, CFSTR("PrettyName"), spsname);
7012 CFRelease(spsname);
7013 }
7014 }
7015
7016 return dict;
7017 }
7018
7019 mDNSlocal CFComparisonResult CompareSPSEntries(const void *val1, const void *val2, void *context)
7020 {
7021 (void)context;
7022 return CFNumberCompare((CFNumberRef)CFDictionaryGetValue((CFDictionaryRef)val1, kMetricRef),
7023 (CFNumberRef)CFDictionaryGetValue((CFDictionaryRef)val2, kMetricRef),
7024 NULL);
7025 }
7026
7027 mDNSlocal void UpdateSPSStatus(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
7028 {
7029 NetworkInterfaceInfo* info = (NetworkInterfaceInfo*)question->QuestionContext;
7030 debugf("UpdateSPSStatus: %s %##s %s %s", info->ifname, question->qname.c, AddRecord ? "Add" : "Rmv", answer ? RRDisplayString(m, answer) : "<null>");
7031
7032 mDNS_Lock(m);
7033 mDNS_UpdateAllowSleep(m);
7034 mDNS_Unlock(m);
7035
7036 if (answer && SPSMetric(answer->rdata->u.name.c) > 999999) return; // Ignore instances with invalid names
7037
7038 if (!spsStatusDict)
7039 {
7040 spsStatusDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
7041 if (!spsStatusDict) { LogMsg("UpdateSPSStatus: Could not create CFDictionary spsStatusDict"); return; }
7042 }
7043
7044 CFStringRef ifname = CFStringCreateWithCString(NULL, info->ifname, kCFStringEncodingUTF8);
7045 if (!ifname) { LogMsg("UpdateSPSStatus: Could not create CFString ifname"); return; }
7046
7047 CFMutableArrayRef array = NULL;
7048
7049 if (!CFDictionaryGetValueIfPresent(spsStatusDict, ifname, (const void**) &array))
7050 {
7051 array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
7052 if (!array) { LogMsg("UpdateSPSStatus: Could not create CFMutableArray"); CFRelease(ifname); return; }
7053 CFDictionarySetValue(spsStatusDict, ifname, array);
7054 CFRelease(array); // let go of our reference, now that the dict has one
7055 }
7056 else
7057 if (!array) { LogMsg("UpdateSPSStatus: Could not get CFMutableArray for %s", info->ifname); CFRelease(ifname); return; }
7058
7059 if (!answer) // special call that means the question has been stopped (because the interface is going away)
7060 CFArrayRemoveAllValues(array);
7061 else
7062 {
7063 CFMutableDictionaryRef dict = SPSCreateDict(answer->rdata->u.name.c);
7064 if (!dict) { CFRelease(ifname); return; }
7065
7066 if (AddRecord)
7067 {
7068 if (!CFArrayContainsValue(array, CFRangeMake(0, CFArrayGetCount(array)), dict))
7069 {
7070 int i=0;
7071 for (i=0; i<CFArrayGetCount(array); i++)
7072 if (CompareSPSEntries(CFArrayGetValueAtIndex(array, i), dict, NULL) != kCFCompareLessThan)
7073 break;
7074 CFArrayInsertValueAtIndex(array, i, dict);
7075 }
7076 else LogMsg("UpdateSPSStatus: %s array already contains %##s", info->ifname, answer->rdata->u.name.c);
7077 }
7078 else
7079 {
7080 CFIndex i = CFArrayGetFirstIndexOfValue(array, CFRangeMake(0, CFArrayGetCount(array)), dict);
7081 if (i != -1) CFArrayRemoveValueAtIndex(array, i);
7082 else LogMsg("UpdateSPSStatus: %s array does not contain %##s", info->ifname, answer->rdata->u.name.c);
7083 }
7084
7085 CFRelease(dict);
7086 }
7087
7088 if (!m->ShutdownTime) mDNSDynamicStoreSetConfig(kmDNSSleepProxyServersState, info->ifname, array);
7089
7090 CFRelease(ifname);
7091 }
7092
7093 mDNSlocal mDNSs32 GetSystemSleepTimerSetting(void)
7094 {
7095 mDNSs32 val = -1;
7096 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:GetSystemSleepTimerSetting"), NULL, NULL);
7097 if (!store)
7098 LogMsg("GetSystemSleepTimerSetting: SCDynamicStoreCreate failed: %s", SCErrorString(SCError()));
7099 else
7100 {
7101 CFDictionaryRef dict = SCDynamicStoreCopyValue(store, NetworkChangedKey_PowerSettings);
7102 if (dict)
7103 {
7104 CFNumberRef number = CFDictionaryGetValue(dict, CFSTR("System Sleep Timer"));
7105 if (number) CFNumberGetValue(number, kCFNumberSInt32Type, &val);
7106 CFRelease(dict);
7107 }
7108 CFRelease(store);
7109 }
7110 return val;
7111 }
7112
7113 mDNSlocal void SetSPS(mDNS *const m)
7114 {
7115
7116 // If we ever want to know InternetSharing status in the future, use DNSXEnableProxy()
7117 mDNSu8 sps = (OfferSleepProxyService && GetSystemSleepTimerSetting() == 0) ? mDNSSleepProxyMetric_IncidentalSoftware : 0;
7118
7119 // For devices that are not running NAT, but are set to never sleep, we may choose to act
7120 // as a Sleep Proxy, but only for non-portable Macs (Portability > 35 means nominal weight < 3kg)
7121 //if (sps > mDNSSleepProxyMetric_PrimarySoftware && SPMetricPortability > 35) sps = 0;
7122
7123 // If we decide to let laptops act as Sleep Proxy, we should do it only when running on AC power, not on battery
7124
7125 // For devices that are unable to sleep at all to save power, or save 1W or less by sleeping,
7126 // it makes sense for them to offer low-priority Sleep Proxy service on the network.
7127 // We rate such a device as metric 70 ("Incidentally Available Hardware")
7128 if (SPMetricMarginalPower <= 60 && !sps) sps = mDNSSleepProxyMetric_IncidentalHardware;
7129
7130 // If the launchd plist specifies an explicit value for the Intent Metric, then use that instead of the
7131 // computed value (currently 40 "Primary Network Infrastructure Software" or 80 "Incidentally Available Software")
7132 if (sps && OfferSleepProxyService && OfferSleepProxyService < 100) sps = OfferSleepProxyService;
7133
7134 #ifdef NO_APPLETV_SLEEP_PROXY_ON_WIFI
7135 // AppleTVs are not reliable sleep proxy servers on WiFi. Do not offer to be a BSP if the WiFi interface is active.
7136 if (IsAppleTV())
7137 {
7138 NetworkInterfaceInfo *intf = mDNSNULL;
7139 mDNSEthAddr bssid = zeroEthAddr;
7140 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7141 {
7142 bssid = GetBSSID(intf->ifname);
7143 if (!mDNSSameEthAddress(&bssid, &zeroEthAddr))
7144 {
7145 LogMsg("SetSPS: AppleTV on WiFi - not advertising BSP services");
7146 sps = 0;
7147 break;
7148 }
7149 }
7150 }
7151 #endif // NO_APPLETV_SLEEP_PROXY_ON_WIFI
7152
7153 mDNSCoreBeSleepProxyServer(m, sps, SPMetricPortability, SPMetricMarginalPower, SPMetricTotalPower, SPMetricFeatures);
7154 }
7155
7156 // The definitions below should eventually come from some externally-supplied header file.
7157 // However, since these definitions can't really be changed without breaking binary compatibility,
7158 // they should never change, so in practice it should not be a big problem to have them defined here.
7159
7160 enum
7161 { // commands from the daemon to the driver
7162 cmd_mDNSOffloadRR = 21, // give the mdns update buffer to the driver
7163 };
7164
7165 typedef union { void *ptr; mDNSOpaque64 sixtyfourbits; } FatPtr;
7166
7167 typedef struct
7168 { // cmd_mDNSOffloadRR structure
7169 uint32_t command; // set to OffloadRR
7170 uint32_t rrBufferSize; // number of bytes of RR records
7171 uint32_t numUDPPorts; // number of SRV UDP ports
7172 uint32_t numTCPPorts; // number of SRV TCP ports
7173 uint32_t numRRRecords; // number of RR records
7174 uint32_t compression; // rrRecords - compression is base for compressed strings
7175 FatPtr rrRecords; // address of array of pointers to the rr records
7176 FatPtr udpPorts; // address of udp port list (SRV)
7177 FatPtr tcpPorts; // address of tcp port list (SRV)
7178 } mDNSOffloadCmd;
7179
7180 #include <IOKit/IOKitLib.h>
7181 #include <dns_util.h>
7182
7183 mDNSlocal mDNSu16 GetPortArray(mDNS *const m, int trans, mDNSIPPort *portarray)
7184 {
7185 const domainlabel *const tp = (trans == mDNSTransport_UDP) ? (const domainlabel *)"\x4_udp" : (const domainlabel *)"\x4_tcp";
7186 int count = 0;
7187 AuthRecord *rr;
7188 for (rr = m->ResourceRecords; rr; rr=rr->next)
7189 if (rr->resrec.rrtype == kDNSType_SRV && SameDomainLabel(ThirdLabel(rr->resrec.name)->c, tp->c))
7190 {
7191 if (portarray) portarray[count] = rr->resrec.rdata->u.srv.port;
7192 count++;
7193 }
7194
7195 // If Back to My Mac is on, also wake for packets to the IPSEC UDP port (4500)
7196 if (trans == mDNSTransport_UDP && m->AutoTunnelNAT.clientContext)
7197 {
7198 LogSPS("GetPortArray Back to My Mac at %d", count);
7199 if (portarray) portarray[count] = IPSECPort;
7200 count++;
7201 }
7202 return(count);
7203 }
7204
7205 #if APPLE_OSX_mDNSResponder && !TARGET_OS_EMBEDDED
7206 mDNSlocal mDNSBool SupportsTCPKeepAlive()
7207 {
7208 IOReturn ret = kIOReturnSuccess;
7209 CFTypeRef obj = NULL;
7210 mDNSBool supports = mDNSfalse;
7211
7212 ret = IOPlatformCopyFeatureActive(CFSTR("TCPKeepAliveDuringSleep"), &obj);
7213 if ((kIOReturnSuccess == ret) && (obj != NULL))
7214 {
7215 supports = (obj == kCFBooleanTrue)? mDNStrue : mDNSfalse;
7216 CFRelease(obj);
7217 }
7218 LogSPS("%s: The hardware %s TCP Keep Alive", __func__, (supports ? "supports" : "does not support"));
7219 return supports;
7220 }
7221
7222 mDNSlocal mDNSBool OnBattery(void)
7223 {
7224 CFTypeRef powerInfo = IOPSCopyPowerSourcesInfo();
7225 CFTypeRef powerSrc = IOPSGetProvidingPowerSourceType(powerInfo);
7226 mDNSBool result = mDNSfalse;
7227
7228 if (powerInfo != NULL)
7229 {
7230 result = CFEqual(CFSTR(kIOPSBatteryPowerValue), powerSrc);
7231 CFRelease(powerInfo);
7232 }
7233 LogSPS("%s: The system is on %s", __func__, (result)? "Battery" : "AC Power");
7234 return result;
7235 }
7236
7237 #endif // !TARGET_OS_EMBEDDED
7238
7239 #define TfrRecordToNIC(RR) \
7240 ((!(RR)->resrec.InterfaceID && ((RR)->ForceMCast || IsLocalDomain((RR)->resrec.name))))
7241
7242 mDNSlocal mDNSu32 CountProxyRecords(mDNS *const m, uint32_t *const numbytes, NetworkInterfaceInfo *const intf, mDNSBool TCPKAOnly, mDNSBool supportsTCPKA)
7243 {
7244 *numbytes = 0;
7245 int count = 0;
7246
7247 AuthRecord *rr;
7248
7249 for (rr = m->ResourceRecords; rr; rr=rr->next)
7250 {
7251 if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
7252 {
7253 #if APPLE_OSX_mDNSResponder && !TARGET_OS_EMBEDDED
7254 mDNSBool isKeepAliveRecord = mDNS_KeepaliveRecord(&rr->resrec);
7255 // Skip over all other records if we are registering TCP KeepAlive records only
7256 // Skip over TCP KeepAlive records if the policy prohibits it or if the interface does not support TCP Keepalive.
7257 if ((TCPKAOnly && !isKeepAliveRecord) || (isKeepAliveRecord && !supportsTCPKA))
7258 continue;
7259
7260 // Update the record before calculating the number of bytes required
7261 // We offload the TCP Keepalive record even if the update fails. When the driver gets the record, it will
7262 // attempt to update the record again.
7263 if (isKeepAliveRecord && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
7264 LogSPS("CountProxyRecords: Failed to update keepalive record - %s", ARDisplayString(m, rr));
7265 #else
7266 (void) TCPKAOnly; // unused
7267 (void) supportsTCPKA; // unused
7268 (void) intf; // unused
7269 #endif // APPLE_OSX_mDNSResponder
7270 if (TfrRecordToNIC(rr))
7271 {
7272 *numbytes += DomainNameLength(rr->resrec.name) + 10 + rr->resrec.rdestimate;
7273 LogSPS("CountProxyRecords: %3d size %5d total %5d %s",
7274 count, DomainNameLength(rr->resrec.name) + 10 + rr->resrec.rdestimate, *numbytes, ARDisplayString(m,rr));
7275 count++;
7276 }
7277 }
7278 }
7279 return(count);
7280 }
7281
7282 mDNSlocal void GetProxyRecords(mDNS *const m, DNSMessage *const msg, uint32_t *const numbytes, FatPtr *const records, mDNSBool TCPKAOnly, mDNSBool supportsTCPKA)
7283 {
7284 mDNSu8 *p = msg->data;
7285 const mDNSu8 *const limit = p + *numbytes;
7286 InitializeDNSMessage(&msg->h, zeroID, zeroID);
7287
7288 int count = 0;
7289 AuthRecord *rr;
7290
7291 for (rr = m->ResourceRecords; rr; rr=rr->next)
7292 {
7293 if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
7294 {
7295 #if APPLE_OSX_mDNSResponder && !TARGET_OS_EMBEDDED
7296 mDNSBool isKeepAliveRecord = mDNS_KeepaliveRecord(&rr->resrec);
7297
7298 // Skip over all other records if we are registering TCP KeepAlive records only
7299 // Skip over TCP KeepAlive records if the policy prohibits it or if the interface does not support TCP Keepalive
7300 if ((TCPKAOnly && !isKeepAliveRecord) || (isKeepAliveRecord && !supportsTCPKA))
7301 continue;
7302 #else
7303 (void) TCPKAOnly; // unused
7304 (void) supportsTCPKA; // unused
7305 #endif // APPLE_OSX_mDNSResponder
7306
7307 if (TfrRecordToNIC(rr))
7308 {
7309 records[count].sixtyfourbits = zeroOpaque64;
7310 records[count].ptr = p;
7311 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
7312 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it
7313 p = PutResourceRecordTTLWithLimit(msg, p, &msg->h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
7314 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state
7315 LogSPS("GetProxyRecords: %3d start %p end %p size %5d total %5d %s",
7316 count, records[count].ptr, p, p - (mDNSu8 *)records[count].ptr, p - msg->data, ARDisplayString(m,rr));
7317 count++;
7318 }
7319 }
7320 }
7321 *numbytes = p - msg->data;
7322 }
7323
7324 // If compiling with old headers and libraries (pre 10.5) that don't include IOConnectCallStructMethod
7325 // then we declare a dummy version here so that the code at least compiles
7326 #ifndef AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER
7327 static kern_return_t
7328 IOConnectCallStructMethod(
7329 mach_port_t connection, // In
7330 uint32_t selector, // In
7331 const void *inputStruct, // In
7332 size_t inputStructCnt, // In
7333 void *outputStruct, // Out
7334 size_t *outputStructCnt) // In/Out
7335 {
7336 (void)connection;
7337 (void)selector;
7338 (void)inputStruct;
7339 (void)inputStructCnt;
7340 (void)outputStruct;
7341 (void)outputStructCnt;
7342 LogMsg("Compiled without IOConnectCallStructMethod");
7343 return(KERN_FAILURE);
7344 }
7345 #endif
7346
7347 mDNSexport mDNSBool SupportsInNICProxy(NetworkInterfaceInfo *const intf)
7348 {
7349 if(!UseInternalSleepProxy)
7350 {
7351 LogSPS("SupportsInNICProxy: Internal Sleep Proxy is disabled");
7352 return mDNSfalse;
7353 }
7354 return CheckInterfaceSupport(intf, mDNS_IOREG_KEY);
7355 }
7356
7357 mDNSexport mStatus ActivateLocalProxy(mDNS *const m, NetworkInterfaceInfo *const intf) // Called with the lock held
7358 {
7359 mStatus result = mStatus_UnknownErr;
7360 mDNSBool TCPKAOnly = mDNSfalse;
7361 mDNSBool supportsTCPKA = mDNSfalse;
7362 mDNSBool onbattery = mDNSfalse;
7363 io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOBSDNameMatching(kIOMasterPortDefault, 0, intf->ifname));
7364
7365 #if APPLE_OSX_mDNSResponder && !TARGET_OS_EMBEDDED
7366 onbattery = OnBattery();
7367 // Check if the interface supports TCP Keepalives and the system policy says it is ok to offload TCP Keepalive records
7368 supportsTCPKA = (InterfaceSupportsKeepAlive(intf) && SupportsTCPKeepAlive());
7369
7370 // Only TCP Keepalive records are to be offloaded if
7371 // - The system is on battery
7372 // - OR wake for network access is not set but powernap is enabled
7373 TCPKAOnly = supportsTCPKA && ((m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery) || onbattery);
7374 #else
7375 (void) onbattery; // unused;
7376 #endif
7377 if (!service) { LogMsg("ActivateLocalProxy: No service for interface %s", intf->ifname); return(mStatus_UnknownErr); }
7378
7379 io_name_t n1, n2;
7380 IOObjectGetClass(service, n1);
7381 io_object_t parent;
7382 kern_return_t kr = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent);
7383 if (kr != KERN_SUCCESS) LogMsg("ActivateLocalProxy: IORegistryEntryGetParentEntry for %s/%s failed %d", intf->ifname, n1, kr);
7384 else
7385 {
7386 IOObjectGetClass(parent, n2);
7387 LogSPS("ActivateLocalProxy: Interface %s service %s parent %s", intf->ifname, n1, n2);
7388 const CFTypeRef ref = IORegistryEntryCreateCFProperty(parent, CFSTR(mDNS_IOREG_KEY), kCFAllocatorDefault, mDNSNULL);
7389 if (!ref) LogSPS("ActivateLocalProxy: No mDNS_IOREG_KEY for interface %s/%s/%s", intf->ifname, n1, n2);
7390 else
7391 {
7392 if (CFGetTypeID(ref) != CFStringGetTypeID() || !CFEqual(ref, CFSTR(mDNS_IOREG_VALUE)))
7393 LogMsg("ActivateLocalProxy: mDNS_IOREG_KEY for interface %s/%s/%s value %s != %s",
7394 intf->ifname, n1, n2, CFStringGetCStringPtr(ref, mDNSNULL), mDNS_IOREG_VALUE);
7395 else if (!UseInternalSleepProxy)
7396 LogSPS("ActivateLocalProxy: Not using internal (NIC) sleep proxy for interface %s", intf->ifname);
7397 else
7398 {
7399 io_connect_t conObj;
7400 kr = IOServiceOpen(parent, mach_task_self(), mDNS_USER_CLIENT_CREATE_TYPE, &conObj);
7401 if (kr != KERN_SUCCESS) LogMsg("ActivateLocalProxy: IOServiceOpen for %s/%s/%s failed %d", intf->ifname, n1, n2, kr);
7402 else
7403 {
7404 mDNSOffloadCmd cmd;
7405 mDNSPlatformMemZero(&cmd, sizeof(cmd)); // When compiling 32-bit, make sure top 32 bits of 64-bit pointers get initialized to zero
7406 cmd.command = cmd_mDNSOffloadRR;
7407 cmd.numUDPPorts = GetPortArray(m, mDNSTransport_UDP, mDNSNULL);
7408 cmd.numTCPPorts = GetPortArray(m, mDNSTransport_TCP, mDNSNULL);
7409 cmd.numRRRecords = CountProxyRecords(m, &cmd.rrBufferSize, intf, TCPKAOnly, supportsTCPKA);
7410 cmd.compression = sizeof(DNSMessageHeader);
7411
7412 DNSMessage *msg = (DNSMessage *)mallocL("mDNSOffloadCmd msg", sizeof(DNSMessageHeader) + cmd.rrBufferSize);
7413 cmd.rrRecords.ptr = mallocL("mDNSOffloadCmd rrRecords", cmd.numRRRecords * sizeof(FatPtr));
7414 cmd.udpPorts.ptr = mallocL("mDNSOffloadCmd udpPorts", cmd.numUDPPorts * sizeof(mDNSIPPort));
7415 cmd.tcpPorts.ptr = mallocL("mDNSOffloadCmd tcpPorts", cmd.numTCPPorts * sizeof(mDNSIPPort));
7416
7417 LogSPS("ActivateLocalProxy: msg %p %d RR %p %d, UDP %p %d, TCP %p %d",
7418 msg, cmd.rrBufferSize,
7419 cmd.rrRecords.ptr, cmd.numRRRecords,
7420 cmd.udpPorts.ptr, cmd.numUDPPorts,
7421 cmd.tcpPorts.ptr, cmd.numTCPPorts);
7422
7423 if (!msg || !cmd.rrRecords.ptr || !cmd.udpPorts.ptr || !cmd.tcpPorts.ptr)
7424 LogMsg("ActivateLocalProxy: Failed to allocate memory: msg %p %d RR %p %d, UDP %p %d, TCP %p %d",
7425 msg, cmd.rrBufferSize,
7426 cmd.rrRecords.ptr, cmd.numRRRecords,
7427 cmd.udpPorts.ptr, cmd.numUDPPorts,
7428 cmd.tcpPorts.ptr, cmd.numTCPPorts);
7429 else
7430 {
7431 GetProxyRecords(m, msg, &cmd.rrBufferSize, cmd.rrRecords.ptr, TCPKAOnly, supportsTCPKA);
7432 GetPortArray(m, mDNSTransport_UDP, cmd.udpPorts.ptr);
7433 GetPortArray(m, mDNSTransport_TCP, cmd.tcpPorts.ptr);
7434 char outputData[2];
7435 size_t outputDataSize = sizeof(outputData);
7436 kr = IOConnectCallStructMethod(conObj, 0, &cmd, sizeof(cmd), outputData, &outputDataSize);
7437 LogSPS("ActivateLocalProxy: IOConnectCallStructMethod for %s/%s/%s %d", intf->ifname, n1, n2, kr);
7438 if (kr == KERN_SUCCESS) result = mStatus_NoError;
7439 }
7440
7441 if (cmd.tcpPorts.ptr) freeL("mDNSOffloadCmd udpPorts", cmd.tcpPorts.ptr);
7442 if (cmd.udpPorts.ptr) freeL("mDNSOffloadCmd tcpPorts", cmd.udpPorts.ptr);
7443 if (cmd.rrRecords.ptr) freeL("mDNSOffloadCmd rrRecords", cmd.rrRecords.ptr);
7444 if (msg) freeL("mDNSOffloadCmd msg", msg);
7445 IOServiceClose(conObj);
7446 }
7447 }
7448 CFRelease(ref);
7449 }
7450 IOObjectRelease(parent);
7451 }
7452 IOObjectRelease(service);
7453 return result;
7454 }
7455
7456 #endif // APPLE_OSX_mDNSResponder
7457
7458 mDNSlocal mDNSu8 SystemWakeForNetworkAccess(void)
7459 {
7460 mDNSs32 val = 0;
7461 mDNSu8 ret = (mDNSu8)mDNS_NoWake;
7462
7463 if (DisableSleepProxyClient)
7464 {
7465 LogSPS("SystemWakeForNetworkAccess: Sleep Proxy Client disabled by command-line option");
7466 return mDNSfalse;
7467 }
7468
7469 GetCurrentPMSetting(CFSTR("Wake On LAN"), &val);
7470
7471 ret = (mDNSu8)(val != 0) ? mDNS_WakeOnAC : mDNS_NoWake;
7472
7473 #if APPLE_OSX_mDNSResponder && !TARGET_OS_EMBEDDED
7474 // If we have TCP Keepalive support, system is capable of registering for TCP Keepalives.
7475 // Further policy decisions on whether to offload the records is handled during sleep processing.
7476 if ((ret == mDNS_NoWake) && SupportsTCPKeepAlive())
7477 ret = (mDNSu8)mDNS_WakeOnBattery;
7478 #endif // APPLE_OSX_mDNSResponder
7479
7480 LogSPS("SystemWakeForNetworkAccess: Wake On LAN: %d", ret);
7481 return ret;
7482 }
7483
7484 mDNSlocal mDNSBool SystemSleepOnlyIfWakeOnLAN(void)
7485 {
7486 mDNSs32 val = 0;
7487 GetCurrentPMSetting(CFSTR("PrioritizeNetworkReachabilityOverSleep"), &val);
7488 return val != 0 ? mDNStrue : mDNSfalse;
7489 }
7490
7491 #if APPLE_OSX_mDNSResponder
7492 // When sleeping, we always ensure that the _autotunnel6 record (if connected to RR relay)
7493 // gets deregistered, so that older peers are forced to connect over direct UDP instead of
7494 // the RR relay.
7495 //
7496 // When sleeping w/o a successful AutoTunnel NAT Mapping, we ensure that all our BTMM
7497 // service records are deregistered, so they do not appear in peers' Finder sidebars.
7498 // We do this by checking for the (non-autotunnel) SRV records, as the PTR and TXT records
7499 // depend on their associated SRV record and therefore will be deregistered together in a
7500 // single update with the SRV record.
7501 //
7502 // Also, the per-zone _kerberos TXT record is always there, including while sleeping, so
7503 // its presence shouldn't delay sleep.
7504 //
7505 // Note that the order of record deregistration is: first _autotunnel6 (if connected to RR
7506 // relay) and host records get deregistered, then SRV (UpdateAllSrvRecords), PTR and TXT.
7507 //
7508 // Also note that returning false here will not delay sleep past the maximum of 10 seconds.
7509 mDNSexport mDNSBool RecordReadyForSleep(mDNS *const m, AuthRecord *rr)
7510 {
7511 if (!AuthRecord_uDNS(rr)) return mDNStrue;
7512
7513 if ((rr->resrec.rrtype == kDNSType_AAAA) && SameDomainLabel(rr->namestorage.c, (const mDNSu8 *)"\x0c_autotunnel6"))
7514 {
7515 LogInfo("RecordReadyForSleep: %s not ready for sleep", ARDisplayString(m, rr));
7516 return mDNSfalse;
7517 }
7518
7519 if ((mDNSIPPortIsZero(m->AutoTunnelNAT.ExternalPort) || m->AutoTunnelNAT.Result))
7520 {
7521 if (rr->resrec.rrtype == kDNSType_SRV && rr->state != regState_NoTarget && rr->zone
7522 && !SameDomainLabel(rr->namestorage.c, (const mDNSu8 *)"\x0b_autotunnel"))
7523 {
7524 DomainAuthInfo *info = GetAuthInfoForName_internal(m, rr->zone);
7525 if (info && info->AutoTunnel)
7526 {
7527 LogInfo("RecordReadyForSleep: %s not ready for sleep", ARDisplayString(m, rr));
7528 return mDNSfalse;
7529 }
7530 }
7531 }
7532
7533 return mDNStrue;
7534 }
7535
7536 // Caller must hold the lock
7537 mDNSexport void RemoveAutoTunnel6Record(mDNS *const m)
7538 {
7539 DomainAuthInfo *info;
7540 // Set the address to zero before calling UpdateAutoTunnel6Record, so that it will
7541 // deregister the record, and the MemFree callback won't re-register.
7542 m->AutoTunnelRelayAddr = zerov6Addr;
7543 for (info = m->AuthInfoList; info; info = info->next)
7544 if (info->AutoTunnel)
7545 UpdateAutoTunnel6Record(m, info);
7546 }
7547
7548 mDNSlocal mDNSBool IPv6AddressIsOnInterface(mDNSv6Addr ipv6Addr, char *ifname)
7549 {
7550 struct ifaddrs *ifa;
7551 struct ifaddrs *ifaddrs;
7552 mDNSAddr addr;
7553
7554 if (if_nametoindex(ifname) == 0) {LogInfo("IPv6AddressIsOnInterface: Invalid name %s", ifname); return mDNSfalse;}
7555
7556 if (getifaddrs(&ifaddrs) < 0) {LogInfo("IPv6AddressIsOnInterface: getifaddrs failed"); return mDNSfalse;}
7557
7558 for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next)
7559 {
7560 if (strncmp(ifa->ifa_name, ifname, IFNAMSIZ) != 0)
7561 continue;
7562 if ((ifa->ifa_flags & IFF_UP) == 0 || !ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET6)
7563 continue;
7564 if (SetupAddr(&addr, ifa->ifa_addr) != mStatus_NoError)
7565 {
7566 LogInfo("IPv6AddressIsOnInterface: SetupAddr error, continuing to the next address");
7567 continue;
7568 }
7569 if (mDNSSameIPv6Address(ipv6Addr, *(mDNSv6Addr*)&addr.ip.v6))
7570 {
7571 LogInfo("IPv6AddressIsOnInterface: found %.16a", &ipv6Addr);
7572 break;
7573 }
7574 }
7575 freeifaddrs(ifaddrs);
7576 return ifa != NULL;
7577 }
7578
7579 mDNSlocal mDNSv6Addr IPv6AddressFromString(char* buf)
7580 {
7581 mDNSv6Addr retVal;
7582 struct addrinfo hints;
7583 struct addrinfo *res0;
7584
7585 memset(&hints, 0, sizeof(hints));
7586 hints.ai_family = AF_INET6;
7587 hints.ai_flags = AI_NUMERICHOST;
7588
7589 int err = getaddrinfo(buf, NULL, &hints, &res0);
7590 if (err)
7591 return zerov6Addr;
7592
7593 retVal = *(mDNSv6Addr*)&((struct sockaddr_in6*)res0->ai_addr)->sin6_addr;
7594
7595 freeaddrinfo(res0);
7596
7597 return retVal;
7598 }
7599
7600 mDNSlocal CFDictionaryRef CopyConnectivityBackToMyMacDict()
7601 {
7602 SCDynamicStoreRef store = NULL;
7603 CFDictionaryRef connd = NULL;
7604 CFDictionaryRef BTMMDict = NULL;
7605
7606 store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:CopyConnectivityBackToMyMacDict"), NULL, NULL);
7607 if (!store)
7608 {
7609 LogMsg("CopyConnectivityBackToMyMacDict: SCDynamicStoreCreate failed: %s", SCErrorString(SCError()));
7610 goto end;
7611 }
7612
7613 connd = SCDynamicStoreCopyValue(store, NetworkChangedKey_BTMMConnectivity);
7614 if (!connd)
7615 {
7616 LogInfo("CopyConnectivityBackToMyMacDict: SCDynamicStoreCopyValue failed: %s", SCErrorString(SCError()));
7617 goto end;
7618 }
7619
7620 BTMMDict = CFDictionaryGetValue(connd, CFSTR("BackToMyMac"));
7621 if (!BTMMDict)
7622 {
7623 LogInfo("CopyConnectivityBackToMyMacDict: CFDictionaryGetValue: No value for BackToMyMac");
7624 goto end;
7625 }
7626
7627 // Non-dictionary is treated as non-existent dictionary
7628 if (CFGetTypeID(BTMMDict) != CFDictionaryGetTypeID())
7629 {
7630 BTMMDict = NULL;
7631 LogMsg("CopyConnectivityBackToMyMacDict: BackToMyMac not a dictionary");
7632 goto end;
7633 }
7634
7635 CFRetain(BTMMDict);
7636
7637 end:
7638 if (connd) CFRelease(connd);
7639 if (store) CFRelease(store);
7640
7641 return BTMMDict;
7642 }
7643
7644 #define MAX_IPV6_TEXTUAL 40
7645
7646 mDNSlocal mDNSv6Addr ParseBackToMyMacAddr(CFDictionaryRef BTMMDict, CFStringRef ifKey, CFStringRef addrKey)
7647 {
7648 mDNSv6Addr retVal = zerov6Addr;
7649 CFTypeRef string = NULL;
7650 char ifname[IFNAMSIZ];
7651 char address[MAX_IPV6_TEXTUAL];
7652
7653 if (!BTMMDict)
7654 return zerov6Addr;
7655
7656 if (!CFDictionaryGetValueIfPresent(BTMMDict, ifKey, &string))
7657 {
7658 LogInfo("ParseBackToMyMacAddr: interface key does not exist");
7659 return zerov6Addr;
7660 }
7661
7662 if (!CFStringGetCString(string, ifname, IFNAMSIZ, kCFStringEncodingUTF8))
7663 {
7664 LogMsg("ParseBackToMyMacAddr: Could not convert interface to CString");
7665 return zerov6Addr;
7666 }
7667
7668 if (!CFDictionaryGetValueIfPresent(BTMMDict, addrKey, &string))
7669 {
7670 LogMsg("ParseBackToMyMacAddr: address key does not exist, but interface key does");
7671 return zerov6Addr;
7672 }
7673
7674 if (!CFStringGetCString(string, address, sizeof(address), kCFStringEncodingUTF8))
7675 {
7676 LogMsg("ParseBackToMyMacAddr: Could not convert address to CString");
7677 return zerov6Addr;
7678 }
7679
7680 retVal = IPv6AddressFromString(address);
7681 LogInfo("ParseBackToMyMacAddr: %s (%s) %.16a", ifname, address, &retVal);
7682
7683 if (mDNSIPv6AddressIsZero(retVal))
7684 return zerov6Addr;
7685
7686 if (!IPv6AddressIsOnInterface(retVal, ifname))
7687 {
7688 LogMsg("ParseBackToMyMacAddr: %.16a is not on %s", &retVal, ifname);
7689 return zerov6Addr;
7690 }
7691
7692 return retVal;
7693 }
7694
7695 mDNSlocal CFDictionaryRef GetBackToMyMacZones(CFDictionaryRef BTMMDict)
7696 {
7697 CFTypeRef zones = NULL;
7698
7699 if (!BTMMDict)
7700 return NULL;
7701
7702 if (!CFDictionaryGetValueIfPresent(BTMMDict, CFSTR("Zones"), &zones))
7703 {
7704 LogInfo("CopyBTMMZones: Zones key does not exist");
7705 return NULL;
7706 }
7707
7708 return zones;
7709 }
7710
7711 mDNSlocal mDNSv6Addr ParseBackToMyMacZone(CFDictionaryRef zones, DomainAuthInfo* info)
7712 {
7713 mDNSv6Addr addr = zerov6Addr;
7714 char buffer[MAX_ESCAPED_DOMAIN_NAME];
7715 CFStringRef domain = NULL;
7716 CFTypeRef theZone = NULL;
7717
7718 if (!zones)
7719 return addr;
7720
7721 ConvertDomainNameToCString(&info->domain, buffer);
7722 domain = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
7723 if (!domain)
7724 return addr;
7725
7726 if (CFDictionaryGetValueIfPresent(zones, domain, &theZone))
7727 addr = ParseBackToMyMacAddr(theZone, CFSTR("Interface"), CFSTR("Address"));
7728
7729 CFRelease(domain);
7730
7731 return addr;
7732 }
7733
7734 mDNSlocal void SetupBackToMyMacInnerAddresses(mDNS *const m, CFDictionaryRef BTMMDict)
7735 {
7736 DomainAuthInfo* info;
7737 CFDictionaryRef zones = GetBackToMyMacZones(BTMMDict);
7738 mDNSv6Addr newAddr;
7739
7740 for (info = m->AuthInfoList; info; info = info->next)
7741 {
7742 if (!info->AutoTunnel)
7743 continue;
7744
7745 newAddr = ParseBackToMyMacZone(zones, info);
7746
7747 if (mDNSSameIPv6Address(newAddr, info->AutoTunnelInnerAddress))
7748 continue;
7749
7750 info->AutoTunnelInnerAddress = newAddr;
7751 DeregisterAutoTunnelHostRecord(m, info);
7752 UpdateAutoTunnelHostRecord(m, info);
7753 UpdateAutoTunnelDomainStatus(m, info);
7754 }
7755 }
7756
7757 // MUST be called holding the lock
7758 mDNSlocal void ProcessConndConfigChanges(mDNS *const m)
7759 {
7760 CFDictionaryRef dict = CopyConnectivityBackToMyMacDict();
7761 if (!dict)
7762 LogInfo("ProcessConndConfigChanges: No BTMM dictionary");
7763 mDNSv6Addr relayAddr = ParseBackToMyMacAddr(dict, CFSTR("RelayInterface"), CFSTR("RelayAddress"));
7764
7765 LogInfo("ProcessConndConfigChanges: relay %.16a", &relayAddr);
7766
7767 SetupBackToMyMacInnerAddresses(m, dict);
7768
7769 if (dict) CFRelease(dict);
7770
7771 if (!mDNSSameIPv6Address(relayAddr, m->AutoTunnelRelayAddr))
7772 {
7773 m->AutoTunnelRelayAddr = relayAddr;
7774
7775 DomainAuthInfo* info;
7776 for (info = m->AuthInfoList; info; info = info->next)
7777 if (info->AutoTunnel)
7778 {
7779 DeregisterAutoTunnel6Record(m, info);
7780 UpdateAutoTunnel6Record(m, info);
7781 UpdateAutoTunnelDomainStatus(m, info);
7782 }
7783
7784 // Determine whether we need racoon to accept incoming connections
7785 UpdateAnonymousRacoonConfig(m);
7786 }
7787
7788 // If awacsd crashes or exits for some reason, restart it
7789 UpdateBTMMRelayConnection(m);
7790 }
7791 #endif /* APPLE_OSX_mDNSResponder */
7792
7793 mDNSlocal mDNSBool IsAppleNetwork(mDNS *const m)
7794 {
7795 DNSServer *s;
7796 // Determine if we're on AppleNW based on DNSServer having 17.x.y.z IPv4 addr
7797 for (s = m->DNSServers; s; s = s->next)
7798 {
7799 if (s->addr.ip.v4.b[0] == 17)
7800 {
7801 LogInfo("IsAppleNetwork: Found 17.x.y.z DNSServer concluding that we are on AppleNW: %##s %#a", s->domain.c, &s->addr);
7802 return mDNStrue;
7803 }
7804 }
7805 return mDNSfalse;
7806 }
7807
7808 mDNSexport void mDNSMacOSXNetworkChanged(mDNS *const m)
7809 {
7810 LogInfo("*** Network Configuration Change *** (%d)%s",
7811 m->p->NetworkChanged ? mDNS_TimeNow(m) - m->p->NetworkChanged : 0,
7812 m->p->NetworkChanged ? "" : " (no scheduled configuration change)");
7813 m->p->NetworkChanged = 0; // If we received a network change event and deferred processing, we're now dealing with it
7814 mDNSs32 utc = mDNSPlatformUTC();
7815 m->SystemWakeOnLANEnabled = SystemWakeForNetworkAccess();
7816 m->SystemSleepOnlyIfWakeOnLAN = SystemSleepOnlyIfWakeOnLAN();
7817 MarkAllInterfacesInactive(m, utc);
7818 UpdateInterfaceList(m, utc);
7819 ClearInactiveInterfaces(m, utc);
7820 SetupActiveInterfaces(m, utc);
7821
7822 #if APPLE_OSX_mDNSResponder
7823
7824 mDNS_Lock(m);
7825 ProcessConndConfigChanges(m);
7826 mDNS_Unlock(m);
7827
7828 // Scan to find client tunnels whose questions have completed,
7829 // but whose local inner/outer addresses have changed since the tunnel was set up
7830 ClientTunnel *p;
7831 for (p = m->TunnelClients; p; p = p->next)
7832 if (p->q.ThisQInterval < 0)
7833 {
7834 DomainAuthInfo* info = GetAuthInfoForName(m, &p->dstname);
7835 if (!info)
7836 {
7837 LogMsg("mDNSMacOSXNetworkChanged: Could not get AuthInfo for %##s, removing tunnel keys", p->dstname.c);
7838 AutoTunnelSetKeys(p, mDNSfalse);
7839 }
7840 else
7841 {
7842 mDNSv6Addr inner = info->AutoTunnelInnerAddress;
7843
7844 if (!mDNSIPPortIsZero(p->rmt_outer_port))
7845 {
7846 mDNSAddr tmpSrc = zeroAddr;
7847 mDNSAddr tmpDst = { mDNSAddrType_IPv4, {{{0}}} };
7848 tmpDst.ip.v4 = p->rmt_outer;
7849 mDNSPlatformSourceAddrForDest(&tmpSrc, &tmpDst);
7850 if (!mDNSSameIPv6Address(p->loc_inner, inner) ||
7851 !mDNSSameIPv4Address(p->loc_outer, tmpSrc.ip.v4))
7852 {
7853 AutoTunnelSetKeys(p, mDNSfalse);
7854 p->loc_inner = inner;
7855 p->loc_outer = tmpSrc.ip.v4;
7856 AutoTunnelSetKeys(p, mDNStrue);
7857 }
7858 }
7859 else
7860 {
7861 if (!mDNSSameIPv6Address(p->loc_inner, inner) ||
7862 !mDNSSameIPv6Address(p->loc_outer6, m->AutoTunnelRelayAddr))
7863 {
7864 AutoTunnelSetKeys(p, mDNSfalse);
7865 p->loc_inner = inner;
7866 p->loc_outer6 = m->AutoTunnelRelayAddr;
7867 AutoTunnelSetKeys(p, mDNStrue);
7868 }
7869 }
7870 }
7871 }
7872
7873 SetSPS(m);
7874
7875 NetworkInterfaceInfoOSX *i;
7876 for (i = m->p->InterfaceList; i; i = i->next)
7877 {
7878 if (!m->SPSSocket) // Not being Sleep Proxy Server; close any open BPF fds
7879 {
7880 if (i->BPF_fd >= 0 && CountProxyTargets(m, i, mDNSNULL, mDNSNULL) == 0) CloseBPF(i);
7881 }
7882 else // else, we're Sleep Proxy Server; open BPF fds
7883 {
7884 if (i->Exists && i->Registered == i && i->ifinfo.McastTxRx && !(i->ifa_flags & IFF_LOOPBACK) && i->BPF_fd == -1)
7885 { LogSPS("%s requesting BPF", i->ifinfo.ifname); i->BPF_fd = -2; mDNSRequestBPF(); }
7886 }
7887 }
7888
7889 #endif // APPLE_OSX_mDNSResponder
7890
7891 uDNS_SetupDNSConfig(m);
7892 mDNS_ConfigChanged(m);
7893
7894 if (IsAppleNetwork(m) != mDNS_McastTracingEnabled)
7895 {
7896 mDNS_McastTracingEnabled = mDNS_McastTracingEnabled ? mDNSfalse : mDNStrue;
7897 LogMsg("mDNSMacOSXNetworkChanged: Multicast Tracing %s", mDNS_McastTracingEnabled ? "Enabled" : "Disabled");
7898 UpdateDebugState();
7899 }
7900
7901 }
7902
7903 // Called with KQueueLock & mDNS lock
7904 mDNSlocal void SetNetworkChanged(mDNS *const m, mDNSs32 delay)
7905 {
7906 if (!m->p->NetworkChanged || m->p->NetworkChanged - NonZeroTime(m->timenow + delay) < 0)
7907 {
7908 m->p->NetworkChanged = NonZeroTime(m->timenow + delay);
7909 LogInfo("SetNetworkChanged: scheduling in %d msec", delay);
7910 }
7911 }
7912
7913 // Called with KQueueLock & mDNS lock
7914 mDNSlocal void SetKeyChainTimer(mDNS *const m, mDNSs32 delay)
7915 {
7916 // If it's not set or it needs to happen sooner than when it's currently set
7917 if (!m->p->KeyChainTimer || m->p->KeyChainTimer - NonZeroTime(m->timenow + delay) > 0)
7918 {
7919 m->p->KeyChainTimer = NonZeroTime(m->timenow + delay);
7920 LogInfo("SetKeyChainTimer: %d", delay);
7921 }
7922 }
7923
7924 // Copy the fourth slash-delimited element from either:
7925 // State:/Network/Interface/<bsdname>/IPv4
7926 // or
7927 // Setup:/Network/Service/<servicename>/Interface
7928 mDNSlocal CFStringRef CopyNameFromKey(CFStringRef key)
7929 {
7930 CFArrayRef a;
7931 CFStringRef name = NULL;
7932
7933 a = CFStringCreateArrayBySeparatingStrings(NULL, key, CFSTR("/"));
7934 if (a && CFArrayGetCount(a) == 5) name = CFRetain(CFArrayGetValueAtIndex(a, 3));
7935 if (a != NULL) CFRelease(a);
7936
7937 return name;
7938 }
7939
7940 // Whether a key from a network change notification corresponds to
7941 // an IP service that is explicitly configured for IPv4 Link Local
7942 mDNSlocal mDNSBool ChangedKeysHaveIPv4LL(CFArrayRef inkeys)
7943 {
7944 SCDynamicStoreRef store = NULL;
7945 CFDictionaryRef dict = NULL;
7946 CFMutableArrayRef a;
7947 const void **keys = NULL, **vals = NULL;
7948 CFStringRef pattern = NULL;
7949 int i, ic, j, jc;
7950 mDNSBool found = mDNSfalse;
7951
7952 jc = CFArrayGetCount(inkeys);
7953 if (!jc) goto done;
7954
7955 store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:ChangedKeysHaveIPv4LL"), NULL, NULL);
7956 if (store == NULL) goto done;
7957
7958 a = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
7959 if (a == NULL) goto done;
7960
7961 // Setup:/Network/Service/[^/]+/Interface
7962 pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, kSCCompAnyRegex, kSCEntNetInterface);
7963 if (pattern == NULL) goto done;
7964 CFArrayAppendValue(a, pattern);
7965 CFRelease(pattern);
7966
7967 // Setup:/Network/Service/[^/]+/IPv4
7968 pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, kSCCompAnyRegex, kSCEntNetIPv4);
7969 if (pattern == NULL) goto done;
7970 CFArrayAppendValue(a, pattern);
7971 CFRelease(pattern);
7972
7973 dict = SCDynamicStoreCopyMultiple(store, NULL, a);
7974 CFRelease(a);
7975
7976 if (!dict)
7977 {
7978 LogMsg("ChangedKeysHaveIPv4LL: Empty dictionary");
7979 goto done;
7980 }
7981
7982 ic = CFDictionaryGetCount(dict);
7983 vals = mDNSPlatformMemAllocate(sizeof (void *) * ic);
7984 keys = mDNSPlatformMemAllocate(sizeof (void *) * ic);
7985 CFDictionaryGetKeysAndValues(dict, keys, vals);
7986
7987 for (j = 0; j < jc && !found; j++)
7988 {
7989 CFStringRef key = CFArrayGetValueAtIndex(inkeys, j);
7990 CFStringRef ifname = NULL;
7991
7992 char buf[256];
7993
7994 // It would be nice to use a regex here
7995 if (!CFStringHasPrefix(key, CFSTR("State:/Network/Interface/")) || !CFStringHasSuffix(key, kSCEntNetIPv4)) continue;
7996
7997 if ((ifname = CopyNameFromKey(key)) == NULL) continue;
7998 if (mDNS_LoggingEnabled)
7999 {
8000 if (!CFStringGetCString(ifname, buf, sizeof(buf), kCFStringEncodingUTF8)) buf[0] = 0;
8001 LogInfo("ChangedKeysHaveIPv4LL: potential ifname %s", buf);
8002 }
8003
8004 for (i = 0; i < ic; i++)
8005 {
8006 CFDictionaryRef ipv4dict;
8007 CFStringRef name;
8008 CFStringRef serviceid;
8009 CFStringRef configmethod;
8010
8011 if (!CFStringHasSuffix(keys[i], kSCEntNetInterface)) continue;
8012
8013 if (CFDictionaryGetTypeID() != CFGetTypeID(vals[i])) continue;
8014
8015 if ((name = CFDictionaryGetValue(vals[i], kSCPropNetInterfaceDeviceName)) == NULL) continue;
8016
8017 if (!CFEqual(ifname, name)) continue;
8018
8019 if ((serviceid = CopyNameFromKey(keys[i])) == NULL) continue;
8020 if (mDNS_LoggingEnabled)
8021 {
8022 if (!CFStringGetCString(serviceid, buf, sizeof(buf), kCFStringEncodingUTF8)) buf[0] = 0;
8023 LogInfo("ChangedKeysHaveIPv4LL: found serviceid %s", buf);
8024 }
8025
8026 pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainSetup, serviceid, kSCEntNetIPv4);
8027 CFRelease(serviceid);
8028 if (pattern == NULL) continue;
8029
8030 ipv4dict = CFDictionaryGetValue(dict, pattern);
8031 CFRelease(pattern);
8032 if (!ipv4dict || CFDictionaryGetTypeID() != CFGetTypeID(ipv4dict)) continue;
8033
8034 configmethod = CFDictionaryGetValue(ipv4dict, kSCPropNetIPv4ConfigMethod);
8035 if (!configmethod) continue;
8036
8037 if (mDNS_LoggingEnabled)
8038 {
8039 if (!CFStringGetCString(configmethod, buf, sizeof(buf), kCFStringEncodingUTF8)) buf[0] = 0;
8040 LogInfo("ChangedKeysHaveIPv4LL: configmethod %s", buf);
8041 }
8042
8043 if (CFEqual(configmethod, kSCValNetIPv4ConfigMethodLinkLocal)) { found = mDNStrue; break; }
8044 }
8045
8046 CFRelease(ifname);
8047 }
8048
8049 done:
8050 if (vals != NULL) mDNSPlatformMemFree(vals);
8051 if (keys != NULL) mDNSPlatformMemFree(keys);
8052 if (dict != NULL) CFRelease(dict);
8053 if (store != NULL) CFRelease(store);
8054
8055 return found;
8056 }
8057
8058 mDNSlocal void NetworkChanged(SCDynamicStoreRef store, CFArrayRef changedKeys, void *context)
8059 {
8060 (void)store; // Parameter not used
8061 mDNSBool changeNow = mDNSfalse;
8062 mDNS *const m = (mDNS *const)context;
8063 KQueueLock(m);
8064 mDNS_Lock(m);
8065
8066 mDNSs32 delay = mDNSPlatformOneSecond * 2; // Start off assuming a two-second delay
8067
8068 int c = CFArrayGetCount(changedKeys); // Count changes
8069 CFRange range = { 0, c };
8070 int c1 = (CFArrayContainsValue(changedKeys, range, NetworkChangedKey_Hostnames ) != 0);
8071 int c2 = (CFArrayContainsValue(changedKeys, range, NetworkChangedKey_Computername) != 0);
8072 int c3 = (CFArrayContainsValue(changedKeys, range, NetworkChangedKey_DynamicDNS ) != 0);
8073 int c4 = (CFArrayContainsValue(changedKeys, range, NetworkChangedKey_DNS ) != 0);
8074 if (c && c - c1 - c2 - c3 - c4 == 0)
8075 delay = mDNSPlatformOneSecond/10; // If these were the only changes, shorten delay
8076
8077 // Do immediate network changed processing for "p2p*" interfaces and
8078 // for interfaces with the IFEF_DIRECTLINK flag set.
8079 {
8080 CFArrayRef labels;
8081 CFIndex n;
8082 for (int i = 0; i < c; i++)
8083 {
8084 CFStringRef key = CFArrayGetValueAtIndex(changedKeys, i);
8085
8086 // Only look at keys with prefix "State:/Network/Interface/"
8087 if (!CFStringHasPrefix(key, NetworkChangedKey_StateInterfacePrefix))
8088 continue;
8089
8090 // And suffix "IPv6" or "IPv4".
8091 if (!CFStringHasSuffix(key, kSCEntNetIPv6) && !CFStringHasSuffix(key, kSCEntNetIPv4))
8092 continue;
8093
8094 labels = CFStringCreateArrayBySeparatingStrings(NULL, key, CFSTR("/"));
8095 if (labels == NULL)
8096 break;
8097 n = CFArrayGetCount(labels);
8098
8099 // Interface changes will have keys of the form:
8100 // State:/Network/Interface/<interfaceName>/IPv6
8101 // Thus five '/' seperated fields, the 4th one being the <interfaceName> string.
8102 if (n == 5)
8103 {
8104 char buf[256];
8105
8106 // The 4th label (index = 3) should be the interface name.
8107 if (CFStringGetCString(CFArrayGetValueAtIndex(labels, 3), buf, sizeof(buf), kCFStringEncodingUTF8)
8108 && (strstr(buf, "p2p") || (getExtendedFlags(buf) & IFEF_DIRECTLINK)))
8109 {
8110 LogInfo("NetworkChanged: interface %s, not delaying network change", buf);
8111 changeNow = mDNStrue;
8112 CFRelease(labels);
8113 break;
8114 }
8115 }
8116 CFRelease(labels);
8117 }
8118 }
8119
8120 mDNSBool btmmChanged = CFArrayContainsValue(changedKeys, range, NetworkChangedKey_BackToMyMac);
8121 if (btmmChanged) delay = 0;
8122
8123 if (mDNS_LoggingEnabled)
8124 {
8125 int i;
8126 for (i=0; i<c; i++)
8127 {
8128 char buf[256];
8129 if (!CFStringGetCString(CFArrayGetValueAtIndex(changedKeys, i), buf, sizeof(buf), kCFStringEncodingUTF8)) buf[0] = 0;
8130 LogInfo("*** NetworkChanged SC key: %s", buf);
8131 }
8132 LogInfo("*** NetworkChanged *** %d change%s %s%s%s%sdelay %d",
8133 c, c>1 ? "s" : "",
8134 c1 ? "(Local Hostname) " : "",
8135 c2 ? "(Computer Name) " : "",
8136 c3 ? "(DynamicDNS) " : "",
8137 c4 ? "(DNS) " : "",
8138 changeNow ? 0 : delay);
8139 }
8140
8141 if (!changeNow)
8142 SetNetworkChanged(m, delay);
8143
8144 // Other software might pick up these changes to register or browse in WAB or BTMM domains,
8145 // so in order for secure updates to be made to the server, make sure to read the keychain and
8146 // setup the DomainAuthInfo before handing the network change.
8147 // If we don't, then we will first try to register services in the clear, then later setup the
8148 // DomainAuthInfo, which is incorrect.
8149 if (c3 || btmmChanged)
8150 SetKeyChainTimer(m, delay);
8151
8152 mDNS_Unlock(m);
8153
8154 // If DNS settings changed, immediately force a reconfig (esp. cache flush)
8155 // Similarly, if an interface changed that is explicitly IPv4 link local, immediately force a reconfig
8156 if (c4 || ChangedKeysHaveIPv4LL(changedKeys) || changeNow) mDNSMacOSXNetworkChanged(m);
8157
8158 KQueueUnlock(m, "NetworkChanged");
8159 }
8160
8161 #if APPLE_OSX_mDNSResponder
8162 mDNSlocal void RefreshSPSStatus(const void *key, const void *value, void *context)
8163 {
8164 (void)context;
8165 char buf[IFNAMSIZ];
8166
8167 CFStringRef ifnameStr = (CFStringRef)key;
8168 CFArrayRef array = (CFArrayRef)value;
8169 if (!CFStringGetCString(ifnameStr, buf, sizeof(buf), kCFStringEncodingUTF8))
8170 buf[0] = 0;
8171
8172 LogInfo("RefreshSPSStatus: Updating SPS state for key %s, array count %d", buf, CFArrayGetCount(array));
8173 mDNSDynamicStoreSetConfig(kmDNSSleepProxyServersState, buf, value);
8174 }
8175 #endif
8176
8177 mDNSlocal void DynamicStoreReconnected(SCDynamicStoreRef store, void *info)
8178 {
8179 mDNS *const m = (mDNS *const)info;
8180 (void)store;
8181
8182 LogInfo("DynamicStoreReconnected: Reconnected");
8183
8184 // State:/Network/MulticastDNS
8185 SetLocalDomains();
8186
8187 // State:/Network/DynamicDNS
8188 if (m->FQDN.c[0])
8189 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
8190
8191 // Note: PrivateDNS and BackToMyMac are automatically populated when configd is restarted
8192 // as we receive network change notifications and thus not necessary. But we leave it here
8193 // so that if things are done differently in the future, this code still works.
8194
8195 // State:/Network/PrivateDNS
8196 if (privateDnsArray)
8197 mDNSDynamicStoreSetConfig(kmDNSPrivateConfig, mDNSNULL, privateDnsArray);
8198
8199 #if APPLE_OSX_mDNSResponder
8200 mDNS_Lock(m);
8201 // State:/Network/BackToMyMac
8202 UpdateAutoTunnelDomainStatuses(m);
8203 mDNS_Unlock(m);
8204
8205 // State:/Network/Interface/en0/SleepProxyServers
8206 if (spsStatusDict)
8207 CFDictionaryApplyFunction(spsStatusDict, RefreshSPSStatus, NULL);
8208 #endif
8209 }
8210
8211 mDNSlocal mStatus WatchForNetworkChanges(mDNS *const m)
8212 {
8213 mStatus err = -1;
8214 SCDynamicStoreContext context = { 0, m, NULL, NULL, NULL };
8215 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder:WatchForNetworkChanges"), NetworkChanged, &context);
8216 CFMutableArrayRef keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
8217 CFStringRef pattern1 = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4);
8218 CFStringRef pattern2 = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv6);
8219 CFMutableArrayRef patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
8220
8221 if (!store) { LogMsg("SCDynamicStoreCreate failed: %s", SCErrorString(SCError())); goto error; }
8222 if (!keys || !pattern1 || !pattern2 || !patterns) goto error;
8223
8224 CFArrayAppendValue(keys, NetworkChangedKey_IPv4);
8225 CFArrayAppendValue(keys, NetworkChangedKey_IPv6);
8226 CFArrayAppendValue(keys, NetworkChangedKey_Hostnames);
8227 CFArrayAppendValue(keys, NetworkChangedKey_Computername);
8228 CFArrayAppendValue(keys, NetworkChangedKey_DNS);
8229 CFArrayAppendValue(keys, NetworkChangedKey_DynamicDNS);
8230 CFArrayAppendValue(keys, NetworkChangedKey_BackToMyMac);
8231 CFArrayAppendValue(keys, NetworkChangedKey_PowerSettings); // should remove as part of <rdar://problem/6751656>
8232 CFArrayAppendValue(keys, NetworkChangedKey_BTMMConnectivity);
8233 CFArrayAppendValue(patterns, pattern1);
8234 CFArrayAppendValue(patterns, pattern2);
8235 CFArrayAppendValue(patterns, CFSTR("State:/Network/Interface/[^/]+/AirPort"));
8236 if (!SCDynamicStoreSetNotificationKeys(store, keys, patterns))
8237 { LogMsg("SCDynamicStoreSetNotificationKeys failed: %s", SCErrorString(SCError())); goto error; }
8238
8239 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
8240 if (!SCDynamicStoreSetDispatchQueue(store, dispatch_get_main_queue()))
8241 { LogMsg("SCDynamicStoreCreateRunLoopSource failed: %s", SCErrorString(SCError())); goto error; }
8242 #else
8243 m->p->StoreRLS = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
8244 if (!m->p->StoreRLS) { LogMsg("SCDynamicStoreCreateRunLoopSource failed: %s", SCErrorString(SCError())); goto error; }
8245 CFRunLoopAddSource(CFRunLoopGetCurrent(), m->p->StoreRLS, kCFRunLoopDefaultMode);
8246 #endif
8247 SCDynamicStoreSetDisconnectCallBack(store, DynamicStoreReconnected);
8248 m->p->Store = store;
8249 err = 0;
8250 goto exit;
8251
8252 error:
8253 if (store) CFRelease(store);
8254
8255 exit:
8256 if (patterns) CFRelease(patterns);
8257 if (pattern2) CFRelease(pattern2);
8258 if (pattern1) CFRelease(pattern1);
8259 if (keys) CFRelease(keys);
8260
8261 return(err);
8262 }
8263
8264 #if 0 // <rdar://problem/6751656>
8265 mDNSlocal void PMChanged(void *context)
8266 {
8267 mDNS *const m = (mDNS *const)context;
8268
8269 KQueueLock(m);
8270 mDNS_Lock(m);
8271
8272 LogSPS("PMChanged");
8273
8274 SetNetworkChanged(m, mDNSPlatformOneSecond * 2);
8275
8276 mDNS_Unlock(m);
8277 KQueueUnlock(m, "PMChanged");
8278 }
8279
8280 mDNSlocal mStatus WatchForPMChanges(mDNS *const m)
8281 {
8282 m->p->PMRLS = IOPMPrefsNotificationCreateRunLoopSource(PMChanged, m);
8283 if (!m->p->PMRLS) { LogMsg("IOPMPrefsNotificationCreateRunLoopSource failed!"); return mStatus_UnknownErr; }
8284
8285 CFRunLoopAddSource(CFRunLoopGetCurrent(), m->p->PMRLS, kCFRunLoopDefaultMode);
8286
8287 return mStatus_NoError;
8288 }
8289 #endif
8290
8291 #if !TARGET_OS_EMBEDDED // don't setup packet filter rules on embedded
8292
8293 mDNSlocal void mDNSSetPacketFilterRules(mDNS *const m, char * ifname, const ResourceRecord *const excludeRecord)
8294 {
8295 AuthRecord *rr;
8296 pfArray_t portArray;
8297 pfArray_t protocolArray;
8298 uint32_t count = 0;
8299
8300 for (rr = m->ResourceRecords; rr; rr=rr->next)
8301 {
8302 if ((rr->resrec.rrtype == kDNSServiceType_SRV)
8303 && ((rr->ARType == AuthRecordAnyIncludeP2P) || (rr->ARType == AuthRecordAnyIncludeAWDLandP2P)))
8304 {
8305 const mDNSu8 *p;
8306
8307 if (count >= PFPortArraySize)
8308 {
8309 LogMsg("mDNSSetPacketFilterRules: %d service limit, skipping %s", PFPortArraySize, ARDisplayString(m, rr));
8310 continue;
8311 }
8312
8313 if (excludeRecord && IdenticalResourceRecord(&rr->resrec, excludeRecord))
8314 {
8315 LogInfo("mDNSSetPacketFilterRules: record being removed, skipping %s", ARDisplayString(m, rr));
8316 continue;
8317 }
8318
8319 LogInfo("mDNSSetPacketFilterRules: found %s", ARDisplayString(m, rr));
8320
8321 portArray[count] = rr->resrec.rdata->u.srv.port.NotAnInteger;
8322
8323 // Assume <Service Instance>.<App Protocol>.<Transport Protocol>.<Name>
8324 p = rr->resrec.name->c;
8325
8326 // Skip to App Protocol
8327 if (p[0]) p += 1 + p[0];
8328
8329 // Skip to Transport Protocol
8330 if (p[0]) p += 1 + p[0];
8331
8332 if (SameDomainLabel(p, (mDNSu8 *)"\x4" "_tcp")) protocolArray[count] = IPPROTO_TCP;
8333 else if (SameDomainLabel(p, (mDNSu8 *)"\x4" "_udp")) protocolArray[count] = IPPROTO_UDP;
8334 else
8335 {
8336 LogMsg("mDNSSetPacketFilterRules: could not determine transport protocol of service");
8337 LogMsg("mDNSSetPacketFilterRules: %s", ARDisplayString(m, rr));
8338 return;
8339 }
8340 count++;
8341 }
8342 }
8343 mDNSPacketFilterControl(PF_SET_RULES, ifname, count, portArray, protocolArray);
8344 }
8345
8346 // If the p2p interface already exists, update the Bonjour packet filter rules for it.
8347 mDNSexport void mDNSUpdatePacketFilter(const ResourceRecord *const excludeRecord)
8348 {
8349 mDNS *const m = &mDNSStorage;
8350
8351 NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
8352 while (intf)
8353 {
8354 if (strncmp(intf->ifname, "p2p", 3) == 0)
8355 {
8356 LogInfo("mDNSInitPacketFilter: Setting rules for ifname %s", intf->ifname);
8357 mDNSSetPacketFilterRules(m, intf->ifname, excludeRecord);
8358 break;
8359 }
8360 intf = GetFirstActiveInterface(intf->next);
8361 }
8362 }
8363
8364 #else // !TARGET_OS_EMBEDDED
8365
8366 // Currently no packet filter setup required on embedded platforms.
8367 mDNSexport void mDNSUpdatePacketFilter(const ResourceRecord *const excludeRecord)
8368 {
8369 (void) excludeRecord; // unused
8370 }
8371
8372 #endif // !TARGET_OS_EMBEDDED
8373
8374 // Handle AWDL KEV_DL_MASTER_ELECTED event by restarting queries and advertisements
8375 // marked to include the AWDL interface.
8376 mDNSlocal void newMasterElected(mDNS *const m, struct net_event_data * ptr)
8377 {
8378 char ifname[IFNAMSIZ];
8379 mDNSu32 interfaceIndex;
8380 DNSQuestion *q;
8381 AuthRecord *rr;
8382 NetworkInterfaceInfoOSX *infoOSX;
8383 mDNSInterfaceID InterfaceID;
8384
8385 snprintf(ifname, IFNAMSIZ, "%s%d", ptr->if_name, ptr->if_unit);
8386 interfaceIndex = if_nametoindex(ifname);
8387
8388 if (!interfaceIndex)
8389 {
8390 LogMsg("newMasterElected: if_nametoindex(%s) failed", ifname);
8391 return;
8392 }
8393
8394 LogInfo("newMasterElected: ifname = %s, interfaceIndex = %d", ifname, interfaceIndex);
8395 infoOSX = IfindexToInterfaceInfoOSX(m, (mDNSInterfaceID)(uintptr_t)interfaceIndex);
8396
8397 // Can get an KEV_DL_MASTER_ELECTED event prior to the interface existing
8398 // when it is first brought up.
8399 if (!infoOSX)
8400 {
8401 LogInfo("newMasterElected: interface not yet active");
8402 return;
8403 }
8404 InterfaceID = infoOSX->ifinfo.InterfaceID;
8405
8406 for (q = m->Questions; q; q=q->next)
8407 {
8408 if ((!q->InterfaceID && (q->flags & kDNSServiceFlagsIncludeAWDL))
8409 || q->InterfaceID == InterfaceID)
8410 {
8411 LogInfo("newMasterElected: restarting %s query for %##s", DNSTypeName(q->qtype), q->qname.c);
8412 mDNSCoreRestartQuestion(m, q);
8413 }
8414 }
8415
8416 for (rr = m->ResourceRecords; rr; rr=rr->next)
8417 {
8418 if ((!rr->resrec.InterfaceID
8419 && ((rr->ARType == AuthRecordAnyIncludeAWDL) || ((rr->ARType == AuthRecordAnyIncludeAWDLandP2P))))
8420 || rr->resrec.InterfaceID == InterfaceID)
8421 {
8422 LogInfo("newMasterElected: restarting %s announcements for %##s", DNSTypeName(rr->resrec.rrtype), rr->namestorage.c);
8423 mDNSCoreRestartRegistration(m, rr, -1);
8424 }
8425 }
8426 }
8427
8428 // An ssth array of all zeroes indicates the peer has no services registered.
8429 mDNSlocal mDNSBool allZeroSSTH(struct opaque_presence_indication *op)
8430 {
8431 int i;
8432 int *intp = (int *) op->ssth;
8433
8434 // MAX_SSTH_SIZE should always be a multiple of sizeof(int), if
8435 // it's not, print an error message and return false so that
8436 // corresponding peer records are not flushed when KEV_DL_NODE_PRESENCE event
8437 // is received.
8438 if (MAX_SSTH_SIZE % sizeof(int))
8439 {
8440 LogInfo("allZeroSSTH: MAX_SSTH_SIZE = %d not a multiple of sizeof(int)", MAX_SSTH_SIZE);
8441 return mDNSfalse;
8442 }
8443
8444 for (i = 0; i < (int)(MAX_SSTH_SIZE / sizeof(int)); i++, intp++)
8445 {
8446 if (*intp)
8447 return mDNSfalse;
8448 }
8449 return mDNStrue;
8450 }
8451
8452 // mDNS_Reconfirm_internal() adds 33% to this interval, so the records should
8453 // be removed in 4 seconds.
8454 #define kAWDLReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 3)
8455
8456 // Mark records from this peer for deletion from the cache.
8457 mDNSlocal void removeCachedPeerRecords(mDNS *const m, mDNSu32 ifindex, mDNSAddr *ap)
8458 {
8459 mDNSu32 slot;
8460 CacheGroup *cg;
8461 CacheRecord *cr;
8462 mDNSInterfaceID InterfaceID = mDNSPlatformInterfaceIDfromInterfaceIndex(m, ifindex);
8463
8464 if (!InterfaceID)
8465 {
8466 LogInfo("removeCachedPeerRecords: Invalid ifindex: %d", ifindex);
8467 return;
8468 }
8469
8470 FORALL_CACHERECORDS(slot, cg, cr)
8471 {
8472 if ((InterfaceID == cr->resrec.InterfaceID) && mDNSSameAddress(ap, & cr->sourceAddress))
8473 {
8474 LogInfo("removeCachedPeerRecords: %s %##s marking for deletion",
8475 DNSTypeName(cr->resrec.rrtype), cr->resrec.name->c);
8476 mDNS_Reconfirm_internal(m, cr, kAWDLReconfirmTime);
8477 }
8478 }
8479 }
8480
8481 // Handle KEV_DL_NODE_PRESENCE event.
8482 mDNSlocal void nodePresence(mDNS *const m, struct kev_dl_node_presence * p)
8483 {
8484 char buf[INET6_ADDRSTRLEN];
8485 struct opaque_presence_indication *op = (struct opaque_presence_indication *) p->node_service_info;
8486
8487 if (inet_ntop(AF_INET6, & p->sin6_node_address.sin6_addr, buf, sizeof(buf)))
8488 LogInfo("nodePresence: IPv6 address: %s, SUI %d", buf, op->SUI);
8489 else
8490 LogInfo("nodePresence: inet_ntop() error");
8491
8492 // AWDL will generate a KEV_DL_NODE_PRESENCE event with SSTH field of
8493 // all zeroes when a node is present and has no services registered.
8494 if (allZeroSSTH(op))
8495 {
8496 mDNSAddr peerAddr;
8497
8498 peerAddr.type = mDNSAddrType_IPv6;
8499 peerAddr.ip.v6 = *(mDNSv6Addr*)&p->sin6_node_address.sin6_addr;
8500
8501 LogInfo("nodePresence: ssth is all zeroes, delete cached records from this peer");
8502 removeCachedPeerRecords(m, p->sdl_node_address.sdl_index, & peerAddr);
8503 }
8504 }
8505
8506 // Handle KEV_DL_NODE_ABSENCE event.
8507 mDNSlocal void nodeAbsence(mDNS *const m, struct kev_dl_node_absence * p)
8508 {
8509 mDNSAddr peerAddr;
8510 char buf[INET6_ADDRSTRLEN];
8511
8512 if (inet_ntop(AF_INET6, & p->sin6_node_address.sin6_addr, buf, sizeof(buf)))
8513 LogInfo("nodeAbsence: IPv6 address: %s", buf);
8514 else
8515 LogInfo("nodeAbsence: inet_ntop() error");
8516
8517 peerAddr.type = mDNSAddrType_IPv6;
8518 peerAddr.ip.v6 = *(mDNSv6Addr*)&p->sin6_node_address.sin6_addr;
8519
8520 LogInfo("nodeAbsence: delete cached records from this peer");
8521 removeCachedPeerRecords(m, p->sdl_node_address.sdl_index, & peerAddr);
8522 }
8523
8524 mDNSlocal void SysEventCallBack(int s1, short __unused filter, void *context)
8525 {
8526 mDNS *const m = (mDNS *const)context;
8527
8528 mDNS_Lock(m);
8529
8530 struct { struct kern_event_msg k; char extra[256]; } msg;
8531 int bytes = recv(s1, &msg, sizeof(msg), 0);
8532 if (bytes < 0)
8533 LogMsg("SysEventCallBack: recv error %d errno %d (%s)", bytes, errno, strerror(errno));
8534 else
8535 {
8536 LogInfo("SysEventCallBack got %d bytes size %d %X %s %X %s %X %s id %d code %d %s",
8537 bytes, msg.k.total_size,
8538 msg.k.vendor_code, msg.k.vendor_code == KEV_VENDOR_APPLE ? "KEV_VENDOR_APPLE" : "?",
8539 msg.k.kev_class, msg.k.kev_class == KEV_NETWORK_CLASS ? "KEV_NETWORK_CLASS" : "?",
8540 msg.k.kev_subclass, msg.k.kev_subclass == KEV_DL_SUBCLASS ? "KEV_DL_SUBCLASS" : "?",
8541 msg.k.id, msg.k.event_code,
8542 msg.k.event_code == KEV_DL_SIFFLAGS ? "KEV_DL_SIFFLAGS" :
8543 msg.k.event_code == KEV_DL_SIFMETRICS ? "KEV_DL_SIFMETRICS" :
8544 msg.k.event_code == KEV_DL_SIFMTU ? "KEV_DL_SIFMTU" :
8545 msg.k.event_code == KEV_DL_SIFPHYS ? "KEV_DL_SIFPHYS" :
8546 msg.k.event_code == KEV_DL_SIFMEDIA ? "KEV_DL_SIFMEDIA" :
8547 msg.k.event_code == KEV_DL_SIFGENERIC ? "KEV_DL_SIFGENERIC" :
8548 msg.k.event_code == KEV_DL_ADDMULTI ? "KEV_DL_ADDMULTI" :
8549 msg.k.event_code == KEV_DL_DELMULTI ? "KEV_DL_DELMULTI" :
8550 msg.k.event_code == KEV_DL_IF_ATTACHED ? "KEV_DL_IF_ATTACHED" :
8551 msg.k.event_code == KEV_DL_IF_DETACHING ? "KEV_DL_IF_DETACHING" :
8552 msg.k.event_code == KEV_DL_IF_DETACHED ? "KEV_DL_IF_DETACHED" :
8553 msg.k.event_code == KEV_DL_LINK_OFF ? "KEV_DL_LINK_OFF" :
8554 msg.k.event_code == KEV_DL_LINK_ON ? "KEV_DL_LINK_ON" :
8555 msg.k.event_code == KEV_DL_PROTO_ATTACHED ? "KEV_DL_PROTO_ATTACHED" :
8556 msg.k.event_code == KEV_DL_PROTO_DETACHED ? "KEV_DL_PROTO_DETACHED" :
8557 msg.k.event_code == KEV_DL_LINK_ADDRESS_CHANGED ? "KEV_DL_LINK_ADDRESS_CHANGED" :
8558 msg.k.event_code == KEV_DL_WAKEFLAGS_CHANGED ? "KEV_DL_WAKEFLAGS_CHANGED" :
8559 msg.k.event_code == KEV_DL_IF_IDLE_ROUTE_REFCNT ? "KEV_DL_IF_IDLE_ROUTE_REFCNT" :
8560 msg.k.event_code == KEV_DL_IFCAP_CHANGED ? "KEV_DL_IFCAP_CHANGED" :
8561 msg.k.event_code == KEV_DL_LINK_QUALITY_METRIC_CHANGED ? "KEV_DL_LINK_QUALITY_METRIC_CHANGED" :
8562 msg.k.event_code == KEV_DL_NODE_PRESENCE ? "KEV_DL_NODE_PRESENCE" :
8563 msg.k.event_code == KEV_DL_NODE_ABSENCE ? "KEV_DL_NODE_ABSENCE" :
8564 msg.k.event_code == KEV_DL_MASTER_ELECTED ? "KEV_DL_MASTER_ELECTED" :
8565 "?");
8566
8567 if (msg.k.event_code == KEV_DL_NODE_PRESENCE)
8568 nodePresence(m, (struct kev_dl_node_presence *) &msg.k.event_data);
8569
8570 if (msg.k.event_code == KEV_DL_NODE_ABSENCE)
8571 nodeAbsence(m, (struct kev_dl_node_absence *) &msg.k.event_data);
8572
8573 if (msg.k.event_code == KEV_DL_MASTER_ELECTED)
8574 newMasterElected(m, (struct net_event_data *) &msg.k.event_data);
8575
8576 // We receive network change notifications both through configd and through SYSPROTO_EVENT socket.
8577 // Configd may not generate network change events for manually configured interfaces (i.e., non-DHCP)
8578 // always during sleep/wakeup due to some race conditions (See radar:8666757). At the same time, if
8579 // "Wake on Network Access" is not turned on, the notification will not have KEV_DL_WAKEFLAGS_CHANGED.
8580 // Hence, during wake up, if we see a KEV_DL_LINK_ON (i.e., link is UP), we trigger a network change.
8581
8582 if (msg.k.event_code == KEV_DL_WAKEFLAGS_CHANGED || msg.k.event_code == KEV_DL_LINK_ON)
8583 SetNetworkChanged(m, mDNSPlatformOneSecond * 2);
8584
8585 #if !TARGET_OS_EMBEDDED // don't setup packet filter rules on embedded
8586
8587 // For p2p interfaces, need to open the advertised service port in the firewall.
8588 if (msg.k.event_code == KEV_DL_IF_ATTACHED)
8589 {
8590 struct net_event_data * p;
8591 p = (struct net_event_data *) &msg.k.event_data;
8592
8593 if (strncmp(p->if_name, "p2p", 3) == 0)
8594 {
8595 char ifname[IFNAMSIZ];
8596 snprintf(ifname, IFNAMSIZ, "%s%d", p->if_name, p->if_unit);
8597
8598 LogInfo("SysEventCallBack: KEV_DL_IF_ATTACHED if_family = %d, if_unit = %d, if_name = %s", p->if_family, p->if_unit, p->if_name);
8599
8600 mDNSSetPacketFilterRules(m, ifname, NULL);
8601 }
8602 }
8603
8604 // For p2p interfaces, need to clear the firewall rules on interface detach
8605 if (msg.k.event_code == KEV_DL_IF_DETACHED)
8606 {
8607 struct net_event_data * p;
8608 p = (struct net_event_data *) &msg.k.event_data;
8609
8610 if (strncmp(p->if_name, "p2p", 3) == 0)
8611 {
8612 pfArray_t portArray, protocolArray; // not initialized since count is 0 for PF_CLEAR_RULES
8613 char ifname[IFNAMSIZ];
8614 snprintf(ifname, IFNAMSIZ, "%s%d", p->if_name, p->if_unit);
8615
8616 LogInfo("SysEventCallBack: KEV_DL_IF_DETACHED if_family = %d, if_unit = %d, if_name = %s", p->if_family, p->if_unit, p->if_name);
8617
8618 mDNSPacketFilterControl(PF_CLEAR_RULES, ifname, 0, portArray, protocolArray);
8619 }
8620 }
8621 #endif // !TARGET_OS_EMBEDDED
8622
8623 }
8624
8625 mDNS_Unlock(m);
8626 }
8627
8628 mDNSlocal mStatus WatchForSysEvents(mDNS *const m)
8629 {
8630 m->p->SysEventNotifier = socket(PF_SYSTEM, SOCK_RAW, SYSPROTO_EVENT);
8631 if (m->p->SysEventNotifier < 0)
8632 { LogMsg("WatchForSysEvents: socket failed error %d errno %d (%s)", m->p->SysEventNotifier, errno, strerror(errno)); return(mStatus_NoMemoryErr); }
8633
8634 struct kev_request kev_req = { KEV_VENDOR_APPLE, KEV_NETWORK_CLASS, KEV_DL_SUBCLASS };
8635 int err = ioctl(m->p->SysEventNotifier, SIOCSKEVFILT, &kev_req);
8636 if (err < 0)
8637 {
8638 LogMsg("WatchForSysEvents: SIOCSKEVFILT failed error %d errno %d (%s)", err, errno, strerror(errno));
8639 close(m->p->SysEventNotifier);
8640 m->p->SysEventNotifier = -1;
8641 return(mStatus_UnknownErr);
8642 }
8643
8644 m->p->SysEventKQueue.KQcallback = SysEventCallBack;
8645 m->p->SysEventKQueue.KQcontext = m;
8646 m->p->SysEventKQueue.KQtask = "System Event Notifier";
8647 KQueueSet(m->p->SysEventNotifier, EV_ADD, EVFILT_READ, &m->p->SysEventKQueue);
8648
8649 return(mStatus_NoError);
8650 }
8651
8652 #ifndef NO_SECURITYFRAMEWORK
8653 mDNSlocal OSStatus KeychainChanged(SecKeychainEvent keychainEvent, SecKeychainCallbackInfo *info, void *context)
8654 {
8655 LogInfo("*** Keychain Changed ***");
8656 mDNS *const m = (mDNS *const)context;
8657 SecKeychainRef skc;
8658 OSStatus err = SecKeychainCopyDefault(&skc);
8659 if (!err)
8660 {
8661 if (info->keychain == skc)
8662 {
8663 // For delete events, attempt to verify what item was deleted fail because the item is already gone, so we just assume they may be relevant
8664 mDNSBool relevant = (keychainEvent == kSecDeleteEvent);
8665 if (!relevant)
8666 {
8667 UInt32 tags[3] = { kSecTypeItemAttr, kSecServiceItemAttr, kSecAccountItemAttr };
8668 SecKeychainAttributeInfo attrInfo = { 3, tags, NULL }; // Count, array of tags, array of formats
8669 SecKeychainAttributeList *a = NULL;
8670 err = SecKeychainItemCopyAttributesAndData(info->item, &attrInfo, NULL, &a, NULL, NULL);
8671 if (!err)
8672 {
8673 relevant = ((a->attr[0].length == 4 && (!strncasecmp(a->attr[0].data, "ddns", 4) || !strncasecmp(a->attr[0].data, "sndd", 4))) ||
8674 (a->attr[1].length >= mDNSPlatformStrLen(dnsprefix) && (!strncasecmp(a->attr[1].data, dnsprefix, mDNSPlatformStrLen(dnsprefix)))) ||
8675 (a->attr[1].length >= mDNSPlatformStrLen(btmmprefix) && (!strncasecmp(a->attr[1].data, btmmprefix, mDNSPlatformStrLen(btmmprefix)))));
8676 SecKeychainItemFreeAttributesAndData(a, NULL);
8677 }
8678 }
8679 if (relevant)
8680 {
8681 LogInfo("*** Keychain Changed *** KeychainEvent=%d %s",
8682 keychainEvent,
8683 keychainEvent == kSecAddEvent ? "kSecAddEvent" :
8684 keychainEvent == kSecDeleteEvent ? "kSecDeleteEvent" :
8685 keychainEvent == kSecUpdateEvent ? "kSecUpdateEvent" : "<Unknown>");
8686 // We're running on the CFRunLoop (Mach port) thread, not the kqueue thread, so we need to grab the KQueueLock before proceeding
8687 KQueueLock(m);
8688 mDNS_Lock(m);
8689
8690 // To not read the keychain twice: when BTMM is enabled, changes happen to the keychain
8691 // then the BTMM DynStore dictionary, so delay reading the keychain for a second.
8692 // NetworkChanged() will reset the keychain timer to fire immediately when the DynStore changes.
8693 //
8694 // In the "fixup" case where the BTMM DNS servers aren't accepting the key mDNSResponder has,
8695 // the DynStore dictionary won't change (because the BTMM zone won't change). In that case,
8696 // a one second delay is ok, as we'll still converge to correctness, and there's no race
8697 // condition between the RegistrationDomain and the DomainAuthInfo.
8698 //
8699 // Lastly, non-BTMM WAB cases can use the keychain but not the DynStore, so we need to set
8700 // the timer here, as it will not get set by NetworkChanged().
8701 SetKeyChainTimer(m, mDNSPlatformOneSecond);
8702
8703 mDNS_Unlock(m);
8704 KQueueUnlock(m, "KeychainChanged");
8705 }
8706 }
8707 CFRelease(skc);
8708 }
8709
8710 return 0;
8711 }
8712 #endif
8713
8714 mDNSlocal void PowerOn(mDNS *const m)
8715 {
8716 mDNSCoreMachineSleep(m, false); // Will set m->SleepState = SleepState_Awake;
8717 if (m->p->WakeAtUTC)
8718 {
8719 long utc = mDNSPlatformUTC();
8720 mDNSPowerRequest(-1,-1); // Need to explicitly clear any previous power requests -- they're not cleared automatically on wake
8721 if (m->p->WakeAtUTC - utc > 30)
8722 {
8723 LogSPS("PowerChanged PowerOn %d seconds early, assuming not maintenance wake", m->p->WakeAtUTC - utc);
8724 }
8725 else if (utc - m->p->WakeAtUTC > 30)
8726 {
8727 LogSPS("PowerChanged PowerOn %d seconds late, assuming not maintenance wake", utc - m->p->WakeAtUTC);
8728 }
8729 else if (IsAppleTV())
8730 {
8731 LogSPS("PowerChanged PowerOn %d seconds late, device is an AppleTV running iOS so not re-sleeping", utc - m->p->WakeAtUTC);
8732 }
8733 else
8734 {
8735 LogSPS("PowerChanged: Waking for network maintenance operations %d seconds early; re-sleeping in 20 seconds", m->p->WakeAtUTC - utc);
8736 m->p->RequestReSleep = mDNS_TimeNow(m) + 20 * mDNSPlatformOneSecond;
8737 }
8738 }
8739 }
8740
8741 mDNSlocal void PowerChanged(void *refcon, io_service_t service, natural_t messageType, void *messageArgument)
8742 {
8743 mDNS *const m = (mDNS *const)refcon;
8744 KQueueLock(m);
8745 (void)service; // Parameter not used
8746 debugf("PowerChanged %X %lX", messageType, messageArgument);
8747
8748 // Make sure our m->SystemWakeOnLANEnabled value correctly reflects the current system setting
8749 m->SystemWakeOnLANEnabled = SystemWakeForNetworkAccess();
8750
8751 switch(messageType)
8752 {
8753 case kIOMessageCanSystemPowerOff: LogSPS("PowerChanged kIOMessageCanSystemPowerOff (no action)"); break; // E0000240
8754 case kIOMessageSystemWillPowerOff: LogSPS("PowerChanged kIOMessageSystemWillPowerOff"); // E0000250
8755 mDNSCoreMachineSleep(m, true);
8756 if (m->SleepState == SleepState_Sleeping) mDNSMacOSXNetworkChanged(m);
8757 break;
8758 case kIOMessageSystemWillNotPowerOff: LogSPS("PowerChanged kIOMessageSystemWillNotPowerOff (no action)"); break; // E0000260
8759 case kIOMessageCanSystemSleep: LogSPS("PowerChanged kIOMessageCanSystemSleep (no action)"); break; // E0000270
8760 case kIOMessageSystemWillSleep: LogSPS("PowerChanged kIOMessageSystemWillSleep"); // E0000280
8761 mDNSCoreMachineSleep(m, true);
8762 break;
8763 case kIOMessageSystemWillNotSleep: LogSPS("PowerChanged kIOMessageSystemWillNotSleep (no action)"); break; // E0000290
8764 case kIOMessageSystemHasPoweredOn: LogSPS("PowerChanged kIOMessageSystemHasPoweredOn"); // E0000300
8765 // If still sleeping (didn't get 'WillPowerOn' message for some reason?) wake now
8766 if (m->SleepState)
8767 {
8768 LogMsg("PowerChanged kIOMessageSystemHasPoweredOn: ERROR m->SleepState %d", m->SleepState);
8769 PowerOn(m);
8770 }
8771 // Just to be safe, schedule a mDNSMacOSXNetworkChanged(), in case we never received
8772 // the System Configuration Framework "network changed" event that we expect
8773 // to receive some time shortly after the kIOMessageSystemWillPowerOn message
8774 mDNS_Lock(m);
8775 if (!m->p->NetworkChanged ||
8776 m->p->NetworkChanged - NonZeroTime(m->timenow + mDNSPlatformOneSecond * 2) < 0)
8777 m->p->NetworkChanged = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 2);
8778 mDNS_Unlock(m);
8779
8780 break;
8781 case kIOMessageSystemWillRestart: LogSPS("PowerChanged kIOMessageSystemWillRestart (no action)"); break; // E0000310
8782 case kIOMessageSystemWillPowerOn: LogSPS("PowerChanged kIOMessageSystemWillPowerOn"); // E0000320
8783
8784 // Make sure our interface list is cleared to the empty state, then tell mDNSCore to wake
8785 if (m->SleepState != SleepState_Sleeping)
8786 {
8787 LogMsg("kIOMessageSystemWillPowerOn: ERROR m->SleepState %d", m->SleepState);
8788 m->SleepState = SleepState_Sleeping;
8789 mDNSMacOSXNetworkChanged(m);
8790 }
8791 PowerOn(m);
8792 break;
8793 default: LogSPS("PowerChanged unknown message %X", messageType); break;
8794 }
8795
8796 if (messageType == kIOMessageSystemWillSleep) m->p->SleepCookie = (long)messageArgument;
8797 else IOAllowPowerChange(m->p->PowerConnection, (long)messageArgument);
8798
8799 KQueueUnlock(m, "PowerChanged Sleep/Wake");
8800 }
8801
8802 // iPhone OS doesn't currently have SnowLeopard's IO Power Management
8803 // but it does define kIOPMAcknowledgmentOptionSystemCapabilityRequirements
8804 #if defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements) && !TARGET_OS_EMBEDDED
8805 mDNSlocal void SnowLeopardPowerChanged(void *refcon, IOPMConnection connection, IOPMConnectionMessageToken token, IOPMSystemPowerStateCapabilities eventDescriptor)
8806 {
8807 mDNS *const m = (mDNS *const)refcon;
8808 KQueueLock(m);
8809 LogSPS("SnowLeopardPowerChanged %X %X %X%s%s%s%s%s",
8810 connection, token, eventDescriptor,
8811 eventDescriptor & kIOPMSystemPowerStateCapabilityCPU ? " CPU" : "",
8812 eventDescriptor & kIOPMSystemPowerStateCapabilityVideo ? " Video" : "",
8813 eventDescriptor & kIOPMSystemPowerStateCapabilityAudio ? " Audio" : "",
8814 eventDescriptor & kIOPMSystemPowerStateCapabilityNetwork ? " Network" : "",
8815 eventDescriptor & kIOPMSystemPowerStateCapabilityDisk ? " Disk" : "");
8816
8817 // Make sure our m->SystemWakeOnLANEnabled value correctly reflects the current system setting
8818 m->SystemWakeOnLANEnabled = SystemWakeForNetworkAccess();
8819
8820 if (eventDescriptor & kIOPMSystemPowerStateCapabilityCPU)
8821 {
8822 // We might be in Sleeping or Transferring state. When we go from "wakeup" to "sleep" state, we don't
8823 // go directly to sleep state, but transfer in to the sleep state during which SleepState is set to
8824 // SleepState_Transferring. During that time, we might get another wakeup before we transition to Sleeping
8825 // state. In that case, we need to acknowledge the previous "sleep" before we acknowledge the wakeup.
8826 if (m->SleepLimit)
8827 {
8828 LogSPS("SnowLeopardPowerChanged: Waking up, Acking old Sleep, SleepLimit %d SleepState %d", m->SleepLimit, m->SleepState);
8829 IOPMConnectionAcknowledgeEvent(connection, m->p->SleepCookie);
8830 m->SleepLimit = 0;
8831 }
8832 LogSPS("SnowLeopardPowerChanged: Waking up, Acking Wakeup, SleepLimit %d SleepState %d", m->SleepLimit, m->SleepState);
8833 // If the network notifications have already come before we got the wakeup, we ignored them and
8834 // in case we get no more, we need to trigger one.
8835 mDNS_Lock(m);
8836 SetNetworkChanged(m, 2 * mDNSPlatformOneSecond);
8837 mDNS_Unlock(m);
8838 // CPU Waking. Note: Can get this message repeatedly, as other subsystems power up or down.
8839 if (m->SleepState != SleepState_Awake) PowerOn(m);
8840 IOPMConnectionAcknowledgeEvent(connection, token);
8841 }
8842 else
8843 {
8844 // CPU sleeping. Should not get this repeatedly -- once we're told that the CPU is halting
8845 // we should hear nothing more until we're told that the CPU has started executing again.
8846 if (m->SleepState) LogMsg("SnowLeopardPowerChanged: Sleep Error %X m->SleepState %d", eventDescriptor, m->SleepState);
8847 //sleep(5);
8848 //mDNSMacOSXNetworkChanged(m);
8849 mDNSCoreMachineSleep(m, true);
8850 //if (m->SleepState == SleepState_Sleeping) mDNSMacOSXNetworkChanged(m);
8851 m->p->SleepCookie = token;
8852 }
8853
8854 KQueueUnlock(m, "SnowLeopardPowerChanged Sleep/Wake");
8855 }
8856 #endif
8857
8858 #if COMPILER_LIKES_PRAGMA_MARK
8859 #pragma mark -
8860 #pragma mark - /etc/hosts support
8861 #endif
8862
8863 // Implementation Notes
8864 //
8865 // As /etc/hosts file can be huge (1000s of entries - when this comment was written, the test file had about
8866 // 23000 entries with about 4000 duplicates), we can't use a linked list to store these entries. So, we parse
8867 // them into a hash table. The implementation need to be able to do the following things efficiently
8868 //
8869 // 1. Detect duplicates e.g., two entries with "1.2.3.4 foo"
8870 // 2. Detect whether /etc/hosts has changed and what has changed since the last read from the disk
8871 // 3. Ability to support multiple addresses per name e.g., "1.2.3.4 foo, 2.3.4.5 foo". To support this, we
8872 // need to be able set the RRSet of a resource record to the first one in the list and also update when
8873 // one of them go away. This is needed so that the core thinks that they are all part of the same RRSet and
8874 // not a duplicate
8875 // 4. Don't maintain any local state about any records registered with the core to detect changes to /etc/hosts
8876 //
8877 // CFDictionary is not a suitable candidate because it does not support duplicates and even if we use a custom
8878 // "hash" function to solve this, the others are hard to solve. Hence, we share the hash (AuthHash) implementation
8879 // of the core layer which does all of the above very efficiently
8880
8881 #define ETCHOSTS_BUFSIZE 1024 // Buffer size to parse a single line in /etc/hosts
8882
8883 mDNSexport void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result)
8884 {
8885 (void)m; // unused
8886 (void)rr;
8887 (void)result;
8888 if (result == mStatus_MemFree)
8889 {
8890 LogInfo("FreeEtcHosts: %s", ARDisplayString(m, rr));
8891 freeL("etchosts", rr);
8892 }
8893 }
8894
8895 // Returns true on success and false on failure
8896 mDNSlocal mDNSBool mDNSMacOSXCreateEtcHostsEntry(mDNS *const m, const domainname *domain, const struct sockaddr *sa, const domainname *cname, char *ifname, AuthHash *auth)
8897 {
8898 AuthRecord *rr;
8899 mDNSu32 slot;
8900 mDNSu32 namehash;
8901 AuthGroup *ag;
8902 mDNSInterfaceID InterfaceID = mDNSInterface_LocalOnly;
8903 mDNSu16 rrtype;
8904
8905 if (!domain)
8906 {
8907 LogMsg("mDNSMacOSXCreateEtcHostsEntry: ERROR!! name NULL");
8908 return mDNSfalse;
8909 }
8910 if (!sa && !cname)
8911 {
8912 LogMsg("mDNSMacOSXCreateEtcHostsEntry: ERROR!! sa and cname both NULL");
8913 return mDNSfalse;
8914 }
8915
8916 if (sa && sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
8917 {
8918 LogMsg("mDNSMacOSXCreateEtcHostsEntry: ERROR!! sa with bad family %d", sa->sa_family);
8919 return mDNSfalse;
8920 }
8921
8922
8923 if (ifname)
8924 {
8925 mDNSu32 ifindex = if_nametoindex(ifname);
8926 if (!ifindex)
8927 {
8928 LogMsg("mDNSMacOSXCreateEtcHostsEntry: hosts entry %##s with invalid ifname %s", domain->c, ifname);
8929 return mDNSfalse;
8930 }
8931 InterfaceID = (mDNSInterfaceID)(uintptr_t)ifindex;
8932 }
8933
8934 if (sa)
8935 rrtype = (sa->sa_family == AF_INET ? kDNSType_A : kDNSType_AAAA);
8936 else
8937 rrtype = kDNSType_CNAME;
8938
8939 // Check for duplicates. See whether we parsed an entry before like this ?
8940 slot = AuthHashSlot(domain);
8941 namehash = DomainNameHashValue(domain);
8942 ag = AuthGroupForName(auth, slot, namehash, domain);
8943 if (ag)
8944 {
8945 rr = ag->members;
8946 while (rr)
8947 {
8948 if (rr->resrec.rrtype == rrtype)
8949 {
8950 if (rrtype == kDNSType_A)
8951 {
8952 mDNSv4Addr ip;
8953 ip.NotAnInteger = ((struct sockaddr_in*)sa)->sin_addr.s_addr;
8954 if (mDNSSameIPv4Address(rr->resrec.rdata->u.ipv4, ip))
8955 {
8956 LogInfo("mDNSMacOSXCreateEtcHostsEntry: Same IPv4 address for name %##s", domain->c);
8957 return mDNSfalse;
8958 }
8959 }
8960 else if (rrtype == kDNSType_AAAA)
8961 {
8962 mDNSv6Addr ip6;
8963 ip6.l[0] = ((struct sockaddr_in6*)sa)->sin6_addr.__u6_addr.__u6_addr32[0];
8964 ip6.l[1] = ((struct sockaddr_in6*)sa)->sin6_addr.__u6_addr.__u6_addr32[1];
8965 ip6.l[2] = ((struct sockaddr_in6*)sa)->sin6_addr.__u6_addr.__u6_addr32[2];
8966 ip6.l[3] = ((struct sockaddr_in6*)sa)->sin6_addr.__u6_addr.__u6_addr32[3];
8967 if (mDNSSameIPv6Address(rr->resrec.rdata->u.ipv6, ip6))
8968 {
8969 LogInfo("mDNSMacOSXCreateEtcHostsEntry: Same IPv6 address for name %##s", domain->c);
8970 return mDNSfalse;
8971 }
8972 }
8973 else if (rrtype == kDNSType_CNAME)
8974 {
8975 if (SameDomainName(&rr->resrec.rdata->u.name, cname))
8976 {
8977 LogInfo("mDNSMacOSXCreateEtcHostsEntry: Same cname %##s for name %##s", cname->c, domain->c);
8978 return mDNSfalse;
8979 }
8980 }
8981 }
8982 rr = rr->next;
8983 }
8984 }
8985 rr= mallocL("etchosts", sizeof(*rr));
8986 if (rr == NULL) return mDNSfalse;
8987 mDNSPlatformMemZero(rr, sizeof(*rr));
8988 mDNS_SetupResourceRecord(rr, NULL, InterfaceID, rrtype, 1, kDNSRecordTypeKnownUnique, AuthRecordLocalOnly, FreeEtcHosts, NULL);
8989 AssignDomainName(&rr->namestorage, domain);
8990
8991 if (sa)
8992 {
8993 rr->resrec.rdlength = sa->sa_family == AF_INET ? sizeof(mDNSv4Addr) : sizeof(mDNSv6Addr);
8994 if (sa->sa_family == AF_INET)
8995 rr->resrec.rdata->u.ipv4.NotAnInteger = ((struct sockaddr_in*)sa)->sin_addr.s_addr;
8996 else
8997 {
8998 rr->resrec.rdata->u.ipv6.l[0] = ((struct sockaddr_in6*)sa)->sin6_addr.__u6_addr.__u6_addr32[0];
8999 rr->resrec.rdata->u.ipv6.l[1] = ((struct sockaddr_in6*)sa)->sin6_addr.__u6_addr.__u6_addr32[1];
9000 rr->resrec.rdata->u.ipv6.l[2] = ((struct sockaddr_in6*)sa)->sin6_addr.__u6_addr.__u6_addr32[2];
9001 rr->resrec.rdata->u.ipv6.l[3] = ((struct sockaddr_in6*)sa)->sin6_addr.__u6_addr.__u6_addr32[3];
9002 }
9003 }
9004 else
9005 {
9006 rr->resrec.rdlength = DomainNameLength(cname);
9007 rr->resrec.rdata->u.name.c[0] = 0;
9008 AssignDomainName(&rr->resrec.rdata->u.name, cname);
9009 }
9010 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
9011 SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
9012 LogInfo("mDNSMacOSXCreateEtcHostsEntry: Adding resource record %s", ARDisplayString(m, rr));
9013 InsertAuthRecord(m, auth, rr);
9014 return mDNStrue;
9015 }
9016
9017 mDNSlocal int EtcHostsParseOneName(int start, int length, char *buffer, char **name)
9018 {
9019 int i;
9020
9021 *name = NULL;
9022 for (i = start; i < length; i++)
9023 {
9024 if (buffer[i] == '#')
9025 return -1;
9026 if (buffer[i] != ' ' && buffer[i] != ',' && buffer[i] != '\t')
9027 {
9028 *name = &buffer[i];
9029
9030 // Found the start of a name, find the end and null terminate
9031 for (i++; i < length; i++)
9032 {
9033 if (buffer[i] == ' ' || buffer[i] == ',' || buffer[i] == '\t')
9034 {
9035 buffer[i] = 0;
9036 break;
9037 }
9038 }
9039 return i;
9040 }
9041 }
9042 return -1;
9043 }
9044
9045 mDNSlocal void mDNSMacOSXParseEtcHostsLine(mDNS *const m, char *buffer, ssize_t length, AuthHash *auth)
9046 {
9047 int i;
9048 int ifStart = 0;
9049 char *ifname = NULL;
9050 domainname name1d;
9051 domainname name2d;
9052 char *name1;
9053 char *name2;
9054 int aliasIndex;
9055
9056 //Ignore leading whitespaces and tabs
9057 while (*buffer == ' ' || *buffer == '\t')
9058 {
9059 buffer++;
9060 length--;
9061 }
9062
9063 // Find the end of the address string
9064 for (i = 0; i < length; i++)
9065 {
9066 if (buffer[i] == ' ' || buffer[i] == ',' || buffer[i] == '\t' || buffer[i] == '%')
9067 {
9068 if (buffer[i] == '%')
9069 ifStart = i + 1;
9070 buffer[i] = 0;
9071 break;
9072 }
9073 }
9074
9075 // Convert the address string to an address
9076 struct addrinfo hints;
9077 bzero(&hints, sizeof(hints));
9078 hints.ai_flags = AI_NUMERICHOST;
9079 struct addrinfo *gairesults = NULL;
9080 if (getaddrinfo(buffer, NULL, &hints, &gairesults) != 0)
9081 {
9082 LogInfo("mDNSMacOSXParseEtcHostsLine: getaddrinfo returning null");
9083 return;
9084 }
9085
9086 if (ifStart)
9087 {
9088 // Parse the interface
9089 ifname = &buffer[ifStart];
9090 for (i = ifStart + 1; i < length; i++)
9091 {
9092 if (buffer[i] == ' ' || buffer[i] == ',' || buffer[i] == '\t')
9093 {
9094 buffer[i] = 0;
9095 break;
9096 }
9097 }
9098 }
9099
9100 i = EtcHostsParseOneName(i + 1, length, buffer, &name1);
9101 if (i == length)
9102 {
9103 // Common case (no aliases) : The entry is of the form "1.2.3.4 somehost" with no trailing white spaces/tabs etc.
9104 if (!MakeDomainNameFromDNSNameString(&name1d, name1))
9105 {
9106 LogMsg("mDNSMacOSXParseEtcHostsLine: ERROR!! cannot convert to domain name %s", name1);
9107 freeaddrinfo(gairesults);
9108 return;
9109 }
9110 mDNSMacOSXCreateEtcHostsEntry(m, &name1d, gairesults->ai_addr, mDNSNULL, ifname, auth);
9111 }
9112 else if (i != -1)
9113 {
9114 domainname first;
9115 // We might have some extra white spaces at the end for the common case of "1.2.3.4 somehost".
9116 // When we parse again below, EtchHostsParseOneName would return -1 and we will end up
9117 // doing the right thing.
9118 if (!MakeDomainNameFromDNSNameString(&first, name1))
9119 {
9120 LogMsg("mDNSMacOSXParseEtcHostsLine: ERROR!! cannot convert to domain name %s", name1);
9121 freeaddrinfo(gairesults);
9122 return;
9123 }
9124 // If the /etc/hosts has an entry like this
9125 //
9126 // 1.2.3.4 sun star bright
9127 //
9128 // star and bright are aliases (gethostbyname h_alias should point to these) and sun is the canonical
9129 // name (getaddrinfo ai_cannonname and gethostbyname h_name points to "sun")
9130 //
9131 // To achieve this, we need to add the entry like this:
9132 //
9133 // star CNAME bright
9134 // bright CNAME sun
9135 // sun A 1.2.3.4
9136 //
9137 // We store the first name we parsed in "first". Then we parse additional names adding CNAME records
9138 // till we reach the end. When we reach the end, we wrap around and add one final CNAME with the last
9139 // entry and the first entry. Finally, we add the Address (A/AAAA) record.
9140 aliasIndex = 0;
9141 while (i <= length)
9142 {
9143 // Parse a name. If there are no names, we need to know whether we
9144 // parsed CNAMEs before or not. If we parsed CNAMEs before, then we
9145 // add a CNAME with the last name and the first name. Otherwise, this
9146 // is same as the common case above where the line has just one name
9147 // but with trailing white spaces.
9148 i = EtcHostsParseOneName(i + 1, length, buffer, &name2);
9149 if (name2)
9150 {
9151 if (!MakeDomainNameFromDNSNameString(&name2d, name2))
9152 {
9153 LogMsg("mDNSMacOSXParseEtcHostsLine: ERROR!! cannot convert to domain name %s", name2);
9154 freeaddrinfo(gairesults);
9155 return;
9156 }
9157 aliasIndex++;
9158 }
9159 else if (!aliasIndex)
9160 {
9161 // We have never parsed any aliases. This case happens if there
9162 // is just one name and some extra white spaces at the end.
9163 LogInfo("mDNSMacOSXParseEtcHostsLine: White space at the end of %##s", first.c);
9164 break;
9165 }
9166 else
9167 {
9168 // We have parsed at least one alias before and we reached the end of the line.
9169 // Setup a CNAME for the last name with "first" name as its RDATA
9170 name2d.c[0] = 0;
9171 AssignDomainName(&name2d, &first);
9172 }
9173
9174 // Don't add a CNAME for the first alias we parse (see the example above).
9175 // As we parse more, we might discover that there are no more aliases, in
9176 // which case we would have set "name2d" to "first" above. We need to add
9177 // the CNAME in that case.
9178
9179 if (aliasIndex > 1 || SameDomainName(&name2d, &first))
9180 {
9181 // Ignore if it points to itself
9182 if (!SameDomainName(&name1d, &name2d))
9183 {
9184 if (!mDNSMacOSXCreateEtcHostsEntry(m, &name1d, mDNSNULL, &name2d, ifname, auth))
9185 {
9186 freeaddrinfo(gairesults);
9187 return;
9188 }
9189 }
9190 else
9191 LogMsg("mDNSMacOSXParseEtcHostsLine: Ignoring entry with same names name1 %##s, name2 %##s", name1d.c, name2d.c);
9192 }
9193
9194 // If we have already wrapped around, we just need to add the A/AAAA record alone
9195 // which is done below
9196 if (SameDomainName(&name2d, &first)) break;
9197
9198 // Remember the current name so that we can set the CNAME record if we parse one
9199 // more name
9200 name1d.c[0] = 0;
9201 AssignDomainName(&name1d, &name2d);
9202 }
9203 // Added all the CNAMEs if any, add the "A/AAAA" record
9204 mDNSMacOSXCreateEtcHostsEntry(m, &first, gairesults->ai_addr, mDNSNULL, ifname, auth);
9205 }
9206 freeaddrinfo(gairesults);
9207 }
9208
9209 mDNSlocal void mDNSMacOSXParseEtcHosts(mDNS *const m, int fd, AuthHash *auth)
9210 {
9211 mDNSBool good;
9212 char buf[ETCHOSTS_BUFSIZE];
9213 ssize_t len;
9214 FILE *fp;
9215
9216 if (fd == -1) { LogInfo("mDNSMacOSXParseEtcHosts: fd is -1"); return; }
9217
9218 fp = fopen("/etc/hosts", "r");
9219 if (!fp) { LogInfo("mDNSMacOSXParseEtcHosts: fp is NULL"); return; }
9220
9221 while (1)
9222 {
9223 good = (fgets(buf, ETCHOSTS_BUFSIZE, fp) != NULL);
9224 if (!good) break;
9225
9226 // skip comment and empty lines
9227 if (buf[0] == '#' || buf[0] == '\r' || buf[0] == '\n')
9228 continue;
9229
9230 len = strlen(buf);
9231 if (!len) break; // sanity check
9232 //Check for end of line code(mostly only \n but pre-OS X Macs could have only \r)
9233 if (buf[len - 1] == '\r' || buf[len - 1] == '\n')
9234 {
9235 buf[len - 1] = '\0';
9236 len = len - 1;
9237 }
9238 // fgets always null terminates and hence even if we have no
9239 // newline at the end, it is null terminated. The callee
9240 // (mDNSMacOSXParseEtcHostsLine) expects the length to be such that
9241 // buf[length] is zero and hence we decrement len to reflect that.
9242 if (len)
9243 {
9244 //Additional check when end of line code is 2 chars ie\r\n(DOS, other old OSes)
9245 //here we need to check for just \r but taking extra caution.
9246 if (buf[len - 1] == '\r' || buf[len - 1] == '\n')
9247 {
9248 buf[len - 1] = '\0';
9249 len = len - 1;
9250 }
9251 }
9252 if (!len) //Sanity Check: len should never be zero
9253 {
9254 LogMsg("mDNSMacOSXParseEtcHosts: Length is zero!");
9255 continue;
9256 }
9257 mDNSMacOSXParseEtcHostsLine(m, buf, len, auth);
9258 }
9259 fclose(fp);
9260 }
9261
9262 mDNSlocal void mDNSMacOSXUpdateEtcHosts(mDNS *const m);
9263
9264 mDNSlocal int mDNSMacOSXGetEtcHostsFD(mDNS *const m)
9265 {
9266 #ifdef __DISPATCH_GROUP__
9267 // Can't do this stuff to be notified of changes in /etc/hosts if we don't have libdispatch
9268 static dispatch_queue_t etcq = 0;
9269 static dispatch_source_t etcsrc = 0;
9270 static dispatch_source_t hostssrc = 0;
9271
9272 // First time through? just schedule ourselves on the main queue and we'll do the work later
9273 if (!etcq)
9274 {
9275 etcq = dispatch_get_main_queue();
9276 if (etcq)
9277 {
9278 // Do this work on the queue, not here - solves potential synchronization issues
9279 dispatch_async(etcq, ^{mDNSMacOSXUpdateEtcHosts(m);});
9280 }
9281 return -1;
9282 }
9283
9284 if (hostssrc) return dispatch_source_get_handle(hostssrc);
9285 #endif
9286
9287 int fd = open("/etc/hosts", O_RDONLY);
9288
9289 #ifdef __DISPATCH_GROUP__
9290 // Can't do this stuff to be notified of changes in /etc/hosts if we don't have libdispatch
9291 if (fd == -1)
9292 {
9293 // If the open failed and we're already watching /etc, we're done
9294 if (etcsrc) { LogInfo("mDNSMacOSXGetEtcHostsFD: Returning etcfd because no etchosts"); return fd; }
9295
9296 // we aren't watching /etc, we should be
9297 fd = open("/etc", O_RDONLY);
9298 if (fd == -1) { LogInfo("mDNSMacOSXGetEtcHostsFD: etc does not exist"); return -1; }
9299 etcsrc = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fd, DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE | DISPATCH_VNODE_RENAME, etcq);
9300 if (etcsrc == NULL)
9301 {
9302 close(fd);
9303 return -1;
9304 }
9305 dispatch_source_set_event_handler(etcsrc,
9306 ^{
9307 u_int32_t flags = dispatch_source_get_data(etcsrc);
9308 LogMsg("mDNSMacOSXGetEtcHostsFD: /etc changed 0x%x", flags);
9309 if ((flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME)) != 0)
9310 {
9311 dispatch_source_cancel(etcsrc);
9312 dispatch_release(etcsrc);
9313 etcsrc = NULL;
9314 dispatch_async(etcq, ^{mDNSMacOSXUpdateEtcHosts(m);});
9315 return;
9316 }
9317 if ((flags & DISPATCH_VNODE_WRITE) != 0 && hostssrc == NULL)
9318 {
9319 mDNSMacOSXUpdateEtcHosts(m);
9320 }
9321 });
9322 dispatch_source_set_cancel_handler(etcsrc, ^{close(fd);});
9323 dispatch_resume(etcsrc);
9324
9325 // Try and open /etc/hosts once more now that we're watching /etc, in case we missed the creation
9326 fd = open("/etc/hosts", O_RDONLY | O_EVTONLY);
9327 if (fd == -1) { LogMsg("mDNSMacOSXGetEtcHostsFD etc hosts does not exist, watching etc"); return -1; }
9328 }
9329
9330 // create a dispatch source to watch for changes to hosts file
9331 hostssrc = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fd,
9332 (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE | DISPATCH_VNODE_RENAME |
9333 DISPATCH_VNODE_ATTRIB | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_LINK | DISPATCH_VNODE_REVOKE), etcq);
9334 if (hostssrc == NULL)
9335 {
9336 close(fd);
9337 return -1;
9338 }
9339 dispatch_source_set_event_handler(hostssrc,
9340 ^{
9341 u_int32_t flags = dispatch_source_get_data(hostssrc);
9342 LogInfo("mDNSMacOSXGetEtcHostsFD: /etc/hosts changed 0x%x", flags);
9343 if ((flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME)) != 0)
9344 {
9345 dispatch_source_cancel(hostssrc);
9346 dispatch_release(hostssrc);
9347 hostssrc = NULL;
9348 // Bug in LibDispatch: wait a second before scheduling the block. If we schedule
9349 // the block immediately, we try to open the file and the file may not exist and may
9350 // fail to get a notification in the future. When the file does not exist and
9351 // we start to monitor the directory, on "dispatch_resume" of that source, there
9352 // is no guarantee that the file creation will be notified always because when
9353 // the dispatch_resume returns, the kevent manager may not have registered the
9354 // kevent yet but the file may have been created
9355 usleep(1000000);
9356 dispatch_async(etcq, ^{mDNSMacOSXUpdateEtcHosts(m);});
9357 return;
9358 }
9359 if ((flags & DISPATCH_VNODE_WRITE) != 0)
9360 {
9361 mDNSMacOSXUpdateEtcHosts(m);
9362 }
9363 });
9364 dispatch_source_set_cancel_handler(hostssrc, ^{LogInfo("mDNSMacOSXGetEtcHostsFD: Closing etchosts fd %d", fd); close(fd);});
9365 dispatch_resume(hostssrc);
9366
9367 // Cleanup /etc source, no need to watch it if we already have /etc/hosts
9368 if (etcsrc)
9369 {
9370 dispatch_source_cancel(etcsrc);
9371 dispatch_release(etcsrc);
9372 etcsrc = NULL;
9373 }
9374
9375 LogInfo("mDNSMacOSXGetEtcHostsFD: /etc/hosts being monitored, and not etc");
9376 return hostssrc ? (int)dispatch_source_get_handle(hostssrc) : -1;
9377 #else
9378 (void)m;
9379 return fd;
9380 #endif
9381 }
9382
9383 // When /etc/hosts is modified, flush all the cache records as there may be local
9384 // authoritative answers now
9385 mDNSlocal void FlushAllCacheRecords(mDNS *const m)
9386 {
9387 CacheRecord *cr;
9388 mDNSu32 slot;
9389 CacheGroup *cg;
9390
9391 FORALL_CACHERECORDS(slot, cg, cr)
9392 {
9393 // Skip multicast.
9394 if (cr->resrec.InterfaceID) continue;
9395
9396 // If a resource record can answer A or AAAA, they need to be flushed so that we will
9397 // never used to deliver an ADD or RMV
9398 if (RRTypeAnswersQuestionType(&cr->resrec, kDNSType_A) ||
9399 RRTypeAnswersQuestionType(&cr->resrec, kDNSType_AAAA))
9400 {
9401 LogInfo("FlushAllCacheRecords: Purging Resourcerecord %s", CRDisplayString(m, cr));
9402 mDNS_PurgeCacheResourceRecord(m, cr);
9403 }
9404 }
9405 }
9406
9407 // Add new entries to the core. If justCheck is set, this function does not add, just returns true
9408 mDNSlocal mDNSBool EtcHostsAddNewEntries(mDNS *const m, AuthHash *newhosts, mDNSBool justCheck)
9409 {
9410 AuthGroup *ag;
9411 mDNSu32 slot;
9412 AuthRecord *rr, *primary, *rrnext;
9413 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
9414 for (ag = newhosts->rrauth_hash[slot]; ag; ag = ag->next)
9415 {
9416 primary = NULL;
9417 for (rr = ag->members; rr; rr = rrnext)
9418 {
9419 rrnext = rr->next;
9420 AuthGroup *ag1;
9421 AuthRecord *rr1;
9422 mDNSBool found = mDNSfalse;
9423 ag1 = AuthGroupForRecord(&m->rrauth, slot, &rr->resrec);
9424 if (ag1 && ag1->members)
9425 {
9426 if (!primary) primary = ag1->members;
9427 rr1 = ag1->members;
9428 while (rr1)
9429 {
9430 // We are not using InterfaceID in checking for duplicates. This means,
9431 // if there are two addresses for a given name e.g., fe80::1%en0 and
9432 // fe80::1%en1, we only add the first one. It is not clear whether
9433 // this is a common case. To fix this, we also need to modify
9434 // mDNS_Register_internal in how it handles duplicates. If it becomes a
9435 // common case, we will fix it then.
9436 if (IdenticalResourceRecord(&rr1->resrec, &rr->resrec))
9437 {
9438 LogInfo("EtcHostsAddNewEntries: Skipping, not adding %s", ARDisplayString(m, rr1));
9439 found = mDNStrue;
9440 break;
9441 }
9442 rr1 = rr1->next;
9443 }
9444 }
9445 if (!found)
9446 {
9447 if (justCheck)
9448 {
9449 LogInfo("EtcHostsAddNewEntries: Entry %s not registered with core yet", ARDisplayString(m, rr));
9450 return mDNStrue;
9451 }
9452 RemoveAuthRecord(m, newhosts, rr);
9453 // if there is no primary, point to self
9454 rr->RRSet = (primary ? primary : rr);
9455 rr->next = NULL;
9456 LogInfo("EtcHostsAddNewEntries: Adding %s", ARDisplayString(m, rr));
9457 if (mDNS_Register_internal(m, rr) != mStatus_NoError)
9458 LogMsg("EtcHostsAddNewEntries: mDNS_Register failed for %s", ARDisplayString(m, rr));
9459 }
9460 }
9461 }
9462 return mDNSfalse;
9463 }
9464
9465 // Delete entries from the core that are no longer needed. If justCheck is set, this function
9466 // does not delete, just returns true
9467 mDNSlocal mDNSBool EtcHostsDeleteOldEntries(mDNS *const m, AuthHash *newhosts, mDNSBool justCheck)
9468 {
9469 AuthGroup *ag;
9470 mDNSu32 slot;
9471 AuthRecord *rr, *primary, *rrnext;
9472 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
9473 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
9474 for (rr = ag->members; rr; rr = rrnext)
9475 {
9476 mDNSBool found = mDNSfalse;
9477 AuthGroup *ag1;
9478 AuthRecord *rr1;
9479 rrnext = rr->next;
9480 if (rr->RecordCallback != FreeEtcHosts) continue;
9481 ag1 = AuthGroupForRecord(newhosts, slot, &rr->resrec);
9482 if (ag1)
9483 {
9484 primary = rr1 = ag1->members;
9485 while (rr1)
9486 {
9487 if (IdenticalResourceRecord(&rr1->resrec, &rr->resrec))
9488 {
9489 LogInfo("EtcHostsDeleteOldEntries: Old record %s found in new, skipping", ARDisplayString(m, rr));
9490 found = mDNStrue;
9491 break;
9492 }
9493 rr1 = rr1->next;
9494 }
9495 }
9496 // there is no corresponding record in newhosts for the same name. This means
9497 // we should delete this from the core.
9498 if (!found)
9499 {
9500 if (justCheck)
9501 {
9502 LogInfo("EtcHostsDeleteOldEntries: Record %s not found in new, deleting", ARDisplayString(m, rr));
9503 return mDNStrue;
9504 }
9505 // if primary is going away, make sure that the rest of the records
9506 // point to the new primary
9507 if (rr == ag->members)
9508 {
9509 AuthRecord *new_primary = rr->next;
9510 AuthRecord *r = new_primary;
9511 while (r)
9512 {
9513 if (r->RRSet == rr)
9514 {
9515 LogInfo("EtcHostsDeleteOldEntries: Updating Resource Record %s to primary", ARDisplayString(m, r));
9516 r->RRSet = new_primary;
9517 }
9518 else LogMsg("EtcHostsDeleteOldEntries: ERROR!! Resource Record %s not pointing to primary %##s", ARDisplayString(m, r), r->resrec.name);
9519 r = r->next;
9520 }
9521 }
9522 LogInfo("EtcHostsDeleteOldEntries: Deleting %s", ARDisplayString(m, rr));
9523 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9524 }
9525 }
9526 return mDNSfalse;
9527 }
9528
9529 mDNSlocal void UpdateEtcHosts(mDNS *const m, void *context)
9530 {
9531 AuthHash *newhosts = (AuthHash *)context;
9532
9533 mDNS_CheckLock(m);
9534
9535 //Delete old entries from the core if they are not present in the newhosts
9536 EtcHostsDeleteOldEntries(m, newhosts, mDNSfalse);
9537 // Add the new entries to the core if not already present in the core
9538 EtcHostsAddNewEntries(m, newhosts, mDNSfalse);
9539 }
9540
9541 mDNSlocal void FreeNewHosts(AuthHash *newhosts)
9542 {
9543 mDNSu32 slot;
9544 AuthGroup *ag, *agnext;
9545 AuthRecord *rr, *rrnext;
9546
9547 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
9548 for (ag = newhosts->rrauth_hash[slot]; ag; ag = agnext)
9549 {
9550 agnext = ag->next;
9551 for (rr = ag->members; rr; rr = rrnext)
9552 {
9553 rrnext = rr->next;
9554 freeL("etchosts", rr);
9555 }
9556 freeL("AuthGroups", ag);
9557 }
9558 }
9559
9560 mDNSlocal void mDNSMacOSXUpdateEtcHosts(mDNS *const m)
9561 {
9562 AuthHash newhosts;
9563
9564 // As we will be modifying the core, we can only have one thread running at
9565 // any point in time.
9566 KQueueLock(m);
9567
9568 mDNSPlatformMemZero(&newhosts, sizeof(AuthHash));
9569
9570 // Get the file desecriptor (will trigger us to start watching for changes)
9571 int fd = mDNSMacOSXGetEtcHostsFD(m);
9572 if (fd != -1)
9573 {
9574 LogInfo("mDNSMacOSXUpdateEtcHosts: Parsing /etc/hosts fd %d", fd);
9575 mDNSMacOSXParseEtcHosts(m, fd, &newhosts);
9576 }
9577 else LogInfo("mDNSMacOSXUpdateEtcHosts: /etc/hosts is not present");
9578
9579 // Optimization: Detect whether /etc/hosts changed or not.
9580 //
9581 // 1. Check to see if there are any new entries. We do this by seeing whether any entries in
9582 // newhosts is already registered with core. If we find at least one entry that is not
9583 // registered with core, then it means we have work to do.
9584 //
9585 // 2. Next, we check to see if any of the entries that are registered with core is not present
9586 // in newhosts. If we find at least one entry that is not present, it means we have work to
9587 // do.
9588 //
9589 // Note: We may not have to hold the lock right here as KQueueLock is held which prevents any
9590 // other thread from running. But mDNS_Lock is needed here as we will be traversing the core
9591 // data structure in EtcHostsDeleteOldEntries/NewEntries which might expect the lock to be held
9592 // in the future and this code does not have to change.
9593 mDNS_Lock(m);
9594 // Add the new entries to the core if not already present in the core
9595 if (!EtcHostsAddNewEntries(m, &newhosts, mDNStrue))
9596 {
9597 // No new entries to add, check to see if we need to delete any old entries from the
9598 // core if they are not present in the newhosts
9599 if (!EtcHostsDeleteOldEntries(m, &newhosts, mDNStrue))
9600 {
9601 LogInfo("mDNSMacOSXUpdateEtcHosts: No work");
9602 mDNS_Unlock(m);
9603 KQueueUnlock(m, "/etc/hosts changed");
9604 FreeNewHosts(&newhosts);
9605 return;
9606 }
9607 }
9608
9609 // This will flush the cache, stop and start the query so that the queries
9610 // can look at the /etc/hosts again
9611 //
9612 // Notes:
9613 //
9614 // We can't delete and free the records here. We wait for the mDNSCoreRestartAddressQueries to
9615 // deliver RMV events. It has to be done in a deferred way because we can't deliver RMV
9616 // events for local records *before* the RMV events for cache records. mDNSCoreRestartAddressQueries
9617 // delivers these events in the right order and then calls us back to delete them.
9618 //
9619 // Similarly, we do a deferred Registration of the record because mDNSCoreRestartAddressQueries
9620 // is a common function that looks at all local auth records and delivers a RMV including
9621 // the records that we might add here. If we deliver a ADD here, it will get a RMV and then when
9622 // the query is restarted, it will get another ADD. To avoid this (ADD-RMV-ADD), we defer registering
9623 // the record until the RMVs are delivered in mDNSCoreRestartAddressQueries after which UpdateEtcHosts
9624 // is called back where we do the Registration of the record. This results in RMV followed by ADD which
9625 // looks normal.
9626 mDNSCoreRestartAddressQueries(m, mDNSfalse, FlushAllCacheRecords, UpdateEtcHosts, &newhosts);
9627 mDNS_Unlock(m);
9628
9629 KQueueUnlock(m, "/etc/hosts changed");
9630 FreeNewHosts(&newhosts);
9631 }
9632
9633 #if COMPILER_LIKES_PRAGMA_MARK
9634 #pragma mark -
9635 #pragma mark - Initialization & Teardown
9636 #endif
9637
9638 CF_EXPORT CFDictionaryRef _CFCopySystemVersionDictionary(void);
9639 CF_EXPORT const CFStringRef _kCFSystemVersionProductNameKey;
9640 CF_EXPORT const CFStringRef _kCFSystemVersionProductVersionKey;
9641 CF_EXPORT const CFStringRef _kCFSystemVersionBuildVersionKey;
9642
9643 // Major version 13 is 10.9.x
9644 mDNSexport void mDNSMacOSXSystemBuildNumber(char *HINFO_SWstring)
9645 {
9646 int major = 0, minor = 0;
9647 char letter = 0, prodname[256]="<Unknown>", prodvers[256]="<Unknown>", buildver[256]="<Unknown>";
9648 CFDictionaryRef vers = _CFCopySystemVersionDictionary();
9649 if (vers)
9650 {
9651 CFStringRef cfprodname = CFDictionaryGetValue(vers, _kCFSystemVersionProductNameKey);
9652 CFStringRef cfprodvers = CFDictionaryGetValue(vers, _kCFSystemVersionProductVersionKey);
9653 CFStringRef cfbuildver = CFDictionaryGetValue(vers, _kCFSystemVersionBuildVersionKey);
9654 if (cfprodname)
9655 CFStringGetCString(cfprodname, prodname, sizeof(prodname), kCFStringEncodingUTF8);
9656 if (cfprodvers)
9657 CFStringGetCString(cfprodvers, prodvers, sizeof(prodvers), kCFStringEncodingUTF8);
9658 if (cfbuildver && CFStringGetCString(cfbuildver, buildver, sizeof(buildver), kCFStringEncodingUTF8))
9659 sscanf(buildver, "%d%c%d", &major, &letter, &minor);
9660 CFRelease(vers);
9661 }
9662 if (!major)
9663 {
9664 major = 13;
9665 LogMsg("Note: No Major Build Version number found; assuming 13");
9666 }
9667 if (HINFO_SWstring)
9668 mDNS_snprintf(HINFO_SWstring, 256, "%s %s (%s), %s", prodname, prodvers, buildver, STRINGIFY(mDNSResponderVersion));
9669 //LogMsg("%s %s (%s), %d %c %d", prodname, prodvers, buildver, major, letter, minor);
9670
9671 // If product name is "Mac OS X" (or similar) we set OSXVers, else we set iOSVers;
9672 if ((prodname[0] & 0xDF) == 'M')
9673 OSXVers = major;
9674 else
9675 iOSVers = major;
9676 }
9677
9678 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
9679 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
9680 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
9681 mDNSlocal mDNSBool mDNSPlatformInit_CanReceiveUnicast(void)
9682 {
9683 int err = -1;
9684 int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
9685 if (s < 3)
9686 LogMsg("mDNSPlatformInit_CanReceiveUnicast: socket error %d errno %d (%s)", s, errno, strerror(errno));
9687 else
9688 {
9689 struct sockaddr_in s5353;
9690 s5353.sin_family = AF_INET;
9691 s5353.sin_port = MulticastDNSPort.NotAnInteger;
9692 s5353.sin_addr.s_addr = 0;
9693 err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
9694 close(s);
9695 }
9696
9697 if (err) LogMsg("No unicast UDP responses");
9698 else debugf("Unicast UDP responses okay");
9699 return(err == 0);
9700 }
9701
9702 mDNSlocal void CreatePTRRecord(mDNS *const m, const domainname *domain)
9703 {
9704 AuthRecord *rr;
9705 const domainname *pname = (domainname *)"\x9" "localhost";
9706
9707 rr= mallocL("localhosts", sizeof(*rr));
9708 if (rr == NULL) return;
9709 mDNSPlatformMemZero(rr, sizeof(*rr));
9710
9711 mDNS_SetupResourceRecord(rr, mDNSNULL, mDNSInterface_LocalOnly, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordLocalOnly, mDNSNULL, mDNSNULL);
9712 AssignDomainName(&rr->namestorage, domain);
9713
9714 rr->resrec.rdlength = DomainNameLength(pname);
9715 rr->resrec.rdata->u.name.c[0] = 0;
9716 AssignDomainName(&rr->resrec.rdata->u.name, pname);
9717
9718 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name);
9719 SetNewRData(&rr->resrec, mDNSNULL, 0); // Sets rr->rdatahash for us
9720 mDNS_Register(m, rr);
9721 }
9722
9723 // Setup PTR records for 127.0.0.1 and ::1. This helps answering them locally rather than relying
9724 // on the external DNS server to answer this. Sometimes, the DNS servers don't respond in a timely
9725 // fashion and applications depending on this e.g., telnetd, times out after 30 seconds creating
9726 // a bad user experience. For now, we specifically create only localhosts to handle radar://9354225
9727 //
9728 // Note: We could have set this up while parsing the entries in /etc/hosts. But this is kept separate
9729 // intentionally to avoid adding to the complexity of code handling /etc/hosts.
9730 mDNSlocal void SetupLocalHostRecords(mDNS *const m)
9731 {
9732 char buffer[MAX_REVERSE_MAPPING_NAME];
9733 domainname name;
9734 int i;
9735 struct in6_addr addr;
9736 mDNSu8 *ptr = addr.__u6_addr.__u6_addr8;
9737
9738 if (inet_pton(AF_INET, "127.0.0.1", &addr) == 1)
9739 {
9740 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
9741 ptr[3], ptr[2], ptr[1], ptr[0]);
9742 MakeDomainNameFromDNSNameString(&name, buffer);
9743 CreatePTRRecord(m, &name);
9744 }
9745 else LogMsg("SetupLocalHostRecords: ERROR!! inet_pton AF_INET failed");
9746
9747 if (inet_pton(AF_INET6, "::1", &addr) == 1)
9748 {
9749 for (i = 0; i < 16; i++)
9750 {
9751 static const char hexValues[] = "0123456789ABCDEF";
9752 buffer[i * 4 ] = hexValues[ptr[15 - i] & 0x0F];
9753 buffer[i * 4 + 1] = '.';
9754 buffer[i * 4 + 2] = hexValues[ptr[15 - i] >> 4];
9755 buffer[i * 4 + 3] = '.';
9756 }
9757 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
9758 MakeDomainNameFromDNSNameString(&name, buffer);
9759 CreatePTRRecord(m, &name);
9760 }
9761 else LogMsg("SetupLocalHostRecords: ERROR!! inet_pton AF_INET6 failed");
9762 }
9763
9764 // Construction of Default Browse domain list (i.e. when clients pass NULL) is as follows:
9765 // 1) query for b._dns-sd._udp.local on LocalOnly interface
9766 // (.local manually generated via explicit callback)
9767 // 2) for each search domain (from prefs pane), query for b._dns-sd._udp.<searchdomain>.
9768 // 3) for each result from (2), register LocalOnly PTR record b._dns-sd._udp.local. -> <result>
9769 // 4) result above should generate a callback from question in (1). result added to global list
9770 // 5) global list delivered to client via GetSearchDomainList()
9771 // 6) client calls to enumerate domains now go over LocalOnly interface
9772 // (!!!KRS may add outgoing interface in addition)
9773
9774 mDNSlocal mStatus mDNSPlatformInit_setup(mDNS *const m)
9775 {
9776 mStatus err;
9777 m->p->CFRunLoop = CFRunLoopGetCurrent();
9778
9779 char HINFO_SWstring[256] = "";
9780 mDNSMacOSXSystemBuildNumber(HINFO_SWstring);
9781
9782 err = mDNSHelperInit();
9783 if (err)
9784 return err;
9785
9786 DynamicStoreQueue = dispatch_queue_create("com.apple.mDNSResponder.DynamicStoreQueue", NULL);
9787 if (DynamicStoreQueue == NULL)
9788 {
9789 LogMsg("dispatch_queue_create: DynamicStoreQueue NULL!");
9790 return mStatus_NoMemoryErr;
9791 }
9792
9793 // Store mDNSResponder Platform
9794 if (OSXVers)
9795 {
9796 m->mDNS_plat = platform_OSX;
9797 }
9798 else if (iOSVers)
9799 {
9800 if (IsAppleTV())
9801 m->mDNS_plat = platform_Atv;
9802 else
9803 m->mDNS_plat = platform_iOS;
9804 }
9805 else
9806 {
9807 m->mDNS_plat = platform_NonApple;
9808 }
9809
9810 // In 10.4, mDNSResponder is launched very early in the boot process, while other subsystems are still in the process of starting up.
9811 // If we can't read the user's preferences, then we sleep a bit and try again, for up to five seconds before we give up.
9812 int i;
9813 for (i=0; i<100; i++)
9814 {
9815 domainlabel testlabel;
9816 testlabel.c[0] = 0;
9817 GetUserSpecifiedLocalHostName(&testlabel);
9818 if (testlabel.c[0]) break;
9819 usleep(50000);
9820 }
9821
9822 m->hostlabel.c[0] = 0;
9823
9824 int get_model[2] = { CTL_HW, HW_MODEL };
9825 size_t len_model = sizeof(HINFO_HWstring_buffer);
9826
9827 // Normal Apple model names are of the form "iPhone2,1", and
9828 // internal code names are strings containing no commas, e.g. "N88AP".
9829 // We used to ignore internal code names, but Apple now uses these internal code names
9830 // even in released shipping products, so we no longer ignore strings containing no commas.
9831 // if (sysctl(get_model, 2, HINFO_HWstring_buffer, &len_model, NULL, 0) == 0 && strchr(HINFO_HWstring_buffer, ','))
9832 if (sysctl(get_model, 2, HINFO_HWstring_buffer, &len_model, NULL, 0) == 0)
9833 HINFO_HWstring = HINFO_HWstring_buffer;
9834
9835 // For names of the form "iPhone2,1" we use "iPhone" as the prefix for automatic name generation.
9836 // For names of the form "N88AP" containg no comma, we use the entire string.
9837 HINFO_HWstring_prefixlen = strchr(HINFO_HWstring_buffer, ',') ? strcspn(HINFO_HWstring, "0123456789") : strlen(HINFO_HWstring);
9838
9839 if (mDNSPlatformInit_CanReceiveUnicast())
9840 m->CanReceiveUnicastOn5353 = mDNStrue;
9841
9842 mDNSu32 hlen = mDNSPlatformStrLen(HINFO_HWstring);
9843 mDNSu32 slen = mDNSPlatformStrLen(HINFO_SWstring);
9844 if (hlen + slen < 254)
9845 {
9846 m->HIHardware.c[0] = hlen;
9847 m->HISoftware.c[0] = slen;
9848 mDNSPlatformMemCopy(&m->HIHardware.c[1], HINFO_HWstring, hlen);
9849 mDNSPlatformMemCopy(&m->HISoftware.c[1], HINFO_SWstring, slen);
9850 }
9851
9852 m->p->permanentsockets.port = MulticastDNSPort;
9853 m->p->permanentsockets.m = m;
9854 m->p->permanentsockets.sktv4 = -1;
9855 m->p->permanentsockets.kqsv4.KQcallback = myKQSocketCallBack;
9856 m->p->permanentsockets.kqsv4.KQcontext = &m->p->permanentsockets;
9857 m->p->permanentsockets.kqsv4.KQtask = "UDP packet reception";
9858 m->p->permanentsockets.sktv6 = -1;
9859 m->p->permanentsockets.kqsv6.KQcallback = myKQSocketCallBack;
9860 m->p->permanentsockets.kqsv6.KQcontext = &m->p->permanentsockets;
9861 m->p->permanentsockets.kqsv6.KQtask = "UDP packet reception";
9862
9863 err = SetupSocket(&m->p->permanentsockets, MulticastDNSPort, AF_INET, mDNSNULL);
9864 err = SetupSocket(&m->p->permanentsockets, MulticastDNSPort, AF_INET6, mDNSNULL);
9865
9866 struct sockaddr_in s4;
9867 socklen_t n4 = sizeof(s4);
9868 if (getsockname(m->p->permanentsockets.sktv4, (struct sockaddr *)&s4, &n4) < 0)
9869 LogMsg("getsockname v4 error %d (%s)", errno, strerror(errno));
9870 else
9871 m->UnicastPort4.NotAnInteger = s4.sin_port;
9872
9873 if (m->p->permanentsockets.sktv6 >= 0)
9874 {
9875 struct sockaddr_in6 s6;
9876 socklen_t n6 = sizeof(s6);
9877 if (getsockname(m->p->permanentsockets.sktv6, (struct sockaddr *)&s6, &n6) < 0) LogMsg("getsockname v6 error %d (%s)", errno, strerror(errno));
9878 else m->UnicastPort6.NotAnInteger = s6.sin6_port;
9879 }
9880
9881 m->p->InterfaceList = mDNSNULL;
9882 m->p->userhostlabel.c[0] = 0;
9883 m->p->usernicelabel.c[0] = 0;
9884 m->p->prevoldnicelabel.c[0] = 0;
9885 m->p->prevnewnicelabel.c[0] = 0;
9886 m->p->prevoldhostlabel.c[0] = 0;
9887 m->p->prevnewhostlabel.c[0] = 0;
9888 m->p->NotifyUser = 0;
9889 m->p->KeyChainTimer = 0;
9890 m->p->WakeAtUTC = 0;
9891 m->p->RequestReSleep = 0;
9892 // Assume that everything is good to begin with. If something is not working,
9893 // we will detect that when we start sending questions.
9894 m->p->v4answers = 1;
9895 m->p->v6answers = 1;
9896 m->p->DNSTrigger = 0;
9897 m->p->LastConfigGeneration = 0;
9898
9899 #if APPLE_OSX_mDNSResponder
9900 uuid_generate(m->asl_uuid);
9901 #endif
9902
9903 m->AutoTunnelRelayAddr = zerov6Addr;
9904
9905 NetworkChangedKey_IPv4 = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4);
9906 NetworkChangedKey_IPv6 = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6);
9907 NetworkChangedKey_Hostnames = SCDynamicStoreKeyCreateHostNames(NULL);
9908 NetworkChangedKey_Computername = SCDynamicStoreKeyCreateComputerName(NULL);
9909 NetworkChangedKey_DNS = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetDNS);
9910 NetworkChangedKey_StateInterfacePrefix = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL, kSCDynamicStoreDomainState, CFSTR(""), NULL);
9911 if (!NetworkChangedKey_IPv4 || !NetworkChangedKey_IPv6 || !NetworkChangedKey_Hostnames || !NetworkChangedKey_Computername || !NetworkChangedKey_DNS || !NetworkChangedKey_StateInterfacePrefix)
9912 { LogMsg("SCDynamicStore string setup failed"); return(mStatus_NoMemoryErr); }
9913
9914 err = WatchForNetworkChanges(m);
9915 if (err) { LogMsg("mDNSPlatformInit_setup: WatchForNetworkChanges failed %d", err); return(err); }
9916
9917 #if 0 // <rdar://problem/6751656>
9918 err = WatchForPMChanges(m);
9919 if (err) { LogMsg("mDNSPlatformInit_setup: WatchForPMChanges failed %d", err); return(err); }
9920 #endif
9921
9922 err = WatchForSysEvents(m);
9923 if (err) { LogMsg("mDNSPlatformInit_setup: WatchForSysEvents failed %d", err); return(err); }
9924
9925 mDNSs32 utc = mDNSPlatformUTC();
9926 m->SystemWakeOnLANEnabled = SystemWakeForNetworkAccess();
9927 UpdateInterfaceList(m, utc);
9928 SetupActiveInterfaces(m, utc);
9929
9930 // Explicitly ensure that our Keychain operations utilize the system domain.
9931 #ifndef NO_SECURITYFRAMEWORK
9932 SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
9933 #endif
9934
9935 mDNS_Lock(m);
9936 SetDomainSecrets(m);
9937 SetLocalDomains();
9938 mDNS_Unlock(m);
9939
9940 #ifndef NO_SECURITYFRAMEWORK
9941 err = SecKeychainAddCallback(KeychainChanged, kSecAddEventMask|kSecDeleteEventMask|kSecUpdateEventMask, m);
9942 if (err) { LogMsg("mDNSPlatformInit_setup: SecKeychainAddCallback failed %d", err); return(err); }
9943 #endif
9944
9945 #if !defined(kIOPMAcknowledgmentOptionSystemCapabilityRequirements) || TARGET_OS_EMBEDDED
9946 LogMsg("Note: Compiled without SnowLeopard Fine-Grained Power Management support");
9947 #else
9948 IOPMConnection c;
9949 IOReturn iopmerr = IOPMConnectionCreate(CFSTR("mDNSResponder"), kIOPMSystemPowerStateCapabilityCPU, &c);
9950 if (iopmerr) LogMsg("IOPMConnectionCreate failed %d", iopmerr);
9951 else
9952 {
9953 iopmerr = IOPMConnectionSetNotification(c, m, SnowLeopardPowerChanged);
9954 if (iopmerr) LogMsg("IOPMConnectionSetNotification failed %d", iopmerr);
9955 else
9956 {
9957 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
9958 IOPMConnectionSetDispatchQueue(c, dispatch_get_main_queue());
9959 LogInfo("IOPMConnectionSetDispatchQueue is now running");
9960 #else
9961 iopmerr = IOPMConnectionScheduleWithRunLoop(c, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
9962 if (iopmerr) LogMsg("IOPMConnectionScheduleWithRunLoop failed %d", iopmerr);
9963 LogInfo("IOPMConnectionScheduleWithRunLoop is now running");
9964 #endif /* MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM */
9965 }
9966 }
9967 m->p->IOPMConnection = iopmerr ? mDNSNULL : c;
9968 if (iopmerr) // If IOPMConnectionCreate unavailable or failed, proceed with old-style power notification code below
9969 #endif // kIOPMAcknowledgmentOptionSystemCapabilityRequirements
9970 {
9971 m->p->PowerConnection = IORegisterForSystemPower(m, &m->p->PowerPortRef, PowerChanged, &m->p->PowerNotifier);
9972 if (!m->p->PowerConnection) { LogMsg("mDNSPlatformInit_setup: IORegisterForSystemPower failed"); return(-1); }
9973 else
9974 {
9975 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
9976 IONotificationPortSetDispatchQueue(m->p->PowerPortRef, dispatch_get_main_queue());
9977 #else
9978 CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(m->p->PowerPortRef), kCFRunLoopDefaultMode);
9979 #endif /* MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM */
9980 }
9981 }
9982
9983 #if APPLE_OSX_mDNSResponder
9984 // Note: We use SPMetricPortability > 35 to indicate a laptop of some kind
9985 // SPMetricPortability <= 35 means nominally a non-portable machine (i.e. Mac mini or better)
9986 // Apple TVs, AirPort base stations, and Time Capsules do not actually weigh 3kg, but we assign them
9987 // higher 'nominal' masses to indicate they should be treated as being relatively less portable than a laptop
9988 if (!strncasecmp(HINFO_HWstring, "Xserve", 6)) { SPMetricPortability = 25 /* 30kg */; SPMetricMarginalPower = 84 /* 250W */; SPMetricTotalPower = 85 /* 300W */; }
9989 else if (!strncasecmp(HINFO_HWstring, "RackMac", 7)) { SPMetricPortability = 25 /* 30kg */; SPMetricMarginalPower = 84 /* 250W */; SPMetricTotalPower = 85 /* 300W */; }
9990 else if (!strncasecmp(HINFO_HWstring, "MacPro", 6)) { SPMetricPortability = 27 /* 20kg */; SPMetricMarginalPower = 84 /* 250W */; SPMetricTotalPower = 85 /* 300W */; }
9991 else if (!strncasecmp(HINFO_HWstring, "PowerMac", 8)) { SPMetricPortability = 27 /* 20kg */; SPMetricMarginalPower = 82 /* 160W */; SPMetricTotalPower = 83 /* 200W */; }
9992 else if (!strncasecmp(HINFO_HWstring, "iMac", 4)) { SPMetricPortability = 30 /* 10kg */; SPMetricMarginalPower = 77 /* 50W */; SPMetricTotalPower = 78 /* 60W */; }
9993 else if (!strncasecmp(HINFO_HWstring, "Macmini", 7)) { SPMetricPortability = 33 /* 5kg */; SPMetricMarginalPower = 73 /* 20W */; SPMetricTotalPower = 74 /* 25W */; }
9994 else if (!strncasecmp(HINFO_HWstring, "TimeCapsule", 11)) { SPMetricPortability = 34 /* 4kg */; SPMetricMarginalPower = 10 /* ~0W */; SPMetricTotalPower = 70 /* 13W */; }
9995 else if (!strncasecmp(HINFO_HWstring, "AirPort", 7)) { SPMetricPortability = 35 /* 3kg */; SPMetricMarginalPower = 10 /* ~0W */; SPMetricTotalPower = 70 /* 12W */; }
9996 else if ( IsAppleTV() ) { SPMetricPortability = 35 /* 3kg */; SPMetricMarginalPower = 60 /* 1W */; SPMetricTotalPower = 63 /* 2W */; }
9997 else if (!strncasecmp(HINFO_HWstring, "MacBook", 7)) { SPMetricPortability = 37 /* 2kg */; SPMetricMarginalPower = 71 /* 13W */; SPMetricTotalPower = 72 /* 15W */; }
9998 else if (!strncasecmp(HINFO_HWstring, "PowerBook", 9)) { SPMetricPortability = 37 /* 2kg */; SPMetricMarginalPower = 71 /* 13W */; SPMetricTotalPower = 72 /* 15W */; }
9999 LogSPS("HW_MODEL: %.*s (%s) Portability %d Marginal Power %d Total Power %d Features %d",
10000 HINFO_HWstring_prefixlen, HINFO_HWstring, HINFO_HWstring, SPMetricPortability, SPMetricMarginalPower, SPMetricTotalPower, SPMetricFeatures);
10001 #endif // APPLE_OSX_mDNSResponder
10002
10003 // Currently this is not defined. SSL code will eventually fix this. If it becomes
10004 // critical, we will define this to workaround the bug in SSL.
10005 #ifdef __SSL_NEEDS_SERIALIZATION__
10006 SSLqueue = dispatch_queue_create("com.apple.mDNSResponder.SSLQueue", NULL);
10007 #else
10008 SSLqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
10009 #endif
10010 if (SSLqueue == mDNSNULL) LogMsg("dispatch_queue_create: SSL queue NULL");
10011
10012 mDNSMacOSXUpdateEtcHosts(m);
10013 SetupLocalHostRecords(m);
10014 CUPInit(m);
10015
10016 return(mStatus_NoError);
10017 }
10018
10019 mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
10020 {
10021 #if MDNS_NO_DNSINFO
10022 LogMsg("Note: Compiled without Apple-specific Split-DNS support");
10023 #endif
10024
10025 // Adding interfaces will use this flag, so set it now.
10026 m->DivertMulticastAdvertisements = !m->AdvertiseLocalAddresses;
10027
10028 #if APPLE_OSX_mDNSResponder
10029 m->SPSBrowseCallback = UpdateSPSStatus;
10030 #endif // APPLE_OSX_mDNSResponder
10031
10032 mStatus result = mDNSPlatformInit_setup(m);
10033
10034 // We don't do asynchronous initialization on OS X, so by the time we get here the setup will already
10035 // have succeeded or failed -- so if it succeeded, we should just call mDNSCoreInitComplete() immediately
10036 if (result == mStatus_NoError)
10037 {
10038 mDNSCoreInitComplete(m, mStatus_NoError);
10039
10040 #if !NO_D2D
10041 // We only initialize if mDNSCore successfully initialized.
10042 if (D2DInitialize)
10043 {
10044 D2DStatus ds = D2DInitialize(m->p->CFRunLoop, xD2DServiceCallback, m) ;
10045 if (ds != kD2DSuccess)
10046 LogMsg("D2DInitialiize failed: %d", ds);
10047 else
10048 LogMsg("D2DInitialize succeeded");
10049 }
10050 #endif // ! NO_D2D
10051
10052 }
10053 result = DNSSECCryptoInit(m);
10054 return(result);
10055 }
10056
10057 mDNSexport void mDNSPlatformClose(mDNS *const m)
10058 {
10059 if (m->p->PowerConnection)
10060 {
10061 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
10062 IONotificationPortSetDispatchQueue(m->p->PowerPortRef, NULL);
10063 #else
10064 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(m->p->PowerPortRef), kCFRunLoopDefaultMode);
10065 #endif
10066 // According to <http://developer.apple.com/qa/qa2004/qa1340.html>, a single call
10067 // to IORegisterForSystemPower creates *three* objects that need to be disposed individually:
10068 IODeregisterForSystemPower(&m->p->PowerNotifier);
10069 IOServiceClose ( m->p->PowerConnection);
10070 IONotificationPortDestroy ( m->p->PowerPortRef);
10071 m->p->PowerConnection = 0;
10072 }
10073
10074 if (m->p->Store)
10075 {
10076 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
10077 if (!SCDynamicStoreSetDispatchQueue(m->p->Store, NULL))
10078 LogMsg("mDNSPlatformClose: SCDynamicStoreSetDispatchQueue failed");
10079 #else
10080 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m->p->StoreRLS, kCFRunLoopDefaultMode);
10081 CFRunLoopSourceInvalidate(m->p->StoreRLS);
10082 CFRelease(m->p->StoreRLS);
10083 m->p->StoreRLS = NULL;
10084 #endif
10085 CFRelease(m->p->Store);
10086 m->p->Store = NULL;
10087 }
10088
10089 if (m->p->PMRLS)
10090 {
10091 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m->p->PMRLS, kCFRunLoopDefaultMode);
10092 CFRunLoopSourceInvalidate(m->p->PMRLS);
10093 CFRelease(m->p->PMRLS);
10094 m->p->PMRLS = NULL;
10095 }
10096
10097 if (m->p->SysEventNotifier >= 0) { close(m->p->SysEventNotifier); m->p->SysEventNotifier = -1; }
10098
10099 #if !NO_D2D
10100 if (D2DTerminate)
10101 {
10102 D2DStatus ds = D2DTerminate();
10103 if (ds != kD2DSuccess)
10104 LogMsg("D2DTerminate failed: %d", ds);
10105 else
10106 LogMsg("D2DTerminate succeeded");
10107 }
10108 #endif // ! NO_D2D
10109
10110 mDNSs32 utc = mDNSPlatformUTC();
10111 MarkAllInterfacesInactive(m, utc);
10112 ClearInactiveInterfaces(m, utc);
10113 CloseSocketSet(&m->p->permanentsockets);
10114
10115 #if APPLE_OSX_mDNSResponder
10116 // clean up tunnels
10117 while (m->TunnelClients)
10118 {
10119 ClientTunnel *cur = m->TunnelClients;
10120 LogInfo("mDNSPlatformClose: removing client tunnel %p %##s from list", cur, cur->dstname.c);
10121 if (cur->q.ThisQInterval >= 0) mDNS_StopQuery(m, &cur->q);
10122 AutoTunnelSetKeys(cur, mDNSfalse);
10123 m->TunnelClients = cur->next;
10124 freeL("ClientTunnel", cur);
10125 }
10126
10127 if (AnonymousRacoonConfig)
10128 {
10129 AnonymousRacoonConfig = mDNSNULL;
10130 LogInfo("mDNSPlatformClose: Deconfiguring autotunnel");
10131 (void)mDNSConfigureServer(kmDNSDown, mDNSNULL, mDNSNULL);
10132 }
10133 #endif // APPLE_OSX_mDNSResponder
10134 }
10135
10136 #if COMPILER_LIKES_PRAGMA_MARK
10137 #pragma mark -
10138 #pragma mark - General Platform Support Layer functions
10139 #endif
10140
10141 mDNSexport mDNSu32 mDNSPlatformRandomNumber(void)
10142 {
10143 return(arc4random());
10144 }
10145
10146 mDNSexport mDNSs32 mDNSPlatformOneSecond = 1000;
10147 mDNSexport mDNSu32 mDNSPlatformClockDivisor = 0;
10148
10149 mDNSexport mStatus mDNSPlatformTimeInit(void)
10150 {
10151 // Notes: Typical values for mach_timebase_info:
10152 // tbi.numer = 1000 million
10153 // tbi.denom = 33 million
10154 // These are set such that (mach_absolute_time() * numer/denom) gives us nanoseconds;
10155 // numer / denom = nanoseconds per hardware clock tick (e.g. 30);
10156 // denom / numer = hardware clock ticks per nanosecond (e.g. 0.033)
10157 // (denom*1000000) / numer = hardware clock ticks per millisecond (e.g. 33333)
10158 // So: mach_absolute_time() / ((denom*1000000)/numer) = milliseconds
10159 //
10160 // Arithmetic notes:
10161 // tbi.denom is at least 1, and not more than 2^32-1.
10162 // Therefore (tbi.denom * 1000000) is at least one million, but cannot overflow a uint64_t.
10163 // tbi.denom is at least 1, and not more than 2^32-1.
10164 // Therefore clockdivisor should end up being a number roughly in the range 10^3 - 10^9.
10165 // If clockdivisor is less than 10^3 then that means that the native clock frequency is less than 1MHz,
10166 // which is unlikely on any current or future Macintosh.
10167 // If clockdivisor is greater than 10^9 then that means the native clock frequency is greater than 1000GHz.
10168 // When we ship Macs with clock frequencies above 1000GHz, we may have to update this code.
10169 struct mach_timebase_info tbi;
10170 kern_return_t result = mach_timebase_info(&tbi);
10171 if (result == KERN_SUCCESS) mDNSPlatformClockDivisor = ((uint64_t)tbi.denom * 1000000) / tbi.numer;
10172 return(result);
10173 }
10174
10175 mDNSexport mDNSs32 mDNSPlatformRawTime(void)
10176 {
10177 if (mDNSPlatformClockDivisor == 0) { LogMsg("mDNSPlatformRawTime called before mDNSPlatformTimeInit"); return(0); }
10178
10179 static uint64_t last_mach_absolute_time = 0;
10180 //static uint64_t last_mach_absolute_time = 0x8000000000000000LL; // Use this value for testing the alert display
10181 uint64_t this_mach_absolute_time = mach_absolute_time();
10182 if ((int64_t)this_mach_absolute_time - (int64_t)last_mach_absolute_time < 0)
10183 {
10184 LogMsg("mDNSPlatformRawTime: last_mach_absolute_time %08X%08X", last_mach_absolute_time);
10185 LogMsg("mDNSPlatformRawTime: this_mach_absolute_time %08X%08X", this_mach_absolute_time);
10186 // Update last_mach_absolute_time *before* calling NotifyOfElusiveBug()
10187 last_mach_absolute_time = this_mach_absolute_time;
10188 // Note: This bug happens all the time on 10.3
10189 NotifyOfElusiveBug("mach_absolute_time went backwards!",
10190 "This error occurs from time to time, often on newly released hardware, "
10191 "and usually the exact cause is different in each instance.\r\r"
10192 "Please file a new Radar bug report with the title “mach_absolute_time went backwards” "
10193 "and assign it to Radar Component “Kernel” Version “X”.");
10194 }
10195 last_mach_absolute_time = this_mach_absolute_time;
10196
10197 return((mDNSs32)(this_mach_absolute_time / mDNSPlatformClockDivisor));
10198 }
10199
10200 mDNSexport mDNSs32 mDNSPlatformUTC(void)
10201 {
10202 return time(NULL);
10203 }
10204
10205 // Locking is a no-op here, because we're single-threaded with a CFRunLoop, so we can never interrupt ourselves
10206 mDNSexport void mDNSPlatformLock (const mDNS *const m) { (void)m; }
10207 mDNSexport void mDNSPlatformUnlock (const mDNS *const m) { (void)m; }
10208 mDNSexport void mDNSPlatformStrCopy( void *dst, const void *src) { strcpy((char *)dst, (char *)src); }
10209 mDNSexport mDNSu32 mDNSPlatformStrLen ( const void *src) { return(strlen((char*)src)); }
10210 mDNSexport void mDNSPlatformMemCopy( void *dst, const void *src, mDNSu32 len) { memcpy(dst, src, len); }
10211 mDNSexport mDNSBool mDNSPlatformMemSame(const void *dst, const void *src, mDNSu32 len) { return(memcmp(dst, src, len) == 0); }
10212 mDNSexport int mDNSPlatformMemCmp(const void *dst, const void *src, mDNSu32 len) { return(memcmp(dst, src, len)); }
10213 mDNSexport void mDNSPlatformMemZero( void *dst, mDNSu32 len) { memset(dst, 0, len); }
10214 mDNSexport void mDNSPlatformQsort ( void *base, int nel, int width, int (*compar)(const void *, const void *))
10215 {
10216 return (qsort(base, nel, width, compar));
10217 }
10218 #if !(APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING)
10219 mDNSexport void * mDNSPlatformMemAllocate(mDNSu32 len) { return(mallocL("mDNSPlatformMemAllocate", len)); }
10220 #endif
10221 mDNSexport void mDNSPlatformMemFree (void *mem) { freeL("mDNSPlatformMemFree", mem); }
10222
10223 mDNSexport void mDNSPlatformSetAllowSleep(mDNS *const m, mDNSBool allowSleep, const char *reason)
10224 {
10225 if (allowSleep && m->p->IOPMAssertion)
10226 {
10227 LogInfo("%s Destroying NoIdleSleep power assertion", __FUNCTION__);
10228 IOPMAssertionRelease(m->p->IOPMAssertion);
10229 m->p->IOPMAssertion = 0;
10230 }
10231 else if (!allowSleep)
10232 {
10233 #ifdef kIOPMAssertionTypeNoIdleSleep
10234 if (m->p->IOPMAssertion)
10235 {
10236 IOPMAssertionRelease(m->p->IOPMAssertion);
10237 m->p->IOPMAssertion = 0;
10238 }
10239
10240 CFStringRef assertionName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%s.%d %s"), getprogname(), getpid(), reason ? reason : "");
10241 IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, assertionName ? assertionName : CFSTR("mDNSResponder"), &m->p->IOPMAssertion);
10242 if (assertionName) CFRelease(assertionName);
10243 LogInfo("%s Creating NoIdleSleep power assertion", __FUNCTION__);
10244 #endif
10245 }
10246 }
10247
10248 mDNSexport void mDNSPlatformSendWakeupPacket(mDNS *const m, mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration)
10249 {
10250 mDNSu32 ifindex;
10251
10252 // Sanity check
10253 ifindex = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10254 if (ifindex <= 0)
10255 {
10256 LogMsg("mDNSPlatformSendWakeupPacket: ERROR!! Invalid InterfaceID %u", ifindex);
10257 return;
10258 }
10259 mDNSSendWakeupPacket(ifindex, EthAddr, IPAddr, iteration);
10260 }
10261
10262 mDNSexport mDNSBool mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID)
10263 {
10264 NetworkInterfaceInfoOSX *info;
10265
10266 if (InterfaceID == mDNSInterface_P2P)
10267 return mDNStrue;
10268
10269 if ( (InterfaceID == mDNSInterface_Any)
10270 || (InterfaceID == mDNSInterfaceMark)
10271 || (InterfaceID == mDNSInterface_LocalOnly)
10272 || (InterfaceID == mDNSInterface_Unicast))
10273 return mDNSfalse;
10274
10275 info = IfindexToInterfaceInfoOSX(&mDNSStorage, InterfaceID);
10276 if (info == NULL)
10277 {
10278 // this log message can print when operations are stopped on an interface that has gone away
10279 LogInfo("mDNSPlatformInterfaceIsD2D: Invalid interface index %d", InterfaceID);
10280 return mDNSfalse;
10281 }
10282
10283 return (mDNSBool) info->D2DInterface;
10284 }
10285
10286 // Filter records send over P2P (D2D) type interfaces
10287 // Note that the terms P2P and D2D are used synonymously in the current code and comments.
10288 mDNSexport mDNSBool mDNSPlatformValidRecordForInterface(AuthRecord *rr, const NetworkInterfaceInfo *intf)
10289 {
10290 // For an explicit match to a valid interface ID, return true.
10291 if (rr->resrec.InterfaceID == intf->InterfaceID)
10292 return mDNStrue;
10293
10294 // Only filtering records for D2D type interfaces, return true for all other interface types.
10295 if (!mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
10296 return mDNStrue;
10297
10298 // If it's an AWDL interface the record must be explicitly marked to include AWDL.
10299 if (intf->InterfaceID == AWDLInterfaceID)
10300 {
10301 if (rr->ARType == AuthRecordAnyIncludeAWDL || rr->ARType == AuthRecordAnyIncludeAWDLandP2P)
10302 return mDNStrue;
10303 else
10304 return mDNSfalse;
10305 }
10306
10307 // Send record if it is explicitly marked to include all other P2P type interfaces.
10308 if (rr->ARType == AuthRecordAnyIncludeP2P || rr->ARType == AuthRecordAnyIncludeAWDLandP2P)
10309 return mDNStrue;
10310
10311 // Don't send the record over this interface.
10312 return mDNSfalse;
10313 }
10314
10315 // Filter questions send over P2P (D2D) type interfaces.
10316 mDNSexport mDNSBool mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf)
10317 {
10318 // For an explicit match to a valid interface ID, return true.
10319 if (q->InterfaceID == intf->InterfaceID)
10320 return mDNStrue;
10321
10322 // Only filtering questions for D2D type interfaces
10323 if (!mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
10324 return mDNStrue;
10325
10326 // If it's an AWDL interface the question must be explicitly marked to include AWDL.
10327 if (intf->InterfaceID == AWDLInterfaceID)
10328 {
10329 if (q->flags & kDNSServiceFlagsIncludeAWDL)
10330 return mDNStrue;
10331 else
10332 return mDNSfalse;
10333 }
10334
10335 // Sent question if it is explicitly marked to include all other P2P type interfaces.
10336 if (q->flags & kDNSServiceFlagsIncludeP2P)
10337 return mDNStrue;
10338
10339 // Don't send the question over this interface.
10340 return mDNSfalse;
10341 }
10342
10343 // Returns true unless record was received over the AWDL interface and
10344 // the question was not specific to the AWDL interface or did not specify kDNSServiceInterfaceIndexAny
10345 // with the kDNSServiceFlagsIncludeAWDL flag set.
10346 mDNSexport mDNSBool mDNSPlatformValidRecordForQuestion(const ResourceRecord *const rr, const DNSQuestion *const q)
10347 {
10348 if (!rr->InterfaceID || (rr->InterfaceID == q->InterfaceID))
10349 return mDNStrue;
10350
10351 if ((rr->InterfaceID == AWDLInterfaceID) && !(q->flags & kDNSServiceFlagsIncludeAWDL))
10352 {
10353 LogInfo("mDNSPlatformValidRecordForQuestion: Record recieved over AWDL not returned for %s %##s query",
10354 DNSTypeName(q->qtype), q->qname.c);
10355 return mDNSfalse;
10356 }
10357
10358 return mDNStrue;
10359 }
10360
10361 // formating time to RFC 4034 format
10362 mDNSexport void mDNSPlatformFormatTime(unsigned long te, mDNSu8 *buf, int bufsize)
10363 {
10364 struct tm tmTime;
10365 time_t t = (time_t)te;
10366 // Time since epoch : strftime takes "tm". Convert seconds to "tm" using
10367 // gmtime_r first and then use strftime
10368 gmtime_r(&t, &tmTime);
10369 strftime((char *)buf, bufsize, "%Y%m%d%H%M%S", &tmTime);
10370 }
10371
10372 mDNSexport mDNSs32 mDNSPlatformGetPID()
10373 {
10374 return getpid();
10375 }
10376
10377 // Schedule a function asynchronously on the main queue
10378 mDNSexport void mDNSPlatformDispatchAsync(mDNS *const m, void *context, AsyncDispatchFunc func)
10379 {
10380 // KQueueLock/Unlock is used for two purposes
10381 //
10382 // 1. We can't be running along with the KQueue thread and hence acquiring the lock
10383 // serializes the access to the "core"
10384 //
10385 // 2. KQueueUnlock also sends a message wake up the KQueue thread which in turn wakes
10386 // up and calls udsserver_idle which schedules the messages across the uds socket.
10387 // If "func" delivers something to the uds socket from the dispatch thread, it will
10388 // not be delivered immediately if not for the Unlock.
10389 dispatch_async(dispatch_get_main_queue(), ^{
10390 KQueueLock(m);
10391 func(m, context);
10392 KQueueUnlock(m, "mDNSPlatformDispatchAsync");
10393 #ifdef MDNSRESPONDER_USES_LIB_DISPATCH_AS_PRIMARY_EVENT_LOOP_MECHANISM
10394 // KQueueUnlock is a noop. Hence, we need to run kick off the idle loop
10395 // to handle any message that "func" might deliver.
10396 TriggerEventCompletion();
10397 #endif
10398 });
10399 }
10400
10401 // definitions for device-info record construction
10402 #define DEVINFO_MODEL "model="
10403 #define DEVINFO_MODEL_LEN strlen(DEVINFO_MODEL)
10404
10405 #define OSX_VER "osxvers="
10406 #define OSX_VER_LEN strlen(OSX_VER)
10407 #define VER_NUM_LEN 2 // 2 digits of version number added to base string
10408
10409 // Bytes available in TXT record for model name after subtracting space for other
10410 // fixed size strings and their length bytes.
10411 #define MAX_MODEL_NAME_LEN (256 - (DEVINFO_MODEL_LEN + 1) - (OSX_VER_LEN + VER_NUM_LEN + 1))
10412
10413 // Initialize device-info TXT record contents and return total length of record data.
10414 mDNSexport mDNSu32 initializeDeviceInfoTXT(mDNS *m, mDNSu8 *ptr)
10415 {
10416 mDNSu8 *bufferStart = ptr;
10417 mDNSu8 len = m->HIHardware.c[0] < MAX_MODEL_NAME_LEN ? m->HIHardware.c[0] : MAX_MODEL_NAME_LEN;
10418
10419 *ptr = DEVINFO_MODEL_LEN + len; // total length of DEVINFO_MODEL string plus the hardware name string
10420 ptr++;
10421 mDNSPlatformMemCopy(ptr, DEVINFO_MODEL, DEVINFO_MODEL_LEN);
10422 ptr += DEVINFO_MODEL_LEN;
10423 mDNSPlatformMemCopy(ptr, m->HIHardware.c + 1, len);
10424 ptr += len;
10425
10426 // only include this string for OSX
10427 if (OSXVers)
10428 {
10429 char ver_num[VER_NUM_LEN + 1]; // version digits + null written by snprintf
10430 *ptr = OSX_VER_LEN + VER_NUM_LEN; // length byte
10431 ptr++;
10432 mDNSPlatformMemCopy(ptr, OSX_VER, OSX_VER_LEN);
10433 ptr += OSX_VER_LEN;
10434 // convert version number to ASCII, add 1 for terminating null byte written by snprintf()
10435 snprintf(ver_num, VER_NUM_LEN + 1, "%d", OSXVers);
10436 mDNSPlatformMemCopy(ptr, ver_num, VER_NUM_LEN);
10437 ptr += VER_NUM_LEN;
10438 }
10439
10440 return (ptr - bufferStart);
10441 }