xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSCore/mDNS.c (revision cda73f64f20b8a0afc4909f5ea1f055ec7913856)
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2002-2015 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 #include "nsec.h"
29 #include "dnssec.h"
30 #include "anonymous.h"
31 
32 // Disable certain benign warnings with Microsoft compilers
33 #if (defined(_MSC_VER))
34 // Disable "conditional expression is constant" warning for debug macros.
35 // Otherwise, this generates warnings for the perfectly natural construct "while(1)"
36 // If someone knows a variant way of writing "while(1)" that doesn't generate warning messages, please let us know
37     #pragma warning(disable:4127)
38 
39 // Disable "assignment within conditional expression".
40 // Other compilers understand the convention that if you place the assignment expression within an extra pair
41 // of parentheses, this signals to the compiler that you really intended an assignment and no warning is necessary.
42 // The Microsoft compiler doesn't understand this convention, so in the absense of any other way to signal
43 // to the compiler that the assignment is intentional, we have to just turn this warning off completely.
44     #pragma warning(disable:4706)
45 #endif
46 
47 #include "dns_sd.h" // for kDNSServiceFlags* definitions
48 
49 #if APPLE_OSX_mDNSResponder
50 #include <WebFilterDNS/WebFilterDNS.h>
51 
52 #if !NO_WCF
53 WCFConnection *WCFConnectionNew(void) __attribute__((weak_import));
54 void WCFConnectionDealloc(WCFConnection* c) __attribute__((weak_import));
55 
56 // Do we really need to define a macro for "if"?
57 #define CHECK_WCF_FUNCTION(X) if (X)
58 #endif // ! NO_WCF
59 
60 #else
61 
62 #define NO_WCF 1
63 #endif // APPLE_OSX_mDNSResponder
64 
65 #if TARGET_OS_EMBEDDED
66 #include "Metrics.h"
67 #endif
68 
69 // Forward declarations
70 mDNSlocal void BeginSleepProcessing(mDNS *const m);
71 mDNSlocal void RetrySPSRegistrations(mDNS *const m);
72 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password);
73 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
74 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q);
75 mDNSlocal void mDNS_PurgeForQuestion(mDNS *const m, DNSQuestion *q);
76 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q);
77 mDNSlocal void mDNS_SendKeepalives(mDNS *const m);
78 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth,
79                                          mDNSu32 *seq, mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win);
80 
81 mDNSlocal void AdvertiseAllInterfaceRecords(mDNS *const m);
82 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m);
83 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords);
84 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
85                                         const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records);
86 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth);
87 
88 
89 // ***************************************************************************
90 #if COMPILER_LIKES_PRAGMA_MARK
91 #pragma mark - Program Constants
92 #endif
93 
94 // To Turn OFF mDNS_Tracer set MDNS_TRACER to 0 or undef it
95 #define MDNS_TRACER 1
96 
97 #define NO_HINFO 1
98 
99 // Any records bigger than this are considered 'large' records
100 #define SmallRecordLimit 1024
101 
102 #define kMaxUpdateCredits 10
103 #define kUpdateCreditRefreshInterval (mDNSPlatformOneSecond * 6)
104 
105 // define special NR_AnswerTo values
106 #define NR_AnswerMulticast  (mDNSu8*)~0
107 #define NR_AnswerUnicast    (mDNSu8*)~1
108 
109 // Defined to set the kDNSQClass_UnicastResponse bit in the first four query packets.
110 // else, it's just set it the first query.
111 #define mDNS_REQUEST_UNICAST_RESPONSE 0
112 
113 // The code (see SendQueries() and BuildQuestion()) needs to have the
114 // RequestUnicast value set to a value one greater than the number of times you want the query
115 // sent with the "request unicast response" (QU) bit set.
116 #define SET_QU_IN_FIRST_QUERY   2
117 #define SET_QU_IN_FIRST_FOUR_QUERIES   5
118 
119 
120 mDNSexport const char *const mDNS_DomainTypeNames[] =
121 {
122     "b._dns-sd._udp.",      // Browse
123     "db._dns-sd._udp.",     // Default Browse
124     "lb._dns-sd._udp.",     // Automatic Browse
125     "r._dns-sd._udp.",      // Registration
126     "dr._dns-sd._udp."      // Default Registration
127 };
128 
129 #ifdef UNICAST_DISABLED
130 #define uDNS_IsActiveQuery(q, u) mDNSfalse
131 #endif
132 
133 // ***************************************************************************
134 #if COMPILER_LIKES_PRAGMA_MARK
135 #pragma mark -
136 #pragma mark - General Utility Functions
137 #endif
138 
139 // Returns true if this is a  unique, authoritative LocalOnly record that answers questions of type
140 // A, AAAA , CNAME, or PTR.  The caller should answer the question with this record and not send out
141 // the question on the wire if LocalOnlyRecordAnswersQuestion() also returns true.
142 // Main use is to handle /etc/hosts records and the LocalOnly PTR records created for localhost.
143 #define UniqueLocalOnlyRecord(rr) ((rr)->ARType == AuthRecordLocalOnly && \
144                                         (rr)->resrec.RecordType & kDNSRecordTypeUniqueMask && \
145                                         ((rr)->resrec.rrtype == kDNSType_A || (rr)->resrec.rrtype == kDNSType_AAAA || \
146                                          (rr)->resrec.rrtype == kDNSType_CNAME || \
147                                          (rr)->resrec.rrtype == kDNSType_PTR))
148 
149 mDNSlocal void SetNextQueryStopTime(mDNS *const m, const DNSQuestion *const q)
150 {
151     mDNS_CheckLock(m);
152 
153     if (m->NextScheduledStopTime - q->StopTime > 0)
154         m->NextScheduledStopTime = q->StopTime;
155 }
156 
157 mDNSexport void SetNextQueryTime(mDNS *const m, const DNSQuestion *const q)
158 {
159     mDNS_CheckLock(m);
160 
161     if (ActiveQuestion(q))
162     {
163         // Depending on whether this is a multicast or unicast question we want to set either:
164         // m->NextScheduledQuery = NextQSendTime(q) or
165         // m->NextuDNSEvent      = NextQSendTime(q)
166         mDNSs32 *const timer = mDNSOpaque16IsZero(q->TargetQID) ? &m->NextScheduledQuery : &m->NextuDNSEvent;
167         if (*timer - NextQSendTime(q) > 0)
168             *timer = NextQSendTime(q);
169     }
170 }
171 
172 mDNSlocal void ReleaseAuthEntity(AuthHash *r, AuthEntity *e)
173 {
174 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
175     unsigned int i;
176     for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
177 #endif
178     e->next = r->rrauth_free;
179     r->rrauth_free = e;
180     r->rrauth_totalused--;
181 }
182 
183 mDNSlocal void ReleaseAuthGroup(AuthHash *r, AuthGroup **cp)
184 {
185     AuthEntity *e = (AuthEntity *)(*cp);
186     LogMsg("ReleaseAuthGroup:  Releasing AuthGroup %##s", (*cp)->name->c);
187     if ((*cp)->rrauth_tail != &(*cp)->members)
188         LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrauth_tail != &(*cp)->members)");
189     if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
190     (*cp)->name = mDNSNULL;
191     *cp = (*cp)->next;          // Cut record from list
192     ReleaseAuthEntity(r, e);
193 }
194 
195 mDNSlocal AuthEntity *GetAuthEntity(AuthHash *r, const AuthGroup *const PreserveAG)
196 {
197     AuthEntity *e = mDNSNULL;
198 
199     if (r->rrauth_lock) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
200     r->rrauth_lock = 1;
201 
202     if (!r->rrauth_free)
203     {
204         // We allocate just one AuthEntity at a time because we need to be able
205         // free them all individually which normally happens when we parse /etc/hosts into
206         // AuthHash where we add the "new" entries and discard (free) the already added
207         // entries. If we allocate as chunks, we can't free them individually.
208         AuthEntity *storage = mDNSPlatformMemAllocate(sizeof(AuthEntity));
209         storage->next = mDNSNULL;
210         r->rrauth_free = storage;
211     }
212 
213     // If we still have no free records, recycle all the records we can.
214     // Enumerating the entire auth is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
215     if (!r->rrauth_free)
216     {
217         mDNSu32 oldtotalused = r->rrauth_totalused;
218         mDNSu32 slot;
219         for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
220         {
221             AuthGroup **cp = &r->rrauth_hash[slot];
222             while (*cp)
223             {
224                 if ((*cp)->members || (*cp)==PreserveAG) cp=&(*cp)->next;
225                 else ReleaseAuthGroup(r, cp);
226             }
227         }
228         LogInfo("GetAuthEntity: Recycled %d records to reduce auth cache from %d to %d",
229                 oldtotalused - r->rrauth_totalused, oldtotalused, r->rrauth_totalused);
230     }
231 
232     if (r->rrauth_free) // If there are records in the free list, take one
233     {
234         e = r->rrauth_free;
235         r->rrauth_free = e->next;
236         if (++r->rrauth_totalused >= r->rrauth_report)
237         {
238             LogInfo("RR Auth now using %ld objects", r->rrauth_totalused);
239             if      (r->rrauth_report <  100) r->rrauth_report += 10;
240             else if (r->rrauth_report < 1000) r->rrauth_report += 100;
241             else r->rrauth_report += 1000;
242         }
243         mDNSPlatformMemZero(e, sizeof(*e));
244     }
245 
246     r->rrauth_lock = 0;
247 
248     return(e);
249 }
250 
251 mDNSexport AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
252 {
253     AuthGroup *ag;
254     for (ag = r->rrauth_hash[slot]; ag; ag=ag->next)
255         if (ag->namehash == namehash && SameDomainName(ag->name, name))
256             break;
257     return(ag);
258 }
259 
260 mDNSexport AuthGroup *AuthGroupForRecord(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
261 {
262     return(AuthGroupForName(r, slot, rr->namehash, rr->name));
263 }
264 
265 mDNSlocal AuthGroup *GetAuthGroup(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr)
266 {
267     mDNSu16 namelen = DomainNameLength(rr->name);
268     AuthGroup *ag = (AuthGroup*)GetAuthEntity(r, mDNSNULL);
269     if (!ag) { LogMsg("GetAuthGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
270     ag->next         = r->rrauth_hash[slot];
271     ag->namehash     = rr->namehash;
272     ag->members      = mDNSNULL;
273     ag->rrauth_tail  = &ag->members;
274     ag->NewLocalOnlyRecords = mDNSNULL;
275     if (namelen > sizeof(ag->namestorage))
276         ag->name = mDNSPlatformMemAllocate(namelen);
277     else
278         ag->name = (domainname*)ag->namestorage;
279     if (!ag->name)
280     {
281         LogMsg("GetAuthGroup: Failed to allocate name storage for %##s", rr->name->c);
282         ReleaseAuthEntity(r, (AuthEntity*)ag);
283         return(mDNSNULL);
284     }
285     AssignDomainName(ag->name, rr->name);
286 
287     if (AuthGroupForRecord(r, slot, rr)) LogMsg("GetAuthGroup: Already have AuthGroup for %##s", rr->name->c);
288     r->rrauth_hash[slot] = ag;
289     if (AuthGroupForRecord(r, slot, rr) != ag) LogMsg("GetAuthGroup: Not finding AuthGroup for %##s", rr->name->c);
290 
291     return(ag);
292 }
293 
294 // Returns the AuthGroup in which the AuthRecord was inserted
295 mDNSexport AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
296 {
297     AuthGroup *ag;
298     const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
299     ag = AuthGroupForRecord(r, slot, &rr->resrec);
300     if (!ag) ag = GetAuthGroup(r, slot, &rr->resrec);   // If we don't have a AuthGroup for this name, make one now
301     if (ag)
302     {
303         LogInfo("InsertAuthRecord: inserting auth record %s from table", ARDisplayString(m, rr));
304         *(ag->rrauth_tail) = rr;                // Append this record to tail of cache slot list
305         ag->rrauth_tail = &(rr->next);          // Advance tail pointer
306     }
307     return ag;
308 }
309 
310 mDNSexport AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr)
311 {
312     AuthGroup *a;
313     AuthGroup **ag = &a;
314     AuthRecord **rp;
315     const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
316 
317     a = AuthGroupForRecord(r, slot, &rr->resrec);
318     if (!a) { LogMsg("RemoveAuthRecord: ERROR!! AuthGroup not found for %s", ARDisplayString(m, rr)); return mDNSNULL; }
319     rp = &(*ag)->members;
320     while (*rp)
321     {
322         if (*rp != rr)
323             rp=&(*rp)->next;
324         else
325         {
326             // We don't break here, so that we can set the tail below without tracking "prev" pointers
327 
328             LogInfo("RemoveAuthRecord: removing auth record %s from table", ARDisplayString(m, rr));
329             *rp = (*rp)->next;          // Cut record from list
330         }
331     }
332     // TBD: If there are no more members, release authgroup ?
333     (*ag)->rrauth_tail = rp;
334     return a;
335 }
336 
337 mDNSexport CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name)
338 {
339     CacheGroup *cg;
340     for (cg = m->rrcache_hash[slot]; cg; cg=cg->next)
341         if (cg->namehash == namehash && SameDomainName(cg->name, name))
342             break;
343     return(cg);
344 }
345 
346 mDNSlocal CacheGroup *CacheGroupForRecord(const mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
347 {
348     return(CacheGroupForName(m, slot, rr->namehash, rr->name));
349 }
350 
351 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
352 {
353     NetworkInterfaceInfo *intf;
354 
355     if (addr->type == mDNSAddrType_IPv4)
356     {
357         // Normally we resist touching the NotAnInteger fields, but here we're doing tricky bitwise masking so we make an exception
358         if (mDNSv4AddressIsLinkLocal(&addr->ip.v4)) return(mDNStrue);
359         for (intf = m->HostInterfaces; intf; intf = intf->next)
360             if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
361                 if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
362                     return(mDNStrue);
363     }
364 
365     if (addr->type == mDNSAddrType_IPv6)
366     {
367         if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue);
368         for (intf = m->HostInterfaces; intf; intf = intf->next)
369             if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
370                 if ((((intf->ip.ip.v6.l[0] ^ addr->ip.v6.l[0]) & intf->mask.ip.v6.l[0]) == 0) &&
371                     (((intf->ip.ip.v6.l[1] ^ addr->ip.v6.l[1]) & intf->mask.ip.v6.l[1]) == 0) &&
372                     (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
373                     (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
374                         return(mDNStrue);
375     }
376 
377     return(mDNSfalse);
378 }
379 
380 mDNSlocal NetworkInterfaceInfo *FirstInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
381 {
382     NetworkInterfaceInfo *intf = m->HostInterfaces;
383     while (intf && intf->InterfaceID != InterfaceID) intf = intf->next;
384     return(intf);
385 }
386 
387 mDNSlocal NetworkInterfaceInfo *FirstIPv4LLInterfaceForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
388 {
389     NetworkInterfaceInfo *intf;
390 
391     if (!InterfaceID)
392         return mDNSNULL;
393 
394     // Note: We don't check for InterfaceActive, as the active interface could be IPv6 and
395     // we still want to find the first IPv4 Link-Local interface
396     for (intf = m->HostInterfaces; intf; intf = intf->next)
397     {
398         if (intf->InterfaceID == InterfaceID &&
399             intf->ip.type == mDNSAddrType_IPv4 && mDNSv4AddressIsLinkLocal(&intf->ip.ip.v4))
400         {
401             debugf("FirstIPv4LLInterfaceForID: found LL interface with address %.4a", &intf->ip.ip.v4);
402             return intf;
403         }
404     }
405     return (mDNSNULL);
406 }
407 
408 mDNSexport char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID)
409 {
410     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
411     return(intf ? intf->ifname : mDNSNULL);
412 }
413 
414 // Caller should hold the lock
415 mDNSlocal void GenerateNegativeResponse(mDNS *const m, QC_result qc)
416 {
417     DNSQuestion *q;
418     if (!m->CurrentQuestion) { LogMsg("GenerateNegativeResponse: ERROR!! CurrentQuestion not set"); return; }
419     q = m->CurrentQuestion;
420     LogInfo("GenerateNegativeResponse: Generating negative response for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
421 
422     MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, mDNSNULL);
423     // We need to force the response through in the following cases
424     //
425     //  a) SuppressUnusable questions that are suppressed
426     //  b) Append search domains and retry the question
427     //
428     // The question may not have set Intermediates in which case we don't deliver negative responses. So, to force
429     // through we use "QC_forceresponse".
430     AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, qc);
431     if (m->CurrentQuestion == q) { q->ThisQInterval = 0; }              // Deactivate this question
432     // Don't touch the question after this
433     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
434 }
435 
436 mDNSexport void AnswerQuestionByFollowingCNAME(mDNS *const m, DNSQuestion *q, ResourceRecord *rr)
437 {
438     const mDNSBool selfref = SameDomainName(&q->qname, &rr->rdata->u.name);
439     if (q->CNAMEReferrals >= 10 || selfref)
440     {
441         LogMsg("AnswerQuestionByFollowingCNAME: %p %##s (%s) NOT following CNAME referral %d%s for %s",
442                q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, selfref ? " (Self-Referential)" : "", RRDisplayString(m, rr));
443     }
444     else
445     {
446         const mDNSu32 c = q->CNAMEReferrals + 1;        // Stash a copy of the new q->CNAMEReferrals value
447         UDPSocket *sock = q->LocalSocket;
448         mDNSOpaque16 id = q->TargetQID;
449 #if TARGET_OS_EMBEDDED
450         domainname *originalQName;
451 #endif
452 
453         // if there is a message waiting at the socket, we want to process that instead
454         // of throwing it away. If we have a CNAME response that answers
455         // both A and AAAA question and while answering it we don't want to throw
456         // away the response where the actual addresses are present.
457         // This is a stupid hack and we should get rid of it.
458         // The chance of there being a second unicast UDP packet already waiting in the kernel before we’ve
459         // finished processing the previous one is virtually nil, and will only happen by luck on very rare
460         // occasions when running on a machine with a fast network connection and a slow or busy processor.
461         // The idea that we’d rely for correctness on this random chance event occurring is ridiculous.
462         // -- SC
463         if (mDNSPlatformPeekUDP(m, q->LocalSocket))
464         {
465             LogInfo("AnswerQuestionByFollowingCNAME: Preserving UDP socket for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
466             q->LocalSocket = mDNSNULL;
467         }
468         else
469         {
470             sock = mDNSNULL;
471         }
472 
473         // The SameDomainName check above is to ignore bogus CNAME records that point right back at
474         // themselves. Without that check we can get into a case where we have two duplicate questions,
475         // A and B, and when we stop question A, UpdateQuestionDuplicates copies the value of CNAMEReferrals
476         // from A to B, and then A is re-appended to the end of the list as a duplicate of B (because
477         // the target name is still the same), and then when we stop question B, UpdateQuestionDuplicates
478         // copies the B's value of CNAMEReferrals back to A, and we end up not incrementing CNAMEReferrals
479         // for either of them. This is not a problem for CNAME loops of two or more records because in
480         // those cases the newly re-appended question A has a different target name and therefore cannot be
481         // a duplicate of any other question ('B') which was itself a duplicate of the previous question A.
482 
483         // Right now we just stop and re-use the existing query. If we really wanted to be 100% perfect,
484         // and track CNAMEs coming and going, we should really create a subordinate query here,
485         // which we would subsequently cancel and retract if the CNAME referral record were removed.
486         // In reality this is such a corner case we'll ignore it until someone actually needs it.
487 
488         LogInfo("AnswerQuestionByFollowingCNAME: %p %##s (%s) following CNAME referral %d for %s",
489                 q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, RRDisplayString(m, rr));
490 
491 #if TARGET_OS_EMBEDDED
492         if (q->metrics.originalQName)
493         {
494             originalQName            = q->metrics.originalQName;
495             q->metrics.originalQName = mDNSNULL;
496         }
497         else
498         {
499             mDNSu16 qNameLen;
500 
501             qNameLen = DomainNameLength(&q->qname);
502             if ((qNameLen > 0) && (qNameLen <= MAX_DOMAIN_NAME))
503             {
504                 originalQName = mDNSPlatformMemAllocate(qNameLen);
505                 if (originalQName)
506                 {
507                     mDNSPlatformMemCopy(originalQName->c, q->qname.c, qNameLen);
508                 }
509             }
510             else
511             {
512                 originalQName = mDNSNULL;
513             }
514         }
515 #endif
516         mDNS_StopQuery_internal(m, q);                              // Stop old query
517         AssignDomainName(&q->qname, &rr->rdata->u.name);            // Update qname
518         q->qnamehash = DomainNameHashValue(&q->qname);              // and namehash
519         // If a unicast query results in a CNAME that points to a .local, we need to re-try
520         // this as unicast. Setting the mDNSInterface_Unicast tells mDNS_StartQuery_internal
521         // to try this as unicast query even though it is a .local name
522         if (!mDNSOpaque16IsZero(q->TargetQID) && IsLocalDomain(&q->qname))
523         {
524             LogInfo("AnswerQuestionByFollowingCNAME: Resolving a .local CNAME %p %##s (%s) Record %s",
525                     q, q->qname.c, DNSTypeName(q->qtype), RRDisplayString(m, rr));
526             q->InterfaceID = mDNSInterface_Unicast;
527         }
528         mDNS_StartQuery_internal(m, q);                             // start new query
529         // Record how many times we've done this. We need to do this *after* mDNS_StartQuery_internal,
530         // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
531         q->CNAMEReferrals = c;
532 #if TARGET_OS_EMBEDDED
533         q->metrics.originalQName = originalQName;
534 #endif
535         if (sock)
536         {
537             // We have a message waiting and that should answer this question.
538             if (q->LocalSocket)
539                 mDNSPlatformUDPClose(q->LocalSocket);
540             q->LocalSocket = sock;
541             q->TargetQID = id;
542         }
543     }
544 }
545 
546 // For a single given DNSQuestion pointed to by CurrentQuestion, deliver an add/remove result for the single given AuthRecord
547 // Note: All the callers should use the m->CurrentQuestion to see if the question is still valid or not
548 mDNSlocal void AnswerLocalQuestionWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
549 {
550     DNSQuestion *q = m->CurrentQuestion;
551     mDNSBool followcname;
552 
553     if (!q)
554     {
555         LogMsg("AnswerLocalQuestionWithLocalAuthRecord: ERROR!! CurrentQuestion NULL while answering with %s", ARDisplayString(m, rr));
556         return;
557     }
558 
559     followcname = FollowCNAME(q, &rr->resrec, AddRecord);
560 
561     // We should not be delivering results for record types Unregistered, Deregistering, and (unverified) Unique
562     if (!(rr->resrec.RecordType & kDNSRecordTypeActiveMask))
563     {
564         LogMsg("AnswerLocalQuestionWithLocalAuthRecord: *NOT* delivering %s event for local record type %X %s",
565                AddRecord ? "Add" : "Rmv", rr->resrec.RecordType, ARDisplayString(m, rr));
566         return;
567     }
568 
569     // Indicate that we've given at least one positive answer for this record, so we should be prepared to send a goodbye for it
570     if (AddRecord) rr->AnsweredLocalQ = mDNStrue;
571     mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
572     if (q->QuestionCallback && !q->NoAnswer)
573     {
574         q->CurrentAnswers += AddRecord ? 1 : -1;
575         if (UniqueLocalOnlyRecord(rr))
576         {
577             if (!followcname || q->ReturnIntermed)
578             {
579                 // Don't send this packet on the wire as we answered from /etc/hosts
580                 q->ThisQInterval = 0;
581                 q->LOAddressAnswers += AddRecord ? 1 : -1;
582                 q->QuestionCallback(m, q, &rr->resrec, AddRecord);
583             }
584             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
585             // The callback above could have caused the question to stop. Detect that
586             // using m->CurrentQuestion
587             if (followcname && m->CurrentQuestion == q)
588                 AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
589             return;
590         }
591         else
592         {
593             q->QuestionCallback(m, q, &rr->resrec, AddRecord);
594         }
595     }
596     mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
597 }
598 
599 mDNSlocal void AnswerInterfaceAnyQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
600 {
601     if (m->CurrentQuestion)
602         LogMsg("AnswerInterfaceAnyQuestionsWithLocalAuthRecord: ERROR m->CurrentQuestion already set: %##s (%s)",
603                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
604     m->CurrentQuestion = m->Questions;
605     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
606     {
607         mDNSBool answered;
608         DNSQuestion *q = m->CurrentQuestion;
609         if (RRAny(rr))
610             answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
611         else
612             answered = LocalOnlyRecordAnswersQuestion(rr, q);
613         if (answered)
614             AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord);       // MUST NOT dereference q again
615         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
616             m->CurrentQuestion = q->next;
617     }
618     m->CurrentQuestion = mDNSNULL;
619 }
620 
621 // When a new local AuthRecord is created or deleted, AnswerAllLocalQuestionsWithLocalAuthRecord()
622 // delivers the appropriate add/remove events to listening questions:
623 // 1. It runs though all our LocalOnlyQuestions delivering answers as appropriate,
624 //    stopping if it reaches a NewLocalOnlyQuestion -- brand-new questions are handled by AnswerNewLocalOnlyQuestion().
625 // 2. If the AuthRecord is marked mDNSInterface_LocalOnly or mDNSInterface_P2P, then it also runs though
626 //    our main question list, delivering answers to mDNSInterface_Any questions as appropriate,
627 //    stopping if it reaches a NewQuestion -- brand-new questions are handled by AnswerNewQuestion().
628 //
629 // AnswerAllLocalQuestionsWithLocalAuthRecord is used by the m->NewLocalRecords loop in mDNS_Execute(),
630 // and by mDNS_Deregister_internal()
631 
632 mDNSlocal void AnswerAllLocalQuestionsWithLocalAuthRecord(mDNS *const m, AuthRecord *rr, QC_result AddRecord)
633 {
634     if (m->CurrentQuestion)
635         LogMsg("AnswerAllLocalQuestionsWithLocalAuthRecord ERROR m->CurrentQuestion already set: %##s (%s)",
636                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
637 
638     m->CurrentQuestion = m->LocalOnlyQuestions;
639     while (m->CurrentQuestion && m->CurrentQuestion != m->NewLocalOnlyQuestions)
640     {
641         mDNSBool answered;
642         DNSQuestion *q = m->CurrentQuestion;
643         // We are called with both LocalOnly/P2P record or a regular AuthRecord
644         if (RRAny(rr))
645             answered = ResourceRecordAnswersQuestion(&rr->resrec, q);
646         else
647             answered = LocalOnlyRecordAnswersQuestion(rr, q);
648         if (answered)
649             AnswerLocalQuestionWithLocalAuthRecord(m, rr, AddRecord);           // MUST NOT dereference q again
650         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
651             m->CurrentQuestion = q->next;
652     }
653 
654     m->CurrentQuestion = mDNSNULL;
655 
656     // If this AuthRecord is marked LocalOnly or P2P, then we want to deliver it to all local 'mDNSInterface_Any' questions
657     if (rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P)
658         AnswerInterfaceAnyQuestionsWithLocalAuthRecord(m, rr, AddRecord);
659 
660 }
661 
662 // ***************************************************************************
663 #if COMPILER_LIKES_PRAGMA_MARK
664 #pragma mark -
665 #pragma mark - Resource Record Utility Functions
666 #endif
667 
668 #define RRTypeIsAddressType(T) ((T) == kDNSType_A || (T) == kDNSType_AAAA)
669 
670 #define ResourceRecordIsValidAnswer(RR) ( ((RR)->resrec.RecordType & kDNSRecordTypeActiveMask)  && \
671                                           ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
672                                           ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->resrec.RecordType & kDNSRecordTypeActiveMask)) && \
673                                           ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->resrec.RecordType & kDNSRecordTypeActiveMask))  )
674 
675 #define ResourceRecordIsValidInterfaceAnswer(RR, INTID) \
676     (ResourceRecordIsValidAnswer(RR) && \
677      ((RR)->resrec.InterfaceID == mDNSInterface_Any || (RR)->resrec.InterfaceID == (INTID)))
678 
679 #define DefaultProbeCountForTypeUnique ((mDNSu8)3)
680 #define DefaultProbeCountForRecordType(X)      ((X) == kDNSRecordTypeUnique ? DefaultProbeCountForTypeUnique : (mDNSu8)0)
681 
682 // See RFC 6762: "8.3 Announcing"
683 // "The Multicast DNS responder MUST send at least two unsolicited responses, one second apart."
684 // Send 4, which is really 8 since we send on both IPv4 and IPv6.
685 #define InitialAnnounceCount ((mDNSu8)4)
686 
687 // For goodbye packets we set the count to 3, and for wakeups we set it to 18
688 // (which will be up to 15 wakeup attempts over the course of 30 seconds,
689 // and then if the machine fails to wake, 3 goodbye packets).
690 #define GoodbyeCount ((mDNSu8)3)
691 #define WakeupCount ((mDNSu8)18)
692 #define MAX_PROBE_RESTARTS ((mDNSu8)20)
693 
694 // Number of wakeups we send if WakeOnResolve is set in the question
695 #define InitialWakeOnResolveCount ((mDNSu8)3)
696 
697 // Note that the announce intervals use exponential backoff, doubling each time. The probe intervals do not.
698 // This means that because the announce interval is doubled after sending the first packet, the first
699 // observed on-the-wire inter-packet interval between announcements is actually one second.
700 // The half-second value here may be thought of as a conceptual (non-existent) half-second delay *before* the first packet is sent.
701 #define DefaultProbeIntervalForTypeUnique (mDNSPlatformOneSecond/4)
702 #define DefaultAnnounceIntervalForTypeShared (mDNSPlatformOneSecond/2)
703 #define DefaultAnnounceIntervalForTypeUnique (mDNSPlatformOneSecond/2)
704 
705 #define DefaultAPIntervalForRecordType(X)  ((X) &kDNSRecordTypeActiveSharedMask ? DefaultAnnounceIntervalForTypeShared : \
706                                             (X) &kDNSRecordTypeUnique           ? DefaultProbeIntervalForTypeUnique    : \
707                                             (X) &kDNSRecordTypeActiveUniqueMask ? DefaultAnnounceIntervalForTypeUnique : 0)
708 
709 #define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && (time) - ((RR)->LastAPTime + (RR)->ThisAPInterval) >= 0)
710 #define TimeToSendThisRecord(RR,time) ((TimeToAnnounceThisRecord(RR,time) || (RR)->ImmedAnswer) && ResourceRecordIsValidAnswer(RR))
711 #define TicksTTL(RR) ((mDNSs32)(RR)->resrec.rroriginalttl * mDNSPlatformOneSecond)
712 #define RRExpireTime(RR) ((RR)->TimeRcvd + TicksTTL(RR))
713 
714 // Adjustment factor to avoid race condition (used for unicast cache entries) :
715 // 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.
716 // If we do our normal refresh at 80% of the TTL, our local caching server will return 20 seconds, so we'll do another
717 // 80% refresh after 16 seconds, and then the server will return 4 seconds, and so on, in the fashion of Zeno's paradox.
718 // To avoid this, we extend the record's effective TTL to give it a little extra grace period.
719 // We adjust the 100 second TTL to 127. This means that when we do our 80% query at 102 seconds,
720 // the cached copy at our local caching server will already have expired, so the server will be forced
721 // to fetch a fresh copy from the authoritative server, and then return a fresh record with the full TTL of 3600 seconds.
722 
723 #define RRAdjustTTL(ttl) ((ttl) + ((ttl)/4) + 2)
724 #define RRUnadjustedTTL(ttl) ((((ttl) - 2) * 4) / 5)
725 
726 #define MaxUnansweredQueries 4
727 
728 // SameResourceRecordSignature returns true if two resources records have the same name, type, and class, and may be sent
729 // (or were received) on the same interface (i.e. if *both* records specify an interface, then it has to match).
730 // TTL and rdata may differ.
731 // This is used for cache flush management:
732 // When sending a unique record, all other records matching "SameResourceRecordSignature" must also be sent
733 // When receiving a unique record, all old cache records matching "SameResourceRecordSignature" are flushed
734 
735 // SameResourceRecordNameClassInterface is functionally the same as SameResourceRecordSignature, except rrtype does not have to match
736 
737 #define SameResourceRecordSignature(A,B) (A)->resrec.rrtype == (B)->resrec.rrtype && SameResourceRecordNameClassInterface((A),(B))
738 
739 mDNSlocal mDNSBool SameResourceRecordNameClassInterface(const AuthRecord *const r1, const AuthRecord *const r2)
740 {
741     if (!r1) { LogMsg("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
742     if (!r2) { LogMsg("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
743     if (r1->resrec.InterfaceID &&
744         r2->resrec.InterfaceID &&
745         r1->resrec.InterfaceID != r2->resrec.InterfaceID) return(mDNSfalse);
746     return (mDNSBool)(
747                r1->resrec.rrclass  == r2->resrec.rrclass &&
748                r1->resrec.namehash == r2->resrec.namehash &&
749                SameDomainName(r1->resrec.name, r2->resrec.name));
750 }
751 
752 // PacketRRMatchesSignature behaves as SameResourceRecordSignature, except that types may differ if our
753 // authoratative record is unique (as opposed to shared). For unique records, we are supposed to have
754 // complete ownership of *all* types for this name, so *any* record type with the same name is a conflict.
755 // In addition, when probing we send our questions with the wildcard type kDNSQType_ANY,
756 // so a response of any type should match, even if it is not actually the type the client plans to use.
757 
758 // For now, to make it easier to avoid false conflicts, we treat SPS Proxy records like shared records,
759 // and require the rrtypes to match for the rdata to be considered potentially conflicting
760 mDNSlocal mDNSBool PacketRRMatchesSignature(const CacheRecord *const pktrr, const AuthRecord *const authrr)
761 {
762     if (!pktrr)  { LogMsg("PacketRRMatchesSignature ERROR: pktrr is NULL"); return(mDNSfalse); }
763     if (!authrr) { LogMsg("PacketRRMatchesSignature ERROR: authrr is NULL"); return(mDNSfalse); }
764     if (pktrr->resrec.InterfaceID &&
765         authrr->resrec.InterfaceID &&
766         pktrr->resrec.InterfaceID != authrr->resrec.InterfaceID) return(mDNSfalse);
767     if (!(authrr->resrec.RecordType & kDNSRecordTypeUniqueMask) || authrr->WakeUp.HMAC.l[0])
768         if (pktrr->resrec.rrtype != authrr->resrec.rrtype) return(mDNSfalse);
769     return (mDNSBool)(
770                pktrr->resrec.rrclass == authrr->resrec.rrclass &&
771                pktrr->resrec.namehash == authrr->resrec.namehash &&
772                SameDomainName(pktrr->resrec.name, authrr->resrec.name));
773 }
774 
775 // CacheRecord *ka is the CacheRecord from the known answer list in the query.
776 // This is the information that the requester believes to be correct.
777 // AuthRecord *rr is the answer we are proposing to give, if not suppressed.
778 // This is the information that we believe to be correct.
779 // We've already determined that we plan to give this answer on this interface
780 // (either the record is non-specific, or it is specific to this interface)
781 // so now we just need to check the name, type, class, rdata and TTL.
782 mDNSlocal mDNSBool ShouldSuppressKnownAnswer(const CacheRecord *const ka, const AuthRecord *const rr)
783 {
784     // If RR signature is different, or data is different, then don't suppress our answer
785     if (!IdenticalResourceRecord(&ka->resrec, &rr->resrec)) return(mDNSfalse);
786 
787     // If the requester's indicated TTL is less than half the real TTL,
788     // we need to give our answer before the requester's copy expires.
789     // If the requester's indicated TTL is at least half the real TTL,
790     // then we can suppress our answer this time.
791     // If the requester's indicated TTL is greater than the TTL we believe,
792     // then that's okay, and we don't need to do anything about it.
793     // (If two responders on the network are offering the same information,
794     // that's okay, and if they are offering the information with different TTLs,
795     // the one offering the lower TTL should defer to the one offering the higher TTL.)
796     return (mDNSBool)(ka->resrec.rroriginalttl >= rr->resrec.rroriginalttl / 2);
797 }
798 
799 mDNSlocal void SetNextAnnounceProbeTime(mDNS *const m, const AuthRecord *const rr)
800 {
801     if (rr->resrec.RecordType == kDNSRecordTypeUnique)
802     {
803         if ((rr->LastAPTime + rr->ThisAPInterval) - m->timenow > mDNSPlatformOneSecond * 10)
804         {
805             LogMsg("SetNextAnnounceProbeTime: ProbeCount %d Next in %d %s", rr->ProbeCount, (rr->LastAPTime + rr->ThisAPInterval) - m->timenow, ARDisplayString(m, rr));
806             LogMsg("SetNextAnnounceProbeTime: m->SuppressProbes %d m->timenow %d diff %d", m->SuppressProbes, m->timenow, m->SuppressProbes - m->timenow);
807         }
808         if (m->NextScheduledProbe - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
809             m->NextScheduledProbe = (rr->LastAPTime + rr->ThisAPInterval);
810         // Some defensive code:
811         // If (rr->LastAPTime + rr->ThisAPInterval) happens to be far in the past, we don't want to allow
812         // NextScheduledProbe to be set excessively in the past, because that can cause bad things to happen.
813         // See: <rdar://problem/7795434> mDNS: Sometimes advertising stops working and record interval is set to zero
814         if (m->NextScheduledProbe - m->timenow < 0)
815             m->NextScheduledProbe = m->timenow;
816     }
817     else if (rr->AnnounceCount && (ResourceRecordIsValidAnswer(rr) || rr->resrec.RecordType == kDNSRecordTypeDeregistering))
818     {
819         if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
820             m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
821     }
822 }
823 
824 mDNSlocal void InitializeLastAPTime(mDNS *const m, AuthRecord *const rr)
825 {
826     // For reverse-mapping Sleep Proxy PTR records, probe interval is one second
827     rr->ThisAPInterval = rr->AddressProxy.type ? mDNSPlatformOneSecond : DefaultAPIntervalForRecordType(rr->resrec.RecordType);
828 
829     // * If this is a record type that's going to probe, then we use the m->SuppressProbes time.
830     // * Otherwise, if it's not going to probe, but m->SuppressProbes is set because we have other
831     //   records that are going to probe, then we delay its first announcement so that it will
832     //   go out synchronized with the first announcement for the other records that *are* probing.
833     //   This is a minor performance tweak that helps keep groups of related records synchronized together.
834     //   The addition of "interval / 2" is to make sure that, in the event that any of the probes are
835     //   delayed by a few milliseconds, this announcement does not inadvertently go out *before* the probing is complete.
836     //   When the probing is complete and those records begin to announce, these records will also be picked up and accelerated,
837     //   because they will meet the criterion of being at least half-way to their scheduled announcement time.
838     // * If it's not going to probe and m->SuppressProbes is not already set then we should announce immediately.
839 
840     if (rr->ProbeCount)
841     {
842         // If we have no probe suppression time set, or it is in the past, set it now
843         if (m->SuppressProbes == 0 || m->SuppressProbes - m->timenow < 0)
844         {
845             // To allow us to aggregate probes when a group of services are registered together,
846             // the first probe is delayed 1/4 second. This means the common-case behaviour is:
847             // 1/4 second wait; probe
848             // 1/4 second wait; probe
849             // 1/4 second wait; probe
850             // 1/4 second wait; announce (i.e. service is normally announced exactly one second after being registered)
851             m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
852 
853             // If we already have a *probe* scheduled to go out sooner, then use that time to get better aggregation
854             if (m->SuppressProbes - m->NextScheduledProbe >= 0)
855                 m->SuppressProbes = NonZeroTime(m->NextScheduledProbe);
856             if (m->SuppressProbes - m->timenow < 0)     // Make sure we don't set m->SuppressProbes excessively in the past
857                 m->SuppressProbes = m->timenow;
858 
859             // If we already have a *query* scheduled to go out sooner, then use that time to get better aggregation
860             if (m->SuppressProbes - m->NextScheduledQuery >= 0)
861                 m->SuppressProbes = NonZeroTime(m->NextScheduledQuery);
862             if (m->SuppressProbes - m->timenow < 0)     // Make sure we don't set m->SuppressProbes excessively in the past
863                 m->SuppressProbes = m->timenow;
864 
865             // except... don't expect to be able to send before the m->SuppressSending timer fires
866             if (m->SuppressSending && m->SuppressProbes - m->SuppressSending < 0)
867                 m->SuppressProbes = NonZeroTime(m->SuppressSending);
868 
869             if (m->SuppressProbes - m->timenow > mDNSPlatformOneSecond * 8)
870             {
871                 LogMsg("InitializeLastAPTime ERROR m->SuppressProbes %d m->NextScheduledProbe %d m->NextScheduledQuery %d m->SuppressSending %d %d",
872                        m->SuppressProbes     - m->timenow,
873                        m->NextScheduledProbe - m->timenow,
874                        m->NextScheduledQuery - m->timenow,
875                        m->SuppressSending,
876                        m->SuppressSending    - m->timenow);
877                 m->SuppressProbes = NonZeroTime(m->timenow + DefaultProbeIntervalForTypeUnique/2 + mDNSRandom(DefaultProbeIntervalForTypeUnique/2));
878             }
879         }
880         rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval;
881     }
882     else if (m->SuppressProbes && m->SuppressProbes - m->timenow >= 0)
883         rr->LastAPTime = m->SuppressProbes - rr->ThisAPInterval + DefaultProbeIntervalForTypeUnique * DefaultProbeCountForTypeUnique + rr->ThisAPInterval / 2;
884     else
885         rr->LastAPTime = m->timenow - rr->ThisAPInterval;
886 
887     // For reverse-mapping Sleep Proxy PTR records we don't want to start probing instantly -- we
888     // wait one second to give the client a chance to go to sleep, and then start our ARP/NDP probing.
889     // After three probes one second apart with no answer, we conclude the client is now sleeping
890     // and we can begin broadcasting our announcements to take over ownership of that IP address.
891     // If we don't wait for the client to go to sleep, then when the client sees our ARP Announcements there's a risk
892     // (depending on the OS and networking stack it's using) that it might interpret it as a conflict and change its IP address.
893     if (rr->AddressProxy.type)
894         rr->LastAPTime = m->timenow;
895 
896     // Set LastMCTime to now, to inhibit multicast responses
897     // (no need to send additional multicast responses when we're announcing anyway)
898     rr->LastMCTime      = m->timenow;
899     rr->LastMCInterface = mDNSInterfaceMark;
900 
901     SetNextAnnounceProbeTime(m, rr);
902 }
903 
904 mDNSlocal const domainname *SetUnicastTargetToHostName(mDNS *const m, AuthRecord *rr)
905 {
906     const domainname *target;
907     if (rr->AutoTarget)
908     {
909         // For autotunnel services pointing at our IPv6 ULA we don't need or want a NAT mapping, but for all other
910         // advertised services referencing our uDNS hostname, we want NAT mappings automatically created as appropriate,
911         // with the port number in our advertised SRV record automatically tracking the external mapped port.
912         DomainAuthInfo *AuthInfo = GetAuthInfoForName_internal(m, rr->resrec.name);
913         if (!AuthInfo || !AuthInfo->AutoTunnel) rr->AutoTarget = Target_AutoHostAndNATMAP;
914     }
915 
916     target = GetServiceTarget(m, rr);
917     if (!target || target->c[0] == 0)
918     {
919         // defer registration until we've got a target
920         LogInfo("SetUnicastTargetToHostName No target for %s", ARDisplayString(m, rr));
921         rr->state = regState_NoTarget;
922         return mDNSNULL;
923     }
924     else
925     {
926         LogInfo("SetUnicastTargetToHostName target %##s for resource record %s", target->c, ARDisplayString(m,rr));
927         return target;
928     }
929 }
930 
931 // Right now this only applies to mDNS (.local) services where the target host is always m->MulticastHostname
932 // Eventually we should unify this with GetServiceTarget() in uDNS.c
933 mDNSlocal void SetTargetToHostName(mDNS *const m, AuthRecord *const rr)
934 {
935     domainname *const target = GetRRDomainNameTarget(&rr->resrec);
936     const domainname *newname = &m->MulticastHostname;
937 
938     if (!target) LogInfo("SetTargetToHostName: Don't know how to set the target of rrtype %s", DNSTypeName(rr->resrec.rrtype));
939 
940     if (!(rr->ForceMCast || rr->ARType == AuthRecordLocalOnly || rr->ARType == AuthRecordP2P || IsLocalDomain(&rr->namestorage)))
941     {
942         const domainname *const n = SetUnicastTargetToHostName(m, rr);
943         if (n) newname = n;
944         else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
945     }
946 
947     if (target && SameDomainName(target, newname))
948         debugf("SetTargetToHostName: Target of %##s is already %##s", rr->resrec.name->c, target->c);
949 
950     if (target && !SameDomainName(target, newname))
951     {
952         AssignDomainName(target, newname);
953         SetNewRData(&rr->resrec, mDNSNULL, 0);      // Update rdlength, rdestimate, rdatahash
954 
955         // If we're in the middle of probing this record, we need to start again,
956         // because changing its rdata may change the outcome of the tie-breaker.
957         // (If the record type is kDNSRecordTypeUnique (unconfirmed unique) then DefaultProbeCountForRecordType is non-zero.)
958         rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
959 
960         // If we've announced this record, we really should send a goodbye packet for the old rdata before
961         // changing to the new rdata. However, in practice, we only do SetTargetToHostName for unique records,
962         // so when we announce them we'll set the kDNSClass_UniqueRRSet and clear any stale data that way.
963         if (rr->RequireGoodbye && rr->resrec.RecordType == kDNSRecordTypeShared)
964             debugf("Have announced shared record %##s (%s) at least once: should have sent a goodbye packet before updating",
965                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
966 
967         rr->AnnounceCount  = InitialAnnounceCount;
968         rr->RequireGoodbye = mDNSfalse;
969         rr->ProbeRestartCount = 0;
970         InitializeLastAPTime(m, rr);
971     }
972 }
973 
974 mDNSlocal void AcknowledgeRecord(mDNS *const m, AuthRecord *const rr)
975 {
976     if (rr->RecordCallback)
977     {
978         // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
979         // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
980         rr->Acknowledged = mDNStrue;
981         mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
982         rr->RecordCallback(m, rr, mStatus_NoError);
983         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
984     }
985 }
986 
987 mDNSexport void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr)
988 {
989     // Make sure that we don't activate the SRV record and associated service records, if it is in
990     // NoTarget state. First time when a service is being instantiated, SRV record may be in NoTarget state.
991     // We should not activate any of the other reords (PTR, TXT) that are part of the service. When
992     // the target becomes available, the records will be reregistered.
993     if (rr->resrec.rrtype != kDNSType_SRV)
994     {
995         AuthRecord *srvRR = mDNSNULL;
996         if (rr->resrec.rrtype == kDNSType_PTR)
997             srvRR = rr->Additional1;
998         else if (rr->resrec.rrtype == kDNSType_TXT)
999             srvRR = rr->DependentOn;
1000         if (srvRR)
1001         {
1002             if (srvRR->resrec.rrtype != kDNSType_SRV)
1003             {
1004                 LogMsg("ActivateUnicastRegistration: ERROR!! Resource record %s wrong, expecting SRV type", ARDisplayString(m, srvRR));
1005             }
1006             else
1007             {
1008                 LogInfo("ActivateUnicastRegistration: Found Service Record %s in state %d for %##s (%s)",
1009                         ARDisplayString(m, srvRR), srvRR->state, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1010                 rr->state = srvRR->state;
1011             }
1012         }
1013     }
1014 
1015     if (rr->state == regState_NoTarget)
1016     {
1017         LogInfo("ActivateUnicastRegistration record %s in regState_NoTarget, not activating", ARDisplayString(m, rr));
1018         return;
1019     }
1020     // When we wake up from sleep, we call ActivateUnicastRegistration. It is possible that just before we went to sleep,
1021     // the service/record was being deregistered. In that case, we should not try to register again. For the cases where
1022     // the records are deregistered due to e.g., no target for the SRV record, we would have returned from above if it
1023     // was already in NoTarget state. If it was in the process of deregistration but did not complete fully before we went
1024     // 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.
1025     if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
1026     {
1027         LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to DeregPending", ARDisplayString(m, rr), rr->state);
1028         rr->state = regState_DeregPending;
1029     }
1030     else
1031     {
1032         LogInfo("ActivateUnicastRegistration: Resource record %s, current state %d, moving to Pending", ARDisplayString(m, rr), rr->state);
1033         rr->state = regState_Pending;
1034     }
1035     rr->ProbeCount     = 0;
1036     rr->ProbeRestartCount = 0;
1037     rr->AnnounceCount  = 0;
1038     rr->ThisAPInterval = INIT_RECORD_REG_INTERVAL;
1039     rr->LastAPTime     = m->timenow - rr->ThisAPInterval;
1040     rr->expire         = 0; // Forget about all the leases, start fresh
1041     rr->uselease       = mDNStrue;
1042     rr->updateid       = zeroID;
1043     rr->SRVChanged     = mDNSfalse;
1044     rr->updateError    = mStatus_NoError;
1045     // RestartRecordGetZoneData calls this function whenever a new interface gets registered with core.
1046     // The records might already be registered with the server and hence could have NAT state.
1047     if (rr->NATinfo.clientContext)
1048     {
1049         mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1050         rr->NATinfo.clientContext = mDNSNULL;
1051     }
1052     if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1053     if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
1054     if (m->NextuDNSEvent - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
1055         m->NextuDNSEvent = (rr->LastAPTime + rr->ThisAPInterval);
1056 }
1057 
1058 // Two records qualify to be local duplicates if:
1059 // (a) the RecordTypes are the same, or
1060 // (b) one is Unique and the other Verified
1061 // (c) either is in the process of deregistering
1062 #define RecordLDT(A,B) ((A)->resrec.RecordType == (B)->resrec.RecordType || \
1063                         ((A)->resrec.RecordType | (B)->resrec.RecordType) == (kDNSRecordTypeUnique | kDNSRecordTypeVerified) || \
1064                         ((A)->resrec.RecordType == kDNSRecordTypeDeregistering || (B)->resrec.RecordType == kDNSRecordTypeDeregistering))
1065 
1066 #define RecordIsLocalDuplicate(A,B) \
1067     ((A)->resrec.InterfaceID == (B)->resrec.InterfaceID && RecordLDT((A),(B)) && IdenticalResourceRecord(& (A)->resrec, & (B)->resrec))
1068 
1069 mDNSlocal AuthRecord *CheckAuthIdenticalRecord(AuthHash *r, AuthRecord *rr)
1070 {
1071     AuthGroup *a;
1072     AuthGroup **ag = &a;
1073     AuthRecord **rp;
1074     const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1075 
1076     a = AuthGroupForRecord(r, slot, &rr->resrec);
1077     if (!a) return mDNSNULL;
1078     rp = &(*ag)->members;
1079     while (*rp)
1080     {
1081         if (!RecordIsLocalDuplicate(*rp, rr))
1082             rp=&(*rp)->next;
1083         else
1084         {
1085             if ((*rp)->resrec.RecordType == kDNSRecordTypeDeregistering)
1086             {
1087                 (*rp)->AnnounceCount = 0;
1088                 rp=&(*rp)->next;
1089             }
1090             else return *rp;
1091         }
1092     }
1093     return (mDNSNULL);
1094 }
1095 
1096 mDNSlocal mDNSBool CheckAuthRecordConflict(AuthHash *r, AuthRecord *rr)
1097 {
1098     AuthGroup *a;
1099     AuthGroup **ag = &a;
1100     AuthRecord **rp;
1101     const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1102 
1103     a = AuthGroupForRecord(r, slot, &rr->resrec);
1104     if (!a) return mDNSfalse;
1105     rp = &(*ag)->members;
1106     while (*rp)
1107     {
1108         const AuthRecord *s1 = rr->RRSet ? rr->RRSet : rr;
1109         const AuthRecord *s2 = (*rp)->RRSet ? (*rp)->RRSet : *rp;
1110         if (s1 != s2 && SameResourceRecordSignature((*rp), rr) && !IdenticalSameNameRecord(&(*rp)->resrec, &rr->resrec))
1111             return mDNStrue;
1112         else
1113             rp=&(*rp)->next;
1114     }
1115     return (mDNSfalse);
1116 }
1117 
1118 // checks to see if "rr" is already present
1119 mDNSlocal AuthRecord *CheckAuthSameRecord(AuthHash *r, AuthRecord *rr)
1120 {
1121     AuthGroup *a;
1122     AuthGroup **ag = &a;
1123     AuthRecord **rp;
1124     const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1125 
1126     a = AuthGroupForRecord(r, slot, &rr->resrec);
1127     if (!a) return mDNSNULL;
1128     rp = &(*ag)->members;
1129     while (*rp)
1130     {
1131         if (*rp != rr)
1132             rp=&(*rp)->next;
1133         else
1134         {
1135             return *rp;
1136         }
1137     }
1138     return (mDNSNULL);
1139 }
1140 
1141 
1142 mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1143 {
1144     if (RRLocalOnly(rr))
1145     {
1146         // A sanity check, this should be prevented in calling code.
1147         LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1148         return;
1149     }
1150 
1151     if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
1152     {
1153         // If about to get rid of the last advertised service
1154         if (m->AutoTargetServices == 1)
1155             DeadvertiseAllInterfaceRecords(m);
1156 
1157         m->AutoTargetServices--;
1158         LogInfo("DecrementAutoTargetServices: AutoTargetServices %d Record %s", m->AutoTargetServices, ARDisplayString(m, rr));
1159     }
1160 
1161 #if TARGET_OS_WATCH
1162     if (!AuthRecord_uDNS(rr))
1163     {
1164         if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1165             m->NetworkChanged = m->timenow;
1166         m->NumAllInterfaceRecords--;
1167         LogInfo("DecrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
1168             m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1169     }
1170 #endif
1171 }
1172 
1173 mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
1174 {
1175     if (RRLocalOnly(rr))
1176     {
1177         // A sanity check, this should be prevented in calling code.
1178         LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
1179         return;
1180     }
1181 
1182 #if TARGET_OS_WATCH
1183     if (!AuthRecord_uDNS(rr))
1184     {
1185         m->NumAllInterfaceRecords++;
1186         LogInfo("IncrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
1187             m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
1188         if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
1189             m->NetworkChanged = m->timenow;
1190     }
1191 #endif
1192 
1193     if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
1194     {
1195         m->AutoTargetServices++;
1196         LogInfo("IncrementAutoTargetServices: AutoTargetServices %d Record %s", m->AutoTargetServices, ARDisplayString(m, rr));
1197         // If this is the first advertised service
1198         if (m->AutoTargetServices == 1)
1199             AdvertiseAllInterfaceRecords(m);
1200     }
1201 }
1202 
1203 mDNSlocal void getKeepaliveRaddr(mDNS *const m, AuthRecord *rr, mDNSAddr *raddr)
1204 {
1205     mDNSAddr     laddr;
1206     mDNSEthAddr  eth;
1207     mDNSIPPort   lport, rport;
1208     mDNSu32      timeout, seq, ack;
1209     mDNSu16      win;
1210 
1211     if (mDNS_KeepaliveRecord(&rr->resrec))
1212     {
1213         mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, raddr, &eth, &seq, &ack, &lport, &rport, &win);
1214         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(raddr) || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport))
1215         {
1216             LogMsg("getKeepaliveRaddr: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, raddr, rport.NotAnInteger);
1217             return;
1218         }
1219     }
1220 }
1221 
1222 // Exported so uDNS.c can call this
1223 mDNSexport mStatus mDNS_Register_internal(mDNS *const m, AuthRecord *const rr)
1224 {
1225     domainname *target = GetRRDomainNameTarget(&rr->resrec);
1226     AuthRecord *r;
1227     AuthRecord **p = &m->ResourceRecords;
1228     AuthRecord **d = &m->DuplicateRecords;
1229 
1230     if ((mDNSs32)rr->resrec.rroriginalttl <= 0)
1231     { LogMsg("mDNS_Register_internal: TTL %X should be 1 - 0x7FFFFFFF %s", rr->resrec.rroriginalttl, ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1232 
1233     if (!rr->resrec.RecordType)
1234     { LogMsg("mDNS_Register_internal: RecordType must be non-zero %s", ARDisplayString(m, rr)); return(mStatus_BadParamErr); }
1235 
1236     if (m->ShutdownTime)
1237     { LogMsg("mDNS_Register_internal: Shutting down, can't register %s", ARDisplayString(m, rr)); return(mStatus_ServiceNotRunning); }
1238 
1239     if (m->DivertMulticastAdvertisements && !AuthRecord_uDNS(rr))
1240     {
1241         mDNSInterfaceID previousID = rr->resrec.InterfaceID;
1242         if (rr->resrec.InterfaceID == mDNSInterface_Any || rr->resrec.InterfaceID == mDNSInterface_P2P)
1243         {
1244             rr->resrec.InterfaceID = mDNSInterface_LocalOnly;
1245             rr->ARType = AuthRecordLocalOnly;
1246         }
1247         if (rr->resrec.InterfaceID != mDNSInterface_LocalOnly)
1248         {
1249             NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
1250             if (intf && !intf->Advertise) { rr->resrec.InterfaceID = mDNSInterface_LocalOnly; rr->ARType = AuthRecordLocalOnly; }
1251         }
1252         if (rr->resrec.InterfaceID != previousID)
1253             LogInfo("mDNS_Register_internal: Diverting record to local-only %s", ARDisplayString(m, rr));
1254     }
1255 
1256     if (RRLocalOnly(rr))
1257     {
1258         if (CheckAuthSameRecord(&m->rrauth, rr))
1259         {
1260             LogMsg("mDNS_Register_internal: ERROR!! Tried to register LocalOnly AuthRecord %p %##s (%s) that's already in the list",
1261                    rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1262             return(mStatus_AlreadyRegistered);
1263         }
1264     }
1265     else
1266     {
1267         while (*p && *p != rr) p=&(*p)->next;
1268         if (*p)
1269         {
1270             LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the list",
1271                    rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1272             return(mStatus_AlreadyRegistered);
1273         }
1274     }
1275 
1276     while (*d && *d != rr) d=&(*d)->next;
1277     if (*d)
1278     {
1279         LogMsg("mDNS_Register_internal: ERROR!! Tried to register AuthRecord %p %##s (%s) that's already in the Duplicate list",
1280                rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1281         return(mStatus_AlreadyRegistered);
1282     }
1283 
1284     if (rr->DependentOn)
1285     {
1286         if (rr->resrec.RecordType == kDNSRecordTypeUnique)
1287             rr->resrec.RecordType =  kDNSRecordTypeVerified;
1288         else
1289         {
1290             LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn && RecordType != kDNSRecordTypeUnique",
1291                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1292             return(mStatus_Invalid);
1293         }
1294         if (!(rr->DependentOn->resrec.RecordType & (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique)))
1295         {
1296             LogMsg("mDNS_Register_internal: ERROR! %##s (%s): rr->DependentOn->RecordType bad type %X",
1297                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->DependentOn->resrec.RecordType);
1298             return(mStatus_Invalid);
1299         }
1300     }
1301 
1302     rr->next = mDNSNULL;
1303 
1304     // Field Group 1: The actual information pertaining to this resource record
1305     // Set up by client prior to call
1306 
1307     // Field Group 2: Persistent metadata for Authoritative Records
1308 //	rr->Additional1       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1309 //	rr->Additional2       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1310 //	rr->DependentOn       = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1311 //	rr->RRSet             = set to mDNSNULL  in mDNS_SetupResourceRecord; may be overridden by client
1312 //	rr->Callback          = already set      in mDNS_SetupResourceRecord
1313 //	rr->Context           = already set      in mDNS_SetupResourceRecord
1314 //	rr->RecordType        = already set      in mDNS_SetupResourceRecord
1315 //	rr->HostTarget        = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1316 //	rr->AllowRemoteQuery  = set to mDNSfalse in mDNS_SetupResourceRecord; may be overridden by client
1317     // Make sure target is not uninitialized data, or we may crash writing debugging log messages
1318     if (rr->AutoTarget && target) target->c[0] = 0;
1319 
1320     // Field Group 3: Transient state for Authoritative Records
1321     rr->Acknowledged      = mDNSfalse;
1322     rr->ProbeCount        = DefaultProbeCountForRecordType(rr->resrec.RecordType);
1323     rr->ProbeRestartCount = 0;
1324     rr->AnnounceCount     = InitialAnnounceCount;
1325     rr->RequireGoodbye    = mDNSfalse;
1326     rr->AnsweredLocalQ    = mDNSfalse;
1327     rr->IncludeInProbe    = mDNSfalse;
1328     rr->ImmedUnicast      = mDNSfalse;
1329     rr->SendNSECNow       = mDNSNULL;
1330     rr->ImmedAnswer       = mDNSNULL;
1331     rr->ImmedAdditional   = mDNSNULL;
1332     rr->SendRNow          = mDNSNULL;
1333     rr->v4Requester       = zerov4Addr;
1334     rr->v6Requester       = zerov6Addr;
1335     rr->NextResponse      = mDNSNULL;
1336     rr->NR_AnswerTo       = mDNSNULL;
1337     rr->NR_AdditionalTo   = mDNSNULL;
1338     if (!rr->AutoTarget) InitializeLastAPTime(m, rr);
1339 //	rr->LastAPTime        = Set for us in InitializeLastAPTime()
1340 //	rr->LastMCTime        = Set for us in InitializeLastAPTime()
1341 //	rr->LastMCInterface   = Set for us in InitializeLastAPTime()
1342     rr->NewRData          = mDNSNULL;
1343     rr->newrdlength       = 0;
1344     rr->UpdateCallback    = mDNSNULL;
1345     rr->UpdateCredits     = kMaxUpdateCredits;
1346     rr->NextUpdateCredit  = 0;
1347     rr->UpdateBlocked     = 0;
1348 
1349     // For records we're holding as proxy (except reverse-mapping PTR records) two announcements is sufficient
1350     if (rr->WakeUp.HMAC.l[0] && !rr->AddressProxy.type) rr->AnnounceCount = 2;
1351 
1352     // Field Group 4: Transient uDNS state for Authoritative Records
1353     rr->state             = regState_Zero;
1354     rr->uselease          = 0;
1355     rr->expire            = 0;
1356     rr->Private           = 0;
1357     rr->updateid          = zeroID;
1358     rr->updateIntID       = zeroOpaque64;
1359     rr->zone              = rr->resrec.name;
1360     rr->nta               = mDNSNULL;
1361     rr->tcp               = mDNSNULL;
1362     rr->OrigRData         = 0;
1363     rr->OrigRDLen         = 0;
1364     rr->InFlightRData     = 0;
1365     rr->InFlightRDLen     = 0;
1366     rr->QueuedRData       = 0;
1367     rr->QueuedRDLen       = 0;
1368     //mDNSPlatformMemZero(&rr->NATinfo, sizeof(rr->NATinfo));
1369     // We should be recording the actual internal port for this service record here. Once we initiate our NAT mapping
1370     // request we'll subsequently overwrite srv.port with the allocated external NAT port -- potentially multiple
1371     // times with different values if the external NAT port changes during the lifetime of the service registration.
1372     //if (rr->resrec.rrtype == kDNSType_SRV) rr->NATinfo.IntPort = rr->resrec.rdata->u.srv.port;
1373 
1374 //	rr->resrec.interface         = already set in mDNS_SetupResourceRecord
1375 //	rr->resrec.name->c           = MUST be set by client
1376 //	rr->resrec.rrtype            = already set in mDNS_SetupResourceRecord
1377 //	rr->resrec.rrclass           = already set in mDNS_SetupResourceRecord
1378 //	rr->resrec.rroriginalttl     = already set in mDNS_SetupResourceRecord
1379 //	rr->resrec.rdata             = MUST be set by client, unless record type is CNAME or PTR and rr->HostTarget is set
1380 
1381     // BIND named (name daemon) doesn't allow TXT records with zero-length rdata. This is strictly speaking correct,
1382     // since RFC 1035 specifies a TXT record as "One or more <character-string>s", not "Zero or more <character-string>s".
1383     // Since some legacy apps try to create zero-length TXT records, we'll silently correct it here.
1384     if (rr->resrec.rrtype == kDNSType_TXT && rr->resrec.rdlength == 0) { rr->resrec.rdlength = 1; rr->resrec.rdata->u.txt.c[0] = 0; }
1385 
1386     if (rr->AutoTarget)
1387     {
1388         SetTargetToHostName(m, rr); // Also sets rdlength and rdestimate for us, and calls InitializeLastAPTime();
1389 #ifndef UNICAST_DISABLED
1390         // If we have no target record yet, SetTargetToHostName will set rr->state == regState_NoTarget
1391         // 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.
1392         if (rr->state == regState_NoTarget)
1393         {
1394             // Initialize the target so that we don't crash while logging etc.
1395             domainname *tar = GetRRDomainNameTarget(&rr->resrec);
1396             if (tar) tar->c[0] = 0;
1397             LogInfo("mDNS_Register_internal: record %s in NoTarget state", ARDisplayString(m, rr));
1398         }
1399 #endif
1400     }
1401     else
1402     {
1403         rr->resrec.rdlength   = GetRDLength(&rr->resrec, mDNSfalse);
1404         rr->resrec.rdestimate = GetRDLength(&rr->resrec, mDNStrue);
1405     }
1406 
1407     if (!ValidateDomainName(rr->resrec.name))
1408     { LogMsg("Attempt to register record with invalid name: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1409 
1410     // Don't do this until *after* we've set rr->resrec.rdlength
1411     if (!ValidateRData(rr->resrec.rrtype, rr->resrec.rdlength, rr->resrec.rdata))
1412     { LogMsg("Attempt to register record with invalid rdata: %s", ARDisplayString(m, rr)); return(mStatus_Invalid); }
1413 
1414     rr->resrec.namehash   = DomainNameHashValue(rr->resrec.name);
1415     rr->resrec.rdatahash  = target ? DomainNameHashValue(target) : RDataHashValue(&rr->resrec);
1416 
1417     if (RRLocalOnly(rr))
1418     {
1419         // If this is supposed to be unique, make sure we don't have any name conflicts.
1420         // If we found a conflict, we may still want to insert the record in the list but mark it appropriately
1421         // (kDNSRecordTypeDeregistering) so that we deliver RMV events to the application. But this causes more
1422         // complications and not clear whether there are any benefits. See rdar:9304275 for details.
1423         // Hence, just bail out.
1424         // This comment is doesn’t make any sense. -- SC
1425         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1426         {
1427             if (CheckAuthRecordConflict(&m->rrauth, rr))
1428             {
1429                 LogInfo("mDNS_Register_internal: Name conflict %s (%p), InterfaceID %p", ARDisplayString(m, rr), rr, rr->resrec.InterfaceID);
1430                 return mStatus_NameConflict;
1431             }
1432         }
1433     }
1434 
1435     // For uDNS records, we don't support duplicate checks at this time.
1436 #ifndef UNICAST_DISABLED
1437     if (AuthRecord_uDNS(rr))
1438     {
1439         if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1440         // When we called SetTargetToHostName, it may have caused mDNS_Register_internal to be re-entered, appending new
1441         // 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.
1442         // Note that for AutoTunnel this should never happen, but this check makes the code future-proof.
1443         while (*p) p=&(*p)->next;
1444         *p = rr;
1445         if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1446         rr->ProbeCount    = 0;
1447         rr->ProbeRestartCount = 0;
1448         rr->AnnounceCount = 0;
1449         if (rr->state != regState_NoTarget) ActivateUnicastRegistration(m, rr);
1450         return(mStatus_NoError);            // <--- Note: For unicast records, code currently bails out at this point
1451     }
1452 #endif
1453 
1454     // Now that we've finished building our new record, make sure it's not identical to one we already have
1455     if (RRLocalOnly(rr))
1456     {
1457         rr->ProbeCount    = 0;
1458         rr->ProbeRestartCount = 0;
1459         rr->AnnounceCount = 0;
1460         r = CheckAuthIdenticalRecord(&m->rrauth, rr);
1461     }
1462     else
1463     {
1464         for (r = m->ResourceRecords; r; r=r->next)
1465             if (RecordIsLocalDuplicate(r, rr))
1466             {
1467                 if (r->resrec.RecordType == kDNSRecordTypeDeregistering) r->AnnounceCount = 0;
1468                 else break;
1469             }
1470     }
1471 
1472     if (r)
1473     {
1474         debugf("mDNS_Register_internal:Adding to duplicate list %s", ARDisplayString(m,rr));
1475         *d = rr;
1476         // If the previous copy of this record is already verified unique,
1477         // then indicate that we should move this record promptly to kDNSRecordTypeUnique state.
1478         // Setting ProbeCount to zero will cause SendQueries() to advance this record to
1479         // kDNSRecordTypeVerified state and call the client callback at the next appropriate time.
1480         if (rr->resrec.RecordType == kDNSRecordTypeUnique && r->resrec.RecordType == kDNSRecordTypeVerified)
1481             rr->ProbeCount = 0;
1482     }
1483     else
1484     {
1485         debugf("mDNS_Register_internal: Adding to active record list %s", ARDisplayString(m,rr));
1486         if (RRLocalOnly(rr))
1487         {
1488             AuthGroup *ag;
1489             ag = InsertAuthRecord(m, &m->rrauth, rr);
1490             if (ag && !ag->NewLocalOnlyRecords)
1491             {
1492                 m->NewLocalOnlyRecords = mDNStrue;
1493                 ag->NewLocalOnlyRecords = rr;
1494             }
1495             // No probing for LocalOnly records; acknowledge them right away
1496             if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
1497             AcknowledgeRecord(m, rr);
1498             return(mStatus_NoError);
1499         }
1500         else
1501         {
1502             if (!m->NewLocalRecords) m->NewLocalRecords = rr;
1503             *p = rr;
1504         }
1505     }
1506 
1507     // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
1508     // This is used by the in-NIC proxy to send the keepalive packets.
1509     if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
1510     {
1511         mDNSAddr raddr;
1512         // Set the record type to known unique to prevent probing keep alive records.
1513         // Also make sure we do not announce the keepalive records.
1514        rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
1515        rr->AnnounceCount     = 0;
1516        getKeepaliveRaddr(m, rr, &raddr);
1517        // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
1518        // asynchronous task to update the resource record
1519        mDNSPlatformGetRemoteMacAddr(m, &raddr);
1520     }
1521 
1522     if (!AuthRecord_uDNS(rr))   // This check is superfluous, given that for unicast records we (currently) bail out above
1523     {
1524         // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
1525         IncrementAutoTargetServices(m, rr);
1526 
1527         // For records that are not going to probe, acknowledge them right away
1528         if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
1529             AcknowledgeRecord(m, rr);
1530 
1531         // Adding a record may affect whether or not we should sleep
1532         mDNS_UpdateAllowSleep(m);
1533     }
1534 
1535     return(mStatus_NoError);
1536 }
1537 
1538 mDNSlocal void RecordProbeFailure(mDNS *const m, const AuthRecord *const rr)
1539 {
1540     m->ProbeFailTime = m->timenow;
1541     m->NumFailedProbes++;
1542     // If we've had fifteen or more probe failures, rate-limit to one every five seconds.
1543     // If a bunch of hosts have all been configured with the same name, then they'll all
1544     // conflict and run through the same series of names: name-2, name-3, name-4, etc.,
1545     // up to name-10. After that they'll start adding random increments in the range 1-100,
1546     // so they're more likely to branch out in the available namespace and settle on a set of
1547     // unique names quickly. If after five more tries the host is still conflicting, then we
1548     // may have a serious problem, so we start rate-limiting so we don't melt down the network.
1549     if (m->NumFailedProbes >= 15)
1550     {
1551         m->SuppressProbes = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
1552         LogMsg("Excessive name conflicts (%lu) for %##s (%s); rate limiting in effect",
1553                m->NumFailedProbes, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1554     }
1555 }
1556 
1557 mDNSlocal void CompleteRDataUpdate(mDNS *const m, AuthRecord *const rr)
1558 {
1559     RData *OldRData = rr->resrec.rdata;
1560     mDNSu16 OldRDLen = rr->resrec.rdlength;
1561     SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);    // Update our rdata
1562     rr->NewRData = mDNSNULL;                                    // Clear the NewRData pointer ...
1563     if (rr->UpdateCallback)
1564         rr->UpdateCallback(m, rr, OldRData, OldRDLen);          // ... and let the client know
1565 }
1566 
1567 // Note: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
1568 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
1569 // Exported so uDNS.c can call this
1570 mDNSexport mStatus mDNS_Deregister_internal(mDNS *const m, AuthRecord *const rr, mDNS_Dereg_type drt)
1571 {
1572     AuthRecord *r2;
1573     mDNSu8 RecordType = rr->resrec.RecordType;
1574     AuthRecord **p = &m->ResourceRecords;   // Find this record in our list of active records
1575     mDNSBool dupList = mDNSfalse;
1576 
1577     if (RRLocalOnly(rr))
1578     {
1579         AuthGroup *a;
1580         AuthGroup **ag = &a;
1581         AuthRecord **rp;
1582         const mDNSu32 slot = AuthHashSlot(rr->resrec.name);
1583 
1584         a = AuthGroupForRecord(&m->rrauth, slot, &rr->resrec);
1585         if (!a) return mDNSfalse;
1586         rp = &(*ag)->members;
1587         while (*rp && *rp != rr) rp=&(*rp)->next;
1588         p = rp;
1589     }
1590     else
1591     {
1592         while (*p && *p != rr) p=&(*p)->next;
1593     }
1594 
1595     if (*p)
1596     {
1597         // We found our record on the main list. See if there are any duplicates that need special handling.
1598         if (drt == mDNS_Dereg_conflict)     // If this was a conflict, see that all duplicates get the same treatment
1599         {
1600             // Scan for duplicates of rr, and mark them for deregistration at the end of this routine, after we've finished
1601             // deregistering rr. We need to do this scan *before* we give the client the chance to free and reuse the rr memory.
1602             for (r2 = m->DuplicateRecords; r2; r2=r2->next) if (RecordIsLocalDuplicate(r2, rr)) r2->ProbeCount = 0xFF;
1603         }
1604         else
1605         {
1606             // Before we delete the record (and potentially send a goodbye packet)
1607             // first see if we have a record on the duplicate list ready to take over from it.
1608             AuthRecord **d = &m->DuplicateRecords;
1609             while (*d && !RecordIsLocalDuplicate(*d, rr)) d=&(*d)->next;
1610             if (*d)
1611             {
1612                 AuthRecord *dup = *d;
1613                 debugf("mDNS_Register_internal: Duplicate record %p taking over from %p %##s (%s)",
1614                        dup, rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1615                 *d        = dup->next;      // Cut replacement record from DuplicateRecords list
1616                 if (RRLocalOnly(rr))
1617                 {
1618                     dup->next = mDNSNULL;
1619                     if (!InsertAuthRecord(m, &m->rrauth, dup)) LogMsg("mDNS_Deregister_internal: ERROR!! cannot insert %s", ARDisplayString(m, dup));
1620                 }
1621                 else
1622                 {
1623                     dup->next = rr->next;       // And then...
1624                     rr->next  = dup;            // ... splice it in right after the record we're about to delete
1625                 }
1626                 dup->resrec.RecordType        = rr->resrec.RecordType;
1627                 dup->ProbeCount      = rr->ProbeCount;
1628                 dup->ProbeRestartCount = rr->ProbeRestartCount;
1629                 dup->AnnounceCount   = rr->AnnounceCount;
1630                 dup->RequireGoodbye  = rr->RequireGoodbye;
1631                 dup->AnsweredLocalQ  = rr->AnsweredLocalQ;
1632                 dup->ImmedAnswer     = rr->ImmedAnswer;
1633                 dup->ImmedUnicast    = rr->ImmedUnicast;
1634                 dup->ImmedAdditional = rr->ImmedAdditional;
1635                 dup->v4Requester     = rr->v4Requester;
1636                 dup->v6Requester     = rr->v6Requester;
1637                 dup->ThisAPInterval  = rr->ThisAPInterval;
1638                 dup->LastAPTime      = rr->LastAPTime;
1639                 dup->LastMCTime      = rr->LastMCTime;
1640                 dup->LastMCInterface = rr->LastMCInterface;
1641                 dup->Private         = rr->Private;
1642                 dup->state           = rr->state;
1643                 rr->RequireGoodbye = mDNSfalse;
1644                 rr->AnsweredLocalQ = mDNSfalse;
1645             }
1646         }
1647     }
1648     else
1649     {
1650         // We didn't find our record on the main list; try the DuplicateRecords list instead.
1651         p = &m->DuplicateRecords;
1652         while (*p && *p != rr) p=&(*p)->next;
1653         // If we found our record on the duplicate list, then make sure we don't send a goodbye for it
1654         if (*p)
1655         {
1656             // Duplicate records are not used for sending wakeups or goodbyes. Hence, deregister them
1657             // immediately. When there is a conflict, we deregister all the conflicting duplicate records
1658             // also that have been marked above in this function. In that case, we come here and if we don't
1659             // deregister (unilink from the DuplicateRecords list), we will be recursing infinitely. Hence,
1660             // clear the HMAC which will cause it to deregister. See <rdar://problem/10380988> for
1661             // details.
1662             rr->WakeUp.HMAC    = zeroEthAddr;
1663             rr->RequireGoodbye = mDNSfalse;
1664             rr->resrec.RecordType = kDNSRecordTypeDeregistering;
1665             dupList = mDNStrue;
1666         }
1667         if (*p) debugf("mDNS_Deregister_internal: Deleting DuplicateRecord %p %##s (%s)",
1668                        rr, rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1669     }
1670 
1671     if (!*p)
1672     {
1673         // No need to log an error message if we already know this is a potentially repeated deregistration
1674         if (drt != mDNS_Dereg_repeat)
1675             LogMsg("mDNS_Deregister_internal: Record %p not found in list %s", rr, ARDisplayString(m,rr));
1676         return(mStatus_BadReferenceErr);
1677     }
1678 
1679     // If this is a shared record and we've announced it at least once,
1680     // we need to retract that announcement before we delete the record
1681 
1682     // If this is a record (including mDNSInterface_LocalOnly records) for which we've given local-only answers then
1683     // it's tempting to just do "AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse)" here, but that would not not be safe.
1684     // The AnswerAllLocalQuestionsWithLocalAuthRecord routine walks the question list invoking client callbacks, using the "m->CurrentQuestion"
1685     // mechanism to cope with the client callback modifying the question list while that's happening.
1686     // However, mDNS_Deregister could have been called from a client callback (e.g. from the domain enumeration callback FoundDomain)
1687     // which means that the "m->CurrentQuestion" mechanism is already in use to protect that list, so we can't use it twice.
1688     // More generally, if we invoke callbacks from within a client callback, then those callbacks could deregister other
1689     // records, thereby invoking yet more callbacks, without limit.
1690     // The solution is to defer delivering the "Remove" events until mDNS_Execute time, just like we do for sending
1691     // actual goodbye packets.
1692 
1693 #ifndef UNICAST_DISABLED
1694     if (AuthRecord_uDNS(rr))
1695     {
1696         if (rr->RequireGoodbye)
1697         {
1698             if (rr->tcp) { DisposeTCPConn(rr->tcp); rr->tcp = mDNSNULL; }
1699             rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
1700             m->LocalRemoveEvents     = mDNStrue;
1701             uDNS_DeregisterRecord(m, rr);
1702             // At this point unconditionally we bail out
1703             // Either uDNS_DeregisterRecord will have completed synchronously, and called CompleteDeregistration,
1704             // which calls us back here with RequireGoodbye set to false, or it will have initiated the deregistration
1705             // process and will complete asynchronously. Either way we don't need to do anything more here.
1706             return(mStatus_NoError);
1707         }
1708         // Sometimes the records don't complete proper deregistration i.e., don't wait for a response
1709         // from the server. In that case, if the records have been part of a group update, clear the
1710         // state here. Some recors e.g., AutoTunnel gets reused without ever being completely initialized
1711         rr->updateid = zeroID;
1712 
1713         // We defer cleaning up NAT state only after sending goodbyes. This is important because
1714         // RecordRegistrationGotZoneData guards against creating NAT state if clientContext is non-NULL.
1715         // This happens today when we turn on/off interface where we get multiple network transitions
1716         // and RestartRecordGetZoneData triggers re-registration of the resource records even though
1717         // they may be in Registered state which causes NAT information to be setup multiple times. Defering
1718         // the cleanup here keeps clientContext non-NULL and hence prevents that. Note that cleaning up
1719         // NAT state here takes care of the case where we did not send goodbyes at all.
1720         if (rr->NATinfo.clientContext)
1721         {
1722             mDNS_StopNATOperation_internal(m, &rr->NATinfo);
1723             rr->NATinfo.clientContext = mDNSNULL;
1724         }
1725         if (rr->nta) { CancelGetZoneData(m, rr->nta); rr->nta = mDNSNULL; }
1726         if (rr->tcp) { DisposeTCPConn(rr->tcp);       rr->tcp = mDNSNULL; }
1727     }
1728 #endif // UNICAST_DISABLED
1729 
1730     if      (RecordType == kDNSRecordTypeUnregistered)
1731         LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeUnregistered", ARDisplayString(m, rr));
1732     else if (RecordType == kDNSRecordTypeDeregistering)
1733     {
1734         LogMsg("mDNS_Deregister_internal: %s already marked kDNSRecordTypeDeregistering", ARDisplayString(m, rr));
1735         return(mStatus_BadReferenceErr);
1736     }
1737 
1738     // <rdar://problem/7457925> Local-only questions don't get remove events for unique records
1739     // We may want to consider changing this code so that we generate local-only question "rmv"
1740     // events (and maybe goodbye packets too) for unique records as well as for shared records
1741     // Note: If we change the logic for this "if" statement, need to ensure that the code in
1742     // CompleteDeregistration() sets the appropriate state variables to gaurantee that "else"
1743     // clause will execute here and the record will be cut from the list.
1744     if (rr->WakeUp.HMAC.l[0] ||
1745         (RecordType == kDNSRecordTypeShared && (rr->RequireGoodbye || rr->AnsweredLocalQ)))
1746     {
1747         verbosedebugf("mDNS_Deregister_internal: Starting deregistration for %s", ARDisplayString(m, rr));
1748         rr->resrec.RecordType    = kDNSRecordTypeDeregistering;
1749         rr->resrec.rroriginalttl = 0;
1750         rr->AnnounceCount        = rr->WakeUp.HMAC.l[0] ? WakeupCount : (drt == mDNS_Dereg_rapid) ? 1 : GoodbyeCount;
1751         rr->ThisAPInterval       = mDNSPlatformOneSecond * 2;
1752         rr->LastAPTime           = m->timenow - rr->ThisAPInterval;
1753         m->LocalRemoveEvents     = mDNStrue;
1754         if (m->NextScheduledResponse - (m->timenow + mDNSPlatformOneSecond/10) >= 0)
1755             m->NextScheduledResponse = (m->timenow + mDNSPlatformOneSecond/10);
1756     }
1757     else
1758     {
1759         if (!dupList && RRLocalOnly(rr))
1760         {
1761             AuthGroup *ag = RemoveAuthRecord(m, &m->rrauth, rr);
1762             if (ag->NewLocalOnlyRecords == rr) ag->NewLocalOnlyRecords = rr->next;
1763         }
1764         else
1765         {
1766             *p = rr->next;                  // Cut this record from the list
1767             if (m->NewLocalRecords == rr) m->NewLocalRecords = rr->next;
1768             DecrementAutoTargetServices(m, rr);
1769         }
1770         // If someone is about to look at this, bump the pointer forward
1771         if (m->CurrentRecord   == rr) m->CurrentRecord   = rr->next;
1772         rr->next = mDNSNULL;
1773 
1774         // Should we generate local remove events here?
1775         // i.e. something like:
1776         // if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, mDNSfalse); rr->AnsweredLocalQ = mDNSfalse; }
1777 
1778         verbosedebugf("mDNS_Deregister_internal: Deleting record for %s", ARDisplayString(m, rr));
1779         rr->resrec.RecordType = kDNSRecordTypeUnregistered;
1780 
1781         if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
1782             debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)",
1783                    rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1784 
1785         // If we have an update queued up which never executed, give the client a chance to free that memory
1786         if (rr->NewRData) CompleteRDataUpdate(m, rr);   // Update our rdata, clear the NewRData pointer, and return memory to the client
1787 
1788 
1789         // CAUTION: MUST NOT do anything more with rr after calling rr->Callback(), because the client's callback function
1790         // is allowed to do anything, including starting/stopping queries, registering/deregistering records, etc.
1791         // In this case the likely client action to the mStatus_MemFree message is to free the memory,
1792         // so any attempt to touch rr after this is likely to lead to a crash.
1793         if (drt != mDNS_Dereg_conflict)
1794         {
1795             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
1796             LogInfo("mDNS_Deregister_internal: mStatus_MemFree for %s", ARDisplayString(m, rr));
1797             if (rr->RecordCallback)
1798                 rr->RecordCallback(m, rr, mStatus_MemFree);         // MUST NOT touch rr after this
1799             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
1800         }
1801         else
1802         {
1803             RecordProbeFailure(m, rr);
1804             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
1805             if (rr->RecordCallback)
1806                 rr->RecordCallback(m, rr, mStatus_NameConflict);    // MUST NOT touch rr after this
1807             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
1808             // Now that we've finished deregistering rr, check our DuplicateRecords list for any that we marked previously.
1809             // Note that with all the client callbacks going on, by the time we get here all the
1810             // records we marked may have been explicitly deregistered by the client anyway.
1811             r2 = m->DuplicateRecords;
1812             while (r2)
1813             {
1814                 if (r2->ProbeCount != 0xFF)
1815                 {
1816                     r2 = r2->next;
1817                 }
1818                 else
1819                 {
1820                     mDNS_Deregister_internal(m, r2, mDNS_Dereg_conflict);
1821                     // As this is a duplicate record, it will be unlinked from the list
1822                     // immediately
1823                     r2 = m->DuplicateRecords;
1824                 }
1825             }
1826         }
1827     }
1828     mDNS_UpdateAllowSleep(m);
1829     return(mStatus_NoError);
1830 }
1831 
1832 // ***************************************************************************
1833 #if COMPILER_LIKES_PRAGMA_MARK
1834 #pragma mark -
1835 #pragma mark - Packet Sending Functions
1836 #endif
1837 
1838 mDNSlocal void AddRecordToResponseList(AuthRecord ***nrpp, AuthRecord *rr, AuthRecord *add)
1839 {
1840     if (rr->NextResponse == mDNSNULL && *nrpp != &rr->NextResponse)
1841     {
1842         **nrpp = rr;
1843         // NR_AdditionalTo must point to a record with NR_AnswerTo set (and not NR_AdditionalTo)
1844         // If 'add' does not meet this requirement, then follow its NR_AdditionalTo pointer to a record that does
1845         // The referenced record will definitely be acceptable (by recursive application of this rule)
1846         if (add && add->NR_AdditionalTo) add = add->NR_AdditionalTo;
1847         rr->NR_AdditionalTo = add;
1848         *nrpp = &rr->NextResponse;
1849     }
1850     debugf("AddRecordToResponseList: %##s (%s) already in list", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
1851 }
1852 
1853 mDNSlocal void AddAdditionalsToResponseList(mDNS *const m, AuthRecord *ResponseRecords, AuthRecord ***nrpp, const mDNSInterfaceID InterfaceID)
1854 {
1855     AuthRecord  *rr, *rr2;
1856     for (rr=ResponseRecords; rr; rr=rr->NextResponse)           // For each record we plan to put
1857     {
1858         // (Note: This is an "if", not a "while". If we add a record, we'll find it again
1859         // later in the "for" loop, and we will follow further "additional" links then.)
1860         if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceID))
1861             AddRecordToResponseList(nrpp, rr->Additional1, rr);
1862 
1863         if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceID))
1864             AddRecordToResponseList(nrpp, rr->Additional2, rr);
1865 
1866         // For SRV records, automatically add the Address record(s) for the target host
1867         if (rr->resrec.rrtype == kDNSType_SRV)
1868         {
1869             for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)                    // Scan list of resource records
1870                 if (RRTypeIsAddressType(rr2->resrec.rrtype) &&                  // For all address records (A/AAAA) ...
1871                     ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&   // ... which are valid for answer ...
1872                     rr->resrec.rdatahash == rr2->resrec.namehash &&         // ... whose name is the name of the SRV target
1873                     SameDomainName(&rr->resrec.rdata->u.srv.target, rr2->resrec.name))
1874                     AddRecordToResponseList(nrpp, rr2, rr);
1875         }
1876         else if (RRTypeIsAddressType(rr->resrec.rrtype))    // For A or AAAA, put counterpart as additional
1877         {
1878             for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)                    // Scan list of resource records
1879                 if (RRTypeIsAddressType(rr2->resrec.rrtype) &&                  // For all address records (A/AAAA) ...
1880                     ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceID) &&   // ... which are valid for answer ...
1881                     rr->resrec.namehash == rr2->resrec.namehash &&              // ... and have the same name
1882                     SameDomainName(rr->resrec.name, rr2->resrec.name))
1883                     AddRecordToResponseList(nrpp, rr2, rr);
1884         }
1885         else if (rr->resrec.rrtype == kDNSType_PTR)         // For service PTR, see if we want to add DeviceInfo record
1886         {
1887             if (ResourceRecordIsValidInterfaceAnswer(&m->DeviceInfo, InterfaceID) &&
1888                 SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
1889                 AddRecordToResponseList(nrpp, &m->DeviceInfo, rr);
1890         }
1891     }
1892 }
1893 
1894 mDNSlocal int AnonInfoSpace(AnonymousInfo *info)
1895 {
1896     ResourceRecord *rr = info->nsec3RR;
1897 
1898     // 2 bytes for compressed name + type (2) class (2) TTL (4) rdlength (2) rdata (n)
1899     return (2 + 10 + rr->rdlength);
1900 }
1901 
1902 mDNSlocal void SendDelayedUnicastResponse(mDNS *const m, const mDNSAddr *const dest, const mDNSInterfaceID InterfaceID)
1903 {
1904     AuthRecord *rr;
1905     AuthRecord  *ResponseRecords = mDNSNULL;
1906     AuthRecord **nrp             = &ResponseRecords;
1907     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
1908     int AnoninfoSpace = 0;
1909 
1910     // Make a list of all our records that need to be unicast to this destination
1911     for (rr = m->ResourceRecords; rr; rr=rr->next)
1912     {
1913         // If we find we can no longer unicast this answer, clear ImmedUnicast
1914         if (rr->ImmedAnswer == mDNSInterfaceMark               ||
1915             mDNSSameIPv4Address(rr->v4Requester, onesIPv4Addr) ||
1916             mDNSSameIPv6Address(rr->v6Requester, onesIPv6Addr)  )
1917             rr->ImmedUnicast = mDNSfalse;
1918 
1919         if (rr->ImmedUnicast && rr->ImmedAnswer == InterfaceID)
1920         {
1921             if ((dest->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->v4Requester, dest->ip.v4)) ||
1922                 (dest->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->v6Requester, dest->ip.v6)))
1923             {
1924                 rr->ImmedAnswer  = mDNSNULL;                // Clear the state fields
1925                 rr->ImmedUnicast = mDNSfalse;
1926                 rr->v4Requester  = zerov4Addr;
1927                 rr->v6Requester  = zerov6Addr;
1928 
1929                 // Only sent records registered for P2P over P2P interfaces
1930                 if (intf && !mDNSPlatformValidRecordForInterface(rr, intf))
1931                 {
1932                     LogInfo("SendDelayedUnicastResponse: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, InterfaceID));
1933                     continue;
1934                 }
1935 
1936                 if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse)   // rr->NR_AnswerTo
1937                 {
1938                     rr->NR_AnswerTo = NR_AnswerMulticast;
1939                     *nrp = rr;
1940                     nrp = &rr->NextResponse;
1941                 }
1942             }
1943         }
1944     }
1945 
1946     AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
1947 
1948     while (ResponseRecords)
1949     {
1950         mDNSu8 *responseptr = m->omsg.data;
1951         mDNSu8 *newptr;
1952         InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
1953 
1954         // Put answers in the packet
1955         while (ResponseRecords && ResponseRecords->NR_AnswerTo)
1956         {
1957             rr = ResponseRecords;
1958             if (rr->resrec.AnonInfo)
1959             {
1960                 AnoninfoSpace += AnonInfoSpace(rr->resrec.AnonInfo);
1961                 rr->resrec.AnonInfo->SendNow = mDNSInterfaceMark;
1962             }
1963             if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
1964                 rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
1965 
1966             // Retract the limit by AnoninfoSpace which we need to put the AnoInfo option.
1967             newptr = PutResourceRecordTTLWithLimit(&m->omsg, responseptr, &m->omsg.h.numAnswers, &rr->resrec, rr->resrec.rroriginalttl,
1968                  m->omsg.data + (AllowedRRSpace(&m->omsg) - AnoninfoSpace));
1969 
1970             rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
1971             if (!newptr && m->omsg.h.numAnswers)
1972             {
1973                 break; // If packet full, send it now
1974             }
1975             if (newptr) responseptr = newptr;
1976             ResponseRecords = rr->NextResponse;
1977             rr->NextResponse    = mDNSNULL;
1978             rr->NR_AnswerTo     = mDNSNULL;
1979             rr->NR_AdditionalTo = mDNSNULL;
1980             rr->RequireGoodbye  = mDNStrue;
1981         }
1982 
1983         // We have reserved the space for AnonInfo option. PutResourceRecord uses the
1984         // standard limit (AllowedRRSpace) and we should have space now.
1985         for (rr = m->ResourceRecords; rr; rr=rr->next)
1986         {
1987             if (rr->resrec.AnonInfo && rr->resrec.AnonInfo->SendNow == mDNSInterfaceMark)
1988             {
1989                 ResourceRecord *nsec3RR = rr->resrec.AnonInfo->nsec3RR;
1990 
1991                 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAuthorities, nsec3RR);
1992                 if (newptr)
1993                 {
1994                     responseptr = newptr;
1995                     debugf("SendDelayedUnicastResponse: Added NSEC3 Record %s on %p", RRDisplayString(m, nsec3RR), intf->InterfaceID);
1996                 }
1997                 else
1998                 {
1999                     // We allocated space and we should not fail. Don't break, we need to clear the SendNow flag.
2000                     LogMsg("SendDelayedUnicastResponse: ERROR!! Cannot Add NSEC3 Record %s on %p", RRDisplayString(m, nsec3RR), intf->InterfaceID);
2001                 }
2002                 rr->resrec.AnonInfo->SendNow = mDNSNULL;
2003             }
2004         }
2005 
2006         // Add additionals, if there's space
2007         while (ResponseRecords && !ResponseRecords->NR_AnswerTo)
2008         {
2009             rr = ResponseRecords;
2010             if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2011                 rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
2012             newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &rr->resrec);
2013             rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
2014 
2015             if (newptr) responseptr = newptr;
2016             if (newptr && m->omsg.h.numAnswers) rr->RequireGoodbye = mDNStrue;
2017             else if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask) rr->ImmedAnswer = mDNSInterfaceMark;
2018             ResponseRecords = rr->NextResponse;
2019             rr->NextResponse    = mDNSNULL;
2020             rr->NR_AnswerTo     = mDNSNULL;
2021             rr->NR_AdditionalTo = mDNSNULL;
2022         }
2023 
2024         if (m->omsg.h.numAnswers)
2025             mDNSSendDNSMessage(m, &m->omsg, responseptr, InterfaceID, mDNSNULL, dest, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2026     }
2027 }
2028 
2029 // CompleteDeregistration guarantees that on exit the record will have been cut from the m->ResourceRecords list
2030 // and the client's mStatus_MemFree callback will have been invoked
2031 mDNSexport void CompleteDeregistration(mDNS *const m, AuthRecord *rr)
2032 {
2033     LogInfo("CompleteDeregistration: called for Resource record %s", ARDisplayString(m, rr));
2034     // Clearing rr->RequireGoodbye signals mDNS_Deregister_internal() that
2035     // it should go ahead and immediately dispose of this registration
2036     rr->resrec.RecordType = kDNSRecordTypeShared;
2037     rr->RequireGoodbye    = mDNSfalse;
2038     rr->WakeUp.HMAC       = zeroEthAddr;
2039     if (rr->AnsweredLocalQ) { AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv); rr->AnsweredLocalQ = mDNSfalse; }
2040     mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);     // Don't touch rr after this
2041 }
2042 
2043 // DiscardDeregistrations is used on shutdown and sleep to discard (forcibly and immediately)
2044 // any deregistering records that remain in the m->ResourceRecords list.
2045 // DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback,
2046 // which may change the record list and/or question list.
2047 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2048 mDNSlocal void DiscardDeregistrations(mDNS *const m)
2049 {
2050     if (m->CurrentRecord)
2051         LogMsg("DiscardDeregistrations ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2052     m->CurrentRecord = m->ResourceRecords;
2053 
2054     while (m->CurrentRecord)
2055     {
2056         AuthRecord *rr = m->CurrentRecord;
2057         if (!AuthRecord_uDNS(rr) && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2058             CompleteDeregistration(m, rr);      // Don't touch rr after this
2059         else
2060             m->CurrentRecord = rr->next;
2061     }
2062 }
2063 
2064 mDNSlocal mStatus GetLabelDecimalValue(const mDNSu8 *const src, mDNSu8 *dst)
2065 {
2066     int i, val = 0;
2067     if (src[0] < 1 || src[0] > 3) return(mStatus_Invalid);
2068     for (i=1; i<=src[0]; i++)
2069     {
2070         if (src[i] < '0' || src[i] > '9') return(mStatus_Invalid);
2071         val = val * 10 + src[i] - '0';
2072     }
2073     if (val > 255) return(mStatus_Invalid);
2074     *dst = (mDNSu8)val;
2075     return(mStatus_NoError);
2076 }
2077 
2078 mDNSlocal mStatus GetIPv4FromName(mDNSAddr *const a, const domainname *const name)
2079 {
2080     int skip = CountLabels(name) - 6;
2081     if (skip < 0) { LogMsg("GetIPFromName: Need six labels in IPv4 reverse mapping name %##s", name); return mStatus_Invalid; }
2082     if (GetLabelDecimalValue(SkipLeadingLabels(name, skip+3)->c, &a->ip.v4.b[0]) ||
2083         GetLabelDecimalValue(SkipLeadingLabels(name, skip+2)->c, &a->ip.v4.b[1]) ||
2084         GetLabelDecimalValue(SkipLeadingLabels(name, skip+1)->c, &a->ip.v4.b[2]) ||
2085         GetLabelDecimalValue(SkipLeadingLabels(name, skip+0)->c, &a->ip.v4.b[3])) return mStatus_Invalid;
2086     a->type = mDNSAddrType_IPv4;
2087     return(mStatus_NoError);
2088 }
2089 
2090 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0'     ) :   \
2091                     ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) :   \
2092                     ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
2093 
2094 mDNSlocal mStatus GetIPv6FromName(mDNSAddr *const a, const domainname *const name)
2095 {
2096     int i, h, l;
2097     const domainname *n;
2098 
2099     int skip = CountLabels(name) - 34;
2100     if (skip < 0) { LogMsg("GetIPFromName: Need 34 labels in IPv6 reverse mapping name %##s", name); return mStatus_Invalid; }
2101 
2102     n = SkipLeadingLabels(name, skip);
2103     for (i=0; i<16; i++)
2104     {
2105         if (n->c[0] != 1) return mStatus_Invalid;
2106         l = HexVal(n->c[1]);
2107         n = (const domainname *)(n->c + 2);
2108 
2109         if (n->c[0] != 1) return mStatus_Invalid;
2110         h = HexVal(n->c[1]);
2111         n = (const domainname *)(n->c + 2);
2112 
2113         if (l<0 || h<0) return mStatus_Invalid;
2114         a->ip.v6.b[15-i] = (mDNSu8)((h << 4) | l);
2115     }
2116 
2117     a->type = mDNSAddrType_IPv6;
2118     return(mStatus_NoError);
2119 }
2120 
2121 mDNSlocal mDNSs32 ReverseMapDomainType(const domainname *const name)
2122 {
2123     int skip = CountLabels(name) - 2;
2124     if (skip >= 0)
2125     {
2126         const domainname *suffix = SkipLeadingLabels(name, skip);
2127         if (SameDomainName(suffix, (const domainname*)"\x7" "in-addr" "\x4" "arpa")) return mDNSAddrType_IPv4;
2128         if (SameDomainName(suffix, (const domainname*)"\x3" "ip6"     "\x4" "arpa")) return mDNSAddrType_IPv6;
2129     }
2130     return(mDNSAddrType_None);
2131 }
2132 
2133 mDNSlocal void SendARP(mDNS *const m, const mDNSu8 op, const AuthRecord *const rr,
2134                        const mDNSv4Addr *const spa, const mDNSEthAddr *const tha, const mDNSv4Addr *const tpa, const mDNSEthAddr *const dst)
2135 {
2136     int i;
2137     mDNSu8 *ptr = m->omsg.data;
2138     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2139     if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2140 
2141     // 0x00 Destination address
2142     for (i=0; i<6; i++) *ptr++ = dst->b[i];
2143 
2144     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2145     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
2146 
2147     // 0x0C ARP Ethertype (0x0806)
2148     *ptr++ = 0x08; *ptr++ = 0x06;
2149 
2150     // 0x0E ARP header
2151     *ptr++ = 0x00; *ptr++ = 0x01;   // Hardware address space; Ethernet = 1
2152     *ptr++ = 0x08; *ptr++ = 0x00;   // Protocol address space; IP = 0x0800
2153     *ptr++ = 6;                     // Hardware address length
2154     *ptr++ = 4;                     // Protocol address length
2155     *ptr++ = 0x00; *ptr++ = op;     // opcode; Request = 1, Response = 2
2156 
2157     // 0x16 Sender hardware address (our MAC address)
2158     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[i];
2159 
2160     // 0x1C Sender protocol address
2161     for (i=0; i<4; i++) *ptr++ = spa->b[i];
2162 
2163     // 0x20 Target hardware address
2164     for (i=0; i<6; i++) *ptr++ = tha->b[i];
2165 
2166     // 0x26 Target protocol address
2167     for (i=0; i<4; i++) *ptr++ = tpa->b[i];
2168 
2169     // 0x2A Total ARP Packet length 42 bytes
2170     mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2171 }
2172 
2173 mDNSlocal mDNSu16 CheckSum(const void *const data, mDNSs32 length, mDNSu32 sum)
2174 {
2175     const mDNSu16 *ptr = data;
2176     while (length > 0) { length -= 2; sum += *ptr++; }
2177     sum = (sum & 0xFFFF) + (sum >> 16);
2178     sum = (sum & 0xFFFF) + (sum >> 16);
2179     return(sum != 0xFFFF ? sum : 0);
2180 }
2181 
2182 mDNSlocal mDNSu16 IPv6CheckSum(const mDNSv6Addr *const src, const mDNSv6Addr *const dst, const mDNSu8 protocol, const void *const data, const mDNSu32 length)
2183 {
2184     IPv6PseudoHeader ph;
2185     ph.src = *src;
2186     ph.dst = *dst;
2187     ph.len.b[0] = length >> 24;
2188     ph.len.b[1] = length >> 16;
2189     ph.len.b[2] = length >> 8;
2190     ph.len.b[3] = length;
2191     ph.pro.b[0] = 0;
2192     ph.pro.b[1] = 0;
2193     ph.pro.b[2] = 0;
2194     ph.pro.b[3] = protocol;
2195     return CheckSum(&ph, sizeof(ph), CheckSum(data, length, 0));
2196 }
2197 
2198 mDNSlocal void SendNDP(mDNS *const m, const mDNSu8 op, const mDNSu8 flags, const AuthRecord *const rr,
2199                        const mDNSv6Addr *const spa, const mDNSEthAddr *const tha, const mDNSv6Addr *const tpa, const mDNSEthAddr *const dst)
2200 {
2201     int i;
2202     mDNSOpaque16 checksum;
2203     mDNSu8 *ptr = m->omsg.data;
2204     // Some recipient hosts seem to ignore Neighbor Solicitations if the IPv6-layer destination address is not the
2205     // appropriate IPv6 solicited node multicast address, so we use that IPv6-layer destination address, even though
2206     // at the Ethernet-layer we unicast the packet to the intended target, to avoid wasting network bandwidth.
2207     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] } };
2208     const mDNSv6Addr *const v6dst = (op == NDP_Sol) ? &mc : tpa;
2209     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, rr->resrec.InterfaceID);
2210     if (!intf) { LogMsg("SendNDP: No interface with InterfaceID %p found %s", rr->resrec.InterfaceID, ARDisplayString(m,rr)); return; }
2211 
2212     // 0x00 Destination address
2213     for (i=0; i<6; i++) *ptr++ = dst->b[i];
2214     // Right now we only send Neighbor Solicitations to verify whether the host we're proxying for has gone to sleep yet.
2215     // Since we know who we're looking for, we send it via Ethernet-layer unicast, rather than bothering every host on the
2216     // link with a pointless link-layer multicast.
2217     // Should we want to send traditional Neighbor Solicitations in the future, where we really don't know in advance what
2218     // Ethernet-layer address we're looking for, we'll need to send to the appropriate Ethernet-layer multicast address:
2219     // *ptr++ = 0x33;
2220     // *ptr++ = 0x33;
2221     // *ptr++ = 0xFF;
2222     // *ptr++ = tpa->b[0xD];
2223     // *ptr++ = tpa->b[0xE];
2224     // *ptr++ = tpa->b[0xF];
2225 
2226     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
2227     for (i=0; i<6; i++)
2228 	if (tha)
2229 	    *ptr++ = tha->b[i];
2230 	else
2231 	    *ptr++ = intf->MAC.b[i];
2232 
2233     // 0x0C IPv6 Ethertype (0x86DD)
2234     *ptr++ = 0x86; *ptr++ = 0xDD;
2235 
2236     // 0x0E IPv6 header
2237     *ptr++ = 0x60; *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;     // Version, Traffic Class, Flow Label
2238     *ptr++ = 0x00; *ptr++ = 0x20;                                   // Length
2239     *ptr++ = 0x3A;                                                  // Protocol == ICMPv6
2240     *ptr++ = 0xFF;                                                  // Hop Limit
2241 
2242     // 0x16 Sender IPv6 address
2243     for (i=0; i<16; i++) *ptr++ = spa->b[i];
2244 
2245     // 0x26 Destination IPv6 address
2246     for (i=0; i<16; i++) *ptr++ = v6dst->b[i];
2247 
2248     // 0x36 NDP header
2249     *ptr++ = op;                    // 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
2250     *ptr++ = 0x00;                  // Code
2251     *ptr++ = 0x00; *ptr++ = 0x00;   // Checksum placeholder (0x38, 0x39)
2252     *ptr++ = flags;
2253     *ptr++ = 0x00; *ptr++ = 0x00; *ptr++ = 0x00;
2254 
2255     if (op == NDP_Sol)  // Neighbor Solicitation. The NDP "target" is the address we seek.
2256     {
2257         // 0x3E NDP target.
2258         for (i=0; i<16; i++) *ptr++ = tpa->b[i];
2259         // 0x4E Source Link-layer Address
2260         // <http://www.ietf.org/rfc/rfc2461.txt>
2261         // MUST NOT be included when the source IP address is the unspecified address.
2262         // Otherwise, on link layers that have addresses this option MUST be included
2263         // in multicast solicitations and SHOULD be included in unicast solicitations.
2264         if (!mDNSIPv6AddressIsZero(*spa))
2265         {
2266             *ptr++ = NDP_SrcLL; // Option Type 1 == Source Link-layer Address
2267             *ptr++ = 0x01;      // Option length 1 (in units of 8 octets)
2268             for (i=0; i<6; i++)
2269 		if (tha)
2270 		    *ptr++ = tha->b[i];
2271 		else
2272 		    *ptr++ = intf->MAC.b[i];
2273         }
2274     }
2275     else            // Neighbor Advertisement. The NDP "target" is the address we're giving information about.
2276     {
2277         // 0x3E NDP target.
2278         for (i=0; i<16; i++) *ptr++ = spa->b[i];
2279         // 0x4E Target Link-layer Address
2280         *ptr++ = NDP_TgtLL; // Option Type 2 == Target Link-layer Address
2281         *ptr++ = 0x01;      // Option length 1 (in units of 8 octets)
2282         for (i=0; i<6; i++)
2283 	    if (tha)
2284 		*ptr++ = tha->b[i];
2285 	    else
2286 		*ptr++ = intf->MAC.b[i];
2287     }
2288 
2289     // 0x4E or 0x56 Total NDP Packet length 78 or 86 bytes
2290     m->omsg.data[0x13] = ptr - &m->omsg.data[0x36];     // Compute actual length
2291     checksum.NotAnInteger = ~IPv6CheckSum(spa, v6dst, 0x3A, &m->omsg.data[0x36], m->omsg.data[0x13]);
2292     m->omsg.data[0x38] = checksum.b[0];
2293     m->omsg.data[0x39] = checksum.b[1];
2294 
2295     mDNSPlatformSendRawPacket(m->omsg.data, ptr, rr->resrec.InterfaceID);
2296 }
2297 
2298 mDNSlocal void SetupTracerOpt(const mDNS *const m, rdataOPT *const Trace)
2299 {
2300     mDNSu32 DNS_VERS = _DNS_SD_H;
2301     Trace->u.tracer.platf    = m->mDNS_plat;
2302     Trace->u.tracer.mDNSv    = DNS_VERS;
2303 
2304     Trace->opt              = kDNSOpt_Trace;
2305     Trace->optlen           = DNSOpt_TraceData_Space - 4;
2306 }
2307 
2308 mDNSlocal void SetupOwnerOpt(const mDNS *const m, const NetworkInterfaceInfo *const intf, rdataOPT *const owner)
2309 {
2310     owner->u.owner.vers     = 0;
2311     owner->u.owner.seq      = m->SleepSeqNum;
2312     owner->u.owner.HMAC     = m->PrimaryMAC;
2313     owner->u.owner.IMAC     = intf->MAC;
2314     owner->u.owner.password = zeroEthAddr;
2315 
2316     // Don't try to compute the optlen until *after* we've set up the data fields
2317     // 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
2318     owner->opt              = kDNSOpt_Owner;
2319     owner->optlen           = DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) - 4;
2320 }
2321 
2322 mDNSlocal void GrantUpdateCredit(AuthRecord *rr)
2323 {
2324     if (++rr->UpdateCredits >= kMaxUpdateCredits) rr->NextUpdateCredit = 0;
2325     else rr->NextUpdateCredit = NonZeroTime(rr->NextUpdateCredit + kUpdateCreditRefreshInterval);
2326 }
2327 
2328 mDNSlocal mDNSBool ShouldSendGoodbyesBeforeSleep(mDNS *const m, const NetworkInterfaceInfo *intf, AuthRecord *rr)
2329 {
2330     // If there are no sleep proxies, we set the state to SleepState_Sleeping explicitly
2331     // and hence there is no need to check for Transfering state. But if we have sleep
2332     // proxies and partially sending goodbyes for some records, we will be in Transfering
2333     // state and hence need to make sure that we send goodbyes in that case too. Checking whether
2334     // we are not awake handles both cases.
2335     if ((rr->AuthFlags & AuthFlagsWakeOnly) && (m->SleepState != SleepState_Awake))
2336     {
2337         debugf("ShouldSendGoodbyesBeforeSleep: marking for goodbye", ARDisplayString(m, rr));
2338         return mDNStrue;
2339     }
2340 
2341     if (m->SleepState != SleepState_Sleeping)
2342         return mDNSfalse;
2343 
2344     // If we are going to sleep and in SleepState_Sleeping, SendGoodbyes on the interface tell you
2345     // whether you can send goodbyes or not.
2346     if (!intf->SendGoodbyes)
2347     {
2348         debugf("ShouldSendGoodbyesBeforeSleep: not sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2349         return mDNSfalse;
2350     }
2351     else
2352     {
2353         debugf("ShouldSendGoodbyesBeforeSleep: sending goodbye %s, int %p", ARDisplayString(m, rr), intf->InterfaceID);
2354         return mDNStrue;
2355     }
2356 }
2357 
2358 // Note about acceleration of announcements to facilitate automatic coalescing of
2359 // multiple independent threads of announcements into a single synchronized thread:
2360 // The announcements in the packet may be at different stages of maturity;
2361 // One-second interval, two-second interval, four-second interval, and so on.
2362 // After we've put in all the announcements that are due, we then consider
2363 // whether there are other nearly-due announcements that are worth accelerating.
2364 // To be eligible for acceleration, a record MUST NOT be older (further along
2365 // its timeline) than the most mature record we've already put in the packet.
2366 // In other words, younger records can have their timelines accelerated to catch up
2367 // with their elder bretheren; this narrows the age gap and helps them eventually get in sync.
2368 // Older records cannot have their timelines accelerated; this would just widen
2369 // the gap between them and their younger bretheren and get them even more out of sync.
2370 
2371 // Note: SendResponses calls mDNS_Deregister_internal which can call a user callback, which may change
2372 // the record list and/or question list.
2373 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
2374 mDNSlocal void SendResponses(mDNS *const m)
2375 {
2376     int pktcount = 0;
2377     AuthRecord *rr, *r2;
2378     mDNSs32 maxExistingAnnounceInterval = 0;
2379     const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
2380 
2381     m->NextScheduledResponse = m->timenow + 0x78000000;
2382 
2383     if (m->SleepState == SleepState_Transferring) RetrySPSRegistrations(m);
2384 
2385     for (rr = m->ResourceRecords; rr; rr=rr->next)
2386         if (rr->ImmedUnicast)
2387         {
2388             mDNSAddr v4 = { mDNSAddrType_IPv4, {{{0}}} };
2389             mDNSAddr v6 = { mDNSAddrType_IPv6, {{{0}}} };
2390             v4.ip.v4 = rr->v4Requester;
2391             v6.ip.v6 = rr->v6Requester;
2392             if (!mDNSIPv4AddressIsZero(rr->v4Requester)) SendDelayedUnicastResponse(m, &v4, rr->ImmedAnswer);
2393             if (!mDNSIPv6AddressIsZero(rr->v6Requester)) SendDelayedUnicastResponse(m, &v6, rr->ImmedAnswer);
2394             if (rr->ImmedUnicast)
2395             {
2396                 LogMsg("SendResponses: ERROR: rr->ImmedUnicast still set: %s", ARDisplayString(m, rr));
2397                 rr->ImmedUnicast = mDNSfalse;
2398             }
2399         }
2400 
2401     // ***
2402     // *** 1. Setup: Set the SendRNow and ImmedAnswer fields to indicate which interface(s) the records need to be sent on
2403     // ***
2404 
2405     // Run through our list of records, and decide which ones we're going to announce on all interfaces
2406     for (rr = m->ResourceRecords; rr; rr=rr->next)
2407     {
2408         while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
2409         if (TimeToAnnounceThisRecord(rr, m->timenow))
2410         {
2411             if (rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2412             {
2413                 if (!rr->WakeUp.HMAC.l[0])
2414                 {
2415                     if (rr->AnnounceCount) rr->ImmedAnswer = mDNSInterfaceMark;     // Send goodbye packet on all interfaces
2416                 }
2417                 else
2418                 {
2419                     LogSPS("SendResponses: Sending wakeup %2d for %.6a %s", rr->AnnounceCount-3, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
2420                     SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password);
2421                     for (r2 = rr; r2; r2=r2->next)
2422                         if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) &&
2423                             mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
2424                         {
2425                             // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
2426                             // owner, because these packets can cause some IPv6 stacks to falsely conclude that there's an address conflict.
2427                             if (r2->AddressProxy.type == mDNSAddrType_IPv6 && r2->AnnounceCount == WakeupCount)
2428                             {
2429                                 LogSPS("NDP Announcement %2d Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
2430                                        r2->AnnounceCount-3, &r2->WakeUp.HMAC, &r2->WakeUp.IMAC, ARDisplayString(m,r2));
2431                                 SendNDP(m, NDP_Adv, NDP_Override, r2, &r2->AddressProxy.ip.v6, &r2->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
2432                             }
2433                             r2->LastAPTime = m->timenow;
2434                             // After 15 wakeups without success (maybe host has left the network) send three goodbyes instead
2435                             if (--r2->AnnounceCount <= GoodbyeCount) r2->WakeUp.HMAC = zeroEthAddr;
2436                         }
2437                 }
2438             }
2439             else if (ResourceRecordIsValidAnswer(rr))
2440             {
2441                 if (rr->AddressProxy.type)
2442                 {
2443                     if (!mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
2444                     {
2445                         rr->AnnounceCount--;
2446                         rr->ThisAPInterval *= 2;
2447                         rr->LastAPTime = m->timenow;
2448                         if (rr->AddressProxy.type == mDNSAddrType_IPv4)
2449                         {
2450                             LogSPS("ARP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2451                                     rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2452                             SendARP(m, 1, rr, &rr->AddressProxy.ip.v4, &zeroEthAddr, &rr->AddressProxy.ip.v4, &onesEthAddr);
2453                         }
2454                         else if (rr->AddressProxy.type == mDNSAddrType_IPv6)
2455                         {
2456                             LogSPS("NDP Announcement %2d Capturing traffic for H-MAC %.6a I-MAC %.6a %s",
2457                                     rr->AnnounceCount, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
2458                             SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
2459                         }
2460                     }
2461                 }
2462                 else
2463                 {
2464                     rr->ImmedAnswer = mDNSInterfaceMark;        // Send on all interfaces
2465                     if (maxExistingAnnounceInterval < rr->ThisAPInterval)
2466                         maxExistingAnnounceInterval = rr->ThisAPInterval;
2467                     if (rr->UpdateBlocked) rr->UpdateBlocked = 0;
2468                 }
2469             }
2470         }
2471     }
2472 
2473     // Any interface-specific records we're going to send are marked as being sent on all appropriate interfaces (which is just one)
2474     // Eligible records that are more than half-way to their announcement time are accelerated
2475     for (rr = m->ResourceRecords; rr; rr=rr->next)
2476         if ((rr->resrec.InterfaceID && rr->ImmedAnswer) ||
2477             (rr->ThisAPInterval <= maxExistingAnnounceInterval &&
2478              TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2) &&
2479              !rr->AddressProxy.type &&                  // Don't include ARP Annoucements when considering which records to accelerate
2480              ResourceRecordIsValidAnswer(rr)))
2481             rr->ImmedAnswer = mDNSInterfaceMark;        // Send on all interfaces
2482 
2483     // When sending SRV records (particularly when announcing a new service) automatically add related Address record(s) as additionals
2484     // Note: Currently all address records are interface-specific, so it's safe to set ImmedAdditional to their InterfaceID,
2485     // which will be non-null. If by some chance there is an address record that's not interface-specific (should never happen)
2486     // then all that means is that it won't get sent -- which would not be the end of the world.
2487     for (rr = m->ResourceRecords; rr; rr=rr->next)
2488     {
2489         if (rr->ImmedAnswer && rr->resrec.rrtype == kDNSType_SRV)
2490             for (r2=m->ResourceRecords; r2; r2=r2->next)                // Scan list of resource records
2491                 if (RRTypeIsAddressType(r2->resrec.rrtype) &&           // For all address records (A/AAAA) ...
2492                     ResourceRecordIsValidAnswer(r2) &&                  // ... which are valid for answer ...
2493                     rr->LastMCTime - r2->LastMCTime >= 0 &&             // ... which we have not sent recently ...
2494                     rr->resrec.rdatahash == r2->resrec.namehash &&      // ... whose name is the name of the SRV target
2495                     SameDomainName(&rr->resrec.rdata->u.srv.target, r2->resrec.name) &&
2496                     (rr->ImmedAnswer == mDNSInterfaceMark || rr->ImmedAnswer == r2->resrec.InterfaceID))
2497                     r2->ImmedAdditional = r2->resrec.InterfaceID;       // ... then mark this address record for sending too
2498         // We also make sure we send the DeviceInfo TXT record too, if necessary
2499         // We check for RecordType == kDNSRecordTypeShared because we don't want to tag the
2500         // DeviceInfo TXT record onto a goodbye packet (RecordType == kDNSRecordTypeDeregistering).
2501         if (rr->ImmedAnswer && rr->resrec.RecordType == kDNSRecordTypeShared && rr->resrec.rrtype == kDNSType_PTR)
2502             if (ResourceRecordIsValidAnswer(&m->DeviceInfo) && SameDomainLabel(rr->resrec.rdata->u.name.c, m->DeviceInfo.resrec.name->c))
2503             {
2504                 if (!m->DeviceInfo.ImmedAnswer) m->DeviceInfo.ImmedAnswer = rr->ImmedAnswer;
2505                 else m->DeviceInfo.ImmedAnswer = mDNSInterfaceMark;
2506             }
2507     }
2508 
2509     // If there's a record which is supposed to be unique that we're going to send, then make sure that we give
2510     // the whole RRSet as an atomic unit. That means that if we have any other records with the same name/type/class
2511     // then we need to mark them for sending too. Otherwise, if we set the kDNSClass_UniqueRRSet bit on a
2512     // record, then other RRSet members that have not been sent recently will get flushed out of client caches.
2513     // -- 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
2514     // -- If any record is marked to be sent on all interfaces, make sure the whole set is marked to be sent on all interfaces
2515     for (rr = m->ResourceRecords; rr; rr=rr->next)
2516         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2517         {
2518             if (rr->ImmedAnswer)            // If we're sending this as answer, see that its whole RRSet is similarly marked
2519             {
2520                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2521                     if (ResourceRecordIsValidAnswer(r2))
2522                         if (r2->ImmedAnswer != mDNSInterfaceMark &&
2523                             r2->ImmedAnswer != rr->ImmedAnswer && SameResourceRecordSignature(r2, rr))
2524                             r2->ImmedAnswer = !r2->ImmedAnswer ? rr->ImmedAnswer : mDNSInterfaceMark;
2525             }
2526             else if (rr->ImmedAdditional)   // If we're sending this as additional, see that its whole RRSet is similarly marked
2527             {
2528                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
2529                     if (ResourceRecordIsValidAnswer(r2))
2530                         if (r2->ImmedAdditional != rr->ImmedAdditional && SameResourceRecordSignature(r2, rr))
2531                             r2->ImmedAdditional = rr->ImmedAdditional;
2532             }
2533         }
2534 
2535     // Now set SendRNow state appropriately
2536     for (rr = m->ResourceRecords; rr; rr=rr->next)
2537     {
2538         if (rr->ImmedAnswer == mDNSInterfaceMark)       // Sending this record on all appropriate interfaces
2539         {
2540             rr->SendRNow = !intf ? mDNSNULL : (rr->resrec.InterfaceID) ? rr->resrec.InterfaceID : intf->InterfaceID;
2541             rr->ImmedAdditional = mDNSNULL;             // No need to send as additional if sending as answer
2542             rr->LastMCTime      = m->timenow;
2543             rr->LastMCInterface = rr->ImmedAnswer;
2544             // If we're announcing this record, and it's at least half-way to its ordained time, then consider this announcement done
2545             if (TimeToAnnounceThisRecord(rr, m->timenow + rr->ThisAPInterval/2))
2546             {
2547                 rr->AnnounceCount--;
2548                 if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
2549                     rr->ThisAPInterval *= 2;
2550                 rr->LastAPTime = m->timenow;
2551                 debugf("Announcing %##s (%s) %d", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), rr->AnnounceCount);
2552             }
2553         }
2554         else if (rr->ImmedAnswer)                       // Else, just respond to a single query on single interface:
2555         {
2556             rr->SendRNow        = rr->ImmedAnswer;      // Just respond on that interface
2557             rr->ImmedAdditional = mDNSNULL;             // No need to send as additional too
2558             rr->LastMCTime      = m->timenow;
2559             rr->LastMCInterface = rr->ImmedAnswer;
2560         }
2561         SetNextAnnounceProbeTime(m, rr);
2562         //if (rr->SendRNow) LogMsg("%-15.4a %s", &rr->v4Requester, ARDisplayString(m, rr));
2563     }
2564 
2565     // ***
2566     // *** 2. Loop through interface list, sending records as appropriate
2567     // ***
2568 
2569     while (intf)
2570     {
2571         int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
2572         int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
2573         int numDereg    = 0;
2574         int numAnnounce = 0;
2575         int numAnswer   = 0;
2576         int AnoninfoSpace = 0;
2577         mDNSu8 *responseptr = m->omsg.data;
2578         mDNSu8 *newptr;
2579         InitializeDNSMessage(&m->omsg.h, zeroID, ResponseFlags);
2580 
2581         // First Pass. Look for:
2582         // 1. Deregistering records that need to send their goodbye packet
2583         // 2. Updated records that need to retract their old data
2584         // 3. Answers and announcements we need to send
2585         for (rr = m->ResourceRecords; rr; rr=rr->next)
2586         {
2587 
2588             // Skip this interface if the record InterfaceID is *Any and the record is not
2589             // appropriate for the interface type.
2590             if ((rr->SendRNow == intf->InterfaceID) &&
2591                 ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf)))
2592             {
2593                 //  LogInfo("SendResponses: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, rr->SendRNow));
2594                 rr->SendRNow = GetNextActiveInterfaceID(intf);
2595             }
2596             else if (rr->SendRNow == intf->InterfaceID)
2597             {
2598                 RData  *OldRData    = rr->resrec.rdata;
2599                 mDNSu16 oldrdlength = rr->resrec.rdlength;
2600                 mDNSu8 active = (mDNSu8)
2601                                 (rr->resrec.RecordType != kDNSRecordTypeDeregistering && !ShouldSendGoodbyesBeforeSleep(m, intf, rr));
2602                 newptr = mDNSNULL;
2603                 if (rr->NewRData && active)
2604                 {
2605                     // See if we should send a courtesy "goodbye" for the old data before we replace it.
2606                     if (ResourceRecordIsValidAnswer(rr) && rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
2607                     {
2608                         newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, 0);
2609                         if (newptr) { responseptr = newptr; numDereg++; rr->RequireGoodbye = mDNSfalse; }
2610                         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
2611                     }
2612                     SetNewRData(&rr->resrec, rr->NewRData, rr->newrdlength);
2613                 }
2614 
2615                 if (rr->resrec.AnonInfo)
2616                 {
2617                     int tmp = AnonInfoSpace(rr->resrec.AnonInfo);
2618 
2619                     AnoninfoSpace += tmp;
2620                     // Adjust OwnerRecordSpace/TraceRecordSpace which is used by PutRR_OS_TTL below so that
2621                     // we have space to put in the NSEC3 record in the authority section.
2622                     OwnerRecordSpace += tmp;
2623                     TraceRecordSpace += tmp;
2624                 }
2625 
2626                 if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2627                     rr->resrec.rrclass |= kDNSClass_UniqueRRSet;        // Temporarily set the cache flush bit so PutResourceRecord will set it
2628                 newptr = PutRR_OS_TTL(responseptr, &m->omsg.h.numAnswers, &rr->resrec, active ? rr->resrec.rroriginalttl : 0);
2629                 rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;           // Make sure to clear cache flush bit back to normal state
2630                 if (newptr)
2631                 {
2632                     responseptr = newptr;
2633                     rr->RequireGoodbye = active;
2634                     if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) numDereg++;
2635                     else if (rr->LastAPTime == m->timenow) numAnnounce++;else numAnswer++;
2636                 }
2637 
2638                 if (rr->NewRData && active)
2639                     SetNewRData(&rr->resrec, OldRData, oldrdlength);
2640 
2641                 // The first time through (pktcount==0), if this record is verified unique
2642                 // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2643                 if (!pktcount && active && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2644                     rr->SendNSECNow = mDNSInterfaceMark;
2645 
2646                 if (newptr)     // If succeeded in sending, advance to next interface
2647                 {
2648                     if (rr->resrec.AnonInfo)
2649                     {
2650                         debugf("SendResponses: Marking %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2651                                 TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2652                         rr->resrec.AnonInfo->SendNow = intf->InterfaceID;
2653                     }
2654 
2655                     // If sending on all interfaces, go to next interface; else we're finished now
2656                     if (rr->ImmedAnswer == mDNSInterfaceMark && rr->resrec.InterfaceID == mDNSInterface_Any)
2657                         rr->SendRNow = GetNextActiveInterfaceID(intf);
2658                     else
2659                         rr->SendRNow = mDNSNULL;
2660                 }
2661             }
2662         }
2663 
2664         // Get the reserved space back
2665         OwnerRecordSpace -= AnoninfoSpace;
2666         TraceRecordSpace -= AnoninfoSpace;
2667         newptr = responseptr;
2668         for (rr = m->ResourceRecords; rr; rr=rr->next)
2669         {
2670             if (rr->resrec.AnonInfo && rr->resrec.AnonInfo->SendNow == intf->InterfaceID)
2671             {
2672                 ResourceRecord *nsec3RR = rr->resrec.AnonInfo->nsec3RR;
2673 
2674                 newptr = PutRR_OS_TTL(newptr, &m->omsg.h.numAuthorities, nsec3RR,  nsec3RR->rroriginalttl);
2675                 if (newptr)
2676                 {
2677                     responseptr = newptr;
2678                     debugf("SendResponses: Added NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2679                             TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2680                 }
2681                 else
2682                 {
2683                     LogMsg("SendResponses: Cannot add NSEC3 %s, OwnerRecordSpace %d, TraceRecordSpace %d, limit %p", ARDisplayString(m, rr), OwnerRecordSpace,
2684                             TraceRecordSpace, m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace);
2685                 }
2686                 rr->resrec.AnonInfo->SendNow = mDNSNULL;
2687             }
2688         }
2689         // Second Pass. Add additional records, if there's space.
2690         newptr = responseptr;
2691         for (rr = m->ResourceRecords; rr; rr=rr->next)
2692             if (rr->ImmedAdditional == intf->InterfaceID)
2693                 if (ResourceRecordIsValidAnswer(rr))
2694                 {
2695                     // If we have at least one answer already in the packet, then plan to add additionals too
2696                     mDNSBool SendAdditional = (m->omsg.h.numAnswers > 0);
2697 
2698                     // If we're not planning to send any additionals, but this record is a unique one, then
2699                     // make sure we haven't already sent any other members of its RRSet -- if we have, then they
2700                     // will have had the cache flush bit set, so now we need to finish the job and send the rest.
2701                     if (!SendAdditional && (rr->resrec.RecordType & kDNSRecordTypeUniqueMask))
2702                     {
2703                         const AuthRecord *a;
2704                         for (a = m->ResourceRecords; a; a=a->next)
2705                             if (a->LastMCTime      == m->timenow &&
2706                                 a->LastMCInterface == intf->InterfaceID &&
2707                                 SameResourceRecordSignature(a, rr)) { SendAdditional = mDNStrue; break; }
2708                     }
2709                     if (!SendAdditional)                    // If we don't want to send this after all,
2710                         rr->ImmedAdditional = mDNSNULL;     // then cancel its ImmedAdditional field
2711                     else if (newptr)                        // Else, try to add it if we can
2712                     {
2713                         // The first time through (pktcount==0), if this record is verified unique
2714                         // (i.e. typically A, AAAA, SRV, TXT and reverse-mapping PTR), set the flag to add an NSEC too.
2715                         if (!pktcount && (rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && !rr->SendNSECNow)
2716                             rr->SendNSECNow = mDNSInterfaceMark;
2717 
2718                         if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
2719                             rr->resrec.rrclass |= kDNSClass_UniqueRRSet;    // Temporarily set the cache flush bit so PutResourceRecord will set it
2720                         newptr = PutRR_OS(newptr, &m->omsg.h.numAdditionals, &rr->resrec);
2721                         rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;       // Make sure to clear cache flush bit back to normal state
2722                         if (newptr)
2723                         {
2724                             responseptr = newptr;
2725                             rr->ImmedAdditional = mDNSNULL;
2726                             rr->RequireGoodbye = mDNStrue;
2727                             // If we successfully put this additional record in the packet, we record LastMCTime & LastMCInterface.
2728                             // This matters particularly in the case where we have more than one IPv6 (or IPv4) address, because otherwise,
2729                             // when we see our own multicast with the cache flush bit set, if we haven't set LastMCTime, then we'll get
2730                             // all concerned and re-announce our record again to make sure it doesn't get flushed from peer caches.
2731                             rr->LastMCTime      = m->timenow;
2732                             rr->LastMCInterface = intf->InterfaceID;
2733                         }
2734                     }
2735                 }
2736 
2737         // Third Pass. Add NSEC records, if there's space.
2738         // When we're generating an NSEC record in response to a specify query for that type
2739         // (recognized by rr->SendNSECNow == intf->InterfaceID) we should really put the NSEC in the Answer Section,
2740         // not Additional Section, but for now it's easier to handle both cases in this Additional Section loop here.
2741         for (rr = m->ResourceRecords; rr; rr=rr->next)
2742             if (rr->SendNSECNow == mDNSInterfaceMark || rr->SendNSECNow == intf->InterfaceID)
2743             {
2744                 AuthRecord nsec;
2745                 mDNSu8 *ptr;
2746                 int len;
2747                 mDNS_SetupResourceRecord(&nsec, mDNSNULL, mDNSInterface_Any, kDNSType_NSEC, rr->resrec.rroriginalttl, kDNSRecordTypeUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2748                 nsec.resrec.rrclass |= kDNSClass_UniqueRRSet;
2749                 AssignDomainName(&nsec.namestorage, rr->resrec.name);
2750                 ptr = nsec.rdatastorage.u.data;
2751                 len = DomainNameLength(rr->resrec.name);
2752                 // We have a nxt name followed by window number, window length and a window bitmap
2753                 nsec.resrec.rdlength = len + 2 + NSEC_MCAST_WINDOW_SIZE;
2754                 if (nsec.resrec.rdlength <= StandardAuthRDSize)
2755                 {
2756                     mDNSPlatformMemZero(ptr, nsec.resrec.rdlength);
2757                     AssignDomainName((domainname *)ptr, rr->resrec.name);
2758                     ptr += len;
2759                     *ptr++ = 0; // window number
2760                     *ptr++ = NSEC_MCAST_WINDOW_SIZE; // window length
2761                     for (r2 = m->ResourceRecords; r2; r2=r2->next)
2762                         if (ResourceRecordIsValidAnswer(r2) && SameResourceRecordNameClassInterface(r2, rr))
2763                         {
2764                             if (r2->resrec.rrtype >= kDNSQType_ANY) { LogMsg("SendResponses: Can't create NSEC for record %s", ARDisplayString(m, r2)); break; }
2765                             else ptr[r2->resrec.rrtype >> 3] |= 128 >> (r2->resrec.rrtype & 7);
2766                         }
2767                     newptr = responseptr;
2768                     if (!r2)    // If we successfully built our NSEC record, add it to the packet now
2769                     {
2770                         newptr = PutRR_OS(responseptr, &m->omsg.h.numAdditionals, &nsec.resrec);
2771                         if (newptr) responseptr = newptr;
2772                     }
2773                 }
2774                 else LogMsg("SendResponses: not enough space (%d)  in authrecord for nsec", nsec.resrec.rdlength);
2775 
2776                 // If we successfully put the NSEC record, clear the SendNSECNow flag
2777                 // If we consider this NSEC optional, then we unconditionally clear the SendNSECNow flag, even if we fail to put this additional record
2778                 if (newptr || rr->SendNSECNow == mDNSInterfaceMark)
2779                 {
2780                     rr->SendNSECNow = mDNSNULL;
2781                     // Run through remainder of list clearing SendNSECNow flag for all other records which would generate the same NSEC
2782                     for (r2 = rr->next; r2; r2=r2->next)
2783                         if (SameResourceRecordNameClassInterface(r2, rr))
2784                             if (r2->SendNSECNow == mDNSInterfaceMark || r2->SendNSECNow == intf->InterfaceID)
2785                                 r2->SendNSECNow = mDNSNULL;
2786                 }
2787             }
2788 
2789         if (m->omsg.h.numAnswers || m->omsg.h.numAdditionals)
2790         {
2791             // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
2792             if (OwnerRecordSpace || TraceRecordSpace)
2793             {
2794                 AuthRecord opt;
2795                 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
2796                 opt.resrec.rrclass    = NormalMaxDNSMessageData;
2797                 opt.resrec.rdlength   = sizeof(rdataOPT);
2798                 opt.resrec.rdestimate = sizeof(rdataOPT);
2799                 if (OwnerRecordSpace && TraceRecordSpace)
2800                 {
2801                     opt.resrec.rdlength   += sizeof(rdataOPT); // Two options in this OPT record
2802                     opt.resrec.rdestimate += sizeof(rdataOPT);
2803                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2804                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
2805                 }
2806                 else if (OwnerRecordSpace)
2807                 {
2808                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
2809                 }
2810                 else if (TraceRecordSpace)
2811                 {
2812                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
2813                 }
2814                 newptr = PutResourceRecord(&m->omsg, responseptr, &m->omsg.h.numAdditionals, &opt.resrec);
2815                 if (newptr)
2816                 {
2817                     responseptr = newptr;
2818                     LogInfo("SendResponses put %s %s: %s %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", intf->ifname, ARDisplayString(m, &opt));
2819                 }
2820                 else if (m->omsg.h.numAnswers + m->omsg.h.numAuthorities + m->omsg.h.numAdditionals == 1)
2821                 {
2822                     LogInfo("SendResponses: No space in packet for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
2823                             m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2824                 }
2825                 else
2826                 {
2827                     LogMsg("SendResponses: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
2828                            m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
2829                 }
2830             }
2831 
2832             debugf("SendResponses: Sending %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s on %p",
2833                    numDereg,                 numDereg                 == 1 ? "" : "s",
2834                    numAnnounce,              numAnnounce              == 1 ? "" : "s",
2835                    numAnswer,                numAnswer                == 1 ? "" : "s",
2836                    m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s", intf->InterfaceID);
2837 
2838             if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2839             if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, responseptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, mDNSfalse);
2840             if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
2841             if (++pktcount >= 1000) { LogMsg("SendResponses exceeded loop limit %d: giving up", pktcount); break; }
2842             // There might be more things to send on this interface, so go around one more time and try again.
2843         }
2844         else    // Nothing more to send on this interface; go to next
2845         {
2846             const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
2847             #if MDNS_DEBUGMSGS && 0
2848             const char *const msg = next ? "SendResponses: Nothing more on %p; moving to %p" : "SendResponses: Nothing more on %p";
2849             debugf(msg, intf, next);
2850             #endif
2851             intf = next;
2852             pktcount = 0;       // When we move to a new interface, reset packet count back to zero -- NSEC generation logic uses it
2853         }
2854     }
2855 
2856     // ***
2857     // *** 3. Cleanup: Now that everything is sent, call client callback functions, and reset state variables
2858     // ***
2859 
2860     if (m->CurrentRecord)
2861         LogMsg("SendResponses ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
2862     m->CurrentRecord = m->ResourceRecords;
2863     while (m->CurrentRecord)
2864     {
2865         rr = m->CurrentRecord;
2866         m->CurrentRecord = rr->next;
2867 
2868         if (rr->SendRNow)
2869         {
2870             if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P)
2871                 LogInfo("SendResponses: No active interface %d to send: %d %02X %s",
2872                      (uint32_t)rr->SendRNow, (uint32_t)rr->resrec.InterfaceID, rr->resrec.RecordType, ARDisplayString(m, rr));
2873             rr->SendRNow = mDNSNULL;
2874         }
2875 
2876         if (rr->ImmedAnswer || rr->resrec.RecordType == kDNSRecordTypeDeregistering)
2877         {
2878             if (rr->NewRData) CompleteRDataUpdate(m, rr);   // Update our rdata, clear the NewRData pointer, and return memory to the client
2879 
2880             if (rr->resrec.RecordType == kDNSRecordTypeDeregistering && rr->AnnounceCount == 0)
2881             {
2882                 // For Unicast, when we get the response from the server, we will call CompleteDeregistration
2883                 if (!AuthRecord_uDNS(rr)) CompleteDeregistration(m, rr);        // Don't touch rr after this
2884             }
2885             else
2886             {
2887                 rr->ImmedAnswer  = mDNSNULL;
2888                 rr->ImmedUnicast = mDNSfalse;
2889                 rr->v4Requester  = zerov4Addr;
2890                 rr->v6Requester  = zerov6Addr;
2891             }
2892         }
2893     }
2894     verbosedebugf("SendResponses: Next in %ld ticks", m->NextScheduledResponse - m->timenow);
2895 }
2896 
2897 // Calling CheckCacheExpiration() is an expensive operation because it has to look at the entire cache,
2898 // so we want to be lazy about how frequently we do it.
2899 // 1. If a cache record is currently referenced by *no* active questions,
2900 //    then we don't mind expiring it up to a minute late (who will know?)
2901 // 2. Else, if a cache record is due for some of its final expiration queries,
2902 //    we'll allow them to be late by up to 2% of the TTL
2903 // 3. Else, if a cache record has completed all its final expiration queries without success,
2904 //    and is expiring, and had an original TTL more than ten seconds, we'll allow it to be one second late
2905 // 4. Else, it is expiring and had an original TTL of ten seconds or less (includes explicit goodbye packets),
2906 //    so allow at most 1/10 second lateness
2907 // 5. For records with rroriginalttl set to zero, that means we really want to delete them immediately
2908 //    (we have a new record with DelayDelivery set, waiting for the old record to go away before we can notify clients).
2909 #define CacheCheckGracePeriod(RR) (                                                   \
2910         ((RR)->CRActiveQuestion == mDNSNULL            ) ? (60 * mDNSPlatformOneSecond) : \
2911         ((RR)->UnansweredQueries < MaxUnansweredQueries) ? (TicksTTL(rr)/50)            : \
2912         ((RR)->resrec.rroriginalttl > 10               ) ? (mDNSPlatformOneSecond)      : \
2913         ((RR)->resrec.rroriginalttl > 0                ) ? (mDNSPlatformOneSecond/10)   : 0)
2914 
2915 #define NextCacheCheckEvent(RR) ((RR)->NextRequiredQuery + CacheCheckGracePeriod(RR))
2916 
2917 mDNSexport void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event)
2918 {
2919     if (m->rrcache_nextcheck[slot] - event > 0)
2920         m->rrcache_nextcheck[slot] = event;
2921     if (m->NextCacheCheck          - event > 0)
2922         m->NextCacheCheck          = event;
2923 }
2924 
2925 // Note: MUST call SetNextCacheCheckTimeForRecord any time we change:
2926 // rr->TimeRcvd
2927 // rr->resrec.rroriginalttl
2928 // rr->UnansweredQueries
2929 // rr->CRActiveQuestion
2930 mDNSexport void SetNextCacheCheckTimeForRecord(mDNS *const m, CacheRecord *const rr)
2931 {
2932     rr->NextRequiredQuery = RRExpireTime(rr);
2933 
2934     // If we have an active question, then see if we want to schedule a refresher query for this record.
2935     // Usually we expect to do four queries, at 80-82%, 85-87%, 90-92% and then 95-97% of the TTL.
2936     if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
2937     {
2938         rr->NextRequiredQuery -= TicksTTL(rr)/20 * (MaxUnansweredQueries - rr->UnansweredQueries);
2939         rr->NextRequiredQuery += mDNSRandom((mDNSu32)TicksTTL(rr)/50);
2940         verbosedebugf("SetNextCacheCheckTimeForRecord: NextRequiredQuery in %ld sec CacheCheckGracePeriod %d ticks for %s",
2941                       (rr->NextRequiredQuery - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m,rr));
2942     }
2943     ScheduleNextCacheCheckTime(m, HashSlot(rr->resrec.name), NextCacheCheckEvent(rr));
2944 }
2945 
2946 #define kMinimumReconfirmTime                     ((mDNSu32)mDNSPlatformOneSecond *  5)
2947 #define kDefaultReconfirmTimeForWake              ((mDNSu32)mDNSPlatformOneSecond *  5)
2948 #define kDefaultReconfirmTimeForNoAnswer          ((mDNSu32)mDNSPlatformOneSecond *  5)
2949 #define kDefaultReconfirmTimeForFlappingInterface ((mDNSu32)mDNSPlatformOneSecond *  5)
2950 
2951 mDNSexport mStatus mDNS_Reconfirm_internal(mDNS *const m, CacheRecord *const rr, mDNSu32 interval)
2952 {
2953     if (interval < kMinimumReconfirmTime)
2954         interval = kMinimumReconfirmTime;
2955     if (interval > 0x10000000)  // Make sure interval doesn't overflow when we multiply by four below
2956         interval = 0x10000000;
2957 
2958     // If the expected expiration time for this record is more than interval+33%, then accelerate its expiration
2959     if (RRExpireTime(rr) - m->timenow > (mDNSs32)((interval * 4) / 3))
2960     {
2961         // Add a 33% random amount to the interval, to avoid synchronization between multiple hosts
2962         // For all the reconfirmations in a given batch, we want to use the same random value
2963         // so that the reconfirmation questions can be grouped into a single query packet
2964         if (!m->RandomReconfirmDelay) m->RandomReconfirmDelay = 1 + mDNSRandom(0x3FFFFFFF);
2965         interval += m->RandomReconfirmDelay % ((interval/3) + 1);
2966         rr->TimeRcvd          = m->timenow - (mDNSs32)interval * 3;
2967         rr->resrec.rroriginalttl     = (interval * 4 + mDNSPlatformOneSecond - 1) / mDNSPlatformOneSecond;
2968         SetNextCacheCheckTimeForRecord(m, rr);
2969     }
2970     debugf("mDNS_Reconfirm_internal:%6ld ticks to go for %s %p",
2971            RRExpireTime(rr) - m->timenow, CRDisplayString(m, rr), rr->CRActiveQuestion);
2972     return(mStatus_NoError);
2973 }
2974 
2975 // BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
2976 // It also appends to the list of known answer records that need to be included,
2977 // and updates the forcast for the size of the known answer section.
2978 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr,
2979                                  DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
2980 {
2981     mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
2982     mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
2983     const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
2984     mDNSu8 anoninfo_space = q->AnonInfo ? AnonInfoSpace(q->AnonInfo) : 0;
2985     mDNSu8 *newptr = putQuestion(query, *queryptr, limit - *answerforecast - anoninfo_space, &q->qname, q->qtype, (mDNSu16)(q->qclass | ucbit));
2986     if (!newptr)
2987     {
2988         debugf("BuildQuestion: No more space in this packet for question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
2989         return(mDNSfalse);
2990     }
2991     else
2992     {
2993         mDNSu32 forecast = *answerforecast + anoninfo_space;
2994         const mDNSu32 slot = HashSlot(&q->qname);
2995         const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
2996         CacheRecord *rr;
2997         CacheRecord **ka = *kalistptrptr;   // Make a working copy of the pointer we're going to update
2998 
2999         for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)             // If we have a resource record in our cache,
3000             if (rr->resrec.InterfaceID == q->SendQNow &&                    // received on this interface
3001                 !(rr->resrec.RecordType & kDNSRecordTypeUniqueMask) &&      // which is a shared (i.e. not unique) record type
3002                 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList &&  // which is not already in the known answer list
3003                 rr->resrec.rdlength <= SmallRecordLimit &&                  // which is small enough to sensibly fit in the packet
3004                 SameNameRecordAnswersQuestion(&rr->resrec, q) &&            // which answers our question
3005                 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >                // and its half-way-to-expiry time is at least 1 second away
3006                 mDNSPlatformOneSecond)                                      // (also ensures we never include goodbye records with TTL=1)
3007             {
3008                 // We don't want to include unique records in the Known Answer section. The Known Answer section
3009                 // is intended to suppress floods of shared-record replies from many other devices on the network.
3010                 // That concept really does not apply to unique records, and indeed if we do send a query for
3011                 // which we have a unique record already in our cache, then including that unique record as a
3012                 // Known Answer, so as to suppress the only answer we were expecting to get, makes little sense.
3013 
3014                 *ka = rr;   // Link this record into our known answer chain
3015                 ka = &rr->NextInKAList;
3016                 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3017                 forecast += 12 + rr->resrec.rdestimate;
3018                 // If we're trying to put more than one question in this packet, and it doesn't fit
3019                 // then undo that last question and try again next time
3020                 if (query->h.numQuestions > 1 && newptr + forecast >= limit)
3021                 {
3022                     query->h.numQuestions--;
3023                     debugf("BuildQuestion: Retracting question %##s (%s) new forecast total %d, total questions %d",
3024                            q->qname.c, DNSTypeName(q->qtype), newptr + forecast - query->data, query->h.numQuestions);
3025                     ka = *kalistptrptr;     // Go back to where we started and retract these answer records
3026                     while (*ka) { CacheRecord *c = *ka; *ka = mDNSNULL; ka = &c->NextInKAList; }
3027                     return(mDNSfalse);      // Return false, so we'll try again in the next packet
3028                 }
3029             }
3030 
3031         // Success! Update our state pointers, increment UnansweredQueries as appropriate, and return
3032         *queryptr        = newptr;              // Update the packet pointer
3033         *answerforecast  = forecast;            // Update the forecast
3034         *kalistptrptr    = ka;                  // Update the known answer list pointer
3035         if (ucast) q->ExpectUnicastResp = NonZeroTime(m->timenow);
3036 
3037         for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)             // For every resource record in our cache,
3038             if (rr->resrec.InterfaceID == q->SendQNow &&                    // received on this interface
3039                 rr->NextInKAList == mDNSNULL && ka != &rr->NextInKAList &&  // which is not in the known answer list
3040                 SameNameRecordAnswersQuestion(&rr->resrec, q))              // which answers our question
3041             {
3042                 rr->UnansweredQueries++;                                    // indicate that we're expecting a response
3043                 rr->LastUnansweredTime = m->timenow;
3044                 SetNextCacheCheckTimeForRecord(m, rr);
3045             }
3046 
3047         return(mDNStrue);
3048     }
3049 }
3050 
3051 // When we have a query looking for a specified name, but there appear to be no answers with
3052 // that name, ReconfirmAntecedents() is called with depth=0 to start the reconfirmation process
3053 // for any records in our cache that reference the given name (e.g. PTR and SRV records).
3054 // For any such cache record we find, we also recursively call ReconfirmAntecedents() for *its* name.
3055 // We increment depth each time we recurse, to guard against possible infinite loops, with a limit of 5.
3056 // A typical reconfirmation scenario might go like this:
3057 // Depth 0: Name "myhost.local" has no address records
3058 // Depth 1: SRV "My Service._example._tcp.local." refers to "myhost.local"; may be stale
3059 // Depth 2: PTR "_example._tcp.local." refers to "My Service"; may be stale
3060 // Depth 3: PTR "_services._dns-sd._udp.local." refers to "_example._tcp.local."; may be stale
3061 // Currently depths 4 and 5 are not expected to occur; if we did get to depth 5 we'd reconfim any records we
3062 // found referring to the given name, but not recursively descend any further reconfirm *their* antecedents.
3063 mDNSlocal void ReconfirmAntecedents(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const int depth)
3064 {
3065     mDNSu32 slot;
3066     CacheGroup *cg;
3067     CacheRecord *cr;
3068     debugf("ReconfirmAntecedents (depth=%d) for %##s", depth, name->c);
3069     FORALL_CACHERECORDS(slot, cg, cr)
3070     {
3071         domainname *crtarget = GetRRDomainNameTarget(&cr->resrec);
3072         if (crtarget && cr->resrec.rdatahash == namehash && SameDomainName(crtarget, name))
3073         {
3074             LogInfo("ReconfirmAntecedents: Reconfirming (depth=%d) %s", depth, CRDisplayString(m, cr));
3075             mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
3076             if (depth < 5)
3077                 ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, depth+1);
3078         }
3079     }
3080 }
3081 
3082 // If we get no answer for a AAAA query, then before doing an automatic implicit ReconfirmAntecedents
3083 // we check if we have an address record for the same name. If we do have an IPv4 address for a given
3084 // name but not an IPv6 address, that's okay (it just means the device doesn't do IPv6) so the failure
3085 // to get a AAAA response is not grounds to doubt the PTR/SRV chain that lead us to that name.
3086 mDNSlocal const CacheRecord *CacheHasAddressTypeForName(mDNS *const m, const domainname *const name, const mDNSu32 namehash)
3087 {
3088     CacheGroup *const cg = CacheGroupForName(m, HashSlot(name), namehash, name);
3089     const CacheRecord *cr = cg ? cg->members : mDNSNULL;
3090     while (cr && !RRTypeIsAddressType(cr->resrec.rrtype)) cr=cr->next;
3091     return(cr);
3092 }
3093 
3094 
3095 mDNSlocal const CacheRecord *FindSPSInCache1(mDNS *const m, const DNSQuestion *const q, const CacheRecord *const c0, const CacheRecord *const c1)
3096 {
3097 #ifndef SPC_DISABLED
3098     CacheGroup *const cg = CacheGroupForName(m, HashSlot(&q->qname), q->qnamehash, &q->qname);
3099     const CacheRecord *cr, *bestcr = mDNSNULL;
3100     mDNSu32 bestmetric = 1000000;
3101     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
3102         if (cr->resrec.rrtype == kDNSType_PTR && cr->resrec.rdlength >= 6)                      // If record is PTR type, with long enough name,
3103             if (cr != c0 && cr != c1)                                                           // that's not one we've seen before,
3104                 if (SameNameRecordAnswersQuestion(&cr->resrec, q))                              // and answers our browse query,
3105                     if (!IdenticalSameNameRecord(&cr->resrec, &m->SPSRecords.RR_PTR.resrec))    // and is not our own advertised service...
3106                     {
3107                         mDNSu32 metric = SPSMetric(cr->resrec.rdata->u.name.c);
3108                         if (bestmetric > metric) { bestmetric = metric; bestcr = cr; }
3109                     }
3110     return(bestcr);
3111 #else // SPC_DISABLED
3112 	(void) m;
3113 	(void) q;
3114 	(void) c0;
3115 	(void) c1;
3116 	(void) c1;
3117     return mDNSNULL;
3118 #endif // SPC_DISABLED
3119 }
3120 
3121 mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2)
3122 {
3123     const CacheRecord *swap_sps;
3124     mDNSu32 metric1, metric2;
3125 
3126     if (!(*sps1) || !(*sps2)) return;
3127     metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c);
3128     metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c);
3129     if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1))
3130     {
3131         swap_sps = *sps1;
3132         *sps1    = *sps2;
3133         *sps2    = swap_sps;
3134     }
3135 }
3136 
3137 mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
3138 {
3139     CheckAndSwapSPS(&sps[0], &sps[1]);
3140     CheckAndSwapSPS(&sps[0], &sps[2]);
3141     CheckAndSwapSPS(&sps[1], &sps[2]);
3142 }
3143 
3144 
3145 // Finds the three best Sleep Proxies we currently have in our cache
3146 mDNSexport void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3])
3147 {
3148     sps[0] =                      FindSPSInCache1(m, q, mDNSNULL, mDNSNULL);
3149     sps[1] = !sps[0] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   mDNSNULL);
3150     sps[2] = !sps[1] ? mDNSNULL : FindSPSInCache1(m, q, sps[0],   sps[1]);
3151 
3152     // SPS is already sorted by metric. We want to move the entries to the beginning of the array
3153     // only if they have equally good metric and support features.
3154     ReorderSPSByFeature(sps);
3155 }
3156 
3157 // Only DupSuppressInfos newer than the specified 'time' are allowed to remain active
3158 mDNSlocal void ExpireDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time)
3159 {
3160     int i;
3161     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3162 }
3163 
3164 mDNSlocal void ExpireDupSuppressInfoOnInterface(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 time, mDNSInterfaceID InterfaceID)
3165 {
3166     int i;
3167     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Time - time < 0) ds[i].InterfaceID = mDNSNULL;
3168 }
3169 
3170 mDNSlocal mDNSBool SuppressOnThisInterface(const DupSuppressInfo ds[DupSuppressInfoSize], const NetworkInterfaceInfo * const intf)
3171 {
3172     int i;
3173     mDNSBool v4 = !intf->IPv4Available;     // If this interface doesn't do v4, we don't need to find a v4 duplicate of this query
3174     mDNSBool v6 = !intf->IPv6Available;     // If this interface doesn't do v6, we don't need to find a v6 duplicate of this query
3175     for (i=0; i<DupSuppressInfoSize; i++)
3176         if (ds[i].InterfaceID == intf->InterfaceID)
3177         {
3178             if      (ds[i].Type == mDNSAddrType_IPv4) v4 = mDNStrue;
3179             else if (ds[i].Type == mDNSAddrType_IPv6) v6 = mDNStrue;
3180             if (v4 && v6) return(mDNStrue);
3181         }
3182     return(mDNSfalse);
3183 }
3184 
3185 mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
3186 {
3187     int i, j;
3188 
3189     // See if we have this one in our list somewhere already
3190     for (i=0; i<DupSuppressInfoSize; i++) if (ds[i].InterfaceID == InterfaceID && ds[i].Type == Type) break;
3191 
3192     // If not, find a slot we can re-use
3193     if (i >= DupSuppressInfoSize)
3194     {
3195         i = 0;
3196         for (j=1; j<DupSuppressInfoSize && ds[i].InterfaceID; j++)
3197             if (!ds[j].InterfaceID || ds[j].Time - ds[i].Time < 0)
3198                 i = j;
3199     }
3200 
3201     // Record the info about this query we saw
3202     ds[i].Time        = Time;
3203     ds[i].InterfaceID = InterfaceID;
3204     ds[i].Type        = Type;
3205 }
3206 
3207 mDNSlocal void mDNSSendWakeOnResolve(mDNS *const m, DNSQuestion *q)
3208 {
3209     int len, i, cnt;
3210     mDNSInterfaceID InterfaceID = q->InterfaceID;
3211     domainname *d = &q->qname;
3212 
3213     // We can't send magic packets without knowing which interface to send it on.
3214     if (InterfaceID == mDNSInterface_Any || InterfaceID == mDNSInterface_LocalOnly || InterfaceID == mDNSInterface_P2P)
3215     {
3216         LogMsg("mDNSSendWakeOnResolve: ERROR!! Invalid InterfaceID %p for question %##s", InterfaceID, q->qname.c);
3217         return;
3218     }
3219 
3220     // Split MAC@IPAddress and pass them separately
3221     len = d->c[0];
3222     cnt = 0;
3223     for (i = 1; i < len; i++)
3224     {
3225         if (d->c[i] == '@')
3226         {
3227             char EthAddr[18];   // ethernet adddress : 12 bytes + 5 ":" + 1 NULL byte
3228             char IPAddr[47];    // Max IP address len: 46 bytes (IPv6) + 1 NULL byte
3229             if (cnt != 5)
3230             {
3231                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, cnt %d", q->qname.c, cnt);
3232                 return;
3233             }
3234             if ((i - 1) > (int) (sizeof(EthAddr) - 1))
3235             {
3236                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed Ethernet address %##s, length %d", q->qname.c, i - 1);
3237                 return;
3238             }
3239             if ((len - i) > (int)(sizeof(IPAddr) - 1))
3240             {
3241                 LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed IP address %##s, length %d", q->qname.c, len - i);
3242                 return;
3243             }
3244             mDNSPlatformMemCopy(EthAddr, &d->c[1], i - 1);
3245             EthAddr[i - 1] = 0;
3246             mDNSPlatformMemCopy(IPAddr, &d->c[i + 1], len - i);
3247             IPAddr[len - i] = 0;
3248             m->mDNSStats.WakeOnResolves++;
3249             mDNSPlatformSendWakeupPacket(m, InterfaceID, EthAddr, IPAddr, InitialWakeOnResolveCount - q->WakeOnResolveCount);
3250             return;
3251         }
3252         else if (d->c[i] == ':')
3253             cnt++;
3254     }
3255     LogMsg("mDNSSendWakeOnResolve: ERROR!! Malformed WakeOnResolve name %##s", q->qname.c);
3256 }
3257 
3258 
3259 mDNSlocal mDNSBool AccelerateThisQuery(mDNS *const m, DNSQuestion *q)
3260 {
3261     // If more than 90% of the way to the query time, we should unconditionally accelerate it
3262     if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/10))
3263         return(mDNStrue);
3264 
3265     // If half-way to next scheduled query time, only accelerate if it will add less than 512 bytes to the packet
3266     if (TimeToSendThisQuestion(q, m->timenow + q->ThisQInterval/2))
3267     {
3268         // We forecast: qname (n) type (2) class (2)
3269         mDNSu32 forecast = (mDNSu32)DomainNameLength(&q->qname) + 4;
3270         const mDNSu32 slot = HashSlot(&q->qname);
3271         const CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
3272         const CacheRecord *rr;
3273         for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)             // If we have a resource record in our cache,
3274             if (rr->resrec.rdlength <= SmallRecordLimit &&                  // which is small enough to sensibly fit in the packet
3275                 SameNameRecordAnswersQuestion(&rr->resrec, q) &&            // which answers our question
3276                 rr->TimeRcvd + TicksTTL(rr)/2 - m->timenow >= 0 &&          // and it is less than half-way to expiry
3277                 rr->NextRequiredQuery - (m->timenow + q->ThisQInterval) > 0) // and we'll ask at least once again before NextRequiredQuery
3278             {
3279                 // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3280                 forecast += 12 + rr->resrec.rdestimate;
3281                 if (forecast >= 512) return(mDNSfalse); // If this would add 512 bytes or more to the packet, don't accelerate
3282             }
3283         return(mDNStrue);
3284     }
3285 
3286     return(mDNSfalse);
3287 }
3288 
3289 // How Standard Queries are generated:
3290 // 1. The Question Section contains the question
3291 // 2. The Additional Section contains answers we already know, to suppress duplicate responses
3292 
3293 // How Probe Queries are generated:
3294 // 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
3295 // if some other host is already using *any* records with this name, we want to know about it.
3296 // 2. The Authority Section contains the proposed values we intend to use for one or more
3297 // of our records with that name (analogous to the Update section of DNS Update packets)
3298 // because if some other host is probing at the same time, we each want to know what the other is
3299 // planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
3300 
3301 mDNSlocal void SendQueries(mDNS *const m)
3302 {
3303     mDNSu32 slot;
3304     CacheGroup *cg;
3305     CacheRecord *cr;
3306     AuthRecord *ar;
3307     int pktcount = 0;
3308     DNSQuestion *q;
3309     // For explanation of maxExistingQuestionInterval logic, see comments for maxExistingAnnounceInterval
3310     mDNSs32 maxExistingQuestionInterval = 0;
3311     const NetworkInterfaceInfo *intf = GetFirstActiveInterface(m->HostInterfaces);
3312     CacheRecord *KnownAnswerList = mDNSNULL;
3313 
3314     // 1. If time for a query, work out what we need to do
3315 
3316     // We're expecting to send a query anyway, so see if any expiring cache records are close enough
3317     // to their NextRequiredQuery to be worth batching them together with this one
3318     FORALL_CACHERECORDS(slot, cg, cr)
3319     {
3320         if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3321         {
3322             if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3323             {
3324                 debugf("Sending %d%% cache expiration query for %s", 80 + 5 * cr->UnansweredQueries, CRDisplayString(m, cr));
3325                 q = cr->CRActiveQuestion;
3326                 ExpireDupSuppressInfoOnInterface(q->DupSuppress, m->timenow - TicksTTL(cr)/20, cr->resrec.InterfaceID);
3327                 // For uDNS queries (TargetQID non-zero) we adjust LastQTime,
3328                 // and bump UnansweredQueries so that we don't spin trying to send the same cache expiration query repeatedly
3329                 if (q->Target.type)
3330                 {
3331                     q->SendQNow = mDNSInterfaceMark; // If targeted query, mark it
3332                 }
3333                 else if (!mDNSOpaque16IsZero(q->TargetQID))
3334                 {
3335                     q->LastQTime = m->timenow - q->ThisQInterval;
3336                     cr->UnansweredQueries++;
3337                     m->mDNSStats.CacheRefreshQueries++;
3338                 }
3339                 else if (q->SendQNow == mDNSNULL)
3340                 {
3341                     q->SendQNow = cr->resrec.InterfaceID;
3342                 }
3343                 else if (q->SendQNow != cr->resrec.InterfaceID)
3344                 {
3345                     q->SendQNow = mDNSInterfaceMark;
3346                 }
3347 
3348                 // Indicate that this question was marked for sending
3349                 // to update an existing cached answer record.
3350                 // The browse throttling logic below uses this to determine
3351                 // if the query should be sent.
3352                 if (mDNSOpaque16IsZero(q->TargetQID))
3353                     q->CachedAnswerNeedsUpdate = mDNStrue;
3354             }
3355         }
3356     }
3357 
3358     // Scan our list of questions to see which:
3359     //     *WideArea*  queries need to be sent
3360     //     *unicast*   queries need to be sent
3361     //     *multicast* queries we're definitely going to send
3362     if (m->CurrentQuestion)
3363         LogMsg("SendQueries ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3364     m->CurrentQuestion = m->Questions;
3365     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
3366     {
3367         q = m->CurrentQuestion;
3368         if (q->Target.type && (q->SendQNow || TimeToSendThisQuestion(q, m->timenow)))
3369         {
3370             mDNSu8       *qptr        = m->omsg.data;
3371             const mDNSu8 *const limit = m->omsg.data + sizeof(m->omsg.data);
3372 
3373             // If we fail to get a new on-demand socket (should only happen cases of the most extreme resource exhaustion), we'll try again next time
3374             if (!q->LocalSocket) q->LocalSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
3375             if (q->LocalSocket)
3376             {
3377                 InitializeDNSMessage(&m->omsg.h, q->TargetQID, QueryFlags);
3378                 qptr = putQuestion(&m->omsg, qptr, limit, &q->qname, q->qtype, q->qclass);
3379                 mDNSSendDNSMessage(m, &m->omsg, qptr, mDNSInterface_Any, q->LocalSocket, &q->Target, q->TargetPort, mDNSNULL, mDNSNULL, q->UseBackgroundTrafficClass);
3380                 q->ThisQInterval    *= QuestionIntervalStep;
3381             }
3382             if (q->ThisQInterval > MaxQuestionInterval)
3383                 q->ThisQInterval = MaxQuestionInterval;
3384             q->LastQTime         = m->timenow;
3385             q->LastQTxTime       = m->timenow;
3386             q->RecentAnswerPkts  = 0;
3387             q->SendQNow          = mDNSNULL;
3388             q->ExpectUnicastResp = NonZeroTime(m->timenow);
3389         }
3390         else if (mDNSOpaque16IsZero(q->TargetQID) && !q->Target.type && TimeToSendThisQuestion(q, m->timenow))
3391         {
3392             //LogInfo("Time to send %##s (%s) %d", q->qname.c, DNSTypeName(q->qtype), m->timenow - NextQSendTime(q));
3393             q->SendQNow = mDNSInterfaceMark;        // Mark this question for sending on all interfaces
3394             if (maxExistingQuestionInterval < q->ThisQInterval)
3395                 maxExistingQuestionInterval = q->ThisQInterval;
3396         }
3397         // If m->CurrentQuestion wasn't modified out from under us, advance it now
3398         // We can't do this at the start of the loop because uDNS_CheckCurrentQuestion() depends on having
3399         // m->CurrentQuestion point to the right question
3400         if (q == m->CurrentQuestion) m->CurrentQuestion = m->CurrentQuestion->next;
3401     }
3402     while (m->CurrentQuestion)
3403     {
3404         LogInfo("SendQueries question loop 1: Skipping NewQuestion %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
3405         m->CurrentQuestion = m->CurrentQuestion->next;
3406     }
3407     m->CurrentQuestion = mDNSNULL;
3408 
3409     // Scan our list of questions
3410     // (a) to see if there are any more that are worth accelerating, and
3411     // (b) to update the state variables for *all* the questions we're going to send
3412     // Note: Don't set NextScheduledQuery until here, because uDNS_CheckCurrentQuestion in the loop above can add new questions to the list,
3413     // which causes NextScheduledQuery to get (incorrectly) set to m->timenow. Setting it here is the right place, because the very
3414     // 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.
3415     m->NextScheduledQuery = m->timenow + 0x78000000;
3416     for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3417     {
3418         if (mDNSOpaque16IsZero(q->TargetQID)
3419             && (q->SendQNow || (!q->Target.type && ActiveQuestion(q) && q->ThisQInterval <= maxExistingQuestionInterval && AccelerateThisQuery(m,q))))
3420         {
3421             // If at least halfway to next query time, advance to next interval
3422             // If less than halfway to next query time, then
3423             // treat this as logically a repeat of the last transmission, without advancing the interval
3424             if (m->timenow - (q->LastQTime + (q->ThisQInterval/2)) >= 0)
3425             {
3426                 // If we have reached the answer threshold for this question,
3427                 // don't send it again until MaxQuestionInterval unless:
3428                 //  one of its cached answers needs to be refreshed,
3429                 //  or it's the initial query for a kDNSServiceFlagsThresholdFinder mode browse.
3430                 if (q->BrowseThreshold
3431                     && (q->CurrentAnswers >= q->BrowseThreshold)
3432                     && (q->CachedAnswerNeedsUpdate == mDNSfalse)
3433                     && !((q->flags & kDNSServiceFlagsThresholdFinder) && (q->ThisQInterval == InitialQuestionInterval)))
3434                 {
3435                     q->SendQNow = mDNSNULL;
3436                     q->ThisQInterval = MaxQuestionInterval;
3437                     q->LastQTime = m->timenow;
3438                     q->RequestUnicast = 0;
3439                     LogInfo("SendQueries: (%s) %##s reached threshold of %d answers",
3440                          DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
3441                 }
3442                 else
3443                 {
3444                     // Mark this question for sending on all interfaces
3445                     q->SendQNow = mDNSInterfaceMark;
3446                     q->ThisQInterval *= QuestionIntervalStep;
3447                 }
3448 
3449                 debugf("SendQueries: %##s (%s) next interval %d seconds RequestUnicast = %d",
3450                        q->qname.c, DNSTypeName(q->qtype), q->ThisQInterval / InitialQuestionInterval, q->RequestUnicast);
3451 
3452                 if (q->ThisQInterval >= QuestionIntervalThreshold)
3453                 {
3454                     q->ThisQInterval = MaxQuestionInterval;
3455                 }
3456                 else if (q->CurrentAnswers == 0 && q->ThisQInterval == InitialQuestionInterval * QuestionIntervalStep3 && !q->RequestUnicast &&
3457                          !(RRTypeIsAddressType(q->qtype) && CacheHasAddressTypeForName(m, &q->qname, q->qnamehash)))
3458                 {
3459                     // Generally don't need to log this.
3460                     // It's not especially noteworthy if a query finds no results -- this usually happens for domain
3461                     // enumeration queries in the LL subdomain (e.g. "db._dns-sd._udp.0.0.254.169.in-addr.arpa")
3462                     // and when there simply happen to be no instances of the service the client is looking
3463                     // for (e.g. iTunes is set to look for RAOP devices, and the current network has none).
3464                     debugf("SendQueries: Zero current answers for %##s (%s); will reconfirm antecedents",
3465                            q->qname.c, DNSTypeName(q->qtype));
3466                     // Sending third query, and no answers yet; time to begin doubting the source
3467                     ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
3468                 }
3469             }
3470 
3471             // Mark for sending. (If no active interfaces, then don't even try.)
3472             q->SendOnAll = (q->SendQNow == mDNSInterfaceMark);
3473             if (q->SendOnAll)
3474             {
3475                 q->SendQNow  = !intf ? mDNSNULL : (q->InterfaceID) ? q->InterfaceID : intf->InterfaceID;
3476                 q->LastQTime = m->timenow;
3477             }
3478 
3479             // If we recorded a duplicate suppression for this question less than half an interval ago,
3480             // then we consider it recent enough that we don't need to do an identical query ourselves.
3481             ExpireDupSuppressInfo(q->DupSuppress, m->timenow - q->ThisQInterval/2);
3482 
3483             q->LastQTxTime      = m->timenow;
3484             q->RecentAnswerPkts = 0;
3485             if (q->RequestUnicast) q->RequestUnicast--;
3486         }
3487         // For all questions (not just the ones we're sending) check what the next scheduled event will be
3488         // We don't need to consider NewQuestions here because for those we'll set m->NextScheduledQuery in AnswerNewQuestion
3489         SetNextQueryTime(m,q);
3490     }
3491 
3492     // 2. Scan our authoritative RR list to see what probes we might need to send
3493 
3494     m->NextScheduledProbe = m->timenow + 0x78000000;
3495 
3496     if (m->CurrentRecord)
3497         LogMsg("SendQueries ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
3498     m->CurrentRecord = m->ResourceRecords;
3499     while (m->CurrentRecord)
3500     {
3501         ar = m->CurrentRecord;
3502         m->CurrentRecord = ar->next;
3503         if (!AuthRecord_uDNS(ar) && ar->resrec.RecordType == kDNSRecordTypeUnique)  // For all records that are still probing...
3504         {
3505             // 1. If it's not reached its probe time, just make sure we update m->NextScheduledProbe correctly
3506             if (m->timenow - (ar->LastAPTime + ar->ThisAPInterval) < 0)
3507             {
3508                 SetNextAnnounceProbeTime(m, ar);
3509             }
3510             // 2. else, if it has reached its probe time, mark it for sending and then update m->NextScheduledProbe correctly
3511             else if (ar->ProbeCount)
3512             {
3513                 if (ar->AddressProxy.type == mDNSAddrType_IPv4)
3514                 {
3515                 	// There's a problem here. If a host is waking up, and we probe to see if it responds, then
3516                 	// it will see those ARP probes as signalling intent to use the address, so it picks a different one.
3517                 	// A more benign way to find out if a host is responding to ARPs might be send a standard ARP *request*
3518                 	// (using our sender IP address) instead of an ARP *probe* (using all-zero sender IP address).
3519                 	// A similar concern may apply to the NDP Probe too. -- SC
3520                     LogSPS("SendQueries ARP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3521                     SendARP(m, 1, ar, &zerov4Addr, &zeroEthAddr, &ar->AddressProxy.ip.v4, &ar->WakeUp.IMAC);
3522                 }
3523                 else if (ar->AddressProxy.type == mDNSAddrType_IPv6)
3524                 {
3525                     LogSPS("SendQueries NDP Probe %d %s %s", ar->ProbeCount, InterfaceNameForID(m, ar->resrec.InterfaceID), ARDisplayString(m,ar));
3526                     // IPv6 source = zero
3527                     // No target hardware address
3528                     // IPv6 target address is address we're probing
3529                     // Ethernet destination address is Ethernet interface address of the Sleep Proxy client we're probing
3530                     SendNDP(m, NDP_Sol, 0, ar, &zerov6Addr, mDNSNULL, &ar->AddressProxy.ip.v6, &ar->WakeUp.IMAC);
3531                 }
3532                 // Mark for sending. (If no active interfaces, then don't even try.)
3533                 ar->SendRNow   = (!intf || ar->WakeUp.HMAC.l[0]) ? mDNSNULL : ar->resrec.InterfaceID ? ar->resrec.InterfaceID : intf->InterfaceID;
3534                 ar->LastAPTime = m->timenow;
3535                 // When we have a late conflict that resets a record to probing state we use a special marker value greater
3536                 // than DefaultProbeCountForTypeUnique. Here we detect that state and reset ar->ProbeCount back to the right value.
3537                 if (ar->ProbeCount > DefaultProbeCountForTypeUnique)
3538                     ar->ProbeCount = DefaultProbeCountForTypeUnique;
3539                 ar->ProbeCount--;
3540                 SetNextAnnounceProbeTime(m, ar);
3541                 if (ar->ProbeCount == 0)
3542                 {
3543                     // If this is the last probe for this record, then see if we have any matching records
3544                     // on our duplicate list which should similarly have their ProbeCount cleared to zero...
3545                     AuthRecord *r2;
3546                     for (r2 = m->DuplicateRecords; r2; r2=r2->next)
3547                         if (r2->resrec.RecordType == kDNSRecordTypeUnique && RecordIsLocalDuplicate(r2, ar))
3548                             r2->ProbeCount = 0;
3549                     // ... then acknowledge this record to the client.
3550                     // We do this optimistically, just as we're about to send the third probe.
3551                     // This helps clients that both advertise and browse, and want to filter themselves
3552                     // from the browse results list, because it helps ensure that the registration
3553                     // confirmation will be delivered 1/4 second *before* the browse "add" event.
3554                     // A potential downside is that we could deliver a registration confirmation and then find out
3555                     // moments later that there's a name conflict, but applications have to be prepared to handle
3556                     // late conflicts anyway (e.g. on connection of network cable, etc.), so this is nothing new.
3557                     if (!ar->Acknowledged) AcknowledgeRecord(m, ar);
3558                 }
3559             }
3560             // else, if it has now finished probing, move it to state Verified,
3561             // and update m->NextScheduledResponse so it will be announced
3562             else
3563             {
3564                 if (!ar->Acknowledged) AcknowledgeRecord(m, ar);    // Defensive, just in case it got missed somehow
3565                 ar->resrec.RecordType     = kDNSRecordTypeVerified;
3566                 ar->ThisAPInterval = DefaultAnnounceIntervalForTypeUnique;
3567                 ar->LastAPTime     = m->timenow - DefaultAnnounceIntervalForTypeUnique;
3568                 SetNextAnnounceProbeTime(m, ar);
3569             }
3570         }
3571     }
3572     m->CurrentRecord = m->DuplicateRecords;
3573     while (m->CurrentRecord)
3574     {
3575         ar = m->CurrentRecord;
3576         m->CurrentRecord = ar->next;
3577         if (ar->resrec.RecordType == kDNSRecordTypeUnique && ar->ProbeCount == 0 && !ar->Acknowledged)
3578             AcknowledgeRecord(m, ar);
3579     }
3580 
3581     // 3. Now we know which queries and probes we're sending,
3582     // go through our interface list sending the appropriate queries on each interface
3583     while (intf)
3584     {
3585         int OwnerRecordSpace = (m->AnnounceOwner && intf->MAC.l[0]) ? DNSOpt_Header_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC) : 0;
3586         int TraceRecordSpace = (mDNS_McastTracingEnabled && MDNS_TRACER) ? DNSOpt_Header_Space + DNSOpt_TraceData_Space : 0;
3587         mDNSu8 *queryptr = m->omsg.data;
3588         mDNSBool useBackgroundTrafficClass = mDNSfalse;    // set if we should use background traffic class
3589 
3590         InitializeDNSMessage(&m->omsg.h, zeroID, QueryFlags);
3591         if (KnownAnswerList) verbosedebugf("SendQueries:   KnownAnswerList set... Will continue from previous packet");
3592         if (!KnownAnswerList)
3593         {
3594             // Start a new known-answer list
3595             CacheRecord **kalistptr = &KnownAnswerList;
3596             mDNSu32 answerforecast = OwnerRecordSpace + TraceRecordSpace;  // Start by assuming we'll need at least enough space to put the Owner+Tracer Option
3597 
3598             // Put query questions in this packet
3599             for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
3600             {
3601                 if (mDNSOpaque16IsZero(q->TargetQID) && (q->SendQNow == intf->InterfaceID))
3602                 {
3603                     mDNSBool Suppress = mDNSfalse;
3604                     debugf("SendQueries: %s question for %##s (%s) at %d forecast total %d",
3605                            SuppressOnThisInterface(q->DupSuppress, intf) ? "Suppressing" : "Putting    ",
3606                            q->qname.c, DNSTypeName(q->qtype), queryptr - m->omsg.data, queryptr + answerforecast - m->omsg.data);
3607 
3608                     // If interface is P2P type, verify that query should be sent over it.
3609                     if (!mDNSPlatformValidQuestionForInterface(q, intf))
3610                     {
3611                         LogInfo("SendQueries: Not sending (%s) %##s on %s", DNSTypeName(q->qtype), q->qname.c, InterfaceNameForID(m, intf->InterfaceID));
3612                         q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3613                     }
3614                     // If we're suppressing this question, or we successfully put it, update its SendQNow state
3615                     else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
3616                         BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
3617                     {
3618                         // We successfully added the question to the packet. Make sure that
3619                         // we also send the NSEC3 record if required. BuildQuestion accounted for
3620                         // the space.
3621                         //
3622                         // Note: We don't suppress anonymous questions and hence Suppress should always
3623                         // be zero.
3624 
3625                         if (Suppress)
3626                             m->mDNSStats.DupQuerySuppressions++;
3627 
3628                         if (!Suppress && q->AnonInfo)
3629                         {
3630                             debugf("SendQueries: marking for question %##s, Suppress %d", q->qname.c, Suppress);
3631                             q->AnonInfo->SendNow = intf->InterfaceID;
3632                         }
3633                         q->SendQNow = (q->InterfaceID || !q->SendOnAll) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3634                         if (q->WakeOnResolveCount)
3635                         {
3636                             mDNSSendWakeOnResolve(m, q);
3637                             q->WakeOnResolveCount--;
3638                         }
3639 
3640                         // use background traffic class if any included question requires it
3641                         if (q->UseBackgroundTrafficClass)
3642                         {
3643                             useBackgroundTrafficClass = mDNStrue;
3644                         }
3645                     }
3646                 }
3647             }
3648 
3649             // Put probe questions in this packet
3650             for (ar = m->ResourceRecords; ar; ar=ar->next)
3651                 if (ar->SendRNow == intf->InterfaceID)
3652                 {
3653                     mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
3654                     mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
3655                     const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
3656                     // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
3657                     mDNSu32 forecast = answerforecast + 12 + ar->resrec.rdestimate;
3658                     mDNSu8 *newptr = putQuestion(&m->omsg, queryptr, limit - forecast, ar->resrec.name, kDNSQType_ANY, (mDNSu16)(ar->resrec.rrclass | ucbit));
3659                     if (newptr)
3660                     {
3661                         queryptr       = newptr;
3662                         answerforecast = forecast;
3663                         ar->SendRNow = (ar->resrec.InterfaceID) ? mDNSNULL : GetNextActiveInterfaceID(intf);
3664                         ar->IncludeInProbe = mDNStrue;
3665                         verbosedebugf("SendQueries:   Put Question %##s (%s) probecount %d",
3666                                       ar->resrec.name->c, DNSTypeName(ar->resrec.rrtype), ar->ProbeCount);
3667                     }
3668                 }
3669         }
3670 
3671         // Put our known answer list (either new one from this question or questions, or remainder of old one from last time)
3672         while (KnownAnswerList)
3673         {
3674             CacheRecord *ka = KnownAnswerList;
3675             mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - ka->TimeRcvd)) / mDNSPlatformOneSecond;
3676             mDNSu8 *newptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAnswers, &ka->resrec, ka->resrec.rroriginalttl - SecsSinceRcvd,
3677                                                            m->omsg.data + NormalMaxDNSMessageData - OwnerRecordSpace - TraceRecordSpace);
3678             if (newptr)
3679             {
3680                 verbosedebugf("SendQueries:   Put %##s (%s) at %d - %d",
3681                               ka->resrec.name->c, DNSTypeName(ka->resrec.rrtype), queryptr - m->omsg.data, newptr - m->omsg.data);
3682                 queryptr = newptr;
3683                 KnownAnswerList = ka->NextInKAList;
3684                 ka->NextInKAList = mDNSNULL;
3685             }
3686             else
3687             {
3688                 // If we ran out of space and we have more than one question in the packet, that's an error --
3689                 // we shouldn't have put more than one question if there was a risk of us running out of space.
3690                 if (m->omsg.h.numQuestions > 1)
3691                     LogMsg("SendQueries:   Put %d answers; No more space for known answers", m->omsg.h.numAnswers);
3692                 m->omsg.h.flags.b[0] |= kDNSFlag0_TC;
3693                 break;
3694             }
3695         }
3696 
3697         for (ar = m->ResourceRecords; ar; ar=ar->next)
3698         {
3699             if (ar->IncludeInProbe)
3700             {
3701                 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, &ar->resrec);
3702                 ar->IncludeInProbe = mDNSfalse;
3703                 if (newptr) queryptr = newptr;
3704                 else LogMsg("SendQueries:   How did we fail to have space for the Update record %s", ARDisplayString(m,ar));
3705             }
3706         }
3707 
3708         for (q = m->Questions; q; q = q->next)
3709         {
3710             if (q->AnonInfo && q->AnonInfo->SendNow == intf->InterfaceID)
3711             {
3712                 mDNSu8 *newptr = PutResourceRecord(&m->omsg, queryptr, &m->omsg.h.numAuthorities, q->AnonInfo->nsec3RR);
3713                 if (newptr)
3714                 {
3715                     debugf("SendQueries: Added NSEC3 record %s on InterfaceID %p", RRDisplayString(m, q->AnonInfo->nsec3RR), intf->InterfaceID);
3716                     queryptr = newptr;
3717                 }
3718                 else
3719                 {
3720                     LogMsg("SendQueries: ERROR!! Cannot add NSEC3 record %s on InterfaceID %p", RRDisplayString(m, q->AnonInfo->nsec3RR), intf->InterfaceID);
3721                 }
3722                 q->AnonInfo->SendNow = mDNSNULL;
3723             }
3724         }
3725 
3726         if (queryptr > m->omsg.data)
3727         {
3728             // If we have data to send, add OWNER/TRACER/OWNER+TRACER option if necessary, then send packet
3729             if (OwnerRecordSpace || TraceRecordSpace)
3730             {
3731                 AuthRecord opt;
3732                 mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
3733                 opt.resrec.rrclass    = NormalMaxDNSMessageData;
3734                 opt.resrec.rdlength   = sizeof(rdataOPT);
3735                 opt.resrec.rdestimate = sizeof(rdataOPT);
3736                 if (OwnerRecordSpace && TraceRecordSpace)
3737                 {
3738                     opt.resrec.rdlength   += sizeof(rdataOPT);  // Two options in this OPT record
3739                     opt.resrec.rdestimate += sizeof(rdataOPT);
3740                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3741                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[1]);
3742                 }
3743                 else if (OwnerRecordSpace)
3744                 {
3745                     SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[0]);
3746                 }
3747                 else if (TraceRecordSpace)
3748                 {
3749                     SetupTracerOpt(m, &opt.resrec.rdata->u.opt[0]);
3750                 }
3751                 LogInfo("SendQueries putting %s %s: %s %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "", intf->ifname, ARDisplayString(m, &opt));
3752                 queryptr = PutResourceRecordTTLWithLimit(&m->omsg, queryptr, &m->omsg.h.numAdditionals,
3753                                                          &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
3754                 if (!queryptr)
3755                 {
3756                     LogMsg("SendQueries: How did we fail to have space for %s %s OPT record (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "", TraceRecordSpace ? "TRACER" : "",
3757                            m->omsg.h.numQuestions, m->omsg.h.numAnswers, m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3758                 }
3759                 if (queryptr > m->omsg.data + NormalMaxDNSMessageData)
3760                 {
3761                     if (m->omsg.h.numQuestions != 1 || m->omsg.h.numAnswers != 0 || m->omsg.h.numAuthorities != 1 || m->omsg.h.numAdditionals != 1)
3762                         LogMsg("SendQueries: Why did we generate oversized packet with %s %s OPT record %p %p %p (%d/%d/%d/%d) %s", OwnerRecordSpace ? "OWNER" : "",
3763                                 TraceRecordSpace ? "TRACER" : "", m->omsg.data, m->omsg.data + NormalMaxDNSMessageData, queryptr, m->omsg.h.numQuestions, m->omsg.h.numAnswers,
3764                                 m->omsg.h.numAuthorities, m->omsg.h.numAdditionals, ARDisplayString(m, &opt));
3765                 }
3766             }
3767 
3768             if ((m->omsg.h.flags.b[0] & kDNSFlag0_TC) && m->omsg.h.numQuestions > 1)
3769                 LogMsg("SendQueries: Should not have more than one question (%d) in a truncated packet", m->omsg.h.numQuestions);
3770             debugf("SendQueries:   Sending %d Question%s %d Answer%s %d Update%s on %p",
3771                    m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
3772                    m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
3773                    m->omsg.h.numAuthorities, m->omsg.h.numAuthorities == 1 ? "" : "s", intf->InterfaceID);
3774             if (intf->IPv4Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v4, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3775             if (intf->IPv6Available) mDNSSendDNSMessage(m, &m->omsg, queryptr, intf->InterfaceID, mDNSNULL, &AllDNSLinkGroup_v6, MulticastDNSPort, mDNSNULL, mDNSNULL, useBackgroundTrafficClass);
3776             if (!m->SuppressSending) m->SuppressSending = NonZeroTime(m->timenow + (mDNSPlatformOneSecond+9)/10);
3777             if (++pktcount >= 1000)
3778             { LogMsg("SendQueries exceeded loop limit %d: giving up", pktcount); break; }
3779             // There might be more records left in the known answer list, or more questions to send
3780             // on this interface, so go around one more time and try again.
3781         }
3782         else    // Nothing more to send on this interface; go to next
3783         {
3784             const NetworkInterfaceInfo *next = GetFirstActiveInterface(intf->next);
3785             #if MDNS_DEBUGMSGS && 0
3786             const char *const msg = next ? "SendQueries:   Nothing more on %p; moving to %p" : "SendQueries:   Nothing more on %p";
3787             debugf(msg, intf, next);
3788             #endif
3789             intf = next;
3790         }
3791     }
3792 
3793     // 4. Final housekeeping
3794 
3795     // 4a. Debugging check: Make sure we announced all our records
3796     for (ar = m->ResourceRecords; ar; ar=ar->next)
3797         if (ar->SendRNow)
3798         {
3799             if (ar->ARType != AuthRecordLocalOnly && ar->ARType != AuthRecordP2P)
3800                 LogInfo("SendQueries: No active interface %d to send probe: %d %s",
3801                     (uint32_t)ar->SendRNow, (uint32_t)ar->resrec.InterfaceID, ARDisplayString(m, ar));
3802             ar->SendRNow = mDNSNULL;
3803         }
3804 
3805     // 4b. When we have lingering cache records that we're keeping around for a few seconds in the hope
3806     // that their interface which went away might come back again, the logic will want to send queries
3807     // for those records, but we can't because their interface isn't here any more, so to keep the
3808     // state machine ticking over we just pretend we did so.
3809     // If the interface does not come back in time, the cache record will expire naturally
3810     FORALL_CACHERECORDS(slot, cg, cr)
3811     {
3812         if (cr->CRActiveQuestion && cr->UnansweredQueries < MaxUnansweredQueries)
3813         {
3814             if (m->timenow + TicksTTL(cr)/50 - cr->NextRequiredQuery >= 0)
3815             {
3816                 cr->UnansweredQueries++;
3817                 cr->CRActiveQuestion->SendQNow = mDNSNULL;
3818                 SetNextCacheCheckTimeForRecord(m, cr);
3819             }
3820         }
3821     }
3822 
3823     // 4c. Debugging check: Make sure we sent all our planned questions
3824     // Do this AFTER the lingering cache records check above, because that will prevent spurious warnings for questions
3825     // we legitimately couldn't send because the interface is no longer available
3826     for (q = m->Questions; q; q=q->next)
3827     {
3828         if (q->SendQNow)
3829         {
3830             DNSQuestion *x;
3831             for (x = m->NewQuestions; x; x=x->next) if (x == q) break;  // Check if this question is a NewQuestion
3832             LogInfo("SendQueries: No active interface %d to send %s question: %d %##s (%s)",
3833                 (uint32_t)q->SendQNow, x ? "new" : "old", (uint32_t)q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
3834             q->SendQNow = mDNSNULL;
3835         }
3836         q->CachedAnswerNeedsUpdate = mDNSfalse;
3837     }
3838 }
3839 
3840 mDNSlocal void SendWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *EthAddr, mDNSOpaque48 *password)
3841 {
3842     int i, j;
3843     mDNSu8 *ptr = m->omsg.data;
3844     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
3845     if (!intf) { LogMsg("SendARP: No interface with InterfaceID %p found", InterfaceID); return; }
3846 
3847     // 0x00 Destination address
3848     for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3849 
3850     // 0x06 Source address (Note: Since we don't currently set the BIOCSHDRCMPLT option, BPF will fill in the real interface address for us)
3851     for (i=0; i<6; i++) *ptr++ = intf->MAC.b[0];
3852 
3853     // 0x0C Ethertype (0x0842)
3854     *ptr++ = 0x08;
3855     *ptr++ = 0x42;
3856 
3857     // 0x0E Wakeup sync sequence
3858     for (i=0; i<6; i++) *ptr++ = 0xFF;
3859 
3860     // 0x14 Wakeup data
3861     for (j=0; j<16; j++) for (i=0; i<6; i++) *ptr++ = EthAddr->b[i];
3862 
3863     // 0x74 Password
3864     for (i=0; i<6; i++) *ptr++ = password->b[i];
3865 
3866     mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3867 
3868     // For Ethernet switches that don't flood-foward packets with unknown unicast destination MAC addresses,
3869     // broadcast is the only reliable way to get a wakeup packet to the intended target machine.
3870     // For 802.11 WPA networks, where a sleeping target machine may have missed a broadcast/multicast
3871     // key rotation, unicast is the only way to get a wakeup packet to the intended target machine.
3872     // So, we send one of each, unicast first, then broadcast second.
3873     for (i=0; i<6; i++) m->omsg.data[i] = 0xFF;
3874     mDNSPlatformSendRawPacket(m->omsg.data, ptr, InterfaceID);
3875 }
3876 
3877 // ***************************************************************************
3878 #if COMPILER_LIKES_PRAGMA_MARK
3879 #pragma mark -
3880 #pragma mark - RR List Management & Task Management
3881 #endif
3882 
3883 // Whenever a question is answered, reset its state so that we don't query
3884 // the network repeatedly. This happens first time when we answer the question and
3885 // and later when we refresh the cache.
3886 mDNSlocal void ResetQuestionState(mDNS *const m, DNSQuestion *q)
3887 {
3888     q->LastQTime        = m->timenow;
3889     q->LastQTxTime      = m->timenow;
3890     q->RecentAnswerPkts = 0;
3891     q->ThisQInterval    = MaxQuestionInterval;
3892     q->RequestUnicast   = 0;
3893     // Reset unansweredQueries so that we don't penalize this server later when we
3894     // start sending queries when the cache expires.
3895     q->unansweredQueries = 0;
3896     debugf("ResetQuestionState: Set MaxQuestionInterval for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
3897 }
3898 
3899 // Note: AnswerCurrentQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
3900 // Any code walking either list must use the m->CurrentQuestion (and possibly m->CurrentRecord) mechanism to protect against this.
3901 // In fact, to enforce this, the routine will *only* answer the question currently pointed to by m->CurrentQuestion,
3902 // which will be auto-advanced (possibly to NULL) if the client callback cancels the question.
3903 mDNSexport void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord)
3904 {
3905     DNSQuestion *const q = m->CurrentQuestion;
3906     mDNSBool followcname = FollowCNAME(q, &rr->resrec, AddRecord);
3907 
3908     verbosedebugf("AnswerCurrentQuestionWithResourceRecord:%4lu %s TTL %d %s",
3909                   q->CurrentAnswers, AddRecord ? "Add" : "Rmv", rr->resrec.rroriginalttl, CRDisplayString(m, rr));
3910 
3911     // When the response for the question was validated, the entire rrset was validated. If we deliver
3912     // a RMV for a single record in the rrset, we invalidate the response. If we deliver another add
3913     // in the future, we will do the revalidation again.
3914     //
3915     // Also, if we deliver an ADD for a negative cache record and it has no NSEC/NSEC3, the ValidationStatus needs
3916     // to be reset. This happens normally when we deliver a "secure" negative response followed by an insecure
3917     // negative response which can happen e.g., when disconnecting from network that leads to a negative response
3918     // due to no DNS servers. As we don't deliver RMVs for negative responses that were delivered before, we need
3919     // to do it on the next ADD of a negative cache record. This ADD could be the result of a timeout, no DNS servers
3920     // etc. in which case we need to reset the state to make sure we don't deliver them as secure. If this is
3921     // a real negative response, we would reset the state here and validate the results at the end of this function.
3922     // or the real response again if we purge the cache.
3923     if (q->ValidationRequired && ((AddRecord == QC_rmv) ||
3924         (rr->resrec.RecordType == kDNSRecordTypePacketNegative && (AddRecord == QC_add))))
3925     {
3926         q->ValidationStatus = 0;
3927         q->ValidationState = DNSSECValRequired;
3928     }
3929 
3930     // Normally we don't send out the unicast query if we have answered using our local only auth records e.g., /etc/hosts.
3931     // But if the query for "A" record has a local answer but query for "AAAA" record has no local answer, we might
3932     // send the AAAA query out which will come back with CNAME and will also answer the "A" query. To prevent that,
3933     // we check to see if that query already has a unique local answer.
3934     if (q->LOAddressAnswers)
3935     {
3936         LogInfo("AnswerCurrentQuestionWithResourceRecord: Question %p %##s (%s) not answering with record %s due to "
3937                 "LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr),
3938                 q->LOAddressAnswers);
3939         return;
3940     }
3941 
3942     if (QuerySuppressed(q))
3943     {
3944         // If the query is suppressed, then we don't want to answer from the cache. But if this query is
3945         // supposed to time out, we still want to callback the clients. We do this only for TimeoutQuestions
3946         // that are timing out, which we know are answered with negative cache record when timing out.
3947         if (!q->TimeoutQuestion || rr->resrec.RecordType != kDNSRecordTypePacketNegative || (m->timenow - q->StopTime < 0))
3948             return;
3949     }
3950 
3951 #if TARGET_OS_EMBEDDED
3952     if ((AddRecord == QC_add) && Question_uDNS(q) && (!q->metrics.answered || (q->metrics.querySendCount > 0)))
3953     {
3954         uDNSMetrics *       metrics;
3955         const domainname *  queryName;
3956         mDNSu32             responseLatencyMs;
3957         mDNSBool            isForCellular;
3958 
3959         metrics   = &q->metrics;
3960         queryName = metrics->originalQName ? metrics->originalQName : &q->qname;
3961         if (metrics->querySendCount > 0)
3962         {
3963             responseLatencyMs = ((m->timenow - metrics->firstQueryTime) * 1000) / mDNSPlatformOneSecond;
3964         }
3965         else
3966         {
3967             responseLatencyMs = 0;
3968         }
3969         isForCellular = (q->qDNSServer && q->qDNSServer->cellIntf);
3970 
3971         MetricsUpdateUDNSStats(queryName, mDNStrue, metrics->querySendCount, responseLatencyMs, isForCellular);
3972         metrics->answered       = mDNStrue;
3973         metrics->querySendCount = 0;
3974     }
3975 #endif
3976     // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
3977     // may be called twice, once when the record is received, and again when it's time to notify local clients.
3978     // If any counters or similar are added here, care must be taken to ensure that they are not double-incremented by this.
3979 
3980     rr->LastUsed = m->timenow;
3981     if (AddRecord == QC_add && !q->DuplicateOf && rr->CRActiveQuestion != q)
3982     {
3983         if (!rr->CRActiveQuestion) m->rrcache_active++; // If not previously active, increment rrcache_active count
3984         debugf("AnswerCurrentQuestionWithResourceRecord: Updating CRActiveQuestion from %p to %p for cache record %s, CurrentAnswer %d",
3985                rr->CRActiveQuestion, q, CRDisplayString(m,rr), q->CurrentAnswers);
3986         rr->CRActiveQuestion = q;                       // We know q is non-null
3987         SetNextCacheCheckTimeForRecord(m, rr);
3988     }
3989 
3990     // If this is:
3991     // (a) a no-cache add, where we've already done at least one 'QM' query, or
3992     // (b) a normal add, where we have at least one unique-type answer,
3993     // then there's no need to keep polling the network.
3994     // (If we have an answer in the cache, then we'll automatically ask again in time to stop it expiring.)
3995     // We do this for mDNS questions and uDNS one-shot questions, but not for
3996     // uDNS LongLived questions, because that would mess up our LLQ lease renewal timing.
3997     if ((AddRecord == QC_addnocache && !q->RequestUnicast) ||
3998         (AddRecord == QC_add && (q->ExpectUnique || (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))))
3999         if (ActiveQuestion(q) && (mDNSOpaque16IsZero(q->TargetQID) || !q->LongLived))
4000         {
4001             ResetQuestionState(m, q);
4002         }
4003 
4004     if (rr->DelayDelivery) return;      // We'll come back later when CacheRecordDeferredAdd() calls us
4005 
4006     // Only deliver negative answers if client has explicitly requested them except when we are forcing a negative response
4007     // for the purpose of retrying search domains/timeout OR the question is suppressed
4008     if (rr->resrec.RecordType == kDNSRecordTypePacketNegative || (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype)))
4009         if (!AddRecord || (AddRecord != QC_suppressed && AddRecord != QC_forceresponse && !q->ReturnIntermed)) return;
4010 
4011     // For CNAME results to non-CNAME questions, only inform the client if they explicitly requested that
4012     if (q->QuestionCallback && !q->NoAnswer && (!followcname || q->ReturnIntermed))
4013     {
4014         mDNS_DropLockBeforeCallback();      // Allow client (and us) to legally make mDNS API calls
4015         if (q->qtype != kDNSType_NSEC && RRAssertsNonexistence(&rr->resrec, q->qtype))
4016         {
4017             CacheRecord neg;
4018             MakeNegativeCacheRecord(m, &neg, &q->qname, q->qnamehash, q->qtype, q->qclass, 1, rr->resrec.InterfaceID, q->qDNSServer);
4019             q->QuestionCallback(m, q, &neg.resrec, AddRecord);
4020         }
4021         else
4022             q->QuestionCallback(m, q, &rr->resrec, AddRecord);
4023         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
4024     }
4025     // If this is an "Add" operation and this question needs validation, validate the response.
4026     // In the case of negative responses, extra care should be taken. Negative cache records are
4027     // used for many purposes. For example,
4028     //
4029     // 1) Suppressing questions (SuppressUnusable)
4030     // 2) Timeout questions
4031     // 3) The name does not exist
4032     // 4) No DNS servers are available and we need a quick response for the application
4033     //
4034     // (1) and (2) are handled by "QC_add" check as AddRecord would be "QC_forceresponse" or "QC_suppressed"
4035     // in that case. For (3), it is possible that we don't get nsecs back but we still need to call
4036     // VerifySignature so that we can deliver the appropriate DNSSEC result. There is no point in verifying
4037     // signature for (4) and hence the explicit check for q->qDNSServer.
4038     //
4039     if (m->CurrentQuestion == q && (AddRecord == QC_add) && !q->ValidatingResponse && q->ValidationRequired &&
4040         q->ValidationState == DNSSECValRequired && q->qDNSServer)
4041     {
4042         q->ValidationState = DNSSECValInProgress;
4043         // Treat it as callback call as that's what dnssec code expects
4044         mDNS_DropLockBeforeCallback();      // Allow client (and us) to legally make mDNS API calls
4045         VerifySignature(m, mDNSNULL, q);
4046         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
4047         return;
4048     }
4049 
4050     // Note: Proceed with caution here because client callback function is allowed to do anything,
4051     // including starting/stopping queries, registering/deregistering records, etc.
4052     //
4053     // If we get a CNAME back while we are validating the response (i.e., CNAME for DS, DNSKEY, RRSIG),
4054     // don't follow them. If it is a ValidationRequired question, wait for the CNAME to be validated
4055     // first before following it
4056     if (!ValidatingQuestion(q) && followcname && m->CurrentQuestion == q)
4057         AnswerQuestionByFollowingCNAME(m, q, &rr->resrec);
4058 }
4059 
4060 mDNSlocal void CacheRecordDeferredAdd(mDNS *const m, CacheRecord *rr)
4061 {
4062     rr->DelayDelivery = 0;
4063     if (m->CurrentQuestion)
4064         LogMsg("CacheRecordDeferredAdd ERROR m->CurrentQuestion already set: %##s (%s)",
4065                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4066     m->CurrentQuestion = m->Questions;
4067     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4068     {
4069         DNSQuestion *q = m->CurrentQuestion;
4070         if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4071             AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4072         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4073             m->CurrentQuestion = q->next;
4074     }
4075     m->CurrentQuestion = mDNSNULL;
4076 }
4077 
4078 mDNSlocal mDNSs32 CheckForSoonToExpireRecords(mDNS *const m, const domainname *const name, const mDNSu32 namehash, const mDNSu32 slot, mDNSBool *purge)
4079 {
4080     const mDNSs32 threshhold = m->timenow + mDNSPlatformOneSecond;  // See if there are any records expiring within one second
4081     const mDNSs32 start      = m->timenow - 0x10000000;
4082     mDNSs32 delay = start;
4083     CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
4084     const CacheRecord *rr;
4085 
4086     if (purge)
4087         *purge = mDNSfalse;
4088     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4089     {
4090         // If there are records that will expire soon, there are cases that need delayed
4091         // delivery of events:
4092         //
4093         // 1) A new cache entry is about to be added as a replacement. The caller needs to
4094         //    deliver a RMV (for the current old entry) followed by ADD (for the new entry).
4095         //    It needs to schedule the timer for the next cache expiry (ScheduleNextCacheCheckTime),
4096         //    so that the cache entry can be purged (purging causes the RMV followed by ADD)
4097         //
4098         // 2) A new question is about to be answered and the caller needs to know whether it's
4099         //    scheduling should be delayed so that the question is not answered with this record.
4100         //    Instead of delivering an ADD (old entry) followed by RMV (old entry) and another ADD
4101         //    (new entry), a single ADD can be delivered by delaying the scheduling of the question
4102         //    immediately.
4103         //
4104         // When the unicast cache record is created, it's TTL has been extended beyond its value
4105         // given in the resource record (See RRAdjustTTL). If it is in the "extended" time, the
4106         // cache is already expired and we set "purge" to indicate that. When "purge" is set, the
4107         // return value of the function should be ignored by the callers.
4108         //
4109         // Note: For case (1), "purge" argument is NULL and hence the following checks are skipped.
4110         // It is okay to skip in that case because the cache records have been set to expire almost
4111         // immediately and the extended time does not apply.
4112         //
4113         // Also, if there is already an active question we don't try to optimize as purging the cache
4114         // would end up delivering RMV for the active question and hence we avoid that.
4115 
4116         if (purge && !rr->resrec.InterfaceID && !rr->CRActiveQuestion && rr->resrec.rroriginalttl)
4117         {
4118             mDNSu32 uTTL = RRUnadjustedTTL(rr->resrec.rroriginalttl);
4119             if (m->timenow - (rr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
4120             {
4121                 LogInfo("CheckForSoonToExpireRecords: %s: rroriginalttl %u, unadjustedTTL %u, currentTTL %u",
4122                     CRDisplayString(m, rr), rr->resrec.rroriginalttl, uTTL, (m->timenow - rr->TimeRcvd)/mDNSPlatformOneSecond);
4123                 *purge = mDNStrue;
4124                 continue;
4125             }
4126         }
4127         if (threshhold - RRExpireTime(rr) >= 0)     // If we have records about to expire within a second
4128         {
4129             if (delay - RRExpireTime(rr) < 0)       // then delay until after they've been deleted
4130                 delay = RRExpireTime(rr);
4131         }
4132     }
4133     if (delay - start > 0)
4134         return(NonZeroTime(delay));
4135     else
4136         return(0);
4137 }
4138 
4139 // CacheRecordAdd is only called from CreateNewCacheEntry, *never* directly as a result of a client API call.
4140 // If new questions are created as a result of invoking client callbacks, they will be added to
4141 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4142 // rr is a new CacheRecord just received into our cache
4143 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4144 // Note: CacheRecordAdd calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4145 // which may change the record list and/or question list.
4146 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4147 mDNSlocal void CacheRecordAdd(mDNS *const m, CacheRecord *rr)
4148 {
4149     DNSQuestion *q;
4150 
4151     // We stop when we get to NewQuestions -- if we increment their CurrentAnswers/LargeAnswers/UniqueAnswers
4152     // counters here we'll end up double-incrementing them when we do it again in AnswerNewQuestion().
4153     for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
4154     {
4155         if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4156         {
4157 	    mDNSIPPort zp = zeroIPPort;
4158             // If this question is one that's actively sending queries, and it's received ten answers within one
4159             // second of sending the last query packet, then that indicates some radical network topology change,
4160             // so reset its exponential backoff back to the start. We must be at least at the eight-second interval
4161             // to do this. If we're at the four-second interval, or less, there's not much benefit accelerating
4162             // because we will anyway send another query within a few seconds. The first reset query is sent out
4163             // randomized over the next four seconds to reduce possible synchronization between machines.
4164             if (q->LastAnswerPktNum != m->PktNum)
4165             {
4166                 q->LastAnswerPktNum = m->PktNum;
4167                 if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q) && ++q->RecentAnswerPkts >= 10 &&
4168                     q->ThisQInterval > InitialQuestionInterval * QuestionIntervalStep3 && m->timenow - q->LastQTxTime < mDNSPlatformOneSecond)
4169                 {
4170                     LogMsg("CacheRecordAdd: %##s (%s) got immediate answer burst (%d); restarting exponential backoff sequence (%d)",
4171                            q->qname.c, DNSTypeName(q->qtype), q->RecentAnswerPkts, q->ThisQInterval);
4172                     q->LastQTime      = m->timenow - InitialQuestionInterval + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*4);
4173                     q->ThisQInterval  = InitialQuestionInterval;
4174                     SetNextQueryTime(m,q);
4175                 }
4176             }
4177             verbosedebugf("CacheRecordAdd %p %##s (%s) %lu %#a:%d question %p", rr, rr->resrec.name->c,
4178                           DNSTypeName(rr->resrec.rrtype), rr->resrec.rroriginalttl, rr->resrec.rDNSServer ?
4179                           &rr->resrec.rDNSServer->addr : mDNSNULL, mDNSVal16(rr->resrec.rDNSServer ?
4180                                                                              rr->resrec.rDNSServer->port : zp), q);
4181             q->CurrentAnswers++;
4182 
4183             q->unansweredQueries = 0;
4184             if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4185             if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4186             if (q->CurrentAnswers > 4000)
4187             {
4188                 static int msgcount = 0;
4189                 if (msgcount++ < 10)
4190                     LogMsg("CacheRecordAdd: %##s (%s) has %d answers; shedding records to resist DOS attack",
4191                            q->qname.c, DNSTypeName(q->qtype), q->CurrentAnswers);
4192                 rr->resrec.rroriginalttl = 0;
4193                 rr->UnansweredQueries = MaxUnansweredQueries;
4194             }
4195         }
4196     }
4197 
4198     if (!rr->DelayDelivery)
4199     {
4200         if (m->CurrentQuestion)
4201             LogMsg("CacheRecordAdd ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4202         m->CurrentQuestion = m->Questions;
4203         while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4204         {
4205             q = m->CurrentQuestion;
4206             if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4207                 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4208             if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4209                 m->CurrentQuestion = q->next;
4210         }
4211         m->CurrentQuestion = mDNSNULL;
4212     }
4213 
4214     SetNextCacheCheckTimeForRecord(m, rr);
4215 }
4216 
4217 // NoCacheAnswer is only called from mDNSCoreReceiveResponse, *never* directly as a result of a client API call.
4218 // If new questions are created as a result of invoking client callbacks, they will be added to
4219 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4220 // rr is a new CacheRecord just received from the wire (kDNSRecordTypePacketAns/AnsUnique/Add/AddUnique)
4221 // but we don't have any place to cache it. We'll deliver question 'add' events now, but we won't have any
4222 // way to deliver 'remove' events in future, nor will we be able to include this in known-answer lists,
4223 // so we immediately bump ThisQInterval up to MaxQuestionInterval to avoid pounding the network.
4224 // Note: NoCacheAnswer calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4225 // which may change the record list and/or question list.
4226 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4227 mDNSlocal void NoCacheAnswer(mDNS *const m, CacheRecord *rr)
4228 {
4229     LogMsg("No cache space: Delivering non-cached result for %##s", m->rec.r.resrec.name->c);
4230     if (m->CurrentQuestion)
4231         LogMsg("NoCacheAnswer ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4232     m->CurrentQuestion = m->Questions;
4233     // We do this for *all* questions, not stopping when we get to m->NewQuestions,
4234     // since we're not caching the record and we'll get no opportunity to do this later
4235     while (m->CurrentQuestion)
4236     {
4237         DNSQuestion *q = m->CurrentQuestion;
4238         if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4239             AnswerCurrentQuestionWithResourceRecord(m, rr, QC_addnocache);  // QC_addnocache means "don't expect remove events for this"
4240         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4241             m->CurrentQuestion = q->next;
4242     }
4243     m->CurrentQuestion = mDNSNULL;
4244 }
4245 
4246 // CacheRecordRmv is only called from CheckCacheExpiration, which is called from mDNS_Execute.
4247 // Note that CacheRecordRmv is *only* called for records that are referenced by at least one active question.
4248 // If new questions are created as a result of invoking client callbacks, they will be added to
4249 // the end of the question list, and m->NewQuestions will be set to indicate the first new question.
4250 // rr is an existing cache CacheRecord that just expired and is being deleted
4251 // (kDNSRecordTypePacketAns/PacketAnsUnique/PacketAdd/PacketAddUnique).
4252 // Note: CacheRecordRmv calls AnswerCurrentQuestionWithResourceRecord which can call a user callback,
4253 // which may change the record list and/or question list.
4254 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
4255 mDNSlocal void CacheRecordRmv(mDNS *const m, CacheRecord *rr)
4256 {
4257     if (m->CurrentQuestion)
4258         LogMsg("CacheRecordRmv ERROR m->CurrentQuestion already set: %##s (%s)",
4259                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4260     m->CurrentQuestion = m->Questions;
4261 
4262     // We stop when we get to NewQuestions -- for new questions their CurrentAnswers/LargeAnswers/UniqueAnswers counters
4263     // will all still be zero because we haven't yet gone through the cache counting how many answers we have for them.
4264     while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
4265     {
4266         DNSQuestion *q = m->CurrentQuestion;
4267         // When a question enters suppressed state, we generate RMV events and generate a negative
4268         // response. A cache may be present that answers this question e.g., cache entry generated
4269         // before the question became suppressed. We need to skip the suppressed questions here as
4270         // the RMV event has already been generated.
4271         if (!QuerySuppressed(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
4272         {
4273             verbosedebugf("CacheRecordRmv %p %s", rr, CRDisplayString(m, rr));
4274             q->FlappingInterface1 = mDNSNULL;
4275             q->FlappingInterface2 = mDNSNULL;
4276 
4277             if (q->CurrentAnswers == 0) {
4278 		mDNSIPPort zp = zeroIPPort;
4279                 LogMsg("CacheRecordRmv ERROR!!: How can CurrentAnswers already be zero for %p %##s (%s) DNSServer %#a:%d",
4280                        q, q->qname.c, DNSTypeName(q->qtype), q->qDNSServer ? &q->qDNSServer->addr : mDNSNULL,
4281                        mDNSVal16(q->qDNSServer ? q->qDNSServer->port : zp));
4282 	    }
4283             else
4284             {
4285                 q->CurrentAnswers--;
4286                 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
4287                 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
4288             }
4289 
4290             // If we have dropped below the answer threshold for this mDNS question,
4291             // restart the queries at InitialQuestionInterval.
4292             if (mDNSOpaque16IsZero(q->TargetQID) && (q->BrowseThreshold > 0) && (q->CurrentAnswers < q->BrowseThreshold))
4293             {
4294                 q->ThisQInterval = InitialQuestionInterval;
4295                 q->LastQTime     = m->timenow - q->ThisQInterval;
4296                 SetNextQueryTime(m,q);
4297                 LogInfo("CacheRecordRmv: (%s) %##s dropped below threshold of %d answers",
4298                     DNSTypeName(q->qtype), q->qname.c, q->BrowseThreshold);
4299             }
4300             if (rr->resrec.rdata->MaxRDLength) // Never generate "remove" events for negative results
4301             {
4302                 if (q->CurrentAnswers == 0)
4303                 {
4304                     LogInfo("CacheRecordRmv: Last answer for %##s (%s) expired from cache; will reconfirm antecedents",
4305                             q->qname.c, DNSTypeName(q->qtype));
4306                     ReconfirmAntecedents(m, &q->qname, q->qnamehash, 0);
4307                 }
4308                 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
4309             }
4310         }
4311         if (m->CurrentQuestion == q)    // If m->CurrentQuestion was not auto-advanced, do it ourselves now
4312             m->CurrentQuestion = q->next;
4313     }
4314     m->CurrentQuestion = mDNSNULL;
4315 }
4316 
4317 mDNSlocal void ReleaseCacheEntity(mDNS *const m, CacheEntity *e)
4318 {
4319 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
4320     unsigned int i;
4321     for (i=0; i<sizeof(*e); i++) ((char*)e)[i] = 0xFF;
4322 #endif
4323     e->next = m->rrcache_free;
4324     m->rrcache_free = e;
4325     m->rrcache_totalused--;
4326 }
4327 
4328 mDNSlocal void ReleaseCacheGroup(mDNS *const m, CacheGroup **cp)
4329 {
4330     CacheEntity *e = (CacheEntity *)(*cp);
4331     //LogMsg("ReleaseCacheGroup:  Releasing CacheGroup for %p, %##s", (*cp)->name->c, (*cp)->name->c);
4332     if ((*cp)->rrcache_tail != &(*cp)->members)
4333         LogMsg("ERROR: (*cp)->members == mDNSNULL but (*cp)->rrcache_tail != &(*cp)->members)");
4334     //if ((*cp)->name != (domainname*)((*cp)->namestorage))
4335     //	LogMsg("ReleaseCacheGroup: %##s, %p %p", (*cp)->name->c, (*cp)->name, (domainname*)((*cp)->namestorage));
4336     if ((*cp)->name != (domainname*)((*cp)->namestorage)) mDNSPlatformMemFree((*cp)->name);
4337     (*cp)->name = mDNSNULL;
4338     *cp = (*cp)->next;          // Cut record from list
4339     ReleaseCacheEntity(m, e);
4340 }
4341 
4342 mDNSlocal void ReleaseAdditionalCacheRecords(mDNS *const m, CacheRecord **rp)
4343 {
4344     while (*rp)
4345     {
4346         CacheRecord *rr = *rp;
4347         *rp = (*rp)->next;          // Cut record from list
4348         if (rr->resrec.rdata && rr->resrec.rdata != (RData*)&rr->smallrdatastorage)
4349         {
4350             mDNSPlatformMemFree(rr->resrec.rdata);
4351             rr->resrec.rdata = mDNSNULL;
4352         }
4353         // NSEC or SOA records that are not added to the CacheGroup do not share the name
4354         // of the CacheGroup.
4355         if (rr->resrec.name)
4356         {
4357             debugf("ReleaseAdditionalCacheRecords: freeing cached record %##s (%s)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype));
4358             mDNSPlatformMemFree((void *)rr->resrec.name);
4359             rr->resrec.name = mDNSNULL;
4360         }
4361         // Don't count the NSEC3 records used by anonymous browse/reg
4362         if (!rr->resrec.InterfaceID)
4363         {
4364             m->rrcache_totalused_unicast -= rr->resrec.rdlength;
4365             if (DNSSECRecordType(rr->resrec.rrtype))
4366                 BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
4367         }
4368         ReleaseCacheEntity(m, (CacheEntity *)rr);
4369     }
4370 }
4371 
4372 mDNSexport void ReleaseCacheRecord(mDNS *const m, CacheRecord *r)
4373 {
4374     CacheGroup *cg;
4375     const mDNSu32 slot = HashSlot(r->resrec.name);
4376 
4377     //LogMsg("ReleaseCacheRecord: Releasing %s", CRDisplayString(m, r));
4378     if (r->resrec.rdata && r->resrec.rdata != (RData*)&r->smallrdatastorage) mDNSPlatformMemFree(r->resrec.rdata);
4379     r->resrec.rdata = mDNSNULL;
4380 
4381     cg = CacheGroupForRecord(m, slot, &r->resrec);
4382 
4383     if (!cg)
4384     {
4385         // It is okay to have this printed for NSEC/NSEC3s
4386         LogInfo("ReleaseCacheRecord: ERROR!! cg NULL for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4387     }
4388     // When NSEC records are not added to the cache, it is usually cached at the "nsec" list
4389     // of the CacheRecord. But sometimes they may be freed without adding to the "nsec" list
4390     // (which is handled below) and in that case it should be freed here.
4391     if (r->resrec.name && cg && r->resrec.name != cg->name)
4392     {
4393         debugf("ReleaseCacheRecord: freeing %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4394         mDNSPlatformMemFree((void *)r->resrec.name);
4395     }
4396     r->resrec.name = mDNSNULL;
4397 
4398     if (r->resrec.AnonInfo)
4399     {
4400         debugf("ReleaseCacheRecord: freeing AnonInfo for %##s (%s)", r->resrec.name->c, DNSTypeName(r->resrec.rrtype));
4401         FreeAnonInfo((void *)r->resrec.AnonInfo);
4402     }
4403     r->resrec.AnonInfo = mDNSNULL;
4404 
4405     if (!r->resrec.InterfaceID)
4406     {
4407         m->rrcache_totalused_unicast -= r->resrec.rdlength;
4408         if (DNSSECRecordType(r->resrec.rrtype))
4409             BumpDNSSECStats(m, kStatsActionDecrement, kStatsTypeMemoryUsage, r->resrec.rdlength);
4410     }
4411 
4412     ReleaseAdditionalCacheRecords(m, &r->nsec);
4413     ReleaseAdditionalCacheRecords(m, &r->soa);
4414 
4415     ReleaseCacheEntity(m, (CacheEntity *)r);
4416 }
4417 
4418 // Note: We want to be careful that we deliver all the CacheRecordRmv calls before delivering
4419 // CacheRecordDeferredAdd calls. The in-order nature of the cache lists ensures that all
4420 // callbacks for old records are delivered before callbacks for newer records.
4421 mDNSlocal void CheckCacheExpiration(mDNS *const m, const mDNSu32 slot, CacheGroup *const cg)
4422 {
4423     CacheRecord **rp = &cg->members;
4424 
4425     if (m->lock_rrcache) { LogMsg("CheckCacheExpiration ERROR! Cache already locked!"); return; }
4426     m->lock_rrcache = 1;
4427 
4428     while (*rp)
4429     {
4430         CacheRecord *const rr = *rp;
4431         mDNSs32 event = RRExpireTime(rr);
4432         if (m->timenow - event >= 0)    // If expired, delete it
4433         {
4434             *rp = rr->next;             // Cut it from the list
4435 
4436             verbosedebugf("CheckCacheExpiration: Deleting%7d %7d %p %s",
4437                           m->timenow - rr->TimeRcvd, rr->resrec.rroriginalttl, rr->CRActiveQuestion, CRDisplayString(m, rr));
4438             if (rr->CRActiveQuestion)   // If this record has one or more active questions, tell them it's going away
4439             {
4440                 DNSQuestion *q = rr->CRActiveQuestion;
4441                 // When a cache record is about to expire, we expect to do four queries at 80-82%, 85-87%, 90-92% and
4442                 // then 95-97% of the TTL. If the DNS server does not respond, then we will remove the cache entry
4443                 // before we pick a new DNS server. As the question interval is set to MaxQuestionInterval, we may
4444                 // not send out a query anytime soon. Hence, we need to reset the question interval. If this is
4445                 // a normal deferred ADD case, then AnswerCurrentQuestionWithResourceRecord will reset it to
4446                 // MaxQuestionInterval. If we have inactive questions referring to negative cache entries,
4447                 // don't ressurect them as they will deliver duplicate "No such Record" ADD events
4448                 if (!mDNSOpaque16IsZero(q->TargetQID) && !q->LongLived && ActiveQuestion(q))
4449                 {
4450                     q->ThisQInterval = InitialQuestionInterval;
4451                     q->LastQTime     = m->timenow - q->ThisQInterval;
4452                     SetNextQueryTime(m, q);
4453                 }
4454                 CacheRecordRmv(m, rr);
4455                 m->rrcache_active--;
4456             }
4457             ReleaseCacheRecord(m, rr);
4458         }
4459         else                            // else, not expired; see if we need to query
4460         {
4461             // If waiting to delay delivery, do nothing until then
4462             if (rr->DelayDelivery && rr->DelayDelivery - m->timenow > 0)
4463                 event = rr->DelayDelivery;
4464             else
4465             {
4466                 if (rr->DelayDelivery) CacheRecordDeferredAdd(m, rr);
4467                 if (rr->CRActiveQuestion && rr->UnansweredQueries < MaxUnansweredQueries)
4468                 {
4469                     if (m->timenow - rr->NextRequiredQuery < 0)     // If not yet time for next query
4470                         event = NextCacheCheckEvent(rr);            // then just record when we want the next query
4471                     else                                            // else trigger our question to go out now
4472                     {
4473                         // Set NextScheduledQuery to timenow so that SendQueries() will run.
4474                         // SendQueries() will see that we have records close to expiration, and send FEQs for them.
4475                         m->NextScheduledQuery = m->timenow;
4476                         // After sending the query we'll increment UnansweredQueries and call SetNextCacheCheckTimeForRecord(),
4477                         // which will correctly update m->NextCacheCheck for us.
4478                         event = m->timenow + 0x3FFFFFFF;
4479                     }
4480                 }
4481             }
4482             verbosedebugf("CheckCacheExpiration:%6d %5d %s",
4483                           (event - m->timenow) / mDNSPlatformOneSecond, CacheCheckGracePeriod(rr), CRDisplayString(m, rr));
4484             if (m->rrcache_nextcheck[slot] - event > 0)
4485                 m->rrcache_nextcheck[slot] = event;
4486             rp = &rr->next;
4487         }
4488     }
4489     if (cg->rrcache_tail != rp) verbosedebugf("CheckCacheExpiration: Updating CacheGroup tail from %p to %p", cg->rrcache_tail, rp);
4490     cg->rrcache_tail = rp;
4491     m->lock_rrcache = 0;
4492 }
4493 
4494 // "LORecord" includes both LocalOnly and P2P record. This function assumes m->CurrentQuestion is pointing to "q".
4495 //
4496 // If "CheckOnly" is set to "true", the question won't be answered but just check to see if there is an answer and
4497 // returns true if there is an answer.
4498 //
4499 // If "CheckOnly" is set to "false", the question will be answered if there is a LocalOnly/P2P record and
4500 // returns true to indicate the same.
4501 mDNSlocal mDNSBool AnswerQuestionWithLORecord(mDNS *const m, DNSQuestion *q, mDNSBool checkOnly)
4502 {
4503     mDNSu32 slot;
4504     AuthRecord *lr;
4505     AuthGroup *ag;
4506 
4507     if (m->CurrentRecord)
4508         LogMsg("AnswerQuestionWithLORecord ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4509 
4510     slot = AuthHashSlot(&q->qname);
4511     ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4512     if (ag)
4513     {
4514         m->CurrentRecord = ag->members;
4515         while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4516         {
4517             AuthRecord *rr = m->CurrentRecord;
4518             m->CurrentRecord = rr->next;
4519             //
4520             // If the question is mDNSInterface_LocalOnly, all records local to the machine should be used
4521             // to answer the query. This is handled in AnswerNewLocalOnlyQuestion.
4522             //
4523             // We handle mDNSInterface_Any and scoped questions here. See LocalOnlyRecordAnswersQuestion for more
4524             // details on how we handle this case. For P2P we just handle "Interface_Any" questions. For LocalOnly
4525             // we handle both mDNSInterface_Any and scoped questions.
4526 
4527             if (rr->ARType == AuthRecordLocalOnly || (rr->ARType == AuthRecordP2P && q->InterfaceID == mDNSInterface_Any))
4528                 if (LocalOnlyRecordAnswersQuestion(rr, q))
4529                 {
4530                     if (checkOnly)
4531                     {
4532                         LogInfo("AnswerQuestionWithLORecord: question %##s (%s) answered by %s", q->qname.c, DNSTypeName(q->qtype),
4533                             ARDisplayString(m, rr));
4534                         m->CurrentRecord = mDNSNULL;
4535                         return mDNStrue;
4536                     }
4537                     AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
4538                     if (m->CurrentQuestion != q)
4539                         break;     // If callback deleted q, then we're finished here
4540                 }
4541         }
4542     }
4543     m->CurrentRecord = mDNSNULL;
4544 
4545     if (m->CurrentQuestion != q)
4546     {
4547         LogInfo("AnswerQuestionWithLORecord: Question deleted while while answering LocalOnly record answers");
4548         return mDNStrue;
4549     }
4550 
4551     if (q->LOAddressAnswers)
4552     {
4553         LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) answered using local auth records LOAddressAnswers %d",
4554                 q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4555         return mDNStrue;
4556     }
4557 
4558     // Before we go check the cache and ship this query on the wire, we have to be sure that there are
4559     // no local records that could possibly answer this question. As we did not check the NewLocalRecords, we
4560     // need to just peek at them to see whether it will answer this question. If it would answer, pretend
4561     // that we answered. AnswerAllLocalQuestionsWithLocalAuthRecord will answer shortly. This happens normally
4562     // when we add new /etc/hosts entries and restart the question. It is a new question and also a new record.
4563     if (ag)
4564     {
4565         lr = ag->NewLocalOnlyRecords;
4566         while (lr)
4567         {
4568             if (UniqueLocalOnlyRecord(lr) && LocalOnlyRecordAnswersQuestion(lr, q))
4569             {
4570                 LogInfo("AnswerQuestionWithLORecord: Question %p %##s (%s) will be answered using new local auth records "
4571                         " LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype), q->LOAddressAnswers);
4572                 return mDNStrue;
4573             }
4574             lr = lr->next;
4575         }
4576     }
4577     return mDNSfalse;
4578 }
4579 
4580 // Today, we suppress questions (not send them on the wire) for several reasons e.g.,
4581 // AAAA query is suppressed because no IPv6 capability or PID is not allowed to make
4582 // DNS requests. We need to temporarily suspend the suppress status so that we can
4583 // deliver a negative response (AnswerCurrentQuestionWithResourceRecord does not answer
4584 // suppressed questions) and reset it back. In the future, if there are other
4585 // reasons for suppressing the query, this function should be updated.
4586 mDNSlocal void AnswerSuppressedQuestion(mDNS *const m, DNSQuestion *q)
4587 {
4588     mDNSBool SuppressQuery = q->SuppressQuery;
4589     mDNSBool DisallowPID   = q->DisallowPID;
4590 
4591     // make sure that QuerySuppressed() returns false
4592     q->SuppressQuery = mDNSfalse;
4593     q->DisallowPID   = mDNSfalse;
4594 
4595     GenerateNegativeResponse(m, QC_suppressed);
4596 
4597     q->SuppressQuery = SuppressQuery;
4598     q->DisallowPID   = DisallowPID;
4599 }
4600 
4601 mDNSlocal void AnswerNewQuestion(mDNS *const m)
4602 {
4603     mDNSBool ShouldQueryImmediately = mDNStrue;
4604     DNSQuestion *const q = m->NewQuestions;     // Grab the question we're going to answer
4605     mDNSu32 slot = HashSlot(&q->qname);
4606     CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
4607     mDNSBool AnsweredFromCache = mDNSfalse;
4608 
4609     verbosedebugf("AnswerNewQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4610 
4611     if (cg) CheckCacheExpiration(m, slot, cg);
4612     if (m->NewQuestions != q) { LogInfo("AnswerNewQuestion: Question deleted while doing CheckCacheExpiration"); goto exit; }
4613     m->NewQuestions = q->next;
4614     // Advance NewQuestions to the next *after* calling CheckCacheExpiration, because if we advance it first
4615     // then CheckCacheExpiration may give this question add/remove callbacks, and it's not yet ready for that.
4616     //
4617     // Also, CheckCacheExpiration() calls CacheRecordDeferredAdd() and CacheRecordRmv(), which invoke
4618     // client callbacks, which may delete their own or any other question. Our mechanism for detecting
4619     // whether our current m->NewQuestions question got deleted by one of these callbacks is to store the
4620     // value of m->NewQuestions in 'q' before calling CheckCacheExpiration(), and then verify afterwards
4621     // that they're still the same. If m->NewQuestions has changed (because mDNS_StopQuery_internal
4622     // advanced it), that means the question was deleted, so we no longer need to worry about answering
4623     // it (and indeed 'q' is now a dangling pointer, so dereferencing it at all would be bad, and the
4624     // values we computed for slot and cg are now stale and relate to a question that no longer exists).
4625     //
4626     // We can't use the usual m->CurrentQuestion mechanism for this because  CacheRecordDeferredAdd() and
4627     // CacheRecordRmv() both use that themselves when walking the list of (non-new) questions generating callbacks.
4628     // Fortunately mDNS_StopQuery_internal auto-advances both m->CurrentQuestion *AND* m->NewQuestions when
4629     // deleting a question, so luckily we have an easy alternative way of detecting if our question got deleted.
4630 
4631     if (m->lock_rrcache) LogMsg("AnswerNewQuestion ERROR! Cache already locked!");
4632     // This should be safe, because calling the client's question callback may cause the
4633     // question list to be modified, but should not ever cause the rrcache list to be modified.
4634     // If the client's question callback deletes the question, then m->CurrentQuestion will
4635     // be advanced, and we'll exit out of the loop
4636     m->lock_rrcache = 1;
4637     if (m->CurrentQuestion)
4638         LogMsg("AnswerNewQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4639                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4640     m->CurrentQuestion = q;     // Indicate which question we're answering, so we'll know if it gets deleted
4641 
4642     if (q->NoAnswer == NoAnswer_Fail)
4643     {
4644         LogMsg("AnswerNewQuestion: NoAnswer_Fail %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4645         MakeNegativeCacheRecord(m, &m->rec.r, &q->qname, q->qnamehash, q->qtype, q->qclass, 60, mDNSInterface_Any, q->qDNSServer);
4646         q->NoAnswer = NoAnswer_Normal;      // Temporarily turn off answer suppression
4647         AnswerCurrentQuestionWithResourceRecord(m, &m->rec.r, QC_addnocache);
4648         // Don't touch the question if it has been stopped already
4649         if (m->CurrentQuestion == q) q->NoAnswer = NoAnswer_Fail;       // Restore NoAnswer state
4650         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
4651     }
4652 
4653     if (m->CurrentQuestion != q)
4654     {
4655         LogInfo("AnswerNewQuestion: Question deleted while generating NoAnswer_Fail response");
4656         goto exit;
4657     }
4658 
4659     // See if we want to tell it about LocalOnly/P2P records. If we answered them using LocalOnly
4660     // or P2P record, then we are done.
4661     if (AnswerQuestionWithLORecord(m, q, mDNSfalse))
4662         goto exit;
4663 
4664     // If we are not supposed to answer this question, generate a negative response.
4665     // Temporarily suspend the SuppressQuery so that AnswerCurrentQuestionWithResourceRecord can answer the question
4666     //
4667     // If it is a question trying to validate some response, it already checked the cache for a response. If it still
4668     // reissues a question it means it could not find the RRSIGs. So, we need to bypass the cache check and send
4669     // the question out.
4670     if (QuerySuppressed(q))
4671     {
4672         AnswerSuppressedQuestion(m, q);
4673     }
4674     else if (!q->ValidatingResponse)
4675     {
4676         CacheRecord *rr;
4677         for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
4678             if (SameNameRecordAnswersQuestion(&rr->resrec, q))
4679             {
4680                 // SecsSinceRcvd is whole number of elapsed seconds, rounded down
4681                 mDNSu32 SecsSinceRcvd = ((mDNSu32)(m->timenow - rr->TimeRcvd)) / mDNSPlatformOneSecond;
4682                 if (rr->resrec.rroriginalttl <= SecsSinceRcvd)
4683                 {
4684                     LogMsg("AnswerNewQuestion: How is rr->resrec.rroriginalttl %lu <= SecsSinceRcvd %lu for %s %d %d",
4685                            rr->resrec.rroriginalttl, SecsSinceRcvd, CRDisplayString(m, rr), m->timenow, rr->TimeRcvd);
4686                     continue;   // Go to next one in loop
4687                 }
4688 
4689                 // If this record set is marked unique, then that means we can reasonably assume we have the whole set
4690                 // -- we don't need to rush out on the network and query immediately to see if there are more answers out there
4691                 if ((rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) || (q->ExpectUnique))
4692                     ShouldQueryImmediately = mDNSfalse;
4693                 q->CurrentAnswers++;
4694                 if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers++;
4695                 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers++;
4696                 AnsweredFromCache = mDNStrue;
4697                 AnswerCurrentQuestionWithResourceRecord(m, rr, QC_add);
4698                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
4699             }
4700             else if (RRTypeIsAddressType(rr->resrec.rrtype) && RRTypeIsAddressType(q->qtype))
4701                 ShouldQueryImmediately = mDNSfalse;
4702     }
4703     // We don't use LogInfo for this "Question deleted" message because it happens so routinely that
4704     // it's not remotely remarkable, and therefore unlikely to be of much help tracking down bugs.
4705     if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving cache answers"); goto exit; }
4706 
4707     // Neither a local record nor a cache entry could answer this question. If this question need to be retried
4708     // with search domains, generate a negative response which will now retry after appending search domains.
4709     // If the query was suppressed above, we already generated a negative response. When it gets unsuppressed,
4710     // we will retry with search domains.
4711     if (!QuerySuppressed(q) && !AnsweredFromCache && q->RetryWithSearchDomains)
4712     {
4713         LogInfo("AnswerNewQuestion: Generating response for retrying with search domains %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4714         GenerateNegativeResponse(m, QC_forceresponse);
4715     }
4716 
4717     if (m->CurrentQuestion != q) { debugf("AnswerNewQuestion: Question deleted while giving negative answer"); goto exit; }
4718 
4719     // Note: When a query gets suppressed or retried with search domains, we de-activate the question.
4720     // Hence we don't execute the following block of code for those cases.
4721     if (ShouldQueryImmediately && ActiveQuestion(q))
4722     {
4723         debugf("AnswerNewQuestion: ShouldQueryImmediately %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4724         q->ThisQInterval  = InitialQuestionInterval;
4725         q->LastQTime      = m->timenow - q->ThisQInterval;
4726         if (mDNSOpaque16IsZero(q->TargetQID))       // For mDNS, spread packets to avoid a burst of simultaneous queries
4727         {
4728             // Compute random delay in the range 1-6 seconds, then divide by 50 to get 20-120ms
4729             if (!m->RandomQueryDelay)
4730                 m->RandomQueryDelay = (mDNSPlatformOneSecond + mDNSRandom(mDNSPlatformOneSecond*5) - 1) / 50 + 1;
4731             q->LastQTime += m->RandomQueryDelay;
4732         }
4733     }
4734 
4735     // IN ALL CASES make sure that m->NextScheduledQuery is set appropriately.
4736     // In cases where m->NewQuestions->DelayAnswering is set, we may have delayed generating our
4737     // answers for this question until *after* its scheduled transmission time, in which case
4738     // m->NextScheduledQuery may now be set to 'never', and in that case -- even though we're *not* doing
4739     // ShouldQueryImmediately -- we still need to make sure we set m->NextScheduledQuery correctly.
4740     SetNextQueryTime(m,q);
4741 
4742 exit:
4743     m->CurrentQuestion = mDNSNULL;
4744     m->lock_rrcache = 0;
4745 }
4746 
4747 // When a NewLocalOnlyQuestion is created, AnswerNewLocalOnlyQuestion runs though our ResourceRecords delivering any
4748 // appropriate answers, stopping if it reaches a NewLocalOnlyRecord -- these will be handled by AnswerAllLocalQuestionsWithLocalAuthRecord
4749 mDNSlocal void AnswerNewLocalOnlyQuestion(mDNS *const m)
4750 {
4751     mDNSu32 slot;
4752     AuthGroup *ag;
4753     DNSQuestion *q = m->NewLocalOnlyQuestions;      // Grab the question we're going to answer
4754     m->NewLocalOnlyQuestions = q->next;             // Advance NewLocalOnlyQuestions to the next (if any)
4755 
4756     debugf("AnswerNewLocalOnlyQuestion: Answering %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
4757 
4758     if (m->CurrentQuestion)
4759         LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentQuestion already set: %##s (%s)",
4760                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
4761     m->CurrentQuestion = q;     // Indicate which question we're answering, so we'll know if it gets deleted
4762 
4763     if (m->CurrentRecord)
4764         LogMsg("AnswerNewLocalOnlyQuestion ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
4765 
4766     // 1. First walk the LocalOnly records answering the LocalOnly question
4767     // 2. As LocalOnly questions should also be answered by any other Auth records local to the machine,
4768     //    walk the ResourceRecords list delivering the answers
4769     slot = AuthHashSlot(&q->qname);
4770     ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
4771     if (ag)
4772     {
4773         m->CurrentRecord = ag->members;
4774         while (m->CurrentRecord && m->CurrentRecord != ag->NewLocalOnlyRecords)
4775         {
4776             AuthRecord *rr = m->CurrentRecord;
4777             m->CurrentRecord = rr->next;
4778             if (LocalOnlyRecordAnswersQuestion(rr, q))
4779             {
4780                 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
4781                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
4782             }
4783         }
4784     }
4785 
4786     if (m->CurrentQuestion == q)
4787     {
4788         m->CurrentRecord = m->ResourceRecords;
4789 
4790         while (m->CurrentRecord && m->CurrentRecord != m->NewLocalRecords)
4791         {
4792             AuthRecord *rr = m->CurrentRecord;
4793             m->CurrentRecord = rr->next;
4794             if (ResourceRecordAnswersQuestion(&rr->resrec, q))
4795             {
4796                 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_add);
4797                 if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
4798             }
4799         }
4800     }
4801 
4802     m->CurrentQuestion = mDNSNULL;
4803     m->CurrentRecord   = mDNSNULL;
4804 }
4805 
4806 mDNSlocal CacheEntity *GetCacheEntity(mDNS *const m, const CacheGroup *const PreserveCG)
4807 {
4808     CacheEntity *e = mDNSNULL;
4809 
4810     if (m->lock_rrcache) { LogMsg("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
4811     m->lock_rrcache = 1;
4812 
4813     // If we have no free records, ask the client layer to give us some more memory
4814     if (!m->rrcache_free && m->MainCallback)
4815     {
4816         if (m->rrcache_totalused != m->rrcache_size)
4817             LogMsg("GetFreeCacheRR: count mismatch: m->rrcache_totalused %lu != m->rrcache_size %lu",
4818                    m->rrcache_totalused, m->rrcache_size);
4819 
4820         // We don't want to be vulnerable to a malicious attacker flooding us with an infinite
4821         // number of bogus records so that we keep growing our cache until the machine runs out of memory.
4822         // To guard against this, if our cache grows above 512kB (approx 3168 records at 164 bytes each),
4823         // and we're actively using less than 1/32 of that cache, then we purge all the unused records
4824         // and recycle them, instead of allocating more memory.
4825         if (m->rrcache_size > 5000 && m->rrcache_size / 32 > m->rrcache_active)
4826             LogInfo("Possible denial-of-service attack in progress: m->rrcache_size %lu; m->rrcache_active %lu",
4827                     m->rrcache_size, m->rrcache_active);
4828         else
4829         {
4830             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
4831             m->MainCallback(m, mStatus_GrowCache);
4832             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
4833         }
4834     }
4835 
4836     // If we still have no free records, recycle all the records we can.
4837     // Enumerating the entire cache is moderately expensive, so when we do it, we reclaim all the records we can in one pass.
4838     if (!m->rrcache_free)
4839     {
4840         mDNSu32 oldtotalused = m->rrcache_totalused;
4841         mDNSu32 slot;
4842         for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
4843         {
4844             CacheGroup **cp = &m->rrcache_hash[slot];
4845             while (*cp)
4846             {
4847                 CacheRecord **rp = &(*cp)->members;
4848                 while (*rp)
4849                 {
4850                     // Records that answer still-active questions are not candidates for recycling
4851                     // Records that are currently linked into the CacheFlushRecords list may not be recycled, or we'll crash
4852                     if ((*rp)->CRActiveQuestion || (*rp)->NextInCFList)
4853                         rp=&(*rp)->next;
4854                     else
4855                     {
4856                         CacheRecord *rr = *rp;
4857                         *rp = (*rp)->next;          // Cut record from list
4858                         ReleaseCacheRecord(m, rr);
4859                     }
4860                 }
4861                 if ((*cp)->rrcache_tail != rp)
4862                     verbosedebugf("GetFreeCacheRR: Updating rrcache_tail[%lu] from %p to %p", slot, (*cp)->rrcache_tail, rp);
4863                 (*cp)->rrcache_tail = rp;
4864                 if ((*cp)->members || (*cp)==PreserveCG) cp=&(*cp)->next;
4865                 else ReleaseCacheGroup(m, cp);
4866             }
4867         }
4868         LogInfo("GetCacheEntity recycled %d records to reduce cache from %d to %d",
4869                 oldtotalused - m->rrcache_totalused, oldtotalused, m->rrcache_totalused);
4870     }
4871 
4872     if (m->rrcache_free)    // If there are records in the free list, take one
4873     {
4874         e = m->rrcache_free;
4875         m->rrcache_free = e->next;
4876         if (++m->rrcache_totalused >= m->rrcache_report)
4877         {
4878             LogInfo("RR Cache now using %ld objects", m->rrcache_totalused);
4879             if      (m->rrcache_report <  100) m->rrcache_report += 10;
4880             else if (m->rrcache_report < 1000) m->rrcache_report += 100;
4881             else m->rrcache_report += 1000;
4882         }
4883         mDNSPlatformMemZero(e, sizeof(*e));
4884     }
4885 
4886     m->lock_rrcache = 0;
4887 
4888     return(e);
4889 }
4890 
4891 mDNSlocal CacheRecord *GetCacheRecord(mDNS *const m, CacheGroup *cg, mDNSu16 RDLength)
4892 {
4893     CacheRecord *r = (CacheRecord *)GetCacheEntity(m, cg);
4894     if (r)
4895     {
4896         r->resrec.rdata = (RData*)&r->smallrdatastorage;    // By default, assume we're usually going to be using local storage
4897         if (RDLength > InlineCacheRDSize)           // If RDLength is too big, allocate extra storage
4898         {
4899             r->resrec.rdata = (RData*)mDNSPlatformMemAllocate(sizeofRDataHeader + RDLength);
4900             if (r->resrec.rdata) r->resrec.rdata->MaxRDLength = r->resrec.rdlength = RDLength;
4901             else { ReleaseCacheEntity(m, (CacheEntity*)r); r = mDNSNULL; }
4902         }
4903     }
4904     return(r);
4905 }
4906 
4907 mDNSlocal CacheGroup *GetCacheGroup(mDNS *const m, const mDNSu32 slot, const ResourceRecord *const rr)
4908 {
4909     mDNSu16 namelen = DomainNameLength(rr->name);
4910     CacheGroup *cg = (CacheGroup*)GetCacheEntity(m, mDNSNULL);
4911     if (!cg) { LogMsg("GetCacheGroup: Failed to allocate memory for %##s", rr->name->c); return(mDNSNULL); }
4912     cg->next         = m->rrcache_hash[slot];
4913     cg->namehash     = rr->namehash;
4914     cg->members      = mDNSNULL;
4915     cg->rrcache_tail = &cg->members;
4916     if (namelen > sizeof(cg->namestorage))
4917         cg->name = mDNSPlatformMemAllocate(namelen);
4918     else
4919         cg->name = (domainname*)cg->namestorage;
4920     if (!cg->name)
4921     {
4922         LogMsg("GetCacheGroup: Failed to allocate name storage for %##s", rr->name->c);
4923         ReleaseCacheEntity(m, (CacheEntity*)cg);
4924         return(mDNSNULL);
4925     }
4926     AssignDomainName(cg->name, rr->name);
4927 
4928     if (CacheGroupForRecord(m, slot, rr)) LogMsg("GetCacheGroup: Already have CacheGroup for %##s", rr->name->c);
4929     m->rrcache_hash[slot] = cg;
4930     if (CacheGroupForRecord(m, slot, rr) != cg) LogMsg("GetCacheGroup: Not finding CacheGroup for %##s", rr->name->c);
4931 
4932     return(cg);
4933 }
4934 
4935 mDNSexport void mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr)
4936 {
4937     mDNS_CheckLock(m);
4938 
4939     // Make sure we mark this record as thoroughly expired -- we don't ever want to give
4940     // a positive answer using an expired record (e.g. from an interface that has gone away).
4941     // We don't want to clear CRActiveQuestion here, because that would leave the record subject to
4942     // summary deletion without giving the proper callback to any questions that are monitoring it.
4943     // By setting UnansweredQueries to MaxUnansweredQueries we ensure it won't trigger any further expiration queries.
4944     rr->TimeRcvd          = m->timenow - mDNSPlatformOneSecond * 60;
4945     rr->UnansweredQueries = MaxUnansweredQueries;
4946     rr->resrec.rroriginalttl     = 0;
4947     SetNextCacheCheckTimeForRecord(m, rr);
4948 }
4949 
4950 mDNSexport mDNSs32 mDNS_TimeNow(const mDNS *const m)
4951 {
4952     mDNSs32 time;
4953     mDNSPlatformLock(m);
4954     if (m->mDNS_busy)
4955     {
4956         LogMsg("mDNS_TimeNow called while holding mDNS lock. This is incorrect. Code protected by lock should just use m->timenow.");
4957         if (!m->timenow) LogMsg("mDNS_TimeNow: m->mDNS_busy is %ld but m->timenow not set", m->mDNS_busy);
4958     }
4959 
4960     if (m->timenow) time = m->timenow;
4961     else time = mDNS_TimeNow_NoLock(m);
4962     mDNSPlatformUnlock(m);
4963     return(time);
4964 }
4965 
4966 // To avoid pointless CPU thrash, we use SetSPSProxyListChanged(X) to record the last interface that
4967 // had its Sleep Proxy client list change, and defer to actual BPF reconfiguration to mDNS_Execute().
4968 // (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
4969 #define SetSPSProxyListChanged(X) do { \
4970         if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
4971         m->SPSProxyListChanged = (X); } while(0)
4972 
4973 // Called from mDNS_Execute() to expire stale proxy records
4974 mDNSlocal void CheckProxyRecords(mDNS *const m, AuthRecord *list)
4975 {
4976     m->CurrentRecord = list;
4977     while (m->CurrentRecord)
4978     {
4979         AuthRecord *rr = m->CurrentRecord;
4980         if (rr->resrec.RecordType != kDNSRecordTypeDeregistering && rr->WakeUp.HMAC.l[0])
4981         {
4982             // If m->SPSSocket is NULL that means we're not acting as a sleep proxy any more,
4983             // so we need to cease proxying for *all* records we may have, expired or not.
4984             if (m->SPSSocket && m->timenow - rr->TimeExpire < 0)    // If proxy record not expired yet, update m->NextScheduledSPS
4985             {
4986                 if (m->NextScheduledSPS - rr->TimeExpire > 0)
4987                     m->NextScheduledSPS = rr->TimeExpire;
4988             }
4989             else                                                    // else proxy record expired, so remove it
4990             {
4991                 LogSPS("CheckProxyRecords: Removing %d H-MAC %.6a I-MAC %.6a %d %s",
4992                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, ARDisplayString(m, rr));
4993                 SetSPSProxyListChanged(rr->resrec.InterfaceID);
4994                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
4995                 // Don't touch rr after this -- memory may have been free'd
4996             }
4997         }
4998         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
4999         // new records could have been added to the end of the list as a result of that call.
5000         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
5001             m->CurrentRecord = rr->next;
5002     }
5003 }
5004 
5005 mDNSlocal void CheckRmvEventsForLocalRecords(mDNS *const m)
5006 {
5007     while (m->CurrentRecord)
5008     {
5009         AuthRecord *rr = m->CurrentRecord;
5010         if (rr->AnsweredLocalQ && rr->resrec.RecordType == kDNSRecordTypeDeregistering)
5011         {
5012             debugf("CheckRmvEventsForLocalRecords: Generating local RMV events for %s", ARDisplayString(m, rr));
5013             rr->resrec.RecordType = kDNSRecordTypeShared;
5014             AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_rmv);
5015             if (m->CurrentRecord == rr) // If rr still exists in list, restore its state now
5016             {
5017                 rr->resrec.RecordType = kDNSRecordTypeDeregistering;
5018                 rr->AnsweredLocalQ = mDNSfalse;
5019                 // SendResponses normally calls CompleteDeregistration after sending goodbyes.
5020                 // For LocalOnly records, we don't do that and hence we need to do that here.
5021                 if (RRLocalOnly(rr)) CompleteDeregistration(m, rr);
5022             }
5023         }
5024         if (m->CurrentRecord == rr)     // If m->CurrentRecord was not auto-advanced, do it ourselves now
5025             m->CurrentRecord = rr->next;
5026     }
5027 }
5028 
5029 mDNSlocal void TimeoutQuestions(mDNS *const m)
5030 {
5031     m->NextScheduledStopTime = m->timenow + 0x3FFFFFFF;
5032     if (m->CurrentQuestion)
5033         LogMsg("TimeoutQuestions ERROR m->CurrentQuestion already set: %##s (%s)", m->CurrentQuestion->qname.c,
5034                DNSTypeName(m->CurrentQuestion->qtype));
5035     m->CurrentQuestion = m->Questions;
5036     while (m->CurrentQuestion)
5037     {
5038         DNSQuestion *const q = m->CurrentQuestion;
5039         if (q->StopTime)
5040         {
5041             if (!q->TimeoutQuestion)
5042                 LogMsg("TimeoutQuestions: ERROR!! TimeoutQuestion not set, but StopTime set for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5043 
5044             if (m->timenow - q->StopTime >= 0)
5045             {
5046                 LogInfo("TimeoutQuestions: question %p %##s timed out, time %d", q, q->qname.c, m->timenow - q->StopTime);
5047                 GenerateNegativeResponse(m, QC_forceresponse);
5048                 if (m->CurrentQuestion == q) q->StopTime = 0;
5049             }
5050             else
5051             {
5052                 if (m->NextScheduledStopTime - q->StopTime > 0)
5053                     m->NextScheduledStopTime = q->StopTime;
5054             }
5055         }
5056         // If m->CurrentQuestion wasn't modified out from under us, advance it now
5057         // We can't do this at the start of the loop because GenerateNegativeResponse
5058         // depends on having m->CurrentQuestion point to the right question
5059         if (m->CurrentQuestion == q)
5060             m->CurrentQuestion = q->next;
5061     }
5062     m->CurrentQuestion = mDNSNULL;
5063 }
5064 
5065 mDNSlocal void mDNSCoreFreeProxyRR(mDNS *const m)
5066 {
5067     AuthRecord *rrPtr = m->SPSRRSet, *rrNext = mDNSNULL;
5068     LogSPS("%s : Freeing stored sleep proxy A/AAAA records", __func__);
5069     while (rrPtr)
5070     {
5071         rrNext = rrPtr->next;
5072         mDNSPlatformMemFree(rrPtr);
5073         rrPtr  = rrNext;
5074     }
5075     m->SPSRRSet = mDNSNULL;
5076 }
5077 
5078 mDNSexport mDNSs32 mDNS_Execute(mDNS *const m)
5079 {
5080     mDNS_Lock(m);   // Must grab lock before trying to read m->timenow
5081 
5082 #if APPLE_OSX_mDNSResponder
5083     mDNSLogStatistics(m);
5084 #endif // APPLE_OSX_mDNSResponder
5085 
5086     if (m->timenow - m->NextScheduledEvent >= 0)
5087     {
5088         int i;
5089         AuthRecord *head, *tail;
5090         mDNSu32 slot;
5091         AuthGroup *ag;
5092 
5093         verbosedebugf("mDNS_Execute");
5094 
5095         if (m->CurrentQuestion)
5096             LogMsg("mDNS_Execute: ERROR m->CurrentQuestion already set: %##s (%s)",
5097                    m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5098 
5099         if (m->CurrentRecord)
5100             LogMsg("mDNS_Execute: ERROR m->CurrentRecord already set: %s", ARDisplayString(m, m->CurrentRecord));
5101 
5102         // 1. If we're past the probe suppression time, we can clear it
5103         if (m->SuppressProbes && m->timenow - m->SuppressProbes >= 0) m->SuppressProbes = 0;
5104 
5105         // 2. If it's been more than ten seconds since the last probe failure, we can clear the counter
5106         if (m->NumFailedProbes && m->timenow - m->ProbeFailTime >= mDNSPlatformOneSecond * 10) m->NumFailedProbes = 0;
5107 
5108         // 3. Purge our cache of stale old records
5109         if (m->rrcache_size && m->timenow - m->NextCacheCheck >= 0)
5110         {
5111             mDNSu32 numchecked = 0;
5112             m->NextCacheCheck = m->timenow + 0x3FFFFFFF;
5113             for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
5114             {
5115                 if (m->timenow - m->rrcache_nextcheck[slot] >= 0)
5116                 {
5117                     CacheGroup **cp = &m->rrcache_hash[slot];
5118                     m->rrcache_nextcheck[slot] = m->timenow + 0x3FFFFFFF;
5119                     while (*cp)
5120                     {
5121                         debugf("m->NextCacheCheck %4d Slot %3d %##s", numchecked, slot, *cp ? (*cp)->name : (domainname*)"\x04NULL");
5122                         numchecked++;
5123                         CheckCacheExpiration(m, slot, *cp);
5124                         if ((*cp)->members) cp=&(*cp)->next;
5125                         else ReleaseCacheGroup(m, cp);
5126                     }
5127                 }
5128                 // Even if we didn't need to actually check this slot yet, still need to
5129                 // factor its nextcheck time into our overall NextCacheCheck value
5130                 if (m->NextCacheCheck - m->rrcache_nextcheck[slot] > 0)
5131                     m->NextCacheCheck = m->rrcache_nextcheck[slot];
5132             }
5133             debugf("m->NextCacheCheck %4d checked, next in %d", numchecked, m->NextCacheCheck - m->timenow);
5134         }
5135 
5136         if (m->timenow - m->NextScheduledSPS >= 0)
5137         {
5138             m->NextScheduledSPS = m->timenow + 0x3FFFFFFF;
5139             CheckProxyRecords(m, m->DuplicateRecords);  // Clear m->DuplicateRecords first, then m->ResourceRecords
5140             CheckProxyRecords(m, m->ResourceRecords);
5141         }
5142 
5143         SetSPSProxyListChanged(mDNSNULL);       // Perform any deferred BPF reconfiguration now
5144 
5145         // Check to see if we need to send any keepalives. Do this after we called CheckProxyRecords above
5146         // as records could have expired during that check
5147         if (m->timenow - m->NextScheduledKA >= 0)
5148         {
5149             m->NextScheduledKA = m->timenow + 0x3FFFFFFF;
5150             mDNS_SendKeepalives(m);
5151         }
5152 
5153         // Clear AnnounceOwner if necessary. (Do this *before* SendQueries() and SendResponses().)
5154         if (m->AnnounceOwner && m->timenow - m->AnnounceOwner >= 0)
5155         {
5156             m->AnnounceOwner = 0;
5157         }
5158 
5159         if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
5160         {
5161             m->DelaySleep = 0;
5162             if (m->SleepState == SleepState_Transferring)
5163             {
5164                 LogSPS("Re-sleep delay passed; now checking for Sleep Proxy Servers");
5165                 BeginSleepProcessing(m);
5166             }
5167         }
5168 
5169         // 4. See if we can answer any of our new local questions from the cache
5170         for (i=0; m->NewQuestions && i<1000; i++)
5171         {
5172             if (m->NewQuestions->DelayAnswering && m->timenow - m->NewQuestions->DelayAnswering < 0) break;
5173             AnswerNewQuestion(m);
5174         }
5175         if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewQuestion exceeded loop limit");
5176 
5177         // Make sure we deliver *all* local RMV events, and clear the corresponding rr->AnsweredLocalQ flags, *before*
5178         // we begin generating *any* new ADD events in the m->NewLocalOnlyQuestions and m->NewLocalRecords loops below.
5179         for (i=0; i<1000 && m->LocalRemoveEvents; i++)
5180         {
5181             m->LocalRemoveEvents = mDNSfalse;
5182             m->CurrentRecord = m->ResourceRecords;
5183             CheckRmvEventsForLocalRecords(m);
5184             // Walk the LocalOnly records and deliver the RMV events
5185             for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5186                 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5187                 {
5188                     m->CurrentRecord = ag->members;
5189                     if (m->CurrentRecord) CheckRmvEventsForLocalRecords(m);
5190                 }
5191         }
5192 
5193         if (i >= 1000) LogMsg("mDNS_Execute: m->LocalRemoveEvents exceeded loop limit");
5194 
5195         for (i=0; m->NewLocalOnlyQuestions && i<1000; i++) AnswerNewLocalOnlyQuestion(m);
5196         if (i >= 1000) LogMsg("mDNS_Execute: AnswerNewLocalOnlyQuestion exceeded loop limit");
5197 
5198         head = tail = mDNSNULL;
5199         for (i=0; i<1000 && m->NewLocalRecords && m->NewLocalRecords != head; i++)
5200         {
5201             AuthRecord *rr = m->NewLocalRecords;
5202             m->NewLocalRecords = m->NewLocalRecords->next;
5203             if (LocalRecordReady(rr))
5204             {
5205                 debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5206                 AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5207             }
5208             else if (!rr->next)
5209             {
5210                 // If we have just one record that is not ready, we don't have to unlink and
5211                 // reinsert. As the NewLocalRecords will be NULL for this case, the loop will
5212                 // terminate and set the NewLocalRecords to rr.
5213                 debugf("mDNS_Execute: Just one LocalAuthRecord %s, breaking out of the loop early", ARDisplayString(m, rr));
5214                 if (head != mDNSNULL || m->NewLocalRecords != mDNSNULL)
5215                     LogMsg("mDNS_Execute: ERROR!!: head %p, NewLocalRecords %p", head, m->NewLocalRecords);
5216 
5217                 head = rr;
5218             }
5219             else
5220             {
5221                 AuthRecord **p = &m->ResourceRecords;   // Find this record in our list of active records
5222                 debugf("mDNS_Execute: Skipping LocalAuthRecord %s", ARDisplayString(m, rr));
5223                 // if this is the first record we are skipping, move to the end of the list.
5224                 // if we have already skipped records before, append it at the end.
5225                 while (*p && *p != rr) p=&(*p)->next;
5226                 if (*p) *p = rr->next;                  // Cut this record from the list
5227                 else { LogMsg("mDNS_Execute: ERROR!! Cannot find record %s in ResourceRecords list", ARDisplayString(m, rr)); break; }
5228                 if (!head)
5229                 {
5230                     while (*p) p=&(*p)->next;
5231                     *p = rr;
5232                     head = tail = rr;
5233                 }
5234                 else
5235                 {
5236                     tail->next = rr;
5237                     tail = rr;
5238                 }
5239                 rr->next = mDNSNULL;
5240             }
5241         }
5242         m->NewLocalRecords = head;
5243         debugf("mDNS_Execute: Setting NewLocalRecords to %s", (head ? ARDisplayString(m, head) : "NULL"));
5244 
5245         if (i >= 1000) LogMsg("mDNS_Execute: m->NewLocalRecords exceeded loop limit");
5246 
5247         // Check to see if we have any new LocalOnly/P2P records to examine for delivering
5248         // to our local questions
5249         if (m->NewLocalOnlyRecords)
5250         {
5251             m->NewLocalOnlyRecords = mDNSfalse;
5252             for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
5253                 for (ag = m->rrauth.rrauth_hash[slot]; ag; ag = ag->next)
5254                 {
5255                     for (i=0; i<100 && ag->NewLocalOnlyRecords; i++)
5256                     {
5257                         AuthRecord *rr = ag->NewLocalOnlyRecords;
5258                         ag->NewLocalOnlyRecords = ag->NewLocalOnlyRecords->next;
5259                         // LocalOnly records should always be ready as they never probe
5260                         if (LocalRecordReady(rr))
5261                         {
5262                             debugf("mDNS_Execute: Delivering Add event with LocalAuthRecord %s", ARDisplayString(m, rr));
5263                             AnswerAllLocalQuestionsWithLocalAuthRecord(m, rr, QC_add);
5264                         }
5265                         else LogMsg("mDNS_Execute: LocalOnlyRecord %s not ready", ARDisplayString(m, rr));
5266                     }
5267                     // We limit about 100 per AuthGroup that can be serviced at a time
5268                     if (i >= 100) LogMsg("mDNS_Execute: ag->NewLocalOnlyRecords exceeded loop limit");
5269                 }
5270         }
5271 
5272         // 5. See what packets we need to send
5273         if (m->mDNSPlatformStatus != mStatus_NoError || (m->SleepState == SleepState_Sleeping))
5274             DiscardDeregistrations(m);
5275         if (m->mDNSPlatformStatus == mStatus_NoError && (m->SuppressSending == 0 || m->timenow - m->SuppressSending >= 0))
5276         {
5277             // If the platform code is ready, and we're not suppressing packet generation right now
5278             // then send our responses, probes, and questions.
5279             // We check the cache first, because there might be records close to expiring that trigger questions to refresh them.
5280             // We send queries next, because there might be final-stage probes that complete their probing here, causing
5281             // them to advance to announcing state, and we want those to be included in any announcements we send out.
5282             // Finally, we send responses, including the previously mentioned records that just completed probing.
5283             m->SuppressSending = 0;
5284 
5285             // 6. Send Query packets. This may cause some probing records to advance to announcing state
5286             if (m->timenow - m->NextScheduledQuery >= 0 || m->timenow - m->NextScheduledProbe >= 0) SendQueries(m);
5287             if (m->timenow - m->NextScheduledQuery >= 0)
5288             {
5289                 DNSQuestion *q;
5290                 LogMsg("mDNS_Execute: SendQueries didn't send all its queries (%d - %d = %d) will try again in one second",
5291                        m->timenow, m->NextScheduledQuery, m->timenow - m->NextScheduledQuery);
5292                 m->NextScheduledQuery = m->timenow + mDNSPlatformOneSecond;
5293                 for (q = m->Questions; q && q != m->NewQuestions; q=q->next)
5294                     if (ActiveQuestion(q) && m->timenow - NextQSendTime(q) >= 0)
5295                         LogMsg("mDNS_Execute: SendQueries didn't send %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
5296             }
5297             if (m->timenow - m->NextScheduledProbe >= 0)
5298             {
5299                 LogMsg("mDNS_Execute: SendQueries didn't send all its probes (%d - %d = %d) will try again in one second",
5300                        m->timenow, m->NextScheduledProbe, m->timenow - m->NextScheduledProbe);
5301                 m->NextScheduledProbe = m->timenow + mDNSPlatformOneSecond;
5302             }
5303 
5304             // 7. Send Response packets, including probing records just advanced to announcing state
5305             if (m->timenow - m->NextScheduledResponse >= 0) SendResponses(m);
5306             if (m->timenow - m->NextScheduledResponse >= 0)
5307             {
5308                 LogMsg("mDNS_Execute: SendResponses didn't send all its responses; will try again in one second");
5309                 m->NextScheduledResponse = m->timenow + mDNSPlatformOneSecond;
5310             }
5311         }
5312 
5313         // Clear RandomDelay values, ready to pick a new different value next time
5314         m->RandomQueryDelay     = 0;
5315         m->RandomReconfirmDelay = 0;
5316 
5317         if (m->NextScheduledStopTime && m->timenow - m->NextScheduledStopTime >= 0) TimeoutQuestions(m);
5318 #ifndef UNICAST_DISABLED
5319         if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0) UpdateAllSRVRecords(m);
5320         if (m->timenow - m->NextScheduledNATOp >= 0) CheckNATMappings(m);
5321         if (m->timenow - m->NextuDNSEvent >= 0) uDNS_Tasks(m);
5322 #endif
5323     }
5324 
5325     // Note about multi-threaded systems:
5326     // On a multi-threaded system, some other thread could run right after the mDNS_Unlock(),
5327     // performing mDNS API operations that change our next scheduled event time.
5328     //
5329     // On multi-threaded systems (like the current Windows implementation) that have a single main thread
5330     // calling mDNS_Execute() (and other threads allowed to call mDNS API routines) it is the responsibility
5331     // of the mDNSPlatformUnlock() routine to signal some kind of stateful condition variable that will
5332     // signal whatever blocking primitive the main thread is using, so that it will wake up and execute one
5333     // more iteration of its loop, and immediately call mDNS_Execute() again. The signal has to be stateful
5334     // in the sense that if the main thread has not yet entered its blocking primitive, then as soon as it
5335     // does, the state of the signal will be noticed, causing the blocking primitive to return immediately
5336     // without blocking. This avoids the race condition between the signal from the other thread arriving
5337     // just *before* or just *after* the main thread enters the blocking primitive.
5338     //
5339     // On multi-threaded systems (like the current Mac OS 9 implementation) that are entirely timer-driven,
5340     // with no main mDNS_Execute() thread, it is the responsibility of the mDNSPlatformUnlock() routine to
5341     // set the timer according to the m->NextScheduledEvent value, and then when the timer fires, the timer
5342     // callback function should call mDNS_Execute() (and ignore the return value, which may already be stale
5343     // by the time it gets to the timer callback function).
5344 
5345     mDNS_Unlock(m);     // Calling mDNS_Unlock is what gives m->NextScheduledEvent its new value
5346     return(m->NextScheduledEvent);
5347 }
5348 
5349 #ifndef UNICAST_DISABLED
5350 mDNSlocal void SuspendLLQs(mDNS *m)
5351 {
5352     DNSQuestion *q;
5353     for (q = m->Questions; q; q = q->next)
5354         if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->state == LLQ_Established)
5355         { q->ReqLease = 0; sendLLQRefresh(m, q); }
5356 }
5357 #endif // UNICAST_DISABLED
5358 
5359 mDNSlocal mDNSBool QuestionHasLocalAnswers(mDNS *const m, DNSQuestion *q)
5360 {
5361     AuthRecord *rr;
5362     mDNSu32 slot;
5363     AuthGroup *ag;
5364 
5365     slot = AuthHashSlot(&q->qname);
5366     ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
5367     if (ag)
5368     {
5369         for (rr = ag->members; rr; rr=rr->next)
5370             // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
5371             if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
5372             {
5373                 LogInfo("QuestionHasLocalAnswers: Question %p %##s (%s) has local answer %s", q, q->qname.c, DNSTypeName(q->qtype), ARDisplayString(m, rr));
5374                 return mDNStrue;
5375             }
5376     }
5377     return mDNSfalse;
5378 }
5379 
5380 // ActivateUnicastQuery() is called from three places:
5381 // 1. When a new question is created
5382 // 2. On wake from sleep
5383 // 3. When the DNS configuration changes
5384 // In case 1 we don't want to mess with our established ThisQInterval and LastQTime (ScheduleImmediately is false)
5385 // In cases 2 and 3 we do want to cause the question to be resent immediately (ScheduleImmediately is true)
5386 mDNSlocal void ActivateUnicastQuery(mDNS *const m, DNSQuestion *const question, mDNSBool ScheduleImmediately)
5387 {
5388     // For now this AutoTunnel stuff is specific to Mac OS X.
5389     // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
5390 #if APPLE_OSX_mDNSResponder
5391     // Even though BTMM client tunnels are only useful for AAAA queries, we need to treat v4 and v6 queries equally.
5392     // Otherwise we can get the situation where the A query completes really fast (with an NXDOMAIN result) and the
5393     // caller then gives up waiting for the AAAA result while we're still in the process of setting up the tunnel.
5394     // To level the playing field, we block both A and AAAA queries while tunnel setup is in progress, and then
5395     // returns results for both at the same time. If we are looking for the _autotunnel6 record, then skip this logic
5396     // as this would trigger looking up _autotunnel6._autotunnel6 and end up failing the original query.
5397 
5398     if (RRTypeIsAddressType(question->qtype) && PrivateQuery(question) &&
5399         !SameDomainLabel(question->qname.c, (const mDNSu8 *)"\x0c_autotunnel6")&& question->QuestionCallback != AutoTunnelCallback)
5400     {
5401         question->NoAnswer = NoAnswer_Suspended;
5402         AddNewClientTunnel(m, question);
5403         return;
5404     }
5405 #endif // APPLE_OSX_mDNSResponder
5406 
5407     if (!question->DuplicateOf)
5408     {
5409         debugf("ActivateUnicastQuery: %##s %s%s%s",
5410                question->qname.c, DNSTypeName(question->qtype), PrivateQuery(question) ? " (Private)" : "", ScheduleImmediately ? " ScheduleImmediately" : "");
5411         question->CNAMEReferrals = 0;
5412         if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
5413         if (question->LongLived)
5414         {
5415             question->state = LLQ_InitialRequest;
5416             question->id = zeroOpaque64;
5417             question->servPort = zeroIPPort;
5418             if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
5419         }
5420         // If the question has local answers, then we don't want answers from outside
5421         if (ScheduleImmediately && !QuestionHasLocalAnswers(m, question))
5422         {
5423             question->ThisQInterval = InitialQuestionInterval;
5424             question->LastQTime     = m->timenow - question->ThisQInterval;
5425             SetNextQueryTime(m, question);
5426         }
5427     }
5428 }
5429 
5430 // Caller should hold the lock
5431 mDNSexport void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
5432                                               CallbackBeforeStartQuery BeforeStartCallback, void *context)
5433 {
5434     DNSQuestion *q;
5435     DNSQuestion *restart = mDNSNULL;
5436 
5437     mDNS_CheckLock(m);
5438 
5439     // 1. Flush the cache records
5440     if (flushCacheRecords) flushCacheRecords(m);
5441 
5442     // 2. Even though we may have purged the cache records above, before it can generate RMV event
5443     // we are going to stop the question. Hence we need to deliver the RMV event before we
5444     // stop the question.
5445     //
5446     // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
5447     // application callback can potentially stop the current question (detected by CurrentQuestion) or
5448     // *any* other question which could be the next one that we may process here. RestartQuestion
5449     // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
5450     // if the "next" question is stopped while the CurrentQuestion is stopped
5451 
5452     if (m->RestartQuestion)
5453         LogMsg("mDNSCoreRestartAddressQueries: ERROR!! m->RestartQuestion already set: %##s (%s)",
5454                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
5455 
5456     m->RestartQuestion = m->Questions;
5457     while (m->RestartQuestion)
5458     {
5459         q = m->RestartQuestion;
5460         m->RestartQuestion = q->next;
5461         // GetZoneData questions are referenced by other questions (original query that started the GetZoneData
5462         // question)  through their "nta" pointer. Normally when the original query stops, it stops the
5463         // GetZoneData question and also frees the memory (See CancelGetZoneData). If we stop the GetZoneData
5464         // question followed by the original query that refers to this GetZoneData question, we will end up
5465         // freeing the GetZoneData question and then start the "freed" question at the end.
5466 
5467         if (IsGetZoneDataQuestion(q))
5468         {
5469             DNSQuestion *refq = q->next;
5470             LogInfo("mDNSCoreRestartAddressQueries: Skipping GetZoneDataQuestion %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5471             // debug stuff, we just try to find the referencing question and don't do much with it
5472             while (refq)
5473             {
5474                 if (q == &refq->nta->question)
5475                 {
5476                     LogInfo("mDNSCoreRestartAddressQueries: Question %p %##s (%s) referring to GetZoneDataQuestion %p, not stopping", refq, refq->qname.c, DNSTypeName(refq->qtype), q);
5477                 }
5478                 refq = refq->next;
5479             }
5480             continue;
5481         }
5482 
5483         // This function is called when /etc/hosts changes and that could affect A, AAAA and CNAME queries
5484         if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA && q->qtype != kDNSType_CNAME) continue;
5485 
5486         // If the search domains did not change, then we restart all the queries. Otherwise, only
5487         // for queries for which we "might" have appended search domains ("might" because we may
5488         // find results before we apply search domains even though AppendSearchDomains is set to 1)
5489         if (!SearchDomainsChanged || q->AppendSearchDomains)
5490         {
5491             // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
5492             // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
5493             // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers). Let us say that
5494             // /etc/hosts has an A Record for web.apple.com. Any queries for web.apple.com will be answered locally.
5495             // But this can't prevent a CNAME/AAAA query to not to be sent on the wire. When it is sent on the wire,
5496             // it could create cache entries. When we are restarting queries, we can't deliver the cache RMV events
5497             // for the original query using these cache entries as ADDs were never delivered using these cache
5498             // entries and hence this order is needed.
5499 
5500             // If the query is suppressed, the RMV events won't be delivered
5501             if (!CacheRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Cache Record RMV events"); continue; }
5502 
5503             // SuppressQuery status does not affect questions that are answered using local records
5504             if (!LocalRecordRmvEventsForQuestion(m, q)) { LogInfo("mDNSCoreRestartAddressQueries: Question deleted while delivering Local Record RMV events"); continue; }
5505 
5506             LogInfo("mDNSCoreRestartAddressQueries: Stop question %p %##s (%s), AppendSearchDomains %d, qnameOrig %p", q,
5507                     q->qname.c, DNSTypeName(q->qtype), q->AppendSearchDomains, q->qnameOrig);
5508             mDNS_StopQuery_internal(m, q);
5509             // Reset state so that it looks like it was in the beginning i.e it should look at /etc/hosts, cache
5510             // and then search domains should be appended. At the beginning, qnameOrig was NULL.
5511             if (q->qnameOrig)
5512             {
5513                 LogInfo("mDNSCoreRestartAddressQueries: qnameOrig %##s", q->qnameOrig);
5514                 AssignDomainName(&q->qname, q->qnameOrig);
5515                 mDNSPlatformMemFree(q->qnameOrig);
5516                 q->qnameOrig = mDNSNULL;
5517                 q->RetryWithSearchDomains = ApplySearchDomainsFirst(q) ? 1 : 0;
5518             }
5519             q->SearchListIndex = 0;
5520             q->next = restart;
5521             restart = q;
5522         }
5523     }
5524 
5525     // 3. Callback before we start the query
5526     if (BeforeStartCallback) BeforeStartCallback(m, context);
5527 
5528     // 4. Restart all the stopped queries
5529     while (restart)
5530     {
5531         q = restart;
5532         restart = restart->next;
5533         q->next = mDNSNULL;
5534         LogInfo("mDNSCoreRestartAddressQueries: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
5535         mDNS_StartQuery_internal(m, q);
5536     }
5537 }
5538 
5539 mDNSexport void mDNSCoreRestartQueries(mDNS *const m)
5540 {
5541     DNSQuestion *q;
5542 
5543 #ifndef UNICAST_DISABLED
5544     // Retrigger all our uDNS questions
5545     if (m->CurrentQuestion)
5546         LogMsg("mDNSCoreRestartQueries: ERROR m->CurrentQuestion already set: %##s (%s)",
5547                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
5548     m->CurrentQuestion = m->Questions;
5549     while (m->CurrentQuestion)
5550     {
5551         q = m->CurrentQuestion;
5552         m->CurrentQuestion = m->CurrentQuestion->next;
5553         if (!mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q)) ActivateUnicastQuery(m, q, mDNStrue);
5554     }
5555 #endif
5556 
5557     // Retrigger all our mDNS questions
5558     for (q = m->Questions; q; q=q->next)                // Scan our list of questions
5559             mDNSCoreRestartQuestion(m, q);
5560 }
5561 
5562 // restart question if it's multicast and currently active
5563 mDNSexport void mDNSCoreRestartQuestion(mDNS *const m, DNSQuestion *q)
5564 {
5565     if (mDNSOpaque16IsZero(q->TargetQID) && ActiveQuestion(q))
5566     {
5567         q->ThisQInterval    = InitialQuestionInterval;  // MUST be > zero for an active question
5568 #if mDNS_REQUEST_UNICAST_RESPONSE
5569         q->RequestUnicast = SET_QU_IN_FIRST_FOUR_QUERIES;
5570 #else   // mDNS_REQUEST_UNICAST_RESPONSE
5571         q->RequestUnicast   = SET_QU_IN_FIRST_QUERY;
5572 #endif  // mDNS_REQUEST_UNICAST_RESPONSE
5573         q->LastQTime        = m->timenow - q->ThisQInterval;
5574         q->RecentAnswerPkts = 0;
5575         ExpireDupSuppressInfo(q->DupSuppress, m->timenow);
5576         m->NextScheduledQuery = m->timenow;
5577     }
5578 }
5579 
5580 // restart the probe/announce cycle for multicast record
5581 mDNSexport void mDNSCoreRestartRegistration(mDNS *const m, AuthRecord  *rr, int announceCount)
5582 {
5583     if (!AuthRecord_uDNS(rr))
5584     {
5585         if (rr->resrec.RecordType == kDNSRecordTypeVerified && !rr->DependentOn) rr->resrec.RecordType = kDNSRecordTypeUnique;
5586         rr->ProbeCount     = DefaultProbeCountForRecordType(rr->resrec.RecordType);
5587 
5588         // announceCount < 0 indicates default announce count should be used
5589         if (announceCount < 0)
5590             announceCount = InitialAnnounceCount;
5591         if (rr->AnnounceCount < announceCount)
5592             rr->AnnounceCount  = announceCount;
5593 
5594         if (mDNS_KeepaliveRecord(&rr->resrec))
5595             rr->AnnounceCount  = 0; // Do not announce keepalive records
5596         else
5597             rr->AnnounceCount  = InitialAnnounceCount;
5598         rr->SendNSECNow    = mDNSNULL;
5599         InitializeLastAPTime(m, rr);
5600     }
5601 }
5602 
5603 // ***************************************************************************
5604 #if COMPILER_LIKES_PRAGMA_MARK
5605 #pragma mark -
5606 #pragma mark - Power Management (Sleep/Wake)
5607 #endif
5608 
5609 mDNSexport void mDNS_UpdateAllowSleep(mDNS *const m)
5610 {
5611 #ifndef IDLESLEEPCONTROL_DISABLED
5612     mDNSBool allowSleep = mDNStrue;
5613     char reason[128];
5614 
5615     reason[0] = 0;
5616 
5617     if (m->SystemSleepOnlyIfWakeOnLAN)
5618     {
5619         // Don't sleep if we are a proxy for any services
5620         if (m->ProxyRecords)
5621         {
5622             allowSleep = mDNSfalse;
5623             mDNS_snprintf(reason, sizeof(reason), "sleep proxy for %d records", m->ProxyRecords);
5624             LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because we are proxying %d records", m->ProxyRecords);
5625         }
5626 
5627         if (allowSleep && mDNSCoreHaveAdvertisedMulticastServices(m))
5628         {
5629             // Scan the list of active interfaces
5630             NetworkInterfaceInfo *intf;
5631             for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
5632             {
5633                 if (intf->McastTxRx && !intf->Loopback && !mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
5634                 {
5635                     // Disallow sleep if this interface doesn't support NetWake
5636                     if (!intf->NetWake)
5637                     {
5638                         allowSleep = mDNSfalse;
5639                         mDNS_snprintf(reason, sizeof(reason), "%s does not support NetWake", intf->ifname);
5640                         LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s does not support NetWake", intf->ifname);
5641                         break;
5642                     }
5643 
5644                     // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
5645                     // that will be offloaded. If not, we should prevent sleep.
5646                     // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
5647 #if APPLE_OSX_mDNSResponder
5648                     if (!SupportsInNICProxy(intf))
5649 #endif
5650                     {
5651                         // Disallow sleep if there is no sleep proxy server
5652                         const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
5653                         if ( cr == mDNSNULL)
5654                         {
5655                             allowSleep = mDNSfalse;
5656                             mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
5657                             LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
5658                             break;
5659                         }
5660                         else if (m->SPSType != 0)
5661                         {
5662                             mDNSu32 mymetric = LocalSPSMetric(m);
5663                             mDNSu32 metric   = SPSMetric(cr->resrec.rdata->u.name.c);
5664                             if (metric >= mymetric)
5665                             {
5666                                 allowSleep = mDNSfalse;
5667                                 mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
5668                                 LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
5669                                 break;
5670                             }
5671                         }
5672                     }
5673                 }
5674             }
5675         }
5676     }
5677 
5678     // Call the platform code to enable/disable sleep
5679     mDNSPlatformSetAllowSleep(m, allowSleep, reason);
5680 #else
5681     (void) m;
5682 #endif /* !defined(IDLESLEEPCONTROL_DISABLED) */
5683 }
5684 
5685 mDNSlocal mDNSBool mDNSUpdateOkToSend(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSu32 scopeid)
5686 {
5687     // If it is not a uDNS record, check to see if the updateid is zero. "updateid" is cleared when we have
5688     // sent the resource record on all the interfaces. If the update id is not zero, check to see if it is time
5689     // to send.
5690     if (AuthRecord_uDNS(rr) || (rr->AuthFlags & AuthFlagsWakeOnly) || mDNSOpaque16IsZero(rr->updateid) ||
5691         m->timenow - (rr->LastAPTime + rr->ThisAPInterval) < 0)
5692     {
5693         return mDNSfalse;
5694     }
5695 
5696     // If we have a pending registration for "scopeid", it is ok to send the update on that interface.
5697     // If the scopeid is too big to check for validity, we don't check against updateIntID. When
5698     // we successfully update on all the interfaces (with whatever set in "rr->updateIntID"), we clear
5699     // updateid and we should have returned from above.
5700     //
5701     // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
5702     // platform function to extract the value from "intf" every time.
5703 
5704     if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
5705         (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
5706         return mDNStrue;
5707 
5708     return mDNSfalse;
5709 }
5710 
5711 mDNSexport void UpdateRMACCallback(mDNS *const m, void *context)
5712 {
5713 	IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
5714 	m->CurrentRecord = m->ResourceRecords;
5715 
5716 	if (!addrmap)
5717 	{
5718 		LogMsg("UpdateRMACCallback: Address mapping is NULL");
5719 		return;
5720 	}
5721 
5722 	while (m->CurrentRecord)
5723 	{
5724 		AuthRecord *rr = m->CurrentRecord;
5725 		// If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
5726 		if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
5727 		{
5728 			mDNSAddr raddr;
5729 			getKeepaliveRaddr(m, rr, &raddr);
5730 			if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
5731 			{
5732 				// Update the MAC address only if it is not a zero MAC address
5733 				mDNSEthAddr macAddr;
5734 				mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr);
5735 				if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr))
5736 				{
5737 					UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
5738 				}
5739 			}
5740 		}
5741 		m->CurrentRecord = rr->next;
5742 	}
5743 
5744 	if (addrmap)
5745 	{
5746 		mDNSPlatformMemFree(addrmap);
5747 	}
5748 }
5749 
5750 mDNSexport mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr)
5751 {
5752     mDNSu16 newrdlength;
5753     mDNSAddr laddr, raddr;
5754     mDNSEthAddr eth;
5755     mDNSIPPort lport, rport;
5756     mDNSu32 timeout, seq, ack;
5757     mDNSu16 win;
5758     UTF8str255 txt;
5759     int rdsize;
5760     RData *newrd;
5761     mDNSTCPInfo mti;
5762     mStatus ret;
5763 
5764     // Note: If we fail to update the  DNS NULL  record with additional information in this function, it will be registered
5765     // with the SPS like any other record. SPS will not send keepalives if it does not have additional information.
5766     mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
5767     if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(lport) ||
5768         mDNSIPPortIsZero(rport))
5769     {
5770         LogMsg("UpdateKeepaliveRData: not a valid record %s for keepalive %#a:%d %#a:%d", ARDisplayString(m, rr), &laddr, lport.NotAnInteger, &raddr, rport.NotAnInteger);
5771         return mStatus_UnknownErr;
5772     }
5773 
5774     if (updateMac)
5775     {
5776         if (laddr.type == mDNSAddrType_IPv4)
5777             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);
5778         else
5779             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);
5780 
5781     }
5782     else
5783     {
5784         // If this keepalive packet would be sent on a different interface than the current one that we are processing
5785         // now, then we don't update the DNS NULL record. But we do not prevent it from registering with the SPS. When SPS sees
5786         // this DNS NULL record, it does not send any keepalives as it does not have all the information
5787         mDNSPlatformMemZero(&mti, sizeof (mDNSTCPInfo));
5788         ret = mDNSPlatformRetrieveTCPInfo(m, &laddr, &lport, &raddr, &rport, &mti);
5789         if (ret != mStatus_NoError)
5790         {
5791             LogMsg("mDNSPlatformRetrieveTCPInfo: mDNSPlatformRetrieveTCPInfo failed %d", ret);
5792             return ret;
5793         }
5794         if ((intf != mDNSNULL) && (mti.IntfId != intf->InterfaceID))
5795         {
5796             LogInfo("mDNSPlatformRetrieveTCPInfo: InterfaceID  mismatch mti.IntfId = %p InterfaceID = %p",  mti.IntfId, intf->InterfaceID);
5797             return mStatus_BadParamErr;
5798         }
5799 
5800         if (laddr.type == mDNSAddrType_IPv4)
5801             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);
5802         else
5803             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);
5804     }
5805 
5806     // Did we insert a null byte at the end ?
5807     if (newrdlength == (sizeof(txt.c) - 1))
5808     {
5809         LogMsg("UpdateKeepaliveRData: could not allocate memory %s", ARDisplayString(m, rr));
5810         return mStatus_NoMemoryErr;
5811     }
5812 
5813     // Include the length for the null byte at the end
5814     txt.c[0] = newrdlength + 1;
5815     // Account for the first length byte and the null byte at the end
5816     newrdlength += 2;
5817 
5818     rdsize = newrdlength > sizeof(RDataBody) ? newrdlength : sizeof(RDataBody);
5819     newrd = mDNSPlatformMemAllocate(sizeof(RData) - sizeof(RDataBody) + rdsize);
5820     if (!newrd) { LogMsg("UpdateKeepaliveRData: ptr NULL"); return mStatus_NoMemoryErr; }
5821 
5822     newrd->MaxRDLength = (mDNSu16) rdsize;
5823     mDNSPlatformMemCopy(&newrd->u, txt.c, newrdlength);
5824 
5825     //  If we are updating the record for the first time, rdata points to rdatastorage as the rdata memory
5826     //  was allocated as part of the AuthRecord itself. We allocate memory when we update the AuthRecord.
5827     //  If the resource record has data that we allocated in a previous pass (to update MAC address),
5828     //  free that memory here before copying in the new data.
5829     if ( rr->resrec.rdata != &rr->rdatastorage)
5830     {
5831         mDNSPlatformMemFree(rr->resrec.rdata);
5832         LogSPS("UpdateKeepaliveRData: Freed allocated memory for keep alive packet: %s ", ARDisplayString(m, rr));
5833     }
5834     SetNewRData(&rr->resrec, newrd, newrdlength);    // Update our rdata
5835 
5836     LogSPS("UpdateKeepaliveRData: successfully updated the record %s", ARDisplayString(m, rr));
5837     return mStatus_NoError;
5838 }
5839 
5840 mDNSlocal void SendSPSRegistrationForOwner(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id, const OwnerOptData *const owner)
5841 {
5842     const int optspace = DNSOpt_Header_Space + DNSOpt_LeaseData_Space + DNSOpt_Owner_Space(&m->PrimaryMAC, &intf->MAC);
5843     const int sps = intf->NextSPSAttempt / 3;
5844     AuthRecord *rr;
5845     mDNSOpaque16 msgid;
5846     mDNSu32 scopeid;
5847 
5848     scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
5849     if (!intf->SPSAddr[sps].type)
5850     {
5851         intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
5852         if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
5853             m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
5854         LogSPS("SendSPSRegistration: %s SPS %d (%d) %##s not yet resolved", intf->ifname, intf->NextSPSAttempt, sps, intf->NetWakeResolve[sps].qname.c);
5855         goto exit;
5856     }
5857 
5858     // Mark our mDNS records (not unicast records) for transfer to SPS
5859     if (mDNSOpaque16IsZero(id))
5860     {
5861         // We may have to register this record over multiple interfaces and we don't want to
5862         // overwrite the id. We send the registration over interface X with id "IDX" and before
5863         // we get a response, we overwrite with id "IDY" for interface Y and we won't accept responses
5864         // for "IDX". Hence, we want to use the same ID across all interfaces.
5865         //
5866         // In the case of sleep proxy server transfering its records when it goes to sleep, the owner
5867         // option check below will set the same ID across the records from the same owner. Records
5868         // with different owner option gets different ID.
5869         msgid = mDNS_NewMessageID(m);
5870         for (rr = m->ResourceRecords; rr; rr=rr->next)
5871         {
5872             if (!(rr->AuthFlags & AuthFlagsWakeOnly) && rr->resrec.RecordType > kDNSRecordTypeDeregistering)
5873             {
5874                 if (rr->resrec.InterfaceID == intf->InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
5875                 {
5876                     if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
5877                     {
5878                         rr->SendRNow = mDNSInterfaceMark;   // mark it now
5879                         // When we are registering on the first interface, rr->updateid is zero in which case
5880                         // initialize with the new ID. For subsequent interfaces, we want to use the same ID.
5881                         // At the end, all the updates sent across all the interfaces with the same ID.
5882                         if (mDNSOpaque16IsZero(rr->updateid))
5883                             rr->updateid = msgid;
5884                         else
5885                             msgid = rr->updateid;
5886                     }
5887                 }
5888             }
5889         }
5890     }
5891     else
5892         msgid = id;
5893 
5894     while (1)
5895     {
5896         mDNSu8 *p = m->omsg.data;
5897         // To comply with RFC 2782, PutResourceRecord suppresses name compression for SRV records in unicast updates.
5898         // For now we follow that same logic for SPS registrations too.
5899         // If we decide to compress SRV records in SPS registrations in the future, we can achieve that by creating our
5900         // initial DNSMessage with h.flags set to zero, and then update it to UpdateReqFlags right before sending the packet.
5901         InitializeDNSMessage(&m->omsg.h, msgid, UpdateReqFlags);
5902 
5903         for (rr = m->ResourceRecords; rr; rr=rr->next)
5904             if (rr->SendRNow || mDNSUpdateOkToSend(m, rr, intf, scopeid))
5905             {
5906                 if (mDNSPlatformMemSame(owner, &rr->WakeUp, sizeof(*owner)))
5907                 {
5908                     mDNSu8 *newptr;
5909                     const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.mDNS_numUpdates ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData) - optspace;
5910 
5911                     // If we can't update the keepalive record, don't send it
5912                     if (mDNS_KeepaliveRecord(&rr->resrec) && (UpdateKeepaliveRData(m, rr, intf, mDNSfalse, mDNSNULL) != mStatus_NoError))
5913                     {
5914                         if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
5915                         {
5916                             bit_clr_opaque64(rr->updateIntID, scopeid);
5917                         }
5918                         rr->SendRNow = mDNSNULL;
5919                         continue;
5920                     }
5921 
5922                     if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
5923                         rr->resrec.rrclass |= kDNSClass_UniqueRRSet;    // Temporarily set the 'unique' bit so PutResourceRecord will set it
5924                     newptr = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.mDNS_numUpdates, &rr->resrec, rr->resrec.rroriginalttl, limit);
5925                     rr->resrec.rrclass &= ~kDNSClass_UniqueRRSet;       // Make sure to clear 'unique' bit back to normal state
5926                     if (!newptr)
5927                         LogSPS("SendSPSRegistration put %s FAILED %d/%d %s", intf->ifname, p - m->omsg.data, limit - m->omsg.data, ARDisplayString(m, rr));
5928                     else
5929                     {
5930                         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));
5931                         rr->SendRNow       = mDNSNULL;
5932                         rr->ThisAPInterval = mDNSPlatformOneSecond;
5933                         rr->LastAPTime     = m->timenow;
5934                         // should be initialized above
5935                         if (mDNSOpaque16IsZero(rr->updateid)) LogMsg("SendSPSRegistration: ERROR!! rr %s updateid is zero", ARDisplayString(m, rr));
5936                         if (m->NextScheduledResponse - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
5937                             m->NextScheduledResponse = (rr->LastAPTime + rr->ThisAPInterval);
5938                         p = newptr;
5939                     }
5940                 }
5941             }
5942 
5943         if (!m->omsg.h.mDNS_numUpdates) break;
5944         else
5945         {
5946             AuthRecord opt;
5947             mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
5948             opt.resrec.rrclass    = NormalMaxDNSMessageData;
5949             opt.resrec.rdlength   = sizeof(rdataOPT) * 2;   // Two options in this OPT record
5950             opt.resrec.rdestimate = sizeof(rdataOPT) * 2;
5951             opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
5952             opt.resrec.rdata->u.opt[0].optlen        = DNSOpt_LeaseData_Space - 4;
5953             opt.resrec.rdata->u.opt[0].u.updatelease = DEFAULT_UPDATE_LEASE;
5954             if (!owner->HMAC.l[0])                                          // If no owner data,
5955                 SetupOwnerOpt(m, intf, &opt.resrec.rdata->u.opt[1]);        // use our own interface information
5956             else                                                            // otherwise, use the owner data we were given
5957             {
5958                 opt.resrec.rdata->u.opt[1].u.owner = *owner;
5959                 opt.resrec.rdata->u.opt[1].opt     = kDNSOpt_Owner;
5960                 opt.resrec.rdata->u.opt[1].optlen  = DNSOpt_Owner_Space(&owner->HMAC, &owner->IMAC) - 4;
5961             }
5962             LogSPS("SendSPSRegistration put %s %s", intf->ifname, ARDisplayString(m, &opt));
5963             p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
5964             if (!p)
5965                 LogMsg("SendSPSRegistration: Failed to put OPT record (%d updates) %s", m->omsg.h.mDNS_numUpdates, ARDisplayString(m, &opt));
5966             else
5967             {
5968                 mStatus err;
5969 
5970                 LogSPS("SendSPSRegistration: Sending Update %s %d (%d) id %5d with %d records %d bytes to %#a:%d", intf->ifname, intf->NextSPSAttempt, sps,
5971                        mDNSVal16(m->omsg.h.id), m->omsg.h.mDNS_numUpdates, p - m->omsg.data, &intf->SPSAddr[sps], mDNSVal16(intf->SPSPort[sps]));
5972                 // if (intf->NextSPSAttempt < 5) m->omsg.h.flags = zeroID;	// For simulating packet loss
5973                 err = mDNSSendDNSMessage(m, &m->omsg, p, intf->InterfaceID, mDNSNULL, &intf->SPSAddr[sps], intf->SPSPort[sps], mDNSNULL, mDNSNULL, mDNSfalse);
5974                 if (err) LogSPS("SendSPSRegistration: mDNSSendDNSMessage err %d", err);
5975                 if (err && intf->SPSAddr[sps].type == mDNSAddrType_IPv4 && intf->NetWakeResolve[sps].ThisQInterval == -1)
5976                 {
5977                     LogSPS("SendSPSRegistration %d %##s failed to send to IPv4 address; will try IPv6 instead", sps, intf->NetWakeResolve[sps].qname.c);
5978                     intf->NetWakeResolve[sps].qtype = kDNSType_AAAA;
5979                     mDNS_StartQuery_internal(m, &intf->NetWakeResolve[sps]);
5980                     return;
5981                 }
5982             }
5983         }
5984     }
5985 
5986     intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond * 10;     // If successful, update NextSPSAttemptTime
5987 
5988 exit:
5989     if (mDNSOpaque16IsZero(id) && intf->NextSPSAttempt < 8) intf->NextSPSAttempt++;
5990 }
5991 
5992 mDNSlocal mDNSBool RecordIsFirstOccurrenceOfOwner(mDNS *const m, const AuthRecord *const rr)
5993 {
5994     AuthRecord *ar;
5995     for (ar = m->ResourceRecords; ar && ar != rr; ar=ar->next)
5996         if (mDNSPlatformMemSame(&rr->WakeUp, &ar->WakeUp, sizeof(rr->WakeUp))) return mDNSfalse;
5997     return mDNStrue;
5998 }
5999 
6000 mDNSlocal void mDNSCoreStoreProxyRR(mDNS *const m, const mDNSInterfaceID InterfaceID, AuthRecord *const rr)
6001 {
6002     AuthRecord *newRR = mDNSPlatformMemAllocate(sizeof(AuthRecord));
6003 
6004     if (newRR == mDNSNULL)
6005     {
6006         LogSPS("%s : could not allocate memory for new resource record", __func__);
6007         return;
6008     }
6009 
6010     mDNSPlatformMemZero(newRR, sizeof(AuthRecord));
6011     mDNS_SetupResourceRecord(newRR, mDNSNULL, InterfaceID, rr->resrec.rrtype,
6012                              rr->resrec.rroriginalttl, rr->resrec.RecordType,
6013                              rr->ARType, mDNSNULL, mDNSNULL);
6014 
6015     AssignDomainName(&newRR->namestorage, &rr->namestorage);
6016     newRR->resrec.rdlength = DomainNameLength(rr->resrec.name);
6017     newRR->resrec.namehash = DomainNameHashValue(newRR->resrec.name);
6018     newRR->resrec.rrclass  = rr->resrec.rrclass;
6019 
6020     if (rr->resrec.rrtype == kDNSType_A)
6021     {
6022         newRR->resrec.rdata->u.ipv4 =  rr->resrec.rdata->u.ipv4;
6023     }
6024     else if (rr->resrec.rrtype == kDNSType_AAAA)
6025     {
6026         newRR->resrec.rdata->u.ipv6 = rr->resrec.rdata->u.ipv6;
6027     }
6028     SetNewRData(&newRR->resrec, mDNSNULL, 0);
6029 
6030     // Insert the new node at the head of the list.
6031     newRR->next        = m->SPSRRSet;
6032     m->SPSRRSet        = newRR;
6033     LogSPS("%s : Storing proxy record : %s ", __func__, ARDisplayString(m, rr));
6034 }
6035 
6036 // Some records are interface specific and some are not. The ones that are supposed to be registered
6037 // on multiple interfaces need to be initialized with all the valid interfaces on which it will be sent.
6038 // updateIntID bit field tells us on which interfaces we need to register this record. When we get an
6039 // ack from the sleep proxy server, we clear the interface bit. This way, we know when a record completes
6040 // registration on all the interfaces
6041 mDNSlocal void SPSInitRecordsBeforeUpdate(mDNS *const m, mDNSOpaque64 updateIntID, mDNSBool *WakeOnlyService)
6042 {
6043     AuthRecord *ar;
6044     LogSPS("SPSInitRecordsBeforeUpdate: UpdateIntID 0x%x 0x%x", updateIntID.l[1], updateIntID.l[0]);
6045 
6046     *WakeOnlyService = mDNSfalse;
6047 
6048     // Before we store the A and AAAA records that we are going to register with the sleep proxy,
6049     // make sure that the old sleep proxy records are removed.
6050     mDNSCoreFreeProxyRR(m);
6051 
6052     // For records that are registered only on a specific interface, mark only that bit as it will
6053     // never be registered on any other interface. For others, it should be sent on all interfaces.
6054     for (ar = m->ResourceRecords; ar; ar=ar->next)
6055     {
6056         ar->updateIntID = zeroOpaque64;
6057         ar->updateid    = zeroID;
6058         if (AuthRecord_uDNS(ar))
6059         {
6060             continue;
6061         }
6062         if (ar->AuthFlags & AuthFlagsWakeOnly)
6063         {
6064             if (ar->resrec.RecordType == kDNSRecordTypeShared && ar->RequireGoodbye)
6065             {
6066                 ar->ImmedAnswer = mDNSInterfaceMark;
6067                 *WakeOnlyService = mDNStrue;
6068                 continue;
6069             }
6070         }
6071         if (!ar->resrec.InterfaceID)
6072         {
6073             LogSPS("Setting scopeid (ALL) 0x%x 0x%x for %s", updateIntID.l[1], updateIntID.l[0], ARDisplayString(m, ar));
6074             ar->updateIntID = updateIntID;
6075         }
6076         else
6077         {
6078             // Filter records that belong to interfaces that we won't register the records on. UpdateIntID captures
6079             // exactly this.
6080             mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, ar->resrec.InterfaceID, mDNStrue);
6081             if ((scopeid < (sizeof(updateIntID) * mDNSNBBY)) && bit_get_opaque64(updateIntID, scopeid))
6082             {
6083                 bit_set_opaque64(ar->updateIntID, scopeid);
6084                 LogSPS("SPSInitRecordsBeforeUpdate: Setting scopeid(%d) 0x%x 0x%x for %s", scopeid, ar->updateIntID.l[1],
6085                     ar->updateIntID.l[0], ARDisplayString(m, ar));
6086             }
6087             else
6088             {
6089                 LogSPS("SPSInitRecordsBeforeUpdate: scopeid %d beyond range or not valid for SPS registration", scopeid);
6090             }
6091         }
6092         // Store the A and AAAA records that we registered with the sleep proxy.
6093         // We will use this to prevent spurious name conflicts that may occur when we wake up
6094         if (ar->resrec.rrtype == kDNSType_A || ar->resrec.rrtype == kDNSType_AAAA)
6095         {
6096             mDNSCoreStoreProxyRR(m, ar->resrec.InterfaceID, ar);
6097         }
6098     }
6099 }
6100 
6101 mDNSlocal void SendSPSRegistration(mDNS *const m, NetworkInterfaceInfo *const intf, const mDNSOpaque16 id)
6102 {
6103     AuthRecord *ar;
6104     OwnerOptData owner = zeroOwner;
6105 
6106     SendSPSRegistrationForOwner(m, intf, id, &owner);
6107 
6108     for (ar = m->ResourceRecords; ar; ar=ar->next)
6109     {
6110         if (!mDNSPlatformMemSame(&owner, &ar->WakeUp, sizeof(owner)) && RecordIsFirstOccurrenceOfOwner(m, ar))
6111         {
6112             owner = ar->WakeUp;
6113             SendSPSRegistrationForOwner(m, intf, id, &owner);
6114         }
6115     }
6116 }
6117 
6118 // RetrySPSRegistrations is called from SendResponses, with the lock held
6119 mDNSlocal void RetrySPSRegistrations(mDNS *const m)
6120 {
6121     AuthRecord *rr;
6122     NetworkInterfaceInfo *intf;
6123 
6124     // First make sure none of our interfaces' NextSPSAttemptTimes are inadvertently set to m->timenow + mDNSPlatformOneSecond * 10
6125     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6126         if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10)
6127             intf->NextSPSAttemptTime++;
6128 
6129     // Retry any record registrations that are due
6130     for (rr = m->ResourceRecords; rr; rr=rr->next)
6131         if (!AuthRecord_uDNS(rr) && !mDNSOpaque16IsZero(rr->updateid) && m->timenow - (rr->LastAPTime + rr->ThisAPInterval) >= 0)
6132         {
6133             for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6134             {
6135                 // If we still have registrations pending on this interface, send it now
6136                 mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6137                 if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
6138                     (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == intf->InterfaceID))
6139                 {
6140                     LogSPS("RetrySPSRegistrations: 0x%x 0x%x (updateid %d) %s", rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m, rr));
6141                     SendSPSRegistration(m, intf, rr->updateid);
6142                 }
6143             }
6144         }
6145 
6146     // For interfaces where we did an SPS registration attempt, increment intf->NextSPSAttempt
6147     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6148         if (intf->NextSPSAttempt && intf->NextSPSAttemptTime == m->timenow + mDNSPlatformOneSecond * 10 && intf->NextSPSAttempt < 8)
6149             intf->NextSPSAttempt++;
6150 }
6151 
6152 mDNSlocal void NetWakeResolve(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
6153 {
6154     NetworkInterfaceInfo *intf = (NetworkInterfaceInfo *)question->QuestionContext;
6155     int sps = (int)(question - intf->NetWakeResolve);
6156     (void)m;            // Unused
6157     LogSPS("NetWakeResolve: SPS: %d Add: %d %s", sps, AddRecord, RRDisplayString(m, answer));
6158 
6159     if (!AddRecord) return;                                             // Don't care about REMOVE events
6160     if (answer->rrtype != question->qtype) return;                      // Don't care about CNAMEs
6161 
6162     // if (answer->rrtype == kDNSType_AAAA && sps == 0) return;	// To test failing to resolve sleep proxy's address
6163 
6164     if (answer->rrtype == kDNSType_SRV)
6165     {
6166         // 1. Got the SRV record; now look up the target host's IP address
6167         mDNS_StopQuery(m, question);
6168         intf->SPSPort[sps] = answer->rdata->u.srv.port;
6169         AssignDomainName(&question->qname, &answer->rdata->u.srv.target);
6170         question->qtype = kDNSType_A;
6171         mDNS_StartQuery(m, question);
6172     }
6173     else if (answer->rrtype == kDNSType_A && answer->rdlength == sizeof(mDNSv4Addr))
6174     {
6175         // 2. Got an IPv4 address for the target host; record address and initiate an SPS registration if appropriate
6176         mDNS_StopQuery(m, question);
6177         question->ThisQInterval = -1;
6178         intf->SPSAddr[sps].type = mDNSAddrType_IPv4;
6179         intf->SPSAddr[sps].ip.v4 = answer->rdata->u.ipv4;
6180         mDNS_Lock(m);
6181         if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);    // If we're ready for this result, use it now
6182         mDNS_Unlock(m);
6183     }
6184     else if (answer->rrtype == kDNSType_A && answer->rdlength == 0)
6185     {
6186         // 3. Got negative response -- target host apparently has IPv6 disabled -- so try looking up the target host's IPv4 address(es) instead
6187         mDNS_StopQuery(m, question);
6188         LogSPS("NetWakeResolve: SPS %d %##s has no IPv4 address, will try IPv6 instead", sps, question->qname.c);
6189         question->qtype = kDNSType_AAAA;
6190         mDNS_StartQuery(m, question);
6191     }
6192     else if (answer->rrtype == kDNSType_AAAA && answer->rdlength == sizeof(mDNSv6Addr) && mDNSv6AddressIsLinkLocal(&answer->rdata->u.ipv6))
6193     {
6194         // 4. Got the target host's IPv6 link-local address; record address and initiate an SPS registration if appropriate
6195         mDNS_StopQuery(m, question);
6196         question->ThisQInterval = -1;
6197         intf->SPSAddr[sps].type = mDNSAddrType_IPv6;
6198         intf->SPSAddr[sps].ip.v6 = answer->rdata->u.ipv6;
6199         mDNS_Lock(m);
6200         if (sps == intf->NextSPSAttempt/3) SendSPSRegistration(m, intf, zeroID);    // If we're ready for this result, use it now
6201         mDNS_Unlock(m);
6202     }
6203 }
6204 
6205 mDNSexport mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m)
6206 {
6207     AuthRecord *rr;
6208     for (rr = m->ResourceRecords; rr; rr=rr->next)
6209         if (mDNS_KeepaliveRecord(&rr->resrec) || (rr->resrec.rrtype == kDNSType_SRV && !AuthRecord_uDNS(rr) && !mDNSSameIPPort(rr->resrec.rdata->u.srv.port, DiscardPort)))
6210             return mDNStrue;
6211     return mDNSfalse;
6212 }
6213 
6214 #define WAKE_ONLY_SERVICE 1
6215 #define AC_ONLY_SERVICE   2
6216 
6217 #ifdef APPLE_OSX_mDNSResponder
6218 mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType)
6219 {
6220     AuthRecord *rr;
6221     *servicePresent = mDNSfalse;
6222 
6223     // Mark all the records we need to deregister and send them
6224     for (rr = m->ResourceRecords; rr; rr=rr->next)
6225     {
6226         // If the service type is wake only service and the auth flags match and requires a goodbye
6227         // OR if the service type is AC only and it is not a keepalive record,
6228         // mark the records we need to deregister and send them
6229         if ((serviceType == WAKE_ONLY_SERVICE && (rr->AuthFlags & AuthFlagsWakeOnly) &&
6230                 rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) ||
6231             (serviceType == AC_ONLY_SERVICE && !mDNS_KeepaliveRecord(&rr->resrec)))
6232         {
6233             rr->ImmedAnswer = mDNSInterfaceMark;
6234             *servicePresent = mDNStrue;
6235         }
6236     }
6237 }
6238 #endif
6239 
6240 #ifdef APPLE_OSX_mDNSResponder
6241 // This function is used only in the case of local NIC proxy. For external
6242 // sleep proxy server, we do this in SPSInitRecordsBeforeUpdate when we
6243 // walk the resource records.
6244 mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
6245 {
6246     return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE);
6247 }
6248 #endif // APPLE_OSx_mDNSResponder
6249 
6250 #ifdef APPLE_OSX_mDNSResponder
6251 mDNSlocal void SendGoodbyesForACOnlyServices(mDNS *const m, mDNSBool *acOnlyService)
6252 {
6253     return SendGoodbyesForSelectServices(m, acOnlyService, AC_ONLY_SERVICE);
6254 }
6255 #endif
6256 
6257 mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
6258 {
6259     AuthRecord *rr;
6260     m->SleepState = SleepState_Sleeping;
6261 
6262     // If AllInterfaces is not set, the caller has already marked it appropriately
6263     // on which interfaces this should be sent.
6264     if (AllInterfaces)
6265     {
6266         NetworkInterfaceInfo *intf;
6267         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6268         {
6269             intf->SendGoodbyes = 1;
6270         }
6271     }
6272     if (unicast)
6273     {
6274 #ifndef UNICAST_DISABLED
6275         SleepRecordRegistrations(m);    // If we have no SPS, need to deregister our uDNS records
6276 #endif /* UNICAST_DISABLED */
6277     }
6278 
6279     // Mark all the records we need to deregister and send them
6280     for (rr = m->ResourceRecords; rr; rr=rr->next)
6281         if (rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
6282             rr->ImmedAnswer = mDNSInterfaceMark;
6283     SendResponses(m);
6284 }
6285 
6286 /*
6287  * This function attempts to detect if multiple interfaces are on the same subnet.
6288  * It makes this determination based only on the IPv4 Addresses and subnet masks.
6289  * IPv6 link local addresses that are configured by default on all interfaces make
6290  * it hard to make this determination
6291  *
6292  * The 'real' fix for this would be to send out multicast packets over one interface
6293  * and conclude that multiple interfaces are on the same subnet only if these packets
6294  * are seen on other interfaces on the same system
6295  */
6296 mDNSlocal mDNSBool skipSameSubnetRegistration(mDNS *const m, mDNSInterfaceID *regID, mDNSu32 count, mDNSInterfaceID intfid)
6297 {
6298     NetworkInterfaceInfo *intf;
6299     NetworkInterfaceInfo *newIntf;
6300     mDNSu32 i;
6301 
6302     for (newIntf = FirstInterfaceForID(m, intfid); newIntf; newIntf = newIntf->next)
6303     {
6304         if ((newIntf->InterfaceID != intfid) ||
6305             (newIntf->ip.type     != mDNSAddrType_IPv4))
6306         {
6307             continue;
6308         }
6309         for ( i = 0; i < count; i++)
6310         {
6311             for (intf = FirstInterfaceForID(m, regID[i]); intf; intf = intf->next)
6312             {
6313                 if ((intf->InterfaceID != regID[i]) ||
6314                     (intf->ip.type     != mDNSAddrType_IPv4))
6315                 {
6316                     continue;
6317                 }
6318                 if ((intf->ip.ip.v4.NotAnInteger & intf->mask.ip.v4.NotAnInteger) == (newIntf->ip.ip.v4.NotAnInteger & newIntf->mask.ip.v4.NotAnInteger))
6319                 {
6320                     LogSPS("%s : Already registered for the same subnet (IPv4) for interface %s", __func__, intf->ifname);
6321                     return (mDNStrue);
6322                 }
6323             }
6324         }
6325     }
6326     return (mDNSfalse);
6327 }
6328 
6329 mDNSlocal void DoKeepaliveCallbacks(mDNS *m)
6330 {
6331     // Loop through the keepalive records and callback with an error
6332     m->CurrentRecord = m->ResourceRecords;
6333     while (m->CurrentRecord)
6334     {
6335         AuthRecord *const rr = m->CurrentRecord;
6336         if ((mDNS_KeepaliveRecord(&rr->resrec)) && (rr->resrec.RecordType != kDNSRecordTypeDeregistering))
6337         {
6338             LogSPS("DoKeepaliveCallbacks: Invoking the callback for %s", ARDisplayString(m, rr));
6339             if (rr->RecordCallback)
6340                 rr->RecordCallback(m, rr, mStatus_BadStateErr);
6341         }
6342         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
6343             m->CurrentRecord = rr->next;
6344     }
6345 }
6346 
6347 // BeginSleepProcessing is called, with the lock held, from either mDNS_Execute or mDNSCoreMachineSleep
6348 mDNSlocal void BeginSleepProcessing(mDNS *const m)
6349 {
6350     mDNSBool SendGoodbyes = mDNStrue;
6351     mDNSBool WakeOnlyService  = mDNSfalse;
6352     mDNSBool ACOnlyService  = mDNSfalse;
6353     mDNSBool invokeKACallback = mDNStrue;
6354     const CacheRecord *sps[3] = { mDNSNULL };
6355     mDNSOpaque64 updateIntID = zeroOpaque64;
6356     mDNSInterfaceID registeredIntfIDS[128];
6357     mDNSu32 registeredCount = 0;
6358     int skippedRegistrations = 0;
6359 
6360     m->NextScheduledSPRetry = m->timenow;
6361 
6362     if      (!m->SystemWakeOnLANEnabled) LogSPS("BeginSleepProcessing: m->SystemWakeOnLANEnabled is false");
6363     else if (!mDNSCoreHaveAdvertisedMulticastServices(m)) LogSPS("BeginSleepProcessing: No advertised services");
6364     else    // If we have at least one advertised service
6365     {
6366         NetworkInterfaceInfo *intf;
6367 
6368         // Clear out the SCDynamic entry that stores the external SPS information
6369         mDNSPlatformClearSPSMACAddr();
6370 
6371         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6372         {
6373             // Intialize it to false. These values make sense only when SleepState is set to Sleeping.
6374             intf->SendGoodbyes = 0;
6375 
6376             // If it is not multicast capable, we could not have possibly discovered sleep proxy
6377             // servers.
6378             if (!intf->McastTxRx || mDNSPlatformInterfaceIsD2D(intf->InterfaceID))
6379             {
6380                 LogSPS("BeginSleepProcessing: %-6s Ignoring for registrations", intf->ifname);
6381                 continue;
6382             }
6383 
6384             // If we are not capable of WOMP, then don't register with sleep proxy.
6385             //
6386             // Note: If we are not NetWake capable, we don't browse for the sleep proxy server.
6387             // We might find sleep proxy servers in the cache and start a resolve on them.
6388             // But then if the interface goes away, we won't stop these questions because
6389             // mDNS_DeactivateNetWake_internal assumes that a browse has been started for it
6390             // to stop both the browse and resolve questions.
6391             if (!intf->NetWake)
6392             {
6393                 LogSPS("BeginSleepProcessing: %-6s not capable of magic packet wakeup", intf->ifname);
6394                 intf->SendGoodbyes = 1;
6395                 skippedRegistrations++;
6396                 continue;
6397             }
6398 
6399             // Check if we have already registered with a sleep proxy for this subnet
6400             if (skipSameSubnetRegistration(m, registeredIntfIDS, registeredCount, intf->InterfaceID))
6401             {
6402                 LogSPS("%s : Skipping sleep proxy registration on %s", __func__, intf->ifname);
6403                 continue;
6404             }
6405 
6406 #if APPLE_OSX_mDNSResponder
6407             else if (SupportsInNICProxy(intf))
6408             {
6409                 mDNSBool keepaliveOnly = mDNSfalse;
6410                 if (ActivateLocalProxy(m, intf, &keepaliveOnly) == mStatus_NoError)
6411                 {
6412                     SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
6413                     if (keepaliveOnly)
6414                         SendGoodbyesForACOnlyServices(m, &ACOnlyService);
6415                     SendGoodbyes = mDNSfalse;
6416                     invokeKACallback  = mDNSfalse;
6417                     LogSPS("BeginSleepProcessing: %-6s using local proxy", intf->ifname);
6418                     // This will leave m->SleepState set to SleepState_Transferring,
6419                     // which is okay because with no outstanding resolves, or updates in flight,
6420                     // mDNSCoreReadyForSleep() will conclude correctly that all the updates have already completed
6421 
6422                     registeredIntfIDS[registeredCount] = intf->InterfaceID;
6423                     registeredCount++;
6424                 }
6425             }
6426 #endif // APPLE_OSX_mDNSResponder
6427             else
6428             {
6429 #if APPLE_OSX_mDNSResponder
6430                 // If on battery, do not attempt to offload to external sleep proxies
6431                 if (m->SystemWakeOnLANEnabled == mDNS_WakeOnBattery)
6432                 {
6433                     LogSPS("BegingSleepProcessing: Not connected to AC power - Not registering with an external sleep proxy.");
6434                     return;
6435                 }
6436 #endif // APPLE_OSX_mDNSResponder
6437                 FindSPSInCache(m, &intf->NetWakeBrowse, sps);
6438                 if (!sps[0]) LogSPS("BeginSleepProcessing: %-6s %#a No Sleep Proxy Server found (Next Browse Q in %d, interval %d)",
6439                                     intf->ifname, &intf->ip, NextQSendTime(&intf->NetWakeBrowse) - m->timenow, intf->NetWakeBrowse.ThisQInterval);
6440                 else
6441                 {
6442                     int i;
6443                     mDNSu32 scopeid;
6444                     SendGoodbyes = mDNSfalse;
6445                     intf->NextSPSAttempt = 0;
6446                     intf->NextSPSAttemptTime = m->timenow + mDNSPlatformOneSecond;
6447 
6448                     scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, intf->InterfaceID, mDNStrue);
6449                     // Now we know for sure that we have to wait for registration to complete on this interface.
6450                     if (scopeid < (sizeof(updateIntID) * mDNSNBBY))
6451                         bit_set_opaque64(updateIntID, scopeid);
6452 
6453                     // Don't need to set m->NextScheduledSPRetry here because we already set "m->NextScheduledSPRetry = m->timenow" above
6454                     for (i=0; i<3; i++)
6455                     {
6456 #if ForceAlerts
6457                         if (intf->SPSAddr[i].type)
6458                             LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type);
6459                         if (intf->NetWakeResolve[i].ThisQInterval >= 0)
6460                             LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval);
6461 #endif
6462                         intf->SPSAddr[i].type = mDNSAddrType_None;
6463                         if (intf->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery(m, &intf->NetWakeResolve[i]);
6464                         intf->NetWakeResolve[i].ThisQInterval = -1;
6465                         if (sps[i])
6466                         {
6467                             LogSPS("BeginSleepProcessing: %-6s Found Sleep Proxy Server %d TTL %d %s", intf->ifname, i, sps[i]->resrec.rroriginalttl, CRDisplayString(m, sps[i]));
6468                             mDNS_SetupQuestion(&intf->NetWakeResolve[i], intf->InterfaceID, &sps[i]->resrec.rdata->u.name, kDNSType_SRV, NetWakeResolve, intf);
6469                             intf->NetWakeResolve[i].ReturnIntermed = mDNStrue;
6470                             mDNS_StartQuery_internal(m, &intf->NetWakeResolve[i]);
6471 
6472                             // If we are registering with a Sleep Proxy for a new subnet, add it to our list
6473                             registeredIntfIDS[registeredCount] = intf->InterfaceID;
6474                             registeredCount++;
6475                         }
6476                     }
6477                 }
6478             }
6479         }
6480     }
6481 
6482     // If we have at least one interface on which we are registering with an external sleep proxy,
6483     // initialize all the records appropriately.
6484     if (!mDNSOpaque64IsZero(&updateIntID))
6485         SPSInitRecordsBeforeUpdate(m, updateIntID, &WakeOnlyService);
6486 
6487     // Call the applicaitons that registered a keepalive record to inform them that we failed to offload
6488     // the records to a sleep proxy.
6489     if (invokeKACallback)
6490     {
6491         LogSPS("BeginSleepProcessing: Did not register with an in-NIC proxy - invoking the callbacks for KA records");
6492         DoKeepaliveCallbacks(m);
6493     }
6494 
6495     // SendSleepGoodbyes last two arguments control whether we send goodbyes on all
6496     // interfaces and also deregister unicast registrations.
6497     //
6498     // - If there are no sleep proxy servers, then send goodbyes on all interfaces
6499     //   for both multicast and unicast.
6500     //
6501     // - If we skipped registrations on some interfaces, then we have already marked
6502     //   them appropriately above. We don't need to send goodbyes for unicast as
6503     //   we have registered with at least one sleep proxy.
6504     //
6505     // - If we are not planning to send any goodbyes, then check for WakeOnlyServices.
6506     //
6507     // Note: If we are planning to send goodbyes, we mark the record with mDNSInterfaceAny
6508     // and call SendResponses which inturn calls ShouldSendGoodbyesBeforeSleep which looks
6509     // at WakeOnlyServices first.
6510     if (SendGoodbyes)
6511     {
6512         LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server");
6513         SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6514     }
6515     else if (skippedRegistrations)
6516     {
6517         LogSPS("BeginSleepProcessing: Not registering with Sleep Proxy Server on all interfaces");
6518         SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
6519     }
6520     else if (WakeOnlyService || ACOnlyService)
6521     {
6522         // If we saw WakeOnly service above, send the goodbyes now.
6523         LogSPS("BeginSleepProcessing: Sending goodbyes for %s", WakeOnlyService? "WakeOnlyService" : "AC Only Service");
6524         SendResponses(m);
6525     }
6526 }
6527 
6528 // Call mDNSCoreMachineSleep(m, mDNStrue) when the machine is about to go to sleep.
6529 // Call mDNSCoreMachineSleep(m, mDNSfalse) when the machine is has just woken up.
6530 // Normally, the platform support layer below mDNSCore should call this, not the client layer above.
6531 mDNSexport void mDNSCoreMachineSleep(mDNS *const m, mDNSBool sleep)
6532 {
6533     AuthRecord *rr;
6534 
6535     LogSPS("%s (old state %d) at %ld", sleep ? "Sleeping" : "Waking", m->SleepState, m->timenow);
6536 
6537     if (sleep && !m->SleepState)        // Going to sleep
6538     {
6539         mDNS_Lock(m);
6540         // If we're going to sleep, need to stop advertising that we're a Sleep Proxy Server
6541         if (m->SPSSocket)
6542         {
6543             mDNSu8 oldstate = m->SPSState;
6544             mDNS_DropLockBeforeCallback();      // mDNS_DeregisterService expects to be called without the lock held, so we emulate that here
6545             m->SPSState = 2;
6546 #ifndef SPC_DISABLED
6547             if (oldstate == 1) mDNS_DeregisterService(m, &m->SPSRecords);
6548 #else
6549 			(void)oldstate;
6550 #endif
6551             mDNS_ReclaimLockAfterCallback();
6552         }
6553 
6554         m->SleepState = SleepState_Transferring;
6555         if (m->SystemWakeOnLANEnabled && m->DelaySleep)
6556         {
6557             // If we just woke up moments ago, allow ten seconds for networking to stabilize before going back to sleep
6558             LogSPS("mDNSCoreMachineSleep: Re-sleeping immediately after waking; will delay for %d ticks", m->DelaySleep - m->timenow);
6559             m->SleepLimit = NonZeroTime(m->DelaySleep + mDNSPlatformOneSecond * 10);
6560         }
6561         else
6562         {
6563             m->DelaySleep = 0;
6564             m->SleepLimit = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 10);
6565             m->mDNSStats.Sleeps++;
6566             BeginSleepProcessing(m);
6567         }
6568 
6569 #ifndef UNICAST_DISABLED
6570         SuspendLLQs(m);
6571 #endif
6572 #if APPLE_OSX_mDNSResponder
6573         RemoveAutoTunnel6Record(m);
6574 #endif
6575         LogSPS("mDNSCoreMachineSleep: m->SleepState %d (%s) seq %d", m->SleepState,
6576                m->SleepState == SleepState_Transferring ? "Transferring" :
6577                m->SleepState == SleepState_Sleeping     ? "Sleeping"     : "?", m->SleepSeqNum);
6578         mDNS_Unlock(m);
6579     }
6580     else if (!sleep)        // Waking up
6581     {
6582         mDNSu32 slot;
6583         CacheGroup *cg;
6584         CacheRecord *cr;
6585         NetworkInterfaceInfo *intf;
6586         mDNSs32 currtime, diff;
6587 
6588         mDNS_Lock(m);
6589         // Reset SleepLimit back to 0 now that we're awake again.
6590         m->SleepLimit = 0;
6591 
6592         // If we were previously sleeping, but now we're not, increment m->SleepSeqNum to indicate that we're entering a new period of wakefulness
6593         if (m->SleepState != SleepState_Awake)
6594         {
6595             m->SleepState = SleepState_Awake;
6596             m->SleepSeqNum++;
6597 			m->DelaySleep = 0;
6598         }
6599 
6600         if (m->SPSState == 3)
6601         {
6602             m->SPSState = 0;
6603             mDNSCoreBeSleepProxyServer_internal(m, m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags);
6604         }
6605         m->mDNSStats.Wakes++;
6606 
6607         // ... and the same for NextSPSAttempt
6608         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next)) intf->NextSPSAttempt = -1;
6609 
6610         // Restart unicast and multicast queries
6611         mDNSCoreRestartQueries(m);
6612 
6613         // and reactivtate service registrations
6614         m->NextSRVUpdate = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
6615         LogInfo("mDNSCoreMachineSleep waking: NextSRVUpdate in %d %d", m->NextSRVUpdate - m->timenow, m->timenow);
6616 
6617         // 2. Re-validate our cache records
6618         currtime = mDNSPlatformUTC();
6619 
6620 #if APPLE_OSX_mDNSResponder
6621         // start time of this statistics gathering interval
6622         m->StatStartTime = currtime;
6623 #endif // APPLE_OSX_mDNSResponder
6624 
6625         diff = currtime - m->TimeSlept;
6626         FORALL_CACHERECORDS(slot, cg, cr)
6627         {
6628             // Temporary fix: For unicast cache records, look at how much time we slept.
6629             // Adjust the RecvTime by the amount of time we slept so that we age the
6630             // cache record appropriately. If it is expired already, purge. If there
6631             // is a network change that happens after the wakeup, we might purge the
6632             // cache anyways and this helps only in the case where there are no network
6633             // changes across sleep/wakeup transition.
6634             //
6635             // Note: If there is a network/DNS server change that already happened and
6636             // these cache entries are already refreshed and we are getting a delayed
6637             // wake up notification, we might adjust the TimeRcvd based on the time slept
6638             // now which can cause the cache to purge pre-maturely. As this is not a very
6639             // common case, this should happen rarely.
6640             if (!cr->resrec.InterfaceID)
6641             {
6642                 if (diff > 0)
6643                 {
6644                     mDNSu32 uTTL = RRUnadjustedTTL(cr->resrec.rroriginalttl);
6645                     const mDNSs32 remain = uTTL - (m->timenow - cr->TimeRcvd) / mDNSPlatformOneSecond;
6646 
6647                     // -if we have slept longer than the remaining TTL, purge and start fresh.
6648                     // -if we have been sleeping for a long time, we could reduce TimeRcvd below by
6649                     //  a sufficiently big value which could cause the value to go into the future
6650                     //  because of the signed comparison of time. For this to happen, we should have been
6651                     //  sleeping really long (~24 days). For now, we want to be conservative and flush even
6652                     //  if we have slept for more than two days.
6653 
6654                     if (diff >= remain || diff > (2 * 24 * 3600))
6655                     {
6656                         LogInfo("mDNSCoreMachineSleep: %s: Purging cache entry SleptTime %d, Remaining TTL %d",
6657                             CRDisplayString(m, cr), diff, remain);
6658                         mDNS_PurgeCacheResourceRecord(m, cr);
6659                         continue;
6660                     }
6661                     cr->TimeRcvd -= (diff * mDNSPlatformOneSecond);
6662                     if (m->timenow - (cr->TimeRcvd + ((mDNSs32)uTTL * mDNSPlatformOneSecond)) >= 0)
6663                     {
6664                         LogInfo("mDNSCoreMachineSleep: %s: Purging after adjusting the remaining TTL %d by %d seconds",
6665                             CRDisplayString(m, cr), remain, diff);
6666                         mDNS_PurgeCacheResourceRecord(m, cr);
6667                     }
6668                     else
6669                     {
6670                         LogInfo("mDNSCoreMachineSleep: %s: Adjusted the remain ttl %u by %d seconds", CRDisplayString(m, cr), remain, diff);
6671                     }
6672                 }
6673             }
6674             else
6675             {
6676                 mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForWake);
6677             }
6678         }
6679 
6680         // 3. Retrigger probing and announcing for all our authoritative records
6681         for (rr = m->ResourceRecords; rr; rr=rr->next)
6682         {
6683             if (AuthRecord_uDNS(rr))
6684             {
6685                 ActivateUnicastRegistration(m, rr);
6686             }
6687             else
6688             {
6689                 mDNSCoreRestartRegistration(m, rr, -1);
6690             }
6691         }
6692 
6693         // 4. Refresh NAT mappings
6694         // We don't want to have to assume that all hardware can necessarily keep accurate
6695         // track of passage of time while asleep, so on wake we refresh our NAT mappings.
6696         // We typically wake up with no interfaces active, so there's no need to rush to try to find our external address.
6697         // But if we do get a network configuration change, mDNSMacOSXNetworkChanged will call uDNS_SetupDNSConfig, which
6698         // will call mDNS_SetPrimaryInterfaceInfo, which will call RecreateNATMappings to refresh them, potentially sooner
6699         // than five seconds from now.
6700         LogInfo("mDNSCoreMachineSleep: recreating NAT mappings in 5 seconds");
6701         RecreateNATMappings(m, mDNSPlatformOneSecond * 5);
6702         mDNS_Unlock(m);
6703     }
6704 }
6705 
6706 mDNSexport mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now)
6707 {
6708     DNSQuestion *q;
6709     AuthRecord *rr;
6710     NetworkInterfaceInfo *intf;
6711 
6712     mDNS_Lock(m);
6713 
6714     if (m->DelaySleep) goto notready;
6715 
6716     // If we've not hit the sleep limit time, and it's not time for our next retry, we can skip these checks
6717     if (m->SleepLimit - now > 0 && m->NextScheduledSPRetry - now > 0) goto notready;
6718 
6719     m->NextScheduledSPRetry = now + 0x40000000UL;
6720 
6721     // See if we might need to retransmit any lost Sleep Proxy Registrations
6722     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6723         if (intf->NextSPSAttempt >= 0)
6724         {
6725             if (now - intf->NextSPSAttemptTime >= 0)
6726             {
6727                 LogSPS("mDNSCoreReadyForSleep: retrying for %s SPS %d try %d",
6728                        intf->ifname, intf->NextSPSAttempt/3, intf->NextSPSAttempt);
6729                 SendSPSRegistration(m, intf, zeroID);
6730                 // Don't need to "goto notready" here, because if we do still have record registrations
6731                 // that have not been acknowledged yet, we'll catch that in the record list scan below.
6732             }
6733             else
6734             if (m->NextScheduledSPRetry - intf->NextSPSAttemptTime > 0)
6735                 m->NextScheduledSPRetry = intf->NextSPSAttemptTime;
6736         }
6737 
6738     // Scan list of interfaces, and see if we're still waiting for any sleep proxy resolves to complete
6739     for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6740     {
6741         int sps = (intf->NextSPSAttempt == 0) ? 0 : (intf->NextSPSAttempt-1)/3;
6742         if (intf->NetWakeResolve[sps].ThisQInterval >= 0)
6743         {
6744             LogSPS("mDNSCoreReadyForSleep: waiting for SPS Resolve %s %##s (%s)",
6745                    intf->ifname, intf->NetWakeResolve[sps].qname.c, DNSTypeName(intf->NetWakeResolve[sps].qtype));
6746             goto spsnotready;
6747         }
6748     }
6749 
6750     // Scan list of registered records
6751     for (rr = m->ResourceRecords; rr; rr = rr->next)
6752         if (!AuthRecord_uDNS(rr))
6753             if (!mDNSOpaque64IsZero(&rr->updateIntID))
6754             { 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; }
6755 
6756     // Scan list of private LLQs, and make sure they've all completed their handshake with the server
6757     for (q = m->Questions; q; q = q->next)
6758         if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived && q->ReqLease == 0 && q->tcp)
6759         {
6760             LogSPS("mDNSCoreReadyForSleep: waiting for LLQ %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
6761             goto notready;
6762         }
6763 
6764     // Scan list of registered records
6765     for (rr = m->ResourceRecords; rr; rr = rr->next)
6766         if (AuthRecord_uDNS(rr))
6767         {
6768             if (rr->state == regState_Refresh && rr->tcp)
6769             { 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; }
6770             #if APPLE_OSX_mDNSResponder
6771             if (!RecordReadyForSleep(m, rr)) { LogSPS("mDNSCoreReadyForSleep: waiting for %s", ARDisplayString(m, rr)); goto notready; }
6772             #endif
6773         }
6774 
6775     mDNS_Unlock(m);
6776     return mDNStrue;
6777 
6778 spsnotready:
6779 
6780     // If we failed to complete sleep proxy registration within ten seconds, we give up on that
6781     // and allow up to ten seconds more to complete wide-area deregistration instead
6782     if (now - m->SleepLimit >= 0)
6783     {
6784         LogMsg("Failed to register with SPS, now sending goodbyes");
6785 
6786         for (intf = GetFirstActiveInterface(m->HostInterfaces); intf; intf = GetFirstActiveInterface(intf->next))
6787             if (intf->NetWakeBrowse.ThisQInterval >= 0)
6788             {
6789                 LogSPS("ReadyForSleep mDNS_DeactivateNetWake %s %##s (%s)",
6790                        intf->ifname, intf->NetWakeResolve[0].qname.c, DNSTypeName(intf->NetWakeResolve[0].qtype));
6791                 mDNS_DeactivateNetWake_internal(m, intf);
6792             }
6793 
6794         for (rr = m->ResourceRecords; rr; rr = rr->next)
6795             if (!AuthRecord_uDNS(rr))
6796                 if (!mDNSOpaque64IsZero(&rr->updateIntID))
6797                 {
6798                     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));
6799                     rr->updateIntID = zeroOpaque64;
6800                 }
6801 
6802         // We'd really like to allow up to ten seconds more here,
6803         // but if we don't respond to the sleep notification within 30 seconds
6804         // we'll be put back to sleep forcibly without the chance to schedule the next maintenance wake.
6805         // Right now we wait 16 sec after wake for all the interfaces to come up, then we wait up to 10 seconds
6806         // more for SPS resolves and record registrations to complete, which puts us at 26 seconds.
6807         // If we allow just one more second to send our goodbyes, that puts us at 27 seconds.
6808         m->SleepLimit = now + mDNSPlatformOneSecond * 1;
6809 
6810         SendSleepGoodbyes(m, mDNStrue, mDNStrue);
6811     }
6812 
6813 notready:
6814     mDNS_Unlock(m);
6815     return mDNSfalse;
6816 }
6817 
6818 mDNSexport mDNSs32 mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now)
6819 {
6820     AuthRecord *ar;
6821 
6822     // Even when we have no wake-on-LAN-capable interfaces, or we failed to find a sleep proxy, or we have other
6823     // failure scenarios, we still want to wake up in at most 120 minutes, to see if the network environment has changed.
6824     // E.g. we might wake up and find no wireless network because the base station got rebooted just at that moment,
6825     // and if that happens we don't want to just give up and go back to sleep and never try again.
6826     mDNSs32 e = now + (120 * 60 * mDNSPlatformOneSecond);       // Sleep for at most 120 minutes
6827 
6828     NATTraversalInfo *nat;
6829     for (nat = m->NATTraversals; nat; nat=nat->next)
6830         if (nat->Protocol && nat->ExpiryTime && nat->ExpiryTime - now > mDNSPlatformOneSecond*4)
6831         {
6832             mDNSs32 t = nat->ExpiryTime - (nat->ExpiryTime - now) / 10;     // Wake up when 90% of the way to the expiry time
6833             if (e - t > 0) e = t;
6834             LogSPS("ComputeWakeTime: %p %s Int %5d Ext %5d Err %d Retry %5d Interval %5d Expire %5d Wake %5d",
6835                    nat, nat->Protocol == NATOp_MapTCP ? "TCP" : "UDP",
6836                    mDNSVal16(nat->IntPort), mDNSVal16(nat->ExternalPort), nat->Result,
6837                    nat->retryPortMap ? (nat->retryPortMap - now) / mDNSPlatformOneSecond : 0,
6838                    nat->retryInterval / mDNSPlatformOneSecond,
6839                    nat->ExpiryTime ? (nat->ExpiryTime - now) / mDNSPlatformOneSecond : 0,
6840                    (t - now) / mDNSPlatformOneSecond);
6841         }
6842 
6843     // This loop checks both the time we need to renew wide-area registrations,
6844     // and the time we need to renew Sleep Proxy registrations
6845     for (ar = m->ResourceRecords; ar; ar = ar->next)
6846         if (ar->expire && ar->expire - now > mDNSPlatformOneSecond*4)
6847         {
6848             mDNSs32 t = ar->expire - (ar->expire - now) / 10;       // Wake up when 90% of the way to the expiry time
6849             if (e - t > 0) e = t;
6850             LogSPS("ComputeWakeTime: %p Int %7d Next %7d Expire %7d Wake %7d %s",
6851                    ar, ar->ThisAPInterval / mDNSPlatformOneSecond,
6852                    (ar->LastAPTime + ar->ThisAPInterval - now) / mDNSPlatformOneSecond,
6853                    ar->expire ? (ar->expire - now) / mDNSPlatformOneSecond : 0,
6854                    (t - now) / mDNSPlatformOneSecond, ARDisplayString(m, ar));
6855         }
6856 
6857     return(e - now);
6858 }
6859 
6860 // ***************************************************************************
6861 #if COMPILER_LIKES_PRAGMA_MARK
6862 #pragma mark -
6863 #pragma mark - Packet Reception Functions
6864 #endif
6865 
6866 #define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
6867 
6868 mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
6869                                           const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, DNSMessage *const response, AuthRecord *ResponseRecords)
6870 {
6871     mDNSu8          *responseptr     = response->data;
6872     const mDNSu8    *const limit     = response->data + sizeof(response->data);
6873     const mDNSu8    *ptr             = query->data;
6874     AuthRecord  *rr;
6875     mDNSu32 maxttl = 0x70000000;
6876     int i;
6877 
6878     // Initialize the response fields so we can answer the questions
6879     InitializeDNSMessage(&response->h, query->h.id, ResponseFlags);
6880 
6881     // ***
6882     // *** 1. Write out the list of questions we are actually going to answer with this packet
6883     // ***
6884     if (LegacyQuery)
6885     {
6886         maxttl = kStaticCacheTTL;
6887         for (i=0; i<query->h.numQuestions; i++)                     // For each question...
6888         {
6889             DNSQuestion q;
6890             ptr = getQuestion(query, ptr, end, InterfaceID, &q);    // get the question...
6891             if (!ptr) return(mDNSNULL);
6892 
6893             for (rr=ResponseRecords; rr; rr=rr->NextResponse)       // and search our list of proposed answers
6894             {
6895                 if (rr->NR_AnswerTo == ptr)                         // If we're going to generate a record answering this question
6896                 {                                                   // then put the question in the question section
6897                     responseptr = putQuestion(response, responseptr, limit, &q.qname, q.qtype, q.qclass);
6898                     if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
6899                     break;      // break out of the ResponseRecords loop, and go on to the next question
6900                 }
6901             }
6902         }
6903 
6904         if (response->h.numQuestions == 0) { LogMsg("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
6905     }
6906 
6907     // ***
6908     // *** 2. Write Answers
6909     // ***
6910     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6911         if (rr->NR_AnswerTo)
6912         {
6913             mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAnswers, &rr->resrec,
6914                                              maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
6915             if (p) responseptr = p;
6916             else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); response->h.flags.b[0] |= kDNSFlag0_TC; }
6917         }
6918 
6919     // ***
6920     // *** 3. Write Additionals
6921     // ***
6922     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
6923         if (rr->NR_AdditionalTo && !rr->NR_AnswerTo)
6924         {
6925             mDNSu8 *p = PutResourceRecordTTL(response, responseptr, &response->h.numAdditionals, &rr->resrec,
6926                                              maxttl < rr->resrec.rroriginalttl ? maxttl : rr->resrec.rroriginalttl);
6927             if (p) responseptr = p;
6928             else debugf("GenerateUnicastResponse: No more space for additionals");
6929         }
6930 
6931     return(responseptr);
6932 }
6933 
6934 // AuthRecord *our is our Resource Record
6935 // CacheRecord *pkt is the Resource Record from the response packet we've witnessed on the network
6936 // Returns 0 if there is no conflict
6937 // Returns +1 if there was a conflict and we won
6938 // Returns -1 if there was a conflict and we lost and have to rename
6939 mDNSlocal int CompareRData(const AuthRecord *const our, const CacheRecord *const pkt)
6940 {
6941     mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
6942     mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
6943     if (!our) { LogMsg("CompareRData ERROR: our is NULL"); return(+1); }
6944     if (!pkt) { LogMsg("CompareRData ERROR: pkt is NULL"); return(+1); }
6945 
6946     ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), &our->resrec);
6947     pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), &pkt->resrec);
6948     while (ourptr < ourend && pktptr < pktend && *ourptr == *pktptr) { ourptr++; pktptr++; }
6949     if (ourptr >= ourend && pktptr >= pktend) return(0);            // If data identical, not a conflict
6950 
6951     if (ourptr >= ourend) return(-1);                               // Our data ran out first; We lost
6952     if (pktptr >= pktend) return(+1);                               // Packet data ran out first; We won
6953     if (*pktptr > *ourptr) return(-1);                              // Our data is numerically lower; We lost
6954     if (*pktptr < *ourptr) return(+1);                              // Packet data is numerically lower; We won
6955 
6956     LogMsg("CompareRData ERROR: Invalid state");
6957     return(-1);
6958 }
6959 
6960 // See if we have an authoritative record that's identical to this packet record,
6961 // whose canonical DependentOn record is the specified master record.
6962 // The DependentOn pointer is typically used for the TXT record of service registrations
6963 // It indicates that there is no inherent conflict detection for the TXT record
6964 // -- it depends on the SRV record to resolve name conflicts
6965 // If we find any identical ResourceRecords in our authoritative list, then follow their DependentOn
6966 // pointer chain (if any) to make sure we reach the canonical DependentOn record
6967 // If the record has no DependentOn, then just return that record's pointer
6968 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
6969 mDNSlocal mDNSBool MatchDependentOn(const mDNS *const m, const CacheRecord *const pktrr, const AuthRecord *const master)
6970 {
6971     const AuthRecord *r1;
6972     for (r1 = m->ResourceRecords; r1; r1=r1->next)
6973     {
6974         if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
6975         {
6976             const AuthRecord *r2 = r1;
6977             while (r2->DependentOn) r2 = r2->DependentOn;
6978             if (r2 == master) return(mDNStrue);
6979         }
6980     }
6981     for (r1 = m->DuplicateRecords; r1; r1=r1->next)
6982     {
6983         if (IdenticalResourceRecord(&r1->resrec, &pktrr->resrec))
6984         {
6985             const AuthRecord *r2 = r1;
6986             while (r2->DependentOn) r2 = r2->DependentOn;
6987             if (r2 == master) return(mDNStrue);
6988         }
6989     }
6990     return(mDNSfalse);
6991 }
6992 
6993 // Find the canonical RRSet pointer for this RR received in a packet.
6994 // If we find any identical AuthRecord in our authoritative list, then follow its RRSet
6995 // pointers (if any) to make sure we return the canonical member of this name/type/class
6996 // Returns NULL if we don't have any local RRs that are identical to the one from the packet
6997 mDNSlocal const AuthRecord *FindRRSet(const mDNS *const m, const CacheRecord *const pktrr)
6998 {
6999     const AuthRecord *rr;
7000     for (rr = m->ResourceRecords; rr; rr=rr->next)
7001     {
7002         if (IdenticalResourceRecord(&rr->resrec, &pktrr->resrec))
7003         {
7004             while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
7005             return(rr);
7006         }
7007     }
7008     return(mDNSNULL);
7009 }
7010 
7011 // PacketRRConflict is called when we've received an RR (pktrr) which has the same name
7012 // as one of our records (our) but different rdata.
7013 // 1. If our record is not a type that's supposed to be unique, we don't care.
7014 // 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
7015 // 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
7016 //     points to our record, ignore this conflict (e.g. the packet record matches one of our
7017 //     TXT records, and that record is marked as dependent on 'our', its SRV record).
7018 // 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
7019 //    are members of the same RRSet, then this is not a conflict.
7020 mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const AuthRecord *const our, const CacheRecord *const pktrr)
7021 {
7022     // If not supposed to be unique, not a conflict
7023     if (!(our->resrec.RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
7024 
7025     // If a dependent record, not a conflict
7026     if (our->DependentOn || MatchDependentOn(m, pktrr, our)) return(mDNSfalse);
7027     else
7028     {
7029         // If the pktrr matches a member of ourset, not a conflict
7030         const AuthRecord *ourset = our->RRSet ? our->RRSet : our;
7031         const AuthRecord *pktset = FindRRSet(m, pktrr);
7032         if (pktset == ourset) return(mDNSfalse);
7033 
7034         // For records we're proxying, where we don't know the full
7035         // relationship between the records, having any matching record
7036         // in our AuthRecords list is sufficient evidence of non-conflict
7037         if (our->WakeUp.HMAC.l[0] && pktset) return(mDNSfalse);
7038     }
7039 
7040     // Okay, this is a conflict
7041     return(mDNStrue);
7042 }
7043 
7044 // Note: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
7045 // the record list and/or question list.
7046 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
7047 mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7048                                         DNSQuestion *q, AuthRecord *our)
7049 {
7050     int i;
7051     const mDNSu8 *ptr = LocateAuthorities(query, end);
7052     mDNSBool FoundUpdate = mDNSfalse;
7053 
7054     for (i = 0; i < query->h.numAuthorities; i++)
7055     {
7056         ptr = GetLargeResourceRecord(m, query, ptr, end, q->InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
7057         if (!ptr) break;
7058         if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
7059         {
7060             FoundUpdate = mDNStrue;
7061             if (PacketRRConflict(m, our, &m->rec.r))
7062             {
7063                 int result          = (int)our->resrec.rrclass - (int)m->rec.r.resrec.rrclass;
7064                 if (!result) result = (int)our->resrec.rrtype  - (int)m->rec.r.resrec.rrtype;
7065                 if (!result) result = CompareRData(our, &m->rec.r);
7066                 if (result)
7067                 {
7068                     const char *const msg = (result < 0) ? "lost:" : (result > 0) ? "won: " : "tie: ";
7069                     LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7070                     LogMsg("ResolveSimultaneousProbe: %p Our Record %d %s %08lX %s", our->resrec.InterfaceID, our->ProbeCount, msg, our->resrec.rdatahash, ARDisplayString(m, our));
7071                 }
7072                 // 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.
7073                 // Instead we pause for one second, to give the other host (if real) a chance to establish its name, and then try probing again.
7074                 // If there really is another live host out there with the same name, it will answer our probes and we'll then rename.
7075                 if (result < 0)
7076                 {
7077                     m->SuppressProbes   = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
7078                     our->ProbeCount     = DefaultProbeCountForTypeUnique;
7079                     our->AnnounceCount  = InitialAnnounceCount;
7080                     InitializeLastAPTime(m, our);
7081                     goto exit;
7082                 }
7083             }
7084 #if 0
7085             else
7086             {
7087                 LogMsg("ResolveSimultaneousProbe: %p Pkt Record:        %08lX %s", q->InterfaceID, m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
7088                 LogMsg("ResolveSimultaneousProbe: %p Our Record %d ign:  %08lX %s", our->resrec.InterfaceID, our->ProbeCount, our->resrec.rdatahash, ARDisplayString(m, our));
7089             }
7090 #endif
7091         }
7092         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7093     }
7094     if (!FoundUpdate)
7095         LogInfo("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->resrec.name->c, DNSTypeName(our->resrec.rrtype));
7096 exit:
7097     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7098 }
7099 
7100 mDNSlocal CacheRecord *FindIdenticalRecordInCache(const mDNS *const m, const ResourceRecord *const pktrr)
7101 {
7102     mDNSu32 slot = HashSlot(pktrr->name);
7103     CacheGroup *cg = CacheGroupForRecord(m, slot, pktrr);
7104     CacheRecord *rr;
7105     mDNSBool match;
7106     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
7107     {
7108         if (!pktrr->InterfaceID)
7109         {
7110             mDNSu16 id1 = (pktrr->rDNSServer ? pktrr->rDNSServer->resGroupID : 0);
7111             mDNSu16 id2 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
7112             match = (id1 == id2);
7113         }
7114         else match = (pktrr->InterfaceID == rr->resrec.InterfaceID);
7115 
7116         if (match && IdenticalSameNameRecord(pktrr, &rr->resrec)) break;
7117     }
7118     return(rr);
7119 }
7120 mDNSlocal void DeregisterProxyRecord(mDNS *const m, AuthRecord *const rr)
7121 {
7122     rr->WakeUp.HMAC    = zeroEthAddr; // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7123     rr->RequireGoodbye = mDNSfalse;   // and we don't want to send goodbye for it
7124     mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7125     SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7126 }
7127 
7128 mDNSlocal void ClearKeepaliveProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist, const mDNSInterfaceID InterfaceID)
7129 {
7130     if (m->CurrentRecord)
7131         LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7132     m->CurrentRecord = thelist;
7133 
7134     // Normally, the RDATA of the keepalive record will be different each time and hence we always
7135     // clean up the keepalive record.
7136     while (m->CurrentRecord)
7137     {
7138         AuthRecord *const rr = m->CurrentRecord;
7139         if (InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7140         {
7141             if (mDNS_KeepaliveRecord(&m->rec.r.resrec))
7142             {
7143                 LogSPS("ClearKeepaliveProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7144                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7145                 DeregisterProxyRecord(m, rr);
7146             }
7147         }
7148         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7149         // new records could have been added to the end of the list as a result of that call.
7150         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7151             m->CurrentRecord = rr->next;
7152     }
7153 }
7154 
7155 // Called from mDNSCoreReceiveUpdate when we get a sleep proxy registration request,
7156 // to check our lists and discard any stale duplicates of this record we already have
7157 mDNSlocal void ClearIdenticalProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7158 {
7159     if (m->CurrentRecord)
7160         LogMsg("ClearIdenticalProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7161     m->CurrentRecord = thelist;
7162     while (m->CurrentRecord)
7163     {
7164         AuthRecord *const rr = m->CurrentRecord;
7165         if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7166             if (IdenticalResourceRecord(&rr->resrec, &m->rec.r.resrec))
7167             {
7168                 LogSPS("ClearIdenticalProxyRecords: Removing %3d H-MAC %.6a I-MAC %.6a %d %d %s",
7169                        m->ProxyRecords, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7170                 DeregisterProxyRecord(m, rr);
7171             }
7172         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7173         // new records could have been added to the end of the list as a result of that call.
7174         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7175             m->CurrentRecord = rr->next;
7176     }
7177 }
7178 
7179 // Called from ProcessQuery when we get an mDNS packet with an owner record in it
7180 mDNSlocal void ClearProxyRecords(mDNS *const m, const OwnerOptData *const owner, AuthRecord *const thelist)
7181 {
7182     if (m->CurrentRecord)
7183         LogMsg("ClearProxyRecords ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7184     m->CurrentRecord = thelist;
7185     while (m->CurrentRecord)
7186     {
7187         AuthRecord *const rr = m->CurrentRecord;
7188         if (m->rec.r.resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&owner->HMAC, &rr->WakeUp.HMAC))
7189             if (owner->seq != rr->WakeUp.seq || m->timenow - rr->TimeRcvd > mDNSPlatformOneSecond * 60)
7190             {
7191                 if (rr->AddressProxy.type == mDNSAddrType_IPv6)
7192                 {
7193                     // We don't do this here because we know that the host is waking up at this point, so we don't send
7194                     // Unsolicited Neighbor Advertisements -- even Neighbor Advertisements agreeing with what the host should be
7195                     // saying itself -- because it can cause some IPv6 stacks to falsely conclude that there's an address conflict.
7196                     #if MDNS_USE_Unsolicited_Neighbor_Advertisements
7197                     LogSPS("NDP Announcement -- Releasing traffic for H-MAC %.6a I-MAC %.6a %s",
7198                            &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m,rr));
7199                     SendNDP(m, NDP_Adv, NDP_Override, rr, &rr->AddressProxy.ip.v6, &rr->WakeUp.IMAC, &AllHosts_v6, &AllHosts_v6_Eth);
7200                     #endif
7201                 }
7202                 LogSPS("ClearProxyRecords: Removing %3d AC %2d %02X H-MAC %.6a I-MAC %.6a %d %d %s",
7203                        m->ProxyRecords, rr->AnnounceCount, rr->resrec.RecordType,
7204                        &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, rr->WakeUp.seq, owner->seq, ARDisplayString(m, rr));
7205                 if (rr->resrec.RecordType == kDNSRecordTypeDeregistering) rr->resrec.RecordType = kDNSRecordTypeShared;
7206                 rr->WakeUp.HMAC = zeroEthAddr;  // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
7207                 rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it, since real host is now back and functional
7208                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
7209                 SetSPSProxyListChanged(m->rec.r.resrec.InterfaceID);
7210             }
7211         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
7212         // new records could have been added to the end of the list as a result of that call.
7213         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
7214             m->CurrentRecord = rr->next;
7215     }
7216 }
7217 
7218 // ProcessQuery examines a received query to see if we have any answers to give
7219 mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
7220                                const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID, mDNSBool LegacyQuery, mDNSBool QueryWasMulticast,
7221                                mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
7222 {
7223     mDNSBool FromLocalSubnet    = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7224     AuthRecord   *ResponseRecords    = mDNSNULL;
7225     AuthRecord  **nrp                = &ResponseRecords;
7226 
7227 #if POOF_ENABLED
7228     CacheRecord  *ExpectedAnswers    = mDNSNULL;            // Records in our cache we expect to see updated
7229     CacheRecord **eap                = &ExpectedAnswers;
7230 #endif // POOF_ENABLED
7231 
7232     DNSQuestion  *DupQuestions       = mDNSNULL;            // Our questions that are identical to questions in this packet
7233     DNSQuestion **dqp                = &DupQuestions;
7234     mDNSs32 delayresponse      = 0;
7235     mDNSBool SendLegacyResponse = mDNSfalse;
7236     const mDNSu8 *ptr;
7237     mDNSu8       *responseptr        = mDNSNULL;
7238     AuthRecord   *rr;
7239     int i;
7240     CacheRecord *McastNSEC3Records   = mDNSNULL;
7241 
7242     // ***
7243     // *** 1. Look in Additional Section for an OPT record
7244     // ***
7245     ptr = LocateOptRR(query, end, DNSOpt_OwnerData_ID_Space);
7246     if (ptr)
7247     {
7248         ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAdd, &m->rec);
7249         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
7250         {
7251             const rdataOPT *opt;
7252             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
7253             // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
7254             // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
7255             for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
7256                 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
7257                 {
7258                     ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
7259                     ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
7260                 }
7261         }
7262         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7263     }
7264 
7265     //
7266     // Look in Authority Section for NSEC3 record
7267     //
7268 
7269     mDNSParseNSEC3Records(m, query, end, InterfaceID, &McastNSEC3Records);
7270 
7271     // ***
7272     // *** 2. Parse Question Section and mark potential answers
7273     // ***
7274     ptr = query->data;
7275     for (i=0; i<query->h.numQuestions; i++)                     // For each question...
7276     {
7277         mDNSBool QuestionNeedsMulticastResponse;
7278         int NumAnswersForThisQuestion = 0;
7279         AuthRecord *NSECAnswer = mDNSNULL;
7280         DNSQuestion pktq, *q;
7281         ptr = getQuestion(query, ptr, end, InterfaceID, &pktq); // get the question...
7282         if (!ptr) goto exit;
7283 
7284         pktq.AnonInfo = mDNSNULL;
7285         if (McastNSEC3Records)
7286             InitializeAnonInfoForQuestion(m, &McastNSEC3Records, &pktq);
7287         // The only queries that *need* a multicast response are:
7288         // * Queries sent via multicast
7289         // * from port 5353
7290         // * that don't have the kDNSQClass_UnicastResponse bit set
7291         // These queries need multicast responses because other clients will:
7292         // * suppress their own identical questions when they see these questions, and
7293         // * expire their cache records if they don't see the expected responses
7294         // For other queries, we may still choose to send the occasional multicast response anyway,
7295         // to keep our neighbours caches warm, and for ongoing conflict detection.
7296         QuestionNeedsMulticastResponse = QueryWasMulticast && !LegacyQuery && !(pktq.qclass & kDNSQClass_UnicastResponse);
7297 
7298         if (pktq.qclass & kDNSQClass_UnicastResponse)
7299             m->mDNSStats.UnicastBitInQueries++;
7300         else
7301             m->mDNSStats.NormalQueries++;
7302 
7303         // Clear the UnicastResponse flag -- don't want to confuse the rest of the code that follows later
7304         pktq.qclass &= ~kDNSQClass_UnicastResponse;
7305 
7306         // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
7307         // can result in user callbacks which may change the record list and/or question list.
7308         // Also note: we just mark potential answer records here, without trying to build the
7309         // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
7310         // from that list while we're in the middle of trying to build it.
7311         if (m->CurrentRecord)
7312             LogMsg("ProcessQuery ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
7313         m->CurrentRecord = m->ResourceRecords;
7314         while (m->CurrentRecord)
7315         {
7316             rr = m->CurrentRecord;
7317             m->CurrentRecord = rr->next;
7318             if (AnyTypeRecordAnswersQuestion(&rr->resrec, &pktq) && (QueryWasMulticast || QueryWasLocalUnicast || rr->AllowRemoteQuery))
7319             {
7320                 m->mDNSStats.MatchingAnswersForQueries++;
7321                 if (RRTypeAnswersQuestionType(&rr->resrec, pktq.qtype))
7322                 {
7323                     if (rr->resrec.RecordType == kDNSRecordTypeUnique)
7324                         ResolveSimultaneousProbe(m, query, end, &pktq, rr);
7325                     else if (ResourceRecordIsValidAnswer(rr))
7326                     {
7327                         NumAnswersForThisQuestion++;
7328                         // As we have verified this question to be part of the same subset,
7329                         // set the anonymous data which is needed below when walk the cache
7330                         // records to see what answers we should be expecting. The cache records
7331                         // may cache only the nsec3RR and not the anonymous data itself.
7332                         if (pktq.AnonInfo && rr->resrec.AnonInfo)
7333                             SetAnonData(&pktq, &rr->resrec, mDNStrue);
7334 
7335                         // Note: We should check here if this is a probe-type query, and if so, generate an immediate
7336                         // unicast answer back to the source, because timeliness in answering probes is important.
7337 
7338                         // Notes:
7339                         // NR_AnswerTo pointing into query packet means "answer via immediate legacy unicast" (may *also* choose to multicast)
7340                         // NR_AnswerTo == NR_AnswerUnicast   means "answer via delayed unicast" (to modern querier; may promote to multicast instead)
7341                         // NR_AnswerTo == NR_AnswerMulticast means "definitely answer via multicast" (can't downgrade to unicast later)
7342                         // If we're not multicasting this record because the kDNSQClass_UnicastResponse bit was set,
7343                         // but the multicast querier is not on a matching subnet (e.g. because of overlaid subnets on one link)
7344                         // then we'll multicast it anyway (if we unicast, the receiver will ignore it because it has an apparently non-local source)
7345                         if (QuestionNeedsMulticastResponse || (!FromLocalSubnet && QueryWasMulticast && !LegacyQuery))
7346                         {
7347                             // We only mark this question for sending if it is at least one second since the last time we multicast it
7348                             // on this interface. If it is more than a second, or LastMCInterface is different, then we may multicast it.
7349                             // This is to guard against the case where someone blasts us with queries as fast as they can.
7350                             if (m->timenow - (rr->LastMCTime + mDNSPlatformOneSecond) >= 0 ||
7351                                 (rr->LastMCInterface != mDNSInterfaceMark && rr->LastMCInterface != InterfaceID))
7352                                 rr->NR_AnswerTo = NR_AnswerMulticast;
7353                         }
7354                         else if (!rr->NR_AnswerTo) rr->NR_AnswerTo = LegacyQuery ? ptr : NR_AnswerUnicast;
7355                     }
7356                 }
7357                 else if ((rr->resrec.RecordType & kDNSRecordTypeActiveUniqueMask) && ResourceRecordIsValidAnswer(rr))
7358                 {
7359                     // If we don't have any answers for this question, but we do own another record with the same name,
7360                     // then we'll want to mark it to generate an NSEC record on this interface
7361                     if (!NSECAnswer) NSECAnswer = rr;
7362                 }
7363             }
7364         }
7365 
7366         if (NumAnswersForThisQuestion == 0 && NSECAnswer)
7367         {
7368             NumAnswersForThisQuestion++;
7369             NSECAnswer->SendNSECNow = InterfaceID;
7370             m->NextScheduledResponse = m->timenow;
7371         }
7372 
7373         // If we couldn't answer this question, someone else might be able to,
7374         // so use random delay on response to reduce collisions
7375         if (NumAnswersForThisQuestion == 0) delayresponse = mDNSPlatformOneSecond;  // Divided by 50 = 20ms
7376 
7377         if (query->h.flags.b[0] & kDNSFlag0_TC)
7378             m->mDNSStats.KnownAnswerMultiplePkts++;
7379 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7380         if (QuestionNeedsMulticastResponse)
7381 #else
7382         // We only do the following accelerated cache expiration and duplicate question suppression processing
7383         // for non-truncated multicast queries with multicast responses.
7384         // For any query generating a unicast response we don't do this because we can't assume we will see the response.
7385         // For truncated queries we don't do this because a response we're expecting might be suppressed by a subsequent
7386         // known-answer packet, and when there's packet loss we can't safely assume we'll receive *all* known-answer packets.
7387         if (QuestionNeedsMulticastResponse && !(query->h.flags.b[0] & kDNSFlag0_TC))
7388 #endif
7389         {
7390 #if POOF_ENABLED
7391             const mDNSu32 slot = HashSlot(&pktq.qname);
7392             CacheGroup *cg = CacheGroupForName(m, slot, pktq.qnamehash, &pktq.qname);
7393             CacheRecord *cr;
7394 
7395             // Make a list indicating which of our own cache records we expect to see updated as a result of this query
7396             // Note: Records larger than 1K are not habitually multicast, so don't expect those to be updated
7397 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7398             if (!(query->h.flags.b[0] & kDNSFlag0_TC))
7399 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7400             for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
7401                 if (SameNameRecordAnswersQuestion(&cr->resrec, &pktq) && cr->resrec.rdlength <= SmallRecordLimit)
7402                     if (!cr->NextInKAList && eap != &cr->NextInKAList)
7403                     {
7404                         *eap = cr;
7405                         eap = &cr->NextInKAList;
7406 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7407                         if (cr->MPUnansweredQ == 0 || m->timenow - cr->MPLastUnansweredQT >= mDNSPlatformOneSecond)
7408                         {
7409                             // Although MPUnansweredQ is only really used for multi-packet query processing,
7410                             // we increment it for both single-packet and multi-packet queries, so that it stays in sync
7411                             // with the MPUnansweredKA value, which by necessity is incremented for both query types.
7412                             cr->MPUnansweredQ++;
7413                             cr->MPLastUnansweredQT = m->timenow;
7414                             cr->MPExpectingKA = mDNStrue;
7415                         }
7416 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7417                     }
7418 #endif // POOF_ENABLED
7419 
7420             // Check if this question is the same as any of mine.
7421             // We only do this for non-truncated queries. Right now it would be too complicated to try
7422             // to keep track of duplicate suppression state between multiple packets, especially when we
7423             // can't guarantee to receive all of the Known Answer packets that go with a particular query.
7424 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7425             if (!(query->h.flags.b[0] & kDNSFlag0_TC))
7426 #endif
7427             // For anonymous question, the duplicate suppressesion should happen if the
7428             // question belongs in the same group. As the group is expected to be
7429             // small, we don't do the optimization for now.
7430             if (!pktq.AnonInfo)
7431             {
7432                 for (q = m->Questions; q; q=q->next)
7433                     if (!q->Target.type && ActiveQuestion(q) && m->timenow - q->LastQTxTime > mDNSPlatformOneSecond / 4)
7434                         if (!q->InterfaceID || q->InterfaceID == InterfaceID)
7435                             if (q->NextInDQList == mDNSNULL && dqp != &q->NextInDQList)
7436                                 if (q->qtype == pktq.qtype &&
7437                                     q->qclass == pktq.qclass &&
7438                                     q->qnamehash == pktq.qnamehash && SameDomainName(&q->qname, &pktq.qname))
7439                                 { *dqp = q; dqp = &q->NextInDQList; }
7440             }
7441         }
7442         if (pktq.AnonInfo)
7443         {
7444             FreeAnonInfo(pktq.AnonInfo);
7445         }
7446     }
7447 
7448     // ***
7449     // *** 3. Now we can safely build the list of marked answers
7450     // ***
7451     for (rr = m->ResourceRecords; rr; rr=rr->next)              // Now build our list of potential answers
7452         if (rr->NR_AnswerTo)                                    // If we marked the record...
7453             AddRecordToResponseList(&nrp, rr, mDNSNULL);        // ... add it to the list
7454 
7455     // ***
7456     // *** 4. Add additional records
7457     // ***
7458     AddAdditionalsToResponseList(m, ResponseRecords, &nrp, InterfaceID);
7459 
7460     // ***
7461     // *** 5. Parse Answer Section and cancel any records disallowed by Known-Answer list
7462     // ***
7463     for (i=0; i<query->h.numAnswers; i++)                       // For each record in the query's answer section...
7464     {
7465         // Get the record...
7466         CacheRecord *ourcacherr;
7467         ptr = GetLargeResourceRecord(m, query, ptr, end, InterfaceID, kDNSRecordTypePacketAns, &m->rec);
7468         if (!ptr) goto exit;
7469         if (m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
7470         {
7471             // See if this Known-Answer suppresses any of our currently planned answers
7472             for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7473             {
7474                 if (MustSendRecord(rr) && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7475                 {
7476                     m->mDNSStats.KnownAnswerSuppressions++;
7477                     rr->NR_AnswerTo = mDNSNULL;
7478                     rr->NR_AdditionalTo = mDNSNULL;
7479                 }
7480             }
7481 
7482             // See if this Known-Answer suppresses any previously scheduled answers (for multi-packet KA suppression)
7483             for (rr=m->ResourceRecords; rr; rr=rr->next)
7484             {
7485                 // If we're planning to send this answer on this interface, and only on this interface, then allow KA suppression
7486                 if (rr->ImmedAnswer == InterfaceID && ShouldSuppressKnownAnswer(&m->rec.r, rr))
7487                 {
7488                     if (srcaddr->type == mDNSAddrType_IPv4)
7489                     {
7490                         if (mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = zerov4Addr;
7491                     }
7492                     else if (srcaddr->type == mDNSAddrType_IPv6)
7493                     {
7494                         if (mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = zerov6Addr;
7495                     }
7496                     if (mDNSIPv4AddressIsZero(rr->v4Requester) && mDNSIPv6AddressIsZero(rr->v6Requester))
7497                     {
7498                         m->mDNSStats.KnownAnswerSuppressions++;
7499                         rr->ImmedAnswer  = mDNSNULL;
7500                         rr->ImmedUnicast = mDNSfalse;
7501     #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7502                         LogMsg("Suppressed after%4d: %s", m->timenow - rr->ImmedAnswerMarkTime, ARDisplayString(m, rr));
7503     #endif
7504                     }
7505                 }
7506             }
7507 
7508             ourcacherr = FindIdenticalRecordInCache(m, &m->rec.r.resrec);
7509 
7510     #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7511             // See if this Known-Answer suppresses any answers we were expecting for our cache records. We do this always,
7512             // even if the TC bit is not set (the TC bit will *not* be set in the *last* packet of a multi-packet KA list).
7513             if (ourcacherr && ourcacherr->MPExpectingKA && m->timenow - ourcacherr->MPLastUnansweredQT < mDNSPlatformOneSecond)
7514             {
7515                 ourcacherr->MPUnansweredKA++;
7516                 ourcacherr->MPExpectingKA = mDNSfalse;
7517             }
7518     #endif
7519 
7520 #if POOF_ENABLED
7521             // Having built our ExpectedAnswers list from the questions in this packet, we then remove
7522             // any records that are suppressed by the Known Answer list in this packet.
7523             eap = &ExpectedAnswers;
7524             while (*eap)
7525             {
7526                 CacheRecord *cr = *eap;
7527                 if (cr->resrec.InterfaceID == InterfaceID && IdenticalResourceRecord(&m->rec.r.resrec, &cr->resrec))
7528                 { *eap = cr->NextInKAList; cr->NextInKAList = mDNSNULL; }
7529                 else eap = &cr->NextInKAList;
7530             }
7531 #endif // POOF_ENABLED
7532 
7533             // See if this Known-Answer is a surprise to us. If so, we shouldn't suppress our own query.
7534             if (!ourcacherr)
7535             {
7536                 dqp = &DupQuestions;
7537                 while (*dqp)
7538                 {
7539                     DNSQuestion *q = *dqp;
7540                     if (ResourceRecordAnswersQuestion(&m->rec.r.resrec, q))
7541                     { *dqp = q->NextInDQList; q->NextInDQList = mDNSNULL; }
7542                     else dqp = &q->NextInDQList;
7543                 }
7544             }
7545         }
7546         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7547     }
7548 
7549     // ***
7550     // *** 6. Cancel any additionals that were added because of now-deleted records
7551     // ***
7552     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7553         if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
7554         { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
7555 
7556     // ***
7557     // *** 7. Mark the send flags on the records we plan to send
7558     // ***
7559     for (rr=ResponseRecords; rr; rr=rr->NextResponse)
7560     {
7561         if (rr->NR_AnswerTo)
7562         {
7563             mDNSBool SendMulticastResponse = mDNSfalse;     // Send modern multicast response
7564             mDNSBool SendUnicastResponse   = mDNSfalse;     // Send modern unicast response (not legacy unicast response)
7565 
7566 #if !TARGET_OS_EMBEDDED
7567     // always honor kDNSQClass_UnicastResponse in embedded environment to increase reliability
7568     // in high multicast packet loss environments.
7569 
7570             // If it's been one TTL/4 since we multicast this, then send a multicast response
7571             // for conflict detection, etc.
7572             if (m->timenow - (rr->LastMCTime + TicksTTL(rr)/4) >= 0)
7573             {
7574                 SendMulticastResponse = mDNStrue;
7575                 // If this record was marked for modern (delayed) unicast response, then mark it as promoted to
7576                 // multicast response instead (don't want to end up ALSO setting SendUnicastResponse in the check below).
7577                 // If this record was marked for legacy unicast response, then we mustn't change the NR_AnswerTo value.
7578                 if (rr->NR_AnswerTo == NR_AnswerUnicast)
7579                 {
7580                     m->mDNSStats.UnicastDemotedToMulticast++;
7581                     rr->NR_AnswerTo = NR_AnswerMulticast;
7582                 }
7583             }
7584 #endif // !TARGET_OS_EMBEDDED
7585 
7586             // If the client insists on a multicast response, then we'd better send one
7587             if      (rr->NR_AnswerTo == NR_AnswerMulticast)
7588             {
7589                 m->mDNSStats.MulticastResponses++;
7590                 SendMulticastResponse = mDNStrue;
7591             }
7592             else if (rr->NR_AnswerTo == NR_AnswerUnicast)
7593             {
7594                 m->mDNSStats.UnicastResponses++;
7595                 SendUnicastResponse   = mDNStrue;
7596             }
7597             else if (rr->NR_AnswerTo)
7598             {
7599                 SendLegacyResponse    = mDNStrue;
7600             }
7601 
7602 
7603             if (SendMulticastResponse || SendUnicastResponse)
7604             {
7605 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7606                 rr->ImmedAnswerMarkTime = m->timenow;
7607 #endif
7608                 m->NextScheduledResponse = m->timenow;
7609                 // If we're already planning to send this on another interface, just send it on all interfaces
7610                 if (rr->ImmedAnswer && rr->ImmedAnswer != InterfaceID)
7611                     rr->ImmedAnswer = mDNSInterfaceMark;
7612                 else
7613                 {
7614                     rr->ImmedAnswer = InterfaceID;          // Record interface to send it on
7615                     if (SendUnicastResponse) rr->ImmedUnicast = mDNStrue;
7616                     if (srcaddr->type == mDNSAddrType_IPv4)
7617                     {
7618                         if      (mDNSIPv4AddressIsZero(rr->v4Requester)) rr->v4Requester = srcaddr->ip.v4;
7619                         else if (!mDNSSameIPv4Address(rr->v4Requester, srcaddr->ip.v4)) rr->v4Requester = onesIPv4Addr;
7620                     }
7621                     else if (srcaddr->type == mDNSAddrType_IPv6)
7622                     {
7623                         if      (mDNSIPv6AddressIsZero(rr->v6Requester)) rr->v6Requester = srcaddr->ip.v6;
7624                         else if (!mDNSSameIPv6Address(rr->v6Requester, srcaddr->ip.v6)) rr->v6Requester = onesIPv6Addr;
7625                     }
7626                 }
7627             }
7628             // If TC flag is set, it means we should expect that additional known answers may be coming in another packet,
7629             // so we allow roughly half a second before deciding to reply (we've observed inter-packet delays of 100-200ms on 802.11)
7630             // else, if record is a shared one, spread responses over 100ms to avoid implosion of simultaneous responses
7631             // else, for a simple unique record reply, we can reply immediately; no need for delay
7632             if      (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNSPlatformOneSecond * 20;            // Divided by 50 = 400ms
7633             else if (rr->resrec.RecordType == kDNSRecordTypeShared) delayresponse = mDNSPlatformOneSecond;      // Divided by 50 = 20ms
7634         }
7635         else if (rr->NR_AdditionalTo && rr->NR_AdditionalTo->NR_AnswerTo == NR_AnswerMulticast)
7636         {
7637             // Since additional records are an optimization anyway, we only ever send them on one interface at a time
7638             // If two clients on different interfaces do queries that invoke the same optional additional answer,
7639             // then the earlier client is out of luck
7640             rr->ImmedAdditional = InterfaceID;
7641             // No need to set m->NextScheduledResponse here
7642             // We'll send these additional records when we send them, or not, as the case may be
7643         }
7644     }
7645 
7646     // ***
7647     // *** 8. If we think other machines are likely to answer these questions, set our packet suppression timer
7648     // ***
7649     if (delayresponse && (!m->SuppressSending || (m->SuppressSending - m->timenow) < (delayresponse + 49) / 50))
7650     {
7651 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7652         mDNSs32 oldss = m->SuppressSending;
7653         if (oldss && delayresponse)
7654             LogMsg("Current SuppressSending delay%5ld; require%5ld", m->SuppressSending - m->timenow, (delayresponse + 49) / 50);
7655 #endif
7656         // Pick a random delay:
7657         // We start with the base delay chosen above (typically either 1 second or 20 seconds),
7658         // and add a random value in the range 0-5 seconds (making 1-6 seconds or 20-25 seconds).
7659         // This is an integer value, with resolution determined by the platform clock rate.
7660         // We then divide that by 50 to get the delay value in ticks. We defer the division until last
7661         // to get better results on platforms with coarse clock granularity (e.g. ten ticks per second).
7662         // The +49 before dividing is to ensure we round up, not down, to ensure that even
7663         // on platforms where the native clock rate is less than fifty ticks per second,
7664         // we still guarantee that the final calculated delay is at least one platform tick.
7665         // We want to make sure we don't ever allow the delay to be zero ticks,
7666         // because if that happens we'll fail the Bonjour Conformance Test.
7667         // Our final computed delay is 20-120ms for normal delayed replies,
7668         // or 400-500ms in the case of multi-packet known-answer lists.
7669         m->SuppressSending = m->timenow + (delayresponse + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*5) + 49) / 50;
7670         if (m->SuppressSending == 0) m->SuppressSending = 1;
7671 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
7672         if (oldss && delayresponse)
7673             LogMsg("Set     SuppressSending to   %5ld", m->SuppressSending - m->timenow);
7674 #endif
7675     }
7676 
7677     // ***
7678     // *** 9. If query is from a legacy client, or from a new client requesting a unicast reply, then generate a unicast response too
7679     // ***
7680     if (SendLegacyResponse)
7681         responseptr = GenerateUnicastResponse(query, end, InterfaceID, LegacyQuery, response, ResponseRecords);
7682 
7683 exit:
7684     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
7685 
7686     // ***
7687     // *** 10. Finally, clear our link chains ready for use next time
7688     // ***
7689     while (ResponseRecords)
7690     {
7691         rr = ResponseRecords;
7692         ResponseRecords = rr->NextResponse;
7693         rr->NextResponse    = mDNSNULL;
7694         rr->NR_AnswerTo     = mDNSNULL;
7695         rr->NR_AdditionalTo = mDNSNULL;
7696     }
7697 
7698 #if POOF_ENABLED
7699     while (ExpectedAnswers)
7700     {
7701         CacheRecord *cr = ExpectedAnswers;
7702         ExpectedAnswers = cr->NextInKAList;
7703         cr->NextInKAList = mDNSNULL;
7704 
7705         // For non-truncated queries, we can definitively say that we should expect
7706         // to be seeing a response for any records still left in the ExpectedAnswers list
7707         if (!(query->h.flags.b[0] & kDNSFlag0_TC))
7708             if (cr->UnansweredQueries == 0 || m->timenow - cr->LastUnansweredTime >= mDNSPlatformOneSecond)
7709             {
7710                 cr->UnansweredQueries++;
7711                 cr->LastUnansweredTime = m->timenow;
7712 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7713                 if (cr->UnansweredQueries > 1)
7714                     debugf("ProcessQuery: (!TC) UAQ %lu MPQ %lu MPKA %lu %s",
7715                            cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
7716 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7717                 SetNextCacheCheckTimeForRecord(m, cr);
7718             }
7719 
7720         // If we've seen multiple unanswered queries for this record,
7721         // then mark it to expire in five seconds if we don't get a response by then.
7722         if (cr->UnansweredQueries >= MaxUnansweredQueries)
7723         {
7724 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7725             // Only show debugging message if this record was not about to expire anyway
7726             if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
7727                 debugf("ProcessQuery: (Max) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
7728                        cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
7729 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7730             m->mDNSStats.PoofCacheDeletions++;
7731             mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
7732         }
7733 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
7734         // Make a guess, based on the multi-packet query / known answer counts, whether we think we
7735         // should have seen an answer for this. (We multiply MPQ by 4 and MPKA by 5, to allow for
7736         // possible packet loss of up to 20% of the additional KA packets.)
7737         else if (cr->MPUnansweredQ * 4 > cr->MPUnansweredKA * 5 + 8)
7738         {
7739             // We want to do this conservatively.
7740             // If there are so many machines on the network that they have to use multi-packet known-answer lists,
7741             // then we don't want them to all hit the network simultaneously with their final expiration queries.
7742             // By setting the record to expire in four minutes, we achieve two things:
7743             // (a) the 90-95% final expiration queries will be less bunched together
7744             // (b) we allow some time for us to witness enough other failed queries that we don't have to do our own
7745             mDNSu32 remain = (mDNSu32)(RRExpireTime(cr) - m->timenow) / 4;
7746             if (remain > 240 * (mDNSu32)mDNSPlatformOneSecond)
7747                 remain = 240 * (mDNSu32)mDNSPlatformOneSecond;
7748 
7749             // Only show debugging message if this record was not about to expire anyway
7750             if (RRExpireTime(cr) - m->timenow > 4 * mDNSPlatformOneSecond)
7751                 debugf("ProcessQuery: (MPQ) UAQ %lu MPQ %lu MPKA %lu mDNS_Reconfirm() for %s",
7752                        cr->UnansweredQueries, cr->MPUnansweredQ, cr->MPUnansweredKA, CRDisplayString(m, cr));
7753 
7754             if (remain <= 60 * (mDNSu32)mDNSPlatformOneSecond)
7755                 cr->UnansweredQueries++;    // Treat this as equivalent to one definite unanswered query
7756             cr->MPUnansweredQ  = 0;         // Clear MPQ/MPKA statistics
7757             cr->MPUnansweredKA = 0;
7758             cr->MPExpectingKA  = mDNSfalse;
7759 
7760             if (remain < kDefaultReconfirmTimeForNoAnswer)
7761                 remain = kDefaultReconfirmTimeForNoAnswer;
7762             mDNS_Reconfirm_internal(m, cr, remain);
7763         }
7764 #endif // ENABLE_MULTI_PACKET_QUERY_SNOOPING
7765     }
7766 #endif // POOF_ENABLED
7767 
7768     while (DupQuestions)
7769     {
7770         DNSQuestion *q = DupQuestions;
7771         DupQuestions = q->NextInDQList;
7772         q->NextInDQList = mDNSNULL;
7773         RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
7774         debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
7775                srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6");
7776     }
7777 
7778     if (McastNSEC3Records)
7779     {
7780         debugf("ProcessQuery: McastNSEC3Records not used");
7781         FreeNSECRecords(m, McastNSEC3Records);
7782     }
7783 
7784     return(responseptr);
7785 }
7786 
7787 mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
7788                                     const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
7789                                     const mDNSInterfaceID InterfaceID)
7790 {
7791     mDNSu8    *responseend = mDNSNULL;
7792     mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
7793                                     !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
7794 
7795     if (!InterfaceID && dstaddr && mDNSAddrIsDNSMulticast(dstaddr))
7796     {
7797         LogMsg("Ignoring Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7798                "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes (Multicast, but no InterfaceID)",
7799                srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7800                msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
7801                msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
7802                msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
7803                msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
7804         return;
7805     }
7806 
7807     verbosedebugf("Received Query from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
7808                   "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
7809                   srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
7810                   msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
7811                   msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
7812                   msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
7813                   msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
7814 
7815     responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceID,
7816                                !mDNSSameIPPort(srcport, MulticastDNSPort), mDNSAddrIsDNSMulticast(dstaddr), QueryWasLocalUnicast, &m->omsg);
7817 
7818     if (responseend)    // If responseend is non-null, that means we built a unicast response packet
7819     {
7820         debugf("Unicast Response: %d Question%s, %d Answer%s, %d Additional%s to %#-15a:%d on %p/%ld",
7821                m->omsg.h.numQuestions,   m->omsg.h.numQuestions   == 1 ? "" : "s",
7822                m->omsg.h.numAnswers,     m->omsg.h.numAnswers     == 1 ? "" : "s",
7823                m->omsg.h.numAdditionals, m->omsg.h.numAdditionals == 1 ? "" : "s",
7824                srcaddr, mDNSVal16(srcport), InterfaceID, srcaddr->type);
7825         mDNSSendDNSMessage(m, &m->omsg, responseend, InterfaceID, mDNSNULL, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
7826     }
7827 }
7828 
7829 #if 0
7830 mDNSlocal mDNSBool TrustedSource(const mDNS *const m, const mDNSAddr *const srcaddr)
7831 {
7832     DNSServer *s;
7833     (void)m; // Unused
7834     (void)srcaddr; // Unused
7835     for (s = m->DNSServers; s; s = s->next)
7836         if (mDNSSameAddress(srcaddr, &s->addr)) return(mDNStrue);
7837     return(mDNSfalse);
7838 }
7839 #endif
7840 
7841 struct UDPSocket_struct
7842 {
7843     mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
7844 };
7845 
7846 mDNSlocal DNSQuestion *ExpectingUnicastResponseForQuestion(const mDNS *const m, const mDNSIPPort port, const mDNSOpaque16 id, const DNSQuestion *const question, mDNSBool tcp)
7847 {
7848     DNSQuestion *q;
7849     for (q = m->Questions; q; q=q->next)
7850     {
7851         if (!tcp && !q->LocalSocket) continue;
7852         if (mDNSSameIPPort(tcp ? q->tcpSrcPort : q->LocalSocket->port, port)     &&
7853             mDNSSameOpaque16(q->TargetQID,         id)       &&
7854             q->qtype                  == question->qtype     &&
7855             q->qclass                 == question->qclass    &&
7856             q->qnamehash              == question->qnamehash &&
7857             SameDomainName(&q->qname, &question->qname))
7858             return(q);
7859     }
7860     return(mDNSNULL);
7861 }
7862 
7863 // This function is called when we receive a unicast response. This could be the case of a unicast response from the
7864 // DNS server or a response to the QU query. Hence, the cache record's InterfaceId can be both NULL or non-NULL (QU case)
7865 mDNSlocal DNSQuestion *ExpectingUnicastResponseForRecord(mDNS *const m,
7866                                                          const mDNSAddr *const srcaddr, const mDNSBool SrcLocal, const mDNSIPPort port, const mDNSOpaque16 id, const CacheRecord *const rr, mDNSBool tcp)
7867 {
7868     DNSQuestion *q;
7869     (void)id;
7870     (void)srcaddr;
7871 
7872     for (q = m->Questions; q; q=q->next)
7873     {
7874         if (!q->DuplicateOf && ResourceRecordAnswersUnicastResponse(&rr->resrec, q))
7875         {
7876             if (!mDNSOpaque16IsZero(q->TargetQID))
7877             {
7878                 debugf("ExpectingUnicastResponseForRecord msg->h.id %d q->TargetQID %d for %s", mDNSVal16(id), mDNSVal16(q->TargetQID), CRDisplayString(m, rr));
7879 
7880                 if (mDNSSameOpaque16(q->TargetQID, id))
7881                 {
7882                     mDNSIPPort srcp;
7883                     if (!tcp)
7884                     {
7885 			if (q->LocalSocket)
7886                             srcp = q->LocalSocket->port;
7887 			else
7888                             srcp = zeroIPPort;
7889                     }
7890                     else
7891                     {
7892                         srcp = q->tcpSrcPort;
7893                     }
7894                     if (mDNSSameIPPort(srcp, port)) return(q);
7895 
7896                     //	if (mDNSSameAddress(srcaddr, &q->Target))                   return(mDNStrue);
7897                     //	if (q->LongLived && mDNSSameAddress(srcaddr, &q->servAddr)) return(mDNStrue); Shouldn't need this now that we have LLQType checking
7898                     //	if (TrustedSource(m, srcaddr))                              return(mDNStrue);
7899                     LogInfo("WARNING: Ignoring suspect uDNS response for %##s (%s) [q->Target %#a:%d] from %#a:%d %s",
7900                             q->qname.c, DNSTypeName(q->qtype), &q->Target, mDNSVal16(srcp), srcaddr, mDNSVal16(port), CRDisplayString(m, rr));
7901                     return(mDNSNULL);
7902                 }
7903             }
7904             else
7905             {
7906                 if (SrcLocal && q->ExpectUnicastResp && (mDNSu32)(m->timenow - q->ExpectUnicastResp) < (mDNSu32)(mDNSPlatformOneSecond*2))
7907                     return(q);
7908             }
7909         }
7910     }
7911     return(mDNSNULL);
7912 }
7913 
7914 // Certain data types need more space for in-memory storage than their in-packet rdlength would imply
7915 // Currently this applies only to rdata types containing more than one domainname,
7916 // or types where the domainname is not the last item in the structure.
7917 mDNSlocal mDNSu16 GetRDLengthMem(const ResourceRecord *const rr)
7918 {
7919     switch (rr->rrtype)
7920     {
7921     case kDNSType_SOA: return sizeof(rdataSOA);
7922     case kDNSType_RP:  return sizeof(rdataRP);
7923     case kDNSType_PX:  return sizeof(rdataPX);
7924     default:           return rr->rdlength;
7925     }
7926 }
7927 
7928 mDNSexport CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress)
7929 {
7930     CacheRecord *rr = mDNSNULL;
7931     mDNSu16 RDLength = GetRDLengthMem(&m->rec.r.resrec);
7932 
7933     if (!m->rec.r.resrec.InterfaceID) debugf("CreateNewCacheEntry %s", CRDisplayString(m, &m->rec.r));
7934 
7935     //if (RDLength > InlineCacheRDSize)
7936     //	LogInfo("Rdata len %4d > InlineCacheRDSize %d %s", RDLength, InlineCacheRDSize, CRDisplayString(m, &m->rec.r));
7937 
7938     if (!cg) cg = GetCacheGroup(m, slot, &m->rec.r.resrec); // If we don't have a CacheGroup for this name, make one now
7939     if (cg) rr = GetCacheRecord(m, cg, RDLength);   // Make a cache record, being careful not to recycle cg
7940     if (!rr) NoCacheAnswer(m, &m->rec.r);
7941     else
7942     {
7943         RData *saveptr = rr->resrec.rdata;      // Save the rr->resrec.rdata pointer
7944         *rr = m->rec.r;                         // Block copy the CacheRecord object
7945         rr->resrec.rdata  = saveptr;            // Restore rr->resrec.rdata after the structure assignment
7946         rr->resrec.name   = cg->name;           // And set rr->resrec.name to point into our CacheGroup header
7947 
7948         // We need to add the anonymous info before we call CacheRecordAdd so that
7949         // if it finds a matching question with this record, it bumps up the counters like
7950         // CurrentAnswers etc. Otherwise, when a cache entry gets removed, CacheRecordRmv
7951         // will complain.
7952         if (m->rec.r.resrec.AnonInfo)
7953         {
7954             rr->resrec.AnonInfo = m->rec.r.resrec.AnonInfo;
7955             m->rec.r.resrec.AnonInfo = mDNSNULL;
7956         }
7957         rr->DelayDelivery = delay;
7958 
7959         // If this is an oversized record with external storage allocated, copy rdata to external storage
7960         if      (rr->resrec.rdata == (RData*)&rr->smallrdatastorage && RDLength > InlineCacheRDSize)
7961             LogMsg("rr->resrec.rdata == &rr->rdatastorage but length > InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
7962         else if (rr->resrec.rdata != (RData*)&rr->smallrdatastorage && RDLength <= InlineCacheRDSize)
7963             LogMsg("rr->resrec.rdata != &rr->rdatastorage but length <= InlineCacheRDSize %##s", m->rec.r.resrec.name->c);
7964         if (RDLength > InlineCacheRDSize)
7965             mDNSPlatformMemCopy(rr->resrec.rdata, m->rec.r.resrec.rdata, sizeofRDataHeader + RDLength);
7966 
7967         rr->next = mDNSNULL;                    // Clear 'next' pointer
7968         rr->nsec = mDNSNULL;
7969         rr->soa  = mDNSNULL;
7970 
7971         if (sourceAddress)
7972             rr->sourceAddress = *sourceAddress;
7973 
7974         if (!rr->resrec.InterfaceID)
7975         {
7976             m->rrcache_totalused_unicast += rr->resrec.rdlength;
7977             if (DNSSECRecordType(rr->resrec.rrtype))
7978                 BumpDNSSECStats(m, kStatsActionIncrement, kStatsTypeMemoryUsage, rr->resrec.rdlength);
7979         }
7980 
7981         if (Add)
7982         {
7983             *(cg->rrcache_tail) = rr;               // Append this record to tail of cache slot list
7984             cg->rrcache_tail = &(rr->next);         // Advance tail pointer
7985             CacheRecordAdd(m, rr);  // CacheRecordAdd calls SetNextCacheCheckTimeForRecord(m, rr); for us
7986         }
7987         else
7988         {
7989             // Can't use the "cg->name" if we are not adding to the cache as the
7990             // CacheGroup may be released anytime if it is empty
7991             domainname *name = mDNSPlatformMemAllocate(DomainNameLength(cg->name));
7992             if (name)
7993             {
7994                 AssignDomainName(name, cg->name);
7995                 rr->resrec.name   = name;
7996             }
7997             else
7998             {
7999                 ReleaseCacheRecord(m, rr);
8000                 NoCacheAnswer(m, &m->rec.r);
8001                 rr = mDNSNULL;
8002             }
8003         }
8004     }
8005     return(rr);
8006 }
8007 
8008 mDNSlocal void RefreshCacheRecord(mDNS *const m, CacheRecord *rr, mDNSu32 ttl)
8009 {
8010     rr->TimeRcvd             = m->timenow;
8011     rr->resrec.rroriginalttl = ttl;
8012     rr->UnansweredQueries = 0;
8013 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
8014     rr->MPUnansweredQ     = 0;
8015     rr->MPUnansweredKA    = 0;
8016     rr->MPExpectingKA     = mDNSfalse;
8017 #endif
8018     SetNextCacheCheckTimeForRecord(m, rr);
8019 }
8020 
8021 mDNSexport void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease)
8022 {
8023     CacheRecord *rr;
8024     const mDNSu32 slot = HashSlot(&q->qname);
8025     CacheGroup *cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
8026     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8027         if (rr->CRActiveQuestion == q)
8028         {
8029             //LogInfo("GrantCacheExtensions: new lease %d / %s", lease, CRDisplayString(m, rr));
8030             RefreshCacheRecord(m, rr, lease);
8031         }
8032 }
8033 
8034 mDNSlocal mDNSu32 GetEffectiveTTL(const uDNS_LLQType LLQType, mDNSu32 ttl)      // TTL in seconds
8035 {
8036     if      (LLQType == uDNS_LLQ_Entire) ttl = kLLQ_DefLease;
8037     else if (LLQType == uDNS_LLQ_Events)
8038     {
8039         // If the TTL is -1 for uDNS LLQ event packet, that means "remove"
8040         if (ttl == 0xFFFFFFFF) ttl = 0;
8041         else ttl = kLLQ_DefLease;
8042     }
8043     else    // else not LLQ (standard uDNS response)
8044     {
8045         // The TTL is already capped to a maximum value in GetLargeResourceRecord, but just to be extra safe we
8046         // also do this check here to make sure we can't get overflow below when we add a quarter to the TTL
8047         if (ttl > 0x60000000UL / mDNSPlatformOneSecond) ttl = 0x60000000UL / mDNSPlatformOneSecond;
8048 
8049         ttl = RRAdjustTTL(ttl);
8050 
8051         // For mDNS, TTL zero means "delete this record"
8052         // For uDNS, TTL zero means: this data is true at this moment, but don't cache it.
8053         // For the sake of network efficiency, we impose a minimum effective TTL of 15 seconds.
8054         // This means that we'll do our 80, 85, 90, 95% queries at 12.00, 12.75, 13.50, 14.25 seconds
8055         // respectively, and then if we get no response, delete the record from the cache at 15 seconds.
8056         // This gives the server up to three seconds to respond between when we send our 80% query at 12 seconds
8057         // and when we delete the record at 15 seconds. Allowing cache lifetimes less than 15 seconds would
8058         // (with the current code) result in the server having even less than three seconds to respond
8059         // before we deleted the record and reported a "remove" event to any active questions.
8060         // Furthermore, with the current code, if we were to allow a TTL of less than 2 seconds
8061         // then things really break (e.g. we end up making a negative cache entry).
8062         // In the future we may want to revisit this and consider properly supporting non-cached (TTL=0) uDNS answers.
8063         if (ttl < 15) ttl = 15;
8064     }
8065 
8066     return ttl;
8067 }
8068 
8069 // When the response does not match the question directly, we still want to cache them sometimes. The current response is
8070 // in m->rec.
8071 mDNSlocal mDNSBool IsResponseAcceptable(mDNS *const m, const CacheRecord *crlist, DNSQuestion *q, mDNSBool *nseclist)
8072 {
8073     CacheRecord *const newcr = &m->rec.r;
8074     ResourceRecord *rr = &newcr->resrec;
8075     const CacheRecord *cr;
8076 
8077     *nseclist = mDNSfalse;
8078     for (cr = crlist; cr != (CacheRecord*)1; cr = cr->NextInCFList)
8079     {
8080         domainname *target = GetRRDomainNameTarget(&cr->resrec);
8081         // When we issue a query for A record, the response might contain both a CNAME and A records. Only the CNAME would
8082         // match the question and we already created a cache entry in the previous pass of this loop. Now when we process
8083         // the A record, it does not match the question because the record name here is the CNAME. Hence we try to
8084         // match with the previous records to make it an AcceptableResponse. We have to be careful about setting the
8085         // DNSServer value that we got in the previous pass. This can happen for other record types like SRV also.
8086 
8087         if (target && cr->resrec.rdatahash == rr->namehash && SameDomainName(target, rr->name))
8088         {
8089             LogInfo("IsResponseAcceptable: Found a matching entry for %##s in the CacheFlushRecords %s", rr->name->c, CRDisplayString(m, cr));
8090             return (mDNStrue);
8091         }
8092     }
8093 
8094     // Either the question requires validation or we are validating a response with DNSSEC in which case
8095     // we need to accept the RRSIGs also so that we can validate the response. It is also possible that
8096     // we receive NSECs for our query which does not match the qname and we need to cache in that case
8097     // too. nseclist is set if they have to be cached as part of the negative cache record.
8098     if (q && DNSSECQuestion(q))
8099     {
8100         mDNSBool same = SameDomainName(&q->qname, rr->name);
8101         if (same && (q->qtype == rr->rrtype || rr->rrtype == kDNSType_CNAME))
8102         {
8103             LogInfo("IsResponseAcceptable: Accepting, same name and qtype %s, CR %s", DNSTypeName(q->qtype),
8104                     CRDisplayString(m, newcr));
8105             return mDNStrue;
8106         }
8107         // We cache RRSIGS if it covers the question type or NSEC.  If it covers a NSEC,
8108         // "nseclist" is set
8109         if (rr->rrtype == kDNSType_RRSIG)
8110         {
8111             RDataBody2 *const rdb = (RDataBody2 *)newcr->smallrdatastorage.data;
8112             rdataRRSig *rrsig = &rdb->rrsig;
8113             mDNSu16 typeCovered = swap16(rrsig->typeCovered);
8114 
8115             // Note the ordering. If we are looking up the NSEC record, then the RRSIG's typeCovered
8116             // would match the qtype and they are cached normally as they are not used to prove the
8117             // non-existence of any name. In that case, it is like any other normal dnssec validation
8118             // and hence nseclist should not be set.
8119 
8120             if (same && ((typeCovered == q->qtype) || (typeCovered == kDNSType_CNAME)))
8121             {
8122                 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches question type %s", CRDisplayString(m, newcr),
8123                         DNSTypeName(q->qtype));
8124                 return mDNStrue;
8125             }
8126             else if (typeCovered == kDNSType_NSEC || typeCovered == kDNSType_NSEC3)
8127             {
8128                 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches %s type (nseclist = 1)", CRDisplayString(m, newcr), DNSTypeName(typeCovered));
8129                 *nseclist = mDNStrue;
8130                 return mDNStrue;
8131             }
8132             else if (typeCovered == kDNSType_SOA)
8133             {
8134                 LogInfo("IsResponseAcceptable: Accepting RRSIG %s matches SOA type (nseclist = 1)", CRDisplayString(m, newcr));
8135                 *nseclist = mDNStrue;
8136                 return mDNStrue;
8137             }
8138             else return mDNSfalse;
8139         }
8140         if (rr->rrtype == kDNSType_NSEC)
8141         {
8142             if (!UNICAST_NSEC(rr))
8143             {
8144                 LogMsg("IsResponseAcceptable: ERROR!! Not a unicast NSEC %s", CRDisplayString(m, newcr));
8145                 return mDNSfalse;
8146             }
8147             LogInfo("IsResponseAcceptable: Accepting NSEC %s (nseclist = 1)", CRDisplayString(m, newcr));
8148             *nseclist = mDNStrue;
8149             return mDNStrue;
8150         }
8151         if (rr->rrtype == kDNSType_SOA)
8152         {
8153             LogInfo("IsResponseAcceptable: Accepting SOA %s (nseclist = 1)", CRDisplayString(m, newcr));
8154             *nseclist = mDNStrue;
8155             return mDNStrue;
8156         }
8157         else if (rr->rrtype == kDNSType_NSEC3)
8158         {
8159             LogInfo("IsResponseAcceptable: Accepting NSEC3 %s (nseclist = 1)", CRDisplayString(m, newcr));
8160             *nseclist = mDNStrue;
8161             return mDNStrue;
8162         }
8163     }
8164     return mDNSfalse;
8165 }
8166 
8167 mDNSlocal void FreeNSECRecords(mDNS *const m, CacheRecord *NSECRecords)
8168 {
8169     CacheRecord *rp, *next;
8170 
8171     for (rp = NSECRecords; rp; rp = next)
8172     {
8173         next = rp->next;
8174         ReleaseCacheRecord(m, rp);
8175     }
8176 }
8177 
8178 // If we received zero DNSSEC records even when the DO/EDNS0 bit was set, we need to provide this
8179 // information to ValidatingResponse question to indicate the DNSSEC status to the application
8180 mDNSlocal void mDNSCoreReceiveNoDNSSECAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8181     mDNSIPPort dstport, const mDNSInterfaceID InterfaceID)
8182 {
8183     int i;
8184     const mDNSu8 *ptr = response->data;
8185 
8186     for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8187     {
8188         DNSQuestion pktq;
8189         DNSQuestion *qptr = mDNSNULL;
8190         ptr = getQuestion(response, ptr, end, InterfaceID, &pktq);
8191         if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &pktq, !dstaddr)) &&
8192             qptr->ValidatingResponse)
8193         {
8194             DNSQuestion *next, *q;
8195 
8196             if (qptr->DuplicateOf)
8197                 LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question matching response", qptr->qname.c, DNSTypeName(qptr->qtype));
8198 
8199             // Be careful to call the callback for duplicate questions first and then the original
8200             // question. If we called the callback on the original question, it could stop and
8201             // a duplicate question would become the original question.
8202             mDNS_DropLockBeforeCallback();      // Allow client (and us) to legally make mDNS API calls
8203             for (q = qptr->next ; q && q != m->NewQuestions; q = next)
8204             {
8205                 next = q->next;
8206                 if (q->DuplicateOf == qptr)
8207                 {
8208                     if (q->ValidatingResponse)
8209                         LogInfo("mDNSCoreReceiveNoDNSSECAnswers: qptr %##s (%s) Duplicate question found", q->qname.c, DNSTypeName(q->qtype));
8210                     else
8211                         LogMsg("mDNSCoreReceiveNoDNSSECAnswers: ERROR!! qptr %##s (%s) Duplicate question not ValidatingResponse", q->qname.c, DNSTypeName(q->qtype));
8212                     if (q->QuestionCallback)
8213                         q->QuestionCallback(m, q, mDNSNULL, QC_nodnssec);
8214                 }
8215             }
8216             if (qptr->QuestionCallback)
8217                 qptr->QuestionCallback(m, qptr, mDNSNULL, QC_nodnssec);
8218             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
8219         }
8220     }
8221 }
8222 
8223 mDNSlocal void mDNSCoreReceiveNoUnicastAnswers(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end, const mDNSAddr *dstaddr,
8224                                                mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, uDNS_LLQType LLQType, mDNSu8 rcode, CacheRecord *NSECRecords)
8225 {
8226     int i;
8227     const mDNSu8 *ptr   = response->data;
8228     CacheRecord *SOARecord = mDNSNULL;
8229 
8230     for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8231     {
8232         DNSQuestion q;
8233         DNSQuestion *qptr = mDNSNULL;
8234         ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8235         if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
8236         {
8237             CacheRecord *rr, *neg = mDNSNULL;
8238             mDNSu32 slot = HashSlot(&q.qname);
8239             CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
8240             for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8241                 if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
8242                 {
8243                     // 1. If we got a fresh answer to this query, then don't need to generate a negative entry
8244                     if (RRExpireTime(rr) - m->timenow > 0) break;
8245                     // 2. If we already had a negative entry, keep track of it so we can resurrect it instead of creating a new one
8246                     if (rr->resrec.RecordType == kDNSRecordTypePacketNegative) neg = rr;
8247                 }
8248             // When we're doing parallel unicast and multicast queries for dot-local names (for supporting Microsoft
8249             // Active Directory sites) we don't want to waste memory making negative cache entries for all the unicast answers.
8250             // Otherwise we just fill up our cache with negative entries for just about every single multicast name we ever look up
8251             // (since the Microsoft Active Directory server is going to assert that pretty much every single multicast name doesn't exist).
8252             // This is not only a waste of memory, but there's also the problem of those negative entries confusing us later -- e.g. we
8253             // suppress sending our mDNS query packet because we think we already have a valid (negative) answer to that query in our cache.
8254             // The one exception is that we *DO* want to make a negative cache entry for "local. SOA", for the (common) case where we're
8255             // *not* on a Microsoft Active Directory network, and there is no authoritative server for "local". Note that this is not
8256             // in conflict with the mDNS spec, because that spec says, "Multicast DNS Zones have no SOA record," so it's okay to cache
8257             // negative answers for "local. SOA" from a uDNS server, because the mDNS spec already says that such records do not exist :-)
8258             //
8259             // By suppressing negative responses, it might take longer to timeout a .local question as it might be expecting a
8260             // response e.g., we deliver a positive "A" response and suppress negative "AAAA" response and the upper layer may
8261             // be waiting longer to get the AAAA response before returning the "A" response to the application. To handle this
8262             // case without creating the negative cache entries, we generate a negative response and let the layer above us
8263             // do the appropriate thing. This negative response is also needed for appending new search domains.
8264             if (!InterfaceID && q.qtype != kDNSType_SOA && IsLocalDomain(&q.qname))
8265             {
8266                 if (!rr)
8267                 {
8268                     LogInfo("mDNSCoreReceiveNoUnicastAnswers: Generate negative response for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
8269                     m->CurrentQuestion = qptr;
8270                     // We are not creating a cache record in this case, we need to pass back
8271                     // the error we got so that the proxy code can return the right one to
8272                     // the application
8273                     if (qptr->ProxyQuestion)
8274                         qptr->responseFlags = response->h.flags;
8275                     GenerateNegativeResponse(m, QC_forceresponse);
8276                     m->CurrentQuestion = mDNSNULL;
8277                 }
8278                 else
8279                 {
8280                     LogInfo("mDNSCoreReceiveNoUnicastAnswers: Skipping check and not creating a negative cache entry for %##s (%s)", q.qname.c, DNSTypeName(q.qtype));
8281                 }
8282             }
8283             else
8284             {
8285                 if (!rr)
8286                 {
8287                     // We start off assuming a negative caching TTL of 60 seconds
8288                     // but then look to see if we can find an SOA authority record to tell us a better value we should be using
8289                     mDNSu32 negttl = 60;
8290                     int repeat = 0;
8291                     const domainname *name = &q.qname;
8292                     mDNSu32 hash = q.qnamehash;
8293 
8294                     // Special case for our special Microsoft Active Directory "local SOA" check.
8295                     // Some cheap home gateways don't include an SOA record in the authority section when
8296                     // they send negative responses, so we don't know how long to cache the negative result.
8297                     // Because we don't want to keep hitting the root name servers with our query to find
8298                     // if we're on a network using Microsoft Active Directory using "local" as a private
8299                     // internal top-level domain, we make sure to cache the negative result for at least one day.
8300                     if (q.qtype == kDNSType_SOA && SameDomainName(&q.qname, &localdomain)) negttl = 60 * 60 * 24;
8301 
8302                     // If we're going to make (or update) a negative entry, then look for the appropriate TTL from the SOA record
8303                     if (response->h.numAuthorities && (ptr = LocateAuthorities(response, end)) != mDNSNULL)
8304                     {
8305                         ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8306                         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_SOA)
8307                         {
8308                             const mDNSu32 s = HashSlot(m->rec.r.resrec.name);
8309                             CacheGroup *cgSOA = CacheGroupForRecord(m, s, &m->rec.r.resrec);
8310                             const rdataSOA *const soa = (const rdataSOA *)m->rec.r.resrec.rdata->u.data;
8311                             mDNSu32 ttl_s = soa->min;
8312                             // We use the lesser of the SOA.MIN field and the SOA record's TTL, *except*
8313                             // for the SOA record for ".", where the record is reported as non-cacheable
8314                             // (TTL zero) for some reason, so in this case we just take the SOA record's TTL as-is
8315                             if (ttl_s > m->rec.r.resrec.rroriginalttl && m->rec.r.resrec.name->c[0])
8316                                 ttl_s = m->rec.r.resrec.rroriginalttl;
8317                             if (negttl < ttl_s) negttl = ttl_s;
8318 
8319                             // Create the SOA record as we may have to return this to the questions
8320                             // that we are acting as a proxy for currently or in the future.
8321                             SOARecord = CreateNewCacheEntry(m, s, cgSOA, 1, mDNSfalse, mDNSNULL);
8322 
8323                             // Special check for SOA queries: If we queried for a.b.c.d.com, and got no answer,
8324                             // with an Authority Section SOA record for d.com, then this is a hint that the authority
8325                             // is d.com, and consequently SOA records b.c.d.com and c.d.com don't exist either.
8326                             // To do this we set the repeat count so the while loop below will make a series of negative cache entries for us
8327                             //
8328                             // For ProxyQuestions, we don't do this as we need to create additional SOA records to cache them
8329                             // along with the negative cache record. For simplicity, we don't create the additional records.
8330                             if (!qptr->ProxyQuestion && q.qtype == kDNSType_SOA)
8331                             {
8332                                 int qcount = CountLabels(&q.qname);
8333                                 int scount = CountLabels(m->rec.r.resrec.name);
8334                                 if (qcount - 1 > scount)
8335                                     if (SameDomainName(SkipLeadingLabels(&q.qname, qcount - scount), m->rec.r.resrec.name))
8336                                         repeat = qcount - 1 - scount;
8337                             }
8338                         }
8339                         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8340                     }
8341 
8342                     // If we already had a negative entry in the cache, then we double our existing negative TTL. This is to avoid
8343                     // the case where the record doesn't exist (e.g. particularly for things like our lb._dns-sd._udp.<domain> query),
8344                     // and the server returns no SOA record (or an SOA record with a small MIN TTL) so we assume a TTL
8345                     // of 60 seconds, and we end up polling the server every minute for a record that doesn't exist.
8346                     // With this fix in place, when this happens, we double the effective TTL each time (up to one hour),
8347                     // so that we back off our polling rate and don't keep hitting the server continually.
8348                     if (neg)
8349                     {
8350                         if (negttl < neg->resrec.rroriginalttl * 2)
8351                             negttl = neg->resrec.rroriginalttl * 2;
8352                         if (negttl > 3600)
8353                             negttl = 3600;
8354                     }
8355 
8356                     negttl = GetEffectiveTTL(LLQType, negttl);  // Add 25% grace period if necessary
8357 
8358                     // If we already had a negative cache entry just update it, else make one or more new negative cache entries.
8359                     if (neg)
8360                     {
8361                         LogInfo("mDNSCoreReceiveNoUnicastAnswers: Renewing negative TTL from %d to %d %s", neg->resrec.rroriginalttl, negttl, CRDisplayString(m, neg));
8362                         RefreshCacheRecord(m, neg, negttl);
8363                         // When we created the cache for the first time and answered the question, the question's
8364                         // interval was set to MaxQuestionInterval. If the cache is about to expire and we are resending
8365                         // the queries, the interval should still be at MaxQuestionInterval. If the query is being
8366                         // restarted (setting it to InitialQuestionInterval) for other reasons e.g., wakeup,
8367                         // we should reset its question interval here to MaxQuestionInterval.
8368                         ResetQuestionState(m, qptr);
8369                         if (DNSSECQuestion(qptr))
8370                             neg->CRDNSSECQuestion = 1;
8371                         // Update the NSEC records again.
8372                         // TBD: Need to purge and revalidate if the cached NSECS and the new set are not same.
8373                         if (NSECRecords)
8374                         {
8375                             if (!AddNSECSForCacheRecord(m, NSECRecords, neg, rcode))
8376                             {
8377                                 // We might just have an SOA record for zones that are not signed and hence don't log
8378                                 // this as an error
8379                                 LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s during refresh", CRDisplayString(m, neg));
8380                                 FreeNSECRecords(m, NSECRecords);
8381                                 neg->CRDNSSECQuestion = 0;
8382                             }
8383                             NSECRecords = mDNSNULL;
8384                         }
8385                         if (SOARecord)
8386                         {
8387                             if (neg->soa)
8388                                 ReleaseCacheRecord(m, neg->soa);
8389                             neg->soa = SOARecord;
8390                             SOARecord = mDNSNULL;
8391                         }
8392                     }
8393                     else while (1)
8394                         {
8395                             CacheRecord *negcr;
8396                             debugf("mDNSCoreReceiveNoUnicastAnswers making negative cache entry TTL %d for %##s (%s)", negttl, name->c, DNSTypeName(q.qtype));
8397                             MakeNegativeCacheRecord(m, &m->rec.r, name, hash, q.qtype, q.qclass, negttl, mDNSInterface_Any, qptr->qDNSServer);
8398                             m->rec.r.responseFlags = response->h.flags;
8399                             // We create SOA records above which might create new cache groups. Earlier
8400                             // in the function we looked up the cache group for the name and it could have
8401                             // been NULL. If we pass NULL cg to new cache entries that we create below,
8402                             // it will create additional cache groups for the same name. To avoid that,
8403                             // look up the cache group again to re-initialize cg again.
8404                             cg = CacheGroupForName(m, slot, hash, name);
8405                             if (NSECRecords && DNSSECQuestion(qptr))
8406                             {
8407                                 // Create the cache entry with delay and then add the NSEC records
8408                                 // to it and add it immediately.
8409                                 negcr = CreateNewCacheEntry(m, slot, cg, 1, mDNStrue, mDNSNULL);
8410                                 if (negcr)
8411                                 {
8412                                     negcr->CRDNSSECQuestion = 0;
8413                                     if (!AddNSECSForCacheRecord(m, NSECRecords, negcr, rcode))
8414                                     {
8415                                         LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord failed to add NSEC for negcr %s",
8416                                             CRDisplayString(m, negcr));
8417                                         FreeNSECRecords(m, NSECRecords);
8418                                     }
8419                                     else
8420                                     {
8421                                         negcr->CRDNSSECQuestion = 1;
8422                                         LogInfo("mDNSCoreReceiveNoUnicastAnswers: AddNSECSForCacheRecord added neg NSEC for %s", CRDisplayString(m, negcr));
8423                                     }
8424                                     NSECRecords = mDNSNULL;
8425                                     negcr->DelayDelivery = 0;
8426                                     CacheRecordDeferredAdd(m, negcr);
8427                                 }
8428                                 m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8429                                 break;
8430                             }
8431                             else
8432                             {
8433                                 // Need to add with a delay so that we can tag the SOA record
8434                                 negcr = CreateNewCacheEntry(m, slot, cg, 1, mDNStrue, mDNSNULL);
8435                                 if (negcr)
8436                                 {
8437                                     negcr->CRDNSSECQuestion = 0;
8438                                     if (DNSSECQuestion(qptr))
8439                                         negcr->CRDNSSECQuestion = 1;
8440                                     negcr->DelayDelivery = 0;
8441 
8442                                     if (SOARecord)
8443                                     {
8444                                         if (negcr->soa)
8445                                             ReleaseCacheRecord(m, negcr->soa);
8446                                         negcr->soa = SOARecord;
8447                                         SOARecord = mDNSNULL;
8448                                     }
8449                                     CacheRecordDeferredAdd(m, negcr);
8450                                 }
8451                             }
8452                             m->rec.r.responseFlags = zeroID;
8453                             m->rec.r.resrec.RecordType = 0; // Clear RecordType to show we're not still using it
8454                             if (!repeat) break;
8455                             repeat--;
8456                             name = (const domainname *)(name->c + 1 + name->c[0]);
8457                             hash = DomainNameHashValue(name);
8458                             slot = HashSlot(name);
8459 							// For now, we don't need to update cg here, because we'll do it again immediately, back up at the start of this loop
8460                             //cg   = CacheGroupForName(m, slot, hash, name);
8461                         }
8462                 }
8463             }
8464         }
8465     }
8466     if (NSECRecords) { LogInfo("mDNSCoreReceiveNoUnicastAnswers: NSECRecords not used"); FreeNSECRecords(m, NSECRecords); }
8467     if (SOARecord)   { LogInfo("mDNSCoreReceiveNoUnicastAnswers: SOARecord not used"); ReleaseCacheRecord(m, SOARecord); }
8468 }
8469 
8470 mDNSlocal void mDNSCorePrintStoredProxyRecords(mDNS *const m)
8471 {
8472     AuthRecord *rrPtr = mDNSNULL;
8473     LogSPS("Stored Proxy records :");
8474     for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8475     {
8476         LogSPS("%s", ARDisplayString(m, rrPtr));
8477     }
8478 }
8479 
8480 mDNSlocal mDNSBool mDNSCoreRegisteredProxyRecord(mDNS *const m, AuthRecord *rr)
8481 {
8482     AuthRecord *rrPtr = mDNSNULL;
8483 
8484     for (rrPtr = m->SPSRRSet; rrPtr; rrPtr = rrPtr->next)
8485     {
8486         if (IdenticalResourceRecord(&rrPtr->resrec, &rr->resrec))
8487         {
8488             LogSPS("mDNSCoreRegisteredProxyRecord: Ignoring packet registered with sleep proxy : %s ", ARDisplayString(m, rr));
8489             return mDNStrue;
8490         }
8491     }
8492     mDNSCorePrintStoredProxyRecords(m);
8493     return mDNSfalse;
8494 }
8495 
8496 mDNSlocal CacheRecord* mDNSCoreReceiveCacheCheck(mDNS *const m, const DNSMessage *const response, uDNS_LLQType LLQType,
8497     const mDNSu32 slot, CacheGroup *cg, DNSQuestion *unicastQuestion, CacheRecord ***cfp, CacheRecord **NSECCachePtr,
8498     mDNSInterfaceID InterfaceID)
8499 {
8500     CacheRecord *rr;
8501     CacheRecord **cflocal = *cfp;
8502 
8503     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8504     {
8505         mDNSBool match;
8506         // Resource record received via unicast, the resGroupID should match ?
8507         if (!InterfaceID)
8508         {
8509             mDNSu16 id1 = (rr->resrec.rDNSServer ? rr->resrec.rDNSServer->resGroupID : 0);
8510             mDNSu16 id2 = (m->rec.r.resrec.rDNSServer ? m->rec.r.resrec.rDNSServer->resGroupID : 0);
8511             match = (id1 == id2);
8512         }
8513         else
8514             match = (rr->resrec.InterfaceID == InterfaceID);
8515         // If we found this exact resource record, refresh its TTL
8516         if (match && IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
8517         {
8518             if (m->rec.r.resrec.rdlength > InlineCacheRDSize)
8519                 verbosedebugf("mDNSCoreReceiveCacheCheck: Found record size %5d interface %p already in cache: %s",
8520                               m->rec.r.resrec.rdlength, InterfaceID, CRDisplayString(m, &m->rec.r));
8521 
8522             if (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8523             {
8524                 // If this packet record has the kDNSClass_UniqueRRSet flag set, then add it to our cache flushing list
8525                 if (rr->NextInCFList == mDNSNULL && *cfp != &rr->NextInCFList && LLQType != uDNS_LLQ_Events)
8526                 {
8527                     *cflocal = rr;
8528                     cflocal = &rr->NextInCFList;
8529                     *cflocal = (CacheRecord*)1;
8530                     *cfp = &rr->NextInCFList;
8531                 }
8532 
8533                 // If this packet record is marked unique, and our previous cached copy was not, then fix it
8534                 if (!(rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask))
8535                 {
8536                     DNSQuestion *q;
8537                     for (q = m->Questions; q; q=q->next)
8538                     {
8539                         if (ResourceRecordAnswersQuestion(&rr->resrec, q))
8540                             q->UniqueAnswers++;
8541                     }
8542                     rr->resrec.RecordType = m->rec.r.resrec.RecordType;
8543                 }
8544             }
8545 
8546             if (!SameRDataBody(&m->rec.r.resrec, &rr->resrec.rdata->u, SameDomainNameCS))
8547             {
8548                 // If the rdata of the packet record differs in name capitalization from the record in our cache
8549                 // then mDNSPlatformMemSame will detect this. In this case, throw the old record away, so that clients get
8550                 // a 'remove' event for the record with the old capitalization, and then an 'add' event for the new one.
8551                 // <rdar://problem/4015377> mDNS -F returns the same domain multiple times with different casing
8552                 rr->resrec.rroriginalttl = 0;
8553                 rr->TimeRcvd = m->timenow;
8554                 rr->UnansweredQueries = MaxUnansweredQueries;
8555                 SetNextCacheCheckTimeForRecord(m, rr);
8556                 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change old: %s", CRDisplayString(m, rr));
8557                 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change new: %s", CRDisplayString(m, &m->rec.r));
8558                 LogInfo("mDNSCoreReceiveCacheCheck: Discarding due to domainname case change in %d slot %3d in %d %d",
8559                         NextCacheCheckEvent(rr) - m->timenow, slot, m->rrcache_nextcheck[slot] - m->timenow, m->NextCacheCheck - m->timenow);
8560                 // DO NOT break out here -- we want to continue as if we never found it
8561             }
8562             else if (!IdenticalAnonInfo(m->rec.r.resrec.AnonInfo, rr->resrec.AnonInfo))
8563             {
8564                 // If the NSEC3 record changed, a few possibilities
8565                 //
8566                 // 1) the peer reinitialized e.g., after network change and still part of the
8567                 //    same set.
8568                 // 2) the peer went to a different set but we did not see the goodbyes. If we just
8569                 //    update the nsec3 record, it would be incorrect. Flush the cache so that we
8570                 //    can deliver a RMV followed by ADD.
8571                 // 3) if the peer is ourselves and we see the goodbye when moving to a different set
8572                 //    and so we flush the cache and create a new cache record with the new set information.
8573                 //    Now we move back to the original set. In this case, we can't just update the
8574                 //    NSEC3 record alone. We need to flush so that we can deliver an RMV followed by ADD
8575                 //    when we create the new cache entry.
8576                 //
8577                 // Note: For case (1), we could avoid flushing the cache but we can't tell the difference
8578                 // from the other cases.
8579                 rr->resrec.rroriginalttl = 0;
8580                 rr->TimeRcvd = m->timenow;
8581                 rr->UnansweredQueries = MaxUnansweredQueries;
8582                 SetNextCacheCheckTimeForRecord(m, rr);
8583                 LogInfo("mDNSCoreReceiveCacheCheck: AnonInfo changed for %s", CRDisplayString(m, rr));
8584                 // DO NOT break out here -- we want to continue as if we never found it. When we return
8585                 // from this function, we will create a new cache entry with the new NSEC3 record
8586             }
8587             else if (m->rec.r.resrec.rroriginalttl > 0)
8588             {
8589                 DNSQuestion *q;
8590 
8591                 m->mDNSStats.CacheRefreshed++;
8592 
8593                 if (rr->resrec.rroriginalttl == 0) debugf("uDNS rescuing %s", CRDisplayString(m, rr));
8594                 RefreshCacheRecord(m, rr, m->rec.r.resrec.rroriginalttl);
8595                 rr->responseFlags = response->h.flags;
8596 
8597                 // If we may have NSEC records returned with the answer (which we don't know yet as it
8598                 // has not been processed), we need to cache them along with the first cache
8599                 // record in the list that answers the question so that it can be used for validation
8600                 // later. The "type" check below is to make sure that we cache on the cache record
8601                 // that would answer the question. It is possible that we might cache additional things
8602                 // e.g., MX question might cache A records also, and we want to cache the NSEC on
8603                 // the record that answers the question.
8604                 if (response->h.numAnswers && unicastQuestion && unicastQuestion->qtype == rr->resrec.rrtype
8605                     && !(*NSECCachePtr))
8606                 {
8607                     LogInfo("mDNSCoreReceiveCacheCheck: rescuing RR %s", CRDisplayString(m, rr));
8608                     *NSECCachePtr = rr;
8609                 }
8610                 // We have to reset the question interval to MaxQuestionInterval so that we don't keep
8611                 // polling the network once we get a valid response back. For the first time when a new
8612                 // cache entry is created, AnswerCurrentQuestionWithResourceRecord does that.
8613                 // Subsequently, if we reissue questions from within the mDNSResponder e.g., DNS server
8614                 // configuration changed, without flushing the cache, we reset the question interval here.
8615                 // Currently, we do this for for both multicast and unicast questions as long as the record
8616                 // type is unique. For unicast, resource record is always unique and for multicast it is
8617                 // true for records like A etc. but not for PTR.
8618                 if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask)
8619                 {
8620                     for (q = m->Questions; q; q=q->next)
8621                     {
8622                         if (!q->DuplicateOf && !q->LongLived &&
8623                             ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
8624                         {
8625                             ResetQuestionState(m, q);
8626                             debugf("mDNSCoreReceiveCacheCheck: Set MaxQuestionInterval for %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
8627                             break;      // Why break here? Aren't there other questions we might want to look at?-- SC July 2010
8628                         }
8629                     }
8630                 }
8631                 break;
8632             }
8633             else
8634             {
8635 
8636                 // If the packet TTL is zero, that means we're deleting this record.
8637                 // To give other hosts on the network a chance to protest, we push the deletion
8638                 // out one second into the future. Also, we set UnansweredQueries to MaxUnansweredQueries.
8639                 // Otherwise, we'll do final queries for this record at 80% and 90% of its apparent
8640                 // lifetime (800ms and 900ms from now) which is a pointless waste of network bandwidth.
8641                 // If record's current expiry time is more than a second from now, we set it to expire in one second.
8642                 // If the record is already going to expire in less than one second anyway, we leave it alone --
8643                 // we don't want to let the goodbye packet *extend* the record's lifetime in our cache.
8644                 debugf("DE for %s", CRDisplayString(m, rr));
8645                 if (RRExpireTime(rr) - m->timenow > mDNSPlatformOneSecond)
8646                 {
8647                     rr->resrec.rroriginalttl = 1;
8648                     rr->TimeRcvd = m->timenow;
8649                     rr->UnansweredQueries = MaxUnansweredQueries;
8650                     SetNextCacheCheckTimeForRecord(m, rr);
8651                 }
8652                 break;
8653             }
8654         }
8655     }
8656     return rr;
8657 }
8658 
8659 mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
8660     const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records)
8661 {
8662     const mDNSu8 *ptr;
8663     CacheRecord *rr;
8664     int i;
8665 
8666     if (!response->h.numAuthorities)
8667         return;
8668     ptr = LocateAuthorities(response, end);
8669     if (!ptr)
8670     {
8671         LogInfo("mDNSParseNSEC3Records: ERROR can't locate authorities");
8672         return;
8673     }
8674     for (i = 0; i < response->h.numAuthorities && ptr && ptr < end; i++)
8675     {
8676         mDNSu32 slot;
8677         CacheGroup *cg;
8678 
8679         ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
8680         if (!ptr || m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative || m->rec.r.resrec.rrtype != kDNSType_NSEC3)
8681         {
8682             debugf("mDNSParseNSEC3Records: ptr %p, Record %s, ignoring", ptr, CRDisplayString(m, &m->rec.r));
8683             m->rec.r.resrec.RecordType = 0;
8684             continue;
8685         }
8686         slot = HashSlot(m->rec.r.resrec.name);
8687         cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
8688         // Create the cache entry but don't add it to the cache it. We need
8689         // to cache this along with the main cache record.
8690         rr = CreateNewCacheEntry(m, slot, cg, 0, mDNSfalse, mDNSNULL);
8691         if (rr)
8692         {
8693             debugf("mDNSParseNSEC3Records: %s", CRDisplayString(m, rr));
8694             *NSEC3Records = rr;
8695             NSEC3Records = &rr->next;
8696         }
8697         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8698     }
8699 }
8700 
8701 mDNSlocal void mDNSCoreResetRecord(mDNS *const m)
8702 {
8703     m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
8704     if (m->rec.r.resrec.AnonInfo)
8705     {
8706         FreeAnonInfo(m->rec.r.resrec.AnonInfo);
8707         m->rec.r.resrec.AnonInfo = mDNSNULL;
8708     }
8709 }
8710 
8711 // Note: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
8712 // the record list and/or question list.
8713 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
8714 // InterfaceID non-NULL tells us the interface this multicast response was received on
8715 // InterfaceID NULL tells us this was a unicast response
8716 // dstaddr NULL tells us we received this over an outgoing TCP connection we made
8717 mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
8718                                        const DNSMessage *const response, const mDNSu8 *end,
8719                                        const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
8720                                        const mDNSInterfaceID InterfaceID)
8721 {
8722     int i;
8723     mDNSBool ResponseMCast    = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
8724     mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
8725     DNSQuestion *llqMatch = mDNSNULL;
8726     DNSQuestion *unicastQuestion = mDNSNULL;
8727     uDNS_LLQType LLQType      = uDNS_recvLLQResponse(m, response, end, srcaddr, srcport, &llqMatch);
8728 
8729     // "(CacheRecord*)1" is a special (non-zero) end-of-list marker
8730     // We use this non-zero marker so that records in our CacheFlushRecords list will always have NextInCFList
8731     // set non-zero, and that tells GetCacheEntity() that they're not, at this moment, eligible for recycling.
8732     CacheRecord *CacheFlushRecords = (CacheRecord*)1;
8733     CacheRecord **cfp = &CacheFlushRecords;
8734     CacheRecord *NSECRecords = mDNSNULL;
8735     CacheRecord *NSECCachePtr = mDNSNULL;
8736     CacheRecord **nsecp = &NSECRecords;
8737     CacheRecord *McastNSEC3Records = mDNSNULL;
8738     mDNSBool nseclist;
8739     mDNSu8 rcode = '\0';
8740     mDNSBool rrsigsCreated = mDNSfalse;
8741     mDNSBool DNSSECQuestion = mDNSfalse;
8742     NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
8743 
8744     // All records in a DNS response packet are treated as equally valid statements of truth. If we want
8745     // to guard against spoof responses, then the only credible protection against that is cryptographic
8746     // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
8747     int firstauthority  =                   response->h.numAnswers;
8748     int firstadditional = firstauthority  + response->h.numAuthorities;
8749     int totalrecords    = firstadditional + response->h.numAdditionals;
8750     const mDNSu8 *ptr   = response->data;
8751     DNSServer *uDNSServer = mDNSNULL;
8752 
8753     debugf("Received Response from %#-15a addressed to %#-15a on %p with "
8754            "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes LLQType %d",
8755            srcaddr, dstaddr, InterfaceID,
8756            response->h.numQuestions,   response->h.numQuestions   == 1 ? ", "   : "s,",
8757            response->h.numAnswers,     response->h.numAnswers     == 1 ? ", "   : "s,",
8758            response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
8759            response->h.numAdditionals, response->h.numAdditionals == 1 ? " "    : "s", end - response->data, LLQType);
8760 
8761     // According to RFC 2181 <http://www.ietf.org/rfc/rfc2181.txt>
8762     //    When a DNS client receives a reply with TC
8763     //    set, it should ignore that response, and query again, using a
8764     //    mechanism, such as a TCP connection, that will permit larger replies.
8765     // It feels wrong to be throwing away data after the network went to all the trouble of delivering it to us, but
8766     // delivering some records of the RRSet first and then the remainder a couple of milliseconds later was causing
8767     // failures in our Microsoft Active Directory client, which expects to get the entire set of answers at once.
8768     // <rdar://problem/6690034> Can't bind to Active Directory
8769     // In addition, if the client immediately canceled its query after getting the initial partial response, then we'll
8770     // abort our TCP connection, and not complete the operation, and end up with an incomplete RRSet in our cache.
8771     // Next time there's a query for this RRSet we'll see answers in our cache, and assume we have the whole RRSet already,
8772     // and not even do the TCP query.
8773     // Accordingly, if we get a uDNS reply with kDNSFlag0_TC set, we bail out and wait for the TCP response containing the entire RRSet.
8774     if (!InterfaceID && (response->h.flags.b[0] & kDNSFlag0_TC)) return;
8775 
8776     if (LLQType == uDNS_LLQ_Ignore) return;
8777 
8778     // 1. We ignore questions (if any) in mDNS response packets
8779     // 2. If this is an LLQ response, we handle it much the same
8780     // 3. If we get a uDNS UDP response with the TC (truncated) bit set, then we can't treat this
8781     //    answer as being the authoritative complete RRSet, and respond by deleting all other
8782     //    matching cache records that don't appear in this packet.
8783     // Otherwise, this is a authoritative uDNS answer, so arrange for any stale records to be purged
8784     if (ResponseMCast || LLQType == uDNS_LLQ_Events || (response->h.flags.b[0] & kDNSFlag0_TC))
8785         ptr = LocateAnswers(response, end);
8786     // Otherwise, for one-shot queries, any answers in our cache that are not also contained
8787     // in this response packet are immediately deemed to be invalid.
8788     else
8789     {
8790         mDNSBool failure, returnEarly;
8791         rcode = (mDNSu8)(response->h.flags.b[1] & kDNSFlag1_RC_Mask);
8792         failure = !(rcode == kDNSFlag1_RC_NoErr || rcode == kDNSFlag1_RC_NXDomain || rcode == kDNSFlag1_RC_NotAuth);
8793         returnEarly = mDNSfalse;
8794         // We could possibly combine this with the similar loop at the end of this function --
8795         // instead of tagging cache records here and then rescuing them if we find them in the answer section,
8796         // we could instead use the "m->PktNum" mechanism to tag each cache record with the packet number in
8797         // which it was received (or refreshed), and then at the end if we find any cache records which
8798         // answer questions in this packet's question section, but which aren't tagged with this packet's
8799         // packet number, then we deduce they are old and delete them
8800         for (i = 0; i < response->h.numQuestions && ptr && ptr < end; i++)
8801         {
8802             DNSQuestion q, *qptr = mDNSNULL;
8803             ptr = getQuestion(response, ptr, end, InterfaceID, &q);
8804             if (ptr && (qptr = ExpectingUnicastResponseForQuestion(m, dstport, response->h.id, &q, !dstaddr)))
8805             {
8806                 if (!failure)
8807                 {
8808                     CacheRecord *rr;
8809                     // Remember the unicast question that we found, which we use to make caching
8810                     // decisions later on in this function
8811                     const mDNSu32 slot = HashSlot(&q.qname);
8812                     CacheGroup *cg = CacheGroupForName(m, slot, q.qnamehash, &q.qname);
8813                     if (!mDNSOpaque16IsZero(response->h.id))
8814                     {
8815                         unicastQuestion = qptr;
8816                         if (qptr->qDNSServer && DNSSECQuestion(qptr))
8817                         {
8818                             LogInfo("mDNSCoreReceiveResponse: Setting aware for %##s (%s) on %#a", qptr->qname.c,
8819                                 DNSTypeName(qptr->qtype), &qptr->qDNSServer->addr);
8820                             qptr->qDNSServer->DNSSECAware = mDNStrue;
8821                             qptr->qDNSServer->req_DO = mDNStrue;
8822                         }
8823                         if (qptr->ValidatingResponse)
8824                             DNSSECQuestion = mDNStrue;
8825                     }
8826                     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
8827                         if (SameNameRecordAnswersQuestion(&rr->resrec, qptr))
8828                         {
8829                             debugf("uDNS marking %p %##s (%s) %p %s", q.InterfaceID, q.qname.c, DNSTypeName(q.qtype),
8830                                    rr->resrec.InterfaceID, CRDisplayString(m, rr));
8831                             // Don't want to disturb rroriginalttl here, because code below might need it for the exponential backoff doubling algorithm
8832                             rr->TimeRcvd          = m->timenow - TicksTTL(rr) - 1;
8833                             rr->UnansweredQueries = MaxUnansweredQueries;
8834                             rr->CRDNSSECQuestion = 0;
8835                             if (unicastQuestion && DNSSECQuestion(unicastQuestion))
8836                             {
8837                                 LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for record %s, question %##s (%s)", CRDisplayString(m, rr),
8838                                     unicastQuestion->qname.c, DNSTypeName(unicastQuestion->qtype));
8839                                 rr->CRDNSSECQuestion = 1;
8840                             }
8841                         }
8842                 }
8843                 else
8844                 {
8845                     if (qptr)
8846                     {
8847                         // If we recv any error from the DNSServer for a DNSSEC Query and if we know that the server
8848                         // is not DNSSEC aware, stop doing DNSSEC for that DNSServer. Note that by setting the
8849                         // req_DO to false here, the next retransmission for this question will turn off validation
8850                         // and hence retransmit without the EDNS0/DOK option.
8851                         if (DNSSECOptionalQuestion(qptr) && qptr->qDNSServer && !qptr->qDNSServer->DNSSECAware)
8852                         {
8853                             LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to DNSSEC Query %##s (%s), clear DO flag",
8854                                     qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
8855                             qptr->qDNSServer->req_DO = mDNSfalse;
8856                         }
8857                         // For Unicast DNS Queries, penalize the DNSServer
8858                         else
8859                         {
8860                             LogInfo("mDNSCoreReceiveResponse: Server %p responded with code %d to query %##s (%s)",
8861                                     qptr->qDNSServer, rcode, q.qname.c, DNSTypeName(q.qtype));
8862                             PenalizeDNSServer(m, qptr, response->h.flags);
8863                         }
8864                     }
8865                     returnEarly = mDNStrue;
8866                 }
8867             }
8868         }
8869         if (returnEarly)
8870         {
8871             LogInfo("Ignoring %2d Answer%s %2d Authorit%s %2d Additional%s",
8872                     response->h.numAnswers,     response->h.numAnswers     == 1 ? ", " : "s,",
8873                     response->h.numAuthorities, response->h.numAuthorities == 1 ? "y,  " : "ies,",
8874                     response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
8875             // not goto exit because we won't have any CacheFlushRecords and we do not want to
8876             // generate negative cache entries (we want to query the next server)
8877             return;
8878         }
8879         if (unicastQuestion && DNSSECQuestion(unicastQuestion))
8880         {
8881             BumpDNSSECStats(m, kStatsActionSet, kStatsTypeMsgSize, (end - response->data));
8882         }
8883     }
8884 
8885     // Parse the NSEC3 records from the Authority section before we process
8886     // the Answer section so that we can cache them along with the proper
8887     // cache records we create.
8888     if (mDNSOpaque16IsZero(response->h.id))
8889         mDNSParseNSEC3Records(m, response, end, InterfaceID, &McastNSEC3Records);
8890 
8891     for (i = 0; i < totalrecords && ptr && ptr < end; i++)
8892     {
8893         // All responses sent via LL multicast are acceptable for caching
8894         // All responses received over our outbound TCP connections are acceptable for caching
8895         mDNSBool AcceptableResponse = ResponseMCast || !dstaddr || LLQType;
8896         // (Note that just because we are willing to cache something, that doesn't necessarily make it a trustworthy answer
8897         // to any specific question -- any code reading records from the cache needs to make that determination for itself.)
8898 
8899         const mDNSu8 RecordType =
8900             (i < firstauthority ) ? (mDNSu8)kDNSRecordTypePacketAns  :
8901             (i < firstadditional) ? (mDNSu8)kDNSRecordTypePacketAuth : (mDNSu8)kDNSRecordTypePacketAdd;
8902         ptr = GetLargeResourceRecord(m, response, ptr, end, InterfaceID, RecordType, &m->rec);
8903         if (!ptr) goto exit;        // Break out of the loop and clean up our CacheFlushRecords list before exiting
8904 
8905         if (m->rec.r.resrec.RecordType == kDNSRecordTypePacketNegative)
8906         {
8907             mDNSCoreResetRecord(m);
8908             continue;
8909         }
8910 
8911         // We have already parsed the NSEC3 records and cached them approrpriately for
8912         // multicast responses.
8913         if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype == kDNSType_NSEC3)
8914         {
8915             mDNSCoreResetRecord(m);
8916             continue;
8917         }
8918         // Don't want to cache OPT or TSIG pseudo-RRs
8919         if (m->rec.r.resrec.rrtype == kDNSType_TSIG)
8920         {
8921             mDNSCoreResetRecord(m);
8922             continue;
8923         }
8924         if (m->rec.r.resrec.rrtype == kDNSType_OPT)
8925         {
8926             const rdataOPT *opt;
8927             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
8928             // Find owner sub-option(s). We verify that the MAC is non-zero, otherwise we could inadvertently
8929             // delete all our own AuthRecords (which are identified by having zero MAC tags on them).
8930             for (opt = &m->rec.r.resrec.rdata->u.opt[0]; opt < e; opt++)
8931                 if (opt->opt == kDNSOpt_Owner && opt->u.owner.vers == 0 && opt->u.owner.HMAC.l[0])
8932                 {
8933                     ClearProxyRecords(m, &opt->u.owner, m->DuplicateRecords);
8934                     ClearProxyRecords(m, &opt->u.owner, m->ResourceRecords);
8935                 }
8936             mDNSCoreResetRecord(m);
8937             continue;
8938         }
8939         // if a CNAME record points to itself, then don't add it to the cache
8940         if ((m->rec.r.resrec.rrtype == kDNSType_CNAME) && SameDomainName(m->rec.r.resrec.name, &m->rec.r.resrec.rdata->u.name))
8941         {
8942             LogInfo("mDNSCoreReceiveResponse: CNAME loop domain name %##s", m->rec.r.resrec.name->c);
8943             mDNSCoreResetRecord(m);
8944             continue;
8945         }
8946 
8947         // When we receive uDNS LLQ responses, we assume a long cache lifetime --
8948         // In the case of active LLQs, we'll get remove events when the records actually do go away
8949         // In the case of polling LLQs, we assume the record remains valid until the next poll
8950         if (!mDNSOpaque16IsZero(response->h.id))
8951             m->rec.r.resrec.rroriginalttl = GetEffectiveTTL(LLQType, m->rec.r.resrec.rroriginalttl);
8952 
8953         // If response was not sent via LL multicast,
8954         // then see if it answers a recent query of ours, which would also make it acceptable for caching.
8955         if (!ResponseMCast)
8956         {
8957             if (LLQType)
8958             {
8959                 // For Long Lived queries that are both sent over UDP and Private TCP, LLQType is set.
8960                 // Even though it is AcceptableResponse, we need a matching DNSServer pointer for the
8961                 // queries to get ADD/RMV events. To lookup the question, we can't use
8962                 // ExpectingUnicastResponseForRecord as the port numbers don't match. uDNS_recvLLQRespose
8963                 // has already matched the question using the 64 bit Id in the packet and we use that here.
8964 
8965                 if (llqMatch != mDNSNULL) m->rec.r.resrec.rDNSServer = uDNSServer = llqMatch->qDNSServer;
8966 
8967                 // If this is a DNSSEC question that is also LongLived, don't accept records from the
8968                 // Additional/Authority section blindly. We need to go through IsAcceptableResponse below
8969                 // so that NSEC/NSEC3 record are cached in the nseclist if we accept them. This can happen
8970                 // for both negative responses and wildcard expanded positive responses as both of come
8971                 // back with NSEC/NSEC3s.
8972                 if (unicastQuestion && DNSSECQuestion(unicastQuestion))
8973                     AcceptableResponse = mDNSfalse;
8974             }
8975             else if (!AcceptableResponse || !dstaddr)
8976             {
8977                 // For responses that come over TCP (Responses that can't fit within UDP) or TLS (Private queries
8978                 // that are not long lived e.g., AAAA lookup in a Private domain), it is indicated by !dstaddr.
8979                 // Even though it is AcceptableResponse, we still need a DNSServer pointer for the resource records that
8980                 // we create.
8981 
8982 				DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
8983 
8984 				// Initialize the DNS server on the resource record which will now filter what questions we answer with
8985 				// this record.
8986 				//
8987 				// We could potentially lookup the DNS server based on the source address, but that may not work always
8988 				// and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
8989 				// from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
8990 				// on the "id" and "source port", then this response answers the question and assume the response
8991 				// came from the same DNS server that we sent the query to.
8992 
8993 				if (q != mDNSNULL)
8994 				{
8995 					AcceptableResponse = mDNStrue;
8996 					if (!InterfaceID)
8997 					{
8998 						debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
8999 						m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
9000 					}
9001 					else
9002 						LogInfo("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
9003 				}
9004 				else
9005 				{
9006 					// If we can't find a matching question, we need to see whether we have seen records earlier that matched
9007 					// the question. The code below does that. So, make this record unacceptable for now
9008 					if (!InterfaceID)
9009 					{
9010 						debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
9011 						AcceptableResponse = mDNSfalse;
9012 					}
9013 				}
9014             }
9015         }
9016         else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
9017         {
9018             // There are some routers (rare, thankfully) that generate bogus ARP responses for
9019             // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
9020             // To work with these broken routers, client devices need to blacklist these broken
9021             // routers and ignore their bogus ARP responses. Some devices implement a technique
9022             // such as the one described in US Patent 7436783, which lets clients detect and
9023             // ignore these broken routers: <https://www.google.com/patents/US7436783>
9024 
9025             // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
9026             // approach of just detecting these broken routers and completely disabling IPv4
9027             // link-local communication on interfaces where a broken router is detected.
9028             // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
9029             // that are deemed “safe” for IPv4 link-local communication;
9030             // the flag is cleared on interfaces where a broken router is detected.
9031 
9032             // OS X and iOS will not even try to communicate with an IPv4
9033             // link-local destination on an interface without the IFEF_ARPLL flag set.
9034             // This can cause some badly written applications to freeze for a long time if they
9035             // attempt to connect to an IPv4 link-local destination address and then wait for
9036             // that connection attempt to time out before trying other candidate addresses.
9037 
9038             // To mask this client bug, we suppress acceptance of IPv4 link-local address
9039             // records on interfaces where we know the OS will be unwilling even to attempt
9040             // communication with those IPv4 link-local destination addresses.
9041             // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
9042 
9043             const CacheRecord *const rr = &m->rec.r;
9044             const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
9045             if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
9046             {
9047                 LogInfo("mDNSResponder: Dropping LinkLocal packet %s", CRDisplayString(m, &m->rec.r));
9048                 mDNSCoreResetRecord(m);
9049                 continue;
9050             }
9051         }
9052 
9053         // 1. Check that this packet resource record does not conflict with any of ours
9054         if (mDNSOpaque16IsZero(response->h.id) && m->rec.r.resrec.rrtype != kDNSType_NSEC)
9055         {
9056             if (m->CurrentRecord)
9057                 LogMsg("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
9058             m->CurrentRecord = m->ResourceRecords;
9059             while (m->CurrentRecord)
9060             {
9061                 AuthRecord *rr = m->CurrentRecord;
9062                 m->CurrentRecord = rr->next;
9063                 // We accept all multicast responses, and unicast responses resulting from queries we issued
9064                 // For other unicast responses, this code accepts them only for responses with an
9065                 // (apparently) local source address that pertain to a record of our own that's in probing state
9066                 if (!AcceptableResponse && !(ResponseSrcLocal && rr->resrec.RecordType == kDNSRecordTypeUnique)) continue;
9067 
9068                 if (PacketRRMatchesSignature(&m->rec.r, rr))        // If interface, name, type (if shared record) and class match...
9069                 {
9070                     // ... check to see if type and rdata are identical
9071                     if (IdenticalSameNameRecord(&m->rec.r.resrec, &rr->resrec))
9072                     {
9073                         // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
9074                         if (m->rec.r.resrec.rroriginalttl >= rr->resrec.rroriginalttl/2 || m->SleepState)
9075                         {
9076                             // If we were planning to send on this -- and only this -- interface, then we don't need to any more
9077                             if      (rr->ImmedAnswer == InterfaceID) { rr->ImmedAnswer = mDNSNULL; rr->ImmedUnicast = mDNSfalse; }
9078                         }
9079                         else
9080                         {
9081                             if      (rr->ImmedAnswer == mDNSNULL)    { rr->ImmedAnswer = InterfaceID;       m->NextScheduledResponse = m->timenow; }
9082                             else if (rr->ImmedAnswer != InterfaceID) { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9083                         }
9084                     }
9085                     // else, the packet RR has different type or different rdata -- check to see if this is a conflict
9086                     else if (m->rec.r.resrec.rroriginalttl > 0 && PacketRRConflict(m, rr, &m->rec.r))
9087                     {
9088                         LogInfo("mDNSCoreReceiveResponse: Pkt Record: %08lX %s", m->rec.r.resrec.rdatahash, CRDisplayString(m, &m->rec.r));
9089                         LogInfo("mDNSCoreReceiveResponse: Our Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9090 
9091                         // If this record is marked DependentOn another record for conflict detection purposes,
9092                         // then *that* record has to be bumped back to probing state to resolve the conflict
9093                         if (rr->DependentOn)
9094                         {
9095                             while (rr->DependentOn) rr = rr->DependentOn;
9096                             LogInfo("mDNSCoreReceiveResponse: Dep Record: %08lX %s", rr->resrec.rdatahash, ARDisplayString(m, rr));
9097                         }
9098 
9099                         // If we've just whacked this record's ProbeCount, don't need to do it again
9100                         if (rr->ProbeCount > DefaultProbeCountForTypeUnique)
9101                             LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
9102                         else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
9103                             LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
9104                         else
9105                         {
9106                             LogMsg("mDNSCoreReceiveResponse: Received from %#a:%d %s", srcaddr, mDNSVal16(srcport), CRDisplayString(m, &m->rec.r));
9107                             // If we'd previously verified this record, put it back to probing state and try again
9108                             if (rr->resrec.RecordType == kDNSRecordTypeVerified)
9109                             {
9110                                 LogMsg("mDNSCoreReceiveResponse: Resetting to Probing: %s", ARDisplayString(m, rr));
9111                                 rr->resrec.RecordType     = kDNSRecordTypeUnique;
9112                                 // We set ProbeCount to one more than the usual value so we know we've already touched this record.
9113                                 // This is because our single probe for "example-name.local" could yield a response with (say) two A records and
9114                                 // three AAAA records in it, and we don't want to call RecordProbeFailure() five times and count that as five conflicts.
9115                                 // This special value is recognised and reset to DefaultProbeCountForTypeUnique in SendQueries().
9116                                 rr->ProbeCount     = DefaultProbeCountForTypeUnique + 1;
9117                                 rr->AnnounceCount  = InitialAnnounceCount;
9118                                 InitializeLastAPTime(m, rr);
9119                                 RecordProbeFailure(m, rr);  // Repeated late conflicts also cause us to back off to the slower probing rate
9120                             }
9121                             // If we're probing for this record, we just failed
9122                             else if (rr->resrec.RecordType == kDNSRecordTypeUnique)
9123                             {
9124                                 // Before we call deregister, check if this is a packet we registered with the sleep proxy.
9125                                 if (!mDNSCoreRegisteredProxyRecord(m, rr))
9126                                 {
9127                                     LogMsg("mDNSCoreReceiveResponse: ProbeCount %d; will deregister %s", rr->ProbeCount, ARDisplayString(m, rr));
9128 
9129                                     m->mDNSStats.NameConflicts++;
9130                                     mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9131                                 }
9132                             }
9133                             // We assumed this record must be unique, but we were wrong. (e.g. There are two mDNSResponders on the
9134                             // same machine giving different answers for the reverse mapping record, or there are two machines on the
9135                             // network using the same IP address.) This is simply a misconfiguration, and there's nothing we can do
9136                             // to fix it -- e.g. it's not our job to be trying to change the machine's IP address. We just discard our
9137                             // record to avoid continued conflicts (as we do for a conflict on our Unique records) and get on with life.
9138                             else if (rr->resrec.RecordType == kDNSRecordTypeKnownUnique)
9139                             {
9140                                 LogMsg("mDNSCoreReceiveResponse: Unexpected conflict discarding %s", ARDisplayString(m, rr));
9141                                 m->mDNSStats.KnownUniqueNameConflicts++;
9142                                 mDNS_Deregister_internal(m, rr, mDNS_Dereg_conflict);
9143                             }
9144                             else
9145                                 LogMsg("mDNSCoreReceiveResponse: Unexpected record type %X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
9146                         }
9147                     }
9148                     // Else, matching signature, different type or rdata, but not a considered a conflict.
9149                     // If the packet record has the cache-flush bit set, then we check to see if we
9150                     // have any record(s) of the same type that we should re-assert to rescue them
9151                     // (see note about "multi-homing and bridged networks" at the end of this function).
9152                     else if (m->rec.r.resrec.rrtype == rr->resrec.rrtype)
9153                         if ((m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && m->timenow - rr->LastMCTime > mDNSPlatformOneSecond/2)
9154                         { rr->ImmedAnswer = mDNSInterfaceMark; m->NextScheduledResponse = m->timenow; }
9155                 }
9156             }
9157         }
9158 
9159         nseclist = mDNSfalse;
9160         if (!AcceptableResponse)
9161         {
9162             AcceptableResponse = IsResponseAcceptable(m, CacheFlushRecords, unicastQuestion, &nseclist);
9163             if (AcceptableResponse) m->rec.r.resrec.rDNSServer = uDNSServer;
9164         }
9165 
9166         // 2. See if we want to add this packet resource record to our cache
9167         // We only try to cache answers if we have a cache to put them in
9168         // Also, we ignore any apparent attempts at cache poisoning unicast to us that do not answer any outstanding active query
9169         if (!AcceptableResponse) LogInfo("mDNSCoreReceiveResponse ignoring %s", CRDisplayString(m, &m->rec.r));
9170         if (m->rrcache_size && AcceptableResponse)
9171         {
9172             const mDNSu32 slot = HashSlot(m->rec.r.resrec.name);
9173             CacheGroup *cg = CacheGroupForRecord(m, slot, &m->rec.r.resrec);
9174             CacheRecord *rr = mDNSNULL;
9175 
9176             if (McastNSEC3Records)
9177                 InitializeAnonInfoForCR(m, &McastNSEC3Records, &m->rec.r);
9178 
9179             // 2a. Check if this packet resource record is already in our cache.
9180             //
9181             // If this record should go in the nseclist, don't look in the cache for updating it.
9182             // They are supposed to be cached under the "nsec" field of the cache record for
9183             // validation. Just create the cache record.
9184             if (!nseclist)
9185             {
9186                 rr = mDNSCoreReceiveCacheCheck(m, response, LLQType, slot, cg, unicastQuestion, &cfp, &NSECCachePtr, InterfaceID);
9187             }
9188 
9189             // If packet resource record not in our cache, add it now
9190             // (unless it is just a deletion of a record we never had, in which case we don't care)
9191             if (!rr && m->rec.r.resrec.rroriginalttl > 0)
9192             {
9193                 const mDNSBool AddToCFList = (m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask) && (LLQType != uDNS_LLQ_Events);
9194                 mDNSs32 delay;
9195 
9196                 if (AddToCFList)
9197                     delay = NonZeroTime(m->timenow + mDNSPlatformOneSecond);
9198                 else
9199                     delay = CheckForSoonToExpireRecords(m, m->rec.r.resrec.name, m->rec.r.resrec.namehash, slot, mDNSNULL);
9200 
9201                 // If unique, assume we may have to delay delivery of this 'add' event.
9202                 // Below, where we walk the CacheFlushRecords list, we either call CacheRecordDeferredAdd()
9203                 // to immediately to generate answer callbacks, or we call ScheduleNextCacheCheckTime()
9204                 // to schedule an mDNS_Execute task at the appropriate time.
9205                 rr = CreateNewCacheEntry(m, slot, cg, delay, !nseclist, srcaddr);
9206                 if (rr)
9207                 {
9208                     rr->responseFlags = response->h.flags;
9209                     // If we are not creating signatures, then we need to inform DNSSEC so that
9210                     // it does not wait forever. Don't do this if we got NSEC records
9211                     // as it indicates that this name does not exist.
9212                     if (rr->resrec.rrtype == kDNSType_RRSIG && !nseclist)
9213                     {
9214                         rrsigsCreated = mDNStrue;
9215                     }
9216                     // Remember whether we created a cache record in response to a DNSSEC question.
9217                     // This helps DNSSEC code not to reissue the question to fetch the DNSSEC records.
9218                     rr->CRDNSSECQuestion = 0;
9219                     if (unicastQuestion && DNSSECQuestion(unicastQuestion))
9220                     {
9221                         LogInfo("mDNSCoreReceiveResponse: CRDNSSECQuestion set for new record %s, question %##s (%s)", CRDisplayString(m, rr),
9222                             unicastQuestion->qname.c, DNSTypeName(unicastQuestion->qtype));
9223                         rr->CRDNSSECQuestion = 1;
9224                     }
9225                     // NSEC/NSEC3 records and its signatures are cached with the negative cache entry
9226                     // which we should be creating below. It is also needed in the wildcard
9227                     // expanded answer case and in that case it is cached along with the answer.
9228                     if (nseclist)
9229                     {
9230                         rr->TimeRcvd = m->timenow;
9231                         *nsecp = rr;
9232                         nsecp = &rr->next;
9233                     }
9234                     else if (AddToCFList)
9235                     {
9236                         *cfp = rr;
9237                         cfp = &rr->NextInCFList;
9238                         *cfp = (CacheRecord*)1;
9239                     }
9240                     else if (rr->DelayDelivery)
9241                     {
9242                         ScheduleNextCacheCheckTime(m, slot, rr->DelayDelivery);
9243                     }
9244                 }
9245             }
9246             else
9247             {
9248                 if (rr && rr->resrec.AnonInfo && m->rec.r.resrec.AnonInfo)
9249                 {
9250                     CopyAnonInfoForCR(m, rr, &m->rec.r);
9251                 }
9252             }
9253         }
9254         mDNSCoreResetRecord(m);
9255     }
9256 
9257 exit:
9258     mDNSCoreResetRecord(m);
9259 
9260     // If we've just received one or more records with their cache flush bits set,
9261     // then scan that cache slot to see if there are any old stale records we need to flush
9262     while (CacheFlushRecords != (CacheRecord*)1)
9263     {
9264         CacheRecord *r1 = CacheFlushRecords, *r2;
9265         const mDNSu32 slot = HashSlot(r1->resrec.name);
9266         const CacheGroup *cg = CacheGroupForRecord(m, slot, &r1->resrec);
9267         CacheFlushRecords = CacheFlushRecords->NextInCFList;
9268         r1->NextInCFList = mDNSNULL;
9269 
9270         // Look for records in the cache with the same signature as this new one with the cache flush
9271         // bit set, and either (a) if they're fresh, just make sure the whole RRSet has the same TTL
9272         // (as required by DNS semantics) or (b) if they're old, mark them for deletion in one second.
9273         // We make these TTL adjustments *only* for records that still have *more* than one second
9274         // remaining to live. Otherwise, a record that we tagged for deletion half a second ago
9275         // (and now has half a second remaining) could inadvertently get its life extended, by either
9276         // (a) if we got an explicit goodbye packet half a second ago, the record would be considered
9277         // "fresh" and would be incorrectly resurrected back to the same TTL as the rest of the RRSet,
9278         // or (b) otherwise, the record would not be fully resurrected, but would be reset to expire
9279         // in one second, thereby inadvertently delaying its actual expiration, instead of hastening it.
9280         // If this were to happen repeatedly, the record's expiration could be deferred indefinitely.
9281         // To avoid this, we need to ensure that the cache flushing operation will only act to
9282         // *decrease* a record's remaining lifetime, never *increase* it.
9283         for (r2 = cg ? cg->members : mDNSNULL; r2; r2=r2->next)
9284         {
9285             mDNSu16 id1;
9286             mDNSu16 id2;
9287             if (!r1->resrec.InterfaceID)
9288             {
9289                 id1 = (r1->resrec.rDNSServer ? r1->resrec.rDNSServer->resGroupID : 0);
9290                 id2 = (r2->resrec.rDNSServer ? r2->resrec.rDNSServer->resGroupID : 0);
9291             }
9292             else
9293             {
9294                 id1 = id2 = 0;
9295             }
9296             // When we receive new RRSIGs e.g., for DNSKEY record, we should not flush the old
9297             // RRSIGS e.g., for TXT record. To do so, we need to look at the typeCovered field of
9298             // the new RRSIG that we received. Process only if the typeCovered matches.
9299             if ((r1->resrec.rrtype == r2->resrec.rrtype) && (r1->resrec.rrtype == kDNSType_RRSIG))
9300             {
9301                 rdataRRSig *rrsig1 = (rdataRRSig *)(((RDataBody2 *)(r1->resrec.rdata->u.data))->data);
9302                 rdataRRSig *rrsig2 = (rdataRRSig *)(((RDataBody2 *)(r2->resrec.rdata->u.data))->data);
9303                 if (swap16(rrsig1->typeCovered) != swap16(rrsig2->typeCovered))
9304                 {
9305                     debugf("mDNSCoreReceiveResponse: Received RRSIG typeCovered %s, found %s, not processing",
9306                         DNSTypeName(swap16(rrsig1->typeCovered)), DNSTypeName(swap16(rrsig2->typeCovered)));
9307                     continue;
9308                 }
9309             }
9310 
9311             // For Unicast (null InterfaceID) the resolver IDs should also match
9312             if ((r1->resrec.InterfaceID == r2->resrec.InterfaceID) &&
9313                 (r1->resrec.InterfaceID || (id1 == id2)) &&
9314                 r1->resrec.rrtype      == r2->resrec.rrtype &&
9315                 r1->resrec.rrclass     == r2->resrec.rrclass)
9316             {
9317                 // If record is recent, just ensure the whole RRSet has the same TTL (as required by DNS semantics)
9318                 // else, if record is old, mark it to be flushed
9319                 if (m->timenow - r2->TimeRcvd < mDNSPlatformOneSecond && RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9320                 {
9321                     // If we find mismatched TTLs in an RRSet, correct them.
9322                     // We only do this for records with a TTL of 2 or higher. It's possible to have a
9323                     // goodbye announcement with the cache flush bit set (or a case-change on record rdata,
9324                     // which we treat as a goodbye followed by an addition) and in that case it would be
9325                     // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
9326 
9327                     // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
9328                     // because certain early Bonjour devices are known to have this specific mismatch, and
9329                     // there's no point filling syslog with messages about something we already know about.
9330                     // We also don't log this for uDNS responses, since a caching name server is obliged
9331                     // to give us an aged TTL to correct for how long it has held the record,
9332                     // so our received TTLs are expected to vary in that case
9333 
9334                     // We also suppress log message in the case of SRV records that are recieved
9335                     // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
9336                     // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
9337                     // GM builds.
9338                     if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
9339                     {
9340                         if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
9341                             !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) &&
9342                             mDNSOpaque16IsZero(response->h.id))
9343                             LogInfo("Correcting TTL from %4d to %4d for %s",
9344                                     r2->resrec.rroriginalttl, r1->resrec.rroriginalttl, CRDisplayString(m, r2));
9345                         r2->resrec.rroriginalttl = r1->resrec.rroriginalttl;
9346                     }
9347                     r2->TimeRcvd = m->timenow;
9348                 }
9349                 else                // else, if record is old, mark it to be flushed
9350                 {
9351                     verbosedebugf("Cache flush new %p age %d expire in %d %s", r1, m->timenow - r1->TimeRcvd, RRExpireTime(r1) - m->timenow, CRDisplayString(m, r1));
9352                     verbosedebugf("Cache flush old %p age %d expire in %d %s", r2, m->timenow - r2->TimeRcvd, RRExpireTime(r2) - m->timenow, CRDisplayString(m, r2));
9353                     // We set stale records to expire in one second.
9354                     // This gives the owner a chance to rescue it if necessary.
9355                     // This is important in the case of multi-homing and bridged networks:
9356                     //   Suppose host X is on Ethernet. X then connects to an AirPort base station, which happens to be
9357                     //   bridged onto the same Ethernet. When X announces its AirPort IP address with the cache-flush bit
9358                     //   set, the AirPort packet will be bridged onto the Ethernet, and all other hosts on the Ethernet
9359                     //   will promptly delete their cached copies of the (still valid) Ethernet IP address record.
9360                     //   By delaying the deletion by one second, we give X a change to notice that this bridging has
9361                     //   happened, and re-announce its Ethernet IP address to rescue it from deletion from all our caches.
9362 
9363                     // We set UnansweredQueries to MaxUnansweredQueries to avoid expensive and unnecessary
9364                     // final expiration queries for this record.
9365 
9366                     // If a record is deleted twice, first with an explicit DE record, then a second time by virtue of the cache
9367                     // flush bit on the new record replacing it, then we allow the record to be deleted immediately, without the usual
9368                     // one-second grace period. This improves responsiveness for mDNS_Update(), as used for things like iChat status updates.
9369                     // <rdar://problem/5636422> Updating TXT records is too slow
9370                     // We check for "rroriginalttl == 1" because we want to include records tagged by the "packet TTL is zero" check above,
9371                     // which sets rroriginalttl to 1, but not records tagged by the rdata case-change check, which sets rroriginalttl to 0.
9372                     if (r2->TimeRcvd == m->timenow && r2->resrec.rroriginalttl == 1 && r2->UnansweredQueries == MaxUnansweredQueries)
9373                     {
9374                         LogInfo("Cache flush for DE record %s", CRDisplayString(m, r2));
9375                         r2->resrec.rroriginalttl = 0;
9376                     }
9377                     else if (RRExpireTime(r2) - m->timenow > mDNSPlatformOneSecond)
9378                     {
9379                         // We only set a record to expire in one second if it currently has *more* than a second to live
9380                         // If it's already due to expire in a second or less, we just leave it alone
9381                         r2->resrec.rroriginalttl = 1;
9382                         r2->UnansweredQueries = MaxUnansweredQueries;
9383                         r2->TimeRcvd = m->timenow - 1;
9384                         // We use (m->timenow - 1) instead of m->timenow, because we use that to identify records
9385                         // that we marked for deletion via an explicit DE record
9386                     }
9387                 }
9388                 SetNextCacheCheckTimeForRecord(m, r2);
9389             }
9390         }
9391 
9392         if (r1->DelayDelivery)  // If we were planning to delay delivery of this record, see if we still need to
9393         {
9394             // If we had a unicast question for this response with at least one positive answer and we
9395             // have NSECRecords, it is most likely a wildcard expanded answer. Cache the NSEC and its
9396             // signatures along with the cache record which will be used for validation later. If
9397             // we rescued a few records earlier in this function, then NSECCachePtr would be set. In that
9398             // use that instead.
9399             if (response->h.numAnswers && unicastQuestion && NSECRecords)
9400             {
9401                 if (!NSECCachePtr)
9402                 {
9403                     LogInfo("mDNSCoreReceiveResponse: Updating NSECCachePtr to %s", CRDisplayString(m, r1));
9404                     NSECCachePtr = r1;
9405                 }
9406                 // Note: We need to do this before we call CacheRecordDeferredAdd as this
9407                 // might start the verification process which needs these NSEC records
9408                 if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9409                 {
9410                     LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9411                     FreeNSECRecords(m, NSECRecords);
9412                 }
9413                 NSECRecords = mDNSNULL;
9414                 NSECCachePtr = mDNSNULL;
9415             }
9416             r1->DelayDelivery = CheckForSoonToExpireRecords(m, r1->resrec.name, r1->resrec.namehash, slot, mDNSNULL);
9417             // If no longer delaying, deliver answer now, else schedule delivery for the appropriate time
9418             if (!r1->DelayDelivery) CacheRecordDeferredAdd(m, r1);
9419             else ScheduleNextCacheCheckTime(m, slot, r1->DelayDelivery);
9420         }
9421     }
9422 
9423     // If we have not consumed the NSEC records yet e.g., just refreshing the cache,
9424     // update them now for future validations.
9425     if (NSECRecords && NSECCachePtr)
9426     {
9427         LogInfo("mDNSCoreReceieveResponse: Updating NSEC records in %s", CRDisplayString(m, NSECCachePtr));
9428         if (!AddNSECSForCacheRecord(m, NSECRecords, NSECCachePtr, rcode))
9429         {
9430             LogInfo("mDNSCoreReceiveResponse: AddNSECSForCacheRecord failed to add NSEC for %s", CRDisplayString(m, NSECCachePtr));
9431             FreeNSECRecords(m, NSECRecords);
9432         }
9433         NSECRecords = mDNSNULL;
9434         NSECCachePtr = mDNSNULL;
9435     }
9436 
9437     // If there is at least one answer and we did not create RRSIGs and there was a
9438     // ValidatingResponse question waiting for this response, give a hint that no RRSIGs
9439     // were created. We don't need to give a hint:
9440     //
9441     // - if we have no answers, the mDNSCoreReceiveNoUnicastAnswers below should
9442     //   generate a negative response
9443     //
9444     // - if we have NSECRecords, it means we might have a potential proof for
9445     //   non-existence of name that we are looking for
9446     //
9447     if (response->h.numAnswers && !rrsigsCreated && DNSSECQuestion && !NSECRecords)
9448         mDNSCoreReceiveNoDNSSECAnswers(m, response, end, dstaddr, dstport, InterfaceID);
9449 
9450     // See if we need to generate negative cache entries for unanswered unicast questions
9451     mDNSCoreReceiveNoUnicastAnswers(m, response, end, dstaddr, dstport, InterfaceID, LLQType, rcode, NSECRecords);
9452 
9453     if (McastNSEC3Records)
9454     {
9455         debugf("mDNSCoreReceiveResponse: McastNSEC3Records not used");
9456         FreeNSECRecords(m, McastNSEC3Records);
9457     }
9458 }
9459 
9460 // ScheduleWakeup causes all proxy records with WakeUp.HMAC matching mDNSEthAddr 'e' to be deregistered, causing
9461 // multiple wakeup magic packets to be sent if appropriate, and all records to be ultimately freed after a few seconds.
9462 // ScheduleWakeup is called on mDNS record conflicts, ARP conflicts, NDP conflicts, or reception of trigger traffic
9463 // that warrants waking the sleeping host.
9464 // ScheduleWakeup must be called with the lock held (ScheduleWakeupForList uses mDNS_Deregister_internal)
9465 
9466 mDNSlocal void ScheduleWakeupForList(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e, AuthRecord *const thelist)
9467 {
9468     // We need to use the m->CurrentRecord mechanism here when dealing with DuplicateRecords list as
9469     // mDNS_Deregister_internal deregisters duplicate records immediately as they are not used
9470     // to send wakeups or goodbyes. See the comment in that function for more details. To keep it
9471     // simple, we use the same mechanism for both lists.
9472     if (!e->l[0])
9473     {
9474         LogMsg("ScheduleWakeupForList ERROR: Target HMAC is zero");
9475         return;
9476     }
9477     m->CurrentRecord = thelist;
9478     while (m->CurrentRecord)
9479     {
9480         AuthRecord *const rr = m->CurrentRecord;
9481         if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering && mDNSSameEthAddress(&rr->WakeUp.HMAC, e))
9482         {
9483             LogInfo("ScheduleWakeupForList: Scheduling wakeup packets for %s", ARDisplayString(m, rr));
9484             mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
9485         }
9486         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
9487             m->CurrentRecord = rr->next;
9488     }
9489 }
9490 
9491 mDNSlocal void ScheduleWakeup(mDNS *const m, mDNSInterfaceID InterfaceID, mDNSEthAddr *e)
9492 {
9493     if (!e->l[0]) { LogMsg("ScheduleWakeup ERROR: Target HMAC is zero"); return; }
9494     ScheduleWakeupForList(m, InterfaceID, e, m->DuplicateRecords);
9495     ScheduleWakeupForList(m, InterfaceID, e, m->ResourceRecords);
9496 }
9497 
9498 mDNSlocal void SPSRecordCallback(mDNS *const m, AuthRecord *const ar, mStatus result)
9499 {
9500     if (result && result != mStatus_MemFree)
9501         LogInfo("SPS Callback %d %s", result, ARDisplayString(m, ar));
9502 
9503     if (result == mStatus_NameConflict)
9504     {
9505         mDNS_Lock(m);
9506         LogMsg("%-7s Conflicting mDNS -- waking %.6a %s", InterfaceNameForID(m, ar->resrec.InterfaceID), &ar->WakeUp.HMAC, ARDisplayString(m, ar));
9507         if (ar->WakeUp.HMAC.l[0])
9508         {
9509             SendWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.IMAC, &ar->WakeUp.password);  // Send one wakeup magic packet
9510             ScheduleWakeup(m, ar->resrec.InterfaceID, &ar->WakeUp.HMAC);                    // Schedule all other records with the same owner to be woken
9511         }
9512         mDNS_Unlock(m);
9513     }
9514 
9515     if (result == mStatus_NameConflict || result == mStatus_MemFree)
9516     {
9517         m->ProxyRecords--;
9518         mDNSPlatformMemFree(ar);
9519         mDNS_UpdateAllowSleep(m);
9520     }
9521 }
9522 
9523 mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth)
9524 {
9525     int     i;
9526     mDNSs8  hval   = 0;
9527     int     colons = 0;
9528     mDNSu16  val    = 0; /* need to use 16 bit int to detect overflow */
9529 
9530     for (i = 0; ptr < limit && *ptr != ' ' && i < 17; i++, ptr++)
9531     {
9532         hval = HexVal(*ptr);
9533         if (hval != -1)
9534         {
9535             val <<= 4;
9536             val |= hval;
9537         }
9538         else if (*ptr == ':')
9539         {
9540             if (colons >=5 || val > 255)
9541             {
9542                 LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val);
9543                 return mDNSNULL;
9544             }
9545             eth->b[colons] = (mDNSs8)val;
9546             colons++;
9547             val = 0;
9548         }
9549     }
9550     if (colons != 5)
9551     {
9552         LogMsg("GetValueForMACAddr: Address malformed colons %d", colons);
9553         return mDNSNULL;
9554     }
9555     eth->b[colons] = (mDNSs8)val;
9556     return ptr;
9557 }
9558 
9559 mDNSlocal mDNSu8 *GetValueForIPv6Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv6Addr *v6)
9560 {
9561     int hval;
9562     int value;
9563     int numBytes;
9564     int digitsProcessed;
9565     int zeroFillStart;
9566     int numColons;
9567     mDNSu8 v6addr[16];
9568 
9569     // RFC 3513: Section 2.2 specifies IPv6 presentation format. The following parsing
9570     // handles both (1) and (2) and does not handle embedded IPv4 addresses.
9571     //
9572     // First forms a address in "v6addr", then expands to fill the zeroes in and returns
9573     // the result in "v6"
9574 
9575     numColons = numBytes = value = digitsProcessed = zeroFillStart = 0;
9576     while (ptr < limit && *ptr != ' ')
9577     {
9578         hval = HexVal(*ptr);
9579         if (hval != -1)
9580         {
9581             value <<= 4;
9582             value |= hval;
9583             digitsProcessed = 1;
9584         }
9585         else if (*ptr == ':')
9586         {
9587             if (!digitsProcessed)
9588             {
9589                 // If we have already seen a "::", we should not see one more. Handle the special
9590                 // case of "::"
9591                 if (numColons)
9592                 {
9593                     // if we never filled any bytes and the next character is space (we have reached the end)
9594                     // we are done
9595                     if (!numBytes && (ptr + 1) < limit && *(ptr + 1) == ' ')
9596                     {
9597                         mDNSPlatformMemZero(v6->b, 16);
9598                         return ptr + 1;
9599                     }
9600                     LogMsg("GetValueForIPv6Addr: zeroFillStart non-zero %d", zeroFillStart);
9601                     return mDNSNULL;
9602                 }
9603 
9604                 // We processed "::". We need to fill zeroes later. For now, mark the
9605                 // point where we will start filling zeroes from.
9606                 zeroFillStart = numBytes;
9607                 numColons++;
9608             }
9609             else if ((ptr + 1) < limit && *(ptr + 1) == ' ')
9610             {
9611                 // We have a trailing ":" i.e., no more characters after ":"
9612                 LogMsg("GetValueForIPv6Addr: Trailing colon");
9613                 return mDNSNULL;
9614             }
9615             else
9616             {
9617                 // For a fully expanded IPv6 address, we fill the 14th and 15th byte outside of this while
9618                 // loop below as there is no ":" at the end. Hence, the last two bytes that can possibly
9619                 // filled here is 12 and 13.
9620                 if (numBytes > 13) { LogMsg("GetValueForIPv6Addr:1: numBytes is %d", numBytes); return mDNSNULL; }
9621 
9622                 v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9623                 v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9624                 digitsProcessed = value = 0;
9625 
9626                 // Make sure that we did not fill the 13th and 14th byte above
9627                 if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:2: numBytes is %d", numBytes); return mDNSNULL; }
9628             }
9629         }
9630         ptr++;
9631     }
9632 
9633     // We should be processing the last set of bytes following the last ":" here
9634     if (!digitsProcessed)
9635     {
9636         LogMsg("GetValueForIPv6Addr: no trailing bytes after colon, numBytes is %d", numBytes);
9637         return mDNSNULL;
9638     }
9639 
9640     if (numBytes > 14) { LogMsg("GetValueForIPv6Addr:3: numBytes is %d", numBytes); return mDNSNULL; }
9641     v6addr[numBytes++] = (mDNSu8) ((value >> 8) & 0xFF);
9642     v6addr[numBytes++] = (mDNSu8) (value & 0xFF);
9643 
9644     if (zeroFillStart)
9645     {
9646         int i, j, n;
9647         for (i = 0; i < zeroFillStart; i++)
9648             v6->b[i] = v6addr[i];
9649         for (j = i, n = 0; n < 16 - numBytes; j++, n++)
9650             v6->b[j] = 0;
9651         for (; j < 16; i++, j++)
9652             v6->b[j] = v6addr[i];
9653     }
9654     else if (numBytes == 16)
9655         mDNSPlatformMemCopy(v6->b, v6addr, 16);
9656     else
9657     {
9658         LogMsg("GetValueForIPv6addr: Not enough bytes for IPv6 address, numBytes is %d", numBytes);
9659         return mDNSNULL;
9660     }
9661     return ptr;
9662 }
9663 
9664 mDNSlocal mDNSu8 *GetValueForIPv4Addr(mDNSu8 *ptr, mDNSu8 *limit, mDNSv4Addr *v4)
9665 {
9666     mDNSu32 val;
9667     int dots = 0;
9668     val = 0;
9669 
9670     for ( ; ptr < limit && *ptr != ' '; ptr++)
9671     {
9672         if (*ptr >= '0' &&  *ptr <= '9')
9673             val = val * 10 + *ptr - '0';
9674         else if (*ptr == '.')
9675         {
9676             if (val > 255 || dots >= 3)
9677             {
9678                 LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots);
9679                 return mDNSNULL;
9680             }
9681             v4->b[dots++] = val;
9682             val = 0;
9683         }
9684         else
9685         {
9686             // We have a zero at the end and if we reached that, then we are done.
9687             if (*ptr == 0 && ptr == limit - 1 && dots == 3)
9688             {
9689                 v4->b[dots] = val;
9690                 return ptr + 1;
9691             }
9692             else { LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots); return mDNSNULL; }
9693         }
9694     }
9695     if (dots != 3) { LogMsg("GetValueForIPv4Addr: Address malformed dots %d", dots); return mDNSNULL; }
9696     v4->b[dots] = val;
9697     return ptr;
9698 }
9699 
9700 mDNSlocal mDNSu8 *GetValueForKeepalive(mDNSu8 *ptr, mDNSu8 *limit, mDNSu32 *value)
9701 {
9702     mDNSu32 val;
9703 
9704     val = 0;
9705     for ( ; ptr < limit && *ptr != ' '; ptr++)
9706     {
9707         if (*ptr < '0' || *ptr > '9')
9708         {
9709             // We have a zero at the end and if we reached that, then we are done.
9710             if (*ptr == 0 && ptr == limit - 1)
9711             {
9712                 *value = val;
9713                 return ptr + 1;
9714             }
9715             else { LogMsg("GetValueForKeepalive: *ptr %d, ptr %p, limit %p, ptr +1 %d", *ptr, ptr, limit, *(ptr + 1)); return mDNSNULL; }
9716         }
9717         val = val * 10 + *ptr - '0';
9718     }
9719     *value = val;
9720     return ptr;
9721 }
9722 
9723 mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr)
9724 {
9725 	mDNSAddr    laddr, raddr;
9726 	mDNSEthAddr eth;
9727 	mDNSIPPort  lport, rport;
9728 	mDNSu32     timeout, seq, ack;
9729 	mDNSu16     win;
9730 
9731 	if (!mDNS_KeepaliveRecord(&rr->resrec))
9732 	{
9733 		return mDNSfalse;
9734 	}
9735 
9736 	timeout = seq = ack = 0;
9737 	win = 0;
9738 	laddr = raddr = zeroAddr;
9739 	lport = rport = zeroIPPort;
9740 
9741 	mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
9742 
9743 	if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) ||
9744 		mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) ||
9745 		mDNSEthAddressIsZero(eth))
9746 	{
9747 		return mDNSfalse;
9748 	}
9749 
9750 	return mDNStrue;
9751 }
9752 
9753 
9754 mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
9755                                          mDNSu32 *ack, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu16 *win)
9756 {
9757     if (ar->resrec.rrtype != kDNSType_NULL)
9758         return;
9759 
9760     if (mDNS_KeepaliveRecord(&ar->resrec))
9761     {
9762         int len = ar->resrec.rdlength;
9763         mDNSu8 *ptr = &ar->resrec.rdata->u.txt.c[1];
9764         mDNSu8 *limit = ptr + len - 1; // Exclude the first byte that is the length
9765         mDNSu32 value = 0;
9766 
9767         while (ptr < limit)
9768         {
9769             mDNSu8 param = *ptr;
9770             ptr += 2;   // Skip the letter and the "="
9771             if (param == 'h')
9772             {
9773                 laddr->type = mDNSAddrType_IPv4;
9774                 ptr = GetValueForIPv4Addr(ptr, limit, &laddr->ip.v4);
9775             }
9776             else if (param == 'd')
9777             {
9778                 raddr->type = mDNSAddrType_IPv4;
9779                 ptr = GetValueForIPv4Addr(ptr, limit, &raddr->ip.v4);
9780             }
9781             if (param == 'H')
9782             {
9783                 laddr->type = mDNSAddrType_IPv6;
9784                 ptr = GetValueForIPv6Addr(ptr, limit, &laddr->ip.v6);
9785             }
9786             else if (param == 'D')
9787             {
9788                 raddr->type = mDNSAddrType_IPv6;
9789                 ptr = GetValueForIPv6Addr(ptr, limit, &raddr->ip.v6);
9790             }
9791             else if (param == 'm')
9792             {
9793                 ptr = GetValueForMACAddr(ptr, limit, eth);
9794             }
9795             else
9796             {
9797                 ptr = GetValueForKeepalive(ptr, limit, &value);
9798             }
9799             if (!ptr) { LogMsg("mDNS_ExtractKeepaliveInfo: Cannot parse\n"); return; }
9800 
9801             // Extract everything in network order so that it is easy for sending a keepalive and also
9802             // for matching incoming TCP packets
9803             switch (param)
9804             {
9805             case 't':
9806                 *timeout = value;
9807                 //if (*timeout < 120) *timeout = 120;
9808                 break;
9809             case 'h':
9810             case 'H':
9811             case 'd':
9812             case 'D':
9813             case 'm':
9814             case 'i':
9815             case 'c':
9816                 break;
9817             case 'l':
9818                 lport->NotAnInteger = swap16((mDNSu16)value);
9819                 break;
9820             case 'r':
9821                 rport->NotAnInteger = swap16((mDNSu16)value);
9822                 break;
9823             case 's':
9824                 *seq = swap32(value);
9825                 break;
9826             case 'a':
9827                 *ack = swap32(value);
9828                 break;
9829             case 'w':
9830                 *win = swap16((mDNSu16)value);
9831                 break;
9832             default:
9833                 LogMsg("mDNS_ExtractKeepaliveInfo: unknown value %c\n", param);
9834                 ptr = limit;
9835                 break;
9836             }
9837             ptr++; // skip the space
9838         }
9839     }
9840 }
9841 
9842 // 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
9843 // the clients need not retrieve this information from the auth record again.
9844 mDNSlocal AuthRecord* mDNS_MatchKeepaliveInfo(mDNS *const m, const mDNSAddr* pladdr, const mDNSAddr* praddr, const mDNSIPPort plport,
9845                                               const mDNSIPPort prport, mDNSu32 *rseq, mDNSu32 *rack)
9846 {
9847     AuthRecord *ar;
9848     mDNSAddr laddr, raddr;
9849     mDNSEthAddr eth;
9850     mDNSIPPort lport, rport;
9851     mDNSu32 timeout, seq, ack;
9852     mDNSu16 win;
9853 
9854     for (ar = m->ResourceRecords; ar; ar=ar->next)
9855     {
9856         timeout = seq = ack = 0;
9857         win = 0;
9858         laddr = raddr = zeroAddr;
9859         lport = rport = zeroIPPort;
9860 
9861         if (!ar->WakeUp.HMAC.l[0]) continue;
9862 
9863         mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
9864 
9865         // Did we parse correctly ?
9866         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
9867         {
9868             debugf("mDNS_MatchKeepaliveInfo: not a valid record %s for keepalive", ARDisplayString(m, ar));
9869             continue;
9870         }
9871 
9872         debugf("mDNS_MatchKeepaliveInfo: laddr %#a pladdr %#a, raddr %#a praddr %#a, lport %d plport %d, rport %d prport %d",
9873                &laddr, pladdr, &raddr, praddr, mDNSVal16(lport), mDNSVal16(plport), mDNSVal16(rport), mDNSVal16(prport));
9874 
9875         // Does it match the incoming TCP packet ?
9876         if (mDNSSameAddress(&laddr, pladdr) && mDNSSameAddress(&raddr, praddr) && mDNSSameIPPort(lport, plport) && mDNSSameIPPort(rport, prport))
9877         {
9878             // returning in network order
9879             *rseq = seq;
9880             *rack = ack;
9881             return ar;
9882         }
9883     }
9884     return mDNSNULL;
9885 }
9886 
9887 mDNSlocal void mDNS_SendKeepalives(mDNS *const m)
9888 {
9889     AuthRecord *ar;
9890 
9891     for (ar = m->ResourceRecords; ar; ar=ar->next)
9892     {
9893         mDNSu32 timeout, seq, ack;
9894         mDNSu16 win;
9895         mDNSAddr laddr, raddr;
9896         mDNSEthAddr eth;
9897         mDNSIPPort lport, rport;
9898 
9899         timeout = seq = ack = 0;
9900         win = 0;
9901 
9902         laddr = raddr = zeroAddr;
9903         lport = rport = zeroIPPort;
9904 
9905         if (!ar->WakeUp.HMAC.l[0]) continue;
9906 
9907         mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
9908 
9909         if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
9910         {
9911             debugf("mDNS_SendKeepalives: not a valid record %s for keepalive", ARDisplayString(m, ar));
9912             continue;
9913         }
9914         LogMsg("mDNS_SendKeepalives: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
9915 
9916         // When we receive a proxy update, we set KATimeExpire to zero so that we always send a keepalive
9917         // immediately (to detect any potential problems). After that we always set it to a non-zero value.
9918         if (!ar->KATimeExpire || (m->timenow - ar->KATimeExpire >= 0))
9919         {
9920             mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
9921             ar->KATimeExpire = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
9922         }
9923         if (m->NextScheduledKA - ar->KATimeExpire > 0)
9924             m->NextScheduledKA = ar->KATimeExpire;
9925     }
9926 }
9927 
9928 mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
9929 {
9930     mDNSu32     timeout, seq, ack, seqInc;
9931     mDNSu16     win;
9932     mDNSAddr    laddr, raddr;
9933     mDNSEthAddr eth;
9934     mDNSIPPort  lport, rport;
9935     mDNSu8      *ptr;
9936 
9937     if (ar == mDNSNULL)
9938     {
9939         LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
9940         return;
9941     }
9942 
9943     timeout = seq = ack = 0;
9944     win = 0;
9945 
9946     laddr = raddr = zeroAddr;
9947     lport = rport = zeroIPPort;
9948 
9949     mDNS_ExtractKeepaliveInfo(ar, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
9950 
9951     if (!timeout || mDNSAddressIsZero(&laddr) || mDNSAddressIsZero(&raddr) || !seq || !ack || mDNSIPPortIsZero(lport) || mDNSIPPortIsZero(rport) || !win)
9952     {
9953         LogInfo("mDNS_SendKeepaliveACK: not a valid record %s for keepalive", ARDisplayString(m, ar));
9954         return;
9955     }
9956 
9957     // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
9958     // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
9959     // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
9960     // it's converted to host byte order before incrementing it by one.
9961     ptr = (mDNSu8 *)&seq;
9962     seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1;
9963     ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF);
9964     ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF);
9965     ptr[2] = (mDNSu8)((seqInc >>  8) & 0xFF);
9966     ptr[3] = (mDNSu8)((seqInc      ) & 0xFF);
9967     LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
9968     mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
9969 }
9970 
9971 mDNSlocal void mDNSCoreReceiveUpdate(mDNS *const m,
9972                                      const DNSMessage *const msg, const mDNSu8 *end,
9973                                      const mDNSAddr *srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, mDNSIPPort dstport,
9974                                      const mDNSInterfaceID InterfaceID)
9975 {
9976     int i;
9977     AuthRecord opt;
9978     mDNSu8 *p = m->omsg.data;
9979     OwnerOptData owner = zeroOwner;     // Need to zero this, so we'll know if this Update packet was missing its Owner option
9980     mDNSu32 updatelease = 0;
9981     const mDNSu8 *ptr;
9982 
9983     LogSPS("Received Update from %#-15a:%-5d to %#-15a:%-5d on 0x%p with "
9984            "%2d Question%s %2d Answer%s %2d Authorit%s %2d Additional%s %d bytes",
9985            srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), InterfaceID,
9986            msg->h.numQuestions,   msg->h.numQuestions   == 1 ? ", "   : "s,",
9987            msg->h.numAnswers,     msg->h.numAnswers     == 1 ? ", "   : "s,",
9988            msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
9989            msg->h.numAdditionals, msg->h.numAdditionals == 1 ? " "    : "s", end - msg->data);
9990 
9991     if (!InterfaceID || !m->SPSSocket || !mDNSSameIPPort(dstport, m->SPSSocket->port)) return;
9992 
9993     if (mDNS_PacketLoggingEnabled)
9994         DumpPacket(m, mStatus_NoError, mDNSfalse, "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
9995 
9996     ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space + DNSOpt_OwnerData_ID_Space);
9997     if (ptr)
9998     {
9999         ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10000         if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10001         {
10002             const rdataOPT *o;
10003             const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10004             for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10005             {
10006                 if      (o->opt == kDNSOpt_Lease) updatelease = o->u.updatelease;
10007                 else if (o->opt == kDNSOpt_Owner && o->u.owner.vers == 0) owner       = o->u.owner;
10008             }
10009         }
10010         m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
10011     }
10012 
10013     InitializeDNSMessage(&m->omsg.h, msg->h.id, UpdateRespFlags);
10014 
10015     if (!updatelease || !owner.HMAC.l[0])
10016     {
10017         static int msgs = 0;
10018         if (msgs < 100)
10019         {
10020             msgs++;
10021             LogMsg("Refusing sleep proxy registration from %#a:%d:%s%s", srcaddr, mDNSVal16(srcport),
10022                    !updatelease ? " No lease" : "", !owner.HMAC.l[0] ? " No owner" : "");
10023         }
10024         m->omsg.h.flags.b[1] |= kDNSFlag1_RC_FormErr;
10025     }
10026     else if (m->ProxyRecords + msg->h.mDNS_numUpdates > MAX_PROXY_RECORDS)
10027     {
10028         static int msgs = 0;
10029         if (msgs < 100)
10030         {
10031             msgs++;
10032             LogMsg("Refusing sleep proxy registration from %#a:%d: Too many records %d + %d = %d > %d", srcaddr, mDNSVal16(srcport),
10033                    m->ProxyRecords, msg->h.mDNS_numUpdates, m->ProxyRecords + msg->h.mDNS_numUpdates, MAX_PROXY_RECORDS);
10034         }
10035         m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10036     }
10037     else
10038     {
10039         LogSPS("Received Update for H-MAC %.6a I-MAC %.6a Password %.6a seq %d", &owner.HMAC, &owner.IMAC, &owner.password, owner.seq);
10040 
10041         if (updatelease > 24 * 60 * 60)
10042             updatelease = 24 * 60 * 60;
10043 
10044         if (updatelease > 0x40000000UL / mDNSPlatformOneSecond)
10045             updatelease = 0x40000000UL / mDNSPlatformOneSecond;
10046 
10047         ptr = LocateAuthorities(msg, end);
10048 
10049         // Clear any stale TCP keepalive records that may exist
10050         ClearKeepaliveProxyRecords(m, &owner, m->DuplicateRecords, InterfaceID);
10051         ClearKeepaliveProxyRecords(m, &owner, m->ResourceRecords, InterfaceID);
10052 
10053         for (i = 0; i < msg->h.mDNS_numUpdates && ptr && ptr < end; i++)
10054         {
10055             ptr = GetLargeResourceRecord(m, msg, ptr, end, InterfaceID, kDNSRecordTypePacketAuth, &m->rec);
10056             if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative)
10057             {
10058                 mDNSu16 RDLengthMem = GetRDLengthMem(&m->rec.r.resrec);
10059                 AuthRecord *ar = mDNSPlatformMemAllocate(sizeof(AuthRecord) - sizeof(RDataBody) + RDLengthMem);
10060                 if (!ar)
10061                 {
10062                     m->omsg.h.flags.b[1] |= kDNSFlag1_RC_Refused;
10063                     break;
10064                 }
10065                 else
10066                 {
10067                     mDNSu8 RecordType = m->rec.r.resrec.RecordType & kDNSRecordTypePacketUniqueMask ? kDNSRecordTypeUnique : kDNSRecordTypeShared;
10068                     m->rec.r.resrec.rrclass &= ~kDNSClass_UniqueRRSet;
10069                     // All stale keepalive records have been flushed prior to this loop.
10070                     if (!mDNS_KeepaliveRecord(&m->rec.r.resrec))
10071                     {
10072                         ClearIdenticalProxyRecords(m, &owner, m->DuplicateRecords); // Make sure we don't have any old stale duplicates of this record
10073                         ClearIdenticalProxyRecords(m, &owner, m->ResourceRecords);
10074                     }
10075                     mDNS_SetupResourceRecord(ar, mDNSNULL, InterfaceID, m->rec.r.resrec.rrtype, m->rec.r.resrec.rroriginalttl, RecordType, AuthRecordAny, SPSRecordCallback, ar);
10076                     AssignDomainName(&ar->namestorage, m->rec.r.resrec.name);
10077                     ar->resrec.rdlength = GetRDLength(&m->rec.r.resrec, mDNSfalse);
10078                     ar->resrec.rdata->MaxRDLength = RDLengthMem;
10079                     mDNSPlatformMemCopy(ar->resrec.rdata->u.data, m->rec.r.resrec.rdata->u.data, RDLengthMem);
10080                     ar->ForceMCast = mDNStrue;
10081                     ar->WakeUp     = owner;
10082                     if (m->rec.r.resrec.rrtype == kDNSType_PTR)
10083                     {
10084                         mDNSs32 t = ReverseMapDomainType(m->rec.r.resrec.name);
10085                         if      (t == mDNSAddrType_IPv4) GetIPv4FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10086                         else if (t == mDNSAddrType_IPv6) GetIPv6FromName(&ar->AddressProxy, m->rec.r.resrec.name);
10087                         debugf("mDNSCoreReceiveUpdate: PTR %d %d %#a %s", t, ar->AddressProxy.type, &ar->AddressProxy, ARDisplayString(m, ar));
10088                         if (ar->AddressProxy.type) SetSPSProxyListChanged(InterfaceID);
10089                     }
10090                     ar->TimeRcvd   = m->timenow;
10091                     ar->TimeExpire = m->timenow + updatelease * mDNSPlatformOneSecond;
10092                     if (m->NextScheduledSPS - ar->TimeExpire > 0)
10093                         m->NextScheduledSPS = ar->TimeExpire;
10094                     ar->KATimeExpire = 0;
10095                     mDNS_Register_internal(m, ar);
10096 
10097                     m->ProxyRecords++;
10098                     mDNS_UpdateAllowSleep(m);
10099                     LogSPS("SPS Registered %4d %X %s", m->ProxyRecords, RecordType, ARDisplayString(m,ar));
10100                 }
10101             }
10102             m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
10103         }
10104 
10105         if (m->omsg.h.flags.b[1] & kDNSFlag1_RC_Mask)
10106         {
10107             LogMsg("Refusing sleep proxy registration from %#a:%d: Out of memory", srcaddr, mDNSVal16(srcport));
10108             ClearProxyRecords(m, &owner, m->DuplicateRecords);
10109             ClearProxyRecords(m, &owner, m->ResourceRecords);
10110         }
10111         else
10112         {
10113             mDNS_SetupResourceRecord(&opt, mDNSNULL, mDNSInterface_Any, kDNSType_OPT, kStandardTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
10114             opt.resrec.rrclass    = NormalMaxDNSMessageData;
10115             opt.resrec.rdlength   = sizeof(rdataOPT);   // One option in this OPT record
10116             opt.resrec.rdestimate = sizeof(rdataOPT);
10117             opt.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
10118             opt.resrec.rdata->u.opt[0].u.updatelease = updatelease;
10119             p = PutResourceRecordTTLWithLimit(&m->omsg, p, &m->omsg.h.numAdditionals, &opt.resrec, opt.resrec.rroriginalttl, m->omsg.data + AbsoluteMaxDNSMessageData);
10120         }
10121     }
10122 
10123     if (p) mDNSSendDNSMessage(m, &m->omsg, p, InterfaceID, m->SPSSocket, srcaddr, srcport, mDNSNULL, mDNSNULL, mDNSfalse);
10124     mDNS_SendKeepalives(m);
10125 }
10126 
10127 mDNSlocal void mDNSCoreReceiveUpdateR(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *end, const mDNSAddr *srcaddr, const mDNSInterfaceID InterfaceID)
10128 {
10129     if (InterfaceID)
10130     {
10131         mDNSu32 updatelease = 60 * 60;      // If SPS fails to indicate lease time, assume one hour
10132         const mDNSu8 *ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space);
10133         mDNSAddr spsaddr;
10134         char *ifname;
10135         if (ptr)
10136         {
10137             ptr = GetLargeResourceRecord(m, msg, ptr, end, 0, kDNSRecordTypePacketAdd, &m->rec);
10138             if (ptr && m->rec.r.resrec.RecordType != kDNSRecordTypePacketNegative && m->rec.r.resrec.rrtype == kDNSType_OPT)
10139             {
10140                 const rdataOPT *o;
10141                 const rdataOPT *const e = (const rdataOPT *)&m->rec.r.resrec.rdata->u.data[m->rec.r.resrec.rdlength];
10142                 for (o = &m->rec.r.resrec.rdata->u.opt[0]; o < e; o++)
10143                     if (o->opt == kDNSOpt_Lease)
10144                     {
10145                         updatelease = o->u.updatelease;
10146                         LogSPS("Sleep Proxy granted lease time %4d seconds, updateid %d, InterfaceID %p", updatelease, mDNSVal16(msg->h.id), InterfaceID);
10147                     }
10148             }
10149             m->rec.r.resrec.RecordType = 0;     // Clear RecordType to show we're not still using it
10150         }
10151 
10152         if (m->CurrentRecord)
10153             LogMsg("mDNSCoreReceiveUpdateR ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
10154         m->CurrentRecord = m->ResourceRecords;
10155         while (m->CurrentRecord)
10156         {
10157             AuthRecord *const rr = m->CurrentRecord;
10158             if (rr->resrec.InterfaceID == InterfaceID || (!rr->resrec.InterfaceID && (rr->ForceMCast || IsLocalDomain(rr->resrec.name))))
10159                 if (mDNSSameOpaque16(rr->updateid, msg->h.id))
10160                 {
10161                     // We successfully completed this record's registration on this "InterfaceID". Clear that bit.
10162                     // Clear the updateid when we are done sending on all interfaces.
10163                     mDNSu32 scopeid = mDNSPlatformInterfaceIndexfromInterfaceID(m, InterfaceID, mDNStrue);
10164                     if (scopeid < (sizeof(rr->updateIntID) * mDNSNBBY))
10165                         bit_clr_opaque64(rr->updateIntID, scopeid);
10166                     if (mDNSOpaque64IsZero(&rr->updateIntID))
10167                         rr->updateid = zeroID;
10168                     rr->expire   = NonZeroTime(m->timenow + updatelease * mDNSPlatformOneSecond);
10169                     LogSPS("Sleep Proxy %s record %5d 0x%x 0x%x (%d) %s", rr->WakeUp.HMAC.l[0] ? "transferred" : "registered", updatelease, rr->updateIntID.l[1], rr->updateIntID.l[0], mDNSVal16(rr->updateid), ARDisplayString(m,rr));
10170                     if (rr->WakeUp.HMAC.l[0])
10171                     {
10172                         rr->WakeUp.HMAC = zeroEthAddr;  // Clear HMAC so that mDNS_Deregister_internal doesn't waste packets trying to wake this host
10173                         rr->RequireGoodbye = mDNSfalse; // and we don't want to send goodbye for it
10174                         mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
10175                     }
10176                 }
10177             // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
10178             // new records could have been added to the end of the list as a result of that call.
10179             if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
10180                 m->CurrentRecord = rr->next;
10181         }
10182 
10183         // Update the dynamic store with the IP Address and MAC address of the sleep proxy
10184         ifname = InterfaceNameForID(m, InterfaceID);
10185         mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
10186         mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
10187     }
10188     // If we were waiting to go to sleep, then this SPS registration or wide-area record deletion
10189     // may have been the thing we were waiting for, so schedule another check to see if we can sleep now.
10190     if (m->SleepLimit) m->NextScheduledSPRetry = m->timenow;
10191 }
10192 
10193 mDNSexport void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
10194                                         const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds, mDNSInterfaceID InterfaceID, DNSServer *dnsserver)
10195 {
10196     if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
10197         LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
10198 
10199     // Create empty resource record
10200     cr->resrec.RecordType    = kDNSRecordTypePacketNegative;
10201     cr->resrec.InterfaceID   = InterfaceID;
10202     cr->resrec.rDNSServer    = dnsserver;
10203     cr->resrec.name          = name;    // Will be updated to point to cg->name when we call CreateNewCacheEntry
10204     cr->resrec.rrtype        = rrtype;
10205     cr->resrec.rrclass       = rrclass;
10206     cr->resrec.rroriginalttl = ttl_seconds;
10207     cr->resrec.rdlength      = 0;
10208     cr->resrec.rdestimate    = 0;
10209     cr->resrec.namehash      = namehash;
10210     cr->resrec.rdatahash     = 0;
10211     cr->resrec.rdata = (RData*)&cr->smallrdatastorage;
10212     cr->resrec.rdata->MaxRDLength = 0;
10213 
10214     cr->NextInKAList       = mDNSNULL;
10215     cr->TimeRcvd           = m->timenow;
10216     cr->DelayDelivery      = 0;
10217     cr->NextRequiredQuery  = m->timenow;
10218     cr->LastUsed           = m->timenow;
10219     cr->CRActiveQuestion   = mDNSNULL;
10220     cr->UnansweredQueries  = 0;
10221     cr->LastUnansweredTime = 0;
10222 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
10223     cr->MPUnansweredQ      = 0;
10224     cr->MPLastUnansweredQT = 0;
10225     cr->MPUnansweredKA     = 0;
10226     cr->MPExpectingKA      = mDNSfalse;
10227 #endif
10228     cr->NextInCFList       = mDNSNULL;
10229     cr->nsec               = mDNSNULL;
10230     cr->soa                = mDNSNULL;
10231     cr->CRDNSSECQuestion   = 0;
10232     // Initialize to the basic one and the caller can set it to more
10233     // specific based on the response if any
10234     cr->responseFlags      = ResponseFlags;
10235 }
10236 
10237 mDNSexport void mDNSCoreReceive(mDNS *const m, void *const pkt, const mDNSu8 *const end,
10238                                 const mDNSAddr *const srcaddr, const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport,
10239                                 const mDNSInterfaceID InterfaceID)
10240 {
10241     mDNSInterfaceID ifid = InterfaceID;
10242     DNSMessage  *msg  = (DNSMessage *)pkt;
10243     const mDNSu8 StdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_StdQuery;
10244     const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
10245     const mDNSu8 UpdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_Update;
10246     const mDNSu8 UpdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_Update;
10247     mDNSu8 QR_OP;
10248     mDNSu8 *ptr = mDNSNULL;
10249     mDNSBool TLS = (dstaddr == (mDNSAddr *)1);  // For debug logs: dstaddr = 0 means TCP; dstaddr = 1 means TLS
10250     if (TLS) dstaddr = mDNSNULL;
10251 
10252 #ifndef UNICAST_DISABLED
10253     if (mDNSSameAddress(srcaddr, &m->Router))
10254     {
10255 #ifdef _LEGACY_NAT_TRAVERSAL_
10256         if (mDNSSameIPPort(srcport, SSDPPort) || (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)))
10257         {
10258             mDNS_Lock(m);
10259             LNT_ConfigureRouterInfo(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
10260             mDNS_Unlock(m);
10261             return;
10262         }
10263 #endif
10264         if (mDNSSameIPPort(srcport, NATPMPPort))
10265         {
10266             mDNS_Lock(m);
10267             uDNS_ReceiveNATPacket(m, InterfaceID, pkt, (mDNSu16)(end - (mDNSu8 *)pkt));
10268             mDNS_Unlock(m);
10269             return;
10270         }
10271     }
10272 #ifdef _LEGACY_NAT_TRAVERSAL_
10273     else if (m->SSDPSocket && mDNSSameIPPort(dstport, m->SSDPSocket->port)) { debugf("Ignoring SSDP response from %#a:%d", srcaddr, mDNSVal16(srcport)); return; }
10274 #endif
10275 
10276 #endif
10277     if ((unsigned)(end - (mDNSu8 *)pkt) < sizeof(DNSMessageHeader))
10278     {
10279         LogMsg("DNS Message from %#a:%d to %#a:%d length %d too short", srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt);
10280         return;
10281     }
10282     QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
10283     // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
10284     ptr = (mDNSu8 *)&msg->h.numQuestions;
10285     msg->h.numQuestions   = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);
10286     msg->h.numAnswers     = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);
10287     msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] << 8 | ptr[5]);
10288     msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] << 8 | ptr[7]);
10289 
10290     if (!m) { LogMsg("mDNSCoreReceive ERROR m is NULL"); return; }
10291 
10292     // We use zero addresses and all-ones addresses at various places in the code to indicate special values like "no address"
10293     // If we accept and try to process a packet with zero or all-ones source address, that could really mess things up
10294     if (srcaddr && !mDNSAddressIsValid(srcaddr)) { debugf("mDNSCoreReceive ignoring packet from %#a", srcaddr); return; }
10295 
10296     mDNS_Lock(m);
10297     m->PktNum++;
10298     if (mDNSOpaque16IsZero(msg->h.id))
10299     {
10300         m->MPktNum++;
10301 #if APPLE_OSX_mDNSResponder
10302         // Track the number of multicast packets received from a source outside our subnet.
10303         // Check the destination address to avoid accounting for spurious packets that
10304         // comes in with message id zero.
10305         if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) &&
10306             mDNSAddressIsAllDNSLinkGroup(dstaddr))
10307         {
10308             m->RemoteSubnet++;
10309         }
10310 #endif // #if APPLE_OSX_mDNSResponder
10311     }
10312 
10313 #ifndef UNICAST_DISABLED
10314     if (!dstaddr || (!mDNSAddressIsAllDNSLinkGroup(dstaddr) && (QR_OP == StdR || QR_OP == UpdR)))
10315         if (!mDNSOpaque16IsZero(msg->h.id)) // uDNS_ReceiveMsg only needs to get real uDNS responses, not "QU" mDNS responses
10316         {
10317             ifid = mDNSInterface_Any;
10318             if (mDNS_PacketLoggingEnabled)
10319                 DumpPacket(m, mStatus_NoError, mDNSfalse, TLS ? "TLS" : !dstaddr ? "TCP" : "UDP", srcaddr, srcport, dstaddr, dstport, msg, end);
10320             uDNS_ReceiveMsg(m, msg, end, srcaddr, srcport);
10321             // Note: mDNSCore also needs to get access to received unicast responses
10322         }
10323 #endif
10324     if      (QR_OP == StdQ) mDNSCoreReceiveQuery   (m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10325     else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end, srcaddr, srcport, dstaddr, dstport, ifid);
10326     else if (QR_OP == UpdQ) mDNSCoreReceiveUpdate  (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceID);
10327     else if (QR_OP == UpdR) mDNSCoreReceiveUpdateR (m, msg, end, srcaddr,                            InterfaceID);
10328     else
10329     {
10330         LogMsg("Unknown DNS packet type %02X%02X from %#-15a:%-5d to %#-15a:%-5d length %d on %p (ignored)",
10331                msg->h.flags.b[0], msg->h.flags.b[1], srcaddr, mDNSVal16(srcport), dstaddr, mDNSVal16(dstport), end - (mDNSu8 *)pkt, InterfaceID);
10332         if (mDNS_LoggingEnabled)
10333         {
10334             int i = 0;
10335             while (i<end - (mDNSu8 *)pkt)
10336             {
10337                 char buffer[128];
10338                 char *p = buffer + mDNS_snprintf(buffer, sizeof(buffer), "%04X", i);
10339                 do if (i<end - (mDNSu8 *)pkt) p += mDNS_snprintf(p, sizeof(buffer), " %02X", ((mDNSu8 *)pkt)[i]);while (++i & 15);
10340                 LogInfo("%s", buffer);
10341             }
10342         }
10343     }
10344     // Packet reception often causes a change to the task list:
10345     // 1. Inbound queries can cause us to need to send responses
10346     // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
10347     // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
10348     // 4. Response packets that answer questions may cause our client to issue new questions
10349     mDNS_Unlock(m);
10350 }
10351 
10352 // ***************************************************************************
10353 #if COMPILER_LIKES_PRAGMA_MARK
10354 #pragma mark -
10355 #pragma mark - Searcher Functions
10356 #endif
10357 
10358 // Targets are considered the same if both queries are untargeted, or
10359 // if both are targeted to the same address+port
10360 // (If Target address is zero, TargetPort is undefined)
10361 #define SameQTarget(A,B) (((A)->Target.type == mDNSAddrType_None && (B)->Target.type == mDNSAddrType_None) || \
10362                           (mDNSSameAddress(& (A)->Target, & (B)->Target) && mDNSSameIPPort((A)->TargetPort, (B)->TargetPort)))
10363 
10364 // Note: We explicitly disallow making a public query be a duplicate of a private one. This is to avoid the
10365 // circular deadlock where a client does a query for something like "dns-sd -Q _dns-query-tls._tcp.company.com SRV"
10366 // and we have a key for company.com, so we try to locate the private query server for company.com, which necessarily entails
10367 // doing a standard DNS query for the _dns-query-tls._tcp SRV record for company.com. If we make the latter (public) query
10368 // a duplicate of the former (private) query, then it will block forever waiting for an answer that will never come.
10369 //
10370 // We keep SuppressUnusable questions separate so that we can return a quick response to them and not get blocked behind
10371 // the queries that are not marked SuppressUnusable. But if the query is not suppressed, they are treated the same as
10372 // non-SuppressUnusable questions. This should be fine as the goal of SuppressUnusable is to return quickly only if it
10373 // is suppressed. If it is not suppressed, we do try all the DNS servers for valid answers like any other question.
10374 // The main reason for this design is that cache entries point to a *single* question and that question is responsible
10375 // for keeping the cache fresh as long as it is active. Having multiple active question for a single cache entry
10376 // breaks this design principle.
10377 //
10378 
10379 // If IsLLQ(Q) is true, it means the question is both:
10380 // (a) long-lived and
10381 // (b) being performed by a unicast DNS long-lived query (either full LLQ, or polling)
10382 // for multicast questions, we don't want to treat LongLived as anything special
10383 #define IsLLQ(Q) ((Q)->LongLived && !mDNSOpaque16IsZero((Q)->TargetQID))
10384 #define IsAWDLIncluded(Q) (((Q)->flags & kDNSServiceFlagsIncludeAWDL) != 0)
10385 
10386 mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
10387 {
10388     DNSQuestion *q;
10389     // Note: A question can only be marked as a duplicate of one that occurs *earlier* in the list.
10390     // This prevents circular references, where two questions are each marked as a duplicate of the other.
10391     // Accordingly, we break out of the loop when we get to 'question', because there's no point searching
10392     // further in the list.
10393     for (q = m->Questions; q && q != question; q=q->next)       // Scan our list for another question
10394         if (q->InterfaceID == question->InterfaceID &&          // with the same InterfaceID,
10395             SameQTarget(q, question)                &&          // and same unicast/multicast target settings
10396             q->qtype      == question->qtype        &&          // type,
10397             q->qclass     == question->qclass       &&          // class,
10398             IsLLQ(q)      == IsLLQ(question)        &&          // and long-lived status matches
10399             (!q->AuthInfo || question->AuthInfo)    &&          // to avoid deadlock, don't make public query dup of a private one
10400             (q->AnonInfo  == question->AnonInfo)    &&          // Anonymous query not a dup of normal query
10401             (q->SuppressQuery == question->SuppressQuery) &&    // Questions that are suppressed/not suppressed
10402             (q->ValidationRequired == question->ValidationRequired) &&  // Questions that require DNSSEC validation
10403             (q->ValidatingResponse == question->ValidatingResponse) &&  // Questions that are validating responses using DNSSEC
10404             (q->DisallowPID == question->DisallowPID)     &&            // Disallowing a PID should not affect a PID that is allowed
10405             (q->BrowseThreshold == question->BrowseThreshold) &&  // browse thresholds must match
10406             q->qnamehash  == question->qnamehash    &&
10407             (IsAWDLIncluded(q) == IsAWDLIncluded(question)) &&  // Inclusion of AWDL interface must match
10408             SameDomainName(&q->qname, &question->qname))        // and name
10409             return(q);
10410     return(mDNSNULL);
10411 }
10412 
10413 // This is called after a question is deleted, in case other identical questions were being suppressed as duplicates
10414 mDNSlocal void UpdateQuestionDuplicates(mDNS *const m, DNSQuestion *const question)
10415 {
10416     DNSQuestion *q;
10417     DNSQuestion *first = mDNSNULL;
10418 
10419     // This is referring to some other question as duplicate. No other question can refer to this
10420     // question as a duplicate.
10421     if (question->DuplicateOf)
10422     {
10423         LogInfo("UpdateQuestionDuplicates: question %p %##s (%s) duplicate of %p %##s (%s)",
10424                 question, question->qname.c, DNSTypeName(question->qtype),
10425                 question->DuplicateOf, question->DuplicateOf->qname.c, DNSTypeName(question->DuplicateOf->qtype));
10426         return;
10427     }
10428 
10429     for (q = m->Questions; q; q=q->next)        // Scan our list of questions
10430         if (q->DuplicateOf == question)         // To see if any questions were referencing this as their duplicate
10431         {
10432             q->DuplicateOf = first;
10433             if (!first)
10434             {
10435                 first = q;
10436                 // If q used to be a duplicate, but now is not,
10437                 // then inherit the state from the question that's going away
10438                 q->LastQTime         = question->LastQTime;
10439                 q->ThisQInterval     = question->ThisQInterval;
10440                 q->ExpectUnicastResp = question->ExpectUnicastResp;
10441                 q->LastAnswerPktNum  = question->LastAnswerPktNum;
10442                 q->RecentAnswerPkts  = question->RecentAnswerPkts;
10443                 q->RequestUnicast    = question->RequestUnicast;
10444                 q->LastQTxTime       = question->LastQTxTime;
10445                 q->CNAMEReferrals    = question->CNAMEReferrals;
10446                 q->nta               = question->nta;
10447                 q->servAddr          = question->servAddr;
10448                 q->servPort          = question->servPort;
10449                 q->qDNSServer        = question->qDNSServer;
10450                 q->validDNSServers   = question->validDNSServers;
10451                 q->unansweredQueries = question->unansweredQueries;
10452                 q->noServerResponse  = question->noServerResponse;
10453                 q->triedAllServersOnce = question->triedAllServersOnce;
10454 
10455                 q->TargetQID         = question->TargetQID;
10456                 if (q->LocalSocket)
10457                 {
10458                     mDNSPlatformUDPClose(q->LocalSocket);
10459                 }
10460 
10461                 q->LocalSocket       = question->LocalSocket;
10462 
10463                 q->state             = question->state;
10464                 //	q->tcp               = question->tcp;
10465                 q->ReqLease          = question->ReqLease;
10466                 q->expire            = question->expire;
10467                 q->ntries            = question->ntries;
10468                 q->id                = question->id;
10469 
10470                 question->LocalSocket = mDNSNULL;
10471                 question->nta        = mDNSNULL;    // If we've got a GetZoneData in progress, transfer it to the newly active question
10472                 //	question->tcp        = mDNSNULL;
10473 
10474                 if (q->LocalSocket)
10475                     debugf("UpdateQuestionDuplicates transferred LocalSocket pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10476 
10477                 if (q->nta)
10478                 {
10479                     LogInfo("UpdateQuestionDuplicates transferred nta pointer for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10480                     q->nta->ZoneDataContext = q;
10481                 }
10482 
10483                 // Need to work out how to safely transfer this state too -- appropriate context pointers need to be updated or the code will crash
10484                 if (question->tcp) LogInfo("UpdateQuestionDuplicates did not transfer tcp pointer");
10485 
10486                 if (question->state == LLQ_Established)
10487                 {
10488                     LogInfo("UpdateQuestionDuplicates transferred LLQ state for %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
10489                     question->state = 0;    // Must zero question->state, or mDNS_StopQuery_internal will clean up and cancel our LLQ from the server
10490                 }
10491 
10492                 SetNextQueryTime(m,q);
10493             }
10494         }
10495 }
10496 
10497 mDNSexport McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout)
10498 {
10499     McastResolver **p = &m->McastResolvers;
10500     McastResolver *tmp = mDNSNULL;
10501 
10502     if (!d) d = (const domainname *)"";
10503 
10504     LogInfo("mDNS_AddMcastResolver: Adding %##s, InterfaceID %p, timeout %u", d->c, interface, timeout);
10505 
10506     mDNS_CheckLock(m);
10507 
10508     while (*p)  // Check if we already have this {interface, domain} tuple registered
10509     {
10510         if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
10511         {
10512             if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
10513             (*p)->flags &= ~McastResolver_FlagDelete;
10514             tmp = *p;
10515             *p = tmp->next;
10516             tmp->next = mDNSNULL;
10517         }
10518         else
10519             p=&(*p)->next;
10520     }
10521 
10522     if (tmp) *p = tmp; // move to end of list, to ensure ordering from platform layer
10523     else
10524     {
10525         // allocate, add to list
10526         *p = mDNSPlatformMemAllocate(sizeof(**p));
10527         if (!*p) LogMsg("mDNS_AddMcastResolver: ERROR!! - malloc");
10528         else
10529         {
10530             (*p)->interface = interface;
10531             (*p)->flags     = McastResolver_FlagNew;
10532             (*p)->timeout   = timeout;
10533             AssignDomainName(&(*p)->domain, d);
10534             (*p)->next = mDNSNULL;
10535         }
10536     }
10537     return(*p);
10538 }
10539 
10540 mDNSinline mDNSs32 PenaltyTimeForServer(mDNS *m, DNSServer *server)
10541 {
10542     mDNSs32 ptime = 0;
10543     if (server->penaltyTime != 0)
10544     {
10545         ptime = server->penaltyTime - m->timenow;
10546         if (ptime < 0)
10547         {
10548             // This should always be a positive value between 0 and DNSSERVER_PENALTY_TIME
10549             // If it does not get reset in ResetDNSServerPenalties for some reason, we do it
10550             // here
10551             LogMsg("PenaltyTimeForServer: PenaltyTime negative %d, (server penaltyTime %d, timenow %d) resetting the penalty",
10552                    ptime, server->penaltyTime, m->timenow);
10553             server->penaltyTime = 0;
10554             ptime = 0;
10555         }
10556     }
10557     return ptime;
10558 }
10559 
10560 //Checks to see whether the newname is a better match for the name, given the best one we have
10561 //seen so far (given in bestcount).
10562 //Returns -1 if the newname is not a better match
10563 //Returns 0 if the newname is the same as the old match
10564 //Returns 1 if the newname is a better match
10565 mDNSlocal int BetterMatchForName(const domainname *name, int namecount, const domainname *newname, int newcount,
10566                                  int bestcount)
10567 {
10568     // If the name contains fewer labels than the new server's domain or the new name
10569     // contains fewer labels than the current best, then it can't possibly be a better match
10570     if (namecount < newcount || newcount < bestcount) return -1;
10571 
10572     // If there is no match, return -1 and the caller will skip this newname for
10573     // selection
10574     //
10575     // If we find a match and the number of labels is the same as bestcount, then
10576     // we return 0 so that the caller can do additional logic to pick one of
10577     // the best based on some other factors e.g., penaltyTime
10578     //
10579     // If we find a match and the number of labels is more than bestcount, then we
10580     // return 1 so that the caller can pick this over the old one.
10581     //
10582     // Note: newcount can either be equal or greater than bestcount beause of the
10583     // check above.
10584 
10585     if (SameDomainName(SkipLeadingLabels(name, namecount - newcount), newname))
10586         return bestcount == newcount ? 0 : 1;
10587     else
10588         return -1;
10589 }
10590 
10591 // Normally, we have McastResolvers for .local, in-addr.arpa and ip6.arpa. But there
10592 // can be queries that can forced to multicast (ForceMCast) even though they don't end in these
10593 // names. In that case, we give a default timeout of 5 seconds
10594 #define DEFAULT_MCAST_TIMEOUT   5
10595 mDNSlocal mDNSu32 GetTimeoutForMcastQuestion(mDNS *m, DNSQuestion *question)
10596 {
10597     McastResolver *curmatch = mDNSNULL;
10598     int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10599     McastResolver *curr;
10600     int bettermatch, currcount;
10601     for (curr = m->McastResolvers; curr; curr = curr->next)
10602     {
10603         currcount = CountLabels(&curr->domain);
10604         bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10605         // Take the first best match. If there are multiple equally good matches (bettermatch = 0), we take
10606         // the timeout value from the first one
10607         if (bettermatch == 1)
10608         {
10609             curmatch = curr;
10610             bestmatchlen = currcount;
10611         }
10612     }
10613     LogInfo("GetTimeoutForMcastQuestion: question %##s curmatch %p, Timeout %d", question->qname.c, curmatch,
10614             curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10615     return ( curmatch ? curmatch->timeout : DEFAULT_MCAST_TIMEOUT);
10616 }
10617 
10618 // Returns true if it is a Domain Enumeration Query
10619 mDNSexport mDNSBool DomainEnumQuery(const domainname *qname)
10620 {
10621     const mDNSu8 *mDNS_DEQLabels[] = { (const mDNSu8 *)"\001b", (const mDNSu8 *)"\002db", (const mDNSu8 *)"\002lb",
10622                                        (const mDNSu8 *)"\001r", (const mDNSu8 *)"\002dr", (const mDNSu8 *)mDNSNULL, };
10623     const domainname *d = qname;
10624     const mDNSu8 *label;
10625     int i = 0;
10626 
10627     // We need at least 3 labels (DEQ prefix) + one more label to make a meaningful DE query
10628     if (CountLabels(qname) < 4) { debugf("DomainEnumQuery: question %##s, not enough labels", qname->c); return mDNSfalse; }
10629 
10630     label = (const mDNSu8 *)d;
10631     while (mDNS_DEQLabels[i] != (const mDNSu8 *)mDNSNULL)
10632     {
10633         if (SameDomainLabel(mDNS_DEQLabels[i], label)) {debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c); break;}
10634         i++;
10635     }
10636     if (mDNS_DEQLabels[i] == (const mDNSu8 *)mDNSNULL)
10637     {
10638         debugf("DomainEnumQuery: Not a DEQ %##s, label1 mismatch", qname->c);
10639         return mDNSfalse;
10640     }
10641     debugf("DomainEnumQuery: DEQ %##s, label1 match", qname->c);
10642 
10643     // CountLabels already verified the number of labels
10644     d = (const domainname *)(d->c + 1 + d->c[0]);   // Second Label
10645     label = (const mDNSu8 *)d;
10646     if (!SameDomainLabel(label, (const mDNSu8 *)"\007_dns-sd"))
10647     {
10648         debugf("DomainEnumQuery: Not a DEQ %##s, label2 mismatch", qname->c);
10649         return(mDNSfalse);
10650     }
10651     debugf("DomainEnumQuery: DEQ %##s, label2 match", qname->c);
10652 
10653     d = (const domainname *)(d->c + 1 + d->c[0]);   // Third Label
10654     label = (const mDNSu8 *)d;
10655     if (!SameDomainLabel(label, (const mDNSu8 *)"\004_udp"))
10656     {
10657         debugf("DomainEnumQuery: Not a DEQ %##s, label3 mismatch", qname->c);
10658         return(mDNSfalse);
10659     }
10660     debugf("DomainEnumQuery: DEQ %##s, label3 match", qname->c);
10661 
10662     debugf("DomainEnumQuery: Question %##s is a Domain Enumeration query", qname->c);
10663 
10664     return mDNStrue;
10665 }
10666 
10667 // Note: InterfaceID is the InterfaceID of the question
10668 mDNSlocal mDNSBool DNSServerMatch(DNSServer *d, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
10669 {
10670     // 1) Unscoped questions (NULL InterfaceID) should  consider *only* unscoped DNSServers ( DNSServer
10671     // with "scoped" set to kScopeNone)
10672     //
10673     // 2) Scoped questions (non-NULL InterfaceID) should consider *only* scoped DNSServers (DNSServer
10674     // with "scoped" set to kScopeInterfaceId) and their InterfaceIDs should match.
10675     //
10676     // 3) Scoped questions (non-zero ServiceID) should consider *only* scoped DNSServers (DNSServer
10677     // with "scoped" set to kScopeServiceID) and their ServiceIDs should match.
10678     //
10679     // The first condition in the "if" statement checks to see if both the question and the DNSServer are
10680     // unscoped. The question is unscoped only if InterfaceID is zero and ServiceID is -1.
10681     //
10682     // If the first condition fails, following are the possible cases (the notes below are using
10683     // InterfaceID for discussion and the same holds good for ServiceID):
10684     //
10685     // - DNSServer is not scoped, InterfaceID is not NULL - we should skip the current DNSServer entry
10686     //   as scoped questions should not pick non-scoped DNSServer entry (Refer to (2) above).
10687     //
10688     // - DNSServer is scoped, InterfaceID is NULL - we should skip the current DNSServer entry as
10689     //   unscoped question should not match scoped DNSServer (Refer to (1) above). The InterfaceID check
10690     //   would fail in this case.
10691     //
10692     // - DNSServer is scoped and InterfaceID is not NULL - the InterfaceID of the question and the DNSServer
10693     //   should match (Refer to (2) above).
10694     //
10695     // Note: mDNSInterface_Unicast is used only by .local unicast questions and are treated as unscoped.
10696     // If a question is scoped both to InterfaceID and ServiceID, the question will be scoped to InterfaceID.
10697 
10698     if (((d->scoped == kScopeNone) && ((!InterfaceID && ServiceID == -1) || InterfaceID == mDNSInterface_Unicast)) ||
10699         ((d->scoped == kScopeInterfaceID) && d->interface == InterfaceID) ||
10700         ((d->scoped == kScopeServiceID) && d->serviceID == ServiceID))
10701     {
10702         return mDNStrue;
10703     }
10704     return mDNSfalse;
10705 }
10706 
10707 // Sets all the Valid DNS servers for a question
10708 mDNSexport mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question)
10709 {
10710     int bestmatchlen = -1, namecount = CountLabels(&question->qname);
10711     DNSServer *curr;
10712     int bettermatch, currcount;
10713     int index = 0;
10714     mDNSu32 timeout = 0;
10715     mDNSBool DEQuery;
10716 
10717     question->validDNSServers = zeroOpaque64;
10718     DEQuery = DomainEnumQuery(&question->qname);
10719     for (curr = m->DNSServers; curr; curr = curr->next)
10720     {
10721         debugf("SetValidDNSServers: Parsing DNS server Address %#a (Domain %##s), Scope: %d", &curr->addr, curr->domain.c, curr->scoped);
10722         // skip servers that will soon be deleted
10723         if (curr->flags & DNSServer_FlagDelete)
10724         {
10725             debugf("SetValidDNSServers: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped);
10726             continue;
10727         }
10728 
10729         // This happens normally when you unplug the interface where we reset the interfaceID to mDNSInterface_Any for all
10730         // the DNS servers whose scope match the interfaceID. Few seconds later, we also receive the updated DNS configuration.
10731         // But any questions that has mDNSInterface_Any scope that are started/restarted before we receive the update
10732         // (e.g., CheckSuppressUnusableQuestions is called when interfaces are deregistered with the core) should not
10733         // match the scoped entries by mistake.
10734         //
10735         // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
10736 
10737         // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
10738         if ((curr->scoped == kScopeInterfaceID && curr->interface == mDNSInterface_Any) || (curr->scoped == kScopeServiceID && curr->serviceID <= 0))
10739         {
10740             LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]", curr->scoped, &curr->addr, curr->domain.c, curr->interface, curr->serviceID);
10741             continue;
10742         }
10743 
10744         currcount = CountLabels(&curr->domain);
10745         if ((!DEQuery || !curr->cellIntf) && DNSServerMatch(curr, question->InterfaceID, question->ServiceID))
10746         {
10747             bettermatch = BetterMatchForName(&question->qname, namecount, &curr->domain, currcount, bestmatchlen);
10748 
10749             // If we found a better match (bettermatch == 1) then clear all the bits
10750             // corresponding to the old DNSServers that we have may set before and start fresh.
10751             // If we find an equal match, then include that DNSServer also by setting the corresponding
10752             // bit
10753             if ((bettermatch == 1) || (bettermatch == 0))
10754             {
10755                 bestmatchlen = currcount;
10756                 if (bettermatch)
10757                 {
10758                     debugf("SetValidDNSServers: Resetting all the bits");
10759                     question->validDNSServers = zeroOpaque64;
10760                     timeout = 0;
10761                 }
10762                 debugf("SetValidDNSServers: question %##s Setting the bit for DNS server Address %#a (Domain %##s), Scoped:%d index %d,"
10763                        " Timeout %d, interface %p", question->qname.c, &curr->addr, curr->domain.c, curr->scoped, index, curr->timeout,
10764                        curr->interface);
10765                 timeout += curr->timeout;
10766                 if (DEQuery)
10767                     debugf("DomainEnumQuery: Question %##s, DNSServer %#a, cell %d", question->qname.c, &curr->addr, curr->cellIntf);
10768                 bit_set_opaque64(question->validDNSServers, index);
10769             }
10770         }
10771         index++;
10772     }
10773     question->noServerResponse = 0;
10774 
10775     debugf("SetValidDNSServers: ValidDNSServer bits  0x%x%x for question %p %##s (%s)",
10776            question->validDNSServers.l[1], question->validDNSServers.l[0], question, question->qname.c, DNSTypeName(question->qtype));
10777     // If there are no matching resolvers, then use the default timeout value.
10778     // For ProxyQuestion, shorten the timeout so that dig does not timeout on us in case of no response.
10779     return ((question->ProxyQuestion || question->ValidatingResponse) ? DEFAULT_UDNSSEC_TIMEOUT : timeout ? timeout : DEFAULT_UDNS_TIMEOUT);
10780 }
10781 
10782 // Get the Best server that matches a name. If you find penalized servers, look for the one
10783 // that will come out of the penalty box soon
10784 mDNSlocal DNSServer *GetBestServer(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID, mDNSOpaque64 validBits,
10785     int *selected, mDNSBool nameMatch)
10786 {
10787     DNSServer *curmatch = mDNSNULL;
10788     int bestmatchlen = -1, namecount = name ? CountLabels(name) : 0;
10789     DNSServer *curr;
10790     mDNSs32 bestPenaltyTime, currPenaltyTime;
10791     int bettermatch, currcount;
10792     int index = 0;
10793     int currindex = -1;
10794 
10795     debugf("GetBestServer: ValidDNSServer bits  0x%x%x", validBits.l[1], validBits.l[0]);
10796     bestPenaltyTime = DNSSERVER_PENALTY_TIME + 1;
10797     for (curr = m->DNSServers; curr; curr = curr->next)
10798     {
10799         // skip servers that will soon be deleted
10800         if (curr->flags & DNSServer_FlagDelete)
10801         {
10802             debugf("GetBestServer: Delete set for index %d, DNS server %#a (Domain %##s), scoped %d", index, &curr->addr, curr->domain.c, curr->scoped);
10803             continue;
10804         }
10805 
10806         // Check if this is a valid DNSServer
10807         if (!bit_get_opaque64(validBits, index))
10808         {
10809             debugf("GetBestServer: continuing for index %d", index);
10810             index++;
10811             continue;
10812         }
10813 
10814         currcount = CountLabels(&curr->domain);
10815         currPenaltyTime = PenaltyTimeForServer(m, curr);
10816 
10817         debugf("GetBestServer: Address %#a (Domain %##s), PenaltyTime(abs) %d, PenaltyTime(rel) %d",
10818                &curr->addr, curr->domain.c, curr->penaltyTime, currPenaltyTime);
10819 
10820         // If there are multiple best servers for a given question, we will pick the first one
10821         // if none of them are penalized. If some of them are penalized in that list, we pick
10822         // the least penalized one. BetterMatchForName walks through all best matches and
10823         // "currPenaltyTime < bestPenaltyTime" check lets us either pick the first best server
10824         // in the list when there are no penalized servers and least one among them
10825         // when there are some penalized servers.
10826 
10827         if (DNSServerMatch(curr, InterfaceID, ServiceID))
10828         {
10829 
10830             // If we know that all the names are already equally good matches, then skip calling BetterMatchForName.
10831             // This happens when we initially walk all the DNS servers and set the validity bit on the question.
10832             // Actually we just need PenaltyTime match, but for the sake of readability we just skip the expensive
10833             // part and still do some redundant steps e.g., InterfaceID match
10834 
10835             if (nameMatch)
10836                 bettermatch = BetterMatchForName(name, namecount, &curr->domain, currcount, bestmatchlen);
10837             else
10838                 bettermatch = 0;
10839 
10840             // If we found a better match (bettermatch == 1) then we don't need to
10841             // compare penalty times. But if we found an equal match, then we compare
10842             // the penalty times to pick a better match
10843 
10844             if ((bettermatch == 1) || ((bettermatch == 0) && currPenaltyTime < bestPenaltyTime))
10845             {
10846                 currindex = index;
10847                 curmatch = curr;
10848                 bestmatchlen = currcount;
10849                 bestPenaltyTime = currPenaltyTime;
10850             }
10851         }
10852         index++;
10853     }
10854     if (selected) *selected = currindex;
10855     return curmatch;
10856 }
10857 
10858 // Look up a DNS Server, matching by name and InterfaceID
10859 mDNSlocal DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID, mDNSs32 ServiceID)
10860 {
10861     DNSServer *curmatch = mDNSNULL;
10862     char *ifname = mDNSNULL;    // for logging purposes only
10863     mDNSOpaque64 allValid;
10864 
10865     if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
10866         InterfaceID = mDNSNULL;
10867 
10868     if (InterfaceID) ifname = InterfaceNameForID(m, InterfaceID);
10869 
10870     // By passing in all ones, we make sure that every DNS server is considered
10871     allValid.l[0] = allValid.l[1] = 0xFFFFFFFF;
10872 
10873     curmatch = GetBestServer(m, name, InterfaceID, ServiceID, allValid, mDNSNULL, mDNStrue);
10874 
10875     if (curmatch != mDNSNULL)
10876         LogInfo("GetServerForName: DNS server %#a:%d (Penalty Time Left %d) (Scope %s:%p) found for name %##s", &curmatch->addr,
10877                 mDNSVal16(curmatch->port), (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
10878                 InterfaceID, name);
10879     else
10880         LogInfo("GetServerForName: no DNS server (Scope %s:%p) found for name %##s", ifname ? ifname : "None", InterfaceID, name);
10881 
10882     return(curmatch);
10883 }
10884 
10885 // Look up a DNS Server for a question within its valid DNSServer bits
10886 mDNSexport DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question)
10887 {
10888     DNSServer *curmatch = mDNSNULL;
10889     char *ifname = mDNSNULL;    // for logging purposes only
10890     mDNSInterfaceID InterfaceID = question->InterfaceID;
10891     const domainname *name = &question->qname;
10892     int currindex;
10893 
10894     if ((InterfaceID == mDNSInterface_Unicast) || (InterfaceID == mDNSInterface_LocalOnly))
10895         InterfaceID = mDNSNULL;
10896 
10897     if (InterfaceID)
10898         ifname = InterfaceNameForID(m, InterfaceID);
10899 
10900     if (!mDNSOpaque64IsZero(&question->validDNSServers))
10901     {
10902         curmatch = GetBestServer(m, name, InterfaceID, question->ServiceID, question->validDNSServers, &currindex, mDNSfalse);
10903         if (currindex != -1)
10904             bit_clr_opaque64(question->validDNSServers, currindex);
10905     }
10906 
10907     if (curmatch != mDNSNULL)
10908     {
10909         LogInfo("GetServerForQuestion: %p DNS server (%p) %#a:%d (Penalty Time Left %d) (Scope %s:%p:%d) found for name %##s (%s)",
10910                 question, curmatch, &curmatch->addr, mDNSVal16(curmatch->port),
10911                 (curmatch->penaltyTime ? (curmatch->penaltyTime - m->timenow) : 0), ifname ? ifname : "None",
10912                 InterfaceID, question->ServiceID, name, DNSTypeName(question->qtype));
10913     }
10914     else
10915     {
10916         LogInfo("GetServerForQuestion: %p no DNS server (Scope %s:%p:%d) found for name %##s (%s)",
10917             question, ifname ? ifname : "None", InterfaceID, question->ServiceID, name, DNSTypeName(question->qtype));
10918     }
10919 
10920     return(curmatch);
10921 }
10922 
10923 
10924 #define ValidQuestionTarget(Q) (((Q)->Target.type == mDNSAddrType_IPv4 || (Q)->Target.type == mDNSAddrType_IPv6) && \
10925                                 (mDNSSameIPPort((Q)->TargetPort, UnicastDNSPort) || mDNSSameIPPort((Q)->TargetPort, MulticastDNSPort)))
10926 
10927 // Called in normal client context (lock not held)
10928 mDNSlocal void LLQNATCallback(mDNS *m, NATTraversalInfo *n)
10929 {
10930     DNSQuestion *q;
10931     mDNS_Lock(m);
10932     LogInfo("LLQNATCallback external address:port %.4a:%u, NAT result %d", &n->ExternalAddress, mDNSVal16(n->ExternalPort), n->Result);
10933     n->clientContext = mDNSNULL; // we received at least one callback since starting this NAT-T
10934     for (q = m->Questions; q; q=q->next)
10935         if (ActiveQuestion(q) && !mDNSOpaque16IsZero(q->TargetQID) && q->LongLived)
10936             startLLQHandshake(m, q);    // If ExternalPort is zero, will do StartLLQPolling instead
10937 #if APPLE_OSX_mDNSResponder
10938     UpdateAutoTunnelDomainStatuses(m);
10939 #endif
10940     mDNS_Unlock(m);
10941 }
10942 
10943 mDNSlocal mDNSBool IsPrivateDomain(mDNS *const m, DNSQuestion *q)
10944 {
10945     DomainAuthInfo *AuthInfo;
10946     // Skip Private domains as we have special addresses to get the hosts in the Private domain
10947     AuthInfo = GetAuthInfoForName_internal(m, &q->qname);
10948     if (AuthInfo && !AuthInfo->deltime && AuthInfo->AutoTunnel)
10949     {
10950         debugf("IsPrivateDomain: %##s true", q->qname.c);
10951         return mDNStrue;
10952     }
10953     else
10954     {
10955         debugf("IsPrivateDomain: %##s false", q->qname.c);
10956         return mDNSfalse;
10957     }
10958 }
10959 
10960 // This function takes the DNSServer as a separate argument because sometimes the
10961 // caller has not yet assigned the DNSServer, but wants to evaluate the SuppressQuery
10962 // status before switching to it.
10963 mDNSlocal mDNSBool ShouldSuppressUnicastQuery(mDNS *const m, DNSQuestion *q, DNSServer *d)
10964 {
10965     // Some callers don't check for the qtype
10966     if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA)
10967     {
10968         LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q->qname.c, DNSTypeName(q->qtype));
10969         return mDNSfalse;
10970     }
10971 
10972     // Private domains are exempted irrespective of what the DNSServer says
10973     if (IsPrivateDomain(m, q))
10974     {
10975         LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, Private Domain", q->qname.c, DNSTypeName(q->qtype));
10976         return mDNSfalse;
10977     }
10978 
10979     if (!d)
10980     {
10981         LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, as the DNS server is NULL", q->qname.c, DNSTypeName(q->qtype));
10982         return mDNStrue;
10983     }
10984 
10985     // Check if the DNS Configuration allows A/AAAA queries to be sent
10986     if ((q->qtype == kDNSType_A) && (d->req_A))
10987     {
10988         LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows A queries", q->qname.c,
10989                 DNSTypeName(q->qtype), d->domain.c, &d->addr, mDNSVal16(d->port));
10990         return mDNSfalse;
10991     }
10992     if ((q->qtype == kDNSType_AAAA) && (d->req_AAAA))
10993     {
10994         LogInfo("ShouldSuppressUnicastQuery: Query not suppressed for %##s, qtype %s, DNSServer %##s %#a:%d allows AAAA queries", q->qname.c,
10995                 DNSTypeName(q->qtype), d->domain.c, &d->addr, mDNSVal16(d->port));
10996         return mDNSfalse;
10997     }
10998 
10999     LogInfo("ShouldSuppressUnicastQuery: Query suppressed for %##s, qtype %s, since DNS Configuration does not allow (req_A is %s and req_AAAA is %s)",
11000         q->qname.c, DNSTypeName(q->qtype), d->req_A ? "true" : "false", d->req_AAAA ? "true" : "false");
11001 
11002     return mDNStrue;
11003 }
11004 
11005 mDNSlocal mDNSBool ShouldSuppressDotLocalQuery(mDNS *const m, DNSQuestion *q)
11006 {
11007     NetworkInterfaceInfo *intf;
11008     AuthRecord *rr;
11009     mDNSBool ret;
11010 
11011     // Check to see if there is at least one interface other than loopback and don't suppress
11012     // .local questions if you find one. If we have at least one interface, it means that
11013     // we can send unicast queries for the .local name and we don't want to suppress
11014     // multicast in that case as upper layers don't know how to handle if we return a
11015     // negative response for multicast followed by a positive response for unicast.
11016     //
11017     // Note: we used to check for multicast capable interfaces instead of just any interface
11018     // present. That did not work in the case where we have a valid interface for unicast
11019     // but not multicast capable e.g., cellular, as we ended up delivering a negative response
11020     // first and the upper layer did not wait for the positive response that came later.
11021     for (intf = m->HostInterfaces; intf; intf = intf->next)
11022     {
11023         if (intf->InterfaceActive && !intf->Loopback)
11024         {
11025             LogInfo("ShouldSuppressDotLocalQuery: Found interface %s, not suppressing", intf->ifname);
11026             return mDNSfalse;
11027         }
11028     }
11029 
11030     // 1. If we find a LocalOnly or P2P record answering this question, then don't suppress it.
11031     //    Set m->CurrentQuestion as it is required by AnswerQuestionWithLORecord.
11032     m->CurrentQuestion = q;
11033     ret = AnswerQuestionWithLORecord(m, q, mDNStrue);
11034     m->CurrentQuestion = mDNSNULL;
11035 
11036     if (ret)
11037     {
11038         LogInfo("ShouldSuppressDotLocalQuery: Found LocalOnly record for %##s (%s), not suppressing", q->qname.c,
11039             DNSTypeName(q->qtype));
11040         return mDNSfalse;
11041     }
11042 
11043     // 2. If we find a local AuthRecord answering this question, then don't suppress it.
11044     for (rr = m->ResourceRecords; rr; rr = rr->next)
11045     {
11046         if (ResourceRecordAnswersQuestion(&rr->resrec, q))
11047         {
11048             LogInfo("ShouldSuppressDotLocalQuery: Found resource record %s for %##s (%s) not suppressing", ARDisplayString(m, rr),
11049                 q->qname.c, DNSTypeName(q->qtype));
11050             return mDNSfalse;
11051         }
11052     }
11053     return mDNStrue;
11054 }
11055 
11056 mDNSlocal mDNSBool ShouldSuppressQuery(mDNS *const m, DNSQuestion *q)
11057 {
11058     if (q->qtype != kDNSType_A && q->qtype != kDNSType_AAAA)
11059     {
11060         LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, not A/AAAA type", q->qname.c, DNSTypeName(q->qtype));
11061         return mDNSfalse;
11062     }
11063 
11064     // We still want the ability to be able to listen to the local services and hence
11065     // don't fail .local query if we have local records that can potentially answer
11066     // the question.
11067     if (q->InterfaceID != mDNSInterface_Unicast && IsLocalDomain(&q->qname))
11068     {
11069         if (!ShouldSuppressDotLocalQuery(m, q))
11070         {
11071             LogInfo("ShouldSuppressQuery: Query not suppressed for %##s, qtype %s, Local question", q->qname.c, DNSTypeName(q->qtype));
11072             return mDNSfalse;
11073         }
11074         else
11075         {
11076             LogInfo("ShouldSuppressQuery: Query suppressed for %##s, qtype %s, Local question", q->qname.c, DNSTypeName(q->qtype));
11077             return mDNStrue;
11078         }
11079     }
11080 
11081     return (ShouldSuppressUnicastQuery(m, q, q->qDNSServer));
11082 }
11083 
11084 mDNSlocal void CacheRecordRmvEventsForCurrentQuestion(mDNS *const m, DNSQuestion *q)
11085 {
11086     CacheRecord *rr;
11087     mDNSu32 slot;
11088     CacheGroup *cg;
11089 
11090     slot = HashSlot(&q->qname);
11091     cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
11092     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
11093     {
11094         // Don't deliver RMV events for negative records
11095         if (rr->resrec.RecordType == kDNSRecordTypePacketNegative)
11096         {
11097             LogInfo("CacheRecordRmvEventsForCurrentQuestion: CacheRecord %s Suppressing RMV events for question %p %##s (%s), CRActiveQuestion %p, CurrentAnswers %d",
11098                     CRDisplayString(m, rr), q, q->qname.c, DNSTypeName(q->qtype), rr->CRActiveQuestion, q->CurrentAnswers);
11099             continue;
11100         }
11101 
11102         if (SameNameRecordAnswersQuestion(&rr->resrec, q))
11103         {
11104             LogInfo("CacheRecordRmvEventsForCurrentQuestion: Calling AnswerCurrentQuestionWithResourceRecord (RMV) for question %##s using resource record %s LocalAnswers %d",
11105                     q->qname.c, CRDisplayString(m, rr), q->LOAddressAnswers);
11106 
11107             q->CurrentAnswers--;
11108             if (rr->resrec.rdlength > SmallRecordLimit) q->LargeAnswers--;
11109             if (rr->resrec.RecordType & kDNSRecordTypePacketUniqueMask) q->UniqueAnswers--;
11110 
11111             if (rr->CRActiveQuestion == q)
11112             {
11113                 DNSQuestion *qptr;
11114                 // If this was the active question for this cache entry, it was the one that was
11115                 // responsible for keeping the cache entry fresh when the cache entry was reaching
11116                 // its expiry. We need to handover the responsibility to someone else. Otherwise,
11117                 // when the cache entry is about to expire, we won't find an active question
11118                 // (pointed by CRActiveQuestion) to refresh the cache.
11119                 for (qptr = m->Questions; qptr; qptr=qptr->next)
11120                     if (qptr != q && ActiveQuestion(qptr) && ResourceRecordAnswersQuestion(&rr->resrec, qptr))
11121                         break;
11122 
11123                 if (qptr)
11124                     LogInfo("CacheRecordRmvEventsForCurrentQuestion: Updating CRActiveQuestion to %p for cache record %s, "
11125                             "Original question CurrentAnswers %d, new question CurrentAnswers %d, SuppressUnusable %d, SuppressQuery %d",
11126                             qptr, CRDisplayString(m,rr), q->CurrentAnswers, qptr->CurrentAnswers, qptr->SuppressUnusable, qptr->SuppressQuery);
11127 
11128                 rr->CRActiveQuestion = qptr;        // Question used to be active; new value may or may not be null
11129                 if (!qptr) m->rrcache_active--; // If no longer active, decrement rrcache_active count
11130             }
11131             AnswerCurrentQuestionWithResourceRecord(m, rr, QC_rmv);
11132             if (m->CurrentQuestion != q) break;     // If callback deleted q, then we're finished here
11133         }
11134     }
11135 }
11136 
11137 mDNSlocal mDNSBool IsQuestionNew(mDNS *const m, DNSQuestion *question)
11138 {
11139     DNSQuestion *q;
11140     for (q = m->NewQuestions; q; q = q->next)
11141         if (q == question) return mDNStrue;
11142     return mDNSfalse;
11143 }
11144 
11145 mDNSlocal mDNSBool LocalRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11146 {
11147     AuthRecord *rr;
11148     mDNSu32 slot;
11149     AuthGroup *ag;
11150 
11151     if (m->CurrentQuestion)
11152         LogMsg("LocalRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11153                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11154 
11155     if (IsQuestionNew(m, q))
11156     {
11157         LogInfo("LocalRecordRmvEventsForQuestion: New Question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11158         return mDNStrue;
11159     }
11160     m->CurrentQuestion = q;
11161     slot = AuthHashSlot(&q->qname);
11162     ag = AuthGroupForName(&m->rrauth, slot, q->qnamehash, &q->qname);
11163     if (ag)
11164     {
11165         for (rr = ag->members; rr; rr=rr->next)
11166             // Filter the /etc/hosts records - LocalOnly, Unique, A/AAAA/CNAME
11167             if (UniqueLocalOnlyRecord(rr) && LocalOnlyRecordAnswersQuestion(rr, q))
11168             {
11169                 LogInfo("LocalRecordRmvEventsForQuestion: Delivering possible Rmv events with record %s",
11170                         ARDisplayString(m, rr));
11171                 if (q->CurrentAnswers <= 0 || q->LOAddressAnswers <= 0)
11172                 {
11173                     LogMsg("LocalRecordRmvEventsForQuestion: ERROR!! CurrentAnswers or LOAddressAnswers is zero %p %##s"
11174                            " (%s) CurrentAnswers %d, LOAddressAnswers %d", q, q->qname.c, DNSTypeName(q->qtype),
11175                            q->CurrentAnswers, q->LOAddressAnswers);
11176                     continue;
11177                 }
11178                 AnswerLocalQuestionWithLocalAuthRecord(m, rr, QC_rmv);      // MUST NOT dereference q again
11179                 if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11180             }
11181     }
11182     m->CurrentQuestion = mDNSNULL;
11183     return mDNStrue;
11184 }
11185 
11186 // Returns false if the question got deleted while delivering the RMV events
11187 // The caller should handle the case
11188 mDNSlocal mDNSBool CacheRecordRmvEventsForQuestion(mDNS *const m, DNSQuestion *q)
11189 {
11190     if (m->CurrentQuestion)
11191         LogMsg("CacheRecordRmvEventsForQuestion: ERROR m->CurrentQuestion already set: %##s (%s)",
11192                m->CurrentQuestion->qname.c, DNSTypeName(m->CurrentQuestion->qtype));
11193 
11194     // If it is a new question, we have not delivered any ADD events yet. So, don't deliver RMV events.
11195     // If this question was answered using local auth records, then you can't deliver RMVs using cache
11196     if (!IsQuestionNew(m, q) && !q->LOAddressAnswers)
11197     {
11198         m->CurrentQuestion = q;
11199         CacheRecordRmvEventsForCurrentQuestion(m, q);
11200         if (m->CurrentQuestion != q) { m->CurrentQuestion = mDNSNULL; return mDNSfalse; }
11201         m->CurrentQuestion = mDNSNULL;
11202     }
11203     else { LogInfo("CacheRecordRmvEventsForQuestion: Question %p %##s (%s) is a new question", q, q->qname.c, DNSTypeName(q->qtype)); }
11204     return mDNStrue;
11205 }
11206 
11207 mDNSlocal void SuppressStatusChanged(mDNS *const m, DNSQuestion *q, DNSQuestion **restart)
11208 {
11209     // NOTE: CacheRecordRmvEventsForQuestion will not generate RMV events for queries that have non-zero
11210     // LOAddressAnswers. Hence it is important that we call CacheRecordRmvEventsForQuestion before
11211     // LocalRecordRmvEventsForQuestion (which decrements LOAddressAnswers)
11212     if (q->SuppressQuery)
11213     {
11214         q->SuppressQuery = mDNSfalse;
11215         if (!CacheRecordRmvEventsForQuestion(m, q))
11216         {
11217             LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from cache");
11218             return;
11219         }
11220         q->SuppressQuery = mDNStrue;
11221     }
11222 
11223     // SuppressUnusable does not affect questions that are answered from the local records (/etc/hosts)
11224     // and SuppressQuery status does not mean anything for these questions. As we are going to stop the
11225     // question below, we need to deliver the RMV events so that the ADDs that will be delivered during
11226     // the restart will not be a duplicate ADD
11227     if (!LocalRecordRmvEventsForQuestion(m, q))
11228     {
11229         LogInfo("SuppressStatusChanged: Question deleted while delivering RMV events from Local AuthRecords");
11230         return;
11231     }
11232 
11233     // There are two cases here.
11234     //
11235     // 1. Previously it was suppressed and now it is not suppressed, restart the question so
11236     // that it will start as a new question. Note that we can't just call ActivateUnicastQuery
11237     // because when we get the response, if we had entries in the cache already, it will not answer
11238     // this question if the cache entry did not change. Hence, we need to restart
11239     // the query so that it can be answered from the cache.
11240     //
11241     // 2. Previously it was not suppressed and now it is suppressed. We need to restart the questions
11242     // so that we redo the duplicate checks in mDNS_StartQuery_internal. A SuppressUnusable question
11243     // is a duplicate of non-SuppressUnusable question if it is not suppressed (SuppressQuery is false).
11244     // A SuppressUnusable question is not a duplicate of non-SuppressUnusable question if it is suppressed
11245     // (SuppressQuery is true). The reason for this is that when a question is suppressed, we want an
11246     // immediate response and not want to be blocked behind a question that is querying DNS servers. When
11247     // the question is not suppressed, we don't want two active questions sending packets on the wire.
11248     // This affects both efficiency and also the current design where there is only one active question
11249     // pointed to from a cache entry.
11250     //
11251     // We restart queries in a two step process by first calling stop and build a temporary list which we
11252     // will restart at the end. The main reason for the two step process is to handle duplicate questions.
11253     // If there are duplicate questions, calling stop inherits the values from another question on the list (which
11254     // will soon become the real question) including q->ThisQInterval which might be zero if it was
11255     // suppressed before. At the end when we have restarted all questions, none of them is active as each
11256     // inherits from one another and we need to reactivate one of the questions here which is a little hacky.
11257     //
11258     // It is much cleaner and less error prone to build a list of questions and restart at the end.
11259 
11260     LogInfo("SuppressStatusChanged: Stop question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11261     mDNS_StopQuery_internal(m, q);
11262     q->next = *restart;
11263     *restart = q;
11264 }
11265 
11266 // The caller should hold the lock
11267 mDNSexport void CheckSuppressUnusableQuestions(mDNS *const m)
11268 {
11269     DNSQuestion *q;
11270     DNSQuestion *restart = mDNSNULL;
11271 
11272     // We look through all questions including new questions. During network change events,
11273     // we potentially restart questions here in this function that ends up as new questions,
11274     // which may be suppressed at this instance. Before it is handled we get another network
11275     // event that changes the status e.g., address becomes available. If we did not process
11276     // new questions, we would never change its SuppressQuery status.
11277     //
11278     // CurrentQuestion is used by RmvEventsForQuestion below. While delivering RMV events, the
11279     // application callback can potentially stop the current question (detected by CurrentQuestion) or
11280     // *any* other question which could be the next one that we may process here. RestartQuestion
11281     // points to the "next" question which will be automatically advanced in mDNS_StopQuery_internal
11282     // if the "next" question is stopped while the CurrentQuestion is stopped
11283     if (m->RestartQuestion)
11284         LogMsg("CheckSuppressUnusableQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11285                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11286     m->RestartQuestion = m->Questions;
11287     while (m->RestartQuestion)
11288     {
11289         q = m->RestartQuestion;
11290         m->RestartQuestion = q->next;
11291         if (q->SuppressUnusable)
11292         {
11293             mDNSBool old = q->SuppressQuery;
11294             q->SuppressQuery = ShouldSuppressQuery(m, q);
11295             if (q->SuppressQuery != old)
11296             {
11297                 // Previously it was not suppressed, Generate RMV events for the ADDs that we might have delivered before
11298                 // followed by a negative cache response. Temporarily turn off suppression so that
11299                 // AnswerCurrentQuestionWithResourceRecord can answer the question
11300                 SuppressStatusChanged(m, q, &restart);
11301             }
11302         }
11303     }
11304     while (restart)
11305     {
11306         q = restart;
11307         restart = restart->next;
11308         q->next = mDNSNULL;
11309         LogInfo("CheckSuppressUnusableQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11310         mDNS_StartQuery_internal(m, q);
11311     }
11312 }
11313 
11314 mDNSlocal void RestartUnicastQuestions(mDNS *const m)
11315 {
11316     DNSQuestion *q;
11317     DNSQuestion *restart = mDNSNULL;
11318 
11319     if (m->RestartQuestion)
11320         LogMsg("RestartUnicastQuestions: ERROR!! m->RestartQuestion already set: %##s (%s)",
11321                m->RestartQuestion->qname.c, DNSTypeName(m->RestartQuestion->qtype));
11322     m->RestartQuestion = m->Questions;
11323     while (m->RestartQuestion)
11324     {
11325         q = m->RestartQuestion;
11326         m->RestartQuestion = q->next;
11327         if (q->Restart)
11328         {
11329             if (mDNSOpaque16IsZero(q->TargetQID))
11330                 LogMsg("RestartUnicastQuestions: ERROR!! Restart set for multicast question %##s (%s)", q->qname.c, DNSTypeName(q->qtype));
11331 
11332             q->Restart = 0;
11333             SuppressStatusChanged(m, q, &restart);
11334         }
11335     }
11336     while (restart)
11337     {
11338         q = restart;
11339         restart = restart->next;
11340         q->next = mDNSNULL;
11341         LogInfo("RestartUnicastQuestions: Start question %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
11342         mDNS_StartQuery_internal(m, q);
11343     }
11344 }
11345 
11346 
11347 // ValidateParameters() is called by mDNS_StartQuery_internal() to check the client parameters of
11348 // DNS Question that are already set by the client before calling mDNS_StartQuery()
11349 mDNSlocal mStatus ValidateParameters(mDNS *const m, DNSQuestion *const question)
11350 {
11351 
11352     if (question->Target.type && !ValidQuestionTarget(question))
11353     {
11354         LogMsg("ValidateParameters: Warning! Target.type = %ld port = %u (Client forgot to initialize before calling mDNS_StartQuery? for question %##s)",
11355                question->Target.type, mDNSVal16(question->TargetPort), question->qname.c);
11356         question->Target.type = mDNSAddrType_None;
11357     }
11358 
11359     // If no question->Target specified, clear TargetPort
11360     if (!question->Target.type)
11361         question->TargetPort = zeroIPPort;
11362 
11363     if (!ValidateDomainName(&question->qname))
11364     {
11365         LogMsg("ValidateParameters: Attempt to start query with invalid qname %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11366         return(mStatus_Invalid);
11367     }
11368 
11369     // If this question is referencing a specific interface, verify it exists
11370     if (question->InterfaceID && question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_Unicast && question->InterfaceID != mDNSInterface_P2P)
11371     {
11372         NetworkInterfaceInfo *intf = FirstInterfaceForID(m, question->InterfaceID);
11373         if (!intf)
11374             LogInfo("ValidateParameters: Note: InterfaceID %d for question %##s (%s) not currently found in active interface list",
11375                     (uint32_t)question->InterfaceID, question->qname.c, DNSTypeName(question->qtype));
11376     }
11377 
11378     return(mStatus_NoError);
11379 }
11380 
11381 // InitDNSConfig() is called by InitCommonState() to initialize the DNS configuration of the Question.
11382 // These are a subset of the internal uDNS fields. Must be done before ShouldSuppressQuery() & mDNS_PurgeForQuestion()
11383 mDNSlocal void InitDNSConfig(mDNS *const m, DNSQuestion *const question)
11384 {
11385     // First reset all DNS Configuration
11386     question->qDNSServer          = mDNSNULL;
11387     question->validDNSServers     = zeroOpaque64;
11388     question->triedAllServersOnce = 0;
11389     question->noServerResponse    = 0;
11390     question->StopTime            = 0;
11391 #if TARGET_OS_EMBEDDED
11392     mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics));
11393 #endif
11394 
11395     // Need not initialize the DNS Configuration for Local Only OR P2P Questions
11396     if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
11397         return;
11398     // Proceed to initialize DNS Configuration (some are set in SetValidDNSServers())
11399     if (!mDNSOpaque16IsZero(question->TargetQID))
11400     {
11401         mDNSu32 timeout = SetValidDNSServers(m, question);
11402 	mDNSIPPort zp = zeroIPPort;
11403         // We set the timeout whenever mDNS_StartQuery_internal is called. This means if we have
11404         // a networking change/search domain change that calls this function again we keep
11405         // reinitializing the timeout value which means it may never timeout. If this becomes
11406         // a common case in the future, we can easily fix this by adding extra state that
11407         // indicates that we have already set the StopTime.
11408         //
11409         // Note that we set the timeout for all questions. If this turns out to be a duplicate,
11410         // it gets a full timeout value even if the original question times out earlier.
11411         if (question->TimeoutQuestion)
11412         {
11413             question->StopTime = NonZeroTime(m->timenow + timeout * mDNSPlatformOneSecond);
11414             LogInfo("InitDNSConfig: Setting StopTime on question %p %##s (%s)", question, question->qname.c, DNSTypeName(question->qtype));
11415         }
11416 
11417         question->qDNSServer = GetServerForQuestion(m, question);
11418         LogInfo("InitDNSConfig: question %p %##s (%s) Timeout %d, DNS Server %#a:%d",
11419                  question, question->qname.c, DNSTypeName(question->qtype), timeout,
11420                  question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11421                  mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zp));
11422     }
11423     else
11424     {
11425         if (question->TimeoutQuestion)
11426             question->StopTime = NonZeroTime(m->timenow + GetTimeoutForMcastQuestion(m, question) * mDNSPlatformOneSecond);
11427     }
11428     // Set StopTime here since it is a part of DNS Configuration
11429     if (question->StopTime)
11430         SetNextQueryStopTime(m, question);
11431     // SetNextQueryTime() need not be initialized for LocalOnly OR P2P Questions since those questions
11432     // will never be transmitted on the wire. Hence we call SetNextQueryTime() here.
11433     SetNextQueryTime(m,question);
11434 }
11435 
11436 // InitCommonState() is called by mDNS_StartQuery_internal() to initialize the common(uDNS/mDNS) internal
11437 // state fields of the DNS Question. These are independent of the Client layer.
11438 mDNSlocal mDNSBool InitCommonState(mDNS *const m, DNSQuestion *const question)
11439 {
11440     mDNSBool purge;
11441     int i;
11442     mDNSBool isCellBlocked = mDNSfalse;
11443 
11444     // Note: In the case where we already have the answer to this question in our cache, that may be all the client
11445     // wanted, and they may immediately cancel their question. In this case, sending an actual query on the wire would
11446     // be a waste. For that reason, we schedule our first query to go out in half a second (InitialQuestionInterval).
11447     // If AnswerNewQuestion() finds that we have *no* relevant answers currently in our cache, then it will accelerate
11448     // that to go out immediately.
11449     question->next              = mDNSNULL;
11450     // ThisQInterval should be initialized before any memory allocations occur. If malloc
11451     // debugging is turned on within mDNSResponder (see mDNSDebug.h for details) it validates
11452     // the question list to check if ThisQInterval is negative which means the question has been
11453     // stopped and can't be on the list. The question is already on the list and ThisQInterval
11454     // can be negative if the caller just stopped it and starting it again. Hence, it always has to
11455     // be initialized. CheckForSoonToExpireRecords below prints the cache records when logging is
11456     // turned ON which can allocate memory e.g., base64 encoding, in the case of DNSSEC.
11457     question->ThisQInterval     = InitialQuestionInterval;                  // MUST be > zero for an active question
11458     question->qnamehash         = DomainNameHashValue(&question->qname);
11459     question->DelayAnswering    = CheckForSoonToExpireRecords(m, &question->qname, question->qnamehash, HashSlot(&question->qname), &purge);
11460     question->LastQTime         = m->timenow;
11461     question->ExpectUnicastResp = 0;
11462     question->LastAnswerPktNum  = m->PktNum;
11463     question->RecentAnswerPkts  = 0;
11464     question->CurrentAnswers    = 0;
11465 
11466 #if APPLE_OSX_mDNSResponder
11467 
11468 // Initial browse threshold used by Finder.
11469 #define mDNSFinderBrowseThreshold 20
11470 
11471     // Set the threshold at which we move to a passive browse state,
11472     // not actively sending queries.
11473     if (question->flags & kDNSServiceFlagsThresholdOne)
11474         question->BrowseThreshold   = 1;
11475     else if (question->flags & kDNSServiceFlagsThresholdFinder)
11476         question->BrowseThreshold   = mDNSFinderBrowseThreshold;
11477     else
11478         question->BrowseThreshold   = 0;
11479 
11480 #else   // APPLE_OSX_mDNSResponder
11481    question->BrowseThreshold   = 0;
11482 #endif  // APPLE_OSX_mDNSResponder
11483     question->CachedAnswerNeedsUpdate = mDNSfalse;
11484 
11485     question->LargeAnswers      = 0;
11486     question->UniqueAnswers     = 0;
11487     question->LOAddressAnswers  = 0;
11488     question->FlappingInterface1 = mDNSNULL;
11489     question->FlappingInterface2 = mDNSNULL;
11490 
11491 	// if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
11492 	// since we would already have the question->ServiceID in that case.
11493 	if (!(question->flags & kDNSServiceFlagsServiceIndex))
11494 		mDNSPlatformGetDNSRoutePolicy(m, question, &isCellBlocked);
11495 	else
11496 		LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c,
11497                 DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID);
11498 
11499     InitDNSConfig(m, question);
11500 
11501     question->AuthInfo          = GetAuthInfoForQuestion(m, question);
11502     question->SuppressQuery     = 0;
11503     if (question->SuppressUnusable)
11504         question->SuppressQuery = ShouldSuppressQuery(m, question);
11505 
11506     // If ServiceID is 0 or the policy disallows making DNS requests,
11507     // set DisallowPID
11508     question->DisallowPID       = (question->ServiceID == 0 || (isCellBlocked && question->qDNSServer && question->qDNSServer->cellIntf));
11509     if (question->DisallowPID)
11510         LogInfo("InitCommonState: Query suppressed for %##s (%s), PID %d/ServiceID %d not allowed", question->qname.c,
11511             DNSTypeName(question->qtype), question->pid, question->ServiceID);
11512 
11513     question->NextInDQList      = mDNSNULL;
11514     question->SendQNow          = mDNSNULL;
11515     question->SendOnAll         = mDNSfalse;
11516 
11517 #if mDNS_REQUEST_UNICAST_RESPONSE
11518     question->RequestUnicast    = SET_QU_IN_FIRST_FOUR_QUERIES;
11519 #else   // mDNS_REQUEST_UNICAST_RESPONSE
11520     question->RequestUnicast    = SET_QU_IN_FIRST_QUERY;
11521 #endif  // mDNS_REQUEST_UNICAST_RESPONSE
11522 
11523 #if APPLE_OSX_mDNSResponder
11524     // Request unicast response for first 4 queries to increase
11525     // reliability in an environment with high multicast packet loss.
11526     // Must set to one more than the number of unicast queries you want, since SendQueries()
11527     // decrements it before calling BuildQuestion() which acts on it.
11528     if (question->flags & kDNSServiceFlagsUnicastResponse)
11529     {
11530         question->RequestUnicast    = SET_QU_IN_FIRST_FOUR_QUERIES;
11531         LogInfo("InitCommonState: setting RequestUnicast = %d for %##s (%s)", question->RequestUnicast, question->qname.c,
11532             DNSTypeName(question->qtype));
11533     }
11534     else if (question->flags & kDNSServiceFlagsThresholdFinder)
11535     {
11536         // always send one request with QU bit set when kDNSServiceFlagsThresholdFinder is set
11537 #if mDNS_REQUEST_UNICAST_RESPONSE
11538         question->RequestUnicast    = SET_QU_IN_FIRST_FOUR_QUERIES;
11539 #else   // mDNS_REQUEST_UNICAST_RESPONSE
11540         question->RequestUnicast    = SET_QU_IN_FIRST_QUERY;
11541 #endif  // mDNS_REQUEST_UNICAST_RESPONSE
11542 
11543         LogInfo("InitCommonState: kDNSServiceFlagsThresholdFinder set, setting RequestUnicast = %d for %##s (%s)",
11544             question->RequestUnicast, question->qname.c, DNSTypeName(question->qtype));
11545     }
11546 #endif  // APPLE_OSX_mDNSResponder
11547 
11548     question->LastQTxTime       = m->timenow;
11549     question->CNAMEReferrals    = 0;
11550 
11551     question->WakeOnResolveCount = 0;
11552     if (question->WakeOnResolve)
11553     {
11554         question->WakeOnResolveCount = InitialWakeOnResolveCount;
11555         purge = mDNStrue;
11556     }
11557 
11558     for (i=0; i<DupSuppressInfoSize; i++)
11559         question->DupSuppress[i].InterfaceID = mDNSNULL;
11560 
11561     question->Restart = 0;
11562 
11563     debugf("InitCommonState: Question %##s (%s) Interface %p Now %d Send in %d Answer in %d (%p) %s (%p)",
11564             question->qname.c, DNSTypeName(question->qtype), question->InterfaceID, m->timenow,
11565             NextQSendTime(question) - m->timenow,
11566             question->DelayAnswering ? question->DelayAnswering - m->timenow : 0,
11567             question, question->DuplicateOf ? "duplicate of" : "not duplicate", question->DuplicateOf);
11568 
11569     if (question->DelayAnswering)
11570         LogInfo("InitCommonState: Delaying answering for %d ticks while cache stabilizes for %##s (%s)",
11571                  question->DelayAnswering - m->timenow, question->qname.c, DNSTypeName(question->qtype));
11572 
11573     return(purge);
11574 }
11575 
11576 // Excludes the DNS Config fields which are already handled by InitDNSConfig()
11577 mDNSlocal void InitWABState(DNSQuestion *const question)
11578 {
11579     // We'll create our question->LocalSocket on demand, if needed.
11580     // We won't need one for duplicate questions, or from questions answered immediately out of the cache.
11581     // We also don't need one for LLQs because (when we're using NAT) we want them all to share a single
11582     // NAT mapping for receiving inbound add/remove events.
11583     question->LocalSocket       = mDNSNULL;
11584     question->unansweredQueries = 0;
11585     question->nta               = mDNSNULL;
11586     question->servAddr          = zeroAddr;
11587     question->servPort          = zeroIPPort;
11588     question->tcp               = mDNSNULL;
11589     question->NoAnswer          = NoAnswer_Normal;
11590 }
11591 
11592 mDNSlocal void InitLLQNATState(mDNS *const m)
11593 {
11594     // If we don't have our NAT mapping active, start it now
11595     if (!m->LLQNAT.clientCallback)
11596     {
11597         m->LLQNAT.Protocol       = NATOp_MapUDP;
11598         m->LLQNAT.IntPort        = m->UnicastPort4;
11599         m->LLQNAT.RequestedPort  = m->UnicastPort4;
11600         m->LLQNAT.clientCallback = LLQNATCallback;
11601         m->LLQNAT.clientContext  = (void*)1; // Means LLQ NAT Traversal just started
11602         mDNS_StartNATOperation_internal(m, &m->LLQNAT);
11603     }
11604 }
11605 
11606 mDNSlocal void InitLLQState(DNSQuestion *const question)
11607 {
11608     question->state             = LLQ_InitialRequest;
11609     question->ReqLease          = 0;
11610     question->expire            = 0;
11611     question->ntries            = 0;
11612     question->id                = zeroOpaque64;
11613 }
11614 
11615 // InitDNSSECProxyState() is called by mDNS_StartQuery_internal() to initialize
11616 // DNSSEC & DNS Proxy fields of the DNS Question.
11617 mDNSlocal void InitDNSSECProxyState(mDNS *const m, DNSQuestion *const question)
11618 {
11619     (void) m;
11620 
11621     // DNS server selection affects DNSSEC. Turn off validation if req_DO is not set
11622     // or the request is going over cellular interface.
11623     //
11624     // Note: This needs to be done here before we call FindDuplicateQuestion as it looks
11625     // at ValidationRequired setting also.
11626     if (question->qDNSServer)
11627     {
11628         if (question->qDNSServer->cellIntf)
11629         {
11630             debugf("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question->qname.c, DNSTypeName(question->qtype));
11631             question->ValidationRequired = mDNSfalse;
11632         }
11633         if (DNSSECOptionalQuestion(question) && !(question->qDNSServer->req_DO))
11634         {
11635             LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); req_DO false",
11636                 question->qname.c, DNSTypeName(question->qtype));
11637             question->ValidationRequired = DNSSEC_VALIDATION_NONE;
11638         }
11639     }
11640     question->ValidationState = (question->ValidationRequired ? DNSSECValRequired : DNSSECValNotRequired);
11641     question->ValidationStatus = 0;
11642     question->responseFlags    = zeroID;
11643 }
11644 
11645 // Once the question is completely initialized including the duplicate logic, this function
11646 // is called to finalize the unicast question which requires flushing the cache if needed,
11647 // activating the query etc.
11648 mDNSlocal void FinalizeUnicastQuestion(mDNS *const m, DNSQuestion *question, mDNSBool purge)
11649 {
11650     // Ensure DNS related info of duplicate question is same as the orig question
11651     if (question->DuplicateOf)
11652     {
11653 	mDNSIPPort zp = zeroIPPort;
11654         question->validDNSServers = question->DuplicateOf->validDNSServers;
11655         question->qDNSServer = question->DuplicateOf->qDNSServer;
11656         LogInfo("FinalizeUnicastQuestion: Duplicate question %p (%p) %##s (%s), DNS Server %#a:%d",
11657                  question, question->DuplicateOf, question->qname.c, DNSTypeName(question->qtype),
11658                  question->qDNSServer ? &question->qDNSServer->addr : mDNSNULL,
11659                  mDNSVal16(question->qDNSServer ? question->qDNSServer->port : zp));
11660     }
11661 
11662     ActivateUnicastQuery(m, question, mDNSfalse);
11663 
11664     // If purge was set above, flush the cache. Need to do this after we set the
11665     // DNS server on the question
11666     if (purge)
11667     {
11668         question->DelayAnswering = 0;
11669         mDNS_PurgeForQuestion(m, question);
11670     }
11671     else if (!question->DuplicateOf && DNSSECQuestion(question))
11672     {
11673         // For DNSSEC questions, we need to have the RRSIGs also for verification.
11674         CheckForDNSSECRecords(m, question);
11675     }
11676     if (question->LongLived)
11677     {
11678         // Unlike other initializations, InitLLQNATState should be done after
11679         // we determine that it is a unicast question.  LongLived is set for
11680         // both multicast and unicast browse questions but we should initialize
11681         // the LLQ NAT state only for unicast. Otherwise we will unnecessarily
11682         // start the NAT traversal that is not needed.
11683         InitLLQNATState(m);
11684 #if APPLE_OSX_mDNSResponder
11685         UpdateAutoTunnelDomainStatuses(m);
11686 #endif
11687     }
11688 }
11689 
11690 mDNSexport mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question)
11691 {
11692     DNSQuestion **q;
11693     mStatus vStatus;
11694     mDNSBool purge;
11695     mDNSOpaque16 zqid = zeroID;
11696 
11697     // First check for cache space (can't do queries if there is no cache space allocated)
11698     if (m->rrcache_size == 0)
11699         return(mStatus_NoCache);
11700 
11701     vStatus = ValidateParameters(m, question);
11702     if (vStatus)
11703         return(vStatus);
11704 
11705     question->TargetQID =
11706 #ifndef UNICAST_DISABLED
11707                           (question->Target.type || Question_uDNS(question)) ? mDNS_NewMessageID(m) :
11708 #endif // UNICAST_DISABLED
11709                           zqid;
11710     debugf("mDNS_StartQuery_internal: %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11711 
11712     // Note: It important that new questions are appended at the *end* of the list, not prepended at the start
11713     q = &m->Questions;
11714     if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
11715         q = &m->LocalOnlyQuestions;
11716     while (*q && *q != question)
11717         q=&(*q)->next;
11718 
11719     if (*q)
11720     {
11721         LogMsg("mDNS_StartQuery_internal: Error! Tried to add a question %##s (%s) %p that's already in the active list",
11722                 question->qname.c, DNSTypeName(question->qtype), question);
11723         return(mStatus_AlreadyRegistered);
11724     }
11725     *q = question;
11726 
11727 
11728     // Intialize the question. The only ordering constraint we have today is that
11729     // InitDNSSECProxyState should be called after the DNS server is selected (in
11730     // InitCommonState -> InitDNSConfig) as DNS server selection affects DNSSEC
11731     // validation.
11732 
11733     purge = InitCommonState(m, question);
11734     InitWABState(question);
11735     InitLLQState(question);
11736     InitDNSSECProxyState(m, question);
11737 
11738     // FindDuplicateQuestion should be called last after all the intialization
11739     // as the duplicate logic could be potentially based on any field in the
11740     // question.
11741     question->DuplicateOf  = FindDuplicateQuestion(m, question);
11742     if (question->DuplicateOf)
11743         question->AuthInfo = question->DuplicateOf->AuthInfo;
11744 
11745     if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P)
11746     {
11747         if (!m->NewLocalOnlyQuestions)
11748             m->NewLocalOnlyQuestions = question;
11749     }
11750     else
11751     {
11752         if (!m->NewQuestions)
11753             m->NewQuestions = question;
11754 
11755         // If the question's id is non-zero, then it's Wide Area
11756         // MUST NOT do this Wide Area setup until near the end of
11757         // mDNS_StartQuery_internal -- this code may itself issue queries (e.g. SOA,
11758         // NS, etc.) and if we haven't finished setting up our own question and setting
11759         // m->NewQuestions if necessary then we could end up recursively re-entering
11760         // this routine with the question list data structures in an inconsistent state.
11761         if (!mDNSOpaque16IsZero(question->TargetQID))
11762         {
11763             FinalizeUnicastQuestion(m, question, purge);
11764         }
11765         else
11766         {
11767 #if TARGET_OS_WATCH
11768 			m->NumAllInterfaceQuestions++;
11769 			LogInfo("mDNS_StartQuery_internal: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
11770 				m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, question->qname.c, DNSTypeName(question->qtype));
11771 			if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
11772 				m->NetworkChanged = m->timenow;
11773 #endif
11774             if (purge)
11775             {
11776                 LogInfo("mDNS_StartQuery_internal: Purging for %##s", question->qname.c);
11777                 mDNS_PurgeForQuestion(m, question);
11778             }
11779         }
11780     }
11781 
11782     return(mStatus_NoError);
11783 }
11784 
11785 // CancelGetZoneData is an internal routine (i.e. must be called with the lock already held)
11786 mDNSexport void CancelGetZoneData(mDNS *const m, ZoneData *nta)
11787 {
11788     debugf("CancelGetZoneData %##s (%s)", nta->question.qname.c, DNSTypeName(nta->question.qtype));
11789     // This function may be called anytime to free the zone information.The question may or may not have stopped.
11790     // If it was already stopped, mDNS_StopQuery_internal would have set q->ThisQInterval to -1 and should not
11791     // call it again
11792     if (nta->question.ThisQInterval != -1)
11793     {
11794         mDNS_StopQuery_internal(m, &nta->question);
11795         if (nta->question.ThisQInterval != -1)
11796             LogMsg("CancelGetZoneData: Question %##s (%s) ThisQInterval %d not -1", nta->question.qname.c, DNSTypeName(nta->question.qtype), nta->question.ThisQInterval);
11797     }
11798     mDNSPlatformMemFree(nta);
11799 }
11800 
11801 mDNSexport mStatus mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
11802 {
11803     const mDNSu32 slot = HashSlot(&question->qname);
11804     CacheGroup *cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
11805     CacheRecord *rr;
11806     DNSQuestion **qp = &m->Questions;
11807 
11808     //LogInfo("mDNS_StopQuery_internal %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
11809 
11810     if (question->InterfaceID == mDNSInterface_LocalOnly || question->InterfaceID == mDNSInterface_P2P) qp = &m->LocalOnlyQuestions;
11811     while (*qp && *qp != question) qp=&(*qp)->next;
11812     if (*qp) *qp = (*qp)->next;
11813     else
11814     {
11815 #if !ForceAlerts
11816         if (question->ThisQInterval >= 0)   // Only log error message if the query was supposed to be active
11817 #endif
11818         LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype));
11819         return(mStatus_BadReferenceErr);
11820     }
11821 
11822 #if TARGET_OS_WATCH
11823     if (question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_P2P && mDNSOpaque16IsZero(question->TargetQID))
11824     {
11825 	if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
11826 		m->NetworkChanged = m->timenow;
11827 	m->NumAllInterfaceQuestions--;
11828 	LogInfo("mDNS_StopQuery_internal:  NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
11829 		m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, question->qname.c, DNSTypeName(question->qtype));
11830     }
11831 #endif
11832 
11833 #if TARGET_OS_EMBEDDED
11834     if (Question_uDNS(question) && !question->metrics.answered)
11835     {
11836         uDNSMetrics *       metrics;
11837         const domainname *  queryName;
11838         mDNSBool            isForCellular;
11839 
11840         metrics       = &question->metrics;
11841         queryName     = metrics->originalQName ? metrics->originalQName : &question->qname;
11842         isForCellular = (question->qDNSServer && question->qDNSServer->cellIntf);
11843 
11844         MetricsUpdateUDNSStats(queryName, mDNSfalse, metrics->querySendCount, 0, isForCellular);
11845     }
11846 #endif
11847     // Take care to cut question from list *before* calling UpdateQuestionDuplicates
11848     UpdateQuestionDuplicates(m, question);
11849     // But don't trash ThisQInterval until afterwards.
11850     question->ThisQInterval = -1;
11851 
11852     // If there are any cache records referencing this as their active question, then see if there is any
11853     // other question that is also referencing them, else their CRActiveQuestion needs to get set to NULL.
11854     for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
11855     {
11856         if (rr->CRActiveQuestion == question)
11857         {
11858             DNSQuestion *q;
11859             // Checking for ActiveQuestion filters questions that are suppressed also
11860             // as suppressed questions are not active
11861             for (q = m->Questions; q; q=q->next)        // Scan our list of questions
11862                 if (ActiveQuestion(q) && ResourceRecordAnswersQuestion(&rr->resrec, q))
11863                     break;
11864             if (q)
11865                 debugf("mDNS_StopQuery_internal: Updating CRActiveQuestion to %p for cache record %s, Original question CurrentAnswers %d, new question "
11866                        "CurrentAnswers %d, SuppressQuery %d", q, CRDisplayString(m,rr), question->CurrentAnswers, q->CurrentAnswers, q->SuppressQuery);
11867             rr->CRActiveQuestion = q;       // Question used to be active; new value may or may not be null
11868             if (!q) m->rrcache_active--;    // If no longer active, decrement rrcache_active count
11869         }
11870     }
11871 
11872     // If we just deleted the question that CacheRecordAdd() or CacheRecordRmv() is about to look at,
11873     // bump its pointer forward one question.
11874     if (m->CurrentQuestion == question)
11875     {
11876         debugf("mDNS_StopQuery_internal: Just deleted the currently active question: %##s (%s)",
11877                question->qname.c, DNSTypeName(question->qtype));
11878         m->CurrentQuestion = question->next;
11879     }
11880 
11881     if (m->NewQuestions == question)
11882     {
11883         debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet: %##s (%s)",
11884                question->qname.c, DNSTypeName(question->qtype));
11885         m->NewQuestions = question->next;
11886     }
11887 
11888     if (m->NewLocalOnlyQuestions == question) m->NewLocalOnlyQuestions = question->next;
11889 
11890     if (m->RestartQuestion == question)
11891     {
11892         LogMsg("mDNS_StopQuery_internal: Just deleted the current restart question: %##s (%s)",
11893                question->qname.c, DNSTypeName(question->qtype));
11894         m->RestartQuestion = question->next;
11895     }
11896 
11897     if (m->ValidationQuestion == question)
11898     {
11899         LogInfo("mDNS_StopQuery_internal: Just deleted the current Validation question: %##s (%s)",
11900                question->qname.c, DNSTypeName(question->qtype));
11901         m->ValidationQuestion = question->next;
11902     }
11903 
11904     // Take care not to trash question->next until *after* we've updated m->CurrentQuestion and m->NewQuestions
11905     question->next = mDNSNULL;
11906 
11907     // LogMsg("mDNS_StopQuery_internal: Question %##s (%s) removed", question->qname.c, DNSTypeName(question->qtype));
11908 
11909     // And finally, cancel any associated GetZoneData operation that's still running.
11910     // Must not do this until last, because there's a good chance the GetZoneData question is the next in the list,
11911     // so if we delete it earlier in this routine, we could find that our "question->next" pointer above is already
11912     // invalid before we even use it. By making sure that we update m->CurrentQuestion and m->NewQuestions if necessary
11913     // *first*, then they're all ready to be updated a second time if necessary when we cancel our GetZoneData query.
11914     if (question->tcp) { DisposeTCPConn(question->tcp); question->tcp = mDNSNULL; }
11915     if (question->LocalSocket) { mDNSPlatformUDPClose(question->LocalSocket); question->LocalSocket = mDNSNULL; }
11916     if (!mDNSOpaque16IsZero(question->TargetQID) && question->LongLived)
11917     {
11918         // Scan our list to see if any more wide-area LLQs remain. If not, stop our NAT Traversal.
11919         DNSQuestion *q;
11920         for (q = m->Questions; q; q=q->next)
11921             if (!mDNSOpaque16IsZero(q->TargetQID) && q->LongLived) break;
11922         if (!q)
11923         {
11924             if (!m->LLQNAT.clientCallback)       // Should never happen, but just in case...
11925             {
11926                 LogMsg("mDNS_StopQuery ERROR LLQNAT.clientCallback NULL");
11927             }
11928             else
11929             {
11930                 LogInfo("Stopping LLQNAT");
11931                 mDNS_StopNATOperation_internal(m, &m->LLQNAT);
11932                 m->LLQNAT.clientCallback = mDNSNULL; // Means LLQ NAT Traversal not running
11933             }
11934         }
11935 
11936         // If necessary, tell server it can delete this LLQ state
11937         if (question->state == LLQ_Established)
11938         {
11939             question->ReqLease = 0;
11940             sendLLQRefresh(m, question);
11941             // If we need need to make a TCP connection to cancel the LLQ, that's going to take a little while.
11942             // We clear the tcp->question backpointer so that when the TCP connection completes, it doesn't
11943             // crash trying to access our cancelled question, but we don't cancel the TCP operation itself --
11944             // we let that run out its natural course and complete asynchronously.
11945             if (question->tcp)
11946             {
11947                 question->tcp->question = mDNSNULL;
11948                 question->tcp           = mDNSNULL;
11949             }
11950         }
11951 #if APPLE_OSX_mDNSResponder
11952         UpdateAutoTunnelDomainStatuses(m);
11953 #endif
11954     }
11955     // wait until we send the refresh above which needs the nta
11956     if (question->nta) { CancelGetZoneData(m, question->nta); question->nta = mDNSNULL; }
11957 
11958     if (question->ValidationRequired && question->DNSSECAuthInfo)
11959     {
11960         LogInfo("mDNS_StopQuery_internal: freeing DNSSECAuthInfo %##s", question->qname.c);
11961         question->DAIFreeCallback(m, question->DNSSECAuthInfo);
11962         question->DNSSECAuthInfo = mDNSNULL;
11963     }
11964     if (question->AnonInfo)
11965     {
11966         FreeAnonInfo(question->AnonInfo);
11967         question->AnonInfo = mDNSNULL;
11968     }
11969 #if TARGET_OS_EMBEDDED
11970     if (question->metrics.originalQName)
11971     {
11972         mDNSPlatformMemFree(question->metrics.originalQName);
11973         question->metrics.originalQName = mDNSNULL;
11974     }
11975 #endif
11976 
11977     return(mStatus_NoError);
11978 }
11979 
11980 mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
11981 {
11982     mStatus status;
11983     mDNS_Lock(m);
11984     status = mDNS_StartQuery_internal(m, question);
11985     mDNS_Unlock(m);
11986     return(status);
11987 }
11988 
11989 mDNSexport mStatus mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
11990 {
11991     mStatus status;
11992     mDNS_Lock(m);
11993     status = mDNS_StopQuery_internal(m, question);
11994     mDNS_Unlock(m);
11995     return(status);
11996 }
11997 
11998 // Note that mDNS_StopQueryWithRemoves() does not currently implement the full generality of the other APIs
11999 // Specifically, question callbacks invoked as a result of this call cannot themselves make API calls.
12000 // We invoke the callback without using mDNS_DropLockBeforeCallback/mDNS_ReclaimLockAfterCallback
12001 // specifically to catch and report if the client callback does try to make API calls
12002 mDNSexport mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question)
12003 {
12004     mStatus status;
12005     DNSQuestion *qq;
12006     mDNS_Lock(m);
12007 
12008     // Check if question is new -- don't want to give remove events for a question we haven't even answered yet
12009     for (qq = m->NewQuestions; qq; qq=qq->next) if (qq == question) break;
12010 
12011     status = mDNS_StopQuery_internal(m, question);
12012     if (status == mStatus_NoError && !qq)
12013     {
12014         const CacheRecord *rr;
12015         const mDNSu32 slot = HashSlot(&question->qname);
12016         CacheGroup *const cg = CacheGroupForName(m, slot, question->qnamehash, &question->qname);
12017         LogInfo("Generating terminal removes for %##s (%s)", question->qname.c, DNSTypeName(question->qtype));
12018         for (rr = cg ? cg->members : mDNSNULL; rr; rr=rr->next)
12019             if (rr->resrec.RecordType != kDNSRecordTypePacketNegative && SameNameRecordAnswersQuestion(&rr->resrec, question))
12020             {
12021                 // Don't use mDNS_DropLockBeforeCallback() here, since we don't allow API calls
12022                 if (question->QuestionCallback)
12023                     question->QuestionCallback(m, question, &rr->resrec, QC_rmv);
12024             }
12025     }
12026     mDNS_Unlock(m);
12027     return(status);
12028 }
12029 
12030 mDNSexport mStatus mDNS_Reconfirm(mDNS *const m, CacheRecord *const cr)
12031 {
12032     mStatus status;
12033     mDNS_Lock(m);
12034     status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12035     if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
12036     mDNS_Unlock(m);
12037     return(status);
12038 }
12039 
12040 mDNSexport mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr)
12041 {
12042     mStatus status = mStatus_BadReferenceErr;
12043     CacheRecord *cr;
12044     mDNS_Lock(m);
12045     cr = FindIdenticalRecordInCache(m, rr);
12046     debugf("mDNS_ReconfirmByValue: %p %s", cr, RRDisplayString(m, rr));
12047     if (cr) status = mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
12048     if (status == mStatus_NoError) ReconfirmAntecedents(m, cr->resrec.name, cr->resrec.namehash, 0);
12049     mDNS_Unlock(m);
12050     return(status);
12051 }
12052 
12053 mDNSlocal mStatus mDNS_StartBrowse_internal(mDNS *const m, DNSQuestion *const question,
12054                                             const domainname *const srv, const domainname *const domain,
12055                                             const mDNSu8 *anondata, const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12056                                             mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12057                                             mDNSQuestionCallback *Callback, void *Context)
12058 {
12059     question->InterfaceID      = InterfaceID;
12060     question->flags            = flags;
12061     question->Target           = zeroAddr;
12062     question->qtype            = kDNSType_PTR;
12063     question->qclass           = kDNSClass_IN;
12064     question->LongLived        = mDNStrue;
12065     question->ExpectUnique     = mDNSfalse;
12066     question->ForceMCast       = ForceMCast;
12067     question->ReturnIntermed   = mDNSfalse;
12068     question->SuppressUnusable = mDNSfalse;
12069     question->DenyOnCellInterface = mDNSfalse;
12070     question->DenyOnExpInterface  = mDNSfalse;
12071     question->SearchListIndex  = 0;
12072     question->AppendSearchDomains = 0;
12073     question->RetryWithSearchDomains = mDNSfalse;
12074     question->TimeoutQuestion  = 0;
12075     question->WakeOnResolve    = 0;
12076     question->UseBackgroundTrafficClass = useBackgroundTrafficClass;
12077     question->ValidationRequired = 0;
12078     question->ValidatingResponse = 0;
12079     question->ProxyQuestion    = 0;
12080     question->qnameOrig        = mDNSNULL;
12081     question->AnonInfo         = mDNSNULL;
12082     question->QuestionCallback = Callback;
12083     question->QuestionContext  = Context;
12084 
12085     if (!ConstructServiceName(&question->qname, mDNSNULL, srv, domain))
12086         return(mStatus_BadParamErr);
12087 
12088     if (anondata)
12089     {
12090         question->AnonInfo = AllocateAnonInfo(&question->qname, anondata, mDNSPlatformStrLen(anondata), mDNSNULL);
12091         if (!question->AnonInfo)
12092             return(mStatus_BadParamErr);
12093     }
12094 
12095     return(mDNS_StartQuery_internal(m, question));
12096 }
12097 
12098 mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
12099                                     const domainname *const srv, const domainname *const domain,
12100                                     const mDNSu8 *anondata, const mDNSInterfaceID InterfaceID, mDNSu32 flags,
12101                                     mDNSBool ForceMCast, mDNSBool useBackgroundTrafficClass,
12102                                     mDNSQuestionCallback *Callback, void *Context)
12103 {
12104     mStatus status;
12105     mDNS_Lock(m);
12106     status = mDNS_StartBrowse_internal(m, question, srv, domain, anondata, InterfaceID, flags, ForceMCast, useBackgroundTrafficClass, Callback, Context);
12107     mDNS_Unlock(m);
12108     return(status);
12109 }
12110 
12111 mDNSlocal mDNSBool MachineHasActiveIPv6(mDNS *const m)
12112 {
12113     NetworkInterfaceInfo *intf;
12114     for (intf = m->HostInterfaces; intf; intf = intf->next)
12115         if (intf->ip.type == mDNSAddrType_IPv6) return(mDNStrue);
12116     return(mDNSfalse);
12117 }
12118 
12119 mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
12120 {
12121     ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
12122     mDNSBool PortChanged = !mDNSSameIPPort(query->info->port, answer->rdata->u.srv.port);
12123     if (!AddRecord) return;
12124     if (answer->rrtype != kDNSType_SRV) return;
12125 
12126     query->info->port = answer->rdata->u.srv.port;
12127 
12128     // If this is our first answer, then set the GotSRV flag and start the address query
12129     if (!query->GotSRV)
12130     {
12131         query->GotSRV             = mDNStrue;
12132         query->qAv4.InterfaceID   = answer->InterfaceID;
12133         AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
12134         query->qAv6.InterfaceID   = answer->InterfaceID;
12135         AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
12136         mDNS_StartQuery(m, &query->qAv4);
12137         // Only do the AAAA query if this machine actually has IPv6 active
12138         if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
12139     }
12140     // If this is not our first answer, only re-issue the address query if the target host name has changed
12141     else if ((query->qAv4.InterfaceID != query->qSRV.InterfaceID && query->qAv4.InterfaceID != answer->InterfaceID) ||
12142              !SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target))
12143     {
12144         mDNS_StopQuery(m, &query->qAv4);
12145         if (query->qAv6.ThisQInterval >= 0) mDNS_StopQuery(m, &query->qAv6);
12146         if (SameDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target) && !PortChanged)
12147         {
12148             // If we get here, it means:
12149             // 1. This is not our first SRV answer
12150             // 2. The interface ID is different, but the target host and port are the same
12151             // This implies that we're seeing the exact same SRV record on more than one interface, so we should
12152             // make our address queries at least as broad as the original SRV query so that we catch all the answers.
12153             query->qAv4.InterfaceID = query->qSRV.InterfaceID;  // Will be mDNSInterface_Any, or a specific interface
12154             query->qAv6.InterfaceID = query->qSRV.InterfaceID;
12155         }
12156         else
12157         {
12158             query->qAv4.InterfaceID   = answer->InterfaceID;
12159             AssignDomainName(&query->qAv4.qname, &answer->rdata->u.srv.target);
12160             query->qAv6.InterfaceID   = answer->InterfaceID;
12161             AssignDomainName(&query->qAv6.qname, &answer->rdata->u.srv.target);
12162         }
12163         debugf("FoundServiceInfoSRV: Restarting address queries for %##s (%s)", query->qAv4.qname.c, DNSTypeName(query->qAv4.qtype));
12164         mDNS_StartQuery(m, &query->qAv4);
12165         // Only do the AAAA query if this machine actually has IPv6 active
12166         if (MachineHasActiveIPv6(m)) mDNS_StartQuery(m, &query->qAv6);
12167     }
12168     else if (query->ServiceInfoQueryCallback && query->GotADD && query->GotTXT && PortChanged)
12169     {
12170         if (++query->Answers >= 100)
12171             debugf("**** WARNING **** Have given %lu answers for %##s (SRV) %##s %u",
12172                    query->Answers, query->qSRV.qname.c, answer->rdata->u.srv.target.c,
12173                    mDNSVal16(answer->rdata->u.srv.port));
12174         query->ServiceInfoQueryCallback(m, query);
12175     }
12176     // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
12177     // callback function is allowed to do anything, including deleting this query and freeing its memory.
12178 }
12179 
12180 mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
12181 {
12182     ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
12183     if (!AddRecord) return;
12184     if (answer->rrtype != kDNSType_TXT) return;
12185     if (answer->rdlength > sizeof(query->info->TXTinfo)) return;
12186 
12187     query->GotTXT       = mDNStrue;
12188     query->info->TXTlen = answer->rdlength;
12189     query->info->TXTinfo[0] = 0;        // In case answer->rdlength is zero
12190     mDNSPlatformMemCopy(query->info->TXTinfo, answer->rdata->u.txt.c, answer->rdlength);
12191 
12192     verbosedebugf("FoundServiceInfoTXT: %##s GotADD=%d", query->info->name.c, query->GotADD);
12193 
12194     // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
12195     // callback function is allowed to do anything, including deleting this query and freeing its memory.
12196     if (query->ServiceInfoQueryCallback && query->GotADD)
12197     {
12198         if (++query->Answers >= 100)
12199             debugf("**** WARNING **** have given %lu answers for %##s (TXT) %#s...",
12200                    query->Answers, query->qSRV.qname.c, answer->rdata->u.txt.c);
12201         query->ServiceInfoQueryCallback(m, query);
12202     }
12203 }
12204 
12205 mDNSlocal void FoundServiceInfo(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord)
12206 {
12207     ServiceInfoQuery *query = (ServiceInfoQuery *)question->QuestionContext;
12208     //LogInfo("FoundServiceInfo %d %s", AddRecord, RRDisplayString(m, answer));
12209     if (!AddRecord) return;
12210 
12211     if (answer->rrtype == kDNSType_A)
12212     {
12213         query->info->ip.type = mDNSAddrType_IPv4;
12214         query->info->ip.ip.v4 = answer->rdata->u.ipv4;
12215     }
12216     else if (answer->rrtype == kDNSType_AAAA)
12217     {
12218         query->info->ip.type = mDNSAddrType_IPv6;
12219         query->info->ip.ip.v6 = answer->rdata->u.ipv6;
12220     }
12221     else
12222     {
12223         debugf("FoundServiceInfo: answer %##s type %d (%s) unexpected", answer->name->c, answer->rrtype, DNSTypeName(answer->rrtype));
12224         return;
12225     }
12226 
12227     query->GotADD = mDNStrue;
12228     query->info->InterfaceID = answer->InterfaceID;
12229 
12230     verbosedebugf("FoundServiceInfo v%ld: %##s GotTXT=%d", query->info->ip.type, query->info->name.c, query->GotTXT);
12231 
12232     // CAUTION: MUST NOT do anything more with query after calling query->Callback(), because the client's
12233     // callback function is allowed to do anything, including deleting this query and freeing its memory.
12234     if (query->ServiceInfoQueryCallback && query->GotTXT)
12235     {
12236         if (++query->Answers >= 100)
12237             debugf(answer->rrtype == kDNSType_A ?
12238                    "**** WARNING **** have given %lu answers for %##s (A) %.4a" :
12239                    "**** WARNING **** have given %lu answers for %##s (AAAA) %.16a",
12240                    query->Answers, query->qSRV.qname.c, &answer->rdata->u.data);
12241         query->ServiceInfoQueryCallback(m, query);
12242     }
12243 }
12244 
12245 // On entry, the client must have set the name and InterfaceID fields of the ServiceInfo structure
12246 // If the query is not interface-specific, then InterfaceID may be zero
12247 // Each time the Callback is invoked, the remainder of the fields will have been filled in
12248 // In addition, InterfaceID will be updated to give the interface identifier corresponding to that response
12249 mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
12250                                             ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context)
12251 {
12252     mStatus status;
12253     mDNS_Lock(m);
12254 
12255     query->qSRV.ThisQInterval       = -1;       // So that mDNS_StopResolveService() knows whether to cancel this question
12256     query->qSRV.InterfaceID         = info->InterfaceID;
12257     query->qSRV.flags               = 0;
12258     query->qSRV.Target              = zeroAddr;
12259     AssignDomainName(&query->qSRV.qname, &info->name);
12260     query->qSRV.qtype               = kDNSType_SRV;
12261     query->qSRV.qclass              = kDNSClass_IN;
12262     query->qSRV.LongLived           = mDNSfalse;
12263     query->qSRV.ExpectUnique        = mDNStrue;
12264     query->qSRV.ForceMCast          = mDNSfalse;
12265     query->qSRV.ReturnIntermed      = mDNSfalse;
12266     query->qSRV.SuppressUnusable    = mDNSfalse;
12267     query->qSRV.DenyOnCellInterface = mDNSfalse;
12268     query->qSRV.DenyOnExpInterface  = mDNSfalse;
12269     query->qSRV.SearchListIndex     = 0;
12270     query->qSRV.AppendSearchDomains = 0;
12271     query->qSRV.RetryWithSearchDomains = mDNSfalse;
12272     query->qSRV.TimeoutQuestion     = 0;
12273     query->qSRV.WakeOnResolve       = 0;
12274     query->qSRV.UseBackgroundTrafficClass = mDNSfalse;
12275     query->qSRV.ValidationRequired  = 0;
12276     query->qSRV.ValidatingResponse  = 0;
12277     query->qSRV.ProxyQuestion       = 0;
12278     query->qSRV.qnameOrig           = mDNSNULL;
12279     query->qSRV.AnonInfo            = mDNSNULL;
12280     query->qSRV.QuestionCallback    = FoundServiceInfoSRV;
12281     query->qSRV.QuestionContext     = query;
12282 
12283     query->qTXT.ThisQInterval       = -1;       // So that mDNS_StopResolveService() knows whether to cancel this question
12284     query->qTXT.InterfaceID         = info->InterfaceID;
12285     query->qTXT.flags               = 0;
12286     query->qTXT.Target              = zeroAddr;
12287     AssignDomainName(&query->qTXT.qname, &info->name);
12288     query->qTXT.qtype               = kDNSType_TXT;
12289     query->qTXT.qclass              = kDNSClass_IN;
12290     query->qTXT.LongLived           = mDNSfalse;
12291     query->qTXT.ExpectUnique        = mDNStrue;
12292     query->qTXT.ForceMCast          = mDNSfalse;
12293     query->qTXT.ReturnIntermed      = mDNSfalse;
12294     query->qTXT.SuppressUnusable    = mDNSfalse;
12295     query->qTXT.DenyOnCellInterface = mDNSfalse;
12296     query->qTXT.DenyOnExpInterface  = mDNSfalse;
12297     query->qTXT.SearchListIndex     = 0;
12298     query->qTXT.AppendSearchDomains = 0;
12299     query->qTXT.RetryWithSearchDomains = mDNSfalse;
12300     query->qTXT.TimeoutQuestion     = 0;
12301     query->qTXT.WakeOnResolve       = 0;
12302     query->qTXT.UseBackgroundTrafficClass = mDNSfalse;
12303     query->qTXT.ValidationRequired  = 0;
12304     query->qTXT.ValidatingResponse  = 0;
12305     query->qTXT.ProxyQuestion       = 0;
12306     query->qTXT.qnameOrig           = mDNSNULL;
12307     query->qTXT.AnonInfo            = mDNSNULL;
12308     query->qTXT.QuestionCallback    = FoundServiceInfoTXT;
12309     query->qTXT.QuestionContext     = query;
12310 
12311     query->qAv4.ThisQInterval       = -1;       // So that mDNS_StopResolveService() knows whether to cancel this question
12312     query->qAv4.InterfaceID         = info->InterfaceID;
12313     query->qAv4.flags               = 0;
12314     query->qAv4.Target              = zeroAddr;
12315     query->qAv4.qname.c[0]          = 0;
12316     query->qAv4.qtype               = kDNSType_A;
12317     query->qAv4.qclass              = kDNSClass_IN;
12318     query->qAv4.LongLived           = mDNSfalse;
12319     query->qAv4.ExpectUnique        = mDNStrue;
12320     query->qAv4.ForceMCast          = mDNSfalse;
12321     query->qAv4.ReturnIntermed      = mDNSfalse;
12322     query->qAv4.SuppressUnusable    = mDNSfalse;
12323     query->qAv4.DenyOnCellInterface = mDNSfalse;
12324     query->qAv4.DenyOnExpInterface  = mDNSfalse;
12325     query->qAv4.SearchListIndex     = 0;
12326     query->qAv4.AppendSearchDomains = 0;
12327     query->qAv4.RetryWithSearchDomains = mDNSfalse;
12328     query->qAv4.TimeoutQuestion     = 0;
12329     query->qAv4.WakeOnResolve       = 0;
12330     query->qAv4.UseBackgroundTrafficClass = mDNSfalse;
12331     query->qAv4.ValidationRequired  = 0;
12332     query->qAv4.ValidatingResponse  = 0;
12333     query->qAv4.ProxyQuestion       = 0;
12334     query->qAv4.qnameOrig           = mDNSNULL;
12335     query->qAv4.AnonInfo            = mDNSNULL;
12336     query->qAv4.QuestionCallback    = FoundServiceInfo;
12337     query->qAv4.QuestionContext     = query;
12338 
12339     query->qAv6.ThisQInterval       = -1;       // So that mDNS_StopResolveService() knows whether to cancel this question
12340     query->qAv6.InterfaceID         = info->InterfaceID;
12341     query->qAv6.flags               = 0;
12342     query->qAv6.Target              = zeroAddr;
12343     query->qAv6.qname.c[0]          = 0;
12344     query->qAv6.qtype               = kDNSType_AAAA;
12345     query->qAv6.qclass              = kDNSClass_IN;
12346     query->qAv6.LongLived           = mDNSfalse;
12347     query->qAv6.ExpectUnique        = mDNStrue;
12348     query->qAv6.ForceMCast          = mDNSfalse;
12349     query->qAv6.ReturnIntermed      = mDNSfalse;
12350     query->qAv6.SuppressUnusable    = mDNSfalse;
12351     query->qAv6.DenyOnCellInterface = mDNSfalse;
12352     query->qAv6.DenyOnExpInterface  = mDNSfalse;
12353     query->qAv6.SearchListIndex     = 0;
12354     query->qAv6.AppendSearchDomains = 0;
12355     query->qAv6.RetryWithSearchDomains = mDNSfalse;
12356     query->qAv6.TimeoutQuestion     = 0;
12357     query->qAv6.UseBackgroundTrafficClass = mDNSfalse;
12358     query->qAv6.ValidationRequired  = 0;
12359     query->qAv6.ValidatingResponse  = 0;
12360     query->qAv6.ProxyQuestion       = 0;
12361     query->qAv6.qnameOrig           = mDNSNULL;
12362     query->qAv6.AnonInfo            = mDNSNULL;
12363     query->qAv6.QuestionCallback    = FoundServiceInfo;
12364     query->qAv6.QuestionContext     = query;
12365 
12366     query->GotSRV                   = mDNSfalse;
12367     query->GotTXT                   = mDNSfalse;
12368     query->GotADD                   = mDNSfalse;
12369     query->Answers                  = 0;
12370 
12371     query->info                     = info;
12372     query->ServiceInfoQueryCallback = Callback;
12373     query->ServiceInfoQueryContext  = Context;
12374 
12375 //	info->name      = Must already be set up by client
12376 //	info->interface = Must already be set up by client
12377     info->ip        = zeroAddr;
12378     info->port      = zeroIPPort;
12379     info->TXTlen    = 0;
12380 
12381     // We use mDNS_StartQuery_internal here because we're already holding the lock
12382     status = mDNS_StartQuery_internal(m, &query->qSRV);
12383     if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT);
12384     if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
12385 
12386     mDNS_Unlock(m);
12387     return(status);
12388 }
12389 
12390 mDNSexport void    mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *q)
12391 {
12392     mDNS_Lock(m);
12393     // We use mDNS_StopQuery_internal here because we're already holding the lock
12394     if (q->qSRV.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qSRV);
12395     if (q->qTXT.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qTXT);
12396     if (q->qAv4.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv4);
12397     if (q->qAv6.ThisQInterval >= 0) mDNS_StopQuery_internal(m, &q->qAv6);
12398     mDNS_Unlock(m);
12399 }
12400 
12401 mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
12402                                    const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context)
12403 {
12404     question->InterfaceID      = InterfaceID;
12405     question->flags            = 0;
12406     question->Target           = zeroAddr;
12407     question->qtype            = kDNSType_PTR;
12408     question->qclass           = kDNSClass_IN;
12409     question->LongLived        = mDNSfalse;
12410     question->ExpectUnique     = mDNSfalse;
12411     question->ForceMCast       = mDNSfalse;
12412     question->ReturnIntermed   = mDNSfalse;
12413     question->SuppressUnusable = mDNSfalse;
12414     question->DenyOnCellInterface = mDNSfalse;
12415     question->DenyOnExpInterface  = mDNSfalse;
12416     question->SearchListIndex  = 0;
12417     question->AppendSearchDomains = 0;
12418     question->RetryWithSearchDomains = mDNSfalse;
12419     question->TimeoutQuestion  = 0;
12420     question->WakeOnResolve    = 0;
12421     question->UseBackgroundTrafficClass = mDNSfalse;
12422     question->ValidationRequired = 0;
12423     question->ValidatingResponse = 0;
12424     question->ProxyQuestion    = 0;
12425     question->qnameOrig        = mDNSNULL;
12426     question->AnonInfo         = mDNSNULL;
12427     question->pid              = mDNSPlatformGetPID();
12428     question->euid			   = 0;
12429     question->QuestionCallback = Callback;
12430     question->QuestionContext  = Context;
12431     if (DomainType > mDNS_DomainTypeMax) return(mStatus_BadParamErr);
12432     if (!MakeDomainNameFromDNSNameString(&question->qname, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
12433     if (!dom) dom = &localdomain;
12434     if (!AppendDomainName(&question->qname, dom)) return(mStatus_BadParamErr);
12435     return(mDNS_StartQuery(m, question));
12436 }
12437 
12438 // ***************************************************************************
12439 #if COMPILER_LIKES_PRAGMA_MARK
12440 #pragma mark -
12441 #pragma mark - Responder Functions
12442 #endif
12443 
12444 mDNSexport mStatus mDNS_Register(mDNS *const m, AuthRecord *const rr)
12445 {
12446     mStatus status;
12447     mDNS_Lock(m);
12448     status = mDNS_Register_internal(m, rr);
12449     mDNS_Unlock(m);
12450     return(status);
12451 }
12452 
12453 mDNSexport mStatus mDNS_Update(mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
12454                                const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback)
12455 {
12456     if (!ValidateRData(rr->resrec.rrtype, newrdlength, newrdata))
12457     {
12458         LogMsg("Attempt to update record with invalid rdata: %s", GetRRDisplayString_rdb(&rr->resrec, &newrdata->u, m->MsgBuffer));
12459         return(mStatus_Invalid);
12460     }
12461 
12462     mDNS_Lock(m);
12463 
12464     // If TTL is unspecified, leave TTL unchanged
12465     if (newttl == 0) newttl = rr->resrec.rroriginalttl;
12466 
12467     // If we already have an update queued up which has not gone through yet, give the client a chance to free that memory
12468     if (rr->NewRData)
12469     {
12470         RData *n = rr->NewRData;
12471         rr->NewRData = mDNSNULL;                            // Clear the NewRData pointer ...
12472         if (rr->UpdateCallback)
12473             rr->UpdateCallback(m, rr, n, rr->newrdlength);  // ...and let the client free this memory, if necessary
12474     }
12475 
12476     rr->NewRData             = newrdata;
12477     rr->newrdlength          = newrdlength;
12478     rr->UpdateCallback       = Callback;
12479 
12480 #ifndef UNICAST_DISABLED
12481     if (rr->ARType != AuthRecordLocalOnly && rr->ARType != AuthRecordP2P && !IsLocalDomain(rr->resrec.name))
12482     {
12483         mStatus status = uDNS_UpdateRecord(m, rr);
12484         // The caller frees the memory on error, don't retain stale pointers
12485         if (status != mStatus_NoError) { rr->NewRData = mDNSNULL; rr->newrdlength = 0; }
12486         mDNS_Unlock(m);
12487         return(status);
12488     }
12489 #endif
12490 
12491     if (RRLocalOnly(rr) || (rr->resrec.rroriginalttl == newttl &&
12492                             rr->resrec.rdlength == newrdlength && mDNSPlatformMemSame(rr->resrec.rdata->u.data, newrdata->u.data, newrdlength)))
12493         CompleteRDataUpdate(m, rr);
12494     else
12495     {
12496         rr->AnnounceCount = InitialAnnounceCount;
12497         InitializeLastAPTime(m, rr);
12498         while (rr->NextUpdateCredit && m->timenow - rr->NextUpdateCredit >= 0) GrantUpdateCredit(rr);
12499         if (!rr->UpdateBlocked && rr->UpdateCredits) rr->UpdateCredits--;
12500         if (!rr->NextUpdateCredit) rr->NextUpdateCredit = NonZeroTime(m->timenow + kUpdateCreditRefreshInterval);
12501         if (rr->AnnounceCount > rr->UpdateCredits + 1) rr->AnnounceCount = (mDNSu8)(rr->UpdateCredits + 1);
12502         if (rr->UpdateCredits <= 5)
12503         {
12504             mDNSu32 delay = 6 - rr->UpdateCredits;      // Delay 1 second, then 2, then 3, etc. up to 6 seconds maximum
12505             if (!rr->UpdateBlocked) rr->UpdateBlocked = NonZeroTime(m->timenow + (mDNSs32)delay * mDNSPlatformOneSecond);
12506             rr->ThisAPInterval *= 4;
12507             rr->LastAPTime = rr->UpdateBlocked - rr->ThisAPInterval;
12508             LogMsg("Excessive update rate for %##s; delaying announcement by %ld second%s",
12509                    rr->resrec.name->c, delay, delay > 1 ? "s" : "");
12510         }
12511         rr->resrec.rroriginalttl = newttl;
12512     }
12513 
12514     mDNS_Unlock(m);
12515     return(mStatus_NoError);
12516 }
12517 
12518 // Note: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
12519 // the record list and/or question list.
12520 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
12521 mDNSexport mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr)
12522 {
12523     mStatus status;
12524     mDNS_Lock(m);
12525     status = mDNS_Deregister_internal(m, rr, mDNS_Dereg_normal);
12526     mDNS_Unlock(m);
12527     return(status);
12528 }
12529 
12530 // Circular reference: AdvertiseInterface references mDNS_HostNameCallback, which calls mDNS_SetFQDN, which call AdvertiseInterface
12531 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
12532 
12533 mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
12534 {
12535     NetworkInterfaceInfo *intf;
12536     for (intf = m->HostInterfaces; intf; intf = intf->next)
12537         if (intf->Advertise) break;
12538     return(intf);
12539 }
12540 
12541 mDNSlocal void AdvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12542 {
12543     char buffer[MAX_REVERSE_MAPPING_NAME];
12544     NetworkInterfaceInfo *primary;
12545     mDNSu8 recordType;
12546 
12547     if (m->AutoTargetServices == 0)
12548     {
12549         LogInfo("AdvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
12550         return;
12551     }
12552 
12553     primary = FindFirstAdvertisedInterface(m);
12554     if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
12555 
12556     // If interface is marked as a direct link, we can assume the address record is unique
12557     // and does not need to go through the probe phase of the probe/announce packet sequence.
12558     recordType = (set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique);
12559 
12560     if (set->DirectLink)
12561         LogInfo("AdvertiseInterface: Marking address record as kDNSRecordTypeKnownUnique for %s", set->ifname);
12562 
12563     // Send dynamic update for non-linklocal IPv4 Addresses
12564     mDNS_SetupResourceRecord(&set->RR_A,     mDNSNULL, set->InterfaceID, kDNSType_A,     kHostNameTTL, recordType,      AuthRecordAny, mDNS_HostNameCallback, set);
12565     mDNS_SetupResourceRecord(&set->RR_PTR,   mDNSNULL, set->InterfaceID, kDNSType_PTR,   kHostNameTTL, kDNSRecordTypeKnownUnique, AuthRecordAny, mDNSNULL, mDNSNULL);
12566     mDNS_SetupResourceRecord(&set->RR_HINFO, mDNSNULL, set->InterfaceID, kDNSType_HINFO, kHostNameTTL, kDNSRecordTypeUnique,      AuthRecordAny, mDNSNULL, mDNSNULL);
12567 
12568 #if ANSWER_REMOTE_HOSTNAME_QUERIES
12569     set->RR_A.AllowRemoteQuery  = mDNStrue;
12570     set->RR_PTR.AllowRemoteQuery  = mDNStrue;
12571     set->RR_HINFO.AllowRemoteQuery  = mDNStrue;
12572 #endif
12573     // 1. Set up Address record to map from host name ("foo.local.") to IP address
12574     // 2. Set up reverse-lookup PTR record to map from our address back to our host name
12575     AssignDomainName(&set->RR_A.namestorage, &m->MulticastHostname);
12576     if (set->ip.type == mDNSAddrType_IPv4)
12577     {
12578         set->RR_A.resrec.rrtype = kDNSType_A;
12579         set->RR_A.resrec.rdata->u.ipv4 = set->ip.ip.v4;
12580         // Note: This is reverse order compared to a normal dotted-decimal IP address, so we can't use our customary "%.4a" format code
12581         mDNS_snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d.in-addr.arpa.",
12582                       set->ip.ip.v4.b[3], set->ip.ip.v4.b[2], set->ip.ip.v4.b[1], set->ip.ip.v4.b[0]);
12583     }
12584     else if (set->ip.type == mDNSAddrType_IPv6)
12585     {
12586         int i;
12587         set->RR_A.resrec.rrtype = kDNSType_AAAA;
12588         set->RR_A.resrec.rdata->u.ipv6 = set->ip.ip.v6;
12589         for (i = 0; i < 16; i++)
12590         {
12591             static const char hexValues[] = "0123456789ABCDEF";
12592             buffer[i * 4    ] = hexValues[set->ip.ip.v6.b[15 - i] & 0x0F];
12593             buffer[i * 4 + 1] = '.';
12594             buffer[i * 4 + 2] = hexValues[set->ip.ip.v6.b[15 - i] >> 4];
12595             buffer[i * 4 + 3] = '.';
12596         }
12597         mDNS_snprintf(&buffer[64], sizeof(buffer)-64, "ip6.arpa.");
12598     }
12599 
12600     MakeDomainNameFromDNSNameString(&set->RR_PTR.namestorage, buffer);
12601     set->RR_PTR.AutoTarget = Target_AutoHost;   // Tell mDNS that the target of this PTR is to be kept in sync with our host name
12602     set->RR_PTR.ForceMCast = mDNStrue;          // This PTR points to our dot-local name, so don't ever try to write it into a uDNS server
12603 
12604     set->RR_A.RRSet = &primary->RR_A;           // May refer to self
12605 
12606     mDNS_Register_internal(m, &set->RR_A);
12607     mDNS_Register_internal(m, &set->RR_PTR);
12608 
12609 #if APPLE_OSX_mDNSResponder
12610     // must be after the mDNS_Register_internal() calls so that records have complete rdata fields, etc
12611     D2D_start_advertising_interface(set);
12612 #endif // APPLE_OSX_mDNSResponder
12613 
12614     if (!NO_HINFO && m->HIHardware.c[0] > 0 && m->HISoftware.c[0] > 0 && m->HIHardware.c[0] + m->HISoftware.c[0] <= 254)
12615     {
12616         mDNSu8 *p = set->RR_HINFO.resrec.rdata->u.data;
12617         AssignDomainName(&set->RR_HINFO.namestorage, &m->MulticastHostname);
12618         set->RR_HINFO.DependentOn = &set->RR_A;
12619         mDNSPlatformMemCopy(p, &m->HIHardware, 1 + (mDNSu32)m->HIHardware.c[0]);
12620         p += 1 + (int)p[0];
12621         mDNSPlatformMemCopy(p, &m->HISoftware, 1 + (mDNSu32)m->HISoftware.c[0]);
12622         mDNS_Register_internal(m, &set->RR_HINFO);
12623     }
12624     else
12625     {
12626         debugf("Not creating HINFO record: platform support layer provided no information");
12627         set->RR_HINFO.resrec.RecordType = kDNSRecordTypeUnregistered;
12628     }
12629 }
12630 
12631 mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
12632 {
12633     if (m->AutoTargetServices == 0)
12634     {
12635         LogInfo("DeadvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
12636         return;
12637     }
12638 
12639     // Unregister these records.
12640     // When doing the mDNS_Exit processing, we first call DeadvertiseInterface for each interface, so by the time the platform
12641     // support layer gets to call mDNS_DeregisterInterface, the address and PTR records have already been deregistered for it.
12642     // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
12643     // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
12644     if (set->RR_A    .resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A,     mDNS_Dereg_normal);
12645     if (set->RR_PTR  .resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR,   mDNS_Dereg_normal);
12646     if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
12647 
12648 #if APPLE_OSX_mDNSResponder
12649     D2D_stop_advertising_interface(set);
12650 #endif // APPLE_OSX_mDNSResponder
12651 
12652 }
12653 
12654 mDNSlocal void AdvertiseAllInterfaceRecords(mDNS *const m)
12655 {
12656     NetworkInterfaceInfo *intf;
12657     for (intf = m->HostInterfaces; intf; intf = intf->next)
12658     {
12659         if (intf->Advertise)
12660         {
12661             LogInfo("AdvertiseInterface: Advertising for ifname %s", intf->ifname);
12662             AdvertiseInterface(m, intf);
12663         }
12664     }
12665 }
12666 
12667 mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m)
12668 {
12669     NetworkInterfaceInfo *intf;
12670     for (intf = m->HostInterfaces; intf; intf = intf->next)
12671     {
12672         if (intf->Advertise)
12673         {
12674             LogInfo("DeadvertiseInterface: Deadvertising for ifname %s", intf->ifname);
12675             DeadvertiseInterface(m, intf);
12676         }
12677     }
12678 }
12679 
12680 mDNSexport void mDNS_SetFQDN(mDNS *const m)
12681 {
12682     domainname newmname;
12683     AuthRecord *rr;
12684     newmname.c[0] = 0;
12685 
12686     if (!AppendDomainLabel(&newmname, &m->hostlabel))  { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12687     if (!AppendLiteralLabelString(&newmname, "local")) { LogMsg("ERROR: mDNS_SetFQDN: Cannot create MulticastHostname"); return; }
12688 
12689     mDNS_Lock(m);
12690 
12691     if (SameDomainNameCS(&m->MulticastHostname, &newmname)) debugf("mDNS_SetFQDN - hostname unchanged");
12692     else
12693     {
12694         AssignDomainName(&m->MulticastHostname, &newmname);
12695         DeadvertiseAllInterfaceRecords(m);
12696         AdvertiseAllInterfaceRecords(m);
12697     }
12698 
12699     // 3. Make sure that any AutoTarget SRV records (and the like) get updated
12700     for (rr = m->ResourceRecords;  rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
12701     for (rr = m->DuplicateRecords; rr; rr=rr->next) if (rr->AutoTarget) SetTargetToHostName(m, rr);
12702 
12703     mDNS_Unlock(m);
12704 }
12705 
12706 mDNSlocal void mDNS_HostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
12707 {
12708     (void)rr;   // Unused parameter
12709 
12710     #if MDNS_DEBUGMSGS
12711     {
12712         char *msg = "Unknown result";
12713         if      (result == mStatus_NoError) msg = "Name registered";
12714         else if (result == mStatus_NameConflict) msg = "Name conflict";
12715         debugf("mDNS_HostNameCallback: %##s (%s) %s (%ld)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
12716     }
12717     #endif
12718 
12719     if (result == mStatus_NoError)
12720     {
12721         // Notify the client that the host name is successfully registered
12722         if (m->MainCallback)
12723             m->MainCallback(m, mStatus_NoError);
12724     }
12725     else if (result == mStatus_NameConflict)
12726     {
12727         domainlabel oldlabel = m->hostlabel;
12728 
12729         // 1. First give the client callback a chance to pick a new name
12730         if (m->MainCallback)
12731             m->MainCallback(m, mStatus_NameConflict);
12732 
12733         // 2. If the client callback didn't do it, add (or increment) an index ourselves
12734         // This needs to be case-INSENSITIVE compare, because we need to know that the name has been changed so as to
12735         // remedy the conflict, and a name that differs only in capitalization will just suffer the exact same conflict again.
12736         if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
12737             IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
12738 
12739         // 3. Generate the FQDNs from the hostlabel,
12740         // and make sure all SRV records, etc., are updated to reference our new hostname
12741         mDNS_SetFQDN(m);
12742         LogMsg("Local Hostname %#s.local already in use; will try %#s.local instead", oldlabel.c, m->hostlabel.c);
12743     }
12744     else if (result == mStatus_MemFree)
12745     {
12746         // .local hostnames do not require goodbyes - we ignore the MemFree (which is sent directly by
12747         // mDNS_Deregister_internal), and allow the caller to deallocate immediately following mDNS_DeadvertiseInterface
12748         debugf("mDNS_HostNameCallback: MemFree (ignored)");
12749     }
12750     else
12751         LogMsg("mDNS_HostNameCallback: Unknown error %d for registration of record %s", result,  rr->resrec.name->c);
12752 }
12753 
12754 mDNSlocal void UpdateInterfaceProtocols(mDNS *const m, NetworkInterfaceInfo *active)
12755 {
12756     NetworkInterfaceInfo *intf;
12757     active->IPv4Available = mDNSfalse;
12758     active->IPv6Available = mDNSfalse;
12759     for (intf = m->HostInterfaces; intf; intf = intf->next)
12760         if (intf->InterfaceID == active->InterfaceID)
12761         {
12762             if (intf->ip.type == mDNSAddrType_IPv4 && intf->McastTxRx) active->IPv4Available = mDNStrue;
12763             if (intf->ip.type == mDNSAddrType_IPv6 && intf->McastTxRx) active->IPv6Available = mDNStrue;
12764         }
12765 }
12766 
12767 mDNSlocal void RestartRecordGetZoneData(mDNS * const m)
12768 {
12769     AuthRecord *rr;
12770     LogInfo("RestartRecordGetZoneData: ResourceRecords");
12771     for (rr = m->ResourceRecords; rr; rr=rr->next)
12772         if (AuthRecord_uDNS(rr) && rr->state != regState_NoTarget)
12773         {
12774             debugf("RestartRecordGetZoneData: StartGetZoneData for %##s", rr->resrec.name->c);
12775             // Zero out the updateid so that if we have a pending response from the server, it won't
12776             // be accepted as a valid response. If we accept the response, we might free the new "nta"
12777             if (rr->nta) { rr->updateid = zeroID; CancelGetZoneData(m, rr->nta); }
12778             rr->nta = StartGetZoneData(m, rr->resrec.name, ZoneServiceUpdate, RecordRegistrationGotZoneData, rr);
12779         }
12780 }
12781 
12782 mDNSlocal void InitializeNetWakeState(mDNS *const m, NetworkInterfaceInfo *set)
12783 {
12784     int i;
12785     // We initialize ThisQInterval to -1 indicating that the question has not been started
12786     // yet. If the question (browse) is started later during interface registration, it will
12787     // be stopped during interface deregistration. We can't sanity check to see if the
12788     // question has been stopped or not before initializing it to -1 because we need to
12789     // initialize it to -1 the very first time.
12790 
12791     set->NetWakeBrowse.ThisQInterval = -1;
12792     for (i=0; i<3; i++)
12793     {
12794         set->NetWakeResolve[i].ThisQInterval = -1;
12795         set->SPSAddr[i].type = mDNSAddrType_None;
12796     }
12797     set->NextSPSAttempt     = -1;
12798     set->NextSPSAttemptTime = m->timenow;
12799 }
12800 
12801 mDNSexport void mDNS_ActivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12802 {
12803     NetworkInterfaceInfo *p = m->HostInterfaces;
12804     while (p && p != set) p=p->next;
12805     if (!p) { LogMsg("mDNS_ActivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12806 
12807     if (set->InterfaceActive)
12808     {
12809         LogSPS("ActivateNetWake for %s (%#a)", set->ifname, &set->ip);
12810         mDNS_StartBrowse_internal(m, &set->NetWakeBrowse, &SleepProxyServiceType, &localdomain, mDNSNULL, set->InterfaceID, 0, mDNSfalse, mDNSfalse, m->SPSBrowseCallback, set);
12811     }
12812 }
12813 
12814 mDNSexport void mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set)
12815 {
12816     NetworkInterfaceInfo *p = m->HostInterfaces;
12817     while (p && p != set) p=p->next;
12818     if (!p) { LogMsg("mDNS_DeactivateNetWake_internal: NetworkInterfaceInfo %p not found in active list", set); return; }
12819 
12820     // Note: We start the browse only if the interface is NetWake capable and we use this to
12821     // stop the resolves also. Hence, the resolves should not be started without the browse
12822     // being started i.e, resolves should not happen unless NetWake capable which is
12823     // guaranteed by BeginSleepProcessing.
12824     if (set->NetWakeBrowse.ThisQInterval >= 0)
12825     {
12826         int i;
12827         LogSPS("DeactivateNetWake for %s (%#a)", set->ifname, &set->ip);
12828 
12829         // Stop our browse and resolve operations
12830         mDNS_StopQuery_internal(m, &set->NetWakeBrowse);
12831         for (i=0; i<3; i++) if (set->NetWakeResolve[i].ThisQInterval >= 0) mDNS_StopQuery_internal(m, &set->NetWakeResolve[i]);
12832 
12833         // Make special call to the browse callback to let it know it can to remove all records for this interface
12834         if (m->SPSBrowseCallback)
12835         {
12836             mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
12837             m->SPSBrowseCallback(m, &set->NetWakeBrowse, mDNSNULL, QC_rmv);
12838             mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
12839         }
12840 
12841         // Reset our variables back to initial state, so we're ready for when NetWake is turned back on
12842         // (includes resetting NetWakeBrowse.ThisQInterval back to -1)
12843         InitializeNetWakeState(m, set);
12844     }
12845 }
12846 
12847 mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
12848 {
12849     AuthRecord *rr;
12850     mDNSBool FirstOfType = mDNStrue;
12851     NetworkInterfaceInfo **p = &m->HostInterfaces;
12852 
12853     if (!set->InterfaceID)
12854     { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with zero InterfaceID", &set->ip); return(mStatus_Invalid); }
12855 
12856     if (!mDNSAddressIsValidNonZero(&set->mask))
12857     { LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo %#a with invalid mask %#a", &set->ip, &set->mask); return(mStatus_Invalid); }
12858 
12859     mDNS_Lock(m);
12860 
12861     // Assume this interface will be active now, unless we find a duplicate already in the list
12862     set->InterfaceActive = mDNStrue;
12863     set->IPv4Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx);
12864     set->IPv6Available   = (mDNSu8)(set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx);
12865 
12866     InitializeNetWakeState(m, set);
12867 
12868     // Scan list to see if this InterfaceID is already represented
12869     while (*p)
12870     {
12871         if (*p == set)
12872         {
12873             LogMsg("mDNS_RegisterInterface: Error! Tried to register a NetworkInterfaceInfo that's already in the list");
12874             mDNS_Unlock(m);
12875             return(mStatus_AlreadyRegistered);
12876         }
12877 
12878         if ((*p)->InterfaceID == set->InterfaceID)
12879         {
12880             // This InterfaceID already represented by a different interface in the list, so mark this instance inactive for now
12881             set->InterfaceActive = mDNSfalse;
12882             if (set->ip.type == (*p)->ip.type) FirstOfType = mDNSfalse;
12883             if (set->ip.type == mDNSAddrType_IPv4 && set->McastTxRx) (*p)->IPv4Available = mDNStrue;
12884             if (set->ip.type == mDNSAddrType_IPv6 && set->McastTxRx) (*p)->IPv6Available = mDNStrue;
12885         }
12886 
12887         p=&(*p)->next;
12888     }
12889 
12890     set->next = mDNSNULL;
12891     *p = set;
12892 
12893     if (set->Advertise)
12894         AdvertiseInterface(m, set);
12895 
12896     LogInfo("mDNS_RegisterInterface: InterfaceID %d %s (%#a) %s",
12897             (uint32_t)set->InterfaceID, set->ifname, &set->ip,
12898             set->InterfaceActive ?
12899             "not represented in list; marking active and retriggering queries" :
12900             "already represented in list; marking inactive for now");
12901 
12902     if (set->NetWake) mDNS_ActivateNetWake_internal(m, set);
12903 
12904     // In early versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
12905     // giving the false impression that there's an active representative of this interface when there really isn't.
12906     // Therefore, when registering an interface, we want to re-trigger our questions and re-probe our Resource Records,
12907     // even if we believe that we previously had an active representative of this interface.
12908     if (set->McastTxRx && (FirstOfType || set->InterfaceActive))
12909     {
12910         DNSQuestion *q;
12911         // Normally, after an interface comes up, we pause half a second before beginning probing.
12912         // This is to guard against cases where there's rapid interface changes, where we could be confused by
12913         // seeing packets we ourselves sent just moments ago (perhaps when this interface had a different address)
12914         // which are then echoed back after a short delay by some Ethernet switches and some 802.11 base stations.
12915         // We don't want to do a probe, and then see a stale echo of an announcement we ourselves sent,
12916         // and think it's a conflicting answer to our probe.
12917         // In the case of a flapping interface, we pause for five seconds, and reduce the announcement count to one packet.
12918         const mDNSs32 probedelay  = flapping ? mDNSPlatformOneSecond * 5 : mDNSPlatformOneSecond / 2;
12919         const mDNSu8 numannounce = flapping ? (mDNSu8)1                 : InitialAnnounceCount;
12920 
12921         // Use a small amount of randomness:
12922         // In the case of a network administrator turning on an Ethernet hub so that all the
12923         // connected machines establish link at exactly the same time, we don't want them all
12924         // to go and hit the network with identical queries at exactly the same moment.
12925         // We set a random delay of up to InitialQuestionInterval (1/3 second).
12926         // We must *never* set m->SuppressSending to more than that (or set it repeatedly in a way
12927         // that causes mDNSResponder to remain in a prolonged state of SuppressSending, because
12928         // suppressing packet sending for more than about 1/3 second can cause protocol correctness
12929         // to start to break down (e.g. we don't answer probes fast enough, and get name conflicts).
12930         // See <rdar://problem/4073853> mDNS: m->SuppressSending set too enthusiastically
12931         if (!m->SuppressSending) m->SuppressSending = m->timenow + (mDNSs32)mDNSRandom((mDNSu32)InitialQuestionInterval);
12932 
12933         if (flapping)
12934         {
12935             LogMsg("mDNS_RegisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
12936             m->mDNSStats.InterfaceUpFlap++;
12937         }
12938 
12939         LogInfo("mDNS_RegisterInterface: %s (%#a) probedelay %d", set->ifname, &set->ip, probedelay);
12940         if (m->SuppressProbes == 0 ||
12941             m->SuppressProbes - NonZeroTime(m->timenow + probedelay) < 0)
12942             m->SuppressProbes = NonZeroTime(m->timenow + probedelay);
12943 
12944         // Include OWNER option in packets for 60 seconds after connecting to the network. Setting
12945         // it here also handles the wake up case as the network link comes UP after waking causing
12946         // us to reconnect to the network. If we do this as part of the wake up code, it is possible
12947         // that the network link comes UP after 60 seconds and we never set the OWNER option
12948         m->AnnounceOwner = NonZeroTime(m->timenow + 60 * mDNSPlatformOneSecond);
12949         LogInfo("mDNS_RegisterInterface: Setting AnnounceOwner");
12950 
12951         m->mDNSStats.InterfaceUp++;
12952         for (q = m->Questions; q; q=q->next)                                // Scan our list of questions
12953         {
12954             if (mDNSOpaque16IsZero(q->TargetQID))
12955             {
12956                 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)      // If non-specific Q, or Q on this specific interface,
12957                 {                                                               // then reactivate this question
12958                     // If flapping, delay between first and second queries is nine seconds instead of one second
12959                     mDNSBool dodelay = flapping && (q->FlappingInterface1 == set->InterfaceID || q->FlappingInterface2 == set->InterfaceID);
12960                     mDNSs32 initial  = dodelay ? InitialQuestionInterval * QuestionIntervalStep2 : InitialQuestionInterval;
12961                     mDNSs32 qdelay   = dodelay ? mDNSPlatformOneSecond * 5 : 0;
12962                     if (dodelay) LogInfo("No cache records expired for %##s (%s); okay to delay questions a little", q->qname.c, DNSTypeName(q->qtype));
12963 
12964                     if (!q->ThisQInterval || q->ThisQInterval > initial)
12965                     {
12966                         q->ThisQInterval = initial;
12967 
12968 #if mDNS_REQUEST_UNICAST_RESPONSE
12969                         q->RequestUnicast = SET_QU_IN_FIRST_FOUR_QUERIES;
12970 #else   // mDNS_REQUEST_UNICAST_RESPONSE
12971                         q->RequestUnicast = SET_QU_IN_FIRST_QUERY;
12972 #endif  // mDNS_REQUEST_UNICAST_RESPONSE
12973 
12974                     }
12975                     q->LastQTime = m->timenow - q->ThisQInterval + qdelay;
12976                     q->RecentAnswerPkts = 0;
12977                     // Change the salt
12978                     ReInitAnonInfo(&q->AnonInfo, &q->qname);
12979                     SetNextQueryTime(m,q);
12980                 }
12981             }
12982         }
12983 
12984         // For all our non-specific authoritative resource records (and any dormant records specific to this interface)
12985         // we now need them to re-probe if necessary, and then re-announce.
12986         for (rr = m->ResourceRecords; rr; rr=rr->next)
12987         {
12988             if (!rr->resrec.InterfaceID || rr->resrec.InterfaceID == set->InterfaceID)
12989             {
12990                 // Change the salt
12991                 ReInitAnonInfo(&rr->resrec.AnonInfo, rr->resrec.name);
12992                 mDNSCoreRestartRegistration(m, rr, numannounce);
12993             }
12994         }
12995 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
12996         DNSSECProbe(m);
12997 #endif
12998     }
12999 
13000     RestartRecordGetZoneData(m);
13001 
13002     mDNS_UpdateAllowSleep(m);
13003 
13004     mDNS_Unlock(m);
13005     return(mStatus_NoError);
13006 }
13007 
13008 // Note: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
13009 // the record list and/or question list.
13010 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13011 mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping)
13012 {
13013     NetworkInterfaceInfo **p = &m->HostInterfaces;
13014     mDNSBool revalidate = mDNSfalse;
13015     NetworkInterfaceInfo *primary;
13016     NetworkInterfaceInfo *intf;
13017     AuthRecord *A;
13018 
13019     mDNS_Lock(m);
13020 
13021     // Find this record in our list
13022     while (*p && *p != set) p=&(*p)->next;
13023     if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); mDNS_Unlock(m); return; }
13024 
13025     mDNS_DeactivateNetWake_internal(m, set);
13026 
13027     // Unlink this record from our list
13028     *p = (*p)->next;
13029     set->next = mDNSNULL;
13030 
13031     if (!set->InterfaceActive)
13032     {
13033         // If this interface not the active member of its set, update the v4/v6Available flags for the active member
13034         for (intf = m->HostInterfaces; intf; intf = intf->next)
13035             if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
13036                 UpdateInterfaceProtocols(m, intf);
13037     }
13038     else
13039     {
13040         intf = FirstInterfaceForID(m, set->InterfaceID);
13041         if (intf)
13042         {
13043             LogInfo("mDNS_DeregisterInterface: Another representative of InterfaceID %d %s (%#a) exists;"
13044                     " making it active", (uint32_t)set->InterfaceID, set->ifname, &set->ip);
13045             if (intf->InterfaceActive)
13046                 LogMsg("mDNS_DeregisterInterface: ERROR intf->InterfaceActive already set for %s (%#a)", set->ifname, &set->ip);
13047             intf->InterfaceActive = mDNStrue;
13048             UpdateInterfaceProtocols(m, intf);
13049 
13050             if (intf->NetWake) mDNS_ActivateNetWake_internal(m, intf);
13051 
13052             // See if another representative *of the same type* exists. If not, we mave have gone from
13053             // dual-stack to v6-only (or v4-only) so we need to reconfirm which records are still valid.
13054             for (intf = m->HostInterfaces; intf; intf = intf->next)
13055                 if (intf->InterfaceID == set->InterfaceID && intf->ip.type == set->ip.type)
13056                     break;
13057             if (!intf) revalidate = mDNStrue;
13058         }
13059         else
13060         {
13061             mDNSu32 slot;
13062             CacheGroup *cg;
13063             CacheRecord *rr;
13064             DNSQuestion *q;
13065 
13066             LogInfo("mDNS_DeregisterInterface: Last representative of InterfaceID %d %s (%#a) deregistered;"
13067                     " marking questions etc. dormant", (uint32_t)set->InterfaceID, set->ifname, &set->ip);
13068 
13069             m->mDNSStats.InterfaceDown++;
13070 
13071             if (set->McastTxRx && flapping)
13072             {
13073                 LogMsg("mDNS_DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
13074                 m->mDNSStats.InterfaceDownFlap++;
13075             }
13076 
13077             // 1. Deactivate any questions specific to this interface, and tag appropriate questions
13078             // so that mDNS_RegisterInterface() knows how swiftly it needs to reactivate them
13079             for (q = m->Questions; q; q=q->next)
13080             {
13081                 if (q->InterfaceID == set->InterfaceID) q->ThisQInterval = 0;
13082                 if (!q->InterfaceID || q->InterfaceID == set->InterfaceID)
13083                 {
13084                     q->FlappingInterface2 = q->FlappingInterface1;
13085                     q->FlappingInterface1 = set->InterfaceID;       // Keep history of the last two interfaces to go away
13086                 }
13087             }
13088 
13089             // 2. Flush any cache records received on this interface
13090             revalidate = mDNSfalse;     // Don't revalidate if we're flushing the records
13091             FORALL_CACHERECORDS(slot, cg, rr)
13092             {
13093                 if (rr->resrec.InterfaceID == set->InterfaceID)
13094                 {
13095                     // If this interface is deemed flapping,
13096                     // postpone deleting the cache records in case the interface comes back again
13097                     if (set->McastTxRx && flapping)
13098                     {
13099                         // For a flapping interface we want these record to go away after 30 seconds
13100                         mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13101                         // We set UnansweredQueries = MaxUnansweredQueries so we don't waste time doing any queries for them --
13102                         // if the interface does come back, any relevant questions will be reactivated anyway
13103                         rr->UnansweredQueries = MaxUnansweredQueries;
13104                     }
13105                     else
13106                     {
13107                         mDNS_PurgeCacheResourceRecord(m, rr);
13108                     }
13109                 }
13110             }
13111         }
13112     }
13113 
13114     // If we still have address records referring to this one, update them.
13115     // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
13116     // so the call to FindFirstAdvertisedInterface() won’t accidentally find it.
13117     primary = FindFirstAdvertisedInterface(m);
13118     A = primary ? &primary->RR_A : mDNSNULL;
13119     for (intf = m->HostInterfaces; intf; intf = intf->next)
13120         if (intf->RR_A.RRSet == &set->RR_A)
13121             intf->RR_A.RRSet = A;
13122 
13123     // If we were advertising on this interface, deregister those address and reverse-lookup records now
13124     if (set->Advertise) DeadvertiseInterface(m, set);
13125 
13126     // If we have any cache records received on this interface that went away, then re-verify them.
13127     // In some versions of OS X the IPv6 address remains on an interface even when the interface is turned off,
13128     // giving the false impression that there's an active representative of this interface when there really isn't.
13129     // Don't need to do this when shutting down, because *all* interfaces are about to go away
13130     if (revalidate && !m->ShutdownTime)
13131     {
13132         mDNSu32 slot;
13133         CacheGroup *cg;
13134         CacheRecord *rr;
13135         FORALL_CACHERECORDS(slot, cg, rr)
13136         if (rr->resrec.InterfaceID == set->InterfaceID)
13137             mDNS_Reconfirm_internal(m, rr, kDefaultReconfirmTimeForFlappingInterface);
13138     }
13139 
13140     mDNS_UpdateAllowSleep(m);
13141 
13142     mDNS_Unlock(m);
13143 }
13144 
13145 mDNSlocal void SetAnonInfoSRS(ServiceRecordSet *sr, int NumSubTypes)
13146 {
13147     int i, len;
13148 
13149     if (!sr->AnonData)
13150         return;
13151 
13152     len = mDNSPlatformStrLen(sr->AnonData);
13153     if (sr->RR_PTR.resrec.AnonInfo)
13154     {
13155         LogMsg("SetAnonInfoSRS: Freeing AnonInfo for PTR record %##s, should have been freed already", sr->RR_PTR.resrec.name->c);
13156         FreeAnonInfo(sr->RR_PTR.resrec.AnonInfo);
13157     }
13158     sr->RR_PTR.resrec.AnonInfo = AllocateAnonInfo(sr->RR_PTR.resrec.name, sr->AnonData, len, mDNSNULL);
13159     for (i=0; i<NumSubTypes; i++)
13160     {
13161         if (sr->SubTypes[i].resrec.AnonInfo)
13162         {
13163             LogMsg("SetAnonInfoSRS: Freeing AnonInfo for subtype record %##s, should have been freed already", sr->SubTypes[i].resrec.name->c);
13164             FreeAnonInfo(sr->SubTypes[i].resrec.AnonInfo);
13165         }
13166         sr->SubTypes[i].resrec.AnonInfo = AllocateAnonInfo(sr->SubTypes[i].resrec.name, sr->AnonData, len, mDNSNULL);
13167     }
13168 }
13169 
13170 mDNSlocal void ResetAnonInfoSRS(ServiceRecordSet *sr, int NumSubTypes)
13171 {
13172     int i;
13173 
13174     if (!sr->AnonData)
13175         return;
13176     if (sr->RR_PTR.resrec.AnonInfo)
13177     {
13178         FreeAnonInfo(sr->RR_PTR.resrec.AnonInfo);
13179         sr->RR_PTR.resrec.AnonInfo = mDNSNULL;
13180     }
13181     for (i=0; i<NumSubTypes; i++)
13182     {
13183         if (sr->SubTypes[i].resrec.AnonInfo)
13184         {
13185             FreeAnonInfo(sr->SubTypes[i].resrec.AnonInfo);
13186             sr->SubTypes[i].resrec.AnonInfo = mDNSNULL;
13187         }
13188     }
13189 }
13190 
13191 mDNSlocal void ServiceCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13192 {
13193     ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13194     (void)m;    // Unused parameter
13195 
13196     #if MDNS_DEBUGMSGS
13197     {
13198         char *msg = "Unknown result";
13199         if      (result == mStatus_NoError) msg = "Name Registered";
13200         else if (result == mStatus_NameConflict) msg = "Name Conflict";
13201         else if (result == mStatus_MemFree) msg = "Memory Free";
13202         debugf("ServiceCallback: %##s (%s) %s (%d)", rr->resrec.name->c, DNSTypeName(rr->resrec.rrtype), msg, result);
13203     }
13204     #endif
13205 
13206     // Only pass on the NoError acknowledgement for the SRV record (when it finishes probing)
13207     if (result == mStatus_NoError && rr != &sr->RR_SRV) return;
13208 
13209     // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
13210     if (result == mStatus_NameConflict)
13211     {
13212         sr->Conflict = mDNStrue;                // Record that this service set had a conflict
13213         mDNS_DeregisterService(m, sr);          // Unlink the records from our list
13214         return;
13215     }
13216 
13217     if (result == mStatus_MemFree)
13218     {
13219         // If the SRV/TXT/PTR records, or the _services._dns-sd._udp record, or any of the subtype PTR records,
13220         // are still in the process of deregistering, don't pass on the NameConflict/MemFree message until
13221         // every record is finished cleaning up.
13222         mDNSu32 i;
13223         ExtraResourceRecord *e = sr->Extras;
13224 
13225         if (sr->RR_SRV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13226         if (sr->RR_TXT.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13227         if (sr->RR_PTR.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13228         if (sr->RR_ADV.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13229         for (i=0; i<sr->NumSubTypes; i++) if (sr->SubTypes[i].resrec.RecordType != kDNSRecordTypeUnregistered) return;
13230 
13231         while (e)
13232         {
13233             if (e->r.resrec.RecordType != kDNSRecordTypeUnregistered) return;
13234             e = e->next;
13235         }
13236         ResetAnonInfoSRS(sr, sr->NumSubTypes);
13237 
13238         // If this ServiceRecordSet was forcibly deregistered, and now its memory is ready for reuse,
13239         // then we can now report the NameConflict to the client
13240         if (sr->Conflict) result = mStatus_NameConflict;
13241 
13242     }
13243 
13244     LogInfo("ServiceCallback: All records %s for %##s", (result == mStatus_MemFree ? "Unregistered" : "Registered"), sr->RR_PTR.resrec.name->c);
13245     // CAUTION: MUST NOT do anything more with sr after calling sr->Callback(), because the client's callback
13246     // function is allowed to do anything, including deregistering this service and freeing its memory.
13247     if (sr->ServiceCallback)
13248         sr->ServiceCallback(m, sr, result);
13249 }
13250 
13251 mDNSlocal void NSSCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
13252 {
13253     ServiceRecordSet *sr = (ServiceRecordSet *)rr->RecordContext;
13254     if (sr->ServiceCallback)
13255         sr->ServiceCallback(m, sr, result);
13256 }
13257 
13258 
13259 mDNSlocal AuthRecType setAuthRecType(mDNSInterfaceID InterfaceID, mDNSu32 flags)
13260 {
13261     AuthRecType artype;
13262 
13263     if (InterfaceID == mDNSInterface_LocalOnly)
13264         artype = AuthRecordLocalOnly;
13265     else if (InterfaceID == mDNSInterface_P2P)
13266         artype = AuthRecordP2P;
13267     else if ((InterfaceID == mDNSInterface_Any) && (flags & coreFlagIncludeP2P)
13268             && (flags & coreFlagIncludeAWDL))
13269         artype = AuthRecordAnyIncludeAWDLandP2P;
13270     else if ((InterfaceID == mDNSInterface_Any) && (flags & coreFlagIncludeP2P))
13271         artype = AuthRecordAnyIncludeP2P;
13272     else if ((InterfaceID == mDNSInterface_Any) && (flags & coreFlagIncludeAWDL))
13273         artype = AuthRecordAnyIncludeAWDL;
13274     else
13275         artype = AuthRecordAny;
13276 
13277     return artype;
13278 }
13279 
13280 // Note:
13281 // Name is first label of domain name (any dots in the name are actual dots, not label separators)
13282 // Type is service type (e.g. "_ipp._tcp.")
13283 // Domain is fully qualified domain name (i.e. ending with a null label)
13284 // We always register a TXT, even if it is empty (so that clients are not
13285 // left waiting forever looking for a nonexistent record.)
13286 // If the host parameter is mDNSNULL or the root domain (ASCII NUL),
13287 // then the default host name (m->MulticastHostname) is automatically used
13288 // If the optional target host parameter is set, then the storage it points to must remain valid for the lifetime of the service registration
13289 mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
13290                                         const domainlabel *const name, const domainname *const type, const domainname *const domain,
13291                                         const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
13292                                         AuthRecord *SubTypes, mDNSu32 NumSubTypes,
13293                                         mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags)
13294 {
13295     mStatus err;
13296     mDNSu32 i;
13297     mDNSu32 hostTTL;
13298     AuthRecType artype;
13299     mDNSu8 recordType = (flags & coreFlagKnownUnique) ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique;
13300 
13301     sr->ServiceCallback = Callback;
13302     sr->ServiceContext  = Context;
13303     sr->Conflict        = mDNSfalse;
13304 
13305     sr->Extras          = mDNSNULL;
13306     sr->NumSubTypes     = NumSubTypes;
13307     sr->SubTypes        = SubTypes;
13308     sr->flags           = flags;
13309 
13310     artype = setAuthRecType(InterfaceID, flags);
13311 
13312     // Initialize the AuthRecord objects to sane values
13313     // Need to initialize everything correctly *before* making the decision whether to do a RegisterNoSuchService and bail out
13314     mDNS_SetupResourceRecord(&sr->RR_ADV, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeAdvisory, artype, ServiceCallback, sr);
13315     mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared,   artype, ServiceCallback, sr);
13316 
13317     if (flags & coreFlagWakeOnly)
13318     {
13319         sr->RR_PTR.AuthFlags = AuthFlagsWakeOnly;
13320     }
13321 
13322     if (SameDomainName(type, (const domainname *) "\x4" "_ubd" "\x4" "_tcp"))
13323         hostTTL = kHostNameSmallTTL;
13324     else
13325         hostTTL = kHostNameTTL;
13326 
13327     mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, InterfaceID, kDNSType_SRV, hostTTL, recordType, artype, ServiceCallback, sr);
13328     mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, InterfaceID, kDNSType_TXT, kStandardTTL, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13329 
13330     // If port number is zero, that means the client is really trying to do a RegisterNoSuchService
13331     if (mDNSIPPortIsZero(port))
13332         return(mDNS_RegisterNoSuchService(m, &sr->RR_SRV, name, type, domain, mDNSNULL, InterfaceID, NSSCallback, sr, flags));
13333 
13334     // If the client is registering an oversized TXT record,
13335     // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
13336     if (sr->RR_TXT.resrec.rdata->MaxRDLength < txtlen)
13337         sr->RR_TXT.resrec.rdata->MaxRDLength = txtlen;
13338 
13339     // Set up the record names
13340     // For now we only create an advisory record for the main type, not for subtypes
13341     // We need to gain some operational experience before we decide if there's a need to create them for subtypes too
13342     if (ConstructServiceName(&sr->RR_ADV.namestorage, (const domainlabel*)"\x09_services", (const domainname*)"\x07_dns-sd\x04_udp", domain) == mDNSNULL)
13343         return(mStatus_BadParamErr);
13344     if (ConstructServiceName(&sr->RR_PTR.namestorage, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13345     if (ConstructServiceName(&sr->RR_SRV.namestorage, name,     type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13346     AssignDomainName(&sr->RR_TXT.namestorage, sr->RR_SRV.resrec.name);
13347 
13348     // 1. Set up the ADV record rdata to advertise our service type
13349     AssignDomainName(&sr->RR_ADV.resrec.rdata->u.name, sr->RR_PTR.resrec.name);
13350 
13351     // 2. Set up the PTR record rdata to point to our service name
13352     // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
13353     // Note: uDNS registration code assumes that Additional1 points to the SRV record
13354     AssignDomainName(&sr->RR_PTR.resrec.rdata->u.name, sr->RR_SRV.resrec.name);
13355     sr->RR_PTR.Additional1 = &sr->RR_SRV;
13356     sr->RR_PTR.Additional2 = &sr->RR_TXT;
13357 
13358     // 2a. Set up any subtype PTRs to point to our service name
13359     // If the client is using subtypes, it is the client's responsibility to have
13360     // already set the first label of the record name to the subtype being registered
13361     for (i=0; i<NumSubTypes; i++)
13362     {
13363         domainname st;
13364         AssignDomainName(&st, sr->SubTypes[i].resrec.name);
13365         st.c[1+st.c[0]] = 0;            // Only want the first label, not the whole FQDN (particularly for mDNS_RenameAndReregisterService())
13366         AppendDomainName(&st, type);
13367         mDNS_SetupResourceRecord(&sr->SubTypes[i], mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, ServiceCallback, sr);
13368         if (ConstructServiceName(&sr->SubTypes[i].namestorage, mDNSNULL, &st, domain) == mDNSNULL) return(mStatus_BadParamErr);
13369         AssignDomainName(&sr->SubTypes[i].resrec.rdata->u.name, &sr->RR_SRV.namestorage);
13370         sr->SubTypes[i].Additional1 = &sr->RR_SRV;
13371         sr->SubTypes[i].Additional2 = &sr->RR_TXT;
13372     }
13373 
13374     SetAnonInfoSRS(sr, NumSubTypes);
13375 
13376     // 3. Set up the SRV record rdata.
13377     sr->RR_SRV.resrec.rdata->u.srv.priority = 0;
13378     sr->RR_SRV.resrec.rdata->u.srv.weight   = 0;
13379     sr->RR_SRV.resrec.rdata->u.srv.port     = port;
13380 
13381     // Setting AutoTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
13382     if (host && host->c[0]) AssignDomainName(&sr->RR_SRV.resrec.rdata->u.srv.target, host);
13383     else { sr->RR_SRV.AutoTarget = Target_AutoHost; sr->RR_SRV.resrec.rdata->u.srv.target.c[0] = '\0'; }
13384 
13385     // 4. Set up the TXT record rdata,
13386     // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
13387     // Note: uDNS registration code assumes that DependentOn points to the SRV record
13388     if (txtinfo == mDNSNULL) sr->RR_TXT.resrec.rdlength = 0;
13389     else if (txtinfo != sr->RR_TXT.resrec.rdata->u.txt.c)
13390     {
13391         sr->RR_TXT.resrec.rdlength = txtlen;
13392         if (sr->RR_TXT.resrec.rdlength > sr->RR_TXT.resrec.rdata->MaxRDLength) return(mStatus_BadParamErr);
13393         mDNSPlatformMemCopy(sr->RR_TXT.resrec.rdata->u.txt.c, txtinfo, txtlen);
13394     }
13395     sr->RR_TXT.DependentOn = &sr->RR_SRV;
13396 
13397     mDNS_Lock(m);
13398     // It is important that we register SRV first. uDNS assumes that SRV is registered first so
13399     // that if the SRV cannot find a target, rest of the records that belong to this service
13400     // will not be activated.
13401     err = mDNS_Register_internal(m, &sr->RR_SRV);
13402     // If we can't register the SRV record due to errors, bail out. It has not been inserted in
13403     // any list and hence no need to deregister. We could probably do similar checks for other
13404     // records below and bail out. For now, this seems to be sufficient to address rdar://9304275
13405     if (err)
13406     {
13407         mDNS_Unlock(m);
13408         return err;
13409     }
13410     if (!err) err = mDNS_Register_internal(m, &sr->RR_TXT);
13411     // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
13412     // mDNS_StartExit, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
13413     // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
13414     // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
13415     // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
13416     if (!err) err = mDNS_Register_internal(m, &sr->RR_ADV);
13417     for (i=0; i<NumSubTypes; i++) if (!err) err = mDNS_Register_internal(m, &sr->SubTypes[i]);
13418     if (!err) err = mDNS_Register_internal(m, &sr->RR_PTR);
13419 
13420     mDNS_Unlock(m);
13421 
13422     if (err) mDNS_DeregisterService(m, sr);
13423     return(err);
13424 }
13425 
13426 mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr,
13427                                            ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl,  mDNSu32 flags)
13428 {
13429     ExtraResourceRecord **e;
13430     mStatus status;
13431     AuthRecType artype;
13432     mDNSInterfaceID InterfaceID = sr->RR_PTR.resrec.InterfaceID;
13433 
13434     artype = setAuthRecType(InterfaceID, flags);
13435 
13436     extra->next = mDNSNULL;
13437     mDNS_SetupResourceRecord(&extra->r, rdata, sr->RR_PTR.resrec.InterfaceID,
13438                              extra->r.resrec.rrtype, ttl, kDNSRecordTypeUnique, artype, ServiceCallback, sr);
13439     AssignDomainName(&extra->r.namestorage, sr->RR_SRV.resrec.name);
13440 
13441     mDNS_Lock(m);
13442     e = &sr->Extras;
13443     while (*e) e = &(*e)->next;
13444 
13445     extra->r.DependentOn = &sr->RR_SRV;
13446 
13447     debugf("mDNS_AddRecordToService adding record to %##s %s %d",
13448            extra->r.resrec.name->c, DNSTypeName(extra->r.resrec.rrtype), extra->r.resrec.rdlength);
13449 
13450     status = mDNS_Register_internal(m, &extra->r);
13451     if (status == mStatus_NoError) *e = extra;
13452 
13453     mDNS_Unlock(m);
13454     return(status);
13455 }
13456 
13457 mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra,
13458                                                 mDNSRecordCallback MemFreeCallback, void *Context)
13459 {
13460     ExtraResourceRecord **e;
13461     mStatus status;
13462 
13463     mDNS_Lock(m);
13464     e = &sr->Extras;
13465     while (*e && *e != extra) e = &(*e)->next;
13466     if (!*e)
13467     {
13468         debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.resrec.name->c);
13469         status = mStatus_BadReferenceErr;
13470     }
13471     else
13472     {
13473         debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.resrec.name->c);
13474         extra->r.RecordCallback = MemFreeCallback;
13475         extra->r.RecordContext  = Context;
13476         *e = (*e)->next;
13477         status = mDNS_Deregister_internal(m, &extra->r, mDNS_Dereg_normal);
13478     }
13479     mDNS_Unlock(m);
13480     return(status);
13481 }
13482 
13483 mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname)
13484 {
13485     // Note: Don't need to use mDNS_Lock(m) here, because this code is just using public routines
13486     // mDNS_RegisterService() and mDNS_AddRecordToService(), which do the right locking internally.
13487     domainlabel name1, name2;
13488     domainname type, domain;
13489     const domainname *host = sr->RR_SRV.AutoTarget ? mDNSNULL : &sr->RR_SRV.resrec.rdata->u.srv.target;
13490     ExtraResourceRecord *extras = sr->Extras;
13491     mStatus err;
13492 
13493     DeconstructServiceName(sr->RR_SRV.resrec.name, &name1, &type, &domain);
13494     if (!newname)
13495     {
13496         name2 = name1;
13497         IncrementLabelSuffix(&name2, mDNStrue);
13498         newname = &name2;
13499     }
13500 
13501     if (SameDomainName(&domain, &localdomain))
13502         debugf("%##s service renamed from \"%#s\" to \"%#s\"", type.c, name1.c, newname->c);
13503     else debugf("%##s service (domain %##s) renamed from \"%#s\" to \"%#s\"",type.c, domain.c, name1.c, newname->c);
13504 
13505     err = mDNS_RegisterService(m, sr, newname, &type, &domain,
13506                                host, sr->RR_SRV.resrec.rdata->u.srv.port, sr->RR_TXT.resrec.rdata->u.txt.c, sr->RR_TXT.resrec.rdlength,
13507                                sr->SubTypes, sr->NumSubTypes,
13508                                sr->RR_PTR.resrec.InterfaceID, sr->ServiceCallback, sr->ServiceContext, sr->flags);
13509 
13510     // mDNS_RegisterService() just reset sr->Extras to NULL.
13511     // Fortunately we already grabbed ourselves a copy of this pointer (above), so we can now run
13512     // through the old list of extra records, and re-add them to our freshly created service registration
13513     while (!err && extras)
13514     {
13515         ExtraResourceRecord *e = extras;
13516         extras = extras->next;
13517         err = mDNS_AddRecordToService(m, sr, e, e->r.resrec.rdata, e->r.resrec.rroriginalttl, 0);
13518     }
13519 
13520     return(err);
13521 }
13522 
13523 // Note: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
13524 // which may change the record list and/or question list.
13525 // Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
13526 mDNSexport mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt)
13527 {
13528     // If port number is zero, that means this was actually registered using mDNS_RegisterNoSuchService()
13529     if (mDNSIPPortIsZero(sr->RR_SRV.resrec.rdata->u.srv.port)) return(mDNS_DeregisterNoSuchService(m, &sr->RR_SRV));
13530 
13531     if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeUnregistered)
13532     {
13533         debugf("Service set for %##s already deregistered", sr->RR_SRV.resrec.name->c);
13534         return(mStatus_BadReferenceErr);
13535     }
13536     else if (sr->RR_PTR.resrec.RecordType == kDNSRecordTypeDeregistering)
13537     {
13538         LogInfo("Service set for %##s already in the process of deregistering", sr->RR_SRV.resrec.name->c);
13539         // Avoid race condition:
13540         // If a service gets a conflict, then we set the Conflict flag to tell us to generate
13541         // an mStatus_NameConflict message when we get the mStatus_MemFree for our PTR record.
13542         // If the client happens to deregister the service in the middle of that process, then
13543         // we clear the flag back to the normal state, so that we deliver a plain mStatus_MemFree
13544         // instead of incorrectly promoting it to mStatus_NameConflict.
13545         // This race condition is exposed particularly when the conformance test generates
13546         // a whole batch of simultaneous conflicts across a range of services all advertised
13547         // using the same system default name, and if we don't take this precaution then
13548         // we end up incrementing m->nicelabel multiple times instead of just once.
13549         // <rdar://problem/4060169> Bug when auto-renaming Computer Name after name collision
13550         sr->Conflict = mDNSfalse;
13551         return(mStatus_NoError);
13552     }
13553     else
13554     {
13555         mDNSu32 i;
13556         mStatus status;
13557         ExtraResourceRecord *e;
13558         mDNS_Lock(m);
13559         e = sr->Extras;
13560 
13561         // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of the
13562         // SRV, TXT, or Extra records could have already been automatically deregistered, and that's okay
13563         mDNS_Deregister_internal(m, &sr->RR_SRV, mDNS_Dereg_repeat);
13564         mDNS_Deregister_internal(m, &sr->RR_TXT, mDNS_Dereg_repeat);
13565 
13566         mDNS_Deregister_internal(m, &sr->RR_ADV, drt);
13567 
13568         // We deregister all of the extra records, but we leave the sr->Extras list intact
13569         // in case the client wants to do a RenameAndReregister and reinstate the registration
13570         while (e)
13571         {
13572             mDNS_Deregister_internal(m, &e->r, mDNS_Dereg_repeat);
13573             e = e->next;
13574         }
13575 
13576         for (i=0; i<sr->NumSubTypes; i++)
13577             mDNS_Deregister_internal(m, &sr->SubTypes[i], drt);
13578 
13579         status = mDNS_Deregister_internal(m, &sr->RR_PTR, drt);
13580         mDNS_Unlock(m);
13581         return(status);
13582     }
13583 }
13584 
13585 // Create a registration that asserts that no such service exists with this name.
13586 // This can be useful where there is a given function is available through several protocols.
13587 // For example, a printer called "Stuart's Printer" may implement printing via the "pdl-datastream" and "IPP"
13588 // protocols, but not via "LPR". In this case it would be prudent for the printer to assert the non-existence of an
13589 // "LPR" service called "Stuart's Printer". Without this precaution, another printer than offers only "LPR" printing
13590 // could inadvertently advertise its service under the same name "Stuart's Printer", which might be confusing for users.
13591 mDNSexport mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
13592                                               const domainlabel *const name, const domainname *const type, const domainname *const domain,
13593                                               const domainname *const host,
13594                                               const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSu32 flags)
13595 {
13596     AuthRecType artype;
13597 
13598     artype = setAuthRecType(InterfaceID, flags);
13599 
13600     mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_SRV, kHostNameTTL, kDNSRecordTypeUnique, artype, Callback, Context);
13601     if (ConstructServiceName(&rr->namestorage, name, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
13602     rr->resrec.rdata->u.srv.priority    = 0;
13603     rr->resrec.rdata->u.srv.weight      = 0;
13604     rr->resrec.rdata->u.srv.port        = zeroIPPort;
13605     if (host && host->c[0]) AssignDomainName(&rr->resrec.rdata->u.srv.target, host);
13606     else rr->AutoTarget = Target_AutoHost;
13607     return(mDNS_Register(m, rr));
13608 }
13609 
13610 mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr,
13611                                          mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname)
13612 {
13613     AuthRecType artype;
13614 
13615     if (InterfaceID == mDNSInterface_LocalOnly)
13616         artype = AuthRecordLocalOnly;
13617     else if (InterfaceID == mDNSInterface_P2P)
13618         artype = AuthRecordP2P;
13619     else
13620         artype = AuthRecordAny;
13621     mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceID, kDNSType_PTR, kStandardTTL, kDNSRecordTypeShared, artype, mDNSNULL, mDNSNULL);
13622     if (!MakeDomainNameFromDNSNameString(&rr->namestorage, mDNS_DomainTypeNames[DomainType])) return(mStatus_BadParamErr);
13623     if (!MakeDomainNameFromDNSNameString(&rr->resrec.rdata->u.name, domname)) return(mStatus_BadParamErr);
13624     return(mDNS_Register(m, rr));
13625 }
13626 
13627 mDNSlocal mDNSBool mDNS_IdUsedInResourceRecordsList(mDNS * const m, mDNSOpaque16 id)
13628 {
13629     AuthRecord *r;
13630     for (r = m->ResourceRecords; r; r=r->next) if (mDNSSameOpaque16(id, r->updateid)) return mDNStrue;
13631     return mDNSfalse;
13632 }
13633 
13634 mDNSlocal mDNSBool mDNS_IdUsedInQuestionsList(mDNS * const m, mDNSOpaque16 id)
13635 {
13636     DNSQuestion *q;
13637     for (q = m->Questions; q; q=q->next) if (mDNSSameOpaque16(id, q->TargetQID)) return mDNStrue;
13638     return mDNSfalse;
13639 }
13640 
13641 mDNSexport mDNSOpaque16 mDNS_NewMessageID(mDNS * const m)
13642 {
13643     mDNSOpaque16 id;
13644     int i;
13645 
13646     for (i=0; i<10; i++)
13647     {
13648         id = mDNSOpaque16fromIntVal(1 + (mDNSu16)mDNSRandom(0xFFFE));
13649         if (!mDNS_IdUsedInResourceRecordsList(m, id) && !mDNS_IdUsedInQuestionsList(m, id)) break;
13650     }
13651 
13652     debugf("mDNS_NewMessageID: %5d", mDNSVal16(id));
13653 
13654     return id;
13655 }
13656 
13657 // ***************************************************************************
13658 #if COMPILER_LIKES_PRAGMA_MARK
13659 #pragma mark -
13660 #pragma mark - Sleep Proxy Server
13661 #endif
13662 
13663 mDNSlocal void RestartARPProbing(mDNS *const m, AuthRecord *const rr)
13664 {
13665     // If we see an ARP from a machine we think is sleeping, then either
13666     // (i) the machine has woken, or
13667     // (ii) it's just a stray old packet from before the machine slept
13668     // To handle the second case, we reset ProbeCount, so we'll suppress our own answers for a while, to avoid
13669     // generating ARP conflicts with a waking machine, and set rr->LastAPTime so we'll start probing again in 10 seconds.
13670     // If the machine has just woken then we'll discard our records when we see the first new mDNS probe from that machine.
13671     // 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*
13672     // need to send new ARP Announcements, because the owner's ARP broadcasts will have updated neighboring ARP caches, so we need to
13673     // re-assert our (temporary) ownership of that IP address in order to receive subsequent packets addressed to that IPv4 address.
13674 
13675     rr->resrec.RecordType = kDNSRecordTypeUnique;
13676     rr->ProbeCount        = DefaultProbeCountForTypeUnique;
13677     rr->ProbeRestartCount++;
13678 
13679     // If we haven't started announcing yet (and we're not already in ten-second-delay mode) the machine is probably
13680     // still going to sleep, so we just reset rr->ProbeCount so we'll continue probing until it stops responding.
13681     // If we *have* started announcing, the machine is probably in the process of waking back up, so in that case
13682     // we're more cautious and we wait ten seconds before probing it again. We do this because while waking from
13683     // sleep, some network interfaces tend to lose or delay inbound packets, and without this delay, if the waking machine
13684     // didn't answer our three probes within three seconds then we'd announce and cause it an unnecessary address conflict.
13685     if (rr->AnnounceCount == InitialAnnounceCount && m->timenow - rr->LastAPTime >= 0)
13686         InitializeLastAPTime(m, rr);
13687     else
13688     {
13689         rr->AnnounceCount  = InitialAnnounceCount;
13690         rr->ThisAPInterval = mDNSPlatformOneSecond;
13691         rr->LastAPTime     = m->timenow + mDNSPlatformOneSecond * 9;    // Send first packet at rr->LastAPTime + rr->ThisAPInterval, i.e. 10 seconds from now
13692         SetNextAnnounceProbeTime(m, rr);
13693     }
13694 }
13695 
13696 mDNSlocal void mDNSCoreReceiveRawARP(mDNS *const m, const ARP_EthIP *const arp, const mDNSInterfaceID InterfaceID)
13697 {
13698     static const mDNSOpaque16 ARP_op_request = { { 0, 1 } };
13699     AuthRecord *rr;
13700     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13701     if (!intf) return;
13702 
13703     mDNS_Lock(m);
13704 
13705     // Pass 1:
13706     // Process ARP Requests and Probes (but not Announcements), and generate an ARP Reply if necessary.
13707     // We also process ARPs from our own kernel (and 'answer' them by injecting a local ARP table entry)
13708     // We ignore ARP Announcements here -- Announcements are not questions, they're assertions, so we don't need to answer them.
13709     // The times we might need to react to an ARP Announcement are:
13710     // (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
13711     // (ii) if it's a conflicting Announcement from another host
13712     // -- and we check for these in Pass 2 below.
13713     if (mDNSSameOpaque16(arp->op, ARP_op_request) && !mDNSSameIPv4Address(arp->spa, arp->tpa))
13714     {
13715         for (rr = m->ResourceRecords; rr; rr=rr->next)
13716             if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13717                 rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->tpa))
13718             {
13719                 static const char msg1[] = "ARP Req from owner -- re-probing";
13720                 static const char msg2[] = "Ignoring  ARP Request from      ";
13721                 static const char msg3[] = "Creating Local ARP Cache entry  ";
13722                 static const char msg4[] = "Answering ARP Request from      ";
13723                 const char *const msg = mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC) ? msg1 :
13724                                         (rr->AnnounceCount == InitialAnnounceCount)     ? msg2 :
13725                                         mDNSSameEthAddress(&arp->sha, &intf->MAC)       ? msg3 : msg4;
13726                 LogSPS("%-7s %s %.6a %.4a for %.4a -- H-MAC %.6a I-MAC %.6a %s",
13727                        intf->ifname, msg, &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13728                 if (msg == msg1)
13729                 {
13730                     if ( rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13731                         RestartARPProbing(m, rr);
13732                     else
13733                         LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13734                 }
13735                 else if (msg == msg3)
13736                 {
13737                     mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13738                 }
13739                 else if (msg == msg4)
13740                 {
13741                     SendARP(m, 2, rr, &arp->tpa, &arp->sha, &arp->spa, &arp->sha);
13742                 }
13743             }
13744     }
13745 
13746     // Pass 2:
13747     // 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.
13748     // (Strictly speaking we're only checking Announcement/Request/Reply packets, since ARP Probes have zero Sender IP address,
13749     // so by definition (and by design) they can never conflict with any real (i.e. non-zero) IP address).
13750     // 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.
13751     // If we see an apparently conflicting ARP, we check the sender hardware address:
13752     //   If the sender hardware address is the original owner this is benign, so we just suppress our own proxy answering for a while longer.
13753     //   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.
13754     if (mDNSSameEthAddress(&arp->sha, &intf->MAC))
13755         debugf("ARP from self for %.4a", &arp->tpa);
13756     else
13757     {
13758         if (!mDNSSameIPv4Address(arp->spa, zerov4Addr))
13759             for (rr = m->ResourceRecords; rr; rr=rr->next)
13760                 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13761                     rr->AddressProxy.type == mDNSAddrType_IPv4 && mDNSSameIPv4Address(rr->AddressProxy.ip.v4, arp->spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
13762                 {
13763                     if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
13764                     {
13765                         LogSPS("%-7s ARP from %.6a %.4a for %.4a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13766                                 &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13767                     }
13768                     else
13769                     {
13770                         RestartARPProbing(m, rr);
13771                         if (mDNSSameEthAddress(&arp->sha, &rr->WakeUp.IMAC))
13772                         {
13773                             LogSPS("%-7s ARP %s from owner %.6a %.4a for %-15.4a -- re-starting probing for %s", intf->ifname,
13774                                     mDNSSameIPv4Address(arp->spa, arp->tpa) ? "Announcement " : mDNSSameOpaque16(arp->op, ARP_op_request) ? "Request      " : "Response     ",
13775                                     &arp->sha, &arp->spa, &arp->tpa, ARDisplayString(m, rr));
13776                         }
13777                         else
13778                         {
13779                             LogMsg("%-7s Conflicting ARP from %.6a %.4a for %.4a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13780                                     &arp->sha, &arp->spa, &arp->tpa, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13781                             ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
13782                         }
13783                     }
13784                 }
13785     }
13786 
13787     mDNS_Unlock(m);
13788 }
13789 
13790 /*
13791    // Option 1 is Source Link Layer Address Option
13792    // Option 2 is Target Link Layer Address Option
13793    mDNSlocal const mDNSEthAddr *GetLinkLayerAddressOption(const IPv6NDP *const ndp, const mDNSu8 *const end, mDNSu8 op)
13794     {
13795     const mDNSu8 *options = (mDNSu8 *)(ndp+1);
13796     while (options < end)
13797         {
13798         debugf("NDP Option %02X len %2d %d", options[0], options[1], end - options);
13799         if (options[0] == op && options[1] == 1) return (const mDNSEthAddr*)(options+2);
13800         options += options[1] * 8;
13801         }
13802     return mDNSNULL;
13803     }
13804  */
13805 
13806 mDNSlocal void mDNSCoreReceiveRawND(mDNS *const m, const mDNSEthAddr *const sha, const mDNSv6Addr *spa,
13807                                     const IPv6NDP *const ndp, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
13808 {
13809     AuthRecord *rr;
13810     NetworkInterfaceInfo *intf = FirstInterfaceForID(m, InterfaceID);
13811     if (!intf) return;
13812 
13813     mDNS_Lock(m);
13814 
13815     // Pass 1: Process Neighbor Solicitations, and generate a Neighbor Advertisement if necessary.
13816     if (ndp->type == NDP_Sol)
13817     {
13818         //const mDNSEthAddr *const sha = GetLinkLayerAddressOption(ndp, end, NDP_SrcLL);
13819         (void)end;
13820         for (rr = m->ResourceRecords; rr; rr=rr->next)
13821             if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13822                 rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, ndp->target))
13823             {
13824                 static const char msg1[] = "NDP Req from owner -- re-probing";
13825                 static const char msg2[] = "Ignoring  NDP Request from      ";
13826                 static const char msg3[] = "Creating Local NDP Cache entry  ";
13827                 static const char msg4[] = "Answering NDP Request from      ";
13828                 static const char msg5[] = "Answering NDP Probe   from      ";
13829                 const char *const msg = sha && mDNSSameEthAddress(sha, &rr->WakeUp.IMAC) ? msg1 :
13830                                         (rr->AnnounceCount == InitialAnnounceCount)      ? msg2 :
13831                                         sha && mDNSSameEthAddress(sha, &intf->MAC)       ? msg3 :
13832                                         spa && mDNSIPv6AddressIsZero(*spa)               ? msg4 : msg5;
13833                 LogSPS("%-7s %s %.6a %.16a for %.16a -- H-MAC %.6a I-MAC %.6a %s",
13834                        intf->ifname, msg, sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13835                 if (msg == msg1)
13836                 {
13837                     if (rr->ProbeRestartCount < MAX_PROBE_RESTARTS)
13838                         RestartARPProbing(m, rr);
13839                     else
13840                         LogSPS("Reached maximum number of restarts for probing - %s", ARDisplayString(m,rr));
13841                 }
13842                 else if (msg == msg3)
13843                     mDNSPlatformSetLocalAddressCacheEntry(m, &rr->AddressProxy, &rr->WakeUp.IMAC, InterfaceID);
13844                 else if (msg == msg4)
13845                     SendNDP(m, NDP_Adv, NDP_Solicited, rr, &ndp->target, mDNSNULL, spa, sha);
13846                 else if (msg == msg5)
13847                     SendNDP(m, NDP_Adv, 0, rr, &ndp->target, mDNSNULL, &AllHosts_v6, &AllHosts_v6_Eth);
13848             }
13849     }
13850 
13851     // 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.
13852     if (mDNSSameEthAddress(sha, &intf->MAC))
13853         debugf("NDP from self for %.16a", &ndp->target);
13854     else
13855     {
13856         // For Neighbor Advertisements we check the Target address field, not the actual IPv6 source address.
13857         // When a machine has both link-local and routable IPv6 addresses, it may send NDP packets making assertions
13858         // about its routable IPv6 address, using its link-local address as the source address for all NDP packets.
13859         // Hence it is the NDP target address we care about, not the actual packet source address.
13860         if (ndp->type == NDP_Adv) spa = &ndp->target;
13861         if (!mDNSSameIPv6Address(*spa, zerov6Addr))
13862             for (rr = m->ResourceRecords; rr; rr=rr->next)
13863                 if (rr->resrec.InterfaceID == InterfaceID && rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
13864                     rr->AddressProxy.type == mDNSAddrType_IPv6 && mDNSSameIPv6Address(rr->AddressProxy.ip.v6, *spa) && (rr->ProbeRestartCount < MAX_PROBE_RESTARTS))
13865                 {
13866                     if (mDNSSameEthAddress(&zeroEthAddr, &rr->WakeUp.HMAC))
13867                     {
13868                         LogSPS("%-7s NDP from %.6a %.16a for %.16a -- Invalid H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13869                                     sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13870                     }
13871                     else
13872                     {
13873                         RestartARPProbing(m, rr);
13874                         if (mDNSSameEthAddress(sha, &rr->WakeUp.IMAC))
13875                         {
13876                             LogSPS("%-7s NDP %s from owner %.6a %.16a for %.16a -- re-starting probing for %s", intf->ifname,
13877                                     ndp->type == NDP_Sol ? "Solicitation " : "Advertisement", sha, spa, &ndp->target, ARDisplayString(m, rr));
13878                         }
13879                         else
13880                         {
13881                             LogMsg("%-7s Conflicting NDP from %.6a %.16a for %.16a -- waking H-MAC %.6a I-MAC %.6a %s", intf->ifname,
13882                                     sha, spa, &ndp->target, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, rr));
13883                             ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
13884                         }
13885                     }
13886                 }
13887     }
13888 
13889     mDNS_Unlock(m);
13890 }
13891 
13892 mDNSlocal void mDNSCoreReceiveRawTransportPacket(mDNS *const m, const mDNSEthAddr *const sha, const mDNSAddr *const src, const mDNSAddr *const dst, const mDNSu8 protocol,
13893                                                  const mDNSu8 *const p, const TransportLayerPacket *const t, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID, const mDNSu16 len)
13894 {
13895     const mDNSIPPort port = (protocol == 0x06) ? t->tcp.dst : (protocol == 0x11) ? t->udp.dst : zeroIPPort;
13896     mDNSBool wake = mDNSfalse;
13897     mDNSBool kaWake = mDNSfalse;
13898 
13899     switch (protocol)
13900     {
13901         #define XX wake ? "Received" : "Ignoring", end-p
13902     case 0x01:  LogSPS("Ignoring %d-byte ICMP from %#a to %#a", end-p, src, dst);
13903         break;
13904 
13905     case 0x06:  {
13906         AuthRecord *kr;
13907         mDNSu32 seq, ack;
13908                     #define TH_FIN  0x01
13909                     #define TH_SYN  0x02
13910                     #define TH_RST  0x04
13911                     #define TH_ACK  0x10
13912 
13913         kr = mDNS_MatchKeepaliveInfo(m, dst, src, port, t->tcp.src, &seq, &ack);
13914         if (kr)
13915         {
13916             LogSPS("mDNSCoreReceiveRawTransportPacket: Found a Keepalive record from %#a:%d  to %#a:%d", src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port));
13917             // Plan to wake if
13918             // (a) RST or FIN is set (the keepalive that we sent could have caused a reset)
13919             // (b) packet that contains new data and acks a sequence number higher than the one
13920             //     we have been sending in the keepalive
13921 
13922             wake = ((t->tcp.flags & TH_RST) || (t->tcp.flags & TH_FIN)) ;
13923             if (!wake)
13924             {
13925                 mDNSu8 *ptr;
13926                 mDNSu32 pseq, pack;
13927                 mDNSBool data = mDNSfalse;
13928                 mDNSu8 tcphlen;
13929 
13930                 // Convert to host order
13931                 ptr = (mDNSu8 *)&seq;
13932                 seq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
13933 
13934                 ptr = (mDNSu8 *)&ack;
13935                 ack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
13936 
13937                 pseq = t->tcp.seq;
13938                 ptr = (mDNSu8 *)&pseq;
13939                 pseq = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
13940 
13941                 pack = t->tcp.ack;
13942                 ptr = (mDNSu8 *)&pack;
13943                 pack = ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
13944 
13945                 // If the other side is acking one more than our sequence number (keepalive is one
13946                 // less than the last valid sequence sent) and it's sequence is more than what we
13947                 // acked before
13948                 //if (end - p - 34  - ((t->tcp.offset >> 4) * 4) > 0) data = mDNStrue;
13949                 tcphlen = ((t->tcp.offset >> 4) * 4);
13950                 if (end - ((mDNSu8 *)t + tcphlen) > 0) data = mDNStrue;
13951                 wake = ((int)(pack - seq) > 0) && ((int)(pseq - ack) >= 0) && data;
13952 
13953                 // If we got a regular keepalive on a connection that was registed with the KeepAlive API, respond with an ACK
13954                 if ((t->tcp.flags & TH_ACK) && (data == mDNSfalse) &&
13955                     ((int)(ack - pseq) == 1))
13956                 {
13957                     // Send an ACK;
13958                     mDNS_SendKeepaliveACK(m, kr);
13959                 }
13960                 LogSPS("mDNSCoreReceiveRawTransportPacket: End %p, hlen %d, Datalen %d, pack %u, seq %u, pseq %u, ack %u, wake %d",
13961                        end, tcphlen, end - ((mDNSu8 *)t + tcphlen), pack, seq, pseq, ack, wake);
13962             }
13963             else { LogSPS("mDNSCoreReceiveRawTransportPacket: waking because of RST or FIN th_flags %d", t->tcp.flags); }
13964             kaWake = wake;
13965         }
13966         else
13967         {
13968             // Plan to wake if
13969             // (a) RST is not set, AND
13970             // (b) packet is SYN, SYN+FIN, or plain data packet (no SYN or FIN). We won't wake for FIN alone.
13971             wake = (!(t->tcp.flags & TH_RST) && (t->tcp.flags & (TH_FIN|TH_SYN)) != TH_FIN);
13972 
13973             // For now, to reduce spurious wakeups, we wake only for TCP SYN,
13974             // except for ssh connections, where we'll wake for plain data packets too
13975             if  (!mDNSSameIPPort(port, SSHPort) && !(t->tcp.flags & 2)) wake = mDNSfalse;
13976 
13977             LogSPS("%s %d-byte TCP from %#a:%d to %#a:%d%s%s%s", XX,
13978                    src, mDNSVal16(t->tcp.src), dst, mDNSVal16(port),
13979                    (t->tcp.flags & 2) ? " SYN" : "",
13980                    (t->tcp.flags & 1) ? " FIN" : "",
13981                    (t->tcp.flags & 4) ? " RST" : "");
13982         }
13983         break;
13984     }
13985 
13986     case 0x11:  {
13987                     #define ARD_AsNumber 3283
13988         static const mDNSIPPort ARD = { { ARD_AsNumber >> 8, ARD_AsNumber & 0xFF } };
13989         const mDNSu16 udplen = (mDNSu16)((mDNSu16)t->bytes[4] << 8 | t->bytes[5]);                  // Length *including* 8-byte UDP header
13990         if (udplen >= sizeof(UDPHeader))
13991         {
13992             const mDNSu16 datalen = udplen - sizeof(UDPHeader);
13993             wake = mDNStrue;
13994 
13995             // For Back to My Mac UDP port 4500 (IPSEC) packets, we do some special handling
13996             if (mDNSSameIPPort(port, IPSECPort))
13997             {
13998                 // Specifically ignore NAT keepalive packets
13999                 if (datalen == 1 && end >= &t->bytes[9] && t->bytes[8] == 0xFF) wake = mDNSfalse;
14000                 else
14001                 {
14002                     // Skip over the Non-ESP Marker if present
14003                     const mDNSBool NonESP = (end >= &t->bytes[12] && t->bytes[8] == 0 && t->bytes[9] == 0 && t->bytes[10] == 0 && t->bytes[11] == 0);
14004                     const IKEHeader *const ike    = (IKEHeader *)(t + (NonESP ? 12 : 8));
14005                     const mDNSu16 ikelen = datalen - (NonESP ? 4 : 0);
14006                     if (ikelen >= sizeof(IKEHeader) && end >= ((mDNSu8 *)ike) + sizeof(IKEHeader))
14007                         if ((ike->Version & 0x10) == 0x10)
14008                         {
14009                             // ExchangeType ==  5 means 'Informational' <http://www.ietf.org/rfc/rfc2408.txt>
14010                             // ExchangeType == 34 means 'IKE_SA_INIT'   <http://www.iana.org/assignments/ikev2-parameters>
14011                             if (ike->ExchangeType == 5 || ike->ExchangeType == 34) wake = mDNSfalse;
14012                             LogSPS("%s %d-byte IKE ExchangeType %d", XX, ike->ExchangeType);
14013                         }
14014                 }
14015             }
14016 
14017             // For now, because we haven't yet worked out a clean elegant way to do this, we just special-case the
14018             // Apple Remote Desktop port number -- we ignore all packets to UDP 3283 (the "Net Assistant" port),
14019             // except for Apple Remote Desktop's explicit manual wakeup packet, which looks like this:
14020             // UDP header (8 bytes)
14021             // Payload: 13 88 00 6a 41 4e 41 20 (8 bytes) ffffffffffff (6 bytes) 16xMAC (96 bytes) = 110 bytes total
14022             if (mDNSSameIPPort(port, ARD)) wake = (datalen >= 110 && end >= &t->bytes[10] && t->bytes[8] == 0x13 && t->bytes[9] == 0x88);
14023 
14024             LogSPS("%s %d-byte UDP from %#a:%d to %#a:%d", XX, src, mDNSVal16(t->udp.src), dst, mDNSVal16(port));
14025         }
14026     }
14027     break;
14028 
14029     case 0x3A:  if (&t->bytes[len] <= end)
14030         {
14031             mDNSu16 checksum = IPv6CheckSum(&src->ip.v6, &dst->ip.v6, protocol, t->bytes, len);
14032             if (!checksum) mDNSCoreReceiveRawND(m, sha, &src->ip.v6, &t->ndp, &t->bytes[len], InterfaceID);
14033             else LogInfo("IPv6CheckSum bad %04X %02X%02X from %#a to %#a", checksum, t->bytes[2], t->bytes[3], src, dst);
14034         }
14035         break;
14036 
14037     default:    LogSPS("Ignoring %d-byte IP packet unknown protocol %d from %#a to %#a", end-p, protocol, src, dst);
14038         break;
14039     }
14040 
14041     if (wake)
14042     {
14043         AuthRecord *rr, *r2;
14044 
14045         mDNS_Lock(m);
14046         for (rr = m->ResourceRecords; rr; rr=rr->next)
14047             if (rr->resrec.InterfaceID == InterfaceID &&
14048                 rr->resrec.RecordType != kDNSRecordTypeDeregistering &&
14049                 rr->AddressProxy.type && mDNSSameAddress(&rr->AddressProxy, dst))
14050             {
14051                 const mDNSu8 *const tp = (protocol == 6) ? (const mDNSu8 *)"\x4_tcp" : (const mDNSu8 *)"\x4_udp";
14052                 for (r2 = m->ResourceRecords; r2; r2=r2->next)
14053                     if (r2->resrec.InterfaceID == InterfaceID && mDNSSameEthAddress(&r2->WakeUp.HMAC, &rr->WakeUp.HMAC) &&
14054                         r2->resrec.RecordType != kDNSRecordTypeDeregistering &&
14055                         r2->resrec.rrtype == kDNSType_SRV && mDNSSameIPPort(r2->resrec.rdata->u.srv.port, port) &&
14056                         SameDomainLabel(ThirdLabel(r2->resrec.name)->c, tp))
14057                         break;
14058                 if (!r2 && mDNSSameIPPort(port, IPSECPort)) r2 = rr;    // So that we wake for BTMM IPSEC packets, even without a matching SRV record
14059                 if (!r2 && kaWake) r2 = rr;                             // So that we wake for keepalive packets, even without a matching SRV record
14060                 if (r2)
14061                 {
14062                     LogMsg("Waking host at %s %#a H-MAC %.6a I-MAC %.6a for %s",
14063                            InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, &rr->WakeUp.IMAC, ARDisplayString(m, r2));
14064                     ScheduleWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.HMAC);
14065                 }
14066                 else
14067                     LogSPS("Sleeping host at %s %#a %.6a has no service on %#s %d",
14068                            InterfaceNameForID(m, rr->resrec.InterfaceID), dst, &rr->WakeUp.HMAC, tp, mDNSVal16(port));
14069             }
14070         mDNS_Unlock(m);
14071     }
14072 }
14073 
14074 mDNSexport void mDNSCoreReceiveRawPacket(mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID)
14075 {
14076     static const mDNSOpaque16 Ethertype_ARP  = { { 0x08, 0x06 } };  // Ethertype 0x0806 = ARP
14077     static const mDNSOpaque16 Ethertype_IPv4 = { { 0x08, 0x00 } };  // Ethertype 0x0800 = IPv4
14078     static const mDNSOpaque16 Ethertype_IPv6 = { { 0x86, 0xDD } };  // Ethertype 0x86DD = IPv6
14079     static const mDNSOpaque16 ARP_hrd_eth    = { { 0x00, 0x01 } };  // Hardware address space (Ethernet = 1)
14080     static const mDNSOpaque16 ARP_pro_ip     = { { 0x08, 0x00 } };  // Protocol address space (IP = 0x0800)
14081 
14082     // Note: BPF guarantees that the NETWORK LAYER header will be word aligned, not the link-layer header.
14083     // In other words, we can safely assume that pkt below (ARP, IPv4 or IPv6) is properly word aligned,
14084     // but if pkt is 4-byte aligned, that necessarily means that eth CANNOT also be 4-byte aligned
14085     // since it points to a an address 14 bytes before pkt.
14086     const EthernetHeader     *const eth = (const EthernetHeader *)p;
14087     const NetworkLayerPacket *const pkt = (const NetworkLayerPacket *)(eth+1);
14088     mDNSAddr src, dst;
14089     #define RequiredCapLen(P) ((P)==0x01 ? 4 : (P)==0x06 ? 20 : (P)==0x11 ? 8 : (P)==0x3A ? 24 : 0)
14090 
14091     // Is ARP? Length must be at least 14 + 28 = 42 bytes
14092     if (end >= p+42 && mDNSSameOpaque16(eth->ethertype, Ethertype_ARP) && mDNSSameOpaque16(pkt->arp.hrd, ARP_hrd_eth) && mDNSSameOpaque16(pkt->arp.pro, ARP_pro_ip))
14093         mDNSCoreReceiveRawARP(m, &pkt->arp, InterfaceID);
14094     // Is IPv4 with zero fragmentation offset? Length must be at least 14 + 20 = 34 bytes
14095     else if (end >= p+34 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv4) && (pkt->v4.flagsfrags.b[0] & 0x1F) == 0 && pkt->v4.flagsfrags.b[1] == 0)
14096     {
14097         const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
14098         const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen);
14099         if (transEnd > end) transEnd = end;
14100         debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
14101         src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
14102         dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
14103         if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol))
14104             mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0);
14105     }
14106     // Is IPv6? Length must be at least 14 + 28 = 42 bytes
14107     else if (end >= p+54 && mDNSSameOpaque16(eth->ethertype, Ethertype_IPv6))
14108     {
14109         const mDNSu8 *const trans = p + 54;
14110         debugf("Got IPv6  %02X from %.16a to %.16a", pkt->v6.pro, &pkt->v6.src, &pkt->v6.dst);
14111         src.type = mDNSAddrType_IPv6; src.ip.v6 = pkt->v6.src;
14112         dst.type = mDNSAddrType_IPv6; dst.ip.v6 = pkt->v6.dst;
14113         if (end >= trans + RequiredCapLen(pkt->v6.pro))
14114             mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v6.pro, p, (TransportLayerPacket*)trans, end, InterfaceID,
14115                                               (mDNSu16)pkt->bytes[4] << 8 | pkt->bytes[5]);
14116     }
14117 }
14118 
14119 mDNSlocal void ConstructSleepProxyServerName(mDNS *const m, domainlabel *name)
14120 {
14121     name->c[0] = (mDNSu8)mDNS_snprintf((char*)name->c+1, 62, "%d-%d-%d-%d.%d %#s",
14122                                        m->SPSType, m->SPSPortability, m->SPSMarginalPower, m->SPSTotalPower, m->SPSFeatureFlags, &m->nicelabel);
14123 }
14124 
14125 #ifndef SPC_DISABLED
14126 mDNSlocal void SleepProxyServerCallback(mDNS *const m, ServiceRecordSet *const srs, mStatus result)
14127 {
14128     if (result == mStatus_NameConflict)
14129         mDNS_RenameAndReregisterService(m, srs, mDNSNULL);
14130     else if (result == mStatus_MemFree)
14131     {
14132         if (m->SleepState)
14133             m->SPSState = 3;
14134         else
14135         {
14136             m->SPSState = (mDNSu8)(m->SPSSocket != mDNSNULL);
14137             if (m->SPSState)
14138             {
14139                 domainlabel name;
14140                 ConstructSleepProxyServerName(m, &name);
14141                 mDNS_RegisterService(m, srs,
14142                                      &name, &SleepProxyServiceType, &localdomain,
14143                                      mDNSNULL, m->SPSSocket->port, // Host, port
14144                                      (mDNSu8 *)"", 1,           // TXT data, length
14145                                      mDNSNULL, 0,               // Subtypes (none)
14146                                      mDNSInterface_Any,         // Interface ID
14147                                      SleepProxyServerCallback, mDNSNULL, 0); // Callback, context, flags
14148             }
14149             LogSPS("Sleep Proxy Server %#s %s", srs->RR_SRV.resrec.name->c, m->SPSState ? "started" : "stopped");
14150         }
14151     }
14152 }
14153 #endif
14154 
14155 // Called with lock held
14156 mDNSexport void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features)
14157 {
14158     // This routine uses mDNS_DeregisterService and calls SleepProxyServerCallback, so we execute in user callback context
14159     mDNS_DropLockBeforeCallback();
14160 
14161     // If turning off SPS, close our socket
14162     // (Do this first, BEFORE calling mDNS_DeregisterService below)
14163     if (!sps && m->SPSSocket) { mDNSPlatformUDPClose(m->SPSSocket); m->SPSSocket = mDNSNULL; }
14164 
14165     // If turning off, or changing type, deregister old name
14166 #ifndef SPC_DISABLED
14167     if (m->SPSState == 1 && sps != m->SPSType)
14168     { m->SPSState = 2; mDNS_DeregisterService_drt(m, &m->SPSRecords, sps ? mDNS_Dereg_rapid : mDNS_Dereg_normal); }
14169 #endif // SPC_DISABLED
14170 
14171     // Record our new SPS parameters
14172     m->SPSType          = sps;
14173     m->SPSPortability   = port;
14174     m->SPSMarginalPower = marginalpower;
14175     m->SPSTotalPower    = totpower;
14176     m->SPSFeatureFlags  = features;
14177     // If turning on, open socket and advertise service
14178     if (sps)
14179     {
14180         if (!m->SPSSocket)
14181         {
14182             m->SPSSocket = mDNSPlatformUDPSocket(m, zeroIPPort);
14183             if (!m->SPSSocket) { LogMsg("mDNSCoreBeSleepProxyServer: Failed to allocate SPSSocket"); goto fail; }
14184         }
14185 #ifndef SPC_DISABLED
14186         if (m->SPSState == 0) SleepProxyServerCallback(m, &m->SPSRecords, mStatus_MemFree);
14187 #endif // SPC_DISABLED
14188     }
14189     else if (m->SPSState)
14190     {
14191         LogSPS("mDNSCoreBeSleepProxyServer turning off from state %d; will wake clients", m->SPSState);
14192         m->NextScheduledSPS = m->timenow;
14193     }
14194 fail:
14195     mDNS_ReclaimLockAfterCallback();
14196 }
14197 
14198 // ***************************************************************************
14199 #if COMPILER_LIKES_PRAGMA_MARK
14200 #pragma mark -
14201 #pragma mark - Startup and Shutdown
14202 #endif
14203 
14204 mDNSlocal void mDNS_GrowCache_internal(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14205 {
14206     if (storage && numrecords)
14207     {
14208         mDNSu32 i;
14209         debugf("Adding cache storage for %d more records (%d bytes)", numrecords, numrecords*sizeof(CacheEntity));
14210         for (i=0; i<numrecords; i++) storage[i].next = &storage[i+1];
14211         storage[numrecords-1].next = m->rrcache_free;
14212         m->rrcache_free = storage;
14213         m->rrcache_size += numrecords;
14214     }
14215 }
14216 
14217 mDNSexport void mDNS_GrowCache(mDNS *const m, CacheEntity *storage, mDNSu32 numrecords)
14218 {
14219     mDNS_Lock(m);
14220     mDNS_GrowCache_internal(m, storage, numrecords);
14221     mDNS_Unlock(m);
14222 }
14223 
14224 mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
14225                              CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
14226                              mDNSBool AdvertiseLocalAddresses, mDNSCallback *Callback, void *Context)
14227 {
14228     mDNSu32 slot;
14229     mDNSs32 timenow;
14230     mStatus result;
14231 
14232     if (!rrcachestorage) rrcachesize = 0;
14233 
14234     m->p                             = p;
14235     m->NetworkChanged                = 0;
14236     m->CanReceiveUnicastOn5353       = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
14237     m->AdvertiseLocalAddresses       = AdvertiseLocalAddresses;
14238     m->DivertMulticastAdvertisements = mDNSfalse;
14239     m->mDNSPlatformStatus            = mStatus_Waiting;
14240     m->UnicastPort4                  = zeroIPPort;
14241     m->UnicastPort6                  = zeroIPPort;
14242     m->PrimaryMAC                    = zeroEthAddr;
14243     m->MainCallback                  = Callback;
14244     m->MainContext                   = Context;
14245     m->rec.r.resrec.RecordType       = 0;
14246     m->rec.r.resrec.AnonInfo         = mDNSNULL;
14247 
14248     // For debugging: To catch and report locking failures
14249     m->mDNS_busy               = 0;
14250     m->mDNS_reentrancy         = 0;
14251     m->ShutdownTime            = 0;
14252     m->lock_rrcache            = 0;
14253     m->lock_Questions          = 0;
14254     m->lock_Records            = 0;
14255 
14256     // Task Scheduling variables
14257     result = mDNSPlatformTimeInit();
14258     if (result != mStatus_NoError) return(result);
14259     m->timenow_adjust = (mDNSs32)mDNSRandom(0xFFFFFFFF);
14260     timenow = mDNS_TimeNow_NoLock(m);
14261 
14262     m->timenow                 = 0;     // MUST only be set within mDNS_Lock/mDNS_Unlock section
14263     m->timenow_last            = timenow;
14264     m->NextScheduledEvent      = timenow;
14265     m->SuppressSending         = timenow;
14266     m->NextCacheCheck          = timenow + 0x78000000;
14267     m->NextScheduledQuery      = timenow + 0x78000000;
14268     m->NextScheduledProbe      = timenow + 0x78000000;
14269     m->NextScheduledResponse   = timenow + 0x78000000;
14270     m->NextScheduledNATOp      = timenow + 0x78000000;
14271     m->NextScheduledSPS        = timenow + 0x78000000;
14272     m->NextScheduledKA         = timenow + 0x78000000;
14273     m->NextScheduledStopTime   = timenow + 0x78000000;
14274     m->RandomQueryDelay        = 0;
14275     m->RandomReconfirmDelay    = 0;
14276     m->PktNum                  = 0;
14277     m->MPktNum                 = 0;
14278     m->LocalRemoveEvents       = mDNSfalse;
14279     m->SleepState              = SleepState_Awake;
14280     m->SleepSeqNum             = 0;
14281     m->SystemWakeOnLANEnabled  = mDNSfalse;
14282     m->AnnounceOwner           = NonZeroTime(timenow + 60 * mDNSPlatformOneSecond);
14283     m->DelaySleep              = 0;
14284     m->SleepLimit              = 0;
14285 
14286 #if APPLE_OSX_mDNSResponder
14287     m->StatStartTime           = mDNSPlatformUTC();
14288     m->NextStatLogTime         = m->StatStartTime + kDefaultNextStatsticsLogTime;
14289     m->ActiveStatTime          = 0;
14290     m->UnicastPacketsSent      = 0;
14291     m->MulticastPacketsSent    = 0;
14292     m->RemoteSubnet            = 0;
14293 #endif // APPLE_OSX_mDNSResponder
14294 
14295     // These fields only required for mDNS Searcher...
14296     m->Questions               = mDNSNULL;
14297     m->NewQuestions            = mDNSNULL;
14298     m->CurrentQuestion         = mDNSNULL;
14299     m->LocalOnlyQuestions      = mDNSNULL;
14300     m->NewLocalOnlyQuestions   = mDNSNULL;
14301     m->RestartQuestion         = mDNSNULL;
14302     m->ValidationQuestion      = mDNSNULL;
14303     m->rrcache_size            = 0;
14304     m->rrcache_totalused       = 0;
14305     m->rrcache_active          = 0;
14306     m->rrcache_report          = 10;
14307     m->rrcache_free            = mDNSNULL;
14308 
14309     for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
14310     {
14311         m->rrcache_hash[slot]      = mDNSNULL;
14312         m->rrcache_nextcheck[slot] = timenow + 0x78000000;;
14313     }
14314 
14315     mDNS_GrowCache_internal(m, rrcachestorage, rrcachesize);
14316     m->rrauth.rrauth_free            = mDNSNULL;
14317 
14318     for (slot = 0; slot < AUTH_HASH_SLOTS; slot++)
14319         m->rrauth.rrauth_hash[slot] = mDNSNULL;
14320 
14321     // Fields below only required for mDNS Responder...
14322     m->hostlabel.c[0]          = 0;
14323     m->nicelabel.c[0]          = 0;
14324     m->MulticastHostname.c[0]  = 0;
14325     m->HIHardware.c[0]         = 0;
14326     m->HISoftware.c[0]         = 0;
14327     m->ResourceRecords         = mDNSNULL;
14328     m->DuplicateRecords        = mDNSNULL;
14329     m->NewLocalRecords         = mDNSNULL;
14330     m->NewLocalOnlyRecords     = mDNSfalse;
14331     m->CurrentRecord           = mDNSNULL;
14332     m->HostInterfaces          = mDNSNULL;
14333     m->ProbeFailTime           = 0;
14334     m->NumFailedProbes         = 0;
14335     m->SuppressProbes          = 0;
14336 
14337 #ifndef UNICAST_DISABLED
14338     m->NextuDNSEvent            = timenow + 0x78000000;
14339     m->NextSRVUpdate            = timenow + 0x78000000;
14340 
14341     m->DNSServers               = mDNSNULL;
14342 
14343     m->Router                   = zeroAddr;
14344     m->AdvertisedV4             = zeroAddr;
14345     m->AdvertisedV6             = zeroAddr;
14346 
14347     m->AuthInfoList             = mDNSNULL;
14348 
14349     m->ReverseMap.ThisQInterval = -1;
14350     m->StaticHostname.c[0]      = 0;
14351     m->FQDN.c[0]                = 0;
14352     m->Hostnames                = mDNSNULL;
14353     m->AutoTunnelNAT.clientContext = mDNSNULL;
14354 
14355     m->WABBrowseQueriesCount    = 0;
14356     m->WABLBrowseQueriesCount   = 0;
14357     m->WABRegQueriesCount       = 0;
14358 #if TARGET_OS_EMBEDDED || TARGET_OS_WATCH
14359     m->AutoTargetServices       = 0;
14360 #else
14361     m->AutoTargetServices       = 1;
14362 #endif
14363 #if TARGET_OS_WATCH
14364     m->NumAllInterfaceRecords   = 0;
14365     m->NumAllInterfaceQuestions = 0;
14366 #else
14367     // Initialize to 1 for these targets to prevent not joining multicast group for interfaces when
14368     // both of these values are zero.
14369     m->NumAllInterfaceRecords   = 1;
14370     m->NumAllInterfaceQuestions = 1;
14371 #endif
14372     // NAT traversal fields
14373     m->LLQNAT.clientCallback    = mDNSNULL;
14374     m->LLQNAT.clientContext     = mDNSNULL;
14375     m->NATTraversals            = mDNSNULL;
14376     m->CurrentNATTraversal      = mDNSNULL;
14377     m->retryIntervalGetAddr     = 0;    // delta between time sent and retry
14378     m->retryGetAddr             = timenow + 0x78000000; // absolute time when we retry
14379     m->ExtAddress               = zerov4Addr;
14380     m->PCPNonce[0]              = mDNSRandom(-1);
14381     m->PCPNonce[1]              = mDNSRandom(-1);
14382     m->PCPNonce[2]              = mDNSRandom(-1);
14383 
14384     m->NATMcastRecvskt          = mDNSNULL;
14385     m->LastNATupseconds         = 0;
14386     m->LastNATReplyLocalTime    = timenow;
14387     m->LastNATMapResultCode     = NATErr_None;
14388 
14389     m->UPnPInterfaceID          = 0;
14390     m->SSDPSocket               = mDNSNULL;
14391     m->SSDPWANPPPConnection     = mDNSfalse;
14392     m->UPnPRouterPort           = zeroIPPort;
14393     m->UPnPSOAPPort             = zeroIPPort;
14394     m->UPnPRouterURL            = mDNSNULL;
14395     m->UPnPWANPPPConnection     = mDNSfalse;
14396     m->UPnPSOAPURL              = mDNSNULL;
14397     m->UPnPRouterAddressString  = mDNSNULL;
14398     m->UPnPSOAPAddressString    = mDNSNULL;
14399     m->SPSType                  = 0;
14400     m->SPSPortability           = 0;
14401     m->SPSMarginalPower         = 0;
14402     m->SPSTotalPower            = 0;
14403     m->SPSFeatureFlags          = 0;
14404     m->SPSState                 = 0;
14405     m->SPSProxyListChanged      = mDNSNULL;
14406     m->SPSSocket                = mDNSNULL;
14407     m->SPSBrowseCallback        = mDNSNULL;
14408     m->ProxyRecords             = 0;
14409 
14410 #endif
14411 
14412 #if APPLE_OSX_mDNSResponder
14413     m->TunnelClients            = mDNSNULL;
14414 
14415 #if !NO_WCF
14416     CHECK_WCF_FUNCTION(WCFConnectionNew)
14417     {
14418         m->WCF = WCFConnectionNew();
14419         if (!m->WCF) { LogMsg("WCFConnectionNew failed"); return -1; }
14420     }
14421 #endif
14422 
14423 #endif
14424 
14425     result = mDNSPlatformInit(m);
14426 
14427 #ifndef UNICAST_DISABLED
14428     // It's better to do this *after* the platform layer has set up the
14429     // interface list and security credentials
14430     uDNS_SetupDNSConfig(m);                     // Get initial DNS configuration
14431 #endif
14432 
14433     return(result);
14434 }
14435 
14436 mDNSexport void mDNS_ConfigChanged(mDNS *const m)
14437 {
14438     if (m->SPSState == 1)
14439     {
14440         domainlabel name, newname;
14441 #ifndef SPC_DISABLED
14442         domainname type, domain;
14443         DeconstructServiceName(m->SPSRecords.RR_SRV.resrec.name, &name, &type, &domain);
14444 #endif // SPC_DISABLED
14445         ConstructSleepProxyServerName(m, &newname);
14446         if (!SameDomainLabelCS(name.c, newname.c))
14447         {
14448             LogSPS("Renaming SPS from “%#s” to “%#s”", name.c, newname.c);
14449             // When SleepProxyServerCallback gets the mStatus_MemFree message,
14450             // it will reregister the service under the new name
14451             m->SPSState = 2;
14452 #ifndef SPC_DISABLED
14453             mDNS_DeregisterService_drt(m, &m->SPSRecords, mDNS_Dereg_rapid);
14454 #endif // SPC_DISABLED
14455         }
14456     }
14457 
14458     if (m->MainCallback)
14459         m->MainCallback(m, mStatus_ConfigChanged);
14460 }
14461 
14462 mDNSlocal void DynDNSHostNameCallback(mDNS *const m, AuthRecord *const rr, mStatus result)
14463 {
14464     (void)m;    // unused
14465     debugf("NameStatusCallback: result %d for registration of name %##s", result, rr->resrec.name->c);
14466     mDNSPlatformDynDNSHostNameStatusChanged(rr->resrec.name, result);
14467 }
14468 
14469 mDNSlocal void PurgeOrReconfirmCacheRecord(mDNS *const m, CacheRecord *cr, const DNSServer * const ptr, mDNSBool lameduck)
14470 {
14471     mDNSBool purge = cr->resrec.RecordType == kDNSRecordTypePacketNegative ||
14472                      cr->resrec.rrtype     == kDNSType_A ||
14473                      cr->resrec.rrtype     == kDNSType_AAAA ||
14474                      cr->resrec.rrtype     == kDNSType_SRV;
14475 
14476     (void) lameduck;
14477     (void) ptr;
14478     debugf("PurgeOrReconfirmCacheRecord: %s cache record due to %s server %p %#a:%d (%##s): %s",
14479            purge    ? "purging"   : "reconfirming",
14480            lameduck ? "lame duck" : "new",
14481            ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, CRDisplayString(m, cr));
14482 
14483     if (purge)
14484     {
14485         LogInfo("PurgeorReconfirmCacheRecord: Purging Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14486         mDNS_PurgeCacheResourceRecord(m, cr);
14487     }
14488     else
14489     {
14490         LogInfo("PurgeorReconfirmCacheRecord: Reconfirming Resourcerecord %s, RecordType %x", CRDisplayString(m, cr), cr->resrec.RecordType);
14491         mDNS_Reconfirm_internal(m, cr, kDefaultReconfirmTimeForNoAnswer);
14492     }
14493 }
14494 
14495 mDNSlocal void mDNS_PurgeForQuestion(mDNS *const m, DNSQuestion *q)
14496 {
14497     const mDNSu32 slot = HashSlot(&q->qname);
14498     CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
14499     CacheRecord *rp;
14500     mDNSu8 validatingResponse = 0;
14501 
14502     // For DNSSEC questions, purge the corresponding RRSIGs also.
14503     if (DNSSECQuestion(q))
14504     {
14505         validatingResponse = q->ValidatingResponse;
14506         q->ValidatingResponse = mDNStrue;
14507     }
14508     for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14509     {
14510         if (SameNameRecordAnswersQuestion(&rp->resrec, q))
14511         {
14512             LogInfo("mDNS_PurgeForQuestion: Flushing %s", CRDisplayString(m, rp));
14513             mDNS_PurgeCacheResourceRecord(m, rp);
14514         }
14515     }
14516     if (DNSSECQuestion(q))
14517     {
14518         q->ValidatingResponse = validatingResponse;
14519     }
14520 }
14521 
14522 // For DNSSEC question, we need the DNSSEC records also. If the cache does not
14523 // have the DNSSEC records, we need to re-issue the question with EDNS0/DO bit set.
14524 // Just re-issuing the question for RRSIGs does not work in practice as the response
14525 // may not contain the RRSIGs whose typeCovered field matches the question's qtype.
14526 //
14527 // For negative responses, we need the NSECs to prove the non-existence. If we don't
14528 // have the cached NSECs, purge them. For positive responses, if we don't have the
14529 // RRSIGs and if we have not already issued the question with EDNS0/DO bit set, purge
14530 // them.
14531 mDNSlocal void CheckForDNSSECRecords(mDNS *const m, DNSQuestion *q)
14532 {
14533     const mDNSu32 slot = HashSlot(&q->qname);
14534     CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
14535     CacheRecord *rp;
14536 
14537     for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14538     {
14539         if (SameNameRecordAnswersQuestion(&rp->resrec, q))
14540         {
14541             if (rp->resrec.RecordType != kDNSRecordTypePacketNegative || !rp->nsec)
14542             {
14543                 if (!rp->CRDNSSECQuestion)
14544                 {
14545                     LogInfo("CheckForDNSSECRecords: Flushing %s", CRDisplayString(m, rp));
14546                     mDNS_PurgeCacheResourceRecord(m, rp);
14547                 }
14548             }
14549         }
14550     }
14551 }
14552 
14553 // Check for a positive unicast response to the question but with qtype
14554 mDNSexport mDNSBool mDNS_CheckForCacheRecord(mDNS *const m, DNSQuestion *q, mDNSu16 qtype)
14555 {
14556     DNSQuestion question;
14557     const mDNSu32 slot = HashSlot(&q->qname);
14558     CacheGroup *const cg = CacheGroupForName(m, slot, q->qnamehash, &q->qname);
14559     CacheRecord *rp;
14560 
14561     // Create an identical question but with qtype
14562     mDNS_SetupQuestion(&question, q->InterfaceID, &q->qname, qtype, mDNSNULL, mDNSNULL);
14563     question.qDNSServer = q->qDNSServer;
14564 
14565     for (rp = cg ? cg->members : mDNSNULL; rp; rp = rp->next)
14566     {
14567         if (!rp->resrec.InterfaceID && rp->resrec.RecordType != kDNSRecordTypePacketNegative &&
14568             SameNameRecordAnswersQuestion(&rp->resrec, &question))
14569         {
14570             LogInfo("mDNS_CheckForCacheRecord: Found %s", CRDisplayString(m, rp));
14571             return mDNStrue;
14572         }
14573     }
14574     return mDNSfalse;
14575 }
14576 
14577 mDNSexport void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *new)
14578 {
14579     DNSQuestion *qptr;
14580 
14581     (void) m;
14582 
14583     if (q->DuplicateOf)
14584         LogMsg("DNSServerChangeForQuestion: ERROR: Called for duplicate question %##s", q->qname.c);
14585 
14586     // Make sure all the duplicate questions point to the same DNSServer so that delivery
14587     // of events for all of them are consistent. Duplicates for a question are always inserted
14588     // after in the list.
14589     q->qDNSServer = new;
14590     for (qptr = q->next ; qptr; qptr = qptr->next)
14591     {
14592         if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = new; }
14593     }
14594 }
14595 
14596 mDNSlocal void SetConfigState(mDNS *const m, mDNSBool delete)
14597 {
14598     McastResolver *mr;
14599     DNSServer *ptr;
14600 
14601     if (delete)
14602     {
14603         for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14604         {
14605             ptr->penaltyTime = 0;
14606             NumUnicastDNSServers--;
14607             ptr->flags |= DNSServer_FlagDelete;
14608 #if APPLE_OSX_mDNSResponder
14609             if (ptr->flags & DNSServer_FlagUnreachable)
14610                 NumUnreachableDNSServers--;
14611 #endif
14612         }
14613         // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
14614         // mcast resolvers. Today we get both mcast and ucast configuration using the same
14615         // API
14616         for (mr = m->McastResolvers; mr; mr = mr->next)
14617             mr->flags |= McastResolver_FlagDelete;
14618     }
14619     else
14620     {
14621         for (ptr = m->DNSServers; ptr; ptr = ptr->next)
14622         {
14623             ptr->penaltyTime = 0;
14624             NumUnicastDNSServers++;
14625             ptr->flags &= ~DNSServer_FlagDelete;
14626 #if APPLE_OSX_mDNSResponder
14627             if (ptr->flags & DNSServer_FlagUnreachable)
14628                 NumUnreachableDNSServers++;
14629 #endif
14630         }
14631         for (mr = m->McastResolvers; mr; mr = mr->next)
14632             mr->flags &= ~McastResolver_FlagDelete;
14633     }
14634 }
14635 
14636 mDNSexport mStatus uDNS_SetupDNSConfig(mDNS *const m)
14637 {
14638     mDNSu32 slot;
14639     CacheGroup *cg;
14640     CacheRecord *cr;
14641     mDNSBool Restart = mDNSfalse;
14642     mDNSAddr v4, v6, r;
14643     domainname fqdn;
14644     DNSServer   *ptr, **p = &m->DNSServers;
14645     const DNSServer *oldServers = m->DNSServers;
14646     DNSQuestion *q;
14647     McastResolver *mr, **mres = &m->McastResolvers;
14648 
14649     debugf("uDNS_SetupDNSConfig: entry");
14650 
14651     // Let the platform layer get the current DNS information and setup the WAB queries if needed.
14652     uDNS_SetupWABQueries(m);
14653 
14654     mDNS_Lock(m);
14655 
14656     // We need to first mark all the entries to be deleted. If the configuration changed, then
14657     // the entries would be undeleted appropriately. Otherwise, we need to clear them.
14658     //
14659     // Note: The last argument to mDNSPlatformSetDNSConfig is "mDNStrue" which means ack the
14660     // configuration. We already processed search domains in uDNS_SetupWABQueries above and
14661     // hence we are ready to ack the configuration as this is the last call to mDNSPlatformSetConfig
14662     // for the dns configuration change notification.
14663     SetConfigState(m, mDNStrue);
14664     if (!mDNSPlatformSetDNSConfig(m, mDNStrue, mDNSfalse, &fqdn, mDNSNULL, mDNSNULL, mDNStrue))
14665     {
14666         SetConfigState(m, mDNSfalse);
14667         mDNS_Unlock(m);
14668         LogInfo("uDNS_SetupDNSConfig: No configuration change");
14669         return mStatus_NoError;
14670     }
14671 
14672     // For now, we just delete the mcast resolvers. We don't deal with cache or
14673     // questions here. Neither question nor cache point to mcast resolvers. Questions
14674     // do inherit the timeout values from mcast resolvers. But we don't bother
14675     // affecting them as they never change.
14676     while (*mres)
14677     {
14678         if (((*mres)->flags & McastResolver_FlagDelete) != 0)
14679         {
14680             mr = *mres;
14681             *mres = (*mres)->next;
14682             debugf("uDNS_SetupDNSConfig: Deleting mcast resolver %##s", mr, mr->domain.c);
14683             mDNSPlatformMemFree(mr);
14684         }
14685         else
14686         {
14687             (*mres)->flags &= ~McastResolver_FlagNew;
14688             mres = &(*mres)->next;
14689         }
14690     }
14691 
14692     // Update our qDNSServer pointers before we go and free the DNSServer object memory
14693     //
14694     // All non-scoped resolvers share the same resGroupID. At no point in time a cache entry using DNSServer
14695     // from scoped resolver will be used to answer non-scoped questions and vice versa, as scoped and non-scoped
14696     // resolvers don't share the same resGroupID. A few examples to describe the interaction with how we pick
14697     // DNSServers and flush the cache.
14698     //
14699     // - A non-scoped question picks DNSServer X, creates a cache entry with X. If a new resolver gets added later that
14700     //   is a better match, we pick the new DNSServer for the question and activate the unicast query. We may or may not
14701     //   flush the cache (See PurgeOrReconfirmCacheRecord). In either case, we don't change the cache record's DNSServer
14702     //   pointer immediately (qDNSServer and rDNSServer may be different but still share the same resGroupID). If we don't
14703     //   flush the cache immediately, the record's rDNSServer pointer will be updated (in mDNSCoreReceiveResponse)
14704     //   later when we get the response. If we purge the cache, we still deliver a RMV when it is purged even though
14705     //   we don't update the cache record's DNSServer pointer to match the question's DNSSever, as they both point to
14706     //   the same resGroupID.
14707     //
14708     //   Note: If the new DNSServer comes back with a different response than what we have in the cache, we will deliver a RMV
14709     //   of the old followed by ADD of the new records.
14710     //
14711     // - A non-scoped question picks DNSServer X,  creates a cache entry with X. If the resolver gets removed later, we will
14712     //   pick a new DNSServer for the question which may or may not be NULL and set the cache record's pointer to the same
14713     //   as in question's qDNSServer if the cache record is not flushed. If there is no active question, it will be set to NULL.
14714     //
14715     // - Two questions scoped and non-scoped for the same name will pick two different DNSServer and will end up creating separate
14716     //   cache records and as the resGroupID is different, you can't use the cache record from the scoped DNSServer to answer the
14717     //   non-scoped question and vice versa.
14718     //
14719     for (q = m->Questions; q; q=q->next)
14720     {
14721         if (!mDNSOpaque16IsZero(q->TargetQID))
14722         {
14723             DNSServer *s, *t;
14724             DNSQuestion *qptr;
14725             if (q->DuplicateOf) continue;
14726             SetValidDNSServers(m, q);
14727             q->triedAllServersOnce = 0;
14728             s = GetServerForQuestion(m, q);
14729             t = q->qDNSServer;
14730             if (t != s)
14731             {
14732                 mDNSBool old, new;
14733 		mDNSIPPort tport, sport;
14734 
14735 		if (t)
14736 			tport = t->port;
14737 		else
14738 			tport = zeroIPPort;
14739 
14740 		if (s)
14741 			sport = s->port;
14742 		else
14743 			sport = zeroIPPort;
14744                 // If DNS Server for this question has changed, reactivate it
14745                 LogInfo("uDNS_SetupDNSConfig: Updating DNS Server from %#a:%d (%##s) to %#a:%d (%##s) for question %##s (%s) (scope:%p)",
14746                         t ? &t->addr : mDNSNULL, mDNSVal16(tport), t ? t->domain.c : (mDNSu8*)"",
14747                         s ? &s->addr : mDNSNULL, mDNSVal16(sport), s ? s->domain.c : (mDNSu8*)"",
14748                         q->qname.c, DNSTypeName(q->qtype), q->InterfaceID);
14749 
14750                 old = q->SuppressQuery;
14751                 new = ShouldSuppressUnicastQuery(m, q, s);
14752                 if (old != new)
14753                 {
14754                     // Changing the DNS server affected the SuppressQuery status. We need to
14755                     // deliver RMVs for the previous ADDs (if any) before switching to the new
14756                     // DNSServer.  To keep it simple, we walk all the questions and mark them
14757                     // to be restarted and then handle all of them at once.
14758                     q->Restart = 1;
14759                     q->SuppressQuery = new;
14760                     for (qptr = q->next ; qptr; qptr = qptr->next)
14761                     {
14762                         if (qptr->DuplicateOf == q)
14763                             qptr->Restart = 1;
14764                     }
14765                     Restart = mDNStrue;
14766                 }
14767                 else
14768                 {
14769                     DNSServerChangeForQuestion(m, q, s);
14770                     q->unansweredQueries = 0;
14771 
14772                     // If we had sent a query out to DNSServer "t" and we are changing to "s", we
14773                     // need to ignore the responses coming back from "t" as the DNS configuration
14774                     // has changed e.g., when a new interface is coming up and that becomes the primary
14775                     // interface, we switch to the DNS servers configured for the primary interface. In
14776                     // this case, we should not accept responses associated with the previous interface as
14777                     // the "name" could resolve differently on this new primary interface. Hence, discard
14778                     // in-flight responses.
14779                     q->TargetQID = mDNS_NewMessageID(m);
14780 
14781                     if (!QuerySuppressed(q))
14782                     {
14783                         debugf("uDNS_SetupDNSConfig: Activating query %p %##s (%s)", q, q->qname.c, DNSTypeName(q->qtype));
14784                         ActivateUnicastQuery(m, q, mDNStrue);
14785                         // ActivateUnicastQuery is called for duplicate questions also as it does something
14786                         // special for AutoTunnel questions
14787                         for (qptr = q->next ; qptr; qptr = qptr->next)
14788                         {
14789                             if (qptr->DuplicateOf == q) ActivateUnicastQuery(m, qptr, mDNStrue);
14790                         }
14791                     }
14792                 }
14793             }
14794             else
14795             {
14796 		mDNSIPPort zp = zeroIPPort;
14797                 debugf("uDNS_SetupDNSConfig: Not Updating DNS server question %p %##s (%s) DNS server %#a:%d %p %d",
14798                        q, q->qname.c, DNSTypeName(q->qtype), t ? &t->addr : mDNSNULL, mDNSVal16(t ? t->port : zp), q->DuplicateOf, q->SuppressUnusable);
14799                 for (qptr = q->next ; qptr; qptr = qptr->next)
14800                     if (qptr->DuplicateOf == q) { qptr->validDNSServers = q->validDNSServers; qptr->qDNSServer = q->qDNSServer; }
14801             }
14802         }
14803     }
14804     if (Restart)
14805         RestartUnicastQuestions(m);
14806 
14807     FORALL_CACHERECORDS(slot, cg, cr)
14808     {
14809         if (cr->resrec.InterfaceID)
14810             continue;
14811 
14812         // We already walked the questions and restarted/reactivated them if the dns server
14813         // change affected the question. That should take care of updating the cache. But
14814         // what if there is no active question at this point when the DNS server change
14815         // happened ? There could be old cache entries lying around and if we don't flush
14816         // them, a new question after the DNS server change could pick up these stale
14817         // entries and get a wrong answer.
14818         //
14819         // For cache entries that have active questions we might have skipped rescheduling
14820         // the questions if they were suppressed (see above). To keep it simple, we walk
14821         // all the cache entries to make sure that there are no stale entries. We use the
14822         // active question's InterfaceID/ServiceID for looking up the right DNS server.
14823         // Note that the unscoped value for ServiceID is -1.
14824         //
14825         // Note: If GetServerForName returns NULL, it could either mean that there are no
14826         // DNS servers or no matching DNS servers for this question. In either case,
14827         // the cache should get purged below when we process deleted DNS servers.
14828 
14829         ptr = GetServerForName(m, cr->resrec.name,
14830                                (cr->CRActiveQuestion ? cr->CRActiveQuestion->InterfaceID : mDNSNULL),
14831                                (cr->CRActiveQuestion ? cr->CRActiveQuestion->ServiceID   : -1));
14832 
14833         // Purge or Reconfirm if this cache entry would use the new DNS server
14834         if (ptr && (ptr != cr->resrec.rDNSServer))
14835         {
14836             // As the DNSServers for this cache record is not the same anymore, we don't
14837             // want any new questions to pick this old value. If there is no active question,
14838             // we can't possibly re-confirm, so purge in that case. If it is a DNSSEC question,
14839             // purge the cache as the DNSSEC capabilities of the DNS server may have changed.
14840 
14841             if (cr->CRActiveQuestion == mDNSNULL || DNSSECQuestion(cr->CRActiveQuestion))
14842             {
14843                 LogInfo("uDNS_SetupDNSConfig: Purging Resourcerecord %s, New DNS server %#a , Old DNS server %#a", CRDisplayString(m, cr),
14844                         &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ?  &cr->resrec.rDNSServer->addr : mDNSNULL));
14845                 mDNS_PurgeCacheResourceRecord(m, cr);
14846             }
14847             else
14848             {
14849                 LogInfo("uDNS_SetupDNSConfig: Purging/Reconfirming Resourcerecord %s, New DNS server %#a, Old DNS server %#a", CRDisplayString(m, cr),
14850                         &ptr->addr, (cr->resrec.rDNSServer != mDNSNULL ?  &cr->resrec.rDNSServer->addr : mDNSNULL));
14851                 PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNSfalse);
14852             }
14853         }
14854     }
14855 
14856     while (*p)
14857     {
14858         if (((*p)->flags & DNSServer_FlagDelete) != 0)
14859         {
14860             // Scan our cache, looking for uDNS records that we would have queried this server for.
14861             // We reconfirm any records that match, because in this world of split DNS, firewalls, etc.
14862             // different DNS servers can give different answers to the same question.
14863             ptr = *p;
14864             FORALL_CACHERECORDS(slot, cg, cr)
14865             {
14866                 if (cr->resrec.InterfaceID) continue;
14867                 if (cr->resrec.rDNSServer == ptr)
14868                 {
14869                     // If we don't have an active question for this cache record, neither Purge can
14870                     // generate RMV events nor Reconfirm can send queries out. Just set the DNSServer
14871                     // pointer on the record NULL so that we don't point to freed memory (We might dereference
14872                     // DNSServer pointers from resource record for logging purposes).
14873                     //
14874                     // If there is an active question, point to its DNSServer as long as it does not point to the
14875                     // freed one. We already went through the questions above and made them point at either the
14876                     // new server or NULL if there is no server.
14877 
14878                     if (cr->CRActiveQuestion)
14879                     {
14880                         DNSQuestion *qptr = cr->CRActiveQuestion;
14881 
14882                         if (qptr->qDNSServer == ptr)
14883                         {
14884                             LogMsg("uDNS_SetupDNSConfig: ERROR!! Cache Record %s  Active question %##s (%s) (scope:%p) poining to DNSServer Address %#a"
14885                                    " to be freed", CRDisplayString(m, cr),  qptr->qname.c, DNSTypeName(qptr->qtype), qptr->InterfaceID, &ptr->addr);
14886                             qptr->validDNSServers = zeroOpaque64;
14887                             qptr->qDNSServer = mDNSNULL;
14888                             cr->resrec.rDNSServer = mDNSNULL;
14889                         }
14890                         else
14891                         {
14892                             LogInfo("uDNS_SetupDNSConfig: Cache Record %s,  Active question %##s (%s) (scope:%p), pointing to DNSServer %#a (to be deleted),"
14893                                     " resetting to  question's DNSServer Address %#a", CRDisplayString(m, cr),  qptr->qname.c, DNSTypeName(qptr->qtype),
14894                                     qptr->InterfaceID, &ptr->addr, (qptr->qDNSServer ? &qptr->qDNSServer->addr : mDNSNULL));
14895                             cr->resrec.rDNSServer = qptr->qDNSServer;
14896                         }
14897                     }
14898                     else
14899                     {
14900                         LogInfo("uDNS_SetupDNSConfig: Cache Record %##s has no Active question, Record's DNSServer Address %#a, Server to be deleted %#a",
14901                                 cr->resrec.name, &cr->resrec.rDNSServer->addr, &ptr->addr);
14902                         cr->resrec.rDNSServer = mDNSNULL;
14903                     }
14904 
14905                     PurgeOrReconfirmCacheRecord(m, cr, ptr, mDNStrue);
14906                 }
14907             }
14908             *p = (*p)->next;
14909             LogInfo("uDNS_SetupDNSConfig: Deleting server %p %#a:%d (%##s) %d", ptr, &ptr->addr, mDNSVal16(ptr->port), ptr->domain.c, NumUnicastDNSServers);
14910             mDNSPlatformMemFree(ptr);
14911         }
14912         else
14913         {
14914             (*p)->flags &= ~DNSServer_FlagNew;
14915             p = &(*p)->next;
14916         }
14917     }
14918 
14919     // 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).
14920     // This is important for giving prompt remove events when the user disconnects the Ethernet cable or turns off wireless.
14921     // Otherwise, stale data lingers for 5-10 seconds, which is not the user-experience people expect from Bonjour.
14922     // 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.
14923     if ((m->DNSServers != mDNSNULL) != (oldServers != mDNSNULL))
14924     {
14925         int count = 0;
14926         FORALL_CACHERECORDS(slot, cg, cr)
14927         {
14928             if (!cr->resrec.InterfaceID)
14929             {
14930                 mDNS_PurgeCacheResourceRecord(m, cr);
14931                 count++;
14932             }
14933         }
14934         LogInfo("uDNS_SetupDNSConfig: %s available; purged %d unicast DNS records from cache",
14935                 m->DNSServers ? "DNS server became" : "No DNS servers", count);
14936 
14937         // Force anything that needs to get zone data to get that information again
14938         RestartRecordGetZoneData(m);
14939     }
14940 
14941     // Did our FQDN change?
14942     if (!SameDomainName(&fqdn, &m->FQDN))
14943     {
14944         if (m->FQDN.c[0]) mDNS_RemoveDynDNSHostName(m, &m->FQDN);
14945 
14946         AssignDomainName(&m->FQDN, &fqdn);
14947 
14948         if (m->FQDN.c[0])
14949         {
14950             mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1);
14951             mDNS_AddDynDNSHostName(m, &m->FQDN, DynDNSHostNameCallback, mDNSNULL);
14952         }
14953     }
14954 
14955     mDNS_Unlock(m);
14956 
14957     // handle router and primary interface changes
14958     v4 = v6 = r = zeroAddr;
14959     v4.type = r.type = mDNSAddrType_IPv4;
14960 
14961     if (mDNSPlatformGetPrimaryInterface(m, &v4, &v6, &r) == mStatus_NoError && !mDNSv4AddressIsLinkLocal(&v4.ip.v4))
14962     {
14963         mDNS_SetPrimaryInterfaceInfo(m,
14964                                      !mDNSIPv4AddressIsZero(v4.ip.v4) ? &v4 : mDNSNULL,
14965                                      !mDNSIPv6AddressIsZero(v6.ip.v6) ? &v6 : mDNSNULL,
14966                                      !mDNSIPv4AddressIsZero(r.ip.v4) ? &r  : mDNSNULL);
14967     }
14968     else
14969     {
14970         mDNS_SetPrimaryInterfaceInfo(m, mDNSNULL, mDNSNULL, mDNSNULL);
14971         if (m->FQDN.c[0]) mDNSPlatformDynDNSHostNameStatusChanged(&m->FQDN, 1); // Set status to 1 to indicate temporary failure
14972     }
14973 
14974     debugf("uDNS_SetupDNSConfig: number of unicast DNS servers %d", NumUnicastDNSServers);
14975     return mStatus_NoError;
14976 }
14977 
14978 mDNSexport void mDNSCoreInitComplete(mDNS *const m, mStatus result)
14979 {
14980     m->mDNSPlatformStatus = result;
14981     if (m->MainCallback)
14982     {
14983         mDNS_Lock(m);
14984         mDNS_DropLockBeforeCallback();      // Allow client to legally make mDNS API calls from the callback
14985         m->MainCallback(m, mStatus_NoError);
14986         mDNS_ReclaimLockAfterCallback();    // Decrement mDNS_reentrancy to block mDNS API calls again
14987         mDNS_Unlock(m);
14988     }
14989 }
14990 
14991 mDNSlocal void DeregLoop(mDNS *const m, AuthRecord *const start)
14992 {
14993     m->CurrentRecord = start;
14994     while (m->CurrentRecord)
14995     {
14996         AuthRecord *rr = m->CurrentRecord;
14997         LogInfo("DeregLoop: %s deregistration for %p %02X %s",
14998                 (rr->resrec.RecordType != kDNSRecordTypeDeregistering) ? "Initiating  " : "Accelerating",
14999                 rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15000         if (rr->resrec.RecordType != kDNSRecordTypeDeregistering)
15001             mDNS_Deregister_internal(m, rr, mDNS_Dereg_rapid);
15002         else if (rr->AnnounceCount > 1)
15003         {
15004             rr->AnnounceCount = 1;
15005             rr->LastAPTime = m->timenow - rr->ThisAPInterval;
15006         }
15007         // Mustn't advance m->CurrentRecord until *after* mDNS_Deregister_internal, because
15008         // new records could have been added to the end of the list as a result of that call.
15009         if (m->CurrentRecord == rr) // If m->CurrentRecord was not advanced for us, do it now
15010             m->CurrentRecord = rr->next;
15011     }
15012 }
15013 
15014 mDNSexport void mDNS_StartExit(mDNS *const m)
15015 {
15016     AuthRecord *rr;
15017 
15018     mDNS_Lock(m);
15019 
15020     LogInfo("mDNS_StartExit");
15021     m->ShutdownTime = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 5);
15022 
15023     mDNSCoreBeSleepProxyServer_internal(m, 0, 0, 0, 0, 0);
15024 
15025 #if APPLE_OSX_mDNSResponder
15026 #if !NO_WCF
15027     CHECK_WCF_FUNCTION(WCFConnectionDealloc)
15028     {
15029         if (m->WCF) WCFConnectionDealloc((WCFConnection *)m->WCF);
15030     }
15031 #endif
15032 #endif
15033 
15034 #ifndef UNICAST_DISABLED
15035     {
15036         SearchListElem *s;
15037         SuspendLLQs(m);
15038         // Don't need to do SleepRecordRegistrations() here
15039         // because we deregister all records and services later in this routine
15040         while (m->Hostnames) mDNS_RemoveDynDNSHostName(m, &m->Hostnames->fqdn);
15041 
15042         // For each member of our SearchList, deregister any records it may have created, and cut them from the list.
15043         // Otherwise they'll be forcibly deregistered for us (without being cut them from the appropriate list)
15044         // and we may crash because the list still contains dangling pointers.
15045         for (s = SearchList; s; s = s->next)
15046             while (s->AuthRecs)
15047             {
15048                 ARListElem *dereg = s->AuthRecs;
15049                 s->AuthRecs = s->AuthRecs->next;
15050                 mDNS_Deregister_internal(m, &dereg->ar, mDNS_Dereg_normal); // Memory will be freed in the FreeARElemCallback
15051             }
15052     }
15053 #endif
15054 
15055     DeadvertiseAllInterfaceRecords(m);
15056 
15057     // Shut down all our active NAT Traversals
15058     while (m->NATTraversals)
15059     {
15060         NATTraversalInfo *t = m->NATTraversals;
15061         mDNS_StopNATOperation_internal(m, t);       // This will cut 't' from the list, thereby advancing m->NATTraversals in the process
15062 
15063         // After stopping the NAT Traversal, we zero out the fields.
15064         // This has particularly important implications for our AutoTunnel records --
15065         // when we deregister our AutoTunnel records below, we don't want their mStatus_MemFree
15066         // handlers to just turn around and attempt to re-register those same records.
15067         // Clearing t->ExternalPort/t->RequestedPort will cause the mStatus_MemFree callback handlers
15068         // to not do this.
15069         t->ExternalAddress = zerov4Addr;
15070         t->NewAddress      = zerov4Addr;
15071         t->ExternalPort    = zeroIPPort;
15072         t->RequestedPort   = zeroIPPort;
15073         t->Lifetime        = 0;
15074         t->Result          = mStatus_NoError;
15075     }
15076 
15077     // Make sure there are nothing but deregistering records remaining in the list
15078     if (m->CurrentRecord)
15079         LogMsg("mDNS_StartExit: ERROR m->CurrentRecord already set %s", ARDisplayString(m, m->CurrentRecord));
15080 
15081     // We're in the process of shutting down, so queries, etc. are no longer available.
15082     // Consequently, determining certain information, e.g. the uDNS update server's IP
15083     // address, will not be possible.  The records on the main list are more likely to
15084     // already contain such information, so we deregister the duplicate records first.
15085     LogInfo("mDNS_StartExit: Deregistering duplicate resource records");
15086     DeregLoop(m, m->DuplicateRecords);
15087     LogInfo("mDNS_StartExit: Deregistering resource records");
15088     DeregLoop(m, m->ResourceRecords);
15089 
15090     // If we scheduled a response to send goodbye packets, we set NextScheduledResponse to now. Normally when deregistering records,
15091     // we allow up to 100ms delay (to help improve record grouping) but when shutting down we don't want any such delay.
15092     if (m->NextScheduledResponse - m->timenow < mDNSPlatformOneSecond)
15093     {
15094         m->NextScheduledResponse = m->timenow;
15095         m->SuppressSending = 0;
15096     }
15097 
15098     if (m->ResourceRecords) LogInfo("mDNS_StartExit: Sending final record deregistrations");
15099     else LogInfo("mDNS_StartExit: No deregistering records remain");
15100 
15101     for (rr = m->DuplicateRecords; rr; rr = rr->next)
15102         LogMsg("mDNS_StartExit: Should not still have Duplicate Records remaining: %02X %s", rr->resrec.RecordType, ARDisplayString(m, rr));
15103 
15104     // If any deregistering records remain, send their deregistration announcements before we exit
15105     if (m->mDNSPlatformStatus != mStatus_NoError) DiscardDeregistrations(m);
15106 
15107     mDNS_Unlock(m);
15108 
15109     LogInfo("mDNS_StartExit: done");
15110 }
15111 
15112 mDNSexport void mDNS_FinalExit(mDNS *const m)
15113 {
15114     mDNSu32 rrcache_active = 0;
15115     mDNSu32 rrcache_totalused = m->rrcache_totalused;
15116     mDNSu32 slot;
15117     AuthRecord *rr;
15118 
15119     LogInfo("mDNS_FinalExit: mDNSPlatformClose");
15120     mDNSPlatformClose(m);
15121 
15122     for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
15123     {
15124         while (m->rrcache_hash[slot])
15125         {
15126             CacheGroup *cg = m->rrcache_hash[slot];
15127             while (cg->members)
15128             {
15129                 CacheRecord *cr = cg->members;
15130                 cg->members = cg->members->next;
15131                 if (cr->CRActiveQuestion) rrcache_active++;
15132                 ReleaseCacheRecord(m, cr);
15133             }
15134             cg->rrcache_tail = &cg->members;
15135             ReleaseCacheGroup(m, &m->rrcache_hash[slot]);
15136         }
15137     }
15138     debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
15139     if (rrcache_active != m->rrcache_active)
15140         LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused, rrcache_active, m->rrcache_active);
15141 
15142     for (rr = m->ResourceRecords; rr; rr = rr->next)
15143         LogMsg("mDNS_FinalExit failed to send goodbye for: %p %02X %s", rr, rr->resrec.RecordType, ARDisplayString(m, rr));
15144 
15145     LogInfo("mDNS_FinalExit: done");
15146 }
15147