1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*- 2 * 3 * Copyright (c) 2002-2024 Apple Inc. All rights reserved. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * https://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 * This code is completely 100% portable C. It does not depend on any external header files 18 * from outside the mDNS project -- all the types it expects to find are defined right here. 19 * 20 * The previous point is very important: This file does not depend on any external 21 * header files. It should compile on *any* platform that has a C compiler, without 22 * making *any* assumptions about availability of so-called "standard" C functions, 23 * routines, or types (which may or may not be present on any given platform). 24 */ 25 26 #include "DNSCommon.h" // Defines general DNS utility routines 27 #include "uDNS.h" // Defines entry points into unicast-specific routines 28 #include <sys/time.h> // For gettimeofday(). 29 30 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 31 #include "D2D.h" 32 #endif 33 34 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS) 35 #include "SymptomReporter.h" 36 #endif 37 38 #if MDNSRESPONDER_SUPPORTS(APPLE, TRACKER_STATE) 39 #include "resolved_cache.h" 40 #endif 41 42 #if MDNSRESPONDER_SUPPORTS(APPLE, ANALYTICS) 43 #include "dnssd_analytics.h" 44 #endif 45 46 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 47 #include "dns_push_discovery.h" 48 #include "dns_push_mdns_core.h" 49 #endif 50 51 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 52 #include "QuerierSupport.h" 53 #endif 54 55 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 56 #include "misc_utilities.h" 57 #include "unicast_assist_cache.h" 58 #endif 59 60 // Disable certain benign warnings with Microsoft compilers 61 #if (defined(_MSC_VER)) 62 // Disable "conditional expression is constant" warning for debug macros. 63 // Otherwise, this generates warnings for the perfectly natural construct "while(1)" 64 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know 65 #pragma warning(disable:4127) 66 67 // Disable "assignment within conditional expression". 68 // Other compilers understand the convention that if you place the assignment expression within an extra pair 69 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary. 70 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal 71 // to the compiler that the assignment is intentional, we have to just turn this warning off completely. 72 #pragma warning(disable:4706) 73 #endif 74 75 #include "bsd_queue.h" 76 #include "CommonServices.h" 77 #include "dns_sd.h" // for kDNSServiceFlags* definitions 78 #include "dns_sd_internal.h" 79 80 81 #ifndef MDNS_LOG_ANSWER_SUPPRESSION_TIMES 82 #define MDNS_LOG_ANSWER_SUPPRESSION_TIMES 0 83 #endif 84 85 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER) 86 #include <WebFilterDNS/WebFilterDNS.h> 87 88 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import)); 89 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import)); 90 #endif 91 92 #if MDNSRESPONDER_SUPPORTS(APPLE, RUNTIME_MDNS_METRICS) 93 #include <CoreAnalytics/CoreAnalytics.h> 94 #endif 95 96 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_ANALYTICS) 97 #include "dnssd_analytics.h" 98 #endif 99 100 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) 101 #include "DNS64.h" 102 #endif 103 104 105 #if MDNSRESPONDER_SUPPORTS(COMMON, LOCAL_DNS_RESOLVER_DISCOVERY) 106 #include "discover_resolver.h" // For resolver_discovery_process(). 107 #include "tls-keychain.h" 108 #endif 109 110 #include "mdns_strict.h" 111 112 // Forward declarations 113 extern mDNS mDNSStorage; // NOLINT(misc-uninitialized-record-variable): Initialized by mDNS_InitStorage(). 114 mDNSlocal void BeginSleepProcessing(mDNS *const m); 115 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 116 mDNSlocal void RetrySPSRegistrations(mDNS *const m); 117 #endif 118 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly); 119 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 120 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q); 121 #endif 122 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q); 123 mDNSlocal void mDNS_SendKeepalives(mDNS *const m); 124 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, 125 mDNSu32 *seq, mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win); 126 127 typedef mDNSu32 DeadvertiseFlags; 128 #define kDeadvertiseFlag_NormalHostname (1U << 0) 129 #define kDeadvertiseFlag_RandHostname (1U << 1) 130 #define kDeadvertiseFlag_All (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname) 131 132 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags); 133 mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set); 134 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth); 135 136 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 137 typedef mdns_dns_service_t DNSServRef; 138 #else 139 typedef DNSServer *DNSServRef; 140 #endif 141 142 mDNSlocal void MakeNegativeCacheRecord(mDNS *m, CacheRecord *cr, const domainname *name, mDNSu32 namehash, mDNSu16 rrtype, 143 mDNSu16 rrclass, mDNSu32 ttl, mDNSInterfaceID InterfaceID, DNSServRef dnsserv, mDNSOpaque16 responseFlags); 144 145 mDNSlocal mStatus mDNS_SetUpDomainEnumeration(mDNS *m, DomainEnumerationOp *op, mDNS_DomainType type); 146 147 // *************************************************************************** 148 // MARK: - Program Constants 149 150 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it 151 #define MDNS_TRACER 1 152 153 // Any records bigger than this are considered 'large' records 154 #define SmallRecordLimit 1024 155 156 #define kMaxUpdateCredits 10 157 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6) 158 159 // define special NR_AnswerTo values 160 #define NR_AnswerMulticast (mDNSu8*)~0 161 #define NR_AnswerUnicast (mDNSu8*)~1 162 163 // Question default timeout values 164 #define DEFAULT_MCAST_TIMEOUT 5 165 #define DEFAULT_LO_OR_P2P_TIMEOUT 5 166 167 // The code (see SendQueries() and BuildQuestion()) needs to have the 168 // RequestUnicast value set to a value one greater than the number of times you want the query 169 // sent with the "request unicast response" (QU) bit set. 170 #define SET_QU_IN_FIRST_QUERY 2 171 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY 172 173 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification 174 #define DARK_WAKE_DELAY_SLEEP 5 175 #define kDarkWakeDelaySleep (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP) 176 177 struct TSRDataRec { 178 SLIST_ENTRY(TSRDataRec) entries; 179 TSROptData tsr; 180 domainname name; 181 }; 182 typedef SLIST_HEAD(, TSRDataRec) TSRDataRecHead; 183 mDNSlocal struct TSRDataRec *TSRDataRecCreate(const DNSMessage *const msg, const mDNSu8 *ptr, const mDNSu8 *const end, 184 const rdataOPT * const opt) 185 { 186 domainname name; 187 const mDNSu8 *next_ptr; 188 struct TSRDataRec *rec = mDNSNULL; 189 190 next_ptr = getDomainName(msg, ptr, end, &name); 191 mdns_require_action_quiet(next_ptr, exit, 192 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 193 "TSRDataRecCreate: Bad RR domain name for TSR - tsrTime %d tsrHost %x recIndex %u", 194 opt->u.tsr.timeStamp, opt->u.tsr.hostkeyHash, opt->u.tsr.recIndex)); 195 196 rec = (struct TSRDataRec *)mDNSPlatformMemAllocateClear(sizeof(*rec)); 197 mdns_require_quiet(rec, exit); 198 199 AssignDomainName(&rec->name, &name); 200 mDNSPlatformMemCopy(&rec->tsr, &opt->u.tsr, sizeof(TSROptData)); 201 exit: 202 return rec; 203 } 204 mDNSlocal void TSRDataRecHeadFreeList(TSRDataRecHead *tsrHead) 205 { 206 mdns_require_quiet(tsrHead, exit); 207 while (!SLIST_EMPTY(tsrHead)) { 208 struct TSRDataRec *next = SLIST_FIRST(tsrHead); 209 SLIST_REMOVE_HEAD(tsrHead, entries); 210 mDNSPlatformMemFree(next); 211 } 212 exit: 213 return; 214 } 215 216 struct TSRDataPtrRec { 217 SLIST_ENTRY(TSRDataPtrRec) entries; 218 const TSROptData *tsr; 219 const domainname *name; 220 }; 221 typedef SLIST_HEAD(, TSRDataPtrRec) TSRDataPtrRecHead; 222 mDNSlocal mDNSBool TSRDataRecPtrHeadAddTSROpt(TSRDataPtrRecHead * const tsrHead, TSROptData * const tsrOpt, 223 const domainname * const name, mDNSu16 index) 224 { 225 struct TSRDataPtrRec *rec = (struct TSRDataPtrRec *)mDNSPlatformMemAllocateClear(sizeof(*rec)); 226 mdns_require_quiet(rec, exit); 227 228 tsrOpt->recIndex = index; 229 rec->tsr = tsrOpt; 230 rec->name = name; 231 SLIST_INSERT_HEAD(tsrHead, rec, entries); 232 return mDNStrue; 233 234 exit: 235 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 236 "TSRDataRecPtrHeadAddRec: Alloc TSRDataPtrRec failed " PRI_DM_NAME " index %u", DM_NAME_PARAM(name), index); 237 return mDNSfalse; 238 } 239 mDNSlocal void TSRDataRecPtrHeadRemoveAndFreeFirst(TSRDataPtrRecHead *tsrHead) 240 { 241 mdns_require_quiet(tsrHead, exit); 242 243 struct TSRDataPtrRec *first = SLIST_FIRST(tsrHead); 244 SLIST_REMOVE_HEAD(tsrHead, entries); 245 mdns_require_quiet(first, exit); 246 247 mDNSPlatformMemFree(first); 248 exit: 249 return; 250 } 251 mDNSlocal void TSRDataRecPtrHeadFreeList(TSRDataPtrRecHead *tsrHead) 252 { 253 mdns_require_quiet(tsrHead, exit); 254 while (!SLIST_EMPTY(tsrHead)) { 255 TSRDataRecPtrHeadRemoveAndFreeFirst(tsrHead); 256 } 257 exit: 258 return; 259 } 260 261 // RFC 6762 defines Passive Observation Of Failures (POOF) 262 // 263 // A host observes the multicast queries issued by the other hosts on 264 // the network. One of the major benefits of also sending responses 265 // using multicast is that it allows all hosts to see the responses 266 // (or lack thereof) to those queries. 267 // 268 // If a host sees queries, for which a record in its cache would be 269 // expected to be given as an answer in a multicast response, but no 270 // such answer is seen, then the host may take this as an indication 271 // that the record may no longer be valid. 272 // 273 // After seeing two or more of these queries, and seeing no multicast 274 // response containing the expected answer within ten seconds, then even 275 // though its TTL may indicate that it is not yet due to expire, that 276 // record SHOULD be flushed from the cache. 277 // 278 // <https://tools.ietf.org/html/rfc6762#section-10.5> 279 280 #define POOF_ENABLED 1 281 282 mDNSexport const char *const mDNS_DomainTypeNames[] = 283 { 284 "b._dns-sd._udp.", // Browse 285 "db._dns-sd._udp.", // Default Browse 286 "lb._dns-sd._udp.", // Automatic Browse 287 "r._dns-sd._udp.", // Registration 288 "dr._dns-sd._udp." // Default Registration 289 }; 290 291 #ifdef UNICAST_DISABLED 292 #define uDNS_IsActiveQuery(q, u) mDNSfalse 293 #endif 294 295 // *************************************************************************** 296 // MARK: - General Utility Functions 297 298 #if MDNS_MALLOC_DEBUGGING 299 // When doing memory allocation debugging, this function traverses all lists in the mDNS query 300 // structures and caches and checks each entry in the list to make sure it's still good. 301 mDNSlocal void mDNS_ValidateLists(void *context) 302 { 303 mDNS *m = context; 304 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 305 mDNSu32 NumAllInterfaceRecords = 0; 306 mDNSu32 NumAllInterfaceQuestions = 0; 307 #endif 308 309 // Check core mDNS lists 310 AuthRecord *rr; 311 for (rr = m->ResourceRecords; rr; rr=rr->next) 312 { 313 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF) 314 LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType); 315 if (rr->resrec.name != &rr->namestorage) 316 LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s", 317 rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c); 318 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 319 if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++; 320 #endif 321 } 322 323 for (rr = m->DuplicateRecords; rr; rr=rr->next) 324 { 325 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF) 326 LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType); 327 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 328 if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++; 329 #endif 330 } 331 332 rr = m->NewLocalRecords; 333 if (rr) 334 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF) 335 LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr, rr->resrec.RecordType); 336 337 rr = m->CurrentRecord; 338 if (rr) 339 if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF) 340 LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr, rr->resrec.RecordType); 341 342 DNSQuestion *q; 343 for (q = m->Questions; q; q=q->next) 344 { 345 if (q->next == (DNSQuestion*)~0 || q->ThisQInterval == (mDNSs32) ~0) 346 LogMemCorruption("Questions list: %p is garbage (%lX %p)", q, q->ThisQInterval, q->next); 347 if (q->DuplicateOf && q->LocalSocket) 348 LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype)); 349 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 350 if (!LocalOnlyOrP2PInterface(q->InterfaceID) && mDNSOpaque16IsZero(q->TargetQID)) 351 NumAllInterfaceQuestions++; 352 #endif 353 } 354 355 CacheGroup *cg; 356 CacheRecord *cr; 357 mDNSu32 slot; 358 FORALL_CACHERECORDS(slot, cg, cr) 359 { 360 if (cr->resrec.RecordType == 0 || cr->resrec.RecordType == 0xFF) 361 LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot, cr, cr->resrec.RecordType); 362 if (cr->CRActiveQuestion) 363 { 364 for (q = m->Questions; q; q=q->next) if (q == cr->CRActiveQuestion) break; 365 if (!q) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot, cr->CRActiveQuestion, CRDisplayString(m, cr)); 366 } 367 } 368 369 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 370 if (m->NumAllInterfaceRecords != NumAllInterfaceRecords) 371 LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m->NumAllInterfaceRecords, NumAllInterfaceRecords); 372 373 if (m->NumAllInterfaceQuestions != NumAllInterfaceQuestions) 374 LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m->NumAllInterfaceQuestions, NumAllInterfaceQuestions); 375 #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 376 } 377 #endif // MDNS_MALLOC_DEBUGGING 378 379 // Returns true if this is a unique, authoritative LocalOnly record that answers questions of type 380 // A, AAAA , CNAME, or PTR. The caller should answer the question with this record and not send out 381 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true. 382 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost. 383 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \ 384 (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \ 385 ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \ 386 (rr)->resrec.rrtype == kDNSType_CNAME || \ 387 (rr)->resrec.rrtype == kDNSType_PTR)) 388 389 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q) 390 { 391 mDNS_CheckLock(m); 392 393 if (m->NextScheduledStopTime - q->StopTime > 0) 394 m->NextScheduledStopTime = q->StopTime; 395 } 396 397 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q) 398 { 399 mDNS_CheckLock(m); 400 401 if (ActiveQuestion(q)) 402 { 403 // Depending on whether this is a multicast or unicast question we want to set either: 404 // m->NextScheduledQuery = NextQSendTime(q) or 405 // m->NextuDNSEvent = NextQSendTime(q) 406 mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent; 407 if (*timer - NextQSendTime(q) > 0) 408 *timer = NextQSendTime(q); 409 } 410 } 411 412 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e) 413 { 414 #if MDNS_MALLOC_DEBUGGING >= 1 415 unsigned int i; 416 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF; 417 #endif 418 e->next = r->rrauth_free; 419 r->rrauth_free = e; 420 r->rrauth_totalused--; 421 } 422 423 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp) 424 { 425 AuthEntity *e = (AuthEntity *)(*cp); 426 LogMsg("ReleaseAuthGroup: Releasing AuthGroup %##s", (*cp)->name->c); 427 if ((*cp)->rrauth_tail != &(*cp)->members) 428 LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)"); 429 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name); 430 (*cp)->name = mDNSNULL; 431 *cp = (*cp)->next; // Cut record from list 432 ReleaseAuthEntity(r, e); 433 } 434 435 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG) 436 { 437 AuthEntity *e = mDNSNULL; 438 439 if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); } 440 r->rrauth_lock = 1; 441 442 if (!r->rrauth_free) 443 { 444 // We allocate just one AuthEntity at a time because we need to be able 445 // free them all individually which normally happens when we parse /etc/hosts into 446 // AuthHash where we add the "new" entries and discard (free) the already added 447 // entries. If we allocate as chunks, we can't free them individually. 448 AuthEntity *storage = (AuthEntity *) mDNSPlatformMemAllocateClear(sizeof(*storage)); 449 storage->next = mDNSNULL; 450 r->rrauth_free = storage; 451 } 452 453 // If we still have no free records, recycle all the records we can. 454 // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass. 455 if (!r->rrauth_free) 456 { 457 mDNSu32 oldtotalused = r->rrauth_totalused; 458 mDNSu32 slot; 459 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++) 460 { 461 AuthGroup **cp = &r->rrauth_hash[slot]; 462 while (*cp) 463 { 464 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next; 465 else ReleaseAuthGroup(r, cp); 466 } 467 } 468 LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d", 469 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused); 470 } 471 472 if (r->rrauth_free) // If there are records in the free list, take one 473 { 474 e = r->rrauth_free; 475 r->rrauth_free = e->next; 476 if (++r->rrauth_totalused >= r->rrauth_report) 477 { 478 LogInfo("RR Auth now using %ld objects", r->rrauth_totalused); 479 if (r->rrauth_report < 100) r->rrauth_report += 10; 480 else if (r->rrauth_report < 1000) r->rrauth_report += 100; 481 else r->rrauth_report += 1000; 482 } 483 mDNSPlatformMemZero(e, sizeof(*e)); 484 } 485 486 r->rrauth_lock = 0; 487 488 return(e); 489 } 490 491 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 namehash, const domainname *const name) 492 { 493 AuthGroup *ag; 494 const mDNSu32 slot = namehash % AUTH_HASH_SLOTS; 495 496 for (ag = r->rrauth_hash[slot]; ag; ag=ag->next) 497 if (ag->namehash == namehash && SameDomainName(ag->name, name)) 498 break; 499 return(ag); 500 } 501 502 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const ResourceRecord *const rr) 503 { 504 return(AuthGroupForName(r, rr->namehash, rr->name)); 505 } 506 507 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const ResourceRecord *const rr) 508 { 509 mDNSu16 namelen = DomainNameLength(rr->name); 510 AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL); 511 const mDNSu32 slot = rr->namehash % AUTH_HASH_SLOTS; 512 if (!ag) 513 { 514 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "GetAuthGroup: Failed to allocate memory for " PRI_DM_NAME, DM_NAME_PARAM(rr->name)); 515 return(mDNSNULL); 516 } 517 ag->next = r->rrauth_hash[slot]; 518 ag->namehash = rr->namehash; 519 ag->members = mDNSNULL; 520 ag->rrauth_tail = &ag->members; 521 ag->NewLocalOnlyRecords = mDNSNULL; 522 if (namelen > sizeof(ag->namestorage)) 523 ag->name = (domainname *) mDNSPlatformMemAllocate(namelen); 524 else 525 ag->name = (domainname*)ag->namestorage; 526 if (!ag->name) 527 { 528 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "GetAuthGroup: Failed to allocate name storage for " PRI_DM_NAME, DM_NAME_PARAM(rr->name)); 529 ReleaseAuthEntity(r, (AuthEntity*)ag); 530 return(mDNSNULL); 531 } 532 AssignDomainName(ag->name, rr->name); 533 534 if (AuthGroupForRecord(r, rr)) 535 { 536 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "GetAuthGroup: Already have AuthGroup for " PRI_DM_NAME, DM_NAME_PARAM(rr->name)); 537 } 538 r->rrauth_hash[slot] = ag; 539 if (AuthGroupForRecord(r, rr) != ag) 540 { 541 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "GetAuthGroup: Not finding AuthGroup for " PRI_DM_NAME, DM_NAME_PARAM(rr->name)); 542 } 543 544 return(ag); 545 } 546 547 // Returns the AuthGroup in which the AuthRecord was inserted 548 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr) 549 { 550 AuthGroup *ag; 551 552 (void)m; 553 ag = AuthGroupForRecord(r, &rr->resrec); 554 if (!ag) ag = GetAuthGroup(r, &rr->resrec); // If we don't have a AuthGroup for this name, make one now 555 if (ag) 556 { 557 *(ag->rrauth_tail) = rr; // Append this record to tail of cache slot list 558 ag->rrauth_tail = &(rr->next); // Advance tail pointer 559 } 560 return ag; 561 } 562 563 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr) 564 { 565 AuthGroup *a; 566 AuthRecord **rp; 567 568 a = AuthGroupForRecord(r, &rr->resrec); 569 if (!a) 570 { 571 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "RemoveAuthRecord: ERROR!! AuthGroup not found for " PRI_S, ARDisplayString(m, rr)); 572 return mDNSNULL; 573 } 574 rp = &a->members; 575 while (*rp) 576 { 577 if (*rp != rr) 578 rp=&(*rp)->next; 579 else 580 { 581 // We don't break here, so that we can set the tail below without tracking "prev" pointers 582 583 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "RemoveAuthRecord: removing auth record " PRI_S " from table", ARDisplayString(m, rr)); 584 *rp = (*rp)->next; // Cut record from list 585 } 586 } 587 // TBD: If there are no more members, release authgroup ? 588 a->rrauth_tail = rp; 589 return a; 590 } 591 592 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 namehash, const domainname *const name) 593 { 594 CacheGroup *cg; 595 mDNSu32 slot = HashSlotFromNameHash(namehash); 596 for (cg = m->rrcache_hash[slot]; cg; cg=cg->next) 597 if (cg->namehash == namehash && SameDomainName(cg->name, name)) 598 break; 599 return(cg); 600 } 601 602 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const ResourceRecord *const rr) 603 { 604 return(CacheGroupForName(m, rr->namehash, rr->name)); 605 } 606 607 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr) 608 { 609 NetworkInterfaceInfo *intf; 610 611 if (addr->type == mDNSAddrType_IPv4) 612 { 613 // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception 614 for (intf = m->HostInterfaces; intf; intf = intf->next) 615 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx) 616 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0) 617 return(mDNStrue); 618 } 619 620 if (addr->type == mDNSAddrType_IPv6) 621 { 622 for (intf = m->HostInterfaces; intf; intf = intf->next) 623 if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx) 624 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) && 625 (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) && 626 (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) && 627 (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0)) 628 return(mDNStrue); 629 } 630 631 return(mDNSfalse); 632 } 633 634 mDNSlocal mDNSBool FollowCNAME(const DNSQuestion *const q, const ResourceRecord *const rr, const QC_result qcResult) 635 { 636 // Do not follow CNAME if it is a remove event. 637 if (qcResult == QC_rmv) 638 { 639 return mDNSfalse; 640 } 641 642 // Do not follow CNAME if the question asks for CNAME record. 643 if (q->qtype == kDNSType_CNAME) 644 { 645 return mDNSfalse; 646 } 647 648 // Do not follow CNAME if the record is not a CNAME record. 649 if (rr->rrtype != kDNSType_CNAME) 650 { 651 return mDNSfalse; 652 } 653 654 // Do not follow CNAME if the record is a negative record, which means CNAME does not exist. 655 if (rr->RecordType == kDNSRecordTypePacketNegative) 656 { 657 return mDNSfalse; 658 } 659 660 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 661 // Only follow the CNAME if: 662 // 1. The question is not DNSSEC question, or 663 // 2. The question is DNSSEC question and the CNAME being followed has been validated by DNSSEC. 664 // So that we can ensure only the secure CNAME can be followed. 665 if (!resource_record_as_cname_should_be_followed(rr, q)) 666 { 667 return mDNSfalse; 668 } 669 #endif 670 671 return mDNStrue; 672 } 673 674 // Caller should hold the lock 675 mDNSlocal void GenerateNegativeResponseEx(mDNS *const m, const mDNSInterfaceID InterfaceID, const QC_result qc, 676 const mDNSOpaque16 responseFlags) 677 { 678 DNSQuestion *q; 679 if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; } 680 q = m->CurrentQuestion; 681 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 682 "[Q%d] GenerateNegativeResponse: Generating negative response for question", mDNSVal16(q->TargetQID)); 683 684 MakeNegativeCacheRecordForQuestion(m, &m->rec.r, q, 60, InterfaceID, responseFlags); 685 686 // We need to force the response through in the following cases 687 // 688 // a) SuppressUnusable questions that are suppressed 689 // b) Append search domains and retry the question 690 // 691 // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force 692 // through we use "QC_forceresponse". 693 AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc); 694 if (m->CurrentQuestion == q) { q->ThisQInterval = 0; } // Deactivate this question 695 // Don't touch the question after this 696 mDNSCoreResetRecord(m); 697 } 698 #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, zeroID) 699 700 mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr) 701 { 702 const domainname *const cname = &rr->rdata->u.name; 703 const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name); 704 if (q->CNAMEReferrals >= 10 || selfref) 705 { 706 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 707 "[Q%u] AnswerQuestionByFollowingCNAME: Not following CNAME referral -- " 708 "CNAME: " PRI_DM_NAME ", referral count: %u, self referential: " PUB_BOOL, 709 mDNSVal16(q->TargetQID), DM_NAME_PARAM_NONNULL(cname), q->CNAMEReferrals, BOOL_PARAM(selfref)); 710 } 711 else 712 { 713 UDPSocket *sock = q->LocalSocket; 714 mDNSOpaque16 id = q->TargetQID; 715 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_ANALYTICS) 716 DNSMetrics metrics; 717 #endif 718 719 q->LocalSocket = mDNSNULL; 720 721 // The SameDomainName check above is to ignore bogus CNAME records that point right back at 722 // themselves. Without that check we can get into a case where we have two duplicate questions, 723 // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals 724 // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because 725 // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates 726 // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals 727 // for either of them. This is not a problem for CNAME loops of two or more records because in 728 // those cases the newly re-appended question A has a different target name and therefore cannot be 729 // a duplicate of any other question ('B') which was itself a duplicate of the previous question A. 730 731 // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect, 732 // and track CNAMEs coming and going, we should really create a subordinate query here, 733 // which we would subsequently cancel and retract if the CNAME referral record were removed. 734 // In reality this is such a corner case we'll ignore it until someone actually needs it. 735 736 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 737 "[Q%u] AnswerQuestionByFollowingCNAME: following CNAME referral -- " 738 "CNAME: " PRI_DM_NAME ", referral count: %u", 739 mDNSVal16(q->TargetQID), DM_NAME_PARAM_NONNULL(cname), q->CNAMEReferrals); 740 741 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_ANALYTICS) 742 metrics = q->metrics; 743 // The metrics will be transplanted to the restarted question, so zero out the old copy instead of using 744 // DNSMetricsClear(), which will free any pointers to allocated memory. 745 mDNSPlatformMemZero(&q->metrics, sizeof(q->metrics)); 746 #endif 747 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 748 mdns_client_t client = mDNSNULL; 749 const mDNSBool handleRestart = !mDNSOpaque16IsZero(q->TargetQID); 750 if (handleRestart) 751 { 752 client = Querier_HandlePreCNAMERestart(q); 753 } 754 #endif 755 mDNS_StopQuery_internal(m, q); // Stop old query 756 AssignDomainName(&q->qname, &rr->rdata->u.name); // Update qname 757 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash 758 // If a unicast query results in a CNAME that points to a .local, we need to re-try 759 // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal 760 // to try this as unicast query even though it is a .local name 761 if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname)) 762 { 763 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 764 "[Q%d] AnswerQuestionByFollowingCNAME: Resolving a .local CNAME -- CNAME: " PRI_DM_NAME, 765 mDNSVal16(q->TargetQID), DM_NAME_PARAM_NONNULL(cname)); 766 q->IsUnicastDotLocal = mDNStrue; 767 } 768 q->CNAMEReferrals += 1; // Increment value before calling mDNS_StartQuery_internal 769 const mDNSu8 c = q->CNAMEReferrals; // Stash a copy of the new q->CNAMEReferrals value 770 mDNS_StartQuery_internal(m, q); // start new query 771 // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal, 772 // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero 773 q->CNAMEReferrals = c; 774 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_ANALYTICS) 775 q->metrics = metrics; 776 #endif 777 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 778 if (handleRestart) 779 { 780 Querier_HandlePostCNAMERestart(q, client); 781 } 782 mdns_forget(&client); 783 #endif 784 if (sock) 785 { 786 // If our new query is a duplicate, then it can't have a socket of its own, so we have to close the one we saved. 787 if (q->DuplicateOf) mDNSPlatformUDPClose(sock); 788 else 789 { 790 // Transplant the old socket into the new question, and copy the query ID across too. 791 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand). 792 q->LocalSocket = sock; 793 q->TargetQID = id; 794 } 795 } 796 } 797 } 798 799 #ifdef USE_LIBIDN 800 801 #include <unicode/uidna.h> 802 803 #define DEBUG_PUNYCODE 0 804 805 mDNSlocal mDNSu8 *PunycodeConvert(const mDNSu8 *const src, mDNSu8 *const dst, const mDNSu8 *const end) 806 { 807 UErrorCode errorCode = U_ZERO_ERROR; 808 UIDNAInfo info = UIDNA_INFO_INITIALIZER; 809 UIDNA *uts46 = uidna_openUTS46(UIDNA_USE_STD3_RULES|UIDNA_NONTRANSITIONAL_TO_UNICODE, &errorCode); 810 int32_t len = uidna_nameToASCII_UTF8(uts46, (const char *)src+1, src[0], (char *)dst+1, (int32_t)(end-(dst+1)), &info, &errorCode); 811 uidna_close(uts46); 812 #if DEBUG_PUNYCODE 813 if (errorCode) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src, errorCode); 814 if (info.errors) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src, info.errors); 815 if (len > MAX_DOMAIN_LABEL) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src, len); 816 #endif 817 if (errorCode || info.errors || len > MAX_DOMAIN_LABEL) return mDNSNULL; 818 *dst = (mDNSu8)len; 819 return(dst + 1 + len); 820 } 821 822 mDNSlocal mDNSBool IsHighASCIILabel(const mDNSu8 *d) 823 { 824 int i; 825 for (i=1; i<=d[0]; i++) if (d[i] & 0x80) return mDNStrue; 826 return mDNSfalse; 827 } 828 829 mDNSlocal const mDNSu8 *FindLastHighASCIILabel(const domainname *const d) 830 { 831 const mDNSu8 *ptr = d->c; 832 const mDNSu8 *ans = mDNSNULL; 833 while (ptr[0]) 834 { 835 const mDNSu8 *const next = ptr + 1 + ptr[0]; 836 if (ptr[0] > MAX_DOMAIN_LABEL || next >= d->c + MAX_DOMAIN_NAME) return mDNSNULL; 837 if (IsHighASCIILabel(ptr)) ans = ptr; 838 ptr = next; 839 } 840 return ans; 841 } 842 843 mDNSlocal mDNSBool PerformNextPunycodeConversion(const DNSQuestion *const q, domainname *const newname) 844 { 845 const mDNSu8 *h = FindLastHighASCIILabel(&q->qname); 846 #if DEBUG_PUNYCODE 847 LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q->qname.c, DNSTypeName(q->qtype), h); 848 #endif 849 if (!h) return mDNSfalse; // There are no high-ascii labels to convert 850 851 mDNSu8 *const dst = PunycodeConvert(h, newname->c + (h - q->qname.c), newname->c + MAX_DOMAIN_NAME); 852 if (!dst) 853 return mDNSfalse; // The label was not convertible to Punycode 854 else 855 { 856 // If Punycode conversion of final eligible label was successful, copy the rest of the domainname 857 const mDNSu8 *const src = h + 1 + h[0]; 858 const mDNSu16 remainder = DomainNameLength((const domainname*)src); 859 if (dst + remainder > newname->c + MAX_DOMAIN_NAME) return mDNSfalse; // Name too long -- cannot be converted to Punycode 860 861 mDNSPlatformMemCopy(newname->c, q->qname.c, (mDNSu32)(h - q->qname.c)); // Fill in the leading part 862 mDNSPlatformMemCopy(dst, src, remainder); // Fill in the trailing part 863 #if DEBUG_PUNYCODE 864 LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q->qname.c, newname->c); 865 #endif 866 return mDNStrue; 867 } 868 } 869 870 #endif // USE_LIBIDN 871 872 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord 873 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not 874 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord) 875 { 876 DNSQuestion *q = m->CurrentQuestion; 877 mDNSBool followcname; 878 879 if (!q) 880 { 881 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with " PUB_S, 882 ARDisplayString(m, rr)); 883 return; 884 } 885 886 followcname = FollowCNAME(q, &rr->resrec, AddRecord); 887 888 // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique 889 if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask)) 890 { 891 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering " PUB_S " event for local record type %X " 892 PRI_S, AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr)); 893 return; 894 } 895 896 // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it 897 if (AddRecord) rr->AnsweredLocalQ = mDNStrue; 898 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback 899 if (q->QuestionCallback) 900 { 901 q->CurrentAnswers += AddRecord ? 1 : -1; 902 if (UniqueLocalOnlyRecord(rr)) 903 { 904 if (!followcname || q->ReturnIntermed) 905 { 906 // Don't send this packet on the wire as we answered from /etc/hosts 907 q->ThisQInterval = 0; 908 q->LOAddressAnswers += AddRecord ? 1 : -1; 909 q->QuestionCallback(m, q, &rr->resrec, AddRecord); 910 } 911 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 912 // The callback above could have caused the question to stop. Detect that 913 // using m->CurrentQuestion 914 if (followcname && m->CurrentQuestion == q) 915 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec); 916 return; 917 } 918 else 919 { 920 q->QuestionCallback(m, q, &rr->resrec, AddRecord); 921 } 922 } 923 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 924 } 925 926 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord) 927 { 928 if (m->CurrentQuestion) 929 LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)", 930 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 931 m->CurrentQuestion = m->Questions; 932 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions) 933 { 934 mDNSBool answered; 935 DNSQuestion *q = m->CurrentQuestion; 936 if (RRAny(ar)) 937 answered = AuthRecordAnswersQuestion(ar, q); 938 else 939 answered = LocalOnlyRecordAnswersQuestion(ar, q); 940 if (answered) 941 AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord); // MUST NOT dereference q again 942 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now 943 m->CurrentQuestion = q->next; 944 } 945 m->CurrentQuestion = mDNSNULL; 946 } 947 948 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord() 949 // delivers the appropriate add/remove events to listening questions: 950 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate, 951 // stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion(). 952 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though 953 // our main question list, delivering answers to mDNSInterface_Any questions as appropriate, 954 // stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion(). 955 // 956 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(), 957 // and by mDNS_Deregister_internal() 958 959 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord) 960 { 961 if (m->CurrentQuestion) 962 { 963 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: " PRI_DM_NAME 964 " (" PUB_S ")", DM_NAME_PARAM(&m->CurrentQuestion->qname), DNSTypeName(m->CurrentQuestion->qtype)); 965 } 966 967 m->CurrentQuestion = m->LocalOnlyQuestions; 968 while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions) 969 { 970 mDNSBool answered; 971 DNSQuestion *q = m->CurrentQuestion; 972 // We are called with both LocalOnly/P2P record or a regular AuthRecord 973 if (RRAny(ar)) 974 answered = AuthRecordAnswersQuestion(ar, q); 975 else 976 answered = LocalOnlyRecordAnswersQuestion(ar, q); 977 if (answered) 978 AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord); // MUST NOT dereference q again 979 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now 980 m->CurrentQuestion = q->next; 981 } 982 983 m->CurrentQuestion = mDNSNULL; 984 985 // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions 986 if (ar->ARType == AuthRecordLocalOnly || ar->ARType == AuthRecordP2P) 987 AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, ar, AddRecord); 988 989 } 990 991 // *************************************************************************** 992 // MARK: - Resource Record Utility Functions 993 994 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA) 995 996 mDNSlocal mDNSBool ResourceRecordIsValidAnswer(const AuthRecord *const rr) 997 { 998 if ((rr->resrec.RecordType & kDNSRecordTypeActiveMask) && 999 ((rr->Additional1 == mDNSNULL) || (rr->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && 1000 ((rr->Additional2 == mDNSNULL) || (rr->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && 1001 ((rr->DependentOn == mDNSNULL) || (rr->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask))) 1002 { 1003 return mDNStrue; 1004 } 1005 else 1006 { 1007 return mDNSfalse; 1008 } 1009 } 1010 1011 mDNSlocal mDNSBool IsInterfaceValidForAuthRecord(const AuthRecord *const rr, const mDNSInterfaceID InterfaceID) 1012 { 1013 if (rr->resrec.InterfaceID == mDNSInterface_Any) 1014 { 1015 return mDNSPlatformValidRecordForInterface(rr, InterfaceID); 1016 } 1017 else 1018 { 1019 return ((rr->resrec.InterfaceID == InterfaceID) ? mDNStrue : mDNSfalse); 1020 } 1021 } 1022 1023 mDNSlocal mDNSBool ResourceRecordIsValidInterfaceAnswer(const AuthRecord *const rr, const mDNSInterfaceID interfaceID) 1024 { 1025 return ((IsInterfaceValidForAuthRecord(rr, interfaceID) && ResourceRecordIsValidAnswer(rr)) ? mDNStrue : mDNSfalse); 1026 } 1027 1028 #define DefaultProbeCountForTypeUnique ((mDNSu8)3) 1029 #define DefaultProbeCountForRecordType(X) ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0) 1030 1031 // Parameters for handling probing conflicts 1032 #define kMaxAllowedMCastProbingConflicts 1 // Maximum number of conflicts to allow from mcast messages. 1033 #define kProbingConflictPauseDuration mDNSPlatformOneSecond // Duration of probing pause after an allowed mcast conflict. 1034 1035 // See RFC 6762: "8.3 Announcing" 1036 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart." 1037 // Send 4, which is really 8 since we send on both IPv4 and IPv6. 1038 #define InitialAnnounceCount ((mDNSu8)4) 1039 1040 // For goodbye packets we set the count to 3, and for wakeups we set it to 18 1041 // (which will be up to 15 wakeup attempts over the course of 30 seconds, 1042 // and then if the machine fails to wake, 3 goodbye packets). 1043 #define GoodbyeCount ((mDNSu8)3) 1044 #define WakeupCount ((mDNSu8)18) 1045 #define MAX_PROBE_RESTARTS ((mDNSu8)20) 1046 #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond)) // One week 1047 1048 // Number of wakeups we send if WakeOnResolve is set in the question 1049 #define InitialWakeOnResolveCount ((mDNSu8)3) 1050 1051 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not. 1052 // This means that because the announce interval is doubled after sending the first packet, the first 1053 // observed on-the-wire inter-packet interval between announcements is actually one second. 1054 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent. 1055 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4) 1056 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2) 1057 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2) 1058 1059 #define DefaultAPIntervalForRecordType(X) ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \ 1060 (X) &kDNSRecordTypeUnique ? DefaultProbeIntervalForTypeUnique : \ 1061 (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0) 1062 1063 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0) 1064 mDNSexport mDNSs32 RRExpireTime(const CacheRecord *const cr) 1065 { 1066 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) || MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 1067 return cr->DNSPushSubscribed ? (mDNSStorage.timenow + FutureTime) : (cr->TimeRcvd + TicksTTL(cr)); 1068 #else 1069 return cr->TimeRcvd + TicksTTL(cr); 1070 #endif 1071 } 1072 1073 // ResourceRecordNameClassInterfaceMatch returns true if two resource records have the same InterfaceID, class and name. 1074 mDNSlocal mDNSBool ResourceRecordNameClassInterfaceMatch(const ResourceRecord *const r1, const ResourceRecord *const r2) 1075 { 1076 if (!r1 || !r2) 1077 { 1078 return mDNSfalse; 1079 } 1080 if (r1->InterfaceID && r2->InterfaceID && r1->InterfaceID != r2->InterfaceID) 1081 { 1082 return mDNSfalse; 1083 } 1084 return (mDNSBool)(r1->rrclass == r2->rrclass && r1->namehash == r2->namehash && SameDomainName(r1->name, r2->name)); 1085 } 1086 1087 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent 1088 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match). 1089 // TTL and rdata may differ. 1090 // This is used for cache flush management: 1091 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent 1092 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed 1093 1094 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match 1095 1096 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B)) 1097 1098 mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2) 1099 { 1100 if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); } 1101 if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); } 1102 return ResourceRecordNameClassInterfaceMatch(&r1->resrec, &r2->resrec); 1103 } 1104 1105 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our 1106 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have 1107 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict. 1108 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY, 1109 // so a response of any type should match, even if it is not actually the type the client plans to use. 1110 1111 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records, 1112 // and require the rrtypes to match for the rdata to be considered potentially conflicting 1113 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr) 1114 { 1115 if (!pktrr) { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); } 1116 if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); } 1117 if (pktrr->resrec.InterfaceID && 1118 authrr->resrec.InterfaceID && 1119 pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse); 1120 if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0]) 1121 if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse); 1122 if ((authrr->resrec.InterfaceID == mDNSInterface_Any) && 1123 !mDNSPlatformValidRecordForInterface(authrr, pktrr->resrec.InterfaceID)) return(mDNSfalse); 1124 return (mDNSBool)( 1125 pktrr->resrec.rrclass == authrr->resrec.rrclass && 1126 pktrr->resrec.namehash == authrr->resrec.namehash && 1127 SameDomainName(pktrr->resrec.name, authrr->resrec.name)); 1128 } 1129 1130 // CacheRecord *ka is the CacheRecord from the known answer list in the query. 1131 // This is the information that the requester believes to be correct. 1132 // AuthRecord *rr is the answer we are proposing to give, if not suppressed. 1133 // This is the information that we believe to be correct. 1134 // We've already determined that we plan to give this answer on this interface 1135 // (either the record is non-specific, or it is specific to this interface) 1136 // so now we just need to check the name, type, class, rdata and TTL. 1137 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr) 1138 { 1139 // If RR signature is different, or data is different, then don't suppress our answer 1140 if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse); 1141 1142 // If the requester's indicated TTL is less than half the real TTL, 1143 // we need to give our answer before the requester's copy expires. 1144 // If the requester's indicated TTL is at least half the real TTL, 1145 // then we can suppress our answer this time. 1146 // If the requester's indicated TTL is greater than the TTL we believe, 1147 // then that's okay, and we don't need to do anything about it. 1148 // (If two responders on the network are offering the same information, 1149 // that's okay, and if they are offering the information with different TTLs, 1150 // the one offering the lower TTL should defer to the one offering the higher TTL.) 1151 return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2); 1152 } 1153 1154 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr) 1155 { 1156 if (rr->resrec.RecordType == kDNSRecordTypeUnique) 1157 { 1158 if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10) 1159 { 1160 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "SetNextAnnounceProbeTime: ProbeCount %d Next in %d " PRI_S, 1161 rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr)); 1162 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", 1163 m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow); 1164 } 1165 if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0) 1166 m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval); 1167 // Some defensive code: 1168 // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow 1169 // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen. 1170 // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero 1171 if (m->NextScheduledProbe - m->timenow < 0) 1172 m->NextScheduledProbe = m->timenow; 1173 } 1174 else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering)) 1175 { 1176 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0) 1177 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval); 1178 } 1179 } 1180 1181 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr) 1182 { 1183 // For reverse-mapping Sleep Proxy PTR records, probe interval is one second 1184 rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType); 1185 1186 // * If this is a record type that's going to probe, then we use the m->SuppressProbes time. 1187 // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other 1188 // records that are going to probe, then we delay its first announcement so that it will 1189 // go out synchronized with the first announcement for the other records that *are* probing. 1190 // This is a minor performance tweak that helps keep groups of related records synchronized together. 1191 // The addition of "interval / 2" is to make sure that, in the event that any of the probes are 1192 // delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete. 1193 // When the probing is complete and those records begin to announce, these records will also be picked up and accelerated, 1194 // because they will meet the criterion of being at least half-way to their scheduled announcement time. 1195 // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately. 1196 1197 if (rr->ProbeCount) 1198 { 1199 rr->ProbingConflictCount = 0; 1200 // If we have no probe suppression time set, or it is in the past, set it now 1201 if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0) 1202 { 1203 // To allow us to aggregate probes when a group of services are registered together, 1204 // the first probe is delayed by a random delay in the range 1/8 to 1/4 second. 1205 // This means the common-case behaviour is: 1206 // randomized wait; probe 1207 // 1/4 second wait; probe 1208 // 1/4 second wait; probe 1209 // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered) 1210 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2)); 1211 1212 // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation 1213 if (m->SuppressProbes - m->NextScheduledProbe >= 0) 1214 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe); 1215 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past 1216 m->SuppressProbes = m->timenow; 1217 1218 // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation 1219 if (m->SuppressProbes - m->NextScheduledQuery >= 0) 1220 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery); 1221 if (m->SuppressProbes - m->timenow < 0) // Make sure we don't set m->SuppressProbes excessively in the past 1222 m->SuppressProbes = m->timenow; 1223 1224 // except... don't expect to be able to send before the m->SuppressQueries timer fires 1225 if (m->SuppressQueries && ((m->SuppressProbes - m->SuppressQueries) < 0)) 1226 { 1227 m->SuppressProbes = NonZeroTime(m->SuppressQueries); 1228 } 1229 if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8) 1230 { 1231 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 1232 "InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d " 1233 "m->NextScheduledQuery %d m->SuppressQueries %d %d", 1234 m->SuppressProbes - m->timenow, m->NextScheduledProbe - m->timenow, 1235 m->NextScheduledQuery - m->timenow, m->SuppressQueries, m->SuppressQueries - m->timenow); 1236 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2)); 1237 } 1238 } 1239 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval; 1240 } 1241 // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so 1242 // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value. 1243 else if ((rr->resrec.RecordType != kDNSRecordTypeKnownUnique) && (rr->resrec.RecordType != kDNSRecordTypeShared) && m->SuppressProbes && (m->SuppressProbes - m->timenow >= 0)) 1244 rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2; 1245 else 1246 rr->LastAPTime = m->timenow - rr->ThisAPInterval; 1247 1248 // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we 1249 // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing. 1250 // After three probes one second apart with no answer, we conclude the client is now sleeping 1251 // and we can begin broadcasting our announcements to take over ownership of that IP address. 1252 // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk 1253 // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address. 1254 if (rr->AddressProxy.type) 1255 rr->LastAPTime = m->timenow; 1256 1257 // Set LastMCTime to now, to inhibit multicast responses 1258 // (no need to send additional multicast responses when we're announcing anyway) 1259 rr->LastMCTime = m->timenow; 1260 rr->LastMCInterface = mDNSInterfaceMark; 1261 1262 SetNextAnnounceProbeTime(m, rr); 1263 } 1264 1265 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr) 1266 { 1267 const domainname *target; 1268 if (rr->AutoTarget) 1269 { 1270 rr->AutoTarget = Target_AutoHostAndNATMAP; 1271 } 1272 1273 target = GetServiceTarget(m, rr); 1274 if (!target || target->c[0] == 0) 1275 { 1276 // defer registration until we've got a target 1277 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "SetUnicastTargetToHostName No target for " PRI_S, ARDisplayString(m, rr)); 1278 rr->state = regState_NoTarget; 1279 return mDNSNULL; 1280 } 1281 else 1282 { 1283 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "SetUnicastTargetToHostName target " PRI_DM_NAME " for resource record " PUB_S, 1284 DM_NAME_PARAM(target), ARDisplayString(m,rr)); 1285 return target; 1286 } 1287 } 1288 1289 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 1290 mDNSlocal mDNSBool AuthRecordIncludesOrIsAWDL(const AuthRecord *const ar) 1291 { 1292 return ((AuthRecordIncludesAWDL(ar) || mDNSPlatformInterfaceIsAWDL(ar->resrec.InterfaceID)) ? mDNStrue : mDNSfalse); 1293 } 1294 #endif 1295 1296 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname 1297 // Eventually we should unify this with GetServiceTarget() in uDNS.c 1298 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr) 1299 { 1300 domainname *const target = GetRRDomainNameTarget(&rr->resrec); 1301 const domainname *newname; 1302 1303 if (0) {} 1304 else if (rr->resrec.InterfaceID == mDNSInterface_LocalOnly) 1305 { 1306 newname = (const domainname *)"\x9" "localhost"; 1307 } 1308 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 1309 else if (AuthRecordIncludesOrIsAWDL(rr)) 1310 { 1311 newname = &m->RandomizedHostname; 1312 } 1313 #endif 1314 else 1315 { 1316 newname = &m->MulticastHostname; 1317 } 1318 if (!target) 1319 { 1320 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "SetTargetToHostName: Don't know how to set the target of rrtype " PUB_S, 1321 DNSTypeName(rr->resrec.rrtype)); 1322 } 1323 1324 if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage))) 1325 { 1326 const domainname *const n = SetUnicastTargetToHostName(m, rr); 1327 if (n) newname = n; 1328 else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; } 1329 } 1330 1331 if (target && SameDomainName(target, newname)) 1332 debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c); 1333 1334 if (target && !SameDomainName(target, newname)) 1335 { 1336 AssignDomainName(target, newname); 1337 SetNewRData(&rr->resrec, mDNSNULL, 0); // Update rdlength, rdestimate, rdatahash 1338 1339 // If we're in the middle of probing this record, we need to start again, 1340 // because changing its rdata may change the outcome of the tie-breaker. 1341 // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.) 1342 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType); 1343 1344 // If we've announced this record, we really should send a goodbye packet for the old rdata before 1345 // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records, 1346 // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way. 1347 if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared) 1348 debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating", 1349 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); 1350 1351 rr->AnnounceCount = InitialAnnounceCount; 1352 rr->RequireGoodbye = mDNSfalse; 1353 rr->ProbeRestartCount = 0; 1354 InitializeLastAPTime(m, rr); 1355 } 1356 } 1357 1358 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr) 1359 { 1360 if (rr->RecordCallback) 1361 { 1362 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function 1363 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc. 1364 rr->Acknowledged = mDNStrue; 1365 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback 1366 rr->RecordCallback(m, rr, mStatus_NoError); 1367 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 1368 } 1369 } 1370 1371 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr) 1372 { 1373 // Make sure that we don't activate the SRV record and associated service records, if it is in 1374 // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state. 1375 // We should not activate any of the other reords (PTR, TXT) that are part of the service. When 1376 // the target becomes available, the records will be reregistered. 1377 if (rr->resrec.rrtype != kDNSType_SRV) 1378 { 1379 AuthRecord *srvRR = mDNSNULL; 1380 if (rr->resrec.rrtype == kDNSType_PTR) 1381 srvRR = rr->Additional1; 1382 else if (rr->resrec.rrtype == kDNSType_TXT) 1383 srvRR = rr->DependentOn; 1384 if (srvRR) 1385 { 1386 if (srvRR->resrec.rrtype != kDNSType_SRV) 1387 { 1388 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR)); 1389 } 1390 else 1391 { 1392 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)", 1393 ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); 1394 rr->state = srvRR->state; 1395 } 1396 } 1397 } 1398 1399 if (rr->state == regState_NoTarget) 1400 { 1401 LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr)); 1402 return; 1403 } 1404 // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep, 1405 // the service/record was being deregistered. In that case, we should not try to register again. For the cases where 1406 // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it 1407 // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went 1408 // to sleep, then it is okay to start in Pending state as we will go back to NoTarget state if we don't have a target. 1409 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) 1410 { 1411 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state); 1412 rr->state = regState_DeregPending; 1413 } 1414 else 1415 { 1416 LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state); 1417 rr->state = regState_Pending; 1418 } 1419 rr->ProbingConflictCount = 0; 1420 rr->LastConflictPktNum = 0; 1421 rr->ProbeRestartCount = 0; 1422 rr->ProbeCount = 0; 1423 rr->AnnounceCount = 0; 1424 rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL; 1425 rr->LastAPTime = m->timenow - rr->ThisAPInterval; 1426 rr->expire = 0; // Forget about all the leases, start fresh 1427 rr->uselease = mDNStrue; 1428 rr->updateid = zeroID; 1429 rr->SRVChanged = mDNSfalse; 1430 rr->updateError = mStatus_NoError; 1431 // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core. 1432 // The records might already be registered with the server and hence could have NAT state. 1433 if (rr->NATinfo.clientContext) 1434 { 1435 mDNS_StopNATOperation_internal(m, &rr->NATinfo); 1436 rr->NATinfo.clientContext = mDNSNULL; 1437 } 1438 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; } 1439 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; } 1440 if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0) 1441 m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval); 1442 } 1443 1444 // Two records qualify to be local duplicates if: 1445 // (a) the RecordTypes are the same, or 1446 // (b) one is Unique and the other Verified 1447 // (c) either is in the process of deregistering 1448 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \ 1449 ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \ 1450 ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering)) 1451 1452 #define RecordIsLocalDuplicate(A,B) \ 1453 ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec)) 1454 1455 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr) 1456 { 1457 const AuthGroup *a; 1458 AuthRecord *rp; 1459 1460 a = AuthGroupForRecord(r, &rr->resrec); 1461 if (!a) return mDNSNULL; 1462 rp = a->members; 1463 while (rp) 1464 { 1465 if (!RecordIsLocalDuplicate(rp, rr)) 1466 rp = rp->next; 1467 else 1468 { 1469 if (rp->resrec.RecordType == kDNSRecordTypeDeregistering) 1470 { 1471 rp->AnnounceCount = 0; 1472 rp = rp->next; 1473 } 1474 else return rp; 1475 } 1476 } 1477 return (mDNSNULL); 1478 } 1479 1480 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr) 1481 { 1482 const AuthGroup *a; 1483 const AuthRecord *rp; 1484 1485 a = AuthGroupForRecord(r, &rr->resrec); 1486 if (!a) return mDNSfalse; 1487 rp = a->members; 1488 while (rp) 1489 { 1490 const uintptr_t s1 = rr->RRSet ? rr->RRSet : (uintptr_t)rr; 1491 const uintptr_t s2 = rp->RRSet ? rp->RRSet : (uintptr_t)rp; 1492 if (s1 != s2 && SameResourceRecordSignature(rp, rr) && !IdenticalSameNameRecord(&rp->resrec, &rr->resrec)) 1493 return mDNStrue; 1494 else 1495 rp = rp->next; 1496 } 1497 return (mDNSfalse); 1498 } 1499 1500 // checks to see if "rr" is already present 1501 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr) 1502 { 1503 const AuthGroup *a; 1504 AuthRecord *rp; 1505 1506 a = AuthGroupForRecord(r, &rr->resrec); 1507 if (!a) return mDNSNULL; 1508 rp = a->members; 1509 while (rp) 1510 { 1511 if (rp != rr) 1512 rp = rp->next; 1513 else 1514 { 1515 return rp; 1516 } 1517 } 1518 return (mDNSNULL); 1519 } 1520 1521 mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr) 1522 { 1523 if (RRLocalOnly(rr)) 1524 { 1525 // A sanity check, this should be prevented in calling code. 1526 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "DecrementAutoTargetServices: called for RRLocalOnly() record: " PUB_S, ARDisplayString(m, rr)); 1527 return; 1528 } 1529 1530 if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost)) 1531 { 1532 NetworkInterfaceInfo *intf; 1533 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 1534 DeadvertiseFlags flags = 0; // DeadvertiseFlags for non-AWDL interfaces. 1535 DeadvertiseFlags flagsAWDL = 0; // DeadvertiseFlags for AWDL interfaces. 1536 if (AuthRecordIncludesOrIsAWDL(rr)) 1537 { 1538 if (AuthRecordIncludesAWDL(rr)) 1539 { 1540 m->AutoTargetAWDLIncludedCount--; 1541 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "DecrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S, 1542 m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr)); 1543 if (m->AutoTargetAWDLIncludedCount == 0) 1544 { 1545 flags |= kDeadvertiseFlag_RandHostname; 1546 if (m->AutoTargetAWDLOnlyCount == 0) flagsAWDL |= kDeadvertiseFlag_RandHostname; 1547 } 1548 } 1549 else 1550 { 1551 m->AutoTargetAWDLOnlyCount--; 1552 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "DecrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S, 1553 m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr)); 1554 if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0)) 1555 { 1556 flagsAWDL |= kDeadvertiseFlag_RandHostname; 1557 } 1558 } 1559 if (flags || flagsAWDL) 1560 { 1561 for (intf = m->HostInterfaces; intf; intf = intf->next) 1562 { 1563 if (!intf->Advertise) continue; 1564 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) 1565 { 1566 if (flagsAWDL) DeadvertiseInterface(m, intf, flagsAWDL); 1567 } 1568 else 1569 { 1570 if (flags) DeadvertiseInterface(m, intf, flags); 1571 } 1572 } 1573 } 1574 if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0)) 1575 { 1576 GetRandomUUIDLocalHostname(&m->RandomizedHostname); 1577 } 1578 } 1579 else 1580 #endif 1581 { 1582 m->AutoTargetServices--; 1583 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "DecrementAutoTargetServices: AutoTargetServices %u Record " PRI_S, 1584 m->AutoTargetServices, ARDisplayString(m, rr)); 1585 if (m->AutoTargetServices == 0) 1586 { 1587 for (intf = m->HostInterfaces; intf; intf = intf->next) 1588 { 1589 if (intf->Advertise) DeadvertiseInterface(m, intf, kDeadvertiseFlag_NormalHostname); 1590 } 1591 } 1592 } 1593 } 1594 1595 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 1596 if (!AuthRecord_uDNS(rr)) 1597 { 1598 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1) 1599 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond)); 1600 m->NumAllInterfaceRecords--; 1601 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S, 1602 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr)); 1603 } 1604 #endif 1605 } 1606 1607 mDNSlocal void AdvertiseNecessaryInterfaceRecords(mDNS *const m) 1608 { 1609 NetworkInterfaceInfo *intf; 1610 for (intf = m->HostInterfaces; intf; intf = intf->next) 1611 { 1612 if (intf->Advertise) AdvertiseInterfaceIfNeeded(m, intf); 1613 } 1614 } 1615 1616 mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr) 1617 { 1618 mDNSBool enablingBonjour = mDNSfalse; 1619 1620 if (RRLocalOnly(rr)) 1621 { 1622 // A sanity check, this should be prevented in calling code. 1623 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "IncrementAutoTargetServices: called for RRLocalOnly() record: " PRI_S, ARDisplayString(m, rr)); 1624 return; 1625 } 1626 1627 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 1628 if (!AuthRecord_uDNS(rr)) 1629 { 1630 m->NumAllInterfaceRecords++; 1631 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S, 1632 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr)); 1633 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1) 1634 { 1635 m->NextBonjourDisableTime = 0; 1636 if (m->BonjourEnabled == 0) 1637 { 1638 // Enable Bonjour immediately by scheduling network changed processing where 1639 // we will join the multicast group on each active interface. 1640 m->BonjourEnabled = 1; 1641 enablingBonjour = mDNStrue; 1642 m->NetworkChanged = m->timenow; 1643 } 1644 } 1645 } 1646 #endif 1647 1648 if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost)) 1649 { 1650 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 1651 if (AuthRecordIncludesAWDL(rr)) 1652 { 1653 m->AutoTargetAWDLIncludedCount++; 1654 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "IncrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S, 1655 m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr)); 1656 } 1657 else if (mDNSPlatformInterfaceIsAWDL(rr->resrec.InterfaceID)) 1658 { 1659 m->AutoTargetAWDLOnlyCount++; 1660 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "IncrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S, 1661 m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr)); 1662 } 1663 else 1664 #endif 1665 { 1666 m->AutoTargetServices++; 1667 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, "IncrementAutoTargetServices: AutoTargetServices %u Record " PRI_S, 1668 m->AutoTargetServices, ARDisplayString(m, rr)); 1669 } 1670 // If this is the first advertised service and we did not just enable Bonjour above, then 1671 // advertise all the interface records. If we did enable Bonjour above, the interface records will 1672 // be advertised during the network changed processing scheduled above, so no need 1673 // to do it here. 1674 if (!enablingBonjour) AdvertiseNecessaryInterfaceRecords(m); 1675 } 1676 } 1677 1678 mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr) 1679 { 1680 mDNSAddr laddr = zeroAddr; 1681 mDNSEthAddr eth = zeroEthAddr; 1682 mDNSIPPort lport = zeroIPPort; 1683 mDNSIPPort rport = zeroIPPort; 1684 mDNSu32 timeout = 0; 1685 mDNSu32 seq = 0; 1686 mDNSu32 ack = 0; 1687 mDNSu16 win = 0; 1688 1689 if (mDNS_KeepaliveRecord(&rr->resrec)) 1690 { 1691 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, ð, &seq, &ack, &lport, &rport, &win); 1692 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport)) 1693 { 1694 LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger); 1695 return; 1696 } 1697 } 1698 } 1699 1700 // Exported so uDNS.c can call this 1701 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr) 1702 { 1703 domainname *target = GetRRDomainNameTarget(&rr->resrec); 1704 AuthRecord *r; 1705 AuthRecord **p = &m->ResourceRecords; 1706 AuthRecord **d = &m->DuplicateRecords; 1707 1708 if ((mDNSs32)rr->resrec.rroriginalttl <= 0) 1709 { 1710 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF " PRI_S, rr->resrec.rroriginalttl, 1711 ARDisplayString(m, rr)); 1712 return(mStatus_BadParamErr); 1713 } 1714 1715 if (!rr->resrec.RecordType) 1716 { 1717 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: RecordType must be non-zero " PRI_S, ARDisplayString(m, rr)); 1718 return(mStatus_BadParamErr); } 1719 1720 if (m->ShutdownTime) 1721 { 1722 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: Shutting down, can't register " PRI_S, ARDisplayString(m, rr)); 1723 return(mStatus_ServiceNotRunning); 1724 } 1725 1726 if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr)) 1727 { 1728 mDNSInterfaceID previousID = rr->resrec.InterfaceID; 1729 if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P) 1730 { 1731 rr->resrec.InterfaceID = mDNSInterface_LocalOnly; 1732 rr->ARType = AuthRecordLocalOnly; 1733 } 1734 if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly) 1735 { 1736 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID); 1737 if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; } 1738 } 1739 if (rr->resrec.InterfaceID != previousID) 1740 { 1741 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: Diverting record to local-only " PRI_S, ARDisplayString(m, rr)); 1742 } 1743 } 1744 1745 if (RRLocalOnly(rr)) 1746 { 1747 if (CheckAuthSameRecord(&m->rrauth, rr)) 1748 { 1749 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p " 1750 PRI_DM_NAME " (" PUB_S ") that's already in the list", 1751 rr, DM_NAME_PARAM(rr->resrec.name), DNSTypeName(rr->resrec.rrtype)); 1752 return(mStatus_AlreadyRegistered); 1753 } 1754 } 1755 else 1756 { 1757 while (*p && *p != rr) p=&(*p)->next; 1758 if (*p) 1759 { 1760 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p " 1761 PRI_DM_NAME " (" PUB_S ") that's already in the list", 1762 rr, DM_NAME_PARAM(rr->resrec.name), DNSTypeName(rr->resrec.rrtype)); 1763 return(mStatus_AlreadyRegistered); 1764 } 1765 } 1766 1767 while (*d && *d != rr) d=&(*d)->next; 1768 if (*d) 1769 { 1770 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p " 1771 PRI_DM_NAME " (" PUB_S ") that's already in the Duplicate list", 1772 rr, DM_NAME_PARAM(rr->resrec.name), DNSTypeName(rr->resrec.rrtype)); 1773 return(mStatus_AlreadyRegistered); 1774 } 1775 1776 if (rr->DependentOn) 1777 { 1778 if (rr->resrec.RecordType == kDNSRecordTypeUnique) 1779 rr->resrec.RecordType = kDNSRecordTypeVerified; 1780 else if (rr->resrec.RecordType != kDNSRecordTypeKnownUnique) 1781 { 1782 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: ERROR! " PRI_DM_NAME " (" PUB_S 1783 "): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique", 1784 DM_NAME_PARAM(rr->resrec.name), DNSTypeName(rr->resrec.rrtype)); 1785 return(mStatus_Invalid); 1786 } 1787 if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique))) 1788 { 1789 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: ERROR! " PRI_DM_NAME " (" PUB_S 1790 "): rr->DependentOn->RecordType bad type %X", 1791 DM_NAME_PARAM(rr->resrec.name), DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType); 1792 return(mStatus_Invalid); 1793 } 1794 } 1795 1796 rr->next = mDNSNULL; 1797 1798 // Field Group 1: The actual information pertaining to this resource record 1799 // Set up by client prior to call 1800 1801 // Field Group 2: Persistent metadata for Authoritative Records 1802 // rr->Additional1 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client 1803 // rr->Additional2 = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client 1804 // rr->DependentOn = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client 1805 // rr->RRSet = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client 1806 // rr->Callback = already set in mDNS_SetupResourceRecord 1807 // rr->Context = already set in mDNS_SetupResourceRecord 1808 // rr->RecordType = already set in mDNS_SetupResourceRecord 1809 // rr->HostTarget = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client 1810 // rr->AllowRemoteQuery = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client 1811 // Make sure target is not uninitialized data, or we may crash writing debugging log messages 1812 if (rr->AutoTarget && target) target->c[0] = 0; 1813 1814 // Field Group 3: Transient state for Authoritative Records 1815 rr->Acknowledged = mDNSfalse; 1816 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType); 1817 rr->ProbeRestartCount = 0; 1818 rr->AnnounceCount = InitialAnnounceCount; 1819 rr->RequireGoodbye = mDNSfalse; 1820 rr->AnsweredLocalQ = mDNSfalse; 1821 rr->IncludeInProbe = mDNSfalse; 1822 rr->ImmedUnicast = mDNSfalse; 1823 rr->SendNSECNow = mDNSNULL; 1824 rr->ImmedAnswer = mDNSNULL; 1825 rr->ImmedAdditional = mDNSNULL; 1826 rr->SendRNow = mDNSNULL; 1827 rr->v4Requester = zerov4Addr; 1828 rr->v6Requester = zerov6Addr; 1829 rr->NextResponse = mDNSNULL; 1830 rr->NR_AnswerTo = mDNSNULL; 1831 rr->NR_AdditionalTo = mDNSNULL; 1832 if (!rr->AutoTarget) InitializeLastAPTime(m, rr); 1833 // rr->LastAPTime = Set for us in InitializeLastAPTime() 1834 // rr->LastMCTime = Set for us in InitializeLastAPTime() 1835 // rr->LastMCInterface = Set for us in InitializeLastAPTime() 1836 rr->NewRData = mDNSNULL; 1837 rr->newrdlength = 0; 1838 rr->UpdateCallback = mDNSNULL; 1839 rr->UpdateCredits = kMaxUpdateCredits; 1840 rr->NextUpdateCredit = 0; 1841 rr->UpdateBlocked = 0; 1842 1843 // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient 1844 if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2; 1845 1846 // Field Group 4: Transient uDNS state for Authoritative Records 1847 rr->state = regState_Zero; 1848 rr->uselease = 0; 1849 rr->expire = 0; 1850 rr->Private = 0; 1851 rr->updateid = zeroID; 1852 rr->updateIntID = zeroOpaque64; 1853 rr->zone = rr->resrec.name; 1854 rr->nta = mDNSNULL; 1855 rr->tcp = mDNSNULL; 1856 rr->OrigRData = 0; 1857 rr->OrigRDLen = 0; 1858 rr->InFlightRData = 0; 1859 rr->InFlightRDLen = 0; 1860 rr->QueuedRData = 0; 1861 rr->QueuedRDLen = 0; 1862 //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo)); 1863 // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping 1864 // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple 1865 // times with different values if the external NAT port changes during the lifetime of the service registration. 1866 //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port; 1867 1868 // rr->resrec.interface = already set in mDNS_SetupResourceRecord 1869 // rr->resrec.name->c = MUST be set by client 1870 // rr->resrec.rrtype = already set in mDNS_SetupResourceRecord 1871 // rr->resrec.rrclass = already set in mDNS_SetupResourceRecord 1872 // rr->resrec.rroriginalttl = already set in mDNS_SetupResourceRecord 1873 // rr->resrec.rdata = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set 1874 1875 // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct, 1876 // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s". 1877 // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here. 1878 if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; } 1879 if (rr->AutoTarget) 1880 { 1881 SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime(); 1882 #ifndef UNICAST_DISABLED 1883 // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget 1884 // In this case we leave the record half-formed in the list, and later we'll remove it from the list and re-add it properly. 1885 if (rr->state == regState_NoTarget) 1886 { 1887 // Initialize the target so that we don't crash while logging etc. 1888 domainname *tar = GetRRDomainNameTarget(&rr->resrec); 1889 if (tar) tar->c[0] = 0; 1890 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: record " PUB_S " in NoTarget state", ARDisplayString(m, rr)); 1891 } 1892 #endif 1893 } 1894 else 1895 { 1896 rr->resrec.rdlength = GetRDLength(&rr->resrec, mDNSfalse); 1897 rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue); 1898 } 1899 1900 if (!ValidateDomainName(rr->resrec.name)) 1901 { 1902 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "Attempt to register record with invalid name: " PRI_S, ARDisplayString(m, rr)); 1903 return(mStatus_Invalid); 1904 } 1905 1906 // Don't do this until *after* we've set rr->resrec.rdlength 1907 if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata)) 1908 { 1909 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "Attempt to register record with invalid rdata: " PRI_S, ARDisplayString(m, rr)); 1910 return(mStatus_Invalid); 1911 } 1912 1913 rr->resrec.namehash = DomainNameHashValue(rr->resrec.name); 1914 rr->resrec.rdatahash = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec); 1915 1916 if (RRLocalOnly(rr)) 1917 { 1918 // If this is supposed to be unique, make sure we don't have any name conflicts. 1919 // If we found a conflict, we may still want to insert the record in the list but mark it appropriately 1920 // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more 1921 // complications and not clear whether there are any benefits. See rdar:9304275 for details. 1922 // Hence, just bail out. 1923 // This comment is doesnt make any sense. -- SC 1924 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) 1925 { 1926 if (CheckAuthRecordConflict(&m->rrauth, rr)) 1927 { 1928 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Register_internal: Name conflict " PRI_S " (%p), InterfaceID %p", 1929 ARDisplayString(m, rr), rr, rr->resrec.InterfaceID); 1930 return mStatus_NameConflict; 1931 } 1932 } 1933 } 1934 1935 // For uDNS records, we don't support duplicate checks at this time. 1936 #ifndef UNICAST_DISABLED 1937 if (AuthRecord_uDNS(rr)) 1938 { 1939 if (!m->NewLocalRecords) m->NewLocalRecords = rr; 1940 // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new 1941 // records to the list, so we now need to update p to advance to the new end to the list before appending our new record. 1942 while (*p) p=&(*p)->next; 1943 *p = rr; 1944 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified; 1945 rr->ProbeCount = 0; 1946 rr->ProbeRestartCount = 0; 1947 rr->AnnounceCount = 0; 1948 if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr); 1949 return(mStatus_NoError); // <--- Note: For unicast records, code currently bails out at this point 1950 } 1951 #endif 1952 1953 // Now that we've finished building our new record, make sure it's not identical to one we already have 1954 if (RRLocalOnly(rr)) 1955 { 1956 rr->ProbeCount = 0; 1957 rr->ProbeRestartCount = 0; 1958 rr->AnnounceCount = 0; 1959 r = CheckAuthIdenticalRecord(&m->rrauth, rr); 1960 } 1961 else 1962 { 1963 for (r = m->ResourceRecords; r; r=r->next) 1964 if (RecordIsLocalDuplicate(r, rr)) 1965 { 1966 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0; 1967 else break; 1968 } 1969 } 1970 1971 const domainname *const rrName = rr->resrec.name; 1972 const mDNSu32 nameHash = mDNS_DomainNameFNV1aHash(rrName); 1973 if (r) 1974 { 1975 MDNS_CORE_LOG_RDATA(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, &((rr)->resrec), 1976 "mDNS_Register_internal: adding to duplicate list -- name: " PRI_DM_NAME " (%x), ", 1977 DM_NAME_PARAM(rrName), nameHash); 1978 *d = rr; 1979 // If the previous copy of this record is already verified unique, 1980 // then indicate that we should move this record promptly to kDNSRecordTypeUnique state. 1981 // Setting ProbeCount to zero will cause SendQueries() to advance this record to 1982 // kDNSRecordTypeVerified state and call the client callback at the next appropriate time. 1983 if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified) 1984 rr->ProbeCount = 0; 1985 } 1986 else 1987 { 1988 MDNS_CORE_LOG_RDATA(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, &((rr)->resrec), 1989 "mDNS_Register_internal: adding to active record list -- name: " PRI_DM_NAME " (%x), ", 1990 DM_NAME_PARAM(rrName), nameHash); 1991 if (RRLocalOnly(rr)) 1992 { 1993 AuthGroup *ag; 1994 ag = InsertAuthRecord(m, &m->rrauth, rr); 1995 if (ag && !ag->NewLocalOnlyRecords) 1996 { 1997 m->NewLocalOnlyRecords = mDNStrue; 1998 ag->NewLocalOnlyRecords = rr; 1999 } 2000 // No probing for LocalOnly records; acknowledge them right away 2001 if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified; 2002 AcknowledgeRecord(m, rr); 2003 return(mStatus_NoError); 2004 } 2005 else 2006 { 2007 if (!m->NewLocalRecords) m->NewLocalRecords = rr; 2008 *p = rr; 2009 } 2010 } 2011 2012 if (!AuthRecord_uDNS(rr)) // This check is superfluous, given that for unicast records we (currently) bail out above 2013 { 2014 // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records. 2015 IncrementAutoTargetServices(m, rr); 2016 2017 // For records that are not going to probe, acknowledge them right away 2018 if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering) 2019 AcknowledgeRecord(m, rr); 2020 2021 // Adding a record may affect whether or not we should sleep 2022 mDNS_UpdateAllowSleep(m); 2023 } 2024 2025 // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host. 2026 // This is used by the in-NIC proxy to send the keepalive packets. 2027 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec)) 2028 { 2029 mDNSAddr raddr; 2030 // Set the record type to known unique to prevent probing keep alive records. 2031 // Also make sure we do not announce the keepalive records. 2032 rr->resrec.RecordType = kDNSRecordTypeKnownUnique; 2033 rr->AnnounceCount = 0; 2034 getKeepaliveRaddr(m, rr, &raddr); 2035 // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an 2036 // asynchronous task to update the resource record 2037 mDNSPlatformGetRemoteMacAddr(&raddr); 2038 } 2039 2040 rr->TimeRegistered = m->timenow; 2041 2042 return(mStatus_NoError); 2043 } 2044 2045 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr) 2046 { 2047 m->ProbeFailTime = m->timenow; 2048 m->NumFailedProbes++; 2049 // If we've had fifteen or more probe failures, rate-limit to one every five seconds. 2050 // If a bunch of hosts have all been configured with the same name, then they'll all 2051 // conflict and run through the same series of names: name-2, name-3, name-4, etc., 2052 // up to name-10. After that they'll start adding random increments in the range 1-100, 2053 // so they're more likely to branch out in the available namespace and settle on a set of 2054 // unique names quickly. If after five more tries the host is still conflicting, then we 2055 // may have a serious problem, so we start rate-limiting so we don't melt down the network. 2056 if (m->NumFailedProbes >= 15) 2057 { 2058 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5); 2059 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "Excessive name conflicts (%u) for " PRI_DM_NAME " (" PUB_S "); rate limiting in effect", 2060 m->NumFailedProbes, DM_NAME_PARAM(rr->resrec.name), DNSTypeName(rr->resrec.rrtype)); 2061 } 2062 } 2063 2064 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr) 2065 { 2066 RData *OldRData = rr->resrec.rdata; 2067 mDNSu16 OldRDLen = rr->resrec.rdlength; 2068 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); // Update our rdata 2069 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ... 2070 if (rr->UpdateCallback) 2071 rr->UpdateCallback(m, rr, OldRData, OldRDLen); // ... and let the client know 2072 } 2073 2074 mDNSexport mDNSBool getValidContinousTSRTime(mDNSs32 *timestampContinuous, mDNSu32 tsrTimestamp) 2075 { 2076 if (tsrTimestamp <= MaxTimeSinceReceived) 2077 { 2078 *timestampContinuous = mDNSPlatformContinuousTimeSeconds() - (mDNSs32)tsrTimestamp; 2079 return mDNStrue; 2080 } 2081 return mDNSfalse; 2082 } 2083 2084 mDNSlocal AuthRecord *mDNSGetTSRForAuthRecordNamed(mDNS *const m, const domainname * const name, const mDNSu32 namehash) 2085 { 2086 AuthRecord *ar = mDNSNULL; 2087 for (ar = m->ResourceRecords; ar; ar = ar->next) 2088 { 2089 if (ar->resrec.rrtype == kDNSType_OPT && 2090 ar->resrec.namehash == namehash && 2091 SameDomainName(ar->resrec.name, name)) 2092 { 2093 const rdataOPT *const opt = (const rdataOPT *)&ar->resrec.rdata->u.data[0]; 2094 if (opt->opt != kDNSOpt_TSR) 2095 { 2096 ar = mDNSNULL; 2097 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, 2098 "mDNSGetTSRForAuthRecordNamed: Found OPT that is not kDNSOpt_TSR (%d)", opt->opt); 2099 } 2100 break; 2101 } 2102 } 2103 return ar; 2104 } 2105 2106 mDNSexport AuthRecord *mDNSGetTSRForAuthRecord(mDNS *const m, const AuthRecord *const rr) 2107 { 2108 return mDNSGetTSRForAuthRecordNamed(m, rr->resrec.name, rr->resrec.namehash); 2109 } 2110 2111 mDNSexport CacheRecord *mDNSGetTSRForCacheGroup(const CacheGroup *const cg) 2112 { 2113 CacheRecord *rr; 2114 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) 2115 { 2116 if (rr->resrec.rrtype == kDNSType_OPT) 2117 { 2118 const rdataOPT *const opt = (const rdataOPT *)&rr->resrec.rdata->u.data[0]; 2119 if (opt->opt == kDNSOpt_TSR) 2120 { 2121 return rr; 2122 } 2123 else 2124 { 2125 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, 2126 "mDNSGetTSRForCacheGroup: Found OPT that is not kDNSOpt_TSR (%d)", opt->opt); 2127 break; 2128 } 2129 } 2130 } 2131 return mDNSNULL; 2132 } 2133 2134 mDNSlocal AuthRecord *FindOrphanedTSR(mDNS *const m, const domainname *const name, const mDNSu32 namehash) 2135 { 2136 AuthRecord *tsr = mDNSGetTSRForAuthRecordNamed(m, name, namehash); 2137 2138 for (const AuthRecord *ar = m->ResourceRecords; ar && tsr ; ar = ar->next) 2139 { 2140 if (ar->resrec.rrtype != kDNSType_OPT && 2141 ar->resrec.namehash == namehash && 2142 SameDomainName(ar->resrec.name, name)) 2143 { 2144 // There is at least one non-TSR record that has the same name. 2145 // So this TSR is not an orphan. 2146 tsr = mDNSNULL; 2147 } 2148 } 2149 2150 return tsr; 2151 } 2152 2153 mDNSlocal void SetupTSROpt(const TSROptData *tsrData, rdataOPT *const tsrOPT) 2154 { 2155 tsrOPT->u.tsr.hostkeyHash = tsrData->hostkeyHash; 2156 tsrOPT->u.tsr.recIndex = tsrData->recIndex; 2157 tsrOPT->u.tsr.timeStamp = tsrData->timeStamp; 2158 2159 tsrOPT->opt = kDNSOpt_TSR; 2160 tsrOPT->optlen = DNSOpt_TSRData_Space - 4; 2161 } 2162 2163 mDNSlocal mDNSu8 *AddTSRROptsToMessage(const TSRDataPtrRecHead * const tsrHead, const DNSMessage *const msg, 2164 mDNSu8 * const rdlengthptr, mDNSu8 *ptr, const mDNSu8 *end) 2165 { 2166 RData rdatastorage = {sizeof(RDataBody), 0, {0}}; 2167 ResourceRecord next_opt; 2168 mDNSu8 *startptr = ptr; 2169 mDNSu16 actualLength = (mDNSu16)(rdlengthptr[0] << 8) + (mDNSu16)rdlengthptr[1]; 2170 next_opt.rrtype = kDNSType_OPT; 2171 next_opt.rdata = &rdatastorage; 2172 next_opt.rdlength = sizeof(rdataOPT); 2173 struct TSRDataPtrRec *next; 2174 SLIST_FOREACH(next, tsrHead, entries) 2175 { 2176 SetupTSROpt(next->tsr, &next_opt.rdata->u.opt[0]); 2177 ptr = putRData(msg, ptr, end, &next_opt); 2178 if (!ptr) 2179 { 2180 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 2181 "AddTSRRDataToMessage: TSR can't be written -- name " PRI_DM_NAME " hashkey %x", 2182 DM_NAME_PARAM(next->name), next->tsr->hostkeyHash); 2183 break; 2184 } 2185 } 2186 if (ptr && startptr != ptr) 2187 { 2188 actualLength += ptr - startptr; 2189 rdlengthptr[0] = (mDNSu8)(actualLength >> 8); 2190 rdlengthptr[1] = (mDNSu8)(actualLength & 0xFF); 2191 } 2192 return ptr; 2193 } 2194 2195 2196 mDNSlocal const TSROptData *TSRForNameFromDataRec(TSRDataRecHead *const tsrHead, const domainname *const name) 2197 { 2198 struct TSRDataRec *nextTSR; 2199 SLIST_FOREACH(nextTSR, tsrHead, entries) 2200 { 2201 if (SameDomainName(&nextTSR->name, name)) 2202 { 2203 return &nextTSR->tsr; 2204 } 2205 } 2206 return mDNSNULL; 2207 } 2208 2209 mDNSlocal const TSROptData *TSRPtrForNameFromDataPtrRec(TSRDataPtrRecHead *const tsrHead, const domainname *const name) 2210 { 2211 struct TSRDataPtrRec *nextTSR; 2212 SLIST_FOREACH(nextTSR, tsrHead, entries) 2213 { 2214 if (SameDomainName(nextTSR->name, name)) 2215 { 2216 return nextTSR->tsr; 2217 } 2218 } 2219 return mDNSNULL; 2220 } 2221 2222 mDNSlocal TSROptData *TSROptGetIfNew(mDNS *const m, const AuthRecord *const rr, TSRDataPtrRecHead * const tsrHead) 2223 { 2224 AuthRecord *tsrOptRecord = mDNSGetTSRForAuthRecord(m, rr); 2225 if (tsrOptRecord && 2226 !TSRPtrForNameFromDataPtrRec(tsrHead, rr->resrec.name)) 2227 { 2228 return &tsrOptRecord->resrec.rdata->u.opt[0].u.tsr; 2229 } 2230 return mDNSNULL; 2231 } 2232 2233 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list. 2234 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 2235 // Exported so uDNS.c can call this 2236 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt) 2237 { 2238 AuthRecord *r2; 2239 mDNSu8 RecordType = rr->resrec.RecordType; 2240 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records 2241 mDNSBool dupList = mDNSfalse; 2242 2243 const CacheGroup *cg = mDNSNULL; 2244 const mDNSu32 nameHashToMatchTSR = rr->resrec.namehash; 2245 domainname nameToMatchTSR; 2246 AssignDomainName(&nameToMatchTSR, rr->resrec.name); 2247 const mDNSBool isTSR = (rr->resrec.rrtype == kDNSType_OPT); 2248 2249 if (RRLocalOnly(rr)) 2250 { 2251 AuthGroup *a; 2252 AuthRecord **rp; 2253 2254 a = AuthGroupForRecord(&m->rrauth, &rr->resrec); 2255 if (!a) return mDNSfalse; 2256 rp = &a->members; 2257 while (*rp && *rp != rr) rp=&(*rp)->next; 2258 p = rp; 2259 } 2260 else 2261 { 2262 while (*p && *p != rr) p=&(*p)->next; 2263 } 2264 2265 if (*p) 2266 { 2267 // We found our record on the main list. See if there are any duplicates that need special handling. 2268 if (drt == mDNS_Dereg_conflict) // If this was a conflict, see that all duplicates get the same treatment 2269 { 2270 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished 2271 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory. 2272 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF; 2273 } 2274 else if (drt == mDNS_Dereg_stale) // If this was stale data, see that all duplicates on all interfaces get the same treatment 2275 { 2276 mDNSInterfaceID storeID = rr->resrec.InterfaceID; 2277 rr->resrec.InterfaceID = kDNSServiceInterfaceIndexAny; 2278 // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished 2279 // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory. 2280 for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF; 2281 rr->resrec.InterfaceID = storeID; 2282 } 2283 else 2284 { 2285 // Before we delete the record (and potentially send a goodbye packet) 2286 // first see if we have a record on the duplicate list ready to take over from it. 2287 AuthRecord **d = &m->DuplicateRecords; 2288 while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next; 2289 if (*d) 2290 { 2291 AuthRecord *dup = *d; 2292 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)", 2293 dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); 2294 *d = dup->next; // Cut replacement record from DuplicateRecords list 2295 if (RRLocalOnly(rr)) 2296 { 2297 dup->next = mDNSNULL; 2298 if (!InsertAuthRecord(m, &m->rrauth, dup)) 2299 { 2300 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Deregister_internal: ERROR!! cannot insert " PRI_S, ARDisplayString(m, dup)); 2301 } 2302 } 2303 else 2304 { 2305 dup->next = rr->next; // And then... 2306 rr->next = dup; // ... splice it in right after the record we're about to delete 2307 } 2308 dup->resrec.RecordType = rr->resrec.RecordType; 2309 dup->ProbeCount = rr->ProbeCount; 2310 dup->ProbeRestartCount = rr->ProbeRestartCount; 2311 dup->AnnounceCount = rr->AnnounceCount; 2312 dup->RequireGoodbye = rr->RequireGoodbye; 2313 dup->AnsweredLocalQ = rr->AnsweredLocalQ; 2314 dup->ImmedAnswer = rr->ImmedAnswer; 2315 dup->ImmedUnicast = rr->ImmedUnicast; 2316 dup->ImmedAdditional = rr->ImmedAdditional; 2317 dup->v4Requester = rr->v4Requester; 2318 dup->v6Requester = rr->v6Requester; 2319 dup->ThisAPInterval = rr->ThisAPInterval; 2320 dup->LastAPTime = rr->LastAPTime; 2321 dup->LastMCTime = rr->LastMCTime; 2322 dup->LastMCInterface = rr->LastMCInterface; 2323 dup->Private = rr->Private; 2324 dup->state = rr->state; 2325 rr->RequireGoodbye = mDNSfalse; 2326 rr->AnsweredLocalQ = mDNSfalse; 2327 } 2328 } 2329 } 2330 else 2331 { 2332 // We didn't find our record on the main list; try the DuplicateRecords list instead. 2333 p = &m->DuplicateRecords; 2334 while (*p && *p != rr) p=&(*p)->next; 2335 // If we found our record on the duplicate list, then make sure we don't send a goodbye for it 2336 if (*p) 2337 { 2338 // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them 2339 // immediately. When there is a conflict, we deregister all the conflicting duplicate records 2340 // also that have been marked above in this function. In that case, we come here and if we don't 2341 // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence, 2342 // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for 2343 // details. 2344 rr->WakeUp.HMAC = zeroEthAddr; 2345 rr->RequireGoodbye = mDNSfalse; 2346 rr->resrec.RecordType = kDNSRecordTypeDeregistering; 2347 dupList = mDNStrue; 2348 } 2349 if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)", 2350 rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); 2351 } 2352 2353 if (!*p) 2354 { 2355 // No need to log an error message if we already know this is a potentially repeated deregistration 2356 if (drt != mDNS_Dereg_repeat) 2357 { 2358 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Deregister_internal: Record %p not found in list " PRI_S, rr, ARDisplayString(m,rr)); 2359 } 2360 return(mStatus_BadReferenceErr); 2361 } 2362 2363 // If this is a shared record and we've announced it at least once, 2364 // we need to retract that announcement before we delete the record 2365 2366 // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then 2367 // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe. 2368 // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion" 2369 // mechanism to cope with the client callback modifying the question list while that's happening. 2370 // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain) 2371 // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice. 2372 // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other 2373 // records, thereby invoking yet more callbacks, without limit. 2374 // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending 2375 // actual goodbye packets. 2376 2377 #ifndef UNICAST_DISABLED 2378 if (AuthRecord_uDNS(rr)) 2379 { 2380 if (rr->RequireGoodbye) 2381 { 2382 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; } 2383 rr->resrec.RecordType = kDNSRecordTypeDeregistering; 2384 m->LocalRemoveEvents = mDNStrue; 2385 uDNS_DeregisterRecord(m, rr); 2386 // At this point unconditionally we bail out 2387 // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration, 2388 // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration 2389 // process and will complete asynchronously. Either way we don't need to do anything more here. 2390 return(mStatus_NoError); 2391 } 2392 // Sometimes the records don't complete proper deregistration i.e., don't wait for a response 2393 // from the server. In that case, if the records have been part of a group update, clear the 2394 // state here. 2395 rr->updateid = zeroID; 2396 2397 // We defer cleaning up NAT state only after sending goodbyes. This is important because 2398 // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL. 2399 // This happens today when we turn on/off interface where we get multiple network transitions 2400 // and RestartRecordGetZoneData triggers re-registration of the resource records even though 2401 // they may be in Registered state which causes NAT information to be setup multiple times. Defering 2402 // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up 2403 // NAT state here takes care of the case where we did not send goodbyes at all. 2404 if (rr->NATinfo.clientContext) 2405 { 2406 mDNS_StopNATOperation_internal(m, &rr->NATinfo); 2407 rr->NATinfo.clientContext = mDNSNULL; 2408 } 2409 if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; } 2410 if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; } 2411 } 2412 #endif // UNICAST_DISABLED 2413 2414 if (RecordType == kDNSRecordTypeUnregistered) 2415 { 2416 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Deregister_internal: " PRI_S " already marked kDNSRecordTypeUnregistered", 2417 ARDisplayString(m, rr)); 2418 } 2419 else if (RecordType == kDNSRecordTypeDeregistering) 2420 { 2421 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Deregister_internal: " PRI_S " already marked kDNSRecordTypeDeregistering", 2422 ARDisplayString(m, rr)); 2423 return(mStatus_BadReferenceErr); 2424 } 2425 2426 if (rr->WakeUp.HMAC.l[0] || 2427 (((RecordType == kDNSRecordTypeShared) || (rr->ARType == AuthRecordLocalOnly)) && 2428 (rr->RequireGoodbye || rr->AnsweredLocalQ))) 2429 { 2430 verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr)); 2431 rr->resrec.RecordType = kDNSRecordTypeDeregistering; 2432 rr->resrec.rroriginalttl = 0; 2433 rr->AnnounceCount = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount; 2434 rr->ThisAPInterval = mDNSPlatformOneSecond * 2; 2435 rr->LastAPTime = m->timenow - rr->ThisAPInterval; 2436 m->LocalRemoveEvents = mDNStrue; 2437 if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0) 2438 m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10); 2439 } 2440 else 2441 { 2442 // If the AuthRecord isn't a duplicate, isn't LocalOnly, and is unique, then flush each cached record that was 2443 // received via an interface that applies to the AuthRecord and whose name, type, class, and record data matches 2444 // that of the AuthRecord. 2445 // 2446 // Some clients are counting on fully deregistered records to no longer be present in the record cache (see 2447 // rdar://121145674). 2448 // 2449 // Notes: 2450 // 1. LocalOnly AuthRecords don't cause any mDNS traffic, so their records never populate the record cache. 2451 // 2. Shared AuthRecords, unlike unique AuthRecords, send out goodbye packets when deregistered, which causes 2452 // their cached copies to be purged from record caches including this mDNSResponder's record cache. 2453 if (!dupList && !RRLocalOnly(rr) && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)) 2454 { 2455 cg = CacheGroupForRecord(m, &rr->resrec); 2456 for (CacheRecord *cr = cg ? cg->members : mDNSNULL; cr; cr = cr->next) 2457 { 2458 const mDNSInterfaceID interface = cr->resrec.InterfaceID; 2459 if (IsInterfaceValidForAuthRecord(rr, interface) && IdenticalSameNameRecord(&cr->resrec, &rr->resrec)) 2460 { 2461 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEBUG, 2462 "mDNS_Deregister_internal: Purging cached record that matches deregistered AuthRecord -- " 2463 "interface: " PUB_S "/%u, record: " PRI_S, 2464 InterfaceNameForIDOrEmptyString(interface), IIDPrintable(interface), CRDisplayString(m, cr)); 2465 mDNS_PurgeCacheResourceRecord(m, cr); 2466 } 2467 } 2468 } 2469 if (!dupList && RRLocalOnly(rr)) 2470 { 2471 AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr); 2472 if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next; 2473 } 2474 else 2475 { 2476 *p = rr->next; // Cut this record from the list 2477 if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next; 2478 DecrementAutoTargetServices(m, rr); 2479 } 2480 // If someone is about to look at this, bump the pointer forward 2481 if (m->CurrentRecord == rr) m->CurrentRecord = rr->next; 2482 rr->next = mDNSNULL; 2483 2484 verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr)); 2485 rr->resrec.RecordType = kDNSRecordTypeUnregistered; 2486 2487 if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_stale || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared) 2488 debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)", 2489 rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); 2490 2491 // If we have an update queued up which never executed, give the client a chance to free that memory 2492 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client 2493 2494 2495 // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function 2496 // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc. 2497 // In this case the likely client action to the mStatus_MemFree message is to free the memory, 2498 // so any attempt to touch rr after this is likely to lead to a crash. 2499 if (drt != mDNS_Dereg_conflict && drt != mDNS_Dereg_stale) 2500 { 2501 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback 2502 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "mDNS_Deregister_internal: callback with mStatus_MemFree for " PRI_S, ARDisplayString(m, rr)); 2503 if (rr->RecordCallback) 2504 rr->RecordCallback(m, rr, mStatus_MemFree); // MUST NOT touch rr after this 2505 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 2506 } 2507 else 2508 { 2509 const mStatus status_result = (drt == mDNS_Dereg_conflict) ? mStatus_NameConflict : mStatus_StaleData; 2510 RecordProbeFailure(m, rr); 2511 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback 2512 if (rr->RecordCallback) 2513 rr->RecordCallback(m, rr, status_result); // MUST NOT touch rr after this 2514 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 2515 // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously. 2516 // Note that with all the client callbacks going on, by the time we get here all the 2517 // records we marked may have been explicitly deregistered by the client anyway. 2518 r2 = m->DuplicateRecords; 2519 while (r2) 2520 { 2521 if (r2->ProbeCount != 0xFF) 2522 { 2523 r2 = r2->next; 2524 } 2525 else 2526 { 2527 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 2528 // See if this record was also registered with any D2D plugins. 2529 D2D_stop_advertising_record(r2); 2530 #endif 2531 mDNS_Deregister_internal(m, r2, status_result); 2532 // As this is a duplicate record, it will be unlinked from the list 2533 // immediately 2534 r2 = m->DuplicateRecords; 2535 } 2536 } 2537 } 2538 } 2539 mDNS_UpdateAllowSleep(m); 2540 2541 // Find the corresponding TSR after we have finished the clean process. 2542 AuthRecord *const tsr = isTSR ? NULL : 2543 FindOrphanedTSR(m, &nameToMatchTSR, nameHashToMatchTSR); 2544 2545 // When the last record sharing the same with the TSR record was deregistered, we should deregister the TSR record. 2546 if (tsr) 2547 { 2548 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 2549 "Deregistering orphaned TSR - " PRI_S, ARDisplayString(m, tsr)); 2550 mDNS_Deregister_internal(m, tsr, mDNS_Dereg_repeat); 2551 2552 if (cg) 2553 { // Also remove associated TSR cache record 2554 CacheRecord *cacheTSR = mDNSGetTSRForCacheGroup(cg); 2555 if (cacheTSR) 2556 { 2557 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, 2558 "Purging cached TSR record that matches orphaned TSR -- " PRI_S, CRDisplayString(m, cacheTSR)); 2559 mDNS_PurgeCacheResourceRecord(m, cacheTSR); 2560 } 2561 } 2562 } 2563 2564 return(mStatus_NoError); 2565 } 2566 2567 // *************************************************************************** 2568 // MARK: - Packet Sending Functions 2569 2570 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add) 2571 { 2572 // Add the record if it hasn't already been added. 2573 if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse) 2574 { 2575 **nrpp = rr; 2576 // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo) 2577 // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does 2578 // The referenced record will definitely be acceptable (by recursive application of this rule) 2579 if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo; 2580 rr->NR_AdditionalTo = add; 2581 *nrpp = &rr->NextResponse; 2582 debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); 2583 } 2584 } 2585 2586 mDNSlocal void AddRRSetAdditionalsToResponseList(mDNS *const m, AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *additional, const mDNSInterfaceID InterfaceID) 2587 { 2588 AuthRecord *rr2; 2589 if (additional->resrec.RecordType & kDNSRecordTypeUniqueMask) 2590 { 2591 for (rr2 = m->ResourceRecords; rr2; rr2 = rr2->next) 2592 { 2593 if ((rr2->resrec.namehash == additional->resrec.namehash) && 2594 (rr2->resrec.rrtype == additional->resrec.rrtype) && 2595 (rr2 != additional) && 2596 (rr2->resrec.RecordType & kDNSRecordTypeUniqueMask) && 2597 (rr2->resrec.rrclass == additional->resrec.rrclass) && 2598 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && 2599 SameDomainName(rr2->resrec.name, additional->resrec.name)) 2600 { 2601 AddRecordToResponseList(nrpp, rr2, rr); 2602 } 2603 } 2604 } 2605 } 2606 2607 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID) 2608 { 2609 AuthRecord *rr, *rr2; 2610 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // For each record we plan to put 2611 { 2612 // (Note: This is an "if", not a "while". If we add a record, we'll find it again 2613 // later in the "for" loop, and we will follow further "additional" links then.) 2614 if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID)) 2615 { 2616 AddRecordToResponseList(nrpp, rr->Additional1, rr); 2617 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional1, InterfaceID); 2618 } 2619 2620 if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID)) 2621 { 2622 AddRecordToResponseList(nrpp, rr->Additional2, rr); 2623 AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional2, InterfaceID); 2624 } 2625 2626 // For SRV records, automatically add the Address record(s) for the target host 2627 if (rr->resrec.rrtype == kDNSType_SRV) 2628 { 2629 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records 2630 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ... 2631 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ... 2632 rr->resrec.rdatahash == rr2->resrec.namehash && // ... whose name is the name of the SRV target 2633 SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name)) 2634 AddRecordToResponseList(nrpp, rr2, rr); 2635 } 2636 else if (RRTypeIsAddressType(rr->resrec.rrtype)) // For A or AAAA, put counterpart as additional 2637 { 2638 for (rr2=m->ResourceRecords; rr2; rr2=rr2->next) // Scan list of resource records 2639 if (RRTypeIsAddressType(rr2->resrec.rrtype) && // For all address records (A/AAAA) ... 2640 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) && // ... which are valid for answer ... 2641 rr->resrec.namehash == rr2->resrec.namehash && // ... and have the same name 2642 SameDomainName(rr->resrec.name, rr2->resrec.name)) 2643 AddRecordToResponseList(nrpp, rr2, rr); 2644 } 2645 else if (rr->resrec.rrtype == kDNSType_PTR) // For service PTR, see if we want to add DeviceInfo record 2646 { 2647 if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) && 2648 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c)) 2649 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr); 2650 } 2651 } 2652 } 2653 2654 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID) 2655 { 2656 AuthRecord *rr; 2657 AuthRecord *ResponseRecords = mDNSNULL; 2658 AuthRecord **nrp = &ResponseRecords; 2659 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID); 2660 2661 // Make a list of all our records that need to be unicast to this destination 2662 for (rr = m->ResourceRecords; rr; rr=rr->next) 2663 { 2664 // If we find we can no longer unicast this answer, clear ImmedUnicast 2665 if (rr->ImmedAnswer == mDNSInterfaceMark || 2666 mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) || 2667 mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr) ) 2668 rr->ImmedUnicast = mDNSfalse; 2669 2670 if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID) 2671 { 2672 if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) || 2673 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6))) 2674 { 2675 rr->ImmedAnswer = mDNSNULL; // Clear the state fields 2676 rr->ImmedUnicast = mDNSfalse; 2677 rr->v4Requester = zerov4Addr; 2678 rr->v6Requester = zerov6Addr; 2679 2680 // Only sent records registered for P2P over P2P interfaces 2681 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID)) 2682 { 2683 continue; 2684 } 2685 2686 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse) // rr->NR_AnswerTo 2687 { 2688 rr->NR_AnswerTo = NR_AnswerMulticast; 2689 *nrp = rr; 2690 nrp = &rr->NextResponse; 2691 } 2692 } 2693 } 2694 } 2695 2696 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID); 2697 2698 while (ResponseRecords) 2699 { 2700 TSRDataPtrRecHead tsrOpts = SLIST_HEAD_INITIALIZER(tsrOpts); 2701 TSROptData *newTSROpt; 2702 mDNSu16 tsrOptsCount = 0; 2703 mDNSu8 *responseptr = m->omsg.data; 2704 mDNSu8 *newptr; 2705 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags); 2706 2707 // Put answers in the packet 2708 while (ResponseRecords && ResponseRecords->NR_AnswerTo) 2709 { 2710 rr = ResponseRecords; 2711 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) 2712 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it 2713 2714 if ((newTSROpt = TSROptGetIfNew(m, rr, &tsrOpts)) != mDNSNULL) tsrOptsCount++; 2715 newptr = PutResourceRecordTSR(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec); 2716 if (newTSROpt) 2717 { 2718 if (newptr) TSRDataRecPtrHeadAddTSROpt(&tsrOpts, newTSROpt, rr->resrec.name, m->omsg.h.numAnswers - 1); 2719 else tsrOptsCount--; 2720 } 2721 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state 2722 if (!newptr && m->omsg.h.numAnswers) 2723 { 2724 break; // If packet full, send it now 2725 } 2726 if (newptr) responseptr = newptr; 2727 ResponseRecords = rr->NextResponse; 2728 rr->NextResponse = mDNSNULL; 2729 rr->NR_AnswerTo = mDNSNULL; 2730 rr->NR_AdditionalTo = mDNSNULL; 2731 rr->RequireGoodbye = mDNStrue; 2732 } 2733 2734 // Add additionals, if there's space 2735 while (ResponseRecords && !ResponseRecords->NR_AnswerTo) 2736 { 2737 rr = ResponseRecords; 2738 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) 2739 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it 2740 if ((newTSROpt = TSROptGetIfNew(m, rr, &tsrOpts)) != mDNSNULL) tsrOptsCount++; 2741 newptr = PutResourceRecordTSR(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec); 2742 if (newTSROpt) 2743 { 2744 if (newptr) TSRDataRecPtrHeadAddTSROpt(&tsrOpts, newTSROpt, rr->resrec.name, m->omsg.h.numAnswers + m->omsg.h.numAdditionals - 1); 2745 else tsrOptsCount--; 2746 } 2747 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state 2748 if (newptr) responseptr = newptr; 2749 if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue; 2750 else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark; 2751 ResponseRecords = rr->NextResponse; 2752 rr->NextResponse = mDNSNULL; 2753 rr->NR_AnswerTo = mDNSNULL; 2754 rr->NR_AdditionalTo = mDNSNULL; 2755 } 2756 2757 if (m->omsg.h.numAnswers) 2758 { 2759 if (!SLIST_EMPTY(&tsrOpts)) 2760 { 2761 mDNSu8 *saveptr; 2762 AuthRecord opt; 2763 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); 2764 opt.resrec.rrclass = NormalMaxDNSMessageData; 2765 opt.resrec.rdlength = 0; 2766 opt.resrec.rdestimate = 0; 2767 if (!SLIST_EMPTY(&tsrOpts)) 2768 { 2769 opt.resrec.rdlength += sizeof(rdataOPT); 2770 opt.resrec.rdestimate += sizeof(rdataOPT); 2771 SetupTSROpt(SLIST_FIRST(&tsrOpts)->tsr, &opt.resrec.rdata->u.opt[0]); 2772 TSRDataRecPtrHeadRemoveAndFreeFirst(&tsrOpts); 2773 } 2774 // Put record after first TSR 2775 saveptr = responseptr; 2776 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec); 2777 if (newptr && !SLIST_EMPTY(&tsrOpts)) 2778 { 2779 mDNSu8 *rdlengthptr = saveptr + 2 + 2 + 4 + 1; // rrtype, rrclass, ttl, 0-length name 2780 newptr = AddTSRROptsToMessage(&tsrOpts, &m->omsg, rdlengthptr, newptr, 2781 m->omsg.data + AllowedRRSpace(&m->omsg)); 2782 } 2783 if (newptr) 2784 { 2785 responseptr = newptr; 2786 } 2787 else 2788 { 2789 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "SendDelayedUnicastResponse: How did we fail to have space for OPT record (%d/%d/%d/%d) %s", 2790 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt)); 2791 } 2792 } 2793 mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSfalse); 2794 } 2795 TSRDataRecPtrHeadFreeList(&tsrOpts); 2796 } 2797 } 2798 2799 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list 2800 // and the client's mStatus_MemFree callback will have been invoked 2801 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr) 2802 { 2803 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "CompleteDeregistration: called for Resource record " PRI_S, ARDisplayString(m, rr)); 2804 // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that 2805 // it should go ahead and immediately dispose of this registration 2806 rr->resrec.RecordType = kDNSRecordTypeShared; 2807 rr->RequireGoodbye = mDNSfalse; 2808 rr->WakeUp.HMAC = zeroEthAddr; 2809 if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); rr->AnsweredLocalQ = mDNSfalse; } 2810 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); // Don't touch rr after this 2811 } 2812 2813 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately) 2814 // any deregistering records that remain in the m->ResourceRecords list. 2815 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback, 2816 // which may change the record list and/or question list. 2817 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 2818 mDNSlocal void DiscardDeregistrations(mDNS *const m) 2819 { 2820 if (m->CurrentRecord) 2821 { 2822 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "DiscardDeregistrations ERROR m->CurrentRecord already set " PRI_S, 2823 ARDisplayString(m, m->CurrentRecord)); 2824 } 2825 m->CurrentRecord = m->ResourceRecords; 2826 2827 while (m->CurrentRecord) 2828 { 2829 AuthRecord *rr = m->CurrentRecord; 2830 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering) 2831 CompleteDeregistration(m, rr); // Don't touch rr after this 2832 else 2833 m->CurrentRecord = rr->next; 2834 } 2835 } 2836 2837 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst) 2838 { 2839 int i, val = 0; 2840 if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid); 2841 for (i=1; i<=src[0]; i++) 2842 { 2843 if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid); 2844 val = val * 10 + src[i] - '0'; 2845 } 2846 if (val > 255) return(mStatus_Invalid); 2847 *dst = (mDNSu8)val; 2848 return(mStatus_NoError); 2849 } 2850 2851 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name) 2852 { 2853 int skip = CountLabels(name) - 6; 2854 if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; } 2855 if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) || 2856 GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) || 2857 GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) || 2858 GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid; 2859 a->type = mDNSAddrType_IPv4; 2860 return(mStatus_NoError); 2861 } 2862 2863 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \ 2864 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \ 2865 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1) 2866 2867 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name) 2868 { 2869 int i, h, l; 2870 const domainname *n; 2871 2872 int skip = CountLabels(name) - 34; 2873 if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; } 2874 2875 n = SkipLeadingLabels(name, skip); 2876 for (i=0; i<16; i++) 2877 { 2878 if (n->c[0] != 1) return mStatus_Invalid; 2879 l = HexVal(n->c[1]); 2880 n = (const domainname *)(n->c + 2); 2881 2882 if (n->c[0] != 1) return mStatus_Invalid; 2883 h = HexVal(n->c[1]); 2884 n = (const domainname *)(n->c + 2); 2885 2886 if (l<0 || h<0) return mStatus_Invalid; 2887 a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l); 2888 } 2889 2890 a->type = mDNSAddrType_IPv6; 2891 return(mStatus_NoError); 2892 } 2893 2894 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name) 2895 { 2896 int skip = CountLabels(name) - 2; 2897 if (skip >= 0) 2898 { 2899 const domainname *suffix = SkipLeadingLabels(name, skip); 2900 if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4; 2901 if (SameDomainName(suffix, (const domainname*)"\x3" "ip6" "\x4" "arpa")) return mDNSAddrType_IPv6; 2902 } 2903 return(mDNSAddrType_None); 2904 } 2905 2906 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr, 2907 const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst) 2908 { 2909 int i; 2910 mDNSu8 *ptr = m->omsg.data; 2911 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID); 2912 if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; } 2913 2914 // 0x00 Destination address 2915 for (i=0; i<6; i++) *ptr++ = dst->b[i]; 2916 2917 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us) 2918 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0]; 2919 2920 // 0x0C ARP Ethertype (0x0806) 2921 *ptr++ = 0x08; *ptr++ = 0x06; 2922 2923 // 0x0E ARP header 2924 *ptr++ = 0x00; *ptr++ = 0x01; // Hardware address space; Ethernet = 1 2925 *ptr++ = 0x08; *ptr++ = 0x00; // Protocol address space; IP = 0x0800 2926 *ptr++ = 6; // Hardware address length 2927 *ptr++ = 4; // Protocol address length 2928 *ptr++ = 0x00; *ptr++ = op; // opcode; Request = 1, Response = 2 2929 2930 // 0x16 Sender hardware address (our MAC address) 2931 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i]; 2932 2933 // 0x1C Sender protocol address 2934 for (i=0; i<4; i++) *ptr++ = spa->b[i]; 2935 2936 // 0x20 Target hardware address 2937 for (i=0; i<6; i++) *ptr++ = tha->b[i]; 2938 2939 // 0x26 Target protocol address 2940 for (i=0; i<4; i++) *ptr++ = tpa->b[i]; 2941 2942 // 0x2A Total ARP Packet length 42 bytes 2943 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID); 2944 } 2945 2946 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum) 2947 { 2948 const mDNSu16 *ptr = data; 2949 while (length > 0) { length -= 2; sum += *ptr++; } 2950 sum = (sum & 0xFFFF) + (sum >> 16); 2951 sum = (sum & 0xFFFF) + (sum >> 16); 2952 return (mDNSu16)(sum != 0xFFFF ? sum : 0); 2953 } 2954 2955 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length) 2956 { 2957 IPv6PseudoHeader ph; 2958 ph.src = *src; 2959 ph.dst = *dst; 2960 ph.len.b[0] = (mDNSu8)(length >> 24); 2961 ph.len.b[1] = (mDNSu8)(length >> 16); 2962 ph.len.b[2] = (mDNSu8)(length >> 8); 2963 ph.len.b[3] = (mDNSu8) length; 2964 ph.pro.b[0] = 0; 2965 ph.pro.b[1] = 0; 2966 ph.pro.b[2] = 0; 2967 ph.pro.b[3] = protocol; 2968 return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0)); 2969 } 2970 2971 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr, 2972 const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst) 2973 { 2974 int i; 2975 mDNSOpaque16 checksum; 2976 mDNSu8 *ptr = m->omsg.data; 2977 // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the 2978 // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though 2979 // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth. 2980 const mDNSv6Addr mc = { { 0xFF,0x02,0x00,0x00, 0,0,0,0, 0,0,0,1, 0xFF,tpa->b[0xD],tpa->b[0xE],tpa->b[0xF] } }; 2981 const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa; 2982 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID); 2983 if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; } 2984 2985 // 0x00 Destination address 2986 for (i=0; i<6; i++) *ptr++ = dst->b[i]; 2987 // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet. 2988 // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the 2989 // link with a pointless link-layer multicast. 2990 // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what 2991 // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address: 2992 // *ptr++ = 0x33; 2993 // *ptr++ = 0x33; 2994 // *ptr++ = 0xFF; 2995 // *ptr++ = tpa->b[0xD]; 2996 // *ptr++ = tpa->b[0xE]; 2997 // *ptr++ = tpa->b[0xF]; 2998 2999 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us) 3000 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i]; 3001 3002 // 0x0C IPv6 Ethertype (0x86DD) 3003 *ptr++ = 0x86; *ptr++ = 0xDD; 3004 3005 // 0x0E IPv6 header 3006 *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; // Version, Traffic Class, Flow Label 3007 *ptr++ = 0x00; *ptr++ = 0x20; // Length 3008 *ptr++ = 0x3A; // Protocol == ICMPv6 3009 *ptr++ = 0xFF; // Hop Limit 3010 3011 // 0x16 Sender IPv6 address 3012 for (i=0; i<16; i++) *ptr++ = spa->b[i]; 3013 3014 // 0x26 Destination IPv6 address 3015 for (i=0; i<16; i++) *ptr++ = v6dst->b[i]; 3016 3017 // 0x36 NDP header 3018 *ptr++ = op; // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement 3019 *ptr++ = 0x00; // Code 3020 *ptr++ = 0x00; *ptr++ = 0x00; // Checksum placeholder (0x38, 0x39) 3021 *ptr++ = flags; 3022 *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00; 3023 3024 if (op == NDP_Sol) // Neighbor Solicitation. The NDP "target" is the address we seek. 3025 { 3026 // 0x3E NDP target. 3027 for (i=0; i<16; i++) *ptr++ = tpa->b[i]; 3028 // 0x4E Source Link-layer Address 3029 // <http://www.ietf.org/rfc/rfc2461.txt> 3030 // MUST NOT be included when the source IP address is the unspecified address. 3031 // Otherwise, on link layers that have addresses this option MUST be included 3032 // in multicast solicitations and SHOULD be included in unicast solicitations. 3033 if (!mDNSIPv6AddressIsZero(*spa)) 3034 { 3035 *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address 3036 *ptr++ = 0x01; // Option length 1 (in units of 8 octets) 3037 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i]; 3038 } 3039 } 3040 else // Neighbor Advertisement. The NDP "target" is the address we're giving information about. 3041 { 3042 // 0x3E NDP target. 3043 for (i=0; i<16; i++) *ptr++ = spa->b[i]; 3044 // 0x4E Target Link-layer Address 3045 *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address 3046 *ptr++ = 0x01; // Option length 1 (in units of 8 octets) 3047 for (i=0; i<6; i++) *ptr++ = (tha ? *tha : intf->MAC).b[i]; 3048 } 3049 3050 // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes 3051 m->omsg.data[0x13] = (mDNSu8)(ptr - &m->omsg.data[0x36]); // Compute actual length 3052 checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]); 3053 m->omsg.data[0x38] = checksum.b[0]; 3054 m->omsg.data[0x39] = checksum.b[1]; 3055 3056 mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID); 3057 } 3058 3059 mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace) 3060 { 3061 mDNSu32 DNS_VERS = _DNS_SD_H; 3062 Trace->u.tracer.platf = m->mDNS_plat; 3063 Trace->u.tracer.mDNSv = DNS_VERS; 3064 3065 Trace->opt = kDNSOpt_Trace; 3066 Trace->optlen = DNSOpt_TraceData_Space - 4; 3067 } 3068 3069 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner) 3070 { 3071 owner->u.owner.vers = 0; 3072 owner->u.owner.seq = m->SleepSeqNum; 3073 owner->u.owner.HMAC = m->PrimaryMAC; 3074 owner->u.owner.IMAC = intf->MAC; 3075 owner->u.owner.password = zeroEthAddr; 3076 3077 // Don't try to compute the optlen until *after* we've set up the data fields 3078 // Right now the DNSOpt_Owner_Space macro does not depend on the owner->u.owner being set up correctly, but in the future it might 3079 owner->opt = kDNSOpt_Owner; 3080 owner->optlen = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4; 3081 } 3082 3083 mDNSlocal void GrantUpdateCredit(AuthRecord *rr) 3084 { 3085 if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0; 3086 else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval); 3087 } 3088 3089 mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr) 3090 { 3091 // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly 3092 // and hence there is no need to check for Transfering state. But if we have sleep 3093 // proxies and partially sending goodbyes for some records, we will be in Transfering 3094 // state and hence need to make sure that we send goodbyes in that case too. Checking whether 3095 // we are not awake handles both cases. 3096 if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake)) 3097 { 3098 debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr)); 3099 return mDNStrue; 3100 } 3101 3102 if (m->SleepState != SleepState_Sleeping) 3103 return mDNSfalse; 3104 3105 // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you 3106 // whether you can send goodbyes or not. 3107 if (!intf->SendGoodbyes) 3108 { 3109 debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID); 3110 return mDNSfalse; 3111 } 3112 else 3113 { 3114 debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID); 3115 return mDNStrue; 3116 } 3117 } 3118 3119 mDNSlocal mDNSu32 DetermineOwnerRecordSpace(const NetworkInterfaceInfo *const intf) 3120 { 3121 mDNSu32 space = 0; 3122 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 3123 mDNS *const m = &mDNSStorage; 3124 if (m->AnnounceOwner && intf->MAC.l[0]) 3125 { 3126 space = DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC); 3127 } 3128 #else 3129 (void)intf; 3130 #endif 3131 return space; 3132 } 3133 3134 // Note about acceleration of announcements to facilitate automatic coalescing of 3135 // multiple independent threads of announcements into a single synchronized thread: 3136 // The announcements in the packet may be at different stages of maturity; 3137 // One-second interval, two-second interval, four-second interval, and so on. 3138 // After we've put in all the announcements that are due, we then consider 3139 // whether there are other nearly-due announcements that are worth accelerating. 3140 // To be eligible for acceleration, a record MUST NOT be older (further along 3141 // its timeline) than the most mature record we've already put in the packet. 3142 // In other words, younger records can have their timelines accelerated to catch up 3143 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync. 3144 // Older records cannot have their timelines accelerated; this would just widen 3145 // the gap between them and their younger bretheren and get them even more out of sync. 3146 3147 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change 3148 // the record list and/or question list. 3149 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 3150 mDNSlocal void SendResponses(mDNS *const m) 3151 { 3152 int pktcount = 0; 3153 AuthRecord *rr, *r2; 3154 mDNSs32 maxExistingAnnounceInterval = 0; 3155 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces); 3156 3157 m->NextScheduledResponse = m->timenow + FutureTime; 3158 3159 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 3160 if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m); 3161 #endif 3162 3163 for (rr = m->ResourceRecords; rr; rr=rr->next) 3164 if (rr->ImmedUnicast) 3165 { 3166 mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} }; 3167 mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} }; 3168 v4.ip.v4 = rr->v4Requester; 3169 v6.ip.v6 = rr->v6Requester; 3170 if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer); 3171 if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer); 3172 if (rr->ImmedUnicast) 3173 { 3174 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr)); 3175 rr->ImmedUnicast = mDNSfalse; 3176 } 3177 } 3178 3179 // *** 3180 // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on 3181 // *** 3182 3183 // Run through our list of records, and decide which ones we're going to announce on all interfaces 3184 for (rr = m->ResourceRecords; rr; rr=rr->next) 3185 { 3186 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr); 3187 if (TimeToAnnounceThisRecord(rr, m->timenow)) 3188 { 3189 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) 3190 { 3191 if (!rr->WakeUp.HMAC.l[0]) 3192 { 3193 if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark; // Send goodbye packet on all interfaces 3194 } 3195 else 3196 { 3197 mDNSBool unicastOnly; 3198 LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); 3199 unicastOnly = ((rr->AnnounceCount == WakeupCount) || (rr->AnnounceCount == WakeupCount - 1)) ? mDNStrue : mDNSfalse; 3200 SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password, unicastOnly); 3201 for (r2 = rr; r2; r2=r2->next) 3202 if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) && 3203 mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC)) 3204 { 3205 // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original 3206 // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict. 3207 if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount) 3208 { 3209 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s", 3210 r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2)); 3211 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth); 3212 } 3213 r2->LastAPTime = m->timenow; 3214 // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead 3215 if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr; 3216 } 3217 } 3218 } 3219 else if (ResourceRecordIsValidAnswer(rr)) 3220 { 3221 if (rr->AddressProxy.type) 3222 { 3223 if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC)) 3224 { 3225 rr->AnnounceCount--; 3226 rr->ThisAPInterval *= 2; 3227 rr->LastAPTime = m->timenow; 3228 if (rr->AddressProxy.type == mDNSAddrType_IPv4) 3229 { 3230 LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s", 3231 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr)); 3232 SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr); 3233 } 3234 else if (rr->AddressProxy.type == mDNSAddrType_IPv6) 3235 { 3236 LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s", 3237 rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr)); 3238 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth); 3239 } 3240 } 3241 } 3242 else 3243 { 3244 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces 3245 if (maxExistingAnnounceInterval < rr->ThisAPInterval) 3246 maxExistingAnnounceInterval = rr->ThisAPInterval; 3247 if (rr->UpdateBlocked) rr->UpdateBlocked = 0; 3248 } 3249 } 3250 } 3251 } 3252 3253 // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one) 3254 // Eligible records that are more than half-way to their announcement time are accelerated 3255 for (rr = m->ResourceRecords; rr; rr=rr->next) 3256 if ((rr->resrec.InterfaceID && rr->ImmedAnswer) || 3257 (rr->ThisAPInterval <= maxExistingAnnounceInterval && 3258 TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) && 3259 !rr->AddressProxy.type && // Don't include ARP Annoucements when considering which records to accelerate 3260 ResourceRecordIsValidAnswer(rr))) 3261 rr->ImmedAnswer = mDNSInterfaceMark; // Send on all interfaces 3262 3263 // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals 3264 // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID, 3265 // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen) 3266 // then all that means is that it won't get sent -- which would not be the end of the world. 3267 for (rr = m->ResourceRecords; rr; rr=rr->next) 3268 { 3269 if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV) 3270 for (r2=m->ResourceRecords; r2; r2=r2->next) // Scan list of resource records 3271 if (RRTypeIsAddressType(r2->resrec.rrtype) && // For all address records (A/AAAA) ... 3272 ResourceRecordIsValidAnswer(r2) && // ... which are valid for answer ... 3273 rr->LastMCTime - r2->LastMCTime >= 0 && // ... which we have not sent recently ... 3274 rr->resrec.rdatahash == r2->resrec.namehash && // ... whose name is the name of the SRV target 3275 SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) && 3276 (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID)) 3277 r2->ImmedAdditional = r2->resrec.InterfaceID; // ... then mark this address record for sending too 3278 // We also make sure we send the DeviceInfo TXT record too, if necessary 3279 // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the 3280 // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering). 3281 if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR) 3282 if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c)) 3283 { 3284 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer; 3285 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark; 3286 } 3287 } 3288 3289 // If there's a record which is supposed to be unique that we're going to send, then make sure that we give 3290 // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class 3291 // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a 3292 // record, then other RRSet members that have not been sent recently will get flushed out of client caches. 3293 // -- If a record is marked to be sent on a certain interface, make sure the whole set is marked to be sent on that interface 3294 // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces 3295 for (rr = m->ResourceRecords; rr; rr=rr->next) 3296 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) 3297 { 3298 if (rr->ImmedAnswer) // If we're sending this as answer, see that its whole RRSet is similarly marked 3299 { 3300 for (r2 = m->ResourceRecords; r2; r2=r2->next) 3301 { 3302 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) && 3303 (r2->ImmedAnswer != mDNSInterfaceMark) && (r2->ImmedAnswer != rr->ImmedAnswer) && 3304 SameResourceRecordSignature(r2, rr) && 3305 ((rr->ImmedAnswer == mDNSInterfaceMark) || IsInterfaceValidForAuthRecord(r2, rr->ImmedAnswer))) 3306 { 3307 r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark; 3308 } 3309 } 3310 } 3311 else if (rr->ImmedAdditional) // If we're sending this as additional, see that its whole RRSet is similarly marked 3312 { 3313 for (r2 = m->ResourceRecords; r2; r2=r2->next) 3314 { 3315 if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) && 3316 (r2->ImmedAdditional != rr->ImmedAdditional) && 3317 SameResourceRecordSignature(r2, rr) && 3318 IsInterfaceValidForAuthRecord(r2, rr->ImmedAdditional)) 3319 { 3320 r2->ImmedAdditional = rr->ImmedAdditional; 3321 } 3322 } 3323 } 3324 } 3325 3326 // Now set SendRNow state appropriately 3327 for (rr = m->ResourceRecords; rr; rr=rr->next) 3328 { 3329 if (rr->ImmedAnswer == mDNSInterfaceMark) // Sending this record on all appropriate interfaces 3330 { 3331 rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID; 3332 rr->ImmedAdditional = mDNSNULL; // No need to send as additional if sending as answer 3333 rr->LastMCTime = m->timenow; 3334 rr->LastMCInterface = rr->ImmedAnswer; 3335 rr->ProbeRestartCount = 0; // Reset the probe restart count 3336 // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done 3337 if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2)) 3338 { 3339 rr->AnnounceCount--; 3340 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering) 3341 rr->ThisAPInterval *= 2; 3342 rr->LastAPTime = m->timenow; 3343 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount); 3344 } 3345 } 3346 else if (rr->ImmedAnswer) // Else, just respond to a single query on single interface: 3347 { 3348 rr->SendRNow = rr->ImmedAnswer; // Just respond on that interface 3349 rr->ImmedAdditional = mDNSNULL; // No need to send as additional too 3350 rr->LastMCTime = m->timenow; 3351 rr->LastMCInterface = rr->ImmedAnswer; 3352 } 3353 SetNextAnnounceProbeTime(m, rr); 3354 //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr)); 3355 } 3356 3357 // *** 3358 // *** 2. Loop through interface list, sending records as appropriate 3359 // *** 3360 3361 while (intf) 3362 { 3363 const mDNSu32 OwnerRecordSpace = DetermineOwnerRecordSpace(intf); 3364 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0; 3365 TSRDataPtrRecHead tsrOpts = SLIST_HEAD_INITIALIZER(tsrOpts); 3366 TSROptData *newTSROpt; 3367 mDNSu16 tsrOptsCount = 0; 3368 int numDereg = 0; 3369 int numAnnounce = 0; 3370 int numAnswer = 0; 3371 mDNSu8 *responseptr = m->omsg.data; 3372 mDNSu8 *newptr; 3373 InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags); 3374 3375 // First Pass. Look for: 3376 // 1. Deregistering records that need to send their goodbye packet 3377 // 2. Updated records that need to retract their old data 3378 // 3. Answers and announcements we need to send 3379 for (rr = m->ResourceRecords; rr; rr=rr->next) 3380 { 3381 3382 // Skip this interface if the record InterfaceID is *Any and the record is not 3383 // appropriate for the interface type. 3384 if ((rr->SendRNow == intf->InterfaceID) && 3385 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID))) 3386 { 3387 rr->SendRNow = GetNextActiveInterfaceID(intf); 3388 } 3389 else if (rr->SendRNow == intf->InterfaceID) 3390 { 3391 RData *OldRData = rr->resrec.rdata; 3392 mDNSu16 oldrdlength = rr->resrec.rdlength; 3393 mDNSu8 active = (mDNSu8) 3394 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr)); 3395 newptr = mDNSNULL; 3396 if (rr->NewRData && active) 3397 { 3398 // See if we should send a courtesy "goodbye" for the old data before we replace it. 3399 if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) 3400 { 3401 if ((newTSROpt = TSROptGetIfNew(m, rr, &tsrOpts)) != mDNSNULL) tsrOptsCount++; 3402 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0); 3403 if (newTSROpt) 3404 { 3405 if (newptr) TSRDataRecPtrHeadAddTSROpt(&tsrOpts, newTSROpt, rr->resrec.name, m->omsg.h.numAnswers - 1); 3406 else tsrOptsCount--; 3407 } 3408 if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; } 3409 else continue; // If this packet is already too full to hold the goodbye for this record, skip it for now and we'll retry later 3410 } 3411 SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength); 3412 } 3413 3414 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) 3415 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it 3416 if ((newTSROpt = TSROptGetIfNew(m, rr, &tsrOpts)) != mDNSNULL) tsrOptsCount++; 3417 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0); 3418 if (newTSROpt) 3419 { 3420 if (newptr) TSRDataRecPtrHeadAddTSROpt(&tsrOpts, newTSROpt, rr->resrec.name, m->omsg.h.numAnswers - 1); 3421 else tsrOptsCount--; 3422 } 3423 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state 3424 if (newptr) 3425 { 3426 responseptr = newptr; 3427 rr->RequireGoodbye = active; 3428 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++; 3429 else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++; 3430 } 3431 3432 if (rr->NewRData && active) 3433 SetNewRData(&rr->resrec, OldRData, oldrdlength); 3434 3435 // The first time through (pktcount==0), if this record is verified unique 3436 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too. 3437 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow) 3438 rr->SendNSECNow = mDNSInterfaceMark; 3439 3440 if (newptr) // If succeeded in sending, advance to next interface 3441 { 3442 // If sending on all interfaces, go to next interface; else we're finished now 3443 if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any) 3444 rr->SendRNow = GetNextActiveInterfaceID(intf); 3445 else 3446 rr->SendRNow = mDNSNULL; 3447 } 3448 } 3449 } 3450 3451 // Second Pass. Add additional records, if there's space. 3452 newptr = responseptr; 3453 for (rr = m->ResourceRecords; rr; rr=rr->next) 3454 if (rr->ImmedAdditional == intf->InterfaceID) 3455 if (ResourceRecordIsValidAnswer(rr)) 3456 { 3457 // If we have at least one answer already in the packet, then plan to add additionals too 3458 mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0); 3459 3460 // If we're not planning to send any additionals, but this record is a unique one, then 3461 // make sure we haven't already sent any other members of its RRSet -- if we have, then they 3462 // will have had the cache flush bit set, so now we need to finish the job and send the rest. 3463 if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)) 3464 { 3465 const AuthRecord *a; 3466 for (a = m->ResourceRecords; a; a=a->next) 3467 if (a->LastMCTime == m->timenow && 3468 a->LastMCInterface == intf->InterfaceID && 3469 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; } 3470 } 3471 if (!SendAdditional) // If we don't want to send this after all, 3472 rr->ImmedAdditional = mDNSNULL; // then cancel its ImmedAdditional field 3473 else if (newptr) // Else, try to add it if we can 3474 { 3475 // The first time through (pktcount==0), if this record is verified unique 3476 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too. 3477 if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow) 3478 rr->SendNSECNow = mDNSInterfaceMark; 3479 3480 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) 3481 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the cache flush bit so PutResourceRecord will set it 3482 if ((newTSROpt = TSROptGetIfNew(m, rr, &tsrOpts)) != mDNSNULL) tsrOptsCount++;; 3483 newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec); 3484 if (newTSROpt) 3485 { 3486 if (newptr) TSRDataRecPtrHeadAddTSROpt(&tsrOpts, newTSROpt, rr->resrec.name, m->omsg.h.numAnswers + m->omsg.h.numAdditionals - 1); 3487 else tsrOptsCount--; 3488 } 3489 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear cache flush bit back to normal state 3490 if (newptr) 3491 { 3492 responseptr = newptr; 3493 rr->ImmedAdditional = mDNSNULL; 3494 rr->RequireGoodbye = mDNStrue; 3495 // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface. 3496 // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise, 3497 // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get 3498 // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches. 3499 rr->LastMCTime = m->timenow; 3500 rr->LastMCInterface = intf->InterfaceID; 3501 } 3502 } 3503 } 3504 3505 // Third Pass. Add NSEC records, if there's space. 3506 // When we're generating an NSEC record in response to a specify query for that type 3507 // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section, 3508 // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here. 3509 for (rr = m->ResourceRecords; rr; rr=rr->next) 3510 if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID) 3511 { 3512 AuthRecord nsec; 3513 int len; 3514 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL); 3515 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet; 3516 AssignDomainName(&nsec.namestorage, rr->resrec.name); 3517 len = DomainNameLength(rr->resrec.name); 3518 // We have a nxt name followed by window number, window length and a window bitmap 3519 nsec.resrec.rdlength = (mDNSu16)(len + 2 + NSEC_MCAST_WINDOW_SIZE); 3520 if (nsec.resrec.rdlength <= StandardAuthRDSize) 3521 { 3522 mDNSu8 *ptr = nsec.rdatastorage.u.data; 3523 mDNSPlatformMemZero(ptr, nsec.resrec.rdlength); 3524 AssignDomainName(&nsec.rdatastorage.u.name, rr->resrec.name); 3525 ptr += len; 3526 *ptr++ = 0; // window number 3527 *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length 3528 for (r2 = m->ResourceRecords; r2; r2=r2->next) 3529 if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr)) 3530 { 3531 if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; } 3532 else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7); 3533 } 3534 newptr = responseptr; 3535 if (!r2) // If we successfully built our NSEC record, add it to the packet now 3536 { 3537 if ((newTSROpt = TSROptGetIfNew(m, rr, &tsrOpts)) != mDNSNULL) tsrOptsCount++; 3538 newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec); 3539 if (newTSROpt) 3540 { 3541 if (newptr) TSRDataRecPtrHeadAddTSROpt(&tsrOpts, newTSROpt, rr->resrec.name, m->omsg.h.numAnswers + m->omsg.h.numAdditionals - 1); 3542 else tsrOptsCount--; 3543 } 3544 if (newptr) responseptr = newptr; 3545 } 3546 } 3547 else LogMsg("SendResponses: not enough space (%d) in authrecord for nsec", nsec.resrec.rdlength); 3548 3549 // If we successfully put the NSEC record, clear the SendNSECNow flag 3550 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record 3551 if (newptr || rr->SendNSECNow == mDNSInterfaceMark) 3552 { 3553 rr->SendNSECNow = mDNSNULL; 3554 // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC 3555 for (r2 = rr->next; r2; r2=r2->next) 3556 if (SameResourceRecordNameClassInterface(r2, rr)) 3557 if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID) 3558 r2->SendNSECNow = mDNSNULL; 3559 } 3560 } 3561 3562 if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals) 3563 { 3564 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet 3565 if (OwnerRecordSpace || TraceRecordSpace || !SLIST_EMPTY(&tsrOpts)) 3566 { 3567 mDNSu8 *saveptr; 3568 AuthRecord opt; 3569 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); 3570 opt.resrec.rrclass = NormalMaxDNSMessageData; 3571 opt.resrec.rdlength = 0; 3572 opt.resrec.rdestimate = 0; 3573 mDNSu16 optCount = 0; 3574 if (OwnerRecordSpace) 3575 { 3576 opt.resrec.rdlength += sizeof(rdataOPT); 3577 opt.resrec.rdestimate += sizeof(rdataOPT); 3578 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[optCount++]); 3579 } 3580 if (TraceRecordSpace) 3581 { 3582 opt.resrec.rdlength += sizeof(rdataOPT); 3583 opt.resrec.rdestimate += sizeof(rdataOPT); 3584 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[optCount++]); 3585 } 3586 if (!SLIST_EMPTY(&tsrOpts)) 3587 { 3588 opt.resrec.rdlength += sizeof(rdataOPT); 3589 opt.resrec.rdestimate += sizeof(rdataOPT); 3590 SetupTSROpt(SLIST_FIRST(&tsrOpts)->tsr, &opt.resrec.rdata->u.opt[optCount++]); 3591 TSRDataRecPtrHeadRemoveAndFreeFirst(&tsrOpts); 3592 } 3593 // Put record after first TSR 3594 saveptr = responseptr; 3595 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec); 3596 if (newptr && !SLIST_EMPTY(&tsrOpts)) 3597 { 3598 mDNSu8 *rdlengthptr = saveptr + 2 + 2 + 4 + 1; // rrtype, rrclass, ttl, 0-length name 3599 newptr = AddTSRROptsToMessage(&tsrOpts, &m->omsg, rdlengthptr, newptr, 3600 m->omsg.data + AbsoluteMaxDNSMessageData); 3601 } 3602 if (newptr) 3603 { 3604 responseptr = newptr; 3605 } 3606 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1) 3607 { 3608 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "SendResponses: No space in packet for %s %s TSR(%d) OPT record (%d/%d/%d/%d) %s", 3609 OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", tsrOptsCount, 3610 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt)); 3611 } 3612 else 3613 { 3614 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "SendResponses: How did we fail to have space for %s %s TSR(%d) OPT record (%d/%d/%d/%d) %s", 3615 OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", tsrOptsCount, 3616 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt)); 3617 } 3618 } 3619 3620 debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p", 3621 numDereg, numDereg == 1 ? "" : "s", 3622 numAnnounce, numAnnounce == 1 ? "" : "s", 3623 numAnswer, numAnswer == 1 ? "" : "s", 3624 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID); 3625 3626 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSfalse); 3627 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSfalse); 3628 // If shutting down, don't suppress responses so that goodbyes for auth records get sent without delay. 3629 if (!m->SuppressResponses && !m->ShutdownTime) 3630 { 3631 m->SuppressResponses = NonZeroTime(m->timenow + ((mDNSPlatformOneSecond + 9) / 10)); 3632 } 3633 if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; } 3634 // There might be more things to send on this interface, so go around one more time and try again. 3635 } 3636 else // Nothing more to send on this interface; go to next 3637 { 3638 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next); 3639 intf = next; 3640 pktcount = 0; // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it 3641 } 3642 TSRDataRecPtrHeadFreeList(&tsrOpts); 3643 } 3644 3645 // *** 3646 // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables 3647 // *** 3648 3649 if (m->CurrentRecord) 3650 LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 3651 m->CurrentRecord = m->ResourceRecords; 3652 while (m->CurrentRecord) 3653 { 3654 rr = m->CurrentRecord; 3655 m->CurrentRecord = rr->next; 3656 3657 if (rr->SendRNow) 3658 { 3659 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P) 3660 { 3661 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "SendResponses: No active interface " 3662 "%d to send: %d %02X " PRI_S, IIDPrintable(rr->SendRNow), IIDPrintable(rr->resrec.InterfaceID), 3663 rr->resrec.RecordType, ARDisplayString(m, rr)); 3664 } 3665 3666 rr->SendRNow = mDNSNULL; 3667 } 3668 3669 if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering) 3670 { 3671 if (rr->NewRData) CompleteRDataUpdate(m, rr); // Update our rdata, clear the NewRData pointer, and return memory to the client 3672 3673 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0) 3674 { 3675 // For Unicast, when we get the response from the server, we will call CompleteDeregistration 3676 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr); // Don't touch rr after this 3677 } 3678 else 3679 { 3680 rr->ImmedAnswer = mDNSNULL; 3681 rr->ImmedUnicast = mDNSfalse; 3682 rr->v4Requester = zerov4Addr; 3683 rr->v6Requester = zerov6Addr; 3684 } 3685 } 3686 } 3687 verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow); 3688 } 3689 3690 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache, 3691 // so we want to be lazy about how frequently we do it. 3692 // 1. If a cache record is currently referenced by *no* active questions, 3693 // then we don't mind expiring it up to a minute late (who will know?) 3694 // 2. Else, if a cache record is due for some of its final expiration queries, 3695 // we'll allow them to be late by up to 2% of the TTL 3696 // 3. Else, if a cache record has completed all its final expiration queries without success, 3697 // and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late 3698 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets), 3699 // so allow at most 1/10 second lateness 3700 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately 3701 // (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients). 3702 #define CacheCheckGracePeriod(CR) ( \ 3703 ((CR)->CRActiveQuestion == mDNSNULL ) ? (60 * mDNSPlatformOneSecond) : \ 3704 ((CR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(CR)/50) : \ 3705 ((CR)->resrec.rroriginalttl > 10 ) ? (mDNSPlatformOneSecond) : \ 3706 ((CR)->resrec.rroriginalttl > 0 ) ? (mDNSPlatformOneSecond/10) : 0) 3707 3708 #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR)) 3709 3710 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event) 3711 { 3712 if (m->rrcache_nextcheck[slot] - event > 0) 3713 m->rrcache_nextcheck[slot] = event; 3714 if (m->NextCacheCheck - event > 0) 3715 m->NextCacheCheck = event; 3716 } 3717 3718 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change: 3719 // rr->TimeRcvd 3720 // rr->resrec.rroriginalttl 3721 // rr->UnansweredQueries 3722 // rr->CRActiveQuestion 3723 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr) 3724 { 3725 rr->NextRequiredQuery = RRExpireTime(rr); 3726 3727 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 3728 // Do not schedule the refresher query for DNSSEC-validated record, because its TTL is controlled by multiple 3729 // records that might be already in the progress of refreshing. 3730 // Set UnansweredQueries to MaxUnansweredQueries to avoid the expensive and unnecessary queries. 3731 if (resource_record_is_dnssec_validated(&rr->resrec) && rr->UnansweredQueries != MaxUnansweredQueries) 3732 { 3733 rr->UnansweredQueries = MaxUnansweredQueries; 3734 } 3735 #endif 3736 3737 // If we have an active question, then see if we want to schedule a refresher query for this record. 3738 // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL. 3739 // Unicast Assist Notes: 3740 // A Unicast Assist query will be expected at 75-77%, then the rest will proceed via multicast as needed. 3741 // The unicast assist query will not increment UnansweredQueries. 3742 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries) 3743 { 3744 mDNSu8 maxUnansweredQueryFactor = MaxUnansweredQueries; 3745 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 3746 if (rr->UnansweredQueries == 0 && 3747 !rr->unicastAssistSent && 3748 mDNSOpaque16IsZero(rr->CRActiveQuestion->TargetQID)) 3749 { 3750 maxUnansweredQueryFactor++; 3751 } 3752 #endif 3753 rr->NextRequiredQuery -= TicksTTL(rr)/20 * (maxUnansweredQueryFactor - rr->UnansweredQueries); 3754 rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50); 3755 verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s", 3756 (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr)); 3757 } 3758 ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(rr->resrec.namehash), NextCacheCheckEvent(rr)); 3759 } 3760 3761 #define kMinimumReconfirmTime ((mDNSu32)mDNSPlatformOneSecond * 5) 3762 #define kDefaultReconfirmTimeForWake ((mDNSu32)mDNSPlatformOneSecond * 5) 3763 #define kDefaultReconfirmTimeForNoAnswer ((mDNSu32)mDNSPlatformOneSecond * 5) 3764 3765 // Delay before restarting questions on a flapping interface. 3766 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond * 3) 3767 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds) 3768 // plus three seconds for "response delay" before removing the reconfirmed records from the cache. 3769 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond * 7)) 3770 3771 mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval) 3772 { 3773 if (interval < kMinimumReconfirmTime) 3774 interval = kMinimumReconfirmTime; 3775 if (interval > 0x10000000) // Make sure interval doesn't overflow when we multiply by four below 3776 interval = 0x10000000; 3777 3778 // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration 3779 if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3)) 3780 { 3781 // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts 3782 // For all the reconfirmations in a given batch, we want to use the same random value 3783 // so that the reconfirmation questions can be grouped into a single query packet 3784 if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(FutureTime); 3785 interval += m->RandomReconfirmDelay % ((interval/3) + 1); 3786 rr->TimeRcvd = m->timenow - (mDNSs32)interval * 3; 3787 rr->resrec.rroriginalttl = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond; 3788 SetNextCacheCheckTimeForRecord(m, rr); 3789 } 3790 debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p", 3791 RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion); 3792 return(mStatus_NoError); 3793 } 3794 3795 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr. 3796 // It also appends to the list of known answer records that need to be included, 3797 // and updates the forcast for the size of the known answer section. 3798 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr, 3799 DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast) 3800 { 3801 mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse; 3802 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0); 3803 const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData; 3804 mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit)); 3805 if (!newptr) 3806 { 3807 debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 3808 return(mDNSfalse); 3809 } 3810 else 3811 { 3812 mDNSu32 forecast = *answerforecast; 3813 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); 3814 CacheRecord *cr; 3815 CacheRecord **ka = *kalistptrptr; // Make a working copy of the pointer we're going to update 3816 3817 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // If we have a resource record in our cache, 3818 if (cr->resrec.InterfaceID == q->SendQNow && // received on this interface 3819 !(cr->resrec.RecordType & kDNSRecordTypeUniqueMask) && // which is a shared (i.e. not unique) record type 3820 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList && // which is not already in the known answer list 3821 cr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet 3822 SameNameCacheRecordAnswersQuestion(cr, q) && // which answers our question 3823 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow > // and its half-way-to-expiry time is at least 1 second away 3824 mDNSPlatformOneSecond) // (also ensures we never include goodbye records with TTL=1) 3825 { 3826 // We don't want to include unique records in the Known Answer section. The Known Answer section 3827 // is intended to suppress floods of shared-record replies from many other devices on the network. 3828 // That concept really does not apply to unique records, and indeed if we do send a query for 3829 // which we have a unique record already in our cache, then including that unique record as a 3830 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense. 3831 3832 *ka = cr; // Link this record into our known answer chain 3833 ka = &cr->NextInKAList; 3834 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n) 3835 forecast += 12 + cr->resrec.rdestimate; 3836 // If we're trying to put more than one question in this packet, and it doesn't fit 3837 // then undo that last question and try again next time 3838 if (query->h.numQuestions > 1 && newptr + forecast >= limit) 3839 { 3840 query->h.numQuestions--; 3841 debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d", 3842 q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions); 3843 ka = *kalistptrptr; // Go back to where we started and retract these answer records 3844 while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; } 3845 return(mDNSfalse); // Return false, so we'll try again in the next packet 3846 } 3847 } 3848 3849 // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return 3850 *queryptr = newptr; // Update the packet pointer 3851 *answerforecast = forecast; // Update the forecast 3852 *kalistptrptr = ka; // Update the known answer list pointer 3853 if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow); 3854 3855 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // For every resource record in our cache, 3856 if (cr->resrec.InterfaceID == q->SendQNow && // received on this interface 3857 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList && // which is not in the known answer list 3858 SameNameCacheRecordAnswersQuestion(cr, q)) // which answers our question 3859 { 3860 cr->UnansweredQueries++; // indicate that we're expecting a response 3861 cr->LastUnansweredTime = m->timenow; 3862 SetNextCacheCheckTimeForRecord(m, cr); 3863 } 3864 3865 return(mDNStrue); 3866 } 3867 } 3868 3869 // When we have a query looking for a specified name, but there appear to be no answers with 3870 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process 3871 // for any records in our cache that reference the given name (e.g. PTR and SRV records). 3872 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name. 3873 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5. 3874 // A typical reconfirmation scenario might go like this: 3875 // Depth 0: Name "myhost.local" has no address records 3876 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale 3877 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale 3878 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale 3879 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we 3880 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents. 3881 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSInterfaceID InterfaceID, const int depth) 3882 { 3883 mDNSu32 slot; 3884 const CacheGroup *cg; 3885 CacheRecord *cr; 3886 debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c); 3887 if (!InterfaceID) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do. 3888 FORALL_CACHERECORDS(slot, cg, cr) 3889 { 3890 const domainname *crtarget; 3891 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) || MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 3892 if (cr->DNSPushSubscribed) continue; // Skip records that are subscribed with a push server. [1] 3893 #endif 3894 if (cr->resrec.InterfaceID != InterfaceID) continue; // Skip non-mDNS records and mDNS records from other interfaces. 3895 if (cr->resrec.rdatahash != namehash) continue; // Skip records whose rdata hash doesn't match the name hash. 3896 // Notes: 3897 // 1. If the records are resolved through DNS push subscription, only the push server can ask us to add or 3898 // remove the record, so we do not need to reconfirm it here. 3899 crtarget = GetRRDomainNameTarget(&cr->resrec); 3900 if (crtarget && SameDomainName(crtarget, name)) 3901 { 3902 const mDNSu32 nameHash = mDNS_NonCryptoHash(mDNSNonCryptoHash_FNV1a, cr->resrec.name->c, 3903 DomainNameLength(cr->resrec.name)); 3904 const mDNSu32 targetNameHash = mDNS_NonCryptoHash(mDNSNonCryptoHash_FNV1a, crtarget->c, 3905 DomainNameLength(crtarget)); 3906 // In the case of a PTR record, name_hash is the name of the service, target_name_hash is the hash 3907 // of the SRV record name, so target_name_hash is also useful information. 3908 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "ReconfirmAntecedents: Reconfirming " 3909 "(depth=%d, InterfaceID=%p, name_hash=%x, target_name_hash=%x) " PRI_S, depth, InterfaceID, nameHash, 3910 targetNameHash, CRDisplayString(m, cr)); 3911 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); 3912 if (depth < 5) 3913 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, InterfaceID, depth+1); 3914 } 3915 } 3916 } 3917 3918 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents 3919 // we check if we have an address record for the same name. If we do have an IPv4 address for a given 3920 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure 3921 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name. 3922 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash) 3923 { 3924 CacheGroup *const cg = CacheGroupForName(m, namehash, name); 3925 const CacheRecord *cr = cg ? cg->members : mDNSNULL; 3926 while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next; 3927 return(cr); 3928 } 3929 3930 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 3931 mDNSlocal mDNSBool CacheGroupHasAddressOnInterface(const CacheGroup *const cg, mDNSu16 rrtype, const mDNSAddr *const addr, const mDNSInterfaceID interfaceID) 3932 { 3933 mDNS *const m = &mDNSStorage; 3934 mDNSBool result = mDNSfalse; 3935 const CacheRecord *cr; 3936 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 3937 { 3938 if (cr->resrec.rrtype == rrtype && 3939 cr->resrec.InterfaceID == interfaceID && 3940 RRExpireTime(cr) - m->timenow > UNICAST_ASSIST_MIN_REFRESH_TIME && 3941 mDNSSameAddress(&cr->sourceAddress, addr)) 3942 { 3943 result = mDNStrue; 3944 break; 3945 } 3946 } 3947 return(result); 3948 } 3949 #endif 3950 3951 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 3952 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1) 3953 { 3954 #ifndef SPC_DISABLED 3955 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); 3956 const CacheRecord *cr, *bestcr = mDNSNULL; 3957 mDNSu32 bestmetric = 1000000; 3958 for (cr = cg ? cg->members : mDNSNULL; cr; cr = cr->next) 3959 if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6) // If record is PTR type, with long enough name, 3960 if (cr != c0 && cr != c1) // that's not one we've seen before, 3961 if (SameNameCacheRecordAnswersQuestion(cr, q)) // and answers our browse query, 3962 if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec)) // and is not our own advertised service... 3963 { 3964 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c); 3965 if (bestmetric > metric) { bestmetric = metric; bestcr = cr; } 3966 } 3967 return(bestcr); 3968 #else // SPC_DISABLED 3969 (void) m; 3970 (void) q; 3971 (void) c0; 3972 (void) c1; 3973 (void) c1; 3974 return mDNSNULL; 3975 #endif // SPC_DISABLED 3976 } 3977 3978 mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2) 3979 { 3980 const CacheRecord *swap_sps; 3981 mDNSu32 metric1, metric2; 3982 3983 if (!(*sps1) || !(*sps2)) return; 3984 metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c); 3985 metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c); 3986 if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1)) 3987 { 3988 swap_sps = *sps1; 3989 *sps1 = *sps2; 3990 *sps2 = swap_sps; 3991 } 3992 } 3993 3994 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3]) 3995 { 3996 CheckAndSwapSPS(&sps[0], &sps[1]); 3997 CheckAndSwapSPS(&sps[0], &sps[2]); 3998 CheckAndSwapSPS(&sps[1], &sps[2]); 3999 } 4000 4001 4002 // Finds the three best Sleep Proxies we currently have in our cache 4003 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3]) 4004 { 4005 sps[0] = FindSPSInCache1(m, q, mDNSNULL, mDNSNULL); 4006 sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], mDNSNULL); 4007 sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0], sps[1]); 4008 4009 // SPS is already sorted by metric. We want to move the entries to the beginning of the array 4010 // only if they have equally good metric and support features. 4011 ReorderSPSByFeature(sps); 4012 } 4013 #endif // MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 4014 4015 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active 4016 mDNSlocal void ExpireDupSuppressInfo(DupSuppressState *const state, const mDNSs32 time) 4017 { 4018 mdns_require_return(state); 4019 4020 for (mDNSu32 i = 0; i < mdns_countof(state->slots); i++) 4021 { 4022 DupSuppressInfo *const slot = &state->slots[i]; 4023 if ((slot->Time - time) < 0) 4024 { 4025 slot->InterfaceID = mDNSNULL; 4026 } 4027 } 4028 } 4029 4030 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressState *const state, const mDNSs32 time, 4031 const mDNSInterfaceID InterfaceID) 4032 { 4033 mdns_require_return(state); 4034 4035 for (mDNSu32 i = 0; i < mdns_countof(state->slots); i++) 4036 { 4037 DupSuppressInfo *const slot = &state->slots[i]; 4038 if ((slot->InterfaceID == InterfaceID) && ((slot->Time - time) < 0)) 4039 { 4040 slot->InterfaceID = mDNSNULL; 4041 } 4042 } 4043 } 4044 4045 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressState *const state, const NetworkInterfaceInfo * const intf) 4046 { 4047 mdns_require_quiet(state, exit); 4048 4049 mDNSBool v4 = !intf->IPv4Available; // If interface doesn't support IPv4, we don't need to find an IPv4 duplicate. 4050 mDNSBool v6 = !intf->IPv6Available; // If interface doesn't support IPv6, we don't need to find an IPv6 duplicate. 4051 for (mDNSu32 i = 0; i < mdns_countof(state->slots); i++) 4052 { 4053 const DupSuppressInfo *const slot = &state->slots[i]; 4054 if (slot->InterfaceID == intf->InterfaceID) 4055 { 4056 if (slot->Type == mDNSAddrType_IPv4) 4057 { 4058 v4 = mDNStrue; 4059 } 4060 else if (slot->Type == mDNSAddrType_IPv6) 4061 { 4062 v6 = mDNStrue; 4063 } 4064 if (v4 && v6) 4065 { 4066 return(mDNStrue); 4067 } 4068 } 4069 } 4070 4071 exit: 4072 return(mDNSfalse); 4073 } 4074 4075 mDNSlocal void RecordDupSuppressInfo(DNSQuestion *const q, const mDNSs32 time, const mDNSInterfaceID InterfaceID, 4076 const mDNSs32 type) 4077 { 4078 DupSuppressInfo *slot = mDNSNULL; 4079 if (!q->DupSuppress) 4080 { 4081 q->DupSuppress = (DupSuppressState *)mDNSPlatformMemAllocateClear(sizeof(*q->DupSuppress)); 4082 mdns_require_quiet(q->DupSuppress, exit); 4083 } 4084 else 4085 { 4086 // See if we have this one in our list somewhere already 4087 DupSuppressState *const state = q->DupSuppress; 4088 for (mDNSu32 i = 0; i < mdns_countof(state->slots); i++) 4089 { 4090 DupSuppressInfo *const candidate = &state->slots[i]; 4091 if ((candidate->InterfaceID == InterfaceID) && (candidate->Type == type)) 4092 { 4093 slot = candidate; 4094 break; 4095 } 4096 } 4097 } 4098 4099 // If not, find a slot we can re-use 4100 if (!slot) 4101 { 4102 DupSuppressState *const state = q->DupSuppress; 4103 slot = &state->slots[0]; 4104 for (mDNSu32 i = 0; i < mdns_countof(state->slots); i++) 4105 { 4106 DupSuppressInfo *const candidate = &state->slots[i]; 4107 const mDNSBool unused = !candidate->InterfaceID; 4108 if (unused || ((candidate->Time - slot->Time) < 0)) 4109 { 4110 slot = candidate; 4111 if (unused) 4112 { 4113 break; 4114 } 4115 } 4116 } 4117 } 4118 4119 // Record the info about this query we saw 4120 slot->Time = time; 4121 slot->InterfaceID = InterfaceID; 4122 slot->Type = type; 4123 4124 exit: 4125 return; 4126 } 4127 4128 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q) 4129 { 4130 int len, i, cnt; 4131 mDNSInterfaceID InterfaceID = q->InterfaceID; 4132 domainname *d = &q->qname; 4133 4134 // We can't send magic packets without knowing which interface to send it on. 4135 if (InterfaceID == mDNSInterface_Any || LocalOnlyOrP2PInterface(InterfaceID)) 4136 { 4137 LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c); 4138 return; 4139 } 4140 4141 // Split MAC@IPAddress and pass them separately 4142 len = d->c[0]; 4143 cnt = 0; 4144 for (i = 1; i < len; i++) 4145 { 4146 if (d->c[i] == '@') 4147 { 4148 char EthAddr[18]; // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte 4149 char IPAddr[47]; // Max IP address len: 46 bytes (IPv6) + 1 NULL byte 4150 if (cnt != 5) 4151 { 4152 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt); 4153 return; 4154 } 4155 if ((i - 1) > (int) (sizeof(EthAddr) - 1)) 4156 { 4157 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1); 4158 return; 4159 } 4160 if ((len - i) > (int)(sizeof(IPAddr) - 1)) 4161 { 4162 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i); 4163 return; 4164 } 4165 mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1); 4166 EthAddr[i - 1] = 0; 4167 mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i); 4168 IPAddr[len - i] = 0; 4169 m->mDNSStats.WakeOnResolves++; 4170 mDNSPlatformSendWakeupPacket(InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount); 4171 return; 4172 } 4173 else if (d->c[i] == ':') 4174 cnt++; 4175 } 4176 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c); 4177 } 4178 4179 4180 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q) 4181 { 4182 // If more than 90% of the way to the query time, we should unconditionally accelerate it 4183 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10)) 4184 return(mDNStrue); 4185 4186 // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet 4187 if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2)) 4188 { 4189 // We forecast: qname (n) type (2) class (2) 4190 mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4; 4191 const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); 4192 const CacheRecord *cr; 4193 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) // If we have a resource record in our cache, 4194 if (cr->resrec.rdlength <= SmallRecordLimit && // which is small enough to sensibly fit in the packet 4195 SameNameCacheRecordAnswersQuestion(cr, q) && // which answers our question 4196 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow >= 0 && // and it is less than half-way to expiry 4197 cr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery 4198 { 4199 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n) 4200 forecast += 12 + cr->resrec.rdestimate; 4201 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate 4202 } 4203 return(mDNStrue); 4204 } 4205 4206 return(mDNSfalse); 4207 } 4208 4209 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DISCOVERY) 4210 mDNSlocal mDNSBool QuestionSendsMDNSQueriesViaUnicast(const DNSQuestion *const q) 4211 { 4212 return (mDNSOpaque16IsZero(q->TargetQID) && mDNSAddressIsValidNonZero(&q->UnicastMDNSResolver)); 4213 } 4214 #endif 4215 4216 // Return true if we should add record rr in the probe packet's authoritative section when probing for ar 4217 // Otherwise return false. 4218 mDNSlocal mDNSBool AddRecordInProbe(mDNS *const m, const AuthRecord *const ar, const AuthRecord *const rr, 4219 const mDNSInterfaceID InterfaceID) 4220 { 4221 // Already marked 4222 if (rr->IncludeInProbe) 4223 { 4224 return mDNSfalse; 4225 } 4226 mDNSBool hasTSR = (mDNSGetTSRForAuthRecord(m, ar) != mDNSNULL); 4227 4228 // Only include TXT record in probe query's authority section if TSR record exist for the name 4229 if (rr->DependentOn && !hasTSR) 4230 { 4231 return mDNSfalse; 4232 } 4233 4234 if (!IsInterfaceValidForAuthRecord(rr, InterfaceID)) 4235 { 4236 return mDNSfalse; 4237 } 4238 4239 // If a probe question is being sent for an AuthRecord and the AuthRecord is associated with a TSR record, then 4240 // all of the AuthRecords with the same name from the same client connection need to be present in the 4241 // authority section. So if one of them happens to have already gotten past the probing stage, it still needs 4242 // to be included. Currently, individually-registered AuthRecords from the same client connection will have the 4243 // same non-zero RRSet value. 4244 mDNSBool skipProbingStageCheck = mDNSfalse; 4245 if (hasTSR) 4246 { 4247 const uintptr_t s1 = ar->RRSet ? ar->RRSet : (uintptr_t)ar; 4248 const uintptr_t s2 = rr->RRSet ? rr->RRSet : (uintptr_t)rr; 4249 if (s1 == s2) 4250 { 4251 skipProbingStageCheck = mDNStrue; 4252 } 4253 } 4254 if (!skipProbingStageCheck) 4255 { 4256 // rr is not in probing stage and not dependent on other records 4257 // This is to exclude record that's already verified, but include TXT and TSR record if it's service registration 4258 // Refer to rdar://109086182 and rdar://109635078 4259 if (rr->resrec.RecordType != kDNSRecordTypeUnique && !rr->DependentOn) 4260 { 4261 return mDNSfalse; 4262 } 4263 } 4264 // Has the same name, class, interface with ar 4265 if (SameResourceRecordNameClassInterface(ar, rr)) 4266 { 4267 return mDNStrue; 4268 } 4269 return mDNSfalse; 4270 } 4271 4272 // How Standard Queries are generated: 4273 // 1. The Question Section contains the question 4274 // 2. The Additional Section contains answers we already know, to suppress duplicate responses 4275 4276 // How Probe Queries are generated: 4277 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because 4278 // if some other host is already using *any* records with this name, we want to know about it. 4279 // 2. The Authority Section contains the proposed values we intend to use for one or more 4280 // of our records with that name (analogous to the Update section of DNS Update packets) 4281 // because if some other host is probing at the same time, we each want to know what the other is 4282 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't. 4283 4284 mDNSlocal void SendQueries(mDNS *const m) 4285 { 4286 mDNSu32 slot; 4287 CacheGroup *cg; 4288 CacheRecord *cr; 4289 AuthRecord *ar; 4290 int pktcount = 0; 4291 DNSQuestion *q; 4292 // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval 4293 mDNSs32 maxExistingQuestionInterval = 0; 4294 const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces); 4295 CacheRecord *KnownAnswerList = mDNSNULL; 4296 4297 // 1. If time for a query, work out what we need to do 4298 4299 // We're expecting to send a query anyway, so see if any expiring cache records are close enough 4300 // to their NextRequiredQuery to be worth batching them together with this one 4301 FORALL_CACHERECORDS(slot, cg, cr) 4302 { 4303 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries) 4304 { 4305 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0) 4306 { 4307 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 4308 debugf("Sending %d%% cache expiration query for %s", (!cr->unicastAssistSent ? 75 : 80) + 5 * cr->UnansweredQueries, CRDisplayString(m, cr)); 4309 #else 4310 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr)); 4311 #endif 4312 q = cr->CRActiveQuestion; 4313 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID); 4314 // For uDNS queries (TargetQID non-zero) we adjust LastQTime, 4315 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly 4316 if (!mDNSOpaque16IsZero(q->TargetQID)) 4317 { 4318 q->LastQTime = m->timenow - q->ThisQInterval; 4319 cr->UnansweredQueries++; 4320 m->mDNSStats.CacheRefreshQueries++; 4321 } 4322 else if (q->SendQNow == mDNSNULL) 4323 { 4324 q->SendQNow = cr->resrec.InterfaceID; 4325 } 4326 else if (q->SendQNow != cr->resrec.InterfaceID) 4327 { 4328 q->SendQNow = mDNSInterfaceMark; 4329 } 4330 4331 // Indicate that this question was marked for sending 4332 // to update an existing cached answer record. 4333 // The browse throttling logic below uses this to determine 4334 // if the query should be sent. 4335 if (mDNSOpaque16IsZero(q->TargetQID)) 4336 { 4337 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 4338 if (!cr->unicastAssistSent && 4339 mDNSAddressIsValidNonZero(&cr->sourceAddress) && 4340 !mDNSAddrIsDNSMulticast(&cr->sourceAddress)) 4341 { 4342 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, 4343 "[Q%u] Sending unicast assist query (expiring) - " PRI_IP_ADDR " " PRI_DM_NAME " %s qhash %x" , 4344 mDNSVal16(q->TargetQID), &cr->sourceAddress, DM_NAME_PARAM(&q->qname), 4345 DNSTypeName(q->qtype), q->qnamehash); 4346 4347 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags); 4348 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data); 4349 const mDNSu16 qclass = q->qclass | kDNSQClass_UnicastResponse; 4350 mDNSu8 *const end = putQuestion(&m->omsg, m->omsg.data, limit, &q->qname, q->qtype, qclass); 4351 mDNSSendDNSMessage(m, &m->omsg, end, cr->resrec.InterfaceID, mDNSNULL, mDNSNULL, &cr->sourceAddress, 4352 MulticastDNSPort, mDNSNULL, q->UseBackgroundTraffic); 4353 q->LastQTime = m->timenow; 4354 q->LastQTxTime = m->timenow; 4355 q->RecentAnswerPkts = 0; 4356 q->ExpectUnicastResp = NonZeroTime(m->timenow); 4357 q->SendQNow = mDNSNULL; 4358 4359 cr->unicastAssistSent = mDNStrue; 4360 cr->LastUnansweredTime = m->timenow; 4361 } 4362 else 4363 #endif 4364 { 4365 q->CachedAnswerNeedsUpdate = mDNStrue; 4366 } 4367 } 4368 } 4369 } 4370 } 4371 4372 // Scan our list of questions to see which: 4373 // *WideArea* queries need to be sent 4374 // *unicast* queries need to be sent 4375 // *multicast* queries we're definitely going to send 4376 if (m->CurrentQuestion) 4377 LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 4378 m->CurrentQuestion = m->Questions; 4379 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions) 4380 { 4381 q = m->CurrentQuestion; 4382 if (mDNSOpaque16IsZero(q->TargetQID)) 4383 { 4384 if (TimeToSendThisQuestion(q, m->timenow)) 4385 { 4386 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DISCOVERY) 4387 if (QuestionSendsMDNSQueriesViaUnicast(q)) 4388 { 4389 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags); 4390 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data); 4391 const mDNSu16 qclass = q->qclass | kDNSQClass_UnicastResponse; 4392 mDNSu8 *const end = putQuestion(&m->omsg, m->omsg.data, limit, &q->qname, q->qtype, qclass); 4393 mDNSSendDNSMessage(m, &m->omsg, end, q->InterfaceID, mDNSNULL, mDNSNULL, &q->UnicastMDNSResolver, 4394 MulticastDNSPort, mDNSNULL, q->UseBackgroundTraffic); 4395 q->ThisQInterval *= QuestionIntervalStep; 4396 if (q->ThisQInterval > MaxQuestionInterval) 4397 { 4398 q->ThisQInterval = MaxQuestionInterval; 4399 } 4400 q->LastQTime = m->timenow; 4401 q->LastQTxTime = m->timenow; 4402 q->RecentAnswerPkts = 0; 4403 q->SendQNow = mDNSNULL; 4404 q->ExpectUnicastResp = NonZeroTime(m->timenow); 4405 } 4406 else 4407 #endif 4408 { 4409 mDNSBool delayQuestion = mDNSfalse; 4410 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 4411 if (!q->initialAssistPerformed) 4412 { 4413 __block CacheGroup *const current_cg = CacheGroupForName(m, q->qnamehash, &q->qname); 4414 __block bool assistSentForUnique = false; 4415 q->initialAssistPerformed = mDNStrue; 4416 unicast_assist_addr_enumerate(q->qnamehash, q->InterfaceID, 4417 ^bool(const mDNSAddr * const addr, mDNSInterfaceID ifid, bool unique) 4418 { 4419 bool result = false; 4420 if (!CacheGroupHasAddressOnInterface(current_cg, q->qtype, addr, ifid)) 4421 { 4422 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, 4423 "[Q%u] Sending unicast assist query - " PRI_IP_ADDR " %d " PRI_DM_NAME " " 4424 PUB_DNS_TYPE " qhash %x", mDNSVal16(q->TargetQID), addr, 4425 IIDPrintable(ifid), DM_NAME_PARAM(&q->qname), DNS_TYPE_PARAM(q->qtype), 4426 q->qnamehash); 4427 4428 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags); 4429 const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data); 4430 const mDNSu16 qclass = q->qclass | kDNSQClass_UnicastResponse; 4431 mDNSu8 *const end = putQuestion(&m->omsg, m->omsg.data, limit, &q->qname, q->qtype, qclass); 4432 mDNSSendDNSMessage(m, &m->omsg, end, ifid, mDNSNULL, mDNSNULL, addr, 4433 MulticastDNSPort, mDNSNULL, q->UseBackgroundTraffic); 4434 q->LastQTime = m->timenow; 4435 q->LastQTxTime = m->timenow; 4436 q->RecentAnswerPkts = 0; 4437 q->SendQNow = mDNSNULL; 4438 q->ExpectUnicastResp = NonZeroTime(m->timenow); 4439 assistSentForUnique = unique; 4440 result = true; 4441 } 4442 else 4443 { 4444 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "SKIPPED unicast assist query - " 4445 PRI_IP_ADDR " %d " PRI_DM_NAME " " PUB_S " qhash %x", 4446 addr, IIDPrintable(ifid), DM_NAME_PARAM(&q->qname), 4447 DNSTypeName(q->qtype), q->qnamehash); 4448 } 4449 return result; 4450 }); 4451 if (assistSentForUnique) 4452 { 4453 delayQuestion = mDNStrue; 4454 } 4455 } 4456 #endif 4457 if (!delayQuestion) 4458 { 4459 //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q)); 4460 q->SendQNow = mDNSInterfaceMark; // Mark this question for sending on all interfaces 4461 if (maxExistingQuestionInterval < q->ThisQInterval) 4462 maxExistingQuestionInterval = q->ThisQInterval; 4463 } 4464 } 4465 } 4466 } 4467 // If m->CurrentQuestion wasn't modified out from under us, advance it now 4468 // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having 4469 // m->CurrentQuestion point to the right question 4470 if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next; 4471 } 4472 while (m->CurrentQuestion) 4473 { 4474 LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 4475 m->CurrentQuestion = m->CurrentQuestion->next; 4476 } 4477 m->CurrentQuestion = mDNSNULL; 4478 4479 // Scan our list of questions 4480 // (a) to see if there are any more that are worth accelerating, and 4481 // (b) to update the state variables for *all* the questions we're going to send 4482 // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list, 4483 // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very 4484 // next thing we do is scan the list and call SetNextQueryTime() for every question we find, so we know we end up with the right value. 4485 m->NextScheduledQuery = m->timenow + FutureTime; 4486 for (q = m->Questions; q && q != m->NewQuestions; q=q->next) 4487 { 4488 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DISCOVERY) 4489 const mDNSBool qIsNormalMDNS = mDNSOpaque16IsZero(q->TargetQID) && !QuestionSendsMDNSQueriesViaUnicast(q); 4490 #else 4491 const mDNSBool qIsNormalMDNS = mDNSOpaque16IsZero(q->TargetQID); 4492 #endif 4493 if (qIsNormalMDNS 4494 && (q->SendQNow || (ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q) 4495 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 4496 && q->LastQTime != m->timenow // Was not just sent above 4497 #endif 4498 ))) 4499 { 4500 // If at least halfway to next query time, advance to next interval 4501 // If less than halfway to next query time, then 4502 // treat this as logically a repeat of the last transmission, without advancing the interval 4503 if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0) 4504 { 4505 // If we have reached the answer threshold for this question, 4506 // don't send it again until MaxQuestionInterval unless: 4507 // one of its cached answers needs to be refreshed, 4508 // or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse. 4509 if (q->BrowseThreshold 4510 && (q->CurrentAnswers >= q->BrowseThreshold) 4511 && (q->CachedAnswerNeedsUpdate == mDNSfalse) 4512 && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval))) 4513 { 4514 q->SendQNow = mDNSNULL; 4515 q->ThisQInterval = MaxQuestionInterval; 4516 q->LastQTime = m->timenow; 4517 q->RequestUnicast = 0; 4518 LogInfo("SendQueries: (%s) %##s reached threshold of %d answers", 4519 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold); 4520 } 4521 else 4522 { 4523 // Mark this question for sending on all interfaces 4524 q->SendQNow = mDNSInterfaceMark; 4525 q->ThisQInterval *= QuestionIntervalStep; 4526 } 4527 4528 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d", 4529 q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast); 4530 4531 if (q->ThisQInterval > MaxQuestionInterval) 4532 { 4533 q->ThisQInterval = MaxQuestionInterval; 4534 } 4535 else if (mDNSOpaque16IsZero(q->TargetQID) && q->InterfaceID && 4536 q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast && 4537 !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash))) 4538 { 4539 // Generally don't need to log this. 4540 // It's not especially noteworthy if a query finds no results -- this usually happens for domain 4541 // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa") 4542 // and when there simply happen to be no instances of the service the client is looking 4543 // for (e.g. iTunes is set to look for RAOP devices, and the current network has none). 4544 debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents", 4545 q->qname.c, DNSTypeName(q->qtype)); 4546 // Sending third query, and no answers yet; time to begin doubting the source 4547 ReconfirmAntecedents(m, &q->qname, q->qnamehash, q->InterfaceID, 0); 4548 } 4549 } 4550 4551 // Mark for sending. (If no active interfaces, then don't even try.) 4552 q->SendOnAll = (q->SendQNow == mDNSInterfaceMark); 4553 if (q->SendOnAll) 4554 { 4555 q->SendQNow = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID; 4556 q->LastQTime = m->timenow; 4557 } 4558 4559 // If we recorded a duplicate suppression for this question less than half an interval ago, 4560 // then we consider it recent enough that we don't need to do an identical query ourselves. 4561 ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2); 4562 4563 q->LastQTxTime = m->timenow; 4564 q->RecentAnswerPkts = 0; 4565 if (q->RequestUnicast) q->RequestUnicast--; 4566 } 4567 // For all questions (not just the ones we're sending) check what the next scheduled event will be 4568 // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion 4569 SetNextQueryTime(m,q); 4570 } 4571 4572 // 2. Scan our authoritative RR list to see what probes we might need to send 4573 4574 m->NextScheduledProbe = m->timenow + FutureTime; 4575 4576 if (m->CurrentRecord) 4577 LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 4578 m->CurrentRecord = m->ResourceRecords; 4579 while (m->CurrentRecord) 4580 { 4581 ar = m->CurrentRecord; 4582 m->CurrentRecord = ar->next; 4583 if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique && ar->resrec.rrtype != kDNSType_OPT) // For all records that are still probing... 4584 { 4585 // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly 4586 if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0) 4587 { 4588 SetNextAnnounceProbeTime(m, ar); 4589 } 4590 // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly 4591 else if (ar->ProbeCount) 4592 { 4593 if (ar->AddressProxy.type == mDNSAddrType_IPv4) 4594 { 4595 // There's a problem here. If a host is waking up, and we probe to see if it responds, then 4596 // it will see those ARP probes as signalling intent to use the address, so it picks a different one. 4597 // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request* 4598 // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address). 4599 // A similar concern may apply to the NDP Probe too. -- SC 4600 LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar)); 4601 SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC); 4602 } 4603 else if (ar->AddressProxy.type == mDNSAddrType_IPv6) 4604 { 4605 LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar)); 4606 // IPv6 source = zero 4607 // No target hardware address 4608 // IPv6 target address is address we're probing 4609 // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing 4610 SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC); 4611 } 4612 // Mark for sending. (If no active interfaces, then don't even try.) 4613 ar->SendRNow = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID; 4614 ar->LastAPTime = m->timenow; 4615 // When we have a late conflict that resets a record to probing state we use a special marker value greater 4616 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value. 4617 if (ar->ProbeCount > DefaultProbeCountForTypeUnique) 4618 ar->ProbeCount = DefaultProbeCountForTypeUnique; 4619 ar->ProbeCount--; 4620 SetNextAnnounceProbeTime(m, ar); 4621 if (ar->ProbeCount == 0) 4622 { 4623 // If this is the last probe for this record, then see if we have any matching records 4624 // on our duplicate list which should similarly have their ProbeCount cleared to zero... 4625 AuthRecord *r2; 4626 for (r2 = m->DuplicateRecords; r2; r2=r2->next) 4627 if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar)) 4628 r2->ProbeCount = 0; 4629 // ... then acknowledge this record to the client. 4630 // We do this optimistically, just as we're about to send the third probe. 4631 // This helps clients that both advertise and browse, and want to filter themselves 4632 // from the browse results list, because it helps ensure that the registration 4633 // confirmation will be delivered 1/4 second *before* the browse "add" event. 4634 // A potential downside is that we could deliver a registration confirmation and then find out 4635 // moments later that there's a name conflict, but applications have to be prepared to handle 4636 // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new. 4637 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); 4638 } 4639 } 4640 // else, if it has now finished probing, move it to state Verified, 4641 // and update m->NextScheduledResponse so it will be announced 4642 else 4643 { 4644 if (!ar->Acknowledged) AcknowledgeRecord(m, ar); // Defensive, just in case it got missed somehow 4645 ar->resrec.RecordType = kDNSRecordTypeVerified; 4646 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique; 4647 ar->LastAPTime = m->timenow - DefaultAnnounceIntervalForTypeUnique; 4648 SetNextAnnounceProbeTime(m, ar); 4649 } 4650 } 4651 } 4652 m->CurrentRecord = m->DuplicateRecords; 4653 while (m->CurrentRecord) 4654 { 4655 ar = m->CurrentRecord; 4656 m->CurrentRecord = ar->next; 4657 if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged) 4658 AcknowledgeRecord(m, ar); 4659 } 4660 4661 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 4662 mDNSBool queryHasDPCBrowse = mDNSfalse; 4663 #endif 4664 // 3. Now we know which queries and probes we're sending, 4665 // go through our interface list sending the appropriate queries on each interface 4666 while (intf) 4667 { 4668 const mDNSu32 OwnerRecordSpace = DetermineOwnerRecordSpace(intf); 4669 int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0; 4670 mDNSu8 *queryptr = m->omsg.data; 4671 mDNSBool useBackgroundTrafficClass = mDNSfalse; // set if we should use background traffic class 4672 TSRDataPtrRecHead tsrOpts = SLIST_HEAD_INITIALIZER(tsrOpts); 4673 TSROptData *newTSROpt; 4674 mDNSu16 tsrOptsCount = 0; 4675 mDNSu32 tsrHeaderSpace = (OwnerRecordSpace || TraceRecordSpace) ? 0 : DNSOpt_Header_Space; 4676 4677 InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags); 4678 if (KnownAnswerList) verbosedebugf("SendQueries: KnownAnswerList set... Will continue from previous packet"); 4679 if (!KnownAnswerList) 4680 { 4681 // Start a new known-answer list 4682 CacheRecord **kalistptr = &KnownAnswerList; 4683 mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace; // Start by assuming we'll need at least enough space to put the Owner+Tracer Option 4684 mDNSu32 numQuestionSkipped = 0; 4685 4686 // Put query questions in this packet 4687 for (q = m->Questions; q && q != m->NewQuestions; q=q->next) 4688 { 4689 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID)) 4690 { 4691 mDNSBool Suppress = mDNSfalse; 4692 debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d", 4693 SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting ", 4694 q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data); 4695 4696 mDNSBool updateInterface = mDNSfalse; 4697 // If interface is P2P type, verify that query should be sent over it. 4698 if (!mDNSPlatformValidQuestionForInterface(q, intf)) 4699 { 4700 updateInterface = mDNStrue; 4701 } 4702 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 4703 else if (DPCSuppressMDNSQuery(q, intf->InterfaceID)) 4704 { 4705 updateInterface = mDNStrue; 4706 } 4707 #endif 4708 // If we're suppressing this question, or we successfully put it, update its SendQNow state 4709 else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) || 4710 BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast)) 4711 { 4712 if (Suppress) 4713 { 4714 m->mDNSStats.DupQuerySuppressions++; 4715 } 4716 #if MDNSRESPONDER_SUPPORTS(APPLE, RUNTIME_MDNS_METRICS) 4717 else if (DNSQuestionCollectsMDNSMetric(q)) 4718 { 4719 // 1. If this is our first time to send query, or 4720 // 2. If we have received some response for the query we sent out before 4721 // The delay timer ticks starting from 0. (which means we are calculating a new delay for a 4722 // new query sent out.) 4723 // The reason why we do this: 4724 // If we have not received any response since our first query has been sent out, then 4725 // reissuing a query should not make the delay we are counting shorter. The more query 4726 // retransmission we have, the greater the response delay should be. Therefore, if we have 4727 // not received any response to the current query, do not update the first query time even 4728 // if we have sent multiple queries. 4729 // However, if the query has been answered by at least one answer (from wire, not from 4730 // cache), then reissuing a new query should reset the first query time so that the delay 4731 // is not exaggerated. 4732 if ((q->metrics.firstQueryTime == 0) || (q->metrics.answered)) 4733 { 4734 q->metrics.firstQueryTime = NonZeroTime(m->timenow); 4735 q->metrics.answered = mDNSfalse; 4736 } 4737 q->metrics.querySendCount++; 4738 } 4739 #endif 4740 updateInterface = mDNStrue; 4741 if (q->WakeOnResolveCount) 4742 { 4743 mDNSSendWakeOnResolve(m, q); 4744 q->WakeOnResolveCount--; 4745 } 4746 4747 // use background traffic class if any included question requires it 4748 if (q->UseBackgroundTraffic) 4749 { 4750 useBackgroundTrafficClass = mDNStrue; 4751 } 4752 } 4753 if (updateInterface) 4754 { 4755 q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf); 4756 } 4757 } 4758 } 4759 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 4760 // If the message being constructed for the current interface contains at least one non-probe question, 4761 // try to opportunistically include the Discovery Proxy browse's question as well. 4762 if (DPCFeatureEnabled() && !queryHasDPCBrowse && (m->omsg.h.numQuestions > 0)) 4763 { 4764 const mDNSu8 *questionPtr = m->omsg.data; 4765 const mDNSu8 *const end = queryptr; 4766 for (mDNSu32 i = 0; i < m->omsg.h.numQuestions; i++) 4767 { 4768 DNSQuestion question; 4769 questionPtr = getQuestion(&m->omsg, questionPtr, end, mDNSInterface_Any, &question); 4770 if (!questionPtr) 4771 { 4772 break; 4773 } 4774 question.qclass &= ~kDNSQClass_UnicastResponse; 4775 if ((question.qtype == DPCBrowse.qtype) && (question.qclass == DPCBrowse.qclass) && 4776 (question.qnamehash == DPCBrowse.qnamehash) && SameDomainName(&question.qname, &DPCBrowse.qname)) 4777 { 4778 queryHasDPCBrowse = mDNStrue; 4779 break; 4780 } 4781 } 4782 if (!queryHasDPCBrowse) 4783 { 4784 DPCBrowse.SendQNow = intf->InterfaceID; 4785 DPCBrowse.RequestUnicast = kDefaultRequestUnicastCount; 4786 BuildQuestion(m, intf, &m->omsg, &queryptr, &DPCBrowse, &kalistptr, &answerforecast); 4787 DPCBrowse.SendQNow = mDNSNULL; 4788 queryHasDPCBrowse = mDNStrue; 4789 } 4790 } 4791 #endif 4792 // Put probe questions in this packet 4793 for (ar = m->ResourceRecords; ar; ar=ar->next) 4794 { // Skip if already marked for probing, or interface does not match, or TSR record 4795 if (ar->IncludeInProbe || (ar->SendRNow != intf->InterfaceID) || 4796 (ar->resrec.rrtype == kDNSType_OPT)) 4797 continue; 4798 4799 // If interface is a P2P variant, verify that the probe should be sent over it. 4800 if (!mDNSPlatformValidRecordForInterface(ar, intf->InterfaceID)) 4801 { 4802 ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf); 4803 ar->IncludeInProbe = mDNSfalse; 4804 } 4805 else 4806 { 4807 mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse; 4808 mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0); 4809 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData); 4810 mDNSu32 forecast = answerforecast; 4811 mDNSBool putProbeQuestion = mDNStrue; 4812 mDNSu16 qclass = ar->resrec.rrclass | ucbit; 4813 4814 {// Determine if this probe question is already in packet's dns message 4815 const mDNSu8 *questionptr = m->omsg.data; 4816 DNSQuestion question; 4817 mDNSu16 n; 4818 for (n = 0; n < m->omsg.h.numQuestions && questionptr; n++) 4819 { 4820 questionptr = getQuestion(&m->omsg, questionptr, limit, mDNSInterface_Any, &question); 4821 if (questionptr && (question.qtype == kDNSQType_ANY) && (question.qclass == qclass) && 4822 (question.qnamehash == ar->resrec.namehash) && SameDomainName(&question.qname, ar->resrec.name)) 4823 { 4824 putProbeQuestion = mDNSfalse; // set to false if already in message 4825 break; 4826 } 4827 } 4828 } 4829 4830 if (TSROptGetIfNew(m, ar, &tsrOpts) != mDNSNULL) 4831 { 4832 forecast += (DNSOpt_TSRData_Space + ((tsrOptsCount == 0) ? tsrHeaderSpace : 0)); 4833 tsrOptsCount++; 4834 } 4835 4836 for (const AuthRecord *tmp = m->ResourceRecords; tmp; tmp = tmp->next) 4837 { 4838 if (AddRecordInProbe(m, ar, tmp, intf->InterfaceID)) 4839 { 4840 // compressed name (2) type (2) class (2) TTL (4) rdlength (2) estimated rdata length 4841 forecast = forecast + 12 + tmp->resrec.rdestimate; 4842 } 4843 } 4844 4845 if (putProbeQuestion) 4846 { 4847 mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, qclass); 4848 if (!newptr) { 4849 // There is not enough space for the probe question and its corresponding records 4850 numQuestionSkipped++; 4851 continue; 4852 } 4853 else 4854 { 4855 queryptr = newptr; 4856 verbosedebugf("SendQueries: Put Question %##s (%s) probecount %d InterfaceID= %d %d %d", 4857 ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount, ar->resrec.InterfaceID, ar->resrec.rdestimate, answerforecast); 4858 } 4859 } 4860 else 4861 { 4862 if (queryptr + forecast >= limit) 4863 { 4864 // There is not enough space 4865 continue; 4866 } 4867 } 4868 4869 answerforecast = forecast; 4870 for (AuthRecord *tmp = m->ResourceRecords; tmp; tmp = tmp->next) 4871 { 4872 if (AddRecordInProbe(m, ar, tmp, intf->InterfaceID)) 4873 { 4874 tmp->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf); 4875 tmp->IncludeInProbe = mDNStrue; 4876 } 4877 } 4878 } 4879 } 4880 if (numQuestionSkipped > 0) 4881 { 4882 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "SendQueries: %u questions will be sent in a later request on InterfaceID= %p", 4883 numQuestionSkipped, intf->InterfaceID); 4884 } 4885 } 4886 4887 // Put our known answer list (either new one from this question or questions, or remainder of old one from last time) 4888 while (KnownAnswerList) 4889 { 4890 CacheRecord *ka = KnownAnswerList; 4891 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond; 4892 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd, 4893 m->omsg.data + NormalMaxDNSMessageData - RR_OPT_SPACE); 4894 if (newptr) 4895 { 4896 verbosedebugf("SendQueries: Put %##s (%s) at %d - %d", 4897 ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data); 4898 queryptr = newptr; 4899 KnownAnswerList = ka->NextInKAList; 4900 ka->NextInKAList = mDNSNULL; 4901 } 4902 else 4903 { 4904 // If we ran out of space and we have more than one question in the packet, that's an error -- 4905 // we shouldn't have put more than one question if there was a risk of us running out of space. 4906 if (m->omsg.h.numQuestions > 1) 4907 LogMsg("SendQueries: Put %d answers; No more space for known answers", m->omsg.h.numAnswers); 4908 m->omsg.h.flags.b[0] |= kDNSFlag0_TC; 4909 break; 4910 } 4911 } 4912 4913 tsrOptsCount = 0; 4914 for (ar = m->ResourceRecords; ar; ar=ar->next) 4915 { 4916 if (ar->IncludeInProbe) 4917 { 4918 mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec, ar->resrec.rroriginalttl, 4919 (m->omsg.h.numQuestions > 1 ? m->omsg.data + NormalMaxDNSMessageData : m->omsg.data + AbsoluteMaxDNSMessageData)); 4920 ar->IncludeInProbe = mDNSfalse; 4921 if (newptr) queryptr = newptr; 4922 else LogMsg("SendQueries: How did we fail to have space for the Update record %s", ARDisplayString(m,ar)); 4923 4924 if ((newTSROpt = TSROptGetIfNew(m, ar, &tsrOpts)) != mDNSNULL) 4925 { 4926 tsrOptsCount++; 4927 TSRDataRecPtrHeadAddTSROpt(&tsrOpts, newTSROpt, ar->resrec.name, m->omsg.h.numAnswers + m->omsg.h.numAdditionals + m->omsg.h.numAuthorities - 1); 4928 } 4929 } 4930 } 4931 4932 if (queryptr > m->omsg.data) 4933 { 4934 // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet 4935 if (OwnerRecordSpace || TraceRecordSpace || !SLIST_EMPTY(&tsrOpts)) 4936 { 4937 mDNSu8 *saveptr; 4938 AuthRecord opt; 4939 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); 4940 opt.resrec.rrclass = NormalMaxDNSMessageData; 4941 opt.resrec.rdlength = 0; 4942 opt.resrec.rdestimate = 0; 4943 mDNSu16 optCount = 0; 4944 if (OwnerRecordSpace) 4945 { 4946 opt.resrec.rdlength += sizeof(rdataOPT); 4947 opt.resrec.rdestimate += sizeof(rdataOPT); 4948 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[optCount++]); 4949 } 4950 if (TraceRecordSpace) 4951 { 4952 opt.resrec.rdlength += sizeof(rdataOPT); 4953 opt.resrec.rdestimate += sizeof(rdataOPT); 4954 SetupTracerOpt(m, &opt.resrec.rdata->u.opt[optCount++]); 4955 } 4956 if (!SLIST_EMPTY(&tsrOpts)) 4957 { 4958 opt.resrec.rdlength += sizeof(rdataOPT); 4959 opt.resrec.rdestimate += sizeof(rdataOPT); 4960 SetupTSROpt(SLIST_FIRST(&tsrOpts)->tsr, &opt.resrec.rdata->u.opt[optCount++]); 4961 TSRDataRecPtrHeadRemoveAndFreeFirst(&tsrOpts); 4962 } 4963 // Put record after first TSR 4964 saveptr = queryptr; 4965 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals, &opt.resrec, 4966 opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData); 4967 if (queryptr && !SLIST_EMPTY(&tsrOpts)) 4968 { 4969 mDNSu8 *rdlengthptr = saveptr + 2 + 2 + 4 + 1; // rrtype, rrclass, ttl, 0-length name 4970 queryptr = AddTSRROptsToMessage(&tsrOpts, &m->omsg, rdlengthptr, queryptr, 4971 m->omsg.data + AbsoluteMaxDNSMessageData); 4972 } 4973 if (!queryptr) 4974 { 4975 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "SendQueries: How did we fail to have space for %s %s TSR(%d) OPT record (%d/%d/%d/%d) %s", 4976 OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", tsrOptsCount, 4977 m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt)); 4978 } 4979 if (queryptr > m->omsg.data + NormalMaxDNSMessageData) 4980 { 4981 if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1) 4982 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "SendQueries: Why did we generate oversized packet with %s %s TSR(%d) OPT record %p %p %p (%d/%d/%d/%d) %s", 4983 OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", tsrOptsCount, 4984 m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, 4985 m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt)); 4986 } 4987 } 4988 4989 if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1) 4990 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions); 4991 debugf("SendQueries: Sending %d Question%s %d Answer%s %d Update%s on %d (%s)", 4992 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s", 4993 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s", 4994 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", 4995 m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", IIDPrintable(intf->InterfaceID), intf->ifname); 4996 if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass); 4997 if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass); 4998 if (!m->SuppressQueries) m->SuppressQueries = NonZeroTime(m->timenow + ((mDNSPlatformOneSecond + 9) / 10)); 4999 if (++pktcount >= 1000) 5000 { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; } 5001 // There might be more records left in the known answer list, or more questions to send 5002 // on this interface, so go around one more time and try again. 5003 } 5004 else // Nothing more to send on this interface; go to next 5005 { 5006 const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next); 5007 intf = next; 5008 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 5009 queryHasDPCBrowse = mDNSfalse; 5010 #endif 5011 } 5012 TSRDataRecPtrHeadFreeList(&tsrOpts); 5013 } 5014 5015 // 4. Final housekeeping 5016 5017 // 4a. Debugging check: Make sure we announced all our records 5018 for (ar = m->ResourceRecords; ar; ar=ar->next) 5019 if (ar->SendRNow) 5020 { 5021 if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P) 5022 LogInfo("SendQueries: No active interface %d to send probe: %d %s", 5023 IIDPrintable(ar->SendRNow), IIDPrintable(ar->resrec.InterfaceID), ARDisplayString(m, ar)); 5024 ar->SendRNow = mDNSNULL; 5025 } 5026 5027 // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope 5028 // that their interface which went away might come back again, the logic will want to send queries 5029 // for those records, but we can't because their interface isn't here any more, so to keep the 5030 // state machine ticking over we just pretend we did so. 5031 // If the interface does not come back in time, the cache record will expire naturally 5032 FORALL_CACHERECORDS(slot, cg, cr) 5033 { 5034 if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries) 5035 { 5036 if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0) 5037 { 5038 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 5039 if (cr->LastUnansweredTime != m->timenow) // It was not just sent 5040 #endif 5041 { 5042 cr->UnansweredQueries++; 5043 } 5044 cr->CRActiveQuestion->SendQNow = mDNSNULL; 5045 SetNextCacheCheckTimeForRecord(m, cr); 5046 } 5047 } 5048 } 5049 5050 // 4c. Debugging check: Make sure we sent all our planned questions 5051 // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions 5052 // we legitimately couldn't send because the interface is no longer available 5053 for (q = m->Questions; q; q=q->next) 5054 { 5055 if (q->SendQNow) 5056 { 5057 DNSQuestion *x; 5058 for (x = m->NewQuestions; x; x=x->next) if (x == q) break; // Check if this question is a NewQuestion 5059 // There will not be an active interface for questions applied to mDNSInterface_BLE 5060 // so don't log the warning in that case. 5061 if (q->InterfaceID != mDNSInterface_BLE) 5062 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)", 5063 IIDPrintable(q->SendQNow), x ? "new" : "old", IIDPrintable(q->InterfaceID), q->qname.c, DNSTypeName(q->qtype)); 5064 q->SendQNow = mDNSNULL; 5065 } 5066 q->CachedAnswerNeedsUpdate = mDNSfalse; 5067 } 5068 } 5069 5070 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly) 5071 { 5072 int i, j; 5073 5074 mDNSu8 *ptr = m->omsg.data; 5075 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID); 5076 if (!intf) 5077 { 5078 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "SendARP: No interface with InterfaceID %p found", InterfaceID); 5079 return; 5080 } 5081 5082 // 0x00 Destination address 5083 for (i=0; i<6; i++) *ptr++ = EthAddr->b[i]; 5084 5085 // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us) 5086 for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0]; 5087 5088 // 0x0C Ethertype (0x0842) 5089 *ptr++ = 0x08; 5090 *ptr++ = 0x42; 5091 5092 // 0x0E Wakeup sync sequence 5093 for (i=0; i<6; i++) *ptr++ = 0xFF; 5094 5095 // 0x14 Wakeup data 5096 for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i]; 5097 5098 // 0x74 Password 5099 for (i=0; i<6; i++) *ptr++ = password->b[i]; 5100 5101 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID); 5102 5103 if (!unicastOnly) 5104 { 5105 // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses, 5106 // broadcast is the only reliable way to get a wakeup packet to the intended target machine. 5107 // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast 5108 // key rotation, unicast is the only way to get a wakeup packet to the intended target machine. 5109 // So, we send one of each, unicast first, then broadcast second. 5110 for (i=0; i<6; i++) m->omsg.data[i] = 0xFF; 5111 mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID); 5112 } 5113 } 5114 5115 // *************************************************************************** 5116 // MARK: - RR List Management & Task Management 5117 5118 // Whenever a question is answered, reset its state so that we don't query 5119 // the network repeatedly. This happens first time when we answer the question and 5120 // and later when we refresh the cache. 5121 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q) 5122 { 5123 q->LastQTime = m->timenow; 5124 q->LastQTxTime = m->timenow; 5125 q->RecentAnswerPkts = 0; 5126 q->ThisQInterval = MaxQuestionInterval; 5127 q->RequestUnicast = 0; 5128 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 5129 q->NeedUpdatedQuerier = mDNSfalse; 5130 #else 5131 // Reset unansweredQueries so that we don't penalize this server later when we 5132 // start sending queries when the cache expires. 5133 q->unansweredQueries = 0; 5134 #endif 5135 debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 5136 } 5137 5138 mDNSlocal void AdjustUnansweredQueries(mDNS *const m, CacheRecord *const rr) 5139 { 5140 const mDNSs32 expireTime = RRExpireTime(rr); 5141 const mDNSu32 interval = TicksTTL(rr) / 20; // Calculate 5% of the cache record's TTL. 5142 mDNSu32 rem; 5143 5144 // If the record is expired or UnansweredQueries is already at the max, then return early. 5145 if (((m->timenow - expireTime) >= 0) || (rr->UnansweredQueries >= MaxUnansweredQueries)) return; 5146 5147 if (interval == 0) 5148 { 5149 LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr), CRDisplayString(m, rr)); 5150 return; 5151 } 5152 5153 // Calculate the number of whole 5% TTL intervals between now and expiration time. 5154 rem = ((mDNSu32)(expireTime - m->timenow)) / interval; 5155 5156 // Calculate the expected number of remaining refresher queries. 5157 // Refresher queries are sent at the start of the last MaxUnansweredQueries intervals. 5158 if (rem > MaxUnansweredQueries) rem = MaxUnansweredQueries; 5159 5160 // If the current number of remaining refresher queries is greater than expected, then at least one refresher query time 5161 // was missed. This can happen if the cache record didn't have an active question during any of the times at which 5162 // refresher queries would have been sent if the cache record did have an active question. The cache record's 5163 // UnansweredQueries count needs to be adjusted to avoid a burst of refresher queries being sent in an attempt to make up 5164 // for lost time. UnansweredQueries is set to the number of queries that would have been sent had the cache record had an 5165 // active question from the 80% point of its lifetime up to now, with one exception: if the number of expected remaining 5166 // refresher queries is zero (because timenow is beyond the 95% point), then UnansweredQueries is set to 5167 // MaxUnansweredQueries - 1 so that at least one refresher query is sent before the cache record expires. 5168 // Note: The cast is safe because rem is never greater than MaxUnansweredQueries; the comparison has to be signed. 5169 if ((MaxUnansweredQueries - rr->UnansweredQueries) > (mDNSs32)rem) 5170 { 5171 if (rem == 0) rem++; 5172 rr->UnansweredQueries = (mDNSu8)(MaxUnansweredQueries - rem); 5173 } 5174 } 5175 5176 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list. 5177 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this. 5178 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion, 5179 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question. 5180 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord) 5181 { 5182 DNSQuestion *const q = m->CurrentQuestion; 5183 const mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord); 5184 5185 verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s", 5186 q->CurrentAnswers, AddRecord ? "Add" : "Rmv", MortalityDisplayString(rr->resrec.mortality), 5187 rr->resrec.rroriginalttl, CRDisplayString(m, rr)); 5188 5189 #if MDNSRESPONDER_SUPPORTS(APPLE, LOG_PRIVACY_LEVEL) 5190 // When a cache record is used to answer a question, check if we need to enable sensitive logging for it. 5191 if (DNSQuestionNeedsSensitiveLogging(q)) // If the question enables sensitive logging. 5192 { 5193 // default means that we have not remember any private log level, by default, this record will be printed in 5194 // the state dump output. 5195 if (rr->PrivacyLevel == mDNSCRLogPrivacyLevel_Default) 5196 { 5197 // Since this cache record is used to answer a question that enables sensitive logging, it will be 5198 // marked as private, and will be redacted in the state dump. 5199 rr->PrivacyLevel = mDNSCRLogPrivacyLevel_Private; 5200 // If it is associated with an SOA record, the SOA should also be marked as private because it 5201 // has the same record name. 5202 if (rr->soa) 5203 { 5204 rr->soa->PrivacyLevel = mDNSCRLogPrivacyLevel_Private; 5205 } 5206 } 5207 } 5208 else // q->logPrivacyLevel == dnssd_log_privacy_level_default // If the question does not enable sensitive logging. 5209 { 5210 // If this cache record is used to answer a question that does not enable sensitive logging, it will be printed 5211 // in the state dump. 5212 rr->PrivacyLevel = mDNSCRLogPrivacyLevel_Public; 5213 if (rr->soa) 5214 { 5215 rr->soa->PrivacyLevel = mDNSCRLogPrivacyLevel_Public; 5216 } 5217 } 5218 #endif 5219 5220 // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts. 5221 // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might 5222 // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that, 5223 // we check to see if that query already has a unique local answer. 5224 if (q->LOAddressAnswers) 5225 { 5226 LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to " 5227 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr), 5228 q->LOAddressAnswers); 5229 return; 5230 } 5231 5232 if (q->Suppressed && (AddRecord != QC_suppressed) && !(q->ForceCNAMEFollows && followcname)) 5233 { 5234 // If the query is suppressed, then we don't want to answer from the cache. But if this query is 5235 // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions 5236 // that are timing out, which we know are answered with negative cache record when timing out. 5237 if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0)) 5238 return; 5239 } 5240 5241 // Set the record to immortal if appropriate 5242 if (!mDNSOpaque16IsZero(q->TargetQID) && (AddRecord == QC_add) && (rr->resrec.mortality == Mortality_Mortal)) 5243 { 5244 switch (q->ExpRecordPolicy) 5245 { 5246 case mDNSExpiredRecordPolicy_DoNotUse: 5247 MDNS_COVERED_SWITCH_DEFAULT: 5248 break; 5249 5250 case mDNSExpiredRecordPolicy_UseCached: 5251 case mDNSExpiredRecordPolicy_Immortalize: 5252 { 5253 mDNSBool eligible = (rr->resrec.RecordType != kDNSRecordTypePacketNegative); 5254 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 5255 // For now, do not use optimistic DNS for DNSSEC response and DNSSEC question. 5256 eligible = eligible && !dns_question_is_dnssec_requestor(q) && !resource_record_is_dnssec_aware(&rr->resrec); 5257 #endif 5258 if (eligible) 5259 { 5260 rr->resrec.mortality = Mortality_Immortal; 5261 } 5262 break; 5263 } 5264 } 5265 } 5266 5267 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_ANALYTICS) 5268 if ((AddRecord == QC_add) && Question_uDNS(q) && !followcname && !q->metrics.answered) 5269 { 5270 mDNSBool skipUpdate = mDNSfalse; 5271 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 5272 mdns_resolver_type_t resolver_type = (!q->dnsservice) ? mdns_resolver_type_null : mdns_dns_service_get_resolver_type(q->dnsservice); 5273 if (resolver_type == mdns_resolver_type_null) 5274 { 5275 skipUpdate = mDNStrue; 5276 } 5277 #endif 5278 if (!skipUpdate) 5279 { 5280 uint32_t responseLatencyMs, querySendCount; 5281 bool isForCellular; 5282 dns_transport_t transport; 5283 5284 querySendCount = q->metrics.querySendCount; 5285 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 5286 const mdns_querier_t querier = mdns_querier_downcast(q->client); 5287 if (querier) 5288 { 5289 querySendCount += mdns_querier_get_send_count(querier); 5290 } 5291 isForCellular = mdns_dns_service_interface_is_cellular(q->dnsservice); 5292 transport = dnssd_analytics_dns_transport_for_resolver_type(resolver_type); 5293 #else 5294 isForCellular = (q->qDNSServer && q->qDNSServer->isCell); 5295 transport = dns_transport_Do53; 5296 #endif 5297 if (querySendCount > 0 && q->metrics.firstQueryTime != 0) 5298 { 5299 responseLatencyMs = ((m->timenow - q->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond; 5300 dnssd_analytics_update_dns_query_info(isForCellular, transport, q->qtype, querySendCount, 5301 responseLatencyMs, rr->resrec.RecordType != kDNSRecordTypePacketNegative); 5302 } 5303 } 5304 q->metrics.answered = mDNStrue; 5305 } 5306 #endif 5307 // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue) 5308 // may be called twice, once when the record is received, and again when it's time to notify local clients. 5309 // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this. 5310 5311 if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q && rr->resrec.mortality != Mortality_Ghost) 5312 { 5313 debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d", 5314 rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers); 5315 if (!rr->CRActiveQuestion) 5316 { 5317 m->rrcache_active++; // If not previously active, increment rrcache_active count 5318 AdjustUnansweredQueries(m, rr); // Adjust UnansweredQueries in case the record missed out on refresher queries 5319 } 5320 rr->CRActiveQuestion = q; // We know q is non-null 5321 SetNextCacheCheckTimeForRecord(m, rr); 5322 } 5323 5324 // If this is: 5325 // (a) a no-cache add, where we've already done at least one 'QM' query, or 5326 // (b) a normal add, where we have at least one unique-type answer, 5327 // then there's no need to keep polling the network. 5328 // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.) 5329 // We do this for mDNS questions and uDNS one-shot questions, but not for 5330 // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing. 5331 if ((AddRecord == QC_addnocache && !q->RequestUnicast) || 5332 (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)))) 5333 if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived)) 5334 { 5335 ResetQuestionState(m, q); 5336 } 5337 5338 if (rr->DelayDelivery) return; // We'll come back later when CacheRecordDeferredAdd() calls us 5339 5340 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) 5341 // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return. 5342 if (!mDNSOpaque16IsZero(q->TargetQID) && DNS64StateMachine(m, q, &rr->resrec, AddRecord)) return; 5343 #endif 5344 5345 #ifdef USE_LIBIDN 5346 if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) // If negative answer, check if we need to try Punycode conversion 5347 { 5348 domainname newname; 5349 if (PerformNextPunycodeConversion(q, &newname)) // Itertative Punycode conversion succeeded, so reissue question with new name 5350 { 5351 UDPSocket *const sock = q->LocalSocket; // Save old socket and transaction ID 5352 const mDNSOpaque16 id = q->TargetQID; 5353 q->LocalSocket = mDNSNULL; 5354 mDNS_StopQuery_internal(m, q); // Stop old query 5355 AssignDomainName(&q->qname, &newname); // Update qname 5356 q->qnamehash = DomainNameHashValue(&q->qname); // and namehash 5357 mDNS_StartQuery_internal(m, q); // Start new query 5358 5359 if (sock) // Transplant saved socket, if appropriate 5360 { 5361 if (q->DuplicateOf) mDNSPlatformUDPClose(sock); 5362 else { q->LocalSocket = sock; q->TargetQID = id; } 5363 } 5364 return; // All done for now; wait until we get the next answer 5365 } 5366 } 5367 #endif // USE_LIBIDN 5368 5369 // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response 5370 // for the purpose of retrying search domains/timeout OR the question is suppressed 5371 const mDNSBool answersQuestionNegativelyDirectly = (rr->resrec.RecordType == kDNSRecordTypePacketNegative); 5372 const mDNSBool answersMDNSQuestionNegativelyIndirectly = (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)); 5373 if (answersQuestionNegativelyDirectly || answersMDNSQuestionNegativelyIndirectly) 5374 { 5375 switch (AddRecord) 5376 { 5377 case QC_rmv: 5378 // Do not deliver remove event for a negative record, because when it is deleted there must be a 5379 // positive record that answers the question coming. The add event of the positive record will 5380 // implicitly indicate the remove of the previously added negative record. 5381 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 5382 // However, if the question is the primary DNSSEC requestor that will validate the records with DNSSEC, 5383 // always deliver the negative record because it contains the denial of existence records that could 5384 // have changed. 5385 if (dns_question_is_primary_dnssec_requestor(q)) 5386 { 5387 // answersMDNSQuestionNegativelyIndirectly should be false here. 5388 break; 5389 } 5390 #endif 5391 return; 5392 case QC_add: 5393 case QC_addnocache: 5394 if (!q->ReturnIntermed) 5395 { 5396 // If the question does not want the intermediate result (for example, NXDomain or NoSuchRecord) 5397 // rather than the requested record, do not deliver the negative record. 5398 return; 5399 } 5400 break; 5401 case QC_forceresponse: 5402 case QC_suppressed: 5403 // A negative response is forced to be delivered to the callback; 5404 // Fall through. 5405 MDNS_COVERED_SWITCH_DEFAULT: 5406 break; 5407 } 5408 } 5409 5410 #if MDNSRESPONDER_SUPPORTS(APPLE, RUNTIME_MDNS_METRICS) 5411 if (AddRecord && DNSQuestionCollectsMDNSMetric(q)) 5412 { 5413 // AddRecord proves that we get a new response. 5414 if (!q->metrics.answered) 5415 { 5416 q->metrics.answered = mDNStrue; 5417 } 5418 5419 const mDNSBool cache_hit = !q->InitialCacheMiss; 5420 // Iterate through all interfaces to save the response delay and cache hit data to the specific interface. 5421 for (const NetworkInterfaceInfo *interface = GetFirstActiveInterface(m->HostInterfaces); interface; 5422 interface = GetFirstActiveInterface(interface->next)) 5423 { 5424 if (interface->delayHistogram && (interface->InterfaceID == rr->resrec.InterfaceID)) 5425 { 5426 if (cache_hit) 5427 { 5428 mdns_multicast_delay_histogram_collect_cache_hit(interface->delayHistogram); 5429 } 5430 else 5431 { 5432 const mDNSs32 diffInTicks = (m->timenow - q->metrics.firstQueryTime); 5433 if ((q->metrics.firstQueryTime != 0) && (diffInTicks > 0)) 5434 { 5435 const mDNSu32 delayInInMillisecond = getMillisecondsFromTicks(diffInTicks); 5436 5437 mdns_multicast_delay_histogram_collect_delay(interface->delayHistogram, delayInInMillisecond); 5438 } 5439 } 5440 break; 5441 } 5442 } 5443 } 5444 #endif 5445 5446 if (q->QuestionCallback) 5447 { 5448 // For CNAME results to non-CNAME questions, only inform the client if they want all intermediates or if 5449 // the expired record policy is mDNSExpiredRecordPolicy_UseCached. 5450 if (!followcname || q->ReturnIntermed || (q->ExpRecordPolicy == mDNSExpiredRecordPolicy_UseCached)) 5451 { 5452 mDNS_DropLockBeforeCallback(); // Allow client (and us) to legally make mDNS API calls 5453 if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)) 5454 { 5455 if (mDNSOpaque16IsZero(q->TargetQID)) 5456 { 5457 CacheRecord neg; 5458 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 5459 mDNSPlatformMemZero(&neg, sizeof(neg)); 5460 #endif 5461 MakeNegativeCacheRecordForQuestion(m, &neg, q, 1, rr->resrec.InterfaceID, zeroID); 5462 q->QuestionCallback(m, q, &neg.resrec, AddRecord); 5463 } 5464 } 5465 else 5466 { 5467 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) 5468 if (DNS64ShouldAnswerQuestion(q, &rr->resrec)) 5469 { 5470 DNS64AnswerCurrentQuestion(m, &rr->resrec, AddRecord); 5471 } 5472 else 5473 #endif 5474 { 5475 q->QuestionCallback(m, q, &rr->resrec, AddRecord); 5476 } 5477 } 5478 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 5479 } 5480 } 5481 // Note: Proceed with caution after this point because client callback function 5482 // invoked above is allowed to do anything, such as starting/stopping queries 5483 // (including this one itself, or the next or previous query in the linked list), 5484 // registering/deregistering records, starting/stopping NAT traversals, etc. 5485 5486 if (m->CurrentQuestion == q) 5487 { 5488 // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG), 5489 // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated 5490 // first before following it 5491 if (followcname) AnswerQuestionByFollowingCNAME(m, q, &rr->resrec); 5492 } 5493 } 5494 5495 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *cr) 5496 { 5497 cr->DelayDelivery = 0; 5498 if (m->CurrentQuestion) 5499 LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)", 5500 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 5501 m->CurrentQuestion = m->Questions; 5502 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions) 5503 { 5504 DNSQuestion *q = m->CurrentQuestion; 5505 if (CacheRecordAnswersQuestion(cr, q)) 5506 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add); 5507 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now 5508 m->CurrentQuestion = q->next; 5509 } 5510 m->CurrentQuestion = mDNSNULL; 5511 } 5512 5513 // Special values to pass to CheckForSoonToExpireRecordsEx() when the caller doesn't care about matching a cache 5514 // record's type or class. 5515 #define kCheckForSoonToExpireAnyType -1 5516 #define kCheckForSoonToExpireAnyClass -1 5517 5518 mDNSlocal mDNSs32 CheckForSoonToExpireRecordsEx(mDNS *const m, const domainname *const name, const mDNSu32 namehash, 5519 const int rrtype, const int rrclass) 5520 { 5521 const mDNSs32 threshold = m->timenow + mDNSPlatformOneSecond; // See if there are any records expiring within one second 5522 const mDNSs32 start = m->timenow - 0x10000000; 5523 mDNSs32 delay = start; 5524 const CacheGroup *const cg = CacheGroupForName(m, namehash, name); 5525 for (const CacheRecord *cr = cg ? cg->members : mDNSNULL; cr; cr = cr->next) 5526 { 5527 const ResourceRecord *const rr = &cr->resrec; 5528 const mDNSBool typeMatch = (rrtype < 0) || (rrtype == kDNSQType_ANY) || (rr->rrtype == rrtype); 5529 const mDNSBool classMatch = (rrclass < 0) || (rr->rrclass == rrclass); 5530 if (typeMatch && classMatch) 5531 { 5532 // If we have a record that is about to expire within a second, then delay until after it's been deleted. 5533 const mDNSs32 expireTime = RRExpireTime(cr); 5534 if (((threshold - expireTime) >= 0) && ((expireTime - delay) > 0)) 5535 { 5536 delay = expireTime; 5537 } 5538 } 5539 } 5540 if (delay - start > 0) 5541 return(NonZeroTime(delay)); 5542 else 5543 return(0); 5544 } 5545 5546 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash) 5547 { 5548 return CheckForSoonToExpireRecordsEx(m, name, namehash, kCheckForSoonToExpireAnyType, kCheckForSoonToExpireAnyClass); 5549 } 5550 5551 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call. 5552 // If new questions are created as a result of invoking client callbacks, they will be added to 5553 // the end of the question list, and m->NewQuestions will be set to indicate the first new question. 5554 // rr is a new CacheRecord just received into our cache 5555 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique). 5556 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback, 5557 // which may change the record list and/or question list. 5558 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 5559 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *cr) 5560 { 5561 DNSQuestion *q; 5562 5563 // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers 5564 // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion(). 5565 for (q = m->Questions; q && q != m->NewQuestions; q=q->next) 5566 { 5567 if (CacheRecordAnswersQuestion(cr, q)) 5568 { 5569 // If this question is one that's actively sending queries, and it's received ten answers within one 5570 // second of sending the last query packet, then that indicates some radical network topology change, 5571 // so reset its exponential backoff back to the start. We must be at least at the eight-second interval 5572 // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating 5573 // because we will anyway send another query within a few seconds. The first reset query is sent out 5574 // randomized over the next four seconds to reduce possible synchronization between machines. 5575 if (q->LastAnswerPktNum != m->PktNum) 5576 { 5577 q->LastAnswerPktNum = m->PktNum; 5578 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 && 5579 q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond) 5580 { 5581 LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)", 5582 q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval); 5583 q->LastQTime = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4); 5584 q->ThisQInterval = InitialQuestionInterval; 5585 SetNextQueryTime(m,q); 5586 } 5587 } 5588 verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", cr, cr->resrec.name->c, 5589 DNSTypeName(cr->resrec.rrtype), cr->resrec.rroriginalttl, cr->resrec.rDNSServer ? 5590 &cr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(cr->resrec.rDNSServer ? 5591 cr->resrec.rDNSServer->port : zeroIPPort), q); 5592 q->CurrentAnswers++; 5593 5594 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 5595 q->unansweredQueries = 0; 5596 #endif 5597 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++; 5598 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++; 5599 if (q->CurrentAnswers > 4000) 5600 { 5601 static int msgcount = 0; 5602 if (msgcount++ < 10) 5603 LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack", 5604 q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers); 5605 cr->resrec.rroriginalttl = 0; 5606 cr->UnansweredQueries = MaxUnansweredQueries; 5607 } 5608 } 5609 } 5610 5611 if (!cr->DelayDelivery) 5612 { 5613 if (m->CurrentQuestion) 5614 LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 5615 m->CurrentQuestion = m->Questions; 5616 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions) 5617 { 5618 q = m->CurrentQuestion; 5619 if (CacheRecordAnswersQuestion(cr, q)) 5620 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add); 5621 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now 5622 m->CurrentQuestion = q->next; 5623 } 5624 m->CurrentQuestion = mDNSNULL; 5625 } 5626 5627 SetNextCacheCheckTimeForRecord(m, cr); 5628 } 5629 5630 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call. 5631 // If new questions are created as a result of invoking client callbacks, they will be added to 5632 // the end of the question list, and m->NewQuestions will be set to indicate the first new question. 5633 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique) 5634 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any 5635 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists, 5636 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network. 5637 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback, 5638 // which may change the record list and/or question list. 5639 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 5640 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *cr) 5641 { 5642 LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c); 5643 if (m->CurrentQuestion) 5644 LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 5645 m->CurrentQuestion = m->Questions; 5646 // We do this for *all* questions, not stopping when we get to m->NewQuestions, 5647 // since we're not caching the record and we'll get no opportunity to do this later 5648 while (m->CurrentQuestion) 5649 { 5650 DNSQuestion *q = m->CurrentQuestion; 5651 if (CacheRecordAnswersQuestion(cr, q)) 5652 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_addnocache); // QC_addnocache means "don't expect remove events for this" 5653 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now 5654 m->CurrentQuestion = q->next; 5655 } 5656 m->CurrentQuestion = mDNSNULL; 5657 } 5658 5659 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute. 5660 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question. 5661 // If new questions are created as a result of invoking client callbacks, they will be added to 5662 // the end of the question list, and m->NewQuestions will be set to indicate the first new question. 5663 // cr is an existing cache CacheRecord that just expired and is being deleted 5664 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique). 5665 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback, 5666 // which may change the record list and/or question list. 5667 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 5668 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *cr) 5669 { 5670 if (m->CurrentQuestion) 5671 LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)", 5672 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 5673 m->CurrentQuestion = m->Questions; 5674 5675 // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters 5676 // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them. 5677 while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions) 5678 { 5679 DNSQuestion *q = m->CurrentQuestion; 5680 // When a question enters suppressed state, we generate RMV events and generate a negative 5681 // response. A cache may be present that answers this question e.g., cache entry generated 5682 // before the question became suppressed. We need to skip the suppressed questions here as 5683 // the RMV event has already been generated. 5684 if (!q->Suppressed && CacheRecordAnswersQuestion(cr, q)) 5685 { 5686 verbosedebugf("CacheRecordRmv %p %s", cr, CRDisplayString(m, cr)); 5687 q->FlappingInterface1 = mDNSNULL; 5688 q->FlappingInterface2 = mDNSNULL; 5689 5690 if (q->CurrentAnswers == 0) 5691 { 5692 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 5693 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d", 5694 q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL, 5695 mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort)); 5696 #endif 5697 } 5698 else 5699 { 5700 q->CurrentAnswers--; 5701 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--; 5702 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--; 5703 } 5704 5705 // If we have dropped below the answer threshold for this mDNS question, 5706 // restart the queries at InitialQuestionInterval. 5707 if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold)) 5708 { 5709 q->ThisQInterval = InitialQuestionInterval; 5710 q->LastQTime = m->timenow - q->ThisQInterval; 5711 SetNextQueryTime(m,q); 5712 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers", 5713 DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold); 5714 } 5715 5716 // Never generate "remove" events for negative results of the DNSSEC-unaware record. 5717 mDNSBool generateRemoveEvents = (cr->resrec.rdata->MaxRDLength > 0); 5718 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 5719 // However, generate "remove" events for negative results of the record that is used for DNSSEC validation: 5720 if (!generateRemoveEvents) 5721 { 5722 // 1. The to-be-validated negative record can contain denial of existence records that are being 5723 // tracked by the DNSSEC callback. 5724 if (resource_record_is_to_be_dnssec_validated(&cr->resrec)) 5725 { 5726 generateRemoveEvents = mDNStrue; 5727 } 5728 // 2. The DNSSEC secure negative record is currently being tracked by the DNSSEC callback. 5729 else if (resource_record_is_dnssec_validated(&cr->resrec)) 5730 { 5731 generateRemoveEvents = (resource_record_get_validation_result(&cr->resrec) == dnssec_secure); 5732 } 5733 5734 if (generateRemoveEvents) 5735 { 5736 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_INFO, "[Q%u] Delivering RMV event for the negative record - " 5737 "rr type: " PUB_DNS_TYPE ", validated: " PUB_BOOL, mDNSVal16(q->TargetQID), 5738 DNS_TYPE_PARAM(cr->resrec.rrtype), BOOL_PARAM(resource_record_is_dnssec_validated(&cr->resrec))); 5739 } 5740 } 5741 #endif 5742 5743 if (generateRemoveEvents) 5744 { 5745 if ((q->CurrentAnswers == 0) && mDNSOpaque16IsZero(q->TargetQID)) 5746 { 5747 LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents", 5748 q->qname.c, DNSTypeName(q->qtype)); 5749 ReconfirmAntecedents(m, &q->qname, q->qnamehash, cr->resrec.InterfaceID, 0); 5750 } 5751 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv); 5752 } 5753 } 5754 if (m->CurrentQuestion == q) // If m->CurrentQuestion was not auto-advanced, do it ourselves now 5755 m->CurrentQuestion = q->next; 5756 } 5757 m->CurrentQuestion = mDNSNULL; 5758 } 5759 5760 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e) 5761 { 5762 #if MDNS_MALLOC_DEBUGGING >= 1 5763 unsigned int i; 5764 for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF; 5765 #endif 5766 e->next = m->rrcache_free; 5767 m->rrcache_free = e; 5768 m->rrcache_totalused--; 5769 } 5770 5771 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp) 5772 { 5773 CacheEntity *e = (CacheEntity *)(*cp); 5774 //LogMsg("ReleaseCacheGroup: Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c); 5775 if ((*cp)->rrcache_tail != &(*cp)->members) 5776 { 5777 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, "ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)"); 5778 } 5779 //if ((*cp)->name != (domainname*)((*cp)->namestorage)) 5780 // LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage)); 5781 if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name); 5782 (*cp)->name = mDNSNULL; 5783 *cp = (*cp)->next; // Cut record from list 5784 ReleaseCacheEntity(m, e); 5785 } 5786 5787 mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp) 5788 { 5789 while (*rp) 5790 { 5791 CacheRecord *rr = *rp; 5792 *rp = (*rp)->next; // Cut record from list 5793 if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage) 5794 { 5795 mDNSPlatformMemFree(rr->resrec.rdata); 5796 rr->resrec.rdata = mDNSNULL; 5797 } 5798 // NSEC or SOA records that are not added to the CacheGroup do not share the name 5799 // of the CacheGroup. 5800 if (rr->resrec.name) 5801 { 5802 debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype)); 5803 mDNSPlatformMemFree((void *)rr->resrec.name); 5804 rr->resrec.name = mDNSNULL; 5805 } 5806 // Don't count the NSEC3 records used by anonymous browse/reg 5807 if (!rr->resrec.InterfaceID) 5808 { 5809 m->rrcache_totalused_unicast -= rr->resrec.rdlength; 5810 } 5811 ReleaseCacheEntity(m, (CacheEntity *)rr); 5812 } 5813 } 5814 5815 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r) 5816 { 5817 CacheGroup *cg; 5818 5819 //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r)); 5820 if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata); 5821 r->resrec.rdata = mDNSNULL; 5822 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 5823 mdns_forget(&r->resrec.metadata); 5824 #endif 5825 5826 cg = CacheGroupForRecord(m, &r->resrec); 5827 5828 if (!cg) 5829 { 5830 // It is okay to have this printed for NSEC/NSEC3s 5831 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "ReleaseCacheRecord: ERROR!! cg NULL for " PRI_DM_NAME " (" PUB_S ")", DM_NAME_PARAM(r->resrec.name), 5832 DNSTypeName(r->resrec.rrtype)); 5833 } 5834 // When NSEC records are not added to the cache, it is usually cached at the "nsec" list 5835 // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list 5836 // (which is handled below) and in that case it should be freed here. 5837 if (r->resrec.name && cg && r->resrec.name != cg->name) 5838 { 5839 debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype)); 5840 mDNSPlatformMemFree((void *)r->resrec.name); 5841 } 5842 r->resrec.name = mDNSNULL; 5843 5844 if (!r->resrec.InterfaceID) 5845 { 5846 m->rrcache_totalused_unicast -= r->resrec.rdlength; 5847 } 5848 5849 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 5850 MDNS_DISPOSE_DNSSEC_OBJ(r->resrec.dnssec); 5851 #endif 5852 5853 ReleaseAdditionalCacheRecords(m, &r->soa); 5854 5855 ReleaseCacheEntity(m, (CacheEntity *)r); 5856 } 5857 5858 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering 5859 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all 5860 // callbacks for old records are delivered before callbacks for newer records. 5861 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg) 5862 { 5863 CacheRecord **rp = &cg->members; 5864 5865 if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; } 5866 m->lock_rrcache = 1; 5867 5868 while (*rp) 5869 { 5870 CacheRecord *const rr = *rp; 5871 mDNSBool recordReleased = mDNSfalse; 5872 mDNSs32 event = RRExpireTime(rr); 5873 if (m->timenow - event >= 0) // If expired, delete it 5874 { 5875 if (rr->CRActiveQuestion) // If this record has one or more active questions, tell them it's going away 5876 { 5877 DNSQuestion *q = rr->CRActiveQuestion; 5878 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s", 5879 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr)); 5880 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and 5881 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry 5882 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may 5883 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is 5884 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to 5885 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries, 5886 // don't ressurect them as they will deliver duplicate "No such Record" ADD events 5887 if (((mDNSOpaque16IsZero(q->TargetQID) && (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)) || 5888 (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived)) && ActiveQuestion(q)) 5889 { 5890 q->ThisQInterval = InitialQuestionInterval; 5891 q->LastQTime = m->timenow - q->ThisQInterval; 5892 SetNextQueryTime(m, q); 5893 } 5894 CacheRecordRmv(m, rr); 5895 m->rrcache_active--; 5896 } 5897 5898 event += MAX_GHOST_TIME; // Adjust so we can check for a ghost expiration 5899 if (rr->resrec.mortality == Mortality_Mortal || // Normal expired mortal record that needs released 5900 rr->resrec.rroriginalttl == 0 || // Non-mortal record that is set to be purged 5901 (rr->resrec.mortality == Mortality_Ghost && m->timenow - event >= 0)) // A ghost record that expired more than MAX_GHOST_TIME ago 5902 { // Release as normal 5903 *rp = rr->next; // Cut it from the list before ReleaseCacheRecord 5904 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s", 5905 MortalityDisplayString(rr->resrec.mortality), 5906 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr)); 5907 ReleaseCacheRecord(m, rr); 5908 recordReleased = mDNStrue; 5909 } 5910 else // An immortal record needs to become a ghost when it expires 5911 { // Don't release this entry 5912 if (rr->resrec.mortality == Mortality_Immortal) 5913 { 5914 rr->resrec.mortality = Mortality_Ghost; // Expired immortal records become ghosts 5915 verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s", 5916 MortalityDisplayString(rr->resrec.mortality), 5917 m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr)); 5918 if (rr->DelayDelivery) 5919 { 5920 rr->DelayDelivery = 0; 5921 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "CheckCacheExpiration: Resetting DelayDelivery for new ghost"); 5922 } 5923 } 5924 } 5925 } 5926 else // else, not expired; see if we need to query 5927 { 5928 // If waiting to delay delivery, do nothing until then 5929 if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0) 5930 event = rr->DelayDelivery; 5931 else 5932 { 5933 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr); 5934 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries) 5935 { 5936 if (m->timenow - rr->NextRequiredQuery < 0) // If not yet time for next query 5937 event = NextCacheCheckEvent(rr); // then just record when we want the next query 5938 else // else trigger our question to go out now 5939 { 5940 // Set NextScheduledQuery to timenow so that SendQueries() will run. 5941 // SendQueries() will see that we have records close to expiration, and send FEQs for them. 5942 m->NextScheduledQuery = m->timenow; 5943 // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(), 5944 // which will correctly update m->NextCacheCheck for us. 5945 event = m->timenow + FutureTime; 5946 } 5947 } 5948 } 5949 } 5950 5951 if (!recordReleased) // Schedule if we did not release the record 5952 { 5953 verbosedebugf("CheckCacheExpiration:%6d %5d %s", 5954 (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr)); 5955 if (m->rrcache_nextcheck[slot] - event > 0) 5956 m->rrcache_nextcheck[slot] = event; 5957 rp = &rr->next; 5958 } 5959 } 5960 if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp); 5961 cg->rrcache_tail = rp; 5962 m->lock_rrcache = 0; 5963 } 5964 5965 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q". 5966 // 5967 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and 5968 // returns true if there is an answer. 5969 // 5970 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and 5971 // returns true to indicate the same. 5972 mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly) 5973 { 5974 AuthRecord *lr; 5975 AuthGroup *ag; 5976 5977 if (m->CurrentRecord) 5978 LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 5979 5980 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname); 5981 if (ag) 5982 { 5983 m->CurrentRecord = ag->members; 5984 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords) 5985 { 5986 AuthRecord *rr = m->CurrentRecord; 5987 m->CurrentRecord = rr->next; 5988 // 5989 // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used 5990 // to answer the query. This is handled in AnswerNewLocalOnlyQuestion. 5991 // 5992 // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more 5993 // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly 5994 // we handle both mDNSInterface_Any and scoped questions. 5995 5996 if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && (q->InterfaceID == mDNSInterface_Any || q->InterfaceID == mDNSInterface_BLE))) 5997 if (LocalOnlyRecordAnswersQuestion(rr, q)) 5998 { 5999 if (checkOnly) 6000 { 6001 LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype), 6002 ARDisplayString(m, rr)); 6003 m->CurrentRecord = mDNSNULL; 6004 return mDNStrue; 6005 } 6006 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add); 6007 if (m->CurrentQuestion != q) 6008 break; // If callback deleted q, then we're finished here 6009 } 6010 } 6011 } 6012 m->CurrentRecord = mDNSNULL; 6013 6014 if (m->CurrentQuestion != q) 6015 { 6016 LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers"); 6017 return mDNStrue; 6018 } 6019 6020 if (q->LOAddressAnswers) 6021 { 6022 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d", 6023 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers); 6024 return mDNStrue; 6025 } 6026 6027 // Before we go check the cache and ship this query on the wire, we have to be sure that there are 6028 // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we 6029 // need to just peek at them to see whether it will answer this question. If it would answer, pretend 6030 // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally 6031 // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record. 6032 if (ag) 6033 { 6034 lr = ag->NewLocalOnlyRecords; 6035 while (lr) 6036 { 6037 if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q)) 6038 { 6039 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records " 6040 " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers); 6041 return mDNStrue; 6042 } 6043 lr = lr->next; 6044 } 6045 } 6046 return mDNSfalse; 6047 } 6048 6049 // Today, we suppress questions (not send them on the wire) for several reasons e.g., 6050 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make 6051 // DNS requests. 6052 mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q) 6053 { 6054 // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response, 6055 // just deactivate the DNSQuestion. 6056 if (q->ReturnIntermed) 6057 { 6058 GenerateNegativeResponse(m, mDNSInterface_Any, QC_suppressed); 6059 } 6060 else 6061 { 6062 q->ThisQInterval = 0; 6063 } 6064 } 6065 6066 mDNSlocal void AnswerNewQuestion(mDNS *const m) 6067 { 6068 mDNSBool ShouldQueryImmediately = mDNStrue; 6069 DNSQuestion *const q = m->NewQuestions; // Grab the question we're going to answer 6070 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) 6071 if (!mDNSOpaque16IsZero(q->TargetQID)) DNS64HandleNewQuestion(m, q); 6072 #endif 6073 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); 6074 6075 verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 6076 6077 if (cg) CheckCacheExpiration(m, HashSlotFromNameHash(q->qnamehash), cg); 6078 if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; } 6079 m->NewQuestions = q->next; 6080 // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first 6081 // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that. 6082 // 6083 // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke 6084 // client callbacks, which may delete their own or any other question. Our mechanism for detecting 6085 // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the 6086 // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards 6087 // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal 6088 // advanced it), that means the question was deleted, so we no longer need to worry about answering 6089 // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the 6090 // values we computed for slot and cg are now stale and relate to a question that no longer exists). 6091 // 6092 // We can't use the usual m->CurrentQuestion mechanism for this because CacheRecordDeferredAdd() and 6093 // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks. 6094 // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when 6095 // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted. 6096 6097 if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!"); 6098 // This should be safe, because calling the client's question callback may cause the 6099 // question list to be modified, but should not ever cause the rrcache list to be modified. 6100 // If the client's question callback deletes the question, then m->CurrentQuestion will 6101 // be advanced, and we'll exit out of the loop 6102 m->lock_rrcache = 1; 6103 if (m->CurrentQuestion) { 6104 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%d->Q%d] AnswerNewQuestion ERROR m->CurrentQuestion already set: " PRI_DM_NAME " (" PUB_S ")", 6105 m->CurrentQuestion->request_id, mDNSVal16(m->CurrentQuestion->TargetQID), 6106 DM_NAME_PARAM(&m->CurrentQuestion->qname), DNSTypeName(m->CurrentQuestion->qtype)); 6107 } 6108 6109 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted 6110 if (m->CurrentQuestion != q) 6111 { 6112 LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response"); 6113 goto exit; 6114 } 6115 6116 // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly 6117 // or P2P record, then we are done. 6118 if (AnswerQuestionWithLORecord(m, q, mDNSfalse)) 6119 goto exit; 6120 6121 // Use expired records for non-mDNS DNSQuestions with the mDNSExpiredRecordPolicy_UseCached policy. 6122 const mDNSExpiredRecordPolicy policy = q->ExpRecordPolicy; 6123 const mDNSBool useExpiredRecords = !mDNSOpaque16IsZero(q->TargetQID) && (policy == mDNSExpiredRecordPolicy_UseCached); 6124 if (!q->Suppressed || q->ForceCNAMEFollows) 6125 { 6126 CacheRecord *cr; 6127 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 6128 mDNSu32 answersToValidateCount = 0; // Count the number of "to be validated" answers for a primary DNSSEC requestor. 6129 mDNSBool wildcardCNameAnswer = mDNSfalse; // Set to true if the returned "to be validated" answers contains a wildcard matched CNAME. 6130 mDNSBool negativeProvesWildcard = mDNSfalse;// Set to true if a negative record that proves wildcard answer exists has been returned. 6131 mDNSu32 positiveRRSetSize = 0; // The positive RRSet size (excluding the denial of existence record). 6132 #endif 6133 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 6134 { 6135 if (SameNameCacheRecordAnswersQuestion(cr, q)) 6136 { 6137 // SecsSinceRcvd is whole number of elapsed seconds, rounded down 6138 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - cr->TimeRcvd)) / mDNSPlatformOneSecond; 6139 mDNSBool IsExpired = (cr->resrec.rroriginalttl <= SecsSinceRcvd); 6140 if (IsExpired) 6141 { 6142 if (!useExpiredRecords || (cr->resrec.RecordType == kDNSRecordTypePacketNegative)) 6143 { 6144 continue; 6145 } 6146 } 6147 // If this record set is unexpired and marked unique, then that means we can reasonably assume we have 6148 // the whole set -- we don't need to rush out on the network and query immediately to see if there are 6149 // more answers out there. 6150 if ((cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique)) 6151 { 6152 if (!IsExpired) 6153 { 6154 ShouldQueryImmediately = mDNSfalse; 6155 } 6156 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 6157 // However, for DNSSEC we need to take extra steps to check if a query is necessary. 6158 if (dns_question_is_primary_dnssec_requestor(q) && resource_record_is_to_be_dnssec_validated(&cr->resrec)) 6159 { 6160 answersToValidateCount++; 6161 if (resource_record_is_positive(&cr->resrec)) 6162 { 6163 if (resource_record_as_rrsig_covers_rr_type(&cr->resrec, kDNSType_CNAME) && 6164 resource_record_as_rrsig_covers_wildcard_rr(&cr->resrec)) 6165 { 6166 // If the RRSIG covers a CNAME, and this RRSIG covers a wildcard resource record, 6167 // then the record (the CNAME) is a wildcard match. 6168 wildcardCNameAnswer = mDNStrue; 6169 } 6170 if (positiveRRSetSize == 0) 6171 { 6172 // Initialized once, to get the positive RRSet size. 6173 positiveRRSetSize = (mDNSu32)dnssec_obj_resource_record_member_get_rrset_size(cr->resrec.dnssec); 6174 } 6175 } 6176 else // Negative record 6177 { 6178 negativeProvesWildcard = resource_record_as_denial_of_existence_proves_wildcard_answer(&cr->resrec); 6179 } 6180 } 6181 #endif 6182 } 6183 q->CurrentAnswers++; 6184 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++; 6185 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++; 6186 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) 6187 cr->LastCachedAnswerTime = m->timenow; 6188 dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_hit); 6189 #endif 6190 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add); 6191 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here 6192 } 6193 else if (mDNSOpaque16IsZero(q->TargetQID) && RRTypeIsAddressType(cr->resrec.rrtype) && RRTypeIsAddressType(q->qtype)) 6194 { 6195 ShouldQueryImmediately = mDNSfalse; 6196 } 6197 } 6198 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 6199 if (m->CurrentQuestion == q && dns_question_is_primary_dnssec_requestor(q) && !ShouldQueryImmediately) 6200 { 6201 // If we have decided to hold the query, check if we still need to send the query out because of an 6202 // incomplete answer set. 6203 // If we have a wildcard CName answer, then we must have a denial of existence record that proves the 6204 // existence of this CName. Therefore, we can only be sure that we have a complete set if and only if: 6205 // answersToValidateCount == positiveRRSetSize + 1, where 1 is the denial of existence record. (which means the 6206 // corresponding nagative record has expired from cache). 6207 // Or if we only returned a denial of existence record that proves a wildcard answer (which means the 6208 // corresponding positive RRSet has expired from cache) 6209 // In either of two cases above, send out query anyway to get the full RRSets. 6210 const mDNSBool onlyPositive = (wildcardCNameAnswer && (answersToValidateCount != positiveRRSetSize + 1)); 6211 const mDNSBool onlyNegative = (negativeProvesWildcard && (answersToValidateCount == 1)); 6212 if (onlyPositive || onlyNegative) 6213 { 6214 ShouldQueryImmediately = mDNStrue; 6215 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_DEFAULT, 6216 "[Q%u] Continue sending out query for the primary DNSSEC question due to incomplete answer set - " 6217 "only positive: " PUB_BOOL ", only negative: " PUB_BOOL, mDNSVal16(q->TargetQID), 6218 BOOL_PARAM(onlyPositive), BOOL_PARAM(onlyNegative)); 6219 } 6220 } 6221 #endif 6222 } 6223 if (m->CurrentQuestion == q) 6224 { 6225 mDNSBool questionStopped = mDNSfalse; 6226 if (useExpiredRecords) 6227 { 6228 if (q->EventHandler) 6229 { 6230 mDNS_DropLockBeforeCallback(); 6231 q->EventHandler(q, mDNSQuestionEvent_NoMoreExpiredRecords); 6232 mDNS_ReclaimLockAfterCallback(); 6233 questionStopped = (m->CurrentQuestion != q); 6234 } 6235 if (!questionStopped) 6236 { 6237 q->ExpRecordPolicy = mDNSExpiredRecordPolicy_Immortalize; 6238 } 6239 } 6240 if (!questionStopped && q->Suppressed) 6241 { 6242 AnswerSuppressedQuestion(m, q); 6243 } 6244 } 6245 // We don't use LogInfo for this "Question deleted" message because it happens so routinely that 6246 // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs. 6247 if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; } 6248 6249 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) 6250 dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_miss); 6251 #endif 6252 q->InitialCacheMiss = mDNStrue; // Initial cache check is done, so mark as a miss from now on 6253 6254 // Note: When a query gets suppressed or retried with search domains, we de-activate the question. 6255 // Hence we don't execute the following block of code for those cases. 6256 if (ShouldQueryImmediately && ActiveQuestion(q)) 6257 { 6258 debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->request_id, mDNSVal16(q->TargetQID), q->qname.c, DNSTypeName(q->qtype)); 6259 q->ThisQInterval = InitialQuestionInterval; 6260 q->LastQTime = m->timenow - q->ThisQInterval; 6261 if (mDNSOpaque16IsZero(q->TargetQID)) // For mDNS, spread packets to avoid a burst of simultaneous queries 6262 { 6263 // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms 6264 if (!m->RandomQueryDelay) 6265 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1; 6266 q->LastQTime += m->RandomQueryDelay; 6267 } 6268 } 6269 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 6270 DPCHandleNewQuestion(q); 6271 #endif 6272 6273 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 6274 if (ActiveQuestion(q) && dns_question_uses_dns_polling(q)) 6275 { 6276 q->LongLived = mDNStrue; 6277 q->state = LLQ_Poll; 6278 q->ThisQInterval = LLQ_POLL_INTERVAL; 6279 // No matter whether the answer is cached or nor, DNS polling always follows the same query schedule. 6280 q->LastQTime = m->timenow - q->ThisQInterval + 1; 6281 } 6282 #endif 6283 6284 // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately. 6285 // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our 6286 // answers for this question until *after* its scheduled transmission time, in which case 6287 // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing 6288 // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly. 6289 SetNextQueryTime(m,q); 6290 6291 exit: 6292 m->CurrentQuestion = mDNSNULL; 6293 m->lock_rrcache = 0; 6294 } 6295 6296 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any 6297 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord 6298 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m) 6299 { 6300 AuthGroup *ag; 6301 DNSQuestion *q = m->NewLocalOnlyQuestions; // Grab the question we're going to answer 6302 mDNSBool retEv = mDNSfalse; 6303 m->NewLocalOnlyQuestions = q->next; // Advance NewLocalOnlyQuestions to the next (if any) 6304 6305 debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 6306 6307 if (m->CurrentQuestion) 6308 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)", 6309 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 6310 m->CurrentQuestion = q; // Indicate which question we're answering, so we'll know if it gets deleted 6311 6312 if (m->CurrentRecord) 6313 LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 6314 6315 // 1. First walk the LocalOnly records answering the LocalOnly question 6316 // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine, 6317 // walk the ResourceRecords list delivering the answers 6318 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname); 6319 if (ag) 6320 { 6321 m->CurrentRecord = ag->members; 6322 while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords) 6323 { 6324 AuthRecord *rr = m->CurrentRecord; 6325 m->CurrentRecord = rr->next; 6326 if (LocalOnlyRecordAnswersQuestion(rr, q)) 6327 { 6328 retEv = mDNStrue; 6329 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add); 6330 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here 6331 } 6332 } 6333 } 6334 6335 if (m->CurrentQuestion == q) 6336 { 6337 m->CurrentRecord = m->ResourceRecords; 6338 6339 while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords) 6340 { 6341 AuthRecord *ar = m->CurrentRecord; 6342 m->CurrentRecord = ar->next; 6343 if (AuthRecordAnswersQuestion(ar, q)) 6344 { 6345 retEv = mDNStrue; 6346 AnswerLocalQuestionWithLocalAuthRecord(m, ar, QC_add); 6347 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here 6348 } 6349 } 6350 } 6351 6352 // The local host is the authoritative source for LocalOnly questions 6353 // so if no records exist and client requested intermediates, then generate a negative response 6354 if (!retEv && (m->CurrentQuestion == q) && q->ReturnIntermed) 6355 GenerateNegativeResponse(m, mDNSInterface_LocalOnly, QC_forceresponse); 6356 6357 m->CurrentQuestion = mDNSNULL; 6358 m->CurrentRecord = mDNSNULL; 6359 } 6360 6361 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG) 6362 { 6363 CacheEntity *e = mDNSNULL; 6364 6365 if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); } 6366 m->lock_rrcache = 1; 6367 6368 // If we have no free records, ask the client layer to give us some more memory 6369 if (!m->rrcache_free && m->MainCallback) 6370 { 6371 if (m->rrcache_totalused != m->rrcache_size) 6372 { 6373 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "GetFreeCacheRR: count mismatch: m->rrcache_totalused %u != m->rrcache_size %u", 6374 m->rrcache_totalused, m->rrcache_size); 6375 } 6376 6377 // We don't want to be vulnerable to a malicious attacker flooding us with an infinite 6378 // number of bogus records so that we keep growing our cache until the machine runs out of memory. 6379 // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each), 6380 // and we're actively using less than 1/32 of that cache, then we purge all the unused records 6381 // and recycle them, instead of allocating more memory. 6382 if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active) 6383 { 6384 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "Possible denial-of-service attack in progress: m->rrcache_size %u; m->rrcache_active %u", 6385 m->rrcache_size, m->rrcache_active); 6386 } 6387 else 6388 { 6389 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback 6390 m->MainCallback(m, mStatus_GrowCache); 6391 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 6392 } 6393 } 6394 6395 // If we still have no free records, recycle all the records we can. 6396 // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass. 6397 if (!m->rrcache_free) 6398 { 6399 mDNSu32 oldtotalused = m->rrcache_totalused; 6400 mDNSu32 slot; 6401 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) 6402 { 6403 CacheGroup **cp = &m->rrcache_hash[slot]; 6404 while (*cp) 6405 { 6406 CacheRecord **rp = &(*cp)->members; 6407 while (*rp) 6408 { 6409 // Cases where we do not want to recycle cache entry: 6410 // 1. Records that answer still-active questions are not candidates for recycling. 6411 // 2. Records that are currently linked into the CacheFlushRecords list may not be recycled, or 6412 // we'll crash. 6413 // 3. Records that are newly added to the cache but whose callback delivery gets delayed should not 6414 // be recycled, because it will end up with an incomplete RRSet. 6415 mDNSBool doNotRecycle = ((*rp)->CRActiveQuestion || (*rp)->NextInCFList 6416 || ((*rp)->DelayDelivery != 0)); 6417 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 6418 // 4. Records that are currently saved to a temporary array to calculate the response set size may 6419 // not be recycled, or we'll crash. 6420 doNotRecycle = doNotRecycle || ((*rp)->ineligibleForRecycling); 6421 #endif 6422 6423 if (doNotRecycle) 6424 { 6425 rp=&(*rp)->next; 6426 } 6427 else 6428 { 6429 CacheRecord *rr = *rp; 6430 *rp = (*rp)->next; // Cut record from list 6431 ReleaseCacheRecord(m, rr); 6432 } 6433 } 6434 if ((*cp)->rrcache_tail != rp) 6435 verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp); 6436 (*cp)->rrcache_tail = rp; 6437 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next; 6438 else ReleaseCacheGroup(m, cp); 6439 } 6440 } 6441 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "GetCacheEntity recycled %d records to reduce cache from %d to %d", 6442 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused); 6443 } 6444 6445 if (m->rrcache_free) // If there are records in the free list, take one 6446 { 6447 e = m->rrcache_free; 6448 m->rrcache_free = e->next; 6449 if (++m->rrcache_totalused >= m->rrcache_report) 6450 { 6451 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "RR Cache now using %u objects", m->rrcache_totalused); 6452 if (m->rrcache_report < 100) m->rrcache_report += 10; 6453 else if (m->rrcache_report < 1000) m->rrcache_report += 100; 6454 else m->rrcache_report += 1000; 6455 } 6456 mDNSPlatformMemZero(e, sizeof(*e)); 6457 } 6458 6459 m->lock_rrcache = 0; 6460 6461 return(e); 6462 } 6463 6464 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength) 6465 { 6466 CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg); 6467 if (r) 6468 { 6469 r->resrec.rdata = (RData*)&r->smallrdatastorage; // By default, assume we're usually going to be using local storage 6470 if (RDLength > InlineCacheRDSize) // If RDLength is too big, allocate extra storage 6471 { 6472 r->resrec.rdata = (RData*) mDNSPlatformMemAllocateClear(sizeofRDataHeader + RDLength); 6473 if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength; 6474 else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; } 6475 } 6476 } 6477 return(r); 6478 } 6479 6480 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr) 6481 { 6482 mDNSu16 namelen = DomainNameLength(rr->name); 6483 CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL); 6484 if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); } 6485 cg->next = m->rrcache_hash[slot]; 6486 cg->namehash = rr->namehash; 6487 cg->members = mDNSNULL; 6488 cg->rrcache_tail = &cg->members; 6489 if (namelen > sizeof(cg->namestorage)) 6490 cg->name = (domainname *) mDNSPlatformMemAllocate(namelen); 6491 else 6492 cg->name = (domainname*)cg->namestorage; 6493 if (!cg->name) 6494 { 6495 LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c); 6496 ReleaseCacheEntity(m, (CacheEntity*)cg); 6497 return(mDNSNULL); 6498 } 6499 AssignDomainName(cg->name, rr->name); 6500 6501 if (CacheGroupForRecord(m, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c); 6502 m->rrcache_hash[slot] = cg; 6503 if (CacheGroupForRecord(m, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c); 6504 6505 return(cg); 6506 } 6507 6508 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr) 6509 { 6510 mDNS_CheckLock(m); 6511 6512 // Make sure we mark this record as thoroughly expired -- we don't ever want to give 6513 // a positive answer using an expired record (e.g. from an interface that has gone away). 6514 // We don't want to clear CRActiveQuestion here, because that would leave the record subject to 6515 // summary deletion without giving the proper callback to any questions that are monitoring it. 6516 // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries. 6517 rr->TimeRcvd = m->timenow - mDNSPlatformOneSecond * 60; 6518 rr->UnansweredQueries = MaxUnansweredQueries; 6519 rr->resrec.rroriginalttl = 0; 6520 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) || MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 6521 rr->DNSPushSubscribed = mDNSfalse; 6522 #endif 6523 SetNextCacheCheckTimeForRecord(m, rr); 6524 } 6525 6526 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m) 6527 { 6528 mDNSs32 time; 6529 mDNSPlatformLock(m); 6530 if (m->mDNS_busy) 6531 { 6532 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, 6533 "Lock failure: mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow."); 6534 if (!m->timenow) 6535 { 6536 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, 6537 "Lock failure: mDNS_TimeNow: m->mDNS_busy is %u but m->timenow not set", m->mDNS_busy); 6538 } 6539 } 6540 6541 if (m->timenow) time = m->timenow; 6542 else time = mDNS_TimeNow_NoLock(m); 6543 mDNSPlatformUnlock(m); 6544 return(time); 6545 } 6546 6547 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that 6548 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute(). 6549 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set) 6550 #define SetSPSProxyListChanged(X) do { \ 6551 if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \ 6552 m->SPSProxyListChanged = (X); } while(0) 6553 6554 // Called from mDNS_Execute() to expire stale proxy records 6555 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list) 6556 { 6557 m->CurrentRecord = list; 6558 while (m->CurrentRecord) 6559 { 6560 AuthRecord *rr = m->CurrentRecord; 6561 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0]) 6562 { 6563 // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more, 6564 // so we need to cease proxying for *all* records we may have, expired or not. 6565 if (m->SPSSocket && m->timenow - rr->TimeExpire < 0) // If proxy record not expired yet, update m->NextScheduledSPS 6566 { 6567 if (m->NextScheduledSPS - rr->TimeExpire > 0) 6568 m->NextScheduledSPS = rr->TimeExpire; 6569 } 6570 else // else proxy record expired, so remove it 6571 { 6572 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s", 6573 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr)); 6574 SetSPSProxyListChanged(rr->resrec.InterfaceID); 6575 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); 6576 // Don't touch rr after this -- memory may have been free'd 6577 } 6578 } 6579 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because 6580 // new records could have been added to the end of the list as a result of that call. 6581 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now 6582 m->CurrentRecord = rr->next; 6583 } 6584 } 6585 6586 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m) 6587 { 6588 while (m->CurrentRecord) 6589 { 6590 AuthRecord *rr = m->CurrentRecord; 6591 if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering) 6592 { 6593 debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr)); 6594 rr->resrec.RecordType = kDNSRecordTypeShared; 6595 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); 6596 if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now 6597 { 6598 rr->resrec.RecordType = kDNSRecordTypeDeregistering; 6599 rr->AnsweredLocalQ = mDNSfalse; 6600 // SendResponses normally calls CompleteDeregistration after sending goodbyes. 6601 // For LocalOnly records, we don't do that and hence we need to do that here. 6602 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr); 6603 } 6604 } 6605 if (m->CurrentRecord == rr) // If m->CurrentRecord was not auto-advanced, do it ourselves now 6606 m->CurrentRecord = rr->next; 6607 } 6608 } 6609 6610 mDNSlocal void TimeoutQuestions_internal(mDNS *const m, DNSQuestion* questions, mDNSInterfaceID InterfaceID) 6611 { 6612 if (m->CurrentQuestion) 6613 LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, 6614 DNSTypeName(m->CurrentQuestion->qtype)); 6615 m->CurrentQuestion = questions; 6616 while (m->CurrentQuestion) 6617 { 6618 DNSQuestion *const q = m->CurrentQuestion; 6619 if (q->StopTime) 6620 { 6621 if (!q->TimeoutQuestion) 6622 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 6623 6624 if (m->timenow - q->StopTime >= 0) 6625 { 6626 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime); 6627 q->LOAddressAnswers = 0; // unset since timing out the question 6628 GenerateNegativeResponse(m, InterfaceID, QC_forceresponse); 6629 if (m->CurrentQuestion == q) q->StopTime = 0; 6630 } 6631 else 6632 { 6633 if (m->NextScheduledStopTime - q->StopTime > 0) 6634 m->NextScheduledStopTime = q->StopTime; 6635 } 6636 } 6637 // If m->CurrentQuestion wasn't modified out from under us, advance it now 6638 // We can't do this at the start of the loop because GenerateNegativeResponse 6639 // depends on having m->CurrentQuestion point to the right question 6640 if (m->CurrentQuestion == q) 6641 m->CurrentQuestion = q->next; 6642 } 6643 m->CurrentQuestion = mDNSNULL; 6644 } 6645 6646 mDNSlocal void TimeoutQuestions(mDNS *const m) 6647 { 6648 m->NextScheduledStopTime = m->timenow + FutureTime; // push reschedule of TimeoutQuestions to way off into the future 6649 TimeoutQuestions_internal(m, m->Questions, mDNSInterface_Any); 6650 TimeoutQuestions_internal(m, m->LocalOnlyQuestions, mDNSInterface_LocalOnly); 6651 } 6652 6653 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m) 6654 { 6655 AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL; 6656 LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__); 6657 while (rrPtr) 6658 { 6659 rrNext = rrPtr->next; 6660 mDNSPlatformMemFree(rrPtr); 6661 rrPtr = rrNext; 6662 } 6663 m->SPSRRSet = mDNSNULL; 6664 } 6665 6666 #if MDNSRESPONDER_SUPPORTS(APPLE, RUNTIME_MDNS_METRICS) 6667 6668 mDNSlocal void mDNSPostResponseDelayMetrics(const mdns_multicast_delay_histogram_t histogram) 6669 { 6670 const bool posted = analytics_send_event_lazy("com.apple.mDNSResponder.mDNSResponseDelayEvent", 6671 ^{ 6672 return mdns_multicast_delay_histogram_create_metrics_dictionary(histogram); 6673 }); 6674 if (!posted) 6675 { 6676 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_WARNING, 6677 "com.apple.mDNSResponder.mDNSResponseDelayEvent: Analytic not posted"); 6678 } 6679 } 6680 6681 mDNSlocal void mDNSGenerateResponseDelayReport(mDNS *const m) 6682 { 6683 mDNSBool analyticPosted = mDNSfalse; 6684 for (const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces); intf; 6685 intf = GetFirstActiveInterface(intf->next)) 6686 { 6687 const mdns_multicast_delay_histogram_t delay_histogram = intf->delayHistogram; 6688 if (!delay_histogram) 6689 { 6690 continue; 6691 } 6692 if (mdns_multicast_delay_histogram_has_records(delay_histogram)) 6693 { 6694 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "mDNS response delay distribution - interface name: " 6695 PUB_S ", interface index: %u, report: %@" , intf->ifname, 6696 mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue), delay_histogram); 6697 if (!analyticPosted) 6698 { 6699 // Every time when we submit analytics, we only report the first available histogram. 6700 // The assumption here is that we will only have one infrastructure type interface at any given time, 6701 // which is Wi-Fi. In the case where we have more than one infrastructure interfaces, which seems 6702 // to be impossible, we always choose the first one to report. 6703 mDNSPostResponseDelayMetrics(delay_histogram); 6704 analyticPosted = mDNStrue; 6705 } 6706 } 6707 mdns_multicast_delay_histogram_reset_records(delay_histogram); 6708 } 6709 } 6710 6711 #endif 6712 6713 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m) 6714 { 6715 mDNS_Lock(m); // Must grab lock before trying to read m->timenow 6716 6717 if (m->timenow - m->NextScheduledEvent >= 0) 6718 { 6719 int i; 6720 AuthRecord *head, *tail; 6721 mDNSu32 slot; 6722 AuthGroup *ag; 6723 6724 verbosedebugf("mDNS_Execute"); 6725 6726 if (m->CurrentQuestion) 6727 LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)", 6728 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 6729 6730 if (m->CurrentRecord) 6731 LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord)); 6732 6733 // 1. If we're past the probe suppression time, we can clear it 6734 if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0; 6735 6736 // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter 6737 if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0; 6738 6739 // 3. Purge our cache of stale old records 6740 if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0) 6741 { 6742 mDNSu32 numchecked = 0; 6743 m->NextCacheCheck = m->timenow + FutureTime; 6744 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) 6745 { 6746 if (m->timenow - m->rrcache_nextcheck[slot] >= 0) 6747 { 6748 CacheGroup **cp = &m->rrcache_hash[slot]; 6749 m->rrcache_nextcheck[slot] = m->timenow + FutureTime; 6750 while (*cp) 6751 { 6752 debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL"); 6753 numchecked++; 6754 CheckCacheExpiration(m, slot, *cp); 6755 if ((*cp)->members) cp=&(*cp)->next; 6756 else ReleaseCacheGroup(m, cp); 6757 } 6758 } 6759 // Even if we didn't need to actually check this slot yet, still need to 6760 // factor its nextcheck time into our overall NextCacheCheck value 6761 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0) 6762 m->NextCacheCheck = m->rrcache_nextcheck[slot]; 6763 } 6764 debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow); 6765 } 6766 6767 if (m->timenow - m->NextScheduledSPS >= 0) 6768 { 6769 m->NextScheduledSPS = m->timenow + FutureTime; 6770 CheckProxyRecords(m, m->DuplicateRecords); // Clear m->DuplicateRecords first, then m->ResourceRecords 6771 CheckProxyRecords(m, m->ResourceRecords); 6772 } 6773 6774 SetSPSProxyListChanged(mDNSNULL); // Perform any deferred BPF reconfiguration now 6775 6776 // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above 6777 // as records could have expired during that check 6778 if (m->timenow - m->NextScheduledKA >= 0) 6779 { 6780 m->NextScheduledKA = m->timenow + FutureTime; 6781 mDNS_SendKeepalives(m); 6782 } 6783 6784 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 6785 if (m->NextBonjourDisableTime && (m->timenow - m->NextBonjourDisableTime >= 0)) 6786 { 6787 // Schedule immediate network change processing to leave the multicast group 6788 // since the delay time has expired since the previous active registration or query. 6789 m->NetworkChanged = m->timenow; 6790 m->NextBonjourDisableTime = 0; 6791 m->BonjourEnabled = 0; 6792 6793 LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group."); 6794 } 6795 #endif 6796 6797 // mDNS_SetUpDomainEnumeration() will check if the domain enumeration operation can be stopped. 6798 for (DomainEnumerationOp *op = m->domainsToDoEnumeration; op != mDNSNULL; op = op->next) 6799 { 6800 for (mDNSu32 type = 0; type < mDNS_DomainTypeMaxCount; type++) 6801 { 6802 mDNS_SetUpDomainEnumeration(m, op, type); 6803 } 6804 } 6805 6806 #if MDNSRESPONDER_SUPPORTS(COMMON, LOCAL_DNS_RESOLVER_DISCOVERY) 6807 ResolverDiscovery_PerformPeriodicTasks(); 6808 #endif 6809 6810 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 6811 // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().) 6812 if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0) 6813 { 6814 m->AnnounceOwner = 0; 6815 } 6816 #endif 6817 6818 if (m->DelaySleep && m->timenow - m->DelaySleep >= 0) 6819 { 6820 m->DelaySleep = 0; 6821 if (m->SleepState == SleepState_Transferring) 6822 { 6823 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers"); 6824 BeginSleepProcessing(m); 6825 } 6826 } 6827 6828 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 6829 // Check if there is any newly DNSSEC-validated record to be added to the cache. 6830 if (m->NextUpdateDNSSECValidatedCache && m->timenow - m->NextUpdateDNSSECValidatedCache >= 0) 6831 { 6832 m->NextUpdateDNSSECValidatedCache = 0; 6833 dnssec_update_cache_for_validated_records(m); 6834 } 6835 #endif 6836 6837 #if MDNSRESPONDER_SUPPORTS(APPLE, RUNTIME_MDNS_METRICS) 6838 const mDNSs32 NextMDNSResponseDelayReport = m->NextMDNSResponseDelayReport; 6839 if (NextMDNSResponseDelayReport && ((m->timenow - NextMDNSResponseDelayReport) >= 0)) 6840 { 6841 mDNSGenerateResponseDelayReport(m); 6842 m->NextMDNSResponseDelayReport = (m->timenow + RuntimeMDNSMetricsReportInterval); 6843 } 6844 #endif 6845 6846 // 4. See if we can answer any of our new local questions from the cache 6847 for (i=0; m->NewQuestions && i<1000; i++) 6848 { 6849 if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break; 6850 AnswerNewQuestion(m); 6851 } 6852 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit"); 6853 6854 // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before* 6855 // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below. 6856 for (i=0; i<1000 && m->LocalRemoveEvents; i++) 6857 { 6858 m->LocalRemoveEvents = mDNSfalse; 6859 m->CurrentRecord = m->ResourceRecords; 6860 CheckRmvEventsForLocalRecords(m); 6861 // Walk the LocalOnly records and deliver the RMV events 6862 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++) 6863 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next) 6864 { 6865 m->CurrentRecord = ag->members; 6866 if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m); 6867 } 6868 } 6869 6870 if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit"); 6871 6872 for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m); 6873 if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit"); 6874 6875 head = tail = mDNSNULL; 6876 for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++) 6877 { 6878 AuthRecord *rr = m->NewLocalRecords; 6879 m->NewLocalRecords = m->NewLocalRecords->next; 6880 if (LocalRecordReady(rr)) 6881 { 6882 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr)); 6883 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add); 6884 } 6885 else if (!rr->next) 6886 { 6887 // If we have just one record that is not ready, we don't have to unlink and 6888 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will 6889 // terminate and set the NewLocalRecords to rr. 6890 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr)); 6891 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL) 6892 LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords); 6893 6894 head = rr; 6895 } 6896 else 6897 { 6898 AuthRecord **p = &m->ResourceRecords; // Find this record in our list of active records 6899 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr)); 6900 // if this is the first record we are skipping, move to the end of the list. 6901 // if we have already skipped records before, append it at the end. 6902 while (*p && *p != rr) p=&(*p)->next; 6903 if (*p) *p = rr->next; // Cut this record from the list 6904 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; } 6905 if (!head) 6906 { 6907 while (*p) p=&(*p)->next; 6908 *p = rr; 6909 head = tail = rr; 6910 } 6911 else 6912 { 6913 tail->next = rr; 6914 tail = rr; 6915 } 6916 rr->next = mDNSNULL; 6917 } 6918 } 6919 m->NewLocalRecords = head; 6920 debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL")); 6921 6922 if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit"); 6923 6924 // Check to see if we have any new LocalOnly/P2P records to examine for delivering 6925 // to our local questions 6926 if (m->NewLocalOnlyRecords) 6927 { 6928 m->NewLocalOnlyRecords = mDNSfalse; 6929 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++) 6930 { 6931 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next) 6932 { 6933 for (i=0; i<100 && ag->NewLocalOnlyRecords; i++) 6934 { 6935 AuthRecord *rr = ag->NewLocalOnlyRecords; 6936 ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next; 6937 // LocalOnly records should always be ready as they never probe 6938 if (LocalRecordReady(rr)) 6939 { 6940 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr)); 6941 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add); 6942 } 6943 else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr)); 6944 } 6945 // We limit about 100 per AuthGroup that can be serviced at a time 6946 if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit"); 6947 } 6948 } 6949 } 6950 6951 // 5. See what packets we need to send 6952 if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping)) 6953 DiscardDeregistrations(m); 6954 if (m->mDNSPlatformStatus == mStatus_NoError) 6955 { 6956 // If the platform code is ready, and we're not suppressing packet generation right now 6957 // then send our responses, probes, and questions. 6958 // We check the cache first, because there might be records close to expiring that trigger questions to refresh them. 6959 // We send queries next, because there might be final-stage probes that complete their probing here, causing 6960 // them to advance to announcing state, and we want those to be included in any announcements we send out. 6961 // Finally, we send responses, including the previously mentioned records that just completed probing. 6962 if (!m->SuppressQueries || ((m->timenow - m->SuppressQueries) >= 0)) 6963 { 6964 m->SuppressQueries = 0; 6965 6966 // 6. Send Query packets. This may cause some probing records to advance to announcing state 6967 if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m); 6968 if (m->timenow - m->NextScheduledQuery >= 0) 6969 { 6970 DNSQuestion *q; 6971 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second", 6972 m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery); 6973 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond; 6974 for (q = m->Questions; q && q != m->NewQuestions; q=q->next) 6975 if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0) 6976 LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 6977 } 6978 if (m->timenow - m->NextScheduledProbe >= 0) 6979 { 6980 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second", 6981 m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe); 6982 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond; 6983 } 6984 } 6985 if (!m->SuppressResponses || ((m->timenow - m->SuppressResponses) >= 0)) 6986 { 6987 m->SuppressResponses = 0; 6988 6989 // 7. Send Response packets, including probing records just advanced to announcing state 6990 if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m); 6991 if (m->timenow - m->NextScheduledResponse >= 0) 6992 { 6993 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second"); 6994 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond; 6995 } 6996 } 6997 } 6998 6999 // Clear RandomDelay values, ready to pick a new different value next time 7000 m->RandomQueryDelay = 0; 7001 m->RandomReconfirmDelay = 0; 7002 7003 // See if any questions (or local-only questions) have timed out 7004 if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m); 7005 #ifndef UNICAST_DISABLED 7006 if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m); 7007 if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m); 7008 if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m); 7009 #endif 7010 } 7011 7012 // Note about multi-threaded systems: 7013 // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(), 7014 // performing mDNS API operations that change our next scheduled event time. 7015 // 7016 // On multi-threaded systems (like the current Windows implementation) that have a single main thread 7017 // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility 7018 // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will 7019 // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one 7020 // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful 7021 // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it 7022 // does, the state of the signal will be noticed, causing the blocking primitive to return immediately 7023 // without blocking. This avoids the race condition between the signal from the other thread arriving 7024 // just *before* or just *after* the main thread enters the blocking primitive. 7025 // 7026 // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven, 7027 // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to 7028 // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer 7029 // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale 7030 // by the time it gets to the timer callback function). 7031 7032 mDNS_Unlock(m); // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value 7033 return(m->NextScheduledEvent); 7034 } 7035 7036 #ifndef UNICAST_DISABLED 7037 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 7038 mDNSlocal void SuspendLLQs(mDNS *m) 7039 { 7040 DNSQuestion *q; 7041 for (q = m->Questions; q; q = q->next) 7042 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established) 7043 { q->ReqLease = 0; sendLLQRefresh(m, q); } 7044 } 7045 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 7046 #endif // UNICAST_DISABLED 7047 7048 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q) 7049 { 7050 AuthRecord *rr; 7051 AuthGroup *ag; 7052 7053 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname); 7054 if (ag) 7055 { 7056 for (rr = ag->members; rr; rr=rr->next) 7057 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME 7058 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q)) 7059 { 7060 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr)); 7061 return mDNStrue; 7062 } 7063 } 7064 return mDNSfalse; 7065 } 7066 7067 // ActivateUnicastQuery() is called from three places: 7068 // 1. When a new question is created 7069 // 2. On wake from sleep 7070 // 3. When the DNS configuration changes 7071 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false) 7072 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true) 7073 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately) 7074 { 7075 if (!question->DuplicateOf) 7076 { 7077 debugf("ActivateUnicastQuery: %##s %s%s", 7078 question->qname.c, DNSTypeName(question->qtype), ScheduleImmediately ? " ScheduleImmediately" : ""); 7079 question->CNAMEReferrals = 0; 7080 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; } 7081 if (question->LongLived) 7082 { 7083 question->state = LLQ_Init; 7084 question->id = zeroOpaque64; 7085 question->servPort = zeroIPPort; 7086 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; } 7087 } 7088 // If the question has local answers, then we don't want answers from outside 7089 if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question)) 7090 { 7091 question->ThisQInterval = InitialQuestionInterval; 7092 question->LastQTime = m->timenow - question->ThisQInterval; 7093 SetNextQueryTime(m, question); 7094 } 7095 } 7096 } 7097 7098 // Caller should hold the lock 7099 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords, 7100 CallbackBeforeStartQuery BeforeStartCallback, void *context) 7101 { 7102 DNSQuestion *q; 7103 DNSQuestion *restart = mDNSNULL; 7104 7105 mDNS_CheckLock(m); 7106 7107 // 1. Flush the cache records 7108 if (flushCacheRecords) flushCacheRecords(m); 7109 7110 // 2. Even though we may have purged the cache records above, before it can generate RMV event 7111 // we are going to stop the question. Hence we need to deliver the RMV event before we 7112 // stop the question. 7113 // 7114 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the 7115 // application callback can potentially stop the current question (detected by CurrentQuestion) or 7116 // *any* other question which could be the next one that we may process here. RestartQuestion 7117 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal 7118 // if the "next" question is stopped while the CurrentQuestion is stopped 7119 7120 if (m->RestartQuestion) 7121 LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)", 7122 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype)); 7123 7124 m->RestartQuestion = m->Questions; 7125 while (m->RestartQuestion) 7126 { 7127 q = m->RestartQuestion; 7128 m->RestartQuestion = q->next; 7129 // GetZoneData questions are referenced by other questions (original query that started the GetZoneData 7130 // question) through their "nta" pointer. Normally when the original query stops, it stops the 7131 // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData 7132 // question followed by the original query that refers to this GetZoneData question, we will end up 7133 // freeing the GetZoneData question and then start the "freed" question at the end. 7134 7135 if (IsGetZoneDataQuestion(q)) 7136 { 7137 DNSQuestion *refq = q->next; 7138 LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype)); 7139 // debug stuff, we just try to find the referencing question and don't do much with it 7140 while (refq) 7141 { 7142 if (q == &refq->nta->question) 7143 { 7144 LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q); 7145 } 7146 refq = refq->next; 7147 } 7148 continue; 7149 } 7150 7151 // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries 7152 if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue; 7153 7154 // If the search domains did not change, then we restart all the queries. Otherwise, only 7155 // for queries for which we "might" have appended search domains ("might" because we may 7156 // find results before we apply search domains even though AppendSearchDomains is set to 1) 7157 if (!SearchDomainsChanged || q->AppendSearchDomains) 7158 { 7159 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero 7160 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before 7161 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that 7162 // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally. 7163 // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire, 7164 // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events 7165 // for the original query using these cache entries as ADDs were never delivered using these cache 7166 // entries and hence this order is needed. 7167 7168 // If the query is suppressed, the RMV events won't be delivered 7169 if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; } 7170 7171 // Suppressed status does not affect questions that are answered using local records 7172 if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; } 7173 7174 LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q, 7175 q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains); 7176 mDNS_StopQuery_internal(m, q); 7177 if (q->ResetHandler) q->ResetHandler(q); 7178 q->next = restart; 7179 restart = q; 7180 } 7181 } 7182 7183 // 3. Callback before we start the query 7184 if (BeforeStartCallback) BeforeStartCallback(m, context); 7185 7186 // 4. Restart all the stopped queries 7187 while (restart) 7188 { 7189 q = restart; 7190 restart = restart->next; 7191 q->next = mDNSNULL; 7192 LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype)); 7193 mDNS_StartQuery_internal(m, q); 7194 } 7195 } 7196 7197 mDNSexport void mDNSCoreRestartQueries(mDNS *const m) 7198 { 7199 DNSQuestion *q; 7200 7201 #ifndef UNICAST_DISABLED 7202 // Retrigger all our uDNS questions 7203 if (m->CurrentQuestion) 7204 LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)", 7205 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 7206 m->CurrentQuestion = m->Questions; 7207 while (m->CurrentQuestion) 7208 { 7209 q = m->CurrentQuestion; 7210 m->CurrentQuestion = m->CurrentQuestion->next; 7211 if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) 7212 { 7213 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 7214 mdns_client_forget(&q->client); 7215 #endif 7216 ActivateUnicastQuery(m, q, mDNStrue); 7217 } 7218 } 7219 #endif 7220 7221 // Retrigger all our mDNS questions 7222 for (q = m->Questions; q; q=q->next) // Scan our list of questions 7223 mDNSCoreRestartQuestion(m, q); 7224 } 7225 7226 // restart question if it's multicast and currently active 7227 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q) 7228 { 7229 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) 7230 { 7231 q->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question 7232 q->RequestUnicast = kDefaultRequestUnicastCount; 7233 q->LastQTime = m->timenow - q->ThisQInterval; 7234 q->RecentAnswerPkts = 0; 7235 ExpireDupSuppressInfo(q->DupSuppress, m->timenow); 7236 m->NextScheduledQuery = m->timenow; 7237 } 7238 } 7239 7240 // restart the probe/announce cycle for multicast record 7241 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount) 7242 { 7243 if (!AuthRecord_uDNS(rr)) 7244 { 7245 if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique; 7246 rr->ProbeCount = DefaultProbeCountForRecordType(rr->resrec.RecordType); 7247 7248 if (mDNS_KeepaliveRecord(&rr->resrec)) 7249 { 7250 rr->AnnounceCount = 0; // Do not announce keepalive records 7251 } 7252 else 7253 { 7254 // announceCount < 0 indicates default announce count should be used 7255 if (announceCount < 0) 7256 announceCount = InitialAnnounceCount; 7257 if (rr->AnnounceCount < (mDNSu8)announceCount) 7258 rr->AnnounceCount = (mDNSu8)announceCount; 7259 } 7260 7261 rr->SendNSECNow = mDNSNULL; 7262 InitializeLastAPTime(m, rr); 7263 } 7264 } 7265 7266 // *************************************************************************** 7267 // MARK: - Power Management (Sleep/Wake) 7268 7269 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m) 7270 { 7271 #ifndef IDLESLEEPCONTROL_DISABLED 7272 mDNSBool allowSleep = mDNStrue; 7273 char reason[128]; 7274 7275 reason[0] = 0; 7276 7277 if (m->SystemSleepOnlyIfWakeOnLAN) 7278 { 7279 // Don't sleep if we are a proxy for any services 7280 if (m->ProxyRecords) 7281 { 7282 allowSleep = mDNSfalse; 7283 mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords); 7284 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords); 7285 } 7286 7287 if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m)) 7288 { 7289 // Scan the list of active interfaces 7290 NetworkInterfaceInfo *intf; 7291 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 7292 { 7293 if (intf->McastTxRx && !intf->Loopback && !intf->MustNotPreventSleep && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID)) 7294 { 7295 // Disallow sleep if this interface doesn't support NetWake 7296 if (!intf->NetWake) 7297 { 7298 allowSleep = mDNSfalse; 7299 mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname); 7300 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_UpdateAllowSleep: Sleep disabled because " PUB_S " does not support NetWake", 7301 intf->ifname); 7302 break; 7303 } 7304 7305 // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records 7306 // that will be offloaded. If not, we should prevent sleep. 7307 // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC. 7308 { 7309 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 7310 // Disallow sleep if there is no sleep proxy server 7311 const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL); 7312 if ( cr == mDNSNULL) 7313 #endif 7314 { 7315 allowSleep = mDNSfalse; 7316 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname); 7317 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_UpdateAllowSleep: Sleep disabled because " PUB_S 7318 " has no sleep proxy server", intf->ifname); 7319 break; 7320 } 7321 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 7322 else if (m->SPSType != 0) 7323 { 7324 mDNSu32 mymetric = LocalSPSMetric(m); 7325 mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c); 7326 if (metric >= mymetric) 7327 { 7328 allowSleep = mDNSfalse; 7329 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname); 7330 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_UpdateAllowSleep: Sleep disabled because " PUB_S 7331 " has no sleep proxy server with a better metric", intf->ifname); 7332 break; 7333 } 7334 } 7335 #endif 7336 } 7337 } 7338 } 7339 } 7340 } 7341 7342 // Call the platform code to enable/disable sleep 7343 mDNSPlatformSetAllowSleep(allowSleep, reason); 7344 #else 7345 (void) m; 7346 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */ 7347 } 7348 7349 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 7350 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid) 7351 { 7352 // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have 7353 // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time 7354 // to send. 7355 if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) || 7356 m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0) 7357 { 7358 return mDNSfalse; 7359 } 7360 7361 // If we have a pending registration for "scopeid", it is ok to send the update on that interface. 7362 // If the scopeid is too big to check for validity, we don't check against updateIntID. When 7363 // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear 7364 // updateid and we should have returned from above. 7365 // 7366 // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the 7367 // platform function to extract the value from "intf" every time. 7368 7369 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) && 7370 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID)) 7371 return mDNStrue; 7372 7373 return mDNSfalse; 7374 } 7375 #endif 7376 7377 mDNSexport void UpdateRMAC(mDNS *const m, void *context) 7378 { 7379 IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ; 7380 m->CurrentRecord = m->ResourceRecords; 7381 7382 if (!addrmap) 7383 { 7384 LogMsg("UpdateRMAC: Address mapping is NULL"); 7385 return; 7386 } 7387 7388 while (m->CurrentRecord) 7389 { 7390 AuthRecord *rr = m->CurrentRecord; 7391 // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData 7392 if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec)) 7393 { 7394 mDNSAddr raddr; 7395 getKeepaliveRaddr(m, rr, &raddr); 7396 if (mDNSSameAddress(&raddr, &addrmap->ipaddr)) 7397 { 7398 // Update the MAC address only if it is not a zero MAC address 7399 mDNSEthAddr macAddr; 7400 mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr); 7401 if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr)) 7402 { 7403 UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr)); 7404 } 7405 } 7406 } 7407 m->CurrentRecord = rr->next; 7408 } 7409 7410 if (addrmap) 7411 mDNSPlatformMemFree(addrmap); 7412 7413 } 7414 7415 mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr) 7416 { 7417 mDNSu16 newrdlength; 7418 mDNSAddr laddr = zeroAddr; 7419 mDNSAddr raddr = zeroAddr; 7420 mDNSEthAddr eth = zeroEthAddr; 7421 mDNSIPPort lport = zeroIPPort; 7422 mDNSIPPort rport = zeroIPPort; 7423 mDNSu32 timeout = 0; 7424 mDNSu32 seq = 0; 7425 mDNSu32 ack = 0; 7426 mDNSu16 win = 0; 7427 UTF8str255 txt; 7428 int rdsize; 7429 RData *newrd; 7430 mDNSTCPInfo mti; 7431 mStatus ret; 7432 7433 // Note: If we fail to update the DNS NULL record with additional information in this function, it will be registered 7434 // with the SPS like any other record. SPS will not send keepalives if it does not have additional information. 7435 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); 7436 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport)) 7437 { 7438 LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger); 7439 return mStatus_UnknownErr; 7440 } 7441 7442 if (updateMac) 7443 { 7444 if (laddr.type == mDNSAddrType_IPv4) 7445 newrdlength = (mDNSu16)mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%s", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), ethAddr); 7446 else 7447 newrdlength = (mDNSu16)mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d H=%#a D=%#a l=%u r=%u m=%s", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), ethAddr); 7448 7449 } 7450 else 7451 { 7452 // If this keepalive packet would be sent on a different interface than the current one that we are processing 7453 // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees 7454 // this DNS NULL record, it does not send any keepalives as it does not have all the information 7455 mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo)); 7456 ret = mDNSPlatformRetrieveTCPInfo(&laddr, &lport, &raddr, &rport, &mti); 7457 if (ret != mStatus_NoError) 7458 { 7459 LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret); 7460 return ret; 7461 } 7462 if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID)) 7463 { 7464 LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p", mti.IntfId, intf->InterfaceID); 7465 return mStatus_BadParamErr; 7466 } 7467 7468 if (laddr.type == mDNSAddrType_IPv4) 7469 newrdlength = (mDNSu16)mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d h=%#a d=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), ð, mti.seq, mti.ack, mti.window); 7470 else 7471 newrdlength = (mDNSu16)mDNS_snprintf((char *)&txt.c[1], sizeof(txt.c) - 1, "t=%d i=%d c=%d H=%#a D=%#a l=%u r=%u m=%.6a s=%u a=%u w=%u", timeout, kKeepaliveRetryInterval, kKeepaliveRetryCount, &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport), ð, mti.seq, mti.ack, mti.window); 7472 } 7473 7474 // Did we insert a null byte at the end ? 7475 if (newrdlength == (sizeof(txt.c) - 1)) 7476 { 7477 LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr)); 7478 return mStatus_NoMemoryErr; 7479 } 7480 7481 // Include the length for the null byte at the end 7482 txt.c[0] = (mDNSu8)(newrdlength + 1); 7483 // Account for the first length byte and the null byte at the end 7484 newrdlength += 2; 7485 7486 rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody); 7487 newrd = (RData *) mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize); 7488 if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; } 7489 7490 newrd->MaxRDLength = (mDNSu16) rdsize; 7491 mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength); 7492 7493 // If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory 7494 // was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord. 7495 // If the resource record has data that we allocated in a previous pass (to update MAC address), 7496 // free that memory here before copying in the new data. 7497 if ( rr->resrec.rdata != &rr->rdatastorage) 7498 { 7499 LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr)); 7500 mDNSPlatformMemFree(rr->resrec.rdata); 7501 } 7502 SetNewRData(&rr->resrec, newrd, newrdlength); // Update our rdata 7503 7504 LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr)); 7505 return mStatus_NoError; 7506 } 7507 7508 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 7509 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner) 7510 { 7511 const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC); 7512 const int sps = intf->NextSPSAttempt / 3; 7513 AuthRecord *rr; 7514 mDNSOpaque16 msgid; 7515 mDNSu32 scopeid; 7516 7517 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue); 7518 if (!intf->SPSAddr[sps].type) 7519 { 7520 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond; 7521 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0) 7522 m->NextScheduledSPRetry = intf->NextSPSAttemptTime; 7523 LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c); 7524 goto exit; 7525 } 7526 7527 // Mark our mDNS records (not unicast records) for transfer to SPS 7528 if (mDNSOpaque16IsZero(id)) 7529 { 7530 // We may have to register this record over multiple interfaces and we don't want to 7531 // overwrite the id. We send the registration over interface X with id "IDX" and before 7532 // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses 7533 // for "IDX". Hence, we want to use the same ID across all interfaces. 7534 // 7535 // In the case of sleep proxy server transfering its records when it goes to sleep, the owner 7536 // option check below will set the same ID across the records from the same owner. Records 7537 // with different owner option gets different ID. 7538 msgid = mDNS_NewMessageID(m); 7539 for (rr = m->ResourceRecords; rr; rr=rr->next) 7540 { 7541 if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering) 7542 { 7543 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name)))) 7544 { 7545 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner))) 7546 { 7547 rr->SendRNow = mDNSInterfaceMark; // mark it now 7548 // When we are registering on the first interface, rr->updateid is zero in which case 7549 // initialize with the new ID. For subsequent interfaces, we want to use the same ID. 7550 // At the end, all the updates sent across all the interfaces with the same ID. 7551 if (mDNSOpaque16IsZero(rr->updateid)) 7552 rr->updateid = msgid; 7553 else 7554 msgid = rr->updateid; 7555 } 7556 } 7557 } 7558 } 7559 } 7560 else 7561 msgid = id; 7562 7563 while (1) 7564 { 7565 mDNSu8 *p = m->omsg.data; 7566 // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates. 7567 // For now we follow that same logic for SPS registrations too. 7568 // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our 7569 // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet. 7570 InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags); 7571 7572 for (rr = m->ResourceRecords; rr; rr=rr->next) 7573 if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid)) 7574 { 7575 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner))) 7576 { 7577 mDNSu8 *newptr; 7578 const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace; 7579 7580 // If we can't update the keepalive record, don't send it 7581 if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError)) 7582 { 7583 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY)) 7584 { 7585 bit_clr_opaque64(rr->updateIntID, scopeid); 7586 } 7587 rr->SendRNow = mDNSNULL; 7588 continue; 7589 } 7590 7591 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) 7592 rr->resrec.rrclass |= kDNSClass_UniqueRRSet; // Temporarily set the 'unique' bit so PutResourceRecord will set it 7593 newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit); 7594 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet; // Make sure to clear 'unique' bit back to normal state 7595 if (!newptr) 7596 LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr)); 7597 else 7598 { 7599 LogSPS("SendSPSRegistration put %s 0x%x 0x%x (updateid %d) %s", intf->ifname, rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(m->omsg.h.id), ARDisplayString(m, rr)); 7600 rr->SendRNow = mDNSNULL; 7601 rr->ThisAPInterval = mDNSPlatformOneSecond; 7602 rr->LastAPTime = m->timenow; 7603 // should be initialized above 7604 if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr)); 7605 if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0) 7606 m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval); 7607 p = newptr; 7608 } 7609 } 7610 } 7611 7612 if (!m->omsg.h.mDNS_numUpdates) break; 7613 else 7614 { 7615 AuthRecord opt; 7616 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); 7617 opt.resrec.rrclass = NormalMaxDNSMessageData; 7618 opt.resrec.rdlength = sizeof(rdataOPT) * 2; // Two options in this OPT record 7619 opt.resrec.rdestimate = sizeof(rdataOPT) * 2; 7620 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease; 7621 opt.resrec.rdata->u.opt[0].optlen = DNSOpt_LeaseData_Space - 4; 7622 opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE; 7623 if (!owner->HMAC.l[0]) // If no owner data, 7624 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]); // use our own interface information 7625 else // otherwise, use the owner data we were given 7626 { 7627 opt.resrec.rdata->u.opt[1].u.owner = *owner; 7628 opt.resrec.rdata->u.opt[1].opt = kDNSOpt_Owner; 7629 opt.resrec.rdata->u.opt[1].optlen = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4; 7630 } 7631 LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt)); 7632 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData); 7633 if (!p) 7634 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt)); 7635 else 7636 { 7637 mStatus err; 7638 // Once we've attempted to register, we need to include our OWNER option in our packets when we re-awaken 7639 m->SentSleepProxyRegistration = mDNStrue; 7640 7641 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps, 7642 mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps])); 7643 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID; // For simulating packet loss 7644 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSfalse); 7645 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err); 7646 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1) 7647 { 7648 LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c); 7649 intf->NetWakeResolve[sps].qtype = kDNSType_AAAA; 7650 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]); 7651 return; 7652 } 7653 } 7654 } 7655 } 7656 7657 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10; // If successful, update NextSPSAttemptTime 7658 7659 exit: 7660 if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++; 7661 } 7662 7663 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr) 7664 { 7665 AuthRecord *ar; 7666 for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next) 7667 if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse; 7668 return mDNStrue; 7669 } 7670 #endif // MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 7671 7672 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr) 7673 { 7674 AuthRecord *newRR = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(*newRR)); 7675 if (newRR == mDNSNULL) 7676 { 7677 LogSPS("%s : could not allocate memory for new resource record", __func__); 7678 return; 7679 } 7680 7681 mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype, 7682 rr->resrec.rroriginalttl, rr->resrec.RecordType, 7683 rr->ARType, mDNSNULL, mDNSNULL); 7684 7685 AssignDomainName(&newRR->namestorage, &rr->namestorage); 7686 newRR->resrec.rdlength = DomainNameLength(rr->resrec.name); 7687 newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name); 7688 newRR->resrec.rrclass = rr->resrec.rrclass; 7689 7690 if (rr->resrec.rrtype == kDNSType_A) 7691 { 7692 newRR->resrec.rdata->u.ipv4 = rr->resrec.rdata->u.ipv4; 7693 } 7694 else if (rr->resrec.rrtype == kDNSType_AAAA) 7695 { 7696 newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6; 7697 } 7698 SetNewRData(&newRR->resrec, mDNSNULL, 0); 7699 7700 // Insert the new node at the head of the list. 7701 newRR->next = m->SPSRRSet; 7702 m->SPSRRSet = newRR; 7703 LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr)); 7704 } 7705 7706 // Some records are interface specific and some are not. The ones that are supposed to be registered 7707 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent. 7708 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an 7709 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes 7710 // registration on all the interfaces 7711 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService) 7712 { 7713 AuthRecord *ar; 7714 LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]); 7715 7716 *WakeOnlyService = mDNSfalse; 7717 7718 // Before we store the A and AAAA records that we are going to register with the sleep proxy, 7719 // make sure that the old sleep proxy records are removed. 7720 mDNSCoreFreeProxyRR(m); 7721 7722 // For records that are registered only on a specific interface, mark only that bit as it will 7723 // never be registered on any other interface. For others, it should be sent on all interfaces. 7724 for (ar = m->ResourceRecords; ar; ar=ar->next) 7725 { 7726 ar->updateIntID = zeroOpaque64; 7727 ar->updateid = zeroID; 7728 if (AuthRecord_uDNS(ar)) 7729 { 7730 continue; 7731 } 7732 if (ar->AuthFlags & AuthFlagsWakeOnly) 7733 { 7734 if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye) 7735 { 7736 ar->ImmedAnswer = mDNSInterfaceMark; 7737 *WakeOnlyService = mDNStrue; 7738 continue; 7739 } 7740 } 7741 if (!ar->resrec.InterfaceID) 7742 { 7743 LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar)); 7744 ar->updateIntID = updateIntID; 7745 } 7746 else 7747 { 7748 // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures 7749 // exactly this. 7750 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue); 7751 if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid)) 7752 { 7753 bit_set_opaque64(ar->updateIntID, scopeid); 7754 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1], 7755 ar->updateIntID.l[0], ARDisplayString(m, ar)); 7756 } 7757 else 7758 { 7759 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid); 7760 } 7761 } 7762 // Store the A and AAAA records that we registered with the sleep proxy. 7763 // We will use this to prevent spurious name conflicts that may occur when we wake up 7764 if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA) 7765 { 7766 mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar); 7767 } 7768 } 7769 } 7770 7771 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 7772 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id) 7773 { 7774 AuthRecord *ar; 7775 OwnerOptData owner = zeroOwner; 7776 7777 SendSPSRegistrationForOwner(m, intf, id, &owner); 7778 7779 for (ar = m->ResourceRecords; ar; ar=ar->next) 7780 { 7781 if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar)) 7782 { 7783 owner = ar->WakeUp; 7784 SendSPSRegistrationForOwner(m, intf, id, &owner); 7785 } 7786 } 7787 } 7788 7789 // RetrySPSRegistrations is called from SendResponses, with the lock held 7790 mDNSlocal void RetrySPSRegistrations(mDNS *const m) 7791 { 7792 AuthRecord *rr; 7793 NetworkInterfaceInfo *intf; 7794 7795 // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10 7796 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 7797 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10) 7798 intf->NextSPSAttemptTime++; 7799 7800 // Retry any record registrations that are due 7801 for (rr = m->ResourceRecords; rr; rr=rr->next) 7802 if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0) 7803 { 7804 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 7805 { 7806 // If we still have registrations pending on this interface, send it now 7807 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue); 7808 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) && 7809 (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID)) 7810 { 7811 LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr)); 7812 SendSPSRegistration(m, intf, rr->updateid); 7813 } 7814 } 7815 } 7816 7817 // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt 7818 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 7819 if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8) 7820 intf->NextSPSAttempt++; 7821 } 7822 7823 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord) 7824 { 7825 NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext; 7826 int sps = (int)(question - intf->NetWakeResolve); 7827 (void)m; // Unused 7828 LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer)); 7829 7830 if (!AddRecord) return; // Don't care about REMOVE events 7831 if (answer->rrtype != question->qtype) return; // Don't care about CNAMEs 7832 7833 // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address 7834 7835 if (answer->rrtype == kDNSType_SRV) 7836 { 7837 // 1. Got the SRV record; now look up the target host's IP address 7838 mDNS_StopQuery(m, question); 7839 intf->SPSPort[sps] = answer->rdata->u.srv.port; 7840 AssignDomainName(&question->qname, &answer->rdata->u.srv.target); 7841 question->qtype = kDNSType_A; 7842 mDNS_StartQuery(m, question); 7843 } 7844 else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr)) 7845 { 7846 // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate 7847 mDNS_StopQuery(m, question); 7848 question->ThisQInterval = -1; 7849 intf->SPSAddr[sps].type = mDNSAddrType_IPv4; 7850 intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4; 7851 mDNS_Lock(m); 7852 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now 7853 mDNS_Unlock(m); 7854 } 7855 else if (answer->rrtype == kDNSType_A && answer->rdlength == 0) 7856 { 7857 // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead 7858 mDNS_StopQuery(m, question); 7859 LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c); 7860 question->qtype = kDNSType_AAAA; 7861 mDNS_StartQuery(m, question); 7862 } 7863 else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6)) 7864 { 7865 // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate 7866 mDNS_StopQuery(m, question); 7867 question->ThisQInterval = -1; 7868 intf->SPSAddr[sps].type = mDNSAddrType_IPv6; 7869 intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6; 7870 mDNS_Lock(m); 7871 if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID); // If we're ready for this result, use it now 7872 mDNS_Unlock(m); 7873 } 7874 } 7875 #endif // MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 7876 7877 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m) 7878 { 7879 AuthRecord *rr; 7880 for (rr = m->ResourceRecords; rr; rr=rr->next) 7881 if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort))) 7882 return mDNStrue; 7883 return mDNSfalse; 7884 } 7885 7886 #define WAKE_ONLY_SERVICE 1 7887 #define AC_ONLY_SERVICE 2 7888 7889 7890 7891 7892 mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast) 7893 { 7894 AuthRecord *rr; 7895 m->SleepState = SleepState_Sleeping; 7896 7897 // If AllInterfaces is not set, the caller has already marked it appropriately 7898 // on which interfaces this should be sent. 7899 if (AllInterfaces) 7900 { 7901 NetworkInterfaceInfo *intf; 7902 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 7903 { 7904 intf->SendGoodbyes = 1; 7905 } 7906 } 7907 if (unicast) 7908 { 7909 #ifndef UNICAST_DISABLED 7910 SleepRecordRegistrations(m); // If we have no SPS, need to deregister our uDNS records 7911 #endif /* UNICAST_DISABLED */ 7912 } 7913 7914 // Mark all the records we need to deregister and send them 7915 for (rr = m->ResourceRecords; rr; rr=rr->next) 7916 if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) 7917 rr->ImmedAnswer = mDNSInterfaceMark; 7918 SendResponses(m); 7919 } 7920 7921 /* 7922 * This function attempts to detect if multiple interfaces are on the same subnet. 7923 * It makes this determination based only on the IPv4 Addresses and subnet masks. 7924 * IPv6 link local addresses that are configured by default on all interfaces make 7925 * it hard to make this determination 7926 * 7927 * The 'real' fix for this would be to send out multicast packets over one interface 7928 * and conclude that multiple interfaces are on the same subnet only if these packets 7929 * are seen on other interfaces on the same system 7930 */ 7931 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid) 7932 { 7933 NetworkInterfaceInfo *intf; 7934 NetworkInterfaceInfo *newIntf; 7935 mDNSu32 i; 7936 7937 for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next) 7938 { 7939 if ((newIntf->InterfaceID != intfid) || 7940 (newIntf->ip.type != mDNSAddrType_IPv4)) 7941 { 7942 continue; 7943 } 7944 for ( i = 0; i < count; i++) 7945 { 7946 for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next) 7947 { 7948 if ((intf->InterfaceID != regID[i]) || 7949 (intf->ip.type != mDNSAddrType_IPv4)) 7950 { 7951 continue; 7952 } 7953 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger)) 7954 { 7955 LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname); 7956 return (mDNStrue); 7957 } 7958 } 7959 } 7960 } 7961 return (mDNSfalse); 7962 } 7963 7964 mDNSlocal void DoKeepaliveCallbacks(mDNS *m) 7965 { 7966 // Loop through the keepalive records and callback with an error 7967 m->CurrentRecord = m->ResourceRecords; 7968 while (m->CurrentRecord) 7969 { 7970 AuthRecord *const rr = m->CurrentRecord; 7971 if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering)) 7972 { 7973 LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr)); 7974 if (rr->RecordCallback) 7975 rr->RecordCallback(m, rr, mStatus_BadStateErr); 7976 } 7977 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now 7978 m->CurrentRecord = rr->next; 7979 } 7980 } 7981 7982 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep 7983 mDNSlocal void BeginSleepProcessing(mDNS *const m) 7984 { 7985 mDNSBool SendGoodbyes = mDNStrue; 7986 mDNSBool WakeOnlyService = mDNSfalse; 7987 mDNSBool invokeKACallback = mDNStrue; 7988 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 7989 const CacheRecord *sps[3] = { mDNSNULL }; 7990 #endif 7991 mDNSOpaque64 updateIntID = zeroOpaque64; 7992 mDNSInterfaceID registeredIntfIDS[128] = { 0 }; 7993 mDNSu32 registeredCount = 0; 7994 int skippedRegistrations = 0; 7995 7996 m->NextScheduledSPRetry = m->timenow; 7997 7998 // Clear out the SCDynamic entry that stores the external SPS information 7999 mDNSPlatformClearSPSData(); 8000 8001 if (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false"); 8002 else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services"); 8003 else // If we have at least one advertised service 8004 { 8005 NetworkInterfaceInfo *intf; 8006 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 8007 { 8008 mDNSBool skipFullSleepProxyRegistration = mDNSfalse; 8009 // Intialize it to false. These values make sense only when SleepState is set to Sleeping. 8010 intf->SendGoodbyes = 0; 8011 8012 // If it is not multicast capable, we could not have possibly discovered sleep proxy 8013 // servers. 8014 if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID)) 8015 { 8016 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname); 8017 continue; 8018 } 8019 8020 // If we are not capable of WOMP, then don't register with sleep proxy. 8021 // 8022 // Note: If we are not NetWake capable, we don't browse for the sleep proxy server. 8023 // We might find sleep proxy servers in the cache and start a resolve on them. 8024 // But then if the interface goes away, we won't stop these questions because 8025 // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it 8026 // to stop both the browse and resolve questions. 8027 if (!intf->NetWake) 8028 { 8029 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname); 8030 intf->SendGoodbyes = 1; 8031 skippedRegistrations++; 8032 continue; 8033 } 8034 8035 // Check if we have already registered with a sleep proxy for this subnet. 8036 // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong 8037 // to the interface. 8038 if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID)) 8039 { 8040 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__, intf->ifname); 8041 skipFullSleepProxyRegistration = mDNStrue; 8042 } 8043 8044 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 8045 if (!skipFullSleepProxyRegistration) 8046 { 8047 FindSPSInCache(m, &intf->NetWakeBrowse, sps); 8048 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)", 8049 intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval); 8050 else 8051 { 8052 int i; 8053 mDNSu32 scopeid; 8054 SendGoodbyes = mDNSfalse; 8055 intf->NextSPSAttempt = 0; 8056 intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond; 8057 8058 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue); 8059 // Now we know for sure that we have to wait for registration to complete on this interface. 8060 if (scopeid < (sizeof(updateIntID) * mDNSNBBY)) 8061 bit_set_opaque64(updateIntID, scopeid); 8062 8063 // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above 8064 for (i=0; i<3; i++) 8065 { 8066 #if ForceAlerts 8067 if (intf->SPSAddr[i].type) 8068 LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); 8069 if (intf->NetWakeResolve[i].ThisQInterval >= 0) 8070 LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); 8071 #endif 8072 intf->SPSAddr[i].type = mDNSAddrType_None; 8073 if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]); 8074 intf->NetWakeResolve[i].ThisQInterval = -1; 8075 if (sps[i]) 8076 { 8077 LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i])); 8078 mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf); 8079 intf->NetWakeResolve[i].ReturnIntermed = mDNStrue; 8080 mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]); 8081 8082 // If we are registering with a Sleep Proxy for a new subnet, add it to our list 8083 registeredIntfIDS[registeredCount] = intf->InterfaceID; 8084 registeredCount++; 8085 } 8086 } 8087 } 8088 } 8089 #endif // MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 8090 } 8091 } 8092 8093 // If we have at least one interface on which we are registering with an external sleep proxy, 8094 // initialize all the records appropriately. 8095 if (!mDNSOpaque64IsZero(&updateIntID)) 8096 SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService); 8097 8098 // Call the applicaitons that registered a keepalive record to inform them that we failed to offload 8099 // the records to a sleep proxy. 8100 if (invokeKACallback) 8101 { 8102 LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records"); 8103 DoKeepaliveCallbacks(m); 8104 } 8105 8106 // SendSleepGoodbyes last two arguments control whether we send goodbyes on all 8107 // interfaces and also deregister unicast registrations. 8108 // 8109 // - If there are no sleep proxy servers, then send goodbyes on all interfaces 8110 // for both multicast and unicast. 8111 // 8112 // - If we skipped registrations on some interfaces, then we have already marked 8113 // them appropriately above. We don't need to send goodbyes for unicast as 8114 // we have registered with at least one sleep proxy. 8115 // 8116 // - If we are not planning to send any goodbyes, then check for WakeOnlyServices. 8117 // 8118 // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny 8119 // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks 8120 // at WakeOnlyServices first. 8121 if (SendGoodbyes) 8122 { 8123 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server"); 8124 SendSleepGoodbyes(m, mDNStrue, mDNStrue); 8125 } 8126 else if (skippedRegistrations) 8127 { 8128 LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces"); 8129 SendSleepGoodbyes(m, mDNSfalse, mDNSfalse); 8130 } 8131 else if (WakeOnlyService) 8132 { 8133 // If we saw WakeOnly service above, send the goodbyes now. 8134 LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService"); 8135 SendResponses(m); 8136 } 8137 } 8138 8139 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep. 8140 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up. 8141 // Normally, the platform support layer below mDNSCore should call this, not the client layer above. 8142 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep) 8143 { 8144 AuthRecord *rr; 8145 8146 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEFAULT, PUB_S " (old state %d) at %d", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow); 8147 8148 if (sleep && !m->SleepState) // Going to sleep 8149 { 8150 mDNS_Lock(m); 8151 // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server 8152 if (m->SPSSocket) 8153 { 8154 mDNSu8 oldstate = m->SPSState; 8155 mDNS_DropLockBeforeCallback(); // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here 8156 m->SPSState = 2; 8157 #ifndef SPC_DISABLED 8158 if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords); 8159 #else 8160 (void)oldstate; 8161 #endif 8162 mDNS_ReclaimLockAfterCallback(); 8163 } 8164 #ifdef _LEGACY_NAT_TRAVERSAL_ 8165 if (m->SSDPSocket) 8166 { 8167 mDNSPlatformUDPClose(m->SSDPSocket); 8168 m->SSDPSocket = mDNSNULL; 8169 } 8170 #endif 8171 m->SleepState = SleepState_Transferring; 8172 if (m->SystemWakeOnLANEnabled && m->DelaySleep) 8173 { 8174 // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep 8175 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", 8176 m->DelaySleep - m->timenow); 8177 m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10); 8178 } 8179 else 8180 { 8181 m->DelaySleep = 0; 8182 m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10); 8183 m->mDNSStats.Sleeps++; 8184 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 8185 Querier_HandleSleep(); 8186 #endif 8187 BeginSleepProcessing(m); 8188 } 8189 8190 #ifndef UNICAST_DISABLED 8191 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 8192 SuspendLLQs(m); 8193 #endif 8194 #endif 8195 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S ") seq %d", m->SleepState, 8196 m->SleepState == SleepState_Transferring ? "Transferring" : 8197 m->SleepState == SleepState_Sleeping ? "Sleeping" : "?", m->SleepSeqNum); 8198 mDNS_Unlock(m); 8199 } 8200 else if (!sleep) // Waking up 8201 { 8202 mDNSu32 slot; 8203 CacheGroup *cg; 8204 CacheRecord *cr; 8205 mDNSs32 currtime, diff; 8206 8207 mDNS_Lock(m); 8208 // Reset SleepLimit back to 0 now that we're awake again. 8209 m->SleepLimit = 0; 8210 8211 // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness 8212 if (m->SleepState != SleepState_Awake) 8213 { 8214 m->SleepState = SleepState_Awake; 8215 m->SleepSeqNum++; 8216 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 8217 if (m->SentSleepProxyRegistration) // Include OWNER option in packets for 60 seconds after waking 8218 { 8219 m->SentSleepProxyRegistration = mDNSfalse; 8220 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond); 8221 LogInfo("mDNSCoreMachineSleep: Waking, Setting AnnounceOwner"); 8222 } 8223 #endif 8224 // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake) 8225 // then we enforce a minimum delay of five seconds before we begin sleep processing. 8226 // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc., 8227 // before we make our determination of whether there's a Sleep Proxy out there we should register with. 8228 m->DelaySleep = NonZeroTime(m->timenow + kDarkWakeDelaySleep); 8229 } 8230 8231 if (m->SPSState == 3) 8232 { 8233 m->SPSState = 0; 8234 mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags); 8235 } 8236 m->mDNSStats.Wakes++; 8237 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 8238 // ... and the same for NextSPSAttempt 8239 NetworkInterfaceInfo *intf; 8240 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 8241 { 8242 intf->NextSPSAttempt = -1; 8243 } 8244 #endif 8245 8246 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 8247 Querier_HandleWake(); 8248 #endif 8249 // Restart unicast and multicast queries 8250 mDNSCoreRestartQueries(m); 8251 8252 // and reactivtate service registrations 8253 m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond); 8254 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow); 8255 8256 // 2. Re-validate our cache records 8257 currtime = mDNSPlatformUTC(); 8258 8259 diff = currtime - m->TimeSlept; 8260 FORALL_CACHERECORDS(slot, cg, cr) 8261 { 8262 // Temporary fix: For unicast cache records, look at how much time we slept. 8263 // Adjust the RecvTime by the amount of time we slept so that we age the 8264 // cache record appropriately. If it is expired already, purge. If there 8265 // is a network change that happens after the wakeup, we might purge the 8266 // cache anyways and this helps only in the case where there are no network 8267 // changes across sleep/wakeup transition. 8268 // 8269 // Note: If there is a network/DNS server change that already happened and 8270 // these cache entries are already refreshed and we are getting a delayed 8271 // wake up notification, we might adjust the TimeRcvd based on the time slept 8272 // now which can cause the cache to purge pre-maturely. As this is not a very 8273 // common case, this should happen rarely. 8274 if (!cr->resrec.InterfaceID) 8275 { 8276 if (diff > 0) 8277 { 8278 mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl); 8279 const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond; 8280 8281 // -if we have slept longer than the remaining TTL, purge and start fresh. 8282 // -if we have been sleeping for a long time, we could reduce TimeRcvd below by 8283 // a sufficiently big value which could cause the value to go into the future 8284 // because of the signed comparison of time. For this to happen, we should have been 8285 // sleeping really long (~24 days). For now, we want to be conservative and flush even 8286 // if we have slept for more than two days. 8287 8288 if (diff >= remain || diff > (2 * 24 * 3600)) 8289 { 8290 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: " PRI_S ": Purging cache entry SleptTime %d, Remaining TTL %d", 8291 CRDisplayString(m, cr), diff, remain); 8292 mDNS_PurgeCacheResourceRecord(m, cr); 8293 continue; 8294 } 8295 cr->TimeRcvd -= (diff * mDNSPlatformOneSecond); 8296 if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0) 8297 { 8298 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: " PRI_S ": Purging after adjusting the remaining TTL %d by %d seconds", 8299 CRDisplayString(m, cr), remain, diff); 8300 mDNS_PurgeCacheResourceRecord(m, cr); 8301 } 8302 else 8303 { 8304 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: " PRI_S ": Adjusted the remain ttl %u by %d seconds", 8305 CRDisplayString(m, cr), remain, diff); 8306 } 8307 } 8308 } 8309 else 8310 { 8311 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake); 8312 } 8313 } 8314 8315 // 3. Retrigger probing and announcing for all our authoritative records 8316 for (rr = m->ResourceRecords; rr; rr=rr->next) 8317 { 8318 if (AuthRecord_uDNS(rr)) 8319 { 8320 ActivateUnicastRegistration(m, rr); 8321 } 8322 else 8323 { 8324 mDNSCoreRestartRegistration(m, rr, -1); 8325 } 8326 } 8327 8328 // 4. Refresh NAT mappings 8329 // We don't want to have to assume that all hardware can necessarily keep accurate 8330 // track of passage of time while asleep, so on wake we refresh our NAT mappings. 8331 // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address. 8332 // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which 8333 // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner 8334 // than five seconds from now. 8335 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds"); 8336 RecreateNATMappings(m, mDNSPlatformOneSecond * 5); 8337 mDNS_Unlock(m); 8338 } 8339 } 8340 8341 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now) 8342 { 8343 DNSQuestion *q; 8344 AuthRecord *rr; 8345 8346 mDNS_Lock(m); 8347 8348 if (m->DelaySleep) goto notready; 8349 8350 // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks 8351 if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready; 8352 8353 m->NextScheduledSPRetry = now + 0x40000000UL; 8354 8355 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 8356 NetworkInterfaceInfo *intf; 8357 // See if we might need to retransmit any lost Sleep Proxy Registrations 8358 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 8359 if (intf->NextSPSAttempt >= 0) 8360 { 8361 if (now - intf->NextSPSAttemptTime >= 0) 8362 { 8363 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d", 8364 intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt); 8365 SendSPSRegistration(m, intf, zeroID); 8366 // Don't need to "goto notready" here, because if we do still have record registrations 8367 // that have not been acknowledged yet, we'll catch that in the record list scan below. 8368 } 8369 else 8370 if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0) 8371 m->NextScheduledSPRetry = intf->NextSPSAttemptTime; 8372 } 8373 8374 // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete 8375 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 8376 { 8377 int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3; 8378 if (intf->NetWakeResolve[sps].ThisQInterval >= 0) 8379 { 8380 LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)", 8381 intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype)); 8382 goto spsnotready; 8383 } 8384 } 8385 8386 // Scan list of registered records 8387 for (rr = m->ResourceRecords; rr; rr = rr->next) 8388 if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType > kDNSRecordTypeDeregistering) 8389 if (!mDNSOpaque64IsZero(&rr->updateIntID)) 8390 { LogSPS("mDNSCoreReadyForSleep: waiting for SPS updateIntID 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto spsnotready; } 8391 #endif 8392 8393 // Scan list of private LLQs, and make sure they've all completed their handshake with the server 8394 for (q = m->Questions; q; q = q->next) 8395 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp) 8396 { 8397 LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 8398 goto notready; 8399 } 8400 8401 // Scan list of registered records 8402 for (rr = m->ResourceRecords; rr; rr = rr->next) 8403 if (AuthRecord_uDNS(rr)) 8404 { 8405 if (rr->state == regState_Refresh && rr->tcp) 8406 { LogSPS("mDNSCoreReadyForSleep: waiting for Record updateIntID 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr)); goto notready; } 8407 } 8408 8409 mDNS_Unlock(m); 8410 return mDNStrue; 8411 8412 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 8413 spsnotready: 8414 8415 // If we failed to complete sleep proxy registration within ten seconds, we give up on that 8416 // and allow up to ten seconds more to complete wide-area deregistration instead 8417 if (now - m->SleepLimit >= 0) 8418 { 8419 LogMsg("Failed to register with SPS, now sending goodbyes"); 8420 8421 for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) 8422 if (intf->NetWakeBrowse.ThisQInterval >= 0) 8423 { 8424 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)", 8425 intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype)); 8426 mDNS_DeactivateNetWake_internal(m, intf); 8427 } 8428 8429 for (rr = m->ResourceRecords; rr; rr = rr->next) 8430 if (!AuthRecord_uDNS(rr)) 8431 if (!mDNSOpaque64IsZero(&rr->updateIntID)) 8432 { 8433 LogSPS("ReadyForSleep clearing updateIntID 0x%x 0x%x (updateid %d) for %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr)); 8434 rr->updateIntID = zeroOpaque64; 8435 } 8436 8437 // We'd really like to allow up to ten seconds more here, 8438 // but if we don't respond to the sleep notification within 30 seconds 8439 // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake. 8440 // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds 8441 // more for SPS resolves and record registrations to complete, which puts us at 26 seconds. 8442 // If we allow just one more second to send our goodbyes, that puts us at 27 seconds. 8443 m->SleepLimit = now + mDNSPlatformOneSecond * 1; 8444 8445 SendSleepGoodbyes(m, mDNStrue, mDNStrue); 8446 } 8447 #endif 8448 8449 notready: 8450 mDNS_Unlock(m); 8451 return mDNSfalse; 8452 } 8453 8454 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now, mDNSNextWakeReason *outReason) 8455 { 8456 AuthRecord *ar; 8457 8458 // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other 8459 // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed. 8460 // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment, 8461 // and if that happens we don't want to just give up and go back to sleep and never try again. 8462 mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond); // Sleep for at most 120 minutes 8463 mDNSNextWakeReason reason = mDNSNextWakeReason_UpkeepWake; 8464 8465 NATTraversalInfo *nat; 8466 for (nat = m->NATTraversals; nat; nat=nat->next) 8467 { 8468 if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4) 8469 { 8470 mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10; // Wake up when 90% of the way to the expiry time 8471 if ((e - t) > 0) 8472 { 8473 e = t; 8474 reason = mDNSNextWakeReason_NATPortMappingRenewal; 8475 } 8476 LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d", 8477 nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP", 8478 mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result, 8479 nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0, 8480 nat->retryInterval / mDNSPlatformOneSecond, 8481 nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0, 8482 (t - now) / mDNSPlatformOneSecond); 8483 } 8484 } 8485 // This loop checks both the time we need to renew wide-area registrations, 8486 // and the time we need to renew Sleep Proxy registrations 8487 for (ar = m->ResourceRecords; ar; ar = ar->next) 8488 { 8489 if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4) 8490 { 8491 mDNSs32 t = ar->expire - (ar->expire - now) / 10; // Wake up when 90% of the way to the expiry time 8492 if ((e - t) > 0) 8493 { 8494 e = t; 8495 reason = mDNSNextWakeReason_RecordRegistrationRenewal; 8496 } 8497 LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s", 8498 ar, ar->ThisAPInterval / mDNSPlatformOneSecond, 8499 (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond, 8500 ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0, 8501 (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar)); 8502 } 8503 } 8504 if (outReason) 8505 { 8506 *outReason = reason; 8507 } 8508 return(e - now); 8509 } 8510 8511 // *************************************************************************** 8512 // MARK: - Packet Reception Functions 8513 8514 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo) 8515 8516 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end, 8517 const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords) 8518 { 8519 mDNSu8 *responseptr = response->data; 8520 const mDNSu8 *const limit = response->data + sizeof(response->data); 8521 const mDNSu8 *ptr = query->data; 8522 AuthRecord *rr; 8523 mDNSu32 maxttl = (!InterfaceID) ? mDNSMaximumUnicastTTLSeconds : mDNSMaximumMulticastTTLSeconds; 8524 int i; 8525 8526 // Initialize the response fields so we can answer the questions 8527 InitializeDNSMessage(&response->h, query->h.id, ResponseFlags); 8528 8529 // *** 8530 // *** 1. Write out the list of questions we are actually going to answer with this packet 8531 // *** 8532 if (LegacyQuery) 8533 { 8534 maxttl = kStaticCacheTTL; 8535 for (i=0; i<query->h.numQuestions; i++) // For each question... 8536 { 8537 DNSQuestion q; 8538 ptr = getQuestion(query, ptr, end, InterfaceID, &q); // get the question... 8539 if (!ptr) return(mDNSNULL); 8540 8541 for (rr=ResponseRecords; rr; rr=rr->NextResponse) // and search our list of proposed answers 8542 { 8543 if (rr->NR_AnswerTo == ptr) // If we're going to generate a record answering this question 8544 { // then put the question in the question section 8545 responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass); 8546 if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); } 8547 break; // break out of the ResponseRecords loop, and go on to the next question 8548 } 8549 } 8550 } 8551 8552 if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); } 8553 } 8554 8555 // *** 8556 // *** 2. Write Answers 8557 // *** 8558 for (rr=ResponseRecords; rr; rr=rr->NextResponse) 8559 if (rr->NR_AnswerTo) 8560 { 8561 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec, 8562 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl); 8563 if (p) responseptr = p; 8564 else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; } 8565 } 8566 8567 // *** 8568 // *** 3. Write Additionals 8569 // *** 8570 for (rr=ResponseRecords; rr; rr=rr->NextResponse) 8571 if (rr->NR_AdditionalTo && !rr->NR_AnswerTo) 8572 { 8573 mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec, 8574 maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl); 8575 if (p) responseptr = p; 8576 else debugf("GenerateUnicastResponse: No more space for additionals"); 8577 } 8578 8579 return(responseptr); 8580 } 8581 8582 // AuthRecord *our is our Resource Record 8583 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network 8584 // Returns 0 if there is no conflict 8585 // Returns +1 if there was a conflict and we won 8586 // Returns -1 if there was a conflict and we lost and have to rename 8587 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt) 8588 { 8589 mDNSu8 ourdata[256], *ourptr = ourdata, *ourend; 8590 mDNSu8 pktdata[256], *pktptr = pktdata, *pktend; 8591 if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); } 8592 if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); } 8593 8594 #if defined(__clang_analyzer__) 8595 // Get rid of analyzer warnings about ourptr and pktptr pointing to garbage after retruning from putRData(). 8596 // There are no clear indications from the analyzer of the cause of the supposed problem. 8597 mDNSPlatformMemZero(ourdata, 1); 8598 mDNSPlatformMemZero(pktdata, 1); 8599 #endif 8600 ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec); 8601 pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec); 8602 while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; } 8603 if (ourptr >= ourend && pktptr >= pktend) return(0); // If data identical, not a conflict 8604 8605 if (ourptr >= ourend) return(-1); // Our data ran out first; We lost 8606 if (pktptr >= pktend) return(+1); // Packet data ran out first; We won 8607 if (*pktptr > *ourptr) return(-1); // Our data is numerically lower; We lost 8608 if (*pktptr < *ourptr) return(+1); // Packet data is numerically lower; We won 8609 8610 LogMsg("CompareRData ERROR: Invalid state"); 8611 return(-1); 8612 } 8613 8614 mDNSlocal mDNSBool PacketRecordMatches(const AuthRecord *const rr, const CacheRecord *const pktrr, const AuthRecord *const master) 8615 { 8616 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec)) 8617 { 8618 const AuthRecord *r2 = rr; 8619 while (r2->DependentOn) r2 = r2->DependentOn; 8620 if (r2 == master) return(mDNStrue); 8621 } 8622 return(mDNSfalse); 8623 } 8624 8625 // See if we have an authoritative record that's identical to this packet record, 8626 // whose canonical DependentOn record is the specified master record. 8627 // The DependentOn pointer is typically used for the TXT record of service registrations 8628 // It indicates that there is no inherent conflict detection for the TXT record 8629 // -- it depends on the SRV record to resolve name conflicts 8630 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn 8631 // pointer chain (if any) to make sure we reach the canonical DependentOn record 8632 // If the record has no DependentOn, then just return that record's pointer 8633 // Returns NULL if we don't have any local RRs that are identical to the one from the packet 8634 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master) 8635 { 8636 const AuthRecord *r1; 8637 for (r1 = m->ResourceRecords; r1; r1=r1->next) 8638 { 8639 if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue); 8640 } 8641 for (r1 = m->DuplicateRecords; r1; r1=r1->next) 8642 { 8643 if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue); 8644 } 8645 return(mDNSfalse); 8646 } 8647 8648 // Find the canonical RRSet pointer for this RR received in a packet. 8649 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet 8650 // pointers (if any) to make sure we return the canonical member of this name/type/class 8651 // Returns NULL if we don't have any local RRs that are identical to the one from the packet 8652 mDNSlocal uintptr_t FindRRSet(const mDNS *const m, const CacheRecord *const pktrr) 8653 { 8654 const AuthRecord *rr; 8655 for (rr = m->ResourceRecords; rr; rr=rr->next) 8656 { 8657 if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec)) 8658 { 8659 return(rr->RRSet ? rr->RRSet : (uintptr_t)rr); 8660 } 8661 } 8662 return(0); 8663 } 8664 8665 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name 8666 // as one of our records (our) but different rdata. 8667 // 1. If our record is not a type that's supposed to be unique, we don't care. 8668 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one. 8669 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer 8670 // points to our record, ignore this conflict (e.g. the packet record matches one of our 8671 // TXT records, and that record is marked as dependent on 'our', its SRV record). 8672 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record 8673 // are members of the same RRSet, then this is not a conflict. 8674 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr) 8675 { 8676 // If not supposed to be unique, not a conflict 8677 if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse); 8678 8679 // If a dependent record, not a conflict 8680 if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse); 8681 else 8682 { 8683 // If the pktrr matches a member of ourset, not a conflict 8684 const uintptr_t ourset = our->RRSet ? our->RRSet : (uintptr_t)our; 8685 const uintptr_t pktset = FindRRSet(m, pktrr); 8686 if (pktset == ourset) return(mDNSfalse); 8687 8688 // For records we're proxying, where we don't know the full 8689 // relationship between the records, having any matching record 8690 // in our AuthRecords list is sufficient evidence of non-conflict 8691 if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse); 8692 } 8693 8694 // Okay, this is a conflict 8695 return(mDNStrue); 8696 } 8697 8698 // If we don't have TSR record or probe doesn't have TSR record that has the same name with auth record, return 0; 8699 // If both have TSR, then compare tsr_value in our TSR AuthRecord and the TSR record in probe. 8700 mDNSexport eTSRCheckResult CheckTSRForResourceRecord(const TSROptData *curTSROpt, const ResourceRecord *ourTSRRec) 8701 { 8702 #define TSR_QUANTIZATION_SECS 2 8703 eTSRCheckResult result = eTSRCheckNoKeyMatch; 8704 if (curTSROpt && ourTSRRec) 8705 { 8706 const TSROptData *ourTSROpt = &ourTSRRec->rdata->u.opt[0].u.tsr; 8707 if (ourTSROpt->hostkeyHash == curTSROpt->hostkeyHash) 8708 { 8709 result = eTSRCheckKeyMatch; 8710 // tsr_value stored locally is absolute time. 8711 mDNSs32 ourTimeOfReceipt = ourTSROpt->timeStamp; 8712 // tsr_value in packet is relative time. 8713 mDNSs32 pktTimeSinceReceived = curTSROpt->timeStamp; 8714 mDNSs32 pktTimeOfReceipt; 8715 // out of range tsr_value in pkt 8716 if (pktTimeSinceReceived < 0 || pktTimeSinceReceived > MaxTimeSinceReceived) 8717 { 8718 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "CheckTSR - Out of range pktTimeSinceReceived %d in Pkt record", pktTimeSinceReceived); 8719 pktTimeSinceReceived = MaxTimeSinceReceived; 8720 } 8721 pktTimeOfReceipt = mDNSPlatformContinuousTimeSeconds() - pktTimeSinceReceived; 8722 // tsr in probe is newer counted as we lose. 8723 if (abs(ourTimeOfReceipt - pktTimeOfReceipt) > TSR_QUANTIZATION_SECS) 8724 { 8725 result = (ourTimeOfReceipt < pktTimeOfReceipt) ? eTSRCheckLose : eTSRCheckWin; 8726 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 8727 "CheckTSR - pktTimeOfReceipt: %d %x " PUB_S " ourTimeOfReceipt: %d %x", 8728 pktTimeOfReceipt, curTSROpt->hostkeyHash, result < 0 ? "lose" : "win", ourTimeOfReceipt, 8729 ourTSROpt->hostkeyHash); 8730 } 8731 } 8732 } 8733 return result; 8734 } 8735 8736 mDNSlocal eTSRCheckResult CheckTSRForAuthRecord(mDNS *const m, const TSROptData *curTSROpt, const AuthRecord *const ar) 8737 { 8738 const AuthRecord *ourTSR = mDNSGetTSRForAuthRecord(m, ar); 8739 if (ourTSR) 8740 { 8741 return CheckTSRForResourceRecord(curTSROpt, &ourTSR->resrec); 8742 } 8743 return eTSRCheckNoKeyMatch; 8744 } 8745 8746 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change 8747 // the record list and/or question list. 8748 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 8749 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end, 8750 DNSQuestion *q, AuthRecord *our, const TSROptData *curTSR) 8751 { 8752 int i; 8753 const mDNSu8 *ptr = LocateAuthorities(query, end); 8754 mDNSBool FoundUpdate = mDNSfalse; 8755 8756 for (i = 0; i < query->h.numAuthorities; i++) 8757 { 8758 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec); 8759 if (!ptr) break; 8760 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && CacheRecordAnswersQuestion(&m->rec.r, q)) 8761 { 8762 FoundUpdate = mDNStrue; 8763 if (curTSR) 8764 { 8765 // When conflict happens, look for TSR loss. 8766 eTSRCheckResult tsrResult = CheckTSRForAuthRecord(m, curTSR, our); 8767 if (tsrResult == eTSRCheckLose) 8768 { 8769 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 8770 "ResolveSimultaneousProbe - deregistering " PRI_DM_NAME " type " PUB_S " on interface id: %p due to TSR conflict", 8771 DM_NAME_PARAM(our->resrec.name), DNSTypeName(our->resrec.rrtype), our->resrec.InterfaceID); 8772 mDNS_Deregister_internal(m, our, mDNS_Dereg_stale); 8773 goto exit; 8774 } 8775 if (tsrResult != eTSRCheckNoKeyMatch) // No else 8776 { 8777 goto exit; 8778 } 8779 } 8780 8781 if (PacketRRConflict(m, our, &m->rec.r)) 8782 { 8783 int result = 0; 8784 8785 if (!result) result = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass; 8786 if (!result) result = (int)our->resrec.rrtype - (int)m->rec.r.resrec.rrtype; 8787 if (!result) result = CompareRData(our, &m->rec.r); 8788 if (result) 8789 { 8790 const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: "; 8791 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r)); 8792 LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our)); 8793 } 8794 // If we lost the tie-break for simultaneous probes, we don't immediately give up, because we might be seeing stale packets on the network. 8795 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again. 8796 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename. 8797 if (result < 0) 8798 { 8799 m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond); 8800 our->ProbeCount = DefaultProbeCountForTypeUnique; 8801 our->AnnounceCount = InitialAnnounceCount; 8802 InitializeLastAPTime(m, our); 8803 goto exit; 8804 } 8805 } 8806 #if 0 8807 else 8808 { 8809 LogMsg("ResolveSimultaneousProbe: %p Pkt Record: %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r)); 8810 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign: %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our)); 8811 } 8812 #endif 8813 } 8814 mDNSCoreResetRecord(m); 8815 } 8816 if (!FoundUpdate) 8817 LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype)); 8818 exit: 8819 mDNSCoreResetRecord(m); 8820 } 8821 8822 8823 // Return mDNStrue if the query is a probe and has an identical record in the authority section. 8824 // Otherwise return mDNSfalse. 8825 mDNSlocal mDNSBool ProbeHasIdenticalRR(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end, 8826 const DNSQuestion *const q, const AuthRecord *const our) 8827 { 8828 int i; 8829 const mDNSu8 *ptr = LocateAuthorities(query, end); 8830 mDNSBool result = mDNSfalse; 8831 8832 // This is not a probe 8833 if (!ptr || query->h.numAuthorities == 0) 8834 { 8835 goto done; 8836 } 8837 for (i = 0; i < query->h.numAuthorities && ptr; i++) 8838 { 8839 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec); 8840 if (!ptr) 8841 { 8842 break; 8843 } 8844 if (IdenticalSameNameRecord(&m->rec.r.resrec, &our->resrec)) 8845 { 8846 mDNSCoreResetRecord(m); 8847 result = mDNStrue; 8848 goto done; 8849 } 8850 mDNSCoreResetRecord(m); 8851 } 8852 done: 8853 return result; 8854 } 8855 8856 // Step1: Compare the TSR AuthRecord and the TSR record in probe, 8857 // skip conflict check if there is no TSR record or no hashkey match 8858 // Step2: Check whether auth names in probe match our auth record; 8859 // Return mDNStrue if the TSR in probe wins, otherwise return mDNSfalse. 8860 mDNSlocal mDNSBool ProbeRRMatchAndTSRCheck(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end, 8861 const DNSQuestion *const q, const AuthRecord *const our, const TSROptData *curTSR) 8862 { 8863 int i; 8864 const mDNSu8 *ptr = LocateAuthorities(query, end); 8865 mDNSBool conflict = mDNSfalse; 8866 mDNSBool probeTSRWin = mDNSfalse; 8867 8868 // This is not a probe 8869 if (ptr == mDNSNULL || query->h.numAuthorities == 0) 8870 { 8871 goto done; 8872 } 8873 if (CheckTSRForAuthRecord(m, curTSR, our) == eTSRCheckLose) 8874 { 8875 probeTSRWin = mDNStrue; 8876 } 8877 else 8878 { 8879 goto done; 8880 } 8881 for (i = 0; i < query->h.numAuthorities && ptr; i++) 8882 { 8883 ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec); 8884 if (ptr == mDNSNULL) 8885 { 8886 break; 8887 } 8888 if (PacketRRMatchesSignature(&m->rec.r, our) && (our->resrec.RecordType & kDNSRecordTypeUniqueMask)) 8889 { 8890 mDNSCoreResetRecord(m); 8891 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "ProbeRRMatchAndTSRCheck: pkt ar on interface %p rrtype: " PRI_S ", name: " PRI_DM_NAME PRI_S, 8892 q->InterfaceID, DNSTypeName(m->rec.r.resrec.rrtype), DM_NAME_PARAM(m->rec.r.resrec.name), CRDisplayString(m, &m->rec.r)); 8893 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "ProbeRRMatchAndTSRCheck: Conflict with our ar %p rrtype: " PRI_S ", name: " PRI_DM_NAME PRI_S, 8894 our->resrec.InterfaceID, DNSTypeName(our->resrec.rrtype), DM_NAME_PARAM(our->resrec.name), ARDisplayString(m, our)); 8895 conflict = mDNStrue; 8896 break; 8897 } 8898 mDNSCoreResetRecord(m); 8899 } 8900 done: 8901 return (conflict && probeTSRWin); 8902 } 8903 8904 mDNSlocal const mDNSu8 *DomainNamePtrAtTSRIndex(const DNSMessage *const msg, const mDNSu8 *const end, mDNSu16 recIndex) 8905 { 8906 mDNSu16 i = 0; 8907 const mDNSu8 *ptr = mDNSNULL; 8908 if (msg->h.numAnswers >= recIndex) 8909 { 8910 ptr = LocateAnswers(msg, end); 8911 } 8912 else if (msg->h.numAnswers + msg->h.numAuthorities >= recIndex) 8913 { 8914 ptr = LocateAuthorities(msg, end); 8915 i = msg->h.numAnswers; 8916 } 8917 else if (msg->h.numAnswers + msg->h.numAuthorities + msg->h.numAdditionals >= recIndex) 8918 { 8919 ptr = LocateAdditionals(msg, end); 8920 i = msg->h.numAnswers + msg->h.numAuthorities; 8921 } 8922 while (ptr && i++ < recIndex) 8923 { 8924 ptr = skipResourceRecord(msg, ptr, end); 8925 } 8926 if (ptr >= end) 8927 { 8928 ptr = mDNSNULL; 8929 } 8930 return ptr; 8931 } 8932 8933 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr) 8934 { 8935 CacheGroup *cg = CacheGroupForRecord(m, pktrr); 8936 CacheRecord *rr; 8937 mDNSBool match; 8938 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) 8939 { 8940 if (!pktrr->InterfaceID) 8941 { 8942 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 8943 match = mdns_cache_metadata_same_dns_service(pktrr->metadata, rr->resrec.metadata); 8944 #else 8945 const mDNSu32 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0); 8946 const mDNSu32 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0); 8947 match = (id1 == id2); 8948 #endif 8949 } 8950 else match = (pktrr->InterfaceID == rr->resrec.InterfaceID); 8951 8952 if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break; 8953 } 8954 return(rr); 8955 } 8956 mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr) 8957 { 8958 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host 8959 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it 8960 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); 8961 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID); 8962 } 8963 8964 mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID) 8965 { 8966 if (m->CurrentRecord) 8967 LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 8968 m->CurrentRecord = thelist; 8969 8970 // Normally, the RDATA of the keepalive record will be different each time and hence we always 8971 // clean up the keepalive record. 8972 while (m->CurrentRecord) 8973 { 8974 AuthRecord *const rr = m->CurrentRecord; 8975 if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC)) 8976 { 8977 if (mDNS_KeepaliveRecord(&m->rec.r.resrec)) 8978 { 8979 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s", 8980 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr)); 8981 DeregisterProxyRecord(m, rr); 8982 } 8983 } 8984 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because 8985 // new records could have been added to the end of the list as a result of that call. 8986 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now 8987 m->CurrentRecord = rr->next; 8988 } 8989 } 8990 8991 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request, 8992 // to check our lists and discard any stale duplicates of this record we already have 8993 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist) 8994 { 8995 if (m->CurrentRecord) 8996 LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 8997 m->CurrentRecord = thelist; 8998 while (m->CurrentRecord) 8999 { 9000 AuthRecord *const rr = m->CurrentRecord; 9001 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC)) 9002 if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec)) 9003 { 9004 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s", 9005 m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr)); 9006 DeregisterProxyRecord(m, rr); 9007 } 9008 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because 9009 // new records could have been added to the end of the list as a result of that call. 9010 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now 9011 m->CurrentRecord = rr->next; 9012 } 9013 } 9014 9015 // Called from ProcessQuery when we get an mDNS packet with an owner record in it 9016 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist) 9017 { 9018 if (m->CurrentRecord) 9019 LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 9020 m->CurrentRecord = thelist; 9021 while (m->CurrentRecord) 9022 { 9023 AuthRecord *const rr = m->CurrentRecord; 9024 if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC)) 9025 if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60) 9026 { 9027 if (rr->AddressProxy.type == mDNSAddrType_IPv6) 9028 { 9029 // We don't do this here because we know that the host is waking up at this point, so we don't send 9030 // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be 9031 // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict. 9032 #if defined(MDNS_USE_Unsolicited_Neighbor_Advertisements) && MDNS_USE_Unsolicited_Neighbor_Advertisements 9033 LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s", 9034 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr)); 9035 SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth); 9036 #endif 9037 } 9038 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s", 9039 m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType, 9040 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr)); 9041 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared; 9042 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host 9043 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional 9044 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); 9045 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID); 9046 } 9047 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because 9048 // new records could have been added to the end of the list as a result of that call. 9049 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now 9050 m->CurrentRecord = rr->next; 9051 } 9052 } 9053 9054 // ProcessQuery examines a received query to see if we have any answers to give 9055 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end, 9056 const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast, 9057 mDNSBool QueryWasLocalUnicast, DNSMessage *const response, mDNSBool *const outHasResponse) 9058 { 9059 const mDNSBool FromLocalSubnet = mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr); 9060 AuthRecord *ResponseRecords = mDNSNULL; 9061 AuthRecord **nrp = &ResponseRecords; 9062 9063 #if POOF_ENABLED 9064 mDNSBool notD2D = !mDNSPlatformInterfaceIsD2D(InterfaceID); // We don't run the POOF algorithm on D2D interfaces. 9065 CacheRecord *ExpectedAnswers = mDNSNULL; // Records in our cache we expect to see updated 9066 CacheRecord **eap = &ExpectedAnswers; 9067 #endif // POOF_ENABLED 9068 9069 DNSQuestion *DupQuestions = mDNSNULL; // Our questions that are identical to questions in this packet 9070 DNSQuestion **dqp = &DupQuestions; 9071 mDNSs32 delayresponse = 0; 9072 mDNSBool SendLegacyResponse = mDNSfalse; 9073 const mDNSu8 *ptr; 9074 mDNSu8 *responseptr = mDNSNULL; 9075 AuthRecord *rr; 9076 TSRDataRecHead tsrs = SLIST_HEAD_INITIALIZER(tsrs); 9077 const TSROptData *curTSRForName = mDNSNULL; 9078 int i; 9079 mdns_assign(outHasResponse, mDNSfalse); 9080 9081 // *** 9082 // *** 1. Look in Additional Section for an OPT record 9083 // *** 9084 ptr = LocateOptRR(query, end, Min(DNSOpt_OwnerData_ID_Space, DNSOpt_TSRData_Space)); 9085 if (ptr) 9086 { 9087 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec); 9088 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT) 9089 { 9090 const rdataOPT *opt; 9091 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength]; 9092 mDNSu8 tsrsCount = 0; 9093 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++) 9094 { 9095 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently 9096 // delete all our own AuthRecords (which are identified by having zero MAC tags on them). 9097 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0]) 9098 { 9099 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords); 9100 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords); 9101 } 9102 else if (opt->opt == kDNSOpt_TSR) 9103 { 9104 tsrsCount++; 9105 const mDNSu8 *name_ptr; 9106 if ((name_ptr = DomainNamePtrAtTSRIndex(query, end, opt->u.tsr.recIndex))) 9107 { 9108 struct TSRDataRec *newTSR = TSRDataRecCreate(query, name_ptr, end, opt); 9109 if (!newTSR) 9110 { 9111 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 9112 "ProcessQuery: Create TSR(%u) failed - if %p tsrTime %d tsrHost %x recIndex %d", 9113 tsrsCount, m->rec.r.resrec.InterfaceID, opt->u.tsr.timeStamp, opt->u.tsr.hostkeyHash, 9114 opt->u.tsr.recIndex); 9115 continue; 9116 } 9117 SLIST_INSERT_HEAD(&tsrs, newTSR, entries); 9118 } 9119 else 9120 { 9121 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 9122 "ProcessQuery: No Domain Name for TSR(%u) if %p tsrTime %d tsrHost %x recIndex %d", 9123 tsrsCount, m->rec.r.resrec.InterfaceID, opt->u.tsr.timeStamp, opt->u.tsr.hostkeyHash, 9124 opt->u.tsr.recIndex); 9125 } 9126 } 9127 } 9128 if (!SLIST_EMPTY(&tsrs)) 9129 { 9130 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, 9131 "ProcessQuery: Received TSR(%u) if %p " PUB_S, 9132 tsrsCount, m->rec.r.resrec.InterfaceID, RRDisplayString(m, &m->rec.r.resrec)); 9133 } 9134 } 9135 mDNSCoreResetRecord(m); 9136 } 9137 9138 // *** 9139 // *** 2. Parse Question Section and mark potential answers 9140 // *** 9141 ptr = query->data; 9142 for (i=0; i<query->h.numQuestions; i++) // For each question... 9143 { 9144 mDNSBool QuestionNeedsMulticastResponse; 9145 int NumAnswersForThisQuestion = 0; 9146 AuthRecord *NSECAnswer = mDNSNULL; 9147 DNSQuestion pktq, *q; 9148 ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question... 9149 if (!ptr) goto exit; 9150 9151 // The only queries that *need* a multicast response are: 9152 // * Queries sent via multicast 9153 // * from port 5353 9154 // * that don't have the kDNSQClass_UnicastResponse bit set 9155 // These queries need multicast responses because other clients will: 9156 // * suppress their own identical questions when they see these questions, and 9157 // * expire their cache records if they don't see the expected responses 9158 // For other queries, we may still choose to send the occasional multicast response anyway, 9159 // to keep our neighbours caches warm, and for ongoing conflict detection. 9160 QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse); 9161 9162 if (pktq.qclass & kDNSQClass_UnicastResponse) 9163 m->mDNSStats.UnicastBitInQueries++; 9164 else 9165 m->mDNSStats.NormalQueries++; 9166 9167 // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later 9168 pktq.qclass &= ~kDNSQClass_UnicastResponse; 9169 9170 // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe 9171 // can result in user callbacks which may change the record list and/or question list. 9172 // Also note: we just mark potential answer records here, without trying to build the 9173 // "ResponseRecords" list, because we don't want to risk user callbacks deleting records 9174 // from that list while we're in the middle of trying to build it. 9175 if (m->CurrentRecord) 9176 LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 9177 m->CurrentRecord = m->ResourceRecords; 9178 while (m->CurrentRecord) 9179 { 9180 rr = m->CurrentRecord; 9181 m->CurrentRecord = rr->next; 9182 if (AnyTypeRecordAnswersQuestion(rr, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery)) 9183 { 9184 m->mDNSStats.MatchingAnswersForQueries++; 9185 9186 const mDNSBool typeMatches = RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype, kRRTypeAnswersQuestionTypeFlagsNone); 9187 if (typeMatches) 9188 { 9189 curTSRForName = TSRForNameFromDataRec(&tsrs, rr->resrec.name); 9190 if (rr->resrec.RecordType == kDNSRecordTypeUnique) 9191 ResolveSimultaneousProbe(m, query, end, &pktq, rr, curTSRForName); 9192 else if (ProbeHasIdenticalRR(m, query, end, &pktq, rr)) 9193 { 9194 // Don't include this rr in response if this is a probe, and it's authority section has an identical RR. 9195 continue; 9196 } 9197 else if (ProbeRRMatchAndTSRCheck(m, query, end, &pktq, rr, curTSRForName)) 9198 { 9199 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 9200 "ProcessQuery - deregistering " PRI_DM_NAME " type " PUB_S " on interface id: %p due to TSR conflict", 9201 DM_NAME_PARAM(rr->resrec.name), DNSTypeName(rr->resrec.rrtype), rr->resrec.InterfaceID); 9202 mDNS_Deregister_internal(m, rr, mDNS_Dereg_stale); 9203 continue; 9204 } 9205 else if (ResourceRecordIsValidAnswer(rr)) 9206 { 9207 NumAnswersForThisQuestion++; 9208 9209 // Note: We should check here if this is a probe-type query, and if so, generate an immediate 9210 // unicast answer back to the source, because timeliness in answering probes is important. 9211 9212 // Notes: 9213 // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast) 9214 // NR_AnswerTo == NR_AnswerUnicast means "answer via delayed unicast" (to modern querier; may promote to multicast instead) 9215 // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later) 9216 // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set, 9217 // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link) 9218 // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source) 9219 if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery)) 9220 { 9221 // We only mark this question for sending if it is at least one second since the last time we multicast it 9222 // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it. 9223 // This is to guard against the case where someone blasts us with queries as fast as they can. 9224 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)mDNSPlatformOneSecond || 9225 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID)) 9226 rr->NR_AnswerTo = NR_AnswerMulticast; 9227 } 9228 else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast; 9229 } 9230 } 9231 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr)) 9232 { 9233 // If we don't have any answers for this question, but we do own another record with the same name, 9234 // then we'll want to mark it to generate an NSEC record on this interface 9235 if (!NSECAnswer) NSECAnswer = rr; 9236 } 9237 } 9238 } 9239 9240 if (NumAnswersForThisQuestion == 0 && NSECAnswer) 9241 { 9242 NumAnswersForThisQuestion++; 9243 NSECAnswer->SendNSECNow = InterfaceID; 9244 m->NextScheduledResponse = m->timenow; 9245 } 9246 9247 // If we couldn't answer this question, someone else might be able to, 9248 // so use random delay on response to reduce collisions 9249 if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms 9250 9251 if (query->h.flags.b[0] & kDNSFlag0_TC) 9252 m->mDNSStats.KnownAnswerMultiplePkts++; 9253 // We only do the following accelerated cache expiration and duplicate question suppression processing 9254 // for non-truncated multicast queries with multicast responses. 9255 // For any query generating a unicast response we don't do this because we can't assume we will see the response. 9256 // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent 9257 // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets. 9258 if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC)) 9259 { 9260 #if POOF_ENABLED 9261 if (notD2D) 9262 { 9263 CacheGroup *cg = CacheGroupForName(m, pktq.qnamehash, &pktq.qname); 9264 CacheRecord *cr; 9265 9266 // Make a list indicating which of our own cache records we expect to see updated as a result of this query 9267 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated 9268 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 9269 { 9270 if (SameNameCacheRecordAnswersQuestion(cr, &pktq) && cr->resrec.rdlength <= SmallRecordLimit) 9271 { 9272 if (!cr->NextInKAList && eap != &cr->NextInKAList) 9273 { 9274 *eap = cr; 9275 eap = &cr->NextInKAList; 9276 } 9277 } 9278 } 9279 } 9280 #endif // POOF_ENABLED 9281 9282 // Check if this question is the same as any of mine. 9283 // We only do this for non-truncated queries. Right now it would be too complicated to try 9284 // to keep track of duplicate suppression state between multiple packets, especially when we 9285 // can't guarantee to receive all of the Known Answer packets that go with a particular query. 9286 for (q = m->Questions; q; q=q->next) 9287 { 9288 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DISCOVERY) 9289 if (QuestionSendsMDNSQueriesViaUnicast(q)) 9290 { 9291 continue; 9292 } 9293 #endif 9294 if (ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4) 9295 { 9296 if (!q->InterfaceID || q->InterfaceID == InterfaceID) 9297 { 9298 if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList) 9299 { 9300 if (q->qtype == pktq.qtype && 9301 q->qclass == pktq.qclass && 9302 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname)) 9303 { *dqp = q; dqp = &q->NextInDQList; } 9304 } 9305 } 9306 } 9307 } 9308 } 9309 } 9310 9311 // *** 9312 // *** 3. Now we can safely build the list of marked answers 9313 // *** 9314 for (rr = m->ResourceRecords; rr; rr=rr->next) // Now build our list of potential answers 9315 if (rr->NR_AnswerTo) // If we marked the record... 9316 AddRecordToResponseList(&nrp, rr, mDNSNULL); // ... add it to the list 9317 9318 // *** 9319 // *** 4. Add additional records 9320 // *** 9321 AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID); 9322 9323 // *** 9324 // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list 9325 // *** 9326 for (i=0; i<query->h.numAnswers; i++) // For each record in the query's answer section... 9327 { 9328 // Get the record... 9329 CacheRecord *ourcacherr; 9330 ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec); 9331 if (!ptr) goto exit; 9332 if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative) 9333 { 9334 // See if this Known-Answer suppresses any of our currently planned answers 9335 for (rr=ResponseRecords; rr; rr=rr->NextResponse) 9336 { 9337 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr)) 9338 { 9339 m->mDNSStats.KnownAnswerSuppressions++; 9340 rr->NR_AnswerTo = mDNSNULL; 9341 rr->NR_AdditionalTo = mDNSNULL; 9342 } 9343 } 9344 9345 // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression) 9346 for (rr=m->ResourceRecords; rr; rr=rr->next) 9347 { 9348 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression 9349 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr)) 9350 { 9351 if (srcaddr->type == mDNSAddrType_IPv4) 9352 { 9353 if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr; 9354 } 9355 else if (srcaddr->type == mDNSAddrType_IPv6) 9356 { 9357 if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr; 9358 } 9359 if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester)) 9360 { 9361 m->mDNSStats.KnownAnswerSuppressions++; 9362 rr->ImmedAnswer = mDNSNULL; 9363 rr->ImmedUnicast = mDNSfalse; 9364 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES 9365 LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr)); 9366 #endif 9367 } 9368 } 9369 } 9370 9371 ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec); 9372 9373 #if POOF_ENABLED 9374 if (notD2D) 9375 { 9376 // Having built our ExpectedAnswers list from the questions in this packet, we then remove 9377 // any records that are suppressed by the Known Answer list in this packet. 9378 eap = &ExpectedAnswers; 9379 while (*eap) 9380 { 9381 CacheRecord *cr = *eap; 9382 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec)) 9383 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; } 9384 else eap = &cr->NextInKAList; 9385 } 9386 } 9387 #endif // POOF_ENABLED 9388 9389 // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query. 9390 if (!ourcacherr) 9391 { 9392 dqp = &DupQuestions; 9393 while (*dqp) 9394 { 9395 DNSQuestion *q = *dqp; 9396 if (CacheRecordAnswersQuestion(&m->rec.r, q)) 9397 { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; } 9398 else dqp = &q->NextInDQList; 9399 } 9400 } 9401 } 9402 mDNSCoreResetRecord(m); 9403 } 9404 9405 // *** 9406 // *** 6. Cancel any additionals that were added because of now-deleted records 9407 // *** 9408 for (rr=ResponseRecords; rr; rr=rr->NextResponse) 9409 if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo)) 9410 { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; } 9411 9412 // *** 9413 // *** 7. Mark the send flags on the records we plan to send 9414 // *** 9415 for (rr=ResponseRecords; rr; rr=rr->NextResponse) 9416 { 9417 if (rr->NR_AnswerTo) 9418 { 9419 mDNSBool SendMulticastResponse = mDNSfalse; // Send modern multicast response 9420 mDNSBool SendUnicastResponse = mDNSfalse; // Send modern unicast response (not legacy unicast response) 9421 9422 // If it's been one TTL/4 since we multicast this, then send a multicast response 9423 // for conflict detection, etc. 9424 if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)TicksTTL(rr)/4 9425 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 9426 && QueryWasMulticast 9427 #endif 9428 ) 9429 { 9430 SendMulticastResponse = mDNStrue; 9431 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to 9432 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below). 9433 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value. 9434 if (rr->NR_AnswerTo == NR_AnswerUnicast) 9435 { 9436 m->mDNSStats.UnicastDemotedToMulticast++; 9437 rr->NR_AnswerTo = NR_AnswerMulticast; 9438 } 9439 } 9440 9441 // If the client insists on a multicast response, then we'd better send one 9442 if (rr->NR_AnswerTo == NR_AnswerMulticast) 9443 { 9444 m->mDNSStats.MulticastResponses++; 9445 SendMulticastResponse = mDNStrue; 9446 } 9447 else if (rr->NR_AnswerTo == NR_AnswerUnicast) 9448 { 9449 m->mDNSStats.UnicastResponses++; 9450 SendUnicastResponse = mDNStrue; 9451 } 9452 else if (rr->NR_AnswerTo) 9453 { 9454 SendLegacyResponse = mDNStrue; 9455 } 9456 9457 if (SendMulticastResponse || SendUnicastResponse) 9458 { 9459 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES 9460 rr->ImmedAnswerMarkTime = m->timenow; 9461 #endif 9462 m->NextScheduledResponse = m->timenow; 9463 // If we're already planning to send this on another interface, just send it on all interfaces 9464 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID) 9465 rr->ImmedAnswer = mDNSInterfaceMark; 9466 else 9467 { 9468 rr->ImmedAnswer = InterfaceID; // Record interface to send it on 9469 if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue; 9470 if (srcaddr->type == mDNSAddrType_IPv4) 9471 { 9472 if (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4; 9473 else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr; 9474 } 9475 else if (srcaddr->type == mDNSAddrType_IPv6) 9476 { 9477 if (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6; 9478 else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr; 9479 } 9480 } 9481 // We have responses for this query. 9482 mdns_assign(outHasResponse, mDNStrue); 9483 } 9484 // If TC flag is set, it means we should expect that additional known answers may be coming in another packet, 9485 // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11) 9486 // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses 9487 // else, for a simple unique record reply, we can reply immediately; no need for delay 9488 if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20; // Divided by 50 = 400ms 9489 else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond; // Divided by 50 = 20ms 9490 } 9491 else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast) 9492 { 9493 // Since additional records are an optimization anyway, we only ever send them on one interface at a time 9494 // If two clients on different interfaces do queries that invoke the same optional additional answer, 9495 // then the earlier client is out of luck 9496 rr->ImmedAdditional = InterfaceID; 9497 // No need to set m->NextScheduledResponse here 9498 // We'll send these additional records when we send them, or not, as the case may be 9499 } 9500 } 9501 9502 // *** 9503 // *** 8. If we think other machines are likely to answer these questions, set our response suppression timer, 9504 // *** unless we're shutting down. While shutting down, we don't want to delay goodbyes for our auth records. 9505 // *** 9506 if (delayresponse && !m->ShutdownTime && (!m->SuppressResponses || ((m->SuppressResponses - m->timenow) < ((delayresponse + 49) / 50)))) 9507 { 9508 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES 9509 const mDNSBool alreadySuppressing = (m->SuppressResponses != 0); 9510 if (alreadySuppressing) 9511 { 9512 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 9513 "Current SuppressResponses delay %5d; require %5d", m->SuppressResponses - m->timenow, (delayresponse + 49) / 50); 9514 } 9515 #endif 9516 // Pick a random delay: 9517 // We start with the base delay chosen above (typically either 1 second or 20 seconds), 9518 // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds). 9519 // This is an integer value, with resolution determined by the platform clock rate. 9520 // We then divide that by 50 to get the delay value in ticks. We defer the division until last 9521 // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second). 9522 // The +49 before dividing is to ensure we round up, not down, to ensure that even 9523 // on platforms where the native clock rate is less than fifty ticks per second, 9524 // we still guarantee that the final calculated delay is at least one platform tick. 9525 // We want to make sure we don't ever allow the delay to be zero ticks, 9526 // because if that happens we'll fail the Bonjour Conformance Test. 9527 // Our final computed delay is 20-120ms for normal delayed replies, 9528 // or 400-500ms in the case of multi-packet known-answer lists. 9529 m->SuppressResponses = NonZeroTime(m->timenow + ((delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond * 5) + 49) / 50)); 9530 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES 9531 if (alreadySuppressing) 9532 { 9533 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 9534 "Set SuppressResponses to %d", m->SuppressResponses - m->timenow); 9535 } 9536 #endif 9537 } 9538 9539 // *** 9540 // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too 9541 // *** 9542 if (SendLegacyResponse) 9543 responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords); 9544 9545 exit: 9546 mDNSCoreResetRecord(m); 9547 9548 // *** 9549 // *** 10. Finally, clear our link chains ready for use next time 9550 // *** 9551 while (ResponseRecords) 9552 { 9553 rr = ResponseRecords; 9554 ResponseRecords = rr->NextResponse; 9555 rr->NextResponse = mDNSNULL; 9556 rr->NR_AnswerTo = mDNSNULL; 9557 rr->NR_AdditionalTo = mDNSNULL; 9558 } 9559 9560 #if POOF_ENABLED 9561 while (ExpectedAnswers && notD2D) 9562 { 9563 CacheRecord *cr = ExpectedAnswers; 9564 ExpectedAnswers = cr->NextInKAList; 9565 cr->NextInKAList = mDNSNULL; 9566 9567 // For non-truncated queries, we can definitively say that we should expect 9568 // to be seeing a response for any records still left in the ExpectedAnswers list 9569 if (!(query->h.flags.b[0] & kDNSFlag0_TC)) 9570 if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond * 3/4) 9571 { 9572 cr->UnansweredQueries++; 9573 cr->LastUnansweredTime = m->timenow; 9574 if (cr->UnansweredQueries > 1) 9575 debugf("ProcessQuery: UnansweredQueries %lu %s", cr->UnansweredQueries, CRDisplayString(m, cr)); 9576 SetNextCacheCheckTimeForRecord(m, cr); 9577 } 9578 9579 // If we've seen multiple unanswered queries for this record, 9580 // then mark it to expire in five seconds if we don't get a response by then. 9581 if (cr->UnansweredQueries >= MaxUnansweredQueries) 9582 { 9583 // Only show debugging message if this record was not about to expire anyway 9584 if (RRExpireTime(cr) - m->timenow > (mDNSs32) kDefaultReconfirmTimeForNoAnswer * 4 / 3 + mDNSPlatformOneSecond) 9585 LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s", 9586 cr->UnansweredQueries, InterfaceID, (RRExpireTime(cr) - m->timenow + mDNSPlatformOneSecond-1) / mDNSPlatformOneSecond, CRDisplayString(m, cr)); 9587 9588 m->mDNSStats.PoofCacheDeletions++; 9589 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); 9590 } 9591 } 9592 #endif // POOF_ENABLED 9593 9594 while (DupQuestions) 9595 { 9596 DNSQuestion *q = DupQuestions; 9597 DupQuestions = q->NextInDQList; 9598 q->NextInDQList = mDNSNULL; 9599 RecordDupSuppressInfo(q, m->timenow, InterfaceID, srcaddr->type); 9600 debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID, 9601 srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6"); 9602 } 9603 TSRDataRecHeadFreeList(&tsrs); 9604 return(responseptr); 9605 } 9606 9607 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end, 9608 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport, 9609 const mDNSInterfaceID InterfaceID) 9610 { 9611 mDNSu8 *responseend = mDNSNULL; 9612 mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr && 9613 !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr); 9614 9615 if (!dstaddr || (!InterfaceID && mDNSAddrIsDNSMulticast(dstaddr))) 9616 { 9617 const char *const reason = !dstaddr ? "Received over TCP connection" : "Multicast, but no InterfaceID"; 9618 LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with " 9619 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)", 9620 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID, 9621 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,", 9622 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,", 9623 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,", 9624 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data, reason); 9625 return; 9626 } 9627 9628 verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with " 9629 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes", 9630 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID, 9631 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,", 9632 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,", 9633 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,", 9634 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data); 9635 9636 mDNSBool hasResponse = mDNSfalse; 9637 responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID, 9638 !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg, 9639 &hasResponse); 9640 9641 if (hasResponse) 9642 { 9643 DumpPacket(mStatus_NoError, mDNSfalse, "N/A", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID); 9644 } 9645 9646 if (responseend) // If responseend is non-null, that means we built a unicast response packet 9647 { 9648 debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld", 9649 m->omsg.h.numQuestions, m->omsg.h.numQuestions == 1 ? "" : "s", 9650 m->omsg.h.numAnswers, m->omsg.h.numAnswers == 1 ? "" : "s", 9651 m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", 9652 srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type); 9653 mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSfalse); 9654 } 9655 } 9656 9657 #if 0 9658 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr) 9659 { 9660 DNSServer *s; 9661 (void)m; // Unused 9662 (void)srcaddr; // Unused 9663 for (s = m->DNSServers; s; s = s->next) 9664 if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue); 9665 return(mDNSfalse); 9666 } 9667 #endif 9668 9669 struct UDPSocket_struct 9670 { 9671 mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port 9672 }; 9673 9674 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, 9675 const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp) 9676 { 9677 DNSQuestion *q; 9678 for (q = m->Questions; q; q=q->next) 9679 { 9680 if (!tcp && !q->LocalSocket) continue; 9681 if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port) && 9682 q->qtype == question->qtype && 9683 q->qclass == question->qclass && 9684 q->qnamehash == question->qnamehash && 9685 SameDomainName(&q->qname, &question->qname)) 9686 { 9687 if (mDNSSameOpaque16(q->TargetQID, id)) return(q); 9688 else 9689 { 9690 return(mDNSNULL); 9691 } 9692 } 9693 } 9694 return(mDNSNULL); 9695 } 9696 9697 // This function is called when we receive a unicast response. This could be the case of a unicast response from the 9698 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case) 9699 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m, 9700 const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp) 9701 { 9702 DNSQuestion *q; 9703 (void)id; 9704 9705 for (q = m->Questions; q; q=q->next) 9706 { 9707 if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q)) 9708 { 9709 if (!mDNSOpaque16IsZero(q->TargetQID)) 9710 { 9711 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr)); 9712 9713 if (mDNSSameOpaque16(q->TargetQID, id)) 9714 { 9715 mDNSIPPort srcp; 9716 if (!tcp) 9717 { 9718 srcp = q->LocalSocket ? q->LocalSocket->port : zeroIPPort; 9719 } 9720 else 9721 { 9722 srcp = q->tcpSrcPort; 9723 } 9724 if (mDNSSameIPPort(srcp, port)) return(q); 9725 9726 // if (mDNSSameAddress(srcaddr, &q->Target)) return(mDNStrue); 9727 // if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking 9728 // if (TrustedSource(m, srcaddr)) return(mDNStrue); 9729 LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) from %#a:%d %s", 9730 q->qname.c, DNSTypeName(q->qtype), srcaddr, mDNSVal16(port), CRDisplayString(m, rr)); 9731 return(mDNSNULL); 9732 } 9733 } 9734 else 9735 { 9736 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2)) 9737 return(q); 9738 } 9739 } 9740 } 9741 return(mDNSNULL); 9742 } 9743 9744 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply 9745 // Currently this applies only to rdata types containing more than one domainname, 9746 // or types where the domainname is not the last item in the structure. 9747 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr) 9748 { 9749 switch (rr->rrtype) 9750 { 9751 case kDNSType_SOA: return sizeof(rdataSOA); 9752 case kDNSType_RP: return sizeof(rdataRP); 9753 case kDNSType_PX: return sizeof(rdataPX); 9754 default: return rr->rdlength; 9755 } 9756 } 9757 9758 mDNSlocal void AddCacheRecordToCacheGroup(CacheGroup *const cg, CacheRecord *const cr) 9759 { 9760 9761 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 9762 if (resource_record_is_to_be_dnssec_validated(&cr->resrec)) 9763 { 9764 // Insert the newly created cache record before the DNSSEC-aware CNAME records. 9765 // This operation ensures that mDNSResponder will deliver all the records including RRSIG or denial of 9766 // existence record before delivering CNAME and following it. 9767 CacheRecord *node = mDNSNULL; 9768 CacheRecord **ptr = &cg->members; 9769 while ((node = *ptr) != mDNSNULL) 9770 { 9771 // Only search for CNAME record that is marked as DNSSEC aware. 9772 if (node->resrec.rrtype == kDNSType_CNAME && resource_record_is_to_be_dnssec_validated(&node->resrec)) 9773 { 9774 break; 9775 } 9776 ptr = &node->next; 9777 } 9778 9779 // Insert the new record. 9780 cr->next = *ptr; 9781 *ptr = cr; 9782 9783 // Update the tail pointer. 9784 if (ptr == cg->rrcache_tail) 9785 { 9786 cg->rrcache_tail = &(cr->next); 9787 } 9788 } 9789 else 9790 #endif 9791 { 9792 *(cg->rrcache_tail) = cr; // Append this record to tail of cache slot list 9793 cg->rrcache_tail = &(cr->next); // Advance tail pointer 9794 } 9795 } 9796 9797 mDNSlocal void AddOrUpdateTSRForCacheGroup(mDNS *const m, const TSROptData *curTSROpt, CacheGroup *const cg, 9798 CacheRecord *ourTsr, mDNSu32 ttl) 9799 { 9800 mDNSs32 timestampContinuous; 9801 mDNSBool new = mDNSfalse; 9802 if (!getValidContinousTSRTime(×tampContinuous, curTSROpt->timeStamp)) 9803 { 9804 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 9805 "AddOrUpdateTSRForCacheGroup: tsrTimestamp[%u] out of range (%u) on TSR for " PRI_DM_NAME "", 9806 curTSROpt->timeStamp, MaxTimeSinceReceived, DM_NAME_PARAM(cg->name)); 9807 return; 9808 } 9809 9810 if (!ourTsr) 9811 { 9812 ourTsr = GetCacheRecord(m, cg, DNSOpt_TSRData_Space); 9813 if (!ourTsr) 9814 { 9815 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_ERROR, 9816 "AddOrUpdateTSRForCacheGroup: No cache record for new TSR " PRI_DM_NAME, DM_NAME_PARAM(cg->name)); 9817 return; 9818 } 9819 ourTsr->resrec.rrclass = NormalMaxDNSMessageData; 9820 ourTsr->resrec.rrtype = kDNSType_OPT; 9821 ourTsr->resrec.name = cg->name; 9822 ourTsr->resrec.namehash = cg->namehash; 9823 ourTsr->resrec.rdlength = DNSOpt_TSRData_Space; 9824 ourTsr->resrec.rdestimate = DNSOpt_TSRData_Space; 9825 AddCacheRecordToCacheGroup(cg, ourTsr); 9826 new = mDNStrue; 9827 } 9828 ourTsr->TimeRcvd = m->timenow; 9829 ourTsr->resrec.rroriginalttl = Max(ourTsr->resrec.rroriginalttl, ttl); 9830 9831 rdataOPT * const rdata = &ourTsr->resrec.rdata->u.opt[0]; 9832 if (new || timestampContinuous - rdata->u.tsr.timeStamp > 0) // Always enter if new 9833 { 9834 rdata->opt = kDNSOpt_TSR; 9835 rdata->optlen = DNSOpt_TSRData_Space - 4; 9836 rdata->u.tsr.timeStamp = timestampContinuous; 9837 rdata->u.tsr.hostkeyHash = curTSROpt->hostkeyHash; 9838 rdata->u.tsr.recIndex = 0; 9839 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, 9840 "AddOrUpdateTSRForCacheGroup: %s TSR " PRI_S, new ? "Added" : "Updated", CRDisplayString(m, ourTsr)); 9841 } 9842 } 9843 9844 mDNSexport CacheRecord * CreateNewCacheEntryEx(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, const mDNSs32 delay, 9845 const mDNSBool add, const mDNSAddr *const sourceAddress, const CreateNewCacheEntryFlags flags) 9846 { 9847 CacheRecord *rr = mDNSNULL; 9848 mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec); 9849 9850 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 9851 const mDNSBool toBeDNSSECValidated = ((flags & kCreateNewCacheEntryFlagsDNSSECRRToValidate) != 0); 9852 const mDNSBool dnssecValidated = ((flags & kCreateNewCacheEntryFlagsDNSSECRRValidatedSecure) != 0) 9853 || ((flags & kCreateNewCacheEntryFlagsDNSSECRRValidatedInsecure) != 0); 9854 dnssec_result_t validation_result = dnssec_indeterminate; 9855 if (dnssecValidated) 9856 { 9857 if ((flags & kCreateNewCacheEntryFlagsDNSSECRRValidatedSecure) != 0) 9858 { 9859 validation_result = dnssec_secure; 9860 } else if ((flags & kCreateNewCacheEntryFlagsDNSSECRRValidatedInsecure) != 0) 9861 { 9862 validation_result = dnssec_insecure; 9863 } 9864 } 9865 if (toBeDNSSECValidated && dnssecValidated) 9866 { 9867 return mDNSNULL; 9868 } 9869 #endif 9870 9871 if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r)); 9872 9873 //if (RDLength > InlineCacheRDSize) 9874 // LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r)); 9875 9876 if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now 9877 if (cg) rr = GetCacheRecord(m, cg, RDLength); // Make a cache record, being careful not to recycle cg 9878 if (!rr) NoCacheAnswer(m, &m->rec.r); 9879 else 9880 { 9881 RData *saveptr = rr->resrec.rdata; // Save the rr->resrec.rdata pointer 9882 *rr = m->rec.r; // Block copy the CacheRecord object 9883 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 9884 mdns_retain_null_safe(rr->resrec.metadata); 9885 #endif 9886 rr->resrec.rdata = saveptr; // Restore rr->resrec.rdata after the structure assignment 9887 rr->resrec.name = cg->name; // And set rr->resrec.name to point into our CacheGroup header 9888 rr->resrec.mortality = Mortality_Mortal; 9889 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 9890 dnssec_error_t err = DNSSEC_ERROR_NO_ERROR; 9891 if (toBeDNSSECValidated) 9892 { 9893 rr->resrec.dnssec = dnssec_obj_resource_record_member_create_to_validate(rr->resrec.RecordType != kDNSRecordTypePacketNegative, rr, &err); 9894 } 9895 else if (dnssecValidated) 9896 { 9897 if (validation_result != dnssec_insecure && validation_result != dnssec_secure) 9898 { 9899 return mDNSNULL; 9900 } 9901 const mDNSBool insecure_validation_usable = ((flags & kCreateNewCacheEntryFlagsDNSSECInsecureValidationUsable) != 0); 9902 rr->resrec.dnssec = dnssec_obj_resource_record_member_create_validated(rr, validation_result, insecure_validation_usable, &err); 9903 } 9904 if (err != DNSSEC_ERROR_NO_ERROR) 9905 { 9906 return mDNSNULL; 9907 } 9908 #endif 9909 9910 rr->DelayDelivery = delay; 9911 9912 // If this is an oversized record with external storage allocated, copy rdata to external storage 9913 if (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize) 9914 LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c); 9915 else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize) 9916 LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c); 9917 if (RDLength > InlineCacheRDSize) 9918 mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength); 9919 9920 rr->next = mDNSNULL; // Clear 'next' pointer 9921 rr->soa = mDNSNULL; 9922 9923 if (sourceAddress) 9924 rr->sourceAddress = *sourceAddress; 9925 9926 if (!rr->resrec.InterfaceID) 9927 { 9928 m->rrcache_totalused_unicast += rr->resrec.rdlength; 9929 } 9930 9931 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) || MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 9932 if (flags & kCreateNewCacheEntryFlagsDNSPushSubscribed) 9933 { 9934 rr->DNSPushSubscribed = mDNStrue; 9935 } 9936 #else 9937 (void)flags; 9938 #endif 9939 9940 #if MDNSRESPONDER_SUPPORTS(APPLE, LOG_PRIVACY_LEVEL) 9941 rr->PrivacyLevel = mDNSCRLogPrivacyLevel_Default; 9942 #endif 9943 9944 if (add) 9945 { 9946 AddCacheRecordToCacheGroup(cg, rr); 9947 CacheRecordAdd(m, rr); // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us 9948 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 9949 if (mDNSAddressIsValidNonZero(&rr->sourceAddress) && 9950 !mDNSAddrIsDNSMulticast(&rr->sourceAddress) && 9951 mDNS_AddressIsLocalSubnet(m, rr->resrec.InterfaceID, &rr->sourceAddress)) 9952 { 9953 unicast_assist_addr_add(rr->resrec.name, rr->resrec.namehash, rr->resrec.rrtype, rr->resrec.RecordType, 9954 &rr->sourceAddress, rr->resrec.InterfaceID); 9955 } 9956 #endif 9957 } 9958 else 9959 { 9960 // Can't use the "cg->name" if we are not adding to the cache as the 9961 // CacheGroup may be released anytime if it is empty 9962 domainname *name = (domainname *) mDNSPlatformMemAllocate(DomainNameLength(cg->name)); 9963 if (name) 9964 { 9965 AssignDomainName(name, cg->name); 9966 rr->resrec.name = name; 9967 } 9968 else 9969 { 9970 ReleaseCacheRecord(m, rr); 9971 NoCacheAnswer(m, &m->rec.r); 9972 rr = mDNSNULL; 9973 } 9974 } 9975 } 9976 return(rr); 9977 } 9978 9979 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, const mDNSs32 delay, 9980 const mDNSBool add, const mDNSAddr *const sourceAddress) 9981 { 9982 return CreateNewCacheEntryEx(m, slot, cg, delay, add, sourceAddress, kCreateNewCacheEntryFlagsNone); 9983 } 9984 9985 mDNSlocal void RefreshCacheRecordCacheGroupOrder(CacheGroup *cg, CacheRecord *cr) 9986 { // Move the cache record to the tail of the cache group to maintain a fresh ordering 9987 if (cg->rrcache_tail != &cr->next) // If not already at the tail 9988 { 9989 CacheRecord **rp; 9990 for (rp = &cg->members; *rp; rp = &(*rp)->next) 9991 { 9992 if (*rp == cr) // This item points to this record 9993 { 9994 *rp = cr->next; // Remove this record 9995 break; 9996 } 9997 } 9998 cr->next = mDNSNULL; // This record is now last 9999 AddCacheRecordToCacheGroup(cg, cr); 10000 } 10001 } 10002 10003 mDNSexport void RefreshCacheRecord(mDNS *const m, CacheRecord *const rr, const mDNSu32 ttl) 10004 { 10005 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 10006 if (rr->CRActiveQuestion && mDNSOpaque16IsZero(rr->CRActiveQuestion->TargetQID)) 10007 { 10008 const mDNSBool sourceAddrValidNonZero = mDNSAddressIsValidNonZero(&rr->sourceAddress); 10009 const mDNSBool sourceAddrIsDNSMulticast = mDNSAddrIsDNSMulticast(&rr->sourceAddress); 10010 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST_ANALYTICS) 10011 if (rr->LastUnansweredTime != 0 && 10012 sourceAddrValidNonZero) 10013 { 10014 const bool is_assist = (rr->unicastAssistSent != mDNSfalse); 10015 const bool is_unicast = (rr->UnansweredQueries == 0 && !sourceAddrIsDNSMulticast); 10016 dnssd_analytics_update_unicast_assist(is_assist, is_unicast); 10017 } 10018 #endif 10019 if (sourceAddrValidNonZero && 10020 !sourceAddrIsDNSMulticast && 10021 mDNS_AddressIsLocalSubnet(m, rr->resrec.InterfaceID, &rr->sourceAddress)) 10022 { 10023 unicast_assist_addr_refresh(rr->resrec.name, rr->resrec.namehash, rr->resrec.rrtype, rr->resrec.RecordType, 10024 &rr->sourceAddress, rr->resrec.InterfaceID); 10025 } 10026 rr->unicastAssistSent = mDNSfalse; 10027 } 10028 #endif 10029 rr->TimeRcvd = m->timenow; 10030 rr->resrec.rroriginalttl = ttl; 10031 rr->UnansweredQueries = 0; 10032 if (rr->resrec.mortality != Mortality_Mortal) rr->resrec.mortality = Mortality_Immortal; 10033 10034 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) && \ 10035 (MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) || MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH)) 10036 const mdns_dns_service_t newService = mdns_cache_metadata_get_dns_service(m->rec.r.resrec.metadata); 10037 const mdns_dns_service_t oldService = mdns_cache_metadata_get_dns_service(rr->resrec.metadata); 10038 const mDNSBool newRecordComesFromPushService = (newService && 10039 (mdns_dns_service_get_type(newService) == mdns_dns_service_type_push)); 10040 if (newRecordComesFromPushService && (newService == oldService)) 10041 { 10042 // A cached record that has been unsubscribed and that comes from the same DNS push service is being refreshed 10043 // by the same subscription response, so we just need to resubscribe it. 10044 mdns_cache_metadata_set_subscriber_id(rr->resrec.metadata, 10045 mdns_cache_metadata_get_subscriber_id(m->rec.r.resrec.metadata)); 10046 rr->DNSPushSubscribed = mDNStrue; 10047 } 10048 #endif 10049 10050 SetNextCacheCheckTimeForRecord(m, rr); 10051 } 10052 10053 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease) 10054 { 10055 CacheRecord *rr; 10056 CacheGroup *cg = CacheGroupForName(m, q->qnamehash, &q->qname); 10057 for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next) 10058 if (rr->CRActiveQuestion == q) 10059 { 10060 //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr)); 10061 RefreshCacheRecord(m, rr, lease); 10062 } 10063 } 10064 10065 // When the response does not match the question directly, we still want to cache them sometimes. The current response is 10066 // in m->rec. 10067 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist) 10068 { 10069 const CacheRecord *const newcr = &m->rec.r; 10070 const ResourceRecord *rr = &newcr->resrec; 10071 const CacheRecord *cr; 10072 10073 for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList) 10074 { 10075 domainname *target = GetRRDomainNameTarget(&cr->resrec); 10076 // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would 10077 // match the question and we already created a cache entry in the previous pass of this loop. Now when we process 10078 // the A record, it does not match the question because the record name here is the CNAME. Hence we try to 10079 // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the 10080 // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also. 10081 10082 if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name)) 10083 { 10084 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Found a matching entry in the CacheFlushRecords - " 10085 "new rrtype: " PRI_S ", matched name: " PRI_DM_NAME ", description: " PRI_S, DNSTypeName(rr->rrtype), 10086 DM_NAME_PARAM(rr->name), CRDisplayString(m, cr)); 10087 return (mDNStrue); 10088 } 10089 } 10090 return mDNSfalse; 10091 } 10092 10093 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10094 10095 #define MAX_CNAME_TRAVERSAL 11 // We follow at most 10 CNAMEs in a CNAME chain. 10096 10097 mDNSlocal void 10098 ParseCNameChainFromMessage( 10099 const DNSMessage *const response, 10100 const mDNSu8 *const limit, 10101 const mDNSInterfaceID InterfaceID, 10102 const domainname *const qname, 10103 domainname cnameChain[static const MAX_CNAME_TRAVERSAL], 10104 mDNSu32 *const outChainLen) 10105 { 10106 if (response == mDNSNULL || limit == mDNSNULL || qname == mDNSNULL || cnameChain == mDNSNULL || outChainLen == mDNSNULL) 10107 { 10108 return; 10109 } 10110 10111 AssignDomainName(&cnameChain[0], qname); 10112 *outChainLen = 1; 10113 10114 const mDNSu16 answerCount = response->h.numAnswers; 10115 if (answerCount == 0) 10116 { 10117 return; 10118 } 10119 10120 const mDNSu8 *ptr = LocateAnswers(response, limit); 10121 if (ptr == mDNSNULL) 10122 { 10123 return; 10124 } 10125 10126 // Parse all CNAMEs in the answer section. 10127 #define MAX_CNAME_TO_PARSE ((MAX_CNAME_TRAVERSAL) * 2) 10128 // Index 0 is the original owner name, Index 1 is the CNAME. 10129 domainname cnames[MAX_CNAME_TO_PARSE][2]; 10130 mDNSu16 cnameCount = 0; 10131 mDNS *const m = &mDNSStorage; 10132 10133 for (mDNSu32 i = 0; i < answerCount && ptr < limit && cnameCount < countof(cnames); mDNSCoreResetRecord(m), i++) 10134 { 10135 ptr = GetLargeResourceRecord(m, response, ptr, limit, InterfaceID, kDNSRecordTypePacketAuth, &m->rec); 10136 const ResourceRecord *const rr = &(m->rec.r.resrec); 10137 if (rr->RecordType == kDNSRecordTypePacketNegative) 10138 { 10139 continue; 10140 } 10141 10142 if (rr->rrtype != kDNSType_CNAME) 10143 { 10144 continue; 10145 } 10146 10147 // A CNAME cannot be placed at the root domain level. 10148 if (IsRootDomain(rr->name)) 10149 { 10150 continue; 10151 } 10152 10153 // Found a CNAME. 10154 if (SameDomainName(rr->name, &rr->rdata->u.name)) 10155 { 10156 continue; 10157 } 10158 10159 // Save the CNAME. 10160 AssignDomainName(&(cnames[cnameCount][0]), rr->name); 10161 AssignDomainName(&(cnames[cnameCount][1]), &rr->rdata->u.name); 10162 cnameCount++; 10163 } 10164 10165 // With the CNAME obtained above, construct a CNAME chain. 10166 // The CNAME chain always starts with the original question name. 10167 const domainname *nameToSearch = qname; 10168 10169 // *outChainLen != MAX_CNAME_TRAVERSAL: Do not follow more than 10 CNAMEs. 10170 // *outChainLen <= cnameCount If all CNAMEs parsed above has been used to form a chain, the chain length would be 10171 // cnameCount. When *outChainLen == cnameCount + 1, there is not point to continue the search. 10172 while (*outChainLen != MAX_CNAME_TRAVERSAL && *outChainLen <= cnameCount) 10173 { 10174 const domainname *nextCName = mDNSNULL; 10175 10176 for (mDNSu32 i = 0; i < cnameCount; i++) 10177 { 10178 // IsRootDomain(&cnames[i][0]): Since root domain cannot have CNAME, here root domain is used to mark 10179 // an already traversed CNAME. If a CNAME has been traversed before, skip it to avoid circular dependence. 10180 if (IsRootDomain(&cnames[i][0]) || !SameDomainName(nameToSearch, &cnames[i][0])) 10181 { 10182 continue; 10183 } 10184 10185 // We found the next name in the chain. 10186 nextCName = &cnames[i][1]; 10187 10188 // Mark the current CNAME as already traversed. 10189 const domainname *const rootDomain = (const domainname *)"\x0"; 10190 AssignDomainName(&cnames[i][0], rootDomain); 10191 break; 10192 } 10193 10194 // If we did not find the next name in the chain, it means we have reached the end. 10195 if (nextCName == mDNSNULL) 10196 { 10197 break; 10198 } 10199 10200 // Place the name into the CNAME chain. 10201 nameToSearch = nextCName; 10202 AssignDomainName(&cnameChain[*outChainLen], nameToSearch); 10203 *outChainLen += 1; 10204 } 10205 } 10206 10207 // A normal denial of existence response should have no more than 3 NSEC/NSEC3 records. Here we use 10 to allow more to 10208 // be able to processed and discarded. 10209 #define MAX_NUM_NSEC_NSEC3_TO_PROCESS 10 10210 // Here we assume that the total number of RRSIG records contained in a response should be no more than 30 (large enough). 10211 #define MAX_NUM_RRSIG_TO_PROCESS 30 10212 10213 #define mDNSInvalidUnicastTTLSeconds (mDNSMaximumUnicastTTLSeconds + 1) 10214 10215 // Parse SOA, NSEC/NSEC3, RRSIG records contained in the DNS message to DNSSEC objects. 10216 mDNSlocal mDNSu32 10217 ParseDenialOfExistenceObjsFromMessage( 10218 const DNSMessage *const response, 10219 const mDNSu8 *const limit, 10220 const mDNSInterfaceID InterfaceID, 10221 dnssec_obj_rr_soa_t *const outObjSOA, 10222 dnssec_obj_rr_rrsig_t objSOARRSIG[static const MAX_NUM_RRSIG_TO_PROCESS], 10223 mDNSu8 *const outSOARRSIGCount, 10224 dnssec_obj_rr_nsec_t outObjNSECs[static const MAX_NUM_NSEC_NSEC3_TO_PROCESS], 10225 mDNSu8 *const outNSECCount, 10226 dnssec_obj_rr_nsec3_t outObjNSEC3s[static const MAX_NUM_NSEC_NSEC3_TO_PROCESS], 10227 mDNSu8 *const outNSEC3Count, 10228 dnssec_obj_rr_rrsig_t outObjRRSIGs[static const MAX_NUM_RRSIG_TO_PROCESS], 10229 mDNSu8 *const outRRSIGCount) 10230 { 10231 dnssec_error_t err; 10232 mDNSu32 negativeTTL = mDNSInvalidUnicastTTLSeconds; 10233 10234 // To parse the authority section, the output pointers should be non-null, in order to get a valid denial of 10235 // existence response set. 10236 if (outObjSOA == mDNSNULL || objSOARRSIG == mDNSNULL || outSOARRSIGCount == mDNSNULL || 10237 outObjNSECs == mDNSNULL || outNSECCount == mDNSNULL || outObjNSEC3s == mDNSNULL || outNSEC3Count == mDNSNULL || 10238 outObjRRSIGs == mDNSNULL || outRRSIGCount == mDNSNULL) 10239 { 10240 goto exit; 10241 } 10242 10243 *outObjSOA = mDNSNULL; 10244 *outSOARRSIGCount = 0; 10245 *outNSECCount = 0; 10246 *outNSEC3Count = 0; 10247 *outRRSIGCount = 0; 10248 10249 // All SOA, NSEC/NSEC3, RRSIG records are in the authority section. 10250 const mDNSu16 authorityCount = response->h.numAuthorities; 10251 if (authorityCount == 0) 10252 { 10253 goto exit; 10254 } 10255 10256 // Go to the authority section. 10257 const mDNSu8 *ptr = LocateAuthorities(response, limit); 10258 if (ptr == mDNSNULL) 10259 { 10260 goto exit; 10261 } 10262 10263 mDNS *const m = &mDNSStorage; 10264 // For each DNS record contained in the authority section. 10265 for (mDNSu32 i = 0; i < authorityCount && ptr < limit; mDNSCoreResetRecord(m), i++) 10266 { 10267 // Get the record from the DNS message. 10268 ptr = GetLargeResourceRecord(m, response, ptr, limit, InterfaceID, kDNSRecordTypePacketAuth, &m->rec); 10269 const ResourceRecord *const rr = &(m->rec.r.resrec); 10270 if (rr->RecordType == kDNSRecordTypePacketNegative) 10271 { 10272 continue; 10273 } 10274 10275 if (negativeTTL == mDNSInvalidUnicastTTLSeconds) 10276 { 10277 // If the denial of existence record's TTL is equal to mDNSInvalidUnicastTTLSeconds, then we choose 10278 // mDNSMaximumUnicastTTLSeconds (which is mDNSInvalidUnicastTTLSeconds minus one). 10279 negativeTTL = (m->rec.r.resrec.rroriginalttl != mDNSInvalidUnicastTTLSeconds) ? m->rec.r.resrec.rroriginalttl : mDNSMaximumUnicastTTLSeconds; 10280 } 10281 else 10282 { 10283 negativeTTL = MIN(negativeTTL, m->rec.r.resrec.rroriginalttl); 10284 } 10285 10286 if (rr->rrtype == kDNSType_SOA) 10287 { 10288 if (*outObjSOA != mDNSNULL) 10289 { 10290 // Should only have one SOA. 10291 continue; 10292 } 10293 10294 // Cautious! 10295 // SOA has compression pointers, GetLargeResourceRecord() expands the compression pointer to the full size 10296 // structure that is represented by mDNSResponder. To construct the uncompressed rdata from the resource 10297 // record parsed by GetLargeResourceRecord(), use putRData(). 10298 // Other than SOA, NSEC/NSEC3/RRSIG can use the rdata parsed by GetLargeResourceRecord() directly because 10299 // these records will not have any compression pointer. 10300 #define MAX_SOA_RD_SIZE (MAX_DOMAIN_NAME + MAX_DOMAIN_NAME + 5 * sizeof(mDNSu32)) 10301 mDNSu8 soaRdata[MAX_SOA_RD_SIZE]; 10302 putRData(mDNSNULL, soaRdata, soaRdata + sizeof(soaRdata), rr); 10303 *outObjSOA = dnssec_obj_rr_soa_create(rr->name->c, soaRdata, rr->rdlength, mDNStrue, &err); 10304 } 10305 else if (rr->rrtype == kDNSType_NSEC) 10306 { 10307 if (*outNSECCount == MAX_NUM_NSEC_NSEC3_TO_PROCESS) 10308 { 10309 continue; 10310 } 10311 outObjNSECs[*outNSECCount] = dnssec_obj_rr_nsec_create(rr->name->c, rr->rdata->u.data, rr->rdlength, mDNStrue, &err); 10312 if (err == DNSSEC_ERROR_NO_ERROR) 10313 { 10314 *outNSECCount += 1; 10315 } 10316 } 10317 else if (rr->rrtype == kDNSType_NSEC3) 10318 { 10319 if (*outNSEC3Count == MAX_NUM_NSEC_NSEC3_TO_PROCESS) 10320 { 10321 continue; 10322 } 10323 outObjNSEC3s[*outNSEC3Count] = dnssec_obj_rr_nsec3_create(rr->name->c, rr->rdata->u.data, rr->rdlength, mDNStrue, &err); 10324 if (err == DNSSEC_ERROR_NO_ERROR) 10325 { 10326 *outNSEC3Count += 1; 10327 } 10328 } 10329 else if (rr->rrtype == kDNSType_RRSIG) 10330 { 10331 dnssec_obj_rr_rrsig_t rrsig = dnssec_obj_rr_rrsig_create(rr->name->c, rr->rdata->u.data, rr->rdlength, mDNStrue, &err); 10332 if (err != DNSSEC_ERROR_NO_ERROR) 10333 { 10334 goto rrsig_parsing_exit; 10335 } 10336 10337 const mDNSu16 typeCovered = dnssec_obj_rr_rrsig_get_type_covered(rrsig); 10338 if (typeCovered == kDNSType_SOA) 10339 { 10340 if (*outSOARRSIGCount == MAX_NUM_RRSIG_TO_PROCESS) 10341 { 10342 goto rrsig_parsing_exit; 10343 } 10344 objSOARRSIG[*outSOARRSIGCount] = rrsig; 10345 dnssec_obj_retain(objSOARRSIG[*outSOARRSIGCount]); 10346 *outSOARRSIGCount += 1; 10347 } 10348 else if ((typeCovered == kDNSType_NSEC) || (typeCovered == kDNSType_NSEC3)) 10349 { 10350 if (*outRRSIGCount == MAX_NUM_RRSIG_TO_PROCESS) 10351 { 10352 goto rrsig_parsing_exit; 10353 } 10354 outObjRRSIGs[*outRRSIGCount] = rrsig; 10355 dnssec_obj_retain(outObjRRSIGs[*outRRSIGCount]); 10356 *outRRSIGCount += 1; 10357 } 10358 10359 rrsig_parsing_exit: 10360 MDNS_DISPOSE_DNSSEC_OBJ(rrsig); 10361 } 10362 } 10363 10364 exit: 10365 return negativeTTL; 10366 } 10367 10368 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10369 10370 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10371 mDNSlocal mDNSBool IsResponseMDNSEquivalent(const mdns_client_t client, const mdns_dns_service_t service) 10372 { 10373 // Determine whether the response is mDNS like response, as opposed to non-mDNS. 10374 mDNSBool ResponseIsMDNSEquivalent; 10375 const mDNSBool usesQuerier = (mdns_querier_downcast(client) != mDNSNULL); 10376 const mDNSBool usesSubscriber = (mdns_subscriber_downcast(client) != mDNSNULL); 10377 10378 if (usesQuerier) 10379 { 10380 // Case 1: Message came from a querier, which is inherently non-mDNS, i.e., Do53, DoT, DoH, or ODoH. 10381 ResponseIsMDNSEquivalent = mDNSfalse; 10382 } 10383 else if (usesSubscriber) 10384 { 10385 // Case 2: Message came from a subscriber, which means it came via DNS Push. Technically, not mDNS, but we may 10386 // or may not want to treat messages like mDNS. 10387 if (!service) 10388 { 10389 // Case 2.1: Message came from a subscriber, but no dns service is being used, the record came from a 10390 // unicast discovery proxy. 10391 ResponseIsMDNSEquivalent = mDNStrue; 10392 } 10393 else if (mdns_dns_service_is_mdns_alternative(service)) 10394 { 10395 // Case 2.2: Message came from a subscriber, the record is mDNS alternative. (custom DNS push case). 10396 ResponseIsMDNSEquivalent = mDNStrue; 10397 } 10398 else 10399 { 10400 // Case 2.2: Message came from a subscriber, the record is non-mDNS (discovered DNS push or configured 10401 // unicast push service case). 10402 ResponseIsMDNSEquivalent = mDNSfalse; 10403 } 10404 } 10405 else 10406 { 10407 // Case 3: No object provided the message, meaning it came via the mDNS protocol, so this is definitely an mDNS 10408 // message. 10409 ResponseIsMDNSEquivalent = mDNStrue; 10410 } 10411 return ResponseIsMDNSEquivalent; 10412 } 10413 #endif 10414 10415 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, 10416 const mDNSAddr *dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, 10417 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10418 const mdns_querier_t querier, const mdns_dns_service_t uDNSService, 10419 #endif 10420 const uDNS_LLQType LLQType) 10421 { 10422 int i; 10423 const mDNSu8 *ptr = response->data; 10424 CacheRecord *SOARecord = mDNSNULL; 10425 10426 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10427 dnssec_obj_denial_of_existence_t denial = NULL; 10428 10429 dnssec_obj_rr_soa_t objSOA = NULL; 10430 dnssec_obj_rr_rrsig_t objSOARRSIG[MAX_NUM_RRSIG_TO_PROCESS]; 10431 mDNSu8 soaRRSIGCount = 0; 10432 10433 dnssec_obj_rr_nsec_t objNSECs[MAX_NUM_NSEC_NSEC3_TO_PROCESS]; 10434 mDNSu8 nsecCount = 0; 10435 10436 dnssec_obj_rr_nsec3_t objNSEC3s[MAX_NUM_NSEC_NSEC3_TO_PROCESS]; 10437 mDNSu8 nsec3Count = 0; 10438 10439 dnssec_obj_rr_rrsig_t objRRSIGs[MAX_NUM_RRSIG_TO_PROCESS]; 10440 mDNSu8 rrsigCount = 0; 10441 10442 mDNSBool hasParsed = mDNSfalse; 10443 10444 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10445 const mDNSBool ResponseIsMDNS = IsResponseMDNSEquivalent(mdns_client_upcast(querier), uDNSService); 10446 #else 10447 const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id); 10448 #endif 10449 10450 const mDNSBool toBeDNSSECValidated = (!ResponseIsMDNS) && 10451 ( 10452 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10453 (querier != mDNSNULL) ? 10454 (mdns_querier_get_dnssec_ok(querier) && mdns_querier_get_checking_disabled(querier)) : 10455 #endif 10456 mDNSfalse 10457 ); 10458 10459 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10460 10461 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++) 10462 { 10463 DNSQuestion q; 10464 ptr = getQuestion(response, ptr, end, InterfaceID, &q); 10465 if (ptr) 10466 { 10467 DNSQuestion *qptr; 10468 CacheRecord *cr, *neg = mDNSNULL; 10469 CacheGroup *cg; 10470 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10471 if (querier) 10472 { 10473 qptr = Querier_GetDNSQuestion(querier, mDNSNULL); 10474 } 10475 else 10476 #endif 10477 { 10478 qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr); 10479 if (!qptr) 10480 { 10481 continue; 10482 } 10483 } 10484 10485 // The CNAME chain always starts from the original question name. 10486 const domainname *currentQNameInCNameChain = &q.qname; 10487 mDNSu32 currentQNameHashInCNameChain = q.qnamehash; 10488 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10489 10490 const uint32_t qid = (qptr != mDNSNULL) ? mDNSVal16(qptr->TargetQID) : 0; 10491 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10492 // When we use querier, it is possible we receive a response whose question has already gone, in which case 10493 // qptr will be NULL and querier is an orphan. We still want to process the response to not waste the 10494 // traffic. Therefore, do not rely on qptr to get DNSSEC response matched, instead, use querier. 10495 // The response will be mDNS if querier is NULL. 10496 const mDNSBool processDenialOfExistence = toBeDNSSECValidated; 10497 const uint16_t qclass = (querier != mDNSNULL) ? mdns_querier_get_qclass(querier) : 0; 10498 const uint16_t qtype = (querier != mDNSNULL) ? mdns_querier_get_qtype(querier) : 0; 10499 #else 10500 const mDNSBool processDenialOfExistence = toBeDNSSECValidated && !ResponseIsMDNS && (qptr != mDNSNULL) && dns_question_is_primary_dnssec_requestor(qptr); 10501 const uint16_t qclass = (qptr != mDNSNULL) ? qptr->qclass : 0; 10502 const uint16_t qtype = (qptr != mDNSNULL) ? qptr->qtype : 0; 10503 #endif 10504 domainname cnameChain[MAX_CNAME_TRAVERSAL]; 10505 mDNSu32 chainLen = 1; 10506 mDNSu32 cnameIndex = 0; 10507 10508 // If we need to process denial of existence record for DNSSEC-enabled question, get the CNAME chain from 10509 // the response answer section. 10510 if (processDenialOfExistence) 10511 { 10512 ParseCNameChainFromMessage(response, end, InterfaceID, &q.qname, cnameChain, &chainLen); 10513 currentQNameInCNameChain = &cnameChain[cnameIndex]; 10514 currentQNameHashInCNameChain = DomainNameHashValue(currentQNameInCNameChain); 10515 } 10516 // If the question has required DNSSEC RRs, iterate through all the CNAMEs in the chain. 10517 #endif 10518 10519 // 1. If the question is a normal non-DNSSEC question, currentQNameInCNameChain will be set to the original 10520 // question name. It will be set to mDNSNULL after the first iteration. 10521 // 2. If the question is a DNSSEC question, currentQNameInCNameChain will be set to the original question 10522 // name as well, and the question name is the start of a CNAME chain. It will be set to the next name 10523 // in the CNAME chain. 10524 while (currentQNameInCNameChain != mDNSNULL) 10525 { 10526 cg = CacheGroupForName(m, currentQNameHashInCNameChain, currentQNameInCNameChain); 10527 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10528 // The following code checks if the newly added or existing records in the cache that answer the question is 10529 // a wildcard answer. If it is, then we must create a negative record to deny the existence of the original 10530 // question name. 10531 const mDNSBool checkWildcardAnswer = processDenialOfExistence && (response->h.numAnswers > 0); 10532 mDNSBool wildcardAnswer = mDNSfalse; 10533 domainname nameAfterWildcardExpansion; 10534 mDNSu16 typeCoveredToCheck = kDNSRecordType_Invalid; 10535 mDNSu32 denial_of_existence_ttl = mDNSInvalidUnicastTTLSeconds; 10536 10537 if (checkWildcardAnswer) 10538 { 10539 for (cr = cg ? cg->members : mDNSNULL; cr != mDNSNULL; cr = cr->next) 10540 { 10541 mDNSBool isAnswer; 10542 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10543 if (querier) 10544 { 10545 const mdns_dns_service_t dnsservice = mdns_cache_metadata_get_dns_service(cr->resrec.metadata); 10546 isAnswer = (dnsservice == uDNSService) && Client_SameNameCacheRecordIsAnswer(cr, 10547 mdns_client_upcast(querier)); 10548 } 10549 else 10550 #endif 10551 { 10552 isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr); 10553 } 10554 10555 const ResourceRecord *const rr = &cr->resrec; 10556 // We only care about the non-negative record that answers our question positively. 10557 // (It is possible that we have a negative record that denies the existence of exact name match, 10558 // while having wildcard expanded positive record in the cache at the same time.) 10559 if (!isAnswer || rr->RecordType == kDNSRecordTypePacketNegative) 10560 { 10561 continue; 10562 } 10563 10564 denial_of_existence_ttl = rr->rroriginalttl; 10565 if (rr->rrtype == kDNSType_RRSIG) 10566 { 10567 if (!resource_record_as_rrsig_covers_wildcard_rr(rr)) 10568 { 10569 // This RRSIG does not cover wildcard, therefore, it is impossible that we have received wildcard 10570 // denial of existence. 10571 wildcardAnswer = mDNSfalse; 10572 break; 10573 } 10574 10575 if (typeCoveredToCheck != 0) 10576 { 10577 if (resource_record_as_rrsig_covers_rr_type(rr, typeCoveredToCheck)) 10578 { 10579 wildcardAnswer = mDNStrue; 10580 AssignDomainName(&nameAfterWildcardExpansion, rr->name); 10581 } 10582 else 10583 { 10584 // This RRSIG does not cover the expected wildcard RRSet type. 10585 wildcardAnswer = mDNSfalse; 10586 break; 10587 } 10588 } 10589 else 10590 { 10591 typeCoveredToCheck = resource_record_as_rrsig_get_covered_type(rr); 10592 wildcardAnswer = mDNStrue; 10593 AssignDomainName(&nameAfterWildcardExpansion, rr->name); 10594 } 10595 10596 } 10597 else 10598 { 10599 if (typeCoveredToCheck != 0) 10600 { 10601 if (typeCoveredToCheck != rr->rrtype) 10602 { 10603 // The wildcard RRSIG does not cover the expected wildcard RRSet type. 10604 wildcardAnswer = mDNSfalse; 10605 break; 10606 } 10607 } 10608 else 10609 { 10610 typeCoveredToCheck = rr->rrtype; 10611 } 10612 } 10613 } 10614 10615 if (!wildcardAnswer) 10616 { 10617 typeCoveredToCheck = 0; 10618 denial_of_existence_ttl = 0; 10619 } 10620 } 10621 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10622 10623 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 10624 { 10625 mDNSBool isAnswer; 10626 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10627 if (querier) 10628 { 10629 const mdns_dns_service_t dnsservice = mdns_cache_metadata_get_dns_service(cr->resrec.metadata); 10630 isAnswer = (dnsservice == uDNSService) && Client_SameNameCacheRecordIsAnswer(cr, 10631 mdns_client_upcast(querier)); 10632 } 10633 else 10634 #endif 10635 { 10636 isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr); 10637 } 10638 if (isAnswer) 10639 { 10640 // 1. If we got a fresh answer to this query, then don't need to generate a negative entry 10641 if (RRExpireTime(cr) - m->timenow > 0) 10642 { 10643 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10644 if (!wildcardAnswer) 10645 #endif 10646 { 10647 // If the matched question is a wildcard match (by looking into the labels field of RRSIG) 10648 // then we need a new or existing negative record to deny the original question name. 10649 break; 10650 } 10651 } 10652 // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one 10653 if (cr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = cr; 10654 else if (cr->resrec.mortality == Mortality_Ghost) 10655 { 10656 // 3. If the existing entry is expired, mark it to be purged 10657 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 10658 "mDNSCoreReceiveNoUnicastAnswers: Removing expired record" PRI_S, CRDisplayString(m, cr)); 10659 mDNS_PurgeCacheResourceRecord(m, cr); 10660 } 10661 } 10662 } 10663 // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft 10664 // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers. 10665 // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up 10666 // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist). 10667 // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we 10668 // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache. 10669 // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're 10670 // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not 10671 // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache 10672 // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-) 10673 // 10674 // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a 10675 // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may 10676 // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this 10677 // case without creating the negative cache entries, we generate a negative response and let the layer above us 10678 // do the appropriate thing. This negative response is also needed for appending new search domains. 10679 mDNSBool doNotCreateUnicastNegativeRecordForLocalDomains = (!InterfaceID && (q.qtype != kDNSType_SOA) && IsLocalDomain(&q.qname)); 10680 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10681 doNotCreateUnicastNegativeRecordForLocalDomains = doNotCreateUnicastNegativeRecordForLocalDomains && !processDenialOfExistence; 10682 #endif 10683 if (doNotCreateUnicastNegativeRecordForLocalDomains) 10684 { 10685 if (!cr) 10686 { 10687 if (qptr) 10688 { 10689 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Generate negative response for " 10690 PRI_DM_NAME " (" PUB_S ")", 10691 q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype)); 10692 m->CurrentQuestion = qptr; 10693 // We are not creating a cache record in this case, we need to pass back 10694 // the error we got so that the proxy code can return the right one to 10695 // the application 10696 if (qptr->ProxyQuestion) 10697 qptr->responseFlags = response->h.flags; 10698 GenerateNegativeResponseEx(m, mDNSInterface_Any, QC_forceresponse, response->h.flags); 10699 m->CurrentQuestion = mDNSNULL; 10700 } 10701 } 10702 else 10703 { 10704 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a " 10705 "negative cache entry for " PRI_DM_NAME " (" PUB_S ")", 10706 q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype)); 10707 } 10708 } 10709 else 10710 { 10711 if (!cr) 10712 { 10713 // We start off assuming a negative caching TTL of 60 seconds 10714 // but then look to see if we can find an SOA authority record to tell us a better value we should be using 10715 mDNSu32 negttl = 60; 10716 int repeat = 0; 10717 const domainname *currentQName = currentQNameInCNameChain; 10718 mDNSu32 currentQNameHash = currentQNameHashInCNameChain; 10719 10720 // Special case for our special Microsoft Active Directory "local SOA" check. 10721 // Some cheap home gateways don't include an SOA record in the authority section when 10722 // they send negative responses, so we don't know how long to cache the negative result. 10723 // Because we don't want to keep hitting the root name servers with our query to find 10724 // if we're on a network using Microsoft Active Directory using "local" as a private 10725 // internal top-level domain, we make sure to cache the negative result for at least one day. 10726 mDNSBool useDefaultTTLForDotLocalDomain = (q.qtype == kDNSType_SOA) && SameDomainName(&q.qname, &localdomain); 10727 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10728 useDefaultTTLForDotLocalDomain = (useDefaultTTLForDotLocalDomain && !processDenialOfExistence); 10729 #endif 10730 if (useDefaultTTLForDotLocalDomain) 10731 { 10732 negttl = 60 * 60 * 24; 10733 } 10734 10735 // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record 10736 if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL) 10737 { 10738 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec); 10739 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA) 10740 { 10741 CacheGroup *cgSOA = CacheGroupForRecord(m, &m->rec.r.resrec); 10742 const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data; 10743 mDNSu32 ttl_s = soa->min; 10744 // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except* 10745 // for the SOA record for ".", where the record is reported as non-cacheable 10746 // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is 10747 if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0]) 10748 ttl_s = m->rec.r.resrec.rroriginalttl; 10749 if (negttl < ttl_s) negttl = ttl_s; 10750 10751 // Create the SOA record as we may have to return this to the questions 10752 // that we are acting as a proxy for currently or in the future. 10753 SOARecord = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cgSOA, 1, mDNSfalse, mDNSNULL); 10754 10755 // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer, 10756 // with an Authority Section SOA record for d.com, then this is a hint that the authority 10757 // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either. 10758 // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us 10759 // 10760 // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them 10761 // along with the negative cache record. For simplicity, we don't create the additional records. 10762 mDNSBool deduceNegativeRecordFromSOA = (!qptr || !qptr->ProxyQuestion) && (q.qtype == kDNSType_SOA); 10763 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10764 // For DNSSEC-aware response, we cannot deduce negative records from SOA, because we need 10765 // the NSEC/NSEC3 records to prove that. However, we can use NSEC/NSEC3 to deduce even more 10766 // negative records, but that cannot be finished here. 10767 deduceNegativeRecordFromSOA = (deduceNegativeRecordFromSOA && !processDenialOfExistence); 10768 #endif 10769 if (deduceNegativeRecordFromSOA) 10770 { 10771 int qcount = CountLabels(&q.qname); 10772 int scount = CountLabels(m->rec.r.resrec.name); 10773 if (qcount - 1 > scount) 10774 if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name)) 10775 repeat = qcount - 1 - scount; 10776 } 10777 } 10778 mDNSCoreResetRecord(m); 10779 } 10780 10781 // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid 10782 // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query), 10783 // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL 10784 // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist. 10785 // With this fix in place, when this happens, we double the effective TTL each time (up to one hour), 10786 // so that we back off our polling rate and don't keep hitting the server continually. 10787 if (neg) 10788 { 10789 if (negttl < neg->resrec.rroriginalttl * 2) 10790 negttl = neg->resrec.rroriginalttl * 2; 10791 if (negttl > 3600) 10792 negttl = 3600; 10793 } 10794 10795 negttl = GetEffectiveTTL(LLQType, negttl); // Add 25% grace period if necessary 10796 10797 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10798 CacheRecord *denialOfExistenceTarget = mDNSNULL; 10799 CacheRecord *const invalidTarget = (CacheRecord *)(-1); 10800 10801 // Only parse the SOA, NSEC/NSEC3, RRSIG out if the question requires DNSSEC RRs and we have not 10802 // parsed it yet. 10803 if (processDenialOfExistence && !hasParsed) 10804 { 10805 const mDNSu32 possible_denial_ttl = ParseDenialOfExistenceObjsFromMessage(response, end, InterfaceID, 10806 &objSOA, objSOARRSIG, &soaRRSIGCount, objNSECs, &nsecCount, objNSEC3s, &nsec3Count, 10807 objRRSIGs, &rrsigCount); 10808 hasParsed = mDNStrue; 10809 10810 // If the positive part of the DNSSEC response does not provide a valid TTL for us to use, 10811 // try to use the minimal TTL value of the denial of existence RRSet as our TTL. 10812 if (denial_of_existence_ttl == mDNSInvalidUnicastTTLSeconds) 10813 { 10814 denial_of_existence_ttl = possible_denial_ttl; 10815 } 10816 } 10817 10818 // If the question requires DNSSEC RRs, and we found an existing negative record that denies the 10819 // question (which means the negative record is DNSSEC-aware), check to see if we need to make it 10820 // expired if its denial of existence record has changed since last time we have processed it. 10821 if (processDenialOfExistence && neg != mDNSNULL && resource_record_is_to_be_dnssec_validated(&neg->resrec)) 10822 { 10823 // Compute the new denial of existence record. 10824 const mDNSBool containsNSECOrNSEC3Records = (nsecCount > 0) || (nsec3Count > 0); 10825 if (denial == mDNSNULL && containsNSECOrNSEC3Records) 10826 { 10827 dnssec_error_t err; 10828 denial = dnssec_obj_denial_of_existence_create(currentQName->c, qclass, qtype, 10829 wildcardAnswer ? nameAfterWildcardExpansion.c : mDNSNULL, typeCoveredToCheck, 10830 objSOA, objSOARRSIG, soaRRSIGCount, objNSECs, nsecCount, 10831 objNSEC3s, nsec3Count, objRRSIGs, rrsigCount, &err); 10832 10833 if (denial == mDNSNULL) 10834 { 10835 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_FAULT, 10836 "[Q%u] Unable to create the denial of existence record set - " 10837 "error: " PUB_S ", qname: " PRI_DM_NAME ", qtype: " PRI_S ", soaRRSIGCount: %u, " 10838 "nsecCount: %u, nsec3Count: %u, rrsigCount: %u.", qid, 10839 dnssec_error_get_error_description(err), DM_NAME_PARAM(currentQName), 10840 DNSTypeName(qtype), soaRRSIGCount, nsecCount, nsec3Count, rrsigCount); 10841 } else { 10842 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_DEFAULT, "[Q%u] Create the denial of existence record set " 10843 "- qname: " PRI_DM_NAME ", qtype: " PRI_S ", denial type: " PUB_S, 10844 qid, DM_NAME_PARAM(currentQName), DNSTypeName(qtype), 10845 dnssec_obj_denial_of_existence_get_denial_type_description(denial)); 10846 } 10847 } 10848 10849 const dnssec_obj_denial_of_existence_t neg_denial = resource_record_get_denial_of_existence(&neg->resrec); 10850 // Check if the denial of existence record has changed. 10851 10852 mDNSBool sameDenialOfExistence; 10853 if (neg_denial != mDNSNULL && denial != mDNSNULL) { 10854 sameDenialOfExistence = dnssec_obj_equal(neg_denial, denial); 10855 } else if (neg_denial == mDNSNULL && denial == mDNSNULL) { 10856 sameDenialOfExistence = true; 10857 } else { 10858 sameDenialOfExistence = false; 10859 } 10860 10861 if (!sameDenialOfExistence) 10862 { 10863 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_DEBUG, "Denial of existence record changes, purging the old negative record - " 10864 "name: " PRI_DM_NAME ", type: " PUB_S, DM_NAME_PARAM(currentQName), DNSTypeName(qtype)); 10865 // If the denial of existence has changed, the old negative record should be removed and 10866 // the question callback needs to be notified about this change, therefore, we mark it 10867 // as expired and create a new negative record that contains the latest denial of 10868 // existence record. 10869 mDNS_PurgeCacheResourceRecord(m, neg); 10870 neg = mDNSNULL; 10871 } 10872 else 10873 { 10874 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_DEBUG, "Denial of existence record does not change, rescuing the old negative record - " 10875 "name: " PRI_DM_NAME ", type: " PUB_S, DM_NAME_PARAM(currentQName), DNSTypeName(qtype)); 10876 } 10877 } 10878 10879 // If negative record is still valid after the checking above, assign it to denialOfExistenceTarget. 10880 // Continue the negative record refresh process. 10881 if (processDenialOfExistence && neg != mDNSNULL) 10882 { 10883 denialOfExistenceTarget = neg; 10884 denialOfExistenceTarget->ineligibleForRecycling = mDNStrue; 10885 } 10886 10887 if (processDenialOfExistence && denial_of_existence_ttl != mDNSInvalidUnicastTTLSeconds) 10888 { 10889 negttl = denial_of_existence_ttl; 10890 } 10891 10892 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10893 10894 // If we already had a negative cache entry just update it, else make one or more new negative cache entries. 10895 if (neg) 10896 { 10897 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 10898 "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d " PRI_S, 10899 q.request_id, mDNSVal16(q.TargetQID), neg->resrec.rroriginalttl, negttl, 10900 CRDisplayString(m, neg)); 10901 RefreshCacheRecord(m, neg, negttl); 10902 // When we created the cache for the first time and answered the question, the question's 10903 // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending 10904 // the queries, the interval should still be at MaxQuestionInterval. If the query is being 10905 // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup, 10906 // we should reset its question interval here to MaxQuestionInterval. 10907 if (qptr) 10908 { 10909 ResetQuestionState(m, qptr); 10910 } 10911 if (SOARecord) 10912 { 10913 if (neg->soa) 10914 ReleaseCacheRecord(m, neg->soa); 10915 neg->soa = SOARecord; 10916 SOARecord = mDNSNULL; 10917 } 10918 } 10919 else while (1) 10920 { 10921 CacheRecord *negcr; 10922 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10923 const DNSServRef dnsserv = uDNSService; 10924 #else 10925 const DNSServRef dnsserv = qptr->qDNSServer; 10926 #endif 10927 debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, currentQName, DNSTypeName(q.qtype)); 10928 // Create a negative record for the current name in the CNAME chain. 10929 MakeNegativeCacheRecord(m, &m->rec.r, currentQName, currentQNameHash, q.qtype, q.qclass, negttl, mDNSInterface_Any, 10930 dnsserv, response->h.flags); 10931 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 10932 if (querier) 10933 { 10934 ResourceRecord *const rr = &m->rec.r.resrec; 10935 if (rr->metadata) 10936 { 10937 const mdns_extended_dns_error_t ede = mdns_querier_get_extended_dns_error(querier); 10938 mdns_cache_metadata_set_extended_dns_error(rr->metadata, ede); 10939 } 10940 } 10941 #endif 10942 // We create SOA records above which might create new cache groups. Earlier 10943 // in the function we looked up the cache group for the name and it could have 10944 // been NULL. If we pass NULL cg to new cache entries that we create below, 10945 // it will create additional cache groups for the same name. To avoid that, 10946 // look up the cache group again to re-initialize cg again. 10947 cg = CacheGroupForName(m, currentQNameHash, currentQName); 10948 10949 CreateNewCacheEntryFlags flags = kCreateNewCacheEntryFlagsNone; 10950 mDNSs32 delay = 1; 10951 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10952 if (toBeDNSSECValidated) 10953 { 10954 flags |= kCreateNewCacheEntryFlagsDNSSECRRToValidate; 10955 delay = NonZeroTime(m->timenow); 10956 } 10957 #endif 10958 // Need to add with a delay so that we can tag the SOA record 10959 negcr = CreateNewCacheEntryEx(m, HashSlotFromNameHash(currentQNameHash), cg, delay, mDNStrue, mDNSNULL, flags); 10960 10961 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10962 // Remember the newly created negative cache record. 10963 if (processDenialOfExistence && denialOfExistenceTarget == mDNSNULL) 10964 { 10965 denialOfExistenceTarget = (negcr != mDNSNULL ? negcr : invalidTarget); 10966 // Make this negative record ineligible for cache recycling temporarily, since we have 10967 // a reference to it. 10968 if (denialOfExistenceTarget != invalidTarget) 10969 { 10970 denialOfExistenceTarget->ineligibleForRecycling = mDNStrue; 10971 } 10972 } 10973 #endif 10974 10975 if (negcr) 10976 { 10977 if (SOARecord) 10978 { 10979 if (negcr->soa) 10980 ReleaseCacheRecord(m, negcr->soa); 10981 negcr->soa = SOARecord; 10982 SOARecord = mDNSNULL; 10983 } 10984 10985 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10986 if (!processDenialOfExistence) 10987 { 10988 #endif 10989 negcr->DelayDelivery = 0; 10990 CacheRecordDeferredAdd(m, negcr); 10991 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 10992 } 10993 else 10994 { 10995 // Always delay deliver DNSSEC response so that we can finish processing the entire response. 10996 ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(currentQNameHash), negcr->DelayDelivery); 10997 } 10998 #endif 10999 } 11000 mDNSCoreResetRecord(m); 11001 if (!repeat) break; 11002 repeat--; 11003 currentQName = SkipLeadingLabels(currentQName, 1); 11004 currentQNameHash = DomainNameHashValue(currentQName); 11005 } 11006 11007 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11008 // Do not set denial of existence object: 11009 // 1. if the records come from mDNS response. 11010 // 2. If we do not know if the question requires DNSSEC RRs. 11011 // 3. If the question does not require DNSSEC RRs. (No one will use the denial object) 11012 // 4. If no negative is found or created. 11013 if (!processDenialOfExistence || denialOfExistenceTarget == invalidTarget || 11014 !resource_record_is_dnssec_aware(&denialOfExistenceTarget->resrec)) 11015 { 11016 goto process_denial_exit; 11017 } 11018 // Make the negative record eligible for cache recycling since we will finish the work with it. 11019 denialOfExistenceTarget->ineligibleForRecycling = mDNSfalse; 11020 11021 // Check if we need to update the old denial of existence object. 11022 // If the denialOfExistenceTarget already has a denial of existence record, it is an existing 11023 // negative record whose denial of existence has not changed since last time. Therefore, we do not 11024 // need to assign new denial of existence object to it. 11025 if (resource_record_get_denial_of_existence(&denialOfExistenceTarget->resrec) != mDNSNULL) 11026 { 11027 goto process_denial_exit; 11028 } 11029 11030 // Create the denial of existence object based on the parsed DNSSEC objects. 11031 const mDNSBool containsNSECOrNSEC3Records = (nsecCount > 0) || (nsec3Count > 0); 11032 if (denial == mDNSNULL && containsNSECOrNSEC3Records) 11033 { 11034 dnssec_error_t err; 11035 // Here, we are creating the denial of existence object because we cannot find an acceptable 11036 // positive record for the question, we can be sure that it is not a wildcard data response. 11037 // Therefore we can pass kDNSRecordType_Invalid to skip the wildcard data response checking. 11038 denial = dnssec_obj_denial_of_existence_create(currentQName->c, qclass, qtype, 11039 wildcardAnswer ? nameAfterWildcardExpansion.c : mDNSNULL, typeCoveredToCheck, 11040 objSOA, objSOARRSIG, soaRRSIGCount, objNSECs, nsecCount, 11041 objNSEC3s, nsec3Count, objRRSIGs, rrsigCount, &err); 11042 11043 if (denial == mDNSNULL) 11044 { 11045 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_FAULT, 11046 "[Q%u] Unable to create the denial of existence record set - " 11047 "error: " PUB_S ", qname: " PRI_DM_NAME ", qtype: " PRI_S ", soaRRSIGCount: %u, " 11048 "nsecCount: %u, nsec3Count: %u, rrsigCount: %u.", qid, 11049 dnssec_error_get_error_description(err), DM_NAME_PARAM(currentQName), 11050 DNSTypeName(qtype), soaRRSIGCount, nsecCount, nsec3Count, rrsigCount); 11051 goto process_denial_exit; 11052 } 11053 else 11054 { 11055 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_DEFAULT, "[Q%u] Create the denial of existence record set " 11056 "- qname: " PRI_DM_NAME ", qtype: " PRI_S ", denial type: " PUB_S, 11057 qid, DM_NAME_PARAM(currentQName), DNSTypeName(qtype), 11058 dnssec_obj_denial_of_existence_get_denial_type_description(denial)); 11059 } 11060 } 11061 11062 resource_record_set_denial_of_existence(&denialOfExistenceTarget->resrec, denial); 11063 11064 process_denial_exit: 11065 (void)denialOfExistenceTarget; // To make process_denial_exit a non-empty label. 11066 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11067 } 11068 } 11069 // By default we do not traverse the CNAME chain. 11070 currentQNameInCNameChain = mDNSNULL; 11071 currentQNameHashInCNameChain = 0; 11072 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11073 // However, if the question has required DNSSEC RRs, we need to traverse the CNAME chain to create the 11074 // negative record for each name in the CNAME chain. 11075 if (processDenialOfExistence) 11076 { 11077 cnameIndex++; 11078 if (cnameIndex < chainLen) 11079 { 11080 currentQNameInCNameChain = &cnameChain[cnameIndex]; 11081 currentQNameHashInCNameChain = DomainNameHashValue(currentQNameInCNameChain); 11082 } 11083 } 11084 11085 if (!ResponseIsMDNS) 11086 { 11087 // Every CNAME in the chain has a separate denial of existence record. 11088 MDNS_DISPOSE_DNSSEC_OBJ(denial); 11089 } 11090 #endif 11091 } // while (currentQNameInCNameChain != mDNSNULL) 11092 } // if (ptr) 11093 } // for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++) 11094 if (SOARecord) 11095 { 11096 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used"); 11097 ReleaseCacheRecord(m, SOARecord); 11098 } 11099 11100 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11101 if (!ResponseIsMDNS) 11102 { 11103 MDNS_DISPOSE_DNSSEC_OBJ(objSOA); 11104 for (mDNSu32 index = 0; index < soaRRSIGCount; index++) 11105 { 11106 MDNS_DISPOSE_DNSSEC_OBJ(objSOARRSIG[index]); 11107 } 11108 11109 for (mDNSu32 index = 0; index < nsecCount; index++) 11110 { 11111 MDNS_DISPOSE_DNSSEC_OBJ(objNSECs[index]); 11112 } 11113 for (mDNSu32 index = 0; index < nsec3Count; index++) 11114 { 11115 MDNS_DISPOSE_DNSSEC_OBJ(objNSEC3s[index]); 11116 } 11117 11118 for (mDNSu32 index = 0; index < rrsigCount; index++) 11119 { 11120 MDNS_DISPOSE_DNSSEC_OBJ(objRRSIGs[index]); 11121 } 11122 } 11123 #endif 11124 } 11125 11126 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m) 11127 { 11128 AuthRecord *rrPtr = mDNSNULL; 11129 if (!m->SPSRRSet) return; 11130 LogSPS("Stored Proxy records :"); 11131 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next) 11132 { 11133 LogSPS("%s", ARDisplayString(m, rrPtr)); 11134 } 11135 } 11136 11137 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr) 11138 { 11139 AuthRecord *rrPtr = mDNSNULL; 11140 11141 for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next) 11142 { 11143 if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec)) 11144 { 11145 LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr)); 11146 return mDNStrue; 11147 } 11148 } 11149 mDNSCorePrintStoredProxyRecords(m); 11150 return mDNSfalse; 11151 } 11152 11153 mDNSexport CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType, 11154 const mDNSu32 slot, CacheGroup *cg, CacheRecord ***cfp, mDNSInterfaceID InterfaceID) 11155 { 11156 CacheRecord *cr; 11157 CacheRecord **cflocal = *cfp; 11158 11159 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 11160 { 11161 mDNSBool match; 11162 // Resource record received via unicast, the resGroupID should match ? 11163 mDNSBool requireMatchedDNSService = !InterfaceID; 11164 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11165 if (!requireMatchedDNSService) 11166 { 11167 // If the associated DNS service has local purview and not mDNS-alternative, then it is a record resolved 11168 // through non-mDNS, although it has non-zero interface ID, it always has a specific DNS service to be 11169 // matched. In which case, we still need to check if the cached record has a matched DNS service with the 11170 // newly received record. 11171 const mdns_dns_service_t newRecordService = mdns_cache_metadata_get_dns_service(m->rec.r.resrec.metadata); 11172 requireMatchedDNSService = (newRecordService && mdns_dns_service_has_local_purview(newRecordService) && 11173 !mdns_dns_service_is_mdns_alternative(newRecordService)); 11174 } 11175 #endif 11176 if (requireMatchedDNSService) 11177 { 11178 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11179 match = mdns_cache_metadata_same_dns_service(cr->resrec.metadata, m->rec.r.resrec.metadata); 11180 #else 11181 const mDNSu32 id1 = (cr->resrec.rDNSServer ? cr->resrec.rDNSServer->resGroupID : 0); 11182 const mDNSu32 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0); 11183 match = (id1 == id2); 11184 #endif 11185 } 11186 else 11187 match = (cr->resrec.InterfaceID == InterfaceID); 11188 // If we found this exact resource record, refresh its TTL 11189 if (match) 11190 { 11191 if (IdenticalSameNameRecord(&m->rec.r.resrec, &cr->resrec)) 11192 { 11193 if (m->rec.r.resrec.rdlength > InlineCacheRDSize) 11194 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s", 11195 m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r)); 11196 11197 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) 11198 { 11199 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list 11200 if (cr->NextInCFList == mDNSNULL && *cfp != &cr->NextInCFList && LLQType != uDNS_LLQ_Events) 11201 { 11202 *cflocal = cr; 11203 cflocal = &cr->NextInCFList; 11204 *cflocal = (CacheRecord*)1; 11205 *cfp = &cr->NextInCFList; 11206 } 11207 11208 // If this packet record is marked unique, and our previous cached copy was not, then fix it 11209 if (!(cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)) 11210 { 11211 DNSQuestion *q; 11212 for (q = m->Questions; q; q=q->next) 11213 { 11214 if (CacheRecordAnswersQuestion(cr, q)) 11215 q->UniqueAnswers++; 11216 } 11217 cr->resrec.RecordType = m->rec.r.resrec.RecordType; 11218 } 11219 } 11220 11221 if (!SameRDataBody(&m->rec.r.resrec, &cr->resrec.rdata->u, SameDomainNameCS)) 11222 { 11223 // If the rdata of the packet record differs in name capitalization from the record in our cache 11224 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get 11225 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one. 11226 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing 11227 cr->resrec.rroriginalttl = 0; 11228 cr->TimeRcvd = m->timenow; 11229 cr->UnansweredQueries = MaxUnansweredQueries; 11230 SetNextCacheCheckTimeForRecord(m, cr); 11231 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: " PRI_S, 11232 CRDisplayString(m, cr)); 11233 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: " PRI_S, 11234 CRDisplayString(m, &m->rec.r)); 11235 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in " 11236 "%d slot %3d in %d %d", NextCacheCheckEvent(cr) - m->timenow, slot, 11237 m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow); 11238 // DO NOT break out here -- we want to continue as if we never found it 11239 } 11240 else if (m->rec.r.resrec.rroriginalttl > 0) 11241 { 11242 DNSQuestion *q; 11243 11244 m->mDNSStats.CacheRefreshed++; 11245 11246 if ((cr->resrec.mortality == Mortality_Ghost) && !cr->DelayDelivery) 11247 { 11248 cr->DelayDelivery = NonZeroTime(m->timenow); 11249 debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m->timenow - RRExpireTime(cr), CRDisplayString(m, cr)); 11250 } 11251 11252 if (cr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, cr)); 11253 mDNSu32 newCRTTL = m->rec.r.resrec.rroriginalttl; 11254 #if MDNSRESPONDER_SUPPORTS(APPLE, AWDL) 11255 if (cr->resrec.rroriginalttl == kStandardTTL && 11256 m->rec.r.resrec.rroriginalttl == kHostNameTTL && 11257 mDNSPlatformInterfaceIsAWDL(cr->resrec.InterfaceID) && 11258 (cr->resrec.rrtype == kDNSType_SRV || cr->resrec.rrtype == kDNSType_AAAA)) 11259 { 11260 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNSCoreReceiveCacheCheck: Keeping Standard TTL for " PRI_S " %p", 11261 CRDisplayString(m, cr), cr->resrec.InterfaceID); 11262 newCRTTL = kStandardTTL; 11263 } 11264 #endif 11265 RefreshCacheRecord(m, cr, newCRTTL); 11266 // RefreshCacheRecordCacheGroupOrder will modify the cache group member list that is currently being iterated over in this for-loop. 11267 // It is safe to call because the else-if body will unconditionally break out of the for-loop now that it has found the entry to update. 11268 RefreshCacheRecordCacheGroupOrder(cg, cr); 11269 CacheRecordSetResponseFlags(cr, response->h.flags); 11270 11271 // If we may have NSEC records returned with the answer (which we don't know yet as it 11272 // has not been processed), we need to cache them along with the first cache 11273 // record in the list that answers the question so that it can be used for validation 11274 // later. The "type" check below is to make sure that we cache on the cache record 11275 // that would answer the question. It is possible that we might cache additional things 11276 // e.g., MX question might cache A records also, and we want to cache the NSEC on 11277 // the record that answers the question. 11278 if (!InterfaceID) 11279 { 11280 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 11281 "mDNSCoreReceiveCacheCheck: rescuing RR with new TTL %u: " PRI_S, 11282 cr->resrec.rroriginalttl, CRDisplayString(m, cr)); 11283 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11284 if (resource_record_is_to_be_dnssec_validated(&cr->resrec) && cr->CRActiveQuestion != mDNSNULL) 11285 { 11286 // We have update the "DNSSEC to be validated" record's TTL, schedule a cache update for 11287 // the "DNSSEC validated" record so their expiration time can also be updated. 11288 schedule_next_validated_cache_update(m); 11289 } 11290 #endif 11291 } 11292 // We have to reset the question interval to MaxQuestionInterval so that we don't keep 11293 // polling the network once we get a valid response back. For the first time when a new 11294 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that. 11295 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server 11296 // configuration changed, without flushing the cache, we reset the question interval here. 11297 // Currently, we do this for for both multicast and unicast questions as long as the record 11298 // type is unique. For unicast, resource record is always unique and for multicast it is 11299 // true for records like A etc. but not for PTR. 11300 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) 11301 { 11302 for (q = m->Questions; q; q=q->next) 11303 { 11304 if (!q->DuplicateOf && !q->LongLived && 11305 ActiveQuestion(q) && CacheRecordAnswersQuestion(cr, q)) 11306 { 11307 ResetQuestionState(m, q); 11308 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype)); 11309 break; // Why break here? Aren't there other questions we might want to look at?-- SC July 2010 11310 } 11311 } 11312 } 11313 break; // Check usage of RefreshCacheRecordCacheGroupOrder before removing (See note above) 11314 } 11315 else 11316 { 11317 // If the packet TTL is zero, that means we're deleting this record. 11318 // To give other hosts on the network a chance to protest, we push the deletion 11319 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries. 11320 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent 11321 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth. 11322 // If record's current expiry time is more than a second from now, we set it to expire in one second. 11323 // If the record is already going to expire in less than one second anyway, we leave it alone -- 11324 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache. 11325 11326 if (RRExpireTime(cr) - m->timenow > mDNSPlatformOneSecond) 11327 { 11328 const ResourceRecord *const resrec = &cr->resrec; 11329 11330 // Since the Goodbye packet we care about is the PTR Goodbye packet, which tells us what 11331 // host is deregistering the record, only print the domain name in the RDATA if the RDATA type 11332 // is PTR. 11333 const domainname *ptrDomain = mDNSNULL; 11334 if (resrec->rrtype == kDNSType_PTR) 11335 { 11336 ptrDomain = &resrec->rdata->u.name; 11337 } 11338 const mDNSu32 nameHash = mDNS_DomainNameFNV1aHash(resrec->name); 11339 const mDNSu32 ptrNameHash = (ptrDomain != mDNSNULL) ? mDNS_DomainNameFNV1aHash(ptrDomain) : 0; 11340 struct timeval now; 11341 mDNSGetTimeOfDay(&now, mDNSNULL); 11342 const mDNSu32 ifIndex = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue); 11343 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 11344 "Received Goodbye packet for cached record -- " 11345 "name hash: %x, type: " PUB_DNS_TYPE ", last time received: " PUB_TIMEV 11346 ", interface index: %d, source address: " PRI_IP_ADDR ", name hash if PTR: %x", 11347 nameHash, DNS_TYPE_PARAM(resrec->rrtype), TIMEV_PARAM(&now), ifIndex, &cr->sourceAddress, 11348 ptrNameHash); 11349 11350 cr->resrec.rroriginalttl = 1; 11351 cr->TimeRcvd = m->timenow; 11352 cr->UnansweredQueries = MaxUnansweredQueries; 11353 SetNextCacheCheckTimeForRecord(m, cr); 11354 } 11355 break; 11356 } 11357 } 11358 else 11359 { 11360 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11361 // The DNSSEC status has to be the same to be comparable. 11362 if (!resource_records_have_same_dnssec_rr_category(&m->rec.r.resrec, &cr->resrec)) 11363 { 11364 continue; 11365 } 11366 #endif 11367 11368 // If the cache record rrtype doesn't match and one is a CNAME, then flush this record. 11369 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME || cr->resrec.rrtype == kDNSType_CNAME)) 11370 { 11371 // Do not mark it to be flushable if it has already been marked as flushable. 11372 if (cr->resrec.rroriginalttl == 0) 11373 { 11374 continue; 11375 } 11376 // Do not mark it to be flushable if they have the same name and type, but different data. 11377 // The only case we want to handle here is the CNAME exclusion. 11378 // The same name and type, but different data case is handled by CacheFlushRecords part of 11379 // mDNSCoreReceiveResponse(). 11380 if (m->rec.r.resrec.rrtype == cr->resrec.rrtype) 11381 { 11382 continue; 11383 } 11384 11385 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11386 // IN DNSSEC, a CNAME record can coexist with: 11387 // 1. RRSIGs that cover it. 11388 // 2. Negative records that indicate the CNAME is a wildcard answer. 11389 11390 // Therefore, do not flush the RRSIG that covers the CNAME record that accompanies this CNAME. 11391 if (resource_record_as_rrsig_covers_rr_type(&m->rec.r.resrec, kDNSType_CNAME) || 11392 resource_record_as_rrsig_covers_rr_type(&cr->resrec, kDNSType_CNAME)) 11393 { 11394 continue; 11395 } 11396 // Do not flush the denial of existence record that accompanies the CNAME record. 11397 if (resource_record_as_denial_of_existence_proves_wildcard_answer(&m->rec.r.resrec) || 11398 resource_record_as_denial_of_existence_proves_wildcard_answer(&cr->resrec)) 11399 { 11400 continue; 11401 } 11402 #endif 11403 11404 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 11405 "mDNSCoreReceiveCacheCheck: Discarding (" PUB_S ") " PRI_S " rrtype change from (" PUB_S PUB_S ") to (" PUB_S PUB_S ")", 11406 MortalityDisplayString(cr->resrec.mortality), CRDisplayString(m, cr), 11407 DNSTypeName(cr->resrec.rrtype), (cr->resrec.RecordType == kDNSRecordTypePacketNegative) ? ", Negative" : "", 11408 DNSTypeName(m->rec.r.resrec.rrtype), (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative) ? ", Negative" : ""); 11409 mDNS_PurgeCacheResourceRecord(m, cr); 11410 // DO NOT break out here -- we want to continue iterating the cache entries. 11411 } 11412 } 11413 } 11414 } 11415 return cr; 11416 } 11417 11418 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11419 11420 // A record set is a group of records received in the same response that have the same name and type. 11421 typedef struct 11422 { 11423 const domainname *name; 11424 mDNSu32 namehash; 11425 mDNSu32 sizeOfRecordSet; // The total number of records with the same name and type added to the cache. 11426 mDNSu16 rrtype; // The DNS type that this record set has in common. The rrtype of the RRSIG should be 11427 // treated as the type it covers. 11428 mDNSBool noNewCachedRecordAdded; // If new cached record has been added. 11429 } RecordSet; 11430 11431 mDNSlocal mDNSBool RecordInTheRRSet(const ResourceRecord * const rr, const RecordSet * const rrset) 11432 { 11433 const mDNSBool typeMatchesDirectly = (rrset->rrtype == rr->rrtype); 11434 const mDNSBool rrsigCoversType = resource_record_as_rrsig_covers_rr_type(rr, rrset->rrtype); 11435 const mDNSBool inTheSameSet = typeMatchesDirectly || rrsigCoversType; 11436 11437 if (!inTheSameSet) 11438 { 11439 return mDNSfalse; 11440 } 11441 if (rrset->namehash != rr->namehash) 11442 { 11443 return mDNSfalse; 11444 } 11445 if (!SameDomainName(rrset->name, rr->name)) 11446 { 11447 return mDNSfalse; 11448 } 11449 11450 return mDNStrue; 11451 } 11452 11453 #endif 11454 11455 mDNSlocal mDNSBool SameNameCacheRecordsMatchInSourceTypeClass(const CacheRecord *const cr1, const CacheRecord *const cr2) 11456 { 11457 const ResourceRecord *const rr1 = &cr1->resrec; 11458 const ResourceRecord *const rr2 = &cr2->resrec; 11459 11460 if (rr1->InterfaceID != rr2->InterfaceID) 11461 { 11462 return mDNSfalse; 11463 } 11464 11465 if (!rr1->InterfaceID) 11466 { 11467 // For Unicast (null InterfaceID) the resolver IDs should also match 11468 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11469 if (!mdns_cache_metadata_same_dns_service(rr1->metadata, rr2->metadata)) 11470 { 11471 return mDNSfalse; 11472 } 11473 #else 11474 const mDNSu32 id1 = (rr1->rDNSServer ? rr1->rDNSServer->resGroupID : 0); 11475 const mDNSu32 id2 = (rr2->rDNSServer ? rr2->rDNSServer->resGroupID : 0); 11476 if (id1 != id2) 11477 { 11478 return mDNSfalse; 11479 } 11480 #endif 11481 } 11482 11483 if ((rr1->rrtype != rr2->rrtype) || (rr1->rrclass != rr2->rrclass)) 11484 { 11485 return mDNSfalse; 11486 } 11487 11488 return mDNStrue; 11489 } 11490 11491 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change 11492 // the record list and/or question list. 11493 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 11494 // InterfaceID non-NULL tells us the interface this multicast response was received on 11495 // InterfaceID NULL tells us this was a unicast response 11496 // dstaddr NULL tells us we received this over an outgoing TCP connection we made 11497 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, 11498 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport, 11499 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11500 mdns_client_t client, mdns_dns_service_t uDNSService, 11501 #endif 11502 const mDNSInterfaceID InterfaceID) 11503 { 11504 int i; 11505 const mDNSBool ResponseMCast = dstaddr && mDNSAddrIsDNSMulticast(dstaddr); 11506 const mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr); 11507 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 11508 DNSQuestion *llqMatch = mDNSNULL; 11509 uDNS_LLQType LLQType = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch); 11510 #else 11511 uDNS_LLQType LLQType = uDNS_LLQ_Not; 11512 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 11513 11514 // "(CacheRecord*)1" is a special (non-zero) end-of-list marker 11515 // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList 11516 // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling. 11517 CacheRecord *CacheFlushRecords = (CacheRecord*)1; 11518 CacheRecord **cfp = &CacheFlushRecords; 11519 NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID); 11520 mDNSBool recordAcceptedInResponse = mDNSfalse; // Set if a record is accepted from a unicast mDNS response that answers an existing question. 11521 11522 // All records in a DNS response packet are treated as equally valid statements of truth. If we want 11523 // to guard against spoof responses, then the only credible protection against that is cryptographic 11524 // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record. 11525 int firstauthority = response->h.numAnswers; 11526 int firstadditional = firstauthority + response->h.numAuthorities; 11527 int totalrecords = firstadditional + response->h.numAdditionals; 11528 const mDNSu8 *ptr = mDNSNULL; 11529 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11530 DNSServer *uDNSServer = mDNSNULL; 11531 #endif 11532 11533 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11534 mdns_cache_metadata_t cache_metadata = mDNSNULL; 11535 const mdns_querier_t querier = mdns_querier_downcast(client); 11536 const mdns_subscriber_t subscriber = mdns_subscriber_downcast(client); 11537 const mDNSBool ResponseIsMDNS = IsResponseMDNSEquivalent(client, uDNSService); 11538 const mDNSBool subscriberResponse = (subscriber != mDNSNULL); 11539 #else 11540 const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id); 11541 const mDNSBool subscriberResponse = mDNSfalse; 11542 #endif 11543 11544 mDNSBool dumpMDNSPacket = mDNSfalse; 11545 11546 TSRDataRecHead tsrs = SLIST_HEAD_INITIALIZER(tsrs); 11547 const TSROptData *curTSRForName = mDNSNULL; 11548 11549 debugf("Received Response from %#-15a addressed to %#-15a on %p with " 11550 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d", 11551 srcaddr, dstaddr, InterfaceID, 11552 response->h.numQuestions, response->h.numQuestions == 1 ? ", " : "s,", 11553 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,", 11554 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,", 11555 response->h.numAdditionals, response->h.numAdditionals == 1 ? " " : "s", end - response->data, LLQType); 11556 11557 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_ANALYTICS) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11558 if (mDNSSameIPPort(srcport, UnicastDNSPort)) 11559 { 11560 bool isForCell = (m->rec.r.resrec.rDNSServer && m->rec.r.resrec.rDNSServer->isCell); 11561 dnssd_analytics_update_dns_reply_size(isForCell, dns_transport_Do53, (uint32_t)(end - (mDNSu8 *)response)); 11562 } 11563 #endif 11564 11565 // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt> 11566 // When a DNS client receives a reply with TC 11567 // set, it should ignore that response, and query again, using a 11568 // mechanism, such as a TCP connection, that will permit larger replies. 11569 // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but 11570 // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing 11571 // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once. 11572 // <rdar://problem/6690034> Can't bind to Active Directory 11573 // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll 11574 // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache. 11575 // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already, 11576 // and not even do the TCP query. 11577 // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the 11578 // entire RRSet, with the following exception. If the response contains an answer section and one or more records in 11579 // either the authority section or additional section, then that implies that truncation occurred beyond the answer 11580 // section, and the answer section is therefore assumed to be complete. 11581 // 11582 // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>: 11583 // When a response is so long that truncation is required, the truncation 11584 // should start at the end of the response and work forward in the 11585 // datagram. Thus if there is any data for the authority section, the 11586 // answer section is guaranteed to be unique. 11587 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11588 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) && !client && 11589 #else 11590 if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) && 11591 #endif 11592 ((response->h.numAnswers == 0) || ((response->h.numAuthorities == 0) && (response->h.numAdditionals == 0)))) 11593 { 11594 goto exit; 11595 } 11596 11597 mdns_require_quiet(LLQType != uDNS_LLQ_Ignore, exit); 11598 11599 // Look in Additional Section for an OPT record 11600 ptr = LocateOptRR(response, end, DNSOpt_TSRData_Space); 11601 if (ptr) 11602 { 11603 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec); 11604 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT) 11605 { 11606 const rdataOPT *opt; 11607 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength]; 11608 mDNSu8 tsrsCount = 0; 11609 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++) 11610 { 11611 if (opt->opt == kDNSOpt_TSR) 11612 { 11613 tsrsCount++; 11614 const mDNSu8 *name_ptr; 11615 if ((name_ptr = DomainNamePtrAtTSRIndex(response, end, opt->u.tsr.recIndex))) 11616 { 11617 struct TSRDataRec *newTSR = TSRDataRecCreate(response, name_ptr, end, opt); 11618 if (!newTSR) 11619 { 11620 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 11621 "mDNSCoreReceiveResponse: Create TSR(%u) failed - if %p tsrTime %d tsrHost %x recIndex %d", 11622 tsrsCount, m->rec.r.resrec.InterfaceID, opt->u.tsr.timeStamp, opt->u.tsr.hostkeyHash, 11623 opt->u.tsr.recIndex); 11624 continue; 11625 } 11626 SLIST_INSERT_HEAD(&tsrs, newTSR, entries); 11627 } 11628 else 11629 { 11630 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 11631 "mDNSCoreReceiveResponse: No Domain Name for TSR(%u) if %p tsrTime %d tsrHost %x recIndex %d", 11632 tsrsCount, m->rec.r.resrec.InterfaceID, opt->u.tsr.timeStamp, opt->u.tsr.hostkeyHash, 11633 opt->u.tsr.recIndex); 11634 } 11635 } 11636 } 11637 if (!SLIST_EMPTY(&tsrs)) 11638 { 11639 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, 11640 "mDNSCoreReceiveResponse: Received TSR(%u) if %p " PUB_S, 11641 tsrsCount, m->rec.r.resrec.InterfaceID, RRDisplayString(m, &m->rec.r.resrec)); 11642 } 11643 } 11644 mDNSCoreResetRecord(m); 11645 } 11646 11647 // 1. We ignore questions (if any) in mDNS response packets 11648 // 2. If this is an LLQ response, we handle it much the same 11649 // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged 11650 if (ResponseMCast || LLQType == uDNS_LLQ_Events) 11651 ptr = LocateAnswers(response, end); 11652 // Otherwise, for one-shot queries, any answers in our cache that are not also contained 11653 // in this response packet are immediately deemed to be invalid. 11654 else 11655 { 11656 mDNSBool failure, returnEarly; 11657 const int rcode = response->h.flags.b[1] & kDNSFlag1_RC_Mask; 11658 failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth); 11659 returnEarly = mDNSfalse; 11660 ptr = response->data; 11661 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11662 // When the QUERIER functionality is enabled, DNS transport is handled exclusively by querier objects. If this 11663 // response was provided by a querier, but the RCODE is considered a failure, then set failure to false so that 11664 // we don't return early. The logic of returning early was so that uDNS_CheckCurrentQuestion() could handle 11665 // resending the query and generate a negative cache record if all servers were tried. If the querier provides a 11666 // response, then it's the best response that it could provide. If the RCODE is considered a failure, 11667 // mDNSCoreReceiveResponse() needs to create negative cache entries for the unanwered question, so totalrecords 11668 // is set to 0 to ignore any records that the response may contain. 11669 if (querier && failure) 11670 { 11671 totalrecords = 0; 11672 failure = mDNSfalse; 11673 } 11674 #endif 11675 // We could possibly combine this with the similar loop at the end of this function -- 11676 // instead of tagging cache records here and then rescuing them if we find them in the answer section, 11677 // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in 11678 // which it was received (or refreshed), and then at the end if we find any cache records which 11679 // answer questions in this packet's question section, but which aren't tagged with this packet's 11680 // packet number, then we deduce they are old and delete them 11681 // Additional condition to check: a response comes from subscriber does not flush previous records, so skip it. 11682 // 11683 // Note: the for loop below must be executed even when we don't need to flush previous records, because we use 11684 // "getQuestion" to advance the response read pointer. 11685 for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++) 11686 { 11687 DNSQuestion q; 11688 DNSQuestion *qptr; 11689 mDNSBool expectingResponse; 11690 ptr = getQuestion(response, ptr, end, InterfaceID, &q); 11691 if (!ptr || subscriberResponse) 11692 { 11693 continue; 11694 } 11695 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11696 if (client) 11697 { 11698 expectingResponse = mDNStrue; 11699 qptr = mDNSNULL; 11700 } 11701 else 11702 #endif 11703 { 11704 qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr); 11705 expectingResponse = qptr ? mDNStrue : mDNSfalse; 11706 } 11707 if (!expectingResponse) 11708 { 11709 continue; 11710 } 11711 if (!failure) 11712 { 11713 CacheRecord *cr; 11714 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname); 11715 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 11716 { 11717 mDNSBool isAnswer; 11718 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11719 if (client) 11720 { 11721 const mdns_dns_service_t dnsservice = mdns_cache_metadata_get_dns_service(cr->resrec.metadata); 11722 isAnswer = (dnsservice == uDNSService) && Client_SameNameCacheRecordIsAnswer(cr, client); 11723 } 11724 else 11725 #endif 11726 { 11727 isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr); 11728 } 11729 mDNSBool flushable = isAnswer; 11730 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 11731 // Push subscribed records will never be flushed by a response (except "remove" push notification). 11732 flushable = flushable && (!cr->DNSPushSubscribed); 11733 #endif 11734 if (flushable) 11735 { 11736 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, 11737 "Making record answered by the current response as expired if it is not refreshed in the response - " 11738 "Q interface ID: %p, qname: " PRI_DM_NAME ", qtype: " PRI_S 11739 ", RR interface ID: %p, RR description: " PRI_S ".", q.InterfaceID, DM_NAME_PARAM(&q.qname), 11740 DNSTypeName(q.qtype), cr->resrec.InterfaceID, CRDisplayString(m, cr)); 11741 11742 // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm 11743 cr->TimeRcvd = m->timenow - TicksTTL(cr) - 1; 11744 cr->UnansweredQueries = MaxUnansweredQueries; 11745 } 11746 } 11747 } 11748 else 11749 { 11750 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11751 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to query " 11752 PRI_DM_NAME " (" PUB_S ")", qptr->request_id, mDNSVal16(qptr->TargetQID), qptr->qDNSServer, rcode, 11753 DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype)); 11754 PenalizeDNSServer(m, qptr, response->h.flags); 11755 #endif 11756 returnEarly = mDNStrue; 11757 } 11758 } 11759 if (returnEarly) 11760 { 11761 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[Q%d] Ignoring %2d Answer" PUB_S " %2d Authorit" PUB_S " %2d Additional" PUB_S, 11762 mDNSVal16(response->h.id), 11763 response->h.numAnswers, response->h.numAnswers == 1 ? ", " : "s,", 11764 response->h.numAuthorities, response->h.numAuthorities == 1 ? "y, " : "ies,", 11765 response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s"); 11766 // not goto exit because we won't have any CacheFlushRecords and we do not want to 11767 // generate negative cache entries (we want to query the next server) 11768 goto exit; 11769 } 11770 } 11771 11772 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11773 // Use this CacheRecord array to track all the answer records we have added into cache. Currently, we allow at 11774 // most 100 records to be contained in the answer section of the response. 11775 #define MAX_RESPONSE_RECORDS 100 11776 CacheRecord *cachedRecords[MAX_RESPONSE_RECORDS]; 11777 mDNSu32 numOfCachedRecords = 0; // The total number of records added to the cache. 11778 RecordSet recordSets[MAX_RESPONSE_RECORDS]; 11779 mDNSu32 numOfRecordSets = 0; 11780 11781 // Because DNSSEC signs record with the same type, when we are counting the number of records with within the 11782 // same response, we should separate them by names and types. 11783 // For example, if we received a CNAME response like this: 11784 // ============================================================================================================= 11785 // www.apple.com. 300 IN CNAME www.apple.com.edgekey.net. 11786 // www.apple.com.edgekey.net. 17716 IN CNAME www.apple.com.edgekey.net.globalredir.akadns.net. 11787 // www.apple.com.edgekey.net.globalredir.akadns.net. 3307 IN CNAME e6858.dscx.akamaiedge.net. 11788 // RRSIG 1 for www.apple.com. CNAME 11789 // RRSIG 2 for www.apple.com. CNAME 11790 // RRSIG for www.apple.com.edgekey.net. CNAME 11791 // RRSIG for www.apple.com.edgekey.net.globalredir.akadns.net. CNAME 11792 // e6858.dscx.akamaiedge.net. 6 IN A 104.123.204.248 11793 // RRSIG for e6858.dscx.akamaiedge.net. A 11794 // ============================================================================================================= 11795 11796 // Instead of treating the response as a single response set with 9 records inside. 11797 // It should be treated as 4 different responses: 11798 // ============================================================================================================= 11799 // www.apple.com. 300 IN CNAME www.apple.com.edgekey.net. 11800 // RRSIG 1 for www.apple.com. CNAME 11801 // RRSIG 2 for www.apple.com. CNAME 11802 // ============================================================================================================= 11803 11804 // ============================================================================================================= 11805 // www.apple.com.edgekey.net. 17716 IN CNAME www.apple.com.edgekey.net.globalredir.akadns.net. 11806 // RRSIG for www.apple.com.edgekey.net. CNAME 11807 // ============================================================================================================= 11808 11809 // ============================================================================================================= 11810 // www.apple.com.edgekey.net.globalredir.akadns.net. 3307 IN CNAME e6858.dscx.akamaiedge.net. 11811 // RRSIG for www.apple.com.edgekey.net.globalredir.akadns.net. CNAME 11812 // ============================================================================================================= 11813 11814 // ============================================================================================================= 11815 // e6858.dscx.akamaiedge.net. 6 IN A 104.123.204.248 11816 // RRSIG for e6858.dscx.akamaiedge.net. A 11817 // ============================================================================================================= 11818 11819 // A similar example can be found when mDNSResponder receives a MX response that contains the A/AAAA records of 11820 // the MX name. The A/AAAA record set needs to be separated with the MX record set. Therefore, we need to count 11821 // the record set size that has the same name and same type, including the RRSIG that covers the same type. 11822 11823 const mDNSBool toBeDNSSECValidated = (!ResponseIsMDNS) && 11824 ( 11825 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11826 (querier != mDNSNULL) ? 11827 (mdns_querier_get_dnssec_ok(querier) && mdns_querier_get_checking_disabled(querier)) : 11828 #endif 11829 mDNSfalse 11830 ); 11831 11832 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11833 11834 for (i = 0; i < totalrecords && ptr && ptr < end; i++) 11835 { 11836 // All responses sent via LL multicast are acceptable for caching 11837 // All responses received over our outbound TCP connections are acceptable for caching 11838 // We accept all records in a unicast response to a multicast query once we find one that 11839 // answers an active question. 11840 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11841 mDNSBool AcceptableResponse = ResponseMCast || (!client && !dstaddr) || LLQType || recordAcceptedInResponse; 11842 #else 11843 mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType || recordAcceptedInResponse; 11844 #endif 11845 // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer 11846 // to any specific question -- any code reading records from the cache needs to make that determination for itself.) 11847 11848 const mDNSu8 RecordType = 11849 (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns : 11850 (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd; 11851 ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec); 11852 mdns_require_quiet(ptr, bail); // Break out of the loop and clean up our CacheFlushRecords list before exiting 11853 11854 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 11855 // If the message being processed is a true mDNS message, i.e., it was received via the mDNS protocol, then 11856 // don't cache the record if there's already a Discovery Proxy subscription for the resource record set because 11857 // the Discovery Proxy is our current source of truth. 11858 if (DPCFeatureEnabled() && ResponseIsMDNS && !subscriber) 11859 { 11860 const ResourceRecord *const rr = &m->rec.r.resrec; 11861 if (DPCHaveSubscriberForRecord(InterfaceID, rr->name, rr->rrtype, rr->rrclass)) 11862 { 11863 mDNSCoreResetRecord(m); 11864 continue; 11865 } 11866 } 11867 #endif 11868 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11869 if (querier || subscriber) 11870 { 11871 if (!cache_metadata) 11872 { 11873 cache_metadata = mdns_cache_metadata_create(); 11874 if (querier) 11875 { 11876 mdns_resolver_type_t resolver_type = mdns_querier_get_resolver_type(querier); 11877 if (resolver_type == mdns_resolver_type_normal) 11878 { 11879 if (mdns_querier_get_over_tcp_reason(querier) != mdns_query_over_tcp_reason_null) 11880 { 11881 resolver_type = mdns_resolver_type_tcp; 11882 } 11883 } 11884 mdns_cache_metadata_set_protocol(cache_metadata, resolver_type); 11885 mdns_cache_metadata_set_extended_dns_error(cache_metadata, mdns_querier_get_extended_dns_error(querier)); 11886 } 11887 if (subscriber) 11888 { 11889 mdns_cache_metadata_set_subscriber_id(cache_metadata, mdns_subscriber_get_id(subscriber)); 11890 } 11891 mdns_cache_metadata_set_dns_service(cache_metadata, uDNSService); 11892 } 11893 ResourceRecord *const rr = &m->rec.r.resrec; 11894 mdns_replace(&rr->metadata, cache_metadata); 11895 } 11896 #endif 11897 if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative) 11898 { 11899 mDNSCoreResetRecord(m); 11900 continue; 11901 } 11902 11903 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 11904 // Mark the parsed record as DNSSEC-aware(can be used for DNSSEC validation) if it applies. 11905 if (toBeDNSSECValidated) 11906 { 11907 m->rec.r.resrec.dnssec = dnssec_obj_resource_record_member_create_to_validate(mDNStrue, &m->rec.r, NULL); 11908 } 11909 #endif 11910 11911 // Don't want to cache OPT or TSIG pseudo-RRs 11912 if (m->rec.r.resrec.rrtype == kDNSType_TSIG) 11913 { 11914 mDNSCoreResetRecord(m); 11915 continue; 11916 } 11917 if (m->rec.r.resrec.rrtype == kDNSType_OPT) 11918 { 11919 const rdataOPT *opt; 11920 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength]; 11921 // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently 11922 // delete all our own AuthRecords (which are identified by having zero MAC tags on them). 11923 for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++) 11924 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0]) 11925 { 11926 ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords); 11927 ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords); 11928 } 11929 mDNSCoreResetRecord(m); 11930 continue; 11931 } 11932 // if a CNAME record points to itself, then don't add it to the cache 11933 if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name)) 11934 { 11935 LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c); 11936 mDNSCoreResetRecord(m); 11937 continue; 11938 } 11939 11940 // When we receive uDNS LLQ responses, we assume a long cache lifetime -- 11941 // In the case of active LLQs, we'll get remove events when the records actually do go away 11942 // In the case of polling LLQs, we assume the record remains valid until the next poll 11943 if (!ResponseIsMDNS) 11944 { 11945 m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl); 11946 } 11947 11948 // If response was not sent via LL multicast, 11949 // then see if it answers a recent query of ours, which would also make it acceptable for caching. 11950 if (!ResponseMCast) 11951 { 11952 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 11953 if (LLQType) 11954 { 11955 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set. 11956 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the 11957 // queries to get ADD/RMV events. To lookup the question, we can't use 11958 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose 11959 // has already matched the question using the 64 bit Id in the packet and we use that here. 11960 11961 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11962 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer; 11963 #endif 11964 } 11965 else 11966 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 11967 11968 if (!AcceptableResponse || !dstaddr) 11969 { 11970 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries 11971 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr. 11972 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that 11973 // we create. 11974 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 11975 if (client) 11976 { 11977 ResourceRecord *const rr = &m->rec.r.resrec; 11978 if (Client_ResourceRecordIsAnswer(rr, client)) 11979 { 11980 AcceptableResponse = mDNStrue; 11981 } 11982 } 11983 else 11984 #endif 11985 { 11986 const DNSQuestion *q; 11987 // Initialize the DNS server on the resource record which will now filter what questions we answer with 11988 // this record. 11989 // 11990 // We could potentially lookup the DNS server based on the source address, but that may not work always 11991 // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came 11992 // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based 11993 // on the "id" and "source port", then this response answers the question and assume the response 11994 // came from the same DNS server that we sent the query to. 11995 q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr); 11996 if (q != mDNSNULL) 11997 { 11998 AcceptableResponse = mDNStrue; 11999 if (!InterfaceID) 12000 { 12001 debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype)); 12002 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 12003 m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer; 12004 #endif 12005 } 12006 else 12007 { 12008 // Accept all remaining records in this unicast response to an mDNS query. 12009 recordAcceptedInResponse = mDNStrue; 12010 // Response that is a unicast assisted mDNS Response should be logged. 12011 dumpMDNSPacket = mDNStrue; 12012 } 12013 } 12014 else 12015 { 12016 // If we can't find a matching question, we need to see whether we have seen records earlier that matched 12017 // the question. The code below does that. So, make this record unacceptable for now 12018 if (!InterfaceID) 12019 { 12020 debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c); 12021 AcceptableResponse = mDNSfalse; 12022 } 12023 } 12024 } 12025 } 12026 } 12027 else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A) 12028 { 12029 // There are some routers (rare, thankfully) that generate bogus ARP responses for 12030 // any IPv4 address they dont recognize, including RFC 3927 IPv4 link-local addresses. 12031 // To work with these broken routers, client devices need to blacklist these broken 12032 // routers and ignore their bogus ARP responses. Some devices implement a technique 12033 // such as the one described in US Patent 7436783, which lets clients detect and 12034 // ignore these broken routers: <https://www.google.com/patents/US7436783> 12035 12036 // OS X and iOS do not implement this defensive mechanism, instead taking a simpler 12037 // approach of just detecting these broken routers and completely disabling IPv4 12038 // link-local communication on interfaces where a broken router is detected. 12039 // OS X and iOS set the IFEF_ARPLL interface flag on interfaces 12040 // that are deemed safe for IPv4 link-local communication; 12041 // the flag is cleared on interfaces where a broken router is detected. 12042 12043 // OS X and iOS will not even try to communicate with an IPv4 12044 // link-local destination on an interface without the IFEF_ARPLL flag set. 12045 // This can cause some badly written applications to freeze for a long time if they 12046 // attempt to connect to an IPv4 link-local destination address and then wait for 12047 // that connection attempt to time out before trying other candidate addresses. 12048 12049 // To mask this client bug, we suppress acceptance of IPv4 link-local address 12050 // records on interfaces where we know the OS will be unwilling even to attempt 12051 // communication with those IPv4 link-local destination addresses. 12052 // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL 12053 12054 const CacheRecord *const rr = &m->rec.r; 12055 const RDataBody2 *const rdb = (const RDataBody2 *)rr->smallrdatastorage.data; 12056 if (mDNSv4AddressIsLinkLocal(&rdb->ipv4)) 12057 { 12058 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r)); 12059 mDNSCoreResetRecord(m); 12060 continue; 12061 } 12062 } 12063 12064 // 1. Check that this packet resource record does not conflict with any of ours 12065 if (ResponseIsMDNS && m->rec.r.resrec.rrtype != kDNSType_NSEC) 12066 { 12067 if (m->CurrentRecord) 12068 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 12069 m->CurrentRecord = m->ResourceRecords; 12070 while (m->CurrentRecord) 12071 { 12072 AuthRecord *rr = m->CurrentRecord; 12073 m->CurrentRecord = rr->next; 12074 // We accept all multicast responses, and unicast responses resulting from queries we issued 12075 // For other unicast responses, this code accepts them only for responses with an 12076 // (apparently) local source address that pertain to a record of our own that's in probing state 12077 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue; 12078 12079 if (PacketRRMatchesSignature(&m->rec.r, rr)) // If interface, name, type (if shared record) and class match... 12080 { 12081 if ((curTSRForName = TSRForNameFromDataRec(&tsrs, m->rec.r.resrec.name)) != mDNSNULL) 12082 { 12083 eTSRCheckResult tsrResult = CheckTSRForAuthRecord(m, curTSRForName, rr); 12084 if (tsrResult == eTSRCheckLose) 12085 { 12086 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12087 "mDNSCoreReceiveResponse - deregistering " PRI_DM_NAME " type " PUB_S " on interface %d due to TSR conflict", 12088 DM_NAME_PARAM(rr->resrec.name), DNSTypeName(rr->resrec.rrtype), (int)IIDPrintable(InterfaceID)); 12089 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 12090 // See if this record was also registered with any D2D plugins. 12091 D2D_stop_advertising_record(rr); 12092 #endif 12093 mDNS_Deregister_internal(m, rr, mDNS_Dereg_stale); 12094 } 12095 12096 if (tsrResult != eTSRCheckNoKeyMatch) // No else 12097 { 12098 continue; 12099 } 12100 } 12101 // ... check to see if type and rdata are identical 12102 if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec)) 12103 { 12104 // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us 12105 if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState) 12106 { 12107 // If we were planning to send on this -- and only this -- interface, then we don't need to any more 12108 if (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; } 12109 } 12110 else 12111 { 12112 if (rr->ImmedAnswer == mDNSNULL) { rr->ImmedAnswer = InterfaceID; m->NextScheduledResponse = m->timenow; } 12113 else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; } 12114 } 12115 } 12116 // else, the packet RR has different type or different rdata -- check to see if this is a conflict 12117 else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r)) 12118 { 12119 // Having a possible conflict, we should log the packet to check why it has possible 12120 // conflicts with us later. 12121 dumpMDNSPacket = mDNStrue; 12122 12123 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12124 "mDNSCoreReceiveResponse: Pkt Record: %08X " PRI_S " (interface %d)", 12125 m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r), IIDPrintable(InterfaceID)); 12126 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12127 "mDNSCoreReceiveResponse: Our Record: %08X " PRI_S, rr->resrec.rdatahash, 12128 ARDisplayString(m, rr)); 12129 12130 // If this record is marked DependentOn another record for conflict detection purposes, 12131 // then *that* record has to be bumped back to probing state to resolve the conflict 12132 if (rr->DependentOn) 12133 { 12134 while (rr->DependentOn) rr = rr->DependentOn; 12135 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12136 "mDNSCoreReceiveResponse: Dep Record: %08X " PRI_S, rr->resrec.rdatahash, 12137 ARDisplayString(m, rr)); 12138 } 12139 12140 // If we've just whacked this record's ProbeCount, don't need to do it again 12141 if (rr->ProbeCount > DefaultProbeCountForTypeUnique) 12142 { 12143 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12144 "mDNSCoreReceiveResponse: Already reset to Probing: " PRI_S, ARDisplayString(m, rr)); 12145 } 12146 else if (rr->ProbeCount == DefaultProbeCountForTypeUnique) 12147 { 12148 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12149 "mDNSCoreReceiveResponse: Ignoring response received before we even began probing: " PRI_S, 12150 ARDisplayString(m, rr)); 12151 } 12152 else 12153 { 12154 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12155 "mDNSCoreReceiveResponse: Received from " PRI_IP_ADDR ":%d " PRI_S, srcaddr, 12156 mDNSVal16(srcport), CRDisplayString(m, &m->rec.r)); 12157 // If we'd previously verified this record, put it back to probing state and try again 12158 if (rr->resrec.RecordType == kDNSRecordTypeVerified) 12159 { 12160 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12161 "mDNSCoreReceiveResponse: Resetting to Probing: " PRI_S, ARDisplayString(m, rr)); 12162 rr->resrec.RecordType = kDNSRecordTypeUnique; 12163 // We set ProbeCount to one more than the usual value so we know we've already touched this record. 12164 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and 12165 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts. 12166 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries(). 12167 rr->ProbeCount = DefaultProbeCountForTypeUnique + 1; 12168 rr->AnnounceCount = InitialAnnounceCount; 12169 InitializeLastAPTime(m, rr); 12170 RecordProbeFailure(m, rr); // Repeated late conflicts also cause us to back off to the slower probing rate 12171 } 12172 // If we're probing for this record, we just failed 12173 else if (rr->resrec.RecordType == kDNSRecordTypeUnique) 12174 { 12175 // At this point in the code, we're probing for uniqueness. 12176 // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique) 12177 // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique). 12178 // Before we call deregister, check if this is a packet we registered with the sleep proxy. 12179 if (!mDNSCoreRegisteredProxyRecord(m, rr)) 12180 { 12181 if ((rr->ProbingConflictCount == 0) || (m->MPktNum != rr->LastConflictPktNum)) 12182 { 12183 const NetworkInterfaceInfo *const intf = FirstInterfaceForID(m, InterfaceID); 12184 rr->ProbingConflictCount++; 12185 rr->LastConflictPktNum = m->MPktNum; 12186 if (ResponseMCast && (!intf || intf->SupportsUnicastMDNSResponse) && 12187 (rr->ProbingConflictCount <= kMaxAllowedMCastProbingConflicts)) 12188 { 12189 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12190 "mDNSCoreReceiveResponse: ProbeCount %u; " 12191 "restarting probing after %u-tick pause due to possibly " 12192 "spurious multicast conflict (%d/%u) via interface %d for " PRI_S, 12193 rr->ProbeCount, kProbingConflictPauseDuration, rr->ProbingConflictCount, 12194 kMaxAllowedMCastProbingConflicts, IIDPrintable(InterfaceID), 12195 ARDisplayString(m, rr)); 12196 12197 rr->ProbeCount = DefaultProbeCountForTypeUnique; 12198 rr->LastAPTime = m->timenow + kProbingConflictPauseDuration - rr->ThisAPInterval; 12199 SetNextAnnounceProbeTime(m, rr); 12200 } 12201 else 12202 { 12203 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12204 "mDNSCoreReceiveResponse: ProbeCount %u; " 12205 "will deregister " PRI_S " due to " PUB_S "cast conflict via interface %d", 12206 rr->ProbeCount, ARDisplayString(m, rr), ResponseMCast ? "multi" : "uni", 12207 IIDPrintable(InterfaceID)); 12208 12209 m->mDNSStats.NameConflicts++; 12210 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 12211 // See if this record was also registered with any D2D plugins. 12212 D2D_stop_advertising_record(rr); 12213 #endif 12214 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict); 12215 } 12216 } 12217 } 12218 } 12219 // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the 12220 // same machine giving different answers for the reverse mapping record, or there are two machines on the 12221 // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do 12222 // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our 12223 // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life. 12224 else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique) 12225 { 12226 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 12227 "mDNSCoreReceiveResponse: Unexpected conflict discarding " PRI_S, 12228 ARDisplayString(m, rr)); 12229 12230 m->mDNSStats.KnownUniqueNameConflicts++; 12231 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 12232 D2D_stop_advertising_record(rr); 12233 #endif 12234 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict); 12235 } 12236 else 12237 { 12238 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, 12239 "mDNSCoreReceiveResponse: Unexpected record type %X " PRI_S, 12240 rr->resrec.RecordType, ARDisplayString(m, rr)); 12241 } 12242 } 12243 } 12244 // Else, matching signature, different type or rdata, but not a considered a conflict. 12245 // If the packet record has the cache-flush bit set, then we check to see if we 12246 // have any record(s) of the same type that we should re-assert to rescue them 12247 // (see note about "multi-homing and bridged networks" at the end of this function). 12248 else if ((m->rec.r.resrec.rrtype == rr->resrec.rrtype) && 12249 (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && 12250 ((mDNSu32)(m->timenow - rr->LastMCTime) > (mDNSu32)mDNSPlatformOneSecond/2) && 12251 ResourceRecordIsValidAnswer(rr)) 12252 { 12253 rr->ImmedAnswer = mDNSInterfaceMark; 12254 m->NextScheduledResponse = m->timenow; 12255 } 12256 } 12257 } 12258 } 12259 12260 if (!AcceptableResponse) 12261 { 12262 AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords); 12263 12264 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 12265 if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer; 12266 #endif 12267 } 12268 12269 CacheGroup *cg = mDNSNULL; 12270 if (AcceptableResponse && 12271 (curTSRForName = TSRForNameFromDataRec(&tsrs, m->rec.r.resrec.name)) != mDNSNULL) 12272 { 12273 cg = CacheGroupForRecord(m, &m->rec.r.resrec); 12274 if (cg) 12275 { 12276 CacheRecord *ourTSR = mDNSGetTSRForCacheGroup(cg); 12277 if (ourTSR) 12278 { 12279 eTSRCheckResult tsrResult = CheckTSRForResourceRecord(curTSRForName, &ourTSR->resrec); 12280 if (tsrResult == eTSRCheckWin) 12281 { 12282 AcceptableResponse = mDNSfalse; 12283 } 12284 else if (tsrResult == eTSRCheckLose) 12285 { 12286 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12287 "mDNSCoreReceiveResponse - flushing cache group " PRI_DM_NAME " type " PUB_S " on interface %d due to TSR conflict", 12288 DM_NAME_PARAM(m->rec.r.resrec.name), DNSTypeName(m->rec.r.resrec.rrtype), (int)IIDPrintable(InterfaceID)); 12289 CacheRecord *cr; 12290 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 12291 { 12292 if (cr->resrec.rrtype != kDNSType_OPT) 12293 { 12294 mDNS_PurgeCacheResourceRecord(m, cr); 12295 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 12296 "mDNSCoreReceiveResponse - flushed interface %d " PRI_S, 12297 (int)IIDPrintable(cr->resrec.InterfaceID), CRDisplayString(m, cr)); 12298 } 12299 } 12300 } 12301 } 12302 if (AcceptableResponse) 12303 { 12304 AddOrUpdateTSRForCacheGroup(m, curTSRForName, cg, ourTSR, m->rec.r.resrec.rroriginalttl); 12305 } 12306 } 12307 } 12308 12309 // 2. See if we want to add this packet resource record to our cache 12310 // We only try to cache answers if we have a cache to put them in 12311 // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query 12312 if (m->rrcache_size && AcceptableResponse) 12313 { 12314 const mDNSu32 slot = HashSlotFromNameHash(m->rec.r.resrec.namehash); 12315 if (!cg) 12316 { 12317 cg = CacheGroupForRecord(m, &m->rec.r.resrec); 12318 } 12319 CacheRecord *rr = mDNSNULL; 12320 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12321 // Set to true if no new cache record has been created for the response, either due to existing cached 12322 // record refresh or the reason that the new response is a subset of the previous one. 12323 mDNSBool newRecordAdded = mDNSfalse; 12324 #endif 12325 12326 // 2a. Check if this packet resource record is already in our cache. 12327 rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, &cfp, InterfaceID); 12328 12329 // If packet resource record not in our cache, add it now 12330 // (unless it is just a deletion of a record we never had, in which case we don't care) 12331 if (!rr && m->rec.r.resrec.rroriginalttl > 0) 12332 { 12333 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events); 12334 mDNSs32 delay; 12335 12336 if (AddToCFList) 12337 delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond); 12338 else 12339 delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash); 12340 12341 CreateNewCacheEntryFlags flags = kCreateNewCacheEntryFlagsNone; 12342 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12343 if (toBeDNSSECValidated) 12344 { 12345 flags |= kCreateNewCacheEntryFlagsDNSSECRRToValidate; 12346 } 12347 #endif 12348 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 12349 if (subscriber) 12350 { 12351 flags |= kCreateNewCacheEntryFlagsDNSPushSubscribed; 12352 } 12353 #endif 12354 // If unique, assume we may have to delay delivery of this 'add' event. 12355 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd() 12356 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime() 12357 // to schedule an mDNS_Execute task at the appropriate time. 12358 rr = CreateNewCacheEntryEx(m, slot, cg, delay, mDNStrue, srcaddr, flags); 12359 if (rr) 12360 { 12361 CacheRecordSetResponseFlags(rr, response->h.flags); 12362 if (AddToCFList) 12363 { 12364 *cfp = rr; 12365 cfp = &rr->NextInCFList; 12366 *cfp = (CacheRecord*)1; 12367 } 12368 else if (rr->DelayDelivery) 12369 { 12370 ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery); 12371 } 12372 12373 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12374 newRecordAdded = mDNStrue; 12375 #endif 12376 } 12377 } 12378 12379 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12380 if (!ResponseIsMDNS) // Only count the answer number for unicast response. 12381 { 12382 // Do not increment the counter if rr is not in the cache (either newly added or existing). 12383 if (rr == mDNSNULL) 12384 { 12385 goto record_set_tracking_exit; 12386 } 12387 // Do not increment the counter if rr is a negative record. 12388 if (rr->resrec.rroriginalttl == 0) 12389 { 12390 goto record_set_tracking_exit; 12391 } 12392 12393 // Do not read/write out of bound for the arrays. 12394 if (numOfCachedRecords == countof(cachedRecords) || 12395 numOfRecordSets == countof(recordSets)) 12396 { 12397 goto record_set_tracking_exit; 12398 } 12399 12400 // Save the record pointer in a temporary array. 12401 // Mark the record as "ineligible for cache recycling" because we will save the pointer to a temporary 12402 // array in mDNSCoreReceiveResponse(). If the saved pointer is recycled while we are still looping 12403 // through the records in the response, we will crash if we try to deference the recycled records later. 12404 rr->ineligibleForRecycling = mDNStrue; 12405 cachedRecords[numOfCachedRecords] = rr; 12406 numOfCachedRecords++; 12407 12408 RecordSet *recordSet = mDNSNULL; 12409 for (mDNSu32 k = 0; k < numOfRecordSets; k++) 12410 { 12411 if (!RecordInTheRRSet(&rr->resrec, &recordSets[k])) 12412 { 12413 continue; 12414 } 12415 12416 recordSet = &recordSets[k]; 12417 break; 12418 } 12419 12420 if (recordSet == mDNSNULL) 12421 { 12422 recordSet = &recordSets[numOfRecordSets]; 12423 numOfRecordSets++; 12424 12425 recordSet->name = rr->resrec.name; 12426 recordSet->namehash = rr->resrec.namehash; 12427 if (rr->resrec.rrtype != kDNSType_RRSIG) 12428 { 12429 recordSet->rrtype = rr->resrec.rrtype; 12430 } 12431 else 12432 { 12433 recordSet->rrtype = resource_record_as_rrsig_get_covered_type(&rr->resrec); 12434 } 12435 12436 recordSet->sizeOfRecordSet = 0; 12437 recordSet->noNewCachedRecordAdded = mDNSfalse; 12438 } 12439 12440 recordSet->sizeOfRecordSet++; 12441 recordSet->noNewCachedRecordAdded = newRecordAdded; 12442 12443 record_set_tracking_exit: 12444 (void)0; // No-op for the label above. 12445 } 12446 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12447 } 12448 mDNSCoreResetRecord(m); 12449 } 12450 TSRDataRecHeadFreeList(&tsrs); 12451 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12452 // After finishing processing all the records in the response, update the corresponding fields for the records 12453 // in the cache. 12454 if (!ResponseIsMDNS) // Only count the answer number for the unicast response. 12455 { 12456 if (numOfCachedRecords == countof(cachedRecords) || 12457 numOfRecordSets == countof(recordSets)) 12458 { 12459 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_FAULT, "Too many records contained in a single response - " 12460 "cached records: %u, record set: %u", numOfCachedRecords, numOfRecordSets); 12461 } 12462 12463 for (mDNSu32 k = 0; k < numOfCachedRecords; k++) 12464 { 12465 CacheRecord *const record = cachedRecords[k]; 12466 12467 // Ensure that the max number of records in a response can be represented by numOfCachedRecords. 12468 mdns_compile_time_check_local(countof(cachedRecords) < UINT8_MAX); 12469 12470 const RecordSet *recordSet = mDNSNULL; 12471 for (mDNSu32 kk = 0; kk < numOfRecordSets; kk++) 12472 { 12473 if (!RecordInTheRRSet(&record->resrec, &recordSets[kk])) 12474 { 12475 continue; 12476 } 12477 12478 recordSet = &recordSets[kk]; 12479 break; 12480 } 12481 12482 if (recordSet == mDNSNULL) 12483 { 12484 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_FAULT, 12485 "Answer set counter not found for the cached record - name: " PRI_DM_NAME ", rrtype: " PRI_S ".", 12486 DM_NAME_PARAM(record->resrec.name), DNSTypeName(record->resrec.rrtype)); 12487 continue; 12488 } 12489 12490 if (record->resrec.dnssec != NULL) 12491 { 12492 dnssec_obj_resource_record_member_set_rrset_size(record->resrec.dnssec, recordSet->sizeOfRecordSet); 12493 dnssec_obj_resource_record_member_set_no_new_rr_added(record->resrec.dnssec, recordSet->noNewCachedRecordAdded); 12494 } 12495 } 12496 } 12497 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12498 12499 if (dumpMDNSPacket) 12500 { 12501 DumpPacket(mStatus_NoError, mDNSfalse, "N/A", srcaddr, srcport, dstaddr, dstport, response, end, InterfaceID); 12502 } 12503 12504 bail: 12505 mDNSCoreResetRecord(m); 12506 12507 // If we've just received one or more records with their cache flush bits set, 12508 // then scan that cache slot to see if there are any old stale records we need to flush 12509 while (CacheFlushRecords != (CacheRecord*)1) 12510 { 12511 CacheRecord *r1 = CacheFlushRecords, *r2; 12512 const mDNSu32 slot = HashSlotFromNameHash(r1->resrec.namehash); 12513 const CacheGroup *cg = CacheGroupForRecord(m, &r1->resrec); 12514 mDNSBool purgedRecords = mDNSfalse; 12515 CacheFlushRecords = CacheFlushRecords->NextInCFList; 12516 r1->NextInCFList = mDNSNULL; 12517 12518 // Look for records in the cache with the same signature as this new one with the cache flush 12519 // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL 12520 // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second. 12521 // We make these TTL adjustments *only* for records that still have *more* than one second 12522 // remaining to live. Otherwise, a record that we tagged for deletion half a second ago 12523 // (and now has half a second remaining) could inadvertently get its life extended, by either 12524 // (a) if we got an explicit goodbye packet half a second ago, the record would be considered 12525 // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet, 12526 // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire 12527 // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it. 12528 // If this were to happen repeatedly, the record's expiration could be deferred indefinitely. 12529 // To avoid this, we need to ensure that the cache flushing operation will only act to 12530 // *decrease* a record's remaining lifetime, never *increase* it. 12531 // Additional condition to check: a response comes from subscriber does not flush previous records, so skip it. 12532 for (r2 = cg ? cg->members : mDNSNULL; r2 && !subscriberResponse; r2=r2->next) 12533 { 12534 mDNSBool proceed = mDNStrue; 12535 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 12536 // Push subscribed records will never be flushed by a response (except "remove" push notification). 12537 proceed = proceed && !r2->DNSPushSubscribed; 12538 #endif 12539 proceed = proceed && SameNameCacheRecordsMatchInSourceTypeClass(r1, r2); 12540 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12541 proceed = proceed && resource_records_is_comparable_for_dnssec(&r1->resrec, &r2->resrec); 12542 #endif 12543 12544 if (proceed) 12545 { 12546 if (r1->resrec.mortality == Mortality_Mortal && r2->resrec.mortality != Mortality_Mortal) 12547 { 12548 verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1, r2); 12549 r1->resrec.mortality = Mortality_Immortal; // Immortalize the replacement record 12550 } 12551 12552 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics) 12553 // else, if record is old, mark it to be flushed 12554 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond) 12555 { 12556 // If we find mismatched TTLs in an RRSet, correct them. 12557 // We only do this for records with a TTL of 2 or higher. It's possible to have a 12558 // goodbye announcement with the cache flush bit set (or a case-change on record rdata, 12559 // which we treat as a goodbye followed by an addition) and in that case it would be 12560 // inappropriate to synchronize all the other records to a TTL of 0 (or 1). 12561 12562 // We suppress the message for the specific case of correcting from 240 to 60 for type TXT, 12563 // because certain early Bonjour devices are known to have this specific mismatch, and 12564 // there's no point filling syslog with messages about something we already know about. 12565 // We also don't log this for uDNS responses, since a caching name server is obliged 12566 // to give us an aged TTL to correct for how long it has held the record, 12567 // so our received TTLs are expected to vary in that case 12568 12569 // We also suppress log message in the case of SRV records that are received 12570 // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since 12571 // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8 12572 // GM builds. 12573 if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1) 12574 { 12575 if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) && 12576 !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) && 12577 ResponseIsMDNS) 12578 { 12579 static mDNSs32 lastLogWindowStartTime = 0; 12580 static mDNSu32 count = 0; 12581 12582 mDNSBool reset = mDNSfalse; 12583 if (lastLogWindowStartTime != 0) 12584 { 12585 const mDNSu32 elapsedTicks = (mDNSu32)(m->timenow - lastLogWindowStartTime); 12586 const mDNSu32 limitTicks = MDNS_SECONDS_PER_HOUR * mDNSPlatformOneSecond; 12587 if (elapsedTicks >= limitTicks) 12588 { 12589 reset = mDNStrue; 12590 } 12591 } 12592 else 12593 { 12594 reset = mDNStrue; 12595 } 12596 if (reset) 12597 { 12598 count = 0; 12599 lastLogWindowStartTime = NonZeroTime(m->timenow); 12600 } 12601 12602 const mDNSu32 ttlCorrectingLogRateLimitCount = 100; 12603 const mDNSBool rateLimiting = (count >= ttlCorrectingLogRateLimitCount); 12604 count++; 12605 12606 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, rateLimiting ? MDNS_LOG_DEBUG : MDNS_LOG_INFO, 12607 "Correcting TTL from %4u to %4u from " PRI_IP_ADDR ":%u for records " PRI_S, 12608 r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, srcaddr, mDNSVal16(srcport), 12609 CRDisplayString(m, r2)); 12610 } 12611 r2->resrec.rroriginalttl = r1->resrec.rroriginalttl; 12612 } 12613 r2->TimeRcvd = m->timenow; 12614 SetNextCacheCheckTimeForRecord(m, r2); 12615 } 12616 else if (r2->resrec.InterfaceID) // else, if record is old, mark it to be flushed 12617 { 12618 verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1)); 12619 verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2)); 12620 #if MDNSRESPONDER_SUPPORTS(APPLE, AWDL_FAST_CACHE_FLUSH) 12621 if (mDNSPlatformInterfaceIsAWDL(r2->resrec.InterfaceID)) 12622 { 12623 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, 12624 "Fast flushing AWDL cache record -- age: %d ticks, expire: %d ticks, record: " PRI_S, 12625 m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2)); 12626 mDNS_PurgeCacheResourceRecord(m, r2); 12627 } 12628 else 12629 #endif 12630 { 12631 // We set stale records to expire in one second. 12632 // This gives the owner a chance to rescue it if necessary. 12633 // This is important in the case of multi-homing and bridged networks: 12634 // Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be 12635 // bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit 12636 // set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet 12637 // will promptly delete their cached copies of the (still valid) Ethernet IP address record. 12638 // By delaying the deletion by one second, we give X a change to notice that this bridging has 12639 // happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches. 12640 12641 // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary 12642 // final expiration queries for this record. 12643 12644 // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache 12645 // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual 12646 // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates. 12647 // <rdar://problem/5636422> Updating TXT records is too slow 12648 // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above, 12649 // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0. 12650 if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries) 12651 { 12652 LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2)); 12653 r2->resrec.rroriginalttl = 0; 12654 } 12655 else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond) 12656 { 12657 // We only set a record to expire in one second if it currently has *more* than a second to live 12658 // If it's already due to expire in a second or less, we just leave it alone 12659 r2->resrec.rroriginalttl = 1; 12660 r2->UnansweredQueries = MaxUnansweredQueries; 12661 r2->TimeRcvd = m->timenow - 1; 12662 // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records 12663 // that we marked for deletion via an explicit DE record 12664 } 12665 SetNextCacheCheckTimeForRecord(m, r2); 12666 } 12667 } 12668 else 12669 { 12670 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12671 // Update the sizeOfRRSet counter of the records that will be flushed to reflect the 12672 // response changes, which will be noticed by the callback function. 12673 12674 // Only update positive record state, negative record will be handled in 12675 // mDNSCoreReceiveNoUnicastAnswers(). 12676 if (!ResponseIsMDNS && resource_record_is_positive(&r2->resrec)) 12677 { 12678 const RecordSet *recordSet = mDNSNULL; 12679 for (mDNSu32 kk = 0; kk < numOfRecordSets; kk++) 12680 { 12681 if (!RecordInTheRRSet(&r2->resrec, &recordSets[kk])) 12682 { 12683 continue; 12684 } 12685 recordSet = &recordSets[kk]; 12686 break; 12687 } 12688 12689 if (recordSet == mDNSNULL) 12690 { 12691 // If we cannot find the records with the same name and type, then it means the records set 12692 // has been marked as expired by the authoritative DNS server. Therefore, there will be 12693 // 0 answer added (sizeOfRRSet == 0), and we do not need to wait for an add 12694 // event(noNewRRAdded == mDNStrue). 12695 if (r2->resrec.dnssec != NULL) 12696 { 12697 dnssec_obj_resource_record_member_set_rrset_size(r2->resrec.dnssec, 0); 12698 dnssec_obj_resource_record_member_set_no_new_rr_added(r2->resrec.dnssec, mDNStrue); 12699 } 12700 } 12701 else 12702 { 12703 if (r2->resrec.dnssec != NULL) 12704 { 12705 dnssec_obj_resource_record_member_set_rrset_size(r2->resrec.dnssec, recordSet->sizeOfRecordSet); 12706 dnssec_obj_resource_record_member_set_no_new_rr_added(r2->resrec.dnssec, recordSet->noNewCachedRecordAdded); 12707 } 12708 } 12709 } 12710 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12711 12712 // Old uDNS records are scheduled to be purged instead of given at most one second to live. 12713 mDNS_PurgeCacheResourceRecord(m, r2); 12714 purgedRecords = mDNStrue; 12715 } 12716 } 12717 } 12718 12719 if (r1->DelayDelivery) // If we were planning to delay delivery of this record, see if we still need to 12720 { 12721 if (r1->resrec.InterfaceID) 12722 { 12723 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash); 12724 } 12725 else 12726 { 12727 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow 12728 // them to be deleted before any ADD events for this record. 12729 mDNSBool delayDelivery = purgedRecords; 12730 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12731 // We always delay the delivery of DNSSEC-aware response to make sure that we generate the corresponding 12732 // negative record for the wildcard answer in mDNSCoreReceiveNoUnicastAnswers(). 12733 delayDelivery = delayDelivery || toBeDNSSECValidated; 12734 #endif 12735 r1->DelayDelivery = delayDelivery ? NonZeroTime(m->timenow) : 0; 12736 } 12737 // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time 12738 if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1); 12739 else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery); 12740 } 12741 } 12742 12743 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 12744 if (!ResponseIsMDNS) 12745 { 12746 for (mDNSu32 k = 0; k < numOfCachedRecords; k++) 12747 { 12748 // Now we have finished the response size counting, the record is now eligible for cache recycling. 12749 cachedRecords[k]->ineligibleForRecycling = mDNSfalse; 12750 } 12751 } 12752 #endif 12753 12754 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 12755 // If this DNS message is constructed from a subscriber with a push service, then skip the negative record handling 12756 // below, because push notification never adds negative records. 12757 if (subscriber) 12758 { 12759 goto exit; 12760 } 12761 #endif 12762 12763 // See if we need to generate negative cache entries for unanswered unicast questions 12764 mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID, 12765 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 12766 querier, uDNSService, 12767 #endif 12768 LLQType); 12769 exit: 12770 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 12771 mdns_forget(&cache_metadata); 12772 #endif 12773 return; 12774 } 12775 12776 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing 12777 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds. 12778 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic 12779 // that warrants waking the sleeping host. 12780 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal) 12781 12782 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist) 12783 { 12784 // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as 12785 // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used 12786 // to send wakeups or goodbyes. See the comment in that function for more details. To keep it 12787 // simple, we use the same mechanism for both lists. 12788 if (!e->l[0]) 12789 { 12790 LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero"); 12791 return; 12792 } 12793 m->CurrentRecord = thelist; 12794 while (m->CurrentRecord) 12795 { 12796 AuthRecord *const rr = m->CurrentRecord; 12797 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e)) 12798 { 12799 LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr)); 12800 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); 12801 } 12802 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now 12803 m->CurrentRecord = rr->next; 12804 } 12805 } 12806 12807 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e) 12808 { 12809 if (!e->l[0]) 12810 { 12811 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "ScheduleWakeup ERROR: Target HMAC is zero"); 12812 return; 12813 } 12814 ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords); 12815 ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords); 12816 } 12817 12818 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result) 12819 { 12820 if (result && result != mStatus_MemFree) 12821 { 12822 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEFAULT, "SPS Callback %d " PRI_S, result, ARDisplayString(m, ar)); 12823 } 12824 12825 if (result == mStatus_NameConflict) 12826 { 12827 mDNS_Lock(m); 12828 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEFAULT, PUB_S " Conflicting mDNS -- waking " PRI_MAC_ADDR " " PRI_S, 12829 InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar)); 12830 if (ar->WakeUp.HMAC.l[0]) 12831 { 12832 SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password, mDNSfalse); // Send one wakeup magic packet 12833 ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC); // Schedule all other records with the same owner to be woken 12834 } 12835 mDNS_Unlock(m); 12836 } 12837 12838 if (result == mStatus_NameConflict || result == mStatus_MemFree) 12839 { 12840 m->ProxyRecords--; 12841 mDNSPlatformMemFree(ar); 12842 mDNS_UpdateAllowSleep(m); 12843 } 12844 } 12845 12846 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth) 12847 { 12848 int i; 12849 mDNSs8 hval = 0; 12850 int colons = 0; 12851 mDNSu8 val = 0; 12852 12853 for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++) 12854 { 12855 hval = HexVal(*ptr); 12856 if (hval != -1) 12857 { 12858 val <<= 4; 12859 val |= hval; 12860 } 12861 else if (*ptr == ':') 12862 { 12863 if (colons >=5) 12864 { 12865 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val); 12866 return mDNSNULL; 12867 } 12868 eth->b[colons] = val; 12869 colons++; 12870 val = 0; 12871 } 12872 } 12873 if (colons != 5) 12874 { 12875 LogMsg("GetValueForMACAddr: Address malformed colons %d", colons); 12876 return mDNSNULL; 12877 } 12878 eth->b[colons] = val; 12879 return ptr; 12880 } 12881 12882 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6) 12883 { 12884 int hval; 12885 int value; 12886 int numBytes; 12887 int digitsProcessed; 12888 int zeroFillStart; 12889 int numColons; 12890 mDNSu8 v6addr[16]; 12891 12892 // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing 12893 // handles both (1) and (2) and does not handle embedded IPv4 addresses. 12894 // 12895 // First forms a address in "v6addr", then expands to fill the zeroes in and returns 12896 // the result in "v6" 12897 12898 numColons = numBytes = value = digitsProcessed = zeroFillStart = 0; 12899 while (ptr < limit && *ptr != ' ') 12900 { 12901 hval = HexVal(*ptr); 12902 if (hval != -1) 12903 { 12904 value <<= 4; 12905 value |= hval; 12906 digitsProcessed = 1; 12907 } 12908 else if (*ptr == ':') 12909 { 12910 if (!digitsProcessed) 12911 { 12912 // If we have already seen a "::", we should not see one more. Handle the special 12913 // case of "::" 12914 if (numColons) 12915 { 12916 // if we never filled any bytes and the next character is space (we have reached the end) 12917 // we are done 12918 if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ') 12919 { 12920 mDNSPlatformMemZero(v6->b, 16); 12921 return ptr + 1; 12922 } 12923 LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart); 12924 return mDNSNULL; 12925 } 12926 12927 // We processed "::". We need to fill zeroes later. For now, mark the 12928 // point where we will start filling zeroes from. 12929 zeroFillStart = numBytes; 12930 numColons++; 12931 } 12932 else if ((ptr + 1) < limit && *(ptr + 1) == ' ') 12933 { 12934 // We have a trailing ":" i.e., no more characters after ":" 12935 LogMsg("GetValueForIPv6Addr: Trailing colon"); 12936 return mDNSNULL; 12937 } 12938 else 12939 { 12940 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while 12941 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly 12942 // filled here is 12 and 13. 12943 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; } 12944 12945 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF); 12946 v6addr[numBytes++] = (mDNSu8) (value & 0xFF); 12947 digitsProcessed = value = 0; 12948 12949 // Make sure that we did not fill the 13th and 14th byte above 12950 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; } 12951 } 12952 } 12953 ptr++; 12954 } 12955 12956 // We should be processing the last set of bytes following the last ":" here 12957 if (!digitsProcessed) 12958 { 12959 LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes); 12960 return mDNSNULL; 12961 } 12962 12963 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; } 12964 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF); 12965 v6addr[numBytes++] = (mDNSu8) (value & 0xFF); 12966 12967 if (zeroFillStart) 12968 { 12969 int i, j, n; 12970 for (i = 0; i < zeroFillStart; i++) 12971 v6->b[i] = v6addr[i]; 12972 for (j = i, n = 0; n < 16 - numBytes; j++, n++) 12973 v6->b[j] = 0; 12974 for (; j < 16; i++, j++) 12975 v6->b[j] = v6addr[i]; 12976 } 12977 else if (numBytes == 16) 12978 mDNSPlatformMemCopy(v6->b, v6addr, 16); 12979 else 12980 { 12981 LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes); 12982 return mDNSNULL; 12983 } 12984 return ptr; 12985 } 12986 12987 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4) 12988 { 12989 mDNSu32 val; 12990 int dots = 0; 12991 val = 0; 12992 12993 for ( ; ptr < limit && *ptr != ' '; ptr++) 12994 { 12995 if (*ptr >= '0' && *ptr <= '9') 12996 val = val * 10 + *ptr - '0'; 12997 else if (*ptr == '.') 12998 { 12999 if (val > 255 || dots >= 3) 13000 { 13001 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); 13002 return mDNSNULL; 13003 } 13004 v4->b[dots++] = (mDNSu8)val; 13005 val = 0; 13006 } 13007 else 13008 { 13009 // We have a zero at the end and if we reached that, then we are done. 13010 if (*ptr == 0 && ptr == limit - 1 && dots == 3) 13011 { 13012 v4->b[dots] = (mDNSu8)val; 13013 return ptr + 1; 13014 } 13015 else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; } 13016 } 13017 } 13018 if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; } 13019 v4->b[dots] = (mDNSu8)val; 13020 return ptr; 13021 } 13022 13023 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value) 13024 { 13025 mDNSu32 val; 13026 13027 val = 0; 13028 for ( ; ptr < limit && *ptr != ' '; ptr++) 13029 { 13030 if (*ptr < '0' || *ptr > '9') 13031 { 13032 // We have a zero at the end and if we reached that, then we are done. 13033 if (*ptr == 0 && ptr == limit - 1) 13034 { 13035 *value = val; 13036 return ptr + 1; 13037 } 13038 else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; } 13039 } 13040 val = val * 10 + *ptr - '0'; 13041 } 13042 *value = val; 13043 return ptr; 13044 } 13045 13046 mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr) 13047 { 13048 mDNSAddr laddr, raddr; 13049 mDNSEthAddr eth; 13050 mDNSIPPort lport, rport; 13051 mDNSu32 timeout, seq, ack; 13052 mDNSu16 win; 13053 13054 if (!mDNS_KeepaliveRecord(&rr->resrec)) 13055 { 13056 return mDNSfalse; 13057 } 13058 13059 timeout = seq = ack = 0; 13060 win = 0; 13061 laddr = raddr = zeroAddr; 13062 lport = rport = zeroIPPort; 13063 eth = zeroEthAddr; 13064 13065 mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); 13066 13067 if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) || 13068 mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) || 13069 mDNSEthAddressIsZero(eth)) 13070 { 13071 return mDNSfalse; 13072 } 13073 13074 return mDNStrue; 13075 } 13076 13077 13078 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq, 13079 mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win) 13080 { 13081 if (ar->resrec.rrtype != kDNSType_NULL) 13082 return; 13083 13084 if (mDNS_KeepaliveRecord(&ar->resrec)) 13085 { 13086 int len = ar->resrec.rdlength; 13087 mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1]; 13088 mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length 13089 mDNSu32 value = 0; 13090 13091 while (ptr < limit) 13092 { 13093 mDNSu8 param = *ptr; 13094 ptr += 2; // Skip the letter and the "=" 13095 if (param == 'h') 13096 { 13097 laddr->type = mDNSAddrType_IPv4; 13098 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4); 13099 } 13100 else if (param == 'd') 13101 { 13102 raddr->type = mDNSAddrType_IPv4; 13103 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4); 13104 } 13105 else if (param == 'H') 13106 { 13107 laddr->type = mDNSAddrType_IPv6; 13108 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6); 13109 } 13110 else if (param == 'D') 13111 { 13112 raddr->type = mDNSAddrType_IPv6; 13113 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6); 13114 } 13115 else if (param == 'm') 13116 { 13117 ptr = GetValueForMACAddr(ptr, limit, eth); 13118 } 13119 else 13120 { 13121 ptr = GetValueForKeepalive(ptr, limit, &value); 13122 } 13123 if (!ptr) 13124 { 13125 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_ExtractKeepaliveInfo: Cannot parse\n"); 13126 return; 13127 } 13128 13129 // Extract everything in network order so that it is easy for sending a keepalive and also 13130 // for matching incoming TCP packets 13131 switch (param) 13132 { 13133 case 't': 13134 *timeout = value; 13135 //if (*timeout < 120) *timeout = 120; 13136 break; 13137 case 'h': 13138 case 'H': 13139 case 'd': 13140 case 'D': 13141 case 'm': 13142 case 'i': 13143 case 'c': 13144 break; 13145 case 'l': 13146 lport->NotAnInteger = swap16((mDNSu16)value); 13147 break; 13148 case 'r': 13149 rport->NotAnInteger = swap16((mDNSu16)value); 13150 break; 13151 case 's': 13152 *seq = swap32(value); 13153 break; 13154 case 'a': 13155 *ack = swap32(value); 13156 break; 13157 case 'w': 13158 *win = swap16((mDNSu16)value); 13159 break; 13160 default: 13161 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_ExtractKeepaliveInfo: unknown value %c\n", param); 13162 ptr = limit; 13163 break; 13164 } 13165 ptr++; // skip the space 13166 } 13167 } 13168 } 13169 13170 // Matches the proxied auth records to the incoming TCP packet and returns the match and its sequence and ack in "rseq" and "rack" so that 13171 // the clients need not retrieve this information from the auth record again. 13172 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport, 13173 const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack) 13174 { 13175 AuthRecord *ar; 13176 mDNSAddr laddr, raddr; 13177 mDNSEthAddr eth; 13178 mDNSIPPort lport, rport; 13179 mDNSu32 timeout, seq, ack; 13180 mDNSu16 win; 13181 13182 for (ar = m->ResourceRecords; ar; ar=ar->next) 13183 { 13184 timeout = seq = ack = 0; 13185 win = 0; 13186 laddr = raddr = zeroAddr; 13187 lport = rport = zeroIPPort; 13188 13189 if (!ar->WakeUp.HMAC.l[0]) continue; 13190 13191 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); 13192 13193 // Did we parse correctly ? 13194 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win) 13195 { 13196 debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar)); 13197 continue; 13198 } 13199 13200 debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d", 13201 &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport)); 13202 13203 // Does it match the incoming TCP packet ? 13204 if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport)) 13205 { 13206 // returning in network order 13207 *rseq = seq; 13208 *rack = ack; 13209 return ar; 13210 } 13211 } 13212 return mDNSNULL; 13213 } 13214 13215 mDNSlocal void mDNS_SendKeepalives(mDNS *const m) 13216 { 13217 AuthRecord *ar; 13218 13219 for (ar = m->ResourceRecords; ar; ar=ar->next) 13220 { 13221 mDNSu32 timeout, seq, ack; 13222 mDNSu16 win; 13223 mDNSAddr laddr, raddr; 13224 mDNSEthAddr eth; 13225 mDNSIPPort lport, rport; 13226 13227 timeout = seq = ack = 0; 13228 win = 0; 13229 13230 laddr = raddr = zeroAddr; 13231 lport = rport = zeroIPPort; 13232 13233 if (!ar->WakeUp.HMAC.l[0]) continue; 13234 13235 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); 13236 13237 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win) 13238 { 13239 debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar)); 13240 continue; 13241 } 13242 LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport)); 13243 13244 // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive 13245 // immediately (to detect any potential problems). After that we always set it to a non-zero value. 13246 if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0)) 13247 { 13248 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win); 13249 ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond); 13250 } 13251 if (m->NextScheduledKA - ar->KATimeExpire > 0) 13252 m->NextScheduledKA = ar->KATimeExpire; 13253 } 13254 } 13255 13256 mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar) 13257 { 13258 mDNSu32 timeout, seq, ack, seqInc; 13259 mDNSu16 win; 13260 mDNSAddr laddr, raddr; 13261 mDNSEthAddr eth; 13262 mDNSIPPort lport, rport; 13263 mDNSu8 *ptr; 13264 13265 if (ar == mDNSNULL) 13266 { 13267 LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL"); 13268 return; 13269 } 13270 13271 timeout = seq = ack = 0; 13272 win = 0; 13273 13274 laddr = raddr = zeroAddr; 13275 lport = rport = zeroIPPort; 13276 13277 mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, ð, &seq, &ack, &lport, &rport, &win); 13278 13279 if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win) 13280 { 13281 LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar)); 13282 return; 13283 } 13284 13285 // To send a keepalive ACK, we need to add one to the sequence number from the keepalive 13286 // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the 13287 // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so 13288 // it's converted to host byte order before incrementing it by one. 13289 ptr = (mDNSu8 *)&seq; 13290 seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1; 13291 ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF); 13292 ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF); 13293 ptr[2] = (mDNSu8)((seqInc >> 8) & 0xFF); 13294 ptr[3] = (mDNSu8)((seqInc ) & 0xFF); 13295 LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport)); 13296 mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win); 13297 } 13298 13299 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m, 13300 const DNSMessage *const msg, const mDNSu8 *end, 13301 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport, 13302 const mDNSInterfaceID InterfaceID) 13303 { 13304 int i; 13305 AuthRecord opt; 13306 mDNSu8 *p = m->omsg.data; 13307 OwnerOptData owner = zeroOwner; // Need to zero this, so we'll know if this Update packet was missing its Owner option 13308 mDNSu32 updatelease = 0; 13309 const mDNSu8 *ptr; 13310 13311 LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with " 13312 "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes", 13313 srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID, 13314 msg->h.numQuestions, msg->h.numQuestions == 1 ? ", " : "s,", 13315 msg->h.numAnswers, msg->h.numAnswers == 1 ? ", " : "s,", 13316 msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y, " : "ies,", 13317 msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " " : "s", end - msg->data); 13318 13319 if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return; 13320 13321 if (mDNS_PacketLoggingEnabled) 13322 DumpPacket(mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID); 13323 13324 ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space); 13325 if (ptr) 13326 { 13327 ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec); 13328 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT) 13329 { 13330 const rdataOPT *o; 13331 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength]; 13332 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++) 13333 { 13334 if (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease; 13335 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner = o->u.owner; 13336 } 13337 } 13338 mDNSCoreResetRecord(m); 13339 } 13340 13341 InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags); 13342 13343 if (!updatelease || !owner.HMAC.l[0]) 13344 { 13345 static int msgs = 0; 13346 if (msgs < 100) 13347 { 13348 msgs++; 13349 LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport), 13350 !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : ""); 13351 } 13352 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr; 13353 } 13354 else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS) 13355 { 13356 static int msgs = 0; 13357 if (msgs < 100) 13358 { 13359 msgs++; 13360 LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport), 13361 m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS); 13362 } 13363 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; 13364 } 13365 else 13366 { 13367 LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq); 13368 13369 if (updatelease > 24 * 60 * 60) 13370 updatelease = 24 * 60 * 60; 13371 13372 if (updatelease > 0x40000000UL / mDNSPlatformOneSecond) 13373 updatelease = 0x40000000UL / mDNSPlatformOneSecond; 13374 13375 ptr = LocateAuthorities(msg, end); 13376 13377 // Clear any stale TCP keepalive records that may exist 13378 ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID); 13379 ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID); 13380 13381 for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++) 13382 { 13383 ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec); 13384 if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative) 13385 { 13386 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec); 13387 AuthRecord *ar = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem); 13388 if (!ar) 13389 { 13390 m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused; 13391 break; 13392 } 13393 else 13394 { 13395 mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared; 13396 m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet; 13397 // All stale keepalive records have been flushed prior to this loop. 13398 if (!mDNS_KeepaliveRecord(&m->rec.r.resrec)) 13399 { 13400 ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record 13401 ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords); 13402 } 13403 mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar); 13404 AssignDomainName(&ar->namestorage, m->rec.r.resrec.name); 13405 ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse); 13406 ar->resrec.rdata->MaxRDLength = RDLengthMem; 13407 mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem); 13408 ar->ForceMCast = mDNStrue; 13409 ar->WakeUp = owner; 13410 if (m->rec.r.resrec.rrtype == kDNSType_PTR) 13411 { 13412 mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name); 13413 if (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name); 13414 else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name); 13415 debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar)); 13416 if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID); 13417 } 13418 ar->TimeRcvd = m->timenow; 13419 ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond; 13420 if (m->NextScheduledSPS - ar->TimeExpire > 0) 13421 m->NextScheduledSPS = ar->TimeExpire; 13422 ar->KATimeExpire = 0; 13423 mDNS_Register_internal(m, ar); 13424 13425 m->ProxyRecords++; 13426 mDNS_UpdateAllowSleep(m); 13427 LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar)); 13428 } 13429 } 13430 mDNSCoreResetRecord(m); 13431 } 13432 13433 if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask) 13434 { 13435 LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport)); 13436 ClearProxyRecords(m, &owner, m->DuplicateRecords); 13437 ClearProxyRecords(m, &owner, m->ResourceRecords); 13438 } 13439 else 13440 { 13441 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); 13442 opt.resrec.rrclass = NormalMaxDNSMessageData; 13443 opt.resrec.rdlength = sizeof(rdataOPT); // One option in this OPT record 13444 opt.resrec.rdestimate = sizeof(rdataOPT); 13445 opt.resrec.rdata->u.opt[0].opt = kDNSOpt_Lease; 13446 opt.resrec.rdata->u.opt[0].u.updatelease = updatelease; 13447 p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData); 13448 } 13449 } 13450 13451 if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, mDNSNULL, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSfalse); 13452 mDNS_SendKeepalives(m); 13453 } 13454 13455 mDNSlocal mDNSu32 mDNSGenerateOwnerOptForInterface(mDNS *const m, const mDNSInterfaceID InterfaceID, DNSMessage *msg) 13456 { 13457 mDNSu8 *ptr = msg->data; 13458 mDNSu8 *end = mDNSNULL; 13459 mDNSu32 length = 0; 13460 AuthRecord opt; 13461 NetworkInterfaceInfo *intf; 13462 13463 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); 13464 opt.resrec.rrclass = NormalMaxDNSMessageData; 13465 opt.resrec.rdlength = sizeof(rdataOPT); 13466 opt.resrec.rdestimate = sizeof(rdataOPT); 13467 13468 intf = FirstInterfaceForID(m, InterfaceID); 13469 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]); 13470 13471 LogSPS("Generated OPT record : %s", ARDisplayString(m, &opt)); 13472 end = PutResourceRecord(msg, ptr, &msg->h.numAdditionals, &opt.resrec); 13473 if (end != mDNSNULL) 13474 { 13475 // Put all the integer values in IETF byte-order (MSB first, LSB second) 13476 SwapDNSHeaderBytes(msg); 13477 length = (mDNSu32)(end - msg->data); 13478 } 13479 else 13480 LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record"); 13481 13482 return length; 13483 } 13484 13485 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic 13486 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case, 13487 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere. 13488 // Really, both should be unified and handled in one place. 13489 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID) 13490 { 13491 if (InterfaceID) 13492 { 13493 mDNSu32 pktlease = 0, spsupdates = 0; 13494 const mDNSBool gotlease = GetPktLease(m, msg, end, &pktlease); 13495 const mDNSu32 updatelease = gotlease ? pktlease : 60 * 60; // If SPS fails to indicate lease time, assume one hour 13496 if (gotlease) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID); 13497 13498 if (m->CurrentRecord) 13499 LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord)); 13500 m->CurrentRecord = m->ResourceRecords; 13501 while (m->CurrentRecord) 13502 { 13503 AuthRecord *const rr = m->CurrentRecord; 13504 if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name)))) 13505 if (mDNSSameOpaque16(rr->updateid, msg->h.id)) 13506 { 13507 // We successfully completed this record's registration on this "InterfaceID". Clear that bit. 13508 // Clear the updateid when we are done sending on all interfaces. 13509 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue); 13510 if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY)) 13511 bit_clr_opaque64(rr->updateIntID, scopeid); 13512 if (mDNSOpaque64IsZero(&rr->updateIntID)) 13513 rr->updateid = zeroID; 13514 rr->expire = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond); 13515 spsupdates++; 13516 LogSPS("Sleep Proxy %s record %2d %5d 0x%x 0x%x (%d) %s", rr->WakeUp.HMAC.l[0] ? "transferred" : "registered", spsupdates, updatelease, rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr)); 13517 if (rr->WakeUp.HMAC.l[0]) 13518 { 13519 rr->WakeUp.HMAC = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host 13520 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it 13521 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); 13522 } 13523 } 13524 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because 13525 // new records could have been added to the end of the list as a result of that call. 13526 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now 13527 m->CurrentRecord = rr->next; 13528 } 13529 if (spsupdates) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response 13530 { 13531 char *ifname; 13532 mDNSAddr spsaddr; 13533 DNSMessage optMsg; 13534 int length; 13535 // Update the dynamic store with the IP Address and MAC address of the sleep proxy 13536 ifname = InterfaceNameForID(m, InterfaceID); 13537 mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr)); 13538 mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname); 13539 13540 // Store the Owner OPT record for this interface. 13541 // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up 13542 InitializeDNSMessage(&optMsg.h, zeroID, ResponseFlags); 13543 length = mDNSGenerateOwnerOptForInterface(m, InterfaceID, &optMsg); 13544 if (length != 0) 13545 { 13546 length += sizeof(DNSMessageHeader); 13547 mDNSPlatformStoreOwnerOptRecord(ifname, &optMsg, length); 13548 } 13549 } 13550 } 13551 // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion 13552 // may have been the thing we were waiting for, so schedule another check to see if we can sleep now. 13553 if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow; 13554 } 13555 13556 mDNSlocal void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr, const domainname *const name, 13557 const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, const mDNSu32 ttl, 13558 const mDNSInterfaceID InterfaceID, const DNSServRef dnsserv, const mDNSOpaque16 responseFlags) 13559 { 13560 if (cr == &m->rec.r && m->rec.r.resrec.RecordType) 13561 LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r)); 13562 13563 // Create empty resource record 13564 cr->resrec.RecordType = kDNSRecordTypePacketNegative; 13565 cr->resrec.InterfaceID = InterfaceID; 13566 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13567 mdns_forget(&cr->resrec.metadata); 13568 if (dnsserv) 13569 { 13570 cr->resrec.metadata = mdns_cache_metadata_create(); 13571 mdns_cache_metadata_set_dns_service(cr->resrec.metadata, dnsserv); 13572 } 13573 #else 13574 cr->resrec.rDNSServer = dnsserv; 13575 #endif 13576 cr->resrec.name = name; // Will be updated to point to cg->name when we call CreateNewCacheEntry 13577 cr->resrec.rrtype = rrtype; 13578 cr->resrec.rrclass = rrclass; 13579 cr->resrec.rroriginalttl = ttl; 13580 cr->resrec.rdlength = 0; 13581 cr->resrec.rdestimate = 0; 13582 cr->resrec.namehash = namehash; 13583 cr->resrec.rdatahash = 0; 13584 cr->resrec.rdata = (RData*)&cr->smallrdatastorage; 13585 cr->resrec.rdata->MaxRDLength = 0; 13586 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 13587 cr->resrec.dnssec = mDNSNULL; 13588 #endif 13589 13590 cr->NextInKAList = mDNSNULL; 13591 cr->TimeRcvd = m->timenow; 13592 cr->DelayDelivery = 0; 13593 cr->NextRequiredQuery = m->timenow; 13594 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) 13595 cr->LastCachedAnswerTime = 0; 13596 #endif 13597 cr->CRActiveQuestion = mDNSNULL; 13598 cr->UnansweredQueries = 0; 13599 cr->LastUnansweredTime = 0; 13600 cr->NextInCFList = mDNSNULL; 13601 cr->soa = mDNSNULL; 13602 CacheRecordSetResponseFlags(cr, responseFlags); 13603 } 13604 13605 mDNSexport void MakeNegativeCacheRecordForQuestion(mDNS *const m, CacheRecord *const cr, const DNSQuestion *const q, 13606 const mDNSu32 ttl, const mDNSInterfaceID InterfaceID, const mDNSOpaque16 responseFlags) 13607 { 13608 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13609 const DNSServRef dnsserv = q->dnsservice; 13610 #else 13611 const DNSServRef dnsserv = q->qDNSServer; 13612 #endif 13613 MakeNegativeCacheRecord(m, cr, &q->qname, q->qnamehash, q->qtype, q->qclass, ttl, InterfaceID, dnsserv, responseFlags); 13614 } 13615 13616 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13617 mDNSexport void mDNSCoreReceiveForQuerier(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end, 13618 const mdns_client_t client, const mdns_dns_service_t dnsservice, const mDNSInterfaceID InterfaceID) 13619 { 13620 SwapDNSHeaderBytes(msg); 13621 mDNS_Lock(m); 13622 mDNSCoreReceiveResponse(m, msg, end, mDNSNULL, zeroIPPort, mDNSNULL, zeroIPPort, client, dnsservice, InterfaceID); 13623 mDNS_Unlock(m); 13624 } 13625 #endif 13626 13627 mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end, 13628 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport, 13629 const mDNSInterfaceID InterfaceID) 13630 { 13631 mDNSInterfaceID ifid = InterfaceID; 13632 const mDNSu8 *const pkt = (mDNSu8 *)msg; 13633 const mDNSu8 StdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_StdQuery; 13634 const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery; 13635 const mDNSu8 UpdQ = kDNSFlag0_QR_Query | kDNSFlag0_OP_Update; 13636 const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update; 13637 mDNSu8 QR_OP; 13638 mDNSu8 *ptr = mDNSNULL; 13639 mDNSBool TLS = (dstaddr == (mDNSAddr *)1); // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS 13640 if (TLS) dstaddr = mDNSNULL; 13641 13642 #ifndef UNICAST_DISABLED 13643 if (mDNSSameAddress(srcaddr, &m->Router)) 13644 { 13645 #ifdef _LEGACY_NAT_TRAVERSAL_ 13646 if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port))) 13647 { 13648 mDNS_Lock(m); 13649 LNT_ConfigureRouterInfo(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt)); 13650 mDNS_Unlock(m); 13651 return; 13652 } 13653 #endif 13654 if (mDNSSameIPPort(srcport, NATPMPPort)) 13655 { 13656 mDNS_Lock(m); 13657 uDNS_ReceiveNATPacket(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt)); 13658 mDNS_Unlock(m); 13659 return; 13660 } 13661 } 13662 #ifdef _LEGACY_NAT_TRAVERSAL_ 13663 else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; } 13664 #endif 13665 13666 #endif 13667 if ((unsigned)(end - pkt) < sizeof(DNSMessageHeader)) 13668 { 13669 LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt)); 13670 return; 13671 } 13672 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask); 13673 // Read the integer parts which are in IETF byte-order (MSB first, LSB second) 13674 ptr = (mDNSu8 *)&msg->h.numQuestions; 13675 msg->h.numQuestions = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]); 13676 msg->h.numAnswers = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]); 13677 msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]); 13678 msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]); 13679 13680 if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; } 13681 13682 // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address" 13683 // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up 13684 if (!mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; } 13685 13686 mDNS_Lock(m); 13687 m->PktNum++; 13688 if (mDNSOpaque16IsZero(msg->h.id)) 13689 { 13690 m->MPktNum++; 13691 } 13692 13693 #ifndef UNICAST_DISABLED 13694 if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR))) 13695 if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses 13696 { 13697 ifid = mDNSInterface_Any; 13698 if (mDNS_PacketLoggingEnabled) 13699 DumpPacket(mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID); 13700 uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport); 13701 // Note: mDNSCore also needs to get access to received unicast responses 13702 } 13703 #endif 13704 if (QR_OP == StdQ) mDNSCoreReceiveQuery (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid); 13705 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13706 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, mDNSNULL, mDNSNULL, ifid); 13707 #else 13708 else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid); 13709 #endif 13710 else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID); 13711 else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr, InterfaceID); 13712 else 13713 { 13714 if (mDNS_LoggingEnabled) 13715 { 13716 static int msgCount = 0; 13717 if (msgCount < 1000) { 13718 int i = 0; 13719 msgCount++; 13720 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)", 13721 msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt), InterfaceID); 13722 while (i < (int)(end - pkt)) 13723 { 13724 char buffer[128]; 13725 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i); 13726 do if (i < (int)(end - pkt)) p += mDNS_snprintf(p, sizeof(buffer), " %02X", pkt[i]);while (++i & 15); 13727 LogInfo("%s", buffer); 13728 } 13729 } 13730 } 13731 } 13732 // Packet reception often causes a change to the task list: 13733 // 1. Inbound queries can cause us to need to send responses 13734 // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses 13735 // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records 13736 // 4. Response packets that answer questions may cause our client to issue new questions 13737 mDNS_Unlock(m); 13738 } 13739 13740 // *************************************************************************** 13741 // MARK: - Searcher Functions 13742 13743 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the 13744 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV" 13745 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails 13746 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query 13747 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come. 13748 // 13749 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind 13750 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as 13751 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it 13752 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question. 13753 // The main reason for this design is that cache entries point to a *single* question and that question is responsible 13754 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry 13755 // breaks this design principle. 13756 // 13757 13758 // If IsLLQ(Q) is true, it means the question is both: 13759 // (a) long-lived and 13760 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling) 13761 // for multicast questions, we don't want to treat LongLived as anything special 13762 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID)) 13763 #define AWDLIsIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0) 13764 #define SameQuestionKind(Q1, Q2) (mDNSOpaque16IsZero((Q1)->TargetQID) == mDNSOpaque16IsZero((Q2)->TargetQID)) 13765 13766 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question) 13767 { 13768 DNSQuestion *q; 13769 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DISCOVERY) 13770 const mDNSBool questionSendsUnicastMDNSQueries = QuestionSendsMDNSQueriesViaUnicast(question); 13771 #endif 13772 // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list. 13773 // This prevents circular references, where two questions are each marked as a duplicate of the other. 13774 // Accordingly, we break out of the loop when we get to 'question', because there's no point searching 13775 // further in the list. 13776 for (q = m->Questions; q && (q != question); q = q->next) 13777 { 13778 if (!SameQuestionKind(q, question)) continue; 13779 if (q->qnamehash != question->qnamehash) continue; 13780 if (q->InterfaceID != question->InterfaceID) continue; 13781 if (q->qtype != question->qtype) continue; 13782 if (q->qclass != question->qclass) continue; 13783 if (IsLLQ(q) != IsLLQ(question)) continue; 13784 if (q->AuthInfo && !question->AuthInfo) continue; 13785 if (!q->Suppressed != !question->Suppressed) continue; 13786 if (q->BrowseThreshold != question->BrowseThreshold) continue; 13787 if (AWDLIsIncluded(q) != AWDLIsIncluded(question)) continue; 13788 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13789 if (q->dnsservice != question->dnsservice) continue; 13790 #endif 13791 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 13792 // DNSSEC-disabled question cannot be duped to DNSSEC-enabled question, vice versa. 13793 if (!q->enableDNSSEC != !question->enableDNSSEC) continue; 13794 // If enables DNSSEC, the question being duped to must be a primary DNSSEC requestor. 13795 if (q->enableDNSSEC && !dns_question_is_primary_dnssec_requestor(q)) continue; 13796 #endif 13797 if (!SameDomainName(&q->qname, &question->qname)) continue; 13798 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_DISCOVERY) 13799 if (questionSendsUnicastMDNSQueries) 13800 { 13801 // If question sends mDNS queries via unicast, then q must also send mDNS queries via 13802 // unicast and to the same mDNS resolver address. 13803 const mDNSAddr *const addr1 = &question->UnicastMDNSResolver; 13804 const mDNSAddr *const addr2 = &q->UnicastMDNSResolver; 13805 if (!QuestionSendsMDNSQueriesViaUnicast(q)) continue; 13806 if (!mDNSSameAddress(addr1, addr2)) continue; 13807 } 13808 else 13809 { 13810 // Otherwise, q must also not send mDNS queries via unicast. 13811 if (QuestionSendsMDNSQueriesViaUnicast(q)) continue; 13812 } 13813 #endif 13814 13815 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) 13816 // Only the DNS push enabled question can be dupped to a DNS push enabled question. 13817 if (dns_question_uses_dns_push(q) != dns_question_uses_dns_push(question)) 13818 { 13819 continue; 13820 } 13821 #endif 13822 13823 return(q); 13824 } 13825 return(mDNSNULL); 13826 } 13827 13828 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates 13829 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question) 13830 { 13831 DNSQuestion *q; 13832 DNSQuestion *first = mDNSNULL; 13833 13834 // This is referring to some other question as duplicate. No other question can refer to this 13835 // question as a duplicate. 13836 if (question->DuplicateOf) 13837 { 13838 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME " (" PUB_S 13839 ") duplicate of %p " PRI_DM_NAME " (" PUB_S ")", 13840 question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID), 13841 question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype), question->DuplicateOf, 13842 DM_NAME_PARAM(&question->DuplicateOf->qname), DNSTypeName(question->DuplicateOf->qtype)); 13843 return; 13844 } 13845 13846 for (q = m->Questions; q; q=q->next) // Scan our list of questions 13847 if (q->DuplicateOf == question) // To see if any questions were referencing this as their duplicate 13848 { 13849 q->DuplicateOf = first; 13850 if (!first) 13851 { 13852 first = q; 13853 // If q used to be a duplicate, but now is not, 13854 // then inherit the state from the question that's going away 13855 q->LastQTime = question->LastQTime; 13856 q->ThisQInterval = question->ThisQInterval; 13857 q->ExpectUnicastResp = question->ExpectUnicastResp; 13858 q->LastAnswerPktNum = question->LastAnswerPktNum; 13859 q->RecentAnswerPkts = question->RecentAnswerPkts; 13860 q->RequestUnicast = question->RequestUnicast; 13861 q->LastQTxTime = question->LastQTxTime; 13862 q->CNAMEReferrals = question->CNAMEReferrals; 13863 q->nta = question->nta; 13864 q->servAddr = question->servAddr; 13865 q->servPort = question->servPort; 13866 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13867 mdns_replace(&q->dnsservice, question->dnsservice); 13868 mdns_forget(&question->dnsservice); 13869 mdns_client_forget(&q->client); 13870 mdns_replace(&q->client, question->client); 13871 mdns_forget(&question->client); 13872 #else 13873 q->qDNSServer = question->qDNSServer; 13874 q->validDNSServers = question->validDNSServers; 13875 q->unansweredQueries = question->unansweredQueries; 13876 q->noServerResponse = question->noServerResponse; 13877 q->triedAllServersOnce = question->triedAllServersOnce; 13878 #endif 13879 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 13880 // Duplicate questions aren't eligible to have Discovery Proxy subscribers, so a simple 13881 // handoff from the former lead question to the new lead is sufficient. 13882 q->DPSubscribers = question->DPSubscribers; 13883 question->DPSubscribers = mDNSNULL; 13884 #endif 13885 13886 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 13887 // If this question is a primary DNSSEC question that does the validation work, transfer the work to 13888 // its duplicate question, by making the duplicate question the primary one. 13889 if (dns_question_is_primary_dnssec_requestor(question)) 13890 { 13891 LogRedact(MDNS_LOG_CATEGORY_DNSSEC, MDNS_LOG_INFO, "[Q%u->Q%u] Non-primary DNSSEC question becomes primary due to primary question cancelation.", 13892 mDNSVal16(q->TargetQID), mDNSVal16(question->TargetQID)); 13893 13894 dns_question_update_primary_dnssec_requestor(q, question); 13895 } 13896 #endif 13897 13898 q->TargetQID = question->TargetQID; 13899 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13900 q->LocalSocket = question->LocalSocket; 13901 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets 13902 #endif 13903 13904 q->state = question->state; 13905 // q->tcp = question->tcp; 13906 q->ReqLease = question->ReqLease; 13907 q->expire = question->expire; 13908 q->ntries = question->ntries; 13909 q->id = question->id; 13910 13911 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) 13912 DNSPushUpdateQuestionDuplicate(question, q); 13913 #endif 13914 13915 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13916 question->LocalSocket = mDNSNULL; 13917 #endif 13918 question->nta = mDNSNULL; // If we've got a GetZoneData in progress, transfer it to the newly active question 13919 // question->tcp = mDNSNULL; 13920 13921 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 13922 if (q->LocalSocket) 13923 debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 13924 #endif 13925 13926 #if MDNSRESPONDER_SUPPORTS(APPLE, RUNTIME_MDNS_METRICS) 13927 // If the question being stopped collects mDNS metric, the new primary should take it. 13928 if (DNSQuestionCollectsMDNSMetric(question)) 13929 { 13930 first->metrics = question->metrics; 13931 } 13932 #endif 13933 if (q->nta) 13934 { 13935 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "UpdateQuestionDuplicates transferred nta pointer for " PRI_DM_NAME " (" PUB_S ")", 13936 DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype)); 13937 q->nta->ZoneDataContext = q; 13938 } 13939 13940 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash 13941 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer"); 13942 13943 if (question->state == LLQ_Established) 13944 { 13945 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "UpdateQuestionDuplicates transferred LLQ state for " PRI_DM_NAME " (" PUB_S ")", 13946 DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype)); 13947 question->state = LLQ_Invalid; // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server 13948 } 13949 13950 SetNextQueryTime(m,q); 13951 } 13952 } 13953 } 13954 13955 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout) 13956 { 13957 McastResolver **p = &m->McastResolvers; 13958 McastResolver *tmp = mDNSNULL; 13959 13960 if (!d) d = (const domainname *)""; 13961 13962 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "mDNS_AddMcastResolver: Adding " PUB_DM_NAME ", InterfaceID %p, timeout %u", 13963 DM_NAME_PARAM(d), interface, timeout); 13964 13965 mDNS_CheckLock(m); 13966 13967 while (*p) // Check if we already have this {interface, domain} tuple registered 13968 { 13969 if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d)) 13970 { 13971 if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface); 13972 (*p)->flags &= ~McastResolver_FlagDelete; 13973 tmp = *p; 13974 *p = tmp->next; 13975 tmp->next = mDNSNULL; 13976 } 13977 else 13978 p=&(*p)->next; 13979 } 13980 13981 if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer 13982 else 13983 { 13984 // allocate, add to list 13985 *p = (McastResolver *) mDNSPlatformMemAllocateClear(sizeof(**p)); 13986 if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc"); 13987 else 13988 { 13989 (*p)->interface = interface; 13990 (*p)->flags = McastResolver_FlagNew; 13991 (*p)->timeout = timeout; 13992 AssignDomainName(&(*p)->domain, d); 13993 (*p)->next = mDNSNULL; 13994 } 13995 } 13996 return(*p); 13997 } 13998 13999 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14000 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server) 14001 { 14002 mDNSs32 ptime = 0; 14003 if (server->penaltyTime != 0) 14004 { 14005 ptime = server->penaltyTime - m->timenow; 14006 if (ptime < 0) 14007 { 14008 // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME 14009 // If it does not get reset in ResetDNSServerPenalties for some reason, we do it 14010 // here 14011 LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty", 14012 ptime, server->penaltyTime, m->timenow); 14013 server->penaltyTime = 0; 14014 ptime = 0; 14015 } 14016 } 14017 return ptime; 14018 } 14019 #endif 14020 14021 //Checks to see whether the newname is a better match for the name, given the best one we have 14022 //seen so far (given in bestcount). 14023 //Returns -1 if the newname is not a better match 14024 //Returns 0 if the newname is the same as the old match 14025 //Returns 1 if the newname is a better match 14026 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount, 14027 int bestcount) 14028 { 14029 // If the name contains fewer labels than the new server's domain or the new name 14030 // contains fewer labels than the current best, then it can't possibly be a better match 14031 if (namecount < newcount || newcount < bestcount) return -1; 14032 14033 // If there is no match, return -1 and the caller will skip this newname for 14034 // selection 14035 // 14036 // If we find a match and the number of labels is the same as bestcount, then 14037 // we return 0 so that the caller can do additional logic to pick one of 14038 // the best based on some other factors e.g., penaltyTime 14039 // 14040 // If we find a match and the number of labels is more than bestcount, then we 14041 // return 1 so that the caller can pick this over the old one. 14042 // 14043 // Note: newcount can either be equal or greater than bestcount beause of the 14044 // check above. 14045 14046 if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname)) 14047 return bestcount == newcount ? 0 : 1; 14048 else 14049 return -1; 14050 } 14051 14052 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there 14053 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these 14054 // names. In that case, we give a default timeout of 5 seconds 14055 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question) 14056 { 14057 McastResolver *curmatch = mDNSNULL; 14058 int bestmatchlen = -1, namecount = CountLabels(&question->qname); 14059 McastResolver *curr; 14060 int bettermatch, currcount; 14061 for (curr = m->McastResolvers; curr; curr = curr->next) 14062 { 14063 currcount = CountLabels(&curr->domain); 14064 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen); 14065 // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take 14066 // the timeout value from the first one 14067 if (bettermatch == 1) 14068 { 14069 curmatch = curr; 14070 bestmatchlen = currcount; 14071 } 14072 } 14073 LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch, 14074 curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT); 14075 return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT); 14076 } 14077 14078 // Returns true if it is a Domain Enumeration Query 14079 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname) 14080 { 14081 const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb", 14082 (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, }; 14083 const domainname *d = qname; 14084 const mDNSu8 *label; 14085 int i = 0; 14086 14087 // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query 14088 if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; } 14089 14090 label = (const mDNSu8 *)d; 14091 while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL) 14092 { 14093 if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;} 14094 i++; 14095 } 14096 if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL) 14097 { 14098 debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c); 14099 return mDNSfalse; 14100 } 14101 debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); 14102 14103 // CountLabels already verified the number of labels 14104 d = (const domainname *)(d->c + 1 + d->c[0]); // Second Label 14105 label = (const mDNSu8 *)d; 14106 if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd")) 14107 { 14108 debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c); 14109 return(mDNSfalse); 14110 } 14111 debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c); 14112 14113 d = (const domainname *)(d->c + 1 + d->c[0]); // Third Label 14114 label = (const mDNSu8 *)d; 14115 if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp")) 14116 { 14117 debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c); 14118 return(mDNSfalse); 14119 } 14120 debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c); 14121 14122 debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c); 14123 14124 return mDNStrue; 14125 } 14126 14127 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14128 // Note: InterfaceID is the InterfaceID of the question 14129 mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID) 14130 { 14131 // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer 14132 // with scopeType set to kScopeNone) 14133 // 14134 // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer 14135 // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match. 14136 // 14137 // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer 14138 // with scopeType set to kScopeServiceID) and their ServiceIDs should match. 14139 // 14140 // The first condition in the "if" statement checks to see if both the question and the DNSServer are 14141 // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1. 14142 // 14143 // If the first condition fails, following are the possible cases (the notes below are using 14144 // InterfaceID for discussion and the same holds good for ServiceID): 14145 // 14146 // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry 14147 // as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above). 14148 // 14149 // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as 14150 // unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check 14151 // would fail in this case. 14152 // 14153 // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer 14154 // should match (Refer to (2) above). 14155 14156 if (((d->scopeType == kScopeNone) && (!InterfaceID && ServiceID == -1)) || 14157 ((d->scopeType == kScopeInterfaceID) && d->interface == InterfaceID) || 14158 ((d->scopeType == kScopeServiceID) && d->serviceID == ServiceID)) 14159 { 14160 return mDNStrue; 14161 } 14162 return mDNSfalse; 14163 } 14164 14165 // Sets all the Valid DNS servers for a question 14166 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question) 14167 { 14168 int bestmatchlen = -1, namecount = CountLabels(&question->qname); 14169 DNSServer *curr; 14170 int bettermatch, currcount; 14171 int index = 0; 14172 mDNSu32 timeout = 0; 14173 mDNSBool DEQuery; 14174 14175 question->validDNSServers = zeroOpaque128; 14176 DEQuery = DomainEnumQuery(&question->qname); 14177 for (curr = m->DNSServers; curr; curr = curr->next) 14178 { 14179 debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scopeType); 14180 // skip servers that will soon be deleted 14181 if (curr->flags & DNSServerFlag_Delete) 14182 { 14183 debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType); 14184 continue; 14185 } 14186 14187 // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all 14188 // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration. 14189 // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update 14190 // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not 14191 // match the scoped entries by mistake. 14192 // 14193 // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout 14194 14195 // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set 14196 if (((curr->scopeType == kScopeInterfaceID) && (curr->interface == mDNSInterface_Any)) || 14197 ((curr->scopeType == kScopeServiceID) && (curr->serviceID <= 0))) 14198 { 14199 LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]", 14200 (int)curr->scopeType, &curr->addr, curr->domain.c, curr->interface, curr->serviceID); 14201 continue; 14202 } 14203 14204 currcount = CountLabels(&curr->domain); 14205 if ((!DEQuery || !curr->isCell) && DNSServerMatch(curr, question->InterfaceID, question->ServiceID)) 14206 { 14207 bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen); 14208 14209 // If we found a better match (bettermatch == 1) then clear all the bits 14210 // corresponding to the old DNSServers that we have may set before and start fresh. 14211 // If we find an equal match, then include that DNSServer also by setting the corresponding 14212 // bit 14213 if ((bettermatch == 1) || (bettermatch == 0)) 14214 { 14215 bestmatchlen = currcount; 14216 if (bettermatch) 14217 { 14218 debugf("SetValidDNSServers: Resetting all the bits"); 14219 question->validDNSServers = zeroOpaque128; 14220 timeout = 0; 14221 } 14222 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d," 14223 " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scopeType, index, curr->timeout, 14224 curr->interface); 14225 timeout += curr->timeout; 14226 if (DEQuery) 14227 debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->isCell); 14228 bit_set_opaque128(question->validDNSServers, index); 14229 } 14230 } 14231 index++; 14232 } 14233 question->noServerResponse = 0; 14234 14235 debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)", 14236 question->validDNSServers.l[3], question->validDNSServers.l[2], question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype)); 14237 // If there are no matching resolvers, then use the default timeout value. 14238 return (timeout ? timeout : DEFAULT_UDNS_TIMEOUT); 14239 } 14240 14241 // Get the Best server that matches a name. If you find penalized servers, look for the one 14242 // that will come out of the penalty box soon 14243 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque128 validBits, 14244 int *selected, mDNSBool nameMatch) 14245 { 14246 DNSServer *curmatch = mDNSNULL; 14247 int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0; 14248 DNSServer *curr; 14249 mDNSs32 bestPenaltyTime, currPenaltyTime; 14250 int bettermatch, currcount; 14251 int index = 0; 14252 int currindex = -1; 14253 14254 debugf("GetBestServer: ValidDNSServer bits 0x%x%x", validBits.l[1], validBits.l[0]); 14255 bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1; 14256 for (curr = m->DNSServers; curr; curr = curr->next) 14257 { 14258 // skip servers that will soon be deleted 14259 if (curr->flags & DNSServerFlag_Delete) 14260 { 14261 debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType); 14262 continue; 14263 } 14264 14265 // Check if this is a valid DNSServer 14266 if (!bit_get_opaque64(validBits, index)) 14267 { 14268 debugf("GetBestServer: continuing for index %d", index); 14269 index++; 14270 continue; 14271 } 14272 14273 currcount = CountLabels(&curr->domain); 14274 currPenaltyTime = PenaltyTimeForServer(m, curr); 14275 14276 debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d", 14277 &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime); 14278 14279 // If there are multiple best servers for a given question, we will pick the first one 14280 // if none of them are penalized. If some of them are penalized in that list, we pick 14281 // the least penalized one. BetterMatchForName walks through all best matches and 14282 // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server 14283 // in the list when there are no penalized servers and least one among them 14284 // when there are some penalized servers. 14285 14286 if (DNSServerMatch(curr, InterfaceID, ServiceID)) 14287 { 14288 14289 // If we know that all the names are already equally good matches, then skip calling BetterMatchForName. 14290 // This happens when we initially walk all the DNS servers and set the validity bit on the question. 14291 // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive 14292 // part and still do some redundant steps e.g., InterfaceID match 14293 14294 if (nameMatch) 14295 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen); 14296 else 14297 bettermatch = 0; 14298 14299 // If we found a better match (bettermatch == 1) then we don't need to 14300 // compare penalty times. But if we found an equal match, then we compare 14301 // the penalty times to pick a better match 14302 14303 if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime)) 14304 { 14305 currindex = index; 14306 curmatch = curr; 14307 bestmatchlen = currcount; 14308 bestPenaltyTime = currPenaltyTime; 14309 } 14310 } 14311 index++; 14312 } 14313 if (selected) *selected = currindex; 14314 return curmatch; 14315 } 14316 14317 // Look up a DNS Server, matching by name and InterfaceID 14318 mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID) 14319 { 14320 DNSServer *curmatch = mDNSNULL; 14321 char *ifname = mDNSNULL; // for logging purposes only 14322 mDNSOpaque128 allValid; 14323 14324 if (InterfaceID == mDNSInterface_LocalOnly) 14325 InterfaceID = mDNSNULL; 14326 14327 if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID); 14328 14329 // By passing in all ones, we make sure that every DNS server is considered 14330 allValid.l[0] = allValid.l[1] = allValid.l[2] = allValid.l[3] = 0xFFFFFFFF; 14331 14332 curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue); 14333 14334 if (curmatch != mDNSNULL) 14335 LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch->addr, 14336 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None", 14337 InterfaceID, name); 14338 else 14339 LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname ? ifname : "None", InterfaceID, name); 14340 14341 return(curmatch); 14342 } 14343 14344 // Look up a DNS Server for a question within its valid DNSServer bits 14345 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question) 14346 { 14347 DNSServer *curmatch = mDNSNULL; 14348 char *ifname = mDNSNULL; // for logging purposes only 14349 mDNSInterfaceID InterfaceID = question->InterfaceID; 14350 const domainname *name = &question->qname; 14351 int currindex; 14352 14353 if (InterfaceID == mDNSInterface_LocalOnly) 14354 InterfaceID = mDNSNULL; 14355 14356 if (InterfaceID) 14357 ifname = InterfaceNameForID(m, InterfaceID); 14358 14359 if (!mDNSOpaque128IsZero(&question->validDNSServers)) 14360 { 14361 curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse); 14362 if (currindex != -1) 14363 bit_clr_opaque128(question->validDNSServers, currindex); 14364 } 14365 14366 if (curmatch != mDNSNULL) 14367 { 14368 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%d->Q%d] GetServerForQuestion: %p DNS server (%p) " PRI_IP_ADDR 14369 ":%d (Penalty Time Left %d) (Scope " PUB_S ":%p:%d) for " PRI_DM_NAME " (" PUB_S ")", 14370 question->request_id, mDNSVal16(question->TargetQID), question, curmatch, &curmatch->addr, 14371 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), 14372 ifname ? ifname : "None", InterfaceID, question->ServiceID, DM_NAME_PARAM(name), 14373 DNSTypeName(question->qtype)); 14374 } 14375 else 14376 { 14377 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%d->Q%d] GetServerForQuestion: %p no DNS server (Scope " PUB_S ":%p:%d) for " 14378 PRI_DM_NAME " (" PUB_S ")", question->request_id, mDNSVal16(question->TargetQID), question, 14379 ifname ? ifname : "None", InterfaceID, question->ServiceID, DM_NAME_PARAM(name), 14380 DNSTypeName(question->qtype)); 14381 } 14382 14383 return(curmatch); 14384 } 14385 #endif // MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14386 14387 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 14388 // Called in normal client context (lock not held) 14389 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n) 14390 { 14391 DNSQuestion *q; 14392 mDNS_Lock(m); 14393 LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result); 14394 n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T 14395 for (q = m->Questions; q; q=q->next) 14396 if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) 14397 startLLQHandshake(m, q); // If ExternalPort is zero, will do StartLLQPolling instead 14398 mDNS_Unlock(m); 14399 } 14400 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 14401 14402 typedef enum 14403 { 14404 mDNSSuppression_None = 0, 14405 mDNSSuppression_BlockedByPolicy = 1, 14406 mDNSSuppression_NoDNSService = 2, 14407 mDNSSuppression_DenyCellular = 3, 14408 mDNSSuppression_DenyExpensive = 4, 14409 mDNSSuppression_DenyConstrained = 5, 14410 mDNSSuppression_RecordsUnusable = 6 14411 } mDNSSuppression; 14412 14413 // This function takes the DNSServer as a separate argument because sometimes the 14414 // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed 14415 // status before switching to it. 14416 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14417 mDNSlocal mDNSSuppression DetermineUnicastQuerySuppression(const DNSQuestion *const q, const mdns_dns_service_t dnsservice) 14418 #else 14419 mDNSlocal mDNSSuppression DetermineUnicastQuerySuppression(const DNSQuestion *const q, const DNSServer *const server) 14420 #endif 14421 { 14422 mDNSSuppression suppress = mDNSSuppression_None; 14423 const char *reason = mDNSNULL; 14424 14425 if (q->BlockedByPolicy) 14426 { 14427 suppress = mDNSSuppression_BlockedByPolicy; 14428 reason = " (blocked by policy)"; 14429 } 14430 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14431 else if (!dnsservice) 14432 { 14433 if (!q->IsUnicastDotLocal) 14434 { 14435 suppress = mDNSSuppression_NoDNSService; 14436 reason = " (no DNS service)"; 14437 } 14438 } 14439 #else 14440 else if (!server) 14441 { 14442 if (!q->IsUnicastDotLocal) 14443 { 14444 suppress = mDNSSuppression_NoDNSService; 14445 reason = " (no DNS server)"; 14446 } 14447 } 14448 #endif 14449 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14450 else if ((q->flags & kDNSServiceFlagsDenyCellular) && mdns_dns_service_interface_is_cellular(dnsservice)) 14451 #else 14452 else if ((q->flags & kDNSServiceFlagsDenyCellular) && server->isCell) 14453 #endif 14454 { 14455 suppress = mDNSSuppression_DenyCellular; 14456 reason = " (interface is cellular)"; 14457 } 14458 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14459 else if ((q->flags & kDNSServiceFlagsDenyExpensive) && mdns_dns_service_interface_is_expensive(dnsservice)) 14460 #else 14461 else if ((q->flags & kDNSServiceFlagsDenyExpensive) && server->isExpensive) 14462 #endif 14463 { 14464 suppress = mDNSSuppression_DenyExpensive; 14465 reason = " (interface is expensive)"; 14466 } 14467 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14468 else if ((q->flags & kDNSServiceFlagsDenyConstrained) && mdns_dns_service_interface_is_constrained(dnsservice)) 14469 #else 14470 else if ((q->flags & kDNSServiceFlagsDenyConstrained) && server->isConstrained) 14471 #endif 14472 { 14473 suppress = mDNSSuppression_DenyConstrained; 14474 reason = " (interface is constrained)"; 14475 } 14476 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) 14477 else if (q->SuppressUnusable && !DNS64IsQueryingARecord(q->dns64.state)) 14478 #else 14479 else if (q->SuppressUnusable) 14480 #endif 14481 { 14482 if (q->qtype == kDNSType_A) 14483 { 14484 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14485 if (!mdns_dns_service_a_queries_advised(dnsservice)) 14486 #else 14487 if (!server->usableA) 14488 #endif 14489 { 14490 suppress = mDNSSuppression_RecordsUnusable; 14491 reason = " (A records are unusable)"; 14492 } 14493 } 14494 else if (q->qtype == kDNSType_AAAA) 14495 { 14496 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14497 if (!mdns_dns_service_aaaa_queries_advised(dnsservice)) 14498 #else 14499 if (!server->usableAAAA) 14500 #endif 14501 { 14502 suppress = mDNSSuppression_RecordsUnusable; 14503 reason = " (AAAA records are unusable)"; 14504 } 14505 } 14506 } 14507 if (suppress != mDNSSuppression_None) 14508 { 14509 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 14510 "[Q%u] DetermineUnicastQuerySuppression: Query suppressed for " PRI_DM_NAME " " PUB_S PUB_S, 14511 mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), reason ? reason : ""); 14512 } 14513 return suppress; 14514 } 14515 14516 mDNSlocal mDNSSuppression DetermineSuppression(const DNSQuestion *const q) 14517 { 14518 // Multicast queries are never suppressed. 14519 if (mDNSOpaque16IsZero(q->TargetQID)) 14520 { 14521 return mDNSSuppression_None; 14522 } 14523 else 14524 { 14525 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14526 const DNSServRef s = q->dnsservice; 14527 #else 14528 const DNSServRef s = q->qDNSServer; 14529 #endif 14530 return DetermineUnicastQuerySuppression(q, s); 14531 } 14532 } 14533 14534 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14535 #define ShouldSuppressUnicastQueryScope mDNSexport 14536 #else 14537 #define ShouldSuppressUnicastQueryScope mDNSlocal 14538 #endif 14539 14540 ShouldSuppressUnicastQueryScope mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const DNSServRef s) 14541 { 14542 return (DetermineUnicastQuerySuppression(q, s) != mDNSSuppression_None); 14543 } 14544 14545 mDNSlocal mDNSBool ShouldSuppressQuery(const DNSQuestion *const q) 14546 { 14547 return (DetermineSuppression(q) != mDNSSuppression_None); 14548 } 14549 14550 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q) 14551 { 14552 CacheRecord *cr; 14553 CacheGroup *cg; 14554 14555 cg = CacheGroupForName(m, q->qnamehash, &q->qname); 14556 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 14557 { 14558 // Don't deliver RMV events for negative records if the question has not required DNSSEC RRs. 14559 if (cr->resrec.RecordType == kDNSRecordTypePacketNegative 14560 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 14561 && !dns_question_is_primary_dnssec_requestor(q) 14562 #endif 14563 ) 14564 { 14565 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 14566 "[Q%u] CacheRecordRmvEventsForCurrentQuestion: Suppressing RMV events for question - " 14567 "rr name: " PRI_DM_NAME ", rr type: " PUB_DNS_TYPE ", current active question: Q%u, current answers: %u", mDNSVal16(q->TargetQID), 14568 DM_NAME_PARAM(cr->resrec.name), DNS_TYPE_PARAM(cr->resrec.rrtype), 14569 cr->CRActiveQuestion ? mDNSVal16(cr->CRActiveQuestion->TargetQID) : 0, q->CurrentAnswers); 14570 14571 continue; 14572 } 14573 14574 if (SameNameCacheRecordAnswersQuestion(cr, q)) 14575 { 14576 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 14577 "[Q%u] CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question - " 14578 "rr name: " PRI_DM_NAME ", rr type: " PUB_DNS_TYPE ", local answers: %u", mDNSVal16(q->TargetQID), 14579 DM_NAME_PARAM(cr->resrec.name), DNS_TYPE_PARAM(cr->resrec.rrtype), q->LOAddressAnswers); 14580 14581 q->CurrentAnswers--; 14582 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--; 14583 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--; 14584 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv); 14585 if (m->CurrentQuestion != q) break; // If callback deleted q, then we're finished here 14586 } 14587 } 14588 } 14589 14590 mDNSlocal mDNSBool IsQuestionInList(const DNSQuestion *const list, const DNSQuestion *const question) 14591 { 14592 for (const DNSQuestion *q = list; q; q = q->next) 14593 { 14594 if (q == question) 14595 { 14596 return mDNStrue; 14597 } 14598 } 14599 return mDNSfalse; 14600 } 14601 14602 mDNSlocal mDNSBool IsQuestionNew(const mDNS *const m, const DNSQuestion *const question) 14603 { 14604 return IsQuestionInList(m->NewQuestions, question); 14605 } 14606 14607 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14608 mDNSexport mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q) 14609 #else 14610 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q) 14611 #endif 14612 { 14613 AuthRecord *rr; 14614 AuthGroup *ag; 14615 14616 if (m->CurrentQuestion) 14617 LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)", 14618 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 14619 14620 if (IsQuestionNew(m, q)) 14621 { 14622 LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 14623 return mDNStrue; 14624 } 14625 m->CurrentQuestion = q; 14626 ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname); 14627 if (ag) 14628 { 14629 for (rr = ag->members; rr; rr=rr->next) 14630 // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME 14631 if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q)) 14632 { 14633 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s", 14634 ARDisplayString(m, rr)); 14635 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0) 14636 { 14637 LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s" 14638 " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), 14639 q->CurrentAnswers, q->LOAddressAnswers); 14640 continue; 14641 } 14642 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv); // MUST NOT dereference q again 14643 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; } 14644 } 14645 } 14646 m->CurrentQuestion = mDNSNULL; 14647 return mDNStrue; 14648 } 14649 14650 // Returns false if the question got deleted while delivering the RMV events 14651 // The caller should handle the case 14652 mDNSexport mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q) 14653 { 14654 if (m->CurrentQuestion) 14655 LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)", 14656 m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype)); 14657 14658 // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events. 14659 // If this question was answered using local auth records, then you can't deliver RMVs using cache 14660 if (!IsQuestionNew(m, q) && !q->LOAddressAnswers) 14661 { 14662 m->CurrentQuestion = q; 14663 CacheRecordRmvEventsForCurrentQuestion(m, q); 14664 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; } 14665 m->CurrentQuestion = mDNSNULL; 14666 } 14667 else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); } 14668 return mDNStrue; 14669 } 14670 14671 mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart) 14672 { 14673 // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero 14674 // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before 14675 // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers) 14676 if (q->Suppressed) 14677 { 14678 q->Suppressed = mDNSfalse; 14679 if (!CacheRecordRmvEventsForQuestion(m, q)) 14680 { 14681 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from cache", 14682 q->request_id, mDNSVal16(q->TargetQID)); 14683 return; 14684 } 14685 q->Suppressed = mDNStrue; 14686 } 14687 14688 // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts) 14689 // and Suppressed status does not mean anything for these questions. As we are going to stop the 14690 // question below, we need to deliver the RMV events so that the ADDs that will be delivered during 14691 // the restart will not be a duplicate ADD 14692 if (!LocalRecordRmvEventsForQuestion(m, q)) 14693 { 14694 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 14695 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords", 14696 q->request_id, mDNSVal16(q->TargetQID)); 14697 return; 14698 } 14699 14700 // There are two cases here. 14701 // 14702 // 1. Previously it was suppressed and now it is not suppressed, restart the question so 14703 // that it will start as a new question. Note that we can't just call ActivateUnicastQuery 14704 // because when we get the response, if we had entries in the cache already, it will not answer 14705 // this question if the cache entry did not change. Hence, we need to restart 14706 // the query so that it can be answered from the cache. 14707 // 14708 // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions 14709 // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question 14710 // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false). 14711 // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed 14712 // (Suppressed is true). The reason for this is that when a question is suppressed, we want an 14713 // immediate response and not want to be blocked behind a question that is querying DNS servers. When 14714 // the question is not suppressed, we don't want two active questions sending packets on the wire. 14715 // This affects both efficiency and also the current design where there is only one active question 14716 // pointed to from a cache entry. 14717 // 14718 // We restart queries in a two step process by first calling stop and build a temporary list which we 14719 // will restart at the end. The main reason for the two step process is to handle duplicate questions. 14720 // If there are duplicate questions, calling stop inherits the values from another question on the list (which 14721 // will soon become the real question) including q->ThisQInterval which might be zero if it was 14722 // suppressed before. At the end when we have restarted all questions, none of them is active as each 14723 // inherits from one another and we need to reactivate one of the questions here which is a little hacky. 14724 // 14725 // It is much cleaner and less error prone to build a list of questions and restart at the end. 14726 14727 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME " (" PUB_S ")", 14728 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype)); 14729 mDNS_StopQuery_internal(m, q); 14730 q->next = *restart; 14731 *restart = q; 14732 } 14733 14734 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 14735 mDNSexport void mDNSCoreReceiveD2DResponse(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, 14736 const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport, 14737 const mDNSInterfaceID InterfaceID) 14738 { 14739 mDNSCoreReceiveResponse(m, response, end, srcaddr, srcport, dstaddr, dstport, mDNSNULL, mDNSNULL, InterfaceID); 14740 } 14741 #endif 14742 14743 // The caller should hold the lock 14744 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m) 14745 { 14746 DNSQuestion *q; 14747 DNSQuestion *restart = mDNSNULL; 14748 14749 // We look through all questions including new questions. During network change events, 14750 // we potentially restart questions here in this function that ends up as new questions, 14751 // which may be suppressed at this instance. Before it is handled we get another network 14752 // event that changes the status e.g., address becomes available. If we did not process 14753 // new questions, we would never change its Suppressed status. 14754 // 14755 // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the 14756 // application callback can potentially stop the current question (detected by CurrentQuestion) or 14757 // *any* other question which could be the next one that we may process here. RestartQuestion 14758 // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal 14759 // if the "next" question is stopped while the CurrentQuestion is stopped 14760 if (m->RestartQuestion) 14761 LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)", 14762 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype)); 14763 m->RestartQuestion = m->Questions; 14764 while (m->RestartQuestion) 14765 { 14766 q = m->RestartQuestion; 14767 m->RestartQuestion = q->next; 14768 if (q->SuppressUnusable) 14769 { 14770 const mDNSBool old = q->Suppressed; 14771 q->Suppressed = ShouldSuppressQuery(q); 14772 if (q->Suppressed != old) 14773 { 14774 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before 14775 // followed by a negative cache response. Temporarily turn off suppression so that 14776 // AnswerCurrentQuestionWithResourceRecord can answer the question 14777 SuppressStatusChanged(m, q, &restart); 14778 } 14779 } 14780 } 14781 while (restart) 14782 { 14783 q = restart; 14784 restart = restart->next; 14785 q->next = mDNSNULL; 14786 LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype)); 14787 mDNS_StartQuery_internal(m, q); 14788 } 14789 } 14790 14791 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14792 mDNSlocal void RestartUnicastQuestions(mDNS *const m) 14793 { 14794 DNSQuestion *q; 14795 DNSQuestion *restartList = mDNSNULL; 14796 14797 if (m->RestartQuestion) 14798 LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)", 14799 m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype)); 14800 m->RestartQuestion = m->Questions; 14801 while (m->RestartQuestion) 14802 { 14803 q = m->RestartQuestion; 14804 m->RestartQuestion = q->next; 14805 if (q->Restart) 14806 { 14807 if (mDNSOpaque16IsZero(q->TargetQID)) 14808 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype)); 14809 14810 q->Restart = mDNSfalse; 14811 SuppressStatusChanged(m, q, &restartList); 14812 } 14813 } 14814 while ((q = restartList) != mDNSNULL) 14815 { 14816 restartList = q->next; 14817 q->next = mDNSNULL; 14818 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME " (" PUB_S ")", 14819 q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype)); 14820 mDNS_StartQuery_internal(m, q); 14821 } 14822 } 14823 #endif 14824 14825 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of 14826 // DNS Question that are already set by the client before calling mDNS_StartQuery() 14827 mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question) 14828 { 14829 if (!ValidateDomainName(&question->qname)) 14830 { 14831 LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype)); 14832 return(mStatus_Invalid); 14833 } 14834 14835 // If this question is referencing a specific interface, verify it exists 14836 if (question->InterfaceID && !LocalOnlyOrP2PInterface(question->InterfaceID)) 14837 { 14838 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID); 14839 if (!intf) 14840 LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list", 14841 IIDPrintable(question->InterfaceID), question->qname.c, DNSTypeName(question->qtype)); 14842 } 14843 14844 return(mStatus_NoError); 14845 } 14846 14847 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question. 14848 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve() 14849 mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question) 14850 { 14851 // First reset all DNS Configuration 14852 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14853 mdns_forget(&question->dnsservice); 14854 question->NeedUpdatedQuerier = mDNSfalse; 14855 #else 14856 question->qDNSServer = mDNSNULL; 14857 question->validDNSServers = zeroOpaque128; 14858 question->triedAllServersOnce = mDNSfalse; 14859 question->noServerResponse = mDNSfalse; 14860 #endif 14861 question->StopTime = (question->TimeoutQuestion) ? question->StopTime : 0; 14862 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_ANALYTICS) 14863 mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics)); 14864 #endif 14865 14866 // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified 14867 if (LocalOnlyOrP2PInterface(question->InterfaceID) && !question->TimeoutQuestion) 14868 return; 14869 // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers()) 14870 if (!mDNSOpaque16IsZero(question->TargetQID)) 14871 { 14872 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14873 mDNSu32 timeout = 30; 14874 #else 14875 mDNSu32 timeout = SetValidDNSServers(m, question); 14876 #endif 14877 // We set the timeout value the first time mDNS_StartQuery_internal is called for a question. 14878 // So if a question is restarted when a network change occurs, the StopTime is not reset. 14879 // Note that we set the timeout for all questions. If this turns out to be a duplicate, 14880 // it gets a full timeout value even if the original question times out earlier. 14881 if (question->TimeoutQuestion && !question->StopTime) 14882 { 14883 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond); 14884 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, 14885 "[Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")", 14886 mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), 14887 DNSTypeName(question->qtype)); 14888 } 14889 14890 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14891 Querier_SetDNSServiceForQuestion(question); 14892 #else 14893 question->qDNSServer = GetServerForQuestion(m, question); 14894 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "[R%u->Q%u] InitDNSConfig: question %p " PRI_DM_NAME " " PUB_S " Timeout %d, DNS Server " 14895 PRI_IP_ADDR ":%d", 14896 question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), 14897 DNSTypeName(question->qtype), timeout, question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL, 14898 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort)); 14899 #endif 14900 } 14901 else if (question->TimeoutQuestion && !question->StopTime) 14902 { 14903 // If the question is to be timed out and its a multicast, local-only or P2P case, 14904 // then set it's stop time. 14905 mDNSu32 timeout = LocalOnlyOrP2PInterface(question->InterfaceID) ? 14906 DEFAULT_LO_OR_P2P_TIMEOUT : GetTimeoutForMcastQuestion(m, question); 14907 question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond); 14908 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, 14909 "[R%u->Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")", 14910 question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), 14911 DNSTypeName(question->qtype)); 14912 } 14913 // Set StopTime here since it is a part of DNS Configuration 14914 if (question->StopTime) 14915 SetNextQueryStopTime(m, question); 14916 // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions 14917 // will never be transmitted on the wire. 14918 if (!(LocalOnlyOrP2PInterface(question->InterfaceID))) 14919 SetNextQueryTime(m,question); 14920 } 14921 14922 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal 14923 // state fields of the DNS Question. These are independent of the Client layer. 14924 mDNSlocal void InitCommonState(mDNS *const m, DNSQuestion *const question) 14925 { 14926 // Note: In the case where we already have the answer to this question in our cache, that may be all the client 14927 // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would 14928 // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval). 14929 // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate 14930 // that to go out immediately. 14931 question->next = mDNSNULL; 14932 // ThisQInterval should be initialized before any memory allocations occur. If malloc 14933 // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates 14934 // the question list to check if ThisQInterval is negative which means the question has been 14935 // stopped and can't be on the list. The question is already on the list and ThisQInterval 14936 // can be negative if the caller just stopped it and starting it again. Hence, it always has to 14937 // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is 14938 // turned ON which can allocate memory e.g., base64 encoding. 14939 question->ThisQInterval = InitialQuestionInterval; // MUST be > zero for an active question 14940 question->qnamehash = DomainNameHashValue(&question->qname); 14941 mDNSs32 delay = 0; 14942 if (mDNSOpaque16IsZero(question->TargetQID)) 14943 { 14944 delay = CheckForSoonToExpireRecordsEx(m, &question->qname, question->qnamehash, question->qtype, question->qclass); 14945 } 14946 question->DelayAnswering = delay; 14947 question->LastQTime = m->timenow; 14948 question->ExpectUnicastResp = 0; 14949 question->LastAnswerPktNum = m->PktNum; 14950 question->RecentAnswerPkts = 0; 14951 question->CurrentAnswers = 0; 14952 14953 question->BrowseThreshold = 0; 14954 question->CachedAnswerNeedsUpdate = mDNSfalse; 14955 14956 question->LargeAnswers = 0; 14957 question->UniqueAnswers = 0; 14958 question->LOAddressAnswers = 0; 14959 question->FlappingInterface1 = mDNSNULL; 14960 question->FlappingInterface2 = mDNSNULL; 14961 14962 // mDNSPlatformGetDNSRoutePolicy() and InitDNSConfig() may set a DNSQuestion's BlockedByPolicy value, 14963 // so they should be called before calling ShouldSuppressQuery(), which checks BlockedByPolicy. 14964 question->BlockedByPolicy = mDNSfalse; 14965 14966 // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy() 14967 // since we would already have the question->ServiceID in that case. 14968 if (!(question->flags & kDNSServiceFlagsServiceIndex)) 14969 { 14970 question->ServiceID = -1; 14971 } 14972 else 14973 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c, 14974 DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID); 14975 14976 InitDNSConfig(m, question); 14977 question->AuthInfo = GetAuthInfoForQuestion(m, question); 14978 const mDNSSuppression suppress = DetermineSuppression(question); 14979 question->Suppressed = (suppress != mDNSSuppression_None); 14980 question->ForceCNAMEFollows = question->PersistWhenRecordsUnusable && (suppress == mDNSSuppression_RecordsUnusable); 14981 question->NextInDQList = mDNSNULL; 14982 question->SendQNow = mDNSNULL; 14983 question->SendOnAll = mDNSfalse; 14984 question->RequestUnicast = kDefaultRequestUnicastCount; 14985 14986 14987 question->LastQTxTime = m->timenow; 14988 question->CNAMEReferrals = 0; 14989 14990 question->WakeOnResolveCount = 0; 14991 if (question->WakeOnResolve) 14992 { 14993 question->WakeOnResolveCount = InitialWakeOnResolveCount; 14994 } 14995 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 14996 question->Restart = mDNSfalse; 14997 #endif 14998 14999 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 15000 question->dnssec = mDNSNULL; 15001 #endif 15002 15003 debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)", 15004 question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow, 15005 NextQSendTime(question) - m->timenow, 15006 question->DelayAnswering ? question->DelayAnswering - m->timenow : 0, 15007 question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf); 15008 15009 if (question->DelayAnswering) 15010 LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)", 15011 question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype)); 15012 } 15013 15014 // Excludes the DNS Config fields which are already handled by InitDNSConfig() 15015 mDNSlocal void InitWABState(DNSQuestion *const question) 15016 { 15017 // We'll create our question->LocalSocket on demand, if needed. 15018 // We won't need one for duplicate questions, or from questions answered immediately out of the cache. 15019 // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single 15020 // NAT mapping for receiving inbound add/remove events. 15021 question->LocalSocket = mDNSNULL; 15022 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 15023 mdns_client_forget(&question->client); 15024 #else 15025 question->unansweredQueries = 0; 15026 #endif 15027 question->nta = mDNSNULL; 15028 question->servAddr = zeroAddr; 15029 question->servPort = zeroIPPort; 15030 question->tcp = mDNSNULL; 15031 } 15032 15033 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 15034 mDNSlocal void InitLLQNATState(mDNS *const m) 15035 { 15036 // If we don't have our NAT mapping active, start it now 15037 if (!m->LLQNAT.clientCallback) 15038 { 15039 m->LLQNAT.Protocol = NATOp_MapUDP; 15040 m->LLQNAT.IntPort = m->UnicastPort4; 15041 m->LLQNAT.RequestedPort = m->UnicastPort4; 15042 m->LLQNAT.clientCallback = LLQNATCallback; 15043 m->LLQNAT.clientContext = (void*)1; // Means LLQ NAT Traversal just started 15044 mDNS_StartNATOperation_internal(m, &m->LLQNAT); 15045 } 15046 } 15047 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 15048 15049 mDNSlocal void InitLLQState(DNSQuestion *const question) 15050 { 15051 question->state = LLQ_Init; 15052 question->ReqLease = 0; 15053 question->expire = 0; 15054 question->ntries = 0; 15055 question->id = zeroOpaque64; 15056 } 15057 15058 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize 15059 // DNSSEC & DNS Proxy fields of the DNS Question. 15060 mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question) 15061 { 15062 (void) m; 15063 question->responseFlags = zeroID; 15064 } 15065 15066 // Once the question is completely initialized including the duplicate logic, this function 15067 // is called to finalize the unicast question which requires flushing the cache if needed, 15068 // activating the query etc. 15069 mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question) 15070 { 15071 // Ensure DNS related info of duplicate question is same as the orig question 15072 if (question->DuplicateOf) 15073 { 15074 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 15075 const DNSQuestion *const duplicateOf = question->DuplicateOf; 15076 mdns_replace(&question->dnsservice, duplicateOf->dnsservice); 15077 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%u->DupQ%u->Q%u] Duplicate question " PRI_DM_NAME " (" PUB_S ")", 15078 question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(duplicateOf->TargetQID), 15079 DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype)); 15080 #else 15081 question->validDNSServers = question->DuplicateOf->validDNSServers; 15082 // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it, 15083 // then we log a line as it could indicate an issue 15084 if (question->DuplicateOf->qDNSServer == mDNSNULL) 15085 { 15086 if (question->qDNSServer) 15087 { 15088 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%d->Q%d] FinalizeUnicastQuestion: Current(dup) question %p has DNSServer(" PRI_IP_ADDR 15089 ":%d) but original question(%p) has no DNS Server! " PRI_DM_NAME " (" PUB_S ")", 15090 question->request_id, mDNSVal16(question->TargetQID), question, 15091 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL, 15092 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort), question->DuplicateOf, 15093 DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype)); 15094 } 15095 } 15096 question->qDNSServer = question->DuplicateOf->qDNSServer; 15097 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "[R%d->DupQ%d->Q%d] FinalizeUnicastQuestion: Duplicate question %p (%p) " PRI_DM_NAME " (" PUB_S 15098 "), DNS Server " PRI_IP_ADDR ":%d", 15099 question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID), 15100 question, question->DuplicateOf, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype), 15101 question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL, 15102 mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort)); 15103 #endif 15104 } 15105 15106 ActivateUnicastQuery(m, question, mDNSfalse); 15107 15108 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 15109 if (question->LongLived) 15110 { 15111 // Unlike other initializations, InitLLQNATState should be done after 15112 // we determine that it is a unicast question. LongLived is set for 15113 // both multicast and unicast browse questions but we should initialize 15114 // the LLQ NAT state only for LLQ. Otherwise we will unnecessarily 15115 // start the NAT traversal that is not needed. 15116 InitLLQNATState(m); 15117 } 15118 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 15119 } 15120 15121 mDNSlocal void InsertNewQuestionInList(DNSQuestion *const question) 15122 { 15123 DNSQuestion **qptr; 15124 DNSQuestion *q; 15125 const mDNSBool localOnlyOrP2P = LocalOnlyOrP2PInterface(question->InterfaceID); 15126 mDNS *const m = &mDNSStorage; 15127 DNSQuestion **const newQSublistPtr = localOnlyOrP2P ? &m->NewLocalOnlyQuestions : &m->NewQuestions; 15128 const DNSQuestion *const newQSublist = *newQSublistPtr; 15129 mDNSBool inNewQSublist = mDNSfalse; 15130 mDNSBool passedPrimary = mDNSfalse; 15131 for (qptr = localOnlyOrP2P ? &m->LocalOnlyQuestions : &m->Questions; (q = *qptr) != mDNSNULL; qptr = &q->next) 15132 { 15133 // If there's no new question sublist, then keep going until the end of the question list so that the new 15134 // question can be appended. Otherwise, the new question needs to be carefully inserted in the sublist such that 15135 // it doesn't precede any questions that are supposed to be answered earlier or at the same clock time as 15136 // itself, and such that it doesn't follow any questions that are supposed to be answered later than itself. 15137 if (newQSublist) 15138 { 15139 // We've entered the new question sublist when we encounter the head of the sublist. 15140 if (!inNewQSublist && (q == newQSublist)) 15141 { 15142 inNewQSublist = mDNStrue; 15143 } 15144 // If we're in the new question sublist, check if it's appropriate to insert the new question before the 15145 // current question: 15146 // 15147 // 1. The current question must also have a delayed answering time. 15148 // 2. For questions that are duplicates, make sure that the new question is inserted after its primary 15149 // question because the rest of the code expects a duplicate question to always come after its primary 15150 // question in a question list. 15151 if (inNewQSublist && (q->DelayAnswering != 0) && (!question->DuplicateOf || passedPrimary)) 15152 { 15153 // Determine when the new question's answering should begin. 15154 const mDNSs32 answeringTime = (question->DelayAnswering != 0) ? question->DelayAnswering : m->timenow; 15155 // If the current question's answering time is later, then the new question should be inserted before. 15156 if ((q->DelayAnswering - answeringTime) > 0) 15157 { 15158 break; 15159 } 15160 } 15161 if (!passedPrimary && question->DuplicateOf && (q == question->DuplicateOf)) 15162 { 15163 passedPrimary = mDNStrue; 15164 } 15165 } 15166 } 15167 // Insert the new question in the list. 15168 question->next = q; 15169 *qptr = question; 15170 // If there was no new question sublist, or the new question was inserted right before the head of the sublist, then 15171 // the new question becomes the head of the new question sublist. 15172 if (!newQSublist || (newQSublist == q)) 15173 { 15174 *newQSublistPtr = question; 15175 } 15176 } 15177 15178 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question) 15179 { 15180 mStatus err; 15181 15182 // First check for cache space (can't do queries if there is no cache space allocated) 15183 mdns_require_action_quiet(m->rrcache_size > 0, exit, err = mStatus_NoCache); 15184 15185 err = ValidateParameters(m, question); 15186 mdns_require_noerr_quiet(err, exit); 15187 15188 #ifdef USE_LIBIDN 15189 // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode. 15190 // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.) 15191 // This applies to the top label (TLD) only 15192 // -- for the second level and down we try UTF-8 first, and then fall back to Punycode only if UTF-8 fails. 15193 if (IsHighASCIILabel(LastLabel(&question->qname))) 15194 { 15195 domainname newname; 15196 if (PerformNextPunycodeConversion(question, &newname)) 15197 AssignDomainName(&question->qname, &newname); 15198 } 15199 #endif // USE_LIBIDN 15200 15201 #ifndef UNICAST_DISABLED 15202 question->TargetQID = Question_uDNS(question) ? mDNS_NewMessageID(m) : zeroID; 15203 #else 15204 question->TargetQID = zeroID; 15205 #endif 15206 debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype)); 15207 15208 #if MDNSRESPONDER_SUPPORTS(APPLE, TERMINUS_ASSISTED_UNICAST_DISCOVERY) 15209 // Check if the query meets the requirement of using mDNS alternative service and if we have such a service 15210 // available. 15211 if (DNSQuestionIsEligibleForMDNSAlternativeService(question) && 15212 Querier_IsMDNSAlternativeServiceAvailableForQuestion(question)) 15213 { 15214 // If so, we convert it to a non-mDNS query to exclude any mDNS query. 15215 question->TargetQID = mDNS_NewMessageID(m); 15216 // After the operation above, DNSQuestionRequestsMDNSAlternativeService returns true indicating that this 15217 // question is an mDNS question but requests an mDNS alternative service to be used. 15218 } 15219 #endif 15220 15221 #if MDNSRESPONDER_SUPPORTS(APPLE, LOG_PRIVACY_LEVEL) 15222 // This code block must: 15223 // 1. Be put after question ID is assigned. 15224 // 2. Be put before any log is printed, or domain name information may leak. 15225 if (DNSQuestionNeedsSensitiveLogging(question)) 15226 { 15227 gNumOfSensitiveLoggingEnabledQuestions++; 15228 if (!gSensitiveLoggingEnabled) 15229 { 15230 gSensitiveLoggingEnabled = mDNStrue; 15231 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 15232 "[Q%u] Question enables sensitive logging, all the sensitive level logs and the state dump of the question will now be redacted.", 15233 mDNSVal16(question->TargetQID)); 15234 } 15235 else 15236 { 15237 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, 15238 "[Q%u] Question enables sensitive logging, redaction already in effect. - " 15239 "number of enabled questions: %d.", mDNSVal16(question->TargetQID), 15240 gNumOfSensitiveLoggingEnabledQuestions); 15241 } 15242 } 15243 #endif // MDNSRESPONDER_SUPPORTS(APPLE, LOG_PRIVACY_LEVEL) 15244 15245 const mDNSBool localOnlyOrP2P = LocalOnlyOrP2PInterface(question->InterfaceID); 15246 #if MDNSRESPONDER_SUPPORTS(APPLE, TRACKER_STATE) 15247 if (resolved_cache_is_enabled() && 15248 !mDNSOpaque16IsZero(question->TargetQID) && 15249 question->qclass == kDNSClass_IN && 15250 !localOnlyOrP2P && 15251 (question->qtype == kDNSType_AAAA || 15252 question->qtype == kDNSType_A || 15253 question->qtype == kDNSType_CNAME)) 15254 { 15255 resolved_cache_prepend_name(question, &question->qname); 15256 } 15257 #endif 15258 const DNSQuestion *const qlist = localOnlyOrP2P ? m->LocalOnlyQuestions : m->Questions; 15259 if (IsQuestionInList(qlist, question)) 15260 { 15261 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartQuery_internal: Error! Tried to add a question " PRI_DM_NAME " (" PUB_S ") %p " 15262 "that's already in the active list", 15263 DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype), question); 15264 err = mStatus_AlreadyRegistered; 15265 goto exit; 15266 } 15267 15268 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) && !defined(UNIT_TEST) 15269 // If the question has requested using DNS push, check if it already has DNS push context initialized: 15270 // 1. If it is initialized, then it is a restarted DNS push question, so we do not reinitialize DNS push context. 15271 // 2. If it is uninitialized, then initialize it and start DNS push bootstrapping. 15272 if (dns_question_enables_dns_push(question) && 15273 !Querier_IsCustomPushServiceAvailableForQuestion(question) && 15274 !dns_question_uses_dns_push(question)) 15275 { 15276 const dns_obj_error_t dns_push_err = dns_push_handle_question_start(m, question); 15277 mdns_require_noerr_action_quiet(dns_push_err, exit, err = mStatus_BadParamErr); 15278 } 15279 #endif 15280 15281 // Intialize the question. The only ordering constraint we have today is that 15282 // InitDNSSECProxyState should be called after the DNS server is selected (in 15283 // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC 15284 // validation. 15285 15286 InitCommonState(m, question); 15287 InitWABState(question); 15288 InitLLQState(question); 15289 InitDNSSECProxyState(m, question); 15290 15291 // FindDuplicateQuestion should be called last after all the intialization 15292 // as the duplicate logic could be potentially based on any field in the 15293 // question. 15294 question->DuplicateOf = FindDuplicateQuestion(m, question); 15295 if (question->DuplicateOf) 15296 question->AuthInfo = question->DuplicateOf->AuthInfo; 15297 15298 InsertNewQuestionInList(question); 15299 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 15300 if (question->enableDNSSEC) 15301 { 15302 const dnssec_error_t dnssec_err = dnssec_handle_question_start(m, question); 15303 mdns_require_noerr_action_quiet(dnssec_err, exit, err = mStatus_UnknownErr); 15304 } 15305 #endif 15306 if (question->request_id == 0) 15307 { 15308 // After: [Q0] mDNS_StartQuery_internal START -- qname: 70-35-60-63\134.1\134 joey-test-atv._sleep-proxy._udp.local., qtype: SRV 15309 // request_id == 0 indicates that the query is started by mDNSResponder itself, in which case no request 15310 // level log is available. Therefore, we need to print the query start log message to indicate that 15311 // mDNSResponder has started a query internally. 15312 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 15313 "[Q%u] mDNS_StartQuery_internal START -- qname: " PRI_DM_NAME " (%x), qtype: " PUB_DNS_TYPE, 15314 mDNSVal16(question->TargetQID), DM_NAME_PARAM_NONNULL(&question->qname), 15315 mDNS_DomainNameFNV1aHash(&question->qname), DNS_TYPE_PARAM(question->qtype)); 15316 } 15317 if (!localOnlyOrP2P) 15318 { 15319 // If the question's id is non-zero, then it's Wide Area 15320 // MUST NOT do this Wide Area setup until near the end of 15321 // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA, 15322 // NS, etc.) and if we haven't finished setting up our own question and setting 15323 // m->NewQuestions if necessary then we could end up recursively re-entering 15324 // this routine with the question list data structures in an inconsistent state. 15325 if (!mDNSOpaque16IsZero(question->TargetQID)) 15326 { 15327 FinalizeUnicastQuestion(m, question); 15328 } 15329 else 15330 { 15331 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 15332 m->NumAllInterfaceQuestions++; 15333 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1) 15334 { 15335 m->NextBonjourDisableTime = 0; 15336 if (m->BonjourEnabled == 0) 15337 { 15338 // Enable Bonjour immediately by scheduling network changed processing where 15339 // we will join the multicast group on each active interface. 15340 m->BonjourEnabled = 1; 15341 m->NetworkChanged = m->timenow; 15342 } 15343 } 15344 #endif 15345 if (question->WakeOnResolve) 15346 { 15347 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 15348 "[Q%u] mDNS_StartQuery_internal: Purging records before resolving", 15349 mDNSVal16(question->TargetQID)); 15350 mDNS_PurgeBeforeResolve(m, question); 15351 } 15352 } 15353 } 15354 15355 #if MDNSRESPONDER_SUPPORTS(COMMON, LOCAL_DNS_RESOLVER_DISCOVERY) 15356 // Only start the resolver discovery if the question meets condition to do so. 15357 // This ensures that we do not recursively start resolver discovery when we start a query to discover the DNS resolver. 15358 const domainname *domain_to_discover_resolver = mDNSNULL; 15359 if (dns_question_requires_resolver_discovery(question, &domain_to_discover_resolver)) 15360 { 15361 // Inside mDNS_StartQuery_internal(), we already grabbed the lock, so no need to lock it again. 15362 resolver_discovery_add(domain_to_discover_resolver, mDNSfalse); 15363 } 15364 #endif // MDNSRESPONDER_SUPPORTS(COMMON, LOCAL_DNS_RESOLVER_DISCOVERY) 15365 15366 exit: 15367 return err; 15368 } 15369 15370 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held) 15371 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta) 15372 { 15373 debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype)); 15374 // This function may be called anytime to free the zone information.The question may or may not have stopped. 15375 // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not 15376 // call it again 15377 if (nta->question.ThisQInterval != -1) 15378 { 15379 mDNS_StopQuery_internal(m, &nta->question); 15380 if (nta->question.ThisQInterval != -1) 15381 { 15382 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "CancelGetZoneData: Question "PRI_DM_NAME" (" PUB_S ") ThisQInterval %d not -1", 15383 DM_NAME_PARAM(&nta->question.qname), DNSTypeName(nta->question.qtype), nta->question.ThisQInterval); 15384 } 15385 } 15386 mDNSPlatformMemFree(nta); 15387 } 15388 15389 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question) 15390 { 15391 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 15392 // Must reset the question's parameters to the original values if it is a DNSSEC question. 15393 dnssec_handle_question_stop(question); 15394 #endif 15395 15396 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_PUSH) && !defined(UNIT_TEST) 15397 // Do not stop DNS push activity if we are restarting this question. 15398 if (m->RestartQuestion != question && dns_question_uses_dns_push(question)) 15399 { 15400 dns_push_handle_question_stop(m, question); 15401 } 15402 #endif 15403 15404 CacheGroup *cg = CacheGroupForName(m, question->qnamehash, &question->qname); 15405 CacheRecord *cr; 15406 DNSQuestion **qp = &m->Questions; 15407 const mDNSu32 request_id = question->request_id; 15408 const mDNSu16 question_id = mDNSVal16(question->TargetQID); 15409 15410 //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype)); 15411 15412 if (LocalOnlyOrP2PInterface(question->InterfaceID)) 15413 qp = &m->LocalOnlyQuestions; 15414 while (*qp && *qp != question) qp=&(*qp)->next; 15415 if (*qp) *qp = (*qp)->next; 15416 else 15417 { 15418 #if !ForceAlerts 15419 if (question->ThisQInterval >= 0) // Only log error message if the query was supposed to be active 15420 #endif 15421 { 15422 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_FAULT, 15423 "[R%u->Q%u] mDNS_StopQuery_internal: Question " PRI_DM_NAME " (" PUB_S ") not found in active list.", 15424 request_id, question_id, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype)); 15425 } 15426 return(mStatus_BadReferenceErr); 15427 } 15428 15429 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 15430 if (!LocalOnlyOrP2PInterface(question->InterfaceID) && mDNSOpaque16IsZero(question->TargetQID)) 15431 { 15432 if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1) 15433 m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond)); 15434 m->NumAllInterfaceQuestions--; 15435 } 15436 #endif 15437 if (question->request_id == 0) 15438 { 15439 // request_id == 0 indicates that the query is stopped by mDNSResponder itself, in which case no request 15440 // level log is available. Therefore, we need to print the query stop log message to indicate that 15441 // mDNSResponder has stopped a query internally. 15442 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 15443 "[Q%u] mDNS_StopQuery_internal STOP -- name hash: %x", 15444 mDNSVal16(question->TargetQID), mDNS_DomainNameFNV1aHash(&question->qname)); 15445 } 15446 15447 // Take care to cut question from list *before* calling UpdateQuestionDuplicates 15448 UpdateQuestionDuplicates(m, question); 15449 // But don't trash ThisQInterval until afterwards. 15450 question->ThisQInterval = -1; 15451 15452 // If there are any cache records referencing this as their active question, then see if there is any 15453 // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL. 15454 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 15455 { 15456 if (cr->CRActiveQuestion == question) 15457 { 15458 DNSQuestion *q; 15459 DNSQuestion *replacement = mDNSNULL; 15460 // If we find an active question that is answered by this cached record, use it as the cache record's 15461 // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive 15462 // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events 15463 // via CacheRecordRmv() when the cache record expires. 15464 for (q = m->Questions; q && (q != m->NewQuestions); q = q->next) 15465 { 15466 if (!q->DuplicateOf && !q->Suppressed && CacheRecordAnswersQuestion(cr, q)) 15467 { 15468 if (q->ThisQInterval > 0) 15469 { 15470 replacement = q; 15471 break; 15472 } 15473 else if (!replacement) 15474 { 15475 replacement = q; 15476 } 15477 } 15478 } 15479 if (replacement) 15480 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question " 15481 "CurrentAnswers %d, Suppressed %d", replacement, CRDisplayString(m,cr), question->CurrentAnswers, replacement->CurrentAnswers, replacement->Suppressed); 15482 cr->CRActiveQuestion = replacement; // Question used to be active; new value may or may not be null 15483 if (!replacement) m->rrcache_active--; // If no longer active, decrement rrcache_active count 15484 } 15485 } 15486 15487 // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at, 15488 // bump its pointer forward one question. 15489 if (m->CurrentQuestion == question) 15490 { 15491 debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)", 15492 question->qname.c, DNSTypeName(question->qtype)); 15493 m->CurrentQuestion = question->next; 15494 } 15495 15496 if (m->NewQuestions == question) 15497 { 15498 debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)", 15499 question->qname.c, DNSTypeName(question->qtype)); 15500 m->NewQuestions = question->next; 15501 } 15502 15503 if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next; 15504 15505 if (m->RestartQuestion == question) 15506 { 15507 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StopQuery_internal: Just deleted the current restart question: " PRI_DM_NAME " (" PUB_S ")", 15508 DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype)); 15509 m->RestartQuestion = question->next; 15510 } 15511 15512 // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions 15513 question->next = mDNSNULL; 15514 15515 // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype)); 15516 15517 // And finally, cancel any associated GetZoneData operation that's still running. 15518 // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list, 15519 // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already 15520 // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary 15521 // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query. 15522 if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; } 15523 if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; } 15524 15525 if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived) 15526 { 15527 // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal. 15528 DNSQuestion *q; 15529 for (q = m->Questions; q; q=q->next) 15530 if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break; 15531 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 15532 if (!q) 15533 { 15534 if (!m->LLQNAT.clientCallback) // Should never happen, but just in case... 15535 { 15536 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StopQuery ERROR LLQNAT.clientCallback NULL"); 15537 } 15538 else 15539 { 15540 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "Stopping LLQNAT"); 15541 mDNS_StopNATOperation_internal(m, &m->LLQNAT); 15542 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running 15543 } 15544 } 15545 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 15546 // https://spc.apple.com/Guidelines.html#_100_16_2_consider_if_0_trick_for_ifelse_if 15547 if (0) {} 15548 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 15549 // If necessary, tell server it can delete this LLQ state 15550 else if (question->state == LLQ_Established) 15551 { 15552 question->ReqLease = 0; 15553 sendLLQRefresh(m, question); 15554 // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while. 15555 // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't 15556 // crash trying to access our cancelled question, but we don't cancel the TCP operation itself -- 15557 // we let that run out its natural course and complete asynchronously. 15558 if (question->tcp) 15559 { 15560 question->tcp->question = mDNSNULL; 15561 question->tcp = mDNSNULL; 15562 } 15563 } 15564 #endif 15565 15566 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) 15567 else if (question->dnsPushServer != mDNSNULL) 15568 { 15569 // UnsubscribeQuestionFromDNSPushServer() must happen before Querier_HandleStoppedDNSQuestion(), because it 15570 // checks the dnsservice to determine if the cached response answers the current long-lived query. 15571 UnsubscribeQuestionFromDNSPushServer(m, question, mDNSfalse); 15572 } 15573 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) 15574 } 15575 // wait until we send the refresh above which needs the nta 15576 if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; } 15577 15578 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 15579 Querier_HandleStoppedDNSQuestion(question); 15580 #endif 15581 15582 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 15583 DPCHandleStoppedDNSQuestion(question); 15584 #endif 15585 15586 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS_ANALYTICS) || MDNSRESPONDER_SUPPORTS(APPLE, RUNTIME_MDNS_METRICS) 15587 DNSMetricsClear(&question->metrics); 15588 #endif 15589 15590 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) 15591 DNS64ResetState(question); 15592 #endif 15593 15594 #if MDNSRESPONDER_SUPPORTS(COMMON, LOCAL_DNS_RESOLVER_DISCOVERY) 15595 const domainname *domain_to_discover_resolver = mDNSNULL; 15596 // Only stop the resolver discover if the question has required the discovery when it is started. 15597 if (dns_question_requires_resolver_discovery(question, &domain_to_discover_resolver)) 15598 { 15599 // Inside mDNS_StopQuery_internal(), we already grabbed the lock, so no need to lock it again. 15600 resolver_discovery_remove(domain_to_discover_resolver, mDNSfalse); 15601 } 15602 #endif 15603 15604 #if MDNSRESPONDER_SUPPORTS(APPLE, LOG_PRIVACY_LEVEL) 15605 if (DNSQuestionNeedsSensitiveLogging(question)) 15606 { 15607 gNumOfSensitiveLoggingEnabledQuestions--; 15608 15609 if (gNumOfSensitiveLoggingEnabledQuestions == 0) 15610 { 15611 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 15612 "[Q%u] Last question that enables sensitive logging is stopped.", mDNSVal16(question->TargetQID)); 15613 gSensitiveLoggingEnabled = mDNSfalse; 15614 } 15615 else 15616 { 15617 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "[Q%u] number of sensitive logging enabled questions: " 15618 "%u.", mDNSVal16(question->TargetQID), gNumOfSensitiveLoggingEnabledQuestions); 15619 } 15620 } 15621 #endif // MDNSRESPONDER_SUPPORTS(APPLE, LOG_PRIVACY_LEVEL) 15622 15623 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 15624 // Must drop the lock before releasing DNSSEC context because its finalizer may stop other questions, which would 15625 // grab the lock again. 15626 // For example: 15627 // Stopping www.ietf.org. AAAA will stop ietf.org. DNSKEY 15628 // Stopping ietf.org. DNSKEY will stop ietf.org. DS 15629 // ...until the root trust anchor is reached. 15630 mDNS_DropLockBeforeCallback(); 15631 MDNS_DISPOSE_DNSSEC_OBJ(question->dnssec); 15632 mDNS_ReclaimLockAfterCallback(); 15633 #endif 15634 if (question->DupSuppress) 15635 { 15636 mDNSPlatformMemFree(question->DupSuppress); 15637 question->DupSuppress = mDNSNULL; 15638 } 15639 return(mStatus_NoError); 15640 } 15641 15642 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question) 15643 { 15644 mStatus status; 15645 mDNS_Lock(m); 15646 status = mDNS_StartQuery_internal(m, question); 15647 mDNS_Unlock(m); 15648 return(status); 15649 } 15650 15651 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question) 15652 { 15653 mStatus status; 15654 mDNS_Lock(m); 15655 status = mDNS_StopQuery_internal(m, question); 15656 mDNS_Unlock(m); 15657 return(status); 15658 } 15659 15660 mDNSlocal mStatus mDNS_CheckQuestionBeforeStoppingQuery(const mDNS *const m, const DNSQuestion *const question) 15661 { 15662 mStatus err = mStatus_NoError; 15663 15664 DNSQuestion *const *qp = LocalOnlyOrP2PInterface(question->InterfaceID) ? &m->LocalOnlyQuestions : &m->Questions; 15665 15666 // Check if the current question is in mDNSResponder's question list. 15667 for (; *qp != mDNSNULL && *qp != question; qp = &(*qp)->next) 15668 ; 15669 if (*qp == mDNSNULL) 15670 { 15671 #if !ForceAlerts 15672 if (question->ThisQInterval >= 0) 15673 #endif 15674 { 15675 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_FAULT, "Question not found in the active list - " 15676 "qname: " PRI_DM_NAME ", qtype: " PUB_S ".", DM_NAME_PARAM(&question->qname), 15677 DNSTypeName(question->qtype)); 15678 } 15679 err = mStatus_BadReferenceErr; 15680 } 15681 15682 return err; 15683 } 15684 15685 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs 15686 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls. 15687 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback 15688 // specifically to catch and report if the client callback does try to make API calls 15689 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question) 15690 { 15691 DNSQuestion *qq; 15692 mDNS_Lock(m); 15693 15694 // Check if question is new -- don't want to give remove events for a question we haven't even answered yet 15695 for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break; 15696 15697 // Ensure that the question is still in the mDNSResponder's question list, or there is no point to deliver RMV 15698 // event. 15699 const mStatus err = mDNS_CheckQuestionBeforeStoppingQuery(m, question); 15700 if (err != mStatus_NoError) 15701 { 15702 goto exit; 15703 } 15704 15705 if (qq == mDNSNULL) // The question being stopped is not a new question. 15706 { 15707 const CacheRecord *cr; 15708 CacheGroup *const cg = CacheGroupForName(m, question->qnamehash, &question->qname); 15709 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 15710 "[Q%u] Generating RMV events because the question will be stopped - " 15711 "qname: " PRI_DM_NAME ", qtype: " PUB_S ".", mDNSVal16(question->TargetQID), 15712 DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype)); 15713 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next) 15714 { 15715 if (cr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameCacheRecordAnswersQuestion(cr, question)) 15716 { 15717 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls 15718 if (question->QuestionCallback) 15719 { 15720 question->QuestionCallback(m, question, &cr->resrec, QC_rmv); 15721 } 15722 } 15723 } 15724 } 15725 15726 mDNS_StopQuery_internal(m, question); 15727 15728 exit: 15729 mDNS_Unlock(m); 15730 return err; 15731 } 15732 15733 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr) 15734 { 15735 mStatus status; 15736 mDNS_Lock(m); 15737 status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); 15738 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0); 15739 mDNS_Unlock(m); 15740 return(status); 15741 } 15742 15743 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr) 15744 { 15745 mStatus status = mStatus_BadReferenceErr; 15746 CacheRecord *cr; 15747 mDNS_Lock(m); 15748 cr = FindIdenticalRecordInCache(m, rr); 15749 debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr)); 15750 if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); 15751 if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0); 15752 mDNS_Unlock(m); 15753 return(status); 15754 } 15755 15756 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question, 15757 const domainname *const srv, const domainname *const domain, 15758 const mDNSInterfaceID InterfaceID, mDNSu32 flags, 15759 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass, 15760 mDNSQuestionCallback *Callback, void *Context) 15761 { 15762 question->InterfaceID = InterfaceID; 15763 question->flags = flags; 15764 question->qtype = kDNSType_PTR; 15765 question->qclass = kDNSClass_IN; 15766 question->LongLived = mDNStrue; 15767 question->ExpectUnique = mDNSfalse; 15768 question->ForceMCast = ForceMCast; 15769 question->ReturnIntermed = (flags & kDNSServiceFlagsReturnIntermediates) != 0; 15770 question->SuppressUnusable = mDNSfalse; 15771 question->AppendSearchDomains = mDNSfalse; 15772 question->TimeoutQuestion = 0; 15773 question->WakeOnResolve = 0; 15774 question->UseBackgroundTraffic = useBackgroundTrafficClass; 15775 question->ProxyQuestion = 0; 15776 question->QuestionCallback = Callback; 15777 question->QuestionContext = Context; 15778 15779 if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain)) 15780 return(mStatus_BadParamErr); 15781 15782 if (question->request_id != 0) 15783 { 15784 // This is the first place where we know the full name of a browsing query. 15785 // After: [R6] DNSServiceBrowse -> SubBrowser START -- qname: _companion-link._tcp.local.(334e2060) 15786 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 15787 "[R%u] DNSServiceBrowse -> SubBrowser START -- qname: " PRI_DM_NAME " (%x)", 15788 question->request_id, DM_NAME_PARAM(&question->qname), mDNS_DomainNameFNV1aHash(&question->qname)); 15789 } 15790 15791 return(mDNS_StartQuery_internal(m, question)); 15792 } 15793 15794 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question, 15795 const domainname *const srv, const domainname *const domain, 15796 const mDNSInterfaceID InterfaceID, mDNSu32 flags, 15797 mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass, 15798 mDNSQuestionCallback *Callback, void *Context) 15799 { 15800 mStatus status; 15801 mDNS_Lock(m); 15802 status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context); 15803 mDNS_Unlock(m); 15804 return(status); 15805 } 15806 15807 mDNSlocal mStatus mDNS_GetDomains_Internal(mDNS *const m, DNSQuestion *const question, const mDNS_DomainType DomainType, 15808 const domainname * domain, const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *const Callback, 15809 void *const Context) 15810 { 15811 question->InterfaceID = InterfaceID; 15812 question->flags = 0; 15813 question->qtype = kDNSType_PTR; 15814 question->qclass = kDNSClass_IN; 15815 question->LongLived = mDNSfalse; 15816 question->ExpectUnique = mDNSfalse; 15817 question->ForceMCast = mDNSfalse; 15818 question->ReturnIntermed = mDNSfalse; 15819 question->SuppressUnusable = mDNSfalse; 15820 question->AppendSearchDomains = mDNSfalse; 15821 question->TimeoutQuestion = 0; 15822 question->WakeOnResolve = 0; 15823 question->UseBackgroundTraffic = mDNSfalse; 15824 question->ProxyQuestion = 0; 15825 question->pid = mDNSPlatformGetPID(); 15826 question->euid = 0; 15827 question->QuestionCallback = Callback; 15828 question->QuestionContext = Context; 15829 if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr); 15830 if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr); 15831 if (!domain) domain = &localdomain; 15832 if (!AppendDomainName(&question->qname, domain)) return(mStatus_BadParamErr); 15833 return(mDNS_StartQuery_internal(m, question)); 15834 } 15835 15836 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, const mDNS_DomainType DomainType, 15837 const domainname *const domain, const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *const Callback, 15838 void *const Context) 15839 { 15840 mDNS_Lock(m); 15841 const mStatus err = mDNS_GetDomains_Internal(m, question, DomainType, domain, InterfaceID, Callback, Context); 15842 mDNS_Unlock(m); 15843 15844 return err; 15845 } 15846 15847 static const char *const mDNS_DomainType_Description[] = 15848 { 15849 "browse domain", // Use index mDNS_DomainTypeBrowse to get. 15850 "default browse domain", // Use index mDNS_DomainTypeBrowseDefault to get. 15851 "automatic browse domain", // Use index mDNS_DomainTypeBrowseAutomatic to get. 15852 "registration domain", // Use index mDNS_DomainTypeRegistration to get. 15853 "default registration domain", // Use index mDNS_DomainTypeRegistrationDefault to get. 15854 }; 15855 #ifdef check_compile_time 15856 // The index count must match the array size above. 15857 check_compile_time(countof(mDNS_DomainType_Description) == mDNS_DomainTypeMaxCount); 15858 #endif 15859 15860 mDNSlocal void mDNS_DeregisterDomainsDiscoveredForDomainEnumeration(mDNS *m, DomainEnumerationOp *op, mDNSu32 type); 15861 15862 mDNSlocal mStatus mDNS_SetUpDomainEnumeration(mDNS *const m, DomainEnumerationOp *const op, 15863 const mDNS_DomainType type) 15864 { 15865 mStatus err; 15866 15867 // Currently, we only support doing domain enumeration looking for automatic browse domain. 15868 if (type != mDNS_DomainTypeBrowseAutomatic) 15869 { 15870 err = mStatus_UnsupportedErr; 15871 goto exit; 15872 } 15873 15874 DomainEnumerationWithType *const enumeration = op->enumerations[type]; 15875 if (enumeration == mDNSNULL) 15876 { 15877 // No operations have been done for this domain enumeration type. 15878 err = mStatus_NoError; 15879 goto exit; 15880 } 15881 15882 switch (enumeration->state) 15883 { 15884 case DomainEnumerationState_Stopped: 15885 if (enumeration->activeClientCount == 1) 15886 { 15887 // If there is a client who needs to do domain enumeration, start it. 15888 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "Starting the " PUB_S " enumeration " 15889 "- domain: " PRI_DM_NAME ".", mDNS_DomainType_Description[type], DM_NAME_PARAM(&op->name)); 15890 15891 // Avoid the build failure for the target mDNSNetMonitor and non-Apple builds. 15892 #if (!defined(NET_MONITOR) || !NET_MONITOR) && defined(__APPLE__) && !defined(POSIX_BUILD) 15893 err = mDNS_GetDomains_Internal(m, &enumeration->question, type, &op->name, mDNSInterface_Any, 15894 FoundNonLocalOnlyAutomaticBrowseDomain, mDNSNULL); 15895 #else 15896 err = mStatus_UnsupportedErr; 15897 #endif 15898 if (err != mStatus_NoError) 15899 { 15900 goto exit; 15901 } 15902 15903 enumeration->state = DomainEnumerationState_Started; 15904 } 15905 // If there are more than one clients need to do enumeration, the process has begun, no need to start again. 15906 break; 15907 15908 case DomainEnumerationState_Started: 15909 if (enumeration->activeClientCount == 0) 15910 { 15911 // If the number of client that need domain enumeration becomes 0, get ready to stop it. 15912 // However, we give it a grace period so that the enumeration will not be stopped immediately, to 15913 // avoid the case where a single client starts and stops request too frequently. 15914 const mDNSs32 gracePeriodInSeconds = 60; 15915 15916 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "Planning to stop the " PUB_S " enumeration " 15917 "- domain: " PRI_DM_NAME ", grace period: %ds.", mDNS_DomainType_Description[type], 15918 DM_NAME_PARAM(&op->name), gracePeriodInSeconds); 15919 15920 enumeration->state = DomainEnumerationState_StopInProgress; 15921 15922 // Ensure that we will check the stop time when the grace period has passed. 15923 const mDNSs32 gracePeriodPlatformTime = gracePeriodInSeconds * mDNSPlatformOneSecond; 15924 enumeration->nextStopTime = NonZeroTime(m->timenow + gracePeriodPlatformTime); 15925 } 15926 break; 15927 15928 case DomainEnumerationState_StopInProgress: 15929 if (enumeration->activeClientCount == 0 && m->timenow - enumeration->nextStopTime >= 0) 15930 { 15931 // If there is no active client that needs the domain enumeration and we have passed the scheduled 15932 // stop time, stop the enumeration immediately. 15933 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "Stopping the " PUB_S " enumeration " 15934 "- domain: " PRI_DM_NAME ".", mDNS_DomainType_Description[type], DM_NAME_PARAM(&op->name)); 15935 15936 err = mDNS_StopGetDomains_Internal(m, &enumeration->question); 15937 if (err != mStatus_NoError) 15938 { 15939 goto exit; 15940 } 15941 15942 mDNS_DeregisterDomainsDiscoveredForDomainEnumeration(m, op, type); 15943 15944 enumeration->state = DomainEnumerationState_Stopped; 15945 } 15946 else if (enumeration->activeClientCount == 1) 15947 { 15948 // If there is new client that needs the domain enumeration, terminate the stopping process and go back 15949 // to the active mode. 15950 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "Resuming the " PUB_S " enumeration " 15951 "- active client count: %u, domain: " PRI_DM_NAME ".", mDNS_DomainType_Description[type], 15952 enumeration->activeClientCount, DM_NAME_PARAM(&op->name)); 15953 15954 // Reschedule the next event since our stopping process is terminated. 15955 enumeration->state = DomainEnumerationState_Started; 15956 } 15957 break; 15958 15959 MDNS_COVERED_SWITCH_DEFAULT: 15960 break; 15961 } 15962 15963 err = mStatus_NoError; 15964 exit: 15965 return err; 15966 } 15967 15968 mDNSexport mStatus mDNS_StartDomainEnumeration(mDNS *const m, const domainname *const domain, const mDNS_DomainType type) 15969 { 15970 mStatus err; 15971 mDNS_Lock(m); 15972 15973 DomainEnumerationOp *op = mDNSNULL; 15974 15975 for (op = m->domainsToDoEnumeration; op != mDNSNULL; op = op->next) 15976 { 15977 if (SameDomainName(&op->name, domain)) 15978 { 15979 break; 15980 } 15981 } 15982 15983 if (op == mDNSNULL) 15984 { 15985 err = mStatus_BadParamErr; 15986 goto exit; 15987 } 15988 15989 if (op->enumerations[type] == mDNSNULL) 15990 { 15991 op->enumerations[type] = mDNSPlatformMemAllocateClear(sizeof(*op->enumerations[type])); 15992 if (op->enumerations[type] == mDNSNULL) 15993 { 15994 err = mStatus_NoMemoryErr; 15995 goto exit; 15996 } 15997 } 15998 15999 op->enumerations[type]->activeClientCount++; 16000 16001 err = mDNS_SetUpDomainEnumeration(m, op, type); 16002 16003 exit: 16004 mDNS_Unlock(m); 16005 return err; 16006 } 16007 16008 mDNSexport mStatus mDNS_StopDomainEnumeration(mDNS *const m, const domainname *const domain, const mDNS_DomainType type) 16009 { 16010 mStatus err; 16011 mDNS_Lock(m); 16012 16013 DomainEnumerationOp *op = mDNSNULL; 16014 16015 for (op = m->domainsToDoEnumeration; op != mDNSNULL; op = op->next) 16016 { 16017 if (SameDomainName(&op->name, domain)) 16018 { 16019 break; 16020 } 16021 } 16022 16023 if (op == mDNSNULL || op->enumerations[type] == mDNSNULL) 16024 { 16025 err = mStatus_BadParamErr; 16026 goto exit; 16027 } 16028 16029 if ( op->enumerations[type]->activeClientCount == 0) 16030 { 16031 err = mStatus_Invalid; 16032 goto exit; 16033 } 16034 16035 op->enumerations[type]->activeClientCount--; 16036 16037 err = mDNS_SetUpDomainEnumeration(m, op, type); 16038 16039 exit: 16040 mDNS_Unlock(m); 16041 return err; 16042 } 16043 16044 mDNSexport mStatus mDNS_AddDomainDiscoveredForDomainEnumeration(mDNS *const m, const domainname *const domain, 16045 const mDNS_DomainType type, const domainname *const domainDiscovered) 16046 { 16047 mStatus err; 16048 mDNS_Lock(m); 16049 16050 DomainEnumerationOp *op = mDNSNULL; 16051 16052 for (op = m->domainsToDoEnumeration; op != mDNSNULL; op = op->next) 16053 { 16054 if (SameDomainName(&op->name, domain)) 16055 { 16056 break; 16057 } 16058 } 16059 16060 if (op == mDNSNULL || op->enumerations[type] == mDNSNULL) 16061 { 16062 err = mStatus_BadParamErr; 16063 goto exit; 16064 } 16065 16066 // Remember the domain name we discovered so that when the domain enumeration is stopped when we can remove them 16067 // from the auth record set. 16068 16069 EnumeratedDomainList *const domainDiscoveredItem = mDNSPlatformMemAllocateClear(sizeof(*domainDiscoveredItem)); 16070 if (domainDiscoveredItem == mDNSNULL) 16071 { 16072 err = mStatus_NoMemoryErr; 16073 goto exit; 16074 } 16075 16076 AssignDomainName(&domainDiscoveredItem->name, domainDiscovered); 16077 16078 domainDiscoveredItem->next = op->enumerations[type]->domainList; 16079 op->enumerations[type]->domainList = domainDiscoveredItem; 16080 err = mStatus_NoError; 16081 16082 exit: 16083 mDNS_Unlock(m); 16084 return err; 16085 } 16086 16087 mDNSexport mStatus mDNS_RemoveDomainDiscoveredForDomainEnumeration(mDNS *const m, const domainname *const domain, 16088 const mDNS_DomainType type, const domainname *const domainDiscovered) 16089 { 16090 mStatus err; 16091 mDNS_Lock(m); 16092 16093 DomainEnumerationOp *op = mDNSNULL; 16094 16095 for (op = m->domainsToDoEnumeration; op != mDNSNULL; op = op->next) 16096 { 16097 if (SameDomainName(&op->name, domain)) 16098 { 16099 break; 16100 } 16101 } 16102 16103 if (op == mDNSNULL || op->enumerations[type] == mDNSNULL) 16104 { 16105 err = mStatus_BadParamErr; 16106 goto exit; 16107 } 16108 16109 EnumeratedDomainList *node; 16110 EnumeratedDomainList **ptr = &op->enumerations[type]->domainList; 16111 while ((node = *ptr) != mDNSNULL) 16112 { 16113 if (SameDomainName(&node->name, domainDiscovered)) 16114 { 16115 break; 16116 } 16117 ptr = &node->next; 16118 } 16119 if (node != mDNSNULL) 16120 { 16121 *ptr = node->next; 16122 mDNSPlatformMemFree(node); 16123 } 16124 16125 err = mStatus_NoError; 16126 16127 exit: 16128 mDNS_Unlock(m); 16129 return err; 16130 } 16131 16132 mDNSlocal void mDNS_DeregisterDomainsDiscoveredForDomainEnumeration(mDNS *const m, DomainEnumerationOp *const op, 16133 const mDNSu32 type) 16134 { 16135 // Given all the domain we have discovered through domain enumeration, deregister them from our cache. 16136 16137 if (op->enumerations[type] == mDNSNULL) 16138 { 16139 return; 16140 } 16141 16142 for (EnumeratedDomainList *node = op->enumerations[type]->domainList, *next = mDNSNULL; node != mDNSNULL; node = next) 16143 { 16144 next = node->next; 16145 16146 // Avoid the build failure for the target mDNSNetMonitor and non-Apple builds. 16147 #if (!defined(NET_MONITOR) || !NET_MONITOR) && defined(__APPLE__) && !defined(POSIX_BUILD) 16148 DeregisterLocalOnlyDomainEnumPTR_Internal(m, &node->name, type, mDNStrue); 16149 #else 16150 (void)m; 16151 #endif 16152 mDNSPlatformMemFree(node); 16153 } 16154 op->enumerations[type]->domainList = mDNSNULL; 16155 } 16156 16157 // *************************************************************************** 16158 // MARK: - Responder Functions 16159 16160 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr) 16161 { 16162 mStatus status; 16163 mDNS_Lock(m); 16164 status = mDNS_Register_internal(m, rr); 16165 mDNS_Unlock(m); 16166 return(status); 16167 } 16168 16169 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl, 16170 const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback) 16171 { 16172 if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata)) 16173 { 16174 LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer)); 16175 return(mStatus_Invalid); 16176 } 16177 16178 mDNS_Lock(m); 16179 16180 // If TTL is unspecified, leave TTL unchanged 16181 if (newttl == 0) newttl = rr->resrec.rroriginalttl; 16182 16183 // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory 16184 if (rr->NewRData) 16185 { 16186 RData *n = rr->NewRData; 16187 rr->NewRData = mDNSNULL; // Clear the NewRData pointer ... 16188 if (rr->UpdateCallback) 16189 rr->UpdateCallback(m, rr, n, rr->newrdlength); // ...and let the client free this memory, if necessary 16190 } 16191 16192 rr->NewRData = newrdata; 16193 rr->newrdlength = newrdlength; 16194 rr->UpdateCallback = Callback; 16195 16196 #ifndef UNICAST_DISABLED 16197 if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && AuthRecord_uDNS(rr)) 16198 { 16199 mStatus status = uDNS_UpdateRecord(m, rr); 16200 // The caller frees the memory on error, don't retain stale pointers 16201 if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; } 16202 mDNS_Unlock(m); 16203 return(status); 16204 } 16205 #endif 16206 16207 if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl && rr->resrec.rdlength == newrdlength && 16208 mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength))) 16209 CompleteRDataUpdate(m, rr); 16210 else 16211 { 16212 rr->AnnounceCount = InitialAnnounceCount; 16213 InitializeLastAPTime(m, rr); 16214 while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr); 16215 if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--; 16216 if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval); 16217 if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1); 16218 if (rr->UpdateCredits <= 5) 16219 { 16220 mDNSu32 delay = 6 - rr->UpdateCredits; // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum 16221 if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond); 16222 rr->ThisAPInterval *= 4; 16223 rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval; 16224 LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s", 16225 rr->resrec.name->c, delay, delay > 1 ? "s" : ""); 16226 } 16227 rr->resrec.rroriginalttl = newttl; 16228 } 16229 16230 mDNS_Unlock(m); 16231 return(mStatus_NoError); 16232 } 16233 16234 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change 16235 // the record list and/or question list. 16236 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 16237 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr) 16238 { 16239 mStatus status; 16240 mDNS_Lock(m); 16241 status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal); 16242 mDNS_Unlock(m); 16243 return(status); 16244 } 16245 16246 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface 16247 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result); 16248 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16249 mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *m, AuthRecord *rr, mStatus result); 16250 #endif 16251 16252 mDNSlocal AuthRecord *GetInterfaceAddressRecord(NetworkInterfaceInfo *intf, mDNSBool forRandHostname) 16253 { 16254 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16255 return(forRandHostname ? &intf->RR_AddrRand : &intf->RR_A); 16256 #else 16257 (void)forRandHostname; // Unused. 16258 return(&intf->RR_A); 16259 #endif 16260 } 16261 16262 mDNSlocal AuthRecord *GetFirstAddressRecordEx(const mDNS *const m, const mDNSBool forRandHostname) 16263 { 16264 NetworkInterfaceInfo *intf; 16265 for (intf = m->HostInterfaces; intf; intf = intf->next) 16266 { 16267 if (!intf->Advertise) continue; 16268 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16269 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue; 16270 #endif 16271 return(GetInterfaceAddressRecord(intf, forRandHostname)); 16272 } 16273 return(mDNSNULL); 16274 } 16275 #if !MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16276 #define GetFirstAddressRecord(M) GetFirstAddressRecordEx(M, mDNSfalse) 16277 #endif 16278 16279 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface. 16280 // (It's a set of records, not a set of interfaces.) 16281 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16282 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool useRandomizedHostname) 16283 #else 16284 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set) 16285 #endif 16286 { 16287 const domainname *hostname; 16288 mDNSRecordCallback *hostnameCallback; 16289 AuthRecord *addrAR; 16290 AuthRecord *ptrAR; 16291 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16292 const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID); 16293 #endif 16294 mDNSu8 addrRecordType; 16295 char buffer[MAX_REVERSE_MAPPING_NAME]; 16296 16297 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16298 if (interfaceIsAWDL || useRandomizedHostname) 16299 { 16300 hostname = &m->RandomizedHostname; 16301 hostnameCallback = mDNS_RandomizedHostNameCallback; 16302 } 16303 else 16304 #endif 16305 { 16306 hostname = &m->MulticastHostname; 16307 hostnameCallback = mDNS_HostNameCallback; 16308 } 16309 16310 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16311 if (!interfaceIsAWDL && useRandomizedHostname) 16312 { 16313 addrAR = &set->RR_AddrRand; 16314 ptrAR = mDNSNULL; 16315 } 16316 else 16317 #endif 16318 { 16319 addrAR = &set->RR_A; 16320 ptrAR = &set->RR_PTR; 16321 } 16322 if (addrAR->resrec.RecordType != kDNSRecordTypeUnregistered) return; 16323 16324 addrRecordType = set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique; 16325 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16326 if (hostname == &m->RandomizedHostname) addrRecordType = kDNSRecordTypeKnownUnique; 16327 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "AdvertiseInterface: Advertising " PUB_S " hostname on interface " PUB_S, 16328 (hostname == &m->RandomizedHostname) ? "randomized" : "normal", set->ifname); 16329 #else 16330 LogInfo("AdvertiseInterface: Advertising for ifname %s", set->ifname); 16331 #endif 16332 16333 // Send dynamic update for non-linklocal IPv4 Addresses 16334 mDNS_SetupResourceRecord(addrAR, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, addrRecordType, AuthRecordAny, hostnameCallback, set); 16335 if (ptrAR) mDNS_SetupResourceRecord(ptrAR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL); 16336 16337 #if ANSWER_REMOTE_HOSTNAME_QUERIES 16338 addrAR->AllowRemoteQuery = mDNStrue; 16339 if (ptrAR) ptrAR->AllowRemoteQuery = mDNStrue; 16340 #endif 16341 // 1. Set up Address record to map from host name ("foo.local.") to IP address 16342 // 2. Set up reverse-lookup PTR record to map from our address back to our host name 16343 AssignDomainName(&addrAR->namestorage, hostname); 16344 if (set->ip.type == mDNSAddrType_IPv4) 16345 { 16346 addrAR->resrec.rrtype = kDNSType_A; 16347 addrAR->resrec.rdata->u.ipv4 = set->ip.ip.v4; 16348 // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code 16349 mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.", 16350 set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]); 16351 } 16352 else if (set->ip.type == mDNSAddrType_IPv6) 16353 { 16354 int i; 16355 addrAR->resrec.rrtype = kDNSType_AAAA; 16356 addrAR->resrec.rdata->u.ipv6 = set->ip.ip.v6; 16357 for (i = 0; i < 16; i++) 16358 { 16359 static const char hexValues[] = "0123456789ABCDEF"; 16360 buffer[i * 4 ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F]; 16361 buffer[i * 4 + 1] = '.'; 16362 buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4]; 16363 buffer[i * 4 + 3] = '.'; 16364 } 16365 mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa."); 16366 } 16367 16368 if (ptrAR) 16369 { 16370 MakeDomainNameFromDNSNameString(&ptrAR->namestorage, buffer); 16371 ptrAR->AutoTarget = Target_AutoHost; // Tell mDNS that the target of this PTR is to be kept in sync with our host name 16372 ptrAR->ForceMCast = mDNStrue; // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server 16373 } 16374 16375 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16376 addrAR->RRSet = (uintptr_t)(interfaceIsAWDL ? addrAR : GetFirstAddressRecordEx(m, useRandomizedHostname)); 16377 #else 16378 addrAR->RRSet = (uintptr_t)(void *)GetFirstAddressRecord(m); 16379 #endif 16380 if (!addrAR->RRSet) addrAR->RRSet = (uintptr_t)addrAR; 16381 mDNS_Register_internal(m, addrAR); 16382 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Initialized RRSet for " PRI_S, ARDisplayString(m, addrAR)); 16383 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "RRSet: %" PRIxPTR "", addrAR->RRSet); 16384 if (ptrAR) mDNS_Register_internal(m, ptrAR); 16385 16386 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 16387 // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc 16388 D2D_start_advertising_interface(set); 16389 #endif 16390 } 16391 16392 mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set) 16393 { 16394 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16395 if (mDNSPlatformInterfaceIsAWDL(set->InterfaceID)) 16396 { 16397 if ((m->AutoTargetAWDLIncludedCount > 0) || (m->AutoTargetAWDLOnlyCount > 0)) 16398 { 16399 AdvertiseInterface(m, set, mDNSfalse); 16400 } 16401 } 16402 else 16403 { 16404 if (m->AutoTargetServices > 0) AdvertiseInterface(m, set, mDNSfalse); 16405 if (m->AutoTargetAWDLIncludedCount > 0) AdvertiseInterface(m, set, mDNStrue); 16406 } 16407 #else 16408 if (m->AutoTargetServices > 0) AdvertiseInterface(m, set); 16409 #endif 16410 } 16411 16412 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags) 16413 { 16414 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16415 const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID); 16416 #endif 16417 16418 // Unregister these records. 16419 // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform 16420 // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it. 16421 // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered. 16422 // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal(). 16423 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16424 if ((!interfaceIsAWDL && (flags & kDeadvertiseFlag_NormalHostname)) || 16425 ( interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname))) 16426 #else 16427 if (flags & kDeadvertiseFlag_NormalHostname) 16428 #endif 16429 { 16430 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "DeadvertiseInterface: Deadvertising " PUB_S " hostname on interface " PUB_S, 16431 (flags & kDeadvertiseFlag_RandHostname) ? "randomized" : "normal", set->ifname); 16432 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 16433 D2D_stop_advertising_interface(set); 16434 #endif 16435 if (set->RR_A.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A, mDNS_Dereg_normal); 16436 if (set->RR_PTR.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal); 16437 } 16438 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16439 if (!interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname)) 16440 { 16441 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "DeadvertiseInterface: Deadvertising randomized hostname on interface " PUB_S, set->ifname); 16442 AuthRecord *const ar = &set->RR_AddrRand; 16443 if (ar->resrec.RecordType) mDNS_Deregister_internal(m, ar, mDNS_Dereg_normal); 16444 } 16445 #endif 16446 } 16447 16448 // Change target host name for record. 16449 mDNSlocal void UpdateTargetHostName(mDNS *const m, AuthRecord *const rr) 16450 { 16451 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 16452 // If this record was also registered with any D2D plugins, stop advertising 16453 // the version with the old host name. 16454 D2D_stop_advertising_record(rr); 16455 #endif 16456 16457 SetTargetToHostName(m, rr); 16458 16459 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D) 16460 // Advertise the record with the updated host name with the D2D plugins if appropriate. 16461 D2D_start_advertising_record(rr); 16462 #endif 16463 } 16464 16465 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m, DeadvertiseFlags flags) 16466 { 16467 NetworkInterfaceInfo *intf; 16468 for (intf = m->HostInterfaces; intf; intf = intf->next) 16469 { 16470 if (intf->Advertise) DeadvertiseInterface(m, intf, flags); 16471 } 16472 } 16473 16474 mDNSexport void mDNS_SetFQDN(mDNS *const m) 16475 { 16476 domainname newmname; 16477 AuthRecord *rr; 16478 newmname.c[0] = 0; 16479 16480 if (!AppendDomainLabel(&newmname, &m->hostlabel)) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; } 16481 if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; } 16482 16483 mDNS_Lock(m); 16484 16485 if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged"); 16486 else 16487 { 16488 AssignDomainName(&m->MulticastHostname, &newmname); 16489 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_NormalHostname); 16490 AdvertiseNecessaryInterfaceRecords(m); 16491 } 16492 16493 // 3. Make sure that any AutoTarget SRV records (and the like) get updated 16494 for (rr = m->ResourceRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr); 16495 for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr); 16496 16497 mDNS_Unlock(m); 16498 } 16499 16500 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result) 16501 { 16502 (void)rr; // Unused parameter 16503 16504 #if MDNS_DEBUGMSGS 16505 { 16506 char *msg = "Unknown result"; 16507 if (result == mStatus_NoError) msg = "Name registered"; 16508 else if (result == mStatus_NameConflict) msg = "Name conflict"; 16509 debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result); 16510 } 16511 #endif 16512 16513 if (result == mStatus_NoError) 16514 { 16515 // Notify the client that the host name is successfully registered 16516 if (m->MainCallback) 16517 m->MainCallback(m, mStatus_NoError); 16518 } 16519 else if (result == mStatus_NameConflict) 16520 { 16521 domainlabel oldlabel = m->hostlabel; 16522 16523 // 1. First give the client callback a chance to pick a new name 16524 if (m->MainCallback) 16525 m->MainCallback(m, mStatus_NameConflict); 16526 16527 // 2. If the client callback didn't do it, add (or increment) an index ourselves 16528 // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to 16529 // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again. 16530 if (SameDomainLabel(m->hostlabel.c, oldlabel.c)) 16531 IncrementLabelSuffix(&m->hostlabel, mDNSfalse); 16532 16533 // 3. Generate the FQDNs from the hostlabel, 16534 // and make sure all SRV records, etc., are updated to reference our new hostname 16535 mDNS_SetFQDN(m); 16536 LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c); 16537 } 16538 else if (result == mStatus_MemFree) 16539 { 16540 // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by 16541 // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface 16542 debugf("mDNS_HostNameCallback: MemFree (ignored)"); 16543 } 16544 else 16545 LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result, rr->resrec.name->c); 16546 } 16547 16548 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16549 mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *const m, AuthRecord *const addrRecord, const mStatus result) 16550 { 16551 (void)addrRecord; // Unused parameter 16552 16553 if (result == mStatus_NameConflict) 16554 { 16555 AuthRecord *rr; 16556 domainlabel newUUIDLabel; 16557 16558 GetRandomUUIDLabel(&newUUIDLabel); 16559 if (SameDomainLabel(newUUIDLabel.c, m->RandomizedHostname.c)) 16560 { 16561 IncrementLabelSuffix(&newUUIDLabel, mDNSfalse); 16562 } 16563 16564 mDNS_Lock(m); 16565 16566 m->RandomizedHostname.c[0] = 0; 16567 AppendDomainLabel(&m->RandomizedHostname, &newUUIDLabel); 16568 AppendLiteralLabelString(&m->RandomizedHostname, "local"); 16569 16570 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_RandHostname); 16571 AdvertiseNecessaryInterfaceRecords(m); 16572 for (rr = m->ResourceRecords; rr; rr = rr->next) 16573 { 16574 if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr); 16575 } 16576 for (rr = m->DuplicateRecords; rr; rr = rr->next) 16577 { 16578 if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr); 16579 } 16580 16581 mDNS_Unlock(m); 16582 } 16583 } 16584 #endif 16585 16586 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active) 16587 { 16588 NetworkInterfaceInfo *intf; 16589 active->IPv4Available = mDNSfalse; 16590 active->IPv6Available = mDNSfalse; 16591 for (intf = m->HostInterfaces; intf; intf = intf->next) 16592 if (intf->InterfaceID == active->InterfaceID) 16593 { 16594 if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue; 16595 if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue; 16596 } 16597 } 16598 16599 mDNSlocal void RestartRecordGetZoneData(mDNS * const m) 16600 { 16601 AuthRecord *rr; 16602 LogInfo("RestartRecordGetZoneData: ResourceRecords"); 16603 for (rr = m->ResourceRecords; rr; rr=rr->next) 16604 if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget) 16605 { 16606 debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c); 16607 // Zero out the updateid so that if we have a pending response from the server, it won't 16608 // be accepted as a valid response. If we accept the response, we might free the new "nta" 16609 if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); } 16610 rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr); 16611 } 16612 } 16613 16614 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 16615 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set) 16616 { 16617 int i; 16618 // We initialize ThisQInterval to -1 indicating that the question has not been started 16619 // yet. If the question (browse) is started later during interface registration, it will 16620 // be stopped during interface deregistration. We can't sanity check to see if the 16621 // question has been stopped or not before initializing it to -1 because we need to 16622 // initialize it to -1 the very first time. 16623 16624 set->NetWakeBrowse.ThisQInterval = -1; 16625 for (i=0; i<3; i++) 16626 { 16627 set->NetWakeResolve[i].ThisQInterval = -1; 16628 set->SPSAddr[i].type = mDNSAddrType_None; 16629 } 16630 set->NextSPSAttempt = -1; 16631 set->NextSPSAttemptTime = m->timenow; 16632 } 16633 #endif 16634 16635 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set) 16636 { 16637 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 16638 NetworkInterfaceInfo *p = m->HostInterfaces; 16639 while (p && p != set) p=p->next; 16640 if (!p) 16641 { 16642 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); 16643 return; 16644 } 16645 16646 if (set->InterfaceActive) 16647 { 16648 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEFAULT, "ActivateNetWake for " PUB_S " (" PRI_IP_ADDR ")", set->ifname, &set->ip); 16649 mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set); 16650 } 16651 #else 16652 (void)m; 16653 (void)set; 16654 #endif 16655 } 16656 16657 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set) 16658 { 16659 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 16660 NetworkInterfaceInfo *p = m->HostInterfaces; 16661 while (p && p != set) p=p->next; 16662 if (!p) 16663 { 16664 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); 16665 return; 16666 } 16667 16668 // Note: We start the browse only if the interface is NetWake capable and we use this to 16669 // stop the resolves also. Hence, the resolves should not be started without the browse 16670 // being started i.e, resolves should not happen unless NetWake capable which is 16671 // guaranteed by BeginSleepProcessing. 16672 if (set->NetWakeBrowse.ThisQInterval >= 0) 16673 { 16674 int i; 16675 LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEFAULT, "DeactivateNetWake for " PUB_S " (" PRI_IP_ADDR ")", set->ifname, &set->ip); 16676 16677 // Stop our browse and resolve operations 16678 mDNS_StopQuery_internal(m, &set->NetWakeBrowse); 16679 for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]); 16680 16681 // Make special call to the browse callback to let it know it can to remove all records for this interface 16682 if (m->SPSBrowseCallback) 16683 { 16684 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback 16685 m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, QC_rmv); 16686 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 16687 } 16688 16689 // Reset our variables back to initial state, so we're ready for when NetWake is turned back on 16690 // (includes resetting NetWakeBrowse.ThisQInterval back to -1) 16691 InitializeNetWakeState(m, set); 16692 } 16693 #else 16694 (void)m; 16695 (void)set; 16696 #endif 16697 } 16698 16699 mDNSlocal mDNSBool IsInterfaceValidForQuestion(const DNSQuestion *const q, const NetworkInterfaceInfo *const intf) 16700 { 16701 if (q->InterfaceID == mDNSInterface_Any) 16702 { 16703 return mDNSPlatformValidQuestionForInterface(q, intf); 16704 } 16705 else 16706 { 16707 return (q->InterfaceID == intf->InterfaceID); 16708 } 16709 } 16710 16711 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed) 16712 { 16713 AuthRecord *rr; 16714 mDNSBool FirstOfType = mDNStrue; 16715 NetworkInterfaceInfo **p = &m->HostInterfaces; 16716 16717 if (!set->InterfaceID) 16718 { 16719 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "Tried to register a NetworkInterfaceInfo with zero InterfaceID - ifaddr: " PRI_IP_ADDR, 16720 &set->ip); 16721 return(mStatus_Invalid); 16722 } 16723 16724 if (!mDNSAddressIsValidNonZero(&set->mask)) 16725 { 16726 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "Tried to register a NetworkInterfaceInfo with invalid mask - ifaddr: " PRI_IP_ADDR 16727 ", ifmask: " PUB_IP_ADDR, &set->ip, &set->mask); 16728 return(mStatus_Invalid); 16729 } 16730 16731 mDNS_Lock(m); 16732 16733 // Assume this interface will be active now, unless we find a duplicate already in the list 16734 set->InterfaceActive = mDNStrue; 16735 set->IPv4Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx); 16736 set->IPv6Available = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx); 16737 16738 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 16739 InitializeNetWakeState(m, set); 16740 #endif 16741 16742 // Scan list to see if this InterfaceID is already represented 16743 while (*p) 16744 { 16745 if (*p == set) 16746 { 16747 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "Tried to register a NetworkInterfaceInfo that's already in the list - " 16748 "ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip); 16749 mDNS_Unlock(m); 16750 return(mStatus_AlreadyRegistered); 16751 } 16752 16753 if ((*p)->InterfaceID == set->InterfaceID) 16754 { 16755 // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now 16756 set->InterfaceActive = mDNSfalse; 16757 if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse; 16758 if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue; 16759 if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue; 16760 } 16761 16762 p=&(*p)->next; 16763 } 16764 16765 set->next = mDNSNULL; 16766 *p = set; 16767 16768 if (set->Advertise) AdvertiseInterfaceIfNeeded(m, set); 16769 16770 if (set->InterfaceActive) 16771 { 16772 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "Interface not represented in list; marking active and retriggering queries - " 16773 "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, IIDPrintable(set->InterfaceID), set->ifname, &set->ip); 16774 } 16775 else 16776 { 16777 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "Interface already represented in list - ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, 16778 IIDPrintable(set->InterfaceID), set->ifname, &set->ip); 16779 } 16780 16781 if (set->NetWake) mDNS_ActivateNetWake_internal(m, set); 16782 16783 // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off, 16784 // giving the false impression that there's an active representative of this interface when there really isn't. 16785 // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records, 16786 // even if we believe that we previously had an active representative of this interface. 16787 if (set->McastTxRx && (FirstOfType || set->InterfaceActive)) 16788 { 16789 DNSQuestion *q; 16790 // Normally, after an interface comes up, we pause half a second before beginning probing. 16791 // This is to guard against cases where there's rapid interface changes, where we could be confused by 16792 // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address) 16793 // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations. 16794 // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent, 16795 // and think it's a conflicting answer to our probe. 16796 // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet. 16797 mDNSs32 probedelay; 16798 mDNSu8 numannounce; 16799 mdns_clang_ignore_warning_begin(-Wswitch-default); 16800 switch (activationSpeed) 16801 { 16802 case FastActivation: 16803 probedelay = (mDNSs32)0; 16804 numannounce = InitialAnnounceCount; 16805 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 16806 "Using fast activation for DirectLink interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, 16807 set->ifname, &set->ip); 16808 break; 16809 16810 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) 16811 case SlowActivation: 16812 probedelay = mDNSPlatformOneSecond * 5; 16813 numannounce = (mDNSu8)1; 16814 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "Frequent transitions for interface, doing slow activation - " 16815 "ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip); 16816 m->mDNSStats.InterfaceUpFlap++; 16817 break; 16818 #endif 16819 16820 case NormalActivation: 16821 probedelay = mDNSPlatformOneSecond / 2; 16822 numannounce = InitialAnnounceCount; 16823 break; 16824 } 16825 mdns_clang_ignore_warning_end(); 16826 16827 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "Interface probe will be delayed - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR ", probe delay: %d", 16828 set->ifname, &set->ip, probedelay); 16829 16830 // No probe or sending suppression on DirectLink type interfaces. 16831 if (activationSpeed == FastActivation) 16832 { 16833 m->SuppressQueries = 0; 16834 m->SuppressResponses = 0; 16835 m->SuppressProbes = 0; 16836 } 16837 else 16838 { 16839 // Use a small amount of randomness: 16840 // In the case of a network administrator turning on an Ethernet hub so that all the 16841 // connected machines establish link at exactly the same time, we don't want them all 16842 // to go and hit the network with identical queries at exactly the same moment. 16843 // We set a random delay of up to InitialQuestionInterval (1/3 second). 16844 // We must *never* set m->SuppressQueries to more than that (or set it repeatedly in a way 16845 // that causes mDNSResponder to remain in a prolonged state of SuppressQueries, because 16846 // suppressing packet sending for more than about 1/3 second can cause protocol correctness 16847 // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts). 16848 // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically 16849 if (!m->SuppressQueries) 16850 { 16851 m->SuppressQueries = NonZeroTime(m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval)); 16852 } 16853 if (m->SuppressProbes == 0 || 16854 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0) 16855 m->SuppressProbes = NonZeroTime(m->timenow + probedelay); 16856 } 16857 16858 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 16859 // Include OWNER option in packets for 60 seconds after connecting to the network. Setting 16860 // it here also handles the wake up case as the network link comes UP after waking causing 16861 // us to reconnect to the network. If we do this as part of the wake up code, it is possible 16862 // that the network link comes UP after 60 seconds and we never set the OWNER option 16863 m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond); 16864 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "Setting AnnounceOwner"); 16865 #endif 16866 16867 m->mDNSStats.InterfaceUp++; 16868 for (q = m->Questions; q; q=q->next) // Scan our list of questions 16869 { 16870 if (mDNSOpaque16IsZero(q->TargetQID)) 16871 { 16872 // If the DNSQuestion's mDNS queries are supposed to be sent over the interface, then reactivate it. 16873 if (IsInterfaceValidForQuestion(q, set)) 16874 { 16875 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) 16876 // If flapping, delay between first and second queries is nine seconds instead of one second 16877 mDNSBool dodelay = (activationSpeed == SlowActivation) && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID); 16878 mDNSs32 initial = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval; 16879 mDNSs32 qdelay = dodelay ? kDefaultQueryDelayTimeForFlappingInterface : 0; 16880 if (dodelay) 16881 { 16882 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "No cache records expired for the question " PRI_DM_NAME " (" PUB_S ");" 16883 " delaying it by %d seconds", DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), qdelay); 16884 } 16885 #else 16886 mDNSs32 initial = InitialQuestionInterval; 16887 mDNSs32 qdelay = 0; 16888 #endif 16889 16890 if (!q->ThisQInterval || q->ThisQInterval > initial) 16891 { 16892 q->ThisQInterval = initial; 16893 q->RequestUnicast = kDefaultRequestUnicastCount; 16894 } 16895 q->LastQTime = m->timenow - q->ThisQInterval + qdelay; 16896 q->RecentAnswerPkts = 0; 16897 SetNextQueryTime(m,q); 16898 } 16899 } 16900 } 16901 16902 // For all our non-specific authoritative resource records (and any dormant records specific to this interface) 16903 // we now need them to re-probe if necessary, and then re-announce. 16904 for (rr = m->ResourceRecords; rr; rr=rr->next) 16905 { 16906 if (IsInterfaceValidForAuthRecord(rr, set->InterfaceID)) 16907 { 16908 mDNSCoreRestartRegistration(m, rr, numannounce); 16909 } 16910 } 16911 } 16912 16913 RestartRecordGetZoneData(m); 16914 16915 mDNS_UpdateAllowSleep(m); 16916 16917 mDNS_Unlock(m); 16918 return(mStatus_NoError); 16919 } 16920 16921 mDNSlocal void AdjustAddressRecordSetsEx(mDNS *const m, NetworkInterfaceInfo *removedIntf, mDNSBool forRandHostname) 16922 { 16923 NetworkInterfaceInfo *intf; 16924 const AuthRecord *oldAR; 16925 AuthRecord *newAR; 16926 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16927 if (mDNSPlatformInterfaceIsAWDL(removedIntf->InterfaceID)) return; 16928 #endif 16929 oldAR = GetInterfaceAddressRecord(removedIntf, forRandHostname); 16930 newAR = GetFirstAddressRecordEx(m, forRandHostname); 16931 for (intf = m->HostInterfaces; intf; intf = intf->next) 16932 { 16933 AuthRecord *ar; 16934 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16935 if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue; 16936 #endif 16937 ar = GetInterfaceAddressRecord(intf, forRandHostname); 16938 if (ar->RRSet == (uintptr_t)oldAR) 16939 { 16940 ar->RRSet = (uintptr_t)(newAR ? newAR : ar); 16941 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Changed RRSet for " PRI_S, ARDisplayString(m, ar)); 16942 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "New RRSet: %" PRIxPTR "", ar->RRSet); 16943 } 16944 } 16945 } 16946 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 16947 #define AdjustAddressRecordSetsForRandHostname(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNStrue) 16948 #endif 16949 #define AdjustAddressRecordSets(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNSfalse) 16950 16951 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change 16952 // the record list and/or question list. 16953 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 16954 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed) 16955 { 16956 #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) 16957 (void)activationSpeed; // Unused parameter 16958 #endif 16959 NetworkInterfaceInfo **p = &m->HostInterfaces; 16960 mDNSBool revalidate = mDNSfalse; 16961 NetworkInterfaceInfo *intf; 16962 16963 mDNS_Lock(m); 16964 16965 // Find this record in our list 16966 while (*p && *p != set) p=&(*p)->next; 16967 if (!*p) 16968 { 16969 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "NetworkInterfaceInfo not found in list"); 16970 mDNS_Unlock(m); 16971 return; 16972 } 16973 16974 mDNS_DeactivateNetWake_internal(m, set); 16975 16976 // Unlink this record from our list 16977 *p = (*p)->next; 16978 set->next = mDNSNULL; 16979 16980 if (!set->InterfaceActive) 16981 { 16982 // If this interface not the active member of its set, update the v4/v6Available flags for the active member 16983 for (intf = m->HostInterfaces; intf; intf = intf->next) 16984 if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID) 16985 UpdateInterfaceProtocols(m, intf); 16986 } 16987 else 16988 { 16989 intf = FirstInterfaceForID(m, set->InterfaceID); 16990 if (intf) 16991 { 16992 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, 16993 "Another representative of InterfaceID exists - ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, 16994 IIDPrintable(set->InterfaceID), set->ifname, &set->ip); 16995 if (intf->InterfaceActive) 16996 { 16997 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR, "intf->InterfaceActive already set for interface - ifname: " 16998 PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip); 16999 } 17000 intf->InterfaceActive = mDNStrue; 17001 UpdateInterfaceProtocols(m, intf); 17002 17003 if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf); 17004 17005 // See if another representative *of the same type* exists. If not, we mave have gone from 17006 // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid. 17007 for (intf = m->HostInterfaces; intf; intf = intf->next) 17008 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type) 17009 break; 17010 if (!intf) revalidate = mDNStrue; 17011 } 17012 else 17013 { 17014 mDNSu32 slot; 17015 CacheGroup *cg; 17016 CacheRecord *rr; 17017 DNSQuestion *q; 17018 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) 17019 mDNSu32 cacheHitMulticastCount = 0; 17020 mDNSu32 cacheMissMulticastCount = 0; 17021 mDNSu32 cacheHitUnicastCount = 0; 17022 mDNSu32 cacheMissUnicastCount = 0; 17023 #endif 17024 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "Last representative of InterfaceID deregistered; marking questions etc. dormant - " 17025 "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, 17026 IIDPrintable(set->InterfaceID), set->ifname, &set->ip); 17027 17028 m->mDNSStats.InterfaceDown++; 17029 17030 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) 17031 if (set->McastTxRx && (activationSpeed == SlowActivation)) 17032 { 17033 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT, "Frequent transitions for interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, 17034 set->ifname, &set->ip); 17035 m->mDNSStats.InterfaceDownFlap++; 17036 } 17037 #endif 17038 17039 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 17040 DPCHandleInterfaceDown(set->InterfaceID); 17041 #endif 17042 // 1. Deactivate any questions specific to this interface, and tag appropriate questions 17043 // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them 17044 for (q = m->Questions; q; q=q->next) 17045 { 17046 if (mDNSOpaque16IsZero(q->TargetQID)) // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.) 17047 { 17048 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0; 17049 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID) 17050 { 17051 q->FlappingInterface2 = q->FlappingInterface1; 17052 q->FlappingInterface1 = set->InterfaceID; // Keep history of the last two interfaces to go away 17053 } 17054 } 17055 } 17056 17057 // 2. Flush any cache records received on this interface 17058 revalidate = mDNSfalse; // Don't revalidate if we're flushing the records 17059 FORALL_CACHERECORDS(slot, cg, rr) 17060 { 17061 if (rr->resrec.InterfaceID == set->InterfaceID) 17062 { 17063 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION) 17064 // If this interface is deemed flapping, 17065 // postpone deleting the cache records in case the interface comes back again 17066 if (set->McastTxRx && (activationSpeed == SlowActivation)) 17067 { 17068 // For a flapping interface we want these records to go away after 17069 // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed. 17070 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface); 17071 // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them -- 17072 // if the interface does come back, any relevant questions will be reactivated anyway 17073 rr->UnansweredQueries = MaxUnansweredQueries; 17074 } 17075 else 17076 #endif 17077 { 17078 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) 17079 if (rr->LastCachedAnswerTime) 17080 { 17081 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 17082 const mdns_dns_service_t dnsservice = mdns_cache_metadata_get_dns_service(rr->resrec.metadata); 17083 if (dnsservice) cacheHitUnicastCount++; 17084 #else 17085 if (rr->resrec.rDNSServer) cacheHitUnicastCount++; 17086 #endif 17087 else cacheHitMulticastCount++; 17088 } 17089 else 17090 { 17091 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 17092 const mdns_dns_service_t dnsservice = mdns_cache_metadata_get_dns_service(rr->resrec.metadata); 17093 if (dnsservice) cacheMissUnicastCount++; 17094 #else 17095 if (rr->resrec.rDNSServer) cacheMissUnicastCount++; 17096 #endif 17097 else cacheMissMulticastCount++; 17098 } 17099 #endif 17100 mDNS_PurgeCacheResourceRecord(m, rr); 17101 } 17102 } 17103 } 17104 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS) 17105 dnssd_analytics_update_cache_usage_counts(cacheHitMulticastCount, cacheMissMulticastCount, cacheHitUnicastCount, cacheMissUnicastCount); 17106 #endif 17107 } 17108 } 17109 17110 // If we still have address records referring to this one, update them. 17111 // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list, 17112 // so the call to AdjustAddressRecordSets*() wont accidentally find it. 17113 AdjustAddressRecordSets(m, set); 17114 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 17115 AdjustAddressRecordSetsForRandHostname(m, set); 17116 #endif 17117 17118 // If we were advertising on this interface, deregister those address and reverse-lookup records now 17119 if (set->Advertise) DeadvertiseInterface(m, set, kDeadvertiseFlag_All); 17120 17121 // If we have any cache records received on this interface that went away, then re-verify them. 17122 // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off, 17123 // giving the false impression that there's an active representative of this interface when there really isn't. 17124 // Don't need to do this when shutting down, because *all* interfaces are about to go away 17125 if (revalidate && !m->ShutdownTime) 17126 { 17127 mDNSu32 slot; 17128 CacheGroup *cg; 17129 CacheRecord *rr; 17130 FORALL_CACHERECORDS(slot, cg, rr) 17131 if (rr->resrec.InterfaceID == set->InterfaceID) 17132 mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface); 17133 } 17134 17135 mDNS_UpdateAllowSleep(m); 17136 17137 mDNS_Unlock(m); 17138 } 17139 17140 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result) 17141 { 17142 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext; 17143 mDNSBool unregistered = mDNSfalse; 17144 17145 #if MDNS_DEBUGMSGS 17146 { 17147 char *msg = "Unknown result"; 17148 if (result == mStatus_NoError) msg = "Name Registered"; 17149 else if (result == mStatus_NameConflict) msg = "Name Conflict"; 17150 else if (result == mStatus_MemFree) msg = "Memory Free"; 17151 debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result); 17152 } 17153 #endif 17154 17155 // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing) 17156 if (result == mStatus_NoError && rr != &sr->RR_SRV) return; 17157 17158 // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that 17159 if (result == mStatus_NameConflict) 17160 { 17161 sr->Conflict = mDNStrue; // Record that this service set had a conflict 17162 mDNS_DeregisterService(m, sr); // Unlink the records from our list 17163 return; 17164 } 17165 17166 if (result == mStatus_MemFree) 17167 { 17168 // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records, 17169 // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until 17170 // every record is finished cleaning up. 17171 mDNSu32 i; 17172 ExtraResourceRecord *e = sr->Extras; 17173 17174 if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return; 17175 if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return; 17176 if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return; 17177 if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return; 17178 for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return; 17179 17180 while (e) 17181 { 17182 if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return; 17183 e = e->next; 17184 } 17185 17186 // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse, 17187 // then we can now report the NameConflict to the client 17188 if (sr->Conflict) result = mStatus_NameConflict; 17189 17190 // Complete any pending record updates to avoid memory leaks. 17191 if (sr->RR_SRV.NewRData) CompleteRDataUpdate(m, &sr->RR_SRV); 17192 if (sr->RR_TXT.NewRData) CompleteRDataUpdate(m, &sr->RR_TXT); 17193 if (sr->RR_PTR.NewRData) CompleteRDataUpdate(m, &sr->RR_PTR); 17194 if (sr->RR_ADV.NewRData) CompleteRDataUpdate(m, &sr->RR_ADV); 17195 unregistered = mDNStrue; 17196 } 17197 17198 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 17199 "ServiceCallback: All records " PUB_S "registered for " PRI_DM_NAME, 17200 unregistered ? "un" : "", DM_NAME_PARAM(sr->RR_PTR.resrec.name)); 17201 // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback 17202 // function is allowed to do anything, including deregistering this service and freeing its memory. 17203 if (sr->ServiceCallback) 17204 sr->ServiceCallback(m, sr, result); 17205 } 17206 17207 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result) 17208 { 17209 ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext; 17210 if (sr->ServiceCallback) 17211 sr->ServiceCallback(m, sr, result); 17212 } 17213 17214 17215 // Derive AuthRecType from the kDNSServiceFlags* values. 17216 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags) 17217 { 17218 AuthRecType artype; 17219 17220 if (InterfaceID == mDNSInterface_LocalOnly) 17221 artype = AuthRecordLocalOnly; 17222 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE) 17223 artype = AuthRecordP2P; 17224 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P) 17225 && (flags & kDNSServiceFlagsIncludeAWDL)) 17226 artype = AuthRecordAnyIncludeAWDLandP2P; 17227 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)) 17228 artype = AuthRecordAnyIncludeP2P; 17229 else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL)) 17230 artype = AuthRecordAnyIncludeAWDL; 17231 else 17232 artype = AuthRecordAny; 17233 17234 return artype; 17235 } 17236 17237 // Note: 17238 // Name is first label of domain name (any dots in the name are actual dots, not label separators) 17239 // Type is service type (e.g. "_ipp._tcp.") 17240 // Domain is fully qualified domain name (i.e. ending with a null label) 17241 // We always register a TXT, even if it is empty (so that clients are not 17242 // left waiting forever looking for a nonexistent record.) 17243 // If the host parameter is mDNSNULL or the root domain (ASCII NUL), 17244 // then the default host name (m->MulticastHostname) is automatically used 17245 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration 17246 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr, 17247 const domainlabel *const name, const domainname *const type, const domainname *const domain, 17248 const domainname *const host, mDNSIPPort port, RData *const txtrdata, const mDNSu8 txtinfo[], mDNSu16 txtlen, 17249 AuthRecord *SubTypes, mDNSu32 NumSubTypes, 17250 mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags) 17251 { 17252 mStatus err; 17253 mDNSu32 i; 17254 AuthRecType artype; 17255 mDNSu8 recordType = (flags & kDNSServiceFlagsKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique; 17256 17257 sr->ServiceCallback = Callback; 17258 sr->ServiceContext = Context; 17259 sr->Conflict = mDNSfalse; 17260 17261 sr->Extras = mDNSNULL; 17262 sr->NumSubTypes = NumSubTypes; 17263 sr->SubTypes = SubTypes; 17264 sr->flags = flags; 17265 17266 artype = setAuthRecType(InterfaceID, flags); 17267 17268 // Initialize the AuthRecord objects to sane values 17269 // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out 17270 mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr); 17271 mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr); 17272 17273 if (flags & kDNSServiceFlagsWakeOnlyService) 17274 { 17275 sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly; 17276 } 17277 17278 mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, recordType, artype, ServiceCallback, sr); 17279 mDNS_SetupResourceRecord(&sr->RR_TXT, txtrdata, InterfaceID, kDNSType_TXT, kStandardTTL, recordType, artype, ServiceCallback, sr); 17280 17281 // If port number is zero, that means the client is really trying to do a RegisterNoSuchService 17282 if (mDNSIPPortIsZero(port)) 17283 return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags)); 17284 17285 // If the caller is registering an oversized TXT record, 17286 // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it 17287 if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen) 17288 sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen; 17289 17290 // Set up the record names 17291 // For now we only create an advisory record for the main type, not for subtypes 17292 // We need to gain some operational experience before we decide if there's a need to create them for subtypes too 17293 if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL) 17294 return(mStatus_BadParamErr); 17295 if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr); 17296 if (ConstructServiceName(&sr->RR_SRV.namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr); 17297 AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name); 17298 17299 // 1. Set up the ADV record rdata to advertise our service type 17300 AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name); 17301 17302 // 2. Set up the PTR record rdata to point to our service name 17303 // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too 17304 // Note: uDNS registration code assumes that Additional1 points to the SRV record 17305 AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name); 17306 sr->RR_PTR.Additional1 = &sr->RR_SRV; 17307 sr->RR_PTR.Additional2 = &sr->RR_TXT; 17308 17309 // 2a. Set up any subtype PTRs to point to our service name 17310 // If the client is using subtypes, it is the client's responsibility to have 17311 // already set the first label of the record name to the subtype being registered 17312 for (i=0; i<NumSubTypes; i++) 17313 { 17314 domainname st; 17315 AssignDomainName(&st, sr->SubTypes[i].resrec.name); 17316 st.c[1+st.c[0]] = 0; // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService()) 17317 AppendDomainName(&st, type); 17318 mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr); 17319 if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr); 17320 AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage); 17321 sr->SubTypes[i].Additional1 = &sr->RR_SRV; 17322 sr->SubTypes[i].Additional2 = &sr->RR_TXT; 17323 } 17324 17325 // 3. Set up the SRV record rdata. 17326 sr->RR_SRV.resrec.rdata->u.srv.priority = 0; 17327 sr->RR_SRV.resrec.rdata->u.srv.weight = 0; 17328 sr->RR_SRV.resrec.rdata->u.srv.port = port; 17329 17330 // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name 17331 if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host); 17332 else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; } 17333 17334 // 4. Set up the TXT record rdata, 17335 // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us 17336 // Note: uDNS registration code assumes that DependentOn points to the SRV record 17337 if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0; 17338 else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c) 17339 { 17340 sr->RR_TXT.resrec.rdlength = txtlen; 17341 if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr); 17342 mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen); 17343 } 17344 sr->RR_TXT.DependentOn = &sr->RR_SRV; 17345 17346 mDNS_Lock(m); 17347 // It is important that we register SRV first. uDNS assumes that SRV is registered first so 17348 // that if the SRV cannot find a target, rest of the records that belong to this service 17349 // will not be activated. 17350 err = mDNS_Register_internal(m, &sr->RR_SRV); 17351 // If we can't register the SRV record due to errors, bail out. It has not been inserted in 17352 // any list and hence no need to deregister. We could probably do similar checks for other 17353 // records below and bail out. For now, this seems to be sufficient to address rdar://9304275 17354 if (err) 17355 { 17356 mDNS_Unlock(m); 17357 return err; 17358 } 17359 if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT); 17360 // We register the RR_PTR last, because we want to be sure that in the event of a forced call to 17361 // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers 17362 // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to 17363 // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to 17364 // make sure we've deregistered all our records and done any other necessary cleanup before that happens. 17365 if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV); 17366 for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]); 17367 if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR); 17368 17369 mDNS_Unlock(m); 17370 17371 if (err) mDNS_DeregisterService(m, sr); 17372 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 17373 else if (!RRLocalOnly(&sr->RR_PTR) && 17374 SameDomainName(domain, &localdomain)) 17375 { 17376 unicast_assist_auth_add(sr->RR_PTR.resrec.name, sr->RR_PTR.resrec.namehash, InterfaceID); 17377 } 17378 #endif 17379 return(err); 17380 } 17381 17382 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr, 17383 ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags) 17384 { 17385 ExtraResourceRecord **e; 17386 mStatus status; 17387 AuthRecType artype; 17388 mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID; 17389 ResourceRecord *rr; 17390 17391 artype = setAuthRecType(InterfaceID, flags); 17392 17393 extra->next = mDNSNULL; 17394 mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID, 17395 extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr); 17396 AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name); 17397 17398 mDNS_Lock(m); 17399 rr = mDNSNULL; 17400 if (extra->r.resrec.rrtype == kDNSType_TXT) 17401 { 17402 if (sr->RR_TXT.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_TXT.resrec; 17403 } 17404 else if (extra->r.resrec.rrtype == kDNSType_SRV) 17405 { 17406 if (sr->RR_SRV.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_SRV.resrec; 17407 } 17408 17409 if (!rr) 17410 { 17411 ExtraResourceRecord *srExtra; 17412 17413 for (srExtra = sr->Extras; srExtra; srExtra = srExtra->next) 17414 { 17415 if ((srExtra->r.resrec.rrtype == extra->r.resrec.rrtype) && (srExtra->r.resrec.RecordType & kDNSRecordTypeUniqueMask)) 17416 { 17417 rr = &srExtra->r.resrec; 17418 break; 17419 } 17420 } 17421 } 17422 17423 if (rr && (extra->r.resrec.rroriginalttl != rr->rroriginalttl)) 17424 { 17425 LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s", 17426 extra->r.resrec.rroriginalttl, rr->rroriginalttl, RRDisplayString(m, &extra->r.resrec)); 17427 extra->r.resrec.rroriginalttl = rr->rroriginalttl; 17428 } 17429 17430 e = &sr->Extras; 17431 while (*e) e = &(*e)->next; 17432 17433 extra->r.DependentOn = &sr->RR_SRV; 17434 17435 debugf("mDNS_AddRecordToService adding record to %##s %s %d", 17436 extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength); 17437 17438 status = mDNS_Register_internal(m, &extra->r); 17439 if (status == mStatus_NoError) *e = extra; 17440 17441 mDNS_Unlock(m); 17442 return(status); 17443 } 17444 17445 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, 17446 mDNSRecordCallback MemFreeCallback, void *Context) 17447 { 17448 ExtraResourceRecord **e; 17449 mStatus status; 17450 17451 mDNS_Lock(m); 17452 e = &sr->Extras; 17453 while (*e && *e != extra) e = &(*e)->next; 17454 if (!*e) 17455 { 17456 debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c); 17457 status = mStatus_BadReferenceErr; 17458 } 17459 else 17460 { 17461 debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c); 17462 extra->r.RecordCallback = MemFreeCallback; 17463 extra->r.RecordContext = Context; 17464 *e = (*e)->next; 17465 status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal); 17466 } 17467 mDNS_Unlock(m); 17468 return(status); 17469 } 17470 17471 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname) 17472 { 17473 // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines 17474 // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally. 17475 domainlabel name1, name2; 17476 domainname type, domain; 17477 const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target; 17478 ExtraResourceRecord *extras = sr->Extras; 17479 mStatus err; 17480 17481 DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain); 17482 if (!newname) 17483 { 17484 name2 = name1; 17485 IncrementLabelSuffix(&name2, mDNStrue); 17486 newname = &name2; 17487 } 17488 17489 if (SameDomainName(&domain, &localdomain)) 17490 debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c); 17491 else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c); 17492 17493 // If there's a pending TXT record update at this point, which can happen if a DNSServiceUpdateRecord() call was made 17494 // after the TXT record's deregistration, execute it now, otherwise it will be lost during the service re-registration. 17495 if (sr->RR_TXT.NewRData) CompleteRDataUpdate(m, &sr->RR_TXT); 17496 err = mDNS_RegisterService(m, sr, newname, &type, &domain, 17497 host, sr->RR_SRV.resrec.rdata->u.srv.port, 17498 (sr->RR_TXT.resrec.rdata != &sr->RR_TXT.rdatastorage) ? sr->RR_TXT.resrec.rdata : mDNSNULL, 17499 sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength, 17500 sr->SubTypes, sr->NumSubTypes, 17501 sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags); 17502 17503 // mDNS_RegisterService() just reset sr->Extras to NULL. 17504 // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run 17505 // through the old list of extra records, and re-add them to our freshly created service registration 17506 while (!err && extras) 17507 { 17508 ExtraResourceRecord *e = extras; 17509 extras = extras->next; 17510 err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0); 17511 } 17512 17513 return(err); 17514 } 17515 17516 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback, 17517 // which may change the record list and/or question list. 17518 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this. 17519 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt) 17520 { 17521 // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService() 17522 if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV)); 17523 17524 if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered) 17525 { 17526 debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c); 17527 return(mStatus_BadReferenceErr); 17528 } 17529 else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering) 17530 { 17531 LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c); 17532 // Avoid race condition: 17533 // If a service gets a conflict, then we set the Conflict flag to tell us to generate 17534 // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record. 17535 // If the client happens to deregister the service in the middle of that process, then 17536 // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree 17537 // instead of incorrectly promoting it to mStatus_NameConflict. 17538 // This race condition is exposed particularly when the conformance test generates 17539 // a whole batch of simultaneous conflicts across a range of services all advertised 17540 // using the same system default name, and if we don't take this precaution then 17541 // we end up incrementing m->nicelabel multiple times instead of just once. 17542 // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision 17543 sr->Conflict = mDNSfalse; 17544 return(mStatus_NoError); 17545 } 17546 else 17547 { 17548 mDNSu32 i; 17549 mStatus status; 17550 ExtraResourceRecord *e; 17551 mDNS_Lock(m); 17552 e = sr->Extras; 17553 17554 // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the 17555 // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay 17556 mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat); 17557 mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat); 17558 mDNS_Deregister_internal(m, &sr->RR_ADV, drt); 17559 17560 // We deregister all of the extra records, but we leave the sr->Extras list intact 17561 // in case the client wants to do a RenameAndReregister and reinstate the registration 17562 while (e) 17563 { 17564 mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat); 17565 e = e->next; 17566 } 17567 17568 for (i=0; i<sr->NumSubTypes; i++) 17569 mDNS_Deregister_internal(m, &sr->SubTypes[i], drt); 17570 17571 #if MDNSRESPONDER_SUPPORTS(APPLE, UNICAST_ASSIST) 17572 if (!RRLocalOnly(&sr->RR_PTR) && 17573 IsLocalDomain(sr->RR_PTR.resrec.name)) 17574 { 17575 unicast_assist_auth_rmv(sr->RR_PTR.resrec.name, sr->RR_PTR.resrec.namehash, sr->RR_PTR.resrec.InterfaceID); 17576 } 17577 #endif 17578 status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt); 17579 mDNS_Unlock(m); 17580 return(status); 17581 } 17582 } 17583 17584 // Create a registration that asserts that no such service exists with this name. 17585 // This can be useful where there is a given function is available through several protocols. 17586 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP" 17587 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an 17588 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing 17589 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users. 17590 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr, 17591 const domainlabel *const name, const domainname *const type, const domainname *const domain, 17592 const domainname *const host, 17593 const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags) 17594 { 17595 AuthRecType artype; 17596 17597 artype = setAuthRecType(InterfaceID, flags); 17598 17599 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context); 17600 if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr); 17601 rr->resrec.rdata->u.srv.priority = 0; 17602 rr->resrec.rdata->u.srv.weight = 0; 17603 rr->resrec.rdata->u.srv.port = zeroIPPort; 17604 if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host); 17605 else rr->AutoTarget = Target_AutoHost; 17606 return(mDNS_Register(m, rr)); 17607 } 17608 17609 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr, 17610 mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname) 17611 { 17612 AuthRecType artype; 17613 17614 if (InterfaceID == mDNSInterface_LocalOnly) 17615 artype = AuthRecordLocalOnly; 17616 else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE) 17617 artype = AuthRecordP2P; 17618 else 17619 artype = AuthRecordAny; 17620 mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL); 17621 if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr); 17622 if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr); 17623 return(mDNS_Register(m, rr)); 17624 } 17625 17626 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id) 17627 { 17628 AuthRecord *r; 17629 for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue; 17630 return mDNSfalse; 17631 } 17632 17633 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id) 17634 { 17635 DNSQuestion *q; 17636 for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue; 17637 return mDNSfalse; 17638 } 17639 17640 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m) 17641 { 17642 mDNSOpaque16 id = zeroID; 17643 int i; 17644 17645 for (i=0; i<10; i++) 17646 { 17647 id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE)); 17648 if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break; 17649 } 17650 17651 debugf("mDNS_NewMessageID: %5d", mDNSVal16(id)); 17652 17653 return id; 17654 } 17655 17656 // *************************************************************************** 17657 // MARK: - Sleep Proxy Server 17658 17659 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr) 17660 { 17661 // If we see an ARP from a machine we think is sleeping, then either 17662 // (i) the machine has woken, or 17663 // (ii) it's just a stray old packet from before the machine slept 17664 // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid 17665 // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds. 17666 // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine. 17667 // If it was a stray old packet, then after 10 seconds we'll probe again and then start answering ARPs again. In this case we *do* 17668 // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to 17669 // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address. 17670 17671 rr->resrec.RecordType = kDNSRecordTypeUnique; 17672 rr->ProbeCount = DefaultProbeCountForTypeUnique; 17673 rr->ProbeRestartCount++; 17674 17675 // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably 17676 // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding. 17677 // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case 17678 // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from 17679 // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine 17680 // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict. 17681 if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0) 17682 InitializeLastAPTime(m, rr); 17683 else 17684 { 17685 rr->AnnounceCount = InitialAnnounceCount; 17686 rr->ThisAPInterval = mDNSPlatformOneSecond; 17687 rr->LastAPTime = m->timenow + mDNSPlatformOneSecond * 9; // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now 17688 SetNextAnnounceProbeTime(m, rr); 17689 } 17690 } 17691 17692 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID) 17693 { 17694 static const mDNSOpaque16 ARP_op_request = { { 0, 1 } }; 17695 AuthRecord *rr; 17696 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID); 17697 if (!intf) return; 17698 17699 mDNS_Lock(m); 17700 17701 // Pass 1: 17702 // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary. 17703 // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry) 17704 // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them. 17705 // The times we might need to react to an ARP Announcement are: 17706 // (i) as an indication that the host in question has not gone to sleep yet (so we should delay beginning to proxy for it) or 17707 // (ii) if it's a conflicting Announcement from another host 17708 // -- and we check for these in Pass 2 below. 17709 if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa)) 17710 { 17711 for (rr = m->ResourceRecords; rr; rr=rr->next) 17712 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && 17713 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa)) 17714 { 17715 static const char msg1[] = "ARP Req from owner -- re-probing"; 17716 static const char msg2[] = "Ignoring ARP Request from "; 17717 static const char msg3[] = "Creating Local ARP Cache entry "; 17718 static const char msg4[] = "Answering ARP Request from "; 17719 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 : 17720 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 : 17721 mDNSSameEthAddress(&arp->sha, &intf->MAC) ? msg3 : msg4; 17722 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s", 17723 intf->ifname, msg, arp->sha.b, arp->spa.b, arp->tpa.b, 17724 &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); 17725 if (msg == msg1) 17726 { 17727 if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS) 17728 RestartARPProbing(m, rr); 17729 else 17730 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr)); 17731 } 17732 else if (msg == msg3) 17733 { 17734 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID); 17735 } 17736 else if (msg == msg4) 17737 { 17738 const mDNSv4Addr tpa = arp->tpa; 17739 const mDNSv4Addr spa = arp->spa; 17740 SendARP(m, 2, rr, &tpa, &arp->sha, &spa, &arp->sha); 17741 } 17742 } 17743 } 17744 17745 // Pass 2: 17746 // For all types of ARP packet we check the Sender IP address to make sure it doesn't conflict with any AddressProxy record we're holding. 17747 // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address, 17748 // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address). 17749 // We ignore ARPs we sent ourselves (Sender MAC address is our MAC address) because our own proxy ARPs do not constitute a conflict that we need to handle. 17750 // If we see an apparently conflicting ARP, we check the sender hardware address: 17751 // If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer. 17752 // If the sender hardware address is *not* the original owner, then this is a conflict, and we need to wake the sleeping machine to handle it. 17753 if (mDNSSameEthAddress(&arp->sha, &intf->MAC)) 17754 debugf("ARP from self for %.4a", arp->tpa.b); 17755 else 17756 { 17757 if (!mDNSSameIPv4Address(arp->spa, zerov4Addr)) 17758 for (rr = m->ResourceRecords; rr; rr=rr->next) 17759 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && 17760 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)) 17761 { 17762 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC)) 17763 { 17764 LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname, 17765 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); 17766 } 17767 else 17768 { 17769 RestartARPProbing(m, rr); 17770 if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC)) 17771 { 17772 LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname, 17773 mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request " : "Response ", 17774 arp->sha.b, arp->spa.b, arp->tpa.b, ARDisplayString(m, rr)); 17775 } 17776 else 17777 { 17778 LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname, 17779 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); 17780 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC); 17781 } 17782 } 17783 } 17784 } 17785 17786 mDNS_Unlock(m); 17787 } 17788 17789 /* 17790 // Option 1 is Source Link Layer Address Option 17791 // Option 2 is Target Link Layer Address Option 17792 mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op) 17793 { 17794 const mDNSu8 *options = (mDNSu8 *)(ndp+1); 17795 while (options < end) 17796 { 17797 debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options); 17798 if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2); 17799 options += options[1] * 8; 17800 } 17801 return mDNSNULL; 17802 } 17803 */ 17804 17805 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa, 17806 const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID) 17807 { 17808 AuthRecord *rr; 17809 NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID); 17810 if (!intf) return; 17811 17812 mDNS_Lock(m); 17813 17814 // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary. 17815 if (ndp->type == NDP_Sol) 17816 { 17817 //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL); 17818 (void)end; 17819 for (rr = m->ResourceRecords; rr; rr=rr->next) 17820 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && 17821 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target)) 17822 { 17823 static const char msg1[] = "NDP Req from owner -- re-probing"; 17824 static const char msg2[] = "Ignoring NDP Request from "; 17825 static const char msg3[] = "Creating Local NDP Cache entry "; 17826 static const char msg4[] = "Answering NDP Request from "; 17827 static const char msg5[] = "Answering NDP Probe from "; 17828 const char *const msg = mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 : 17829 (rr->AnnounceCount == InitialAnnounceCount) ? msg2 : 17830 mDNSSameEthAddress(sha, &intf->MAC) ? msg3 : 17831 mDNSIPv6AddressIsZero(*spa) ? msg4 : msg5; 17832 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s", 17833 intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); 17834 if (msg == msg1) 17835 { 17836 if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS) 17837 RestartARPProbing(m, rr); 17838 else 17839 LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr)); 17840 } 17841 else if (msg == msg3) 17842 mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID); 17843 else if (msg == msg4) 17844 SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha); 17845 else if (msg == msg5) 17846 SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth); 17847 } 17848 } 17849 17850 // Pass 2: For all types of NDP packet we check the Sender IP address to make sure it doesn't conflict with any AddressProxy record we're holding. 17851 if (mDNSSameEthAddress(sha, &intf->MAC)) 17852 debugf("NDP from self for %.16a", &ndp->target); 17853 else 17854 { 17855 // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address. 17856 // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions 17857 // about its routable IPv6 address, using its link-local address as the source address for all NDP packets. 17858 // Hence it is the NDP target address we care about, not the actual packet source address. 17859 if (ndp->type == NDP_Adv) spa = &ndp->target; 17860 if (!mDNSSameIPv6Address(*spa, zerov6Addr)) 17861 for (rr = m->ResourceRecords; rr; rr=rr->next) 17862 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && 17863 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)) 17864 { 17865 if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC)) 17866 { 17867 LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname, 17868 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); 17869 } 17870 else 17871 { 17872 RestartARPProbing(m, rr); 17873 if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC)) 17874 { 17875 LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname, 17876 ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr)); 17877 } 17878 else 17879 { 17880 LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname, 17881 sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr)); 17882 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC); 17883 } 17884 } 17885 } 17886 } 17887 17888 mDNS_Unlock(m); 17889 } 17890 17891 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol, 17892 const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len) 17893 { 17894 const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort; 17895 mDNSBool wake = mDNSfalse; 17896 mDNSBool kaWake = mDNSfalse; 17897 17898 switch (protocol) 17899 { 17900 #define XX wake ? "Received" : "Ignoring", end-p 17901 case 0x01: LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst); 17902 break; 17903 17904 case 0x06: { 17905 AuthRecord *kr; 17906 mDNSu32 seq, ack; 17907 #define TH_FIN 0x01 17908 #define TH_SYN 0x02 17909 #define TH_RST 0x04 17910 #define TH_ACK 0x10 17911 17912 kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack); 17913 if (kr) 17914 { 17915 LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port)); 17916 // Plan to wake if 17917 // (a) RST or FIN is set (the keepalive that we sent could have caused a reset) 17918 // (b) packet that contains new data and acks a sequence number higher than the one 17919 // we have been sending in the keepalive 17920 17921 wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ; 17922 if (!wake) 17923 { 17924 mDNSu8 *ptr; 17925 mDNSu32 pseq, pack; 17926 mDNSBool data = mDNSfalse; 17927 mDNSu8 tcphlen; 17928 17929 // Convert to host order 17930 ptr = (mDNSu8 *)&seq; 17931 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; 17932 17933 ptr = (mDNSu8 *)&ack; 17934 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; 17935 17936 pseq = t->tcp.seq; 17937 ptr = (mDNSu8 *)&pseq; 17938 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; 17939 17940 pack = t->tcp.ack; 17941 ptr = (mDNSu8 *)&pack; 17942 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3]; 17943 17944 // If the other side is acking one more than our sequence number (keepalive is one 17945 // less than the last valid sequence sent) and it's sequence is more than what we 17946 // acked before 17947 //if (end - p - 34 - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue; 17948 tcphlen = ((t->tcp.offset >> 4) * 4); 17949 if (end - ((const mDNSu8 *)t + tcphlen) > 0) data = mDNStrue; 17950 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data; 17951 17952 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK 17953 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) && 17954 ((int)(ack - pseq) == 1)) 17955 { 17956 // Send an ACK; 17957 mDNS_SendKeepaliveACK(m, kr); 17958 } 17959 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d", 17960 end, tcphlen, end - ((const mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake); 17961 } 17962 else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); } 17963 kaWake = wake; 17964 } 17965 else 17966 { 17967 // Plan to wake if 17968 // (a) RST is not set, AND 17969 // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone. 17970 wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN); 17971 17972 // For now, to reduce spurious wakeups, we wake only for TCP SYN, 17973 // except for ssh connections, where we'll wake for plain data packets too 17974 if (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse; 17975 17976 LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX, 17977 src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port), 17978 (t->tcp.flags & 2) ? " SYN" : "", 17979 (t->tcp.flags & 1) ? " FIN" : "", 17980 (t->tcp.flags & 4) ? " RST" : ""); 17981 } 17982 break; 17983 } 17984 17985 case 0x11: { 17986 #define ARD_AsNumber 3283 17987 static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } }; 17988 const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]); // Length *including* 8-byte UDP header 17989 if (udplen >= sizeof(UDPHeader)) 17990 { 17991 const mDNSu16 datalen = udplen - sizeof(UDPHeader); 17992 wake = mDNStrue; 17993 17994 // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling 17995 if (mDNSSameIPPort(port, IPSECPort)) 17996 { 17997 // Specifically ignore NAT keepalive packets 17998 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse; 17999 else 18000 { 18001 // Skip over the Non-ESP Marker if present 18002 const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0); 18003 const IKEHeader *const ike = (const IKEHeader *)(t + (NonESP ? 12 : 8)); 18004 const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0); 18005 if (ikelen >= sizeof(IKEHeader) && end >= ((const mDNSu8 *)ike) + sizeof(IKEHeader)) 18006 if ((ike->Version & 0x10) == 0x10) 18007 { 18008 // ExchangeType == 5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt> 18009 // ExchangeType == 34 means 'IKE_SA_INIT' <http://www.iana.org/assignments/ikev2-parameters> 18010 if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse; 18011 LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType); 18012 } 18013 } 18014 } 18015 18016 // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the 18017 // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port), 18018 // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this: 18019 // UDP header (8 bytes) 18020 // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total 18021 if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88); 18022 18023 LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port)); 18024 } 18025 } 18026 break; 18027 18028 case 0x3A: if (&t->bytes[len] <= end) 18029 { 18030 mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len); 18031 if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID); 18032 else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst); 18033 } 18034 break; 18035 18036 default: LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst); 18037 break; 18038 } 18039 18040 if (wake) 18041 { 18042 AuthRecord *rr, *r2; 18043 18044 mDNS_Lock(m); 18045 for (rr = m->ResourceRecords; rr; rr=rr->next) 18046 if (rr->resrec.InterfaceID == InterfaceID && 18047 rr->resrec.RecordType != kDNSRecordTypeDeregistering && 18048 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst)) 18049 { 18050 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp"; 18051 for (r2 = m->ResourceRecords; r2; r2=r2->next) 18052 if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) && 18053 r2->resrec.RecordType != kDNSRecordTypeDeregistering && 18054 r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) && 18055 SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp)) 18056 break; 18057 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr; // So that we wake for BTMM IPSEC packets, even without a matching SRV record 18058 if (!r2 && kaWake) r2 = rr; // So that we wake for keepalive packets, even without a matching SRV record 18059 if (r2) 18060 { 18061 LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s", 18062 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2)); 18063 ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC); 18064 } 18065 else 18066 LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d", 18067 InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port)); 18068 } 18069 mDNS_Unlock(m); 18070 } 18071 } 18072 18073 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID) 18074 { 18075 static const mDNSOpaque16 Ethertype_ARP = { { 0x08, 0x06 } }; // Ethertype 0x0806 = ARP 18076 static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } }; // Ethertype 0x0800 = IPv4 18077 static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } }; // Ethertype 0x86DD = IPv6 18078 static const mDNSOpaque16 ARP_hrd_eth = { { 0x00, 0x01 } }; // Hardware address space (Ethernet = 1) 18079 static const mDNSOpaque16 ARP_pro_ip = { { 0x08, 0x00 } }; // Protocol address space (IP = 0x0800) 18080 18081 // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header. 18082 // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned, 18083 // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned 18084 // since it points to a an address 14 bytes before pkt. 18085 const EthernetHeader *const eth = (const EthernetHeader *)p; 18086 const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1); 18087 mDNSAddr src, dst; 18088 #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0) 18089 18090 // Is ARP? Length must be at least 14 + 28 = 42 bytes 18091 if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip)) 18092 mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID); 18093 // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes 18094 else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0) 18095 { 18096 const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4; 18097 const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen); 18098 if (transEnd > end) transEnd = end; 18099 debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src.b, &pkt->v4.dst.b); 18100 src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src; 18101 dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst; 18102 if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol)) 18103 mDNSCoreReceiveRawTransportPacket(m, ð->src, &src, &dst, pkt->v4.protocol, p, (const TransportLayerPacket*)trans, transEnd, InterfaceID, 0); 18104 } 18105 // Is IPv6? Length must be at least 14 + 28 = 42 bytes 18106 else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6)) 18107 { 18108 const mDNSu8 *const trans = p + 54; 18109 debugf("Got IPv6 %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src.b, &pkt->v6.dst.b); 18110 src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src; 18111 dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst; 18112 if (end >= trans + RequiredCapLen(pkt->v6.pro)) 18113 mDNSCoreReceiveRawTransportPacket(m, ð->src, &src, &dst, pkt->v6.pro, p, (const TransportLayerPacket*)trans, end, InterfaceID, 18114 (mDNSu16)(pkt->bytes[4] << 8) | pkt->bytes[5]); 18115 } 18116 } 18117 18118 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name) 18119 { 18120 name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s", 18121 m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel); 18122 } 18123 18124 #ifndef SPC_DISABLED 18125 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result) 18126 { 18127 if (result == mStatus_NameConflict) 18128 mDNS_RenameAndReregisterService(m, srs, mDNSNULL); 18129 else if (result == mStatus_MemFree) 18130 { 18131 if (m->SleepState) 18132 m->SPSState = 3; 18133 else 18134 { 18135 m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL); 18136 if (m->SPSState) 18137 { 18138 domainlabel name; 18139 ConstructSleepProxyServerName(m, &name); 18140 mDNS_RegisterService(m, srs, 18141 &name, &SleepProxyServiceType, &localdomain, 18142 mDNSNULL, m->SPSSocket->port, // Host, port 18143 mDNSNULL, 18144 (mDNSu8 *)"", 1, // TXT data, length 18145 mDNSNULL, 0, // Subtypes (none) 18146 mDNSInterface_Any, // Interface ID 18147 SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags 18148 } 18149 LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped"); 18150 } 18151 } 18152 } 18153 #endif 18154 18155 // Called with lock held 18156 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features) 18157 { 18158 // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context 18159 mDNS_DropLockBeforeCallback(); 18160 18161 // If turning off SPS, close our socket 18162 // (Do this first, BEFORE calling mDNS_DeregisterService below) 18163 if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; } 18164 18165 // If turning off, or changing type, deregister old name 18166 #ifndef SPC_DISABLED 18167 if (m->SPSState == 1 && sps != m->SPSType) 18168 { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); } 18169 #endif // SPC_DISABLED 18170 18171 // Record our new SPS parameters 18172 m->SPSType = sps; 18173 m->SPSPortability = port; 18174 m->SPSMarginalPower = marginalpower; 18175 m->SPSTotalPower = totpower; 18176 m->SPSFeatureFlags = features; 18177 // If turning on, open socket and advertise service 18178 if (sps) 18179 { 18180 if (!m->SPSSocket) 18181 { 18182 m->SPSSocket = mDNSPlatformUDPSocket(zeroIPPort); 18183 if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; } 18184 } 18185 #ifndef SPC_DISABLED 18186 if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree); 18187 #endif // SPC_DISABLED 18188 } 18189 else if (m->SPSState) 18190 { 18191 LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState); 18192 m->NextScheduledSPS = m->timenow; 18193 } 18194 fail: 18195 mDNS_ReclaimLockAfterCallback(); 18196 } 18197 18198 // *************************************************************************** 18199 // MARK: - Startup and Shutdown 18200 18201 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords) 18202 { 18203 if (storage && numrecords) 18204 { 18205 mDNSu32 i; 18206 debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity)); 18207 for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1]; 18208 storage[numrecords-1].next = m->rrcache_free; 18209 m->rrcache_free = storage; 18210 m->rrcache_size += numrecords; 18211 } 18212 } 18213 18214 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords) 18215 { 18216 mDNS_Lock(m); 18217 mDNS_GrowCache_internal(m, storage, numrecords); 18218 mDNS_Unlock(m); 18219 } 18220 18221 mDNSlocal mStatus mDNS_InitStorage(mDNS *const m, mDNS_PlatformSupport *const p, 18222 CacheEntity *rrcachestorage, mDNSu32 rrcachesize, 18223 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context) 18224 { 18225 mDNSu32 slot; 18226 mDNSs32 timenow; 18227 mStatus result; 18228 18229 if (!rrcachestorage) rrcachesize = 0; 18230 18231 m->p = p; 18232 m->NetworkChanged = 0; 18233 m->CanReceiveUnicastOn5353 = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise 18234 m->AdvertiseLocalAddresses = AdvertiseLocalAddresses; 18235 m->DivertMulticastAdvertisements = mDNSfalse; 18236 m->mDNSPlatformStatus = mStatus_Waiting; 18237 m->UnicastPort4 = zeroIPPort; 18238 m->UnicastPort6 = zeroIPPort; 18239 m->PrimaryMAC = zeroEthAddr; 18240 m->MainCallback = Callback; 18241 m->MainContext = Context; 18242 m->rec.r.resrec.RecordType = 0; 18243 18244 // For debugging: To catch and report locking failures 18245 m->mDNS_busy = 0; 18246 m->mDNS_reentrancy = 0; 18247 m->ShutdownTime = 0; 18248 m->lock_rrcache = 0; 18249 m->lock_Questions = 0; 18250 m->lock_Records = 0; 18251 18252 // Task Scheduling variables 18253 result = mDNSPlatformTimeInit(); 18254 if (result != mStatus_NoError) return(result); 18255 m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF); 18256 timenow = mDNS_TimeNow_NoLock(m); 18257 18258 m->timenow = 0; // MUST only be set within mDNS_Lock/mDNS_Unlock section 18259 m->timenow_last = timenow; 18260 m->NextScheduledEvent = timenow; 18261 m->SuppressQueries = timenow; 18262 m->SuppressResponses = timenow; 18263 m->NextCacheCheck = timenow + FutureTime; 18264 m->NextScheduledQuery = timenow + FutureTime; 18265 m->NextScheduledProbe = timenow + FutureTime; 18266 m->NextScheduledResponse = timenow + FutureTime; 18267 m->NextScheduledNATOp = timenow + FutureTime; 18268 m->NextScheduledSPS = timenow + FutureTime; 18269 m->NextScheduledKA = timenow + FutureTime; 18270 m->NextScheduledStopTime = timenow + FutureTime; 18271 m->NextBLEServiceTime = 0; // zero indicates inactive 18272 18273 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 18274 m->NextBonjourDisableTime = 0; // Timer active when non zero. 18275 m->BonjourEnabled = 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled. 18276 #endif 18277 18278 m->RandomQueryDelay = 0; 18279 m->RandomReconfirmDelay = 0; 18280 m->PktNum = 0; 18281 m->MPktNum = 0; 18282 m->LocalRemoveEvents = mDNSfalse; 18283 m->SleepState = SleepState_Awake; 18284 m->SleepSeqNum = 0; 18285 m->SystemWakeOnLANEnabled = mDNSfalse; 18286 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 18287 m->SentSleepProxyRegistration = mDNSfalse; 18288 m->AnnounceOwner = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond); 18289 #endif 18290 m->DelaySleep = 0; 18291 m->SleepLimit = 0; 18292 18293 18294 // These fields only required for mDNS Searcher... 18295 m->Questions = mDNSNULL; 18296 m->NewQuestions = mDNSNULL; 18297 m->CurrentQuestion = mDNSNULL; 18298 m->LocalOnlyQuestions = mDNSNULL; 18299 m->NewLocalOnlyQuestions = mDNSNULL; 18300 m->RestartQuestion = mDNSNULL; 18301 m->rrcache_size = 0; 18302 m->rrcache_totalused = 0; 18303 m->rrcache_active = 0; 18304 m->rrcache_report = 10; 18305 m->rrcache_free = mDNSNULL; 18306 18307 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) 18308 { 18309 m->rrcache_hash[slot] = mDNSNULL; 18310 m->rrcache_nextcheck[slot] = timenow + FutureTime;; 18311 } 18312 18313 mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize); 18314 m->rrauth.rrauth_free = mDNSNULL; 18315 18316 for (slot = 0; slot < AUTH_HASH_SLOTS; slot++) 18317 m->rrauth.rrauth_hash[slot] = mDNSNULL; 18318 18319 // Fields below only required for mDNS Responder... 18320 m->hostlabel.c[0] = 0; 18321 m->nicelabel.c[0] = 0; 18322 m->MulticastHostname.c[0] = 0; 18323 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME) 18324 m->RandomizedHostname.c[0] = 0; 18325 #endif 18326 m->HIHardware.c[0] = 0; 18327 m->HISoftware.c[0] = 0; 18328 m->ResourceRecords = mDNSNULL; 18329 m->DuplicateRecords = mDNSNULL; 18330 m->NewLocalRecords = mDNSNULL; 18331 m->NewLocalOnlyRecords = mDNSfalse; 18332 m->CurrentRecord = mDNSNULL; 18333 m->HostInterfaces = mDNSNULL; 18334 m->ProbeFailTime = 0; 18335 m->NumFailedProbes = 0; 18336 m->SuppressProbes = 0; 18337 18338 #ifndef UNICAST_DISABLED 18339 m->NextuDNSEvent = timenow + FutureTime; 18340 m->NextSRVUpdate = timenow + FutureTime; 18341 18342 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18343 m->DNSServers = mDNSNULL; 18344 #endif 18345 18346 m->Router = zeroAddr; 18347 m->AdvertisedV4 = zeroAddr; 18348 m->AdvertisedV6 = zeroAddr; 18349 18350 m->AuthInfoList = mDNSNULL; 18351 18352 m->ReverseMap.ThisQInterval = -1; 18353 m->StaticHostname.c[0] = 0; 18354 m->FQDN.c[0] = 0; 18355 m->Hostnames = mDNSNULL; 18356 18357 m->WABBrowseQueriesCount = 0; 18358 m->WABLBrowseQueriesCount = 0; 18359 m->WABRegQueriesCount = 0; 18360 m->AutoTargetServices = 1; 18361 18362 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND) 18363 m->NumAllInterfaceRecords = 0; 18364 m->NumAllInterfaceQuestions = 0; 18365 #endif 18366 // NAT traversal fields 18367 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 18368 m->LLQNAT.clientCallback = mDNSNULL; 18369 m->LLQNAT.clientContext = mDNSNULL; 18370 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 18371 m->NATTraversals = mDNSNULL; 18372 m->CurrentNATTraversal = mDNSNULL; 18373 m->retryIntervalGetAddr = 0; // delta between time sent and retry 18374 m->retryGetAddr = timenow + FutureTime; // absolute time when we retry 18375 m->ExtAddress = zerov4Addr; 18376 m->PCPNonce[0] = mDNSRandom(-1); 18377 m->PCPNonce[1] = mDNSRandom(-1); 18378 m->PCPNonce[2] = mDNSRandom(-1); 18379 18380 m->NATMcastRecvskt = mDNSNULL; 18381 m->LastNATupseconds = 0; 18382 m->LastNATReplyLocalTime = timenow; 18383 m->LastNATMapResultCode = NATErr_None; 18384 18385 m->UPnPInterfaceID = 0; 18386 m->SSDPSocket = mDNSNULL; 18387 m->SSDPWANPPPConnection = mDNSfalse; 18388 m->UPnPRouterPort = zeroIPPort; 18389 m->UPnPSOAPPort = zeroIPPort; 18390 m->UPnPRouterURL = mDNSNULL; 18391 m->UPnPWANPPPConnection = mDNSfalse; 18392 m->UPnPSOAPURL = mDNSNULL; 18393 m->UPnPRouterAddressString = mDNSNULL; 18394 m->UPnPSOAPAddressString = mDNSNULL; 18395 m->SPSType = 0; 18396 m->SPSPortability = 0; 18397 m->SPSMarginalPower = 0; 18398 m->SPSTotalPower = 0; 18399 m->SPSFeatureFlags = 0; 18400 m->SPSState = 0; 18401 m->SPSProxyListChanged = mDNSNULL; 18402 m->SPSSocket = mDNSNULL; 18403 #if MDNSRESPONDER_SUPPORTS(COMMON, SPS_CLIENT) 18404 m->SPSBrowseCallback = mDNSNULL; 18405 #endif 18406 m->ProxyRecords = 0; 18407 18408 m->DNSPushServers = mDNSNULL; 18409 m->DNSPushZones = mDNSNULL; 18410 #endif 18411 18412 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER) 18413 if (WCFConnectionNew) 18414 { 18415 m->WCF = WCFConnectionNew(); 18416 if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; } 18417 } 18418 #endif 18419 18420 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 18421 // Currently we only support the root trust anchor. 18422 dnssec_error_t dnssec_err; 18423 m->DNSSECTrustAnchorManager = dnssec_obj_trust_anchor_manager_with_root_anchor_create(&dnssec_err); 18424 if (dnssec_err != DNSSEC_ERROR_NO_ERROR) 18425 { 18426 return mStatus_UnknownErr; 18427 } 18428 #endif 18429 18430 #if MDNSRESPONDER_SUPPORTS(APPLE, RUNTIME_MDNS_METRICS) 18431 // The first mDNS report will be generated in "RuntimeMDNSMetricsReportInterval"s. 18432 m->NextMDNSResponseDelayReport = NonZeroTime(timenow + RuntimeMDNSMetricsReportInterval); 18433 #endif 18434 18435 // Set .local domain as one of the domain that can do domain enumeration. 18436 DomainEnumerationOp *const dotLocalDomainToDoEnumeration = mDNSPlatformMemAllocateClear(sizeof(*dotLocalDomainToDoEnumeration)); 18437 if (dotLocalDomainToDoEnumeration != mDNSNULL) 18438 { 18439 AssignDomainName(&dotLocalDomainToDoEnumeration->name, &localdomain); 18440 m->domainsToDoEnumeration = dotLocalDomainToDoEnumeration; 18441 } 18442 18443 return(result); 18444 } 18445 18446 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p, 18447 CacheEntity *rrcachestorage, mDNSu32 rrcachesize, 18448 mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context) 18449 { 18450 mStatus result = mDNS_InitStorage(m, p, rrcachestorage, rrcachesize, AdvertiseLocalAddresses, Callback, Context); 18451 if (result != mStatus_NoError) 18452 return(result); 18453 18454 #if MDNS_MALLOC_DEBUGGING 18455 static mDNSListValidator lv; 18456 mDNSPlatformAddListValidator(&lv, mDNS_ValidateLists, "mDNS_ValidateLists", m); 18457 #endif 18458 result = mDNSPlatformInit(m); 18459 18460 #ifndef UNICAST_DISABLED 18461 // It's better to do this *after* the platform layer has set up the 18462 // interface list and security credentials 18463 uDNS_SetupDNSConfig(m); // Get initial DNS configuration 18464 #endif 18465 18466 #if MDNSRESPONDER_SUPPORTS(APPLE, DISCOVERY_PROXY_CLIENT) 18467 if (DPCFeatureEnabled()) 18468 { 18469 mDNSPlatformMemZero(&DPCBrowse, sizeof(DPCBrowse)); 18470 // Note: ConstructServiceName(), which is called by mDNS_StartBrowse_internal(), will turn 18471 // "_local._dnssd-dp._tcp" to "_local._sub._dnssd-dp._tcp". See <rdar://3588761>. 18472 const domainname *const serviceType = (const domainname *)"\x6" "_local" "\x9" "_dnssd-dp" "\x4" "_tcp"; 18473 mDNS_StartBrowse_internal(m, &DPCBrowse, serviceType, &localdomain, mDNSInterface_Any, 0, mDNSfalse, mDNSfalse, 18474 DPCBrowseHandler, mDNSNULL); 18475 // Set querying interval to -1 to avoid scheduling queries for the browse. They'll instead be sent 18476 // opportunistically along with other non-probe questions. 18477 DPCBrowse.ThisQInterval = -1; 18478 } 18479 #endif 18480 return(result); 18481 } 18482 18483 mDNSexport void mDNS_ConfigChanged(mDNS *const m) 18484 { 18485 if (m->SPSState == 1) 18486 { 18487 domainlabel name, newname; 18488 #ifndef SPC_DISABLED 18489 domainname type, domain; 18490 DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain); 18491 #endif // SPC_DISABLED 18492 ConstructSleepProxyServerName(m, &newname); 18493 if (!SameDomainLabelCS(name.c, newname.c)) 18494 { 18495 LogSPS("Renaming SPS from %#s to %#s", name.c, newname.c); 18496 // When SleepProxyServerCallback gets the mStatus_MemFree message, 18497 // it will reregister the service under the new name 18498 m->SPSState = 2; 18499 #ifndef SPC_DISABLED 18500 mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid); 18501 #endif // SPC_DISABLED 18502 } 18503 } 18504 18505 if (m->MainCallback) 18506 m->MainCallback(m, mStatus_ConfigChanged); 18507 } 18508 18509 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result) 18510 { 18511 (void)m; // unused 18512 debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c); 18513 mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result); 18514 } 18515 18516 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18517 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr) 18518 { 18519 mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative || 18520 cr->resrec.rrtype == kDNSType_A || 18521 cr->resrec.rrtype == kDNSType_AAAA || 18522 cr->resrec.rrtype == kDNSType_SRV || 18523 cr->resrec.rrtype == kDNSType_CNAME; 18524 18525 debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s", 18526 purge ? "purging" : "reconfirming", 18527 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL, 18528 cr->resrec.rDNSServer ? mDNSVal16(cr->resrec.rDNSServer->port) : -1, 18529 cr->resrec.rDNSServer ? cr->resrec.rDNSServer->domain.c : mDNSNULL, CRDisplayString(m, cr)); 18530 18531 if (purge) 18532 { 18533 LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType); 18534 mDNS_PurgeCacheResourceRecord(m, cr); 18535 } 18536 else 18537 { 18538 LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType); 18539 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer); 18540 } 18541 } 18542 #endif 18543 18544 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q) 18545 { 18546 CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname); 18547 CacheRecord *rp; 18548 for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next) 18549 { 18550 if (SameNameCacheRecordAnswersQuestion(rp, q)) 18551 { 18552 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_PurgeBeforeResolve: Flushing " PRI_S, CRDisplayString(m, rp)); 18553 mDNS_PurgeCacheResourceRecord(m, rp); 18554 } 18555 } 18556 } 18557 18558 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18559 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new) 18560 { 18561 DNSQuestion *qptr; 18562 18563 (void) m; 18564 18565 if (q->DuplicateOf) 18566 LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c); 18567 18568 // Make sure all the duplicate questions point to the same DNSServer so that delivery 18569 // of events for all of them are consistent. Duplicates for a question are always inserted 18570 // after in the list. 18571 q->qDNSServer = new; 18572 for (qptr = q->next ; qptr; qptr = qptr->next) 18573 { 18574 if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; } 18575 } 18576 } 18577 #endif 18578 18579 mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete) 18580 { 18581 McastResolver *mr; 18582 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18583 DNSServer *ptr; 18584 #endif 18585 18586 if (delete) 18587 { 18588 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18589 for (ptr = m->DNSServers; ptr; ptr = ptr->next) 18590 { 18591 ptr->penaltyTime = 0; 18592 ptr->flags |= DNSServerFlag_Delete; 18593 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS) 18594 if (ptr->flags & DNSServerFlag_Unreachable) 18595 NumUnreachableDNSServers--; 18596 #endif 18597 } 18598 #endif 18599 // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at 18600 // mcast resolvers. Today we get both mcast and ucast configuration using the same 18601 // API 18602 for (mr = m->McastResolvers; mr; mr = mr->next) 18603 mr->flags |= McastResolver_FlagDelete; 18604 } 18605 else 18606 { 18607 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18608 for (ptr = m->DNSServers; ptr; ptr = ptr->next) 18609 { 18610 ptr->penaltyTime = 0; 18611 ptr->flags &= ~DNSServerFlag_Delete; 18612 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS) 18613 if (ptr->flags & DNSServerFlag_Unreachable) 18614 NumUnreachableDNSServers++; 18615 #endif 18616 } 18617 #endif 18618 for (mr = m->McastResolvers; mr; mr = mr->next) 18619 mr->flags &= ~McastResolver_FlagDelete; 18620 } 18621 } 18622 18623 mDNSlocal void SetDynDNSHostNameIfChanged(mDNS *const m, domainname *const fqdn) 18624 { 18625 // Did our FQDN change? 18626 if (!SameDomainName(fqdn, &m->FQDN)) 18627 { 18628 if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN); 18629 18630 AssignDomainName(&m->FQDN, fqdn); 18631 18632 if (m->FQDN.c[0]) 18633 { 18634 mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); 18635 mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL); 18636 } 18637 } 18638 } 18639 18640 // Even though this is called Setup it is not called just once at startup. 18641 // Its actually called multiple times, every time theres a configuration change. 18642 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m) 18643 { 18644 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18645 mDNSu32 slot; 18646 CacheGroup *cg; 18647 CacheRecord *cr; 18648 #endif 18649 mDNSAddr v4, v6, r; 18650 domainname fqdn; 18651 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18652 DNSServer *ptr, **p = &m->DNSServers; 18653 const DNSServer *oldServers = m->DNSServers; 18654 DNSQuestion *q; 18655 #endif 18656 McastResolver *mr, **mres = &m->McastResolvers; 18657 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18658 DNSPushServer **psp; 18659 #endif 18660 18661 debugf("uDNS_SetupDNSConfig: entry"); 18662 18663 // Let the platform layer get the current DNS information and setup the WAB queries if needed. 18664 uDNS_SetupWABQueries(m); 18665 18666 mDNS_Lock(m); 18667 18668 // We need to first mark all the entries to be deleted. If the configuration changed, then 18669 // the entries would be undeleted appropriately. Otherwise, we need to clear them. 18670 // 18671 // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the 18672 // configuration. We already processed search domains in uDNS_SetupWABQueries above and 18673 // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig 18674 // for the dns configuration change notification. 18675 SetConfigState(m, mDNStrue); 18676 if (!mDNSPlatformSetDNSConfig(mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue)) 18677 { 18678 SetDynDNSHostNameIfChanged(m, &fqdn); 18679 SetConfigState(m, mDNSfalse); 18680 mDNS_Unlock(m); 18681 LogRedact(MDNS_LOG_CATEGORY_STATE, MDNS_LOG_DEFAULT, "uDNS_SetupDNSConfig: No configuration change"); 18682 return mStatus_NoError; 18683 } 18684 18685 // For now, we just delete the mcast resolvers. We don't deal with cache or 18686 // questions here. Neither question nor cache point to mcast resolvers. Questions 18687 // do inherit the timeout values from mcast resolvers. But we don't bother 18688 // affecting them as they never change. 18689 while (*mres) 18690 { 18691 if (((*mres)->flags & McastResolver_FlagDelete) != 0) 18692 { 18693 mr = *mres; 18694 *mres = (*mres)->next; 18695 debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c); 18696 mDNSPlatformMemFree(mr); 18697 } 18698 else 18699 { 18700 (*mres)->flags &= ~McastResolver_FlagNew; 18701 mres = &(*mres)->next; 18702 } 18703 } 18704 18705 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18706 Querier_ProcessDNSServiceChanges(mDNSfalse); 18707 #else 18708 // Update our qDNSServer pointers before we go and free the DNSServer object memory 18709 // 18710 // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer 18711 // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped 18712 // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick 18713 // DNSServers and flush the cache. 18714 // 18715 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that 18716 // is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not 18717 // flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer 18718 // pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't 18719 // flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse) 18720 // later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though 18721 // we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to 18722 // the same resGroupID. 18723 // 18724 // Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV 18725 // of the old followed by ADD of the new records. 18726 // 18727 // - A non-scoped question picks DNSServer X, creates a cache entry with X. If the resolver gets removed later, we will 18728 // pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same 18729 // as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL. 18730 // 18731 // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate 18732 // cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the 18733 // non-scoped question and vice versa. 18734 // 18735 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64) 18736 DNS64RestartQuestions(m); 18737 #endif 18738 18739 // First, restart questions whose suppression status will change. The suppression status of each question in a given 18740 // question set, i.e., a non-duplicate question and all of its duplicates, if any, may or may not change. For example, 18741 // a suppressed (or non-suppressed) question that is currently a duplicate of a suppressed (or non-suppressed) question 18742 // may become a non-suppressed (or suppressed) question, while the question that it's a duplicate of may remain 18743 // suppressed (or non-suppressed). 18744 for (q = m->Questions; q; q = q->next) 18745 { 18746 DNSServer *s; 18747 const DNSServer *t; 18748 mDNSBool oldSuppressed; 18749 18750 if (mDNSOpaque16IsZero(q->TargetQID)) continue; 18751 18752 SetValidDNSServers(m, q); 18753 q->triedAllServersOnce = mDNSfalse; 18754 s = GetServerForQuestion(m, q); 18755 t = q->qDNSServer; 18756 if (s != t) 18757 { 18758 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, 18759 "[R%u->Q%u] uDNS_SetupDNSConfig: Updating DNS server from " PRI_IP_ADDR ":%d (" PRI_DM_NAME ") to " 18760 PRI_IP_ADDR ":%d (" PRI_DM_NAME ") for question " PRI_DM_NAME " (" PUB_S ") (scope:%p)", 18761 q->request_id, mDNSVal16(q->TargetQID), 18762 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), DM_NAME_PARAM(t ? &t->domain : mDNSNULL), 18763 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), DM_NAME_PARAM(s ? &s->domain : mDNSNULL), 18764 DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->InterfaceID); 18765 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) 18766 // If this question had a DNS Push server associated with it, substitute the new server for the 18767 // old one. If there is no new server, then we'll clean up the push server later. 18768 if (!q->DuplicateOf && (q->dnsPushServer != mDNSNULL)) 18769 { 18770 if (q->dnsPushServer->qDNSServer == t) 18771 { 18772 q->dnsPushServer->qDNSServer = s; // which might be null 18773 } 18774 // If it is null, cancel the DNS push server. 18775 if (q->dnsPushServer->qDNSServer == mDNSNULL) 18776 { 18777 DNSPushReconcileConnection(m, q); 18778 } 18779 } 18780 #endif 18781 } 18782 oldSuppressed = q->Suppressed; 18783 q->Suppressed = ShouldSuppressUnicastQuery(q, s); 18784 if (!q->Suppressed != !oldSuppressed) q->Restart = mDNStrue; 18785 } 18786 RestartUnicastQuestions(m); 18787 18788 // Now, change the server for each question set, if necessary. Note that questions whose suppression status changed 18789 // have already had their server changed by being restarted. 18790 for (q = m->Questions; q; q = q->next) 18791 { 18792 DNSServer *s; 18793 const DNSServer *t; 18794 18795 if (mDNSOpaque16IsZero(q->TargetQID) || q->DuplicateOf) continue; 18796 18797 SetValidDNSServers(m, q); 18798 q->triedAllServersOnce = mDNSfalse; 18799 s = GetServerForQuestion(m, q); 18800 t = q->qDNSServer; 18801 DNSServerChangeForQuestion(m, q, s); 18802 if (s == t) continue; 18803 18804 q->Suppressed = ShouldSuppressUnicastQuery(q, s); 18805 q->unansweredQueries = 0; 18806 q->TargetQID = mDNS_NewMessageID(m); 18807 if (!q->Suppressed) ActivateUnicastQuery(m, q, mDNStrue); 18808 } 18809 18810 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) 18811 // The above code may have found some DNS Push servers that are no longer valid. Now that we 18812 // are done running through the code, we need to drop our connections to those servers. 18813 // When we get here, any such servers should have zero questions associated with them. 18814 for (psp = &m->DNSPushServers; *psp != mDNSNULL; ) 18815 { 18816 DNSPushServer *server = *psp; 18817 18818 // It's possible that a push server whose DNS server has been deleted could be still connected but 18819 // not referenced by any questions. In this case, we just delete the push server rather than trying 18820 // to figure out with which DNS server (if any) to associate it. 18821 if (server->qDNSServer == mDNSNULL || (server->qDNSServer->flags & DNSServerFlag_Delete)) 18822 { 18823 // Since we are changing the m->DNSPushServers that DNSPushServerCancel() will iterate later, we will do the 18824 // server removal for it. And tell it to not touch the m->DNSPushServers by passing alreadyRemovedFromSystem 18825 // == true. 18826 // Unlink from the m->DNSPushServers list. 18827 *psp = server->next; 18828 server->next = mDNSNULL; 18829 // Release all the DNS push zones that use this server from the m->DNSPushZones list. 18830 DNSPushZoneRemove(m, server); 18831 // Cancel the server. 18832 DNSPushServerCancel(server, mDNStrue); 18833 // Release the reference to the server that m->DNSPushServers list holds. 18834 DNS_PUSH_RELEASE(server, DNSPushServerFinalize); 18835 } 18836 else 18837 { 18838 psp = &(server->next); 18839 } 18840 } 18841 #endif 18842 18843 FORALL_CACHERECORDS(slot, cg, cr) 18844 { 18845 if (cr->resrec.InterfaceID) continue; 18846 18847 // We already walked the questions and restarted/reactivated them if the dns server 18848 // change affected the question. That should take care of updating the cache. But 18849 // what if there is no active question at this point when the DNS server change 18850 // happened ? There could be old cache entries lying around and if we don't flush 18851 // them, a new question after the DNS server change could pick up these stale 18852 // entries and get a wrong answer. 18853 // 18854 // For cache entries that have active questions we might have skipped rescheduling 18855 // the questions if they were suppressed (see above). To keep it simple, we walk 18856 // all the cache entries to make sure that there are no stale entries. We use the 18857 // active question's InterfaceID/ServiceID for looking up the right DNS server. 18858 // 18859 // Note: If GetServerForName returns NULL, it could either mean that there are no 18860 // DNS servers or no matching DNS servers for this question. In either case, 18861 // the cache should get purged below when we process deleted DNS servers. 18862 18863 if (cr->CRActiveQuestion) 18864 { 18865 // Purge or Reconfirm if this cache entry would use the new DNS server 18866 ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion->InterfaceID, cr->CRActiveQuestion->ServiceID); 18867 if (ptr && (ptr != cr->resrec.rDNSServer)) 18868 { 18869 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a", 18870 CRDisplayString(m, cr), &ptr->addr, 18871 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL); 18872 PurgeOrReconfirmCacheRecord(m, cr); 18873 18874 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration 18875 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events. 18876 if (!cr->resrec.rDNSServer && cr->CRActiveQuestion->qDNSServer) 18877 { 18878 LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr->CRActiveQuestion->qDNSServer->addr, CRDisplayString(m, cr)); 18879 cr->resrec.rDNSServer = cr->CRActiveQuestion->qDNSServer; 18880 } 18881 } 18882 18883 if (cr->resrec.rDNSServer && cr->resrec.rDNSServer->flags & DNSServerFlag_Delete) 18884 { 18885 DNSQuestion *qptr = cr->CRActiveQuestion; 18886 if (qptr->qDNSServer == cr->resrec.rDNSServer) 18887 { 18888 LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a" 18889 " to be freed", CRDisplayString(m, cr), 18890 qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID, 18891 &cr->resrec.rDNSServer->addr); 18892 qptr->validDNSServers = zeroOpaque128; 18893 qptr->qDNSServer = mDNSNULL; 18894 cr->resrec.rDNSServer = mDNSNULL; 18895 } 18896 else 18897 { 18898 LogInfo("uDNS_SetupDNSConfig: Cache Record %s, Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted)," 18899 " resetting to question's DNSServer Address %#a", CRDisplayString(m, cr), 18900 qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID, 18901 &cr->resrec.rDNSServer->addr, 18902 qptr->qDNSServer ? &qptr->qDNSServer->addr : mDNSNULL); 18903 cr->resrec.rDNSServer = qptr->qDNSServer; 18904 } 18905 PurgeOrReconfirmCacheRecord(m, cr); 18906 } 18907 } 18908 else if (!cr->resrec.rDNSServer || cr->resrec.rDNSServer->flags & DNSServerFlag_Delete) 18909 { 18910 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, 18911 "uDNS_SetupDNSConfig: Purging Resourcerecord " PRI_S ", DNS server " PUB_S " " PRI_IP_ADDR " " PUB_S, 18912 CRDisplayString(m, cr), !cr->resrec.rDNSServer ? "(to be deleted)" : "", 18913 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL, 18914 cr->resrec.rDNSServer ? DNSScopeToString(cr->resrec.rDNSServer->scopeType) : "" ); 18915 cr->resrec.rDNSServer = mDNSNULL; 18916 mDNS_PurgeCacheResourceRecord(m, cr); 18917 } 18918 } 18919 18920 // Delete all the DNS servers that are flagged for deletion 18921 while (*p) 18922 { 18923 if (((*p)->flags & DNSServerFlag_Delete) != 0) 18924 { 18925 ptr = *p; 18926 *p = (*p)->next; 18927 LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c); 18928 mDNSPlatformMemFree(ptr); 18929 } 18930 else 18931 { 18932 p = &(*p)->next; 18933 } 18934 } 18935 LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m)); 18936 18937 // If we now have no DNS servers at all and we used to have some, then immediately purge all unicast cache records (including for LLQs). 18938 // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless. 18939 // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour. 18940 // Similarly, if we now have some DNS servers and we used to have none, we want to purge any fake negative results we may have generated. 18941 if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL)) 18942 { 18943 int count = 0; 18944 FORALL_CACHERECORDS(slot, cg, cr) 18945 { 18946 if (!cr->resrec.InterfaceID) 18947 { 18948 mDNS_PurgeCacheResourceRecord(m, cr); 18949 count++; 18950 } 18951 } 18952 LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache", 18953 m->DNSServers ? "DNS server became" : "No DNS servers", count); 18954 18955 // Force anything that needs to get zone data to get that information again 18956 RestartRecordGetZoneData(m); 18957 } 18958 #endif // !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER) 18959 18960 SetDynDNSHostNameIfChanged(m, &fqdn); 18961 18962 mDNS_Unlock(m); 18963 18964 // handle router and primary interface changes 18965 v4 = v6 = r = zeroAddr; 18966 v4.type = r.type = mDNSAddrType_IPv4; 18967 18968 if (mDNSPlatformGetPrimaryInterface(&v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4)) 18969 { 18970 mDNS_SetPrimaryInterfaceInfo(m, 18971 !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL, 18972 !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL, 18973 !mDNSIPv4AddressIsZero(r.ip.v4) ? &r : mDNSNULL); 18974 } 18975 else 18976 { 18977 mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL); 18978 if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure 18979 } 18980 return mStatus_NoError; 18981 } 18982 18983 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result) 18984 { 18985 m->mDNSPlatformStatus = result; 18986 if (m->MainCallback) 18987 { 18988 mDNS_Lock(m); 18989 mDNS_DropLockBeforeCallback(); // Allow client to legally make mDNS API calls from the callback 18990 m->MainCallback(m, mStatus_NoError); 18991 mDNS_ReclaimLockAfterCallback(); // Decrement mDNS_reentrancy to block mDNS API calls again 18992 mDNS_Unlock(m); 18993 } 18994 } 18995 18996 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start) 18997 { 18998 m->CurrentRecord = start; 18999 while (m->CurrentRecord) 19000 { 19001 AuthRecord *rr = m->CurrentRecord; 19002 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "DeregLoop: " PUB_S " deregistration for %p %02X " PRI_S, 19003 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating " : "Accelerating", 19004 rr, rr->resrec.RecordType, ARDisplayString(m, rr)); 19005 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering) 19006 mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid); 19007 else if (rr->AnnounceCount > 1) 19008 { 19009 rr->AnnounceCount = 1; 19010 rr->LastAPTime = m->timenow - rr->ThisAPInterval; 19011 SetNextAnnounceProbeTime(m, rr); 19012 } 19013 // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because 19014 // new records could have been added to the end of the list as a result of that call. 19015 if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now 19016 m->CurrentRecord = rr->next; 19017 } 19018 } 19019 19020 mDNSexport void mDNS_StartExit(mDNS *const m) 19021 { 19022 AuthRecord *rr; 19023 19024 mDNS_Lock(m); 19025 19026 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit"); 19027 m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5); 19028 19029 mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0); 19030 19031 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER) 19032 if (WCFConnectionDealloc) 19033 { 19034 if (m->WCF) 19035 { 19036 WCFConnectionDealloc(m->WCF); 19037 m->WCF = mDNSNULL; 19038 } 19039 } 19040 #endif 19041 19042 #ifndef UNICAST_DISABLED 19043 { 19044 SearchListElem *s; 19045 19046 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 19047 SuspendLLQs(m); 19048 #endif // MDNSRESPONDER_SUPPORTS(COMMON, DNS_LLQ) 19049 // Don't need to do SleepRecordRegistrations() here 19050 // because we deregister all records and services later in this routine 19051 while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn); 19052 19053 // For each member of our SearchList, deregister any records it may have created, and cut them from the list. 19054 // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list) 19055 // and we may crash because the list still contains dangling pointers. 19056 for (s = SearchList; s; s = s->next) 19057 while (s->AuthRecs) 19058 { 19059 ARListElem *dereg = s->AuthRecs; 19060 s->AuthRecs = s->AuthRecs->next; 19061 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback 19062 } 19063 } 19064 #endif 19065 19066 // When mDNSResponder exits, also deregister all the domains that are discovered through domain enumeration. 19067 for (DomainEnumerationOp *op = m->domainsToDoEnumeration; op != mDNSNULL; op = op->next) 19068 { 19069 for (mDNSu32 type = 0; type < mDNS_DomainTypeMaxCount; type++) 19070 { 19071 mDNS_DeregisterDomainsDiscoveredForDomainEnumeration(m, op, type); 19072 } 19073 } 19074 19075 DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_All); 19076 19077 // Shut down all our active NAT Traversals 19078 while (m->NATTraversals) 19079 { 19080 NATTraversalInfo *t = m->NATTraversals; 19081 mDNS_StopNATOperation_internal(m, t); // This will cut 't' from the list, thereby advancing m->NATTraversals in the process 19082 19083 // After stopping the NAT Traversal, we zero out the fields. 19084 // This has particularly important implications for our AutoTunnel records -- 19085 // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree 19086 // handlers to just turn around and attempt to re-register those same records. 19087 // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers 19088 // to not do this. 19089 t->ExternalAddress = zerov4Addr; 19090 t->NewAddress = zerov4Addr; 19091 t->ExternalPort = zeroIPPort; 19092 t->RequestedPort = zeroIPPort; 19093 t->Lifetime = 0; 19094 t->Result = mStatus_NoError; 19095 } 19096 19097 // Make sure there are nothing but deregistering records remaining in the list 19098 if (m->CurrentRecord) 19099 { 19100 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: ERROR m->CurrentRecord already set " PRI_S, ARDisplayString(m, m->CurrentRecord)); 19101 } 19102 19103 // We're in the process of shutting down, so queries, etc. are no longer available. 19104 // Consequently, determining certain information, e.g. the uDNS update server's IP 19105 // address, will not be possible. The records on the main list are more likely to 19106 // already contain such information, so we deregister the duplicate records first. 19107 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering duplicate resource records"); 19108 DeregLoop(m, m->DuplicateRecords); 19109 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering resource records"); 19110 19111 DeregLoop(m, m->ResourceRecords); 19112 19113 // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records, 19114 // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay. 19115 if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond) 19116 { 19117 m->NextScheduledResponse = m->timenow; 19118 m->SuppressResponses = 0; 19119 } 19120 19121 if (m->ResourceRecords) 19122 { 19123 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Sending final record deregistrations"); 19124 } 19125 else 19126 { 19127 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: No deregistering records remain"); 19128 } 19129 19130 for (rr = m->DuplicateRecords; rr; rr = rr->next) 19131 { 19132 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Should not still have Duplicate Records remaining: %02X " PRI_S, 19133 rr->resrec.RecordType, ARDisplayString(m, rr)); 19134 } 19135 19136 // If any deregistering records remain, send their deregistration announcements before we exit 19137 if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m); 19138 19139 mDNS_Unlock(m); 19140 19141 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: done"); 19142 } 19143 19144 mDNSexport void mDNS_FinalExit(mDNS *const m) 19145 { 19146 mDNSu32 rrcache_active = 0; 19147 mDNSu32 rrcache_totalused = m->rrcache_totalused; 19148 mDNSu32 slot; 19149 AuthRecord *rr; 19150 19151 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: mDNSPlatformClose"); 19152 mDNSPlatformClose(m); 19153 19154 for (slot = 0; slot < CACHE_HASH_SLOTS; slot++) 19155 { 19156 while (m->rrcache_hash[slot]) 19157 { 19158 CacheGroup *cg = m->rrcache_hash[slot]; 19159 while (cg->members) 19160 { 19161 CacheRecord *cr = cg->members; 19162 cg->members = cg->members->next; 19163 if (cr->CRActiveQuestion) rrcache_active++; 19164 ReleaseCacheRecord(m, cr); 19165 } 19166 cg->rrcache_tail = &cg->members; 19167 ReleaseCacheGroup(m, &m->rrcache_hash[slot]); 19168 } 19169 } 19170 debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active); 19171 if (rrcache_active != m->rrcache_active) 19172 { 19173 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "*** ERROR *** rrcache_totalused %u; rrcache_active %u != m->rrcache_active %u", 19174 rrcache_totalused, rrcache_active, m->rrcache_active); 19175 } 19176 19177 for (rr = m->ResourceRecords; rr; rr = rr->next) 19178 { 19179 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit failed to send goodbye for: %p %02X " PRI_S, rr, rr->resrec.RecordType, 19180 ARDisplayString(m, rr)); 19181 } 19182 19183 #if MDNSRESPONDER_SUPPORTS(COMMON, LOCAL_DNS_RESOLVER_DISCOVERY) 19184 tls_cert_dispose(); 19185 #endif 19186 19187 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2) 19188 MDNS_DISPOSE_DNSSEC_OBJ(m->DNSSECTrustAnchorManager); 19189 #endif 19190 19191 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: done"); 19192 } 19193 19194 #ifdef UNIT_TEST 19195 #include "../unittests/mdns_ut.c" 19196 #endif 19197