xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSCore/mDNS.c (revision ddb365bfc9e868ad24ccdcb0dc91af18b10df082)
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-2020 Apple Inc. All rights reserved.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * 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 
29 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
30 #include "D2D.h"
31 #endif
32 
33 #if MDNSRESPONDER_SUPPORTS(APPLE, AUDIT_TOKEN)
34 #include <bsm/libbsm.h>
35 #endif
36 
37 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
38 #include "dnssd_analytics.h"
39 #endif
40 
41 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
42 #include "QuerierSupport.h"
43 #endif
44 
45 // Disable certain benign warnings with Microsoft compilers
46 #if (defined(_MSC_VER))
47 // Disable "conditional expression is constant" warning for debug macros.
48 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
49 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
50     #pragma warning(disable:4127)
51 
52 // Disable "assignment within conditional expression".
53 // Other compilers understand the convention that if you place the assignment expression within an extra pair
54 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
55 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
56 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
57     #pragma warning(disable:4706)
58 #endif
59 
60 #include "dns_sd.h" // for kDNSServiceFlags* definitions
61 #include "dns_sd_internal.h"
62 
63 #if APPLE_OSX_mDNSResponder
64 // Delay in seconds before disabling multicast after there are no active queries or registrations.
65 #define BONJOUR_DISABLE_DELAY 60
66 #endif
67 
68 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
69 #include <WebFilterDNS/WebFilterDNS.h>
70 
71 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
72 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
73 #endif
74 
75 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
76 #include "Metrics.h"
77 #endif
78 
79 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
80 #include "DNS64.h"
81 #endif
82 
83 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
84 #include "dnssec_v2.h"
85 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
86 
87 // Forward declarations
88 mDNSlocal void BeginSleepProcessing(mDNS *const m);
89 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
90 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly);
91 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
92 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
93 #endif
94 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q);
95 mDNSlocal void mDNS_SendKeepalives(mDNS *const m);
96 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth,
97                                          mDNSu32 *seq, mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win);
98 
99 typedef mDNSu32 DeadvertiseFlags;
100 #define kDeadvertiseFlag_NormalHostname (1U << 0)
101 #define kDeadvertiseFlag_RandHostname   (1U << 1)
102 #define kDeadvertiseFlag_All            (kDeadvertiseFlag_NormalHostname | kDeadvertiseFlag_RandHostname)
103 
104 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags);
105 mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set);
106 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth);
107 
108 // ***************************************************************************
109 #if COMPILER_LIKES_PRAGMA_MARK
110 #pragma mark - Program Constants
111 #endif
112 
113 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
114 #define MDNS_TRACER 1
115 
116 // Any records bigger than this are considered 'large' records
117 #define SmallRecordLimit 1024
118 
119 #define kMaxUpdateCredits 10
120 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
121 
122 // define special NR_AnswerTo values
123 #define NR_AnswerMulticast  (mDNSu8*)~0
124 #define NR_AnswerUnicast    (mDNSu8*)~1
125 
126 // Question default timeout values
127 #define DEFAULT_MCAST_TIMEOUT       5
128 #define DEFAULT_LO_OR_P2P_TIMEOUT   5
129 
130 // The code (see SendQueries() and BuildQuestion()) needs to have the
131 // RequestUnicast value set to a value one greater than the number of times you want the query
132 // sent with the "request unicast response" (QU) bit set.
133 #define SET_QU_IN_FIRST_QUERY   2
134 #define kDefaultRequestUnicastCount SET_QU_IN_FIRST_QUERY
135 
136 // The time needed to offload records to a sleep proxy after powerd sends the kIOMessageSystemWillSleep notification
137 #define DARK_WAKE_DELAY_SLEEP  5
138 #define kDarkWakeDelaySleep    (mDNSPlatformOneSecond * DARK_WAKE_DELAY_SLEEP)
139 
140 // The maximum number of times we delay probing to prevent spurious conflicts due to stale packets
141 #define MAX_CONFLICT_PROCESSING_DELAYS 3
142 
143 // RFC 6762 defines Passive Observation Of Failures (POOF)
144 //
145 //    A host observes the multicast queries issued by the other hosts on
146 //    the network.  One of the major benefits of also sending responses
147 //    using multicast is that it allows all hosts to see the responses
148 //    (or lack thereof) to those queries.
149 //
150 //    If a host sees queries, for which a record in its cache would be
151 //    expected to be given as an answer in a multicast response, but no
152 //    such answer is seen, then the host may take this as an indication
153 //    that the record may no longer be valid.
154 //
155 //    After seeing two or more of these queries, and seeing no multicast
156 //    response containing the expected answer within ten seconds, then even
157 //    though its TTL may indicate that it is not yet due to expire, that
158 //    record SHOULD be flushed from the cache.
159 //
160 // <https://tools.ietf.org/html/rfc6762#section-10.5>
161 
162 #define POOF_ENABLED 1
163 
164 mDNSexport const char *const mDNS_DomainTypeNames[] =
165 {
166     "b._dns-sd._udp.",      // Browse
167     "db._dns-sd._udp.",     // Default Browse
168     "lb._dns-sd._udp.",     // Automatic Browse
169     "r._dns-sd._udp.",      // Registration
170     "dr._dns-sd._udp."      // Default Registration
171 };
172 
173 #ifdef UNICAST_DISABLED
174 #define uDNS_IsActiveQuery(q, u) mDNSfalse
175 #endif
176 
177 // ***************************************************************************
178 #if COMPILER_LIKES_PRAGMA_MARK
179 #pragma mark -
180 #pragma mark - General Utility Functions
181 #endif
182 
183 #if MDNS_MALLOC_DEBUGGING
184 // When doing memory allocation debugging, this function traverses all lists in the mDNS query
185 // structures and caches and checks each entry in the list to make sure it's still good.
186 mDNSlocal void mDNS_ValidateLists(void *context)
187 {
188     mDNS *m = context;
189 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
190     mDNSu32 NumAllInterfaceRecords   = 0;
191     mDNSu32 NumAllInterfaceQuestions = 0;
192 #endif
193 
194     // Check core mDNS lists
195     AuthRecord                  *rr;
196     for (rr = m->ResourceRecords; rr; rr=rr->next)
197     {
198         if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
199             LogMemCorruption("ResourceRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
200         if (rr->resrec.name != &rr->namestorage)
201             LogMemCorruption("ResourceRecords list: %p name %p does not point to namestorage %p %##s",
202                              rr, rr->resrec.name->c, rr->namestorage.c, rr->namestorage.c);
203 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
204         if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
205 #endif
206     }
207 
208     for (rr = m->DuplicateRecords; rr; rr=rr->next)
209     {
210         if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
211             LogMemCorruption("DuplicateRecords list: %p is garbage (%X)", rr, rr->resrec.RecordType);
212 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
213         if (!AuthRecord_uDNS(rr) && !RRLocalOnly(rr)) NumAllInterfaceRecords++;
214 #endif
215     }
216 
217     rr = m->NewLocalRecords;
218     if (rr)
219         if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
220             LogMemCorruption("NewLocalRecords: %p is garbage (%X)", rr, rr->resrec.RecordType);
221 
222     rr = m->CurrentRecord;
223     if (rr)
224         if (rr->next == (AuthRecord *)~0 || rr->resrec.RecordType == 0 || rr->resrec.RecordType == 0xFF)
225             LogMemCorruption("CurrentRecord: %p is garbage (%X)", rr, rr->resrec.RecordType);
226 
227     DNSQuestion                 *q;
228     for (q = m->Questions; q; q=q->next)
229     {
230         if (q->next == (DNSQuestion*)~0 || q->ThisQInterval == (mDNSs32) ~0)
231             LogMemCorruption("Questions list: %p is garbage (%lX %p)", q, q->ThisQInterval, q->next);
232         if (q->DuplicateOf && q->LocalSocket)
233             LogMemCorruption("Questions list: Duplicate Question %p should not have LocalSocket set %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
234 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
235         if (!LocalOnlyOrP2PInterface(q->InterfaceID) && mDNSOpaque16IsZero(q->TargetQID))
236             NumAllInterfaceQuestions++;
237 #endif
238     }
239 
240     CacheGroup                  *cg;
241     CacheRecord                 *cr;
242     mDNSu32 slot;
243     FORALL_CACHERECORDS(slot, cg, cr)
244     {
245         if (cr->resrec.RecordType == 0 || cr->resrec.RecordType == 0xFF)
246             LogMemCorruption("Cache slot %lu: %p is garbage (%X)", slot, cr, cr->resrec.RecordType);
247         if (cr->CRActiveQuestion)
248         {
249             for (q = m->Questions; q; q=q->next) if (q == cr->CRActiveQuestion) break;
250             if (!q) LogMemCorruption("Cache slot %lu: CRActiveQuestion %p not in m->Questions list %s", slot, cr->CRActiveQuestion, CRDisplayString(m, cr));
251         }
252     }
253 
254 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
255     if (m->NumAllInterfaceRecords != NumAllInterfaceRecords)
256     	LogMemCorruption("NumAllInterfaceRecords is %d should be %d", m->NumAllInterfaceRecords, NumAllInterfaceRecords);
257 
258     if (m->NumAllInterfaceQuestions != NumAllInterfaceQuestions)
259     	LogMemCorruption("NumAllInterfaceQuestions is %d should be %d", m->NumAllInterfaceQuestions, NumAllInterfaceQuestions);
260 #endif // MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
261 }
262 #endif // MDNS_MALLOC_DEBUGGING
263 
264 // Returns true if this is a  unique, authoritative LocalOnly record that answers questions of type
265 // A, AAAA , CNAME, or PTR.  The caller should answer the question with this record and not send out
266 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
267 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
268 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
269                                         (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
270                                         ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
271                                          (rr)->resrec.rrtype == kDNSType_CNAME || \
272                                          (rr)->resrec.rrtype == kDNSType_PTR))
273 
274 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
275 {
276     mDNS_CheckLock(m);
277 
278     if (m->NextScheduledStopTime - q->StopTime > 0)
279         m->NextScheduledStopTime = q->StopTime;
280 }
281 
282 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
283 {
284     mDNS_CheckLock(m);
285 
286     if (ActiveQuestion(q))
287     {
288         // Depending on whether this is a multicast or unicast question we want to set either:
289         // m->NextScheduledQuery = NextQSendTime(q) or
290         // m->NextuDNSEvent      = NextQSendTime(q)
291         mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
292         if (*timer - NextQSendTime(q) > 0)
293             *timer = NextQSendTime(q);
294     }
295 }
296 
297 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
298 {
299 #if MDNS_MALLOC_DEBUGGING >= 1
300     unsigned int i;
301     for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
302 #endif
303     e->next = r->rrauth_free;
304     r->rrauth_free = e;
305     r->rrauth_totalused--;
306 }
307 
308 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
309 {
310     AuthEntity *e = (AuthEntity *)(*cp);
311     LogMsg("ReleaseAuthGroup:  Releasing AuthGroup %##s", (*cp)->name->c);
312     if ((*cp)->rrauth_tail != &(*cp)->members)
313         LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
314     if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
315     (*cp)->name = mDNSNULL;
316     *cp = (*cp)->next;          // Cut record from list
317     ReleaseAuthEntity(r, e);
318 }
319 
320 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
321 {
322     AuthEntity *e = mDNSNULL;
323 
324     if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
325     r->rrauth_lock = 1;
326 
327     if (!r->rrauth_free)
328     {
329         // We allocate just one AuthEntity at a time because we need to be able
330         // free them all individually which normally happens when we parse /etc/hosts into
331         // AuthHash where we add the "new" entries and discard (free) the already added
332         // entries. If we allocate as chunks, we can't free them individually.
333         AuthEntity *storage = (AuthEntity *) mDNSPlatformMemAllocateClear(sizeof(*storage));
334         storage->next = mDNSNULL;
335         r->rrauth_free = storage;
336     }
337 
338     // If we still have no free records, recycle all the records we can.
339     // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
340     if (!r->rrauth_free)
341     {
342         mDNSu32 oldtotalused = r->rrauth_totalused;
343         mDNSu32 slot;
344         for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
345         {
346             AuthGroup **cp = &r->rrauth_hash[slot];
347             while (*cp)
348             {
349                 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
350                 else ReleaseAuthGroup(r, cp);
351             }
352         }
353         LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
354                 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
355     }
356 
357     if (r->rrauth_free) // If there are records in the free list, take one
358     {
359         e = r->rrauth_free;
360         r->rrauth_free = e->next;
361         if (++r->rrauth_totalused >= r->rrauth_report)
362         {
363             LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
364             if      (r->rrauth_report <  100) r->rrauth_report += 10;
365             else if (r->rrauth_report < 1000) r->rrauth_report += 100;
366             else r->rrauth_report += 1000;
367         }
368         mDNSPlatformMemZero(e, sizeof(*e));
369     }
370 
371     r->rrauth_lock = 0;
372 
373     return(e);
374 }
375 
376 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 namehash, const domainname *const name)
377 {
378     AuthGroup *ag;
379     const mDNSu32 slot = namehash % AUTH_HASH_SLOTS;
380 
381     for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
382         if (ag->namehash == namehash && SameDomainName(ag->name, name))
383             break;
384     return(ag);
385 }
386 
387 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const ResourceRecord *const rr)
388 {
389     return(AuthGroupForName(r, rr->namehash, rr->name));
390 }
391 
392 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const ResourceRecord *const rr)
393 {
394     mDNSu16 namelen = DomainNameLength(rr->name);
395     AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
396     const mDNSu32 slot = rr->namehash % AUTH_HASH_SLOTS;
397     if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
398     ag->next         = r->rrauth_hash[slot];
399     ag->namehash     = rr->namehash;
400     ag->members      = mDNSNULL;
401     ag->rrauth_tail  = &ag->members;
402     ag->NewLocalOnlyRecords = mDNSNULL;
403     if (namelen > sizeof(ag->namestorage))
404         ag->name = (domainname *) mDNSPlatformMemAllocate(namelen);
405     else
406         ag->name = (domainname*)ag->namestorage;
407     if (!ag->name)
408     {
409         LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
410         ReleaseAuthEntity(r, (AuthEntity*)ag);
411         return(mDNSNULL);
412     }
413     AssignDomainName(ag->name, rr->name);
414 
415     if (AuthGroupForRecord(r, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
416     r->rrauth_hash[slot] = ag;
417     if (AuthGroupForRecord(r, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
418 
419     return(ag);
420 }
421 
422 // Returns the AuthGroup in which the AuthRecord was inserted
423 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
424 {
425     AuthGroup *ag;
426 
427     (void)m;
428     ag = AuthGroupForRecord(r, &rr->resrec);
429     if (!ag) ag = GetAuthGroup(r, &rr->resrec);   // If we don't have a AuthGroup for this name, make one now
430     if (ag)
431     {
432         *(ag->rrauth_tail) = rr;                // Append this record to tail of cache slot list
433         ag->rrauth_tail = &(rr->next);          // Advance tail pointer
434     }
435     return ag;
436 }
437 
438 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
439 {
440     AuthGroup *a;
441     AuthRecord **rp;
442 
443     a = AuthGroupForRecord(r, &rr->resrec);
444     if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
445     rp = &a->members;
446     while (*rp)
447     {
448         if (*rp != rr)
449             rp=&(*rp)->next;
450         else
451         {
452             // We don't break here, so that we can set the tail below without tracking "prev" pointers
453 
454             LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
455             *rp = (*rp)->next;          // Cut record from list
456         }
457     }
458     // TBD: If there are no more members, release authgroup ?
459     a->rrauth_tail = rp;
460     return a;
461 }
462 
463 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 namehash, const domainname *const name)
464 {
465     CacheGroup *cg;
466     mDNSu32    slot = HashSlotFromNameHash(namehash);
467     for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
468         if (cg->namehash == namehash && SameDomainName(cg->name, name))
469             break;
470     return(cg);
471 }
472 
473 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const ResourceRecord *const rr)
474 {
475     return(CacheGroupForName(m, rr->namehash, rr->name));
476 }
477 
478 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
479 {
480     NetworkInterfaceInfo *intf;
481 
482     if (addr->type == mDNSAddrType_IPv4)
483     {
484         // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
485         if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
486         for (intf = m->HostInterfaces; intf; intf = intf->next)
487             if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
488                 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
489                     return(mDNStrue);
490     }
491 
492     if (addr->type == mDNSAddrType_IPv6)
493     {
494         if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue);
495         for (intf = m->HostInterfaces; intf; intf = intf->next)
496             if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
497                 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
498                     (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
499                     (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
500                     (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
501                         return(mDNStrue);
502     }
503 
504     return(mDNSfalse);
505 }
506 
507 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
508 {
509     NetworkInterfaceInfo *intf = m->HostInterfaces;
510     while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
511     return(intf);
512 }
513 
514 mDNSlocal NetworkInterfaceInfo *FirstIPv4LLInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
515 {
516     NetworkInterfaceInfo *intf;
517 
518     if (!InterfaceID)
519         return mDNSNULL;
520 
521     // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
522     // we still want to find the first IPv4 Link-Local interface
523     for (intf = m->HostInterfaces; intf; intf = intf->next)
524     {
525         if (intf->InterfaceID == InterfaceID &&
526             intf->ip.type == mDNSAddrType_IPv4 && mDNSv4AddressIsLinkLocal(&intf->ip.ip.v4))
527         {
528             debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf->ip.ip.v4);
529             return intf;
530         }
531     }
532     return (mDNSNULL);
533 }
534 
535 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
536 {
537     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
538     return(intf ? intf->ifname : mDNSNULL);
539 }
540 
541 // Caller should hold the lock
542 mDNSlocal void GenerateNegativeResponseEx(mDNS *const m, mDNSInterfaceID InterfaceID, QC_result qc, mDNSBool noData)
543 {
544     DNSQuestion *q;
545     if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
546     q = m->CurrentQuestion;
547     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
548            "[R%d->Q%d] GenerateNegativeResponse: Generating negative response for question " PRI_DM_NAME " (" PUB_S ")",
549            q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
550 
551     MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, InterfaceID, mDNSNULL);
552     m->rec.r.resrec.negativeRecordType = noData ? kNegativeRecordType_NoData : kNegativeRecordType_Unspecified;
553 
554     // We need to force the response through in the following cases
555     //
556     //  a) SuppressUnusable questions that are suppressed
557     //  b) Append search domains and retry the question
558     //
559     // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
560     // through we use "QC_forceresponse".
561     AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc);
562     if (m->CurrentQuestion == q) { q->ThisQInterval = 0; }              // Deactivate this question
563     // Don't touch the question after this
564     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
565 }
566 #define GenerateNegativeResponse(M, INTERFACE_ID, QC) GenerateNegativeResponseEx(M, INTERFACE_ID, QC, mDNSfalse)
567 
568 mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
569 {
570     const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
571     if (q->CNAMEReferrals >= 10 || selfref)
572     {
573         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
574                "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME " (" PUB_S ")  NOT following CNAME referral %d" PUB_S " for " PRI_S,
575                q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype),
576                q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
577 
578     }
579     else
580     {
581         UDPSocket *sock = q->LocalSocket;
582         mDNSOpaque16 id = q->TargetQID;
583 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
584         uDNSMetrics metrics;
585 #endif
586 
587         q->LocalSocket = mDNSNULL;
588 
589         // The SameDomainName check above is to ignore bogus CNAME records that point right back at
590         // themselves. Without that check we can get into a case where we have two duplicate questions,
591         // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
592         // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
593         // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
594         // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
595         // for either of them. This is not a problem for CNAME loops of two or more records because in
596         // those cases the newly re-appended question A has a different target name and therefore cannot be
597         // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
598 
599         // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
600         // and track CNAMEs coming and going, we should really create a subordinate query here,
601         // which we would subsequently cancel and retract if the CNAME referral record were removed.
602         // In reality this is such a corner case we'll ignore it until someone actually needs it.
603 
604         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
605                "[R%d->Q%d] AnswerQuestionByFollowingCNAME: %p " PRI_DM_NAME " (" PUB_S ") following CNAME referral %d for " PRI_S,
606                q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype),
607                q->CNAMEReferrals, RRDisplayString(m, rr));
608 
609 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
610         if (!mDNSOpaque16IsZero(q->TargetQID))
611         {
612             // Must be called before zeroing out q->metrics below.
613             Querier_PrepareQuestionForCNAMERestart(q);
614         }
615 #endif
616 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
617         if ((q->CNAMEReferrals == 0) && !q->metrics.originalQName)
618         {
619             domainname *    qName;
620             mDNSu16         qNameLen;
621 
622             qNameLen = DomainNameLength(&q->qname);
623             if ((qNameLen > 0) && (qNameLen <= MAX_DOMAIN_NAME))
624             {
625                 qName = (domainname *) mDNSPlatformMemAllocate(qNameLen);
626                 if (qName)
627                 {
628                     mDNSPlatformMemCopy(qName->c, q->qname.c, qNameLen);
629                     q->metrics.originalQName = qName;
630                 }
631             }
632         }
633         metrics = q->metrics;
634         // The metrics will be transplanted to the restarted question, so zero out the old copy instead of using
635         // uDNSMetricsClear(), which will free any pointers to allocated memory.
636         mDNSPlatformMemZero(&q->metrics, sizeof(q->metrics));
637 #endif
638         mDNS_StopQuery_internal(m, q);                              // Stop old query
639         AssignDomainName(&q->qname, &rr->rdata->u.name);            // Update qname
640         q->qnamehash = DomainNameHashValue(&q->qname);              // and namehash
641         // If a unicast query results in a CNAME that points to a .local, we need to re-try
642         // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
643         // to try this as unicast query even though it is a .local name
644         if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
645         {
646             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
647                    "[R%d->Q%d] AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p " PRI_DM_NAME " (" PUB_S ") Record " PRI_S,
648                    q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), RRDisplayString(m, rr));
649             q->IsUnicastDotLocal = mDNStrue;
650         }
651         q->CNAMEReferrals += 1;                                     // Increment value before calling mDNS_StartQuery_internal
652         const mDNSu32 c = q->CNAMEReferrals;                        // Stash a copy of the new q->CNAMEReferrals value
653         mDNS_StartQuery_internal(m, q);                             // start new query
654         // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
655         // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
656         q->CNAMEReferrals = c;
657 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
658         metrics.expiredAnswerState  = q->metrics.expiredAnswerState; //  We want the newly initialized state for this value
659         metrics.dnsOverTCPState     = q->metrics.dnsOverTCPState;    //  We want the newly initialized state for this value
660         q->metrics = metrics;
661 #endif
662         if (sock)
663         {
664             // 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.
665             if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
666             else
667             {
668                 // Transplant the old socket into the new question, and copy the query ID across too.
669                 // No need to close the old q->LocalSocket value because it won't have been created yet (they're made lazily on-demand).
670                 q->LocalSocket = sock;
671                 q->TargetQID = id;
672             }
673         }
674     }
675 }
676 
677 #ifdef USE_LIBIDN
678 
679 #include <unicode/uidna.h>
680 
681 // #define DEBUG_PUNYCODE 1
682 
683 mDNSlocal mDNSu8 *PunycodeConvert(const mDNSu8 *const src, mDNSu8 *const dst, const mDNSu8 *const end)
684 {
685     UErrorCode errorCode = U_ZERO_ERROR;
686     UIDNAInfo info = UIDNA_INFO_INITIALIZER;
687     UIDNA *uts46 = uidna_openUTS46(UIDNA_USE_STD3_RULES|UIDNA_NONTRANSITIONAL_TO_UNICODE, &errorCode);
688     int32_t len = uidna_nameToASCII_UTF8(uts46, (const char *)src+1, src[0], (char *)dst+1, (int32_t)(end-(dst+1)), &info, &errorCode);
689     uidna_close(uts46);
690     #if DEBUG_PUNYCODE
691     if (errorCode) LogMsg("uidna_nameToASCII_UTF8(%##s) failed errorCode %d", src, errorCode);
692     if (info.errors) LogMsg("uidna_nameToASCII_UTF8(%##s) failed info.errors 0x%08X", src, info.errors);
693     if (len > MAX_DOMAIN_LABEL) LogMsg("uidna_nameToASCII_UTF8(%##s) result too long %d", src, len);
694     #endif
695     if (errorCode || info.errors || len > MAX_DOMAIN_LABEL) return mDNSNULL;
696     *dst = len;
697     return(dst + 1 + len);
698 }
699 
700 mDNSlocal mDNSBool IsHighASCIILabel(const mDNSu8 *d)
701 {
702     int i;
703     for (i=1; i<=d[0]; i++) if (d[i] & 0x80) return mDNStrue;
704     return mDNSfalse;
705 }
706 
707 mDNSlocal const mDNSu8 *FindLastHighASCIILabel(const domainname *const d)
708 {
709     const mDNSu8 *ptr = d->c;
710     const mDNSu8 *ans = mDNSNULL;
711     while (ptr[0])
712     {
713         const mDNSu8 *const next = ptr + 1 + ptr[0];
714         if (ptr[0] > MAX_DOMAIN_LABEL || next >= d->c + MAX_DOMAIN_NAME) return mDNSNULL;
715         if (IsHighASCIILabel(ptr)) ans = ptr;
716         ptr = next;
717     }
718     return ans;
719 }
720 
721 mDNSlocal mDNSBool PerformNextPunycodeConversion(const DNSQuestion *const q, domainname *const newname)
722 {
723     const mDNSu8 *h = FindLastHighASCIILabel(&q->qname);
724     #if DEBUG_PUNYCODE
725     LogMsg("PerformNextPunycodeConversion: %##s (%s) Last High-ASCII Label %##s", q->qname.c, DNSTypeName(q->qtype), h);
726     #endif
727     if (!h) return mDNSfalse;  // There are no high-ascii labels to convert
728 
729     mDNSu8 *const dst = PunycodeConvert(h, newname->c + (h - q->qname.c), newname->c + MAX_DOMAIN_NAME);
730     if (!dst)
731         return mDNSfalse;  // The label was not convertible to Punycode
732     else
733     {
734         // If Punycode conversion of final eligible label was successful, copy the rest of the domainname
735         const mDNSu8 *const src = h + 1 + h[0];
736         const mDNSu8 remainder  = DomainNameLength((domainname*)src);
737         if (dst + remainder > newname->c + MAX_DOMAIN_NAME) return mDNSfalse;  // Name too long -- cannot be converted to Punycode
738 
739         mDNSPlatformMemCopy(newname->c, q->qname.c, (mDNSu32)(h - q->qname.c));  // Fill in the leading part
740         mDNSPlatformMemCopy(dst, src, remainder);                     // Fill in the trailing part
741         #if DEBUG_PUNYCODE
742         LogMsg("PerformNextPunycodeConversion: %##s converted to %##s", q->qname.c, newname->c);
743         #endif
744         return mDNStrue;
745     }
746 }
747 
748 #endif // USE_LIBIDN
749 
750 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
751 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
752 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
753 {
754     DNSQuestion *q = m->CurrentQuestion;
755     mDNSBool followcname;
756 
757     if (!q)
758     {
759         LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
760         return;
761     }
762 
763     followcname = FollowCNAME(q, &rr->resrec, AddRecord);
764 
765     // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
766     if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
767     {
768         LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
769                AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
770         return;
771     }
772 
773     // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
774     if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
775     mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
776     if (q->QuestionCallback && !q->NoAnswer)
777     {
778         q->CurrentAnswers += AddRecord ? 1 : -1;
779         if (UniqueLocalOnlyRecord(rr))
780         {
781             if (!followcname || q->ReturnIntermed)
782             {
783                 // Don't send this packet on the wire as we answered from /etc/hosts
784                 q->ThisQInterval = 0;
785                 q->LOAddressAnswers += AddRecord ? 1 : -1;
786                 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
787             }
788             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
789             // The callback above could have caused the question to stop. Detect that
790             // using m->CurrentQuestion
791             if (followcname && m->CurrentQuestion == q)
792                 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
793             return;
794         }
795         else
796         {
797             q->QuestionCallback(m, q, &rr->resrec, AddRecord);
798         }
799     }
800     mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
801 }
802 
803 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord)
804 {
805     if (m->CurrentQuestion)
806         LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
807                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
808     m->CurrentQuestion = m->Questions;
809     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
810     {
811         mDNSBool answered;
812         DNSQuestion *q = m->CurrentQuestion;
813         if (RRAny(ar))
814             answered = AuthRecordAnswersQuestion(ar, q);
815         else
816             answered = LocalOnlyRecordAnswersQuestion(ar, q);
817         if (answered)
818             AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord);       // MUST NOT dereference q again
819         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
820             m->CurrentQuestion = q->next;
821     }
822     m->CurrentQuestion = mDNSNULL;
823 }
824 
825 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
826 // delivers the appropriate add/remove events to listening questions:
827 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
828 //    stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
829 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
830 //    our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
831 //    stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
832 //
833 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
834 // and by mDNS_Deregister_internal()
835 
836 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *ar, QC_result AddRecord)
837 {
838     if (m->CurrentQuestion)
839         LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
840                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
841 
842     m->CurrentQuestion = m->LocalOnlyQuestions;
843     while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
844     {
845         mDNSBool answered;
846         DNSQuestion *q = m->CurrentQuestion;
847         // We are called with both LocalOnly/P2P record or a regular AuthRecord
848         if (RRAny(ar))
849             answered = AuthRecordAnswersQuestion(ar, q);
850         else
851             answered = LocalOnlyRecordAnswersQuestion(ar, q);
852         if (answered)
853             AnswerLocalQuestionWithLocalAuthRecord(m, ar, AddRecord);           // MUST NOT dereference q again
854         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
855             m->CurrentQuestion = q->next;
856     }
857 
858     m->CurrentQuestion = mDNSNULL;
859 
860     // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
861     if (ar->ARType == AuthRecordLocalOnly || ar->ARType == AuthRecordP2P)
862         AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, ar, AddRecord);
863 
864 }
865 
866 // ***************************************************************************
867 #if COMPILER_LIKES_PRAGMA_MARK
868 #pragma mark -
869 #pragma mark - Resource Record Utility Functions
870 #endif
871 
872 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
873 
874 mDNSlocal mDNSBool ResourceRecordIsValidAnswer(const AuthRecord *const rr)
875 {
876     if ((rr->resrec.RecordType & kDNSRecordTypeActiveMask) &&
877         ((rr->Additional1 == mDNSNULL) || (rr->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) &&
878         ((rr->Additional2 == mDNSNULL) || (rr->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) &&
879         ((rr->DependentOn == mDNSNULL) || (rr->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask)))
880     {
881         return mDNStrue;
882     }
883     else
884     {
885         return mDNSfalse;
886     }
887 }
888 
889 mDNSlocal mDNSBool IsInterfaceValidForAuthRecord(const AuthRecord *const rr, const mDNSInterfaceID InterfaceID)
890 {
891     if (rr->resrec.InterfaceID == mDNSInterface_Any)
892     {
893         return mDNSPlatformValidRecordForInterface(rr, InterfaceID);
894     }
895     else
896     {
897         return ((rr->resrec.InterfaceID == InterfaceID) ? mDNStrue : mDNSfalse);
898     }
899 }
900 
901 mDNSlocal mDNSBool ResourceRecordIsValidInterfaceAnswer(const AuthRecord *const rr, const mDNSInterfaceID interfaceID)
902 {
903     return ((IsInterfaceValidForAuthRecord(rr, interfaceID) && ResourceRecordIsValidAnswer(rr)) ? mDNStrue : mDNSfalse);
904 }
905 
906 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
907 #define DefaultProbeCountForRecordType(X)      ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
908 
909 // Parameters for handling probing conflicts
910 #define kMaxAllowedMCastProbingConflicts 1                     // Maximum number of conflicts to allow from mcast messages.
911 #define kProbingConflictPauseDuration    mDNSPlatformOneSecond // Duration of probing pause after an allowed mcast conflict.
912 
913 // See RFC 6762: "8.3 Announcing"
914 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
915 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
916 #define InitialAnnounceCount ((mDNSu8)4)
917 
918 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
919 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
920 // and then if the machine fails to wake, 3 goodbye packets).
921 #define GoodbyeCount ((mDNSu8)3)
922 #define WakeupCount ((mDNSu8)18)
923 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
924 #define MAX_GHOST_TIME ((mDNSs32)((60*60*24*7)*mDNSPlatformOneSecond))  //  One week
925 
926 // Number of wakeups we send if WakeOnResolve is set in the question
927 #define InitialWakeOnResolveCount ((mDNSu8)3)
928 
929 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
930 // This means that because the announce interval is doubled after sending the first packet, the first
931 // observed on-the-wire inter-packet interval between announcements is actually one second.
932 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
933 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
934 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
935 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
936 
937 #define DefaultAPIntervalForRecordType(X)  ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
938                                             (X) &kDNSRecordTypeUnique           ? DefaultProbeIntervalForTypeUnique    : \
939                                             (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
940 
941 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
942 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
943 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
944 
945 // Adjustment factor to avoid race condition (used for unicast cache entries) :
946 // Suppose real record has TTL of 3600, and our local caching server has held it for 3500 seconds, so it returns an aged TTL of 100.
947 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
948 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
949 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
950 // We adjust the 100 second TTL to 127. This means that when we do our 80% query after 102 seconds,
951 // the cached copy at our local caching server will already have expired, so the server will be forced
952 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
953 
954 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
955 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
956 
957 #define MaxUnansweredQueries 4
958 
959 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
960 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
961 // TTL and rdata may differ.
962 // This is used for cache flush management:
963 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
964 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
965 
966 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
967 
968 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
969 
970 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
971 {
972     if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
973     if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
974     if (r1->resrec.InterfaceID &&
975         r2->resrec.InterfaceID &&
976         r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
977     return (mDNSBool)(
978                r1->resrec.rrclass  == r2->resrec.rrclass &&
979                r1->resrec.namehash == r2->resrec.namehash &&
980                SameDomainName(r1->resrec.name, r2->resrec.name));
981 }
982 
983 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
984 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
985 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
986 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
987 // so a response of any type should match, even if it is not actually the type the client plans to use.
988 
989 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
990 // and require the rrtypes to match for the rdata to be considered potentially conflicting
991 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
992 {
993     if (!pktrr)  { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
994     if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
995     if (pktrr->resrec.InterfaceID &&
996         authrr->resrec.InterfaceID &&
997         pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
998     if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
999         if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
1000     if ((authrr->resrec.InterfaceID == mDNSInterface_Any) &&
1001         !mDNSPlatformValidRecordForInterface(authrr, pktrr->resrec.InterfaceID)) return(mDNSfalse);
1002     return (mDNSBool)(
1003                pktrr->resrec.rrclass == authrr->resrec.rrclass &&
1004                pktrr->resrec.namehash == authrr->resrec.namehash &&
1005                SameDomainName(pktrr->resrec.name, authrr->resrec.name));
1006 }
1007 
1008 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
1009 // This is the information that the requester believes to be correct.
1010 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
1011 // This is the information that we believe to be correct.
1012 // We've already determined that we plan to give this answer on this interface
1013 // (either the record is non-specific, or it is specific to this interface)
1014 // so now we just need to check the name, type, class, rdata and TTL.
1015 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
1016 {
1017     // If RR signature is different, or data is different, then don't suppress our answer
1018     if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
1019 
1020     // If the requester's indicated TTL is less than half the real TTL,
1021     // we need to give our answer before the requester's copy expires.
1022     // If the requester's indicated TTL is at least half the real TTL,
1023     // then we can suppress our answer this time.
1024     // If the requester's indicated TTL is greater than the TTL we believe,
1025     // then that's okay, and we don't need to do anything about it.
1026     // (If two responders on the network are offering the same information,
1027     // that's okay, and if they are offering the information with different TTLs,
1028     // the one offering the lower TTL should defer to the one offering the higher TTL.)
1029     return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
1030 }
1031 
1032 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
1033 {
1034     if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1035     {
1036         if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
1037         {
1038             LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
1039             LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
1040         }
1041         if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1042             m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
1043         // Some defensive code:
1044         // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
1045         // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
1046         // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
1047         if (m->NextScheduledProbe - m->timenow < 0)
1048             m->NextScheduledProbe = m->timenow;
1049     }
1050     else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
1051     {
1052         if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1053             m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
1054     }
1055 }
1056 
1057 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
1058 {
1059     // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
1060     rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
1061 
1062     // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
1063     // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
1064     //   records that are going to probe, then we delay its first announcement so that it will
1065     //   go out synchronized with the first announcement for the other records that *are* probing.
1066     //   This is a minor performance tweak that helps keep groups of related records synchronized together.
1067     //   The addition of "interval / 2" is to make sure that, in the event that any of the probes are
1068     //   delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
1069     //   When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
1070     //   because they will meet the criterion of being at least half-way to their scheduled announcement time.
1071     // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
1072 
1073     if (rr->ProbeCount)
1074     {
1075         rr->ProbingConflictCount = 0;
1076         // If we have no probe suppression time set, or it is in the past, set it now
1077         if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
1078         {
1079             // To allow us to aggregate probes when a group of services are registered together,
1080             // the first probe is delayed by a random delay in the range 1/8 to 1/4 second.
1081             // This means the common-case behaviour is:
1082             // randomized wait; probe
1083             // 1/4 second wait; probe
1084             // 1/4 second wait; probe
1085             // 1/4 second wait; announce (i.e. service is normally announced 7/8 to 1 second after being registered)
1086             m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
1087 
1088             // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
1089             if (m->SuppressProbes - m->NextScheduledProbe >= 0)
1090                 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
1091             if (m->SuppressProbes - m->timenow < 0)     // Make sure we don't set m->SuppressProbes excessively in the past
1092                 m->SuppressProbes = m->timenow;
1093 
1094             // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
1095             if (m->SuppressProbes - m->NextScheduledQuery >= 0)
1096                 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
1097             if (m->SuppressProbes - m->timenow < 0)     // Make sure we don't set m->SuppressProbes excessively in the past
1098                 m->SuppressProbes = m->timenow;
1099 
1100             // except... don't expect to be able to send before the m->SuppressSending timer fires
1101             if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
1102                 m->SuppressProbes = NonZeroTime(m->SuppressSending);
1103 
1104             if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
1105             {
1106                 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
1107                        m->SuppressProbes     - m->timenow,
1108                        m->NextScheduledProbe - m->timenow,
1109                        m->NextScheduledQuery - m->timenow,
1110                        m->SuppressSending,
1111                        m->SuppressSending    - m->timenow);
1112                 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
1113             }
1114         }
1115         rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
1116     }
1117     // Skip kDNSRecordTypeKnownUnique and kDNSRecordTypeShared records here and set their LastAPTime in the "else" block below so
1118     // that they get announced immediately, otherwise, their announcement would be delayed until the based on the SuppressProbes value.
1119     else if ((rr->resrec.RecordType != kDNSRecordTypeKnownUnique) && (rr->resrec.RecordType != kDNSRecordTypeShared) && m->SuppressProbes && (m->SuppressProbes - m->timenow >= 0))
1120         rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
1121     else
1122         rr->LastAPTime = m->timenow - rr->ThisAPInterval;
1123 
1124     // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
1125     // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
1126     // After three probes one second apart with no answer, we conclude the client is now sleeping
1127     // and we can begin broadcasting our announcements to take over ownership of that IP address.
1128     // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
1129     // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
1130     if (rr->AddressProxy.type)
1131         rr->LastAPTime = m->timenow;
1132 
1133     // Set LastMCTime to now, to inhibit multicast responses
1134     // (no need to send additional multicast responses when we're announcing anyway)
1135     rr->LastMCTime      = m->timenow;
1136     rr->LastMCInterface = mDNSInterfaceMark;
1137 
1138     SetNextAnnounceProbeTime(m, rr);
1139 }
1140 
1141 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
1142 {
1143     const domainname *target;
1144     if (rr->AutoTarget)
1145     {
1146         rr->AutoTarget = Target_AutoHostAndNATMAP;
1147     }
1148 
1149     target = GetServiceTarget(m, rr);
1150     if (!target || target->c[0] == 0)
1151     {
1152         // defer registration until we've got a target
1153         LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
1154         rr->state = regState_NoTarget;
1155         return mDNSNULL;
1156     }
1157     else
1158     {
1159         LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
1160         return target;
1161     }
1162 }
1163 
1164 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1165 mDNSlocal mDNSBool AuthRecordIncludesOrIsAWDL(const AuthRecord *const ar)
1166 {
1167     return ((AuthRecordIncludesAWDL(ar) || mDNSPlatformInterfaceIsAWDL(ar->resrec.InterfaceID)) ? mDNStrue : mDNSfalse);
1168 }
1169 #endif
1170 
1171 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
1172 // Eventually we should unify this with GetServiceTarget() in uDNS.c
1173 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
1174 {
1175     domainname *const target = GetRRDomainNameTarget(&rr->resrec);
1176     const domainname *newname;
1177 
1178 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1179     if (AuthRecordIncludesOrIsAWDL(rr))
1180     {
1181         newname = &m->RandomizedHostname;
1182     }
1183     else
1184 #endif
1185     {
1186         newname = &m->MulticastHostname;
1187     }
1188     if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
1189 
1190     if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
1191     {
1192         const domainname *const n = SetUnicastTargetToHostName(m, rr);
1193         if (n) newname = n;
1194         else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
1195     }
1196 
1197     if (target && SameDomainName(target, newname))
1198         debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
1199 
1200     if (target && !SameDomainName(target, newname))
1201     {
1202         AssignDomainName(target, newname);
1203         SetNewRData(&rr->resrec, mDNSNULL, 0);      // Update rdlength, rdestimate, rdatahash
1204 
1205         // If we're in the middle of probing this record, we need to start again,
1206         // because changing its rdata may change the outcome of the tie-breaker.
1207         // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
1208         rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1209 
1210         // If we've announced this record, we really should send a goodbye packet for the old rdata before
1211         // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
1212         // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
1213         if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
1214             debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
1215                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1216 
1217         rr->AnnounceCount  = InitialAnnounceCount;
1218         rr->RequireGoodbye = mDNSfalse;
1219         rr->ProbeRestartCount = 0;
1220         InitializeLastAPTime(m, rr);
1221     }
1222 }
1223 
1224 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
1225 {
1226     if (rr->RecordCallback)
1227     {
1228         // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1229         // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1230         rr->Acknowledged = mDNStrue;
1231         mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
1232         rr->RecordCallback(m, rr, mStatus_NoError);
1233         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
1234     }
1235 }
1236 
1237 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
1238 {
1239     // Make sure that we don't activate the SRV record and associated service records, if it is in
1240     // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
1241     // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
1242     // the target becomes available, the records will be reregistered.
1243     if (rr->resrec.rrtype != kDNSType_SRV)
1244     {
1245         AuthRecord *srvRR = mDNSNULL;
1246         if (rr->resrec.rrtype == kDNSType_PTR)
1247             srvRR = rr->Additional1;
1248         else if (rr->resrec.rrtype == kDNSType_TXT)
1249             srvRR = rr->DependentOn;
1250         if (srvRR)
1251         {
1252             if (srvRR->resrec.rrtype != kDNSType_SRV)
1253             {
1254                 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1255             }
1256             else
1257             {
1258                 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1259                         ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1260                 rr->state = srvRR->state;
1261             }
1262         }
1263     }
1264 
1265     if (rr->state == regState_NoTarget)
1266     {
1267         LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
1268         return;
1269     }
1270     // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1271     // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1272     // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1273     // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1274     // 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.
1275     if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1276     {
1277         LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
1278         rr->state = regState_DeregPending;
1279     }
1280     else
1281     {
1282         LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
1283         rr->state = regState_Pending;
1284     }
1285     rr->ProbingConflictCount = 0;
1286     rr->LastConflictPktNum   = 0;
1287     rr->ProbeRestartCount    = 0;
1288     rr->ProbeCount           = 0;
1289     rr->AnnounceCount        = 0;
1290     rr->ThisAPInterval       = INIT_RECORD_REG_INTERVAL;
1291     rr->LastAPTime           = m->timenow - rr->ThisAPInterval;
1292     rr->expire               = 0; // Forget about all the leases, start fresh
1293     rr->uselease             = mDNStrue;
1294     rr->updateid             = zeroID;
1295     rr->SRVChanged           = mDNSfalse;
1296     rr->updateError          = mStatus_NoError;
1297     // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1298     // The records might already be registered with the server and hence could have NAT state.
1299     if (rr->NATinfo.clientContext)
1300     {
1301         mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1302         rr->NATinfo.clientContext = mDNSNULL;
1303     }
1304     if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1305     if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
1306     if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1307         m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
1308 }
1309 
1310 // Two records qualify to be local duplicates if:
1311 // (a) the RecordTypes are the same, or
1312 // (b) one is Unique and the other Verified
1313 // (c) either is in the process of deregistering
1314 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1315                         ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1316                         ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1317 
1318 #define RecordIsLocalDuplicate(A,B) \
1319     ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1320 
1321 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
1322 {
1323     const AuthGroup *a;
1324     AuthRecord *rp;
1325 
1326     a = AuthGroupForRecord(r, &rr->resrec);
1327     if (!a) return mDNSNULL;
1328     rp = a->members;
1329     while (rp)
1330     {
1331         if (!RecordIsLocalDuplicate(rp, rr))
1332             rp = rp->next;
1333         else
1334         {
1335             if (rp->resrec.RecordType == kDNSRecordTypeDeregistering)
1336             {
1337                 rp->AnnounceCount = 0;
1338                 rp = rp->next;
1339             }
1340             else return rp;
1341         }
1342     }
1343     return (mDNSNULL);
1344 }
1345 
1346 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
1347 {
1348     const AuthGroup *a;
1349     const AuthRecord *rp;
1350 
1351     a = AuthGroupForRecord(r, &rr->resrec);
1352     if (!a) return mDNSfalse;
1353     rp = a->members;
1354     while (rp)
1355     {
1356         const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1357         const AuthRecord *s2 = rp->RRSet ? rp->RRSet : rp;
1358         if (s1 != s2 && SameResourceRecordSignature(rp, rr) && !IdenticalSameNameRecord(&rp->resrec, &rr->resrec))
1359             return mDNStrue;
1360         else
1361             rp = rp->next;
1362     }
1363     return (mDNSfalse);
1364 }
1365 
1366 // checks to see if "rr" is already present
1367 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1368 {
1369     const AuthGroup *a;
1370     AuthRecord *rp;
1371 
1372     a = AuthGroupForRecord(r, &rr->resrec);
1373     if (!a) return mDNSNULL;
1374     rp = a->members;
1375     while (rp)
1376     {
1377         if (rp != rr)
1378             rp = rp->next;
1379         else
1380         {
1381             return rp;
1382         }
1383     }
1384     return (mDNSNULL);
1385 }
1386 
1387 mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1388 {
1389     if (RRLocalOnly(rr))
1390     {
1391         // A sanity check, this should be prevented in calling code.
1392         LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1393         return;
1394     }
1395 
1396     if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost))
1397     {
1398         NetworkInterfaceInfo *intf;
1399 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1400         DeadvertiseFlags flags     = 0; // DeadvertiseFlags for non-AWDL interfaces.
1401         DeadvertiseFlags flagsAWDL = 0; // DeadvertiseFlags for AWDL interfaces.
1402         if (AuthRecordIncludesOrIsAWDL(rr))
1403         {
1404             if (AuthRecordIncludesAWDL(rr))
1405             {
1406                 m->AutoTargetAWDLIncludedCount--;
1407                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1408                     "DecrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S,
1409                     m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr));
1410                 if (m->AutoTargetAWDLIncludedCount == 0)
1411                 {
1412                     flags |= kDeadvertiseFlag_RandHostname;
1413                     if (m->AutoTargetAWDLOnlyCount == 0) flagsAWDL |= kDeadvertiseFlag_RandHostname;
1414                 }
1415             }
1416             else
1417             {
1418                 m->AutoTargetAWDLOnlyCount--;
1419                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1420                     "DecrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S,
1421                     m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr));
1422                 if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0))
1423                 {
1424                     flagsAWDL |= kDeadvertiseFlag_RandHostname;
1425                 }
1426             }
1427             if (flags || flagsAWDL)
1428             {
1429                 for (intf = m->HostInterfaces; intf; intf = intf->next)
1430                 {
1431                     if (!intf->Advertise) continue;
1432                     if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID))
1433                     {
1434                         if (flagsAWDL) DeadvertiseInterface(m, intf, flagsAWDL);
1435                     }
1436                     else
1437                     {
1438                         if (flags) DeadvertiseInterface(m, intf, flags);
1439                     }
1440                 }
1441             }
1442             if ((m->AutoTargetAWDLIncludedCount == 0) && (m->AutoTargetAWDLOnlyCount == 0))
1443             {
1444                 GetRandomUUIDLocalHostname(&m->RandomizedHostname);
1445             }
1446         }
1447         else
1448 #endif
1449         {
1450             m->AutoTargetServices--;
1451             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1452                 "DecrementAutoTargetServices: AutoTargetServices %u Record " PRI_S,
1453                 m->AutoTargetServices, ARDisplayString(m, rr));
1454             if (m->AutoTargetServices == 0)
1455             {
1456                 for (intf = m->HostInterfaces; intf; intf = intf->next)
1457                 {
1458                     if (intf->Advertise) DeadvertiseInterface(m, intf, kDeadvertiseFlag_NormalHostname);
1459                 }
1460             }
1461         }
1462     }
1463 
1464 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1465     if (!AuthRecord_uDNS(rr))
1466     {
1467         if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1468             m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
1469         m->NumAllInterfaceRecords--;
1470         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1471             "DecrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S,
1472             m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1473     }
1474 #endif
1475 }
1476 
1477 mDNSlocal void AdvertiseNecessaryInterfaceRecords(mDNS *const m)
1478 {
1479     NetworkInterfaceInfo *intf;
1480     for (intf = m->HostInterfaces; intf; intf = intf->next)
1481     {
1482         if (intf->Advertise) AdvertiseInterfaceIfNeeded(m, intf);
1483     }
1484 }
1485 
1486 mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1487 {
1488     mDNSBool enablingBonjour = mDNSfalse;
1489 
1490     if (RRLocalOnly(rr))
1491     {
1492         // A sanity check, this should be prevented in calling code.
1493         LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1494         return;
1495     }
1496 
1497 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
1498     if (!AuthRecord_uDNS(rr))
1499     {
1500         m->NumAllInterfaceRecords++;
1501         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1502             "IncrementAutoTargetServices: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_S,
1503             m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1504         if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1505         {
1506             m->NextBonjourDisableTime = 0;
1507             if (m->BonjourEnabled == 0)
1508             {
1509                 // Enable Bonjour immediately by scheduling network changed processing where
1510                 // we will join the multicast group on each active interface.
1511                 m->BonjourEnabled = 1;
1512                 enablingBonjour = mDNStrue;
1513                 m->NetworkChanged = m->timenow;
1514             }
1515         }
1516     }
1517 #endif
1518 
1519     if (!AuthRecord_uDNS(rr) && (rr->resrec.rrtype == kDNSType_SRV) && (rr->AutoTarget == Target_AutoHost))
1520     {
1521 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
1522         if (AuthRecordIncludesAWDL(rr))
1523         {
1524             m->AutoTargetAWDLIncludedCount++;
1525             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1526                 "IncrementAutoTargetServices: AutoTargetAWDLIncludedCount %u Record " PRI_S,
1527                 m->AutoTargetAWDLIncludedCount, ARDisplayString(m, rr));
1528         }
1529         else if (mDNSPlatformInterfaceIsAWDL(rr->resrec.InterfaceID))
1530         {
1531             m->AutoTargetAWDLOnlyCount++;
1532             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1533                 "IncrementAutoTargetServices: AutoTargetAWDLOnlyCount %u Record " PRI_S,
1534                 m->AutoTargetAWDLOnlyCount, ARDisplayString(m, rr));
1535         }
1536         else
1537 #endif
1538         {
1539             m->AutoTargetServices++;
1540             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
1541                 "IncrementAutoTargetServices: AutoTargetServices %u Record " PRI_S,
1542                 m->AutoTargetServices, ARDisplayString(m, rr));
1543         }
1544         // If this is the first advertised service and we did not just enable Bonjour above, then
1545         // advertise all the interface records.  If we did enable Bonjour above, the interface records will
1546         // be advertised during the network changed processing scheduled above, so no need
1547         // to do it here.
1548         if (!enablingBonjour) AdvertiseNecessaryInterfaceRecords(m);
1549     }
1550 }
1551 
1552 mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr)
1553 {
1554     mDNSAddr     laddr = zeroAddr;
1555     mDNSEthAddr  eth = zeroEthAddr;
1556     mDNSIPPort   lport = zeroIPPort;
1557     mDNSIPPort   rport = zeroIPPort;
1558     mDNSu32      timeout = 0;
1559     mDNSu32      seq = 0;
1560     mDNSu32      ack = 0;
1561     mDNSu16      win = 0;
1562 
1563     if (mDNS_KeepaliveRecord(&rr->resrec))
1564     {
1565         mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, &eth, &seq, &ack, &lport, &rport, &win);
1566         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
1567         {
1568             LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger);
1569             return;
1570         }
1571     }
1572 }
1573 
1574 // Exported so uDNS.c can call this
1575 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1576 {
1577     domainname *target = GetRRDomainNameTarget(&rr->resrec);
1578     AuthRecord *r;
1579     AuthRecord **p = &m->ResourceRecords;
1580     AuthRecord **d = &m->DuplicateRecords;
1581 
1582     if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1583     { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1584 
1585     if (!rr->resrec.RecordType)
1586     { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1587 
1588     if (m->ShutdownTime)
1589     { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1590 
1591     if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1592     {
1593         mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1594         if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1595         {
1596             rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1597             rr->ARType = AuthRecordLocalOnly;
1598         }
1599         if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1600         {
1601             NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1602             if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1603         }
1604         if (rr->resrec.InterfaceID != previousID)
1605             LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1606     }
1607 
1608     if (RRLocalOnly(rr))
1609     {
1610         if (CheckAuthSameRecord(&m->rrauth, rr))
1611         {
1612             LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1613                    rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1614             return(mStatus_AlreadyRegistered);
1615         }
1616     }
1617     else
1618     {
1619         while (*p && *p != rr) p=&(*p)->next;
1620         if (*p)
1621         {
1622             LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1623                    rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1624             return(mStatus_AlreadyRegistered);
1625         }
1626     }
1627 
1628     while (*d && *d != rr) d=&(*d)->next;
1629     if (*d)
1630     {
1631         LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1632                rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1633         return(mStatus_AlreadyRegistered);
1634     }
1635 
1636     if (rr->DependentOn)
1637     {
1638         if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1639             rr->resrec.RecordType =  kDNSRecordTypeVerified;
1640         else if (rr->resrec.RecordType != kDNSRecordTypeKnownUnique)
1641         {
1642             LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique or kDNSRecordTypeKnownUnique",
1643                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1644             return(mStatus_Invalid);
1645         }
1646         if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1647         {
1648             LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1649                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1650             return(mStatus_Invalid);
1651         }
1652     }
1653 
1654     rr->next = mDNSNULL;
1655 
1656     // Field Group 1: The actual information pertaining to this resource record
1657     // Set up by client prior to call
1658 
1659     // Field Group 2: Persistent metadata for Authoritative Records
1660 //  rr->Additional1       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1661 //  rr->Additional2       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1662 //  rr->DependentOn       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1663 //  rr->RRSet             = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1664 //  rr->Callback          = already set      in mDNS_SetupResourceRecord
1665 //  rr->Context           = already set      in mDNS_SetupResourceRecord
1666 //  rr->RecordType        = already set      in mDNS_SetupResourceRecord
1667 //  rr->HostTarget        = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1668 //  rr->AllowRemoteQuery  = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1669     // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1670     if (rr->AutoTarget && target) target->c[0] = 0;
1671 
1672     // Field Group 3: Transient state for Authoritative Records
1673     rr->Acknowledged      = mDNSfalse;
1674     rr->ProbeCount        = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1675     rr->ProbeRestartCount = 0;
1676     rr->AnnounceCount     = InitialAnnounceCount;
1677     rr->RequireGoodbye    = mDNSfalse;
1678     rr->AnsweredLocalQ    = mDNSfalse;
1679     rr->IncludeInProbe    = mDNSfalse;
1680     rr->ImmedUnicast      = mDNSfalse;
1681     rr->SendNSECNow       = mDNSNULL;
1682     rr->ImmedAnswer       = mDNSNULL;
1683     rr->ImmedAdditional   = mDNSNULL;
1684     rr->SendRNow          = mDNSNULL;
1685     rr->v4Requester       = zerov4Addr;
1686     rr->v6Requester       = zerov6Addr;
1687     rr->NextResponse      = mDNSNULL;
1688     rr->NR_AnswerTo       = mDNSNULL;
1689     rr->NR_AdditionalTo   = mDNSNULL;
1690     if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1691 //  rr->LastAPTime        = Set for us in InitializeLastAPTime()
1692 //  rr->LastMCTime        = Set for us in InitializeLastAPTime()
1693 //  rr->LastMCInterface   = Set for us in InitializeLastAPTime()
1694     rr->NewRData          = mDNSNULL;
1695     rr->newrdlength       = 0;
1696     rr->UpdateCallback    = mDNSNULL;
1697     rr->UpdateCredits     = kMaxUpdateCredits;
1698     rr->NextUpdateCredit  = 0;
1699     rr->UpdateBlocked     = 0;
1700 
1701     // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1702     if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1703 
1704     // Field Group 4: Transient uDNS state for Authoritative Records
1705     rr->state             = regState_Zero;
1706     rr->uselease          = 0;
1707     rr->expire            = 0;
1708     rr->Private           = 0;
1709     rr->updateid          = zeroID;
1710     rr->updateIntID       = zeroOpaque64;
1711     rr->zone              = rr->resrec.name;
1712     rr->nta               = mDNSNULL;
1713     rr->tcp               = mDNSNULL;
1714     rr->OrigRData         = 0;
1715     rr->OrigRDLen         = 0;
1716     rr->InFlightRData     = 0;
1717     rr->InFlightRDLen     = 0;
1718     rr->QueuedRData       = 0;
1719     rr->QueuedRDLen       = 0;
1720     //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1721     // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1722     // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1723     // times with different values if the external NAT port changes during the lifetime of the service registration.
1724     //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1725 
1726 //  rr->resrec.interface         = already set in mDNS_SetupResourceRecord
1727 //  rr->resrec.name->c           = MUST be set by client
1728 //  rr->resrec.rrtype            = already set in mDNS_SetupResourceRecord
1729 //  rr->resrec.rrclass           = already set in mDNS_SetupResourceRecord
1730 //  rr->resrec.rroriginalttl     = already set in mDNS_SetupResourceRecord
1731 //  rr->resrec.rdata             = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1732 
1733     // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1734     // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1735     // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1736     if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1737 
1738     if (rr->AutoTarget)
1739     {
1740         SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1741 #ifndef UNICAST_DISABLED
1742         // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1743         // 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.
1744         if (rr->state == regState_NoTarget)
1745         {
1746             // Initialize the target so that we don't crash while logging etc.
1747             domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1748             if (tar) tar->c[0] = 0;
1749             LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1750         }
1751 #endif
1752     }
1753     else
1754     {
1755         rr->resrec.rdlength   = GetRDLength(&rr->resrec, mDNSfalse);
1756         rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1757     }
1758 
1759     if (!ValidateDomainName(rr->resrec.name))
1760     { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1761 
1762     // Don't do this until *after* we've set rr->resrec.rdlength
1763     if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1764     { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1765 
1766     rr->resrec.namehash   = DomainNameHashValue(rr->resrec.name);
1767     rr->resrec.rdatahash  = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1768 
1769     if (RRLocalOnly(rr))
1770     {
1771         // If this is supposed to be unique, make sure we don't have any name conflicts.
1772         // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1773         // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1774         // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1775         // Hence, just bail out.
1776         // This comment is doesn’t make any sense. -- SC
1777         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1778         {
1779             if (CheckAuthRecordConflict(&m->rrauth, rr))
1780             {
1781                 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1782                 return mStatus_NameConflict;
1783             }
1784         }
1785     }
1786 
1787     // For uDNS records, we don't support duplicate checks at this time.
1788 #ifndef UNICAST_DISABLED
1789     if (AuthRecord_uDNS(rr))
1790     {
1791         if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1792         // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1793         // 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.
1794         while (*p) p=&(*p)->next;
1795         *p = rr;
1796         if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1797         rr->ProbeCount    = 0;
1798         rr->ProbeRestartCount = 0;
1799         rr->AnnounceCount = 0;
1800         if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1801         return(mStatus_NoError);            // <--- Note: For unicast records, code currently bails out at this point
1802     }
1803 #endif
1804 
1805     // Now that we've finished building our new record, make sure it's not identical to one we already have
1806     if (RRLocalOnly(rr))
1807     {
1808         rr->ProbeCount    = 0;
1809         rr->ProbeRestartCount = 0;
1810         rr->AnnounceCount = 0;
1811         r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1812     }
1813     else
1814     {
1815         for (r = m->ResourceRecords; r; r=r->next)
1816             if (RecordIsLocalDuplicate(r, rr))
1817             {
1818                 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1819                 else break;
1820             }
1821     }
1822 
1823     if (r)
1824     {
1825         LogInfo("mDNS_Register_internal: Adding to duplicate list %s", ARDisplayString(m,rr));
1826         *d = rr;
1827         // If the previous copy of this record is already verified unique,
1828         // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1829         // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1830         // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1831         if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1832             rr->ProbeCount = 0;
1833     }
1834     else
1835     {
1836         LogInfo("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1837         if (RRLocalOnly(rr))
1838         {
1839             AuthGroup *ag;
1840             ag = InsertAuthRecord(m, &m->rrauth, rr);
1841             if (ag && !ag->NewLocalOnlyRecords)
1842             {
1843                 m->NewLocalOnlyRecords = mDNStrue;
1844                 ag->NewLocalOnlyRecords = rr;
1845             }
1846             // No probing for LocalOnly records; acknowledge them right away
1847             if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1848             AcknowledgeRecord(m, rr);
1849             return(mStatus_NoError);
1850         }
1851         else
1852         {
1853             if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1854             *p = rr;
1855         }
1856     }
1857 
1858     if (!AuthRecord_uDNS(rr))   // This check is superfluous, given that for unicast records we (currently) bail out above
1859     {
1860         // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1861         IncrementAutoTargetServices(m, rr);
1862 
1863         // For records that are not going to probe, acknowledge them right away
1864         if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1865             AcknowledgeRecord(m, rr);
1866 
1867         // Adding a record may affect whether or not we should sleep
1868         mDNS_UpdateAllowSleep(m);
1869     }
1870 
1871     // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1872     // This is used by the in-NIC proxy to send the keepalive packets.
1873     if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
1874     {
1875         mDNSAddr raddr;
1876         // Set the record type to known unique to prevent probing keep alive records.
1877         // Also make sure we do not announce the keepalive records.
1878        rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
1879        rr->AnnounceCount     = 0;
1880        getKeepaliveRaddr(m, rr, &raddr);
1881        // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1882        // asynchronous task to update the resource record
1883        mDNSPlatformGetRemoteMacAddr(&raddr);
1884     }
1885 
1886     return(mStatus_NoError);
1887 }
1888 
1889 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1890 {
1891     m->ProbeFailTime = m->timenow;
1892     m->NumFailedProbes++;
1893     // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1894     // If a bunch of hosts have all been configured with the same name, then they'll all
1895     // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1896     // up to name-10. After that they'll start adding random increments in the range 1-100,
1897     // so they're more likely to branch out in the available namespace and settle on a set of
1898     // unique names quickly. If after five more tries the host is still conflicting, then we
1899     // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1900     if (m->NumFailedProbes >= 15)
1901     {
1902         m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1903         LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1904                m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1905     }
1906 }
1907 
1908 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1909 {
1910     RData *OldRData = rr->resrec.rdata;
1911     mDNSu16 OldRDLen = rr->resrec.rdlength;
1912     SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);    // Update our rdata
1913     rr->NewRData = mDNSNULL;                                    // Clear the NewRData pointer ...
1914     if (rr->UpdateCallback)
1915         rr->UpdateCallback(m, rr, OldRData, OldRDLen);          // ... and let the client know
1916 }
1917 
1918 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1919 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1920 // Exported so uDNS.c can call this
1921 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1922 {
1923     AuthRecord *r2;
1924     mDNSu8 RecordType = rr->resrec.RecordType;
1925     AuthRecord **p = &m->ResourceRecords;   // Find this record in our list of active records
1926     mDNSBool dupList = mDNSfalse;
1927 
1928     if (RRLocalOnly(rr))
1929     {
1930         AuthGroup *a;
1931         AuthRecord **rp;
1932 
1933         a = AuthGroupForRecord(&m->rrauth, &rr->resrec);
1934         if (!a) return mDNSfalse;
1935         rp = &a->members;
1936         while (*rp && *rp != rr) rp=&(*rp)->next;
1937         p = rp;
1938     }
1939     else
1940     {
1941         while (*p && *p != rr) p=&(*p)->next;
1942     }
1943 
1944     if (*p)
1945     {
1946         // We found our record on the main list. See if there are any duplicates that need special handling.
1947         if (drt == mDNS_Dereg_conflict)     // If this was a conflict, see that all duplicates get the same treatment
1948         {
1949             // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1950             // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1951             for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1952         }
1953         else
1954         {
1955             // Before we delete the record (and potentially send a goodbye packet)
1956             // first see if we have a record on the duplicate list ready to take over from it.
1957             AuthRecord **d = &m->DuplicateRecords;
1958             while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1959             if (*d)
1960             {
1961                 AuthRecord *dup = *d;
1962                 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1963                        dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1964                 *d        = dup->next;      // Cut replacement record from DuplicateRecords list
1965                 if (RRLocalOnly(rr))
1966                 {
1967                     dup->next = mDNSNULL;
1968                     if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1969                 }
1970                 else
1971                 {
1972                     dup->next = rr->next;       // And then...
1973                     rr->next  = dup;            // ... splice it in right after the record we're about to delete
1974                 }
1975                 dup->resrec.RecordType        = rr->resrec.RecordType;
1976                 dup->ProbeCount      = rr->ProbeCount;
1977                 dup->ProbeRestartCount = rr->ProbeRestartCount;
1978                 dup->AnnounceCount   = rr->AnnounceCount;
1979                 dup->RequireGoodbye  = rr->RequireGoodbye;
1980                 dup->AnsweredLocalQ  = rr->AnsweredLocalQ;
1981                 dup->ImmedAnswer     = rr->ImmedAnswer;
1982                 dup->ImmedUnicast    = rr->ImmedUnicast;
1983                 dup->ImmedAdditional = rr->ImmedAdditional;
1984                 dup->v4Requester     = rr->v4Requester;
1985                 dup->v6Requester     = rr->v6Requester;
1986                 dup->ThisAPInterval  = rr->ThisAPInterval;
1987                 dup->LastAPTime      = rr->LastAPTime;
1988                 dup->LastMCTime      = rr->LastMCTime;
1989                 dup->LastMCInterface = rr->LastMCInterface;
1990                 dup->Private         = rr->Private;
1991                 dup->state           = rr->state;
1992                 rr->RequireGoodbye = mDNSfalse;
1993                 rr->AnsweredLocalQ = mDNSfalse;
1994             }
1995         }
1996     }
1997     else
1998     {
1999         // We didn't find our record on the main list; try the DuplicateRecords list instead.
2000         p = &m->DuplicateRecords;
2001         while (*p && *p != rr) p=&(*p)->next;
2002         // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
2003         if (*p)
2004         {
2005             // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
2006             // immediately. When there is a conflict, we deregister all the conflicting duplicate records
2007             // also that have been marked above in this function. In that case, we come here and if we don't
2008             // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
2009             // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
2010             // details.
2011             rr->WakeUp.HMAC    = zeroEthAddr;
2012             rr->RequireGoodbye = mDNSfalse;
2013             rr->resrec.RecordType = kDNSRecordTypeDeregistering;
2014             dupList = mDNStrue;
2015         }
2016         if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
2017                        rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2018     }
2019 
2020     if (!*p)
2021     {
2022         // No need to log an error message if we already know this is a potentially repeated deregistration
2023         if (drt != mDNS_Dereg_repeat)
2024             LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
2025         return(mStatus_BadReferenceErr);
2026     }
2027 
2028     // If this is a shared record and we've announced it at least once,
2029     // we need to retract that announcement before we delete the record
2030 
2031     // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
2032     // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv)" here, but that would not not be safe.
2033     // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
2034     // mechanism to cope with the client callback modifying the question list while that's happening.
2035     // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
2036     // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
2037     // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
2038     // records, thereby invoking yet more callbacks, without limit.
2039     // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
2040     // actual goodbye packets.
2041 
2042 #ifndef UNICAST_DISABLED
2043     if (AuthRecord_uDNS(rr))
2044     {
2045         if (rr->RequireGoodbye)
2046         {
2047             if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
2048             rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
2049             m->LocalRemoveEvents     = mDNStrue;
2050             uDNS_DeregisterRecord(m, rr);
2051             // At this point unconditionally we bail out
2052             // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
2053             // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
2054             // process and will complete asynchronously. Either way we don't need to do anything more here.
2055             return(mStatus_NoError);
2056         }
2057         // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
2058         // from the server. In that case, if the records have been part of a group update, clear the
2059         // state here.
2060         rr->updateid = zeroID;
2061 
2062         // We defer cleaning up NAT state only after sending goodbyes. This is important because
2063         // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
2064         // This happens today when we turn on/off interface where we get multiple network transitions
2065         // and RestartRecordGetZoneData triggers re-registration of the resource records even though
2066         // they may be in Registered state which causes NAT information to be setup multiple times. Defering
2067         // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
2068         // NAT state here takes care of the case where we did not send goodbyes at all.
2069         if (rr->NATinfo.clientContext)
2070         {
2071             mDNS_StopNATOperation_internal(m, &rr->NATinfo);
2072             rr->NATinfo.clientContext = mDNSNULL;
2073         }
2074         if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
2075         if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
2076     }
2077 #endif // UNICAST_DISABLED
2078 
2079     if      (RecordType == kDNSRecordTypeUnregistered)
2080         LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
2081     else if (RecordType == kDNSRecordTypeDeregistering)
2082     {
2083         LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
2084         return(mStatus_BadReferenceErr);
2085     }
2086 
2087     if (rr->WakeUp.HMAC.l[0] ||
2088         (((RecordType == kDNSRecordTypeShared) || (rr->ARType == AuthRecordLocalOnly)) &&
2089         (rr->RequireGoodbye || rr->AnsweredLocalQ)))
2090     {
2091         verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
2092         rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
2093         rr->resrec.rroriginalttl = 0;
2094         rr->AnnounceCount        = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
2095         rr->ThisAPInterval       = mDNSPlatformOneSecond * 2;
2096         rr->LastAPTime           = m->timenow - rr->ThisAPInterval;
2097         m->LocalRemoveEvents     = mDNStrue;
2098         if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
2099             m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
2100     }
2101     else
2102     {
2103         if (!dupList && RRLocalOnly(rr))
2104         {
2105             AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
2106             if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
2107         }
2108         else
2109         {
2110             *p = rr->next;                  // Cut this record from the list
2111             if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
2112             DecrementAutoTargetServices(m, rr);
2113         }
2114         // If someone is about to look at this, bump the pointer forward
2115         if (m->CurrentRecord   == rr) m->CurrentRecord   = rr->next;
2116         rr->next = mDNSNULL;
2117 
2118         verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
2119         rr->resrec.RecordType = kDNSRecordTypeUnregistered;
2120 
2121         if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
2122             debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
2123                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2124 
2125         // If we have an update queued up which never executed, give the client a chance to free that memory
2126         if (rr->NewRData) CompleteRDataUpdate(m, rr);   // Update our rdata, clear the NewRData pointer, and return memory to the client
2127 
2128 
2129         // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
2130         // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
2131         // In this case the likely client action to the mStatus_MemFree message is to free the memory,
2132         // so any attempt to touch rr after this is likely to lead to a crash.
2133         if (drt != mDNS_Dereg_conflict)
2134         {
2135             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
2136             LogInfo("mDNS_Deregister_internal: callback with mStatus_MemFree for %s", ARDisplayString(m, rr));
2137             if (rr->RecordCallback)
2138                 rr->RecordCallback(m, rr, mStatus_MemFree);         // MUST NOT touch rr after this
2139             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
2140         }
2141         else
2142         {
2143             RecordProbeFailure(m, rr);
2144             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
2145             if (rr->RecordCallback)
2146                 rr->RecordCallback(m, rr, mStatus_NameConflict);    // MUST NOT touch rr after this
2147             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
2148             // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
2149             // Note that with all the client callbacks going on, by the time we get here all the
2150             // records we marked may have been explicitly deregistered by the client anyway.
2151             r2 = m->DuplicateRecords;
2152             while (r2)
2153             {
2154                 if (r2->ProbeCount != 0xFF)
2155                 {
2156                     r2 = r2->next;
2157                 }
2158                 else
2159                 {
2160 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
2161                     // See if this record was also registered with any D2D plugins.
2162                     D2D_stop_advertising_record(r2);
2163 #endif
2164                     mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
2165                     // As this is a duplicate record, it will be unlinked from the list
2166                     // immediately
2167                     r2 = m->DuplicateRecords;
2168                 }
2169             }
2170         }
2171     }
2172     mDNS_UpdateAllowSleep(m);
2173     return(mStatus_NoError);
2174 }
2175 
2176 // ***************************************************************************
2177 #if COMPILER_LIKES_PRAGMA_MARK
2178 #pragma mark -
2179 #pragma mark - Packet Sending Functions
2180 #endif
2181 
2182 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
2183 {
2184     if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
2185     {
2186         **nrpp = rr;
2187         // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
2188         // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
2189         // The referenced record will definitely be acceptable (by recursive application of this rule)
2190         if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
2191         rr->NR_AdditionalTo = add;
2192         *nrpp = &rr->NextResponse;
2193     }
2194     debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
2195 }
2196 
2197 mDNSlocal void AddRRSetAdditionalsToResponseList(mDNS *const m, AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *additional, const mDNSInterfaceID InterfaceID)
2198 {
2199     AuthRecord *rr2;
2200     if (additional->resrec.RecordType & kDNSRecordTypeUniqueMask)
2201     {
2202         for (rr2 = m->ResourceRecords; rr2; rr2 = rr2->next)
2203         {
2204             if ((rr2->resrec.namehash == additional->resrec.namehash) &&
2205                 (rr2->resrec.rrtype   == additional->resrec.rrtype) &&
2206                 (rr2 != additional) &&
2207                 (rr2->resrec.RecordType & kDNSRecordTypeUniqueMask) &&
2208                 (rr2->resrec.rrclass  == additional->resrec.rrclass) &&
2209                 ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&
2210                 SameDomainName(rr2->resrec.name, additional->resrec.name))
2211             {
2212                 AddRecordToResponseList(nrpp, rr2, rr);
2213             }
2214         }
2215     }
2216 }
2217 
2218 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
2219 {
2220     AuthRecord  *rr, *rr2;
2221     for (rr=ResponseRecords; rr; rr=rr->NextResponse)           // For each record we plan to put
2222     {
2223         // (Note: This is an "if", not a "while". If we add a record, we'll find it again
2224         // later in the "for" loop, and we will follow further "additional" links then.)
2225         if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
2226         {
2227             AddRecordToResponseList(nrpp, rr->Additional1, rr);
2228             AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional1, InterfaceID);
2229         }
2230 
2231         if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
2232         {
2233             AddRecordToResponseList(nrpp, rr->Additional2, rr);
2234             AddRRSetAdditionalsToResponseList(m, nrpp, rr, rr->Additional2, InterfaceID);
2235         }
2236 
2237         // For SRV records, automatically add the Address record(s) for the target host
2238         if (rr->resrec.rrtype == kDNSType_SRV)
2239         {
2240             for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)                    // Scan list of resource records
2241                 if (RRTypeIsAddressType(rr2->resrec.rrtype) &&                  // For all address records (A/AAAA) ...
2242                     ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&   // ... which are valid for answer ...
2243                     rr->resrec.rdatahash == rr2->resrec.namehash &&         // ... whose name is the name of the SRV target
2244                     SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
2245                     AddRecordToResponseList(nrpp, rr2, rr);
2246         }
2247         else if (RRTypeIsAddressType(rr->resrec.rrtype))    // For A or AAAA, put counterpart as additional
2248         {
2249             for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)                    // Scan list of resource records
2250                 if (RRTypeIsAddressType(rr2->resrec.rrtype) &&                  // For all address records (A/AAAA) ...
2251                     ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&   // ... which are valid for answer ...
2252                     rr->resrec.namehash == rr2->resrec.namehash &&              // ... and have the same name
2253                     SameDomainName(rr->resrec.name, rr2->resrec.name))
2254                     AddRecordToResponseList(nrpp, rr2, rr);
2255         }
2256         else if (rr->resrec.rrtype == kDNSType_PTR)         // For service PTR, see if we want to add DeviceInfo record
2257         {
2258             if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
2259                 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2260                 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
2261         }
2262     }
2263 }
2264 
2265 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
2266 {
2267     AuthRecord *rr;
2268     AuthRecord  *ResponseRecords = mDNSNULL;
2269     AuthRecord **nrp             = &ResponseRecords;
2270     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
2271 
2272     // Make a list of all our records that need to be unicast to this destination
2273     for (rr = m->ResourceRecords; rr; rr=rr->next)
2274     {
2275         // If we find we can no longer unicast this answer, clear ImmedUnicast
2276         if (rr->ImmedAnswer == mDNSInterfaceMark               ||
2277             mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
2278             mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr)  )
2279             rr->ImmedUnicast = mDNSfalse;
2280 
2281         if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
2282         {
2283             if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
2284                 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
2285             {
2286                 rr->ImmedAnswer  = mDNSNULL;                // Clear the state fields
2287                 rr->ImmedUnicast = mDNSfalse;
2288                 rr->v4Requester  = zerov4Addr;
2289                 rr->v6Requester  = zerov6Addr;
2290 
2291                 // Only sent records registered for P2P over P2P interfaces
2292                 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID))
2293                 {
2294                     continue;
2295                 }
2296 
2297                 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse)   // rr->NR_AnswerTo
2298                 {
2299                     rr->NR_AnswerTo = NR_AnswerMulticast;
2300                     *nrp = rr;
2301                     nrp = &rr->NextResponse;
2302                 }
2303             }
2304         }
2305     }
2306 
2307     AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
2308 
2309     while (ResponseRecords)
2310     {
2311         mDNSu8 *responseptr = m->omsg.data;
2312         mDNSu8 *newptr;
2313         InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2314 
2315         // Put answers in the packet
2316         while (ResponseRecords && ResponseRecords->NR_AnswerTo)
2317         {
2318             rr = ResponseRecords;
2319             if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2320                 rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
2321 
2322             newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec);
2323 
2324             rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
2325             if (!newptr && m->omsg.h.numAnswers)
2326             {
2327                 break; // If packet full, send it now
2328             }
2329             if (newptr) responseptr = newptr;
2330             ResponseRecords = rr->NextResponse;
2331             rr->NextResponse    = mDNSNULL;
2332             rr->NR_AnswerTo     = mDNSNULL;
2333             rr->NR_AdditionalTo = mDNSNULL;
2334             rr->RequireGoodbye  = mDNStrue;
2335         }
2336 
2337         // Add additionals, if there's space
2338         while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
2339         {
2340             rr = ResponseRecords;
2341             if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2342                 rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
2343             newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
2344             rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
2345 
2346             if (newptr) responseptr = newptr;
2347             if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
2348             else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
2349             ResponseRecords = rr->NextResponse;
2350             rr->NextResponse    = mDNSNULL;
2351             rr->NR_AnswerTo     = mDNSNULL;
2352             rr->NR_AdditionalTo = mDNSNULL;
2353         }
2354 
2355         if (m->omsg.h.numAnswers)
2356             mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSfalse);
2357     }
2358 }
2359 
2360 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2361 // and the client's mStatus_MemFree callback will have been invoked
2362 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
2363 {
2364     LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
2365     // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2366     // it should go ahead and immediately dispose of this registration
2367     rr->resrec.RecordType = kDNSRecordTypeShared;
2368     rr->RequireGoodbye    = mDNSfalse;
2369     rr->WakeUp.HMAC       = zeroEthAddr;
2370     if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); rr->AnsweredLocalQ = mDNSfalse; }
2371     mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);     // Don't touch rr after this
2372 }
2373 
2374 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2375 // any deregistering records that remain in the m->ResourceRecords list.
2376 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2377 // which may change the record list and/or question list.
2378 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2379 mDNSlocal void DiscardDeregistrations(mDNS *const m)
2380 {
2381     if (m->CurrentRecord)
2382         LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2383     m->CurrentRecord = m->ResourceRecords;
2384 
2385     while (m->CurrentRecord)
2386     {
2387         AuthRecord *rr = m->CurrentRecord;
2388         if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2389             CompleteDeregistration(m, rr);      // Don't touch rr after this
2390         else
2391             m->CurrentRecord = rr->next;
2392     }
2393 }
2394 
2395 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
2396 {
2397     int i, val = 0;
2398     if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
2399     for (i=1; i<=src[0]; i++)
2400     {
2401         if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
2402         val = val * 10 + src[i] - '0';
2403     }
2404     if (val > 255) return(mStatus_Invalid);
2405     *dst = (mDNSu8)val;
2406     return(mStatus_NoError);
2407 }
2408 
2409 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
2410 {
2411     int skip = CountLabels(name) - 6;
2412     if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
2413     if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
2414         GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
2415         GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
2416         GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
2417     a->type = mDNSAddrType_IPv4;
2418     return(mStatus_NoError);
2419 }
2420 
2421 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0'     ) :   \
2422                     ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) :   \
2423                     ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2424 
2425 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
2426 {
2427     int i, h, l;
2428     const domainname *n;
2429 
2430     int skip = CountLabels(name) - 34;
2431     if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
2432 
2433     n = SkipLeadingLabels(name, skip);
2434     for (i=0; i<16; i++)
2435     {
2436         if (n->c[0] != 1) return mStatus_Invalid;
2437         l = HexVal(n->c[1]);
2438         n = (const domainname *)(n->c + 2);
2439 
2440         if (n->c[0] != 1) return mStatus_Invalid;
2441         h = HexVal(n->c[1]);
2442         n = (const domainname *)(n->c + 2);
2443 
2444         if (l<0 || h<0) return mStatus_Invalid;
2445         a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
2446     }
2447 
2448     a->type = mDNSAddrType_IPv6;
2449     return(mStatus_NoError);
2450 }
2451 
2452 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
2453 {
2454     int skip = CountLabels(name) - 2;
2455     if (skip >= 0)
2456     {
2457         const domainname *suffix = SkipLeadingLabels(name, skip);
2458         if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
2459         if (SameDomainName(suffix, (const domainname*)"\x3" "ip6"     "\x4" "arpa")) return mDNSAddrType_IPv6;
2460     }
2461     return(mDNSAddrType_None);
2462 }
2463 
2464 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
2465                        const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
2466 {
2467     int i;
2468     mDNSu8 *ptr = m->omsg.data;
2469     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2470     if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2471 
2472     // 0x00 Destination address
2473     for (i=0; i<6; i++) *ptr++ = dst->b[i];
2474 
2475     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2476     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2477 
2478     // 0x0C ARP Ethertype (0x0806)
2479     *ptr++ = 0x08; *ptr++ = 0x06;
2480 
2481     // 0x0E ARP header
2482     *ptr++ = 0x00; *ptr++ = 0x01;   // Hardware address space; Ethernet = 1
2483     *ptr++ = 0x08; *ptr++ = 0x00;   // Protocol address space; IP = 0x0800
2484     *ptr++ = 6;                     // Hardware address length
2485     *ptr++ = 4;                     // Protocol address length
2486     *ptr++ = 0x00; *ptr++ = op;     // opcode; Request = 1, Response = 2
2487 
2488     // 0x16 Sender hardware address (our MAC address)
2489     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
2490 
2491     // 0x1C Sender protocol address
2492     for (i=0; i<4; i++) *ptr++ = spa->b[i];
2493 
2494     // 0x20 Target hardware address
2495     for (i=0; i<6; i++) *ptr++ = tha->b[i];
2496 
2497     // 0x26 Target protocol address
2498     for (i=0; i<4; i++) *ptr++ = tpa->b[i];
2499 
2500     // 0x2A Total ARP Packet length 42 bytes
2501     mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2502 }
2503 
2504 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
2505 {
2506     const mDNSu16 *ptr = data;
2507     while (length > 0) { length -= 2; sum += *ptr++; }
2508     sum = (sum & 0xFFFF) + (sum >> 16);
2509     sum = (sum & 0xFFFF) + (sum >> 16);
2510     return(sum != 0xFFFF ? sum : 0);
2511 }
2512 
2513 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
2514 {
2515     IPv6PseudoHeader ph;
2516     ph.src = *src;
2517     ph.dst = *dst;
2518     ph.len.b[0] = length >> 24;
2519     ph.len.b[1] = length >> 16;
2520     ph.len.b[2] = length >> 8;
2521     ph.len.b[3] = length;
2522     ph.pro.b[0] = 0;
2523     ph.pro.b[1] = 0;
2524     ph.pro.b[2] = 0;
2525     ph.pro.b[3] = protocol;
2526     return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
2527 }
2528 
2529 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
2530                        const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
2531 {
2532     int i;
2533     mDNSOpaque16 checksum;
2534     mDNSu8 *ptr = m->omsg.data;
2535     // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2536     // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2537     // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2538     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] } };
2539     const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
2540     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2541     if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2542 
2543     // 0x00 Destination address
2544     for (i=0; i<6; i++) *ptr++ = dst->b[i];
2545     // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2546     // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2547     // link with a pointless link-layer multicast.
2548     // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2549     // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2550     // *ptr++ = 0x33;
2551     // *ptr++ = 0x33;
2552     // *ptr++ = 0xFF;
2553     // *ptr++ = tpa->b[0xD];
2554     // *ptr++ = tpa->b[0xE];
2555     // *ptr++ = tpa->b[0xF];
2556 
2557     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2558     for (i=0; i<6; i++)
2559 	if (tha)
2560 	    *ptr++ = tha->b[i];
2561 	else
2562 	    *ptr++ = intf->MAC.b[i];
2563 
2564     // 0x0C IPv6 Ethertype (0x86DD)
2565     *ptr++ = 0x86; *ptr++ = 0xDD;
2566 
2567     // 0x0E IPv6 header
2568     *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;     // Version, Traffic Class, Flow Label
2569     *ptr++ = 0x00; *ptr++ = 0x20;                                   // Length
2570     *ptr++ = 0x3A;                                                  // Protocol == ICMPv6
2571     *ptr++ = 0xFF;                                                  // Hop Limit
2572 
2573     // 0x16 Sender IPv6 address
2574     for (i=0; i<16; i++) *ptr++ = spa->b[i];
2575 
2576     // 0x26 Destination IPv6 address
2577     for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2578 
2579     // 0x36 NDP header
2580     *ptr++ = op;                    // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2581     *ptr++ = 0x00;                  // Code
2582     *ptr++ = 0x00; *ptr++ = 0x00;   // Checksum placeholder (0x38, 0x39)
2583     *ptr++ = flags;
2584     *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2585 
2586     if (op == NDP_Sol)  // Neighbor Solicitation. The NDP "target" is the address we seek.
2587     {
2588         // 0x3E NDP target.
2589         for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2590         // 0x4E Source Link-layer Address
2591         // <http://www.ietf.org/rfc/rfc2461.txt>
2592         // MUST NOT be included when the source IP address is the unspecified address.
2593         // Otherwise, on link layers that have addresses this option MUST be included
2594         // in multicast solicitations and SHOULD be included in unicast solicitations.
2595         if (!mDNSIPv6AddressIsZero(*spa))
2596         {
2597             *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2598             *ptr++ = 0x01;      // Option length 1 (in units of 8 octets)
2599             for (i=0; i<6; i++)
2600 		if (tha)
2601 		    *ptr++ = tha->b[i];
2602 		else
2603 		    *ptr++ = intf->MAC.b[i];
2604         }
2605     }
2606     else            // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2607     {
2608         // 0x3E NDP target.
2609         for (i=0; i<16; i++) *ptr++ = spa->b[i];
2610         // 0x4E Target Link-layer Address
2611         *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2612         *ptr++ = 0x01;      // Option length 1 (in units of 8 octets)
2613         for (i=0; i<6; i++)
2614 	    if (tha)
2615 		*ptr++ = tha->b[i];
2616 	    else
2617 		*ptr++ = intf->MAC.b[i];
2618     }
2619 
2620     // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2621     m->omsg.data[0x13] = ptr - &m->omsg.data[0x36];     // Compute actual length
2622     checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2623     m->omsg.data[0x38] = checksum.b[0];
2624     m->omsg.data[0x39] = checksum.b[1];
2625 
2626     mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2627 }
2628 
2629 mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace)
2630 {
2631     mDNSu32 DNS_VERS = _DNS_SD_H;
2632     Trace->u.tracer.platf    = m->mDNS_plat;
2633     Trace->u.tracer.mDNSv    = DNS_VERS;
2634 
2635     Trace->opt              = kDNSOpt_Trace;
2636     Trace->optlen           = DNSOpt_TraceData_Space - 4;
2637 }
2638 
2639 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2640 {
2641     owner->u.owner.vers     = 0;
2642     owner->u.owner.seq      = m->SleepSeqNum;
2643     owner->u.owner.HMAC     = m->PrimaryMAC;
2644     owner->u.owner.IMAC     = intf->MAC;
2645     owner->u.owner.password = zeroEthAddr;
2646 
2647     // Don't try to compute the optlen until *after* we've set up the data fields
2648     // 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
2649     owner->opt              = kDNSOpt_Owner;
2650     owner->optlen           = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2651 }
2652 
2653 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2654 {
2655     if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2656     else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2657 }
2658 
2659 mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr)
2660 {
2661     // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2662     // and hence there is no need to check for Transfering state. But if we have sleep
2663     // proxies and partially sending goodbyes for some records, we will be in Transfering
2664     // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2665     // we are not awake handles both cases.
2666     if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake))
2667     {
2668         debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr));
2669         return mDNStrue;
2670     }
2671 
2672     if (m->SleepState != SleepState_Sleeping)
2673         return mDNSfalse;
2674 
2675     // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2676     // whether you can send goodbyes or not.
2677     if (!intf->SendGoodbyes)
2678     {
2679         debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2680         return mDNSfalse;
2681     }
2682     else
2683     {
2684         debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2685         return mDNStrue;
2686     }
2687 }
2688 
2689 // Note about acceleration of announcements to facilitate automatic coalescing of
2690 // multiple independent threads of announcements into a single synchronized thread:
2691 // The announcements in the packet may be at different stages of maturity;
2692 // One-second interval, two-second interval, four-second interval, and so on.
2693 // After we've put in all the announcements that are due, we then consider
2694 // whether there are other nearly-due announcements that are worth accelerating.
2695 // To be eligible for acceleration, a record MUST NOT be older (further along
2696 // its timeline) than the most mature record we've already put in the packet.
2697 // In other words, younger records can have their timelines accelerated to catch up
2698 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2699 // Older records cannot have their timelines accelerated; this would just widen
2700 // the gap between them and their younger bretheren and get them even more out of sync.
2701 
2702 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2703 // the record list and/or question list.
2704 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2705 mDNSlocal void SendResponses(mDNS *const m)
2706 {
2707     int pktcount = 0;
2708     AuthRecord *rr, *r2;
2709     mDNSs32 maxExistingAnnounceInterval = 0;
2710     const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2711 
2712     m->NextScheduledResponse = m->timenow + FutureTime;
2713 
2714     if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2715 
2716     for (rr = m->ResourceRecords; rr; rr=rr->next)
2717         if (rr->ImmedUnicast)
2718         {
2719             mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2720             mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2721             v4.ip.v4 = rr->v4Requester;
2722             v6.ip.v6 = rr->v6Requester;
2723             if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2724             if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2725             if (rr->ImmedUnicast)
2726             {
2727                 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2728                 rr->ImmedUnicast = mDNSfalse;
2729             }
2730         }
2731 
2732     // ***
2733     // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2734     // ***
2735 
2736     // Run through our list of records, and decide which ones we're going to announce on all interfaces
2737     for (rr = m->ResourceRecords; rr; rr=rr->next)
2738     {
2739         while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2740         if (TimeToAnnounceThisRecord(rr, m->timenow))
2741         {
2742             if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2743             {
2744                 if (!rr->WakeUp.HMAC.l[0])
2745                 {
2746                     if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark;     // Send goodbye packet on all interfaces
2747                 }
2748                 else
2749                 {
2750                     mDNSBool unicastOnly;
2751                     LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2752                     unicastOnly = ((rr->AnnounceCount == WakeupCount) || (rr->AnnounceCount == WakeupCount - 1)) ? mDNStrue : mDNSfalse;
2753                     SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password, unicastOnly);
2754                     for (r2 = rr; r2; r2=r2->next)
2755                         if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) &&
2756                             mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
2757                         {
2758                             // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2759                             // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2760                             if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2761                             {
2762                                 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2763                                        r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2764                                 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2765                             }
2766                             r2->LastAPTime = m->timenow;
2767                             // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2768                             if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2769                         }
2770                 }
2771             }
2772             else if (ResourceRecordIsValidAnswer(rr))
2773             {
2774                 if (rr->AddressProxy.type)
2775                 {
2776                     if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
2777                     {
2778                         rr->AnnounceCount--;
2779                         rr->ThisAPInterval *= 2;
2780                         rr->LastAPTime = m->timenow;
2781                         if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2782                         {
2783                             LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2784                                     rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2785                             SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2786                         }
2787                         else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2788                         {
2789                             LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2790                                     rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2791                             SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2792                         }
2793                     }
2794                 }
2795                 else
2796                 {
2797                     rr->ImmedAnswer = mDNSInterfaceMark;        // Send on all interfaces
2798                     if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2799                         maxExistingAnnounceInterval = rr->ThisAPInterval;
2800                     if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2801                 }
2802             }
2803         }
2804     }
2805 
2806     // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2807     // Eligible records that are more than half-way to their announcement time are accelerated
2808     for (rr = m->ResourceRecords; rr; rr=rr->next)
2809         if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2810             (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2811              TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2812              !rr->AddressProxy.type &&                  // Don't include ARP Annoucements when considering which records to accelerate
2813              ResourceRecordIsValidAnswer(rr)))
2814             rr->ImmedAnswer = mDNSInterfaceMark;        // Send on all interfaces
2815 
2816     // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2817     // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2818     // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2819     // then all that means is that it won't get sent -- which would not be the end of the world.
2820     for (rr = m->ResourceRecords; rr; rr=rr->next)
2821     {
2822         if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2823             for (r2=m->ResourceRecords; r2; r2=r2->next)                // Scan list of resource records
2824                 if (RRTypeIsAddressType(r2->resrec.rrtype) &&           // For all address records (A/AAAA) ...
2825                     ResourceRecordIsValidAnswer(r2) &&                  // ... which are valid for answer ...
2826                     rr->LastMCTime - r2->LastMCTime >= 0 &&             // ... which we have not sent recently ...
2827                     rr->resrec.rdatahash == r2->resrec.namehash &&      // ... whose name is the name of the SRV target
2828                     SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2829                     (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2830                     r2->ImmedAdditional = r2->resrec.InterfaceID;       // ... then mark this address record for sending too
2831         // We also make sure we send the DeviceInfo TXT record too, if necessary
2832         // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2833         // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2834         if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2835             if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2836             {
2837                 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2838                 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2839             }
2840     }
2841 
2842     // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2843     // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2844     // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2845     // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2846     // -- 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
2847     // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2848     for (rr = m->ResourceRecords; rr; rr=rr->next)
2849         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2850         {
2851             if (rr->ImmedAnswer)            // If we're sending this as answer, see that its whole RRSet is similarly marked
2852             {
2853                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2854                 {
2855                     if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2856                         (r2->ImmedAnswer != mDNSInterfaceMark) && (r2->ImmedAnswer != rr->ImmedAnswer) &&
2857                         SameResourceRecordSignature(r2, rr) &&
2858                         ((rr->ImmedAnswer == mDNSInterfaceMark) || IsInterfaceValidForAuthRecord(r2, rr->ImmedAnswer)))
2859                     {
2860                         r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2861                     }
2862                 }
2863             }
2864             else if (rr->ImmedAdditional)   // If we're sending this as additional, see that its whole RRSet is similarly marked
2865             {
2866                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2867                 {
2868                     if ((r2->resrec.RecordType & kDNSRecordTypeUniqueMask) && ResourceRecordIsValidAnswer(r2) &&
2869                         (r2->ImmedAdditional != rr->ImmedAdditional) &&
2870                         SameResourceRecordSignature(r2, rr) &&
2871                         IsInterfaceValidForAuthRecord(r2, rr->ImmedAdditional))
2872                     {
2873                         r2->ImmedAdditional = rr->ImmedAdditional;
2874                     }
2875                 }
2876             }
2877         }
2878 
2879     // Now set SendRNow state appropriately
2880     for (rr = m->ResourceRecords; rr; rr=rr->next)
2881     {
2882         if (rr->ImmedAnswer == mDNSInterfaceMark)       // Sending this record on all appropriate interfaces
2883         {
2884             rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2885             rr->ImmedAdditional = mDNSNULL;             // No need to send as additional if sending as answer
2886             rr->LastMCTime      = m->timenow;
2887             rr->LastMCInterface = rr->ImmedAnswer;
2888             rr->ProbeRestartCount = 0;                  // Reset the probe restart count
2889             // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2890             if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2891             {
2892                 rr->AnnounceCount--;
2893                 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2894                     rr->ThisAPInterval *= 2;
2895                 rr->LastAPTime = m->timenow;
2896                 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2897             }
2898         }
2899         else if (rr->ImmedAnswer)                       // Else, just respond to a single query on single interface:
2900         {
2901             rr->SendRNow        = rr->ImmedAnswer;      // Just respond on that interface
2902             rr->ImmedAdditional = mDNSNULL;             // No need to send as additional too
2903             rr->LastMCTime      = m->timenow;
2904             rr->LastMCInterface = rr->ImmedAnswer;
2905         }
2906         SetNextAnnounceProbeTime(m, rr);
2907         //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2908     }
2909 
2910     // ***
2911     // *** 2. Loop through interface list, sending records as appropriate
2912     // ***
2913 
2914     while (intf)
2915     {
2916         int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2917         int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
2918         int numDereg    = 0;
2919         int numAnnounce = 0;
2920         int numAnswer   = 0;
2921         mDNSu8 *responseptr = m->omsg.data;
2922         mDNSu8 *newptr;
2923         InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2924 
2925         // First Pass. Look for:
2926         // 1. Deregistering records that need to send their goodbye packet
2927         // 2. Updated records that need to retract their old data
2928         // 3. Answers and announcements we need to send
2929         for (rr = m->ResourceRecords; rr; rr=rr->next)
2930         {
2931 
2932             // Skip this interface if the record InterfaceID is *Any and the record is not
2933             // appropriate for the interface type.
2934             if ((rr->SendRNow == intf->InterfaceID) &&
2935                 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf->InterfaceID)))
2936             {
2937                 rr->SendRNow = GetNextActiveInterfaceID(intf);
2938             }
2939             else if (rr->SendRNow == intf->InterfaceID)
2940             {
2941                 RData  *OldRData    = rr->resrec.rdata;
2942                 mDNSu16 oldrdlength = rr->resrec.rdlength;
2943                 mDNSu8 active = (mDNSu8)
2944                                 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr));
2945                 newptr = mDNSNULL;
2946                 if (rr->NewRData && active)
2947                 {
2948                     // See if we should send a courtesy "goodbye" for the old data before we replace it.
2949                     if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2950                     {
2951                         newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2952                         if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2953                         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
2954                     }
2955                     SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2956                 }
2957 
2958                 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2959                     rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
2960                 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2961                 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
2962                 if (newptr)
2963                 {
2964                     responseptr = newptr;
2965                     rr->RequireGoodbye = active;
2966                     if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2967                     else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2968                 }
2969 
2970                 if (rr->NewRData && active)
2971                     SetNewRData(&rr->resrec, OldRData, oldrdlength);
2972 
2973                 // The first time through (pktcount==0), if this record is verified unique
2974                 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2975                 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2976                     rr->SendNSECNow = mDNSInterfaceMark;
2977 
2978                 if (newptr)     // If succeeded in sending, advance to next interface
2979                 {
2980                     // If sending on all interfaces, go to next interface; else we're finished now
2981                     if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2982                         rr->SendRNow = GetNextActiveInterfaceID(intf);
2983                     else
2984                         rr->SendRNow = mDNSNULL;
2985                 }
2986             }
2987         }
2988 
2989         // Second Pass. Add additional records, if there's space.
2990         newptr = responseptr;
2991         for (rr = m->ResourceRecords; rr; rr=rr->next)
2992             if (rr->ImmedAdditional == intf->InterfaceID)
2993                 if (ResourceRecordIsValidAnswer(rr))
2994                 {
2995                     // If we have at least one answer already in the packet, then plan to add additionals too
2996                     mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2997 
2998                     // If we're not planning to send any additionals, but this record is a unique one, then
2999                     // make sure we haven't already sent any other members of its RRSet -- if we have, then they
3000                     // will have had the cache flush bit set, so now we need to finish the job and send the rest.
3001                     if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
3002                     {
3003                         const AuthRecord *a;
3004                         for (a = m->ResourceRecords; a; a=a->next)
3005                             if (a->LastMCTime      == m->timenow &&
3006                                 a->LastMCInterface == intf->InterfaceID &&
3007                                 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
3008                     }
3009                     if (!SendAdditional)                    // If we don't want to send this after all,
3010                         rr->ImmedAdditional = mDNSNULL;     // then cancel its ImmedAdditional field
3011                     else if (newptr)                        // Else, try to add it if we can
3012                     {
3013                         // The first time through (pktcount==0), if this record is verified unique
3014                         // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
3015                         if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
3016                             rr->SendNSECNow = mDNSInterfaceMark;
3017 
3018                         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
3019                             rr->resrec.rrclass |= kDNSClass_UniqueRRSet;    // Temporarily set the cache flush bit so PutResourceRecord will set it
3020                         newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
3021                         rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;       // Make sure to clear cache flush bit back to normal state
3022                         if (newptr)
3023                         {
3024                             responseptr = newptr;
3025                             rr->ImmedAdditional = mDNSNULL;
3026                             rr->RequireGoodbye = mDNStrue;
3027                             // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
3028                             // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
3029                             // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
3030                             // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
3031                             rr->LastMCTime      = m->timenow;
3032                             rr->LastMCInterface = intf->InterfaceID;
3033                         }
3034                     }
3035                 }
3036 
3037         // Third Pass. Add NSEC records, if there's space.
3038         // When we're generating an NSEC record in response to a specify query for that type
3039         // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
3040         // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
3041         for (rr = m->ResourceRecords; rr; rr=rr->next)
3042             if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
3043             {
3044                 AuthRecord nsec;
3045                 mDNSu8 *ptr;
3046                 int len;
3047                 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3048                 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
3049                 AssignDomainName(&nsec.namestorage, rr->resrec.name);
3050                 ptr = nsec.rdatastorage.u.data;
3051                 len = DomainNameLength(rr->resrec.name);
3052                 // We have a nxt name followed by window number, window length and a window bitmap
3053                 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
3054                 if (nsec.resrec.rdlength <= StandardAuthRDSize)
3055                 {
3056                     mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
3057                     AssignDomainName((domainname *)ptr, rr->resrec.name);
3058                     ptr += len;
3059                     *ptr++ = 0; // window number
3060                     *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
3061                     for (r2 = m->ResourceRecords; r2; r2=r2->next)
3062                         if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
3063                         {
3064                             if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
3065                             else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
3066                         }
3067                     newptr = responseptr;
3068                     if (!r2)    // If we successfully built our NSEC record, add it to the packet now
3069                     {
3070                         newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
3071                         if (newptr) responseptr = newptr;
3072                     }
3073                 }
3074                 else LogMsg("SendResponses: not enough space (%d)  in authrecord for nsec", nsec.resrec.rdlength);
3075 
3076                 // If we successfully put the NSEC record, clear the SendNSECNow flag
3077                 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
3078                 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
3079                 {
3080                     rr->SendNSECNow = mDNSNULL;
3081                     // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
3082                     for (r2 = rr->next; r2; r2=r2->next)
3083                         if (SameResourceRecordNameClassInterface(r2, rr))
3084                             if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
3085                                 r2->SendNSECNow = mDNSNULL;
3086                 }
3087             }
3088 
3089         if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
3090         {
3091             // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3092             if (OwnerRecordSpace || TraceRecordSpace)
3093             {
3094                 AuthRecord opt;
3095                 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3096                 opt.resrec.rrclass    = NormalMaxDNSMessageData;
3097                 opt.resrec.rdlength   = sizeof(rdataOPT);
3098                 opt.resrec.rdestimate = sizeof(rdataOPT);
3099                 if (OwnerRecordSpace && TraceRecordSpace)
3100                 {
3101                     opt.resrec.rdlength   += sizeof(rdataOPT); // Two options in this OPT record
3102                     opt.resrec.rdestimate += sizeof(rdataOPT);
3103                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3104                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3105                 }
3106                 else if (OwnerRecordSpace)
3107                 {
3108                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3109                 }
3110                 else if (TraceRecordSpace)
3111                 {
3112                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
3113                 }
3114                 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
3115                 if (newptr)
3116                 {
3117                     responseptr = newptr;
3118                 }
3119                 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
3120                 {
3121                     LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3122                             m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3123                 }
3124                 else
3125                 {
3126                     LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3127                            m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3128                 }
3129             }
3130 
3131             debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
3132                    numDereg,                 numDereg                 == 1 ? "" : "s",
3133                    numAnnounce,              numAnnounce              == 1 ? "" : "s",
3134                    numAnswer,                numAnswer                == 1 ? "" : "s",
3135                    m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
3136 
3137             if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSfalse);
3138             if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSfalse);
3139             if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3140             if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
3141             // There might be more things to send on this interface, so go around one more time and try again.
3142         }
3143         else    // Nothing more to send on this interface; go to next
3144         {
3145             const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3146             #if MDNS_DEBUGMSGS && 0
3147             const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
3148             debugf(msg, intf, next);
3149             #endif
3150             intf = next;
3151             pktcount = 0;       // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
3152         }
3153     }
3154 
3155     // ***
3156     // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
3157     // ***
3158 
3159     if (m->CurrentRecord)
3160         LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3161     m->CurrentRecord = m->ResourceRecords;
3162     while (m->CurrentRecord)
3163     {
3164         rr = m->CurrentRecord;
3165         m->CurrentRecord = rr->next;
3166 
3167         if (rr->SendRNow)
3168         {
3169             if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
3170                 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
3171                 IIDPrintable(rr->SendRNow), IIDPrintable(rr->resrec.InterfaceID), rr->resrec.RecordType, ARDisplayString(m, rr));
3172             rr->SendRNow = mDNSNULL;
3173         }
3174 
3175         if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
3176         {
3177             if (rr->NewRData) CompleteRDataUpdate(m, rr);   // Update our rdata, clear the NewRData pointer, and return memory to the client
3178 
3179             if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
3180             {
3181                 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
3182                 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr);        // Don't touch rr after this
3183             }
3184             else
3185             {
3186                 rr->ImmedAnswer  = mDNSNULL;
3187                 rr->ImmedUnicast = mDNSfalse;
3188                 rr->v4Requester  = zerov4Addr;
3189                 rr->v6Requester  = zerov6Addr;
3190             }
3191         }
3192     }
3193     verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
3194 }
3195 
3196 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
3197 // so we want to be lazy about how frequently we do it.
3198 // 1. If a cache record is currently referenced by *no* active questions,
3199 //    then we don't mind expiring it up to a minute late (who will know?)
3200 // 2. Else, if a cache record is due for some of its final expiration queries,
3201 //    we'll allow them to be late by up to 2% of the TTL
3202 // 3. Else, if a cache record has completed all its final expiration queries without success,
3203 //    and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
3204 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
3205 //    so allow at most 1/10 second lateness
3206 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
3207 //    (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
3208 #define CacheCheckGracePeriod(CR) (                                                   \
3209         ((CR)->CRActiveQuestion == mDNSNULL            ) ? (60 * mDNSPlatformOneSecond) : \
3210         ((CR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(CR)/50)            : \
3211         ((CR)->resrec.rroriginalttl > 10               ) ? (mDNSPlatformOneSecond)      : \
3212         ((CR)->resrec.rroriginalttl > 0                ) ? (mDNSPlatformOneSecond/10)   : 0)
3213 
3214 #define NextCacheCheckEvent(CR) ((CR)->NextRequiredQuery + CacheCheckGracePeriod(CR))
3215 
3216 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
3217 {
3218     if (m->rrcache_nextcheck[slot] - event > 0)
3219         m->rrcache_nextcheck[slot] = event;
3220     if (m->NextCacheCheck          - event > 0)
3221         m->NextCacheCheck          = event;
3222 }
3223 
3224 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
3225 // rr->TimeRcvd
3226 // rr->resrec.rroriginalttl
3227 // rr->UnansweredQueries
3228 // rr->CRActiveQuestion
3229 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
3230 {
3231     rr->NextRequiredQuery = RRExpireTime(rr);
3232 
3233     // If we have an active question, then see if we want to schedule a refresher query for this record.
3234     // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
3235     if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
3236     {
3237         rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
3238         rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
3239         verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
3240                       (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
3241     }
3242     ScheduleNextCacheCheckTime(m, HashSlotFromNameHash(rr->resrec.namehash), NextCacheCheckEvent(rr));
3243 }
3244 
3245 #define kMinimumReconfirmTime                     ((mDNSu32)mDNSPlatformOneSecond *  5)
3246 #define kDefaultReconfirmTimeForWake              ((mDNSu32)mDNSPlatformOneSecond *  5)
3247 #define kDefaultReconfirmTimeForNoAnswer          ((mDNSu32)mDNSPlatformOneSecond *  5)
3248 
3249 // Delay before restarting questions on a flapping interface.
3250 #define kDefaultQueryDelayTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond *  3)
3251 // After kDefaultQueryDelayTimeForFlappingInterface seconds, allow enough time for up to three queries (0, 1, and 4 seconds)
3252 // plus three seconds for "response delay" before removing the reconfirmed records from the cache.
3253 #define kDefaultReconfirmTimeForFlappingInterface (kDefaultQueryDelayTimeForFlappingInterface + ((mDNSu32)mDNSPlatformOneSecond *  7))
3254 
3255 mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
3256 {
3257     if (interval < kMinimumReconfirmTime)
3258         interval = kMinimumReconfirmTime;
3259     if (interval > 0x10000000)  // Make sure interval doesn't overflow when we multiply by four below
3260         interval = 0x10000000;
3261 
3262     // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
3263     if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
3264     {
3265         // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
3266         // For all the reconfirmations in a given batch, we want to use the same random value
3267         // so that the reconfirmation questions can be grouped into a single query packet
3268         if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(FutureTime);
3269         interval += m->RandomReconfirmDelay % ((interval/3) + 1);
3270         rr->TimeRcvd          = m->timenow - (mDNSs32)interval * 3;
3271         rr->resrec.rroriginalttl     = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
3272         SetNextCacheCheckTimeForRecord(m, rr);
3273     }
3274     debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
3275            RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
3276     return(mStatus_NoError);
3277 }
3278 
3279 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
3280 // It also appends to the list of known answer records that need to be included,
3281 // and updates the forcast for the size of the known answer section.
3282 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr,
3283                                  DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
3284 {
3285     mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3286     mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3287     const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
3288     mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
3289     if (!newptr)
3290     {
3291         debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3292         return(mDNSfalse);
3293     }
3294     else
3295     {
3296         mDNSu32 forecast = *answerforecast;
3297         const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3298         CacheRecord *cr;
3299         CacheRecord **ka = *kalistptrptr;   // Make a working copy of the pointer we're going to update
3300 
3301         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)             // If we have a resource record in our cache,
3302             if (cr->resrec.InterfaceID == q->SendQNow &&                    // received on this interface
3303                 !(cr->resrec.RecordType & kDNSRecordTypeUniqueMask) &&      // which is a shared (i.e. not unique) record type
3304                 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList &&  // which is not already in the known answer list
3305                 cr->resrec.rdlength <= SmallRecordLimit &&                  // which is small enough to sensibly fit in the packet
3306                 SameNameCacheRecordAnswersQuestion(cr, q) &&                // which answers our question
3307                 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow >                // and its half-way-to-expiry time is at least 1 second away
3308                 mDNSPlatformOneSecond)                                      // (also ensures we never include goodbye records with TTL=1)
3309             {
3310                 // We don't want to include unique records in the Known Answer section. The Known Answer section
3311                 // is intended to suppress floods of shared-record replies from many other devices on the network.
3312                 // That concept really does not apply to unique records, and indeed if we do send a query for
3313                 // which we have a unique record already in our cache, then including that unique record as a
3314                 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3315 
3316                 *ka = cr;   // Link this record into our known answer chain
3317                 ka = &cr->NextInKAList;
3318                 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3319                 forecast += 12 + cr->resrec.rdestimate;
3320                 // If we're trying to put more than one question in this packet, and it doesn't fit
3321                 // then undo that last question and try again next time
3322                 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
3323                 {
3324                     query->h.numQuestions--;
3325                     debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3326                            q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions);
3327                     ka = *kalistptrptr;     // Go back to where we started and retract these answer records
3328                     while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
3329                     return(mDNSfalse);      // Return false, so we'll try again in the next packet
3330                 }
3331             }
3332 
3333         // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3334         *queryptr        = newptr;              // Update the packet pointer
3335         *answerforecast  = forecast;            // Update the forecast
3336         *kalistptrptr    = ka;                  // Update the known answer list pointer
3337         if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
3338 
3339         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)             // For every resource record in our cache,
3340             if (cr->resrec.InterfaceID == q->SendQNow &&                    // received on this interface
3341                 cr->NextInKAList == mDNSNULL && ka != &cr->NextInKAList &&  // which is not in the known answer list
3342                 SameNameCacheRecordAnswersQuestion(cr, q))                  // which answers our question
3343             {
3344                 cr->UnansweredQueries++;                                    // indicate that we're expecting a response
3345                 cr->LastUnansweredTime = m->timenow;
3346                 SetNextCacheCheckTimeForRecord(m, cr);
3347             }
3348 
3349         return(mDNStrue);
3350     }
3351 }
3352 
3353 // When we have a query looking for a specified name, but there appear to be no answers with
3354 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3355 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3356 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3357 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3358 // A typical reconfirmation scenario might go like this:
3359 // Depth 0: Name "myhost.local" has no address records
3360 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3361 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3362 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3363 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3364 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3365 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSInterfaceID InterfaceID, const int depth)
3366 {
3367     mDNSu32 slot;
3368     const CacheGroup *cg;
3369     CacheRecord *cr;
3370     debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
3371     if (!InterfaceID) return; // mDNS records have a non-zero InterfaceID. If InterfaceID is 0, then there's nothing to do.
3372     FORALL_CACHERECORDS(slot, cg, cr)
3373     {
3374         const domainname *crtarget;
3375         if (cr->resrec.InterfaceID != InterfaceID) continue; // Skip non-mDNS records and mDNS records from other interfaces.
3376         if (cr->resrec.rdatahash != namehash)      continue; // Skip records whose rdata hash doesn't match the name hash.
3377         crtarget = GetRRDomainNameTarget(&cr->resrec);
3378         if (crtarget && SameDomainName(crtarget, name))
3379         {
3380             LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d, InterfaceID=%p) %s", depth, InterfaceID, CRDisplayString(m, cr));
3381             mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
3382             if (depth < 5)
3383                 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, InterfaceID, depth+1);
3384         }
3385     }
3386 }
3387 
3388 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3389 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3390 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3391 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3392 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
3393 {
3394     CacheGroup *const cg = CacheGroupForName(m, namehash, name);
3395     const CacheRecord *cr = cg ? cg->members : mDNSNULL;
3396     while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
3397     return(cr);
3398 }
3399 
3400 
3401 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
3402 {
3403 #ifndef SPC_DISABLED
3404     CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3405     const CacheRecord *cr, *bestcr = mDNSNULL;
3406     mDNSu32 bestmetric = 1000000;
3407     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
3408         if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6)                      // If record is PTR type, with long enough name,
3409             if (cr != c0 && cr != c1)                                                           // that's not one we've seen before,
3410                 if (SameNameCacheRecordAnswersQuestion(cr, q))                                  // and answers our browse query,
3411                     if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec))    // and is not our own advertised service...
3412                     {
3413                         mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
3414                         if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
3415                     }
3416     return(bestcr);
3417 #else // SPC_DISABLED
3418     (void) m;
3419     (void) q;
3420     (void) c0;
3421     (void) c1;
3422     (void) c1;
3423     return mDNSNULL;
3424 #endif // SPC_DISABLED
3425 }
3426 
3427 mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2)
3428 {
3429     const CacheRecord *swap_sps;
3430     mDNSu32 metric1, metric2;
3431 
3432     if (!(*sps1) || !(*sps2)) return;
3433     metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c);
3434     metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c);
3435     if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1))
3436     {
3437         swap_sps = *sps1;
3438         *sps1    = *sps2;
3439         *sps2    = swap_sps;
3440     }
3441 }
3442 
3443 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
3444 {
3445     CheckAndSwapSPS(&sps[0], &sps[1]);
3446     CheckAndSwapSPS(&sps[0], &sps[2]);
3447     CheckAndSwapSPS(&sps[1], &sps[2]);
3448 }
3449 
3450 
3451 // Finds the three best Sleep Proxies we currently have in our cache
3452 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
3453 {
3454     sps[0] =                      FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
3455     sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   mDNSNULL);
3456     sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   sps[1]);
3457 
3458     // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3459     // only if they have equally good metric and support features.
3460     ReorderSPSByFeature(sps);
3461 }
3462 
3463 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3464 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3465 {
3466     int i;
3467     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3468 }
3469 
3470 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3471 {
3472     int i;
3473     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3474 }
3475 
3476 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3477 {
3478     int i;
3479     mDNSBool v4 = !intf->IPv4Available;     // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3480     mDNSBool v6 = !intf->IPv6Available;     // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3481     for (i=0; i<DupSuppressInfoSize; i++)
3482         if (ds[i].InterfaceID == intf->InterfaceID)
3483         {
3484             if      (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3485             else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3486             if (v4 && v6) return(mDNStrue);
3487         }
3488     return(mDNSfalse);
3489 }
3490 
3491 mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3492 {
3493     int i, j;
3494 
3495     // See if we have this one in our list somewhere already
3496     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3497 
3498     // If not, find a slot we can re-use
3499     if (i >= DupSuppressInfoSize)
3500     {
3501         i = 0;
3502         for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3503             if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3504                 i = j;
3505     }
3506 
3507     // Record the info about this query we saw
3508     ds[i].Time        = Time;
3509     ds[i].InterfaceID = InterfaceID;
3510     ds[i].Type        = Type;
3511 }
3512 
3513 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
3514 {
3515     int len, i, cnt;
3516     mDNSInterfaceID InterfaceID = q->InterfaceID;
3517     domainname *d = &q->qname;
3518 
3519     // We can't send magic packets without knowing which interface to send it on.
3520     if (InterfaceID == mDNSInterface_Any || LocalOnlyOrP2PInterface(InterfaceID))
3521     {
3522         LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
3523         return;
3524     }
3525 
3526     // Split MAC@IPAddress and pass them separately
3527     len = d->c[0];
3528     cnt = 0;
3529     for (i = 1; i < len; i++)
3530     {
3531         if (d->c[i] == '@')
3532         {
3533             char EthAddr[18];   // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3534             char IPAddr[47];    // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3535             if (cnt != 5)
3536             {
3537                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
3538                 return;
3539             }
3540             if ((i - 1) > (int) (sizeof(EthAddr) - 1))
3541             {
3542                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
3543                 return;
3544             }
3545             if ((len - i) > (int)(sizeof(IPAddr) - 1))
3546             {
3547                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
3548                 return;
3549             }
3550             mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
3551             EthAddr[i - 1] = 0;
3552             mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
3553             IPAddr[len - i] = 0;
3554             m->mDNSStats.WakeOnResolves++;
3555             mDNSPlatformSendWakeupPacket(InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
3556             return;
3557         }
3558         else if (d->c[i] == ':')
3559             cnt++;
3560     }
3561     LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
3562 }
3563 
3564 
3565 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3566 {
3567     // If more than 90% of the way to the query time, we should unconditionally accelerate it
3568     if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3569         return(mDNStrue);
3570 
3571     // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3572     if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3573     {
3574         // We forecast: qname (n) type (2) class (2)
3575         mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3576         const CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
3577         const CacheRecord *cr;
3578         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)              // If we have a resource record in our cache,
3579             if (cr->resrec.rdlength <= SmallRecordLimit &&                   // which is small enough to sensibly fit in the packet
3580                 SameNameCacheRecordAnswersQuestion(cr, q) &&                 // which answers our question
3581                 cr->TimeRcvd + TicksTTL(cr)/2 - m->timenow >= 0 &&           // and it is less than half-way to expiry
3582                 cr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
3583             {
3584                 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3585                 forecast += 12 + cr->resrec.rdestimate;
3586                 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3587             }
3588         return(mDNStrue);
3589     }
3590 
3591     return(mDNSfalse);
3592 }
3593 
3594 // How Standard Queries are generated:
3595 // 1. The Question Section contains the question
3596 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3597 
3598 // How Probe Queries are generated:
3599 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3600 // if some other host is already using *any* records with this name, we want to know about it.
3601 // 2. The Authority Section contains the proposed values we intend to use for one or more
3602 // of our records with that name (analogous to the Update section of DNS Update packets)
3603 // because if some other host is probing at the same time, we each want to know what the other is
3604 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3605 
3606 mDNSlocal void SendQueries(mDNS *const m)
3607 {
3608     mDNSu32 slot;
3609     CacheGroup *cg;
3610     CacheRecord *cr;
3611     AuthRecord *ar;
3612     int pktcount = 0;
3613     DNSQuestion *q;
3614     // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3615     mDNSs32 maxExistingQuestionInterval = 0;
3616     const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3617     CacheRecord *KnownAnswerList = mDNSNULL;
3618 
3619     // 1. If time for a query, work out what we need to do
3620 
3621     // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3622     // to their NextRequiredQuery to be worth batching them together with this one
3623     FORALL_CACHERECORDS(slot, cg, cr)
3624     {
3625         if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3626         {
3627             if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3628             {
3629                 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
3630                 q = cr->CRActiveQuestion;
3631                 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
3632                 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3633                 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3634                 if (!mDNSOpaque16IsZero(q->TargetQID))
3635                 {
3636                     q->LastQTime = m->timenow - q->ThisQInterval;
3637                     cr->UnansweredQueries++;
3638                     m->mDNSStats.CacheRefreshQueries++;
3639                 }
3640                 else if (q->SendQNow == mDNSNULL)
3641                 {
3642                     q->SendQNow = cr->resrec.InterfaceID;
3643                 }
3644                 else if (q->SendQNow != cr->resrec.InterfaceID)
3645                 {
3646                     q->SendQNow = mDNSInterfaceMark;
3647                 }
3648 
3649                 // Indicate that this question was marked for sending
3650                 // to update an existing cached answer record.
3651                 // The browse throttling logic below uses this to determine
3652                 // if the query should be sent.
3653                 if (mDNSOpaque16IsZero(q->TargetQID))
3654                     q->CachedAnswerNeedsUpdate = mDNStrue;
3655             }
3656         }
3657     }
3658 
3659     // Scan our list of questions to see which:
3660     //     *WideArea*  queries need to be sent
3661     //     *unicast*   queries need to be sent
3662     //     *multicast* queries we're definitely going to send
3663     if (m->CurrentQuestion)
3664         LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3665     m->CurrentQuestion = m->Questions;
3666     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3667     {
3668         q = m->CurrentQuestion;
3669         if (mDNSOpaque16IsZero(q->TargetQID) && TimeToSendThisQuestion(q, m->timenow))
3670         {
3671             //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3672             q->SendQNow = mDNSInterfaceMark;        // Mark this question for sending on all interfaces
3673             if (maxExistingQuestionInterval < q->ThisQInterval)
3674                 maxExistingQuestionInterval = q->ThisQInterval;
3675         }
3676         // If m->CurrentQuestion wasn't modified out from under us, advance it now
3677         // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3678         // m->CurrentQuestion point to the right question
3679         if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3680     }
3681     while (m->CurrentQuestion)
3682     {
3683         LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3684         m->CurrentQuestion = m->CurrentQuestion->next;
3685     }
3686     m->CurrentQuestion = mDNSNULL;
3687 
3688     // Scan our list of questions
3689     // (a) to see if there are any more that are worth accelerating, and
3690     // (b) to update the state variables for *all* the questions we're going to send
3691     // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3692     // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3693     // 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.
3694     m->NextScheduledQuery = m->timenow + FutureTime;
3695     for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3696     {
3697         if (mDNSOpaque16IsZero(q->TargetQID)
3698             && (q->SendQNow || (ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3699         {
3700             // If at least halfway to next query time, advance to next interval
3701             // If less than halfway to next query time, then
3702             // treat this as logically a repeat of the last transmission, without advancing the interval
3703             if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3704             {
3705                 // If we have reached the answer threshold for this question,
3706                 // don't send it again until MaxQuestionInterval unless:
3707                 //  one of its cached answers needs to be refreshed,
3708                 //  or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3709                 if (q->BrowseThreshold
3710                     && (q->CurrentAnswers >= q->BrowseThreshold)
3711                     && (q->CachedAnswerNeedsUpdate == mDNSfalse)
3712                     && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval)))
3713                 {
3714                     q->SendQNow = mDNSNULL;
3715                     q->ThisQInterval = MaxQuestionInterval;
3716                     q->LastQTime = m->timenow;
3717                     q->RequestUnicast = 0;
3718                     LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3719                          DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
3720                 }
3721                 else
3722                 {
3723                     // Mark this question for sending on all interfaces
3724                     q->SendQNow = mDNSInterfaceMark;
3725                     q->ThisQInterval *= QuestionIntervalStep;
3726                 }
3727 
3728                 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3729                        q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3730 
3731                 if (q->ThisQInterval > MaxQuestionInterval)
3732                 {
3733                     q->ThisQInterval = MaxQuestionInterval;
3734                 }
3735                 else if (mDNSOpaque16IsZero(q->TargetQID) && q->InterfaceID &&
3736                          q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3737                          !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3738                 {
3739                     // Generally don't need to log this.
3740                     // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3741                     // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3742                     // and when there simply happen to be no instances of the service the client is looking
3743                     // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3744                     debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3745                            q->qname.c, DNSTypeName(q->qtype));
3746                     // Sending third query, and no answers yet; time to begin doubting the source
3747                     ReconfirmAntecedents(m, &q->qname, q->qnamehash, q->InterfaceID, 0);
3748                 }
3749             }
3750 
3751             // Mark for sending. (If no active interfaces, then don't even try.)
3752             q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3753             if (q->SendOnAll)
3754             {
3755                 q->SendQNow  = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3756                 q->LastQTime = m->timenow;
3757             }
3758 
3759             // If we recorded a duplicate suppression for this question less than half an interval ago,
3760             // then we consider it recent enough that we don't need to do an identical query ourselves.
3761             ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3762 
3763             q->LastQTxTime      = m->timenow;
3764             q->RecentAnswerPkts = 0;
3765             if (q->RequestUnicast) q->RequestUnicast--;
3766         }
3767         // For all questions (not just the ones we're sending) check what the next scheduled event will be
3768         // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3769         SetNextQueryTime(m,q);
3770     }
3771 
3772     // 2. Scan our authoritative RR list to see what probes we might need to send
3773 
3774     m->NextScheduledProbe = m->timenow + FutureTime;
3775 
3776     if (m->CurrentRecord)
3777         LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3778     m->CurrentRecord = m->ResourceRecords;
3779     while (m->CurrentRecord)
3780     {
3781         ar = m->CurrentRecord;
3782         m->CurrentRecord = ar->next;
3783         if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique)  // For all records that are still probing...
3784         {
3785             // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3786             if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3787             {
3788                 SetNextAnnounceProbeTime(m, ar);
3789             }
3790             // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3791             else if (ar->ProbeCount)
3792             {
3793                 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3794                 {
3795                     // There's a problem here. If a host is waking up, and we probe to see if it responds, then
3796                     // it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3797                     // A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3798                     // (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3799                     // A similar concern may apply to the NDP Probe too. -- SC
3800                     LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3801                     SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3802                 }
3803                 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3804                 {
3805                     LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3806                     // IPv6 source = zero
3807                     // No target hardware address
3808                     // IPv6 target address is address we're probing
3809                     // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3810                     SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3811                 }
3812                 // Mark for sending. (If no active interfaces, then don't even try.)
3813                 ar->SendRNow   = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3814                 ar->LastAPTime = m->timenow;
3815                 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3816                 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3817                 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3818                     ar->ProbeCount = DefaultProbeCountForTypeUnique;
3819                 ar->ProbeCount--;
3820                 SetNextAnnounceProbeTime(m, ar);
3821                 if (ar->ProbeCount == 0)
3822                 {
3823                     // If this is the last probe for this record, then see if we have any matching records
3824                     // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3825                     AuthRecord *r2;
3826                     for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3827                         if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3828                             r2->ProbeCount = 0;
3829                     // ... then acknowledge this record to the client.
3830                     // We do this optimistically, just as we're about to send the third probe.
3831                     // This helps clients that both advertise and browse, and want to filter themselves
3832                     // from the browse results list, because it helps ensure that the registration
3833                     // confirmation will be delivered 1/4 second *before* the browse "add" event.
3834                     // A potential downside is that we could deliver a registration confirmation and then find out
3835                     // moments later that there's a name conflict, but applications have to be prepared to handle
3836                     // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3837                     if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3838                 }
3839             }
3840             // else, if it has now finished probing, move it to state Verified,
3841             // and update m->NextScheduledResponse so it will be announced
3842             else
3843             {
3844                 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);    // Defensive, just in case it got missed somehow
3845                 ar->resrec.RecordType     = kDNSRecordTypeVerified;
3846                 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3847                 ar->LastAPTime     = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3848                 SetNextAnnounceProbeTime(m, ar);
3849             }
3850         }
3851     }
3852     m->CurrentRecord = m->DuplicateRecords;
3853     while (m->CurrentRecord)
3854     {
3855         ar = m->CurrentRecord;
3856         m->CurrentRecord = ar->next;
3857         if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3858             AcknowledgeRecord(m, ar);
3859     }
3860 
3861     // 3. Now we know which queries and probes we're sending,
3862     // go through our interface list sending the appropriate queries on each interface
3863     while (intf)
3864     {
3865         int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3866         int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
3867         mDNSu8 *queryptr = m->omsg.data;
3868         mDNSBool useBackgroundTrafficClass = mDNSfalse;    // set if we should use background traffic class
3869 
3870         InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3871         if (KnownAnswerList) verbosedebugf("SendQueries:   KnownAnswerList set... Will continue from previous packet");
3872         if (!KnownAnswerList)
3873         {
3874             // Start a new known-answer list
3875             CacheRecord **kalistptr = &KnownAnswerList;
3876             mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace;  // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3877 
3878             // Put query questions in this packet
3879             for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3880             {
3881                 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3882                 {
3883                     mDNSBool Suppress = mDNSfalse;
3884                     debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3885                            SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting    ",
3886                            q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3887 
3888                     // If interface is P2P type, verify that query should be sent over it.
3889                     if (!mDNSPlatformValidQuestionForInterface(q, intf))
3890                     {
3891                         q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3892                     }
3893                     // If we're suppressing this question, or we successfully put it, update its SendQNow state
3894                     else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
3895                         BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3896                     {
3897                         if (Suppress)
3898                             m->mDNSStats.DupQuerySuppressions++;
3899 
3900                         q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3901                         if (q->WakeOnResolveCount)
3902                         {
3903                             mDNSSendWakeOnResolve(m, q);
3904                             q->WakeOnResolveCount--;
3905                         }
3906 
3907                         // use background traffic class if any included question requires it
3908                         if (q->UseBackgroundTraffic)
3909                         {
3910                             useBackgroundTrafficClass = mDNStrue;
3911                         }
3912                     }
3913                 }
3914             }
3915 
3916             // Put probe questions in this packet
3917             for (ar = m->ResourceRecords; ar; ar=ar->next)
3918             {
3919                 if (ar->SendRNow != intf->InterfaceID)
3920                     continue;
3921 
3922                 // If interface is a P2P variant, verify that the probe should be sent over it.
3923                 if (!mDNSPlatformValidRecordForInterface(ar, intf->InterfaceID))
3924                 {
3925                     ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3926                     ar->IncludeInProbe = mDNSfalse;
3927                 }
3928                 else
3929                 {
3930                     mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3931                     mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3932                     const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3933                     // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3934                     mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3935                     mDNSBool putProbe = mDNStrue;
3936                     mDNSu16 qclass = ar->resrec.rrclass | ucbit;
3937 
3938                     {// Determine if this probe question is already in packet's dns message
3939                         const mDNSu8 *questionptr = m->omsg.data;
3940                         DNSQuestion question;
3941                         mDNSu16 n;
3942                         for (n = 0; n < m->omsg.h.numQuestions && questionptr; n++)
3943                         {
3944                             questionptr = getQuestion(&m->omsg, questionptr, limit, mDNSInterface_Any, &question);
3945                             if (questionptr && (question.qtype == kDNSQType_ANY) && (question.qclass == qclass) &&
3946                                 (question.qnamehash == ar->resrec.namehash) && SameDomainName(&question.qname, ar->resrec.name))
3947                             {
3948                                 putProbe = mDNSfalse;  // set to false if already in message
3949                                 break;
3950                             }
3951                         }
3952                     }
3953 
3954                     if (putProbe)
3955                     {
3956                         mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, qclass);
3957                         if (newptr)
3958                         {
3959                             queryptr       = newptr;
3960                             answerforecast = forecast;
3961                             ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3962                             ar->IncludeInProbe = mDNStrue;
3963                             verbosedebugf("SendQueries:   Put Question %##s (%s) probecount %d InterfaceID= %d %d %d",
3964                                       ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount, ar->resrec.InterfaceID, ar->resrec.rdestimate, answerforecast);
3965                         }
3966                     }
3967                     else
3968                     {
3969                         ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3970                         ar->IncludeInProbe = mDNStrue;
3971                     }
3972                 }
3973             }
3974         }
3975 
3976         // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3977         while (KnownAnswerList)
3978         {
3979             CacheRecord *ka = KnownAnswerList;
3980             mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3981             mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd,
3982                                                            m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace);
3983             if (newptr)
3984             {
3985                 verbosedebugf("SendQueries:   Put %##s (%s) at %d - %d",
3986                               ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3987                 queryptr = newptr;
3988                 KnownAnswerList = ka->NextInKAList;
3989                 ka->NextInKAList = mDNSNULL;
3990             }
3991             else
3992             {
3993                 // If we ran out of space and we have more than one question in the packet, that's an error --
3994                 // we shouldn't have put more than one question if there was a risk of us running out of space.
3995                 if (m->omsg.h.numQuestions > 1)
3996                     LogMsg("SendQueries:   Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3997                 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3998                 break;
3999             }
4000         }
4001 
4002         for (ar = m->ResourceRecords; ar; ar=ar->next)
4003         {
4004             if (ar->IncludeInProbe)
4005             {
4006                 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
4007                 ar->IncludeInProbe = mDNSfalse;
4008                 if (newptr) queryptr = newptr;
4009                 else LogMsg("SendQueries:   How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
4010             }
4011         }
4012 
4013         if (queryptr > m->omsg.data)
4014         {
4015             // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
4016             if (OwnerRecordSpace || TraceRecordSpace)
4017             {
4018                 AuthRecord opt;
4019                 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
4020                 opt.resrec.rrclass    = NormalMaxDNSMessageData;
4021                 opt.resrec.rdlength   = sizeof(rdataOPT);
4022                 opt.resrec.rdestimate = sizeof(rdataOPT);
4023                 if (OwnerRecordSpace && TraceRecordSpace)
4024                 {
4025                     opt.resrec.rdlength   += sizeof(rdataOPT);  // Two options in this OPT record
4026                     opt.resrec.rdestimate += sizeof(rdataOPT);
4027                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
4028                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
4029                 }
4030                 else if (OwnerRecordSpace)
4031                 {
4032                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
4033                 }
4034                 else if (TraceRecordSpace)
4035                 {
4036                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
4037                 }
4038                 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
4039                                                          &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
4040                 if (!queryptr)
4041                 {
4042                     LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
4043                            m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
4044                 }
4045                 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
4046                 {
4047                     if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
4048                         LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "",
4049                                 TraceRecordSpace ? "TRACER" : "", m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, m->omsg.h.numAnswers,
4050                                 m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
4051                 }
4052             }
4053 
4054             if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
4055                 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
4056             debugf("SendQueries:   Sending %d Question%s %d Answer%s %d Update%s on %d (%s)",
4057                    m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
4058                    m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
4059                    m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", IIDPrintable(intf->InterfaceID), intf->ifname);
4060             if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass);
4061             if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, useBackgroundTrafficClass);
4062             if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
4063             if (++pktcount >= 1000)
4064             { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
4065             // There might be more records left in the known answer list, or more questions to send
4066             // on this interface, so go around one more time and try again.
4067         }
4068         else    // Nothing more to send on this interface; go to next
4069         {
4070             const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
4071             #if MDNS_DEBUGMSGS && 0
4072             const char *const msg = next ? "SendQueries:   Nothing more on %p; moving to %p" : "SendQueries:   Nothing more on %p";
4073             debugf(msg, intf, next);
4074             #endif
4075             intf = next;
4076         }
4077     }
4078 
4079     // 4. Final housekeeping
4080 
4081     // 4a. Debugging check: Make sure we announced all our records
4082     for (ar = m->ResourceRecords; ar; ar=ar->next)
4083         if (ar->SendRNow)
4084         {
4085             if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
4086                 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
4087                         IIDPrintable(ar->SendRNow), IIDPrintable(ar->resrec.InterfaceID), ARDisplayString(m, ar));
4088             ar->SendRNow = mDNSNULL;
4089         }
4090 
4091     // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
4092     // that their interface which went away might come back again, the logic will want to send queries
4093     // for those records, but we can't because their interface isn't here any more, so to keep the
4094     // state machine ticking over we just pretend we did so.
4095     // If the interface does not come back in time, the cache record will expire naturally
4096     FORALL_CACHERECORDS(slot, cg, cr)
4097     {
4098         if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
4099         {
4100             if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
4101             {
4102                 cr->UnansweredQueries++;
4103                 cr->CRActiveQuestion->SendQNow = mDNSNULL;
4104                 SetNextCacheCheckTimeForRecord(m, cr);
4105             }
4106         }
4107     }
4108 
4109     // 4c. Debugging check: Make sure we sent all our planned questions
4110     // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
4111     // we legitimately couldn't send because the interface is no longer available
4112     for (q = m->Questions; q; q=q->next)
4113     {
4114         if (q->SendQNow)
4115         {
4116             DNSQuestion *x;
4117             for (x = m->NewQuestions; x; x=x->next) if (x == q) break;  // Check if this question is a NewQuestion
4118             // There will not be an active interface for questions applied to mDNSInterface_BLE
4119             // so don't log the warning in that case.
4120             if (q->InterfaceID != mDNSInterface_BLE)
4121                 LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
4122                         IIDPrintable(q->SendQNow), x ? "new" : "old", IIDPrintable(q->InterfaceID), q->qname.c, DNSTypeName(q->qtype));
4123             q->SendQNow = mDNSNULL;
4124         }
4125         q->CachedAnswerNeedsUpdate = mDNSfalse;
4126     }
4127 }
4128 
4129 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password, mDNSBool unicastOnly)
4130 {
4131     int i, j;
4132 
4133     mDNSu8 *ptr = m->omsg.data;
4134     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
4135     if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
4136 
4137     // 0x00 Destination address
4138     for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4139 
4140     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
4141     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
4142 
4143     // 0x0C Ethertype (0x0842)
4144     *ptr++ = 0x08;
4145     *ptr++ = 0x42;
4146 
4147     // 0x0E Wakeup sync sequence
4148     for (i=0; i<6; i++) *ptr++ = 0xFF;
4149 
4150     // 0x14 Wakeup data
4151     for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
4152 
4153     // 0x74 Password
4154     for (i=0; i<6; i++) *ptr++ = password->b[i];
4155 
4156     mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4157 
4158     if (!unicastOnly)
4159     {
4160         // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
4161         // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
4162         // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
4163         // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
4164         // So, we send one of each, unicast first, then broadcast second.
4165         for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
4166         mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
4167     }
4168 }
4169 
4170 // ***************************************************************************
4171 #if COMPILER_LIKES_PRAGMA_MARK
4172 #pragma mark -
4173 #pragma mark - RR List Management & Task Management
4174 #endif
4175 
4176 // Whenever a question is answered, reset its state so that we don't query
4177 // the network repeatedly. This happens first time when we answer the question and
4178 // and later when we refresh the cache.
4179 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
4180 {
4181     q->LastQTime        = m->timenow;
4182     q->LastQTxTime      = m->timenow;
4183     q->RecentAnswerPkts = 0;
4184     q->ThisQInterval    = MaxQuestionInterval;
4185     q->RequestUnicast   = 0;
4186 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4187     // Reset unansweredQueries so that we don't penalize this server later when we
4188     // start sending queries when the cache expires.
4189     q->unansweredQueries = 0;
4190 #endif
4191     debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4192 }
4193 
4194 mDNSlocal void AdjustUnansweredQueries(mDNS *const m, CacheRecord *const rr)
4195 {
4196     const mDNSs32 expireTime = RRExpireTime(rr);
4197     const mDNSu32 interval = TicksTTL(rr) / 20; // Calculate 5% of the cache record's TTL.
4198     mDNSu32 rem;
4199 
4200     // If the record is expired or UnansweredQueries is already at the max, then return early.
4201     if (((m->timenow - expireTime) >= 0) || (rr->UnansweredQueries >= MaxUnansweredQueries)) return;
4202 
4203     if (interval == 0)
4204     {
4205         LogInfo("AdjustUnansweredQueries: WARNING: unusually small TTL (%d ticks) for %s", TicksTTL(rr), CRDisplayString(m, rr));
4206         return;
4207     }
4208 
4209     // Calculate the number of whole 5% TTL intervals between now and expiration time.
4210     rem = ((mDNSu32)(expireTime - m->timenow)) / interval;
4211 
4212     // Calculate the expected number of remaining refresher queries.
4213     // Refresher queries are sent at the start of the last MaxUnansweredQueries intervals.
4214     if (rem > MaxUnansweredQueries) rem = MaxUnansweredQueries;
4215 
4216     // If the current number of remaining refresher queries is greater than expected, then at least one refresher query time
4217     // was missed. This can happen if the cache record didn't have an active question during any of the times at which
4218     // refresher queries would have been sent if the cache record did have an active question. The cache record's
4219     // UnansweredQueries count needs to be adjusted to avoid a burst of refresher queries being sent in an attempt to make up
4220     // for lost time. UnansweredQueries is set to the number of queries that would have been sent had the cache record had an
4221     // active question from the 80% point of its lifetime up to now, with one exception: if the number of expected remaining
4222     // refresher queries is zero (because timenow is beyond the 95% point), then UnansweredQueries is set to
4223     // MaxUnansweredQueries - 1 so that at least one refresher query is sent before the cache record expires.
4224 	// Note: The cast is safe because rem is never greater than MaxUnansweredQueries; the comparison has to be signed.
4225     if ((MaxUnansweredQueries - rr->UnansweredQueries) > (mDNSs32)rem)
4226     {
4227         if (rem == 0) rem++;
4228         rr->UnansweredQueries = (mDNSu8)(MaxUnansweredQueries - rem);
4229     }
4230 }
4231 
4232 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
4233 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
4234 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
4235 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
4236 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
4237 {
4238     DNSQuestion *const q = m->CurrentQuestion;
4239     const mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
4240 
4241     verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s (%s) TTL %d %s",
4242                   q->CurrentAnswers, AddRecord ? "Add" : "Rmv", MortalityDisplayString(rr->resrec.mortality),
4243                   rr->resrec.rroriginalttl, CRDisplayString(m, rr));
4244 
4245     // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
4246     // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
4247     // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
4248     // we check to see if that query already has a unique local answer.
4249     if (q->LOAddressAnswers)
4250     {
4251         LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
4252                 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
4253                 q->LOAddressAnswers);
4254         return;
4255     }
4256 
4257     if (q->Suppressed && (AddRecord != QC_suppressed))
4258     {
4259         // If the query is suppressed, then we don't want to answer from the cache. But if this query is
4260         // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
4261         // that are timing out, which we know are answered with negative cache record when timing out.
4262         if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
4263             return;
4264     }
4265 
4266     //  Set the record to immortal if appropriate
4267     if (AddRecord == QC_add && Question_uDNS(q) && rr->resrec.RecordType != kDNSRecordTypePacketNegative &&
4268         q->allowExpired != AllowExpired_None && rr->resrec.mortality == Mortality_Mortal ) rr->resrec.mortality = Mortality_Immortal; // Update a non-expired cache record to immortal if appropriate
4269 
4270 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
4271     if ((AddRecord == QC_add) && Question_uDNS(q) && !followcname && !q->metrics.answered)
4272     {
4273         mDNSBool skipUpdate = mDNSfalse;
4274 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4275         if (!q->dnsservice || (mdns_dns_service_get_resolver_type(q->dnsservice) != mdns_resolver_type_normal))
4276         {
4277             skipUpdate = mDNStrue;
4278         }
4279 #endif
4280         if (!skipUpdate)
4281         {
4282             const domainname *  queryName;
4283             mDNSu32             responseLatencyMs, querySendCount;
4284             mDNSBool            isForCellular;
4285 
4286             queryName = q->metrics.originalQName ? q->metrics.originalQName : &q->qname;
4287             querySendCount = q->metrics.querySendCount;
4288 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4289             if (q->querier)
4290             {
4291                 querySendCount += mdns_querier_get_send_count(q->querier);
4292             }
4293             isForCellular = mdns_dns_service_interface_is_cellular(q->dnsservice);
4294 #else
4295             isForCellular = (q->qDNSServer && q->qDNSServer->isCell);
4296 #endif
4297             if (q->metrics.querySendCount > 0)
4298             {
4299                 responseLatencyMs = ((m->timenow - q->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
4300             }
4301             else
4302             {
4303                 responseLatencyMs = 0;
4304             }
4305             MetricsUpdateDNSQueryStats(queryName, q->qtype, &rr->resrec, querySendCount, q->metrics.expiredAnswerState,
4306                 q->metrics.dnsOverTCPState, responseLatencyMs, isForCellular);
4307         }
4308         q->metrics.answered = mDNStrue;
4309     }
4310 #endif
4311     // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
4312     // may be called twice, once when the record is received, and again when it's time to notify local clients.
4313     // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
4314 
4315     if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q && rr->resrec.mortality != Mortality_Ghost)
4316     {
4317         debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
4318                rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
4319         if (!rr->CRActiveQuestion)
4320         {
4321             m->rrcache_active++;            // If not previously active, increment rrcache_active count
4322             AdjustUnansweredQueries(m, rr); // Adjust UnansweredQueries in case the record missed out on refresher queries
4323         }
4324         rr->CRActiveQuestion = q;           // We know q is non-null
4325         SetNextCacheCheckTimeForRecord(m, rr);
4326     }
4327 
4328     // If this is:
4329     // (a) a no-cache add, where we've already done at least one 'QM' query, or
4330     // (b) a normal add, where we have at least one unique-type answer,
4331     // then there's no need to keep polling the network.
4332     // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
4333     // We do this for mDNS questions and uDNS one-shot questions, but not for
4334     // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
4335     if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
4336         (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
4337         if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
4338         {
4339             ResetQuestionState(m, q);
4340         }
4341 
4342     if (rr->DelayDelivery) return;      // We'll come back later when CacheRecordDeferredAdd() calls us
4343 
4344 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4345     // If DNS64StateMachine() returns true, then the question was restarted as a different question, so return.
4346     if (!mDNSOpaque16IsZero(q->TargetQID) && DNS64StateMachine(m, q, &rr->resrec, AddRecord)) return;
4347 #endif
4348 
4349 #ifdef USE_LIBIDN
4350     if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)  // If negative answer, check if we need to try Punycode conversion
4351     {
4352         domainname newname;
4353         if (PerformNextPunycodeConversion(q, &newname))         // Itertative Punycode conversion succeeded, so reissue question with new name
4354         {
4355             UDPSocket *const sock = q->LocalSocket;             // Save old socket and transaction ID
4356             const mDNSOpaque16 id = q->TargetQID;
4357             q->LocalSocket = mDNSNULL;
4358             mDNS_StopQuery_internal(m, q);                      // Stop old query
4359             AssignDomainName(&q->qname, &newname);              // Update qname
4360             q->qnamehash = DomainNameHashValue(&q->qname);      // and namehash
4361             mDNS_StartQuery_internal(m, q);                     // Start new query
4362 
4363             if (sock)                                           // Transplant saved socket, if appropriate
4364             {
4365                 if (q->DuplicateOf) mDNSPlatformUDPClose(sock);
4366                 else { q->LocalSocket = sock; q->TargetQID = id; }
4367             }
4368             return;                                             // All done for now; wait until we get the next answer
4369         }
4370     }
4371 #endif // USE_LIBIDN
4372 
4373     // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4374     // for the purpose of retrying search domains/timeout OR the question is suppressed
4375     if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
4376         if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
4377 
4378     // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4379     if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
4380     {
4381         mDNS_DropLockBeforeCallback();      // Allow client (and us) to legally make mDNS API calls
4382         if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
4383         {
4384             if (mDNSOpaque16IsZero(q->TargetQID))
4385             {
4386                 CacheRecord neg;
4387             #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4388                 mDNSPlatformMemZero(&neg, sizeof(neg));
4389                 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->dnsservice);
4390             #else
4391                 MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
4392             #endif
4393                 q->QuestionCallback(m, q, &neg.resrec, AddRecord);
4394             }
4395         }
4396         else
4397         {
4398 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4399             if (DNS64ShouldAnswerQuestion(q, &rr->resrec))
4400             {
4401                 DNS64AnswerCurrentQuestion(m, &rr->resrec, AddRecord);
4402             }
4403             else
4404 #endif
4405             {
4406 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4407                 get_denial_records_from_negative_cache_to_dnssec_context(q->DNSSECStatus.enable_dnssec,
4408                     q->DNSSECStatus.context, rr);
4409 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4410                 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4411             }
4412         }
4413         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
4414     }
4415     // Note: Proceed with caution after this point because client callback function
4416     // invoked above is allowed to do anything, such as starting/stopping queries
4417     // (including this one itself, or the next or previous query in the linked list),
4418     // registering/deregistering records, starting/stopping NAT traversals, etc.
4419 
4420     if (m->CurrentQuestion == q)
4421     {
4422         // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4423         // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4424         // first before following it
4425         if (followcname)  AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
4426 
4427         // If we are returning expired RRs, then remember the first expired qname we we can start the query again
4428         if (rr->resrec.mortality == Mortality_Ghost && !q->firstExpiredQname.c[0] && (q->allowExpired == AllowExpired_AllowExpiredAnswers) && rr->resrec.RecordType != kDNSRecordTypePacketNegative)
4429         {
4430             debugf("AnswerCurrentQuestionWithResourceRecord: Keeping track of domain for expired RR %s for question %p", CRDisplayString(m,rr), q);
4431             // Note: question->qname is already changed at this point if following a CNAME
4432             AssignDomainName(&q->firstExpiredQname, rr->resrec.name);           // Update firstExpiredQname
4433         }
4434     }
4435 }
4436 
4437 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *cr)
4438 {
4439     cr->DelayDelivery = 0;
4440     if (m->CurrentQuestion)
4441         LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4442                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4443     m->CurrentQuestion = m->Questions;
4444     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4445     {
4446         DNSQuestion *q = m->CurrentQuestion;
4447         if (CacheRecordAnswersQuestion(cr, q))
4448             AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
4449         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4450             m->CurrentQuestion = q->next;
4451     }
4452     m->CurrentQuestion = mDNSNULL;
4453 }
4454 
4455 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
4456 {
4457     const mDNSs32 threshold = m->timenow + mDNSPlatformOneSecond;  // See if there are any records expiring within one second
4458     const mDNSs32 start      = m->timenow - 0x10000000;
4459     mDNSs32 delay = start;
4460     CacheGroup *cg = CacheGroupForName(m, namehash, name);
4461     const CacheRecord *rr;
4462 
4463     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4464     {
4465         if (threshold - RRExpireTime(rr) >= 0)     // If we have records about to expire within a second
4466         {
4467             if (delay - RRExpireTime(rr) < 0)       // then delay until after they've been deleted
4468                 delay = RRExpireTime(rr);
4469         }
4470     }
4471     if (delay - start > 0)
4472         return(NonZeroTime(delay));
4473     else
4474         return(0);
4475 }
4476 
4477 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4478 // If new questions are created as a result of invoking client callbacks, they will be added to
4479 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4480 // rr is a new CacheRecord just received into our cache
4481 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4482 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4483 // which may change the record list and/or question list.
4484 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4485 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *cr)
4486 {
4487     DNSQuestion *q;
4488 
4489     // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4490     // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4491     for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4492     {
4493         if (CacheRecordAnswersQuestion(cr, q))
4494         {
4495 	    mDNSIPPort zp = zeroIPPort;
4496             // If this question is one that's actively sending queries, and it's received ten answers within one
4497             // second of sending the last query packet, then that indicates some radical network topology change,
4498             // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4499             // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4500             // because we will anyway send another query within a few seconds. The first reset query is sent out
4501             // randomized over the next four seconds to reduce possible synchronization between machines.
4502             if (q->LastAnswerPktNum != m->PktNum)
4503             {
4504                 q->LastAnswerPktNum = m->PktNum;
4505                 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
4506                     q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4507                 {
4508                     LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4509                            q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
4510                     q->LastQTime      = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4511                     q->ThisQInterval  = InitialQuestionInterval;
4512                     SetNextQueryTime(m,q);
4513                 }
4514             }
4515             verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", cr, cr->resrec.name->c,
4516                           DNSTypeName(cr->resrec.rrtype), cr->resrec.rroriginalttl, cr->resrec.rDNSServer ?
4517                           &cr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(cr->resrec.rDNSServer ?
4518                                                                              cr->resrec.rDNSServer->port : zeroIPPort), q);
4519             q->CurrentAnswers++;
4520 
4521 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4522             q->unansweredQueries = 0;
4523 #endif
4524             if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4525             if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4526             if (q->CurrentAnswers > 4000)
4527             {
4528                 static int msgcount = 0;
4529                 if (msgcount++ < 10)
4530                     LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4531                            q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
4532                 cr->resrec.rroriginalttl = 0;
4533                 cr->UnansweredQueries = MaxUnansweredQueries;
4534             }
4535         }
4536     }
4537 
4538     if (!cr->DelayDelivery)
4539     {
4540         if (m->CurrentQuestion)
4541             LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4542         m->CurrentQuestion = m->Questions;
4543         while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4544         {
4545             q = m->CurrentQuestion;
4546             if (CacheRecordAnswersQuestion(cr, q))
4547                 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
4548             if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4549                 m->CurrentQuestion = q->next;
4550         }
4551         m->CurrentQuestion = mDNSNULL;
4552     }
4553 
4554     SetNextCacheCheckTimeForRecord(m, cr);
4555 }
4556 
4557 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4558 // If new questions are created as a result of invoking client callbacks, they will be added to
4559 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4560 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4561 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4562 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4563 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4564 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4565 // which may change the record list and/or question list.
4566 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4567 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *cr)
4568 {
4569     LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
4570     if (m->CurrentQuestion)
4571         LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4572     m->CurrentQuestion = m->Questions;
4573     // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4574     // since we're not caching the record and we'll get no opportunity to do this later
4575     while (m->CurrentQuestion)
4576     {
4577         DNSQuestion *q = m->CurrentQuestion;
4578         if (CacheRecordAnswersQuestion(cr, q))
4579             AnswerCurrentQuestionWithResourceRecord(m, cr, QC_addnocache);  // QC_addnocache means "don't expect remove events for this"
4580         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4581             m->CurrentQuestion = q->next;
4582     }
4583     m->CurrentQuestion = mDNSNULL;
4584 }
4585 
4586 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4587 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4588 // If new questions are created as a result of invoking client callbacks, they will be added to
4589 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4590 // cr is an existing cache CacheRecord that just expired and is being deleted
4591 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4592 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4593 // which may change the record list and/or question list.
4594 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4595 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *cr)
4596 {
4597     if (m->CurrentQuestion)
4598         LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4599                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4600     m->CurrentQuestion = m->Questions;
4601 
4602     // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4603     // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4604     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4605     {
4606         DNSQuestion *q = m->CurrentQuestion;
4607         // When a question enters suppressed state, we generate RMV events and generate a negative
4608         // response. A cache may be present that answers this question e.g., cache entry generated
4609         // before the question became suppressed. We need to skip the suppressed questions here as
4610         // the RMV event has already been generated.
4611         if (!q->Suppressed && CacheRecordAnswersQuestion(cr, q) &&
4612             (q->allowExpired == AllowExpired_None || cr->resrec.mortality == Mortality_Mortal))
4613         {
4614             verbosedebugf("CacheRecordRmv %p %s", cr, CRDisplayString(m, cr));
4615             q->FlappingInterface1 = mDNSNULL;
4616             q->FlappingInterface2 = mDNSNULL;
4617 
4618             if (q->CurrentAnswers == 0)
4619             {
4620 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4621                 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4622                        q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
4623                        mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zeroIPPort));
4624 #endif
4625             }
4626             else
4627             {
4628                 q->CurrentAnswers--;
4629                 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4630                 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4631             }
4632 
4633             // If we have dropped below the answer threshold for this mDNS question,
4634             // restart the queries at InitialQuestionInterval.
4635             if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold))
4636             {
4637                 q->ThisQInterval = InitialQuestionInterval;
4638                 q->LastQTime     = m->timenow - q->ThisQInterval;
4639                 SetNextQueryTime(m,q);
4640                 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4641                     DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
4642             }
4643             if (cr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
4644             {
4645                 if ((q->CurrentAnswers == 0) && mDNSOpaque16IsZero(q->TargetQID))
4646                 {
4647                     LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4648                             q->qname.c, DNSTypeName(q->qtype));
4649                     ReconfirmAntecedents(m, &q->qname, q->qnamehash, cr->resrec.InterfaceID, 0);
4650                 }
4651                 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv);
4652             }
4653         }
4654         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4655             m->CurrentQuestion = q->next;
4656     }
4657     m->CurrentQuestion = mDNSNULL;
4658 }
4659 
4660 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
4661 {
4662 #if MDNS_MALLOC_DEBUGGING >= 1
4663     unsigned int i;
4664     for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
4665 #endif
4666     e->next = m->rrcache_free;
4667     m->rrcache_free = e;
4668     m->rrcache_totalused--;
4669 }
4670 
4671 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
4672 {
4673     CacheEntity *e = (CacheEntity *)(*cp);
4674     //LogMsg("ReleaseCacheGroup:  Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4675     if ((*cp)->rrcache_tail != &(*cp)->members)
4676         LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4677     //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4678     //  LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4679     if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
4680     (*cp)->name = mDNSNULL;
4681     *cp = (*cp)->next;          // Cut record from list
4682     ReleaseCacheEntity(m, e);
4683 }
4684 
4685 mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp)
4686 {
4687     while (*rp)
4688     {
4689         CacheRecord *rr = *rp;
4690         *rp = (*rp)->next;          // Cut record from list
4691         if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
4692         {
4693             mDNSPlatformMemFree(rr->resrec.rdata);
4694             rr->resrec.rdata = mDNSNULL;
4695         }
4696         // NSEC or SOA records that are not added to the CacheGroup do not share the name
4697         // of the CacheGroup.
4698         if (rr->resrec.name)
4699         {
4700             debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
4701             mDNSPlatformMemFree((void *)rr->resrec.name);
4702             rr->resrec.name = mDNSNULL;
4703         }
4704         // Don't count the NSEC3 records used by anonymous browse/reg
4705         if (!rr->resrec.InterfaceID)
4706         {
4707             m->rrcache_totalused_unicast -= rr->resrec.rdlength;
4708         }
4709         ReleaseCacheEntity(m, (CacheEntity *)rr);
4710     }
4711 }
4712 
4713 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
4714 {
4715     CacheGroup *cg;
4716 
4717     //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4718     if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
4719     r->resrec.rdata = mDNSNULL;
4720 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
4721     mdns_forget(&r->resrec.dnsservice);
4722 #endif
4723 
4724 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
4725     release_denial_records_in_cache_record(r);
4726 #endif
4727 
4728     cg = CacheGroupForRecord(m, &r->resrec);
4729 
4730     if (!cg)
4731     {
4732         // It is okay to have this printed for NSEC/NSEC3s
4733         LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4734     }
4735     // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4736     // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4737     // (which is handled below) and in that case it should be freed here.
4738     if (r->resrec.name && cg && r->resrec.name != cg->name)
4739     {
4740         debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4741         mDNSPlatformMemFree((void *)r->resrec.name);
4742     }
4743     r->resrec.name = mDNSNULL;
4744 
4745     if (!r->resrec.InterfaceID)
4746     {
4747         m->rrcache_totalused_unicast -= r->resrec.rdlength;
4748     }
4749 
4750     ReleaseAdditionalCacheRecords(m, &r->soa);
4751 
4752     ReleaseCacheEntity(m, (CacheEntity *)r);
4753 }
4754 
4755 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4756 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4757 // callbacks for old records are delivered before callbacks for newer records.
4758 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
4759 {
4760     CacheRecord **rp = &cg->members;
4761 
4762     if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4763     m->lock_rrcache = 1;
4764 
4765     while (*rp)
4766     {
4767         CacheRecord *const rr = *rp;
4768         mDNSBool recordReleased = mDNSfalse;
4769         mDNSs32 event = RRExpireTime(rr);
4770         if (m->timenow - event >= 0)    // If expired, delete it
4771         {
4772             if (rr->CRActiveQuestion)   // If this record has one or more active questions, tell them it's going away
4773             {
4774                 DNSQuestion *q = rr->CRActiveQuestion;
4775                 verbosedebugf("CheckCacheExpiration: Removing%7d %7d %p %s",
4776                               m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4777                 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4778                 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4779                 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4780                 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4781                 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4782                 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4783                 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4784                 if (((mDNSOpaque16IsZero(q->TargetQID) && (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)) ||
4785                      (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived)) && ActiveQuestion(q))
4786                 {
4787                     q->ThisQInterval = InitialQuestionInterval;
4788                     q->LastQTime     = m->timenow - q->ThisQInterval;
4789                     SetNextQueryTime(m, q);
4790                 }
4791                 CacheRecordRmv(m, rr);
4792                 m->rrcache_active--;
4793             }
4794 
4795             event += MAX_GHOST_TIME;                                                    // Adjust so we can check for a ghost expiration
4796             if (rr->resrec.mortality == Mortality_Mortal ||                             // Normal expired mortal record that needs released
4797                 rr->resrec.rroriginalttl == 0            ||                             // Non-mortal record that is set to be purged
4798                 (rr->resrec.mortality == Mortality_Ghost && m->timenow - event >= 0))   // A ghost record that expired more than MAX_GHOST_TIME ago
4799             {   //  Release as normal
4800                 *rp = rr->next;                                     // Cut it from the list before ReleaseCacheRecord
4801                 verbosedebugf("CheckCacheExpiration: Deleting (%s)%7d %7d %p %s",
4802                               MortalityDisplayString(rr->resrec.mortality),
4803                               m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4804                 ReleaseCacheRecord(m, rr);
4805                 recordReleased = mDNStrue;
4806             }
4807             else                                                    // An immortal record needs to become a ghost when it expires
4808             {   // Don't release this entry
4809                 if (rr->resrec.mortality == Mortality_Immortal)
4810                 {
4811                     rr->resrec.mortality = Mortality_Ghost;         // Expired immortal records become ghosts
4812                     verbosedebugf("CheckCacheExpiration: NOT Deleting (%s)%7d %7d %p %s",
4813                                   MortalityDisplayString(rr->resrec.mortality),
4814                                   m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4815                 }
4816             }
4817         }
4818         else                                                        // else, not expired; see if we need to query
4819         {
4820             // If waiting to delay delivery, do nothing until then
4821             if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
4822                 event = rr->DelayDelivery;
4823             else
4824             {
4825                 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
4826                 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4827                 {
4828                     if (m->timenow - rr->NextRequiredQuery < 0)     // If not yet time for next query
4829                         event = NextCacheCheckEvent(rr);            // then just record when we want the next query
4830                     else                                            // else trigger our question to go out now
4831                     {
4832                         // Set NextScheduledQuery to timenow so that SendQueries() will run.
4833                         // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4834                         m->NextScheduledQuery = m->timenow;
4835                         // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4836                         // which will correctly update m->NextCacheCheck for us.
4837                         event = m->timenow + FutureTime;
4838                     }
4839                 }
4840             }
4841         }
4842 
4843         if (!recordReleased)  //  Schedule if we did not release the record
4844         {
4845             verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4846                           (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
4847             if (m->rrcache_nextcheck[slot] - event > 0)
4848                 m->rrcache_nextcheck[slot] = event;
4849             rp = &rr->next;
4850         }
4851     }
4852     if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
4853     cg->rrcache_tail = rp;
4854     m->lock_rrcache = 0;
4855 }
4856 
4857 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4858 //
4859 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4860 // returns true if there is an answer.
4861 //
4862 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4863 // returns true to indicate the same.
4864 mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly)
4865 {
4866     AuthRecord *lr;
4867     AuthGroup *ag;
4868 
4869     if (m->CurrentRecord)
4870         LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4871 
4872     ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
4873     if (ag)
4874     {
4875         m->CurrentRecord = ag->members;
4876         while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4877         {
4878             AuthRecord *rr = m->CurrentRecord;
4879             m->CurrentRecord = rr->next;
4880             //
4881             // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4882             // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4883             //
4884             // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4885             // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4886             // we handle both mDNSInterface_Any and scoped questions.
4887 
4888             if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && (q->InterfaceID == mDNSInterface_Any || q->InterfaceID == mDNSInterface_BLE)))
4889                 if (LocalOnlyRecordAnswersQuestion(rr, q))
4890                 {
4891                     if (checkOnly)
4892                     {
4893                         LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype),
4894                             ARDisplayString(m, rr));
4895                         m->CurrentRecord = mDNSNULL;
4896                         return mDNStrue;
4897                     }
4898                     AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
4899                     if (m->CurrentQuestion != q)
4900                         break;     // If callback deleted q, then we're finished here
4901                 }
4902         }
4903     }
4904     m->CurrentRecord = mDNSNULL;
4905 
4906     if (m->CurrentQuestion != q)
4907     {
4908         LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4909         return mDNStrue;
4910     }
4911 
4912     if (q->LOAddressAnswers)
4913     {
4914         LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4915                 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4916         return mDNStrue;
4917     }
4918 
4919     // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4920     // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4921     // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4922     // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4923     // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4924     if (ag)
4925     {
4926         lr = ag->NewLocalOnlyRecords;
4927         while (lr)
4928         {
4929             if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4930             {
4931                 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4932                         " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4933                 return mDNStrue;
4934             }
4935             lr = lr->next;
4936         }
4937     }
4938     return mDNSfalse;
4939 }
4940 
4941 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4942 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4943 // DNS requests.
4944 mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q)
4945 {
4946     // If the client did not set the kDNSServiceFlagsReturnIntermediates flag, then don't generate a negative response,
4947     // just deactivate the DNSQuestion.
4948     if (q->ReturnIntermed)
4949     {
4950         GenerateNegativeResponse(m, mDNSInterface_Any, QC_suppressed);
4951     }
4952     else
4953     {
4954         q->ThisQInterval = 0;
4955     }
4956 }
4957 
4958 mDNSlocal void AnswerNewQuestion(mDNS *const m)
4959 {
4960     mDNSBool ShouldQueryImmediately = mDNStrue;
4961     DNSQuestion *const q = m->NewQuestions;     // Grab the question we're going to answer
4962 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
4963     if (!mDNSOpaque16IsZero(q->TargetQID)) DNS64HandleNewQuestion(m, q);
4964 #endif
4965     CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
4966 
4967     verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4968 
4969     if (cg) CheckCacheExpiration(m, HashSlotFromNameHash(q->qnamehash), cg);
4970     if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
4971     m->NewQuestions = q->next;
4972     // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4973     // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4974     //
4975     // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4976     // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4977     // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4978     // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4979     // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4980     // advanced it), that means the question was deleted, so we no longer need to worry about answering
4981     // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4982     // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4983     //
4984     // We can't use the usual m->CurrentQuestion mechanism for this because  CacheRecordDeferredAdd() and
4985     // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4986     // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4987     // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4988 
4989     if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4990     // This should be safe, because calling the client's question callback may cause the
4991     // question list to be modified, but should not ever cause the rrcache list to be modified.
4992     // If the client's question callback deletes the question, then m->CurrentQuestion will
4993     // be advanced, and we'll exit out of the loop
4994     m->lock_rrcache = 1;
4995     if (m->CurrentQuestion) {
4996         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
4997                "[R%d->Q%d] AnswerNewQuestion ERROR m->CurrentQuestion already set: " PRI_DM_NAME " (" PUB_S ")",
4998                m->CurrentQuestion->request_id, mDNSVal16(m->CurrentQuestion->TargetQID),
4999                DM_NAME_PARAM(&m->CurrentQuestion->qname), DNSTypeName(m->CurrentQuestion->qtype));
5000     }
5001 
5002     m->CurrentQuestion = q;     // Indicate which question we're answering, so we'll know if it gets deleted
5003 
5004     if (q->NoAnswer == NoAnswer_Fail)
5005     {
5006         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5007                "[R%d->Q%d] AnswerNewQuestion: NoAnswer_Fail " PRI_DM_NAME " (" PUB_S ")",
5008                q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
5009 
5010 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5011         MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->dnsservice);
5012 #else
5013         MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
5014 #endif
5015         q->NoAnswer = NoAnswer_Normal;      // Temporarily turn off answer suppression
5016         AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
5017         // Don't touch the question if it has been stopped already
5018         if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail;       // Restore NoAnswer state
5019         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
5020     }
5021 
5022     if (m->CurrentQuestion != q)
5023     {
5024         LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
5025         goto exit;
5026     }
5027 
5028     // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
5029     // or P2P record, then we are done.
5030     if (AnswerQuestionWithLORecord(m, q, mDNSfalse))
5031         goto exit;
5032 
5033     // If it is a question trying to validate some response, it already checked the cache for a response. If it still
5034     // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
5035     // the question out.
5036     if (q->Suppressed)
5037     {
5038         AnswerSuppressedQuestion(m, q);
5039     }
5040     else
5041     {
5042         CacheRecord *cr;
5043         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
5044             if (SameNameCacheRecordAnswersQuestion(cr, q))
5045             {
5046                 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
5047                 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - cr->TimeRcvd)) / mDNSPlatformOneSecond;
5048                 mDNSBool IsExpired = (cr->resrec.rroriginalttl <= SecsSinceRcvd);
5049                 if (IsExpired && q->allowExpired != AllowExpired_AllowExpiredAnswers) continue;   // Go to next one in loop
5050 
5051                 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
5052                 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
5053                 if ((cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
5054                     ShouldQueryImmediately = mDNSfalse;
5055                 q->CurrentAnswers++;
5056                 if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
5057                 if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
5058 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
5059                 if (q->metrics.expiredAnswerState == ExpiredAnswer_Allowed) q->metrics.expiredAnswerState = IsExpired ? ExpiredAnswer_AnsweredWithExpired : ExpiredAnswer_AnsweredWithCache;
5060 #endif
5061 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
5062                 cr->LastCachedAnswerTime = m->timenow;
5063                 dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_hit);
5064 #endif
5065                 AnswerCurrentQuestionWithResourceRecord(m, cr, QC_add);
5066                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
5067             }
5068             else if (mDNSOpaque16IsZero(q->TargetQID) && RRTypeIsAddressType(cr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
5069                 ShouldQueryImmediately = mDNSfalse;
5070     }
5071     // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
5072     // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
5073     if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
5074 
5075 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
5076     dnssd_analytics_update_cache_request(mDNSOpaque16IsZero(q->TargetQID) ? CacheRequestType_multicast : CacheRequestType_unicast, CacheState_miss);
5077 #endif
5078     q->InitialCacheMiss  = mDNStrue;                                    // Initial cache check is done, so mark as a miss from now on
5079     if (q->allowExpired == AllowExpired_AllowExpiredAnswers)
5080     {
5081         q->allowExpired = AllowExpired_MakeAnswersImmortal;             // After looking through the cache for an answer, demote to make immortal
5082         if (q->firstExpiredQname.c[0])                                  // If an original query name was saved on an expired answer, start it over in case it is updated
5083         {
5084             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5085                    "[R%d->Q%d] AnswerNewQuestion: Restarting original question %p firstExpiredQname " PRI_DM_NAME " for allowExpiredAnswers question",
5086                    q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->firstExpiredQname));
5087             mDNS_StopQuery_internal(m, q);                              // Stop old query
5088 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5089             if (!SameDomainName(&q->qname, &q->firstExpiredQname))
5090             {
5091                 Querier_PrepareQuestionForUnwindRestart(q);
5092             }
5093 #endif
5094             AssignDomainName(&q->qname, &q->firstExpiredQname);         // Update qname
5095             q->qnamehash = DomainNameHashValue(&q->qname);              // and namehash
5096             mDNS_StartQuery_internal(m, q);                             // start new query
5097             q->CNAMEReferrals = 0;                                      // Reset referral count
5098             q->firstExpiredQname.c[0] = 0;                              // Erase the domain name
5099         }
5100     }
5101 
5102     // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
5103     // Hence we don't execute the following block of code for those cases.
5104     if (ShouldQueryImmediately && ActiveQuestion(q))
5105     {
5106         debugf("[R%d->Q%d] AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->request_id, mDNSVal16(q->TargetQID), q->qname.c, DNSTypeName(q->qtype));
5107         q->ThisQInterval  = InitialQuestionInterval;
5108         q->LastQTime      = m->timenow - q->ThisQInterval;
5109         if (mDNSOpaque16IsZero(q->TargetQID))       // For mDNS, spread packets to avoid a burst of simultaneous queries
5110         {
5111             // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
5112             if (!m->RandomQueryDelay)
5113                 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
5114             q->LastQTime += m->RandomQueryDelay;
5115         }
5116     }
5117 
5118     // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
5119     // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
5120     // answers for this question until *after* its scheduled transmission time, in which case
5121     // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
5122     // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
5123     SetNextQueryTime(m,q);
5124 
5125 exit:
5126     m->CurrentQuestion = mDNSNULL;
5127     m->lock_rrcache = 0;
5128 }
5129 
5130 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
5131 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
5132 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
5133 {
5134     AuthGroup *ag;
5135     DNSQuestion *q = m->NewLocalOnlyQuestions;      // Grab the question we're going to answer
5136     mDNSBool retEv = mDNSfalse;
5137     m->NewLocalOnlyQuestions = q->next;             // Advance NewLocalOnlyQuestions to the next (if any)
5138 
5139     debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5140 
5141     if (m->CurrentQuestion)
5142         LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
5143                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5144     m->CurrentQuestion = q;     // Indicate which question we're answering, so we'll know if it gets deleted
5145 
5146     if (m->CurrentRecord)
5147         LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
5148 
5149     // 1. First walk the LocalOnly records answering the LocalOnly question
5150     // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
5151     //    walk the ResourceRecords list delivering the answers
5152     ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5153     if (ag)
5154     {
5155         m->CurrentRecord = ag->members;
5156         while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
5157         {
5158             AuthRecord *rr = m->CurrentRecord;
5159             m->CurrentRecord = rr->next;
5160             if (LocalOnlyRecordAnswersQuestion(rr, q))
5161             {
5162                 retEv = mDNStrue;
5163                 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
5164                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
5165             }
5166         }
5167     }
5168 
5169     if (m->CurrentQuestion == q)
5170     {
5171         m->CurrentRecord = m->ResourceRecords;
5172 
5173         while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
5174         {
5175             AuthRecord *ar = m->CurrentRecord;
5176             m->CurrentRecord = ar->next;
5177             if (AuthRecordAnswersQuestion(ar, q))
5178             {
5179                 retEv = mDNStrue;
5180                 AnswerLocalQuestionWithLocalAuthRecord(m, ar, QC_add);
5181                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
5182             }
5183         }
5184     }
5185 
5186     // The local host is the authoritative source for LocalOnly questions
5187     // so if no records exist and client requested intermediates, then generate a negative response
5188     if (!retEv && (m->CurrentQuestion == q) && q->ReturnIntermed)
5189         GenerateNegativeResponse(m, mDNSInterface_LocalOnly, QC_forceresponse);
5190 
5191     m->CurrentQuestion = mDNSNULL;
5192     m->CurrentRecord   = mDNSNULL;
5193 }
5194 
5195 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
5196 {
5197     CacheEntity *e = mDNSNULL;
5198 
5199     if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
5200     m->lock_rrcache = 1;
5201 
5202     // If we have no free records, ask the client layer to give us some more memory
5203     if (!m->rrcache_free && m->MainCallback)
5204     {
5205         if (m->rrcache_totalused != m->rrcache_size)
5206         {
5207             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
5208                       "GetFreeCacheRR: count mismatch: m->rrcache_totalused %u != m->rrcache_size %u",
5209                       m->rrcache_totalused, m->rrcache_size);
5210         }
5211 
5212         // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
5213         // number of bogus records so that we keep growing our cache until the machine runs out of memory.
5214         // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
5215         // and we're actively using less than 1/32 of that cache, then we purge all the unused records
5216         // and recycle them, instead of allocating more memory.
5217         if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
5218         {
5219             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
5220                       "Possible denial-of-service attack in progress: m->rrcache_size %u; m->rrcache_active %u",
5221                       m->rrcache_size, m->rrcache_active);
5222         }
5223         else
5224         {
5225             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
5226             m->MainCallback(m, mStatus_GrowCache);
5227             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
5228         }
5229     }
5230 
5231     // If we still have no free records, recycle all the records we can.
5232     // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
5233     if (!m->rrcache_free)
5234     {
5235         mDNSu32 oldtotalused = m->rrcache_totalused;
5236         mDNSu32 slot;
5237         for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5238         {
5239             CacheGroup **cp = &m->rrcache_hash[slot];
5240             while (*cp)
5241             {
5242                 CacheRecord **rp = &(*cp)->members;
5243                 while (*rp)
5244                 {
5245                     // Records that answer still-active questions are not candidates for recycling
5246                     // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
5247                     if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
5248                         rp=&(*rp)->next;
5249                     else
5250                     {
5251                         CacheRecord *rr = *rp;
5252                         *rp = (*rp)->next;          // Cut record from list
5253                         ReleaseCacheRecord(m, rr);
5254                     }
5255                 }
5256                 if ((*cp)->rrcache_tail != rp)
5257                     verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
5258                 (*cp)->rrcache_tail = rp;
5259                 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
5260                 else ReleaseCacheGroup(m, cp);
5261             }
5262         }
5263         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "GetCacheEntity recycled %d records to reduce cache from %d to %d",
5264                   oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
5265     }
5266 
5267     if (m->rrcache_free)    // If there are records in the free list, take one
5268     {
5269         e = m->rrcache_free;
5270         m->rrcache_free = e->next;
5271         if (++m->rrcache_totalused >= m->rrcache_report)
5272         {
5273             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "RR Cache now using %u objects", m->rrcache_totalused);
5274             if      (m->rrcache_report <  100) m->rrcache_report += 10;
5275             else if (m->rrcache_report < 1000) m->rrcache_report += 100;
5276             else m->rrcache_report += 1000;
5277         }
5278         mDNSPlatformMemZero(e, sizeof(*e));
5279     }
5280 
5281     m->lock_rrcache = 0;
5282 
5283     return(e);
5284 }
5285 
5286 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
5287 {
5288     CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
5289     if (r)
5290     {
5291         r->resrec.rdata = (RData*)&r->smallrdatastorage;    // By default, assume we're usually going to be using local storage
5292         if (RDLength > InlineCacheRDSize)           // If RDLength is too big, allocate extra storage
5293         {
5294             r->resrec.rdata = (RData*) mDNSPlatformMemAllocateClear(sizeofRDataHeader + RDLength);
5295             if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
5296             else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
5297         }
5298     }
5299     return(r);
5300 }
5301 
5302 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
5303 {
5304     mDNSu16 namelen = DomainNameLength(rr->name);
5305     CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
5306     if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
5307     cg->next         = m->rrcache_hash[slot];
5308     cg->namehash     = rr->namehash;
5309     cg->members      = mDNSNULL;
5310     cg->rrcache_tail = &cg->members;
5311     if (namelen > sizeof(cg->namestorage))
5312         cg->name = (domainname *) mDNSPlatformMemAllocate(namelen);
5313     else
5314         cg->name = (domainname*)cg->namestorage;
5315     if (!cg->name)
5316     {
5317         LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
5318         ReleaseCacheEntity(m, (CacheEntity*)cg);
5319         return(mDNSNULL);
5320     }
5321     AssignDomainName(cg->name, rr->name);
5322 
5323     if (CacheGroupForRecord(m, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
5324     m->rrcache_hash[slot] = cg;
5325     if (CacheGroupForRecord(m, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
5326 
5327     return(cg);
5328 }
5329 
5330 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
5331 {
5332     mDNS_CheckLock(m);
5333 
5334     // Make sure we mark this record as thoroughly expired -- we don't ever want to give
5335     // a positive answer using an expired record (e.g. from an interface that has gone away).
5336     // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
5337     // summary deletion without giving the proper callback to any questions that are monitoring it.
5338     // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
5339     rr->TimeRcvd          = m->timenow - mDNSPlatformOneSecond * 60;
5340     rr->UnansweredQueries = MaxUnansweredQueries;
5341     rr->resrec.rroriginalttl     = 0;
5342     SetNextCacheCheckTimeForRecord(m, rr);
5343 }
5344 
5345 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
5346 {
5347     mDNSs32 time;
5348     mDNSPlatformLock(m);
5349     if (m->mDNS_busy)
5350     {
5351         LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
5352         if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
5353     }
5354 
5355     if (m->timenow) time = m->timenow;
5356     else time = mDNS_TimeNow_NoLock(m);
5357     mDNSPlatformUnlock(m);
5358     return(time);
5359 }
5360 
5361 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
5362 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
5363 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
5364 #define SetSPSProxyListChanged(X) do { \
5365         if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m->SPSProxyListChanged); \
5366         m->SPSProxyListChanged = (X); } while(0)
5367 
5368 // Called from mDNS_Execute() to expire stale proxy records
5369 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
5370 {
5371     m->CurrentRecord = list;
5372     while (m->CurrentRecord)
5373     {
5374         AuthRecord *rr = m->CurrentRecord;
5375         if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
5376         {
5377             // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
5378             // so we need to cease proxying for *all* records we may have, expired or not.
5379             if (m->SPSSocket && m->timenow - rr->TimeExpire < 0)    // If proxy record not expired yet, update m->NextScheduledSPS
5380             {
5381                 if (m->NextScheduledSPS - rr->TimeExpire > 0)
5382                     m->NextScheduledSPS = rr->TimeExpire;
5383             }
5384             else                                                    // else proxy record expired, so remove it
5385             {
5386                 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
5387                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
5388                 SetSPSProxyListChanged(rr->resrec.InterfaceID);
5389                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
5390                 // Don't touch rr after this -- memory may have been free'd
5391             }
5392         }
5393         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
5394         // new records could have been added to the end of the list as a result of that call.
5395         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5396             m->CurrentRecord = rr->next;
5397     }
5398 }
5399 
5400 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
5401 {
5402     while (m->CurrentRecord)
5403     {
5404         AuthRecord *rr = m->CurrentRecord;
5405         if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
5406         {
5407             debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
5408             rr->resrec.RecordType = kDNSRecordTypeShared;
5409             AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv);
5410             if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
5411             {
5412                 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
5413                 rr->AnsweredLocalQ = mDNSfalse;
5414                 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5415                 // For LocalOnly records, we don't do that and hence we need to do that here.
5416                 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
5417             }
5418         }
5419         if (m->CurrentRecord == rr)     // If m->CurrentRecord was not auto-advanced, do it ourselves now
5420             m->CurrentRecord = rr->next;
5421     }
5422 }
5423 
5424 mDNSlocal void TimeoutQuestions_internal(mDNS *const m, DNSQuestion* questions, mDNSInterfaceID InterfaceID)
5425 {
5426     if (m->CurrentQuestion)
5427         LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
5428                DNSTypeName(m->CurrentQuestion->qtype));
5429     m->CurrentQuestion = questions;
5430     while (m->CurrentQuestion)
5431     {
5432         DNSQuestion *const q = m->CurrentQuestion;
5433         if (q->StopTime)
5434         {
5435             if (!q->TimeoutQuestion)
5436                 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5437 
5438             if (m->timenow - q->StopTime >= 0)
5439             {
5440                 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime);
5441                 q->LOAddressAnswers = 0; // unset since timing out the question
5442                 GenerateNegativeResponse(m, InterfaceID, QC_forceresponse);
5443                 if (m->CurrentQuestion == q) q->StopTime = 0;
5444             }
5445             else
5446             {
5447                 if (m->NextScheduledStopTime - q->StopTime > 0)
5448                     m->NextScheduledStopTime = q->StopTime;
5449             }
5450         }
5451         // If m->CurrentQuestion wasn't modified out from under us, advance it now
5452         // We can't do this at the start of the loop because GenerateNegativeResponse
5453         // depends on having m->CurrentQuestion point to the right question
5454         if (m->CurrentQuestion == q)
5455             m->CurrentQuestion = q->next;
5456     }
5457     m->CurrentQuestion = mDNSNULL;
5458 }
5459 
5460 mDNSlocal void TimeoutQuestions(mDNS *const m)
5461 {
5462     m->NextScheduledStopTime = m->timenow + FutureTime; // push reschedule of TimeoutQuestions to way off into the future
5463     TimeoutQuestions_internal(m, m->Questions, mDNSInterface_Any);
5464     TimeoutQuestions_internal(m, m->LocalOnlyQuestions, mDNSInterface_LocalOnly);
5465 }
5466 
5467 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
5468 {
5469     AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
5470     LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
5471     while (rrPtr)
5472     {
5473         rrNext = rrPtr->next;
5474         mDNSPlatformMemFree(rrPtr);
5475         rrPtr  = rrNext;
5476     }
5477     m->SPSRRSet = mDNSNULL;
5478 }
5479 
5480 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
5481 {
5482     mDNS_Lock(m);   // Must grab lock before trying to read m->timenow
5483 
5484     if (m->timenow - m->NextScheduledEvent >= 0)
5485     {
5486         int i;
5487         AuthRecord *head, *tail;
5488         mDNSu32 slot;
5489         AuthGroup *ag;
5490 
5491         verbosedebugf("mDNS_Execute");
5492 
5493         if (m->CurrentQuestion)
5494             LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5495                    m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5496 
5497         if (m->CurrentRecord)
5498             LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
5499 
5500         // 1. If we're past the probe suppression time, we can clear it
5501         if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
5502 
5503         // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5504         if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
5505 
5506         // 3. Purge our cache of stale old records
5507         if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
5508         {
5509             mDNSu32 numchecked = 0;
5510             m->NextCacheCheck = m->timenow + FutureTime;
5511             for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5512             {
5513                 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
5514                 {
5515                     CacheGroup **cp = &m->rrcache_hash[slot];
5516                     m->rrcache_nextcheck[slot] = m->timenow + FutureTime;
5517                     while (*cp)
5518                     {
5519                         debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
5520                         numchecked++;
5521                         CheckCacheExpiration(m, slot, *cp);
5522                         if ((*cp)->members) cp=&(*cp)->next;
5523                         else ReleaseCacheGroup(m, cp);
5524                     }
5525                 }
5526                 // Even if we didn't need to actually check this slot yet, still need to
5527                 // factor its nextcheck time into our overall NextCacheCheck value
5528                 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
5529                     m->NextCacheCheck = m->rrcache_nextcheck[slot];
5530             }
5531             debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
5532         }
5533 
5534         if (m->timenow - m->NextScheduledSPS >= 0)
5535         {
5536             m->NextScheduledSPS = m->timenow + FutureTime;
5537             CheckProxyRecords(m, m->DuplicateRecords);  // Clear m->DuplicateRecords first, then m->ResourceRecords
5538             CheckProxyRecords(m, m->ResourceRecords);
5539         }
5540 
5541         SetSPSProxyListChanged(mDNSNULL);       // Perform any deferred BPF reconfiguration now
5542 
5543         // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5544         // as records could have expired during that check
5545         if (m->timenow - m->NextScheduledKA >= 0)
5546         {
5547             m->NextScheduledKA = m->timenow + FutureTime;
5548             mDNS_SendKeepalives(m);
5549         }
5550 
5551 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
5552         if (m->NextBonjourDisableTime && (m->timenow - m->NextBonjourDisableTime >= 0))
5553         {
5554             // Schedule immediate network change processing to leave the multicast group
5555             // since the delay time has expired since the previous active registration or query.
5556             m->NetworkChanged = m->timenow;
5557             m->NextBonjourDisableTime = 0;
5558             m->BonjourEnabled = 0;
5559 
5560             LogInfo("mDNS_Execute: Scheduled network changed processing to leave multicast group.");
5561         }
5562 #endif
5563 
5564         // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5565         if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
5566         {
5567             m->AnnounceOwner = 0;
5568         }
5569 
5570         if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
5571         {
5572             m->DelaySleep = 0;
5573             if (m->SleepState == SleepState_Transferring)
5574             {
5575                 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5576                 BeginSleepProcessing(m);
5577             }
5578         }
5579 
5580         // 4. See if we can answer any of our new local questions from the cache
5581         for (i=0; m->NewQuestions && i<1000; i++)
5582         {
5583             if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
5584             AnswerNewQuestion(m);
5585         }
5586         if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5587 
5588         // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5589         // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5590         for (i=0; i<1000 && m->LocalRemoveEvents; i++)
5591         {
5592             m->LocalRemoveEvents = mDNSfalse;
5593             m->CurrentRecord = m->ResourceRecords;
5594             CheckRmvEventsForLocalRecords(m);
5595             // Walk the LocalOnly records and deliver the RMV events
5596             for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5597                 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5598                 {
5599                     m->CurrentRecord = ag->members;
5600                     if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
5601                 }
5602         }
5603 
5604         if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5605 
5606         for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
5607         if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5608 
5609         head = tail = mDNSNULL;
5610         for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
5611         {
5612             AuthRecord *rr = m->NewLocalRecords;
5613             m->NewLocalRecords = m->NewLocalRecords->next;
5614             if (LocalRecordReady(rr))
5615             {
5616                 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5617                 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5618             }
5619             else if (!rr->next)
5620             {
5621                 // If we have just one record that is not ready, we don't have to unlink and
5622                 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5623                 // terminate and set the NewLocalRecords to rr.
5624                 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
5625                 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
5626                     LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
5627 
5628                 head = rr;
5629             }
5630             else
5631             {
5632                 AuthRecord **p = &m->ResourceRecords;   // Find this record in our list of active records
5633                 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
5634                 // if this is the first record we are skipping, move to the end of the list.
5635                 // if we have already skipped records before, append it at the end.
5636                 while (*p && *p != rr) p=&(*p)->next;
5637                 if (*p) *p = rr->next;                  // Cut this record from the list
5638                 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
5639                 if (!head)
5640                 {
5641                     while (*p) p=&(*p)->next;
5642                     *p = rr;
5643                     head = tail = rr;
5644                 }
5645                 else
5646                 {
5647                     tail->next = rr;
5648                     tail = rr;
5649                 }
5650                 rr->next = mDNSNULL;
5651             }
5652         }
5653         m->NewLocalRecords = head;
5654         debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
5655 
5656         if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5657 
5658         // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5659         // to our local questions
5660         if (m->NewLocalOnlyRecords)
5661         {
5662             m->NewLocalOnlyRecords = mDNSfalse;
5663             for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5664             {
5665                 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5666                 {
5667                     for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
5668                     {
5669                         AuthRecord *rr = ag->NewLocalOnlyRecords;
5670                         ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
5671                         // LocalOnly records should always be ready as they never probe
5672                         if (LocalRecordReady(rr))
5673                         {
5674                             debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5675                             AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5676                         }
5677                         else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
5678                     }
5679                     // We limit about 100 per AuthGroup that can be serviced at a time
5680                     if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5681                 }
5682             }
5683         }
5684 
5685         // 5. See what packets we need to send
5686         if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
5687             DiscardDeregistrations(m);
5688         if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
5689         {
5690             // If the platform code is ready, and we're not suppressing packet generation right now
5691             // then send our responses, probes, and questions.
5692             // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5693             // We send queries next, because there might be final-stage probes that complete their probing here, causing
5694             // them to advance to announcing state, and we want those to be included in any announcements we send out.
5695             // Finally, we send responses, including the previously mentioned records that just completed probing.
5696             m->SuppressSending = 0;
5697 
5698             // 6. Send Query packets. This may cause some probing records to advance to announcing state
5699             if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
5700             if (m->timenow - m->NextScheduledQuery >= 0)
5701             {
5702                 DNSQuestion *q;
5703                 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5704                        m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
5705                 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
5706                 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
5707                     if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
5708                         LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5709             }
5710             if (m->timenow - m->NextScheduledProbe >= 0)
5711             {
5712                 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5713                        m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
5714                 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
5715             }
5716 
5717             // 7. Send Response packets, including probing records just advanced to announcing state
5718             if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
5719             if (m->timenow - m->NextScheduledResponse >= 0)
5720             {
5721                 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5722                 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
5723             }
5724         }
5725 
5726         // Clear RandomDelay values, ready to pick a new different value next time
5727         m->RandomQueryDelay     = 0;
5728         m->RandomReconfirmDelay = 0;
5729 
5730         // See if any questions (or local-only questions) have timed out
5731         if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
5732 #ifndef UNICAST_DISABLED
5733         if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
5734         if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
5735         if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
5736 #endif
5737 #if APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5738         extern void serviceBLE();
5739         if (m->NextBLEServiceTime && (m->timenow - m->NextBLEServiceTime >= 0)) serviceBLE();
5740 #endif // APPLE_OSX_mDNSResponder && ENABLE_BLE_TRIGGERED_BONJOUR
5741     }
5742 
5743     // Note about multi-threaded systems:
5744     // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5745     // performing mDNS API operations that change our next scheduled event time.
5746     //
5747     // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5748     // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5749     // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5750     // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5751     // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5752     // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5753     // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5754     // without blocking. This avoids the race condition between the signal from the other thread arriving
5755     // just *before* or just *after* the main thread enters the blocking primitive.
5756     //
5757     // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5758     // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5759     // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5760     // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5761     // by the time it gets to the timer callback function).
5762 
5763     mDNS_Unlock(m);     // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5764     return(m->NextScheduledEvent);
5765 }
5766 
5767 #ifndef UNICAST_DISABLED
5768 mDNSlocal void SuspendLLQs(mDNS *m)
5769 {
5770     DNSQuestion *q;
5771     for (q = m->Questions; q; q = q->next)
5772         if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
5773         { q->ReqLease = 0; sendLLQRefresh(m, q); }
5774 }
5775 #endif // UNICAST_DISABLED
5776 
5777 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
5778 {
5779     AuthRecord *rr;
5780     AuthGroup *ag;
5781 
5782     ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
5783     if (ag)
5784     {
5785         for (rr = ag->members; rr; rr=rr->next)
5786             // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5787             if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
5788             {
5789                 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
5790                 return mDNStrue;
5791             }
5792     }
5793     return mDNSfalse;
5794 }
5795 
5796 // ActivateUnicastQuery() is called from three places:
5797 // 1. When a new question is created
5798 // 2. On wake from sleep
5799 // 3. When the DNS configuration changes
5800 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5801 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5802 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
5803 {
5804     if (!question->DuplicateOf)
5805     {
5806         debugf("ActivateUnicastQuery: %##s %s%s",
5807                question->qname.c, DNSTypeName(question->qtype), ScheduleImmediately ? " ScheduleImmediately" : "");
5808         question->CNAMEReferrals = 0;
5809         if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
5810         if (question->LongLived)
5811         {
5812             question->state = LLQ_Init;
5813             question->id = zeroOpaque64;
5814             question->servPort = zeroIPPort;
5815             if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
5816         }
5817         // If the question has local answers, then we don't want answers from outside
5818         if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
5819         {
5820             question->ThisQInterval = InitialQuestionInterval;
5821             question->LastQTime     = m->timenow - question->ThisQInterval;
5822             SetNextQueryTime(m, question);
5823         }
5824     }
5825 }
5826 
5827 // Caller should hold the lock
5828 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
5829                                               CallbackBeforeStartQuery BeforeStartCallback, void *context)
5830 {
5831     DNSQuestion *q;
5832     DNSQuestion *restart = mDNSNULL;
5833 
5834     mDNS_CheckLock(m);
5835 
5836     // 1. Flush the cache records
5837     if (flushCacheRecords) flushCacheRecords(m);
5838 
5839     // 2. Even though we may have purged the cache records above, before it can generate RMV event
5840     // we are going to stop the question. Hence we need to deliver the RMV event before we
5841     // stop the question.
5842     //
5843     // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5844     // application callback can potentially stop the current question (detected by CurrentQuestion) or
5845     // *any* other question which could be the next one that we may process here. RestartQuestion
5846     // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5847     // if the "next" question is stopped while the CurrentQuestion is stopped
5848 
5849     if (m->RestartQuestion)
5850         LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5851                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
5852 
5853     m->RestartQuestion = m->Questions;
5854     while (m->RestartQuestion)
5855     {
5856         q = m->RestartQuestion;
5857         m->RestartQuestion = q->next;
5858         // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5859         // question)  through their "nta" pointer. Normally when the original query stops, it stops the
5860         // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5861         // question followed by the original query that refers to this GetZoneData question, we will end up
5862         // freeing the GetZoneData question and then start the "freed" question at the end.
5863 
5864         if (IsGetZoneDataQuestion(q))
5865         {
5866             DNSQuestion *refq = q->next;
5867             LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5868             // debug stuff, we just try to find the referencing question and don't do much with it
5869             while (refq)
5870             {
5871                 if (q == &refq->nta->question)
5872                 {
5873                     LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
5874                 }
5875                 refq = refq->next;
5876             }
5877             continue;
5878         }
5879 
5880         // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5881         if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
5882 
5883         // If the search domains did not change, then we restart all the queries. Otherwise, only
5884         // for queries for which we "might" have appended search domains ("might" because we may
5885         // find results before we apply search domains even though AppendSearchDomains is set to 1)
5886         if (!SearchDomainsChanged || q->AppendSearchDomains)
5887         {
5888             // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5889             // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5890             // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5891             // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5892             // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5893             // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5894             // for the original query using these cache entries as ADDs were never delivered using these cache
5895             // entries and hence this order is needed.
5896 
5897             // If the query is suppressed, the RMV events won't be delivered
5898             if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5899 
5900             // Suppressed status does not affect questions that are answered using local records
5901             if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5902 
5903             LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d", q,
5904                     q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains);
5905             mDNS_StopQuery_internal(m, q);
5906             if (q->ResetHandler) q->ResetHandler(q);
5907             q->next = restart;
5908             restart = q;
5909         }
5910     }
5911 
5912     // 3. Callback before we start the query
5913     if (BeforeStartCallback) BeforeStartCallback(m, context);
5914 
5915     // 4. Restart all the stopped queries
5916     while (restart)
5917     {
5918         q = restart;
5919         restart = restart->next;
5920         q->next = mDNSNULL;
5921         LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5922         mDNS_StartQuery_internal(m, q);
5923     }
5924 }
5925 
5926 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
5927 {
5928     DNSQuestion *q;
5929 
5930 #ifndef UNICAST_DISABLED
5931     // Retrigger all our uDNS questions
5932     if (m->CurrentQuestion)
5933         LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5934                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5935     m->CurrentQuestion = m->Questions;
5936     while (m->CurrentQuestion)
5937     {
5938         q = m->CurrentQuestion;
5939         m->CurrentQuestion = m->CurrentQuestion->next;
5940         if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5941         {
5942 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
5943             mdns_querier_forget(&q->querier);
5944 #endif
5945             ActivateUnicastQuery(m, q, mDNStrue);
5946         }
5947     }
5948 #endif
5949 
5950     // Retrigger all our mDNS questions
5951     for (q = m->Questions; q; q=q->next)                // Scan our list of questions
5952             mDNSCoreRestartQuestion(m, q);
5953 }
5954 
5955 // restart question if it's multicast and currently active
5956 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
5957 {
5958     if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5959     {
5960         q->ThisQInterval    = InitialQuestionInterval;  // MUST be > zero for an active question
5961         q->RequestUnicast   = kDefaultRequestUnicastCount;
5962         q->LastQTime        = m->timenow - q->ThisQInterval;
5963         q->RecentAnswerPkts = 0;
5964         ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
5965         m->NextScheduledQuery = m->timenow;
5966     }
5967 }
5968 
5969 // restart the probe/announce cycle for multicast record
5970 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord *rr, int announceCount)
5971 {
5972     if (!AuthRecord_uDNS(rr))
5973     {
5974         if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5975         rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5976 
5977         if (mDNS_KeepaliveRecord(&rr->resrec))
5978         {
5979             rr->AnnounceCount = 0; // Do not announce keepalive records
5980         }
5981         else
5982         {
5983             // announceCount < 0 indicates default announce count should be used
5984             if (announceCount < 0)
5985                 announceCount = InitialAnnounceCount;
5986             if (rr->AnnounceCount < (mDNSu8)announceCount)
5987                 rr->AnnounceCount = (mDNSu8)announceCount;
5988         }
5989 
5990         rr->SendNSECNow    = mDNSNULL;
5991         InitializeLastAPTime(m, rr);
5992     }
5993 }
5994 
5995 // ***************************************************************************
5996 #if COMPILER_LIKES_PRAGMA_MARK
5997 #pragma mark -
5998 #pragma mark - Power Management (Sleep/Wake)
5999 #endif
6000 
6001 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
6002 {
6003 #ifndef IDLESLEEPCONTROL_DISABLED
6004     mDNSBool allowSleep = mDNStrue;
6005     char reason[128];
6006 
6007     reason[0] = 0;
6008 
6009     if (m->SystemSleepOnlyIfWakeOnLAN)
6010     {
6011         // Don't sleep if we are a proxy for any services
6012         if (m->ProxyRecords)
6013         {
6014             allowSleep = mDNSfalse;
6015             mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
6016             LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords);
6017         }
6018 
6019         if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
6020         {
6021             // Scan the list of active interfaces
6022             NetworkInterfaceInfo *intf;
6023             for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6024             {
6025                 if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6026                 {
6027                     // Disallow sleep if this interface doesn't support NetWake
6028                     if (!intf->NetWake)
6029                     {
6030                         allowSleep = mDNSfalse;
6031                         mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
6032                         LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname);
6033                         break;
6034                     }
6035 
6036                     // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
6037                     // that will be offloaded. If not, we should prevent sleep.
6038                     // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
6039 #if APPLE_OSX_mDNSResponder
6040                     if (!SupportsInNICProxy(intf))
6041 #endif
6042                     {
6043                         // Disallow sleep if there is no sleep proxy server
6044                         const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
6045                         if ( cr == mDNSNULL)
6046                         {
6047                             allowSleep = mDNSfalse;
6048                             mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
6049                             LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
6050                             break;
6051                         }
6052                         else if (m->SPSType != 0)
6053                         {
6054                             mDNSu32 mymetric = LocalSPSMetric(m);
6055                             mDNSu32 metric   = SPSMetric(cr->resrec.rdata->u.name.c);
6056                             if (metric >= mymetric)
6057                             {
6058                                 allowSleep = mDNSfalse;
6059                                 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
6060                                 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
6061                                 break;
6062                             }
6063                         }
6064                     }
6065                 }
6066             }
6067         }
6068     }
6069 
6070     // Call the platform code to enable/disable sleep
6071     mDNSPlatformSetAllowSleep(allowSleep, reason);
6072 #else
6073     (void) m;
6074 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
6075 }
6076 
6077 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
6078 {
6079     // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
6080     // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
6081     // to send.
6082     if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) ||
6083         m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
6084     {
6085         return mDNSfalse;
6086     }
6087 
6088     // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
6089     // If the scopeid is too big to check for validity, we don't check against updateIntID. When
6090     // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
6091     // updateid and we should have returned from above.
6092     //
6093     // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
6094     // platform function to extract the value from "intf" every time.
6095 
6096     if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6097         (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6098         return mDNStrue;
6099 
6100     return mDNSfalse;
6101 }
6102 
6103 mDNSexport void UpdateRMAC(mDNS *const m, void *context)
6104 {
6105     IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
6106     m->CurrentRecord = m->ResourceRecords;
6107 
6108     if (!addrmap)
6109     {
6110         LogMsg("UpdateRMAC: Address mapping is NULL");
6111         return;
6112     }
6113 
6114     while (m->CurrentRecord)
6115     {
6116         AuthRecord *rr = m->CurrentRecord;
6117         // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
6118         if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
6119         {
6120             mDNSAddr raddr;
6121             getKeepaliveRaddr(m, rr, &raddr);
6122             if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
6123             {
6124                 // Update the MAC address only if it is not a zero MAC address
6125                 mDNSEthAddr macAddr;
6126                 mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr);
6127                 if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr))
6128                 {
6129                     UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
6130                 }
6131             }
6132         }
6133         m->CurrentRecord = rr->next;
6134     }
6135 
6136     if (addrmap)
6137         mDNSPlatformMemFree(addrmap);
6138 
6139 }
6140 
6141 mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr)
6142 {
6143     mDNSu16 newrdlength;
6144     mDNSAddr laddr = zeroAddr;
6145     mDNSAddr raddr = zeroAddr;
6146     mDNSEthAddr eth = zeroEthAddr;
6147     mDNSIPPort lport = zeroIPPort;
6148     mDNSIPPort rport = zeroIPPort;
6149     mDNSu32 timeout = 0;
6150     mDNSu32 seq = 0;
6151     mDNSu32 ack = 0;
6152     mDNSu16 win = 0;
6153     UTF8str255 txt;
6154     int rdsize;
6155     RData *newrd;
6156     mDNSTCPInfo mti;
6157     mStatus ret;
6158 
6159     // Note: If we fail to update the  DNS NULL  record with additional information in this function, it will be registered
6160     // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
6161     mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
6162     if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
6163     {
6164         LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
6165         return mStatus_UnknownErr;
6166     }
6167 
6168     if (updateMac)
6169     {
6170         if (laddr.type == mDNSAddrType_IPv4)
6171             newrdlength = 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);
6172         else
6173             newrdlength = 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);
6174 
6175     }
6176     else
6177     {
6178         // If this keepalive packet would be sent on a different interface than the current one that we are processing
6179         // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
6180         // this DNS NULL record, it does not send any keepalives as it does not have all the information
6181         mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo));
6182         ret = mDNSPlatformRetrieveTCPInfo(&laddr, &lport, &raddr, &rport, &mti);
6183         if (ret != mStatus_NoError)
6184         {
6185             LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
6186             return ret;
6187         }
6188         if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID))
6189         {
6190             LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID mismatch mti.IntfId = %p InterfaceID = %p",  mti.IntfId, intf->InterfaceID);
6191             return mStatus_BadParamErr;
6192         }
6193 
6194         if (laddr.type == mDNSAddrType_IPv4)
6195             newrdlength = 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), &eth, mti.seq, mti.ack, mti.window);
6196         else
6197             newrdlength = 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), &eth, mti.seq, mti.ack, mti.window);
6198     }
6199 
6200     // Did we insert a null byte at the end ?
6201     if (newrdlength == (sizeof(txt.c) - 1))
6202     {
6203         LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
6204         return mStatus_NoMemoryErr;
6205     }
6206 
6207     // Include the length for the null byte at the end
6208     txt.c[0] = newrdlength + 1;
6209     // Account for the first length byte and the null byte at the end
6210     newrdlength += 2;
6211 
6212     rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
6213     newrd = (RData *) mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
6214     if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
6215 
6216     newrd->MaxRDLength = (mDNSu16) rdsize;
6217     mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
6218 
6219     //  If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
6220     //  was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
6221     //  If the resource record has data that we allocated in a previous pass (to update MAC address),
6222     //  free that memory here before copying in the new data.
6223     if ( rr->resrec.rdata != &rr->rdatastorage)
6224     {
6225         LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr));
6226         mDNSPlatformMemFree(rr->resrec.rdata);
6227     }
6228     SetNewRData(&rr->resrec, newrd, newrdlength);    // Update our rdata
6229 
6230     LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
6231     return mStatus_NoError;
6232 }
6233 
6234 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
6235 {
6236     const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
6237     const int sps = intf->NextSPSAttempt / 3;
6238     AuthRecord *rr;
6239     mDNSOpaque16 msgid;
6240     mDNSu32 scopeid;
6241 
6242     scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6243     if (!intf->SPSAddr[sps].type)
6244     {
6245         intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6246         if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6247             m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6248         LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
6249         goto exit;
6250     }
6251 
6252     // Mark our mDNS records (not unicast records) for transfer to SPS
6253     if (mDNSOpaque16IsZero(id))
6254     {
6255         // We may have to register this record over multiple interfaces and we don't want to
6256         // overwrite the id. We send the registration over interface X with id "IDX" and before
6257         // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
6258         // for "IDX". Hence, we want to use the same ID across all interfaces.
6259         //
6260         // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
6261         // option check below will set the same ID across the records from the same owner. Records
6262         // with different owner option gets different ID.
6263         msgid = mDNS_NewMessageID(m);
6264         for (rr = m->ResourceRecords; rr; rr=rr->next)
6265         {
6266             if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
6267             {
6268                 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
6269                 {
6270                     if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6271                     {
6272                         rr->SendRNow = mDNSInterfaceMark;   // mark it now
6273                         // When we are registering on the first interface, rr->updateid is zero in which case
6274                         // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
6275                         // At the end, all the updates sent across all the interfaces with the same ID.
6276                         if (mDNSOpaque16IsZero(rr->updateid))
6277                             rr->updateid = msgid;
6278                         else
6279                             msgid = rr->updateid;
6280                     }
6281                 }
6282             }
6283         }
6284     }
6285     else
6286         msgid = id;
6287 
6288     while (1)
6289     {
6290         mDNSu8 *p = m->omsg.data;
6291         // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
6292         // For now we follow that same logic for SPS registrations too.
6293         // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
6294         // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
6295         InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
6296 
6297         for (rr = m->ResourceRecords; rr; rr=rr->next)
6298             if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
6299             {
6300                 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
6301                 {
6302                     mDNSu8 *newptr;
6303                     const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
6304 
6305                     // If we can't update the keepalive record, don't send it
6306                     if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
6307                     {
6308                         if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
6309                         {
6310                             bit_clr_opaque64(rr->updateIntID, scopeid);
6311                         }
6312                         rr->SendRNow = mDNSNULL;
6313                         continue;
6314                     }
6315 
6316                     if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
6317                         rr->resrec.rrclass |= kDNSClass_UniqueRRSet;    // Temporarily set the 'unique' bit so PutResourceRecord will set it
6318                     newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
6319                     rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;       // Make sure to clear 'unique' bit back to normal state
6320                     if (!newptr)
6321                         LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
6322                     else
6323                     {
6324                         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));
6325                         rr->SendRNow       = mDNSNULL;
6326                         rr->ThisAPInterval = mDNSPlatformOneSecond;
6327                         rr->LastAPTime     = m->timenow;
6328                         // should be initialized above
6329                         if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
6330                         if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6331                             m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
6332                         p = newptr;
6333                     }
6334                 }
6335             }
6336 
6337         if (!m->omsg.h.mDNS_numUpdates) break;
6338         else
6339         {
6340             AuthRecord opt;
6341             mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
6342             opt.resrec.rrclass    = NormalMaxDNSMessageData;
6343             opt.resrec.rdlength   = sizeof(rdataOPT) * 2;   // Two options in this OPT record
6344             opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
6345             opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
6346             opt.resrec.rdata->u.opt[0].optlen        = DNSOpt_LeaseData_Space - 4;
6347             opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
6348             if (!owner->HMAC.l[0])                                          // If no owner data,
6349                 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]);        // use our own interface information
6350             else                                                            // otherwise, use the owner data we were given
6351             {
6352                 opt.resrec.rdata->u.opt[1].u.owner = *owner;
6353                 opt.resrec.rdata->u.opt[1].opt     = kDNSOpt_Owner;
6354                 opt.resrec.rdata->u.opt[1].optlen  = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
6355             }
6356             LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
6357             p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
6358             if (!p)
6359                 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
6360             else
6361             {
6362                 mStatus err;
6363 
6364                 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
6365                        mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
6366                 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID;  // For simulating packet loss
6367                 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSfalse);
6368                 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
6369                 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
6370                 {
6371                     LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
6372                     intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
6373                     mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
6374                     return;
6375                 }
6376             }
6377         }
6378     }
6379 
6380     intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10;     // If successful, update NextSPSAttemptTime
6381 
6382 exit:
6383     if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
6384 }
6385 
6386 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
6387 {
6388     AuthRecord *ar;
6389     for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
6390         if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
6391     return mDNStrue;
6392 }
6393 
6394 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
6395 {
6396     AuthRecord *newRR = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(*newRR));
6397     if (newRR == mDNSNULL)
6398     {
6399         LogSPS("%s : could not allocate memory for new resource record", __func__);
6400         return;
6401     }
6402 
6403     mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
6404                              rr->resrec.rroriginalttl, rr->resrec.RecordType,
6405                              rr->ARType, mDNSNULL, mDNSNULL);
6406 
6407     AssignDomainName(&newRR->namestorage, &rr->namestorage);
6408     newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
6409     newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
6410     newRR->resrec.rrclass  = rr->resrec.rrclass;
6411 
6412     if (rr->resrec.rrtype == kDNSType_A)
6413     {
6414         newRR->resrec.rdata->u.ipv4 =  rr->resrec.rdata->u.ipv4;
6415     }
6416     else if (rr->resrec.rrtype == kDNSType_AAAA)
6417     {
6418         newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
6419     }
6420     SetNewRData(&newRR->resrec, mDNSNULL, 0);
6421 
6422     // Insert the new node at the head of the list.
6423     newRR->next        = m->SPSRRSet;
6424     m->SPSRRSet        = newRR;
6425     LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
6426 }
6427 
6428 // Some records are interface specific and some are not. The ones that are supposed to be registered
6429 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6430 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6431 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6432 // registration on all the interfaces
6433 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService)
6434 {
6435     AuthRecord *ar;
6436     LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
6437 
6438     *WakeOnlyService = mDNSfalse;
6439 
6440     // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6441     // make sure that the old sleep proxy records are removed.
6442     mDNSCoreFreeProxyRR(m);
6443 
6444     // For records that are registered only on a specific interface, mark only that bit as it will
6445     // never be registered on any other interface. For others, it should be sent on all interfaces.
6446     for (ar = m->ResourceRecords; ar; ar=ar->next)
6447     {
6448         ar->updateIntID = zeroOpaque64;
6449         ar->updateid    = zeroID;
6450         if (AuthRecord_uDNS(ar))
6451         {
6452             continue;
6453         }
6454         if (ar->AuthFlags & AuthFlagsWakeOnly)
6455         {
6456             if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye)
6457             {
6458                 ar->ImmedAnswer = mDNSInterfaceMark;
6459                 *WakeOnlyService = mDNStrue;
6460                 continue;
6461             }
6462         }
6463         if (!ar->resrec.InterfaceID)
6464         {
6465             LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
6466             ar->updateIntID = updateIntID;
6467         }
6468         else
6469         {
6470             // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6471             // exactly this.
6472             mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
6473             if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
6474             {
6475                 bit_set_opaque64(ar->updateIntID, scopeid);
6476                 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1],
6477                     ar->updateIntID.l[0], ARDisplayString(m, ar));
6478             }
6479             else
6480             {
6481                 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
6482             }
6483         }
6484         // Store the A and AAAA records that we registered with the sleep proxy.
6485         // We will use this to prevent spurious name conflicts that may occur when we wake up
6486         if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
6487         {
6488             mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
6489         }
6490     }
6491 }
6492 
6493 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
6494 {
6495     AuthRecord *ar;
6496     OwnerOptData owner = zeroOwner;
6497 
6498     SendSPSRegistrationForOwner(m, intf, id, &owner);
6499 
6500     for (ar = m->ResourceRecords; ar; ar=ar->next)
6501     {
6502         if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
6503         {
6504             owner = ar->WakeUp;
6505             SendSPSRegistrationForOwner(m, intf, id, &owner);
6506         }
6507     }
6508 }
6509 
6510 // RetrySPSRegistrations is called from SendResponses, with the lock held
6511 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
6512 {
6513     AuthRecord *rr;
6514     NetworkInterfaceInfo *intf;
6515 
6516     // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6517     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6518         if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
6519             intf->NextSPSAttemptTime++;
6520 
6521     // Retry any record registrations that are due
6522     for (rr = m->ResourceRecords; rr; rr=rr->next)
6523         if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6524         {
6525             for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6526             {
6527                 // If we still have registrations pending on this interface, send it now
6528                 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6529                 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6530                     (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6531                 {
6532                     LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
6533                     SendSPSRegistration(m, intf, rr->updateid);
6534                 }
6535             }
6536         }
6537 
6538     // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6539     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6540         if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
6541             intf->NextSPSAttempt++;
6542 }
6543 
6544 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
6545 {
6546     NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
6547     int sps = (int)(question - intf->NetWakeResolve);
6548     (void)m;            // Unused
6549     LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
6550 
6551     if (!AddRecord) return;                                             // Don't care about REMOVE events
6552     if (answer->rrtype != question->qtype) return;                      // Don't care about CNAMEs
6553 
6554     // if (answer->rrtype == kDNSType_AAAA && sps == 0) return; // To test failing to resolve sleep proxy's address
6555 
6556     if (answer->rrtype == kDNSType_SRV)
6557     {
6558         // 1. Got the SRV record; now look up the target host's IP address
6559         mDNS_StopQuery(m, question);
6560         intf->SPSPort[sps] = answer->rdata->u.srv.port;
6561         AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
6562         question->qtype = kDNSType_A;
6563         mDNS_StartQuery(m, question);
6564     }
6565     else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
6566     {
6567         // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6568         mDNS_StopQuery(m, question);
6569         question->ThisQInterval = -1;
6570         intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
6571         intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
6572         mDNS_Lock(m);
6573         if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);    // If we're ready for this result, use it now
6574         mDNS_Unlock(m);
6575     }
6576     else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
6577     {
6578         // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6579         mDNS_StopQuery(m, question);
6580         LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
6581         question->qtype = kDNSType_AAAA;
6582         mDNS_StartQuery(m, question);
6583     }
6584     else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
6585     {
6586         // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6587         mDNS_StopQuery(m, question);
6588         question->ThisQInterval = -1;
6589         intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
6590         intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
6591         mDNS_Lock(m);
6592         if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);    // If we're ready for this result, use it now
6593         mDNS_Unlock(m);
6594     }
6595 }
6596 
6597 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
6598 {
6599     AuthRecord *rr;
6600     for (rr = m->ResourceRecords; rr; rr=rr->next)
6601         if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
6602             return mDNStrue;
6603     return mDNSfalse;
6604 }
6605 
6606 #define WAKE_ONLY_SERVICE 1
6607 #define AC_ONLY_SERVICE   2
6608 
6609 #ifdef APPLE_OSX_mDNSResponder
6610 mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType)
6611 {
6612     AuthRecord *rr;
6613     *servicePresent = mDNSfalse;
6614 
6615     // Mark all the records we need to deregister and send them
6616     for (rr = m->ResourceRecords; rr; rr=rr->next)
6617     {
6618         // If the service type is wake only service and the auth flags match and requires a goodbye
6619         // OR if the service type is AC only and it is not a keepalive record,
6620         // mark the records we need to deregister and send them
6621         if ((serviceType == WAKE_ONLY_SERVICE && (rr->AuthFlags & AuthFlagsWakeOnly) &&
6622                 rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) ||
6623             (serviceType == AC_ONLY_SERVICE && !mDNS_KeepaliveRecord(&rr->resrec)))
6624         {
6625             rr->ImmedAnswer = mDNSInterfaceMark;
6626             *servicePresent = mDNStrue;
6627         }
6628     }
6629 }
6630 #endif
6631 
6632 #ifdef APPLE_OSX_mDNSResponder
6633 // This function is used only in the case of local NIC proxy. For external
6634 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6635 // walk the resource records.
6636 mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
6637 {
6638     return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE);
6639 }
6640 #endif // APPLE_OSX_mDNSResponder
6641 
6642 
6643 mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
6644 {
6645     AuthRecord *rr;
6646     m->SleepState = SleepState_Sleeping;
6647 
6648     // If AllInterfaces is not set, the caller has already marked it appropriately
6649     // on which interfaces this should be sent.
6650     if (AllInterfaces)
6651     {
6652         NetworkInterfaceInfo *intf;
6653         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6654         {
6655             intf->SendGoodbyes = 1;
6656         }
6657     }
6658     if (unicast)
6659     {
6660 #ifndef UNICAST_DISABLED
6661         SleepRecordRegistrations(m);    // If we have no SPS, need to deregister our uDNS records
6662 #endif /* UNICAST_DISABLED */
6663     }
6664 
6665     // Mark all the records we need to deregister and send them
6666     for (rr = m->ResourceRecords; rr; rr=rr->next)
6667         if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6668             rr->ImmedAnswer = mDNSInterfaceMark;
6669     SendResponses(m);
6670 }
6671 
6672 /*
6673  * This function attempts to detect if multiple interfaces are on the same subnet.
6674  * It makes this determination based only on the IPv4 Addresses and subnet masks.
6675  * IPv6 link local addresses that are configured by default on all interfaces make
6676  * it hard to make this determination
6677  *
6678  * The 'real' fix for this would be to send out multicast packets over one interface
6679  * and conclude that multiple interfaces are on the same subnet only if these packets
6680  * are seen on other interfaces on the same system
6681  */
6682 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
6683 {
6684     NetworkInterfaceInfo *intf;
6685     NetworkInterfaceInfo *newIntf;
6686     mDNSu32 i;
6687 
6688     for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
6689     {
6690         if ((newIntf->InterfaceID != intfid) ||
6691             (newIntf->ip.type     != mDNSAddrType_IPv4))
6692         {
6693             continue;
6694         }
6695         for ( i = 0; i < count; i++)
6696         {
6697             for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
6698             {
6699                 if ((intf->InterfaceID != regID[i]) ||
6700                     (intf->ip.type     != mDNSAddrType_IPv4))
6701                 {
6702                     continue;
6703                 }
6704                 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
6705                 {
6706                     LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
6707                     return (mDNStrue);
6708                 }
6709             }
6710         }
6711     }
6712     return (mDNSfalse);
6713 }
6714 
6715 mDNSlocal void DoKeepaliveCallbacks(mDNS *m)
6716 {
6717     // Loop through the keepalive records and callback with an error
6718     m->CurrentRecord = m->ResourceRecords;
6719     while (m->CurrentRecord)
6720     {
6721         AuthRecord *const rr = m->CurrentRecord;
6722         if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering))
6723         {
6724             LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr));
6725             if (rr->RecordCallback)
6726                 rr->RecordCallback(m, rr, mStatus_BadStateErr);
6727         }
6728         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6729             m->CurrentRecord = rr->next;
6730     }
6731 }
6732 
6733 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6734 mDNSlocal void BeginSleepProcessing(mDNS *const m)
6735 {
6736     mDNSBool SendGoodbyes = mDNStrue;
6737     mDNSBool WakeOnlyService  = mDNSfalse;
6738     mDNSBool invokeKACallback = mDNStrue;
6739     const CacheRecord *sps[3] = { mDNSNULL };
6740     mDNSOpaque64 updateIntID = zeroOpaque64;
6741     mDNSInterfaceID registeredIntfIDS[128] = { 0 };
6742     mDNSu32 registeredCount = 0;
6743     int skippedRegistrations = 0;
6744 
6745     m->NextScheduledSPRetry = m->timenow;
6746 
6747     // Clear out the SCDynamic entry that stores the external SPS information
6748     mDNSPlatformClearSPSData();
6749 
6750     if      (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6751     else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
6752     else    // If we have at least one advertised service
6753     {
6754         NetworkInterfaceInfo *intf;
6755         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6756         {
6757             mDNSBool skipFullSleepProxyRegistration = mDNSfalse;
6758             // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6759             intf->SendGoodbyes = 0;
6760 
6761             // If it is not multicast capable, we could not have possibly discovered sleep proxy
6762             // servers.
6763             if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6764             {
6765                 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname);
6766                 continue;
6767             }
6768 
6769             // If we are not capable of WOMP, then don't register with sleep proxy.
6770             //
6771             // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6772             // We might find sleep proxy servers in the cache and start a resolve on them.
6773             // But then if the interface goes away, we won't stop these questions because
6774             // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6775             // to stop both the browse and resolve questions.
6776             if (!intf->NetWake)
6777             {
6778                 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
6779                 intf->SendGoodbyes = 1;
6780                 skippedRegistrations++;
6781                 continue;
6782             }
6783 
6784             // Check if we have already registered with a sleep proxy for this subnet.
6785             // If so, then the subsequent in-NIC sleep proxy registration is limited to any keepalive records that belong
6786             // to the interface.
6787             if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
6788             {
6789                 LogSPS("%s : Skipping full sleep proxy registration on %s", __func__, intf->ifname);
6790                 skipFullSleepProxyRegistration = mDNStrue;
6791             }
6792 
6793 #if APPLE_OSX_mDNSResponder
6794             if (SupportsInNICProxy(intf))
6795             {
6796                 mDNSBool keepaliveOnly = mDNSfalse;
6797                 const mStatus err = ActivateLocalProxy(intf, skipFullSleepProxyRegistration, &keepaliveOnly);
6798                 if (!skipFullSleepProxyRegistration && !err)
6799                 {
6800                     SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
6801 
6802                     // Send goodbyes for all advertised services if the only record offloaded was the keepalive record.
6803                     SendGoodbyes     = (keepaliveOnly) ? mDNStrue: mDNSfalse;
6804                     invokeKACallback = mDNSfalse;
6805                     LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
6806                     // This will leave m->SleepState set to SleepState_Transferring,
6807                     // which is okay because with no outstanding resolves, or updates in flight,
6808                     // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6809 
6810                     registeredIntfIDS[registeredCount] = intf->InterfaceID;
6811                     registeredCount++;
6812                 }
6813                 continue;
6814             }
6815 #endif // APPLE_OSX_mDNSResponder
6816             if (!skipFullSleepProxyRegistration)
6817             {
6818 #if APPLE_OSX_mDNSResponder
6819                 // If on battery, do not attempt to offload to external sleep proxies
6820                 if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery)
6821                 {
6822                     LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6823                     return;
6824                 }
6825 #endif // APPLE_OSX_mDNSResponder
6826                 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
6827                 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6828                                     intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
6829                 else
6830                 {
6831                     int i;
6832                     mDNSu32 scopeid;
6833                     SendGoodbyes = mDNSfalse;
6834                     intf->NextSPSAttempt = 0;
6835                     intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6836 
6837                     scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6838                     // Now we know for sure that we have to wait for registration to complete on this interface.
6839                     if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
6840                         bit_set_opaque64(updateIntID, scopeid);
6841 
6842                     // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6843                     for (i=0; i<3; i++)
6844                     {
6845 #if ForceAlerts
6846                         if (intf->SPSAddr[i].type)
6847                             LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type);
6848                         if (intf->NetWakeResolve[i].ThisQInterval >= 0)
6849                             LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval);
6850 #endif
6851                         intf->SPSAddr[i].type = mDNSAddrType_None;
6852                         if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
6853                         intf->NetWakeResolve[i].ThisQInterval = -1;
6854                         if (sps[i])
6855                         {
6856                             LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
6857                             mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
6858                             intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
6859                             mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
6860 
6861                             // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6862                             registeredIntfIDS[registeredCount] = intf->InterfaceID;
6863                             registeredCount++;
6864                         }
6865                     }
6866                 }
6867             }
6868         }
6869     }
6870 
6871     // If we have at least one interface on which we are registering with an external sleep proxy,
6872     // initialize all the records appropriately.
6873     if (!mDNSOpaque64IsZero(&updateIntID))
6874         SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService);
6875 
6876     // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6877     // the records to a sleep proxy.
6878     if (invokeKACallback)
6879     {
6880         LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6881         DoKeepaliveCallbacks(m);
6882     }
6883 
6884     // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6885     // interfaces and also deregister unicast registrations.
6886     //
6887     // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6888     //   for both multicast and unicast.
6889     //
6890     // - If we skipped registrations on some interfaces, then we have already marked
6891     //   them appropriately above. We don't need to send goodbyes for unicast as
6892     //   we have registered with at least one sleep proxy.
6893     //
6894     // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6895     //
6896     // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6897     // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6898     // at WakeOnlyServices first.
6899     if (SendGoodbyes)
6900     {
6901         LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6902         SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6903     }
6904     else if (skippedRegistrations)
6905     {
6906         LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6907         SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
6908     }
6909     else if (WakeOnlyService)
6910     {
6911         // If we saw WakeOnly service above, send the goodbyes now.
6912         LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyService");
6913         SendResponses(m);
6914     }
6915 }
6916 
6917 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6918 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6919 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6920 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
6921 {
6922     AuthRecord *rr;
6923 
6924     LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_INFO,
6925         PUB_S " (old state %d) at %d", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
6926 
6927     if (sleep && !m->SleepState)        // Going to sleep
6928     {
6929         mDNS_Lock(m);
6930         // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6931         if (m->SPSSocket)
6932         {
6933             mDNSu8 oldstate = m->SPSState;
6934             mDNS_DropLockBeforeCallback();      // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6935             m->SPSState = 2;
6936 #ifndef SPC_DISABLED
6937             if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
6938 #else
6939             (void)oldstate;
6940 #endif
6941             mDNS_ReclaimLockAfterCallback();
6942         }
6943 #ifdef _LEGACY_NAT_TRAVERSAL_
6944         if (m->SSDPSocket)
6945         {
6946             mDNSPlatformUDPClose(m->SSDPSocket);
6947             m->SSDPSocket = mDNSNULL;
6948         }
6949 #endif
6950         m->SleepState = SleepState_Transferring;
6951         if (m->SystemWakeOnLANEnabled && m->DelaySleep)
6952         {
6953             // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6954             LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
6955                       "mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
6956             m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
6957         }
6958         else
6959         {
6960             m->DelaySleep = 0;
6961             m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
6962             m->mDNSStats.Sleeps++;
6963 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
6964             Querier_HandleSleep();
6965 #endif
6966             BeginSleepProcessing(m);
6967         }
6968 
6969 #ifndef UNICAST_DISABLED
6970         SuspendLLQs(m);
6971 #endif
6972         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: m->SleepState %d (" PUB_S ") seq %d",
6973                   m->SleepState,
6974                   m->SleepState == SleepState_Transferring ? "Transferring" :
6975                   m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?", m->SleepSeqNum);
6976         mDNS_Unlock(m);
6977     }
6978     else if (!sleep)        // Waking up
6979     {
6980         mDNSu32 slot;
6981         CacheGroup *cg;
6982         CacheRecord *cr;
6983         NetworkInterfaceInfo *intf;
6984         mDNSs32 currtime, diff;
6985 
6986         mDNS_Lock(m);
6987         // Reset SleepLimit back to 0 now that we're awake again.
6988         m->SleepLimit = 0;
6989 
6990         // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6991         if (m->SleepState != SleepState_Awake)
6992         {
6993             m->SleepState = SleepState_Awake;
6994             m->SleepSeqNum++;
6995             // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
6996             // then we enforce a minimum delay of five seconds before we begin sleep processing.
6997             // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
6998             // before we make our determination of whether there's a Sleep Proxy out there we should register with.
6999             m->DelaySleep = NonZeroTime(m->timenow + kDarkWakeDelaySleep);
7000         }
7001 
7002         if (m->SPSState == 3)
7003         {
7004             m->SPSState = 0;
7005             mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
7006         }
7007         m->mDNSStats.Wakes++;
7008         // ... and the same for NextSPSAttempt
7009         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
7010 
7011 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
7012         Querier_HandleWake();
7013 #endif
7014         // Restart unicast and multicast queries
7015         mDNSCoreRestartQueries(m);
7016 
7017         // and reactivtate service registrations
7018         m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7019         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7020                   "mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
7021 
7022         // 2. Re-validate our cache records
7023         currtime = mDNSPlatformUTC();
7024 
7025         diff = currtime - m->TimeSlept;
7026         FORALL_CACHERECORDS(slot, cg, cr)
7027         {
7028             // Temporary fix: For unicast cache records, look at how much time we slept.
7029             // Adjust the RecvTime by the amount of time we slept so that we age the
7030             // cache record appropriately. If it is expired already, purge. If there
7031             // is a network change that happens after the wakeup, we might purge the
7032             // cache anyways and this helps only in the case where there are no network
7033             // changes across sleep/wakeup transition.
7034             //
7035             // Note: If there is a network/DNS server change that already happened and
7036             // these cache entries are already refreshed and we are getting a delayed
7037             // wake up notification, we might adjust the TimeRcvd based on the time slept
7038             // now which can cause the cache to purge pre-maturely. As this is not a very
7039             // common case, this should happen rarely.
7040             if (!cr->resrec.InterfaceID)
7041             {
7042                 if (diff > 0)
7043                 {
7044                     mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl);
7045                     const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond;
7046 
7047                     // -if we have slept longer than the remaining TTL, purge and start fresh.
7048                     // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
7049                     //  a sufficiently big value which could cause the value to go into the future
7050                     //  because of the signed comparison of time. For this to happen, we should have been
7051                     //  sleeping really long (~24 days). For now, we want to be conservative and flush even
7052                     //  if we have slept for more than two days.
7053 
7054                     if (diff >= remain || diff > (2 * 24 * 3600))
7055                     {
7056                         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7057                                   "mDNSCoreMachineSleep: " PRI_S ": Purging cache entry SleptTime %d, Remaining TTL %d",
7058                                   CRDisplayString(m, cr), diff, remain);
7059                         mDNS_PurgeCacheResourceRecord(m, cr);
7060                         continue;
7061                     }
7062                     cr->TimeRcvd -= (diff * mDNSPlatformOneSecond);
7063                     if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
7064                     {
7065                         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7066                                   "mDNSCoreMachineSleep: " PRI_S ": Purging after adjusting the remaining TTL %d by %d seconds",
7067                                   CRDisplayString(m, cr), remain, diff);
7068                         mDNS_PurgeCacheResourceRecord(m, cr);
7069                     }
7070                     else
7071                     {
7072                         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG,
7073                                   "mDNSCoreMachineSleep: " PRI_S ": Adjusted the remain ttl %u by %d seconds",
7074                                   CRDisplayString(m, cr), remain, diff);
7075                     }
7076                 }
7077             }
7078             else
7079             {
7080                 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
7081             }
7082         }
7083 
7084         // 3. Retrigger probing and announcing for all our authoritative records
7085         for (rr = m->ResourceRecords; rr; rr=rr->next)
7086         {
7087             if (AuthRecord_uDNS(rr))
7088             {
7089                 ActivateUnicastRegistration(m, rr);
7090             }
7091             else
7092             {
7093                 mDNSCoreRestartRegistration(m, rr, -1);
7094             }
7095         }
7096 
7097         // 4. Refresh NAT mappings
7098         // We don't want to have to assume that all hardware can necessarily keep accurate
7099         // track of passage of time while asleep, so on wake we refresh our NAT mappings.
7100         // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
7101         // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
7102         // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
7103         // than five seconds from now.
7104         LogRedact(MDNS_LOG_CATEGORY_SPS, MDNS_LOG_DEBUG, "mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
7105         RecreateNATMappings(m, mDNSPlatformOneSecond * 5);
7106         mDNS_Unlock(m);
7107     }
7108 }
7109 
7110 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
7111 {
7112     DNSQuestion *q;
7113     AuthRecord *rr;
7114     NetworkInterfaceInfo *intf;
7115 
7116     mDNS_Lock(m);
7117 
7118     if (m->DelaySleep) goto notready;
7119 
7120     // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
7121     if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
7122 
7123     m->NextScheduledSPRetry = now + 0x40000000UL;
7124 
7125     // See if we might need to retransmit any lost Sleep Proxy Registrations
7126     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7127         if (intf->NextSPSAttempt >= 0)
7128         {
7129             if (now - intf->NextSPSAttemptTime >= 0)
7130             {
7131                 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
7132                        intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
7133                 SendSPSRegistration(m, intf, zeroID);
7134                 // Don't need to "goto notready" here, because if we do still have record registrations
7135                 // that have not been acknowledged yet, we'll catch that in the record list scan below.
7136             }
7137             else
7138             if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
7139                 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
7140         }
7141 
7142     // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
7143     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7144     {
7145         int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
7146         if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
7147         {
7148             LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
7149                    intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
7150             goto spsnotready;
7151         }
7152     }
7153 
7154     // Scan list of registered records
7155     for (rr = m->ResourceRecords; rr; rr = rr->next)
7156         if (!AuthRecord_uDNS(rr))
7157             if (!mDNSOpaque64IsZero(&rr->updateIntID))
7158             { 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; }
7159 
7160     // Scan list of private LLQs, and make sure they've all completed their handshake with the server
7161     for (q = m->Questions; q; q = q->next)
7162         if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
7163         {
7164             LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
7165             goto notready;
7166         }
7167 
7168     // Scan list of registered records
7169     for (rr = m->ResourceRecords; rr; rr = rr->next)
7170         if (AuthRecord_uDNS(rr))
7171         {
7172             if (rr->state == regState_Refresh && rr->tcp)
7173             { 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; }
7174         }
7175 
7176     mDNS_Unlock(m);
7177     return mDNStrue;
7178 
7179 spsnotready:
7180 
7181     // If we failed to complete sleep proxy registration within ten seconds, we give up on that
7182     // and allow up to ten seconds more to complete wide-area deregistration instead
7183     if (now - m->SleepLimit >= 0)
7184     {
7185         LogMsg("Failed to register with SPS, now sending goodbyes");
7186 
7187         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
7188             if (intf->NetWakeBrowse.ThisQInterval >= 0)
7189             {
7190                 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
7191                        intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
7192                 mDNS_DeactivateNetWake_internal(m, intf);
7193             }
7194 
7195         for (rr = m->ResourceRecords; rr; rr = rr->next)
7196             if (!AuthRecord_uDNS(rr))
7197                 if (!mDNSOpaque64IsZero(&rr->updateIntID))
7198                 {
7199                     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));
7200                     rr->updateIntID = zeroOpaque64;
7201                 }
7202 
7203         // We'd really like to allow up to ten seconds more here,
7204         // but if we don't respond to the sleep notification within 30 seconds
7205         // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
7206         // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
7207         // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
7208         // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
7209         m->SleepLimit = now + mDNSPlatformOneSecond * 1;
7210 
7211         SendSleepGoodbyes(m, mDNStrue, mDNStrue);
7212     }
7213 
7214 notready:
7215     mDNS_Unlock(m);
7216     return mDNSfalse;
7217 }
7218 
7219 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now, mDNSNextWakeReason *outReason)
7220 {
7221     AuthRecord *ar;
7222 
7223     // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
7224     // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
7225     // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
7226     // and if that happens we don't want to just give up and go back to sleep and never try again.
7227     mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond);       // Sleep for at most 120 minutes
7228     mDNSNextWakeReason reason = mDNSNextWakeReason_UpkeepWake;
7229 
7230     NATTraversalInfo *nat;
7231     for (nat = m->NATTraversals; nat; nat=nat->next)
7232     {
7233         if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
7234         {
7235             mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10;     // Wake up when 90% of the way to the expiry time
7236             if ((e - t) > 0)
7237             {
7238                 e = t;
7239                 reason = mDNSNextWakeReason_NATPortMappingRenewal;
7240             }
7241             LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
7242                    nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
7243                    mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
7244                    nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
7245                    nat->retryInterval / mDNSPlatformOneSecond,
7246                    nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
7247                    (t - now) / mDNSPlatformOneSecond);
7248         }
7249     }
7250     // This loop checks both the time we need to renew wide-area registrations,
7251     // and the time we need to renew Sleep Proxy registrations
7252     for (ar = m->ResourceRecords; ar; ar = ar->next)
7253     {
7254         if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
7255         {
7256             mDNSs32 t = ar->expire - (ar->expire - now) / 10;       // Wake up when 90% of the way to the expiry time
7257             if ((e - t) > 0)
7258             {
7259                 e = t;
7260                 reason = mDNSNextWakeReason_RecordRegistrationRenewal;
7261             }
7262             LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
7263                    ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
7264                    (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
7265                    ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
7266                    (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
7267         }
7268     }
7269     if (outReason)
7270     {
7271         *outReason = reason;
7272     }
7273     return(e - now);
7274 }
7275 
7276 // ***************************************************************************
7277 #if COMPILER_LIKES_PRAGMA_MARK
7278 #pragma mark -
7279 #pragma mark - Packet Reception Functions
7280 #endif
7281 
7282 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
7283 
7284 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
7285                                           const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
7286 {
7287     mDNSu8          *responseptr     = response->data;
7288     const mDNSu8    *const limit     = response->data + sizeof(response->data);
7289     const mDNSu8    *ptr             = query->data;
7290     AuthRecord  *rr;
7291     mDNSu32 maxttl = (!InterfaceID) ? mDNSMaximumUnicastTTLSeconds : mDNSMaximumMulticastTTLSeconds;
7292     int i;
7293 
7294     // Initialize the response fields so we can answer the questions
7295     InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
7296 
7297     // ***
7298     // *** 1. Write out the list of questions we are actually going to answer with this packet
7299     // ***
7300     if (LegacyQuery)
7301     {
7302         maxttl = kStaticCacheTTL;
7303         for (i=0; i<query->h.numQuestions; i++)                     // For each question...
7304         {
7305             DNSQuestion q;
7306             ptr = getQuestion(query, ptr, end, InterfaceID, &q);    // get the question...
7307             if (!ptr) return(mDNSNULL);
7308 
7309             for (rr=ResponseRecords; rr; rr=rr->NextResponse)       // and search our list of proposed answers
7310             {
7311                 if (rr->NR_AnswerTo == ptr)                         // If we're going to generate a record answering this question
7312                 {                                                   // then put the question in the question section
7313                     responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
7314                     if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
7315                     break;      // break out of the ResponseRecords loop, and go on to the next question
7316                 }
7317             }
7318         }
7319 
7320         if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
7321     }
7322 
7323     // ***
7324     // *** 2. Write Answers
7325     // ***
7326     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7327         if (rr->NR_AnswerTo)
7328         {
7329             mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
7330                                              maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7331             if (p) responseptr = p;
7332             else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
7333         }
7334 
7335     // ***
7336     // *** 3. Write Additionals
7337     // ***
7338     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7339         if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
7340         {
7341             mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
7342                                              maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
7343             if (p) responseptr = p;
7344             else debugf("GenerateUnicastResponse: No more space for additionals");
7345         }
7346 
7347     return(responseptr);
7348 }
7349 
7350 // AuthRecord *our is our Resource Record
7351 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
7352 // Returns 0 if there is no conflict
7353 // Returns +1 if there was a conflict and we won
7354 // Returns -1 if there was a conflict and we lost and have to rename
7355 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
7356 {
7357     mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
7358     mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
7359     if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
7360     if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
7361 
7362 #if defined(__clang_analyzer__)
7363     // Get rid of analyzer warnings about ourptr and pktptr pointing to garbage after retruning from putRData().
7364     // There are no clear indications from the analyzer of the cause of the supposed problem.
7365     mDNSPlatformMemZero(ourdata, 1);
7366     mDNSPlatformMemZero(pktdata, 1);
7367 #endif
7368     ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
7369     pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
7370     while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
7371     if (ourptr >= ourend && pktptr >= pktend) return(0);            // If data identical, not a conflict
7372 
7373     if (ourptr >= ourend) return(-1);                               // Our data ran out first; We lost
7374     if (pktptr >= pktend) return(+1);                               // Packet data ran out first; We won
7375     if (*pktptr > *ourptr) return(-1);                              // Our data is numerically lower; We lost
7376     if (*pktptr < *ourptr) return(+1);                              // Packet data is numerically lower; We won
7377 
7378     LogMsg("CompareRData ERROR: Invalid state");
7379     return(-1);
7380 }
7381 
7382 mDNSlocal mDNSBool PacketRecordMatches(const AuthRecord *const rr, const CacheRecord *const pktrr, const AuthRecord *const master)
7383 {
7384     if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7385     {
7386         const AuthRecord *r2 = rr;
7387         while (r2->DependentOn) r2 = r2->DependentOn;
7388         if (r2 == master) return(mDNStrue);
7389     }
7390     return(mDNSfalse);
7391 }
7392 
7393 // See if we have an authoritative record that's identical to this packet record,
7394 // whose canonical DependentOn record is the specified master record.
7395 // The DependentOn pointer is typically used for the TXT record of service registrations
7396 // It indicates that there is no inherent conflict detection for the TXT record
7397 // -- it depends on the SRV record to resolve name conflicts
7398 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
7399 // pointer chain (if any) to make sure we reach the canonical DependentOn record
7400 // If the record has no DependentOn, then just return that record's pointer
7401 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7402 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
7403 {
7404     const AuthRecord *r1;
7405     for (r1 = m->ResourceRecords; r1; r1=r1->next)
7406     {
7407         if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue);
7408     }
7409     for (r1 = m->DuplicateRecords; r1; r1=r1->next)
7410     {
7411         if (PacketRecordMatches(r1, pktrr, master)) return(mDNStrue);
7412     }
7413     return(mDNSfalse);
7414 }
7415 
7416 // Find the canonical RRSet pointer for this RR received in a packet.
7417 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
7418 // pointers (if any) to make sure we return the canonical member of this name/type/class
7419 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
7420 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
7421 {
7422     const AuthRecord *rr;
7423     for (rr = m->ResourceRecords; rr; rr=rr->next)
7424     {
7425         if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7426         {
7427             return(rr->RRSet ? rr->RRSet : rr);
7428         }
7429     }
7430     return(mDNSNULL);
7431 }
7432 
7433 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7434 // as one of our records (our) but different rdata.
7435 // 1. If our record is not a type that's supposed to be unique, we don't care.
7436 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7437 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7438 //     points to our record, ignore this conflict (e.g. the packet record matches one of our
7439 //     TXT records, and that record is marked as dependent on 'our', its SRV record).
7440 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7441 //    are members of the same RRSet, then this is not a conflict.
7442 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
7443 {
7444     // If not supposed to be unique, not a conflict
7445     if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
7446 
7447     // If a dependent record, not a conflict
7448     if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
7449     else
7450     {
7451         // If the pktrr matches a member of ourset, not a conflict
7452         const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
7453         const AuthRecord *pktset = FindRRSet(m, pktrr);
7454         if (pktset == ourset) return(mDNSfalse);
7455 
7456         // For records we're proxying, where we don't know the full
7457         // relationship between the records, having any matching record
7458         // in our AuthRecords list is sufficient evidence of non-conflict
7459         if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
7460     }
7461 
7462     // Okay, this is a conflict
7463     return(mDNStrue);
7464 }
7465 
7466 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7467 // the record list and/or question list.
7468 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7469 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7470                                         DNSQuestion *q, AuthRecord *our)
7471 {
7472     int i;
7473     const mDNSu8 *ptr = LocateAuthorities(query, end);
7474     mDNSBool FoundUpdate = mDNSfalse;
7475 
7476     for (i = 0; i < query->h.numAuthorities; i++)
7477     {
7478         ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7479         if (!ptr) break;
7480         if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && CacheRecordAnswersQuestion(&m->rec.r, q))
7481         {
7482             FoundUpdate = mDNStrue;
7483             if (PacketRRConflict(m, our, &m->rec.r))
7484             {
7485                 int result          = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
7486                 if (!result) result = (int)our->resrec.rrtype  - (int)m->rec.r.resrec.rrtype;
7487                 if (!result) result = CompareRData(our, &m->rec.r);
7488                 if (result)
7489                 {
7490                     const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
7491                     LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7492                     LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
7493                 }
7494                 // 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.
7495                 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7496                 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7497                 if (result < 0)
7498                 {
7499                     m->SuppressProbes   = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7500                     our->ProbeCount     = DefaultProbeCountForTypeUnique;
7501                     our->AnnounceCount  = InitialAnnounceCount;
7502                     InitializeLastAPTime(m, our);
7503                     goto exit;
7504                 }
7505             }
7506 #if 0
7507             else
7508             {
7509                 LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7510                 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign:  %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
7511             }
7512 #endif
7513         }
7514         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7515     }
7516     if (!FoundUpdate)
7517         LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
7518 exit:
7519     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7520 }
7521 
7522 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
7523 {
7524     CacheGroup *cg = CacheGroupForRecord(m, pktrr);
7525     CacheRecord *rr;
7526     mDNSBool match;
7527     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7528     {
7529         if (!pktrr->InterfaceID)
7530         {
7531 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
7532             match = (pktrr->dnsservice == rr->resrec.dnsservice) ? mDNStrue : mDNSfalse;
7533 #else
7534             const mDNSu32 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
7535             const mDNSu32 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
7536             match = (id1 == id2);
7537 #endif
7538         }
7539         else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
7540 
7541         if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
7542     }
7543     return(rr);
7544 }
7545 mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr)
7546 {
7547     rr->WakeUp.HMAC    = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7548     rr->RequireGoodbye = mDNSfalse;   // and we don't want to send goodbye for it
7549     mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7550     SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7551 }
7552 
7553 mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID)
7554 {
7555     if (m->CurrentRecord)
7556         LogMsg("ClearKeepaliveProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7557     m->CurrentRecord = thelist;
7558 
7559     // Normally, the RDATA of the keepalive record will be different each time and hence we always
7560     // clean up the keepalive record.
7561     while (m->CurrentRecord)
7562     {
7563         AuthRecord *const rr = m->CurrentRecord;
7564         if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7565         {
7566             if (mDNS_KeepaliveRecord(&m->rec.r.resrec))
7567             {
7568                 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7569                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7570                 DeregisterProxyRecord(m, rr);
7571             }
7572         }
7573         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7574         // new records could have been added to the end of the list as a result of that call.
7575         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7576             m->CurrentRecord = rr->next;
7577     }
7578 }
7579 
7580 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7581 // to check our lists and discard any stale duplicates of this record we already have
7582 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7583 {
7584     if (m->CurrentRecord)
7585         LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7586     m->CurrentRecord = thelist;
7587     while (m->CurrentRecord)
7588     {
7589         AuthRecord *const rr = m->CurrentRecord;
7590         if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7591             if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
7592             {
7593                 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7594                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7595                 DeregisterProxyRecord(m, rr);
7596             }
7597         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7598         // new records could have been added to the end of the list as a result of that call.
7599         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7600             m->CurrentRecord = rr->next;
7601     }
7602 }
7603 
7604 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7605 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7606 {
7607     if (m->CurrentRecord)
7608         LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7609     m->CurrentRecord = thelist;
7610     while (m->CurrentRecord)
7611     {
7612         AuthRecord *const rr = m->CurrentRecord;
7613         if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7614             if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
7615             {
7616                 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
7617                 {
7618                     // We don't do this here because we know that the host is waking up at this point, so we don't send
7619                     // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7620                     // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7621                     #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7622                     LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7623                            &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
7624                     SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
7625                     #endif
7626                 }
7627                 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7628                        m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
7629                        &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7630                 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
7631                 rr->WakeUp.HMAC = zeroEthAddr;  // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7632                 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
7633                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7634                 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7635             }
7636         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7637         // new records could have been added to the end of the list as a result of that call.
7638         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7639             m->CurrentRecord = rr->next;
7640     }
7641 }
7642 
7643 // ProcessQuery examines a received query to see if we have any answers to give
7644 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7645                                const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
7646                                mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
7647 {
7648     const mDNSBool FromLocalSubnet   = mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7649     AuthRecord   *ResponseRecords    = mDNSNULL;
7650     AuthRecord  **nrp                = &ResponseRecords;
7651 
7652 #if POOF_ENABLED
7653     mDNSBool    notD2D = !mDNSPlatformInterfaceIsD2D(InterfaceID);  // We don't run the POOF algorithm on D2D interfaces.
7654     CacheRecord  *ExpectedAnswers    = mDNSNULL;            // Records in our cache we expect to see updated
7655     CacheRecord **eap                = &ExpectedAnswers;
7656 #endif // POOF_ENABLED
7657 
7658     DNSQuestion  *DupQuestions       = mDNSNULL;            // Our questions that are identical to questions in this packet
7659     DNSQuestion **dqp                = &DupQuestions;
7660     mDNSs32 delayresponse      = 0;
7661     mDNSBool SendLegacyResponse = mDNSfalse;
7662     const mDNSu8 *ptr;
7663     mDNSu8       *responseptr        = mDNSNULL;
7664     AuthRecord   *rr;
7665     int i;
7666 
7667     // ***
7668     // *** 1. Look in Additional Section for an OPT record
7669     // ***
7670     ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
7671     if (ptr)
7672     {
7673         ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
7674         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7675         {
7676             const rdataOPT *opt;
7677             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7678             // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7679             // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7680             for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7681                 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7682                 {
7683                     ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7684                     ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7685                 }
7686         }
7687         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7688     }
7689 
7690     // ***
7691     // *** 2. Parse Question Section and mark potential answers
7692     // ***
7693     ptr = query->data;
7694     for (i=0; i<query->h.numQuestions; i++)                     // For each question...
7695     {
7696         mDNSBool QuestionNeedsMulticastResponse;
7697         int NumAnswersForThisQuestion = 0;
7698         AuthRecord *NSECAnswer = mDNSNULL;
7699         DNSQuestion pktq, *q;
7700         ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
7701         if (!ptr) goto exit;
7702 
7703         // The only queries that *need* a multicast response are:
7704         // * Queries sent via multicast
7705         // * from port 5353
7706         // * that don't have the kDNSQClass_UnicastResponse bit set
7707         // These queries need multicast responses because other clients will:
7708         // * suppress their own identical questions when they see these questions, and
7709         // * expire their cache records if they don't see the expected responses
7710         // For other queries, we may still choose to send the occasional multicast response anyway,
7711         // to keep our neighbours caches warm, and for ongoing conflict detection.
7712         QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
7713 
7714         if (pktq.qclass & kDNSQClass_UnicastResponse)
7715             m->mDNSStats.UnicastBitInQueries++;
7716         else
7717             m->mDNSStats.NormalQueries++;
7718 
7719         // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7720         pktq.qclass &= ~kDNSQClass_UnicastResponse;
7721 
7722         // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7723         // can result in user callbacks which may change the record list and/or question list.
7724         // Also note: we just mark potential answer records here, without trying to build the
7725         // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7726         // from that list while we're in the middle of trying to build it.
7727         if (m->CurrentRecord)
7728             LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7729         m->CurrentRecord = m->ResourceRecords;
7730         while (m->CurrentRecord)
7731         {
7732             rr = m->CurrentRecord;
7733             m->CurrentRecord = rr->next;
7734             if (AnyTypeRecordAnswersQuestion(rr, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
7735             {
7736                 m->mDNSStats.MatchingAnswersForQueries++;
7737                 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
7738                 {
7739                     if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7740                         ResolveSimultaneousProbe(m, query, end, &pktq, rr);
7741                     else if (ResourceRecordIsValidAnswer(rr))
7742                     {
7743                         NumAnswersForThisQuestion++;
7744 
7745                         // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7746                         // unicast answer back to the source, because timeliness in answering probes is important.
7747 
7748                         // Notes:
7749                         // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7750                         // NR_AnswerTo == NR_AnswerUnicast   means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7751                         // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7752                         // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7753                         // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7754                         // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7755                         if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
7756                         {
7757                             // We only mark this question for sending if it is at least one second since the last time we multicast it
7758                             // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7759                             // This is to guard against the case where someone blasts us with queries as fast as they can.
7760                             if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)mDNSPlatformOneSecond ||
7761                                 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
7762                                 rr->NR_AnswerTo = NR_AnswerMulticast;
7763                         }
7764                         else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast;
7765                     }
7766                 }
7767                 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
7768                 {
7769                     // If we don't have any answers for this question, but we do own another record with the same name,
7770                     // then we'll want to mark it to generate an NSEC record on this interface
7771                     if (!NSECAnswer) NSECAnswer = rr;
7772                 }
7773             }
7774         }
7775 
7776         if (NumAnswersForThisQuestion == 0 && NSECAnswer)
7777         {
7778             NumAnswersForThisQuestion++;
7779             NSECAnswer->SendNSECNow = InterfaceID;
7780             m->NextScheduledResponse = m->timenow;
7781         }
7782 
7783         // If we couldn't answer this question, someone else might be able to,
7784         // so use random delay on response to reduce collisions
7785         if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond;  // Divided by 50 = 20ms
7786 
7787         if (query->h.flags.b[0] & kDNSFlag0_TC)
7788             m->mDNSStats.KnownAnswerMultiplePkts++;
7789         // We only do the following accelerated cache expiration and duplicate question suppression processing
7790         // for non-truncated multicast queries with multicast responses.
7791         // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7792         // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7793         // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7794         if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
7795         {
7796 #if POOF_ENABLED
7797             if (notD2D)
7798             {
7799                 CacheGroup *cg = CacheGroupForName(m, pktq.qnamehash, &pktq.qname);
7800                 CacheRecord *cr;
7801 
7802                 // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7803                 // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7804                 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7805                 {
7806                     if (SameNameCacheRecordAnswersQuestion(cr, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
7807                     {
7808                         if (!cr->NextInKAList && eap != &cr->NextInKAList)
7809                         {
7810                             *eap = cr;
7811                             eap = &cr->NextInKAList;
7812                         }
7813                     }
7814                 }
7815             }
7816 #endif // POOF_ENABLED
7817 
7818             // Check if this question is the same as any of mine.
7819             // We only do this for non-truncated queries. Right now it would be too complicated to try
7820             // to keep track of duplicate suppression state between multiple packets, especially when we
7821             // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7822             for (q = m->Questions; q; q=q->next)
7823             {
7824                 if (ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
7825                 {
7826                     if (!q->InterfaceID || q->InterfaceID == InterfaceID)
7827                     {
7828                         if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
7829                         {
7830                             if (q->qtype == pktq.qtype &&
7831                                 q->qclass == pktq.qclass &&
7832                                 q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
7833                             { *dqp = q; dqp = &q->NextInDQList; }
7834                         }
7835                     }
7836                 }
7837             }
7838         }
7839     }
7840 
7841     // ***
7842     // *** 3. Now we can safely build the list of marked answers
7843     // ***
7844     for (rr = m->ResourceRecords; rr; rr=rr->next)              // Now build our list of potential answers
7845         if (rr->NR_AnswerTo)                                    // If we marked the record...
7846             AddRecordToResponseList(&nrp, rr, mDNSNULL);        // ... add it to the list
7847 
7848     // ***
7849     // *** 4. Add additional records
7850     // ***
7851     AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
7852 
7853     // ***
7854     // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7855     // ***
7856     for (i=0; i<query->h.numAnswers; i++)                       // For each record in the query's answer section...
7857     {
7858         // Get the record...
7859         CacheRecord *ourcacherr;
7860         ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
7861         if (!ptr) goto exit;
7862         if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7863         {
7864             // See if this Known-Answer suppresses any of our currently planned answers
7865             for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7866             {
7867                 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7868                 {
7869                     m->mDNSStats.KnownAnswerSuppressions++;
7870                     rr->NR_AnswerTo = mDNSNULL;
7871                     rr->NR_AdditionalTo = mDNSNULL;
7872                 }
7873             }
7874 
7875             // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7876             for (rr=m->ResourceRecords; rr; rr=rr->next)
7877             {
7878                 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7879                 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7880                 {
7881                     if (srcaddr->type == mDNSAddrType_IPv4)
7882                     {
7883                         if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
7884                     }
7885                     else if (srcaddr->type == mDNSAddrType_IPv6)
7886                     {
7887                         if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
7888                     }
7889                     if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
7890                     {
7891                         m->mDNSStats.KnownAnswerSuppressions++;
7892                         rr->ImmedAnswer  = mDNSNULL;
7893                         rr->ImmedUnicast = mDNSfalse;
7894     #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7895                         LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
7896     #endif
7897                     }
7898                 }
7899             }
7900 
7901             ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
7902 
7903 #if POOF_ENABLED
7904             if (notD2D)
7905             {
7906                 // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7907                 // any records that are suppressed by the Known Answer list in this packet.
7908                 eap = &ExpectedAnswers;
7909                 while (*eap)
7910                 {
7911                     CacheRecord *cr = *eap;
7912                     if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
7913                     { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
7914                     else eap = &cr->NextInKAList;
7915                 }
7916             }
7917 #endif // POOF_ENABLED
7918 
7919             // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7920             if (!ourcacherr)
7921             {
7922                 dqp = &DupQuestions;
7923                 while (*dqp)
7924                 {
7925                     DNSQuestion *q = *dqp;
7926                     if (CacheRecordAnswersQuestion(&m->rec.r, q))
7927                     { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
7928                     else dqp = &q->NextInDQList;
7929                 }
7930             }
7931         }
7932         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7933     }
7934 
7935     // ***
7936     // *** 6. Cancel any additionals that were added because of now-deleted records
7937     // ***
7938     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7939         if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
7940         { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
7941 
7942     // ***
7943     // *** 7. Mark the send flags on the records we plan to send
7944     // ***
7945     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7946     {
7947         if (rr->NR_AnswerTo)
7948         {
7949             mDNSBool SendMulticastResponse = mDNSfalse;     // Send modern multicast response
7950             mDNSBool SendUnicastResponse   = mDNSfalse;     // Send modern unicast response (not legacy unicast response)
7951 
7952             // If it's been one TTL/4 since we multicast this, then send a multicast response
7953             // for conflict detection, etc.
7954             if ((mDNSu32)(m->timenow - rr->LastMCTime) >= (mDNSu32)TicksTTL(rr)/4)
7955             {
7956                 SendMulticastResponse = mDNStrue;
7957                 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7958                 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7959                 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7960                 if (rr->NR_AnswerTo == NR_AnswerUnicast)
7961                 {
7962                     m->mDNSStats.UnicastDemotedToMulticast++;
7963                     rr->NR_AnswerTo = NR_AnswerMulticast;
7964                 }
7965             }
7966 
7967             // If the client insists on a multicast response, then we'd better send one
7968             if      (rr->NR_AnswerTo == NR_AnswerMulticast)
7969             {
7970                 m->mDNSStats.MulticastResponses++;
7971                 SendMulticastResponse = mDNStrue;
7972             }
7973             else if (rr->NR_AnswerTo == NR_AnswerUnicast)
7974             {
7975                 m->mDNSStats.UnicastResponses++;
7976                 SendUnicastResponse   = mDNStrue;
7977             }
7978             else if (rr->NR_AnswerTo)
7979             {
7980                 SendLegacyResponse    = mDNStrue;
7981             }
7982 
7983             if (SendMulticastResponse || SendUnicastResponse)
7984             {
7985 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7986                 rr->ImmedAnswerMarkTime = m->timenow;
7987 #endif
7988                 m->NextScheduledResponse = m->timenow;
7989                 // If we're already planning to send this on another interface, just send it on all interfaces
7990                 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
7991                     rr->ImmedAnswer = mDNSInterfaceMark;
7992                 else
7993                 {
7994                     rr->ImmedAnswer = InterfaceID;          // Record interface to send it on
7995                     if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
7996                     if (srcaddr->type == mDNSAddrType_IPv4)
7997                     {
7998                         if      (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
7999                         else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
8000                     }
8001                     else if (srcaddr->type == mDNSAddrType_IPv6)
8002                     {
8003                         if      (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
8004                         else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
8005                     }
8006                 }
8007             }
8008             // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
8009             // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
8010             // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
8011             // else, for a simple unique record reply, we can reply immediately; no need for delay
8012             if      (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20;            // Divided by 50 = 400ms
8013             else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond;      // Divided by 50 = 20ms
8014         }
8015         else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast)
8016         {
8017             // Since additional records are an optimization anyway, we only ever send them on one interface at a time
8018             // If two clients on different interfaces do queries that invoke the same optional additional answer,
8019             // then the earlier client is out of luck
8020             rr->ImmedAdditional = InterfaceID;
8021             // No need to set m->NextScheduledResponse here
8022             // We'll send these additional records when we send them, or not, as the case may be
8023         }
8024     }
8025 
8026     // ***
8027     // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
8028     // ***
8029     if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
8030     {
8031 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
8032         mDNSs32 oldss = m->SuppressSending;
8033         if (oldss && delayresponse)
8034             LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
8035 #endif
8036         // Pick a random delay:
8037         // We start with the base delay chosen above (typically either 1 second or 20 seconds),
8038         // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
8039         // This is an integer value, with resolution determined by the platform clock rate.
8040         // We then divide that by 50 to get the delay value in ticks. We defer the division until last
8041         // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
8042         // The +49 before dividing is to ensure we round up, not down, to ensure that even
8043         // on platforms where the native clock rate is less than fifty ticks per second,
8044         // we still guarantee that the final calculated delay is at least one platform tick.
8045         // We want to make sure we don't ever allow the delay to be zero ticks,
8046         // because if that happens we'll fail the Bonjour Conformance Test.
8047         // Our final computed delay is 20-120ms for normal delayed replies,
8048         // or 400-500ms in the case of multi-packet known-answer lists.
8049         m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
8050         if (m->SuppressSending == 0) m->SuppressSending = 1;
8051 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
8052         if (oldss && delayresponse)
8053             LogMsg("Set     SuppressSending to   %5ld", m->SuppressSending - m->timenow);
8054 #endif
8055     }
8056 
8057     // ***
8058     // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
8059     // ***
8060     if (SendLegacyResponse)
8061         responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
8062 
8063 exit:
8064     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8065 
8066     // ***
8067     // *** 10. Finally, clear our link chains ready for use next time
8068     // ***
8069     while (ResponseRecords)
8070     {
8071         rr = ResponseRecords;
8072         ResponseRecords = rr->NextResponse;
8073         rr->NextResponse    = mDNSNULL;
8074         rr->NR_AnswerTo     = mDNSNULL;
8075         rr->NR_AdditionalTo = mDNSNULL;
8076     }
8077 
8078 #if POOF_ENABLED
8079     while (ExpectedAnswers && notD2D)
8080     {
8081         CacheRecord *cr = ExpectedAnswers;
8082         ExpectedAnswers = cr->NextInKAList;
8083         cr->NextInKAList = mDNSNULL;
8084 
8085         // For non-truncated queries, we can definitively say that we should expect
8086         // to be seeing a response for any records still left in the ExpectedAnswers list
8087         if (!(query->h.flags.b[0] & kDNSFlag0_TC))
8088             if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond * 3/4)
8089             {
8090                 cr->UnansweredQueries++;
8091                 cr->LastUnansweredTime = m->timenow;
8092                 if (cr->UnansweredQueries > 1)
8093                         debugf("ProcessQuery: UnansweredQueries %lu %s", cr->UnansweredQueries, CRDisplayString(m, cr));
8094                 SetNextCacheCheckTimeForRecord(m, cr);
8095             }
8096 
8097         // If we've seen multiple unanswered queries for this record,
8098         // then mark it to expire in five seconds if we don't get a response by then.
8099         if (cr->UnansweredQueries >= MaxUnansweredQueries)
8100         {
8101             // Only show debugging message if this record was not about to expire anyway
8102             if (RRExpireTime(cr) - m->timenow > (mDNSs32) kDefaultReconfirmTimeForNoAnswer * 4 / 3 + mDNSPlatformOneSecond)
8103                     LogInfo("ProcessQuery: UnansweredQueries %lu interface %lu TTL %lu mDNS_Reconfirm() for %s",
8104                        cr->UnansweredQueries, InterfaceID, (RRExpireTime(cr) - m->timenow + mDNSPlatformOneSecond-1) / mDNSPlatformOneSecond, CRDisplayString(m, cr));
8105 
8106             m->mDNSStats.PoofCacheDeletions++;
8107             mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
8108         }
8109     }
8110 #endif // POOF_ENABLED
8111 
8112     while (DupQuestions)
8113     {
8114         DNSQuestion *q = DupQuestions;
8115         DupQuestions = q->NextInDQList;
8116         q->NextInDQList = mDNSNULL;
8117         RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
8118         debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
8119                srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6");
8120     }
8121     return(responseptr);
8122 }
8123 
8124 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
8125                                     const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8126                                     const mDNSInterfaceID InterfaceID)
8127 {
8128     mDNSu8    *responseend = mDNSNULL;
8129     mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
8130                                     !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8131 
8132     if (!dstaddr || (!InterfaceID && mDNSAddrIsDNSMulticast(dstaddr)))
8133     {
8134         const char *const reason = !dstaddr ? "Received over TCP connection" : "Multicast, but no InterfaceID";
8135         LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8136                "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (%s)",
8137                srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8138                msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
8139                msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
8140                msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
8141                msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data, reason);
8142         return;
8143     }
8144 
8145     verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
8146                   "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
8147                   srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
8148                   msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
8149                   msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
8150                   msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
8151                   msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
8152 
8153     responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
8154                                !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
8155 
8156     if (responseend)    // If responseend is non-null, that means we built a unicast response packet
8157     {
8158         debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
8159                m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
8160                m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
8161                m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
8162                srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
8163         mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSfalse);
8164     }
8165 }
8166 
8167 #if 0
8168 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
8169 {
8170     DNSServer *s;
8171     (void)m; // Unused
8172     (void)srcaddr; // Unused
8173     for (s = m->DNSServers; s; s = s->next)
8174         if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
8175     return(mDNSfalse);
8176 }
8177 #endif
8178 
8179 struct UDPSocket_struct
8180 {
8181     mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
8182 };
8183 
8184 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port,
8185     const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
8186 {
8187     DNSQuestion *q;
8188     for (q = m->Questions; q; q=q->next)
8189     {
8190         if (!tcp && !q->LocalSocket) continue;
8191         if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port)       &&
8192             q->qtype                  == question->qtype     &&
8193             q->qclass                 == question->qclass    &&
8194             q->qnamehash              == question->qnamehash &&
8195             SameDomainName(&q->qname, &question->qname))
8196         {
8197             if (mDNSSameOpaque16(q->TargetQID, id)) return(q);
8198             else
8199             {
8200                 return(mDNSNULL);
8201             }
8202         }
8203     }
8204     return(mDNSNULL);
8205 }
8206 
8207 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
8208 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
8209 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
8210                                                          const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
8211 {
8212     DNSQuestion *q;
8213     (void)id;
8214 
8215     for (q = m->Questions; q; q=q->next)
8216     {
8217         if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
8218         {
8219             if (!mDNSOpaque16IsZero(q->TargetQID))
8220             {
8221                 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
8222 
8223                 if (mDNSSameOpaque16(q->TargetQID, id))
8224                 {
8225                     mDNSIPPort srcp;
8226                     if (!tcp)
8227                     {
8228 			if (q->LocalSocket)
8229                             srcp = q->LocalSocket->port;
8230 			else
8231                             srcp = zeroIPPort;
8232                     }
8233                     else
8234                     {
8235                         srcp = q->tcpSrcPort;
8236                     }
8237                     if (mDNSSameIPPort(srcp, port)) return(q);
8238 
8239                     //  if (mDNSSameAddress(srcaddr, &q->Target))                   return(mDNStrue);
8240                     //  if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
8241                     //  if (TrustedSource(m, srcaddr))                              return(mDNStrue);
8242                     LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) from %#a:%d %s",
8243                             q->qname.c, DNSTypeName(q->qtype), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
8244                     return(mDNSNULL);
8245                 }
8246             }
8247             else
8248             {
8249                 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
8250                     return(q);
8251             }
8252         }
8253     }
8254     return(mDNSNULL);
8255 }
8256 
8257 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
8258 // Currently this applies only to rdata types containing more than one domainname,
8259 // or types where the domainname is not the last item in the structure.
8260 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
8261 {
8262     switch (rr->rrtype)
8263     {
8264     case kDNSType_SOA: return sizeof(rdataSOA);
8265     case kDNSType_RP:  return sizeof(rdataRP);
8266     case kDNSType_PX:  return sizeof(rdataPX);
8267     default:           return rr->rdlength;
8268     }
8269 }
8270 
8271 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
8272 {
8273     CacheRecord *rr = mDNSNULL;
8274     mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
8275 
8276     if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
8277 
8278     //if (RDLength > InlineCacheRDSize)
8279     //  LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
8280 
8281     if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
8282     if (cg) rr = GetCacheRecord(m, cg, RDLength);   // Make a cache record, being careful not to recycle cg
8283     if (!rr) NoCacheAnswer(m, &m->rec.r);
8284     else
8285     {
8286         RData *saveptr              = rr->resrec.rdata;     // Save the rr->resrec.rdata pointer
8287         *rr                         = m->rec.r;             // Block copy the CacheRecord object
8288 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8289         mdns_retain_null_safe(rr->resrec.dnsservice);
8290 #endif
8291         rr->resrec.rdata            = saveptr;              // Restore rr->resrec.rdata after the structure assignment
8292         rr->resrec.name             = cg->name;             // And set rr->resrec.name to point into our CacheGroup header
8293         rr->resrec.mortality        = Mortality_Mortal;
8294 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8295         rr->resrec.dnssec_result    = dnssec_indeterminate; // Set the DNSSEC validation result of a record as "indeterminate" by default.
8296 #endif
8297 
8298         rr->DelayDelivery = delay;
8299 
8300         // If this is an oversized record with external storage allocated, copy rdata to external storage
8301         if      (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
8302             LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8303         else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
8304             LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
8305         if (RDLength > InlineCacheRDSize)
8306             mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
8307 
8308         rr->next = mDNSNULL;                    // Clear 'next' pointer
8309         rr->soa  = mDNSNULL;
8310 
8311         if (sourceAddress)
8312             rr->sourceAddress = *sourceAddress;
8313 
8314         if (!rr->resrec.InterfaceID)
8315         {
8316             m->rrcache_totalused_unicast += rr->resrec.rdlength;
8317         }
8318 
8319 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8320         if (rr != mDNSNULL)
8321         {
8322             rr->denial_of_existence_records = mDNSNULL;
8323         }
8324 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8325 
8326         if (Add)
8327         {
8328             *(cg->rrcache_tail) = rr;               // Append this record to tail of cache slot list
8329             cg->rrcache_tail = &(rr->next);         // Advance tail pointer
8330             CacheRecordAdd(m, rr);  // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
8331         }
8332         else
8333         {
8334             // Can't use the "cg->name" if we are not adding to the cache as the
8335             // CacheGroup may be released anytime if it is empty
8336             domainname *name = (domainname *) mDNSPlatformMemAllocate(DomainNameLength(cg->name));
8337             if (name)
8338             {
8339                 AssignDomainName(name, cg->name);
8340                 rr->resrec.name   = name;
8341             }
8342             else
8343             {
8344                 ReleaseCacheRecord(m, rr);
8345                 NoCacheAnswer(m, &m->rec.r);
8346                 rr = mDNSNULL;
8347             }
8348         }
8349     }
8350     return(rr);
8351 }
8352 
8353 mDNSlocal void RefreshCacheRecordCacheGroupOrder(CacheGroup *cg, CacheRecord *cr)
8354 {   //  Move the cache record to the tail of the cache group to maintain a fresh ordering
8355     if (cg->rrcache_tail != &cr->next)          // If not already at the tail
8356     {
8357         CacheRecord **rp;
8358         for (rp = &cg->members; *rp; rp = &(*rp)->next)
8359         {
8360             if (*rp == cr)                      // This item points to this record
8361             {
8362                 *rp = cr->next;                 // Remove this record
8363                 break;
8364             }
8365         }
8366         cr->next = mDNSNULL;                    // This record is now last
8367         *(cg->rrcache_tail) = cr;               // Append this record to tail of cache group
8368         cg->rrcache_tail = &(cr->next);         // Advance tail pointer
8369     }
8370 }
8371 
8372 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
8373 {
8374     rr->TimeRcvd             = m->timenow;
8375     rr->resrec.rroriginalttl = ttl;
8376     rr->UnansweredQueries = 0;
8377     if (rr->resrec.mortality != Mortality_Mortal) rr->resrec.mortality = Mortality_Immortal;
8378     SetNextCacheCheckTimeForRecord(m, rr);
8379 }
8380 
8381 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
8382 {
8383     CacheRecord *rr;
8384     CacheGroup *cg = CacheGroupForName(m, q->qnamehash, &q->qname);
8385     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8386         if (rr->CRActiveQuestion == q)
8387         {
8388             //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8389             RefreshCacheRecord(m, rr, lease);
8390         }
8391 }
8392 
8393 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl)      // TTL in seconds
8394 {
8395     if      (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
8396     else if (LLQType == uDNS_LLQ_Events)
8397     {
8398         // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8399         if (ttl == 0xFFFFFFFF) ttl = 0;
8400         else ttl = kLLQ_DefLease;
8401     }
8402     else    // else not LLQ (standard uDNS response)
8403     {
8404         // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8405         // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8406         if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
8407 
8408         ttl = RRAdjustTTL(ttl);
8409 
8410         // For mDNS, TTL zero means "delete this record"
8411         // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8412         // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8413         // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8414         // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8415         // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8416         // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8417         // (with the current code) result in the server having even less than three seconds to respond
8418         // before we deleted the record and reported a "remove" event to any active questions.
8419         // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8420         // then things really break (e.g. we end up making a negative cache entry).
8421         // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8422         if (ttl < 15) ttl = 15;
8423     }
8424 
8425     return ttl;
8426 }
8427 
8428 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8429 // in m->rec.
8430 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist)
8431 {
8432     CacheRecord *const newcr = &m->rec.r;
8433     ResourceRecord *rr = &newcr->resrec;
8434     const CacheRecord *cr;
8435 
8436     for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
8437     {
8438         domainname *target = GetRRDomainNameTarget(&cr->resrec);
8439         // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8440         // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8441         // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8442         // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8443         // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8444 
8445         if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
8446         {
8447             LogDebug("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
8448             return (mDNStrue);
8449         }
8450     }
8451     return mDNSfalse;
8452 }
8453 
8454 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8455     const mDNSAddr *dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID,
8456 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8457     const mdns_querier_t querier, const mdns_dns_service_t uDNSService,
8458 #endif
8459 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8460     denial_of_existence_records_t **denial_of_existence_records_ptr,
8461 #endif
8462     const uDNS_LLQType LLQType)
8463 {
8464     int i;
8465     const mDNSu8 *ptr   = response->data;
8466     CacheRecord *SOARecord = mDNSNULL;
8467 
8468     for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8469     {
8470         DNSQuestion q;
8471         ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8472         if (ptr)
8473         {
8474             DNSQuestion *qptr;
8475             CacheRecord *cr, *neg = mDNSNULL;
8476             CacheGroup *cg;
8477 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8478             if (querier)
8479             {
8480                 qptr = Querier_GetDNSQuestion(querier);
8481             }
8482             else
8483 #endif
8484             {
8485                 qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr);
8486                 if (!qptr)
8487                 {
8488                     continue;
8489                 }
8490             }
8491             cg = CacheGroupForName(m, q.qnamehash, &q.qname);
8492             for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
8493             {
8494                 mDNSBool isAnswer;
8495 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8496                 if (querier)
8497                 {
8498                     isAnswer = (cr->resrec.dnsservice == uDNSService) && Querier_SameNameCacheRecordIsAnswer(cr, querier);
8499                 }
8500                 else
8501 #endif
8502                 {
8503                     isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr);
8504                 }
8505                 if (isAnswer)
8506                 {
8507                     // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8508                     if (RRExpireTime(cr) - m->timenow > 0) break;
8509                     // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8510                     if (cr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = cr;
8511                     else if (cr->resrec.mortality == Mortality_Ghost)
8512                     {
8513                         // 3. If the existing entry is expired, mark it to be purged
8514                         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8515                             "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Removing expired record" PRI_S,
8516                             q.request_id, mDNSVal16(q.TargetQID), CRDisplayString(m, cr));
8517                         mDNS_PurgeCacheResourceRecord(m, cr);
8518                    }
8519                 }
8520             }
8521             // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8522             // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8523             // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8524             // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8525             // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8526             // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8527             // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8528             // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8529             // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8530             // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8531             //
8532             // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8533             // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8534             // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8535             // case without creating the negative cache entries, we generate a negative response and let the layer above us
8536             // do the appropriate thing. This negative response is also needed for appending new search domains.
8537             if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
8538             {
8539                 if (!cr)
8540                 {
8541                     if (qptr)
8542                     {
8543                         const mDNSBool noData = ((response->h.flags.b[1] & kDNSFlag1_RC_Mask) == kDNSFlag1_RC_NoErr) ? mDNStrue : mDNSfalse;
8544                         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8545                             "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Generate negative response for " PRI_DM_NAME " (" PUB_S ")",
8546                             q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
8547                         m->CurrentQuestion = qptr;
8548                         // We are not creating a cache record in this case, we need to pass back
8549                         // the error we got so that the proxy code can return the right one to
8550                         // the application
8551                         if (qptr->ProxyQuestion)
8552                             qptr->responseFlags = response->h.flags;
8553                         GenerateNegativeResponseEx(m, mDNSInterface_Any, QC_forceresponse, noData);
8554                         m->CurrentQuestion = mDNSNULL;
8555                     }
8556                 }
8557                 else
8558                 {
8559                     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8560                         "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for " PRI_DM_NAME " (" PUB_S ")",
8561                         q.request_id, mDNSVal16(q.TargetQID), DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
8562                 }
8563             }
8564             else
8565             {
8566                 if (!cr)
8567                 {
8568                     // We start off assuming a negative caching TTL of 60 seconds
8569                     // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8570                     mDNSu32 negttl = 60;
8571                     int repeat = 0;
8572                     const domainname *name = &q.qname;
8573                     mDNSu32 hash = q.qnamehash;
8574 
8575                     // Special case for our special Microsoft Active Directory "local SOA" check.
8576                     // Some cheap home gateways don't include an SOA record in the authority section when
8577                     // they send negative responses, so we don't know how long to cache the negative result.
8578                     // Because we don't want to keep hitting the root name servers with our query to find
8579                     // if we're on a network using Microsoft Active Directory using "local" as a private
8580                     // internal top-level domain, we make sure to cache the negative result for at least one day.
8581                     if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
8582 
8583                     // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8584                     if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
8585                     {
8586                         ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8587                         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
8588                         {
8589                             CacheGroup *cgSOA = CacheGroupForRecord(m, &m->rec.r.resrec);
8590                             const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
8591                             mDNSu32 ttl_s = soa->min;
8592                             // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8593                             // for the SOA record for ".", where the record is reported as non-cacheable
8594                             // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8595                             if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
8596                                 ttl_s = m->rec.r.resrec.rroriginalttl;
8597                             if (negttl < ttl_s) negttl = ttl_s;
8598 
8599                             // Create the SOA record as we may have to return this to the questions
8600                             // that we are acting as a proxy for currently or in the future.
8601                             SOARecord = CreateNewCacheEntry(m, HashSlotFromNameHash(m->rec.r.resrec.namehash), cgSOA, 1, mDNSfalse, mDNSNULL);
8602 
8603                             // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8604                             // with an Authority Section SOA record for d.com, then this is a hint that the authority
8605                             // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8606                             // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8607                             //
8608                             // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8609                             // along with the negative cache record. For simplicity, we don't create the additional records.
8610                             if ((!qptr || !qptr->ProxyQuestion) && (q.qtype == kDNSType_SOA))
8611                             {
8612                                 int qcount = CountLabels(&q.qname);
8613                                 int scount = CountLabels(m->rec.r.resrec.name);
8614                                 if (qcount - 1 > scount)
8615                                     if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
8616                                         repeat = qcount - 1 - scount;
8617                             }
8618                         }
8619                         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8620                     }
8621 
8622                     // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8623                     // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8624                     // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8625                     // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8626                     // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8627                     // so that we back off our polling rate and don't keep hitting the server continually.
8628                     if (neg)
8629                     {
8630                         if (negttl < neg->resrec.rroriginalttl * 2)
8631                             negttl = neg->resrec.rroriginalttl * 2;
8632                         if (negttl > 3600)
8633                             negttl = 3600;
8634                     }
8635 
8636                     negttl = GetEffectiveTTL(LLQType, negttl);  // Add 25% grace period if necessary
8637 
8638                     // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8639                     if (neg)
8640                     {
8641                         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
8642                             "[R%u->Q%u] mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d " PRI_S,
8643                             q.request_id, mDNSVal16(q.TargetQID), neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
8644                         RefreshCacheRecord(m, neg, negttl);
8645 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8646                         // replace the old records with the new ones
8647                         // If qptr is NULL, it means the question is no longer active, and we do not process the record
8648                         // for DNSSEC.
8649                         if ((qptr != mDNSNULL) && qptr->DNSSECStatus.enable_dnssec)
8650                         {
8651                             update_denial_records_in_cache_record(neg, denial_of_existence_records_ptr);
8652                         }
8653 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8654                         // When we created the cache for the first time and answered the question, the question's
8655                         // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8656                         // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8657                         // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8658                         // we should reset its question interval here to MaxQuestionInterval.
8659                         if (qptr)
8660                         {
8661                             ResetQuestionState(m, qptr);
8662                         }
8663                         if (SOARecord)
8664                         {
8665                             if (neg->soa)
8666                                 ReleaseCacheRecord(m, neg->soa);
8667                             neg->soa = SOARecord;
8668                             SOARecord = mDNSNULL;
8669                         }
8670                     }
8671                     else while (1)
8672                         {
8673                             CacheRecord *negcr;
8674                             debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
8675 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8676                             MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, uDNSService);
8677 #else
8678                             MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
8679 #endif
8680                             m->rec.r.responseFlags = response->h.flags;
8681                             // We create SOA records above which might create new cache groups. Earlier
8682                             // in the function we looked up the cache group for the name and it could have
8683                             // been NULL. If we pass NULL cg to new cache entries that we create below,
8684                             // it will create additional cache groups for the same name. To avoid that,
8685                             // look up the cache group again to re-initialize cg again.
8686                             cg = CacheGroupForName(m, hash, name);
8687                             // Need to add with a delay so that we can tag the SOA record
8688                             negcr = CreateNewCacheEntry(m, HashSlotFromNameHash(hash), cg, 1, mDNStrue, mDNSNULL);
8689 
8690                             if (negcr)
8691                             {
8692 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8693                                 // If qptr is NULL, it means the question is no longer active, and we do not process the
8694                                 // record for DNSSEC.
8695                                 if (qptr != mDNSNULL && qptr->DNSSECStatus.enable_dnssec)
8696                                 {
8697                                     update_denial_records_in_cache_record(negcr, denial_of_existence_records_ptr);
8698                                 }
8699 #endif
8700                                 negcr->DelayDelivery = 0;
8701 
8702                                 if (SOARecord)
8703                                 {
8704                                     if (negcr->soa)
8705                                         ReleaseCacheRecord(m, negcr->soa);
8706                                     negcr->soa = SOARecord;
8707                                     SOARecord = mDNSNULL;
8708                                 }
8709                                 CacheRecordDeferredAdd(m, negcr);
8710                             }
8711                             m->rec.r.responseFlags = zeroID;
8712                             m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8713                             if (!repeat) break;
8714                             repeat--;
8715                             name = (const domainname *)(name->c + 1 + name->c[0]);
8716                             hash = DomainNameHashValue(name);
8717                         }
8718                 }
8719             }
8720         }
8721     }
8722     if (SOARecord)
8723     {
8724         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveNoUnicastAnswers: SOARecord not used");
8725         ReleaseCacheRecord(m, SOARecord);
8726     }
8727 }
8728 
8729 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
8730 {
8731     AuthRecord *rrPtr = mDNSNULL;
8732     if (!m->SPSRRSet) return;
8733     LogSPS("Stored Proxy records :");
8734     for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8735     {
8736         LogSPS("%s", ARDisplayString(m, rrPtr));
8737     }
8738 }
8739 
8740 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
8741 {
8742     AuthRecord *rrPtr = mDNSNULL;
8743 
8744     for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8745     {
8746         if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
8747         {
8748             LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
8749             return mDNStrue;
8750         }
8751     }
8752     mDNSCorePrintStoredProxyRecords(m);
8753     return mDNSfalse;
8754 }
8755 
8756 mDNSexport CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType,
8757     const mDNSu32 slot, CacheGroup *cg, CacheRecord ***cfp, mDNSInterfaceID InterfaceID)
8758 {
8759     CacheRecord *cr;
8760     CacheRecord **cflocal = *cfp;
8761 
8762     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
8763     {
8764         mDNSBool match;
8765         // Resource record received via unicast, the resGroupID should match ?
8766         if (!InterfaceID)
8767         {
8768 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8769             match = (cr->resrec.dnsservice == m->rec.r.resrec.dnsservice) ? mDNStrue : mDNSfalse;
8770 #else
8771             const mDNSu32 id1 = (cr->resrec.rDNSServer ? cr->resrec.rDNSServer->resGroupID : 0);
8772             const mDNSu32 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
8773             match = (id1 == id2);
8774 #endif
8775         }
8776         else
8777             match = (cr->resrec.InterfaceID == InterfaceID);
8778         // If we found this exact resource record, refresh its TTL
8779         if (match)
8780         {
8781             if (IdenticalSameNameRecord(&m->rec.r.resrec, &cr->resrec))
8782             {
8783                 if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
8784                     verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8785                                   m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
8786 
8787                 if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8788                 {
8789                     // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8790                     if (cr->NextInCFList == mDNSNULL && *cfp != &cr->NextInCFList && LLQType != uDNS_LLQ_Events)
8791                     {
8792                         *cflocal = cr;
8793                         cflocal = &cr->NextInCFList;
8794                         *cflocal = (CacheRecord*)1;
8795                         *cfp = &cr->NextInCFList;
8796                     }
8797 
8798                     // If this packet record is marked unique, and our previous cached copy was not, then fix it
8799                     if (!(cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
8800                     {
8801                         DNSQuestion *q;
8802                         for (q = m->Questions; q; q=q->next)
8803                         {
8804                             if (CacheRecordAnswersQuestion(cr, q))
8805                                 q->UniqueAnswers++;
8806                         }
8807                         cr->resrec.RecordType = m->rec.r.resrec.RecordType;
8808                     }
8809                 }
8810 
8811                 if (!SameRDataBody(&m->rec.r.resrec, &cr->resrec.rdata->u, SameDomainNameCS))
8812                 {
8813                     // If the rdata of the packet record differs in name capitalization from the record in our cache
8814                     // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8815                     // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8816                     // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8817                     cr->resrec.rroriginalttl = 0;
8818                     cr->TimeRcvd = m->timenow;
8819                     cr->UnansweredQueries = MaxUnansweredQueries;
8820                     SetNextCacheCheckTimeForRecord(m, cr);
8821                     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: " PRI_S, CRDisplayString(m, cr));
8822                     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: " PRI_S, CRDisplayString(m, &m->rec.r));
8823                     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8824                               NextCacheCheckEvent(cr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
8825                     // DO NOT break out here -- we want to continue as if we never found it
8826                 }
8827                 else if (m->rec.r.resrec.rroriginalttl > 0)
8828                 {
8829                     DNSQuestion *q;
8830 
8831                     m->mDNSStats.CacheRefreshed++;
8832 
8833                     if ((cr->resrec.mortality == Mortality_Ghost) && !cr->DelayDelivery)
8834                     {
8835                         cr->DelayDelivery = NonZeroTime(m->timenow);
8836                         debugf("mDNSCoreReceiveCacheCheck: Reset DelayDelivery for mortalityExpired EXP:%d RR %s", m->timenow - RRExpireTime(cr), CRDisplayString(m, cr));
8837                     }
8838 
8839                     if (cr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, cr));
8840                     RefreshCacheRecord(m, cr, m->rec.r.resrec.rroriginalttl);
8841                     // RefreshCacheRecordCacheGroupOrder will modify the cache group member list that is currently being iterated over in this for-loop.
8842                     // 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.
8843                     RefreshCacheRecordCacheGroupOrder(cg, cr);
8844                     cr->responseFlags = response->h.flags;
8845 
8846                     // If we may have NSEC records returned with the answer (which we don't know yet as it
8847                     // has not been processed), we need to cache them along with the first cache
8848                     // record in the list that answers the question so that it can be used for validation
8849                     // later. The "type" check below is to make sure that we cache on the cache record
8850                     // that would answer the question. It is possible that we might cache additional things
8851                     // e.g., MX question might cache A records also, and we want to cache the NSEC on
8852                     // the record that answers the question.
8853                     if (!InterfaceID)
8854                     {
8855                         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: rescuing RR " PRI_S, CRDisplayString(m, cr));
8856                     }
8857                     // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8858                     // polling the network once we get a valid response back. For the first time when a new
8859                     // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8860                     // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8861                     // configuration changed, without flushing the cache, we reset the question interval here.
8862                     // Currently, we do this for for both multicast and unicast questions as long as the record
8863                     // type is unique. For unicast, resource record is always unique and for multicast it is
8864                     // true for records like A etc. but not for PTR.
8865                     if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8866                     {
8867                         for (q = m->Questions; q; q=q->next)
8868                         {
8869                             if (!q->DuplicateOf && !q->LongLived &&
8870                                 ActiveQuestion(q) && CacheRecordAnswersQuestion(cr, q))
8871                             {
8872                                 ResetQuestionState(m, q);
8873                                 debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8874                                 break;      // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8875                             }
8876                         }
8877                     }
8878                     break;  // Check usage of RefreshCacheRecordCacheGroupOrder before removing (See note above)
8879                 }
8880                 else
8881                 {
8882                     // If the packet TTL is zero, that means we're deleting this record.
8883                     // To give other hosts on the network a chance to protest, we push the deletion
8884                     // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8885                     // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8886                     // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8887                     // If record's current expiry time is more than a second from now, we set it to expire in one second.
8888                     // If the record is already going to expire in less than one second anyway, we leave it alone --
8889                     // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8890                     debugf("DE for %s", CRDisplayString(m, cr));
8891                     if (RRExpireTime(cr) - m->timenow > mDNSPlatformOneSecond)
8892                     {
8893                         cr->resrec.rroriginalttl = 1;
8894                         cr->TimeRcvd = m->timenow;
8895                         cr->UnansweredQueries = MaxUnansweredQueries;
8896                         SetNextCacheCheckTimeForRecord(m, cr);
8897                     }
8898                     break;
8899                 }
8900             }
8901             else if (cr->resrec.rroriginalttl != 0                  &&      // Not already marked for discarding
8902                      m->rec.r.resrec.rrclass == cr->resrec.rrclass  &&
8903                         (m->rec.r.resrec.rrtype != cr->resrec.rrtype    &&
8904                          (m->rec.r.resrec.rrtype == kDNSType_CNAME || cr->resrec.rrtype == kDNSType_CNAME)))
8905             {
8906                 // If the cache record rrtype doesn't match and one is a CNAME, then flush this record
8907                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "mDNSCoreReceiveCacheCheck: Discarding (%s) " PRI_S " rrtype change from (%s) to (%s)",
8908                           MortalityDisplayString(cr->resrec.mortality), CRDisplayString(m, cr), DNSTypeName(cr->resrec.rrtype), DNSTypeName(m->rec.r.resrec.rrtype));
8909                 mDNS_PurgeCacheResourceRecord(m, cr);
8910                 // DO NOT break out here -- we want to continue iterating the cache entries
8911             }
8912         }
8913     }
8914     return cr;
8915 }
8916 
8917 mDNSlocal void mDNSCoreResetRecord(mDNS *const m)
8918 {
8919     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8920 }
8921 
8922 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8923 // the record list and/or question list.
8924 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8925 // InterfaceID non-NULL tells us the interface this multicast response was received on
8926 // InterfaceID NULL tells us this was a unicast response
8927 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
8928 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8929     const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8930 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8931     mdns_querier_t querier, mdns_dns_service_t uDNSService,
8932 #endif
8933     const mDNSInterfaceID InterfaceID)
8934 {
8935     int i;
8936     const mDNSBool ResponseMCast    = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
8937     const mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8938     DNSQuestion *llqMatch = mDNSNULL;
8939     uDNS_LLQType LLQType      = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
8940 
8941     // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8942     // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8943     // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8944     CacheRecord *CacheFlushRecords = (CacheRecord*)1;
8945     CacheRecord **cfp = &CacheFlushRecords;
8946     NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
8947     mDNSBool    recordAcceptedInResponse = mDNSfalse; // Set if a record is accepted from a unicast mDNS response that answers an existing question.
8948 
8949     // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8950     // to guard against spoof responses, then the only credible protection against that is cryptographic
8951     // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
8952     int firstauthority  =                   response->h.numAnswers;
8953     int firstadditional = firstauthority  + response->h.numAuthorities;
8954     int totalrecords    = firstadditional + response->h.numAdditionals;
8955     const mDNSu8 *ptr   = response->data;
8956 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8957     DNSServer *uDNSServer = mDNSNULL;
8958 #endif
8959 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
8960     denial_of_existence_records_t *denial_of_existence_records = mDNSNULL;
8961     mDNSBool not_answer_but_required_for_dnssec = mDNSfalse;
8962 #endif
8963 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8964     // Determine whether the response is mDNS, as opposed to DNS.
8965     // Thus far, the code has assumed that responses with IDs set to zero are mDNS responses. However, this condition
8966     // isn't sufficient because queriers, which are used exclusively for DNS queries, may set the IDs of their queries
8967     // to zero. And consequently, their responses may have their IDs set to zero. Specifically, zero-valued IDs are used
8968     // for DNS over HTTPs, as specified by <https://tools.ietf.org/html/rfc8484#section-4.1>.
8969     const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id) && !querier;
8970 #else
8971     const mDNSBool ResponseIsMDNS = mDNSOpaque16IsZero(response->h.id);
8972 #endif
8973 
8974     debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8975            "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8976            srcaddr, dstaddr, InterfaceID,
8977            response->h.numQuestions,   response->h.numQuestions   == 1 ? ", "   : "s,",
8978            response->h.numAnswers,     response->h.numAnswers     == 1 ? ", "   : "s,",
8979            response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
8980            response->h.numAdditionals, response->h.numAdditionals == 1 ? " "    : "s", end - response->data, LLQType);
8981 
8982 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
8983     if (mDNSSameIPPort(srcport, UnicastDNSPort))
8984     {
8985         MetricsUpdateDNSResponseSize((mDNSu32)(end - (mDNSu8 *)response));
8986     }
8987 #endif
8988 
8989     // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
8990     //    When a DNS client receives a reply with TC
8991     //    set, it should ignore that response, and query again, using a
8992     //    mechanism, such as a TCP connection, that will permit larger replies.
8993     // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
8994     // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
8995     // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
8996     // <rdar://problem/6690034> Can't bind to Active Directory
8997     // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
8998     // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
8999     // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
9000     // and not even do the TCP query.
9001     // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the
9002     // entire RRSet, with the following exception. If the response contains an answer section and one or more records in
9003     // either the authority section or additional section, then that implies that truncation occurred beyond the answer
9004     // section, and the answer section is therefore assumed to be complete.
9005     //
9006     // From section 6.2 of RFC 1035 <https://tools.ietf.org/html/rfc1035>:
9007     //    When a response is so long that truncation is required, the truncation
9008     //    should start at the end of the response and work forward in the
9009     //    datagram.  Thus if there is any data for the authority section, the
9010     //    answer section is guaranteed to be unique.
9011 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9012     if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) && !querier &&
9013 #else
9014     if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC) &&
9015 #endif
9016         ((response->h.numAnswers == 0) || ((response->h.numAuthorities == 0) && (response->h.numAdditionals == 0)))) return;
9017 
9018     if (LLQType == uDNS_LLQ_Ignore) return;
9019 
9020     // 1. We ignore questions (if any) in mDNS response packets
9021     // 2. If this is an LLQ response, we handle it much the same
9022     // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
9023     if (ResponseMCast || LLQType == uDNS_LLQ_Events)
9024         ptr = LocateAnswers(response, end);
9025     // Otherwise, for one-shot queries, any answers in our cache that are not also contained
9026     // in this response packet are immediately deemed to be invalid.
9027     else
9028     {
9029         mDNSBool failure, returnEarly;
9030         const int rcode = response->h.flags.b[1] & kDNSFlag1_RC_Mask;
9031         failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
9032         returnEarly = mDNSfalse;
9033 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9034         // When the QUERIER functionality is enabled, DNS transport is handled exclusively by querier objects. If this
9035         // response was provided by a querier, but the RCODE is considered a failure, then set failure to false so that
9036         // we don't return early. The logic of returning early was so that uDNS_CheckCurrentQuestion() could handle
9037         // resending the query and generate a negative cache record if all servers were tried. If the querier provides a
9038         // response, then it's the best response that it could provide. If the RCODE is considered a failure,
9039         // mDNSCoreReceiveResponse() needs to create negative cache entries for the unanwered question, so totalrecords
9040         // is set to 0 to ignore any records that the response may contain.
9041         if (querier && failure)
9042         {
9043             totalrecords = 0;
9044             failure = mDNSfalse;
9045         }
9046 #endif
9047         // We could possibly combine this with the similar loop at the end of this function --
9048         // instead of tagging cache records here and then rescuing them if we find them in the answer section,
9049         // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
9050         // which it was received (or refreshed), and then at the end if we find any cache records which
9051         // answer questions in this packet's question section, but which aren't tagged with this packet's
9052         // packet number, then we deduce they are old and delete them
9053         for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
9054         {
9055             DNSQuestion q;
9056             DNSQuestion *qptr;
9057             mDNSBool expectingResponse;
9058             ptr = getQuestion(response, ptr, end, InterfaceID, &q);
9059             if (!ptr)
9060             {
9061                 continue;
9062             }
9063 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9064             if (querier)
9065             {
9066                 expectingResponse = mDNStrue;
9067                 qptr = mDNSNULL;
9068             }
9069             else
9070 #endif
9071             {
9072                 qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr);
9073                 expectingResponse = qptr ? mDNStrue : mDNSfalse;
9074             }
9075             if (!expectingResponse)
9076             {
9077                 continue;
9078             }
9079             if (!failure)
9080             {
9081                 CacheRecord *cr;
9082                 CacheGroup *cg = CacheGroupForName(m, q.qnamehash, &q.qname);
9083                 for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
9084                 {
9085                     mDNSBool isAnswer;
9086 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9087                     if (querier)
9088                     {
9089                         isAnswer = (cr->resrec.dnsservice == uDNSService) && Querier_SameNameCacheRecordIsAnswer(cr, querier);
9090                     }
9091                     else
9092 #endif
9093                     {
9094                         isAnswer = SameNameCacheRecordAnswersQuestion(cr, qptr);
9095                     }
9096                     if (isAnswer)
9097                     {
9098                         debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
9099                                cr->resrec.InterfaceID, CRDisplayString(m, cr));
9100                         // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
9101                         cr->TimeRcvd          = m->timenow - TicksTTL(cr) - 1;
9102                         cr->UnansweredQueries = MaxUnansweredQueries;
9103                     }
9104                 }
9105             }
9106             else
9107             {
9108 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9109                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9110                     "[R%d->Q%d] mDNSCoreReceiveResponse: Server %p responded with code %d to query " PRI_DM_NAME " (" PUB_S ")",
9111                     qptr->request_id, mDNSVal16(qptr->TargetQID), qptr->qDNSServer, rcode,
9112                     DM_NAME_PARAM(&q.qname), DNSTypeName(q.qtype));
9113                 PenalizeDNSServer(m, qptr, response->h.flags);
9114 #endif
9115                 returnEarly = mDNStrue;
9116             }
9117         }
9118         if (returnEarly)
9119         {
9120             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9121                    "[Q%d] Ignoring %2d Answer" PUB_S " %2d Authorit" PUB_S " %2d Additional" PUB_S,
9122                    mDNSVal16(response->h.id),
9123                    response->h.numAnswers,     response->h.numAnswers     == 1 ? ", " : "s,",
9124                    response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
9125                    response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
9126             // not goto exit because we won't have any CacheFlushRecords and we do not want to
9127             // generate negative cache entries (we want to query the next server)
9128             return;
9129         }
9130     }
9131 
9132     for (i = 0; i < totalrecords && ptr && ptr < end; i++)
9133     {
9134         // All responses sent via LL multicast are acceptable for caching
9135         // All responses received over our outbound TCP connections are acceptable for caching
9136         // We accept all records in a unicast response to a multicast query once we find one that
9137         // answers an active question.
9138 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9139         mDNSBool AcceptableResponse = ResponseMCast || (!querier && !dstaddr) || LLQType || recordAcceptedInResponse;
9140 #else
9141         mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType || recordAcceptedInResponse;
9142 #endif
9143         // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
9144         // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
9145 
9146         const mDNSu8 RecordType =
9147             (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns  :
9148             (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
9149         ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
9150         if (!ptr) goto exit;        // Break out of the loop and clean up our CacheFlushRecords list before exiting
9151 
9152         if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
9153         {
9154             mDNSCoreResetRecord(m);
9155             continue;
9156         }
9157 
9158         // Don't want to cache OPT or TSIG pseudo-RRs
9159         if (m->rec.r.resrec.rrtype == kDNSType_TSIG)
9160         {
9161             mDNSCoreResetRecord(m);
9162             continue;
9163         }
9164         if (m->rec.r.resrec.rrtype == kDNSType_OPT)
9165         {
9166             const rdataOPT *opt;
9167             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
9168             // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
9169             // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
9170             for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
9171                 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
9172                 {
9173                     ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
9174                     ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
9175                 }
9176             mDNSCoreResetRecord(m);
9177             continue;
9178         }
9179         // if a CNAME record points to itself, then don't add it to the cache
9180         if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
9181         {
9182             LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
9183             mDNSCoreResetRecord(m);
9184             continue;
9185         }
9186 
9187         // When we receive uDNS LLQ responses, we assume a long cache lifetime --
9188         // In the case of active LLQs, we'll get remove events when the records actually do go away
9189         // In the case of polling LLQs, we assume the record remains valid until the next poll
9190         if (!ResponseIsMDNS)
9191         {
9192             m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
9193         }
9194 
9195         // If response was not sent via LL multicast,
9196         // then see if it answers a recent query of ours, which would also make it acceptable for caching.
9197         if (!ResponseMCast)
9198         {
9199             if (LLQType)
9200             {
9201                 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
9202                 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
9203                 // queries to get ADD/RMV events. To lookup the question, we can't use
9204                 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
9205                 // has already matched the question using the 64 bit Id in the packet and we use that here.
9206 
9207 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9208                 if (querier)
9209                 {
9210                     mdns_replace(&m->rec.r.resrec.dnsservice, uDNSService);
9211                 }
9212 #else
9213                 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
9214 #endif
9215             }
9216             else if (!AcceptableResponse || !dstaddr)
9217             {
9218                 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
9219                 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
9220                 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
9221                 // we create.
9222 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9223                 if (querier)
9224                 {
9225                     ResourceRecord *const rr = &m->rec.r.resrec;
9226                     if (Querier_ResourceRecordIsAnswer(rr, querier))
9227                     {
9228                         const mdns_resolver_type_t resolver_type = mdns_querier_get_resolver_type(querier);
9229                         if ((resolver_type == mdns_resolver_type_normal) &&
9230                             (mdns_querier_get_over_tcp_reason(querier) != mdns_query_over_tcp_reason_null))
9231                         {
9232                             rr->protocol = mdns_resolver_type_tcp;
9233                         }
9234                         else
9235                         {
9236                             rr->protocol = resolver_type;
9237                         }
9238                         mdns_replace(&rr->dnsservice, uDNSService);
9239                         AcceptableResponse = mDNStrue;
9240                     }
9241                 }
9242                 else
9243 #endif
9244                 {
9245                     const DNSQuestion *q;
9246                     // Initialize the DNS server on the resource record which will now filter what questions we answer with
9247                     // this record.
9248                     //
9249                     // We could potentially lookup the DNS server based on the source address, but that may not work always
9250                     // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
9251                     // from the DNS server that queried. We follow the same logic here. If we can find a matching question based
9252                     // on the "id" and "source port", then this response answers the question and assume the response
9253                     // came from the same DNS server that we sent the query to.
9254                     q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
9255                     if (q != mDNSNULL)
9256                     {
9257                         AcceptableResponse = mDNStrue;
9258                         if (!InterfaceID)
9259                         {
9260                             debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
9261 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9262                             m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
9263 #endif
9264                         }
9265                         else
9266                         {
9267                             // Accept all remaining records in this unicast response to an mDNS query.
9268                             recordAcceptedInResponse = mDNStrue;
9269                             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
9270                                 "[R%d->Q%d] mDNSCoreReceiveResponse: Accepting response for query: " PRI_DM_NAME " (" PUB_S ")",
9271                                 q->request_id, mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
9272                         }
9273                     }
9274                     else
9275                     {
9276                         // If we can't find a matching question, we need to see whether we have seen records earlier that matched
9277                         // the question. The code below does that. So, make this record unacceptable for now
9278                         if (!InterfaceID)
9279                         {
9280                             debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
9281                             AcceptableResponse = mDNSfalse;
9282                         }
9283                     }
9284                 }
9285             }
9286         }
9287         else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
9288         {
9289             // There are some routers (rare, thankfully) that generate bogus ARP responses for
9290             // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9291             // To work with these broken routers, client devices need to blacklist these broken
9292             // routers and ignore their bogus ARP responses. Some devices implement a technique
9293             // such as the one described in US Patent 7436783, which lets clients detect and
9294             // ignore these broken routers: <https://www.google.com/patents/US7436783>
9295 
9296             // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9297             // approach of just detecting these broken routers and completely disabling IPv4
9298             // link-local communication on interfaces where a broken router is detected.
9299             // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9300             // that are deemed “safe” for IPv4 link-local communication;
9301             // the flag is cleared on interfaces where a broken router is detected.
9302 
9303             // OS X and iOS will not even try to communicate with an IPv4
9304             // link-local destination on an interface without the IFEF_ARPLL flag set.
9305             // This can cause some badly written applications to freeze for a long time if they
9306             // attempt to connect to an IPv4 link-local destination address and then wait for
9307             // that connection attempt to time out before trying other candidate addresses.
9308 
9309             // To mask this client bug, we suppress acceptance of IPv4 link-local address
9310             // records on interfaces where we know the OS will be unwilling even to attempt
9311             // communication with those IPv4 link-local destination addresses.
9312             // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9313 
9314             const CacheRecord *const rr = &m->rec.r;
9315             const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
9316             if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
9317             {
9318                 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r));
9319                 mDNSCoreResetRecord(m);
9320                 continue;
9321             }
9322         }
9323 
9324         // 1. Check that this packet resource record does not conflict with any of ours
9325         if (ResponseIsMDNS && m->rec.r.resrec.rrtype != kDNSType_NSEC)
9326         {
9327             if (m->CurrentRecord)
9328                 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
9329             m->CurrentRecord = m->ResourceRecords;
9330             while (m->CurrentRecord)
9331             {
9332                 AuthRecord *rr = m->CurrentRecord;
9333                 m->CurrentRecord = rr->next;
9334                 // We accept all multicast responses, and unicast responses resulting from queries we issued
9335                 // For other unicast responses, this code accepts them only for responses with an
9336                 // (apparently) local source address that pertain to a record of our own that's in probing state
9337                 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
9338 
9339                 if (PacketRRMatchesSignature(&m->rec.r, rr))        // If interface, name, type (if shared record) and class match...
9340                 {
9341                     // ... check to see if type and rdata are identical
9342                     if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
9343                     {
9344                         // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9345                         if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
9346                         {
9347                             // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9348                             if      (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
9349                         }
9350                         else
9351                         {
9352                             if      (rr->ImmedAnswer == mDNSNULL)    { rr->ImmedAnswer = InterfaceID;       m->NextScheduledResponse = m->timenow; }
9353                             else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9354                         }
9355                     }
9356                     // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9357                     else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
9358                     {
9359                         LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s (interface %d)",
9360                             m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r), IIDPrintable(InterfaceID));
9361                         LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9362 
9363                         // If this record is marked DependentOn another record for conflict detection purposes,
9364                         // then *that* record has to be bumped back to probing state to resolve the conflict
9365                         if (rr->DependentOn)
9366                         {
9367                             while (rr->DependentOn) rr = rr->DependentOn;
9368                             LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9369                         }
9370 
9371                         // If we've just whacked this record's ProbeCount, don't need to do it again
9372                         if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
9373                             LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
9374                         else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
9375                             LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
9376                         else
9377                         {
9378                             LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
9379                             // If we'd previously verified this record, put it back to probing state and try again
9380                             if (rr->resrec.RecordType == kDNSRecordTypeVerified)
9381                             {
9382                                 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
9383                                 rr->resrec.RecordType     = kDNSRecordTypeUnique;
9384                                 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9385                                 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9386                                 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9387                                 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9388                                 rr->ProbeCount     = DefaultProbeCountForTypeUnique + 1;
9389                                 rr->AnnounceCount  = InitialAnnounceCount;
9390                                 InitializeLastAPTime(m, rr);
9391                                 RecordProbeFailure(m, rr);  // Repeated late conflicts also cause us to back off to the slower probing rate
9392                             }
9393                             // If we're probing for this record, we just failed
9394                             else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
9395                             {
9396 	                            // At this point in the code, we're probing for uniqueness.
9397 	                            // We've sent at least one probe (rr->ProbeCount < DefaultProbeCountForTypeUnique)
9398 	                            // but we haven't completed probing yet (rr->resrec.RecordType == kDNSRecordTypeUnique).
9399                                 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9400                                 if (!mDNSCoreRegisteredProxyRecord(m, rr))
9401                                 {
9402                                     if ((rr->ProbingConflictCount == 0) || (m->MPktNum != rr->LastConflictPktNum))
9403                                     {
9404                                         const NetworkInterfaceInfo *const intf = FirstInterfaceForID(m, InterfaceID);
9405                                         rr->ProbingConflictCount++;
9406                                         rr->LastConflictPktNum = m->MPktNum;
9407                                         if (ResponseMCast && (!intf || intf->SupportsUnicastMDNSResponse) &&
9408                                             (rr->ProbingConflictCount <= kMaxAllowedMCastProbingConflicts))
9409                                         {
9410                                             LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; restarting probing after %d-tick pause due to possibly "
9411                                                 "spurious multicast conflict (%d/%d) via interface %d for %s",
9412                                                 rr->ProbeCount, kProbingConflictPauseDuration, rr->ProbingConflictCount,
9413                                                 kMaxAllowedMCastProbingConflicts, IIDPrintable(InterfaceID), ARDisplayString(m, rr));
9414                                             rr->ProbeCount = DefaultProbeCountForTypeUnique;
9415                                             rr->LastAPTime = m->timenow + kProbingConflictPauseDuration - rr->ThisAPInterval;
9416                                             SetNextAnnounceProbeTime(m, rr);
9417                                         }
9418                                         else
9419                                         {
9420                                             LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s due to %scast conflict via interface %d",
9421                                                 rr->ProbeCount, ARDisplayString(m, rr), ResponseMCast ? "multi" : "uni", IIDPrintable(InterfaceID));
9422                                             m->mDNSStats.NameConflicts++;
9423 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9424                                             // See if this record was also registered with any D2D plugins.
9425                                             D2D_stop_advertising_record(rr);
9426 #endif
9427                                             mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9428                                         }
9429                                     }
9430                                 }
9431                             }
9432                             // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9433                             // same machine giving different answers for the reverse mapping record, or there are two machines on the
9434                             // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9435                             // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9436                             // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9437                             else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
9438                             {
9439                                 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
9440                                 m->mDNSStats.KnownUniqueNameConflicts++;
9441 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
9442                                 D2D_stop_advertising_record(rr);
9443 #endif
9444                                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9445                             }
9446                             else
9447                                 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
9448                         }
9449                     }
9450                     // Else, matching signature, different type or rdata, but not a considered a conflict.
9451                     // If the packet record has the cache-flush bit set, then we check to see if we
9452                     // have any record(s) of the same type that we should re-assert to rescue them
9453                     // (see note about "multi-homing and bridged networks" at the end of this function).
9454                     else if ((m->rec.r.resrec.rrtype == rr->resrec.rrtype) &&
9455                         (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) &&
9456                         ((mDNSu32)(m->timenow - rr->LastMCTime) > (mDNSu32)mDNSPlatformOneSecond/2) &&
9457                         ResourceRecordIsValidAnswer(rr))
9458                     {
9459                         rr->ImmedAnswer = mDNSInterfaceMark;
9460                         m->NextScheduledResponse = m->timenow;
9461                     }
9462                 }
9463             }
9464         }
9465 
9466         if (!AcceptableResponse)
9467         {
9468 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9469     #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9470             not_answer_but_required_for_dnssec = adds_denial_records_in_cache_record(&m->rec.r.resrec,
9471                 querier != mDNSNULL && mdns_querier_get_dnssec_ok(querier), &denial_of_existence_records);
9472     #else
9473             not_answer_but_required_for_dnssec = mDNSfalse;
9474     #endif
9475 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9476             AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords);
9477 
9478 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9479             if (AcceptableResponse) mdns_replace(&m->rec.r.resrec.dnsservice, uDNSService);
9480 #else
9481             if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
9482 #endif
9483         }
9484 
9485         // 2. See if we want to add this packet resource record to our cache
9486         // We only try to cache answers if we have a cache to put them in
9487         // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9488         if (!AcceptableResponse) {
9489             const char* savedString = "";
9490 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9491             savedString = (not_answer_but_required_for_dnssec ? "Saved for DNSSEC" : "");
9492 #endif
9493             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO, "[Q%d] mDNSCoreReceiveResponse ignoring " PRI_S " %s",
9494                 mDNSVal16(response->h.id), CRDisplayString(m, &m->rec.r), savedString);
9495         }
9496 
9497         if (m->rrcache_size && AcceptableResponse)
9498         {
9499             const mDNSu32 slot = HashSlotFromNameHash(m->rec.r.resrec.namehash);
9500             CacheGroup *cg = CacheGroupForRecord(m, &m->rec.r.resrec);
9501             CacheRecord *rr = mDNSNULL;
9502 
9503             // 2a. Check if this packet resource record is already in our cache.
9504             rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, &cfp, InterfaceID);
9505 
9506             // If packet resource record not in our cache, add it now
9507             // (unless it is just a deletion of a record we never had, in which case we don't care)
9508             if (!rr && m->rec.r.resrec.rroriginalttl > 0)
9509             {
9510                 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
9511                 mDNSs32 delay;
9512 
9513                 if (AddToCFList)
9514                     delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9515                 else
9516                     delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash);
9517 
9518                 // If unique, assume we may have to delay delivery of this 'add' event.
9519                 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9520                 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9521                 // to schedule an mDNS_Execute task at the appropriate time.
9522                 rr = CreateNewCacheEntry(m, slot, cg, delay, mDNStrue, srcaddr);
9523                 if (rr)
9524                 {
9525 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9526                     set_denial_records_in_cache_record(rr, &denial_of_existence_records);
9527 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9528 
9529                     rr->responseFlags = response->h.flags;
9530 
9531                     if (AddToCFList)
9532                     {
9533                         *cfp = rr;
9534                         cfp = &rr->NextInCFList;
9535                         *cfp = (CacheRecord*)1;
9536                     }
9537                     else if (rr->DelayDelivery)
9538                     {
9539                         ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
9540                     }
9541                 }
9542             }
9543         }
9544         mDNSCoreResetRecord(m);
9545     }
9546 
9547 exit:
9548     mDNSCoreResetRecord(m);
9549 
9550     // If we've just received one or more records with their cache flush bits set,
9551     // then scan that cache slot to see if there are any old stale records we need to flush
9552     while (CacheFlushRecords != (CacheRecord*)1)
9553     {
9554         CacheRecord *r1 = CacheFlushRecords, *r2;
9555         const mDNSu32 slot = HashSlotFromNameHash(r1->resrec.namehash);
9556         const CacheGroup *cg = CacheGroupForRecord(m, &r1->resrec);
9557         mDNSBool purgedRecords = mDNSfalse;
9558         CacheFlushRecords = CacheFlushRecords->NextInCFList;
9559         r1->NextInCFList = mDNSNULL;
9560 
9561         // Look for records in the cache with the same signature as this new one with the cache flush
9562         // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9563         // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9564         // We make these TTL adjustments *only* for records that still have *more* than one second
9565         // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9566         // (and now has half a second remaining) could inadvertently get its life extended, by either
9567         // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9568         // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9569         // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9570         // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9571         // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9572         // To avoid this, we need to ensure that the cache flushing operation will only act to
9573         // *decrease* a record's remaining lifetime, never *increase* it.
9574         for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
9575         {
9576 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9577             mDNSBool match;
9578 #else
9579             mDNSu32 id1;
9580             mDNSu32 id2;
9581 #endif
9582             if (!r1->resrec.InterfaceID)
9583             {
9584 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9585                 match = (r1->resrec.dnsservice == r2->resrec.dnsservice) ? mDNStrue : mDNSfalse;
9586 #else
9587                 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
9588                 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
9589 #endif
9590             }
9591             else
9592             {
9593 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9594                 match = mDNStrue;
9595 #else
9596                 id1 = id2 = 0;
9597 #endif
9598             }
9599             // For Unicast (null InterfaceID) the resolver IDs should also match
9600             if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
9601 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9602                 (r1->resrec.InterfaceID || match) &&
9603 #else
9604                 (r1->resrec.InterfaceID || (id1 == id2)) &&
9605 #endif
9606                 r1->resrec.rrtype      == r2->resrec.rrtype &&
9607                 r1->resrec.rrclass     == r2->resrec.rrclass
9608 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9609                 // 2 RRSIGs need to cover the same DNS type to be identified as one RRSET, and have the same TTL
9610                 && are_records_in_the_same_cache_set_for_dnssec(&r1->resrec, &r2->resrec)
9611 #endif
9612                 )
9613             {
9614                     if (r1->resrec.mortality == Mortality_Mortal && r2->resrec.mortality != Mortality_Mortal)
9615                     {
9616                         verbosedebugf("mDNSCoreReceiveResponse: R1(%p) is being immortalized by R2(%p)", r1, r2);
9617                         r1->resrec.mortality = Mortality_Immortal;   //  Immortalize the replacement record
9618                     }
9619 
9620                     // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9621                     // else, if record is old, mark it to be flushed
9622                     if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9623                     {
9624                         // If we find mismatched TTLs in an RRSet, correct them.
9625                         // We only do this for records with a TTL of 2 or higher. It's possible to have a
9626                         // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9627                         // which we treat as a goodbye followed by an addition) and in that case it would be
9628                         // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9629 
9630                         // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9631                         // because certain early Bonjour devices are known to have this specific mismatch, and
9632                         // there's no point filling syslog with messages about something we already know about.
9633                         // We also don't log this for uDNS responses, since a caching name server is obliged
9634                         // to give us an aged TTL to correct for how long it has held the record,
9635                         // so our received TTLs are expected to vary in that case
9636 
9637                         // We also suppress log message in the case of SRV records that are received
9638                         // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9639                         // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9640                         // GM builds.
9641                         if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
9642                         {
9643                             if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
9644                                 !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) &&
9645                                 ResponseIsMDNS)
9646                                 LogInfo("Correcting TTL from %4d to %4d for %s",
9647                                         r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
9648                             r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
9649                         }
9650                         r2->TimeRcvd = m->timenow;
9651                         SetNextCacheCheckTimeForRecord(m, r2);
9652                     }
9653                     else if (r2->resrec.InterfaceID) // else, if record is old, mark it to be flushed
9654                     {
9655                         verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
9656                         verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
9657                         // We set stale records to expire in one second.
9658                         // This gives the owner a chance to rescue it if necessary.
9659                         // This is important in the case of multi-homing and bridged networks:
9660                         //   Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9661                         //   bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9662                         //   set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9663                         //   will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9664                         //   By delaying the deletion by one second, we give X a change to notice that this bridging has
9665                         //   happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9666 
9667                         // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9668                         // final expiration queries for this record.
9669 
9670                         // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9671                         // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9672                         // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9673                         // <rdar://problem/5636422> Updating TXT records is too slow
9674                         // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9675                         // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9676                         if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
9677                         {
9678                             LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
9679                             r2->resrec.rroriginalttl = 0;
9680                         }
9681                         else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9682                         {
9683                             // We only set a record to expire in one second if it currently has *more* than a second to live
9684                             // If it's already due to expire in a second or less, we just leave it alone
9685                             r2->resrec.rroriginalttl = 1;
9686                             r2->UnansweredQueries = MaxUnansweredQueries;
9687                             r2->TimeRcvd = m->timenow - 1;
9688                             // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9689                             // that we marked for deletion via an explicit DE record
9690                         }
9691                         SetNextCacheCheckTimeForRecord(m, r2);
9692                     }
9693                     else
9694                     {
9695 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
9696                     if (r2->resrec.mortality == Mortality_Ghost)
9697                     {
9698                         DNSQuestion * q;
9699                         for (q = m->Questions; q; q=q->next)
9700                         {
9701                             if (!q->LongLived && ActiveQuestion(q) &&
9702                                 CacheRecordAnswersQuestion(r2, q) &&
9703                                 q->metrics.expiredAnswerState == ExpiredAnswer_AnsweredWithExpired)
9704                             {
9705                                 q->metrics.expiredAnswerState = ExpiredAnswer_ExpiredAnswerChanged;
9706                             }
9707                         }
9708                     }
9709 #endif
9710                     // Old uDNS records are scheduled to be purged instead of given at most one second to live.
9711                     mDNS_PurgeCacheResourceRecord(m, r2);
9712                     purgedRecords = mDNStrue;
9713                 }
9714             }
9715        }
9716 
9717         if (r1->DelayDelivery)  // If we were planning to delay delivery of this record, see if we still need to
9718         {
9719             if (r1->resrec.InterfaceID)
9720             {
9721                 r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash);
9722             }
9723             else
9724             {
9725                 // If uDNS records from an older RRset were scheduled to be purged, then delay delivery slightly to allow
9726                 // them to be deleted before any ADD events for this record.
9727                 r1->DelayDelivery = purgedRecords ? NonZeroTime(m->timenow) : 0;
9728             }
9729             // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9730             if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
9731             else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
9732         }
9733     }
9734 
9735     // See if we need to generate negative cache entries for unanswered unicast questions
9736     mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID,
9737 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
9738         querier, uDNSService,
9739 #endif
9740 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9741         &denial_of_existence_records,
9742 #endif
9743         LLQType);
9744 
9745 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9746         destroy_denial_of_existence_records_t_if_nonnull(denial_of_existence_records);
9747 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
9748 }
9749 
9750 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9751 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9752 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9753 // that warrants waking the sleeping host.
9754 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9755 
9756 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
9757 {
9758     // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9759     // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9760     // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9761     // simple, we use the same mechanism for both lists.
9762     if (!e->l[0])
9763     {
9764         LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9765         return;
9766     }
9767     m->CurrentRecord = thelist;
9768     while (m->CurrentRecord)
9769     {
9770         AuthRecord *const rr = m->CurrentRecord;
9771         if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
9772         {
9773             LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
9774             mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9775         }
9776         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
9777             m->CurrentRecord = rr->next;
9778     }
9779 }
9780 
9781 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
9782 {
9783     if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9784     ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
9785     ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
9786 }
9787 
9788 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
9789 {
9790     if (result && result != mStatus_MemFree)
9791         LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
9792 
9793     if (result == mStatus_NameConflict)
9794     {
9795         mDNS_Lock(m);
9796         LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
9797         if (ar->WakeUp.HMAC.l[0])
9798         {
9799             SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password, mDNSfalse);  // Send one wakeup magic packet
9800             ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC);                               // Schedule all other records with the same owner to be woken
9801         }
9802         mDNS_Unlock(m);
9803     }
9804 
9805     if (result == mStatus_NameConflict || result == mStatus_MemFree)
9806     {
9807         m->ProxyRecords--;
9808         mDNSPlatformMemFree(ar);
9809         mDNS_UpdateAllowSleep(m);
9810     }
9811 }
9812 
9813 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth)
9814 {
9815     int     i;
9816     mDNSs8  hval   = 0;
9817     int     colons = 0;
9818     mDNSu16  val    = 0; /* need to use 16 bit int to detect overflow */
9819 
9820     for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++)
9821     {
9822         hval = HexVal(*ptr);
9823         if (hval != -1)
9824         {
9825             val <<= 4;
9826             val |= hval;
9827         }
9828         else if (*ptr == ':')
9829         {
9830             if (colons >=5)
9831             {
9832                 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val);
9833                 return mDNSNULL;
9834             }
9835             eth->b[colons] = (mDNSs8)val;
9836             colons++;
9837             val = 0;
9838         }
9839     }
9840     if (colons != 5)
9841     {
9842         LogMsg("GetValueForMACAddr: Address malformed colons %d", colons);
9843         return mDNSNULL;
9844     }
9845     eth->b[colons] = (mDNSs8)val;
9846     return ptr;
9847 }
9848 
9849 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
9850 {
9851     int hval;
9852     int value;
9853     int numBytes;
9854     int digitsProcessed;
9855     int zeroFillStart;
9856     int numColons;
9857     mDNSu8 v6addr[16];
9858 
9859     // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9860     // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9861     //
9862     // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9863     // the result in "v6"
9864 
9865     numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
9866     while (ptr < limit && *ptr != ' ')
9867     {
9868         hval = HexVal(*ptr);
9869         if (hval != -1)
9870         {
9871             value <<= 4;
9872             value |= hval;
9873             digitsProcessed = 1;
9874         }
9875         else if (*ptr == ':')
9876         {
9877             if (!digitsProcessed)
9878             {
9879                 // If we have already seen a "::", we should not see one more. Handle the special
9880                 // case of "::"
9881                 if (numColons)
9882                 {
9883                     // if we never filled any bytes and the next character is space (we have reached the end)
9884                     // we are done
9885                     if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
9886                     {
9887                         mDNSPlatformMemZero(v6->b, 16);
9888                         return ptr + 1;
9889                     }
9890                     LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
9891                     return mDNSNULL;
9892                 }
9893 
9894                 // We processed "::". We need to fill zeroes later. For now, mark the
9895                 // point where we will start filling zeroes from.
9896                 zeroFillStart = numBytes;
9897                 numColons++;
9898             }
9899             else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
9900             {
9901                 // We have a trailing ":" i.e., no more characters after ":"
9902                 LogMsg("GetValueForIPv6Addr: Trailing colon");
9903                 return mDNSNULL;
9904             }
9905             else
9906             {
9907                 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9908                 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9909                 // filled here is 12 and 13.
9910                 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
9911 
9912                 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9913                 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9914                 digitsProcessed = value = 0;
9915 
9916                 // Make sure that we did not fill the 13th and 14th byte above
9917                 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
9918             }
9919         }
9920         ptr++;
9921     }
9922 
9923     // We should be processing the last set of bytes following the last ":" here
9924     if (!digitsProcessed)
9925     {
9926         LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
9927         return mDNSNULL;
9928     }
9929 
9930     if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
9931     v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9932     v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9933 
9934     if (zeroFillStart)
9935     {
9936         int i, j, n;
9937         for (i = 0; i < zeroFillStart; i++)
9938             v6->b[i] = v6addr[i];
9939         for (j = i, n = 0; n < 16 - numBytes; j++, n++)
9940             v6->b[j] = 0;
9941         for (; j < 16; i++, j++)
9942             v6->b[j] = v6addr[i];
9943     }
9944     else if (numBytes == 16)
9945         mDNSPlatformMemCopy(v6->b, v6addr, 16);
9946     else
9947     {
9948         LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
9949         return mDNSNULL;
9950     }
9951     return ptr;
9952 }
9953 
9954 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
9955 {
9956     mDNSu32 val;
9957     int dots = 0;
9958     val = 0;
9959 
9960     for ( ; ptr < limit && *ptr != ' '; ptr++)
9961     {
9962         if (*ptr >= '0' &&  *ptr <= '9')
9963             val = val * 10 + *ptr - '0';
9964         else if (*ptr == '.')
9965         {
9966             if (val > 255 || dots >= 3)
9967             {
9968                 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots);
9969                 return mDNSNULL;
9970             }
9971             v4->b[dots++] = val;
9972             val = 0;
9973         }
9974         else
9975         {
9976             // We have a zero at the end and if we reached that, then we are done.
9977             if (*ptr == 0 && ptr == limit - 1 && dots == 3)
9978             {
9979                 v4->b[dots] = val;
9980                 return ptr + 1;
9981             }
9982             else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
9983         }
9984     }
9985     if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
9986     v4->b[dots] = val;
9987     return ptr;
9988 }
9989 
9990 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
9991 {
9992     mDNSu32 val;
9993 
9994     val = 0;
9995     for ( ; ptr < limit && *ptr != ' '; ptr++)
9996     {
9997         if (*ptr < '0' || *ptr > '9')
9998         {
9999             // We have a zero at the end and if we reached that, then we are done.
10000             if (*ptr == 0 && ptr == limit - 1)
10001             {
10002                 *value = val;
10003                 return ptr + 1;
10004             }
10005             else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
10006         }
10007         val = val * 10 + *ptr - '0';
10008     }
10009     *value = val;
10010     return ptr;
10011 }
10012 
10013 mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr)
10014 {
10015     mDNSAddr    laddr, raddr;
10016     mDNSEthAddr eth;
10017     mDNSIPPort  lport, rport;
10018     mDNSu32     timeout, seq, ack;
10019     mDNSu16     win;
10020 
10021     if (!mDNS_KeepaliveRecord(&rr->resrec))
10022     {
10023         return mDNSfalse;
10024     }
10025 
10026     timeout = seq = ack = 0;
10027     win = 0;
10028     laddr = raddr = zeroAddr;
10029     lport = rport = zeroIPPort;
10030     eth = zeroEthAddr;
10031 
10032     mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10033 
10034     if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) ||
10035         mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) ||
10036         mDNSEthAddressIsZero(eth))
10037     {
10038         return mDNSfalse;
10039     }
10040 
10041     return mDNStrue;
10042 }
10043 
10044 
10045 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
10046                                          mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
10047 {
10048     if (ar->resrec.rrtype != kDNSType_NULL)
10049         return;
10050 
10051     if (mDNS_KeepaliveRecord(&ar->resrec))
10052     {
10053         int len = ar->resrec.rdlength;
10054         mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
10055         mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
10056         mDNSu32 value = 0;
10057 
10058         while (ptr < limit)
10059         {
10060             mDNSu8 param = *ptr;
10061             ptr += 2;   // Skip the letter and the "="
10062             if (param == 'h')
10063             {
10064                 laddr->type = mDNSAddrType_IPv4;
10065                 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
10066             }
10067             else if (param == 'd')
10068             {
10069                 raddr->type = mDNSAddrType_IPv4;
10070                 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
10071             }
10072             else if (param == 'H')
10073             {
10074                 laddr->type = mDNSAddrType_IPv6;
10075                 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
10076             }
10077             else if (param == 'D')
10078             {
10079                 raddr->type = mDNSAddrType_IPv6;
10080                 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
10081             }
10082             else if (param == 'm')
10083             {
10084                 ptr = GetValueForMACAddr(ptr, limit, eth);
10085             }
10086             else
10087             {
10088                 ptr = GetValueForKeepalive(ptr, limit, &value);
10089             }
10090             if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
10091 
10092             // Extract everything in network order so that it is easy for sending a keepalive and also
10093             // for matching incoming TCP packets
10094             switch (param)
10095             {
10096             case 't':
10097                 *timeout = value;
10098                 //if (*timeout < 120) *timeout = 120;
10099                 break;
10100             case 'h':
10101             case 'H':
10102             case 'd':
10103             case 'D':
10104             case 'm':
10105             case 'i':
10106             case 'c':
10107                 break;
10108             case 'l':
10109                 lport->NotAnInteger = swap16((mDNSu16)value);
10110                 break;
10111             case 'r':
10112                 rport->NotAnInteger = swap16((mDNSu16)value);
10113                 break;
10114             case 's':
10115                 *seq = swap32(value);
10116                 break;
10117             case 'a':
10118                 *ack = swap32(value);
10119                 break;
10120             case 'w':
10121                 *win = swap16((mDNSu16)value);
10122                 break;
10123             default:
10124                 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param);
10125                 ptr = limit;
10126                 break;
10127             }
10128             ptr++; // skip the space
10129         }
10130     }
10131 }
10132 
10133 // 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
10134 // the clients need not retrieve this information from the auth record again.
10135 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport,
10136                                               const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
10137 {
10138     AuthRecord *ar;
10139     mDNSAddr laddr, raddr;
10140     mDNSEthAddr eth;
10141     mDNSIPPort lport, rport;
10142     mDNSu32 timeout, seq, ack;
10143     mDNSu16 win;
10144 
10145     for (ar = m->ResourceRecords; ar; ar=ar->next)
10146     {
10147         timeout = seq = ack = 0;
10148         win = 0;
10149         laddr = raddr = zeroAddr;
10150         lport = rport = zeroIPPort;
10151 
10152         if (!ar->WakeUp.HMAC.l[0]) continue;
10153 
10154         mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10155 
10156         // Did we parse correctly ?
10157         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10158         {
10159             debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
10160             continue;
10161         }
10162 
10163         debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
10164                &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
10165 
10166         // Does it match the incoming TCP packet ?
10167         if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
10168         {
10169             // returning in network order
10170             *rseq = seq;
10171             *rack = ack;
10172             return ar;
10173         }
10174     }
10175     return mDNSNULL;
10176 }
10177 
10178 mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
10179 {
10180     AuthRecord *ar;
10181 
10182     for (ar = m->ResourceRecords; ar; ar=ar->next)
10183     {
10184         mDNSu32 timeout, seq, ack;
10185         mDNSu16 win;
10186         mDNSAddr laddr, raddr;
10187         mDNSEthAddr eth;
10188         mDNSIPPort lport, rport;
10189 
10190         timeout = seq = ack = 0;
10191         win = 0;
10192 
10193         laddr = raddr = zeroAddr;
10194         lport = rport = zeroIPPort;
10195 
10196         if (!ar->WakeUp.HMAC.l[0]) continue;
10197 
10198         mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10199 
10200         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10201         {
10202             debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
10203             continue;
10204         }
10205         LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10206 
10207         // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
10208         // immediately (to detect any potential problems). After that we always set it to a non-zero value.
10209         if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
10210         {
10211             mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10212             ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
10213         }
10214         if (m->NextScheduledKA - ar->KATimeExpire > 0)
10215             m->NextScheduledKA = ar->KATimeExpire;
10216     }
10217 }
10218 
10219 mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
10220 {
10221     mDNSu32     timeout, seq, ack, seqInc;
10222     mDNSu16     win;
10223     mDNSAddr    laddr, raddr;
10224     mDNSEthAddr eth;
10225     mDNSIPPort  lport, rport;
10226     mDNSu8      *ptr;
10227 
10228     if (ar == mDNSNULL)
10229     {
10230         LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
10231         return;
10232     }
10233 
10234     timeout = seq = ack = 0;
10235     win = 0;
10236 
10237     laddr = raddr = zeroAddr;
10238     lport = rport = zeroIPPort;
10239 
10240     mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
10241 
10242     if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
10243     {
10244         LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar));
10245         return;
10246     }
10247 
10248     // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
10249     // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
10250     // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
10251     // it's converted to host byte order before incrementing it by one.
10252     ptr = (mDNSu8 *)&seq;
10253     seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1;
10254     ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF);
10255     ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF);
10256     ptr[2] = (mDNSu8)((seqInc >>  8) & 0xFF);
10257     ptr[3] = (mDNSu8)((seqInc      ) & 0xFF);
10258     LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
10259     mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
10260 }
10261 
10262 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
10263                                      const DNSMessage *const msg, const mDNSu8 *end,
10264                                      const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
10265                                      const mDNSInterfaceID InterfaceID)
10266 {
10267     int i;
10268     AuthRecord opt;
10269     mDNSu8 *p = m->omsg.data;
10270     OwnerOptData owner = zeroOwner;     // Need to zero this, so we'll know if this Update packet was missing its Owner option
10271     mDNSu32 updatelease = 0;
10272     const mDNSu8 *ptr;
10273 
10274     LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
10275            "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
10276            srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
10277            msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
10278            msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
10279            msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
10280            msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
10281 
10282     if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
10283 
10284     if (mDNS_PacketLoggingEnabled)
10285         DumpPacket(mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID);
10286 
10287     ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
10288     if (ptr)
10289     {
10290         ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10291         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10292         {
10293             const rdataOPT *o;
10294             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10295             for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10296             {
10297                 if      (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
10298                 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner       = o->u.owner;
10299             }
10300         }
10301         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
10302     }
10303 
10304     InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
10305 
10306     if (!updatelease || !owner.HMAC.l[0])
10307     {
10308         static int msgs = 0;
10309         if (msgs < 100)
10310         {
10311             msgs++;
10312             LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
10313                    !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
10314         }
10315         m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
10316     }
10317     else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
10318     {
10319         static int msgs = 0;
10320         if (msgs < 100)
10321         {
10322             msgs++;
10323             LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
10324                    m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
10325         }
10326         m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10327     }
10328     else
10329     {
10330         LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
10331 
10332         if (updatelease > 24 * 60 * 60)
10333             updatelease = 24 * 60 * 60;
10334 
10335         if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
10336             updatelease = 0x40000000UL / mDNSPlatformOneSecond;
10337 
10338         ptr = LocateAuthorities(msg, end);
10339 
10340         // Clear any stale TCP keepalive records that may exist
10341         ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID);
10342         ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID);
10343 
10344         for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
10345         {
10346             ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
10347             if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
10348             {
10349                 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
10350                 AuthRecord *ar = (AuthRecord *) mDNSPlatformMemAllocateClear(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
10351                 if (!ar)
10352                 {
10353                     m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10354                     break;
10355                 }
10356                 else
10357                 {
10358                     mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
10359                     m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
10360                     // All stale keepalive records have been flushed prior to this loop.
10361                     if (!mDNS_KeepaliveRecord(&m->rec.r.resrec))
10362                     {
10363                         ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
10364                         ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
10365                     }
10366                     mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
10367                     AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
10368                     ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
10369                     ar->resrec.rdata->MaxRDLength = RDLengthMem;
10370                     mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
10371                     ar->ForceMCast = mDNStrue;
10372                     ar->WakeUp     = owner;
10373                     if (m->rec.r.resrec.rrtype == kDNSType_PTR)
10374                     {
10375                         mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
10376                         if      (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10377                         else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10378                         debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
10379                         if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
10380                     }
10381                     ar->TimeRcvd   = m->timenow;
10382                     ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
10383                     if (m->NextScheduledSPS - ar->TimeExpire > 0)
10384                         m->NextScheduledSPS = ar->TimeExpire;
10385                     ar->KATimeExpire = 0;
10386                     mDNS_Register_internal(m, ar);
10387 
10388                     m->ProxyRecords++;
10389                     mDNS_UpdateAllowSleep(m);
10390                     LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
10391                 }
10392             }
10393             m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
10394         }
10395 
10396         if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
10397         {
10398             LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
10399             ClearProxyRecords(m, &owner, m->DuplicateRecords);
10400             ClearProxyRecords(m, &owner, m->ResourceRecords);
10401         }
10402         else
10403         {
10404             mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10405             opt.resrec.rrclass    = NormalMaxDNSMessageData;
10406             opt.resrec.rdlength   = sizeof(rdataOPT);   // One option in this OPT record
10407             opt.resrec.rdestimate = sizeof(rdataOPT);
10408             opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
10409             opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
10410             p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
10411         }
10412     }
10413 
10414     if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, mDNSNULL, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSfalse);
10415     mDNS_SendKeepalives(m);
10416 }
10417 
10418 mDNSlocal mDNSu32 mDNSGenerateOwnerOptForInterface(mDNS *const m, const mDNSInterfaceID InterfaceID, DNSMessage *msg)
10419 {
10420     mDNSu8 *ptr    = msg->data;
10421     mDNSu8 *end    = mDNSNULL;
10422     mDNSu32 length = 0;
10423     AuthRecord opt;
10424     NetworkInterfaceInfo *intf;
10425 
10426     mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10427     opt.resrec.rrclass    = NormalMaxDNSMessageData;
10428     opt.resrec.rdlength   = sizeof(rdataOPT);
10429     opt.resrec.rdestimate = sizeof(rdataOPT);
10430 
10431     intf = FirstInterfaceForID(m, InterfaceID);
10432     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
10433 
10434     LogSPS("Generated OPT record : %s", ARDisplayString(m, &opt));
10435     end = PutResourceRecord(msg, ptr, &msg->h.numAdditionals, &opt.resrec);
10436     if (end != mDNSNULL)
10437     {
10438         // Put all the integer values in IETF byte-order (MSB first, LSB second)
10439         SwapDNSHeaderBytes(msg);
10440         length = (mDNSu32)(end - msg->data);
10441     }
10442     else
10443         LogSPS("mDNSGenerateOwnerOptForInterface: Failed to generate owner OPT record");
10444 
10445     return length;
10446 }
10447 
10448 // Note that this routine is called both for Sleep Proxy Registrations, and for Standard Dynamic
10449 // DNS registrations, but (currently) only has to handle the Sleep Proxy Registration reply case,
10450 // and should ignore Standard Dynamic DNS registration replies, because those are handled elsewhere.
10451 // Really, both should be unified and handled in one place.
10452 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID)
10453 {
10454     if (InterfaceID)
10455     {
10456         mDNSu32 pktlease = 0, spsupdates = 0;
10457         const mDNSBool gotlease = GetPktLease(m, msg, end, &pktlease);
10458         const mDNSu32 updatelease = gotlease ? pktlease : 60 * 60; // If SPS fails to indicate lease time, assume one hour
10459         if (gotlease) LogSPS("DNS Update response contains lease option granting %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
10460 
10461         if (m->CurrentRecord)
10462             LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10463         m->CurrentRecord = m->ResourceRecords;
10464         while (m->CurrentRecord)
10465         {
10466             AuthRecord *const rr = m->CurrentRecord;
10467             if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
10468                 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
10469                 {
10470                     // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10471                     // Clear the updateid when we are done sending on all interfaces.
10472                     mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10473                     if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
10474                         bit_clr_opaque64(rr->updateIntID, scopeid);
10475                     if (mDNSOpaque64IsZero(&rr->updateIntID))
10476                         rr->updateid = zeroID;
10477                     rr->expire   = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
10478                     spsupdates++;
10479                     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));
10480                     if (rr->WakeUp.HMAC.l[0])
10481                     {
10482                         rr->WakeUp.HMAC = zeroEthAddr;  // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10483                         rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
10484                         mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10485                     }
10486                 }
10487             // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10488             // new records could have been added to the end of the list as a result of that call.
10489             if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10490                 m->CurrentRecord = rr->next;
10491         }
10492         if (spsupdates) // Only do this dynamic store stuff if this was, in fact, a Sleep Proxy Update response
10493         {
10494             char *ifname;
10495             mDNSAddr spsaddr;
10496             DNSMessage optMsg;
10497             int length;
10498             // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10499             ifname = InterfaceNameForID(m, InterfaceID);
10500             mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
10501             mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
10502 
10503             // Store the Owner OPT record for this interface.
10504             // Configd may use the OPT record if it detects a conflict with the BSP when the system wakes up
10505             InitializeDNSMessage(&optMsg.h, zeroID, ResponseFlags);
10506             length = mDNSGenerateOwnerOptForInterface(m, InterfaceID, &optMsg);
10507             if (length != 0)
10508             {
10509                 length += sizeof(DNSMessageHeader);
10510                 mDNSPlatformStoreOwnerOptRecord(ifname, &optMsg, length);
10511             }
10512         }
10513     }
10514     // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10515     // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10516     if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
10517 }
10518 
10519 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr, const domainname *const name,
10520     const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID,
10521 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10522     mdns_dns_service_t service)
10523 #else
10524     DNSServer *dnsserver)
10525 #endif
10526 {
10527     if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
10528         LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
10529 
10530     // Create empty resource record
10531     cr->resrec.RecordType    = kDNSRecordTypePacketNegative;
10532     cr->resrec.InterfaceID   = InterfaceID;
10533 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10534     mdns_replace(&cr->resrec.dnsservice, service);
10535 #else
10536     cr->resrec.rDNSServer    = dnsserver;
10537 #endif
10538     cr->resrec.name          = name;    // Will be updated to point to cg->name when we call CreateNewCacheEntry
10539     cr->resrec.rrtype        = rrtype;
10540     cr->resrec.rrclass       = rrclass;
10541     cr->resrec.rroriginalttl = ttl_seconds;
10542     cr->resrec.rdlength      = 0;
10543     cr->resrec.rdestimate    = 0;
10544     cr->resrec.namehash      = namehash;
10545     cr->resrec.rdatahash     = 0;
10546     cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
10547     cr->resrec.rdata->MaxRDLength = 0;
10548 
10549     cr->NextInKAList       = mDNSNULL;
10550     cr->TimeRcvd           = m->timenow;
10551     cr->DelayDelivery      = 0;
10552     cr->NextRequiredQuery  = m->timenow;
10553 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
10554     cr->LastCachedAnswerTime= 0;
10555 #endif
10556     cr->CRActiveQuestion   = mDNSNULL;
10557     cr->UnansweredQueries  = 0;
10558     cr->LastUnansweredTime = 0;
10559     cr->NextInCFList       = mDNSNULL;
10560     cr->soa                = mDNSNULL;
10561     // Initialize to the basic one and the caller can set it to more
10562     // specific based on the response if any
10563     cr->responseFlags      = ResponseFlags;
10564 }
10565 
10566 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10567 mDNSexport void mDNSCoreReceiveForQuerier(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10568     mdns_querier_t querier, mdns_dns_service_t dnsservice)
10569 {
10570     SwapDNSHeaderBytes(msg);
10571     mDNS_Lock(m);
10572     mDNSCoreReceiveResponse(m, msg, end, mDNSNULL, zeroIPPort, mDNSNULL, zeroIPPort, querier, dnsservice, mDNSNULL);
10573     mDNS_Unlock(m);
10574 }
10575 #endif
10576 
10577 mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
10578                                 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
10579                                 const mDNSInterfaceID InterfaceID)
10580 {
10581     mDNSInterfaceID ifid = InterfaceID;
10582     const mDNSu8 *const pkt = (mDNSu8 *)msg;
10583     const mDNSu8 StdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_StdQuery;
10584     const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
10585     const mDNSu8 UpdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_Update;
10586     const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
10587     mDNSu8 QR_OP;
10588     mDNSu8 *ptr = mDNSNULL;
10589     mDNSBool TLS = (dstaddr == (mDNSAddr *)1);  // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10590     if (TLS) dstaddr = mDNSNULL;
10591 
10592 #ifndef UNICAST_DISABLED
10593     if (mDNSSameAddress(srcaddr, &m->Router))
10594     {
10595 #ifdef _LEGACY_NAT_TRAVERSAL_
10596         if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
10597         {
10598             mDNS_Lock(m);
10599             LNT_ConfigureRouterInfo(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10600             mDNS_Unlock(m);
10601             return;
10602         }
10603 #endif
10604         if (mDNSSameIPPort(srcport, NATPMPPort))
10605         {
10606             mDNS_Lock(m);
10607             uDNS_ReceiveNATPacket(m, InterfaceID, (mDNSu8 *)msg, (mDNSu16)(end - pkt));
10608             mDNS_Unlock(m);
10609             return;
10610         }
10611     }
10612 #ifdef _LEGACY_NAT_TRAVERSAL_
10613     else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
10614 #endif
10615 
10616 #endif
10617     if ((unsigned)(end - pkt) < sizeof(DNSMessageHeader))
10618     {
10619         LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt));
10620         return;
10621     }
10622     QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
10623     // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10624     ptr = (mDNSu8 *)&msg->h.numQuestions;
10625     msg->h.numQuestions   = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
10626     msg->h.numAnswers     = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
10627     msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
10628     msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
10629 
10630     if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10631 
10632     // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10633     // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10634     if (!mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
10635 
10636     mDNS_Lock(m);
10637     m->PktNum++;
10638     if (mDNSOpaque16IsZero(msg->h.id))
10639     {
10640         m->MPktNum++;
10641 #if APPLE_OSX_mDNSResponder
10642         // Track the number of multicast packets received from a source outside our subnet.
10643         // Check the destination address to avoid accounting for spurious packets that
10644         // comes in with message id zero.
10645         if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) && dstaddr &&
10646             mDNSAddressIsAllDNSLinkGroup(dstaddr))
10647         {
10648             m->RemoteSubnet++;
10649         }
10650 #endif // #if APPLE_OSX_mDNSResponder
10651     }
10652 
10653 #ifndef UNICAST_DISABLED
10654     if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
10655         if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10656         {
10657             ifid = mDNSInterface_Any;
10658             if (mDNS_PacketLoggingEnabled)
10659                 DumpPacket(mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end, InterfaceID);
10660             uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
10661             // Note: mDNSCore also needs to get access to received unicast responses
10662         }
10663 #endif
10664     if      (QR_OP == StdQ) mDNSCoreReceiveQuery   (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10665 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10666     else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, mDNSNULL, mDNSNULL, ifid);
10667 #else
10668     else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10669 #endif
10670     else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate  (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
10671     else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr,                            InterfaceID);
10672     else
10673     {
10674         if (mDNS_LoggingEnabled)
10675         {
10676             static int msgCount = 0;
10677             if (msgCount < 1000) {
10678                 int i = 0;
10679                 msgCount++;
10680                 LogInfo("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10681                         msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), (int)(end - pkt), InterfaceID);
10682                 while (i < (int)(end - pkt))
10683                 {
10684                     char buffer[128];
10685                     char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
10686                     do if (i < (int)(end - pkt)) p += mDNS_snprintf(p, sizeof(buffer), " %02X", pkt[i]);while (++i & 15);
10687                     LogInfo("%s", buffer);
10688                 }
10689             }
10690         }
10691     }
10692     // Packet reception often causes a change to the task list:
10693     // 1. Inbound queries can cause us to need to send responses
10694     // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10695     // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10696     // 4. Response packets that answer questions may cause our client to issue new questions
10697     mDNS_Unlock(m);
10698 }
10699 
10700 // ***************************************************************************
10701 #if COMPILER_LIKES_PRAGMA_MARK
10702 #pragma mark -
10703 #pragma mark - Searcher Functions
10704 #endif
10705 
10706 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10707 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10708 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10709 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10710 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10711 //
10712 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10713 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10714 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10715 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10716 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10717 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10718 // breaks this design principle.
10719 //
10720 
10721 // If IsLLQ(Q) is true, it means the question is both:
10722 // (a) long-lived and
10723 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10724 // for multicast questions, we don't want to treat LongLived as anything special
10725 #define IsLLQ(Q)                 ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10726 #define AWDLIsIncluded(Q)        (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10727 #define SameQuestionKind(Q1, Q2) (mDNSOpaque16IsZero((Q1)->TargetQID) == mDNSOpaque16IsZero((Q2)->TargetQID))
10728 
10729 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
10730 {
10731     DNSQuestion *q;
10732     // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10733     // This prevents circular references, where two questions are each marked as a duplicate of the other.
10734     // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10735     // further in the list.
10736     for (q = m->Questions; q && (q != question); q = q->next)
10737     {
10738         if (!SameQuestionKind(q, question))                             continue;
10739         if (q->qnamehash          != question->qnamehash)               continue;
10740         if (q->InterfaceID        != question->InterfaceID)             continue;
10741         if (q->qtype              != question->qtype)                   continue;
10742         if (q->qclass             != question->qclass)                  continue;
10743         if (IsLLQ(q)              != IsLLQ(question))                   continue;
10744         if (q->AuthInfo && !question->AuthInfo)                         continue;
10745         if (!q->Suppressed        != !question->Suppressed)             continue;
10746         if (q->BrowseThreshold    != question->BrowseThreshold)         continue;
10747         if (AWDLIsIncluded(q)     != AWDLIsIncluded(question))          continue;
10748 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10749         if (q->dnsservice         != question->dnsservice)              continue;
10750 #endif
10751         if (!SameDomainName(&q->qname, &question->qname))               continue;
10752         return(q);
10753     }
10754     return(mDNSNULL);
10755 }
10756 
10757 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10758 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
10759 {
10760     DNSQuestion *q;
10761     DNSQuestion *first = mDNSNULL;
10762 
10763     // This is referring to some other question as duplicate. No other question can refer to this
10764     // question as a duplicate.
10765     if (question->DuplicateOf)
10766     {
10767         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
10768                "[R%d->DupQ%d->Q%d] UpdateQuestionDuplicates: question %p " PRI_DM_NAME " (" PUB_S ") duplicate of %p " PRI_DM_NAME " (" PUB_S ")",
10769                question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID),
10770                question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype), question->DuplicateOf,
10771                DM_NAME_PARAM(&question->DuplicateOf->qname), DNSTypeName(question->DuplicateOf->qtype));
10772         return;
10773     }
10774 
10775     for (q = m->Questions; q; q=q->next)        // Scan our list of questions
10776         if (q->DuplicateOf == question)         // To see if any questions were referencing this as their duplicate
10777         {
10778             q->DuplicateOf = first;
10779             if (!first)
10780             {
10781                 first = q;
10782                 // If q used to be a duplicate, but now is not,
10783                 // then inherit the state from the question that's going away
10784                 q->LastQTime         = question->LastQTime;
10785                 q->ThisQInterval     = question->ThisQInterval;
10786                 q->ExpectUnicastResp = question->ExpectUnicastResp;
10787                 q->LastAnswerPktNum  = question->LastAnswerPktNum;
10788                 q->RecentAnswerPkts  = question->RecentAnswerPkts;
10789                 q->RequestUnicast    = question->RequestUnicast;
10790                 q->LastQTxTime       = question->LastQTxTime;
10791                 q->CNAMEReferrals    = question->CNAMEReferrals;
10792                 q->nta               = question->nta;
10793                 q->servAddr          = question->servAddr;
10794                 q->servPort          = question->servPort;
10795 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10796                 mdns_replace(&q->dnsservice, question->dnsservice);
10797                 mdns_forget(&question->dnsservice);
10798                 mdns_querier_forget(&q->querier);
10799                 mdns_replace(&q->querier, question->querier);
10800                 mdns_forget(&question->querier);
10801 #else
10802                 q->qDNSServer        = question->qDNSServer;
10803                 q->validDNSServers   = question->validDNSServers;
10804                 q->unansweredQueries = question->unansweredQueries;
10805                 q->noServerResponse  = question->noServerResponse;
10806                 q->triedAllServersOnce = question->triedAllServersOnce;
10807 #endif
10808 
10809                 q->TargetQID         = question->TargetQID;
10810 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10811                 q->LocalSocket       = question->LocalSocket;
10812                 // No need to close old q->LocalSocket first -- duplicate questions can't have their own sockets
10813 #endif
10814 
10815                 q->state             = question->state;
10816                 //  q->tcp               = question->tcp;
10817                 q->ReqLease          = question->ReqLease;
10818                 q->expire            = question->expire;
10819                 q->ntries            = question->ntries;
10820                 q->id                = question->id;
10821 
10822 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10823                 question->LocalSocket = mDNSNULL;
10824 #endif
10825                 question->nta        = mDNSNULL;    // If we've got a GetZoneData in progress, transfer it to the newly active question
10826                 //  question->tcp        = mDNSNULL;
10827 
10828 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10829                 if (q->LocalSocket)
10830                     debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10831 #endif
10832                 if (q->nta)
10833                 {
10834                     LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10835                     q->nta->ZoneDataContext = q;
10836                 }
10837 
10838                 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10839                 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10840 
10841                 if (question->state == LLQ_Established)
10842                 {
10843                     LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10844                     question->state = 0;    // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10845                 }
10846 
10847                 SetNextQueryTime(m,q);
10848             }
10849         }
10850 }
10851 
10852 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
10853 {
10854     McastResolver **p = &m->McastResolvers;
10855     McastResolver *tmp = mDNSNULL;
10856 
10857     if (!d) d = (const domainname *)"";
10858 
10859     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
10860         "mDNS_AddMcastResolver: Adding " PUB_DM_NAME ", InterfaceID %p, timeout %u", DM_NAME_PARAM(d), interface, timeout);
10861 
10862     mDNS_CheckLock(m);
10863 
10864     while (*p)  // Check if we already have this {interface, domain} tuple registered
10865     {
10866         if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
10867         {
10868             if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
10869             (*p)->flags &= ~McastResolver_FlagDelete;
10870             tmp = *p;
10871             *p = tmp->next;
10872             tmp->next = mDNSNULL;
10873         }
10874         else
10875             p=&(*p)->next;
10876     }
10877 
10878     if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
10879     else
10880     {
10881         // allocate, add to list
10882         *p = (McastResolver *) mDNSPlatformMemAllocateClear(sizeof(**p));
10883         if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10884         else
10885         {
10886             (*p)->interface = interface;
10887             (*p)->flags     = McastResolver_FlagNew;
10888             (*p)->timeout   = timeout;
10889             AssignDomainName(&(*p)->domain, d);
10890             (*p)->next = mDNSNULL;
10891         }
10892     }
10893     return(*p);
10894 }
10895 
10896 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
10897 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
10898 {
10899     mDNSs32 ptime = 0;
10900     if (server->penaltyTime != 0)
10901     {
10902         ptime = server->penaltyTime - m->timenow;
10903         if (ptime < 0)
10904         {
10905             // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10906             // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10907             // here
10908             LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10909                    ptime, server->penaltyTime, m->timenow);
10910             server->penaltyTime = 0;
10911             ptime = 0;
10912         }
10913     }
10914     return ptime;
10915 }
10916 #endif
10917 
10918 //Checks to see whether the newname is a better match for the name, given the best one we have
10919 //seen so far (given in bestcount).
10920 //Returns -1 if the newname is not a better match
10921 //Returns 0 if the newname is the same as the old match
10922 //Returns 1 if the newname is a better match
10923 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
10924                                  int bestcount)
10925 {
10926     // If the name contains fewer labels than the new server's domain or the new name
10927     // contains fewer labels than the current best, then it can't possibly be a better match
10928     if (namecount < newcount || newcount < bestcount) return -1;
10929 
10930     // If there is no match, return -1 and the caller will skip this newname for
10931     // selection
10932     //
10933     // If we find a match and the number of labels is the same as bestcount, then
10934     // we return 0 so that the caller can do additional logic to pick one of
10935     // the best based on some other factors e.g., penaltyTime
10936     //
10937     // If we find a match and the number of labels is more than bestcount, then we
10938     // return 1 so that the caller can pick this over the old one.
10939     //
10940     // Note: newcount can either be equal or greater than bestcount beause of the
10941     // check above.
10942 
10943     if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
10944         return bestcount == newcount ? 0 : 1;
10945     else
10946         return -1;
10947 }
10948 
10949 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10950 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10951 // names. In that case, we give a default timeout of 5 seconds
10952 #define DEFAULT_MCAST_TIMEOUT   5
10953 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
10954 {
10955     McastResolver *curmatch = mDNSNULL;
10956     int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10957     McastResolver *curr;
10958     int bettermatch, currcount;
10959     for (curr = m->McastResolvers; curr; curr = curr->next)
10960     {
10961         currcount = CountLabels(&curr->domain);
10962         bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10963         // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10964         // the timeout value from the first one
10965         if (bettermatch == 1)
10966         {
10967             curmatch = curr;
10968             bestmatchlen = currcount;
10969         }
10970     }
10971     LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
10972             curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10973     return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10974 }
10975 
10976 // Returns true if it is a Domain Enumeration Query
10977 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
10978 {
10979     const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
10980                                        (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
10981     const domainname *d = qname;
10982     const mDNSu8 *label;
10983     int i = 0;
10984 
10985     // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10986     if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
10987 
10988     label = (const mDNSu8 *)d;
10989     while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
10990     {
10991         if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
10992         i++;
10993     }
10994     if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
10995     {
10996         debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
10997         return mDNSfalse;
10998     }
10999     debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
11000 
11001     // CountLabels already verified the number of labels
11002     d = (const domainname *)(d->c + 1 + d->c[0]);   // Second Label
11003     label = (const mDNSu8 *)d;
11004     if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
11005     {
11006         debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
11007         return(mDNSfalse);
11008     }
11009     debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
11010 
11011     d = (const domainname *)(d->c + 1 + d->c[0]);   // Third Label
11012     label = (const mDNSu8 *)d;
11013     if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
11014     {
11015         debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
11016         return(mDNSfalse);
11017     }
11018     debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
11019 
11020     debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
11021 
11022     return mDNStrue;
11023 }
11024 
11025 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11026 // Note: InterfaceID is the InterfaceID of the question
11027 mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11028 {
11029     // 1) Unscoped questions (NULL InterfaceID) should consider *only* unscoped DNSServers ( DNSServer
11030     // with scopeType set to kScopeNone)
11031     //
11032     // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
11033     // with scopeType set to kScopeInterfaceID) and their InterfaceIDs should match.
11034     //
11035     // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
11036     // with scopeType set to kScopeServiceID) and their ServiceIDs should match.
11037     //
11038     // The first condition in the "if" statement checks to see if both the question and the DNSServer are
11039     // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
11040     //
11041     // If the first condition fails, following are the possible cases (the notes below are using
11042     // InterfaceID for discussion and the same holds good for ServiceID):
11043     //
11044     // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
11045     //   as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
11046     //
11047     // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
11048     //   unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
11049     //   would fail in this case.
11050     //
11051     // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
11052     //   should match (Refer to (2) above).
11053 
11054     if (((d->scopeType == kScopeNone) && (!InterfaceID && ServiceID == -1))  ||
11055         ((d->scopeType == kScopeInterfaceID) && d->interface == InterfaceID) ||
11056         ((d->scopeType == kScopeServiceID) && d->serviceID == ServiceID))
11057     {
11058         return mDNStrue;
11059     }
11060     return mDNSfalse;
11061 }
11062 
11063 // Sets all the Valid DNS servers for a question
11064 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
11065 {
11066     int bestmatchlen = -1, namecount = CountLabels(&question->qname);
11067     DNSServer *curr;
11068     int bettermatch, currcount;
11069     int index = 0;
11070     mDNSu32 timeout = 0;
11071     mDNSBool DEQuery;
11072 
11073     question->validDNSServers = zeroOpaque128;
11074     DEQuery = DomainEnumQuery(&question->qname);
11075     for (curr = m->DNSServers; curr; curr = curr->next)
11076     {
11077         debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scopeType);
11078         // skip servers that will soon be deleted
11079         if (curr->flags & DNSServerFlag_Delete)
11080         {
11081             debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType);
11082             continue;
11083         }
11084 
11085         // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
11086         // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
11087         // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
11088         // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
11089         // match the scoped entries by mistake.
11090         //
11091         // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
11092 
11093         // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
11094         if (((curr->scopeType == kScopeInterfaceID) && (curr->interface == mDNSInterface_Any)) ||
11095             ((curr->scopeType == kScopeServiceID) && (curr->serviceID <= 0)))
11096         {
11097             LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]",
11098                 (int)curr->scopeType, &curr->addr, curr->domain.c, curr->interface, curr->serviceID);
11099             continue;
11100         }
11101 
11102         currcount = CountLabels(&curr->domain);
11103         if ((!DEQuery || !curr->isCell) && DNSServerMatch(curr, question->InterfaceID, question->ServiceID))
11104         {
11105             bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
11106 
11107             // If we found a better match (bettermatch == 1) then clear all the bits
11108             // corresponding to the old DNSServers that we have may set before and start fresh.
11109             // If we find an equal match, then include that DNSServer also by setting the corresponding
11110             // bit
11111             if ((bettermatch == 1) || (bettermatch == 0))
11112             {
11113                 bestmatchlen = currcount;
11114                 if (bettermatch)
11115                 {
11116                     debugf("SetValidDNSServers: Resetting all the bits");
11117                     question->validDNSServers = zeroOpaque128;
11118                     timeout = 0;
11119                 }
11120                 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
11121                        " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scopeType, index, curr->timeout,
11122                        curr->interface);
11123                 timeout += curr->timeout;
11124                 if (DEQuery)
11125                     debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->isCell);
11126                 bit_set_opaque128(question->validDNSServers, index);
11127             }
11128         }
11129         index++;
11130     }
11131     question->noServerResponse = 0;
11132 
11133     debugf("SetValidDNSServers: ValidDNSServer bits 0x%08x%08x%08x%08x for question %p %##s (%s)",
11134            question->validDNSServers.l[3], question->validDNSServers.l[2], question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
11135     // If there are no matching resolvers, then use the default timeout value.
11136     return (timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
11137 }
11138 
11139 // Get the Best server that matches a name. If you find penalized servers, look for the one
11140 // that will come out of the penalty box soon
11141 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque128 validBits,
11142     int *selected, mDNSBool nameMatch)
11143 {
11144     DNSServer *curmatch = mDNSNULL;
11145     int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
11146     DNSServer *curr;
11147     mDNSs32 bestPenaltyTime, currPenaltyTime;
11148     int bettermatch, currcount;
11149     int index = 0;
11150     int currindex = -1;
11151 
11152     debugf("GetBestServer: ValidDNSServer bits  0x%x%x", validBits.l[1], validBits.l[0]);
11153     bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
11154     for (curr = m->DNSServers; curr; curr = curr->next)
11155     {
11156         // skip servers that will soon be deleted
11157         if (curr->flags & DNSServerFlag_Delete)
11158         {
11159             debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scopeType);
11160             continue;
11161         }
11162 
11163         // Check if this is a valid DNSServer
11164         if (!bit_get_opaque64(validBits, index))
11165         {
11166             debugf("GetBestServer: continuing for index %d", index);
11167             index++;
11168             continue;
11169         }
11170 
11171         currcount = CountLabels(&curr->domain);
11172         currPenaltyTime = PenaltyTimeForServer(m, curr);
11173 
11174         debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
11175                &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
11176 
11177         // If there are multiple best servers for a given question, we will pick the first one
11178         // if none of them are penalized. If some of them are penalized in that list, we pick
11179         // the least penalized one. BetterMatchForName walks through all best matches and
11180         // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
11181         // in the list when there are no penalized servers and least one among them
11182         // when there are some penalized servers.
11183 
11184         if (DNSServerMatch(curr, InterfaceID, ServiceID))
11185         {
11186 
11187             // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
11188             // This happens when we initially walk all the DNS servers and set the validity bit on the question.
11189             // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
11190             // part and still do some redundant steps e.g., InterfaceID match
11191 
11192             if (nameMatch)
11193                 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
11194             else
11195                 bettermatch = 0;
11196 
11197             // If we found a better match (bettermatch == 1) then we don't need to
11198             // compare penalty times. But if we found an equal match, then we compare
11199             // the penalty times to pick a better match
11200 
11201             if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
11202             {
11203                 currindex = index;
11204                 curmatch = curr;
11205                 bestmatchlen = currcount;
11206                 bestPenaltyTime = currPenaltyTime;
11207             }
11208         }
11209         index++;
11210     }
11211     if (selected) *selected = currindex;
11212     return curmatch;
11213 }
11214 
11215 // Look up a DNS Server, matching by name and InterfaceID
11216 mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
11217 {
11218     DNSServer *curmatch = mDNSNULL;
11219     char *ifname = mDNSNULL;    // for logging purposes only
11220     mDNSOpaque128 allValid;
11221 
11222     if (InterfaceID == mDNSInterface_LocalOnly)
11223         InterfaceID = mDNSNULL;
11224 
11225     if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
11226 
11227     // By passing in all ones, we make sure that every DNS server is considered
11228     allValid.l[0] = allValid.l[1] = allValid.l[2] = allValid.l[3] = 0xFFFFFFFF;
11229 
11230     curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue);
11231 
11232     if (curmatch != mDNSNULL)
11233         LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) for %##s", &curmatch->addr,
11234                 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
11235                 InterfaceID, name);
11236     else
11237         LogInfo("GetServerForName: no DNS server (Scope %s:%p) for %##s", ifname ? ifname : "None", InterfaceID, name);
11238 
11239     return(curmatch);
11240 }
11241 
11242 // Look up a DNS Server for a question within its valid DNSServer bits
11243 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
11244 {
11245     DNSServer *curmatch = mDNSNULL;
11246     char *ifname = mDNSNULL;    // for logging purposes only
11247     mDNSInterfaceID InterfaceID = question->InterfaceID;
11248     const domainname *name = &question->qname;
11249     int currindex;
11250 
11251     if (InterfaceID == mDNSInterface_LocalOnly)
11252         InterfaceID = mDNSNULL;
11253 
11254     if (InterfaceID)
11255         ifname = InterfaceNameForID(m, InterfaceID);
11256 
11257     if (!mDNSOpaque128IsZero(&question->validDNSServers))
11258     {
11259         curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse);
11260         if (currindex != -1)
11261             bit_clr_opaque128(question->validDNSServers, currindex);
11262     }
11263 
11264     if (curmatch != mDNSNULL)
11265     {
11266         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11267                "[R%d->Q%d] GetServerForQuestion: %p DNS server (%p) " PRI_IP_ADDR ":%d (Penalty Time Left %d) (Scope " PUB_S ":%p:%d) for " PRI_DM_NAME " (" PUB_S ")",
11268                question->request_id, mDNSVal16(question->TargetQID), question, curmatch, &curmatch->addr,
11269                mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0),
11270                ifname ? ifname : "None", InterfaceID, question->ServiceID, DM_NAME_PARAM(name), DNSTypeName(question->qtype));
11271     }
11272     else
11273     {
11274         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11275                "[R%d->Q%d] GetServerForQuestion: %p no DNS server (Scope " PUB_S ":%p:%d) for " PRI_DM_NAME " (" PUB_S ")",
11276                question->request_id, mDNSVal16(question->TargetQID), question, ifname ? ifname : "None", InterfaceID,
11277                question->ServiceID, DM_NAME_PARAM(name), DNSTypeName(question->qtype));
11278     }
11279 
11280     return(curmatch);
11281 }
11282 #endif // MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11283 
11284 // Called in normal client context (lock not held)
11285 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
11286 {
11287     DNSQuestion *q;
11288     mDNS_Lock(m);
11289     LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
11290     n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T
11291     for (q = m->Questions; q; q=q->next)
11292         if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
11293             startLLQHandshake(m, q);    // If ExternalPort is zero, will do StartLLQPolling instead
11294     mDNS_Unlock(m);
11295 }
11296 
11297 // This function takes the DNSServer as a separate argument because sometimes the
11298 // caller has not yet assigned the DNSServer, but wants to evaluate the Suppressed
11299 // status before switching to it.
11300 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11301 mDNSexport mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const mdns_dns_service_t dnsservice)
11302 #else
11303 mDNSlocal mDNSBool ShouldSuppressUnicastQuery(const DNSQuestion *const q, const DNSServer *const server)
11304 #endif
11305 {
11306     mDNSBool suppress = mDNSfalse;
11307     const char *reason = mDNSNULL;
11308 
11309     if (q->BlockedByPolicy)
11310     {
11311         suppress = mDNStrue;
11312         reason   = " (blocked by policy)";
11313     }
11314 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11315     else if (!dnsservice)
11316     {
11317         if (!q->IsUnicastDotLocal)
11318         {
11319             suppress = mDNStrue;
11320             reason   = " (no DNS service)";
11321         }
11322     }
11323 #else
11324     else if (!server)
11325     {
11326         if (!q->IsUnicastDotLocal)
11327         {
11328             suppress = mDNStrue;
11329             reason   = " (no DNS server)";
11330         }
11331     }
11332 #endif
11333 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11334     else if ((q->flags & kDNSServiceFlagsDenyCellular) && mdns_dns_service_interface_is_cellular(dnsservice))
11335 #else
11336     else if ((q->flags & kDNSServiceFlagsDenyCellular) && server->isCell)
11337 #endif
11338     {
11339         suppress = mDNStrue;
11340         reason   = " (interface is cellular)";
11341     }
11342 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11343     else if ((q->flags & kDNSServiceFlagsDenyExpensive) && mdns_dns_service_interface_is_expensive(dnsservice))
11344 #else
11345     else if ((q->flags & kDNSServiceFlagsDenyExpensive) && server->isExpensive)
11346 #endif
11347     {
11348         suppress = mDNStrue;
11349         reason   = " (interface is expensive)";
11350     }
11351 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11352     else if ((q->flags & kDNSServiceFlagsDenyConstrained) && mdns_dns_service_interface_is_constrained(dnsservice))
11353 #else
11354     else if ((q->flags & kDNSServiceFlagsDenyConstrained) && server->isConstrained)
11355 #endif
11356     {
11357         suppress = mDNStrue;
11358         reason   = " (interface is constrained)";
11359     }
11360 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
11361     else if (q->SuppressUnusable && !DNS64IsQueryingARecord(q->dns64.state))
11362 #else
11363     else if (q->SuppressUnusable)
11364 #endif
11365     {
11366         if (q->qtype == kDNSType_A)
11367         {
11368 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11369             if (!mdns_dns_service_a_queries_advised(dnsservice))
11370 #else
11371             if (!server->usableA)
11372 #endif
11373             {
11374                 suppress = mDNStrue;
11375                 reason   = " (A records are unusable)";
11376             }
11377             // If the server's configuration allows A record queries, suppress this query if
11378             //     1. the interface associated with the server is CLAT46; and
11379             //     2. the query has the kDNSServiceFlagsPathEvaluationDone flag, indicating that it's from libnetwork.
11380             // See <rdar://problem/42672030> for more info.
11381 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11382             else if ((q->flags & kDNSServiceFlagsPathEvaluationDone) && mdns_dns_service_interface_is_clat46(dnsservice))
11383 #else
11384             else if ((q->flags & kDNSServiceFlagsPathEvaluationDone) && server->isCLAT46)
11385 #endif
11386             {
11387                 suppress = mDNStrue;
11388                 reason   = " (CLAT46 A records are unusable)";
11389             }
11390         }
11391         else if (q->qtype == kDNSType_AAAA)
11392         {
11393 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11394             if (!mdns_dns_service_aaaa_queries_advised(dnsservice))
11395 #else
11396             if (!server->usableAAAA)
11397 #endif
11398             {
11399                 suppress = mDNStrue;
11400                 reason   = " (AAAA records are unusable)";
11401             }
11402         }
11403     }
11404     if (suppress)
11405     {
11406         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11407             "[Q%u] ShouldSuppressUnicastQuery: Query suppressed for " PRI_DM_NAME " " PUB_S PUB_S,
11408             mDNSVal16(q->TargetQID), DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), reason ? reason : "");
11409     }
11410     return suppress;
11411 }
11412 
11413 mDNSlocal mDNSBool ShouldSuppressQuery(DNSQuestion *q)
11414 {
11415     // Multicast queries are never suppressed.
11416     if (mDNSOpaque16IsZero(q->TargetQID))
11417     {
11418         return mDNSfalse;
11419     }
11420 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11421     return (ShouldSuppressUnicastQuery(q, q->dnsservice));
11422 #else
11423     return (ShouldSuppressUnicastQuery(q, q->qDNSServer));
11424 #endif
11425 }
11426 
11427 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
11428 {
11429     CacheRecord *cr;
11430     CacheGroup *cg;
11431 
11432     cg = CacheGroupForName(m, q->qnamehash, &q->qname);
11433     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
11434     {
11435         // Don't deliver RMV events for negative records
11436         if (cr->resrec.RecordType == kDNSRecordTypePacketNegative)
11437         {
11438             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11439                       "[R%u->Q%u] CacheRecordRmvEventsForCurrentQuestion: CacheRecord " PRI_S " Suppressing RMV events for question %p " PRI_DM_NAME " (" PUB_S "), CRActiveQuestion %p, CurrentAnswers %d",
11440                       q->request_id, mDNSVal16(q->TargetQID), CRDisplayString(m, cr), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), cr->CRActiveQuestion, q->CurrentAnswers);
11441             continue;
11442         }
11443 
11444         if (SameNameCacheRecordAnswersQuestion(cr, q))
11445         {
11446             LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11447                     q->qname.c, CRDisplayString(m, cr), q->LOAddressAnswers);
11448 
11449             q->CurrentAnswers--;
11450             if (cr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
11451             if (cr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
11452             AnswerCurrentQuestionWithResourceRecord(m, cr, QC_rmv);
11453             if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
11454         }
11455     }
11456 }
11457 
11458 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
11459 {
11460     DNSQuestion *q;
11461     for (q = m->NewQuestions; q; q = q->next)
11462         if (q == question) return mDNStrue;
11463     return mDNSfalse;
11464 }
11465 
11466 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11467 mDNSexport mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11468 #else
11469 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11470 #endif
11471 {
11472     AuthRecord *rr;
11473     AuthGroup *ag;
11474 
11475     if (m->CurrentQuestion)
11476         LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11477                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11478 
11479     if (IsQuestionNew(m, q))
11480     {
11481         LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11482         return mDNStrue;
11483     }
11484     m->CurrentQuestion = q;
11485     ag = AuthGroupForName(&m->rrauth, q->qnamehash, &q->qname);
11486     if (ag)
11487     {
11488         for (rr = ag->members; rr; rr=rr->next)
11489             // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11490             if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
11491             {
11492                 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11493                         ARDisplayString(m, rr));
11494                 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
11495                 {
11496                     LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11497                            " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
11498                            q->CurrentAnswers, q->LOAddressAnswers);
11499                     continue;
11500                 }
11501                 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv);      // MUST NOT dereference q again
11502                 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11503             }
11504     }
11505     m->CurrentQuestion = mDNSNULL;
11506     return mDNStrue;
11507 }
11508 
11509 // Returns false if the question got deleted while delivering the RMV events
11510 // The caller should handle the case
11511 mDNSexport mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11512 {
11513     if (m->CurrentQuestion)
11514         LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11515                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11516 
11517     // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11518     // If this question was answered using local auth records, then you can't deliver RMVs using cache
11519     if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
11520     {
11521         m->CurrentQuestion = q;
11522         CacheRecordRmvEventsForCurrentQuestion(m, q);
11523         if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11524         m->CurrentQuestion = mDNSNULL;
11525     }
11526     else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
11527     return mDNStrue;
11528 }
11529 
11530 mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart)
11531 {
11532     // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11533     // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11534     // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11535     if (q->Suppressed)
11536     {
11537         q->Suppressed = mDNSfalse;
11538         if (!CacheRecordRmvEventsForQuestion(m, q))
11539         {
11540             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11541                 "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from cache",
11542                 q->request_id, mDNSVal16(q->TargetQID));
11543             return;
11544         }
11545         q->Suppressed = mDNStrue;
11546     }
11547 
11548     // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11549     // and Suppressed status does not mean anything for these questions. As we are going to stop the
11550     // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11551     // the restart will not be a duplicate ADD
11552     if (!LocalRecordRmvEventsForQuestion(m, q))
11553     {
11554         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11555             "[R%u->Q%u] SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords",
11556             q->request_id, mDNSVal16(q->TargetQID));
11557         return;
11558     }
11559 
11560     // There are two cases here.
11561     //
11562     // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11563     // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11564     // because when we get the response, if we had entries in the cache already, it will not answer
11565     // this question if the cache entry did not change. Hence, we need to restart
11566     // the query so that it can be answered from the cache.
11567     //
11568     // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11569     // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11570     // is a duplicate of non-SuppressUnusable question if it is not suppressed (Suppressed is false).
11571     // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11572     // (Suppressed is true). The reason for this is that when a question is suppressed, we want an
11573     // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11574     // the question is not suppressed, we don't want two active questions sending packets on the wire.
11575     // This affects both efficiency and also the current design where there is only one active question
11576     // pointed to from a cache entry.
11577     //
11578     // We restart queries in a two step process by first calling stop and build a temporary list which we
11579     // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11580     // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11581     // will soon become the real question) including q->ThisQInterval which might be zero if it was
11582     // suppressed before. At the end when we have restarted all questions, none of them is active as each
11583     // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11584     //
11585     // It is much cleaner and less error prone to build a list of questions and restart at the end.
11586 
11587     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11588         "[R%u->Q%u] SuppressStatusChanged: Stop question %p " PRI_DM_NAME " (" PUB_S ")",
11589         q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
11590     mDNS_StopQuery_internal(m, q);
11591     q->next = *restart;
11592     *restart = q;
11593 }
11594 
11595 // The caller should hold the lock
11596 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
11597 {
11598     DNSQuestion *q;
11599     DNSQuestion *restart = mDNSNULL;
11600 
11601     // We look through all questions including new questions. During network change events,
11602     // we potentially restart questions here in this function that ends up as new questions,
11603     // which may be suppressed at this instance. Before it is handled we get another network
11604     // event that changes the status e.g., address becomes available. If we did not process
11605     // new questions, we would never change its Suppressed status.
11606     //
11607     // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11608     // application callback can potentially stop the current question (detected by CurrentQuestion) or
11609     // *any* other question which could be the next one that we may process here. RestartQuestion
11610     // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11611     // if the "next" question is stopped while the CurrentQuestion is stopped
11612     if (m->RestartQuestion)
11613         LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11614                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11615     m->RestartQuestion = m->Questions;
11616     while (m->RestartQuestion)
11617     {
11618         q = m->RestartQuestion;
11619         m->RestartQuestion = q->next;
11620         if (q->SuppressUnusable)
11621         {
11622             const mDNSBool old = q->Suppressed;
11623             q->Suppressed = ShouldSuppressQuery(q);
11624             if (q->Suppressed != old)
11625             {
11626                 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11627                 // followed by a negative cache response. Temporarily turn off suppression so that
11628                 // AnswerCurrentQuestionWithResourceRecord can answer the question
11629                 SuppressStatusChanged(m, q, &restart);
11630             }
11631         }
11632     }
11633     while (restart)
11634     {
11635         q = restart;
11636         restart = restart->next;
11637         q->next = mDNSNULL;
11638         LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11639         mDNS_StartQuery_internal(m, q);
11640     }
11641 }
11642 
11643 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11644 mDNSlocal void RestartUnicastQuestions(mDNS *const m)
11645 {
11646     DNSQuestion *q;
11647     DNSQuestion *restartList = mDNSNULL;
11648 
11649     if (m->RestartQuestion)
11650         LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11651                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11652     m->RestartQuestion = m->Questions;
11653     while (m->RestartQuestion)
11654     {
11655         q = m->RestartQuestion;
11656         m->RestartQuestion = q->next;
11657         if (q->Restart)
11658         {
11659             if (mDNSOpaque16IsZero(q->TargetQID))
11660                 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11661 
11662             q->Restart = mDNSfalse;
11663             SuppressStatusChanged(m, q, &restartList);
11664         }
11665     }
11666     while ((q = restartList) != mDNSNULL)
11667     {
11668         restartList = q->next;
11669         q->next = mDNSNULL;
11670         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11671             "[R%u->Q%u] RestartUnicastQuestions: Start question %p " PRI_DM_NAME " (" PUB_S ")",
11672              q->request_id, mDNSVal16(q->TargetQID), q, DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype));
11673         mDNS_StartQuery_internal(m, q);
11674     }
11675 }
11676 #endif
11677 
11678 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11679 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11680 mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question)
11681 {
11682     if (!ValidateDomainName(&question->qname))
11683     {
11684         LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11685         return(mStatus_Invalid);
11686     }
11687 
11688     // If this question is referencing a specific interface, verify it exists
11689     if (question->InterfaceID && !LocalOnlyOrP2PInterface(question->InterfaceID))
11690     {
11691         NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
11692         if (!intf)
11693             LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11694                     IIDPrintable(question->InterfaceID), question->qname.c, DNSTypeName(question->qtype));
11695     }
11696 
11697     return(mStatus_NoError);
11698 }
11699 
11700 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11701 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeBeforeResolve()
11702 mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question)
11703 {
11704     // First reset all DNS Configuration
11705 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11706     mdns_forget(&question->dnsservice);
11707 #else
11708     question->qDNSServer          = mDNSNULL;
11709     question->validDNSServers     = zeroOpaque128;
11710     question->triedAllServersOnce = mDNSfalse;
11711     question->noServerResponse    = mDNSfalse;
11712 #endif
11713     question->StopTime            = (question->TimeoutQuestion) ? question->StopTime : 0;
11714 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
11715     mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics));
11716     question->metrics.expiredAnswerState = (question->allowExpired != AllowExpired_None) ? ExpiredAnswer_Allowed : ExpiredAnswer_None;
11717 #endif
11718 
11719     // Need not initialize the DNS Configuration for Local Only OR P2P Questions when timeout not specified
11720     if (LocalOnlyOrP2PInterface(question->InterfaceID) && !question->TimeoutQuestion)
11721         return;
11722     // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11723     if (!mDNSOpaque16IsZero(question->TargetQID))
11724     {
11725 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11726         mDNSu32 timeout = 30;
11727 #else
11728         mDNSu32 timeout = SetValidDNSServers(m, question);
11729 #endif
11730         // We set the timeout value the first time mDNS_StartQuery_internal is called for a question.
11731         // So if a question is restarted when a network change occurs, the StopTime is not reset.
11732         // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11733         // it gets a full timeout value even if the original question times out earlier.
11734         if (question->TimeoutQuestion && !question->StopTime)
11735         {
11736             question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11737             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11738                 "[Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")",
11739                 mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11740         }
11741 
11742 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11743         Querier_SetDNSServiceForQuestion(question);
11744 #else
11745         question->qDNSServer = GetServerForQuestion(m, question);
11746         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
11747             "[R%u->Q%u] InitDNSConfig: question %p " PRI_DM_NAME " " PUB_S " Timeout %d, DNS Server " PRI_IP_ADDR ":%d",
11748             question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname),
11749             DNSTypeName(question->qtype), timeout, question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11750             mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11751 #endif
11752     }
11753     else if (question->TimeoutQuestion && !question->StopTime)
11754     {
11755         // If the question is to be timed out and its a multicast, local-only or P2P case,
11756         // then set it's stop time.
11757         mDNSu32 timeout = LocalOnlyOrP2PInterface(question->InterfaceID) ?
11758                             DEFAULT_LO_OR_P2P_TIMEOUT : GetTimeoutForMcastQuestion(m, question);
11759         question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11760         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11761                   "[R%u->Q%u] InitDNSConfig: Setting StopTime on the uDNS question %p " PRI_DM_NAME " (" PUB_S ")",
11762                   question->request_id, mDNSVal16(question->TargetQID), question, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11763     }
11764     // Set StopTime here since it is a part of DNS Configuration
11765     if (question->StopTime)
11766         SetNextQueryStopTime(m, question);
11767     // Don't call SetNextQueryTime() if a LocalOnly OR P2P Question since those questions
11768     // will never be transmitted on the wire.
11769     if (!(LocalOnlyOrP2PInterface(question->InterfaceID)))
11770         SetNextQueryTime(m,question);
11771 }
11772 
11773 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11774 // state fields of the DNS Question. These are independent of the Client layer.
11775 mDNSlocal void InitCommonState(mDNS *const m, DNSQuestion *const question)
11776 {
11777     int i;
11778 
11779     // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11780     // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11781     // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11782     // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11783     // that to go out immediately.
11784     question->next              = mDNSNULL;
11785     // ThisQInterval should be initialized before any memory allocations occur. If malloc
11786     // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11787     // the question list to check if ThisQInterval is negative which means the question has been
11788     // stopped and can't be on the list. The question is already on the list and ThisQInterval
11789     // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11790     // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11791     // turned ON which can allocate memory e.g., base64 encoding.
11792     question->ThisQInterval     = InitialQuestionInterval;                  // MUST be > zero for an active question
11793     question->qnamehash         = DomainNameHashValue(&question->qname);
11794     question->DelayAnswering    = mDNSOpaque16IsZero(question->TargetQID) ? CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash) : 0;
11795     question->LastQTime         = m->timenow;
11796     question->ExpectUnicastResp = 0;
11797     question->LastAnswerPktNum  = m->PktNum;
11798     question->RecentAnswerPkts  = 0;
11799     question->CurrentAnswers    = 0;
11800 
11801 #if APPLE_OSX_mDNSResponder
11802 
11803 // Initial browse threshold used by Finder.
11804 #define mDNSFinderBrowseThreshold 20
11805 
11806     // Set the threshold at which we move to a passive browse state,
11807     // not actively sending queries.
11808     if (question->flags & kDNSServiceFlagsThresholdOne)
11809         question->BrowseThreshold   = 1;
11810     else if (question->flags & kDNSServiceFlagsThresholdFinder)
11811         question->BrowseThreshold   = mDNSFinderBrowseThreshold;
11812     else
11813         question->BrowseThreshold   = 0;
11814 
11815 #else   // APPLE_OSX_mDNSResponder
11816    question->BrowseThreshold   = 0;
11817 #endif  // APPLE_OSX_mDNSResponder
11818     question->CachedAnswerNeedsUpdate = mDNSfalse;
11819 
11820     question->LargeAnswers      = 0;
11821     question->UniqueAnswers     = 0;
11822     question->LOAddressAnswers  = 0;
11823     question->FlappingInterface1 = mDNSNULL;
11824     question->FlappingInterface2 = mDNSNULL;
11825 
11826     // mDNSPlatformGetDNSRoutePolicy() and InitDNSConfig() may set a DNSQuestion's BlockedByPolicy value,
11827     // so they should be called before calling ShouldSuppressQuery(), which checks BlockedByPolicy.
11828     question->BlockedByPolicy = mDNSfalse;
11829 
11830     // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11831     // since we would already have the question->ServiceID in that case.
11832     if (!(question->flags & kDNSServiceFlagsServiceIndex))
11833     {
11834         question->ServiceID = -1;
11835 #if APPLE_OSX_mDNSResponder
11836         if (!(question->flags & kDNSServiceFlagsPathEvaluationDone) || question->ForcePathEval)
11837         {
11838             if (question->flags & kDNSServiceFlagsPathEvaluationDone)
11839             {
11840                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11841                     "[R%u->Q%u] Forcing another path evaluation", question->request_id, mDNSVal16(question->TargetQID));
11842             }
11843             question->ForcePathEval = mDNSfalse;
11844             mDNSPlatformGetDNSRoutePolicy(question);
11845         }
11846 #endif
11847     }
11848     else
11849         LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c,
11850                 DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID);
11851 
11852     InitDNSConfig(m, question);
11853     question->AuthInfo          = GetAuthInfoForQuestion(m, question);
11854     question->Suppressed        = ShouldSuppressQuery(question);
11855     question->NextInDQList      = mDNSNULL;
11856     question->SendQNow          = mDNSNULL;
11857     question->SendOnAll         = mDNSfalse;
11858     question->RequestUnicast    = kDefaultRequestUnicastCount;
11859 
11860 #if APPLE_OSX_mDNSResponder
11861     // Set the QU bit in the first query for the following options.
11862     if ((question->flags & kDNSServiceFlagsUnicastResponse) || (question->flags & kDNSServiceFlagsThresholdFinder))
11863     {
11864         question->RequestUnicast    = SET_QU_IN_FIRST_QUERY;
11865         LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c,
11866             DNSTypeName(question->qtype));
11867     }
11868 #endif  // APPLE_OSX_mDNSResponder
11869 
11870     question->LastQTxTime       = m->timenow;
11871     question->CNAMEReferrals    = 0;
11872 
11873     question->WakeOnResolveCount = 0;
11874     if (question->WakeOnResolve)
11875     {
11876         question->WakeOnResolveCount = InitialWakeOnResolveCount;
11877     }
11878 
11879     for (i=0; i<DupSuppressInfoSize; i++)
11880         question->DupSuppress[i].InterfaceID = mDNSNULL;
11881 
11882 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11883     question->Restart = mDNSfalse;
11884 #endif
11885 
11886     debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11887             question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
11888             NextQSendTime(question) - m->timenow,
11889             question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
11890             question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
11891 
11892     if (question->DelayAnswering)
11893         LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11894                  question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
11895 }
11896 
11897 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11898 mDNSlocal void InitWABState(DNSQuestion *const question)
11899 {
11900     // We'll create our question->LocalSocket on demand, if needed.
11901     // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11902     // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11903     // NAT mapping for receiving inbound add/remove events.
11904     question->LocalSocket       = mDNSNULL;
11905 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11906     mdns_querier_forget(&question->querier);
11907 #else
11908     question->unansweredQueries = 0;
11909 #endif
11910     question->nta               = mDNSNULL;
11911     question->servAddr          = zeroAddr;
11912     question->servPort          = zeroIPPort;
11913     question->tcp               = mDNSNULL;
11914     question->NoAnswer          = NoAnswer_Normal;
11915 }
11916 
11917 mDNSlocal void InitLLQNATState(mDNS *const m)
11918 {
11919     // If we don't have our NAT mapping active, start it now
11920     if (!m->LLQNAT.clientCallback)
11921     {
11922         m->LLQNAT.Protocol       = NATOp_MapUDP;
11923         m->LLQNAT.IntPort        = m->UnicastPort4;
11924         m->LLQNAT.RequestedPort  = m->UnicastPort4;
11925         m->LLQNAT.clientCallback = LLQNATCallback;
11926         m->LLQNAT.clientContext  = (void*)1; // Means LLQ NAT Traversal just started
11927         mDNS_StartNATOperation_internal(m, &m->LLQNAT);
11928     }
11929 }
11930 
11931 mDNSlocal void InitLLQState(DNSQuestion *const question)
11932 {
11933     question->state             = LLQ_Init;
11934     question->ReqLease          = 0;
11935     question->expire            = 0;
11936     question->ntries            = 0;
11937     question->id                = zeroOpaque64;
11938 }
11939 
11940 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11941 // DNSSEC & DNS Proxy fields of the DNS Question.
11942 mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question)
11943 {
11944     (void) m;
11945     question->responseFlags = zeroID;
11946 }
11947 
11948 // Once the question is completely initialized including the duplicate logic, this function
11949 // is called to finalize the unicast question which requires flushing the cache if needed,
11950 // activating the query etc.
11951 mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question)
11952 {
11953     // Ensure DNS related info of duplicate question is same as the orig question
11954     if (question->DuplicateOf)
11955     {
11956 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
11957         const DNSQuestion *const duplicateOf = question->DuplicateOf;
11958         mdns_replace(&question->dnsservice, duplicateOf->dnsservice);
11959         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11960            "[R%u->DupQ%u->Q%u] Duplicate question " PRI_DM_NAME " (" PUB_S ")",
11961            question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(duplicateOf->TargetQID),
11962            DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11963 #else
11964         question->validDNSServers = question->DuplicateOf->validDNSServers;
11965         // If current(dup) question has DNS Server assigned but the original question has no DNS Server assigned to it,
11966         // then we log a line as it could indicate an issue
11967         if (question->DuplicateOf->qDNSServer == mDNSNULL)
11968         {
11969             if (question->qDNSServer)
11970             {
11971                 LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11972                        "[R%d->Q%d] FinalizeUnicastQuestion: Current(dup) question %p has DNSServer(" PRI_IP_ADDR ":%d) but original question(%p) has no DNS Server! " PRI_DM_NAME " (" PUB_S ")",
11973                        question->request_id, mDNSVal16(question->TargetQID), question,
11974                        question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11975                        mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort), question->DuplicateOf,
11976                        DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
11977             }
11978         }
11979         question->qDNSServer = question->DuplicateOf->qDNSServer;
11980         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
11981                "[R%d->DupQ%d->Q%d] FinalizeUnicastQuestion: Duplicate question %p (%p) " PRI_DM_NAME " (" PUB_S "), DNS Server " PRI_IP_ADDR ":%d",
11982                question->request_id, mDNSVal16(question->TargetQID), mDNSVal16(question->DuplicateOf->TargetQID),
11983                question, question->DuplicateOf, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype),
11984                question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11985                mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zeroIPPort));
11986 #endif
11987     }
11988 
11989     ActivateUnicastQuery(m, question, mDNSfalse);
11990 
11991     if (question->LongLived)
11992     {
11993         // Unlike other initializations, InitLLQNATState should be done after
11994         // we determine that it is a unicast question.  LongLived is set for
11995         // both multicast and unicast browse questions but we should initialize
11996         // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11997         // start the NAT traversal that is not needed.
11998         InitLLQNATState(m);
11999     }
12000 }
12001 
12002 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
12003 {
12004     DNSQuestion **q;
12005     mStatus vStatus;
12006 
12007     // First check for cache space (can't do queries if there is no cache space allocated)
12008     if (m->rrcache_size == 0)
12009         return(mStatus_NoCache);
12010 
12011     vStatus = ValidateParameters(m, question);
12012     if (vStatus)
12013         return(vStatus);
12014 
12015 #ifdef USE_LIBIDN
12016     // If the TLD includes high-ascii bytes, assume it will need to be converted to Punycode.
12017     // (In the future the root name servers may answer UTF-8 queries directly, but for now they do not.)
12018     // This applies to the top label (TLD) only
12019     // -- for the second level and down we try UTF-8 first, and then fall back to Punycode only if UTF-8 fails.
12020     if (IsHighASCIILabel(LastLabel(&question->qname)))
12021     {
12022         domainname newname;
12023         if (PerformNextPunycodeConversion(question, &newname))
12024             AssignDomainName(&question->qname, &newname);
12025     }
12026 #endif // USE_LIBIDN
12027 
12028 #ifndef UNICAST_DISABLED
12029     question->TargetQID = Question_uDNS(question) ? mDNS_NewMessageID(m) : zeroID;
12030 #else
12031     question->TargetQID = zeroID;
12032 #endif
12033     debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12034 
12035     // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
12036     q = &m->Questions;
12037     if (LocalOnlyOrP2PInterface(question->InterfaceID))
12038         q = &m->LocalOnlyQuestions;
12039     while (*q && *q != question)
12040         q=&(*q)->next;
12041 
12042     if (*q)
12043     {
12044         LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
12045                 question->qname.c, DNSTypeName(question->qtype), question);
12046         return(mStatus_AlreadyRegistered);
12047     }
12048     *q = question;
12049 
12050     // Intialize the question. The only ordering constraint we have today is that
12051     // InitDNSSECProxyState should be called after the DNS server is selected (in
12052     // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
12053     // validation.
12054 
12055     InitCommonState(m, question);
12056     InitWABState(question);
12057     InitLLQState(question);
12058     InitDNSSECProxyState(m, question);
12059 
12060     // FindDuplicateQuestion should be called last after all the intialization
12061     // as the duplicate logic could be potentially based on any field in the
12062     // question.
12063     question->DuplicateOf  = FindDuplicateQuestion(m, question);
12064     if (question->DuplicateOf)
12065         question->AuthInfo = question->DuplicateOf->AuthInfo;
12066 
12067     if (LocalOnlyOrP2PInterface(question->InterfaceID))
12068     {
12069         if (!m->NewLocalOnlyQuestions)
12070             m->NewLocalOnlyQuestions = question;
12071     }
12072     else
12073     {
12074         if (!m->NewQuestions)
12075             m->NewQuestions = question;
12076 
12077         // If the question's id is non-zero, then it's Wide Area
12078         // MUST NOT do this Wide Area setup until near the end of
12079         // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
12080         // NS, etc.) and if we haven't finished setting up our own question and setting
12081         // m->NewQuestions if necessary then we could end up recursively re-entering
12082         // this routine with the question list data structures in an inconsistent state.
12083         if (!mDNSOpaque16IsZero(question->TargetQID))
12084         {
12085             FinalizeUnicastQuestion(m, question);
12086         }
12087         else
12088         {
12089 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12090             m->NumAllInterfaceQuestions++;
12091             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12092                 "mDNS_StartQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME " (" PUB_S ")",
12093                 m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
12094             if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12095             {
12096                 m->NextBonjourDisableTime = 0;
12097                 if (m->BonjourEnabled == 0)
12098                 {
12099                     // Enable Bonjour immediately by scheduling network changed processing where
12100                     // we will join the multicast group on each active interface.
12101                     m->BonjourEnabled = 1;
12102                     m->NetworkChanged = m->timenow;
12103                 }
12104             }
12105 #endif
12106             if (question->WakeOnResolve)
12107             {
12108                 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c);
12109                 mDNS_PurgeBeforeResolve(m, question);
12110             }
12111         }
12112     }
12113 
12114     return(mStatus_NoError);
12115 }
12116 
12117 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
12118 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
12119 {
12120     debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
12121     // This function may be called anytime to free the zone information.The question may or may not have stopped.
12122     // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
12123     // call it again
12124     if (nta->question.ThisQInterval != -1)
12125     {
12126         mDNS_StopQuery_internal(m, &nta->question);
12127         if (nta->question.ThisQInterval != -1)
12128             LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
12129     }
12130     mDNSPlatformMemFree(nta);
12131 }
12132 
12133 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
12134 {
12135     CacheGroup *cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12136     CacheRecord *cr;
12137     DNSQuestion **qp = &m->Questions;
12138 
12139     //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12140 
12141     if (LocalOnlyOrP2PInterface(question->InterfaceID))
12142         qp = &m->LocalOnlyQuestions;
12143     while (*qp && *qp != question) qp=&(*qp)->next;
12144     if (*qp) *qp = (*qp)->next;
12145     else
12146     {
12147 #if !ForceAlerts
12148         if (question->ThisQInterval >= 0)   // Only log error message if the query was supposed to be active
12149 #endif
12150         LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype));
12151         return(mStatus_BadReferenceErr);
12152     }
12153 
12154 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
12155     if (!LocalOnlyOrP2PInterface(question->InterfaceID) && mDNSOpaque16IsZero(question->TargetQID))
12156     {
12157         if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
12158             m->NextBonjourDisableTime = NonZeroTime(m->timenow + (BONJOUR_DISABLE_DELAY * mDNSPlatformOneSecond));
12159         m->NumAllInterfaceQuestions--;
12160         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
12161             "mDNS_StopQuery_internal: NumAllInterfaceRecords %u NumAllInterfaceQuestions %u " PRI_DM_NAME " (" PUB_S ")",
12162             m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, DM_NAME_PARAM(&question->qname), DNSTypeName(question->qtype));
12163     }
12164 #endif
12165 
12166 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12167     if (Question_uDNS(question) && !question->metrics.answered && (question->metrics.firstQueryTime != 0))
12168     {
12169         mDNSu32 querySendCount = question->metrics.querySendCount;
12170 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12171         if (question->querier)
12172         {
12173             querySendCount += mdns_querier_get_send_count(question->querier);
12174         }
12175 #endif
12176         if (querySendCount > 0)
12177         {
12178             const domainname *  queryName;
12179             mDNSBool            isForCell;
12180             mDNSu32             durationMs;
12181 
12182             queryName  = question->metrics.originalQName ? question->metrics.originalQName : &question->qname;
12183 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12184             isForCell = (question->dnsservice && mdns_dns_service_interface_is_cellular(question->dnsservice));
12185 #else
12186             isForCell  = (question->qDNSServer && question->qDNSServer->isCell);
12187 #endif
12188             durationMs = ((m->timenow - question->metrics.firstQueryTime) * 1000) / mDNSPlatformOneSecond;
12189             MetricsUpdateDNSQueryStats(queryName, question->qtype, mDNSNULL, querySendCount,
12190                 question->metrics.expiredAnswerState, question->metrics.dnsOverTCPState, durationMs, isForCell);
12191         }
12192     }
12193 #endif
12194     // Take care to cut question from list *before* calling UpdateQuestionDuplicates
12195     UpdateQuestionDuplicates(m, question);
12196     // But don't trash ThisQInterval until afterwards.
12197     question->ThisQInterval = -1;
12198 
12199     // If there are any cache records referencing this as their active question, then see if there is any
12200     // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
12201     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
12202     {
12203         if (cr->CRActiveQuestion == question)
12204         {
12205             DNSQuestion *q;
12206             DNSQuestion *replacement = mDNSNULL;
12207             // If we find an active question that is answered by this cached record, use it as the cache record's
12208             // CRActiveQuestion replacement. If there are no such questions, but there's at least one unsuppressed inactive
12209             // question that is answered by this cache record, then use an inactive one to not forgo generating RMV events
12210             // via CacheRecordRmv() when the cache record expires.
12211             for (q = m->Questions; q && (q != m->NewQuestions); q = q->next)
12212             {
12213                 if (!q->DuplicateOf && !q->Suppressed && CacheRecordAnswersQuestion(cr, q))
12214                 {
12215                     if (q->ThisQInterval > 0)
12216                     {
12217                         replacement = q;
12218                         break;
12219                     }
12220                     else if (!replacement)
12221                     {
12222                         replacement = q;
12223                     }
12224                 }
12225             }
12226             if (replacement)
12227                 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
12228                        "CurrentAnswers %d, Suppressed %d", replacement, CRDisplayString(m,cr), question->CurrentAnswers, replacement->CurrentAnswers, replacement->Suppressed);
12229             cr->CRActiveQuestion = replacement;    // Question used to be active; new value may or may not be null
12230             if (!replacement) m->rrcache_active--; // If no longer active, decrement rrcache_active count
12231         }
12232     }
12233 
12234     // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
12235     // bump its pointer forward one question.
12236     if (m->CurrentQuestion == question)
12237     {
12238         debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
12239                question->qname.c, DNSTypeName(question->qtype));
12240         m->CurrentQuestion = question->next;
12241     }
12242 
12243     if (m->NewQuestions == question)
12244     {
12245         debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
12246                question->qname.c, DNSTypeName(question->qtype));
12247         m->NewQuestions = question->next;
12248     }
12249 
12250     if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
12251 
12252     if (m->RestartQuestion == question)
12253     {
12254         LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
12255                question->qname.c, DNSTypeName(question->qtype));
12256         m->RestartQuestion = question->next;
12257     }
12258 
12259     // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
12260     question->next = mDNSNULL;
12261 
12262     // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
12263 
12264     // And finally, cancel any associated GetZoneData operation that's still running.
12265     // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
12266     // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
12267     // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
12268     // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
12269     if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
12270     if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
12271 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
12272     Querier_HandleStoppedDNSQuestion(question);
12273 #endif
12274     if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
12275     {
12276         // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
12277         DNSQuestion *q;
12278         for (q = m->Questions; q; q=q->next)
12279             if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
12280         if (!q)
12281         {
12282             if (!m->LLQNAT.clientCallback)       // Should never happen, but just in case...
12283             {
12284                 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
12285             }
12286             else
12287             {
12288                 LogInfo("Stopping LLQNAT");
12289                 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
12290                 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running
12291             }
12292         }
12293 
12294         // If necessary, tell server it can delete this LLQ state
12295         if (question->state == LLQ_Established)
12296         {
12297             question->ReqLease = 0;
12298             sendLLQRefresh(m, question);
12299             // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
12300             // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
12301             // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
12302             // we let that run out its natural course and complete asynchronously.
12303             if (question->tcp)
12304             {
12305                 question->tcp->question = mDNSNULL;
12306                 question->tcp           = mDNSNULL;
12307             }
12308         }
12309 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
12310         else if (question->dnsPushServer != mDNSNULL)
12311         {
12312             UnSubscribeToDNSPushNotificationServer(m, question);
12313         }
12314 #endif
12315     }
12316     // wait until we send the refresh above which needs the nta
12317     if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
12318 
12319 #if MDNSRESPONDER_SUPPORTS(APPLE, METRICS)
12320     uDNSMetricsClear(&question->metrics);
12321 #endif
12322 
12323 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
12324     DNS64ResetState(question);
12325 #endif
12326 
12327     return(mStatus_NoError);
12328 }
12329 
12330 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
12331 {
12332     mStatus status;
12333     mDNS_Lock(m);
12334     status = mDNS_StartQuery_internal(m, question);
12335     mDNS_Unlock(m);
12336     return(status);
12337 }
12338 
12339 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
12340 {
12341     mStatus status;
12342     mDNS_Lock(m);
12343     status = mDNS_StopQuery_internal(m, question);
12344     mDNS_Unlock(m);
12345     return(status);
12346 }
12347 
12348 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
12349 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12350 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12351 // specifically to catch and report if the client callback does try to make API calls
12352 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
12353 {
12354     mStatus status;
12355     DNSQuestion *qq;
12356     mDNS_Lock(m);
12357 
12358     // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12359     for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
12360 
12361     status = mDNS_StopQuery_internal(m, question);
12362     if (status == mStatus_NoError && !qq)
12363     {
12364         const CacheRecord *cr;
12365         CacheGroup *const cg = CacheGroupForName(m, question->qnamehash, &question->qname);
12366         LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12367         for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
12368         {
12369             if (cr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameCacheRecordAnswersQuestion(cr, question))
12370             {
12371                 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12372                 if (question->QuestionCallback)
12373                     question->QuestionCallback(m, question, &cr->resrec, QC_rmv);
12374             }
12375         }
12376     }
12377     mDNS_Unlock(m);
12378     return(status);
12379 }
12380 
12381 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
12382 {
12383     mStatus status;
12384     mDNS_Lock(m);
12385     status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12386     if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12387     mDNS_Unlock(m);
12388     return(status);
12389 }
12390 
12391 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
12392 {
12393     mStatus status = mStatus_BadReferenceErr;
12394     CacheRecord *cr;
12395     mDNS_Lock(m);
12396     cr = FindIdenticalRecordInCache(m, rr);
12397     debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
12398     if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12399     if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, cr->resrec.InterfaceID, 0);
12400     mDNS_Unlock(m);
12401     return(status);
12402 }
12403 
12404 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
12405                                             const domainname *const srv, const domainname *const domain,
12406                                             const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12407                                             mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12408                                             mDNSQuestionCallback *Callback, void *Context)
12409 {
12410     question->InterfaceID      = InterfaceID;
12411     question->flags            = flags;
12412     question->qtype            = kDNSType_PTR;
12413     question->qclass           = kDNSClass_IN;
12414     question->LongLived        = mDNStrue;
12415     question->ExpectUnique     = mDNSfalse;
12416     question->ForceMCast       = ForceMCast;
12417     question->ReturnIntermed   = (flags & kDNSServiceFlagsReturnIntermediates) != 0;
12418     question->SuppressUnusable = mDNSfalse;
12419     question->AppendSearchDomains = mDNSfalse;
12420     question->TimeoutQuestion  = 0;
12421     question->WakeOnResolve    = 0;
12422     question->UseBackgroundTraffic = useBackgroundTrafficClass;
12423     question->ProxyQuestion    = 0;
12424     question->QuestionCallback = Callback;
12425     question->QuestionContext  = Context;
12426 
12427     if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain))
12428         return(mStatus_BadParamErr);
12429 
12430     return(mDNS_StartQuery_internal(m, question));
12431 }
12432 
12433 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
12434                                     const domainname *const srv, const domainname *const domain,
12435                                     const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12436                                     mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12437                                     mDNSQuestionCallback *Callback, void *Context)
12438 {
12439     mStatus status;
12440     mDNS_Lock(m);
12441     status = mDNS_StartBrowse_internal(m, question, srv, domain, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
12442     mDNS_Unlock(m);
12443     return(status);
12444 }
12445 
12446 
12447 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
12448                                    const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
12449 {
12450     question->InterfaceID      = InterfaceID;
12451     question->flags            = 0;
12452     question->qtype            = kDNSType_PTR;
12453     question->qclass           = kDNSClass_IN;
12454     question->LongLived        = mDNSfalse;
12455     question->ExpectUnique     = mDNSfalse;
12456     question->ForceMCast       = mDNSfalse;
12457     question->ReturnIntermed   = mDNSfalse;
12458     question->SuppressUnusable = mDNSfalse;
12459     question->AppendSearchDomains = mDNSfalse;
12460     question->TimeoutQuestion  = 0;
12461     question->WakeOnResolve    = 0;
12462     question->UseBackgroundTraffic = mDNSfalse;
12463     question->ProxyQuestion    = 0;
12464     question->pid              = mDNSPlatformGetPID();
12465     question->euid             = 0;
12466     question->QuestionCallback = Callback;
12467     question->QuestionContext  = Context;
12468     if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
12469     if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
12470     if (!dom) dom = &localdomain;
12471     if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
12472     return(mDNS_StartQuery(m, question));
12473 }
12474 
12475 // ***************************************************************************
12476 #if COMPILER_LIKES_PRAGMA_MARK
12477 #pragma mark -
12478 #pragma mark - Responder Functions
12479 #endif
12480 
12481 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
12482 {
12483     mStatus status;
12484     mDNS_Lock(m);
12485     status = mDNS_Register_internal(m, rr);
12486     mDNS_Unlock(m);
12487     return(status);
12488 }
12489 
12490 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
12491                                const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
12492 {
12493     if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
12494     {
12495         LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
12496         return(mStatus_Invalid);
12497     }
12498 
12499     mDNS_Lock(m);
12500 
12501     // If TTL is unspecified, leave TTL unchanged
12502     if (newttl == 0) newttl = rr->resrec.rroriginalttl;
12503 
12504     // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12505     if (rr->NewRData)
12506     {
12507         RData *n = rr->NewRData;
12508         rr->NewRData = mDNSNULL;                            // Clear the NewRData pointer ...
12509         if (rr->UpdateCallback)
12510             rr->UpdateCallback(m, rr, n, rr->newrdlength);  // ...and let the client free this memory, if necessary
12511     }
12512 
12513     rr->NewRData             = newrdata;
12514     rr->newrdlength          = newrdlength;
12515     rr->UpdateCallback       = Callback;
12516 
12517 #ifndef UNICAST_DISABLED
12518     if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
12519     {
12520         mStatus status = uDNS_UpdateRecord(m, rr);
12521         // The caller frees the memory on error, don't retain stale pointers
12522         if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
12523         mDNS_Unlock(m);
12524         return(status);
12525     }
12526 #endif
12527 
12528     if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
12529                             rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
12530         CompleteRDataUpdate(m, rr);
12531     else
12532     {
12533         rr->AnnounceCount = InitialAnnounceCount;
12534         InitializeLastAPTime(m, rr);
12535         while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
12536         if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
12537         if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
12538         if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
12539         if (rr->UpdateCredits <= 5)
12540         {
12541             mDNSu32 delay = 6 - rr->UpdateCredits;      // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12542             if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
12543             rr->ThisAPInterval *= 4;
12544             rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
12545             LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12546                    rr->resrec.name->c, delay, delay > 1 ? "s" : "");
12547         }
12548         rr->resrec.rroriginalttl = newttl;
12549     }
12550 
12551     mDNS_Unlock(m);
12552     return(mStatus_NoError);
12553 }
12554 
12555 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12556 // the record list and/or question list.
12557 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12558 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
12559 {
12560     mStatus status;
12561     mDNS_Lock(m);
12562     status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
12563     mDNS_Unlock(m);
12564     return(status);
12565 }
12566 
12567 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12568 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
12569 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12570 mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *m, AuthRecord *rr, mStatus result);
12571 #endif
12572 
12573 mDNSlocal AuthRecord *GetInterfaceAddressRecord(NetworkInterfaceInfo *intf, mDNSBool forRandHostname)
12574 {
12575 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12576         return(forRandHostname ? &intf->RR_AddrRand : &intf->RR_A);
12577 #else
12578         (void)forRandHostname; // Unused.
12579         return(&intf->RR_A);
12580 #endif
12581 }
12582 
12583 mDNSlocal AuthRecord *GetFirstAddressRecordEx(const mDNS *const m, const mDNSBool forRandHostname)
12584 {
12585     NetworkInterfaceInfo *intf;
12586     for (intf = m->HostInterfaces; intf; intf = intf->next)
12587     {
12588         if (!intf->Advertise) continue;
12589 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12590         if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue;
12591 #endif
12592         return(GetInterfaceAddressRecord(intf, forRandHostname));
12593     }
12594     return(mDNSNULL);
12595 }
12596 #define GetFirstAddressRecord(M)    GetFirstAddressRecordEx(M, mDNSfalse)
12597 
12598 // The parameter "set" here refers to the set of AuthRecords used to advertise this interface.
12599 // (It's a set of records, not a set of interfaces.)
12600 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12601 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool useRandomizedHostname)
12602 #else
12603 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12604 #endif
12605 {
12606     const domainname *hostname;
12607     mDNSRecordCallback *hostnameCallback;
12608     AuthRecord *addrAR;
12609     AuthRecord *ptrAR;
12610 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12611     const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID);
12612 #endif
12613     mDNSu8 addrRecordType;
12614     char buffer[MAX_REVERSE_MAPPING_NAME];
12615 
12616 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12617     if (interfaceIsAWDL || useRandomizedHostname)
12618     {
12619         hostname         = &m->RandomizedHostname;
12620         hostnameCallback = mDNS_RandomizedHostNameCallback;
12621     }
12622     else
12623 #endif
12624     {
12625         hostname         = &m->MulticastHostname;
12626         hostnameCallback = mDNS_HostNameCallback;
12627     }
12628 
12629 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12630     if (!interfaceIsAWDL && useRandomizedHostname)
12631     {
12632         addrAR = &set->RR_AddrRand;
12633         ptrAR  = mDNSNULL;
12634     }
12635     else
12636 #endif
12637     {
12638         addrAR = &set->RR_A;
12639         ptrAR  = &set->RR_PTR;
12640     }
12641     if (addrAR->resrec.RecordType != kDNSRecordTypeUnregistered) return;
12642 
12643     addrRecordType = set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
12644 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12645     if (hostname == &m->RandomizedHostname) addrRecordType = kDNSRecordTypeKnownUnique;
12646     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12647         "AdvertiseInterface: Advertising " PUB_S " hostname on interface " PUB_S,
12648         (hostname == &m->RandomizedHostname) ? "randomized" : "normal", set->ifname);
12649 #else
12650     LogInfo("AdvertiseInterface: Advertising for ifname %s", set->ifname);
12651 #endif
12652 
12653     // Send dynamic update for non-linklocal IPv4 Addresses
12654     mDNS_SetupResourceRecord(addrAR, mDNSNULL, set->InterfaceID, kDNSType_A, kHostNameTTL, addrRecordType, AuthRecordAny, hostnameCallback, set);
12655     if (ptrAR) mDNS_SetupResourceRecord(ptrAR, mDNSNULL, set->InterfaceID, kDNSType_PTR, kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12656 
12657 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12658     addrAR->AllowRemoteQuery = mDNStrue;
12659     if (ptrAR) ptrAR->AllowRemoteQuery = mDNStrue;
12660 #endif
12661     // 1. Set up Address record to map from host name ("foo.local.") to IP address
12662     // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12663     AssignDomainName(&addrAR->namestorage, hostname);
12664     if (set->ip.type == mDNSAddrType_IPv4)
12665     {
12666         addrAR->resrec.rrtype        = kDNSType_A;
12667         addrAR->resrec.rdata->u.ipv4 = set->ip.ip.v4;
12668         // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12669         mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
12670                       set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
12671     }
12672     else if (set->ip.type == mDNSAddrType_IPv6)
12673     {
12674         int i;
12675         addrAR->resrec.rrtype        = kDNSType_AAAA;
12676         addrAR->resrec.rdata->u.ipv6 = set->ip.ip.v6;
12677         for (i = 0; i < 16; i++)
12678         {
12679             static const char hexValues[] = "0123456789ABCDEF";
12680             buffer[i * 4    ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
12681             buffer[i * 4 + 1] = '.';
12682             buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
12683             buffer[i * 4 + 3] = '.';
12684         }
12685         mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
12686     }
12687 
12688     if (ptrAR)
12689     {
12690         MakeDomainNameFromDNSNameString(&ptrAR->namestorage, buffer);
12691         ptrAR->AutoTarget = Target_AutoHost;    // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12692         ptrAR->ForceMCast = mDNStrue;           // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12693     }
12694 
12695 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12696     addrAR->RRSet = interfaceIsAWDL ? addrAR : GetFirstAddressRecordEx(m, useRandomizedHostname);
12697 #else
12698     addrAR->RRSet = GetFirstAddressRecord(m);
12699 #endif
12700     if (!addrAR->RRSet) addrAR->RRSet = addrAR;
12701     mDNS_Register_internal(m, addrAR);
12702     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Initialized RRSet for " PRI_S, ARDisplayString(m, addrAR));
12703     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "RRSet:                " PRI_S, ARDisplayString(m, addrAR->RRSet));
12704     if (ptrAR) mDNS_Register_internal(m, ptrAR);
12705 
12706 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12707     // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12708     D2D_start_advertising_interface(set);
12709 #endif
12710 }
12711 
12712 mDNSlocal void AdvertiseInterfaceIfNeeded(mDNS *const m, NetworkInterfaceInfo *set)
12713 {
12714 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12715     if (mDNSPlatformInterfaceIsAWDL(set->InterfaceID))
12716     {
12717         if ((m->AutoTargetAWDLIncludedCount > 0) || (m->AutoTargetAWDLOnlyCount > 0))
12718         {
12719             AdvertiseInterface(m, set, mDNSfalse);
12720         }
12721     }
12722     else
12723     {
12724         if (m->AutoTargetServices          > 0) AdvertiseInterface(m, set, mDNSfalse);
12725         if (m->AutoTargetAWDLIncludedCount > 0) AdvertiseInterface(m, set, mDNStrue);
12726     }
12727 #else
12728     if (m->AutoTargetServices > 0) AdvertiseInterface(m, set);
12729 #endif
12730 }
12731 
12732 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, DeadvertiseFlags flags)
12733 {
12734 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12735     const mDNSBool interfaceIsAWDL = mDNSPlatformInterfaceIsAWDL(set->InterfaceID);
12736 #endif
12737 
12738     // Unregister these records.
12739     // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12740     // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12741     // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12742     // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12743 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12744     if ((!interfaceIsAWDL && (flags & kDeadvertiseFlag_NormalHostname)) ||
12745         ( interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname)))
12746 #else
12747     if (flags & kDeadvertiseFlag_NormalHostname)
12748 #endif
12749     {
12750         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12751             "DeadvertiseInterface: Deadvertising " PUB_S " hostname on interface " PUB_S,
12752             (flags & kDeadvertiseFlag_RandHostname) ? "randomized" : "normal", set->ifname);
12753 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12754         D2D_stop_advertising_interface(set);
12755 #endif
12756         if (set->RR_A.resrec.RecordType)   mDNS_Deregister_internal(m, &set->RR_A,   mDNS_Dereg_normal);
12757         if (set->RR_PTR.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR, mDNS_Dereg_normal);
12758     }
12759 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12760     if (!interfaceIsAWDL && (flags & kDeadvertiseFlag_RandHostname))
12761     {
12762         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
12763             "DeadvertiseInterface: Deadvertising randomized hostname on interface " PUB_S, set->ifname);
12764         AuthRecord *const ar = &set->RR_AddrRand;
12765         if (ar->resrec.RecordType) mDNS_Deregister_internal(m, ar, mDNS_Dereg_normal);
12766     }
12767 #endif
12768 }
12769 
12770 // Change target host name for record.
12771 mDNSlocal void UpdateTargetHostName(mDNS *const m, AuthRecord *const rr)
12772 {
12773 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12774     // If this record was also registered with any D2D plugins, stop advertising
12775     // the version with the old host name.
12776     D2D_stop_advertising_record(rr);
12777 #endif
12778 
12779     SetTargetToHostName(m, rr);
12780 
12781 #if MDNSRESPONDER_SUPPORTS(APPLE, D2D)
12782     // Advertise the record with the updated host name with the D2D plugins if appropriate.
12783     D2D_start_advertising_record(rr);
12784 #endif
12785 }
12786 
12787 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m, DeadvertiseFlags flags)
12788 {
12789     NetworkInterfaceInfo *intf;
12790     for (intf = m->HostInterfaces; intf; intf = intf->next)
12791     {
12792         if (intf->Advertise) DeadvertiseInterface(m, intf, flags);
12793     }
12794 }
12795 
12796 mDNSexport void mDNS_SetFQDN(mDNS *const m)
12797 {
12798     domainname newmname;
12799     AuthRecord *rr;
12800     newmname.c[0] = 0;
12801 
12802     if (!AppendDomainLabel(&newmname, &m->hostlabel))  { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12803     if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12804 
12805     mDNS_Lock(m);
12806 
12807     if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
12808     else
12809     {
12810         AssignDomainName(&m->MulticastHostname, &newmname);
12811         DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_NormalHostname);
12812         AdvertiseNecessaryInterfaceRecords(m);
12813     }
12814 
12815     // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12816     for (rr = m->ResourceRecords;  rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12817     for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) UpdateTargetHostName(m, rr);
12818 
12819     mDNS_Unlock(m);
12820 }
12821 
12822 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
12823 {
12824     (void)rr;   // Unused parameter
12825 
12826     #if MDNS_DEBUGMSGS
12827     {
12828         char *msg = "Unknown result";
12829         if      (result == mStatus_NoError) msg = "Name registered";
12830         else if (result == mStatus_NameConflict) msg = "Name conflict";
12831         debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
12832     }
12833     #endif
12834 
12835     if (result == mStatus_NoError)
12836     {
12837         // Notify the client that the host name is successfully registered
12838         if (m->MainCallback)
12839             m->MainCallback(m, mStatus_NoError);
12840     }
12841     else if (result == mStatus_NameConflict)
12842     {
12843         domainlabel oldlabel = m->hostlabel;
12844 
12845         // 1. First give the client callback a chance to pick a new name
12846         if (m->MainCallback)
12847             m->MainCallback(m, mStatus_NameConflict);
12848 
12849         // 2. If the client callback didn't do it, add (or increment) an index ourselves
12850         // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12851         // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12852         if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
12853             IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
12854 
12855         // 3. Generate the FQDNs from the hostlabel,
12856         // and make sure all SRV records, etc., are updated to reference our new hostname
12857         mDNS_SetFQDN(m);
12858         LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
12859     }
12860     else if (result == mStatus_MemFree)
12861     {
12862         // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12863         // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12864         debugf("mDNS_HostNameCallback: MemFree (ignored)");
12865     }
12866     else
12867         LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result,  rr->resrec.name->c);
12868 }
12869 
12870 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
12871 mDNSlocal void mDNS_RandomizedHostNameCallback(mDNS *const m, AuthRecord *const addrRecord, const mStatus result)
12872 {
12873     (void)addrRecord;   // Unused parameter
12874 
12875     if (result == mStatus_NameConflict)
12876     {
12877         AuthRecord *rr;
12878         domainlabel newUUIDLabel;
12879 
12880         GetRandomUUIDLabel(&newUUIDLabel);
12881         if (SameDomainLabel(newUUIDLabel.c, m->RandomizedHostname.c))
12882         {
12883             IncrementLabelSuffix(&newUUIDLabel, mDNSfalse);
12884         }
12885 
12886         mDNS_Lock(m);
12887 
12888         m->RandomizedHostname.c[0] = 0;
12889         AppendDomainLabel(&m->RandomizedHostname, &newUUIDLabel);
12890         AppendLiteralLabelString(&m->RandomizedHostname, "local");
12891 
12892         DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_RandHostname);
12893         AdvertiseNecessaryInterfaceRecords(m);
12894         for (rr = m->ResourceRecords; rr; rr = rr->next)
12895         {
12896             if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr);
12897         }
12898         for (rr = m->DuplicateRecords; rr; rr = rr->next)
12899         {
12900             if (rr->AutoTarget && AuthRecordIncludesOrIsAWDL(rr)) UpdateTargetHostName(m, rr);
12901         }
12902 
12903         mDNS_Unlock(m);
12904     }
12905 }
12906 #endif
12907 
12908 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
12909 {
12910     NetworkInterfaceInfo *intf;
12911     active->IPv4Available = mDNSfalse;
12912     active->IPv6Available = mDNSfalse;
12913     for (intf = m->HostInterfaces; intf; intf = intf->next)
12914         if (intf->InterfaceID == active->InterfaceID)
12915         {
12916             if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
12917             if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
12918         }
12919 }
12920 
12921 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
12922 {
12923     AuthRecord *rr;
12924     LogInfo("RestartRecordGetZoneData: ResourceRecords");
12925     for (rr = m->ResourceRecords; rr; rr=rr->next)
12926         if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
12927         {
12928             debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
12929             // Zero out the updateid so that if we have a pending response from the server, it won't
12930             // be accepted as a valid response. If we accept the response, we might free the new "nta"
12931             if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
12932             rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
12933         }
12934 }
12935 
12936 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
12937 {
12938     int i;
12939     // We initialize ThisQInterval to -1 indicating that the question has not been started
12940     // yet. If the question (browse) is started later during interface registration, it will
12941     // be stopped during interface deregistration. We can't sanity check to see if the
12942     // question has been stopped or not before initializing it to -1 because we need to
12943     // initialize it to -1 the very first time.
12944 
12945     set->NetWakeBrowse.ThisQInterval = -1;
12946     for (i=0; i<3; i++)
12947     {
12948         set->NetWakeResolve[i].ThisQInterval = -1;
12949         set->SPSAddr[i].type = mDNSAddrType_None;
12950     }
12951     set->NextSPSAttempt     = -1;
12952     set->NextSPSAttemptTime = m->timenow;
12953 }
12954 
12955 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12956 {
12957     NetworkInterfaceInfo *p = m->HostInterfaces;
12958     while (p && p != set) p=p->next;
12959     if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12960 
12961     if (set->InterfaceActive)
12962     {
12963         LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
12964         mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
12965     }
12966 }
12967 
12968 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12969 {
12970     NetworkInterfaceInfo *p = m->HostInterfaces;
12971     while (p && p != set) p=p->next;
12972     if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12973 
12974     // Note: We start the browse only if the interface is NetWake capable and we use this to
12975     // stop the resolves also. Hence, the resolves should not be started without the browse
12976     // being started i.e, resolves should not happen unless NetWake capable which is
12977     // guaranteed by BeginSleepProcessing.
12978     if (set->NetWakeBrowse.ThisQInterval >= 0)
12979     {
12980         int i;
12981         LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
12982 
12983         // Stop our browse and resolve operations
12984         mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
12985         for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
12986 
12987         // Make special call to the browse callback to let it know it can to remove all records for this interface
12988         if (m->SPSBrowseCallback)
12989         {
12990             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
12991             m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, QC_rmv);
12992             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
12993         }
12994 
12995         // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12996         // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12997         InitializeNetWakeState(m, set);
12998     }
12999 }
13000 
13001 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13002 {
13003     AuthRecord *rr;
13004     mDNSBool FirstOfType = mDNStrue;
13005     NetworkInterfaceInfo **p = &m->HostInterfaces;
13006 
13007     if (!set->InterfaceID)
13008     {
13009         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13010             "Tried to register a NetworkInterfaceInfo with zero InterfaceID - ifaddr: " PRI_IP_ADDR, &set->ip);
13011         return(mStatus_Invalid);
13012     }
13013 
13014     if (!mDNSAddressIsValidNonZero(&set->mask))
13015     {
13016         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13017             "Tried to register a NetworkInterfaceInfo with invalid mask - ifaddr: " PRI_IP_ADDR ", ifmask: " PUB_IP_ADDR,
13018             &set->ip, &set->mask);
13019         return(mStatus_Invalid);
13020     }
13021 
13022     mDNS_Lock(m);
13023 
13024     // Assume this interface will be active now, unless we find a duplicate already in the list
13025     set->InterfaceActive = mDNStrue;
13026     set->IPv4Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
13027     set->IPv6Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
13028 
13029     InitializeNetWakeState(m, set);
13030 
13031     // Scan list to see if this InterfaceID is already represented
13032     while (*p)
13033     {
13034         if (*p == set)
13035         {
13036             LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13037                 "Tried to register a NetworkInterfaceInfo that's already in the list - "
13038                 "ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip);
13039             mDNS_Unlock(m);
13040             return(mStatus_AlreadyRegistered);
13041         }
13042 
13043         if ((*p)->InterfaceID == set->InterfaceID)
13044         {
13045             // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
13046             set->InterfaceActive = mDNSfalse;
13047             if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
13048             if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
13049             if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
13050         }
13051 
13052         p=&(*p)->next;
13053     }
13054 
13055     set->next = mDNSNULL;
13056     *p = set;
13057 
13058     if (set->Advertise) AdvertiseInterfaceIfNeeded(m, set);
13059 
13060     if (set->InterfaceActive)
13061     {
13062         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13063             "Interface not represented in list; marking active and retriggering queries - "
13064             "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13065     }
13066     else
13067     {
13068         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13069             "Interface already represented in list - "
13070             "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13071     }
13072 
13073     if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
13074 
13075     // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13076     // giving the false impression that there's an active representative of this interface when there really isn't.
13077     // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
13078     // even if we believe that we previously had an active representative of this interface.
13079     if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
13080     {
13081         DNSQuestion *q;
13082         // Normally, after an interface comes up, we pause half a second before beginning probing.
13083         // This is to guard against cases where there's rapid interface changes, where we could be confused by
13084         // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
13085         // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
13086         // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
13087         // and think it's a conflicting answer to our probe.
13088         // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
13089         mDNSs32 probedelay;
13090         mDNSu8 numannounce;
13091         switch (activationSpeed)
13092         {
13093             case FastActivation:
13094                 probedelay = (mDNSs32)0;
13095                 numannounce = InitialAnnounceCount;
13096                 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13097                     "Using fast activation for DirectLink interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13098                     set->ifname, &set->ip);
13099                 break;
13100 
13101 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13102             case SlowActivation:
13103                 probedelay = mDNSPlatformOneSecond * 5;
13104                 numannounce = (mDNSu8)1;
13105                 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13106                     "Frequent transitions for interface, doing slow activation - "
13107                     "ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR, set->ifname, &set->ip);
13108                 m->mDNSStats.InterfaceUpFlap++;
13109                 break;
13110 #endif
13111 
13112             case NormalActivation:
13113             default:
13114                 probedelay = mDNSPlatformOneSecond / 2;
13115                 numannounce = InitialAnnounceCount;
13116                 break;
13117         }
13118 
13119         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13120             "Interface probe will be delayed - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR ", probe delay: %d",
13121             set->ifname, &set->ip, probedelay);
13122 
13123         // No probe or sending suppression on DirectLink type interfaces.
13124         if (activationSpeed == FastActivation)
13125         {
13126             m->SuppressSending = 0;
13127             m->SuppressProbes = 0;
13128         }
13129         else
13130         {
13131 	        // Use a small amount of randomness:
13132 	        // In the case of a network administrator turning on an Ethernet hub so that all the
13133 	        // connected machines establish link at exactly the same time, we don't want them all
13134 	        // to go and hit the network with identical queries at exactly the same moment.
13135 	        // We set a random delay of up to InitialQuestionInterval (1/3 second).
13136 	        // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
13137 	        // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
13138 	        // suppressing packet sending for more than about 1/3 second can cause protocol correctness
13139 	        // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
13140 	        // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
13141             if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
13142 
13143             if (m->SuppressProbes == 0 ||
13144                 m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
13145                 m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
13146         }
13147 
13148         // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
13149         // it here also handles the wake up case as the network link comes UP after waking causing
13150         // us to reconnect to the network. If we do this as part of the wake up code, it is possible
13151         // that the network link comes UP after 60 seconds and we never set the OWNER option
13152         m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
13153         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "Setting AnnounceOwner");
13154 
13155         m->mDNSStats.InterfaceUp++;
13156         for (q = m->Questions; q; q=q->next)                                // Scan our list of questions
13157         {
13158             if (mDNSOpaque16IsZero(q->TargetQID))
13159             {
13160                 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)      // If non-specific Q, or Q on this specific interface,
13161                 {                                                               // then reactivate this question
13162 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13163                     // If flapping, delay between first and second queries is nine seconds instead of one second
13164                     mDNSBool dodelay = (activationSpeed == SlowActivation) && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
13165                     mDNSs32 initial  = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
13166                     mDNSs32 qdelay   = dodelay ? kDefaultQueryDelayTimeForFlappingInterface : 0;
13167                     if (dodelay)
13168                     {
13169                         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13170                             "No cache records expired for the question " PRI_DM_NAME " (" PUB_S ");"
13171                             " delaying it by %d seconds", DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), qdelay);
13172                     }
13173 #else
13174                     mDNSs32 initial  = InitialQuestionInterval;
13175                     mDNSs32 qdelay   = 0;
13176 #endif
13177 
13178                     if (!q->ThisQInterval || q->ThisQInterval > initial)
13179                     {
13180                         q->ThisQInterval  = initial;
13181                         q->RequestUnicast = kDefaultRequestUnicastCount;
13182                     }
13183                     q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
13184                     q->RecentAnswerPkts = 0;
13185                     SetNextQueryTime(m,q);
13186                 }
13187             }
13188         }
13189 
13190         // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
13191         // we now need them to re-probe if necessary, and then re-announce.
13192         for (rr = m->ResourceRecords; rr; rr=rr->next)
13193         {
13194             if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
13195             {
13196                 mDNSCoreRestartRegistration(m, rr, numannounce);
13197             }
13198         }
13199     }
13200 
13201     RestartRecordGetZoneData(m);
13202 
13203     mDNS_UpdateAllowSleep(m);
13204 
13205     mDNS_Unlock(m);
13206     return(mStatus_NoError);
13207 }
13208 
13209 mDNSlocal void AdjustAddressRecordSetsEx(mDNS *const m, NetworkInterfaceInfo *removedIntf, mDNSBool forRandHostname)
13210 {
13211     NetworkInterfaceInfo *intf;
13212     const AuthRecord *oldAR;
13213     AuthRecord *newAR;
13214 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13215     if (mDNSPlatformInterfaceIsAWDL(removedIntf->InterfaceID)) return;
13216 #endif
13217     oldAR = GetInterfaceAddressRecord(removedIntf, forRandHostname);
13218     newAR = GetFirstAddressRecordEx(m, forRandHostname);
13219     for (intf = m->HostInterfaces; intf; intf = intf->next)
13220     {
13221         AuthRecord *ar;
13222 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13223         if (mDNSPlatformInterfaceIsAWDL(intf->InterfaceID)) continue;
13224 #endif
13225         ar = GetInterfaceAddressRecord(intf, forRandHostname);
13226         if (ar->RRSet == oldAR)
13227         {
13228             ar->RRSet = newAR ? newAR : ar;
13229             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "Changed RRSet for " PRI_S, ARDisplayString(m, ar));
13230             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG, "New RRSet:        " PRI_S, ARDisplayString(m, ar->RRSet));
13231         }
13232     }
13233 }
13234 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13235 #define AdjustAddressRecordSetsForRandHostname(M, REMOVED_INTF) AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNStrue)
13236 #endif
13237 #define AdjustAddressRecordSets(M, REMOVED_INTF)                AdjustAddressRecordSetsEx(M, REMOVED_INTF, mDNSfalse)
13238 
13239 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13240 // the record list and/or question list.
13241 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13242 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, InterfaceActivationSpeed activationSpeed)
13243 {
13244 #if !MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13245     (void)activationSpeed;   // Unused parameter
13246 #endif
13247     NetworkInterfaceInfo **p = &m->HostInterfaces;
13248     mDNSBool revalidate = mDNSfalse;
13249     NetworkInterfaceInfo *intf;
13250 
13251     mDNS_Lock(m);
13252 
13253     // Find this record in our list
13254     while (*p && *p != set) p=&(*p)->next;
13255     if (!*p)
13256     {
13257         LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEBUG, "NetworkInterfaceInfo not found in list");
13258         mDNS_Unlock(m);
13259         return;
13260     }
13261 
13262     mDNS_DeactivateNetWake_internal(m, set);
13263 
13264     // Unlink this record from our list
13265     *p = (*p)->next;
13266     set->next = mDNSNULL;
13267 
13268     if (!set->InterfaceActive)
13269     {
13270         // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13271         for (intf = m->HostInterfaces; intf; intf = intf->next)
13272             if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
13273                 UpdateInterfaceProtocols(m, intf);
13274     }
13275     else
13276     {
13277         intf = FirstInterfaceForID(m, set->InterfaceID);
13278         if (intf)
13279         {
13280             LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13281                 "Another representative of InterfaceID exists - ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13282                 IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13283             if (intf->InterfaceActive)
13284             {
13285                 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_ERROR,
13286                     "intf->InterfaceActive already set for interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13287                     set->ifname, &set->ip);
13288             }
13289             intf->InterfaceActive = mDNStrue;
13290             UpdateInterfaceProtocols(m, intf);
13291 
13292             if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
13293 
13294             // See if another representative *of the same type* exists. If not, we mave have gone from
13295             // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13296             for (intf = m->HostInterfaces; intf; intf = intf->next)
13297                 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
13298                     break;
13299             if (!intf) revalidate = mDNStrue;
13300         }
13301         else
13302         {
13303             mDNSu32 slot;
13304             CacheGroup *cg;
13305             CacheRecord *rr;
13306             DNSQuestion *q;
13307 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13308             mDNSu32     cacheHitMulticastCount = 0;
13309             mDNSu32     cacheMissMulticastCount = 0;
13310             mDNSu32     cacheHitUnicastCount = 0;
13311             mDNSu32     cacheMissUnicastCount = 0;
13312 #endif
13313             LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_INFO,
13314                 "Last representative of InterfaceID deregistered; marking questions etc. dormant - "
13315                 "ifid: %d, ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13316                 IIDPrintable(set->InterfaceID), set->ifname, &set->ip);
13317 
13318             m->mDNSStats.InterfaceDown++;
13319 
13320 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13321             if (set->McastTxRx && (activationSpeed == SlowActivation))
13322             {
13323                 LogRedact(MDNS_LOG_CATEGORY_MDNS, MDNS_LOG_DEFAULT,
13324                     "Frequent transitions for interface - ifname: " PUB_S ", ifaddr: " PRI_IP_ADDR,
13325                     set->ifname, &set->ip);
13326                 m->mDNSStats.InterfaceDownFlap++;
13327             }
13328 #endif
13329 
13330             // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13331             // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13332             for (q = m->Questions; q; q=q->next)
13333             {
13334                 if (mDNSOpaque16IsZero(q->TargetQID))                   // Only deactivate multicast quesstions. (Unicast questions are stopped when/if the associated DNS server group goes away.)
13335                 {
13336                     if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
13337                     if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
13338                     {
13339                         q->FlappingInterface2 = q->FlappingInterface1;
13340                         q->FlappingInterface1 = set->InterfaceID;       // Keep history of the last two interfaces to go away
13341                     }
13342                 }
13343             }
13344 
13345             // 2. Flush any cache records received on this interface
13346             revalidate = mDNSfalse;     // Don't revalidate if we're flushing the records
13347             FORALL_CACHERECORDS(slot, cg, rr)
13348             {
13349                 if (rr->resrec.InterfaceID == set->InterfaceID)
13350                 {
13351 #if MDNSRESPONDER_SUPPORTS(APPLE, SLOW_ACTIVATION)
13352                     // If this interface is deemed flapping,
13353                     // postpone deleting the cache records in case the interface comes back again
13354                     if (set->McastTxRx && (activationSpeed == SlowActivation))
13355                     {
13356                         // For a flapping interface we want these records to go away after
13357                         // kDefaultReconfirmTimeForFlappingInterface seconds if they are not reconfirmed.
13358                         mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13359                         // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13360                         // if the interface does come back, any relevant questions will be reactivated anyway
13361                         rr->UnansweredQueries = MaxUnansweredQueries;
13362                     }
13363                     else
13364 #endif
13365                     {
13366 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13367                         if (rr->LastCachedAnswerTime)
13368                         {
13369 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
13370                             if (rr->resrec.dnsservice)  cacheHitUnicastCount++;
13371 #else
13372                             if (rr->resrec.rDNSServer)  cacheHitUnicastCount++;
13373 #endif
13374                             else                        cacheHitMulticastCount++;
13375                         }
13376                         else
13377                         {
13378 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
13379                             if (rr->resrec.dnsservice)  cacheMissUnicastCount++;
13380 #else
13381                             if (rr->resrec.rDNSServer)  cacheMissUnicastCount++;
13382 #endif
13383                             else                        cacheMissMulticastCount++;
13384                         }
13385 #endif
13386                         mDNS_PurgeCacheResourceRecord(m, rr);
13387                     }
13388                 }
13389             }
13390 #if MDNSRESPONDER_SUPPORTS(APPLE, CACHE_ANALYTICS)
13391             dnssd_analytics_update_cache_usage_counts(cacheHitMulticastCount, cacheMissMulticastCount, cacheHitUnicastCount, cacheMissUnicastCount);
13392 #endif
13393         }
13394     }
13395 
13396     // If we still have address records referring to this one, update them.
13397     // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13398     // so the call to AdjustAddressRecordSets*() won’t accidentally find it.
13399     AdjustAddressRecordSets(m, set);
13400 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
13401     AdjustAddressRecordSetsForRandHostname(m, set);
13402 #endif
13403 
13404     // If we were advertising on this interface, deregister those address and reverse-lookup records now
13405     if (set->Advertise) DeadvertiseInterface(m, set, kDeadvertiseFlag_All);
13406 
13407     // If we have any cache records received on this interface that went away, then re-verify them.
13408     // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13409     // giving the false impression that there's an active representative of this interface when there really isn't.
13410     // Don't need to do this when shutting down, because *all* interfaces are about to go away
13411     if (revalidate && !m->ShutdownTime)
13412     {
13413         mDNSu32 slot;
13414         CacheGroup *cg;
13415         CacheRecord *rr;
13416         FORALL_CACHERECORDS(slot, cg, rr)
13417         if (rr->resrec.InterfaceID == set->InterfaceID)
13418             mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13419     }
13420 
13421     mDNS_UpdateAllowSleep(m);
13422 
13423     mDNS_Unlock(m);
13424 }
13425 
13426 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13427 {
13428     ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13429     (void)m;    // Unused parameter
13430 
13431     #if MDNS_DEBUGMSGS
13432     {
13433         char *msg = "Unknown result";
13434         if      (result == mStatus_NoError) msg = "Name Registered";
13435         else if (result == mStatus_NameConflict) msg = "Name Conflict";
13436         else if (result == mStatus_MemFree) msg = "Memory Free";
13437         debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
13438     }
13439     #endif
13440 
13441     // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13442     if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
13443 
13444     // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13445     if (result == mStatus_NameConflict)
13446     {
13447         sr->Conflict = mDNStrue;                // Record that this service set had a conflict
13448         mDNS_DeregisterService(m, sr);          // Unlink the records from our list
13449         return;
13450     }
13451 
13452     if (result == mStatus_MemFree)
13453     {
13454         // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13455         // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13456         // every record is finished cleaning up.
13457         mDNSu32 i;
13458         ExtraResourceRecord *e = sr->Extras;
13459 
13460         if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13461         if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13462         if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13463         if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13464         for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
13465 
13466         while (e)
13467         {
13468             if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13469             e = e->next;
13470         }
13471 
13472         // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13473         // then we can now report the NameConflict to the client
13474         if (sr->Conflict) result = mStatus_NameConflict;
13475 
13476     }
13477 
13478     LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
13479     // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13480     // function is allowed to do anything, including deregistering this service and freeing its memory.
13481     if (sr->ServiceCallback)
13482         sr->ServiceCallback(m, sr, result);
13483 }
13484 
13485 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13486 {
13487     ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13488     if (sr->ServiceCallback)
13489         sr->ServiceCallback(m, sr, result);
13490 }
13491 
13492 
13493 // Derive AuthRecType from the kDNSServiceFlags* values.
13494 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
13495 {
13496     AuthRecType artype;
13497 
13498     if (InterfaceID == mDNSInterface_LocalOnly)
13499         artype = AuthRecordLocalOnly;
13500     else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13501         artype = AuthRecordP2P;
13502     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P)
13503             && (flags & kDNSServiceFlagsIncludeAWDL))
13504         artype = AuthRecordAnyIncludeAWDLandP2P;
13505     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeP2P))
13506         artype = AuthRecordAnyIncludeP2P;
13507     else if ((InterfaceID == mDNSInterface_Any) && (flags & kDNSServiceFlagsIncludeAWDL))
13508         artype = AuthRecordAnyIncludeAWDL;
13509     else
13510         artype = AuthRecordAny;
13511 
13512     return artype;
13513 }
13514 
13515 // Note:
13516 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13517 // Type is service type (e.g. "_ipp._tcp.")
13518 // Domain is fully qualified domain name (i.e. ending with a null label)
13519 // We always register a TXT, even if it is empty (so that clients are not
13520 // left waiting forever looking for a nonexistent record.)
13521 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13522 // then the default host name (m->MulticastHostname) is automatically used
13523 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13524 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
13525                                         const domainlabel *const name, const domainname *const type, const domainname *const domain,
13526                                         const domainname *const host, mDNSIPPort port, RData *const txtrdata, const mDNSu8 txtinfo[], mDNSu16 txtlen,
13527                                         AuthRecord *SubTypes, mDNSu32 NumSubTypes,
13528                                         mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
13529 {
13530     mStatus err;
13531     mDNSu32 i;
13532     AuthRecType artype;
13533     mDNSu8 recordType = (flags & kDNSServiceFlagsKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
13534 
13535     sr->ServiceCallback = Callback;
13536     sr->ServiceContext  = Context;
13537     sr->Conflict        = mDNSfalse;
13538 
13539     sr->Extras          = mDNSNULL;
13540     sr->NumSubTypes     = NumSubTypes;
13541     sr->SubTypes        = SubTypes;
13542     sr->flags           = flags;
13543 
13544     artype = setAuthRecType(InterfaceID, flags);
13545 
13546     // Initialize the AuthRecord objects to sane values
13547     // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13548     mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
13549     mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared,   artype, ServiceCallback, sr);
13550 
13551     if (flags & kDNSServiceFlagsWakeOnlyService)
13552     {
13553         sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly;
13554     }
13555 
13556     mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, recordType, artype, ServiceCallback, sr);
13557     mDNS_SetupResourceRecord(&sr->RR_TXT, txtrdata, InterfaceID, kDNSType_TXT, kStandardTTL, recordType, artype, ServiceCallback, sr);
13558 
13559     // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13560     if (mDNSIPPortIsZero(port))
13561         return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
13562 
13563     // If the caller is registering an oversized TXT record,
13564     // it is the caller's responsibility to allocate a ServiceRecordSet structure that is large enough for it
13565     if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
13566         sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
13567 
13568     // Set up the record names
13569     // For now we only create an advisory record for the main type, not for subtypes
13570     // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13571     if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
13572         return(mStatus_BadParamErr);
13573     if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13574     if (ConstructServiceName(&sr->RR_SRV.namestorage, name,     type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13575     AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
13576 
13577     // 1. Set up the ADV record rdata to advertise our service type
13578     AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
13579 
13580     // 2. Set up the PTR record rdata to point to our service name
13581     // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13582     // Note: uDNS registration code assumes that Additional1 points to the SRV record
13583     AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
13584     sr->RR_PTR.Additional1 = &sr->RR_SRV;
13585     sr->RR_PTR.Additional2 = &sr->RR_TXT;
13586 
13587     // 2a. Set up any subtype PTRs to point to our service name
13588     // If the client is using subtypes, it is the client's responsibility to have
13589     // already set the first label of the record name to the subtype being registered
13590     for (i=0; i<NumSubTypes; i++)
13591     {
13592         domainname st;
13593         AssignDomainName(&st, sr->SubTypes[i].resrec.name);
13594         st.c[1+st.c[0]] = 0;            // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13595         AppendDomainName(&st, type);
13596         mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13597         if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
13598         AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
13599         sr->SubTypes[i].Additional1 = &sr->RR_SRV;
13600         sr->SubTypes[i].Additional2 = &sr->RR_TXT;
13601     }
13602 
13603     // 3. Set up the SRV record rdata.
13604     sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
13605     sr->RR_SRV.resrec.rdata->u.srv.weight   = 0;
13606     sr->RR_SRV.resrec.rdata->u.srv.port     = port;
13607 
13608     // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13609     if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
13610     else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
13611 
13612     // 4. Set up the TXT record rdata,
13613     // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13614     // Note: uDNS registration code assumes that DependentOn points to the SRV record
13615     if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
13616     else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
13617     {
13618         sr->RR_TXT.resrec.rdlength = txtlen;
13619         if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
13620         mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
13621     }
13622     sr->RR_TXT.DependentOn = &sr->RR_SRV;
13623 
13624     mDNS_Lock(m);
13625     // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13626     // that if the SRV cannot find a target, rest of the records that belong to this service
13627     // will not be activated.
13628     err = mDNS_Register_internal(m, &sr->RR_SRV);
13629     // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13630     // any list and hence no need to deregister. We could probably do similar checks for other
13631     // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13632     if (err)
13633     {
13634         mDNS_Unlock(m);
13635         return err;
13636     }
13637     if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
13638     // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13639     // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13640     // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13641     // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13642     // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13643     if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
13644     for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
13645     if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
13646 
13647     mDNS_Unlock(m);
13648 
13649     if (err) mDNS_DeregisterService(m, sr);
13650     return(err);
13651 }
13652 
13653 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
13654                                            ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl,  mDNSu32 flags)
13655 {
13656     ExtraResourceRecord **e;
13657     mStatus status;
13658     AuthRecType artype;
13659     mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
13660     ResourceRecord *rr;
13661 
13662     artype = setAuthRecType(InterfaceID, flags);
13663 
13664     extra->next = mDNSNULL;
13665     mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
13666                              extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13667     AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
13668 
13669     mDNS_Lock(m);
13670     rr = mDNSNULL;
13671     if (extra->r.resrec.rrtype == kDNSType_TXT)
13672     {
13673         if (sr->RR_TXT.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_TXT.resrec;
13674     }
13675     else if (extra->r.resrec.rrtype == kDNSType_SRV)
13676     {
13677         if (sr->RR_SRV.resrec.RecordType & kDNSRecordTypeUniqueMask) rr = &sr->RR_SRV.resrec;
13678     }
13679 
13680     if (!rr)
13681     {
13682         ExtraResourceRecord *srExtra;
13683 
13684         for (srExtra = sr->Extras; srExtra; srExtra = srExtra->next)
13685         {
13686             if ((srExtra->r.resrec.rrtype == extra->r.resrec.rrtype) && (srExtra->r.resrec.RecordType & kDNSRecordTypeUniqueMask))
13687             {
13688                 rr = &srExtra->r.resrec;
13689                 break;
13690             }
13691         }
13692     }
13693 
13694     if (rr && (extra->r.resrec.rroriginalttl != rr->rroriginalttl))
13695     {
13696         LogMsg("mDNS_AddRecordToService: Correcting TTL from %4d to %4d for %s",
13697             extra->r.resrec.rroriginalttl, rr->rroriginalttl, RRDisplayString(m, &extra->r.resrec));
13698         extra->r.resrec.rroriginalttl = rr->rroriginalttl;
13699     }
13700 
13701     e = &sr->Extras;
13702     while (*e) e = &(*e)->next;
13703 
13704     extra->r.DependentOn = &sr->RR_SRV;
13705 
13706     debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13707            extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
13708 
13709     status = mDNS_Register_internal(m, &extra->r);
13710     if (status == mStatus_NoError) *e = extra;
13711 
13712     mDNS_Unlock(m);
13713     return(status);
13714 }
13715 
13716 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
13717                                                 mDNSRecordCallback MemFreeCallback, void *Context)
13718 {
13719     ExtraResourceRecord **e;
13720     mStatus status;
13721 
13722     mDNS_Lock(m);
13723     e = &sr->Extras;
13724     while (*e && *e != extra) e = &(*e)->next;
13725     if (!*e)
13726     {
13727         debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
13728         status = mStatus_BadReferenceErr;
13729     }
13730     else
13731     {
13732         debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
13733         extra->r.RecordCallback = MemFreeCallback;
13734         extra->r.RecordContext  = Context;
13735         *e = (*e)->next;
13736         status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
13737     }
13738     mDNS_Unlock(m);
13739     return(status);
13740 }
13741 
13742 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
13743 {
13744     // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13745     // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13746     domainlabel name1, name2;
13747     domainname type, domain;
13748     const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
13749     ExtraResourceRecord *extras = sr->Extras;
13750     mStatus err;
13751 
13752     DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
13753     if (!newname)
13754     {
13755         name2 = name1;
13756         IncrementLabelSuffix(&name2, mDNStrue);
13757         newname = &name2;
13758     }
13759 
13760     if (SameDomainName(&domain, &localdomain))
13761         debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
13762     else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
13763 
13764     // If there's a pending TXT record update at this point, which can happen if a DNSServiceUpdateRecord() call was made
13765     // after the TXT record's deregistration, execute it now, otherwise it will be lost during the service re-registration.
13766     if (sr->RR_TXT.NewRData) CompleteRDataUpdate(m, &sr->RR_TXT);
13767     err = mDNS_RegisterService(m, sr, newname, &type, &domain,
13768                                host, sr->RR_SRV.resrec.rdata->u.srv.port,
13769                                (sr->RR_TXT.resrec.rdata != &sr->RR_TXT.rdatastorage) ? sr->RR_TXT.resrec.rdata : mDNSNULL,
13770                                sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
13771                                sr->SubTypes, sr->NumSubTypes,
13772                                sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags);
13773 
13774     // mDNS_RegisterService() just reset sr->Extras to NULL.
13775     // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13776     // through the old list of extra records, and re-add them to our freshly created service registration
13777     while (!err && extras)
13778     {
13779         ExtraResourceRecord *e = extras;
13780         extras = extras->next;
13781         err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
13782     }
13783 
13784     return(err);
13785 }
13786 
13787 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13788 // which may change the record list and/or question list.
13789 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13790 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
13791 {
13792     // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13793     if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
13794 
13795     if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
13796     {
13797         debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
13798         return(mStatus_BadReferenceErr);
13799     }
13800     else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
13801     {
13802         LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
13803         // Avoid race condition:
13804         // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13805         // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13806         // If the client happens to deregister the service in the middle of that process, then
13807         // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13808         // instead of incorrectly promoting it to mStatus_NameConflict.
13809         // This race condition is exposed particularly when the conformance test generates
13810         // a whole batch of simultaneous conflicts across a range of services all advertised
13811         // using the same system default name, and if we don't take this precaution then
13812         // we end up incrementing m->nicelabel multiple times instead of just once.
13813         // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13814         sr->Conflict = mDNSfalse;
13815         return(mStatus_NoError);
13816     }
13817     else
13818     {
13819         mDNSu32 i;
13820         mStatus status;
13821         ExtraResourceRecord *e;
13822         mDNS_Lock(m);
13823         e = sr->Extras;
13824 
13825         // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13826         // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13827         mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
13828         mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
13829         mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
13830 
13831         // We deregister all of the extra records, but we leave the sr->Extras list intact
13832         // in case the client wants to do a RenameAndReregister and reinstate the registration
13833         while (e)
13834         {
13835             mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
13836             e = e->next;
13837         }
13838 
13839         for (i=0; i<sr->NumSubTypes; i++)
13840             mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
13841 
13842         status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
13843         mDNS_Unlock(m);
13844         return(status);
13845     }
13846 }
13847 
13848 // Create a registration that asserts that no such service exists with this name.
13849 // This can be useful where there is a given function is available through several protocols.
13850 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13851 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13852 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13853 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13854 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
13855                                               const domainlabel *const name, const domainname *const type, const domainname *const domain,
13856                                               const domainname *const host,
13857                                               const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
13858 {
13859     AuthRecType artype;
13860 
13861     artype = setAuthRecType(InterfaceID, flags);
13862 
13863     mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
13864     if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13865     rr->resrec.rdata->u.srv.priority    = 0;
13866     rr->resrec.rdata->u.srv.weight      = 0;
13867     rr->resrec.rdata->u.srv.port        = zeroIPPort;
13868     if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
13869     else rr->AutoTarget = Target_AutoHost;
13870     return(mDNS_Register(m, rr));
13871 }
13872 
13873 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
13874                                          mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
13875 {
13876     AuthRecType artype;
13877 
13878     if (InterfaceID == mDNSInterface_LocalOnly)
13879         artype = AuthRecordLocalOnly;
13880     else if (InterfaceID == mDNSInterface_P2P || InterfaceID == mDNSInterface_BLE)
13881         artype = AuthRecordP2P;
13882     else
13883         artype = AuthRecordAny;
13884     mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
13885     if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
13886     if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
13887     return(mDNS_Register(m, rr));
13888 }
13889 
13890 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
13891 {
13892     AuthRecord *r;
13893     for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
13894     return mDNSfalse;
13895 }
13896 
13897 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
13898 {
13899     DNSQuestion *q;
13900     for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
13901     return mDNSfalse;
13902 }
13903 
13904 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
13905 {
13906     mDNSOpaque16 id;
13907     int i;
13908 
13909     for (i=0; i<10; i++)
13910     {
13911         id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
13912         if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
13913     }
13914 
13915     debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
13916 
13917     return id;
13918 }
13919 
13920 // ***************************************************************************
13921 #if COMPILER_LIKES_PRAGMA_MARK
13922 #pragma mark -
13923 #pragma mark - Sleep Proxy Server
13924 #endif
13925 
13926 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
13927 {
13928     // If we see an ARP from a machine we think is sleeping, then either
13929     // (i) the machine has woken, or
13930     // (ii) it's just a stray old packet from before the machine slept
13931     // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13932     // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13933     // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13934     // 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*
13935     // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13936     // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13937 
13938     rr->resrec.RecordType = kDNSRecordTypeUnique;
13939     rr->ProbeCount        = DefaultProbeCountForTypeUnique;
13940     rr->ProbeRestartCount++;
13941 
13942     // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13943     // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13944     // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13945     // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13946     // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13947     // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13948     if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
13949         InitializeLastAPTime(m, rr);
13950     else
13951     {
13952         rr->AnnounceCount  = InitialAnnounceCount;
13953         rr->ThisAPInterval = mDNSPlatformOneSecond;
13954         rr->LastAPTime     = m->timenow + mDNSPlatformOneSecond * 9;    // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13955         SetNextAnnounceProbeTime(m, rr);
13956     }
13957 }
13958 
13959 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
13960 {
13961     static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
13962     AuthRecord *rr;
13963     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13964     if (!intf) return;
13965 
13966     mDNS_Lock(m);
13967 
13968     // Pass 1:
13969     // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13970     // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13971     // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13972     // The times we might need to react to an ARP Announcement are:
13973     // (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
13974     // (ii) if it's a conflicting Announcement from another host
13975     // -- and we check for these in Pass 2 below.
13976     if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
13977     {
13978         for (rr = m->ResourceRecords; rr; rr=rr->next)
13979             if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13980                 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
13981             {
13982                 static const char msg1[] = "ARP Req from owner -- re-probing";
13983                 static const char msg2[] = "Ignoring  ARP Request from      ";
13984                 static const char msg3[] = "Creating Local ARP Cache entry  ";
13985                 static const char msg4[] = "Answering ARP Request from      ";
13986                 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
13987                                         (rr->AnnounceCount == InitialAnnounceCount)     ? msg2 :
13988                                         mDNSSameEthAddress(&arp->sha, &intf->MAC)       ? msg3 : msg4;
13989                 LogMsg("Arp %-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13990                        intf->ifname, msg, arp->sha.b, arp->spa.b, arp->tpa.b,
13991                        &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13992                 if (msg == msg1)
13993                 {
13994                     if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13995                         RestartARPProbing(m, rr);
13996                     else
13997                         LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13998                 }
13999                 else if (msg == msg3)
14000                 {
14001                     mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
14002                 }
14003                 else if (msg == msg4)
14004                 {
14005 		    mDNSv4Addr tpa = arp->tpa;
14006 		    mDNSv4Addr spa = arp->spa;
14007                     SendARP(m, 2, rr, &tpa, &arp->sha, &spa, &arp->sha);
14008                 }
14009             }
14010     }
14011 
14012     // Pass 2:
14013     // 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.
14014     // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
14015     // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
14016     // 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.
14017     // If we see an apparently conflicting ARP, we check the sender hardware address:
14018     //   If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
14019     //   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.
14020     if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
14021         debugf("ARP from self for %.4a", arp->tpa.b);
14022     else
14023     {
14024         if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
14025             for (rr = m->ResourceRecords; rr; rr=rr->next)
14026                 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14027                     rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
14028                 {
14029                     if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
14030                     {
14031                         LogMsg("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14032                                 arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14033                     }
14034                     else
14035                     {
14036                         RestartARPProbing(m, rr);
14037                         if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
14038                         {
14039                             LogMsg("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
14040                                     mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request      " : "Response     ",
14041                                     arp->sha.b, arp->spa.b, arp->tpa.b, ARDisplayString(m, rr));
14042                         }
14043                         else
14044                         {
14045                             LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14046                                     arp->sha.b, arp->spa.b, arp->tpa.b, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14047                             ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14048                         }
14049                     }
14050                 }
14051     }
14052 
14053     mDNS_Unlock(m);
14054 }
14055 
14056 /*
14057    // Option 1 is Source Link Layer Address Option
14058    // Option 2 is Target Link Layer Address Option
14059    mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
14060     {
14061     const mDNSu8 *options = (mDNSu8 *)(ndp+1);
14062     while (options < end)
14063         {
14064         debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
14065         if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
14066         options += options[1] * 8;
14067         }
14068     return mDNSNULL;
14069     }
14070  */
14071 
14072 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
14073                                     const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14074 {
14075     AuthRecord *rr;
14076     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
14077     if (!intf) return;
14078 
14079     mDNS_Lock(m);
14080 
14081     // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
14082     if (ndp->type == NDP_Sol)
14083     {
14084         //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
14085         (void)end;
14086         for (rr = m->ResourceRecords; rr; rr=rr->next)
14087             if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14088                 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
14089             {
14090                 static const char msg1[] = "NDP Req from owner -- re-probing";
14091                 static const char msg2[] = "Ignoring  NDP Request from      ";
14092                 static const char msg3[] = "Creating Local NDP Cache entry  ";
14093                 static const char msg4[] = "Answering NDP Request from      ";
14094                 static const char msg5[] = "Answering NDP Probe   from      ";
14095                 const char *const msg = mDNSSameEthAddress(sha, &rr->WakeUp.IMAC)   ? msg1 :
14096                                         (rr->AnnounceCount == InitialAnnounceCount) ? msg2 :
14097                                         mDNSSameEthAddress(sha, &intf->MAC)         ? msg3 :
14098                                         mDNSIPv6AddressIsZero(*spa)                 ? msg4 : msg5;
14099                 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
14100                        intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14101                 if (msg == msg1)
14102                 {
14103                     if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
14104                         RestartARPProbing(m, rr);
14105                     else
14106                         LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
14107                 }
14108                 else if (msg == msg3)
14109                     mDNSPlatformSetLocalAddressCacheEntry(&rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
14110                 else if (msg == msg4)
14111                     SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha);
14112                 else if (msg == msg5)
14113                     SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
14114             }
14115     }
14116 
14117     // 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.
14118     if (mDNSSameEthAddress(sha, &intf->MAC))
14119         debugf("NDP from self for %.16a", &ndp->target);
14120     else
14121     {
14122         // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
14123         // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
14124         // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
14125         // Hence it is the NDP target address we care about, not the actual packet source address.
14126         if (ndp->type == NDP_Adv) spa = &ndp->target;
14127         if (!mDNSSameIPv6Address(*spa, zerov6Addr))
14128             for (rr = m->ResourceRecords; rr; rr=rr->next)
14129                 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14130                     rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
14131                 {
14132                     if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
14133                     {
14134                         LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14135                                     sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14136                     }
14137                     else
14138                     {
14139                         RestartARPProbing(m, rr);
14140                         if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
14141                         {
14142                             LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
14143                                     ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
14144                         }
14145                         else
14146                         {
14147                             LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
14148                                     sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
14149                             ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14150                         }
14151                     }
14152                 }
14153     }
14154 
14155     mDNS_Unlock(m);
14156 }
14157 
14158 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
14159                                                  const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
14160 {
14161     const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
14162     mDNSBool wake = mDNSfalse;
14163     mDNSBool kaWake = mDNSfalse;
14164 
14165     switch (protocol)
14166     {
14167         #define XX wake ? "Received" : "Ignoring", end-p
14168     case 0x01:  LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
14169         break;
14170 
14171     case 0x06:  {
14172         AuthRecord *kr;
14173         mDNSu32 seq, ack;
14174                     #define TH_FIN  0x01
14175                     #define TH_SYN  0x02
14176                     #define TH_RST  0x04
14177                     #define TH_ACK  0x10
14178 
14179         kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
14180         if (kr)
14181         {
14182             LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d  to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
14183             // Plan to wake if
14184             // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
14185             // (b) packet that contains new data and acks a sequence number higher than the one
14186             //     we have been sending in the keepalive
14187 
14188             wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
14189             if (!wake)
14190             {
14191                 mDNSu8 *ptr;
14192                 mDNSu32 pseq, pack;
14193                 mDNSBool data = mDNSfalse;
14194                 mDNSu8 tcphlen;
14195 
14196                 // Convert to host order
14197                 ptr = (mDNSu8 *)&seq;
14198                 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14199 
14200                 ptr = (mDNSu8 *)&ack;
14201                 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14202 
14203                 pseq = t->tcp.seq;
14204                 ptr = (mDNSu8 *)&pseq;
14205                 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14206 
14207                 pack = t->tcp.ack;
14208                 ptr = (mDNSu8 *)&pack;
14209                 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
14210 
14211                 // If the other side is acking one more than our sequence number (keepalive is one
14212                 // less than the last valid sequence sent) and it's sequence is more than what we
14213                 // acked before
14214                 //if (end - p - 34  - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
14215                 tcphlen = ((t->tcp.offset >> 4) * 4);
14216                 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
14217                 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
14218 
14219                 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
14220                 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) &&
14221                     ((int)(ack - pseq) == 1))
14222                 {
14223                     // Send an ACK;
14224                     mDNS_SendKeepaliveACK(m, kr);
14225                 }
14226                 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
14227                        end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
14228             }
14229             else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
14230             kaWake = wake;
14231         }
14232         else
14233         {
14234             // Plan to wake if
14235             // (a) RST is not set, AND
14236             // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
14237             wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
14238 
14239             // For now, to reduce spurious wakeups, we wake only for TCP SYN,
14240             // except for ssh connections, where we'll wake for plain data packets too
14241             if  (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
14242 
14243             LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
14244                    src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
14245                    (t->tcp.flags & 2) ? " SYN" : "",
14246                    (t->tcp.flags & 1) ? " FIN" : "",
14247                    (t->tcp.flags & 4) ? " RST" : "");
14248         }
14249         break;
14250     }
14251 
14252     case 0x11:  {
14253                     #define ARD_AsNumber 3283
14254         static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
14255         const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]);                  // Length *including* 8-byte UDP header
14256         if (udplen >= sizeof(UDPHeader))
14257         {
14258             const mDNSu16 datalen = udplen - sizeof(UDPHeader);
14259             wake = mDNStrue;
14260 
14261             // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
14262             if (mDNSSameIPPort(port, IPSECPort))
14263             {
14264                 // Specifically ignore NAT keepalive packets
14265                 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
14266                 else
14267                 {
14268                     // Skip over the Non-ESP Marker if present
14269                     const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
14270                     const IKEHeader *const ike    = (IKEHeader *)(t + (NonESP ? 12 : 8));
14271                     const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
14272                     if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
14273                         if ((ike->Version & 0x10) == 0x10)
14274                         {
14275                             // ExchangeType ==  5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14276                             // ExchangeType == 34 means 'IKE_SA_INIT'   <http://www.iana.org/assignments/ikev2-parameters>
14277                             if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
14278                             LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
14279                         }
14280                 }
14281             }
14282 
14283             // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14284             // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14285             // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14286             // UDP header (8 bytes)
14287             // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14288             if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
14289 
14290             LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
14291         }
14292     }
14293     break;
14294 
14295     case 0x3A:  if (&t->bytes[len] <= end)
14296         {
14297             mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
14298             if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
14299             else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
14300         }
14301         break;
14302 
14303     default:    LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
14304         break;
14305     }
14306 
14307     if (wake)
14308     {
14309         AuthRecord *rr, *r2;
14310 
14311         mDNS_Lock(m);
14312         for (rr = m->ResourceRecords; rr; rr=rr->next)
14313             if (rr->resrec.InterfaceID == InterfaceID &&
14314                 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14315                 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
14316             {
14317                 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
14318                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
14319                     if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
14320                         r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
14321                         r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
14322                         SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
14323                         break;
14324                 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr;    // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14325                 if (!r2 && kaWake) r2 = rr;                             // So that we wake for keepalive packets, even without a matching SRV record
14326                 if (r2)
14327                 {
14328                     LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14329                            InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
14330                     ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14331                 }
14332                 else
14333                     LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14334                            InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
14335             }
14336         mDNS_Unlock(m);
14337     }
14338 }
14339 
14340 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14341 {
14342     static const mDNSOpaque16 Ethertype_ARP  = { { 0x08, 0x06 } };  // Ethertype 0x0806 = ARP
14343     static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } };  // Ethertype 0x0800 = IPv4
14344     static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } };  // Ethertype 0x86DD = IPv6
14345     static const mDNSOpaque16 ARP_hrd_eth    = { { 0x00, 0x01 } };  // Hardware address space (Ethernet = 1)
14346     static const mDNSOpaque16 ARP_pro_ip     = { { 0x08, 0x00 } };  // Protocol address space (IP = 0x0800)
14347 
14348     // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14349     // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14350     // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14351     // since it points to a an address 14 bytes before pkt.
14352     const EthernetHeader     *const eth = (const EthernetHeader *)p;
14353     const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
14354     mDNSAddr src, dst;
14355     #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14356 
14357     // Is ARP? Length must be at least 14 + 28 = 42 bytes
14358     if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
14359         mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
14360     // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14361     else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
14362     {
14363         const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
14364         const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen);
14365         if (transEnd > end) transEnd = end;
14366         debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src.b, &pkt->v4.dst.b);
14367         src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
14368         dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
14369         if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol))
14370             mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0);
14371     }
14372     // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14373     else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
14374     {
14375         const mDNSu8 *const trans = p + 54;
14376         debugf("Got IPv6  %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src.b, &pkt->v6.dst.b);
14377         src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
14378         dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
14379         if (end >= trans + RequiredCapLen(pkt->v6.pro))
14380             mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
14381                                               (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
14382     }
14383 }
14384 
14385 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
14386 {
14387     name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
14388                                        m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
14389 }
14390 
14391 #ifndef SPC_DISABLED
14392 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
14393 {
14394     if (result == mStatus_NameConflict)
14395         mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
14396     else if (result == mStatus_MemFree)
14397     {
14398         if (m->SleepState)
14399             m->SPSState = 3;
14400         else
14401         {
14402             m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
14403             if (m->SPSState)
14404             {
14405                 domainlabel name;
14406                 ConstructSleepProxyServerName(m, &name);
14407                 mDNS_RegisterService(m, srs,
14408                                      &name, &SleepProxyServiceType, &localdomain,
14409                                      mDNSNULL, m->SPSSocket->port, // Host, port
14410                                      mDNSNULL,
14411                                      (mDNSu8 *)"", 1,           // TXT data, length
14412                                      mDNSNULL, 0,               // Subtypes (none)
14413                                      mDNSInterface_Any,         // Interface ID
14414                                      SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
14415             }
14416             LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
14417         }
14418     }
14419 }
14420 #endif
14421 
14422 // Called with lock held
14423 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
14424 {
14425     // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14426     mDNS_DropLockBeforeCallback();
14427 
14428     // If turning off SPS, close our socket
14429     // (Do this first, BEFORE calling mDNS_DeregisterService below)
14430     if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
14431 
14432     // If turning off, or changing type, deregister old name
14433 #ifndef SPC_DISABLED
14434     if (m->SPSState == 1 && sps != m->SPSType)
14435     { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
14436 #endif // SPC_DISABLED
14437 
14438     // Record our new SPS parameters
14439     m->SPSType          = sps;
14440     m->SPSPortability   = port;
14441     m->SPSMarginalPower = marginalpower;
14442     m->SPSTotalPower    = totpower;
14443     m->SPSFeatureFlags  = features;
14444     // If turning on, open socket and advertise service
14445     if (sps)
14446     {
14447         if (!m->SPSSocket)
14448         {
14449             m->SPSSocket = mDNSPlatformUDPSocket(zeroIPPort);
14450             if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
14451         }
14452 #ifndef SPC_DISABLED
14453         if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
14454 #endif // SPC_DISABLED
14455     }
14456     else if (m->SPSState)
14457     {
14458         LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
14459         m->NextScheduledSPS = m->timenow;
14460     }
14461 fail:
14462     mDNS_ReclaimLockAfterCallback();
14463 }
14464 
14465 // ***************************************************************************
14466 #if COMPILER_LIKES_PRAGMA_MARK
14467 #pragma mark -
14468 #pragma mark - Startup and Shutdown
14469 #endif
14470 
14471 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14472 {
14473     if (storage && numrecords)
14474     {
14475         mDNSu32 i;
14476         debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
14477         for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
14478         storage[numrecords-1].next = m->rrcache_free;
14479         m->rrcache_free = storage;
14480         m->rrcache_size += numrecords;
14481     }
14482 }
14483 
14484 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14485 {
14486     mDNS_Lock(m);
14487     mDNS_GrowCache_internal(m, storage, numrecords);
14488     mDNS_Unlock(m);
14489 }
14490 
14491 mDNSlocal mStatus mDNS_InitStorage(mDNS *const m, mDNS_PlatformSupport *const p,
14492                                    CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14493                                    mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14494 {
14495     mDNSu32 slot;
14496     mDNSs32 timenow;
14497     mStatus result;
14498 
14499     if (!rrcachestorage) rrcachesize = 0;
14500 
14501     m->p                             = p;
14502     m->NetworkChanged                = 0;
14503     m->CanReceiveUnicastOn5353       = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14504     m->AdvertiseLocalAddresses       = AdvertiseLocalAddresses;
14505     m->DivertMulticastAdvertisements = mDNSfalse;
14506     m->mDNSPlatformStatus            = mStatus_Waiting;
14507     m->UnicastPort4                  = zeroIPPort;
14508     m->UnicastPort6                  = zeroIPPort;
14509     m->PrimaryMAC                    = zeroEthAddr;
14510     m->MainCallback                  = Callback;
14511     m->MainContext                   = Context;
14512     m->rec.r.resrec.RecordType       = 0;
14513 
14514     // For debugging: To catch and report locking failures
14515     m->mDNS_busy               = 0;
14516     m->mDNS_reentrancy         = 0;
14517     m->ShutdownTime            = 0;
14518     m->lock_rrcache            = 0;
14519     m->lock_Questions          = 0;
14520     m->lock_Records            = 0;
14521 
14522     // Task Scheduling variables
14523     result = mDNSPlatformTimeInit();
14524     if (result != mStatus_NoError) return(result);
14525     m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
14526     timenow = mDNS_TimeNow_NoLock(m);
14527 
14528     m->timenow                 = 0;     // MUST only be set within mDNS_Lock/mDNS_Unlock section
14529     m->timenow_last            = timenow;
14530     m->NextScheduledEvent      = timenow;
14531     m->SuppressSending         = timenow;
14532     m->NextCacheCheck          = timenow + FutureTime;
14533     m->NextScheduledQuery      = timenow + FutureTime;
14534     m->NextScheduledProbe      = timenow + FutureTime;
14535     m->NextScheduledResponse   = timenow + FutureTime;
14536     m->NextScheduledNATOp      = timenow + FutureTime;
14537     m->NextScheduledSPS        = timenow + FutureTime;
14538     m->NextScheduledKA         = timenow + FutureTime;
14539     m->NextScheduledStopTime   = timenow + FutureTime;
14540     m->NextBLEServiceTime      = 0;    // zero indicates inactive
14541 
14542 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14543     m->NextBonjourDisableTime  = 0; // Timer active when non zero.
14544     m->BonjourEnabled          = 0; // Set when Bonjour on Demand is enabled and Bonjour is currently enabled.
14545 #endif
14546 
14547     m->RandomQueryDelay        = 0;
14548     m->RandomReconfirmDelay    = 0;
14549     m->PktNum                  = 0;
14550     m->MPktNum                 = 0;
14551     m->LocalRemoveEvents       = mDNSfalse;
14552     m->SleepState              = SleepState_Awake;
14553     m->SleepSeqNum             = 0;
14554     m->SystemWakeOnLANEnabled  = mDNSfalse;
14555     m->AnnounceOwner           = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
14556     m->DelaySleep              = 0;
14557     m->SleepLimit              = 0;
14558 
14559 #if APPLE_OSX_mDNSResponder
14560     m->UnicastPacketsSent      = 0;
14561     m->MulticastPacketsSent    = 0;
14562     m->RemoteSubnet            = 0;
14563 #endif // APPLE_OSX_mDNSResponder
14564 
14565     // These fields only required for mDNS Searcher...
14566     m->Questions               = mDNSNULL;
14567     m->NewQuestions            = mDNSNULL;
14568     m->CurrentQuestion         = mDNSNULL;
14569     m->LocalOnlyQuestions      = mDNSNULL;
14570     m->NewLocalOnlyQuestions   = mDNSNULL;
14571     m->RestartQuestion         = mDNSNULL;
14572     m->rrcache_size            = 0;
14573     m->rrcache_totalused       = 0;
14574     m->rrcache_active          = 0;
14575     m->rrcache_report          = 10;
14576     m->rrcache_free            = mDNSNULL;
14577 
14578     for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14579     {
14580         m->rrcache_hash[slot]      = mDNSNULL;
14581         m->rrcache_nextcheck[slot] = timenow + FutureTime;;
14582     }
14583 
14584     mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
14585     m->rrauth.rrauth_free            = mDNSNULL;
14586 
14587     for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
14588         m->rrauth.rrauth_hash[slot] = mDNSNULL;
14589 
14590     // Fields below only required for mDNS Responder...
14591     m->hostlabel.c[0]          = 0;
14592     m->nicelabel.c[0]          = 0;
14593     m->MulticastHostname.c[0]  = 0;
14594 #if MDNSRESPONDER_SUPPORTS(APPLE, RANDOM_AWDL_HOSTNAME)
14595     m->RandomizedHostname.c[0] = 0;
14596 #endif
14597     m->HIHardware.c[0]         = 0;
14598     m->HISoftware.c[0]         = 0;
14599     m->ResourceRecords         = mDNSNULL;
14600     m->DuplicateRecords        = mDNSNULL;
14601     m->NewLocalRecords         = mDNSNULL;
14602     m->NewLocalOnlyRecords     = mDNSfalse;
14603     m->CurrentRecord           = mDNSNULL;
14604     m->HostInterfaces          = mDNSNULL;
14605     m->ProbeFailTime           = 0;
14606     m->NumFailedProbes         = 0;
14607     m->SuppressProbes          = 0;
14608 
14609 #ifndef UNICAST_DISABLED
14610     m->NextuDNSEvent            = timenow + FutureTime;
14611     m->NextSRVUpdate            = timenow + FutureTime;
14612 
14613 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14614     m->DNSServers               = mDNSNULL;
14615 #endif
14616 
14617     m->Router                   = zeroAddr;
14618     m->AdvertisedV4             = zeroAddr;
14619     m->AdvertisedV6             = zeroAddr;
14620 
14621     m->AuthInfoList             = mDNSNULL;
14622 
14623     m->ReverseMap.ThisQInterval = -1;
14624     m->StaticHostname.c[0]      = 0;
14625     m->FQDN.c[0]                = 0;
14626     m->Hostnames                = mDNSNULL;
14627 
14628     m->WABBrowseQueriesCount    = 0;
14629     m->WABLBrowseQueriesCount   = 0;
14630     m->WABRegQueriesCount       = 0;
14631     m->AutoTargetServices       = 1;
14632 
14633 #if MDNSRESPONDER_SUPPORTS(APPLE, BONJOUR_ON_DEMAND)
14634     m->NumAllInterfaceRecords   = 0;
14635     m->NumAllInterfaceQuestions = 0;
14636 #endif
14637     // NAT traversal fields
14638     m->LLQNAT.clientCallback    = mDNSNULL;
14639     m->LLQNAT.clientContext     = mDNSNULL;
14640     m->NATTraversals            = mDNSNULL;
14641     m->CurrentNATTraversal      = mDNSNULL;
14642     m->retryIntervalGetAddr     = 0;    // delta between time sent and retry
14643     m->retryGetAddr             = timenow + FutureTime; // absolute time when we retry
14644     m->ExtAddress               = zerov4Addr;
14645     m->PCPNonce[0]              = mDNSRandom(-1);
14646     m->PCPNonce[1]              = mDNSRandom(-1);
14647     m->PCPNonce[2]              = mDNSRandom(-1);
14648 
14649     m->NATMcastRecvskt          = mDNSNULL;
14650     m->LastNATupseconds         = 0;
14651     m->LastNATReplyLocalTime    = timenow;
14652     m->LastNATMapResultCode     = NATErr_None;
14653 
14654     m->UPnPInterfaceID          = 0;
14655     m->SSDPSocket               = mDNSNULL;
14656     m->SSDPWANPPPConnection     = mDNSfalse;
14657     m->UPnPRouterPort           = zeroIPPort;
14658     m->UPnPSOAPPort             = zeroIPPort;
14659     m->UPnPRouterURL            = mDNSNULL;
14660     m->UPnPWANPPPConnection     = mDNSfalse;
14661     m->UPnPSOAPURL              = mDNSNULL;
14662     m->UPnPRouterAddressString  = mDNSNULL;
14663     m->UPnPSOAPAddressString    = mDNSNULL;
14664     m->SPSType                  = 0;
14665     m->SPSPortability           = 0;
14666     m->SPSMarginalPower         = 0;
14667     m->SPSTotalPower            = 0;
14668     m->SPSFeatureFlags          = 0;
14669     m->SPSState                 = 0;
14670     m->SPSProxyListChanged      = mDNSNULL;
14671     m->SPSSocket                = mDNSNULL;
14672     m->SPSBrowseCallback        = mDNSNULL;
14673     m->ProxyRecords             = 0;
14674 
14675     m->DNSPushServers           = mDNSNULL;
14676     m->DNSPushZones             = mDNSNULL;
14677 #endif
14678 
14679 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
14680     if (WCFConnectionNew)
14681     {
14682         m->WCF = WCFConnectionNew();
14683         if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
14684     }
14685 #endif
14686 
14687 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
14688     result = init_and_load_trust_anchors();
14689     if (result != mStatus_NoError) return(result);
14690 #endif
14691 
14692     return(result);
14693 }
14694 
14695 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
14696                              CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14697                              mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14698 {
14699     mStatus result = mDNS_InitStorage(m, p, rrcachestorage, rrcachesize, AdvertiseLocalAddresses, Callback, Context);
14700     if (result != mStatus_NoError)
14701         return(result);
14702 
14703 #if MDNS_MALLOC_DEBUGGING
14704     static mDNSListValidator lv;
14705     mDNSPlatformAddListValidator(&lv, mDNS_ValidateLists, "mDNS_ValidateLists", m);
14706 #endif
14707     result = mDNSPlatformInit(m);
14708 
14709 #ifndef UNICAST_DISABLED
14710     // It's better to do this *after* the platform layer has set up the
14711     // interface list and security credentials
14712     uDNS_SetupDNSConfig(m);                     // Get initial DNS configuration
14713 #endif
14714 
14715     return(result);
14716 }
14717 
14718 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
14719 {
14720     if (m->SPSState == 1)
14721     {
14722         domainlabel name, newname;
14723 #ifndef SPC_DISABLED
14724         domainname type, domain;
14725         DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
14726 #endif // SPC_DISABLED
14727         ConstructSleepProxyServerName(m, &newname);
14728         if (!SameDomainLabelCS(name.c, newname.c))
14729         {
14730             LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
14731             // When SleepProxyServerCallback gets the mStatus_MemFree message,
14732             // it will reregister the service under the new name
14733             m->SPSState = 2;
14734 #ifndef SPC_DISABLED
14735             mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
14736 #endif // SPC_DISABLED
14737         }
14738     }
14739 
14740     if (m->MainCallback)
14741         m->MainCallback(m, mStatus_ConfigChanged);
14742 }
14743 
14744 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
14745 {
14746     (void)m;    // unused
14747     debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
14748     mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
14749 }
14750 
14751 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14752 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr)
14753 {
14754     mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
14755                      cr->resrec.rrtype     == kDNSType_A ||
14756                      cr->resrec.rrtype     == kDNSType_AAAA ||
14757                      cr->resrec.rrtype     == kDNSType_SRV ||
14758                      cr->resrec.rrtype     == kDNSType_CNAME;
14759 
14760     debugf("PurgeOrReconfirmCacheRecord: %s cache record due to server %#a:%d (%##s): %s",
14761            purge    ? "purging"   : "reconfirming",
14762            cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL,
14763            cr->resrec.rDNSServer ? mDNSVal16(cr->resrec.rDNSServer->port) : -1,
14764            cr->resrec.rDNSServer ? cr->resrec.rDNSServer->domain.c : mDNSNULL, CRDisplayString(m, cr));
14765 
14766     if (purge)
14767     {
14768         LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14769         mDNS_PurgeCacheResourceRecord(m, cr);
14770     }
14771     else
14772     {
14773         LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14774         mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
14775     }
14776 }
14777 #endif
14778 
14779 mDNSlocal void mDNS_PurgeBeforeResolve(mDNS *const m, DNSQuestion *q)
14780 {
14781     CacheGroup *const cg = CacheGroupForName(m, q->qnamehash, &q->qname);
14782     CacheRecord *rp;
14783     for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14784     {
14785         if (SameNameCacheRecordAnswersQuestion(rp, q))
14786         {
14787             LogInfo("mDNS_PurgeBeforeResolve: Flushing %s", CRDisplayString(m, rp));
14788             mDNS_PurgeCacheResourceRecord(m, rp);
14789         }
14790     }
14791 }
14792 
14793 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14794 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
14795 {
14796     DNSQuestion *qptr;
14797 
14798     (void) m;
14799 
14800     if (q->DuplicateOf)
14801         LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
14802 
14803     // Make sure all the duplicate questions point to the same DNSServer so that delivery
14804     // of events for all of them are consistent. Duplicates for a question are always inserted
14805     // after in the list.
14806     q->qDNSServer = new;
14807     for (qptr = q->next ; qptr; qptr = qptr->next)
14808     {
14809         if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
14810     }
14811 }
14812 #endif
14813 
14814 mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete)
14815 {
14816     McastResolver *mr;
14817 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14818     DNSServer *ptr;
14819 #endif
14820 
14821     if (delete)
14822     {
14823 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14824         for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14825         {
14826             ptr->penaltyTime = 0;
14827             ptr->flags |= DNSServerFlag_Delete;
14828 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14829             if (ptr->flags & DNSServerFlag_Unreachable)
14830                 NumUnreachableDNSServers--;
14831 #endif
14832         }
14833 #endif
14834         // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14835         // mcast resolvers. Today we get both mcast and ucast configuration using the same
14836         // API
14837         for (mr = m->McastResolvers; mr; mr = mr->next)
14838             mr->flags |= McastResolver_FlagDelete;
14839     }
14840     else
14841     {
14842 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14843         for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14844         {
14845             ptr->penaltyTime = 0;
14846             ptr->flags &= ~DNSServerFlag_Delete;
14847 #if MDNSRESPONDER_SUPPORTS(APPLE, SYMPTOMS)
14848             if (ptr->flags & DNSServerFlag_Unreachable)
14849                 NumUnreachableDNSServers++;
14850 #endif
14851         }
14852 #endif
14853         for (mr = m->McastResolvers; mr; mr = mr->next)
14854             mr->flags &= ~McastResolver_FlagDelete;
14855     }
14856 }
14857 
14858 mDNSlocal void SetDynDNSHostNameIfChanged(mDNS *const m, domainname *const fqdn)
14859 {
14860     // Did our FQDN change?
14861     if (!SameDomainName(fqdn, &m->FQDN))
14862     {
14863         if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
14864 
14865         AssignDomainName(&m->FQDN, fqdn);
14866 
14867         if (m->FQDN.c[0])
14868         {
14869             mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
14870             mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
14871         }
14872     }
14873 }
14874 
14875 // Even though this is called “Setup” it is not called just once at startup.
14876 // It’s actually called multiple times, every time there’s a configuration change.
14877 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
14878 {
14879 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14880     mDNSu32 slot;
14881     CacheGroup *cg;
14882     CacheRecord *cr;
14883 #endif
14884     mDNSAddr v4, v6, r;
14885     domainname fqdn;
14886 #if !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14887     DNSServer   *ptr, **p = &m->DNSServers;
14888     const DNSServer *oldServers = m->DNSServers;
14889     DNSQuestion *q;
14890 #endif
14891     McastResolver *mr, **mres = &m->McastResolvers;
14892 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH) && !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14893     DNSPushNotificationServer **psp;
14894 #endif
14895 
14896     debugf("uDNS_SetupDNSConfig: entry");
14897 
14898     // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14899     uDNS_SetupWABQueries(m);
14900 
14901     mDNS_Lock(m);
14902 
14903     // We need to first mark all the entries to be deleted. If the configuration changed, then
14904     // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14905     //
14906     // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14907     // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14908     // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14909     // for the dns configuration change notification.
14910     SetConfigState(m, mDNStrue);
14911     if (!mDNSPlatformSetDNSConfig(mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue))
14912     {
14913         SetDynDNSHostNameIfChanged(m, &fqdn);
14914         SetConfigState(m, mDNSfalse);
14915         mDNS_Unlock(m);
14916         LogInfo("uDNS_SetupDNSConfig: No configuration change");
14917         return mStatus_NoError;
14918     }
14919 
14920     // For now, we just delete the mcast resolvers. We don't deal with cache or
14921     // questions here. Neither question nor cache point to mcast resolvers. Questions
14922     // do inherit the timeout values from mcast resolvers. But we don't bother
14923     // affecting them as they never change.
14924     while (*mres)
14925     {
14926         if (((*mres)->flags & McastResolver_FlagDelete) != 0)
14927         {
14928             mr = *mres;
14929             *mres = (*mres)->next;
14930             debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
14931             mDNSPlatformMemFree(mr);
14932         }
14933         else
14934         {
14935             (*mres)->flags &= ~McastResolver_FlagNew;
14936             mres = &(*mres)->next;
14937         }
14938     }
14939 
14940 #if MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
14941     Querier_ProcessDNSServiceChanges();
14942 #else
14943     // Update our qDNSServer pointers before we go and free the DNSServer object memory
14944     //
14945     // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14946     // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14947     // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14948     // DNSServers and flush the cache.
14949     //
14950     // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14951     //   is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14952     //   flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14953     //   pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14954     //   flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14955     //   later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14956     //   we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14957     //   the same resGroupID.
14958     //
14959     //   Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14960     //   of the old followed by ADD of the new records.
14961     //
14962     // - A non-scoped question picks DNSServer X,  creates a cache entry with X. If the resolver gets removed later, we will
14963     //   pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14964     //   as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14965     //
14966     // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14967     //   cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14968     //   non-scoped question and vice versa.
14969     //
14970 #if MDNSRESPONDER_SUPPORTS(APPLE, DNS64)
14971     DNS64RestartQuestions(m);
14972 #endif
14973 
14974     // First, restart questions whose suppression status will change. The suppression status of each question in a given
14975     // question set, i.e., a non-duplicate question and all of its duplicates, if any, may or may not change. For example,
14976     // a suppressed (or non-suppressed) question that is currently a duplicate of a suppressed (or non-suppressed) question
14977     // may become a non-suppressed (or suppressed) question, while the question that it's a duplicate of may remain
14978     // suppressed (or non-suppressed).
14979     for (q = m->Questions; q; q = q->next)
14980     {
14981         DNSServer *s;
14982         const DNSServer *t;
14983         mDNSBool oldSuppressed;
14984 
14985         if (mDNSOpaque16IsZero(q->TargetQID)) continue;
14986 
14987         SetValidDNSServers(m, q);
14988         q->triedAllServersOnce = mDNSfalse;
14989         s = GetServerForQuestion(m, q);
14990         t = q->qDNSServer;
14991         if (s != t)
14992         {
14993             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_INFO,
14994                 "[R%u->Q%u] uDNS_SetupDNSConfig: Updating DNS server from " PRI_IP_ADDR ":%d (" PRI_DM_NAME ") to "
14995                 PRI_IP_ADDR ":%d (" PRI_DM_NAME ") for question " PRI_DM_NAME " (" PUB_S ") (scope:%p)",
14996                 q->request_id, mDNSVal16(q->TargetQID),
14997                 t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zeroIPPort), DM_NAME_PARAM(t ? &t->domain : mDNSNULL),
14998                 s ? &s->addr : mDNSNULL, mDNSVal16(s ? s->port : zeroIPPort), DM_NAME_PARAM(s ? &s->domain : mDNSNULL),
14999                 DM_NAME_PARAM(&q->qname), DNSTypeName(q->qtype), q->InterfaceID);
15000 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
15001             // If this question had a DNS Push server associated with it, substitute the new server for the
15002             // old one.   If there is no new server, then we'll clean up the push server later.
15003             if (!q->DuplicateOf && (q->dnsPushServer != mDNSNULL))
15004             {
15005                 if (q->dnsPushServer->qDNSServer == t)
15006                 {
15007                     q->dnsPushServer->qDNSServer = s; // which might be null
15008                 }
15009                 // If it is null, do the accounting and drop the push server.
15010                 if (q->dnsPushServer->qDNSServer == mDNSNULL)
15011                 {
15012                     DNSPushReconcileConnection(m, q);
15013                 }
15014             }
15015 #endif
15016         }
15017         oldSuppressed = q->Suppressed;
15018         q->Suppressed = ShouldSuppressUnicastQuery(q, s);
15019         if (!q->Suppressed != !oldSuppressed) q->Restart = mDNStrue;
15020     }
15021     RestartUnicastQuestions(m);
15022 
15023     // Now, change the server for each question set, if necessary. Note that questions whose suppression status changed
15024     // have already had their server changed by being restarted.
15025     for (q = m->Questions; q; q = q->next)
15026     {
15027         DNSServer *s;
15028         const DNSServer *t;
15029 
15030         if (mDNSOpaque16IsZero(q->TargetQID) || q->DuplicateOf) continue;
15031 
15032         SetValidDNSServers(m, q);
15033         q->triedAllServersOnce = mDNSfalse;
15034         s = GetServerForQuestion(m, q);
15035         t = q->qDNSServer;
15036         DNSServerChangeForQuestion(m, q, s);
15037         if (s == t) continue;
15038 
15039         q->Suppressed = ShouldSuppressUnicastQuery(q, s);
15040         q->unansweredQueries = 0;
15041         q->TargetQID = mDNS_NewMessageID(m);
15042         if (!q->Suppressed) ActivateUnicastQuery(m, q, mDNStrue);
15043     }
15044 
15045 #if MDNSRESPONDER_SUPPORTS(COMMON, DNS_PUSH)
15046     // The above code may have found some DNS Push servers that are no longer valid.   Now that we
15047     // are done running through the code, we need to drop our connections to those servers.
15048     // When we get here, any such servers should have zero questions associated with them.
15049     for (psp = &m->DNSPushServers; *psp != mDNSNULL; )
15050     {
15051         DNSPushNotificationServer *server = *psp;
15052 
15053         // It's possible that a push server whose DNS server has been deleted could be still connected but
15054         // not referenced by any questions.  In this case, we just delete the push server rather than trying
15055         // to figure out with which DNS server (if any) to associate it.
15056         if (server->qDNSServer != mDNSNULL && server->qDNSServer->flags & DNSServerFlag_Delete)
15057         {
15058             server->qDNSServer = mDNSNULL;
15059         }
15060 
15061         if (server->qDNSServer == mDNSNULL)
15062         {
15063             // This would be a programming error, so should never happen.
15064             if (server->numberOfQuestions != 0)
15065             {
15066                 LogInfo("uDNS_SetupDNSConfig: deleting push server %##s that has questions.", &server->serverName);
15067             }
15068             DNSPushServerDrop(server);
15069             *psp = server->next;
15070             mDNSPlatformMemFree(server);
15071         }
15072         else
15073         {
15074             psp = &(*psp)->next;
15075         }
15076     }
15077 #endif
15078 
15079     FORALL_CACHERECORDS(slot, cg, cr)
15080     {
15081         if (cr->resrec.InterfaceID) continue;
15082 
15083         // We already walked the questions and restarted/reactivated them if the dns server
15084         // change affected the question. That should take care of updating the cache. But
15085         // what if there is no active question at this point when the DNS server change
15086         // happened ? There could be old cache entries lying around and if we don't flush
15087         // them, a new question after the DNS server change could pick up these stale
15088         // entries and get a wrong answer.
15089         //
15090         // For cache entries that have active questions we might have skipped rescheduling
15091         // the questions if they were suppressed (see above). To keep it simple, we walk
15092         // all the cache entries to make sure that there are no stale entries. We use the
15093         // active question's InterfaceID/ServiceID for looking up the right DNS server.
15094         //
15095         // Note: If GetServerForName returns NULL, it could either mean that there are no
15096         // DNS servers or no matching DNS servers for this question. In either case,
15097         // the cache should get purged below when we process deleted DNS servers.
15098 
15099         if (cr->CRActiveQuestion)
15100         {
15101             // Purge or Reconfirm if this cache entry would use the new DNS server
15102             ptr = GetServerForName(m, cr->resrec.name, cr->CRActiveQuestion->InterfaceID, cr->CRActiveQuestion->ServiceID);
15103             if (ptr && (ptr != cr->resrec.rDNSServer))
15104             {
15105                 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a",
15106                         CRDisplayString(m, cr), &ptr->addr,
15107                         cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL);
15108                 PurgeOrReconfirmCacheRecord(m, cr);
15109 
15110                 // If a cache record's DNSServer pointer is NULL, but its active question got a DNSServer in this DNS configuration
15111                 // update, then use its DNSServer. This way, the active question and its duplicates don't miss out on RMV events.
15112                 if (!cr->resrec.rDNSServer && cr->CRActiveQuestion->qDNSServer)
15113                 {
15114                     LogInfo("uDNS_SetupDNSConfig: Using active question's DNS server %#a for cache record %s", &cr->CRActiveQuestion->qDNSServer->addr, CRDisplayString(m, cr));
15115                     cr->resrec.rDNSServer = cr->CRActiveQuestion->qDNSServer;
15116                 }
15117             }
15118 
15119             if (cr->resrec.rDNSServer && cr->resrec.rDNSServer->flags & DNSServerFlag_Delete)
15120             {
15121                 DNSQuestion *qptr = cr->CRActiveQuestion;
15122                 if (qptr->qDNSServer == cr->resrec.rDNSServer)
15123                 {
15124                     LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s  Active question %##s (%s) (scope:%p) pointing to DNSServer Address %#a"
15125                            " to be freed", CRDisplayString(m, cr),
15126                            qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID,
15127                            &cr->resrec.rDNSServer->addr);
15128                     qptr->validDNSServers = zeroOpaque128;
15129                     qptr->qDNSServer = mDNSNULL;
15130                     cr->resrec.rDNSServer = mDNSNULL;
15131                 }
15132                 else
15133                 {
15134                     LogInfo("uDNS_SetupDNSConfig: Cache Record %s,  Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
15135                             " resetting to  question's DNSServer Address %#a", CRDisplayString(m, cr),
15136                             qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID,
15137                             &cr->resrec.rDNSServer->addr,
15138                             qptr->qDNSServer ? &qptr->qDNSServer->addr : mDNSNULL);
15139                     cr->resrec.rDNSServer = qptr->qDNSServer;
15140                 }
15141                 PurgeOrReconfirmCacheRecord(m, cr);
15142             }
15143         }
15144         else if (!cr->resrec.rDNSServer || cr->resrec.rDNSServer->flags & DNSServerFlag_Delete)
15145         {
15146             LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEBUG,
15147                 "uDNS_SetupDNSConfig: Purging Resourcerecord " PRI_S ", DNS server " PUB_S " " PRI_IP_ADDR " " PUB_S,
15148                 CRDisplayString(m, cr), !cr->resrec.rDNSServer ? "(to be deleted)" : "",
15149                 cr->resrec.rDNSServer ? &cr->resrec.rDNSServer->addr : mDNSNULL,
15150                 cr->resrec.rDNSServer ? DNSScopeToString(cr->resrec.rDNSServer->scopeType) : "" );
15151             cr->resrec.rDNSServer = mDNSNULL;
15152             mDNS_PurgeCacheResourceRecord(m, cr);
15153         }
15154     }
15155 
15156     //  Delete all the DNS servers that are flagged for deletion
15157     while (*p)
15158     {
15159         if (((*p)->flags & DNSServerFlag_Delete) != 0)
15160         {
15161             ptr = *p;
15162             *p = (*p)->next;
15163             LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s)", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c);
15164             mDNSPlatformMemFree(ptr);
15165         }
15166         else
15167         {
15168             p = &(*p)->next;
15169         }
15170     }
15171     LogInfo("uDNS_SetupDNSConfig: CountOfUnicastDNSServers %d", CountOfUnicastDNSServers(m));
15172 
15173     // 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).
15174     // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
15175     // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
15176     // 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.
15177     if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
15178     {
15179         int count = 0;
15180         FORALL_CACHERECORDS(slot, cg, cr)
15181         {
15182             if (!cr->resrec.InterfaceID)
15183             {
15184                 mDNS_PurgeCacheResourceRecord(m, cr);
15185                 count++;
15186             }
15187         }
15188         LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
15189                 m->DNSServers ? "DNS server became" : "No DNS servers", count);
15190 
15191         // Force anything that needs to get zone data to get that information again
15192         RestartRecordGetZoneData(m);
15193     }
15194 #endif // !MDNSRESPONDER_SUPPORTS(APPLE, QUERIER)
15195 
15196     SetDynDNSHostNameIfChanged(m, &fqdn);
15197 
15198     mDNS_Unlock(m);
15199 
15200     // handle router and primary interface changes
15201     v4 = v6 = r = zeroAddr;
15202     v4.type = r.type = mDNSAddrType_IPv4;
15203 
15204     if (mDNSPlatformGetPrimaryInterface(&v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
15205     {
15206         mDNS_SetPrimaryInterfaceInfo(m,
15207                                      !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
15208                                      !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
15209                                      !mDNSIPv4AddressIsZero(r.ip.v4) ? &r  : mDNSNULL);
15210     }
15211     else
15212     {
15213         mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
15214         if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
15215     }
15216 
15217     debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", CountOfUnicastDNSServers(m));
15218     return mStatus_NoError;
15219 }
15220 
15221 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
15222 {
15223     m->mDNSPlatformStatus = result;
15224     if (m->MainCallback)
15225     {
15226         mDNS_Lock(m);
15227         mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
15228         m->MainCallback(m, mStatus_NoError);
15229         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
15230         mDNS_Unlock(m);
15231     }
15232 }
15233 
15234 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
15235 {
15236     m->CurrentRecord = start;
15237     while (m->CurrentRecord)
15238     {
15239         AuthRecord *rr = m->CurrentRecord;
15240         LogInfo("DeregLoop: %s deregistration for %p %02X %s",
15241                 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating  " : "Accelerating",
15242                 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15243         if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
15244             mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
15245         else if (rr->AnnounceCount > 1)
15246         {
15247             rr->AnnounceCount = 1;
15248             rr->LastAPTime = m->timenow - rr->ThisAPInterval;
15249         }
15250         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15251         // new records could have been added to the end of the list as a result of that call.
15252         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
15253             m->CurrentRecord = rr->next;
15254     }
15255 }
15256 
15257 mDNSexport void mDNS_StartExit(mDNS *const m)
15258 {
15259     AuthRecord *rr;
15260 
15261     mDNS_Lock(m);
15262 
15263     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit");
15264     m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
15265 
15266     mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
15267 
15268 #if MDNSRESPONDER_SUPPORTS(APPLE, WEB_CONTENT_FILTER)
15269     if (WCFConnectionDealloc)
15270     {
15271         if (m->WCF)
15272         {
15273             WCFConnectionDealloc(m->WCF);
15274             m->WCF = mDNSNULL;
15275         }
15276     }
15277 #endif
15278 
15279 #ifndef UNICAST_DISABLED
15280     {
15281         SearchListElem *s;
15282         SuspendLLQs(m);
15283         // Don't need to do SleepRecordRegistrations() here
15284         // because we deregister all records and services later in this routine
15285         while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
15286 
15287         // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15288         // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15289         // and we may crash because the list still contains dangling pointers.
15290         for (s = SearchList; s; s = s->next)
15291             while (s->AuthRecs)
15292             {
15293                 ARListElem *dereg = s->AuthRecs;
15294                 s->AuthRecs = s->AuthRecs->next;
15295                 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
15296             }
15297     }
15298 #endif
15299 
15300     DeadvertiseAllInterfaceRecords(m, kDeadvertiseFlag_All);
15301 
15302     // Shut down all our active NAT Traversals
15303     while (m->NATTraversals)
15304     {
15305         NATTraversalInfo *t = m->NATTraversals;
15306         mDNS_StopNATOperation_internal(m, t);       // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15307 
15308         // After stopping the NAT Traversal, we zero out the fields.
15309         // This has particularly important implications for our AutoTunnel records --
15310         // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15311         // handlers to just turn around and attempt to re-register those same records.
15312         // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15313         // to not do this.
15314         t->ExternalAddress = zerov4Addr;
15315         t->NewAddress      = zerov4Addr;
15316         t->ExternalPort    = zeroIPPort;
15317         t->RequestedPort   = zeroIPPort;
15318         t->Lifetime        = 0;
15319         t->Result          = mStatus_NoError;
15320     }
15321 
15322     // Make sure there are nothing but deregistering records remaining in the list
15323     if (m->CurrentRecord)
15324     {
15325         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
15326             "mDNS_StartExit: ERROR m->CurrentRecord already set " PRI_S, ARDisplayString(m, m->CurrentRecord));
15327     }
15328 
15329     // We're in the process of shutting down, so queries, etc. are no longer available.
15330     // Consequently, determining certain information, e.g. the uDNS update server's IP
15331     // address, will not be possible.  The records on the main list are more likely to
15332     // already contain such information, so we deregister the duplicate records first.
15333     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering duplicate resource records");
15334     DeregLoop(m, m->DuplicateRecords);
15335     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Deregistering resource records");
15336     DeregLoop(m, m->ResourceRecords);
15337 
15338     // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15339     // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15340     if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
15341     {
15342         m->NextScheduledResponse = m->timenow;
15343         m->SuppressSending = 0;
15344     }
15345 
15346     if (m->ResourceRecords)
15347     {
15348         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: Sending final record deregistrations");
15349     }
15350     else
15351     {
15352         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: No deregistering records remain");
15353     }
15354 
15355     for (rr = m->DuplicateRecords; rr; rr = rr->next)
15356     {
15357         LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT,
15358             "mDNS_StartExit: Should not still have Duplicate Records remaining: %02X " PRI_S,
15359             rr->resrec.RecordType, ARDisplayString(m, rr));
15360     }
15361 
15362     // If any deregistering records remain, send their deregistration announcements before we exit
15363     if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
15364 
15365     mDNS_Unlock(m);
15366 
15367     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_StartExit: done");
15368 }
15369 
15370 mDNSexport void mDNS_FinalExit(mDNS *const m)
15371 {
15372     mDNSu32 rrcache_active = 0;
15373     mDNSu32 rrcache_totalused = m->rrcache_totalused;
15374     mDNSu32 slot;
15375     AuthRecord *rr;
15376 
15377     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: mDNSPlatformClose");
15378     mDNSPlatformClose(m);
15379 
15380     for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
15381     {
15382         while (m->rrcache_hash[slot])
15383         {
15384             CacheGroup *cg = m->rrcache_hash[slot];
15385             while (cg->members)
15386             {
15387                 CacheRecord *cr = cg->members;
15388                 cg->members = cg->members->next;
15389                 if (cr->CRActiveQuestion) rrcache_active++;
15390                 ReleaseCacheRecord(m, cr);
15391             }
15392             cg->rrcache_tail = &cg->members;
15393             ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
15394         }
15395     }
15396     debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
15397     if (rrcache_active != m->rrcache_active)
15398         LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused, rrcache_active, m->rrcache_active);
15399 
15400     for (rr = m->ResourceRecords; rr; rr = rr->next)
15401         LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15402 
15403 #if MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
15404     uninit_trust_anchors();
15405 #endif // MDNSRESPONDER_SUPPORTS(APPLE, DNSSECv2)
15406 
15407     LogRedact(MDNS_LOG_CATEGORY_DEFAULT, MDNS_LOG_DEFAULT, "mDNS_FinalExit: done");
15408 }
15409 
15410 #ifdef UNIT_TEST
15411 #include "../unittests/mdns_ut.c"
15412 #endif
15413